AmirZpr
AmirZpr

Reputation: 275

Merge two for-loops into one for-loop

The goal of this code is to determine whether a number is prime or not, and if it isn't, prints the numbers that the given number can be divided by.

My question is: Is it possible to merge two for loops into one for loop in the code presented below?

num = 224

list1 = []

for i in range(2, num):
    if num % i == 0:
        list1.append(i)

for i in range(2, num):
    if num % i == 0:
        print(num, 'is not prime and can be divided by the following numbers:\n', list1)
        break
else:
    print(num, 'is Prime.')

Upvotes: 0

Views: 876

Answers (4)

AmirZpr
AmirZpr

Reputation: 275

Based on given answers, the best way to redesign the code is this:

num = 224

list1 = [i for i in range(2, num) if num % i == 0]

if list1:
    print(num, 'is not prime and can be divided by the following numbers:\n', list1)
else:
    print(num, 'is Prime.')

Thank you @matthieu-brucher and @blhsing

Upvotes: 1

Jake
Jake

Reputation: 637

The second for loop is not needed

num = 224

list1 = []

for i in range(2, num):
    if num % i == 0:
        list1.append(i)

if (not list1):
    print(num, 'is Prime.')
else:
    print(num, 'is not prime and can be divided by the following numbers:\n', list1)

Upvotes: 0

zipa
zipa

Reputation: 27879

This should do it, example with 10 numbers:

n = 10

for i in range(2, n + 1):
    divisors = []
    for j in range(2, i):
        if i % j == 0:
            divisors.append(j)
    if divisors:
        print('{} is not prime and can be divided by the following numbers: {}.'.format(i, divisors))
    else:
        print('{} is prime.'.format(i))

Output:

2 is prime.
3 is prime.
4 is not prime and can be divided by the following numbers: [2].
5 is prime.
6 is not prime and can be divided by the following numbers: [2, 3].
7 is prime.
8 is not prime and can be divided by the following numbers: [2, 4].
9 is not prime and can be divided by the following numbers: [3].
10 is not prime and can be divided by the following numbers: [2, 5].

Upvotes: 0

blhsing
blhsing

Reputation: 106768

Since you've already constructed list1 with all the divisors in the first loop you can just make use of it in a condition instead of iterating through the same sequence for the second time:

for i in range(2, num):
    if num % i == 0:
        list1.append(i)
if list1:
    print(num, 'is not prime and can be divided by the following numbers:\n', list1)
else:
    print(num, 'is Prime.')

Upvotes: 1

Related Questions