如何修改以下代码,以使其打印包含给定列表中项目因素的单独列表?
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)
答案 0 :(得分:1)
我会使用一个简单的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]
答案 1 :(得分:-1)
这对我有用:
hash
结果:
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
与Linux命令('Factors of ', 3)
3
('Factors of ', 4)
2
2
('Factors of ', 5)
5
>>>
巧合地工作:
factor
答案 2 :(得分:-1)
我对您的代码进行了一些重构,以使其更具可读性和易懂性:
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])
让我知道这是否回答了您的问题吗?