Reputation: 59
I need to write a function that takes a character and a string as inputs and then compares that character to each element in the string. It then prints and finally returns the number of times that the character appeared in the string.
This is the code I've come up with, but it isn't working out the right way. I'd appreciate it if someone could explain and correct the error.
I thought first to write a function that compares two characters to check if they are equal, like this:
def func1(x1, x2):
if x1 == x2:
return True
else:
return False
And then, I thought I'd wite the other, main function like this:
def func2():
ch1 = input("Enter one character. ")
str1 = str(input("Enter a string. "))
list_1 = list(str1)
a = 0
for 1 in list_1:
if func1(ch1, list_1):
a += 1
else:
a += 0
print(a)
return a
What is the error here? If I choose "a" as my character, and then enter a string of five a's as my string, the function still tells me that "a" appeared in the string only once. Why is this and how do I fix it?
Upvotes: 1
Views: 37806
Reputation: 3704
Few possible ways.
Using list
>>> len([x for x in test_string if x == test_char])
Using collections.Counter
>>> from collections import Counter
>>> print(Counter(test_string)[test_char])
Upvotes: 3
Reputation: 304255
To fix your immediate problem, you just need to dedent the print and return
def func2():
ch1 = input("Enter one character. ")
str1 = str(input("Enter a string. "))
list_1 = list(str1)
a = 0
for 1 in list_1:
if func1(ch1, list_1):
a += 1
else:
a += 0
print(a) # <-- dedent
return a # <-- dedent
You don't need to convert the string to a list to iterate over it. You don't need the else
clause if it doesn't do anything. You shouldn't return from inside the for loop
def func2():
ch1 = input("Enter one character. ")
str1 = input("Enter a string. ")
a = 0
for c in str1:
if c == ch:
a += 1
print(a)
return a
More simply
def func2():
ch1 = input("Enter one character. ")
str1 = input("Enter a string. ")
return str1.count(ch1)
Upvotes: 1
Reputation: 9237
Here is a simple code that does what you want:
It returns the number of times the character ch appears in text.
def test(ch, text): // ch is character and text is the string
numAppears = 0
for t in text:
if t == ch:
numAppears += 1
return numAppears
example:
>>> test("a", "saherbaderahwal")
4
>>> test("c", "hello")
0
>>> test(" ", "nice to meet you")
3
>>>
Upvotes: 1
Reputation: 1367
assuming the code you put there is correctly formatted unindent your return
one block - it looks like it's getting called once throught the for block
Upvotes: 0
Reputation: 363627
The problem is that the return
is indented one block to deep, so after comparing the first character of the list, the function returns.
(Another problem is that your function func1
is not only poorly named, but also far too complicated:
def cmp_chars(x, y):
return x == y
Though you really don't need a function for that at all.)
Upvotes: 0