+ 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
4 odpowiedzi
+ 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') = }")
+ 3
Look at this article, their approach is similiar to yours
https://www.geeksforgeeks.org/convert-a-string-to-an-integer-using-recursion/
+ 3
Per Bratthammar yeah, i didn't think it that way. thanks!
+ 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)