查找最多5个数字的LCM [英] Find the LCM for up to 5 numbers

查看:55
本文介绍了查找最多5个数字的LCM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序来计算最多五个数字的 LCM.
到目前为止,我已经编写了以下代码:

I'm trying to write a program that will calculate the LCM of up to five numbers.
I've written this code so far:

a = b = True
while a == True:
    x = input('\nEnter two to five numbers separated by commas: ').split(',')
    if x.index(0) == True:
        print('\nNo zeroes.')
    if len(x) < 2:
        while b == True:
            x.append(input('\nTwo numbers are needed. Enter one more: '))
            b = False
    if len(x) > 5:
        print('\nDon\'t enter more than five numbers.')
        continue
    a = False

当我尝试运行代码时,出现此错误:

When I try to run the code I get this error:

Enter two to five numbers separated by commas: 0
Traceback (most recent call last):

  File "/home/mint/.config/spyder-py3/lcm.py", line 4, in <module>
    if x.index(0) == True:

ValueError: 0 is not in list

这怎么可能?我的输入是 0 .

How is this possible? My input was 0.

推荐答案

也许像这样的东西,可能适合您的目的:

Maybe something like this, might be suitable for your purposes:

from functools import reduce
from math import gcd

x = []
while len(x) < 2 and len(x) <= 5: # Using this condition removes unneccesary break code:
    x = [int(i) for i in input('\nEnter two to five numbers separated by commas: ').split(',')]
    if x[0] == 0:
        print('\nNo zeroes.')
    if len(x) > 5:
        print('\nDon\'t enter more than five numbers.')
    if len(x) < 2:
        x.append(int(input('\nTwo numbers are needed. Enter one more: ')))

lcm = reduce(lambda x, y: x * y // gcd(x, y), x) # lcm = x * y / gcd(x, y)
print(lcm)

运行时会打印输入的5个数字中的lcm.

When run this prints the lcm, of the 5 inputted numbers.

Enter two to five numbers separated by commas: 1, 2, 3, 4, 5
60

这篇关于查找最多5个数字的LCM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆