题
我正在尝试制作一个程序,以将任何基部的数字转换为用户选择的另一个基础。到目前为止,我所拥有的代码如下:
innitvar = float(raw_input("Please enter a number: "))
basevar = int(raw_input("Please enter the base that your number is in: "))
convertvar = int(raw_input("Please enter the base that you would like to convert to: "))
这些是我从用户那里获得的数据。初始数字,其初始基础以及用户想要转换为的基础。据我了解,我需要转换为基础10,然后转换为用户指定的所需基础。
这是我撞到砖墙的地方:我需要将初始数字中的最左数乘以其初始底座,然后在右侧添加下一个数字,然后重复直到击中最右边的数字。我了解如何在纸上执行此操作,但我不知道如何将其放入Python代码中。我不确定如何乘以第一个数字,然后添加下一个数字,也不了解如何让程序知道何时停止执行此操作。
我并不是要为我编写该程序,但我想指出正确的方向。
谢谢你的时间!
解决方案
这应该是您问题的答案的前半部分。您能弄清楚如何转换为基础吗?
# Create a symbol-to-value table.
SY2VA = {'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'A': 10,
'B': 11,
'C': 12,
'D': 13,
'E': 14,
'F': 15,
'G': 16,
'H': 17,
'I': 18,
'J': 19,
'K': 20,
'L': 21,
'M': 22,
'N': 23,
'O': 24,
'P': 25,
'Q': 26,
'R': 27,
'S': 28,
'T': 29,
'U': 30,
'V': 31,
'W': 32,
'X': 33,
'Y': 34,
'Z': 35,
'a': 36,
'b': 37,
'c': 38,
'd': 39,
'e': 40,
'f': 41,
'g': 42,
'h': 43,
'i': 44,
'j': 45,
'k': 46,
'l': 47,
'm': 48,
'n': 49,
'o': 50,
'p': 51,
'q': 52,
'r': 53,
's': 54,
't': 55,
'u': 56,
'v': 57,
'w': 58,
'x': 59,
'y': 60,
'z': 61,
'!': 62,
'"': 63,
'#': 64,
'$': 65,
'%': 66,
'&': 67,
"'": 68,
'(': 69,
')': 70,
'*': 71,
'+': 72,
',': 73,
'-': 74,
'.': 75,
'/': 76,
':': 77,
';': 78,
'<': 79,
'=': 80,
'>': 81,
'?': 82,
'@': 83,
'[': 84,
'\\': 85,
']': 86,
'^': 87,
'_': 88,
'`': 89,
'{': 90,
'|': 91,
'}': 92,
'~': 93}
# Take a string and base to convert to.
# Allocate space to store your number.
# For each character in your string:
# Ensure character is in your table.
# Find the value of your character.
# Ensure value is within your base.
# Self-multiply your number with the base.
# Self-add your number with the digit's value.
# Return the number.
def str2int(string, base):
integer = 0
for character in string:
assert character in SY2VA, 'Found unknown character!'
value = SY2VA[character]
assert value < base, 'Found digit outside base!'
integer *= base
integer += value
return integer
这是解决方案的后半部分。通过使用这两个功能,转换基础非常容易执行。
# Create a value-to-symbol table.
VA2SY = dict(map(reversed, SY2VA.items()))
# Take a integer and base to convert to.
# Create an array to store the digits in.
# While the integer is not zero:
# Divide the integer by the base to:
# (1) Find the "last" digit in your number (value).
# (2) Store remaining number not "chopped" (integer).
# Save the digit in your storage array.
# Return your joined digits after putting them in the right order.
def int2str(integer, base):
array = []
while integer:
integer, value = divmod(integer, base)
array.append(VA2SY[value])
return ''.join(reversed(array))
将所有内容放在一起之后,您应该最终以下面的程序结束。请花点时间弄清楚!
innitvar = raw_input("Please enter a number: ")
basevar = int(raw_input("Please enter the base that your number is in: "))
convertvar = int(raw_input("Please enter the base that you would like to convert to: "))
# Create a symbol-to-value table.
SY2VA = {'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'A': 10,
'B': 11,
'C': 12,
'D': 13,
'E': 14,
'F': 15,
'G': 16,
'H': 17,
'I': 18,
'J': 19,
'K': 20,
'L': 21,
'M': 22,
'N': 23,
'O': 24,
'P': 25,
'Q': 26,
'R': 27,
'S': 28,
'T': 29,
'U': 30,
'V': 31,
'W': 32,
'X': 33,
'Y': 34,
'Z': 35,
'a': 36,
'b': 37,
'c': 38,
'd': 39,
'e': 40,
'f': 41,
'g': 42,
'h': 43,
'i': 44,
'j': 45,
'k': 46,
'l': 47,
'm': 48,
'n': 49,
'o': 50,
'p': 51,
'q': 52,
'r': 53,
's': 54,
't': 55,
'u': 56,
'v': 57,
'w': 58,
'x': 59,
'y': 60,
'z': 61,
'!': 62,
'"': 63,
'#': 64,
'$': 65,
'%': 66,
'&': 67,
"'": 68,
'(': 69,
')': 70,
'*': 71,
'+': 72,
',': 73,
'-': 74,
'.': 75,
'/': 76,
':': 77,
';': 78,
'<': 79,
'=': 80,
'>': 81,
'?': 82,
'@': 83,
'[': 84,
'\\': 85,
']': 86,
'^': 87,
'_': 88,
'`': 89,
'{': 90,
'|': 91,
'}': 92,
'~': 93}
# Take a string and base to convert to.
# Allocate space to store your number.
# For each character in your string:
# Ensure character is in your table.
# Find the value of your character.
# Ensure value is within your base.
# Self-multiply your number with the base.
# Self-add your number with the digit's value.
# Return the number.
integer = 0
for character in innitvar:
assert character in SY2VA, 'Found unknown character!'
value = SY2VA[character]
assert value < basevar, 'Found digit outside base!'
integer *= basevar
integer += value
# Create a value-to-symbol table.
VA2SY = dict(map(reversed, SY2VA.items()))
# Take a integer and base to convert to.
# Create an array to store the digits in.
# While the integer is not zero:
# Divide the integer by the base to:
# (1) Find the "last" digit in your number (value).
# (2) Store remaining number not "chopped" (integer).
# Save the digit in your storage array.
# Return your joined digits after putting them in the right order.
array = []
while integer:
integer, value = divmod(integer, convertvar)
array.append(VA2SY[value])
answer = ''.join(reversed(array))
# Display the results of the calculations.
print answer
其他提示
我需要将初始数字中的最左数乘以其固有的基础,然后在右侧添加下一个数字,然后重复直到击中最右边的数字。
因此,您需要获得数字。在列表中。
提示1:使用 divmod()
功能将数字分解为数字。除以10,获得小数位数。
提示2:而 n > 0:您可以使用 divmod()
获得商和剩余的。如果将其余的保存在列表中,并将商用作新值 n 您的电话号码越小,直到剩下的数字为零,您就完成了。
提示3:您的数字以左顺序到达。利用 reverse
要切换此列表的顺序,您会打扰您。或使用使用 insert(0,digit)
.
现在您有了数字。在列表中。您可以迭代列表。
尝试 for
尺寸的语句。
您可能需要使用“多个”和“添加”循环。 total = total * new_base + next_digit
是循环的身体经常外观的方式。
只是一个学生,对您需要的东西的想法放慢了脚步。您可能不需要您认为需要的东西。
从开头开始:用户输入一个数字。用户输入一个基础。这些都是字符串。假设基地为12,数字为1ab3。因此,您在12^3的位置中有一个“ 1”,在12^2的位置中有一个'a',在12^1中有a'b',在12^0(一个)位置中有一个'b'。如果您希望在基本10中使用此数字,则需要将一些数字添加在一起。
具体来说,您需要添加1*12^3 + 10*12^2 + 11*12^1 + 3*12^0。在这里注意:您有3,2,1,0。这很好地对应于输入字符串1AB3的长度。所以可能是一个 for
循环在这里会有所帮助。用户不输入整数,他们输入字符串。因此,您需要字符串中的字符,而不是数字中的数字。
您怎么知道符号为“ A”和“ C”在十进制表示法中表示什么?看看Noctis Skytower的答案!
因此,您的第一个任务是弄清楚如何通过字符串迭代。您的第二个任务是弄清楚如何使用字符串中的单个字符值以在Noctis Skytower的答案中访问字典,而您的第三个任务是弄清楚如何编写利用该信息的循环。
您需要编写两个功能。在方案中(由于我知道方案比Python:-P要好得多),这两个功能被称为 string->number
和 number->string
, ,尽管您当然可以随心所欲地命名它们。
这些功能中的每一个都需要采用基本参数来进行转换。如果愿意,您可以将其默认为10。
一旦您成功实施了每个这些,其余的就是小菜一碟。
给您的测试用例:
assert str2num('1234', 10) == 1234
assert str2num('1234', 16) == 0x1234
assert num2str(1234, 10) == '1234'
assert num2str(1234, 16) == '4d2'
assert num2str(0x1234, 16) == '1234'
我来这里寻找捷径,但看起来不存在。因此,这是我发现的漫长方法。这个答案是基于答案 Quora 并在这里与其他答案有关。
最简单的方法(可能)是将任何数字从基本B1转换为B2是转换B1→十进制→B2。
基础B1中的数字可以像基础B1中的多项式一样对待
即,一个4位数字abcd = d*(b1^0)+c*(b1^1)+b*(b1^2)+a*(b1^3)
例如,123(十进制)= 3*(10^0)+2*(10^1)+1*(10^2)
因此,要从任何基数转换为十进制,请找到所有的总和 [digit*(base^power)]
(其中功率为0至[numofdigits-1]) 以数字的相反顺序。为此,将数字视为 string
并使用一个 for
环形。
因此,输入应该是 string
和OP int
.
下一步是将小数数D转换为基本B2。
Divide D/B2,其余的是最右边的数字。将商除以B2,其余的是下一个最右边的数字。重复此周期,直到商为0。
例如。,
8(12月)到二进制:
8/2=4; 8%2=0
4/2=2; 4%2=0
2/2=1; 2%2=0
1/2=0; 1%2=1
8(dec)= 1000(bin)
这是通过将输出编号视为字符串的,并在将所有数字串联后逆转字符串来完成。 (看上面: '0' + '0' + '0' + '1' ='0001'
,将其反转🠢'1000'
对于这两个过程,以下Python程序将做:
N=input("Num:")
B1=int(input("FromBase:"))
B2=int(input("ToBase:"))
print("Base[",B1,"]:",N)
#From Base B1 to Decimal
DN=0
for i in range(len(N)):
DN+= int(N[::-1][i]) * (B1 ** i)
print("Decimal:",DN)
#From Decimal to Base B2
if int(N) == 0:
BN = 0
else:
BN = ""
while DN > 0:
BN += str(DN % B2)
DN = int(DN / B2)
print("Base[",B2,"]:",int(BN[::-1]))
但是您会注意到,使用碱超过10。为此,您需要使用更多数字来表示值超过0-9。为此,您必须长时间使用 if-else
梯子可以根据面值选择数字,反之亦然。
N=input("Num:")
B1=int(input("FromBase:"))
B2=int(input("ToBase:"))
print("Base[",B1,"]:",N)
#From Base B1 to Decimal
DN=0
for i in range(len(N)):
if N[::-1][i] == '0':
DN += 0 * (B1 ** i)
elif N[::-1][i] == '1':
DN += 1 * (B1 ** i)
elif N[::-1][i] == '2':
DN += 2 * (B1 ** i)
''' :
: '''
elif N[::-1][i] == 'A':
DN += 10 * (B1 ** i)
''' :
: (fill it) ....
: '''
print("Decimal:",DN)
#From Decimal to Base B2
if int(N) == 0:
BN = 0
else:
BN = ""
while DN > 0:
R = DN % B2
if R==0:
BN += '0'
elif R==1:
BN += '1'
elif R==2:
BN += '2'
''' :
:
: '''
elif R==10:
BN += 'A'
''' :
:
: '''
DN = int(DN / B2)
print("Base[",B2,"]:",int(BN[::-1]))
几乎每个人都避免了这么长的时间 if-else
通过使用带有面值的字典作为键,符号/数字作为其各自的值。现在该程序变为:
Dig={0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F', 16: 'G', 17: 'H', 18: 'I', 19: 'J'}
N=input("Num:")
B1=int(input("FromBase:"))
B2=int(input("ToBase:"))
print("Base[",B1,"]:",N)
#From Base B1 to Decimal
DN=0
for i in range(len(N)):
for fv in Dig:
if Dig[fv]== N[::-1][i]: # FaceValue of the Digit
DN+= fv * (B1 ** i)
print("Decimal:",DN)
#From Decimal to Base B2
if N == '0':
BN = 0
else:
BN = ""
while DN > 0:
BN += Dig[DN % B2] # Digit for the Value
DN = int(DN / B2)
print("Base[",B2,"]:",BN[::-1])
🠅有您的作业。选择这些三种方法的任何内容。
要使用更多的基础,您可以扩展字典并创建一个像 @这样的长字典。Noctis Skytower.
我检查过的每个网站都有这样的长词典,但是我倾向于使用几乎所有内容的快捷方式。我用简单 range()
功能, if-else
陈述和简单 for
循环缩短过程(但我认为尽管很简单,但我认为它看起来有些混乱)。这样做的优点是,只要添加键就可以很容易地添加更多基础 range(a,b)
, ,对于数字的面值和值的范围 range(x,y)
, ,对于各个值的字符的Unicode值范围。
Val = {range(10):range(48, 58), range(10,36): range(65, 91)}
N=input("Num:")
B1=int(input("FromBase:"))
B2=int(input("ToBase:"))
print("Base[",B1,"]:",N)
#From Base B1 to Decimal
DN = 0
for i in range(len(N)):
for j in Val:
if ord(N[i]) in Val[j]:
FV=j[ord(N[i])-Val[j][0]] # FaceValue of the Digit
if FV>= B1: # Digits aren't >=Base, right?
print("Base Error..")
exit()
else:
DN += FV * (B1 ** (len(N) - 1 - i))
print("Decimal:",DN)
#From Decimal to Base B2
if int(DN) == 0:
BN = '0'
else:
BN = ""
while DN > 0:
R = DN % B2
for i in Val:
if R in i:
BN+=chr(Val[i][R-i[0]]) #Finding the Digit for the Value
DN = int(DN / B2)
print("Base[", B2, "]:", BN[::-1])
这也可以使用功能来完成:
Val = {range(10):range(48, 58), range(10,36): range(65, 91)}
def B2D(N,B1):
'''From Base B1 to Decimal'''
DN = 0
for i in range(len(N)):
for j in Val:
if ord(N[i]) in Val[j]:
FV=j[ord(N[i])-Val[j][0]] # FaceValue of the Digit
if FV>= B1: # Digits aren't >=Base, right?
print("Base Error..")
exit()
else:
DN += FV * (B1 ** (len(N) - 1 - i))
return DN
def D2B(DN,B2):
'''From Decimal to Base B2'''
if int(DN) == 0:
BN = '0'
else:
BN = ""
while DN > 0:
R = DN % B2
for i in Val:
if R in i:
BN+=chr(Val[i][R-i[0]]) #Finding the Digit for the Value
DN = int(DN / B2)
return BN[::-1]
def B2B(N,B1,B2):
return D2B(B2D(N,B1),B2)
N=input("Num:")
B1=int(input("FromBase:"))
B2=int(input("ToBase:"))
print("Base[",B1,"]:",N)
print("Decimal:",B2D(N,B1))
print("Base[",B2,"]:",B2B(N,B1,B2))
现在,如果您可以扩展字典,则可以转换为 任何 基础 任何 根据。 😎
这些是我在其他Stackoverflow QA和其他网站上发现的一些快捷方式:
将2和36之间的任何基部的数字转换为十进制: int(‘NumberString’,Base)
>>> int('1000',2)
8
>>> int('100',12)
144
>>> int('AA',17)
180
>>> int('Z',36)
35
>>> int('Z',37)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: int() base must be >= 2 and <= 36, or 0
将小数转换为二进制,八分和十六进制:
>>> bin(8)
'0b1000'
>>> oct(8)
'0o10'
>>> hex(8)
'0x8'
希望这个 TL;DR
帮助某人。如果有人可以指出任何错误,进行编辑或提供较短的方法,我将不胜感激。