I am learning about recursive functions and I have made a simple " string to ASCII " converter which returns the ASCII value of each character of a string.
Here is what I have made so far:
def cod(n):
if n == "":
return ""
else:
a = str(ord(n[0])) + cod(n[1:])
return a
This works fine like this:
=> cod('hello')
=> '104101108108111'
The problem is when I am trying to get an int
as output instead of a string
. I can't simply convert variable a
because it's a recursive function, and it's not possible to iterate over an int.
After this point I am a little lost, can someone point out how to get an int as a final result of this recursive function?
def cod(n):
if n == "":
return ""
else:
a = str(ord(n[0])) + str(cod(n[1:]))
return int(a)
You might want to create another method for returning integer. Just to keep the code clean,
def cod(n):
if n == "":
return ""
else:
a = str(ord(n[0])) + cod(n[1:])
return a
def codI(n):
return int(cod(n))
print type(codI("hello"))
print type(cod("hello"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.