[英]Decimal to Hexadecimal recursively python
I can get the function to work regularly but when I do it recursively, it repeats infintely and I have to 'Ctrl C'to end it in the shell.我可以让函数定期工作,但是当我递归地执行它时,它会无限重复,我必须“Ctrl C”才能在 shell 中结束它。
Non recursive非递归
def convert_10_to_16(n):
hexlist =[]
x = n // 16
if x < 10:
hexlist.append(x)
elif (x == 10):
hexlist.append('A')
elif (x == 11):
hexlist.append('B')
elif (x == 12):
hexlist.append('C')
elif (x == 13):
hexlist.append('D')
elif (x == 14):
hexlist.append('E')
elif (x == 15):
hexlist.append('F')
y = n % 16
if y < 10:
hexlist.append(y)
elif (y == 10):
hexlist.append('A')
elif (y == 11):
hexlist.append('B')
elif (y == 12):
hexlist.append('C')
elif (y == 13):
hexlist.append('D')
elif (y == 14):
hexlist.append('E')
elif (y == 15):
hexlist.append('F')
return ''.join(hexlist)
Recursive递归
def convert_10_to_16(n):
hexlist =[]
x = n // 16
if x < 10:
hexlist.append(x)
elif (x == 10):
hexlist.append('A')
elif (x == 11):
hexlist.append('B')
elif (x == 12):
hexlist.append('C')
elif (x == 13):
hexlist.append('D')
elif (x == 14):
hexlist.append('E')
elif (x == 15):
hexlist.append('F')
y = n % 16
if y < 10:
hexlist.append(y)
elif y >= 10:
z = y
convert_10_to_16(z)
I'm not sure how I can get it to work recursively so any help is greatly appreciated!我不确定如何让它递归工作,因此非常感谢任何帮助!
You need a recursive case and a base case.您需要一个递归案例和一个基本案例。
But more important than that is to use variable names that have meaning .但比这更重要的是使用有意义的变量名。
def convert_digit_to_hex(x):
if x < 10:
return str(x)
elif (x == 10):
return 'A'
elif (x == 11):
return 'B'
elif (x == 12):
return 'C'
elif (x == 13):
return 'D'
elif (x == 14):
return 'E'
elif (x == 15):
return 'F'
def convert_number_to_hex(n):
remaining_digits = n // 16
last_digit = n % 16
if remaining_digits == 0:
return convert_digit_to_hex(last_digit)
else:
return convert_number_to_hex(remaining_digits) + convert_digit_to_hex(last_digit)
This can be done simply, and recursively, without built-in functions and without a list
data structure:这可以简单地递归完成,无需内置函数和list
数据结构:
DIGITS = "0123456789ABCDEF"
def convert_10_to_16(number):
number, remainder = number // 16, DIGITS[number % 16]
if number:
return convert_10_to_16(number) + remainder
return remainder
if __name__ == "__main__":
for number in range(257):
print(number, '=', convert_10_to_16(number))
When doing a recursive function for converting decimal to hexadecimal in python, you can use the "%" which is a string formatting operator.在python中执行将十进制转换为十六进制的递归函数时,可以使用“%”,它是一个字符串格式化操作符。 By using "%x" or "%X" it helps convert the decimal into hexadecimal.通过使用“%x”或“%X”,它有助于将十进制转换为十六进制。
def main():
#Asks user for decimal
number = int(input("Enter a decimal: "))
num = convert(number)
print(num)
def convert(dec):
#Converts the decimal to hexadecimal
hex = "%X" % dec
print("The hexadecimal is: ", end="")
#Prints hexadecimal
return hex
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.