Piotr Koller
Piotr Koller

Reputation: 621

Print numbers divisible by prime numbers in Python

I want to create a function that print numbers from a list in this order:

-numbers divisible by 0 and 1

-numbers divisible by prime numbers (all numbers divisble by 2,then numbers divisible by 3,etc.)

I have two functions earlier in my code. Basic "max" function and "prime_numbers" function that prints prime numbers up to given number, e.g. prime_numbers (50). Both are working fine.

This is the part of my function I have problems with:

if max(x) >= 2: 
    divisors = prime_numbers(maks(x)) 
    for i in divisors:
        sel = [x % i == 0 for x in i]
        result.append([i for i in sequence if sequence in sel])
        sequence = [i for i in sequence if i not in sequence]

For loop is a mess. What I want to do is the thing I did when writing same function in R.

sel <- !as.logical(sequence %% i) 
result <- c(result,sequence[sel]) 
sequence <- sequence[!sel]

'Sequence' is already declared in the code and it contains numbers from the list that are bigger or equal to 2. 'Result' is also declared and it contains numbers smaller than 2.

I want to iterate over divisors (prime_numbers) and:

I'm much more familiar with R than Python and it was easier there. I tried to do something with list comprehensions, but I don't understand it as good.

Upvotes: 1

Views: 985

Answers (1)

Bestasttung
Bestasttung

Reputation: 2458

That should do the trick :

# result and sequence are defined higher
# and are lists
if max(x) >= 2: 
    divisors = prime_numbers(maks(x)) 
    for i in divisors:
        result += [x for x in sequence if x % i == 0]

As your answered comment I edited my answer and this should do the work

Upvotes: 1

Related Questions