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 :

print 'test'




test




In :

# Version 1
pi = 2*reduce(lambda x,y :x*y, [4.*i**2/(4*i**2-1) for i in range(1,10**6)])
print(pi)




3.14159186819




In :

# Version 2
def getpi(i=1):

pi = 4.*i**2/(4.*i**2-1)
if i==101:
return pi

return pi * getpi(i+1)

res = 2 * getpi()
print res




3.1338642935



## 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 [ ]:

# 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.




In [ ]:

# Look at a couple of words. What might be systematically wrong here?
# Fix it using str.strip()




In [ ]:

# Disregard capitalization
# Hint: Use "str.lower()"
# Test with 15th word from the list: "Aaliyah's".




In [ ]:

#### 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.




In [ ]:

# 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).




In [ ]:

# Find Palindromes.




In [ ]:

# Plot histograms
# Hint: use "hist()"



## Exercise 3

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



In :

n = 2*3*5*7*11*13*17+1
test = np.array([n%i for i in xrange(2,int(np.ceil(n/2)))])
print(np.any(test == 0))
ind,= np.where(test == 0)
print(ind+2)
print(n/(ind+2))




True
[   19    97   277  1843  5263 26869]
[26869  5263  1843   277    97    19]




In :




In [ ]:




In [ ]: