Search code examples
pythonlistlcm

Find the LCM for up to 5 numbers


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

How is this possible? My input was 0.


Solution

  • 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)
    

    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