Программа для отображения основных факторов целого числа - PullRequest
0 голосов
/ 09 июня 2018

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

# we ask for input
num = int(input('enter the number of which you would like to find prime factors of\n='))
div_list = []  # we create an empty list to store all the divisors of the number
prime_div = []  # we create a list for all the prime divisors
for _ in range(2, num-1):  # we check all the divisors
    if num % _ == 0:
        div_list.append(_)  # we add all the divisors to the list
for i in range(len(div_list)):  # this loop will run the next loop for the duration of all the nums
    for j in range(2, div_list[i]):
        if div_list[i] % j == 0:
            pass
        else:
            prime_div.append(div_list[i])


print('the list of all the prime factors is')
print(prime_div)

, но когда я запускаю эту программу, она дает мне ввод только 1 цифры.:

enter the number of which you would like to find prime factors of
=49
the list of all the prime factors is
[7, 7, 7, 7, 7]

Я не понимаю, почему это происходит.Есть идеи?

1 Ответ

0 голосов
/ 09 июня 2018

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

num = int(input('enter the number of which you would like to find prime factors of\n='))
div_list = []  # we create an empty list to store all the divisors of the number
prime_div = []  # we create a list for all the prime divisors
for _ in range(2, num-1):  # we check all the divisors
    if num % _ == 0:
        div_list.append(_)  # we add all the divisors to the list

for i in range(len(div_list)):  # this loop will run the next loop for the duration of all the nums
    for j in range(2, div_list[i]):
        if div_list[i] % j == 0:
            pass
    else: #This line will execute if div_list[i] is a prime number. You were executing else clause again and again
        prime_div.append(div_list[i]) #removed extra indentation, this was causing your error


print('the list of all the prime factors is')
print(prime_div)

Примечание: пожалуйста, старайтесь не использовать _ в качествепеременная или заполнитель в python.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...