代码敲出来跟想要的有出入,大佬看看该怎么改
N=int(input())for num in range(2, N):
num_list = []
for i in range(1, num):
if num % i == 0:
num_list.append(i)
if num == sum(num_list):
print("{} its factors are {}".format(num ,num_list))
代码输出的结果
6 its factors are
28 its factors are
496 its factors are
想要的结果
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
N=int(input())
for num in range(2, N):
num_list = []
for i in range(1, num):
if num % i == 0:
num_list.append(i)
if num == sum(num_list):
print("{} its factors are {}".format(num , ' '.join(num_list)))# 改了这里 N = int(input())
for num in range(2, N):
num_list = []
for i in range(1, num):
if num % i == 0:
num_list.append(i)
if num == sum(num_list):
print(num, "its factors are ", end = " ")
for number in num_list:
print(number, end = " ")
print() isdkz 发表于 2022-12-30 15:17
这个貌似不行吧{:10_282:}>>> ' '.join()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
' '.join()
TypeError: sequence item 0: expected str instance, int found
N=int(input())
for num in range(2, N):
num_list = []
for i in range(1, num):
if num % i == 0:
num_list.append(i)
if num == sum(num_list):
print("{} its factors are {}".format(num, str(num_list).replace(',', '')) )
或者N=int(input())
for num in range(2, N):
num_list = []
for i in range(1, num):
if num % i == 0:
num_list.append(i)
if num == sum(num_list):
nums = ''
for i in num_list: nums += str(i)+' '
print("{} its factors are {}".format(num, nums[:len(nums)-1]))#去掉末尾空格
tommyyu 发表于 2022-12-30 15:21
这个貌似不行吧
是我疏忽了,我改一下 本帖最后由 isdkz 于 2022-12-30 15:33 编辑
N=int(input())
for num in range(2, N):
num_list = []
for i in range(1, num):
if num % i == 0:
num_list.append(i)
if num == sum(num_list):
print("{} its factors are {}".format(num , ' '.join(map(str, num_list))))# 改了这里 isdkz 发表于 2022-12-30 15:24
输入20224
输出最后一项的时候卡了。运行超时
20224
6 its factors are1 2 3
28 its factors are1 2 4 7 14
496 its factors are1 2 4 8 16 31 62 124 248
8128 its factors are1 2 4 8 16 32 64 127 254 508 1016 2032 4064 爱意随风起9306 发表于 2022-12-30 15:39
输入20224
输出最后一项的时候卡了。运行超时
20224
数太大了,建议改进一下算法 isdkz 发表于 2022-12-30 15:47
数太大了,建议改进一下算法
{:5_99:} for num in range(2, N):
改成for num in range(2, N+1):
要不然执行不到N
页:
[1]