CS1010S Tutorial 10 PDF
CS1010S Tutorial 10 PDF
- Start from the starting value, rather from calculating from the end.
- E.g fib(0), fib(1), fib(2)..... instead of fib(2), fib(1), fib(0)
- You avoid calculating the same thing more than once
- Use a dictionary (Or array with a known index) to keep access at - O(1).
- If not, then it defeats the entire purpose of using dynamic programming
- Memoization
- Standard formula: If the result is in the dictionary, then just return the value stored. If not, calculate and keep
the result in the dictionary then return
(c) Give a memoized version of max_collatz_distance_memo(n) using memoize as provided in the lecture.
def collatz_distance_memo(n):
def helper(n):
if n == 1:
return 0
elif n%2 == 0:
return 1 + collatz_distance_memo(n/2)
else:
return 1 + collatz_distance_memo(3*n + 1)
return memoize(helper, "memo_collatz")(n)
def max_collatz_distance_memo(n):
return max(map(collatz_distance_memo, range(1, n+1)))
Q1
(d) Memoize it without using the function provided in the lecture. You should be able to do better.
Q1
(d) Memoize it without using the function provided in the lecture. You should be able to do better.
def max_collatz_distance_memo_own(n):
collatz_table = {1: 0}
def collatz(n):
if n in collatz_table:
return collatz_table[n]
elif n%2 == 0:
collatz_table[n] = 1 + collatz(n/2)
else:
collatz_table[n] = 1 + collatz(3*n + 1)
return collatz_table[n]
return max(map(collatz, range(1, n+1)))
Q2
Q2
(b) Why is it a good idea to raise an error instead of simply returning a string ‘Not Found’ or an empty
string to indicate that the URL is not accessible?
Q2
(b) Why is it a good idea to raise an error instead of simply returning a string ‘Not Found’ or an empty
string to indicate that the URL is not accessible?
- Skip the question first if you get stuck. Usually it is easier to earn marks
from q3
- Do not panic. Don’t care what others around you are doing.
- Do and test on IDLE, “Run code” on coursemology will be limited.
- All test cases pass != 30/30
class A:
Variables/Class/Function/Method names can
def __init__(self): override each other.
self.x = 1
def x(self, .......): Likely to happen when you do OOP and get
pass careless
What is A().x???