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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With