如何修改以下代码,使其打印包含给定列表中项目因子的单独列表?
n = [3,4,5]
for i in n:
print('Factors of ', i)
for j in range(1,i+1):
if i%j == 0:
print(j)
我会选择一个简单的factors
函数,然后执行循环
def factors(n):
"""Not the most optimal solution"""
return [i for i in range(1, n+1) if not n % i]
n = [3, 4, 5]
for i in n:
print(f'Factors of {i} = {factors(i)}')
输出
Factors of 3 = [1, 3]
Factors of 4 = [1, 2, 4]
Factors of 5 = [1, 5]
我已经重构了你的代码,使其更具可读性和易于理解:
n = [3, 4, 5]
def get_factors(num):
result = []
for i in range(1, num+1):
if num % i == 0:
result.append(i)
return result
print([get_factors(elem) for elem in n])
让我知道这是否回答了您的问题?
这对我有用:
n = [3,4,5]
for i in n:
print('Factors of ', i)
remaining = i
while remaining > 1 :
for j in range(2,remaining+1):
if remaining%j == 0:
print(j)
remaining /= j
结果:
('Factors of ', 3)
3
('Factors of ', 4)
2
2
('Factors of ', 5)
5
>>>
巧合的是,它的工作原理类似于 Linux 命令factor
:
$ factor 3 4 5
3: 3
4: 2 2
5: 5