Exercises

If you have got this far you will have a reasonable grasp of the key ideas of programming in Python. To finish, here are a few exercises that you can use to practice your programming skills for next week. Also, to learn more Python ideas, try visiting .

Exercise 1

Write a Python function to add up all of the numbers from 1 to n.

Exercise 2

Euclid’s algorithm to find the greatest common divisor (GCD) of two integers is one of the oldest documented algorithms in the world, dating back to around 300BC. The GCD is the largest number that divides exactly into the two numbers supplied - so for example the GCD of 18 and 15 is 3. The algorithm can be described as follows:

  1. take two numbers, `aandb` - the aim is to find their GCD
  2. while b is greater than zero, repeat the following two steps:
    1. replace b with the remainder when a is divided by b
    2. replace a with the old value of b
  3. When b is zero, a is the GCD

Write a Python function, gcd(a,b) that returns the GCD of a and b.

Solutions to Exercises

Exercise 1

Good Answer:

def sum_upto(n):
    result = 0
    for i in range(n):
        result += i + 1
    return result
print(sum_upto(50))
## 1275

Genius Answer:

def sum_upto(n):
    return n*(n+1)//2
print(sum_upto(50))
## 1275

(see http://mathandmultimedia.com/2010/09/15/sum-first-n-positive-integers/ )

Exercise 2

Good Answer:

def gcd(a,b):
    while b != 0 :
        old_b = b
        b = a % b
        a = old_b
    return a
    
print(gcd(18,15))
## 3

Genius Answer:

def gcd(a,b):
    while b != 0:
        a,b = b, a % b
    return a
print(gcd(18,15))
## 3

(see http://en.wikibooks.org/wiki/Python_Programming/Tuples )