The Big Exercise - Part 1

Exercise 1

Calculate Pi using the Wallis formula:

$ \Large\pi = 2\cdot{\LARGE\Pi}_{i=1}^\infty\frac{4i^2}{4i^2 - 1} $

  • Ok, not exactly :)
  • But find at least 2 ways to do it!
  • Bonus point if you use recursion.

In [17]:
# Version 1
limit = 10000
p = 2
for i in range(1,limit+1):
    p *= (4.0 * i**2)/(4.0 * i**2 - 1)
    
print(p)


3.14151411868

In [1]:
# Version 2
def pirec(i):
    if i == 0:
        return(2)
    return((4.0 * i**2)/(4.0 * i**2 - 1) * pirec(i-1))

## Don't call with larger parameter!
pirec(100)


Out[1]:
3.133787490628162

Exercise 2

Based on the system dictionary, find

  1. Palindromes (words that remain the same when read backward), and
  2. Semordnilap (words that become other words, when read backward).

What are the longest five palindromes and semordnilap, respectively?
Plot histograms of the palindrome- and semordnilap-distribution.


In [1]:
# The path to the dictionary:
wordspath = "/usr/share/dict/american"
# Each line of the file contains one word

# Read the words in the file into a list; don't forget to close the file when you are done.
wordsfile = open(wordspath, 'r')
words = wordsfile.readlines()
wordsfile.close()

In [2]:
# Look at a couple of words. What might be systematically wrong here?
# Fix it using str.strip()
print(words[30:40])
words = [x.strip('\n') for x in words]
print(words[30:40])
words[14]


['Aaronical\n', 'Aaronsburg\n', "Aaronsburg's\n", 'aarrgh\n', 'aarrghh\n', "AA's\n", "A'asia\n", 'aasvogel\n', 'aasvogels\n', 'AB\n']
['Aaronical', 'Aaronsburg', "Aaronsburg's", 'aarrgh', 'aarrghh', "AA's", "A'asia", 'aasvogel', 'aasvogels', 'AB']
Out[2]:
"Aaliyah's"

In [3]:
# Disregard capitalization
# Hint: Use "str.lower()"
# Test with 15th word from the list: "Aaliyah's".
print(words[14])
words = [ x.lower() for x in words ]
print(words[14])


Aaliyah's
aaliyah's

In [4]:
#### EXTRA BONUS - IGNORE IN FIRST TRY !!! ##########
# remove non-letter characters, such as apostrophes

## Hint: Use "char()"; the ASCII-codes for lower-case letters are 97 to 122.
## Hint: The "[f(x) for x in list if condition]" - "filter" construct could be handy here.
## Hint: How to make a list of characters into a string? Use " ''.join(list) ".
## Hint: Also nested list-comprehension can be used.

letters = [chr(x) for x in range(97, 123)]
words = [''.join([x for x in word if x in letters]) for word in words]
print(words[14])


aaliyahs

In [5]:
# Find semordnilap. (A semornildap is a word that, spelled backwards, gives a different word)
## Hint: Maybe use the "set"-datatype
## Hint:The string-method "list.sort(key=len)" will sort a list according to len(list_element).

revwords = [ x[::-1] for x in words ]
semordnilap = set(words) & set(revwords)
semordnilap = list(semordnilap)
semordnilap.sort(key=len)
print(semordnilap[-1:-6:-1])
print([x[::-1] for x in semordnilap[-1:-6:-1]])


['rotavator', 'malayalam', 'desserts', 'redrawer', 'rewarder']
['rotavator', 'malayalam', 'stressed', 'rewarder', 'redrawer']

In [6]:
# Find Palindromes.
palindromes = [x for x in semordnilap if x[::-1] == x]
print(palindromes[-1:-6:-1])


['rotavator', 'malayalam', 'rotator', 'halalah', 'reviver']

In [7]:
# Plot histograms
# Hint: use "hist()"

subplot(1,2,1)
hist([len(x) for x in palindromes], bins=arange(0.5,10,1))
title('Palindromes')
subplot(1,2,2)
hist([len(x) for x in semordnilap], bins=arange(0.5, 19,1) )
title('Semordnilap')


Out[7]:
<matplotlib.text.Text at 0x409c190>

Exercise 3

Write a program that takes an integer as user input and reports whether that is a prime number or not.


In [ ]: