Python Club

Meeting 4


Exercises

Exercise 5.a

The following uses the logical operator not with the relational operator '>'. See if you can write this using only relational operators (!=, >, <, >=, <=).

Solution


In [113]:
x = 5
if not x > 5:
    print 'x is not bigger than 5'
if x <= 5:
    print 'version 2: x is not bigger than 5'


x is not bigger than 5
version 2: x is not bigger than 5

Exercise 5.b

What is the point of elif? Why not just use two if statements in a row? Write an example that demonstrates the differece between:

if <condition>
  <body>
if <condition>
  <body>

and

if <condition>
  <body>
elif <condition>
  <body>

Solution

In the first case both if statements will be reached in the flow of the program. In the second case the elif will only be reached if the condition from the if is false:

if <condition 1>
  <body>
if <condition 2>  <--- flow of execution will reach this no matter what the first if is
  <body>

and

if <condition 1>
  <body>
elif <condition 2>  <--- flow of execution will only reach this if <condition 1> is false
  <body>

In [2]:
x = 1
if x > 0:
    x += 1
if x > 1:
    x += 1
print(x)


3

In [3]:
x = 1
if x > 0:
    x += 1
elif x > 1:
    x += 1
print(x)


2

Exercise 5.c

We have an annotation that starts at position 1000 and ends at position 2000. Write a function that returns true if a gene occupies any part of the annotation. For example:

>>> gene_in_annotation(snp=432)
False
>>> gene_in_annotation(snp=1023)
True
>>> gene_in_annotation(snp=4502)
False

Solution


In [11]:
def gene_in_annotation(snp):
    if snp >= 1000 and snp <= 2000:
        return True
    else:
        return False

In [7]:
gene_in_annotation(snp=432)


Out[7]:
False

In [13]:
gene_in_annotation(snp=1023)


Out[13]:
True

In [12]:
gene_in_annotation(snp=4502)


Out[12]:
False

Exercise 5.3

Fermat’s Last Theorem says that there are no positive integers a, b, and c such that

a**n + b**n = c**n

for any values of n greater than 2.

  1. Write a function named check_fermat that takes four parameters—a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that an + bn = cn the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.”

  2. Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat’s theorem.

Solution


In [16]:
#!/usr/bin/env python

def check_fermat(a,b,c,n):
    if n <= 2:
        print("Fermat's Last Theorem only holds for n>2")
        return
    else:
        if a ** n + b ** n == c ** n:
            print("Holy smokes, Fermat was wrong!")
        else:
            print("No, that doesn't work")


def get_user_input():
    a = int(raw_input("Enter a: "))
    b = int(raw_input("Enter b: "))
    c = int(raw_input("Enter c: "))
    n = int(raw_input("Enter n: "))
    check_fermat(a, b, c, n)


if __name__ == "__main__":
    get_user_input()


Enter a: 5
Enter b: 6
Enter c: 9090
Enter n: 65
No, that doesn't work

Exercise 5.4

If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle: If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.)

  1. Write a function named is_triangle that takes three integers as arguments, and that prints either “Yes” or “No,” depending on whether you can or cannot form a triangle from sticks with the given lengths.
  2. Write a function that prompts the user to input three stick lengths, converts them to integers, and uses is_triangle to check whether sticks with the given lengths can form a triangle.

Solution


In [20]:
#!/usr/bin/env python

def is_triangle(side1, side2, side3):
    if (side1 + side2 == side3) or (side1 + side3 == side2) or (side2 + side3 == side1):
        print("Yes")
    else:
        print("No")


def get_user_input():
    side1 = int(raw_input("Enter length of side 1: "))
    side2 = int(raw_input("Enter length of side 2: "))
    side3 = int(raw_input("Enter length of side 3: "))
    is_triangle(side1, side2, side3)

if __name__ == "__main__":
    get_user_input()


Enter length of side 1: 23
Enter length of side 2: 23
Enter length of side 3: 46
Yes

Exercise 5.c

Bonus. Sometimes we want to split a file location into its file name and directory parts. Look into the os module documentation to figure out how to split the following up:

loc = '/a/path/name/to/something/filename.ext'
==>
('/a/path/name/to/something', 'filename.ext')

Solution


In [14]:
loc = '/a/path/name/to/something/filename.ext'
import os
parts = os.path.split(loc)
print parts[0]
print parts[1]


/a/path/name/to/something
filename.ext