Day 13 - Russian Peasant's Algorithm Complete.

I woke up early this morning, and decided that I should get moving on the Python Next Level course. I’ve gone through the first couple of sections, but it’s time to really dig in. I finally finished up the first exercise, the Russian Peasant’s Algorithm. If you need to know more about what it is, go here . In a nutshell, it’s one of the first methods used to multiply to large numbers together.

The things I learned in this section of the course were:

Here’s the code:

#!/usr/bin/env python
""" Russian Peasant's Algorithm """
import time

CACHE = {}

def russian(num1, num2):
    key = (num1, num2)

    if key in CACHE:
        z = CACHE[key]
    else:
        print 'Not in Cache'
        x = num1; y = num2    ## Compound Assignment
        z = 0                 ## Acumulator

        while x > 0:          ## While Loop Begins
            if x % 2 == 1:    ## Modulo operator
                z = z + y     ## Acumulate Sum
            y = y << 1        ## Shift Binary Left
            x = x >> 1        ## Shift Binary Right

        CACHE[key] = z
        return z              ## Return Z

def test_russian():
    start_time = time.time()
    print russian(357, 16)
    print 'Russian Algorithm took %f seconds' % (time.time() - start_time)

    start_time = time.time()
    print russian(357, 16)
    print 'Russian Algorithm took %f seconds' % (time.time() - start_time)

    #assert russian(357, 16) == 5712

test_russian()

I commented out that last assertion b/c I kept getting an AssertionError, and I’m not sure why. It’s probably something simple. I’ll look into it, but if you have a clue, help me out.

#hustleandcode.

Jason T Clark

Jason T Clark

Father. Musician. Gamer. Coder.

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin