[英]Converting input to int throws “invalid literal for int() base 10” when passing in decimal numbers
[英]Conversion of pental to decimal, decimal to pental, adding base 5 numbers and multiplying base 5 numbers using def function
如何将基数为5的数字转换为十进制数,十进制数转换为基数为5的数字,添加基数为5的数字,并使用def函数将基数为5的数字相乘:
gumatj_to_decimal(a)
,将Gumatj数转换为十进制数 decimal_to_gumatj(a)
,将十进制数转换为Gumatj gumatj_add(a, b)
,增加2个Gumatj数字 gumatj_multiply(a, b)
,它是2个Gumatj数的倍数 choice = input ("Choose test:\n")
action = choice[:1]
print ("calling function")
if action == 'g' or action == 'd':
num = int(choice[2:])
if action == 'g':
answer = gumatj.gumatj_to_decimal (num)
else:
answer = gumatj.decimal_to_gumatj (num)
elif action == 'a' or action == 'm':
num1, num2 = map (int, choice[2:].split(" "))
if action == 'a':
answer = gumatj.gumatj_add (num1, num2)
else:
answer = gumatj.gumatj_multiply (num1, num2)
print ("called function")
print (answer)
样本I / O:
Choose test:
d 12
calling function
called function
22
样本I / O:
Choose test:
g 22
calling function
called function
12
样本I / O:
Choose test:
a 12 14
calling function
called function
31
样本I / O:
Choose test:
m 3 4
calling function
called function
22
试试这段代码:
import numpy
def gumatj_to_decimal(num):
return int(str(num), 5)
def decimal_to_gumatj(num):
return numpy.base_repr(num, 5)
def gumatj_add(num1, num2):
return decimal_to_gumatj(gumatj_to_decimal(num1) + gumatj_to_decimal(num2))
def gumatj_multiply(num1, num2):
return decimal_to_gumatj(gumatj_to_decimal(num1) * gumatj_to_decimal(num2))
choice = input("Choose test:\n")
action = choice[:1]
print("calling function")
if action == 'g' or action == 'd':
num = int(choice[2:])
if action == 'g':
answer = gumatj_to_decimal(num)
else:
answer = decimal_to_gumatj(num)
elif action == 'a' or action == 'm':
num1, num2 = map(int, choice[2:].split(" "))
if action == 'a':
answer = gumatj_add(num1, num2)
else:
answer = gumatj_multiply(num1, num2)
print("called function")
print(answer)
示例输出:
Choose test:
d 12
calling function
called function
22
Choose test:
g 22
calling function
called function
12
Choose test:
a 12 14
calling function
called function
31
Choose test:
m 3 4
calling function
called function
22
说明:
Python int
可以将任何base的字符串转换为整数:
def gumatj_to_decimal(num):
return int(str(num), 5)
Numpy的base_repr
可以做到这一点:
def decimal_to_gumatj(num):
return numpy.base_repr(num, 5)
首先将它们转换为十进制,添加它们并将它们转换回基数5:
def gumatj_add(num1, num2):
return decimal_to_gumatj(gumatj_to_decimal(num1) + gumatj_to_decimal(num2))
首先将它们转换为十进制,乘以,将它们转换回基数5:
def gumatj_multiply(num1, num2):
return decimal_to_gumatj(gumatj_to_decimal(num1) * gumatj_to_decimal(num2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.