I’m a beginner programmer, I decided to write a simple program getting prime factors out of a number and then printing them, but I’m having trouble in printing the final result. Here’s the code:
n = int(raw_input("Number?: "))
m = n
k = 2
czynniki = []
while(m != 1):
if m%k == 0:
czynniki.append(k)
print m, "\t", '|', k
m = m/k
else:
k+=1
print m
print n, ' = ',
for czynnik in czynniki:
if czynniki.count(czynnik)>1:
print czynnik, '^', czynniki.count(czynnik), ' *',
czynniki = filter(lambda x: x!=czynnik, czynniki)
else:
print czynnik, ' *',
Everything is okay until the very end. For example I’d like it to print “1025 = 5^2 * 41” when 1025 is inputed, but instead it will print “1025 = 5^2 * 5 * 41”, as if filter function had no impact at all. Where’s the bug?
You’re starting the
forloop over the list that is stored inczynniki, that you’re later changing whatczynnikireferences (a totally new list) does not change which list theforloops over. It’s not safe to change the actual list a loop is running over either, so you can’t really do it like this either way.You may want to rewrite the loop something like this, just skip the duplicate values instead and not try to change the loop while running;