141B Lab 2: Pythonic things

In this lab, you will add python code to the empty cells according to the instructions. Tests with the intended output are included so that you can check your progress.

Exercise 1. create a function that takes a character as an argument, if it is 'a' then return 'A' otherwise return the original character. f('a') = 'A' and f(x) = x for all other x.

In [24]:
def f(x):
    if x == 'a':
        up = 'A'
        return up
    else:
        return x
  • Using a list comprehension, apply f to each element of 'banana' and return a list of characters.
  • Try to do the same thing with the map function.
  • Using ''.join concatenate the characters in the list to make a string (the result should be 'bAnAnA').
In [39]:
list = []
for i in range(0, len(word)):
    letter = list.append(f(word[i]))
print list
map(f, list)
['b', 'A', 'n', 'A', 'n', 'A']
Out[39]:
['b', 'A', 'n', 'A', 'n', 'A']
In [40]:
"".join(list)
Out[40]:
'bAnAnA'

Exercise 2. Sum the first 100 numbers in a for loop.

In [6]:
num = 0
for i in range(1, 101):
    num = num + i
print num
5050

Sum the first 100 numbers, but using a generator expression.

In [1]:
sum(x for x in range(1,101))
Out[1]:
5050

Using a generator expression sum the square of the first 100 numbers.

In [2]:
sum(x**2 for x in range(1,101))
Out[2]:
338350

Exercise 3. Let's create the Fibonacci sequence. Start a list $Fib$ of where the first elements are 1,1, and follow the relation that $$Fib[i] = Fib[i-1] + Fib[i-2]$$ Generate the Fibonacci numbers less than 1000 and store it in a list.

In [12]:
list = [1,1]
def fib(x):
    if x == 0:
        return 0
    elif x == 1:
        return 1
    else:
        x = fib(x - 1) + fib(x - 2)
        return x
i = 3
while fib(i) < 1000:
    y = fib(i)
    letter = list.append(y)
    i = i + 1
Fib = list
In [13]:
print Fib
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

Exercise 4. Create a function called addone that does the following depending on the type of the input.

  • Integer: add 1
  • Float: add 1.0
  • String: take the last character and increment the character to the next character in alphabetical order using ord and chr.
In [39]:
def addone(x):
    if type(x) == int:
        x = x + 1
        return x
    elif type(x) == float:
        x = x + 1.0
        return x
    else:
        list = []
        for i in range(0, len(x)):
            letter = list.append(x[i])
        y = ord(x[len(x) - 1])
        y = y + 1
        list.remove(x[len(x) - 1])
        list.append(chr(y))
        return list
In [41]:
print addone('bonfire'), addone(1), addone(3.2)
['b', 'o', 'n', 'f', 'i', 'r', 'f'] 2 4.2

Exercise 5. Create a function called commarem that removes all commas from a string. Try to make it so that it will run faster if there is no comma in it. Below is a timing of these two different inputs.

In [47]:
def commarem(x):
    list = []
    for i in range(0, len(x)):
            letter = list.append(x[i])
    for i in range(0, len(x)):
        if x[i] == ',':
            list.remove(x[i])
    new = "".join(list)
    return new
In [48]:
%timeit commarem('1300')
1000000 loops, best of 3: 1.87 µs per loop
In [49]:
%timeit commarem('1,300')
The slowest run took 15.67 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.17 µs per loop

Exercise 6. Create a set of the 5 lower case vowels and the set of 21 lower case consonants by removing the set of vowels from the alphabet.

In [52]:
vowels = ['a', 'e', 'i', 'o', 'u']
consanants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']

Create a function called newletters that takes a string, s, and returns a list of strings formed by appending a new character to s, with the provision that that character must be a vowel if the last letter of s is a consonant and must be a consonant if the last letter of s is a vowel.

In [232]:
def newletters(s):
    list = []
    for i in range(0, len(s)):
        letter = list.append(s[i])
    new = "".join(list)
    if s[len(s) - 1] == 'a' or s[len(s) - 1] == 'e' or s[len(s) - 1] == 'i' or s[len(s) - 1] == 'o' or s[len(s) - 1] == 'u':
        list2 = []
        for i in range(0, len(consanants)):
            letter2 = list2.append(new)
            letter2 = list2.extend(consanants[i])
            list3 = []
            for i in range(0, len(list2), 2):
                letter3 = list3.append(list2[i] + list2[i+1])
    else:
        list2 = []
        for i in range(0, len(vowels)):
            letter2 = list2.append(new)
            letter2 = list2.extend(vowels[i])
            list3 = []
            for i in range(0, len(list2), 2):
                letter3 = list3.append(list2[i] + list2[i+1])
    return list3
In [233]:
newletters('banan')
Out[233]:
['banana', 'banane', 'banani', 'banano', 'bananu']
In [234]:
words = ['hamburge','chicke','hotdog','rubarb','tahini']

For the words list above, using a generator expression, create a dictionary with the keys being the elements of words and the items being newletters applied to the key.

In [255]:
newwords = dict([('hamburge', newletters('hamburge')), ('chicke', newletters('chicke')), ('hotdog', newletters('hotdog')), ('rubarb', newletters('rubarb')),, ('tahini', newletters('tahini')),])
In [256]:
newwords['hotdog']
Out[256]:
['hotdoga', 'hotdoge', 'hotdogi', 'hotdogo', 'hotdogu']