JamCoders

💾 Download
In [ ]:
# PLEASE RUN THIS CELL
%config InteractiveShell.ast_node_interactivity="none"
%pip install termcolor
def print_locals(*which):
    """Print the local variables in the caller's frame."""
    import inspect
    ls = inspect.currentframe().f_back.f_locals
    which = set(which if which else ls.keys())
    ll = {k: v for k, v in ls.items() if k in which}
    print("; ".join(f"{k}{v}" for k, v in ll.items()))

Lecture 3, Part 2 Exercises

Question 1

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

In [ ]:
def listLen(l):
    # write here
    pass


# Test your code here.
print(listLen([1, 2, 3]) == 3) # prints true only if the function returns 3 when called on that list
print(listLen(["Anakai", "Nadia", "Orr", "Boaz", "Elijah"]) == 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)
In [ ]:
# Your answer:

How about in this example?

for elem in range(10):
    print(elem + 5)
In [ ]:
# Your answer:

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

for elem in range(0, 10):
    print(elem + 5)
In [ ]:
# Your answer:

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)
In [ ]:
# Your answer:

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


# Test your 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 [ ]:
# Define your function here.


# Test your function here.

2.5 -optional

This is challenging and completely optional

Challenge: can you write this function in one line? It may help to start writing the first few sums and finding a pattern.

In [ ]:
def sumx(x):
  return # Write this in one line!

sumx(5) # Should be 10

Question 3

3.1

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

In [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
print(first([1, 1, 2, 3, 5, 8, 13]) == 1)

3.2

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

In [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
last([2, 5, 7])

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 [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
extreme([2, 3, 6])

Question 4

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

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

Do this using for x in l syntax.

In [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
sum([5, 1, 2, 8])

Now do this without using for x in l syntax. Hint: Remember the range function

In [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
sum([5, 1, 2, 8])

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 [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
oddval([5, 2, 8, 17, 32, 2, 8, 9])

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 [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
oddind([1, 2, 3, 4, 9, 15])

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 $1<i<x$, $(x$ ``` mod

$ i) \neq 0$.
In [ ]:
# Define your function here.


# Test your function here.
# Write some of your own test cases as well.
isPrime(15)

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

In [ ]:
def test():
    inputs = [4, 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])
In [ ]:
# Your answer:

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 a list of floats and returns the minimum temperature in the list.

In [ ]:
# Define your function here.
In [ ]:
# Run this cell to test your function.
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. 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 Kingston, second is Montego Bay, followed by Port Antonio, Portmore, and Spanish Town. 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.

For example: coldestCity([22,44,33,11,10,9,8],[21,22,23,24,25,26,27])

Should return: 19.6

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

In [ ]:
# Define coldestCity here.
In [ ]:
# Run this cell to test your function.
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 tests passed!")

test()

Question 10 -skip this question:

this question is very challenging and completely optional

Some functions return functions! For example:

def return_print():
  # This actually returns the print function!
  return print

# Now, the variable print_function holds the print function!
print_function = return_print()
print(type(print_function))
>>> <class 'builtin_function_or_method'>

# We can call the print function
print_function('Hello World')

# Prints as expected
>>> Hello World
In [ ]:
# Same as example above, try running me to understand what is going on!
def return_print():
  return print

print_function = return_print()
print(type(print_function))
print_function('Hello World')
<class 'builtin_function_or_method'>
Hello World

Can you write a function called get_nth_power_function(n) that takes in an integer n, and returns a function? The function that is returned should raise the input x to the nth power.

In [ ]:
# Try writing your code here!
def get_nth_power_function(n):
  
  # Define a new function to return that depends on the value of n

  return # Return the function that you just created above!

cubic_function = get_nth_power_function(3)
hundred_power_function = get_nth_power_function(100)
print(cubic_function(5)) # Should print 125 == 5 ** 3
print(hundred_power_function(2)) # Should print something very very large == 2 ** 100
Hello World

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. This function should return a modified string.

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

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

In [ ]:
# Write code here
def removeCharacter(s, c):
  pass

# Test your function here. You'll never guess what this word is supposed to be >:)
removeCharacter("eeejeameaeicaeeee", "e")

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

In [ ]:
def test():
    tests = [("hello world", "h"), ("Jabari", "r"), ("Tyler", "y")]
    answers = ['ello world', 'Jabai', 'Tler']
    if [removeCharacter(*x) for x in tests] == answers:
        print("You've Done Well Friend!")
    else:
        print("Errors ! Errors ! Errors!")

test()