简体   繁体   中英

Do not understand how this recursion function works in Python

0 -> 'Z', 1->'X', 2->'T', 3->'J', 4->'A', 5->'W', 6->'F', 7->'S', 8->'B', 9->'V'

To help your friend recover the integer, write a recursive function re_decry(x) in the answer box such that if x = re_encry(m), then re_decry(x) returns the integer m.

So basically, if x = "XTJA", the output should be 1234.

My code

def de_encry(x):
    if len(x) == 1:
        return mydict[x]
    if len(x) > 1:
        return de_encry(x[0:len(x)-1]) + mydict[x[len(x)-1]]

I wrote this, but the output is wrong. This outputs 10

The suggested answer is

def de_encry(x):
    if len(x) == 1:
        return mydict[x]
    if len(x) > 1:
        return de_encry(x[0:len(x)-1])*10 + mydict[x[len(x)-1]]

This outputs 1234

I don't get why the *10 makes or breaks the answer, why doesn't my code work? This is not a homework question, I am just practicing

Write tests against smaller input. For example, if your input is WW , then your first solution would return 10, 5+5. You get the digits correct, but not the addition

If you multiply through each number by 10, then add the "ones position", you're effectively shifting the numbers left, so would return 55 (5*10+5 = 50+5), or logically, "5, shifted left, then appended with 5" for WW .

Expand that to three letters, you get ((x*10)+y)*10 + z = x*100 + y*10 + z , which is a three digit number for x, y, z < 10

Note: You should ask if a string of all Z's is a string 0000 , or just int 0

The number 1234 is not equal to 1+2+3+4; it is equal to (((1*10)+2)*10+3)*10)+4.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM