4

I have a word problem I am trying to solve but am getting stuck on a key part.

Convert the following English description into Python code.

Initialize n to be 100. Initialize numbers to be a list of numbers from 2 to n, but not including n. With results starting as the empty list, repeat the following as long as numbers contains any numbers.

  • Add the first number in numbers to the end of results.

  • Remove every number in numbers that is evenly divisible by (has no remainder when divided by) the number that you had just added to results.

How long is result?

When n is 100, the length of results is 25.

So far I have understood to set n = 100, and a range(2, 100), results = [] and that the result will be an append situation as in results.append(numbers[]), but I am having a mental block figuring the key of "Remove every number in numbers that is divisible by the number that was added to results".

======after a couple minutes=======

As Michael0x2a said - this is a problem when i have to implement an algorithm that finds all the primes from 2 to n, using the Sieve of Eratosthenes.

I think I can continue to deal with this problem.

Thank's a lot for your answers guys.

Community
  • 1
  • 1
Matt
  • 75
  • 1
  • 8

2 Answers2

3
n = 100
numbers = range(2,100)
results = []
while len(numbers) > 0:
    results.append(numbers[0])
    numbers = [number for number in numbers if number % results[-1] != 0]
print len(results)
Kyle Neary
  • 889
  • 6
  • 7
  • Dear Kyle, Can you please write a full implementation of your solution? I just trying to figure out how exactly it works. Thanks. – Matt Nov 24 '13 at 17:28
  • Thank's for help Kyle. I've done with your help right that way: `codedef long_implementation(n): numbers = range(2,n) results = [] while len(numbers) > 0: results.append(numbers[0]) for number in numbers: if number % results[-1] == 0: # numbers.remove(number)` – Matt Nov 24 '13 at 18:03
  • @Matvey after `results.append(numbers[0])`, `results[-1]` is just `== numbers[0]`; also, `for number in numbers: if number % results[-1] == 0: numbers.remove(number)` is ***trial division***; but it is the same as `for number in range(numbers[0],100,numbers[0]): if number in numbers: numbers.remove(number)` and *that* ***is*** the sieve of Eratosthenes. – Will Ness Nov 25 '13 at 17:30
2

The following:

Add the first number in numbers to the end of results.

...is not the same as:

results.append(numbers[])

To access the first number in a list, you can use the first index.

Thus:

numbers[0] ## would be the first "number" in numbers

Further, to do the following:

But I am having a mental block figuring the key of "Remove every number in numbers that is divisible by the number that was added to results".

...you will need some way of testing what a number is divisible by, which means you'll need to use modulo:

some_number % some_other_number

If there's no remainder, the modulo will result in a zero.

erewok
  • 7,555
  • 3
  • 33
  • 45