Lecture 2, Part 2 Exercises

Before starting, please run the following cell

In [ ]:
from __future__ import division, print_function 

Question 1

Write a function that takes in a list and returns the length of the list. Fill in the function definition below.

In [3]:
def listLen(l):
    #write here
In [4]:
print(listLen([1, 2, 3]) == 3)
print(listLen(["Daniel","Basi", "Mike", "Leello", "Rupal"]) == 5)
print(listLen([]) == 0)

Question 2

2.1

What is the last number printed in this example:

for elem in [23, 42, 10]:
    print(elem)

How about in this example?

for elem in range(10):
    print(elem + 5)

How if at all, is this different from the previous example?

for elem in range(0, 10):
    print(elem + 5)

Is the last element printed in this example different from the last element printed in the above example?

for elem in range(0, 10, 2):
    print(elem + 5)

2.2

Using a for loop print every element in the list l. Do this using

1) for x in l syntax

2) for x in range syntax

In [ ]:
l = [2,7,5]
# write for loop here with method 1

# use method 2 here

2.3

Write a function printNums(x) that prints every number between $0$ and $x-1$.

For example when $x = 3$, printNums(x) should give:

0
1
2
In [ ]:
# Write code here

2.4

Write a function sumx(x), using a for loop, that sums every number between $0$ and $x - 1$ inclusive. Hint: you may want to define a variable inside your function to keep track of the running sum.

For example, with $x = 5$

sumx(x)

would return $10 (= 0+1+2+3+4)$.

In [6]:
print(sumx(4)==10)
print(sumx(0)==0)
print(sumx(10)=55)

Question 3

3.1

Write a function first(l) that takes in a list and returns the first element of the list.

In [ ]:
print(first([1,1,2,3,5,8,13])==1)
print(first(["Hello","please","print","the","first", "word"])=="Hello")
print(last([42, 10, 15, 50])==42)

3.2

Write a function last(l) that takes in a list and returns the last element of the list.

In [8]:
print(last([1,1,2,3,5,8,13])==13)
print(last(["Hello","please","print","the","last", "word"])=="word")
print(last([42, 10, 15, 50])==50)

3.3

Using calls to the functions above, write a function extreme(l) that takes in a list (l) and returns the sum of the first and last element of the list. If the list has length less than 1 return a string saying "Not possible".

In [ ]:
print(extreme([1,2,3]) == 4)
print(extreme([0,2,4,0]) == 0)
print(extreme([0]) == "Not possible")

Question 4

Write a function sum(l) that given a list returns the sum of all the elements in the list.

sum([]) = 0
sum([1,2,3]) = 6

First do this using for x in l syntax.

In [ ]:
print(sum([]) == 0)
print(sum[1, 2, 3] == 6)
print(sum[10, 20, 30, 5, 1] == 66)

Now do this without using the for x in l syntax.

In [ ]:
print(sum([]) == 0)
print(sum[1, 2, 3] == 6)
print(sum[10, 20, 30, 5, 1] == 66)

Question 5

Write a function oddval(l) that prints all the odd numbers in a list.

For example:

oddval([5, 2, 8, 17, 32, 2, 8, 9])

should print:

5
17
9
In [ ]:
print("Test1:")
oddval([5, 2, 8, 17, 32, 2, 8, 9])

print("Test2:")
oddval([10, 0, 3, 8, 6, 8])

print("Test3:")
oddval([1, 2, 3, 4, 5, 6])

Question 6

Write a function oddind(l) that prints all the values in odd indices.

For example:

oddind([1, 2, 3, 4, 9, 15])

should print:

2
4
15
In [ ]:
print("Test1:")
oddind([1, 2, 3, 4, 9, 15])

print("Test2:")
oddval([5, 2, 8, 17, 32, 2, 8, 9])

print("Test3:")
oddval([10, 0, 3, 8, 6, 8])

print("Test4:")
oddval([123, 234, 345])

Question 7

Write a function isPrime(x) that given integer x will return True if x is prime and False otherwise.

Formally, $x$ is prime if and only if for all $1<i<x$, $(x$ mod $ i) \neq 0$.

In [ ]:
# Write code here

Run the cell below to test your isPrime(x) function.

In [ ]:
def test():
    inputs = [1, 2, 25, 11, 13, 51]
    expected_output = [False, True, False, True, True, False]
    for i in range(len(inputs)):
        if (isPrime(inputs[i]) != expected_output[i]):
            print("Failed on input: ", inputs[i])
            return
    print("All test cases passed!")
    

test()

Question 8

What does the following code print?

for i in range(3):
    for j in range(3):
        print([i, j])

Question 9

In this problem you will be dealing with a set of temperatures over a week represented as floats in a list. After you complete each of the subproblems run the test cell to verify your solution.

9.1

Given a list of temperatures in a week, write a function findMin(l) that takes in such a list of floats and returns the minimum temperature in the list.

In [ ]:
# Write code here
In [ ]:
def test():
    #list of test cases
    inputs = [[13.25,14.11,15.64,20.53,17.32,18.63,14.90],
              [-1.34,0.0,5.89,6.73,2.54,4.53,7.01],
              [5.53,2.63,0.7,8.26, 10.1, 6.13,2.43],
              [7.98,12.34,10.52,13.64,15.42,14.42,16.32],
              [8.42,12.542,13.25,17.52,15.24,10.45,8.86]]
    expected_output = [13.25, -1.34, 0.7, 7.98, 8.42]
    for i in range(len(inputs)):
        if (findMin(inputs[i]) != expected_output[i]):
            print("Failed on input: ", inputs[i])
            return
    print("All test cases passed!")
            
test()

9.2

Now find the average temperture of each week. So given a list of temperatures, write a function findAvg(l) that returns the average temperature of the list using for loop(s).

In [ ]:
# Write code here
In [ ]:
def test():
    #list of test cases 
    inputs = [[13.25,14.11,15.64,20.53,17.32,18.63,14.90],
              [-1.34,0.0,5.89,6.73,2.54,4.53,7.01],
              [5.53,2.63,0.7,8.26, 10.1, 6.13,2.43],
              [7.98,12.34,10.52,13.64,15.42,14.42,16.32],
              [8.42,12.542,13.25,17.52,15.24,10.45,8.86]]
    expected_output = [16.34, 3.6228571428571428, 5.111428571428571, 12.94857142857143, 12.325999999999999]
    for i in range(len(inputs)):
        if (abs(findAvg(inputs[i]) - expected_output[i]) > 0.1):
            print("Failed on input: ", inputs[i])
            return
    print("All test cases passed!")
            
test()

9.3

Now you are given a list of 5 cities' temperatures in a certain week. The first is Addis, second is Harar, followed by Lalibela, Aksum, and Gondar. Write a function coldestCity(l) that takes in a list of lists, where each list contains 7 floats, and returns the index of the city with the minimum average temperature. Then, write the city name corresponding to that index in the cell provided below the test function.

Hint: It may be useful to call findMin and findAvg in this function.

In [ ]:
# Write code here
In [ ]:
def test():
    temps = [[13.25,14.11,15.64,20.53,17.32,18.63,14.90],
              [-1.34,0.0,5.89,6.73,2.54,4.53,7.01],
              [5.53,2.63,0.7,8.26, 10.1, 6.13,2.43],
              [7.98,12.34,10.52,13.64,15.42,14.42,16.32],
              [8.42,12.542,13.25,17.52,15.24,10.45,8.86]]
    expected_output = 1
    if coldestCity(temps) != expected_output:
        print("Test Failed")
    else:
        print("All test case!")
            
test()

City Name: (write as a string)

Question 10

Write a function mostCommon(s) that takes in a string and returns the most common character in a string. If no character occurs more often than any other character, return any character in the string.

For example mostCommon("salaam") should give "a".

Something like mostCommon("aabbbcddeeeee") should give "e".

Something like mostCommon("abc") could give "a", "b", or "c".

In [ ]:
# Write code here

Run the cell below. If what you wrote is correct it should output : "TEST CASES PASSED !"

In [ ]:
# Test cases

def test():
    tests = ["aaa", "The quick Brown Fox jumped over the lazy Fox", "bdabbbd", "bbbacedddde"]
    answers = ['a', ' ', 'b', 'd']
    for i in range(len(tests)):
        if mostCommon(tests[i]) != answers[i]:
            print("TEST CASE FAILED")
            break
    print("TEST CASES PASSED !")
    
test()

Question 11

Write a function removeCharacter(s, c) that given a string (s) and a character (c), removes all the instances of character c in s. So this function will return a modified string.

For example removeCharacter("hello", "e") = "hllo"

Another example removeCharacter("hello", "f") = "hello"

In [18]:
# Write code here

Run the cell below. If what you wrote is correct it should output : "You've Done Well Friend!"

In [1]:
def test():
    tests = [("hello world", "h"), ("Jessica", "c"), ("ThunderStick", "r")]
    answers = ['ello world', 'Jessia', 'ThundeStick']
    if [removeCharacters(*x) for x in tests] == answers:
        print("You've Done Well Friend!")
    else:
        print("Errors ! Errors ! Errors!")