Reputation: 3
I am creating a program that would get all the factors of a number(including its negative counterpart) for rational root theorem purposes.
I am successful in getting the positive roots but I can't seem to append the negative roots into my list and it just keeps requiring an input. Here's the code.
a = input("Number:")
c = []
for b in (1,a+1):
if a%b == 0:
c.append(b)
for d in c:
e = (-1)*d
c.append(d)
print c
So I tried deleting the "c.append(d)" part and replaced it with "print e". And it printed the negative factors.
Upvotes: 0
Views: 3749
Reputation: 19264
1st, never modify the list as you're looping over it, there is always a high chance something bad will happen.
2nd, you call for b in (1,a+1)
, you need a range
before the (1, a+1)
, as such: for b in range(1,a+1)
.
3rd, if print e
gives the correct info, then e
must contain what you want to add. Thus, you can just add c.append(e)
under c.append(d)
.
4th, your use of input()
leads me to think you are using python2.x. However, if this is the case, consider using int(raw_input())
instead of input()
. If you are not using python2.x, and using python3.x then cast int()
to your input()
to make int(input())
.
a = input("Number:")
c = []
for b in range(1,a+1):
if a%b == 0:
c.append(b)
temp = []
for d in c:
e = (-1)*d
temp.append(d)
temp.append(e)
for i in temp:
c.append(i)
print c
Upvotes: 1
Reputation: 304393
Here you are chasing your tail forever. Since you are appending one new item for each iteration. ie. you are looping over the "live" c, not a snapshot of what it was when the loop started.
for d in c:
e = (-1)*d
c.append(d)
Simpler to replace it with a list comprehension
c += [-d for d in c]
Here is a snippet that shows the problem of extending c
on the fly
>>> for d in c:
... print -d
... c.append(-d)
...
-1
-2
-3
-4
-5
1
2
3
4
5
-1
-2
-3
-4
-5
1
2
3
4
5
-1
-2
-3
-4
-5
1
2
3
4
5
-1
-2
-3
-4
-5
Upvotes: 0
Reputation: 805
This may be simpler to read
a = input("Number:")
positives = []
for i in range(1, a+1):
if a % i == 0:
positives.append(i)
negatives = [-x for x in positives]
print 'positives:', positives
print 'negatives:', negatives
Upvotes: 0
Reputation: 102902
You're appending the wrong variable. Try this:
a = int(input("Number: "))
c = []
for b in range(1, a+1):
if a % b == 0:
c.append(b)
for d in c:
e = -1 * d
c.append(e) # append the negated number instead of the original...
And yes, modifying the list you're iterating over is a bad idea. Try using a temp list instead.
Upvotes: 0