Python Hello I am trying to learn basic recursive function on Python and I am do
ID: 3899424 • Letter: P
Question
Python
Hello I am trying to learn basic recursive function on Python and I am doing some of few exercises for practice. I am trying to make a function that returns the number that numbers in the list are strictly increasing using recursive, but counting algorithm is problem here is my code so far...
def count_increasing_number(string, number=0):
#If string length is 1, ans is 1
counter = 1
for i in range(1, len(string)-1):
#If first part is greater than previous number
if int(string[:i]) > number:
#If last part is empty, increment ans
res_string = string[i:]
if len(res_string) == 0:
counter += 1
#Proceed with the remaining part
else:
number = int(string[:i])
counter += count_increasing_number(res_string, number)
return counter
if __name__ == '__main__':
print(count_increasing_number('19325'))
print(count_increasing_number('10203'))
I want to get 4 and 4 which are [1,9, 325], [1,9325], [19, 325], [19325] and [1, 02, 03], [1, 0203], [10, 203], [10203] but the output of my code are 6 and 5. There seems to be a problem with the counting algorithm, but I don't know where it's wrong. I know this is really stupid question, but I cannot find the solution. Please help me....
Explanation / Answer
Every thing looks perfect here. But you missed the base case condition. here you are comparing current substring with previous number. If you take example of 19325 after processing 1, 9 remaing string is 325 . now it will take 32, 5 thus it leads to invalid sequences but counted in the answer. Here is the working code.
def count_increasing_number(string, number=0):
counter = 1
#added this in base condition
if(number > int(string)):
return 0
for i in range(1, len(string)):
#If first part is greater than previous number
if int(string[:i]) > number:
#If last part is empty, increment ans
res_string = string[i:]
if len(res_string) == 0:
counter += 1
#Proceed with the remaining part
else:
number = int(string[:i])
counter += count_increasing_number(res_string, number)
return counter
if __name__ == '__main__':
print(count_increasing_number('19325'))
print(count_increasing_number('10203'))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.