JamCoders

💾 Download

Lecture 6, Exercises C

In [ ]:
# Please always run this code block.
%config InteractiveShell.ast_node_interactivity="none"
%pip install termcolor
import base64
import termcolor

# Defines print_locals
code="ZGVmIG1ha2VfcHJpbnRfbG9jYWxzKCk6IAogICMgSW4gYSBmdW5jdGlvbiB0byBwcmV2ZW50IGxvY2FscyBhbmQgaW1wb3J0cyBmcm9tIGxlYWtpbmcuCiAgICBnbG9iYWwgbWFrZV9wcmludF9sb2NhbHMKICAgIGRlbCBtYWtlX3ByaW50X2xvY2FscyAgIyBPbmx5IHJ1biB0aGlzIGZ1bmN0aW9uIG9uY2UuCgogICAgaW1wb3J0IElQeXRob24KICAgIGltcG9ydCBhc3QKICAgIGltcG9ydCBpbnNwZWN0CgogICAgY2xhc3MgVmlzaXRvcihhc3QuTm9kZVZpc2l0b3IpOgogICAgICAgIGRlZiBfX2luaXRfXyhzZWxmKToKICAgICAgICAgICAgc2VsZi52YXJpYWJsZXMgPSBzZXQoKQogICAgICAgIGRlZiB2aXNpdF9OYW1lKHNlbGYsIG5hbWUpOgogICAgICAgICAgICBzZWxmLnZhcmlhYmxlcy5hZGQobmFtZS5pZCkKICAgICAgICAjIFRPRE86IFBvc3NpYmx5IGRldGVjdCB3aGV0aGVyIHZhcmlhYmxlcyBhcmUgYXNzaWduZWQgdG8uCgogICAgQUxMT1dfVFlQRVMgPSBbaW50LCBmbG9hdCwgc3RyLCBib29sLCBsaXN0LCBkaWN0LCB0dXBsZSwgcmFuZ2VdCiAgICBkZWYgZmlsdGVyX3ZhcmlhYmxlcyh2YXJpYWJsZXMsIGxvY2Fscyk6CiAgICAgICAgZm9yIHYgaW4gdmFyaWFibGVzOgogICAgICAgICAgICBpZiB2IGluIGxvY2FscyBhbmQgdHlwZShsb2NhbHNbdl0pIGluIEFMTE9XX1RZUEVTOgogICAgICAgICAgICAgICAgeWllbGQgdgogIAogICAgIyBVbmZvcnR1bmF0ZWx5LCB0aGVyZSBkb2Vzbid0IHNlZW0gdG8gYmU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0eXBlcz1GYWxzZSk6CiAgICAgICAgIiIiUHJpbnQgdGhlIGxvY2FsIHZhcmlhYmxlcyBpbiB0aGUgY2FsbGVyJ3MgZnJhbWUuIiIiCiAgICAgICAgaW1wb3J0IGluc3BlY3QKICAgICAgICAjIGN1cnJlbnRmcmFtZSgpIGZyYW1lIGlzIHByaW50X2xvY2Fscy4gV2Ugd2FudCB0aGUgY2FsbGVyJ3MgZnJhbWUKICAgICAgICBmcmFtZSA9IGluc3BlY3QuY3VycmVudGZyYW1lKCkuZl9iYWNrCiAgICAgICAgbG9jYWxzID0gZmluZF9sb2NhbHMoZnJhbWUpCiAgICAgICAgd2hpY2ggPSBzZXQod2hpY2gpIGlmIHdoaWNoIGVsc2UgZmluZF93aGljaChmcmFtZSkKICAgICAgICBsbCA9IHtrOiB2IGZvciBrLCB2IGluIGxvY2Fscy5pdGVtcygpIGlmIGsgaW4gd2hpY2h9CiAgICAgICAgaWYgdHlwZXM6CiAgICAgICAgICAgIHByaW50KCJcbiIuam9pbihmIntrfToge3R5cGUodikuX19uYW1lX199IOKGkCB7dn0iIGZvciBrLCB2IGluIGxsLml0ZW1zKCkpKQogICAgICAgIGVsc2U6CiAgICAgICAgICAgIHByaW50KCI7ICIuam9pbihmIntrfSDihpAge3Z9IiBmb3IgaywgdiBpbiBsbC5pdGVtcygpKSkKCiAgICByZXR1cm4gcHJpbnRfbG9jYWxzCgpwcmludF9sb2NhbHMgPSBtYWtlX3ByaW50X2xvY2Fscygp"
exec(base64.b64decode(code), globals(), locals())
del code

def check(actual, expected):
    if expected != actual:
        print(
            f"Function should return the value {expected}, it is returning the value {actual}")
    else:
        print(f"Congratulations, the test case passed!")
In [ ]:
def check(actual, expected):
    if expected != actual:
        print(
            f"Function should return the value {expected}, it is returning the value {actual}")
    else:
        print(f"Congratulations, the test case passed!")

Challenge Question 1 -- Calculator

3.1

A math exam exam is coming up. You want to prepare, but you misplaced your calculator, and the computer your using only has jupyter notebook available. Normally you could use arithmetic operators, but your input is given as a string (ex. '1 + 2 * 8 ÷ 2'). Make a calculator capable of completing addition, subtraction, multiplication, and division. (Do not take order of operations into account. Perform functions from left to right.)

In [ ]:
def calc1(string):
    return False

# Test your function on this equation '10 + 20 * 80 ÷ 20'
In [ ]:
check(calc1('1+2+3÷2*12'), 36)
check(calc1('1+2+3÷2*0'), 0)
check(calc1('100+2+3÷5*12'), 252)

3.2

Now complete exercise 3.1 taking into acount the order of operations. Again, you only need to add functionality for addition, subtraction, multiplication, and division.

In [ ]:
def calc2(string):
    return False

# Test your function on the equation '10 + 20 * 80 ÷ 20'
In [ ]:
check(calc2('1+2+3÷2*12'), 21)
check(calc2('1+2+3÷2*0'), 3)
check(calc2('100+2+3÷5*12'), 109.2)

Challenge: Ancient Egyptian multiplication method

The ancient Egyptians had a method of multiplying integers using only addition, doubling, and halving. Here is how the method works:

  1. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
  2. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
  3. Examine the table produced and discard any row where the value in the left column is even.
  1. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
  1. Take two numbers to be multiplied and write them down at the top of two columns.

For example: 17 × 34 Halving the first column:

17 34
8
4
2
1

Doubling the second column:

17 34
8 68
4 136
2 272
1 544

Strike-out rows whose first cell is even:

17 34
8 68
4 136
2 272
1  544

Sum the remaining numbers in the right-hand column:

17 34
8 --
4 ---
2 ---
1 544
Total 578

So 17 multiplied by 34, by the Egyptian method is 578.

4.1

Define a helper function named isEven that takes in an integer and returns True if the number is even or False if it's odd.

In [ ]:
def isEven(n):
    # Put your code below this comment
    return False
In [ ]:
# TEST_CASE
# Note: if an error is given saying "check" is not defined, rerun the first code
#       cell in this notebook.

check(isEven, 2, expected=True)
check(isEven, 1, expected=False)
check(isEven, 15, expected=False)

4.2

Define another helper function named halve that takes in an integer and then returns a list with the halved values till it reaches 1. Make sure the list you are returning is sorted from smallest to largest. For example, if you give it the number 17 it should return the list [1, 2, 4, 8, 17], and if you give it the number 105 it should return the list [1, 3, 6, 13, 26, 52, 105].

In [ ]:
def halve(n):
    # Put your code below this comment
    return []
In [ ]:
# TEST_CASE
# Note: if an error is given saying "check" is not defined, rerun the first code
#       cell in this notebook.

check(halve, 17, expected=[1, 2, 4, 8, 17])
check(halve, 105, expected=[1, 3, 6, 13, 26, 52, 105])

4.3

Define another helper function named doubleIt that takes in two argument. The first argument should be the number that is going to be doubled, and the second should number should be the target length of the list to be returned.(If the second number is 5, you will double the starting number 4 times.) Your function should return a list with the doubled values. Make sure the list is sorted from smallest to largest. For example, if you pass 34 and 5 to your function it should return the list [34, 68, 136, 272, 544].

In [ ]:
def doubleIt(num, n):
    # Put your code below this line
    return []
In [ ]:
# TEST_CASE
# Note: if an error is given saying "check" is not defined, rerun the first code
#       cell in this notebook.

check(doubleIt, 34, 5, expected=[34, 68, 136, 272, 544])

4.4

Define a helper function named sum that takes in two lists. The two lists must have equal length. You should loop through each corresponding pair of elements in the two lists, and if the element in the first list is not even, then you should add the corresponding element from the second list to your total. Your function should use the isEven function you defined earlier to check if the element in the first list is even or not. For example, calling sum([17, 8, 4, 2, 1], [34, 68, 136, 272, 544]) should return 578.

In [ ]:
def sum(list1, list2):
    # Put your code below this comment
    return 0
In [ ]:
# TEST_CASE
# Note: if an error is given saying "check" is not defined, rerun the first code
#       cell in this notebook.

check(sum, [17, 8, 4, 2, 1], [34, 68, 136, 272, 544], expected=578)

4.5

Finally, define a function named multiply that takes in two arguments (the numbers that are going to be multiplied) and returns the result of multiplying the first number by the second number. You should use the halve and doubleIt functions inside this function. Then, pass the results returned from the two helper functions to the sum function.

In [ ]:
def multiply(a, b):
    # Put your code below this comment
    return 0
In [ ]:
# TEST_CASE
# Note: if an error is given saying "check" is not defined, rerun the first code
#       cell in this notebook.

check(multiply, 17, 34, expected=578)
check(multiply, 15, 15, expected=225)
check(multiply, 24, 34, expected=816)