Calculate Pi using the Wallis formula:
$ \Large\pi = 2\cdot{\LARGE\Pi}_{i=1}^\infty\frac{4i^2}{4i^2 - 1} $
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)
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]:
Based on the system dictionary, find
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]
Out[2]:
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])
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])
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]])
In [6]:
# Find Palindromes.
palindromes = [x for x in semordnilap if x[::-1] == x]
print(palindromes[-1:-6:-1])
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]:
In [ ]: