【问题标题】:Counting commas but not vowels and consonants计算逗号但不计算元音和辅音
【发布时间】:2021-12-12 15:38:14
【问题描述】:

我已经构建了两个使用return 不计算元音和辅音的函数。

我现在正在尝试计算逗号,并认为它就像交换 return 而不是 return 一样简单。

我在这里遗漏了什么导致此失败?

def check_comma(x):
    x = x.lower()

    return x == ','


def countCommas(string):
    count = 0

    for i in range(len(string)):

        if check_comma(string[i]):
            count += 1

    return count

然后我有一个 app.py 来创建一个端点,以便前端可以调用这个函数,如下所示

import json
from http import HTTPStatus
from flask import Flask, request, Response, jsonify
from commas import countCommas


app = Flask(__name__)


@app.route('/')
def home():
    user_input = str(request.args.get('text'))
    ans = str(countCommas(user_input))

    payload = {
        'word': user_input,
        'answer': ans
    }

    reply = json.dumps(payload)

    response = Response(response=reply, status=HTTPStatus.OK, mimetype="application/json")
    response.headers['Content-Type'] = "application/json"
    response.headers['Access-Control-Allow-Origin']='*'

    return response


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=2000)

这是用 docker/kubernetes 设置的,可以调用该函数,但它返回的答案是“0”,输入字段中有任意数量的逗号

【问题讨论】:

  • .count 方法怎么样

标签: python count


【解决方案1】:

首先,您无需调用.lower() 来检查逗号。其次,代码似乎对我来说很好用。我认为问题是由第 1 行的错误缩进引起的(def check_comma(x):)。但是,您可以简单地使用string.count(',')

简单的方法:

def countCommas(string):
    count = 0

    for i in range(len(string)):
        if string[i] == ',':
            count += 1
    return count

print(countCommas("hi,this,has,4,commas")) # 4

【讨论】:

    【解决方案2】:

    您没有接受输入。(STRING)

    
    def check_comma(x):
        x = x.lower()
    
        return x == ','
    
    
    def countCommas(string):
        count = 0
    
        for i in range(len(string)):
    
            if check_comma(string[i]):
                count += 1
    
        print("No. of commas are: ",count)
    string= input("Enter String: ")
    countCommas(string)
    

    【讨论】:

      【解决方案3】:

      我认为不需要x.lower()。其余的都很好。这是您可以尝试的代码:

      def check_comma(x):
          x = x.lower()
          if x == ',':
               count = count + 1
          return count
      
      def Commas(string):
          count = 0
          for i in range(len(string)):
               count = count + check_comma(string[i])
          return count
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-07
        • 2018-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多