Reputation: 23
I have a script that creates a list of numbers, and i want to remove all numbers from the list that are not whole numbers (i.e have anything other than zero after the decimal point) however python creates lists where even whole numbers get .0 put on the end, and as a result i cant tell them apart from numbers with anything else. I can't use the int() function as it would apply to all of them and make them all integers, and then i'd lose the ones that originally were.
Here is my code:
z = 300
mylist = []
while(z > 1):
z = z - 1
x = 600851475143 / z
mylist.append(x)
print(mylist)
[y for y in mylist if y #insert rule to tell if it contains .0 here]
the first bit just divides 600851475143 by every number between 300 and 1 in turn. I then need to filter this list to get only the ones that are whole numbers. I have a filter in place, but where the comment is i need a rule that will tell if the particular value in the list has .0
Any way this can be achieved?
Upvotes: 2
Views: 659
Reputation: 29913
You're performing an integer division, so your results will all be integers anyway.
Even if you'd divide by float(z)
instead, you'd run the risk of getting rounding errors, so checking for .0
wouldn't be a good idea anyway.
Maybe what you want is
if 600851475143 % z == 0:
mylist.append(600851475143/z)
It's called the "modulo operator", cf. http://docs.python.org/reference/expressions.html#binary-arithmetic-operations
EDIT: Ralph is right, I didn't put the division result into the list. Now it looks ugly, due to the repetition of the division ... :) gnibbler's answer is probably preferable, or Ralph's.
Upvotes: 4
Reputation: 76057
jellybean's answer is quite good, so I'd summarise:
magic_num = 600851475143
filtered_list = [magic_num/i for i in range(300,0,-1) if magic_num%i == 0]
(the division operator should be integer //
, but the code coloriser interprets it as a comment, so I've left the single slash)
Upvotes: 0
Reputation: 5232
You can use divmod() and only put the result of an "even divide" in to your list:
z = 300
mylist = []
while(z > 1):
z = z - 1
x,y = divmod(600851475143, z)
if y==0:
mylist.append(x)
print(mylist)
Upvotes: 2
Reputation: 304167
You can use int()
- just not the way you were thinking of perhaps
z = 300
mylist = []
while(z > 1):
z = z - 1
x = 600851475143 / z
mylist.append(x)
print(mylist)
[y for y in mylist if y==int(y)]
Upvotes: 1
Reputation: 463
Use regular expressions to match what you need. In your case, it should be check for ".0" at the end of the string, thus re.search("\.0$", y)
. Please be aware that you should use re.search, because re.match checks only for match at the beginning of the string.
Edit: sorry, I was disappointed with
however python creates lists where even whole numbers get .0
and thought that you are making it list of strings. jellybean gave you the answer.
Upvotes: 0