Tutorial Questions: Week 6: "" "Hello"
Tutorial Questions: Week 6: "" "Hello"
Semester 1, 2016
Tutorial Questions: Week 6
VERSION : 810, DATE : A PRIL 7, 2016
Exercises
1. For the following list comprehensions: (a) evaluate the expression; and (b) write
the corresponding Python code which would generate an object of the same
content, without using a list comprehension (using for statements, etc.):
(a)
(b)
(c)
3. Compare the following two functions with respect to the given function calls,
and answer the following questions. (1) Are there inputs for which the output of
the two functions will differ? (2) Are there instances where one version should
be preferred over the other?
def noletter1(wordlist, letter='z'):
for word in wordlist:
if letter in word:
return False
return True
def noletter2(wordlist, letter='z'):
noz = True
for word in wordlist:
if letter in word:
noz = False
return noz
wordlist = ['zizzer'] + ['aadvark'] * 10000000
print(noletter1(wordlist))
print(noletter2(wordlist))
Problems
1. [From the Early-Release Tutesheet] A palindromic number is a positive integer that reads the same both ways. The largest palindromic number made from
the product of two 2-digit integers is 9009 = 91 99.
Write a function palnum(num) that returns the largest palindromic number made
from the product of two num-digit numbers.
2. Write a function hypotenuse(a, b) that returns (as a float) the length of the hypotenuse of a right-angled triangle with side lengths a and b (both positive numbers). Use Pythagoras theorem a2 + b2 = c2 , and the implementation of square
root in the math library (math.sqrt).
4. Using a defaultdict, write a function hapax(text) which returns an alphabeticallysorted (based on Unicode code point values) list of all words in text that occur
exactly once. Note that a word is defined simply to be a string that is surrounded by white space.