Time: Wed 10/18/17 6 pm
Draw the environment diagram that results from executing the code after the entire program is finished. No errors occur during the execution of this example.
def scramble(egg):
return [egg, over(egg)]
def over(easy):
easy[1] = [[easy], 2]
return list(easy[1])
egg = scramble([12, 24])
For each of the following code fragments, draw the final state of the program in boxes and arrows.
Code:
L = Link(1, Link(2))
P = L
Q = Link(L, Link(P))
P.rest.rest = Q
Code:
L = Link.empty
for i in range(3):
L = Link(i, L)
Code:
P = Link(0, Link(1, Link(2)))
def crack1(L):
if L is Link.empty:
return (Link.empty, Link.empty)
L1, L2 = crack1(L.rest)
return (Link(L.first, L2), L1)
Q, R = crack1(P)
Code:
P = Link(0, Link(1, Link(2)))
def crack2(L):
if L is Link.empty:
return (Link.empty, Link.empty)
L1, L2 = crack2(L.rest)
L.rest = L2
return (L, L1)
Q, R = crack2(P)
__repr__()
Several scenarios while you are interacting with the Python interpreter.
'abc' # 'abc' - There are quotation marks around it
1 # 1 - There's no quotation mark around it
However, things can become interesting working with custom objects in terms of __repr__()
!
class Foo:
def __repr__(self):
return 'abc'
f = Foo()
f # abc - There's no quotation mark around it
Compared to the following:
class Bar:
def __repr__(self):
return "'abc'"
b = Bar()
b # 'abc' - There are quotation marks around it
However, when you are simply printing something out with print()
, Python will display the __str__()
of the object you passed to it.
When you are querying an statement/expression in REPL, Python will display the __repr__()
of the object (if not None
). You can think the following...
'howdy' # 'howdy'
As print(repr('howdy'))
, meaning you are printing out the repr for the string 'howdy'
.
NB: Both __repr__()
and __str__()
needs to return strings.