Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply math operations to each number from a list in python?

I am a beginner at python (one week). Here I am trying print the list of all the prime factor of 60. But for line 19, I am getting following error: TypeError: unsupported operand type(s) for %: 'float' and 'list'

The code:

whylist = []
factor = []
boom = []
primefactor = []
n = 60
j = (list(range(1, n, 1)))



for numbers in j:
    if n%numbers == 0:
        whylist.append(numbers)
        for everynumber in whylist:
            factor.append(everynumber)

for things in factor:
    u = (list(range(1, things, 1)))
    d = float(things)
    if d%u == 0:
        boom.append(things)
    if len(boom) == 1:
        for every in boom:
            primefactor.append(every)
print(primefactor)

What am I doing wrong?

like image 766
Mubtasim Avatar asked Jul 16 '12 19:07

Mubtasim


1 Answers

To apply a math operation to every element in a list you can use a list-comprehension:

new_list = [ x%num for x in old_list]

There are other ways to do it as well. Sometimes people will use map

new_list = map(lambda x: x%num, old_list)

but most people prefer the first form which is generally more efficient and clear than using lambda (which can be a little confusing when you're just starting to learn python).

EDIT

Here's a recursive implementation of what you were trying:

def factorize(n):
    out=[]
    for i in range(2,n):
        if(n%i == 0): #first thing to hit this is always prime
            out.append(i) #add it to the list
            out+=factorize(n/i)  #get the list of primes from the other factor and append to this list.
            return out
        else:
            return [n] # n%i was never 0, must be prime.

print factorize(2000)
like image 69
mgilson Avatar answered Nov 04 '22 13:11

mgilson