【问题标题】:How do I print out a list of common factors for two numbers?如何打印出两个数字的公因数列表?
【发布时间】:2020-01-06 21:14:24
【问题描述】:
我需要打印出两个数字的公因数列表
def print_nums(x, y):
for i in range(1, x + 1):
if x % i == 0:
print(i)
for t in range(1, y + 1):
if y % t == 0:
print(t)
number = int(input("Enter a number: "))
number2 = int(input("Enter a second number: "))
print("Common factors are: ".format(number, number2))
print_nums(number, number2)
它打印出两个列表,但不是每个列表的公因子
【问题讨论】:
标签:
python
python-3.x
list
for-loop
【解决方案1】:
def print_nums(x, y):
zet = []
for i in range(1, x + 1):
if x % i == 0:
#print(i)
zet.append(i)
for t in range(1, y + 1):
if y % t == 0 and t in zet:
print(t)
number = int(input("Enter a number: "))
number2 = int(input("Enter a second number: "))
print("Common factors are:")
print_nums(number, number2)
运行代码示例:
Enter a number: 24
Enter a second number: 18
Common factors are:
1
2
3
6
【解决方案2】:
您的代码只打印因子,而不是公因子。您可以遍历x 和y 的公共范围并检查i 是否是两者的一个因素:
def common_factors(x, y):
for i in range(2, min(x, y)+1): # 1 is trivial, so ignore it
if x % i == 0 and y % i == 0: # If x and y are both multiples of i
yield i
print(list(common_factors(9, 12))) # -> [3]
【解决方案3】:
与上述解决方案的想法基本相同..但是一个漂亮的函数基本上只检查列表中非唯一的项目..就像 set 的反面一样...这会返回共同因素,因为它们会出现更多一次
from iteration_utilities import duplicates, unique_everseen
facs=[]
def print_nums(x, y, facs):
for i in range(1, x + 1):
if x % i == 0:
facs.append(i)
for t in range(1, y + 1):
if y % t == 0:
facs.append(t)
return list(unique_everseen(duplicates(facs)))