0% found this document useful (0 votes)
61 views19 pages

CS1010S Tutorial 10 PDF

A().x would call the instance method x on the class A, rather than accessing the instance variable x. This is because methods take precedence over instance variables in Python. So in the example code: - A().x would call the instance method x on the A object, rather than accessing the instance variable x - The instance method x doesn't return anything, so A().x would return None - To access the instance variable x, you would need to do A().x (without calling the method) So in summary: - Methods take precedence over variables of the same name in Python - A().x calls the instance method x rather than accessing instance variable x - To access the instance variable

Uploaded by

simyanzi1010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views19 pages

CS1010S Tutorial 10 PDF

A().x would call the instance method x on the class A, rather than accessing the instance variable x. This is because methods take precedence over instance variables in Python. So in the example code: - A().x would call the instance method x on the A object, rather than accessing the instance variable x - The instance method x doesn't return anything, so A().x would return None - To access the instance variable x, you would need to do A().x (without calling the method) So in summary: - Methods take precedence over variables of the same name in Python - A().x calls the instance method x rather than accessing instance variable x - To access the instance variable

Uploaded by

simyanzi1010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

CS1010S Tutorial 10

Memoization and Dynamic Programming


Quick Recap: Dynamic Programming

- 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

NOT TESTED IN PRACTICAL/FINALS


Quick Recap: Exceptions
- This is tested.
- To raise (or throw) an error:
- raise ValueError(“this is a value error”)
- Catching errors
- If errors are not caught, your program will just crash
try:
stuff
except ValueError:
bla
except Error as err:
print(err) # err refers to the error raised
finally: # Optional
stuff # This block is carried out after everything above is executed.
# REGARDLESS of whether error is raised or not.
Q1
Q1

def collatz_distance(n): def max_collatz_distance(n):


if n == 1: return max(map(collatz_distance, range(1, n+1)))
return 0
elif n%2 == 0:
return 1 + collatz_distance(n/2)
else:
return 1 + collatz_distance(3*n + 1)
Q1

(c) Give a memoized version of max_collatz_distance_memo(n) using memoize as provided in the lecture.

memoize_table = {} def collatz_distance_memo(n):


def memoize(f, name): def helper(n):
if name not in memoize_table: if n == 1:
memoize_table[name] = {} return 0
table = memoize_table[name] elif n%2 == 0:
def helper(*args):
return 1 + collatz_distance_memo(n/2)
if args in table:
else:
return table[args]
return 1 + collatz_distance_memo(3*n + 1)
else:
return ????
result = f(*args)
table[args] = result
return result
return helper
Q1

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?

It is possible that an empty string is an actual response


from a server.
Q2
Q2
def httpget(url):
parsed = urlsplit(url)
if not parsed.scheme: # protocol insertion
url = 'http://'+url
elif parsed.scheme != 'http':
raise ValueError("Unknown protocol")
try:
return urlopen(url).read()
except ???:
???
except ???:
????
except ???:
????
Q2
def httpget(url):
parsed = urlsplit(url)
if not parsed.scheme: # protocol insertion
url = 'http://'+url
elif parsed.scheme != 'http':
raise ValueError("Unknown protocol")
try:
return urlopen(url).read()
except HTTPError as err:
???
except URLError as err:
????
except Exception as err:
????
Q2
def httpget(url):
parsed = urlsplit(url)
if not parsed.scheme: # protocol insertion
url = 'http://'+url
elif parsed.scheme != 'http':
raise ValueError("Unknown protocol")
try:
return urlopen(url).read()
except HTTPError as err: # HTTPError is a subclass of URLError, hence it must be first
raise InternetFail("HTTPError - " + str(err))
except URLError as err:
raise ValueError(str(err))
except Exception as err:
raise err
Q3
Q3
def download_URLs(URL_filenames):
for url, filename in URL_filenames:
with open(filename, 'wb') as myFile:
try:
myFile.write(httpget(url))
except (InternetFail, ValueError) as err: #conditional ignore and print
print("could not get "+url+" :"+str(err))
except Exception as err:
raise err
Tips for practical

- 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???

You might also like