Like worksheet 1, this worksheet consists of Python programming exercises on topics typically covered in prerequisite courses of MCS 275. Compared to worksheet 1, this one is a bit more complex and the problems are more open-ended.
Each worksheet covers the previous week's lecture material. Last week's lectures were used to review some MCS 260 topics, so we still don't have new material to cover this time.
These things might be helpful while working on the problems. Remember that for worksheets, we don't strictly limit what resources you can consult, so these are only suggestions.
Suppose you have a list of integers. Even if the list is not entirely in increasing order, there are sometimes parts of the list that are in increasing order.
For example, consider L = [1,21,4,17,39,35,22,0,6,2,5]
. The list is not in increasing order, but the first two elements (i.e. L[0:2]
or [1,21]
) are in increasing order. Also, if you take the slice L[2:6]
, which is [4,17,38,39]
, that is in increasing order.
Let's call a slice of a list that is in increasing order an increasing run. In the example given above, the longest increasing run is L[2:6]
, of length 4.
Write a function IRL(L)
that takes a list L
whose elements can be compared to one another (e.g. a mix of integers and floats, or a collection of strings) and returns the length of the longest increasing run within L
.
Special cases (not necessarily requiring special handling, but explained here to clarify the extremes):
L
is empty, the function should return 0L
is in decreasing order, the function should return 1 because a slice with one element can be considered to be in "increasing order", and that would be the longest increasing run.Here are some sample outputs:
IRL([40, 1, 63, 20, 53, 9]) # [1,63] and [20,53] are the longest, each has length 2
IRL([22, 40, 47, 46, 26, 45, 25, 30, 47, 40]) # [22,40,47] and [25, 30, 47] are the longest
IRL([78, 26, 1, 20, 72, 19, 44, 50, 59, 67]) # [19, 44, 50, 59, 67] is the longest
IRL([1,2,3,4,5,6,7,8]) # The entire list, of length 8, is increasing!
IRL([]) # no elements = no increasing runs = max increasing run length 0
IRL([275]) # [275] is the longest increasing run
IRL([10,8,6,4,2]) # [10] and [8] and [6] and [4] and [2] are the longest, each has length 1
Hint: Here is one possible strategy: Use a for loop to scan through the list, keeping track of the current element and the previous one. As you go, make note of how many successive elements have been increasing. Use another variable to hold the largest number of increasing elements seen so far, and update it as needed on each iteration.
def IRL(L):
"""Takes in a list and returns length of longest increasing run"""
if len(L) == 0:
return 0
# Initialize the variable representing the previous value
# by using the first value in the list
previous_val = L[0]
current_length = 1
max_length = 1
# Iterate over each item in the list except the first one
for value in L[1:]:
if value >= previous_val: # Increase length of run if applicable
current_length += 1
else: # Otherwise, reset the length of the run
current_length = 1
previous_val = value
max_length = max(max_length, current_length) # Update the longest run
return max_length
Zitterbewegung is a German word meaning "jittery motion".
This is an exercise in object-oriented programming.
Make a class ZBPoint
that stores a point (x,y)
in the plane with integer coordinates.
The constructor should take (x,y)
as arguments and store them as attributes.
Add a __str__
method Printing an instance of this class should produce a nice string like
ZBPoint(17,-2)
Also include a method .jitter()
that will move the point up, down, left or right by one unit. The direction should be chosen at random (e.g. using random.choice
or random.randint
from the Python random module that you can import with import random
.)
The code below demonstrates how you would use this class to create a point at (20,22)
and then let it jitter about for 30 steps, printing the location each time.
P = ZBPoint(20,22)
for _ in range(30):
print(P)
P.jitter()
import random
class ZBPoint:
"""Class representing a point on the plane which can be jittered"""
def __init__(self, x, y):
"""Inputs: x and y coordinates of point"""
self.x = x
self.y = y
def __str__(self):
"""String representation (e.g. for printing)"""
return "ZBPoint({},{})".format(self.x, self.y)
def jitter(self):
"""Randomly move the point left/right/up/down by 1 unit"""
direction = random.choice(["L","R","U","D"])
if direction == "L": # Left
self.x -= 1
elif direction == "R": # Right
self.x += 1
elif direction == "U": # Up
self.y += 1
else: # Down
self.y -= 1
Write a program circle.py
that takes one command line argument, r
, and then prints 40 lines of text, each containing 80 characters. The output should make a picture of a circle, using characters as pixels. When r=20
the circle should be slightly too big to fit in the block of text, and when r=1
it should be nearly too small to have any empty space inside.
For example, here is possible output for r=5. (It will only look right if lines of width 80 characters don't wrap around on your browser display. If it looks wrong, try zooming out or maximizing the window.)
@@@@@@@@@@@
@@@@ @@@@
@@@ @@@
@@@ @@@
@@@ @@@
@@@ @@@
@@@ @@@
@@@ @@@
@@@ @@@
@@@@ @@@@
@@@@@@@@@@@
And here is possible output for r=15:
@@@@@@@@@@@@@@@@@
@@@@@@@ @@@@@@@
@@@@@ @@@@@
@@@@ @@@@
@@@@ @@@@
@@@ @@@
@@@ @@@
@@@ @@@
@@ @@
@@ @@
@@ @@
@@@ @@@
@@ @@
@@ @@
@@@ @@@
@@@ @@@
@@@ @@@
@@ @@
@@ @@
@@@ @@@
@@ @@
@@ @@
@@ @@
@@@ @@@
@@@ @@@
@@@ @@@
@@@@ @@@@
@@@@ @@@@
@@@@@ @@@@@
@@@@@@@ @@@@@@@
@@@@@@@@@@@@@@@@@
This exercise is deliberately a little vague about how to go about this, but here is a hint: Each character you print corresponds to a certain point (x,y) in the plane, with character 40 on line 20 corresponding to (20,20). Calculating those coordinates inside of the main loop will be useful. Then, how would you decide whether to print a " "
or a "@"
?
Note: The reason for using 40 lines of 80 characters is that a character in the terminal is often approximately twice as tall as it is wide.
Bonus round: Skip this part unless you have extra time, or want an extra challenge after lab ends. Modify the program so that it makes circles with softer edges, like this:
...............
..***@@@@@@@@@@@@@@@@@***..
..**@@@@@@@******.******@@@@@@@**..
.*@@@@@**... ...**@@@@@*.
.**@@@@*.. ..*@@@@**.
.*@@@@*.. ..*@@@@*.
.*@@@*. .*@@@*.
.*@@@*. .*@@@*.
.*@@@*. .*@@@*.
.*@@*. .*@@*.
.*@@*. .*@@*.
.*@@*. .*@@*.
.@@@*. .*@@@.
.*@@*. .*@@*.
.*@@*. .*@@*.
.@@@* *@@@.
.@@@. .@@@.
.@@@* *@@@.
.*@@*. .*@@*.
.*@@*. .*@@*.
.@@@*. .*@@@.
.*@@*. .*@@*.
.*@@*. .*@@*.
.*@@*. .*@@*.
.*@@@*. .*@@@*.
.*@@@*. .*@@@*.
.*@@@*. .*@@@*.
.*@@@@*.. ..*@@@@*.
.**@@@@*.. ..*@@@@**.
.*@@@@@**... ...**@@@@@*.
..**@@@@@@@******.******@@@@@@@**..
..***@@@@@@@@@@@@@@@@@***..
...............
This code that produces a circle using only @
symbols:
# Solution by Jennifer Vaccaro
import sys
r = int(sys.argv[1])
outer_rad1 = r*1.2
inner_rad1 = r*0.9
for y in range(-20,21):
for x in range(-40,41):
x = x/2
dist = (x**2 + y**2)**0.5
if dist>inner_rad1 and dist<outer_rad1:
print("@",end="")
else:
print(" ",end="")
print() # Make a newline
Alternatively, this code does the same thing, but is condensed:
import sys
r = int(sys.argv[1])
for y in range(-20, 21):
print("".join(["@" if 0.9*r < ((x/2)**2+y**2)**0.5 < 1.2*r else " " for x in range(-40, 41) ]))
Lastly, here's a solution to the bonus problem (using soft edges):
# Solution by Jennifer Vaccaro
import sys
r = int(sys.argv[1])
outer_rad1 = r*1.2
inner_rad1 = r*0.9
outer_rad2 = r*1.4
inner_rad2 = r*0.8
outer_rad3 = r*1.6
inner_rad3 = r*0.7
for y in range(-20,21):
for x in range(-40,41):
x = x/2
dist = (x**2 + y**2)**0.5
if dist>inner_rad1 and dist<outer_rad1:
print("@",end="")
elif dist>inner_rad2 and dist<outer_rad2:
print("*",end="")
elif dist>inner_rad3 and dist<outer_rad3:
print(".",end="")
else:
print(" ",end="")
print() # Make a newline
This builds on the ZBPoint
class from problem 2.
Suppose you start a ZBPoint
at (0,0)
and then repeatedly call the method .jitter()
until the first time it returns to (0,0)
. The number of steps it takes to do this is called the recurrence time. It's possible that this may never happen, but that is very unlikely. (It can be shown that the probability it will eventually return to (0,0)
is 100%.)
Write a program that runs this process 1000 times and records the recurrence times. (It's OK to give up on a point if it's taken 200 steps and hasn't yet returned to (0,0)
.) The program should then print a table showing how many times each recurrence time was seen (a histogram). Here's an example of what it might look like:
Ran 1000 random walks starting at (0,0). Of these:
235 returned to (0,0) after 2 steps
76 returned to (0,0) after 4 steps
51 returned to (0,0) after 6 steps
31 returned to (0,0) after 8 steps
24 returned to (0,0) after 10 steps
17 returned to (0,0) after 12 steps
18 returned to (0,0) after 14 steps
7 returned to (0,0) after 16 steps
6 returned to (0,0) after 18 steps
13 returned to (0,0) after 20 steps
7 returned to (0,0) after 22 steps
8 returned to (0,0) after 24 steps
9 returned to (0,0) after 26 steps
4 returned to (0,0) after 28 steps
2 returned to (0,0) after 30 steps
5 returned to (0,0) after 32 steps
3 returned to (0,0) after 34 steps
5 returned to (0,0) after 36 steps
2 returned to (0,0) after 38 steps
2 returned to (0,0) after 40 steps
3 returned to (0,0) after 42 steps
2 returned to (0,0) after 44 steps
1 returned to (0,0) after 46 steps
4 returned to (0,0) after 48 steps
2 returned to (0,0) after 50 steps
1 returned to (0,0) after 52 steps
7 returned to (0,0) after 54 steps
1 returned to (0,0) after 58 steps
3 returned to (0,0) after 60 steps
4 returned to (0,0) after 62 steps
4 returned to (0,0) after 64 steps
2 returned to (0,0) after 66 steps
1 returned to (0,0) after 68 steps
2 returned to (0,0) after 70 steps
1 returned to (0,0) after 72 steps
3 returned to (0,0) after 76 steps
2 returned to (0,0) after 78 steps
1 returned to (0,0) after 80 steps
2 returned to (0,0) after 82 steps
1 returned to (0,0) after 84 steps
2 returned to (0,0) after 86 steps
2 returned to (0,0) after 92 steps
2 returned to (0,0) after 94 steps
1 returned to (0,0) after 96 steps
1 returned to (0,0) after 98 steps
2 returned to (0,0) after 106 steps
1 returned to (0,0) after 108 steps
2 returned to (0,0) after 110 steps
4 returned to (0,0) after 116 steps
2 returned to (0,0) after 118 steps
1 returned to (0,0) after 122 steps
1 returned to (0,0) after 124 steps
1 returned to (0,0) after 126 steps
1 returned to (0,0) after 128 steps
3 returned to (0,0) after 130 steps
1 returned to (0,0) after 134 steps
2 returned to (0,0) after 136 steps
2 returned to (0,0) after 138 steps
1 returned to (0,0) after 142 steps
1 returned to (0,0) after 144 steps
2 returned to (0,0) after 146 steps
1 returned to (0,0) after 156 steps
1 returned to (0,0) after 158 steps
1 returned to (0,0) after 160 steps
3 returned to (0,0) after 162 steps
1 returned to (0,0) after 166 steps
1 returned to (0,0) after 174 steps
2 returned to (0,0) after 178 steps
1 returned to (0,0) after 180 steps
3 returned to (0,0) after 184 steps
1 returned to (0,0) after 190 steps
2 returned to (0,0) after 198 steps
376 didn't return to (0,0) after 200 steps
# Create dict to keep track of results of each trial.
# Initially starts as {0:0, 1:0, 2:0, 3:0, ... , 200:0}
# with each 0 representing the number of times the outcome occurred
results_dict = {i:0 for i in range(202)}
# Run 1000 trials, creating a new ZBPoint each time
for trial in range(1000):
point = ZBPoint(0,0)
point.jitter()
recurrence_time = 1
while point.x != 0 or point.y != 0:
point.jitter()
recurrence_time += 1
if recurrence_time > 200:
break # Stop trying to jitter if we've tried more than 200 times
# Record the result in the dictionary
results_dict[recurrence_time] += 1
print("Ran 1000 random walks starting at (0,0). Of these: ")
for key, value in results_dict.items():
if key <= 200: # Consider the 200 value separately because it needs a different message
if value != 0:
# Use :3d for alignment - ensures that the number takes up 3 spaces.
print("{:3d} returned to (0,0) after {} steps".format(value,key))
else:
print("{:3d} failed to return to (0,0) after 200 steps".format(value))