Primes Problem in Python

السلام عليكم و رحمة الله و بركاته

Lately I decided to give SPOJ website a try ..
And my first problem after the TEST problem was the “PRIME1” problem..
Which is basically finding the prime numbers between 2 given numbers ..

Yesterday, regardless the fact of being truly ill and I hardly could open my eyes ..
I decided to solve the problem ..

and after I think 1 hour It started to output relatively right solution ..

here is my code in python:

times = input()
while times > 0:
    times -= 1
    limits = raw_input()
    limits = limits.split(" ")
    downLimit = int(limits[0])
    upLimit = int(limits[1])
    numsList = []
    numsList = [i for i in range(downLimit,upLimit) if (i%2 or i==2) and i != 1 and i!=0]
    primesList = list(numsList)
    for oddNumber in numsList:
        primeNumber = True;
        for number in range( 2 , oddNumber / 2):
            if oddNumber % number == 0:
                primeNumber = False;
                break;

        if not primeNumber:
            primesList.remove( oddNumber )

    for primeNumber in primesList:
        print primeNumber

Notes:
1-in line 9, I used list() to assign the numsList value to the primesList list .. not the numsList as python-strangely- assigns the old list reference to the new list and that caused +1 hour of debug .. :@
2-As shown in page title after submitting the problem they replied that solution exceed the time limit .. so any help will be appreciated ..
3-Python version 2.6.2 on Mac

10 Comments

KAMFebruary 5th, 2010 at 2:11 PM

hehe .. exceeds the time limit :) .. it should.

First about your first note:
“python-strangely” :D … Actually , i can say “AlSayedGamal – strangely – haven’t already known about that yet :)

Second some obvious – and stupid – optimizations:

1 -
numsList = [i for i in range(downLimit,upLimit) if (i%2 or i==2) and i != 1 and i!=0]
do you know that you’re asking every single element in the list created by range(x,y) if it’s 1 and if it’s 0 and if it’s 2 .. is it possible to have more than 0 , 1 , 2 elements …. just start from 3 and then include 2 later ( of course after checking you downLimit to see where should you start )

2 -
if not primeNumber:
primesList.remove( oddNumber )
begad alot of time will be wasted here (unless python’s implementation is caching the last list accesses :) , you can just print the primes – and this is exactly what you did later :D – since the list itself is of no good later

if primeNumber:
print THE_PRIME

3 – Use another approach
Just keep incrementing from your donwLimit to your upLimit in a loop and do all the possible checks in a nested loop – which will safe you the overhead of creating a zillion list.

KAMFebruary 5th, 2010 at 2:15 PM

Just to clarify , “in point 3″ – mine not yours – loop here as in “while” loop.

meFebruary 5th, 2010 at 2:33 PM

Thanks for your comment ..
So first of all did you expected that .. from Python behavior .. ?
2,3
Reason of doing that is I’m thinking of using this list in next time .. I generate primes..
Anyway:
Check that:

times = input()
while times > 0:
    times -= 1
    limits = raw_input()
    limits = limits.split(" ")
    downLimit = int(limits[0])
    upLimit = int(limits[1])
    numsList = []
    if downLimit < = 2:
        numsList = [i for i in range(2,upLimit) if  i == 2 or i % 2]
    else:
        numsList = [i for i in range(downLimit,upLimit) if  i % 2 ]

    for oddNumber in numsList:
        primeNumber = True;
        for number in range( 2 , oddNumber / 2):
            if oddNumber % number == 0:
                primeNumber = False;
                break;

        if primeNumber:
            print oddNumber
meFebruary 5th, 2010 at 2:46 PM

Again ..
time limit exceeded - 4.9M memory usage :(

BTW, someone -using C#- had time limit exceed and 14 M memory usage :)

There must be a better solution
Thanks KAM I Saved .2 Mega

KAMFebruary 5th, 2010 at 3:06 PM

Just a question , how do you write your code with syntax high-lighting enabled in you blog ?( is it just [code][/code] ? ) .

And by the way , Prime Number Generation is a huge topic and a topic under research for centuries . So , yes there must be a better solution. :)

meFebruary 5th, 2010 at 3:13 PM

http://www.lastengine.com/syntax-highlighter-wordpress-plugin/#usage

Check this page for how to use the syntax highlighter ..
I don’t want to search any pre-known algorithms before running out of trials :)

Thanks for your help :)

KAMFebruary 5th, 2010 at 6:31 PM

“So first of all did you expected that .. from Python behavior .. ?”

Maybe python’s everything-is-so-easy behavior may tell you that it’s assigning by value but – a big one is coming – think again , what would things be like if you are assigning by value ? Things will be OK until you need a reference to your objects – as in passing by reference – so python will have to give developers some way to extract the reference – yeah i know pointers and the big “&” is popping up now – and Oops we are hit again by the complex and hazardous pointer programming which some programmers hate – those girls – and we have noway to avoid it.
Now think of the world with assign by reference :) , it’s a pretty nice and girlish one.

The same behavior exist in Java and i’m sure it’ll be in every other programming language that wants to avoid the pointer programming – unless i’m mistaken-.

meFebruary 6th, 2010 at 5:13 AM

well I didn’t get the girlish thing, but it sounded like you meant the pythonic style that enforces less special characters including ampersand ..
Finally I always considered python data structures (tuple, list and dictionary) to be acting like numeric and string data types ..
But It sounds they are not .. and it sounds that PHP effect is still there ..
as PHP array used to be deeply copied in assignment ..

$myArray = array(1,2,3);
$yourArray = $myArray ; // here $yourArray is new copy of $myArray .. "deeply" copied
$yourArray[0] = 3;
$myArray[0] =2;
var_dump($myArray); // first element will be 2
var_dump($yourArray);//first element will be 3

Again thanks for your participation KAM :)

KAMFebruary 6th, 2010 at 8:42 AM

about the girlish thing , check this and it may give you some insights :)
http://www.23monkeys.com/designs/python

and another thing , even numerical and string data types have the same behavior and are implemented in the say way.
For Strings , it doesn’t matter because they’re immutable anyway so you can’t see the effect of changing it somewhere and seeing this change every where through different variables referencing the same object.
and the same thing will apply for integers.

you can check this by

x = "test"
y = x
print id(x)
print id(y)

:) .. BTW , i love the elegance of your theme.

meFebruary 6th, 2010 at 2:54 PM

Well, I knew that fact in the meeting, Ahmed Soliman told me That ..
And I tried that now and they both had the same id :)

BTW, The theme is Mac-like :)

Leave a comment

Your comment


Get Adobe Flash playerPlugin by wpburn.com wordpress themes