JamCoders

💾 Download

Lecture 2, Part 3 Extra Exercises

Core Questions

Question 1: More printing

1.1

How can we print the string

He said, "Hello there!"

?

In [ ]:
# Write your answer here!

1.2

This print statement will fail with an error. Please fix the code so that it prints "my age is 24".

In [ ]:
print('my age is ' + 24)

1.3

For what value of x will the following code segment print "yes"? Modify these lines to make this happen.

In [ ]:
def printX(x):
    if x == 5:
        print("yes")


# Modify this line to make this happen! e.g. what happens if you try printX(2), printX(3), etc..
printX(1)

Question 2: Guessing The Output

2.1

For what value of x would this function print "five"? "six"? "other"?

In [ ]:
def printX(x):
    if x == 5:
        print("five")
    elif x == 6:
        print("six")
    else:
        print("other")


printX(1)  # Copy and modify this line

Question 3: Guessing The Output #2

3.1

What do you expect will be printed if you run this code?

def foo():
    if -10 == 10:
        print('Hello world!')
    else:
        print('Goodbye world!')
foo()

Your Answer:

How can you verify your solution using the code above?

In [ ]:
def foo():
    if -10 == 10:
        print('Hello world!')
    else:
        print('Goodbye world!')


# Write code here to verify!

3.2

What do you expect will be printed if you run this code?

def bar():
    if -10 < 10:
        print('Hello world!')
    else:
        print('Goodbye world!')
bar()

Your Answer:

How can you verify your solution using the code above?

In [ ]:
def bar():
    if -10 < 10:
        print('Hello world!')
    else:
        print('Goodbye world!')


# Write code here to verify!

3.3

What do you expect will be printed if you run this code?

def foobar():
    if -10 != 10:
        print('Hello world!')
    else:
        print('Goodbye world!')
foobar()

Your Answer:

How can you verify your solution using the code above?

In [ ]:
def foobar():
    if -10 != 10:
        print('Hello world!')
    else:
        print('Goodbye world!')


# Write code here to verify!

Question 4: Grades?

4.1

We will present incorrect functions that takes an integer test score between 0 and 100 as an input, and prints the corresponding letter grade. You will be asked to fix the errors in the code.

(This process of finding and fixing the errors is called debugging.)

Here are the cutoffs:

90-100   A

80-89    B

70-79    C

60-69    D

0-60     F     

Warmup: Elijah has a score of 59 on a history exam. What letter grade (from A to F) does this correspond to?

In [ ]:
# Write your answer from A to F here

4.2

A student tried to write the code for this. Here is their attempt:

In [ ]:
def printGradeIncomplete(x):
    if x >= 90:
        print("A")
    elif x >= 80:
        print("B")
    elif x >= 70:
        print("C")
    elif x >= 60:
        print("D")

This code, however, is incomplete. Can you see why? What happens if a student gets 55? Modify the code above (add an else statement to the printGradeIncomplete function) to take care of this case.

In [ ]:
# Modify this code to take care of the case where student gets 55.
def printGradeIncomplete(x):
    if x >= 90:
        print("A")
    elif x >= 80:
        print("B")
    elif x >= 70:
        print("C")
    elif x >= 60:
        print("D")


# Test your code here
printGradeIncomplete(55)t

4.3

Another student tries to code a different method. This however, is also incorrect.

In [ ]:
def printGradeIncorrect(x):
    if x >= 60:
        print("D")
    elif x >= 70:
        print("C")
    elif x >= 80:
        print("D")
    elif x >= 90:
        print("A")
    else:
        print("F")


printGradeIncorrect(55)  # This one is correct
printGradeIncorrect(65)  # This one is correct
printGradeIncorrect(96)  # And this one is incorrect

Can you spot the error in the code above? For what input scores will this print the right letter?

In [ ]:
# Your answer here

4.4

Now the student thinks he's got it. This also does not work as expected though.

In [ ]:
def printGradeIncorrect2(x):
    if x >= 90:
        print("A")
    if x >= 80:
        print("B")
    if x >= 70:
        print("C")
    if x >= 60:
        print("D")
    else:
        print("F")

Can you spot the error in the code above? Again, for what input scores will this print the right letter?

In [ ]:
# Your answer here

Modify the code above (printGradeIncorrect2 function) to make it correct. Make sure it only prints one letter grade for each input and that it prints the correct letter grade.

How can you verify that your function is correct? Write some test cases to verify your solution.

In [ ]:
# Modify this function to fix it.
def printGradeIncorrect2(x):
    if x >= 90:
        print("A")
    if x >= 80:
        print("B")
    if x >= 70:
        print("C")
    if x >= 60:
        print("D")
    else:
        print("F")


# Your test cases here.

Question 5: More Indexing! optional

We have not learned more complex slicing yet, so we recommend skipping this question

5.1

Create a list storing five (5) different integers. Store this in a variable called x.

In [ ]:
# Create the list here

5.2

Using list indexing print the first and last values in the list. For the last value, do this two ways:

  1. using -1

  2. NOT using -1

In [ ]:
# Write code to print the first value here


# Write code to print the last value for method 1 here (using -1)


# Write code to print the last value for method 2 here (NOT using -1)

5.3

Using slicing on list x make another list y containing the second to fourth elements inclusive. Print y and verify it is in fact the correct slicing.

In [ ]:
# Write code to make another list `y` here

5.4

Change the first value of y to be "hello", without making a new list.

In [ ]:
# Write code to change the first value here

5.5

Using the len() function, print the length of x and the length of the first element of y (which should now be the string "hello").

In [ ]:
# Write code here to print the lengths of `x` and the first element of `y`

Using code show that x and the first element of y are the same lengths.

In [ ]:
# Write code here to show the lengths of `x` and the first element of `y` are the same

However, also using code and the type function, show they are not the same type.

In [ ]:
# Write code here to show the lengths of `x` and the first element of `y` are not the same type

Question 6: Sign

Write a function verifyInteger(x) that takes in an integer x and prints if it is "positive", "negative" or "zero".

In [ ]:
# Define your function verifyInteger here


# Write your test cases here.

Challenge Questions

If you've finished the core questions above, feel free to move on to these challenge questions.

Question 7

Different ages correspond to different schools in Jamaica. This shows these categories:

0         No School  

1 - 2     Preschool

3 - 4     Kindergarten

5 - 10    Primary/Prep School     

11 - 17   High School

18 - 22   University

23 - 100  No School   

7.1

# This is formatted as code

Write a variable for Boaz that stores his age (an integer between 0 and 100).

Now using this variable, how would you write a conditional to check if Boaz is in Primary/Prep School ** school? If this is True, **print the string "Primary/Prep School".

In [ ]:
# Write code here to verify if Boaz is in "Primary/Prep School" using conditionals (`if`, `elif`, `else`)

7.2

Similar to above, how would you write a conditional to check if Boaz is in the "No School" category? Make sure to verify both cases ("Primary/Prep School" and "No School") and if the age is in those ranges, print the appropriate string.

In [ ]:
# Write code here to verify if Boaz is in "Primary/Prep School" or "No School" using conditionals (`if`, `elif`, `else`)

7.3

Write a function isInSchool(age) where age is an integer between 0 and 100, that either returns "No School" if the person is not in school or "School" if the person is in school.

In [ ]:
# Write a function here to verify if someone is in "School" or "No School" using conditional (`if`, `elif`, `else`)

7.4

Now using the code pieces you just wrote and your knowledge of conditionals, write a function schoolCategory(age) that will take in an age integer between 0 - 100 and prints the category of school they are in (string). Try to do this using only one if statement.

In [ ]:
def schoolCategory(age):
    # Complete the function here using the code from 5.1 to 5.3


    # Here are some tests to check that your code is working correctly.
    # Please add your own tests here so that you can be sure your code is
    # working correctly.
print(schoolCategory(20))
print(schoolCategory(2))

Question 8

Write a function listLen(l) that takes in a list l and returns the length of the list if the list is not empty. If the input is the empty list, return "this is empty".

In [ ]:
# Define your function listLen(l) here


# Test your code here.

Question 9

Write a function allEqual(l) that takes in a list l and returns True if all the elements in the list are equal and False otherwise. You do not need for loops for this. Hint: You can multiply lists with integers and you can compare two lists to check if they are equal.

allEqual([1,1,1]) == True
allEqual([]) == True
allEqual([1,2]) == False
allEqual(["salaam", "salaam"]) == True
In [ ]:
# Define your function allEqual(l) here


# Here are some tests to check that your code is working correctly.
# Please add your own tests here so that you can be sure your code is
# working correctly.
print(allEqual([1, 1, 1]))
print(allEqual([]))
print(allEqual([1, 2]))

Question 10

You are given two lists of strings called names and cities. The first person in names lives in the last city in cities, the second person lives in the second to last city, the third lives in the third to last, and so on. Write code to create a third list called inOrder such that the even indexes (0, 2, 4, etc.) are the names of the people (in order) and that the odd indexes (1, 3, 5, etc.) are the cities. For a person in index $i$, their corresponding city should be in index $i+1$.

For example:

names = ["Elijah", "Jabari", "Tyler"]
cities = ["Cambridge","Kingston", "Berkeley"]

In this case, - Elijah lives Cambridge - Jabari lives in Kingston - Tyler lives in Berkeley

You should create the final list:

inOrder = ["Elijah", "Cambridge", "Jabari", "Kingston", "Tyler", "Berkeley"]

(hint: you can add to the end of a list using the + operator, or the append function)

In [ ]:
names = ["Orr", "Boaz", "Nadia"]
cities = ["Berkeley", "Cambridge", "Kingston"]
In [ ]:
# Write code to create `inOrder` list from `names` and `cities` lists

Question 11

Write a function round(x) that takes in a number x and returns the rounded version of that number.

For example, round(1.2) = 1

Similarly, round(2.6) = 3

In [ ]:
# Write the function `round(x)` here


# Here are some tests to check that your code is working correctly.
# Please add your own tests here so that you can be sure your code is
# working correctly.
print(round(3.4))
print(round(3.5))

Question 12

Write a function addFractions(l0, l1) that takes in 2 lists l0 and l1 where each list represents a fractional number where the first number is the numerator and the second is the denominator.

For example, $[2,1] => \frac{2}{1} = 2$, (Numerator is 2, denominator is 1)

For example, $[3,4] => \frac{3}{4} $, (Numerator is 3, denominator is 4)

We want to return the sum of these two fractions.

For example, addFractions([3,4], [2,3]) should return [17, 12] because $\frac{3}{4} + \frac{2}{3} = \frac{17}{12}$

In [ ]:
# Write your `addFractions(l0, l1)` function here


# Here are some tests to check that your code is working correctly.
# Please add your own tests here so that you can be sure your code is
# working correctly.
print(addFractions([3, 4], [2, 3]))

Question 13

Write a function costToM(n, m, upcost, downcost) that takes in four (4) integers, n, m, upcost, downcost. We want to know the cost to make n a multiple of m.It costs amount upcost for every increment ($+$) of 1 and costs amount downcost for every decrement ($-$) of 1.

Return the cheapest cost to get from n to a multiple of m.

For example, costToM(14, 5, 1, 1) should return 1 because you can get to 15 (a multiple of 5) with cost 1 and you can get to 10 (a multiple of 5) with cost 4.

costToM(14, 5, 20, 1) should return 4 because you can get to 15 (a multiple of 5) with cost 20 and you can get to 10 (a multiple of 5) with cost 4.

In [ ]:
# Write your function `costToM(n, m, upcost, downcost)` here


# Here are some tests to check that your code is working correctly.
# Please add your own tests here so that you can be sure your code is
# working correctly.
print(costToM(11, 7, 1, 1))

Question 14

Write a function calcArea(p0, p1) that takes in 2 points p0, p1 where the first is the bottom left coordinate (x0, y0) and the second is the top right coordinate (x1, y1) of a rectangle. Return the area of the rectangle.

For example, calcArea((1,1), (4,5)) should return $4*3 = 12$.

title

In [ ]:
# Write function `calcArea(p0, p1)` here


# Here are some tests to check that your code is working correctly.
# Please add your own tests here so that you can be sure your code is
# working correctly.
print(calcArea((1, 1), (4, 5)))

Question 15

15.1

Write a function overlappingRectangles(l1, r1, l2, r2) that takes in 4 points l1, r1, l2, r2. The first 2 points are the bottom left coordinate and top right coordinates of the first rectangle. The second 2 points are the bottom left and top right coordinates of the second rectangle. Return True if the 2 different rectangles overlap.

For example, with the image below we would call the function with inputs as such: overlappingRectangles((2,2), (7,3), (8,5), (9,7)), and since they do not overlap, return False.

title

In [ ]:
# Write overlappingRectangles(l1, r1, l2, r2) function here!


# Here are some tests to check that your code is working correctly.
# Please add your own tests here so that you can be sure your code is
# working correctly.
print(overlappingRectangles((1, 1), (7, 7), (2, 2), (8, 8)))

15.2

Write a function areaOverlap(l1, r1, l2, r2) to compute the area of the overlapping rectangles. If the rectangles do not overlap, return 0.

In [ ]:
# Write areaOverlap(l1, r1, l2, r2) functiono here!


# Here are some tests to check that your code is working correctly.
# Please add your own tests here so that you can be sure your code is
# working correctly.
print(areaOverlap((1, 1), (7, 7), (2, 2), (8, 8)))

Question 16

Write a function age_seconds(day, month, year) that gets as input a birthday, and returns the number of seconds that person has been alive for! Assume that all years have exactly 365 days, and February always has 28 days.

For example: age_seconds(5, 7, 2021) == 31536000 because they have been alive for exactly a year!

In [ ]:
# Write your code here

def age_seconds(day, month, year):
  pass

# Test your code, make sure that the code is correct regardless what months we are adding!