0

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?

7
  • 1
    what is the expected output? Commented Dec 10, 2015 at 17:05
  • Why do you need to convert a? Commented Dec 10, 2015 at 17:06
  • On the example i gave 'cod('hello')', it's the same '104101108108111' but in int format instead of str... Commented Dec 10, 2015 at 17:07
  • 3
    Make cod return integers. Have it return 0 if n == "" and also convert cod to an str before adding. Then convert a to an int. Commented Dec 10, 2015 at 17:08
  • Do you want to return the sum of ord or to cast the string into an int at the end? i.e. is your desired output 104101108108111 or 532? Commented Dec 10, 2015 at 17:09

2 Answers 2

1
def cod(n):
    if n == "":
        return "" 
    else:
        a = str(ord(n[0])) + str(cod(n[1:]))
        return int(a)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that is it. It's the solution PeterWood pointed out, i was overcomplicating :)
0

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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.