Home > Back-end >  Counting commas but not vowels and consonants
Counting commas but not vowels and consonants

Time:12-13

I have built two functions that use return not to count vowels and consonants.

I am now trying to count commas and thought it would be as simple as exchanging return not for return.

What am I missing here that is causing this to fail?

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

I then have an app.py to create an endpoint so that this function can be called by a front end as follows

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)

This is set up with docker/kubernetes and the function can be called, but it is returning the answer "0" with any number of commas in the input field

CodePudding user response:

First of, you don't need to call .lower() to check for commas. Secondly, the code seems to work fine for me. I think the problem is caused by the wrong indentation on line 1 (def check_comma(x):). However, you can just simply use string.count(',').

Simple approach:

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

CodePudding user response:

You wasn't taking the input.(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)

CodePudding user response:

I think there is no need of x.lower() rest is fine. Here is code u can try

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
  • Related