+ 1

how do i correct this?

this functions takes a string as input and convert it to integer recursively def atoi(string): if string.isalpha() or string == '': return 0 return ord(string[0]) - ord('0') + 10 * atoi(string[1:]) this produces the output inversed i.e, atoi('123') = 321 how do i correct this? https://code.sololearn.com/c2gJ18Rw669p/?ref=app

10th Aug 2022, 6:08 AM
Harsha S
Harsha S - avatar
4 Answers
+ 4
# Hi, Harsha S ! # It’s easy fixed! Just start to read the charaters the in the opposite # direction, comparing to what you’re doing now (I call 'string' just s # below): # 0) It acctually possible to change your if condition to just 'not s', # as long as yo input integer numbers. (Thats because when its s is empty # it becomes false, otherwise true.) # 1) s[0] -> s[-1] # 2) s[1:] -> s[:-1] def atoi(s: "string of integers >= 0"): if not s: return 0 else: return ord(s[-1]) - ord('0') + 10*atoi(s[:-1]) print(f"{atoi('8811335577') = }")
10th Aug 2022, 8:12 AM
Per Bratthammar
Per Bratthammar - avatar
+ 3
Look at this article, their approach is similiar to yours https://www.geeksforgeeks.org/convert-a-string-to-an-integer-using-recursion/
10th Aug 2022, 6:50 AM
Sandeep
Sandeep - avatar
+ 3
Per Bratthammar yeah, i didn't think it that way. thanks!
10th Aug 2022, 8:13 AM
Harsha S
Harsha S - avatar
+ 2
i created an inner function and that did the work def atoi(string): num = 0 def stoi(string): nonlocal num if string.isalpha() or string == '': return 0 num = num * 10 + ord(string[0]) - ord('0') stoi(string[1:]) return num return stoi(string)
10th Aug 2022, 8:01 AM
Harsha S
Harsha S - avatar