Найти LCM на срок до 5 номеров - PullRequest
1 голос
/ 16 марта 2020

Я пытаюсь написать программу, которая будет рассчитывать LCM до пяти чисел.
Я уже написал этот код:

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

Когда я пытаюсь запустить код Я получаю эту ошибку:

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.

Ответы [ 3 ]

2 голосов
/ 16 марта 2020

Потому что x - это список string, а не integers. Для проверки вы можете конвертировать x в список integers.

a=b=True
while a:
    # Map x to list of integers
    x = list(map(int, input('\nEnter two to five numbers separated by commas: ').split(',')))   
    # Check if there is zero or any negative number in x.
    if len(list(filter(lambda e: e <= 0, x))) > 0:
        print('\n No zeroes or negative numbers')
        continue
    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
1 голос
/ 16 марта 2020

вы можете сначала выполнить простую факторизацию, а затем вычислить LSM:

from collections import Counter, defaultdict
from functools import reduce

def prime_factors(n):
    primes = []

    i = 2
    while n > 1:
        while n % i == 0:
            n = n / i
            primes.append(i)
        i = i + 1
    if primes:
        return primes

    return [n] # if n is a prime

def lcm(my_list):
    f = [Counter(prime_factors(e)) for e in my_list]

    lcm_primes =  Counter()
    for d in f:
        for prime, count in d.items():
            lcm_primes[prime] = max((lcm_primes[prime], count))

    return reduce(lambda x, y: x * (y[0] ** y[1]),  lcm_primes.items(), 1)

lcm([3, 15, 9, 6, 2])

output:

90
1 голос
/ 16 марта 2020

Может быть, что-то вроде этого, может подойти для ваших целей:

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)

При запуске печатает lcm из 5 введенных чисел.

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