I want to count how many times 3 and 4 appear. What is going wrong?
def count(x):
y=0
if x[0]=='':
print(y)
return
if x[0]=='3':
y=y+1
return count(x[1:])
count('23334')
I want to count how many times 3 and 4 appear. What is going wrong?
def count(x):
y=0
if x[0]=='':
print(y)
return
if x[0]=='3':
y=y+1
return count(x[1:])
count('23334')
Your code has some logic problems. Here is the table test for input 23334
:
count
is called with x = '23334'
; y
is set to 0; x
. False, move on; count('3334')
; count
is called with x = '3334'
; y
is set to 0; x
. False, move on; y
( y = 1
); count('334')
; count
is called with x = '334'
; y
is set to 0; x
. False, move on; y
( y = 1
); count('34')
; count
is called with x = '34'
; y
is set to 0; x
. False, move on; y
( y = 1
); count('4')
; count
is called with x = '4'
; y
is set to 0; x
. False, move on; count('')
; count
is called with x = ''
; y
is set to 0; x
. Error! There is no position 0 in x
; y
( y = 0
); In short: your code gives an error and you have omitted this information in the question.
IndexError: string index out of range
The same is explained in item 28 of the test table.
And even if the error was disregarded, its function would print 9 on the screen, returning a null value.
First, let's prevent the error from happening. To verify that the x
value is not null, just if x: ...
. In this way, our function will be:
def count(x):
y = 0
if x:
... # Implementado posteriormente
return y
Since x
is null, it returns the value of y
, which will be 0. Now, within if
, we guarantee that x
is not null and that there is a 0 position. even has the number 3:
def count(x):
y = 0
if x:
if x[0] == '3':
y += 1
... # Implementado posteriormente
return y
If the number is 3, we increment the value of y
to 1, but regardless of whether or not it is 3, the value of y
must be incremented by the amount of 3 digits in the rest of the string. This was your other mistake: you did not accumulate the current value of y
with the value that is returned from the next function calls. For this we do:
def count(x):
y = 0
if x:
if x[0] == '3':
y += 1
y += count(x[1:])
return y
And in this way our function is already complete and functional. If we call it passing as a parameter the value '23334'
, the answer will be 3.
See working at Repl.it .
If you want to count both numbers 3 and 4, you can do:
def count(x):
y = 0
if x:
if x[0] in ('3', '4'):
y += 1
y += count(x[1:])
return y
print(count("23334"))
See working at Repl.it .
The test of this solution of my table I leave as an activity for you to do.
For a solution without recursion, just use the count
method of string object:
>>> print("23334".count("3"))
3
>>> print("23334".count("4"))
1