我创建了一个Python函数,它接受任意数量的整数输入并返回LCM。我想让用户以友好的方式传递任意数量的输入,然后让我的函数计算它们。在
我已经找到了一种合理的方法,让用户一次传递一个整数并将它们附加到一个列表中,但是,我似乎无法让我的函数以列表或元组的形式来处理这个问题。在
这是我的代码:
#Ask user for Inputs
inputs = []
while True:
inp = input("This program returns the LCM, Enter an integer,\
enter nothing after last integer to be evaluated: ")
if inp == "":
break
inputs.append(int(inp))
#Define function that returns LCM
def lcm(*args):
""" Returns the least common multiple of 'args' """
#Initialize counter & condition
counter = 1
condition = False
#While loop iterates until LCM condition is satisfied
while condition == False :
counter = counter + 1
xcondition = []
for x in args:
xcondition.append(counter % x == 0)
if False in xcondition:
condition = False
else:
condition = True
return counter
#Execute function on inputs
result = lcm(inputs)
#Print Result
print(result)
*args
的思想是获取任意数量的参数,并将它们作为一个列表处理,以便于处理。在但是只插入一个参数-列表。在
要么使用
lcm(*inputs)
(它将列表解压为不同的参数),要么只将列表作为参数(这意味着lcm
被简单地定义为lcm(args)
)。在你需要打开你的清单
但总的来说,我会说接受一个序列(
list
,tuple
,等等)参数要比担心*arg
解包更具Python味。在相关问题 更多 >
编程相关推荐