简体   繁体   English

递归十六进制​​转换Python 3

[英]Recursive Hexadecimal Conversion Python 3

I've made a hexadecimal converter to practice recursion/recursive thinking. 我制作了一个十六进制转换器来练习递归/递归思维。 I, however, The recurssion doesn't appear to be happening as the functions seems to just output the result of 9 as of current.The code is as follows: 但是,我似乎没有发生递归,因为函数似乎只是从当前输出9的结果。代码如下:

import math
curr=0
def convert(x):
    L=len(x)
    L-=1
    sol=0
    if L == 0:
        return 0
    else:
        if x[curr]==["A","a"]:
            v=10
        elif x[curr]==["B","b"]:
            v=11
        elif x[curr]==["C","c"]:
            v=12
        elif x[curr]==["D","d"]:
            v=13
        elif x[curr]==["E","e"]:
            v=14
        elif x[curr]==["F","f"]:
            v=15
        else:
            v=int(x[curr])
        sol+=((v)*(16**(L-1)))
        return sol + convert(x[curr+1])


def main():
    print(convert('98A'))

main()

You can use something like this: 您可以使用如下形式:

class HexMap:
    # mapping char to int
     d = { hex(n)[2:]:n for n in range(16)}

def convert(x):        
    s = 0
    # use reverse string and sum up - no need for recursion
    for i,c in enumerate(x.lower()[::-1]): 
        s += HexMap.d[c]*16**i
    return s

def main():
    print(convert('98A'))

main()

Output: 输出:

2442 

Recursive version: 递归版本:

# class HexMap: see above 

def convert(x):       
    def convert(x,fak): 
        if not x:
            return 0
        else:
            return HexMap.d[x[-1]]*16**fak + convert(x[:-1],fak+1)
    return convert(x.lower(),0)


def main():
    print(convert('98A'))

main()

Same output. 输出相同。

You were setting L = len(x) everytime you call the function. 每次调用该函数时,您都要设置L = len(x)。 Here is one solution: 这是一种解决方案:

    import math
    def convert(x, L):
      c = len(x) - 1
      sol=0
      if L > c:
          return 0
      else:
          if (x[L]=="A" or x[L]=="a"):
              v=10
          elif (x[L]=="B" or x[L]=="b"):
              v=11
          elif (x[L]=="C" or x[L]=="c"):
              v=12
          elif (x[L]=="D" or x[L]=="d"):
              v=13
          elif (x[L]=="E" or x[L]=="e"):
              v=14
          elif (x[L]=="F" or x[L]=="f"):
              v=15
          else:
              v=int(x[L])
          sol+=((v)*(16**(c - L)))
          print(sol)
          return sol + convert(x, L + 1)



    def main():
        print(convert('98A', 0))

    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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