所以,我已经在这个工作了几个小时,这是一个家庭作业,我只是无法弄清楚代码为什么不能完全执行。我提供了所有代码,看看是否有一些我错过了&assign?' assign2'功能。但是,我知道问题就在那里,想弄清楚什么是错的。
我基本上试图获取最后生成的数字并将其转回代表Napier arithmetic的字母(即a = 0,b = 1,c = 2 ... z = 25 )并将它们放在一个列表中,我可以在主函数中打印。除了最后一部分之外,其他一切都有效,我试图找出原因。
def main():
again = "y"
while again == "y" or again == "Y":
var = checkalpha()
num = assign(var)
print("The first number is: {}".format(num))
var2 = checkalpha()
num2 = assign(var2)
print("The second number is: {}".format(num2))
arithmetic = getsign()
value = equation(num, num2, arithmetic)
newvar = assign2(value)
print("The result is {} or {}".format(value, newvar))
again = input("Would you like to repeat the program? Enter y for yes, n for no: ")
def checkalpha():
num = input("Enter Napier number: ")
while not num.isalpha():
print("Something is wrong. Try again.")
num = input("Enter Napier number: ")
return num
def assign(char):
value = 0
for ch in char:
value += 2 ** (ord(ch) - ord("a"))
return value
def getsign():
operand = input("Enter the desired arithmetic operation: ")
while operand not in "+-*/":
operand = input("Something is wrong. Try again. ")
return operand
def equation(num, num2, arithmetic):
if arithmetic == "+":
answer = num + num2
elif arithmetic == "-":
answer = num - num2
elif arithmetic == "*":
answer = num * num2
elif arithmetic == "/":
answer = num / num2
else:
input("Something is wrong. Try again. ")
return answer
def assign2(n):
new = []
while n != 0:
value = n%2
x = n//2
ch = chr(value + ord("a"))
new.append(ch)
n = x
return new
main()
答案 0 :(得分:0)
你的功能相当接近。问题出在ch = chr(value + ord("a"))
上。我们需要将位位置编码到字母表中该位置的字母中。如果该位置的位不为零,则会将一个字母添加到列表中。在函数结束时,我们可以将字母列表加入到字符串中。
这是您的函数的修复版本,其中包含一些测试代码,用于验证它是否适用于Location_arithmetic上的维基百科文章中的示例
def assign2(n):
new = []
position = 0
while n != 0:
value = n % 2
x = n // 2
if value:
ch = chr(position + ord("a"))
new.append(ch)
n = x
position += 1
return ''.join(new)
# test
data = [
(87, 'abceg'),
(3147, 'abdgkl'),
]
for n, napier_string in data:
s = assign2(n)
print(n, napier_string, s, napier_string == s)
<强>输出强>
87 abceg abceg True
3147 abdgkl abdgkl True
这是该函数的更多Pythonic版本,名称更有意义。
def int_to_napier(n):
new = []
for position in range(26):
if n == 0:
break
value, n = n % 2, n // 2
if value:
new.append(chr(position + ord("a")))
return ''.join(new)
这是另一个通过循环包含小写字母的字符串来避免字符计算。
from string import ascii_lowercase
def int_to_napier(n):
new = []
for ch in ascii_lowercase:
if n == 0:
break
value, n = n % 2, n // 2
if value:
new.append(ch)
return ''.join(new)