-1

I know that similar questions exist, but I'd like to know what is wrong with my code in particular. Thanks in advance!

isum = 0
l = list(range(2, uplim + 1))

while l != []:
    isum += l[0]
    temp = list(range(l[0], uplim + 1, l[0]))
    l = list(set(l) - set(temp))

print(isum)

Explanation: the first loop execution will add 2 (being the first term in the list) to the sum variable and remove all multiples of 2 from the list. 3 will now be the first term in the list and this will be added to isum, followed by all multiples of 3 being removed. 5 will now be the first term (because 4 was removed - being a multiple of 2) etc.

NVH
  • 13
  • 2
  • In what way does it not behave as you want? – Scott Hunter Nov 24 '13 at 12:28
  • 2
    Welcome to Stack Overflow! It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, stack traces, compiler errors - whatever is applicable). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask] – Inbar Rose Nov 24 '13 at 12:28
  • It simply doesn't output the correct answer :/ – NVH Nov 24 '13 at 12:32
  • 1
    Well, for a start, you don't seem to be restricting the sum to include only primes. How did you think that would happen? – Chris Johnson Nov 24 '13 at 12:36
  • it's based on the sieve of eratosthene – NVH Nov 24 '13 at 12:39
  • Really, the actual algorithm looks so much different http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes here is an optimization thread of fast primes http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/2068548#2068548 – user1462442 Nov 24 '13 at 12:47
  • Can you provide a few examples of input (uplim) and the output, and how it differs from what you expected? I ran a few simplistic test cases -- seemed to work fine. – Chris Johnson Nov 24 '13 at 13:07
  • Thank you but I found that that the list just needed to be sorted after each loop execution – NVH Nov 24 '13 at 13:12

1 Answers1

0

Sets are unordered. The idea behind the code is okay, but converting lists to sets loses the ordering information, and converting back to lists produces a worse than random ordering; you can't make any guarantees about it, even statistically. The first element of l isn't guaranteed to be the lowest, so it isn't guaranteed to be a prime, and everything goes to hell.

user2357112 supports Monica
  • 215,440
  • 22
  • 321
  • 400