1. Define a function maximum that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.)
In [ ]:
def maximum(x, y):
if x > y:
return x
else:
return y
In [ ]:
assert maximum(3, 3) == 3
assert maximum(1, 2) == 2
assert maximum(3, 2) == 3
2. Define a function max_of_three that takes three numbers as arguments and returns the largest of them.
In [ ]:
def max_of_three(x, y, z):
if x > y and x > z:
return x
elif y > x and y > z:
return y
elif z > x and z > y:
return z
else:
return x
In [ ]:
assert max_of_three(1, 2, 3) == 3
assert max_of_three(1, 1, 2) == 2
assert max_of_three(2, 1 , .5) == 2
assert max_of_three(0, 0, 0) == 0
3. Define a function length that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.)
In [ ]:
def length(obj):
len = 0
for _ in obj:
len += 1
return len
In [ ]:
assert length([1, 2, 3]) == 3
assert length('this is some string') == 19
4. Write a function is_vowel that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
In [ ]:
def is_vowel(char):
return char in 'aeiou'
In [ ]:
assert is_vowel('t') == False
assert is_vowel('a') == True
5. Define a function accumulate and a function multiply that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.
In [ ]:
def accumulate(obj):
res = 0
for num in obj:
res += num
return res
def multiply(obj):
res = 1
for num in obj:
res *= num
return res
In [ ]:
assert accumulate([1, 2, 3, 4]) == 10
assert multiply([1, 2, 3, 4]) == 24
A more elegant and generic solution is given hereafter. It uses a functional approach, as the function that is to be calculated is passed to the function:
In [ ]:
from operator import add, mul
def calc(obj, func):
res = None
if func == add:
res = 0
if func == mul:
res = 1
for num in obj:
res = func(res, num)
return res
print(calc([1, 2, 3, 4], mul))
print(calc([1, 2, 3, 4], add))
6. Define a function reverse that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".
In [ ]:
def reverse(s):
return ''.join([c for c in s[::-1]])
In [ ]:
assert reverse('I am testing') == 'gnitset ma I'
7. Define a function is_palindrome that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True.
In [ ]:
def is_palindrome(s):
return s == reverse(s)
In [ ]:
assert is_palindrome('radar') == True
assert is_palindrome('sonar') == False
8. Write a function is_member that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)
In [ ]:
def is_member(x, a):
for v in x:
if v == a:
return True
return False
In [ ]:
assert is_member([1, 2, 3], 4) == False
assert is_member([1, 2, 3], 2) == True
9. Define a procedure histogram that takes a list of integers and prints a histogram to the screen. For example, histogram([4, 9, 7]) should print the following:
****
*********
*******
In [ ]:
def histogram(obj):
for n in obj:
print('*' * n, '\n')
In [ ]:
histogram([4, 9, 7])
10. Write a function filter_long_words that takes a list of words and an integer n and returns the list of words that are longer than n.
In [ ]:
def filter_long_words(words, n):
return [word for word in words if len(word) >= n]
In [ ]:
assert len(filter_long_words('this is some sentence'.split(), 3)) == 3
11. A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: "The quick brown fox jumps over the lazy dog". Your task here is to write a function is_pangram to check a sentence to see if it is a pangram or not.
In [ ]:
def is_pangram(sentence):
alphabet = set('a b c d e f g h i j k l m n o p q r s t u v w x y z'.split())
for char in sentence:
try:
alphabet.remove(char)
except KeyError:
pass
if len(alphabet) == 0:
return True
else:
return False
In [ ]:
assert is_pangram('foo') == False
assert is_pangram('The quick brown fox jumps over the lazy dog') == True
12. Represent a small bilingual lexicon as a Python dictionary in the following fashion {"may": "möge", "the": "die", "force": "macht", "be": "sein", "with": "mit", "you": "dir"} and use it to translate the sentence "may the force be with you" from English into German. That is, write a function translate that takes a list of English words and returns a list of German words.
In [ ]:
def translate(eng):
dictionary = {
"may": "möge",
"the": "die",
"force": "macht",
"be": "sein",
"with": "mit",
"you": "dir"
}
ger = []
for word in eng:
if word in dictionary:
ger.append(dictionary[word])
else:
ger.append(word)
return ger
In [ ]:
assert translate("may the force be with you".split()) == ['möge', 'die', 'macht', 'sein', 'mit', 'dir']
13. In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary:
key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
Your task in this exercise is to implement an encoder/decoder of ROT-13 called rot13. Once you're done, you will be able to read the following secret message:
Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English.
In [ ]:
def rot13(msg):
key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
res = []
for char in msg:
if char in key:
res.append(key[char])
else:
res.append(char)
return ''.join(res)
In [ ]:
text = 'this is some text'
assert rot13(rot13(text)) == text
14. Write a procedure char_freq_table that accepts the file name material/jedi.txt as argument, builds a frequency listing of the characters contained in the file, and prints a sorted and nicely formatted character frequency table to the screen.
In [1]:
from collections import defaultdict
import string
def char_freq_table(filename):
char_counter = defaultdict(int)
with open(filename) as fh:
text = fh.read()
for character in text:
char_counter[character] += 1
return char_counter
frequencies = char_freq_table('material/jedi.txt')
with open('jedi_frequencies.txt', 'w') as fh:
for k, v in frequencies.items():
if k in string.printable.replace('\n', '') :
fh.writelines('| {} || {} |\n'.format(k, v))
In [2]:
with open('material/jedi_frequencies.txt') as fh:
print(fh.read())