Python:拆分数字并将其分解为2
此代码用于标识第四次将数字分解为2时是否会得到1Python:拆分数字并将其分解为2,python,Python,此代码用于标识第四次将数字分解为2时是否会得到1 a = int(input()) terms = 4 result = list(map(lambda x: a ** x, range(terms))) for i in range(terms): print(a, "^2 = ", result[i]) if result == 1: print('True') else: print('False') 如果我输入14,这是结果: 14 ^2 = 1 14 ^2 =
a = int(input())
terms = 4
result = list(map(lambda x: a ** x, range(terms)))
for i in range(terms):
print(a, "^2 = ", result[i])
if result == 1:
print('True')
else:
print('False')
如果我输入14,这是结果:
14 ^2 = 1
14 ^2 = 14
14 ^2 = 196
14 ^2 = 2744
False
但我希望它是这样的
1^2 + 4^2 = 17
1^2 + 7^2 = 50
5^2 + 0^2 = 25
2^2 + 5^2 = 29
False
首先,
a=str(int(input())
似乎没有必要,因为input()
本身返回字符串
其次,将其强制转换为字符串。。。在str(a)中:
再次(再次不必要)
第三,您正在迭代某个字符串(在本例中为a
),该字符串将生成一个字符流,但您的代码的编写方式与您期望的一样
例如
for char in "abc":
print(char)
for a, b in "abc":
print(a, b)
。。。将打印
a
b
c
你基本拥有的
for char in "abc":
print(char)
for a, b in "abc":
print(a, b)
。。。这里会发生什么
你希望你的代码会发生什么 试试这个:
a = str(int(input()))
def split_and_print(a):
x = [int(y) for y in list(str(a))]
return sum([y**2 for y in x])
def split_sum_print(a):
a_split = list(str(a))
print(' + '.join([x+'^2' for x in a])+ ' = '+str(split_and_print(a)))
return str(split_and_print(a))
n = 4
for i in range(n):
a = split_sum_print(a)
if a == '1':
print(True)
else:
print(False)
输出:
14
1^2 + 4^2 = 17
1^2 + 7^2 = 50
5^2 + 0^2 = 25
2^2 + 5^2 = 29
False
我做了两个函数,一个负责计算,另一个负责打印。然后将它们组合起来,并对循环使用
。更改n
以获得不同的迭代次数。您是否绝对确定您得到了“nothing”,或者是否出现了错误?我不确定您想要什么,但至少我可以说您比较了列表和数字,这没有任何意义。有一个错误是::str(a)中的b,c:ValueError:没有足够的值来解包(预期2,得到1)我无法理解你认为“str(a)中的b,c”应该怎么做。str(a)将只返回a,因为a已经是一个字符串。我将编辑并放入运行的原始代码,但这不是我想要的结果。