Ask Your Question
0

Is it possible to speed up loop iteration in Sage?

asked 2018-03-03 12:10:30 +0100

anonymous user

Anonymous

updated 2018-03-03 13:16:20 +0100

I have a sage code that looks like this:

    uni = {}
    end = (l[idx]^(e[idx] - 1)) * (l[idx] + 1) # where end in my case is about 2013265922 but can also be much larger
    for count in range(0, end):
        i = randint(1, 303325737249669131)  
        if i in uni:
            uni[i] += 1
        else:
            uni[i] = 1

So basically, I want to create very large number of random integers in the given range, check whether the number was already in the dictionary, if yes increment its count, if not initialize it to 1. But, this takes such a long time that it doesn't finish in a reasonable time. Is there any way to speed up this kind of loops in Sage (or Python)?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2018-03-03 13:52:14 +0100

calc314 gravatar image

Using Cython can dramatically improve performance by converting the code to C and compiling it. For example,

%%cython
import random
def run(end): 
    uni = {}

    for count in range(0, end):
        i = random.randint(1, 303325737249669131)  
        if i in uni:
            uni[i] += 1
        else:
            uni[i] = 1
    return uni
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-03-03 12:10:30 +0100

Seen: 523 times

Last updated: Mar 03 '18