0% found this document useful (0 votes)
16 views

module-5-arbitrary-sized-data-worksheet

Uploaded by

aleahjiang1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

module-5-arbitrary-sized-data-worksheet

Uploaded by

aleahjiang1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

module-5-arbitrary-sized-data-worksheet

October 21, 2024

[4]: from cs103 import *


from typing import NamedTuple, List, Optional
from enum import Enum

0.1 Arbitrary Sized Data Worksheet


0.2 Part One
0.2.1 Problem 1
Let’s trace a loop to understand how it works and why! For each of the examples in this function
design, fill in the trace table below to show the value stored in the variable max and the portion
of the list that has been “seen” so far each time the body of the loop is executed. We’ve done the
first example. Note that you won’t always need to fill in every box.
@typecheck
def maximum(loi: List[int]) -> int:
"""
return the maximum integer in a list of positive
integers (loi), or -1 if loi is empty
"""
# template from List[int]
# max stores the maximum integer seen so far in loi
max = -1 # type: int
for i in loi:
if i > max:
max = i
return max

start_testing()
expect(maximum([1, 2, 3]), 3) # example a
expect(maximum([]), -1) # example b
expect(maximum([11, 2, 3]), 11) # example c
expect(maximum([3, 9, 4]), 9) # example d
expect(maximum([1, 7, 3, 2, 11]), 11) # example e
summary()
Double click to edit this table

1
Just before Just before Just before Just before Just before
the first time the second the third time the fourth the fifth time
through the time through through the time through through the
Example loop the loop loop the loop loop
[1, 2, 3] max = -1 [] max = 1 [1] max = 2 [1, 2] max = 3 [1, 2, never happens
3]
[] max = -1 [] n/a n/a n/a n/a
[11, 2, 3] max = -1 [] max = 11 [11] max = 11 [11, max = 11 [11, never happens
2] 2, 3]
[3, 9, 4] max = -1 [] max = 1 [3] max = 1 [3, 9] max = 1 [3, 9, never happens
4]
[1, 7, 3,2, 11] max = -1 [] max = 1 [1] max = 1 [1, 7] max = 1 [1, 7, max = 1 [1, 7,
3] 3,2]

0.2.2 Problem 2
Label 1) the accumulator, 2) the list that is looped over, and 3) the body of the loop in the below
code snippet.
words = ["phone", "desk", "computer"]
res = ""
for w in words:
res = res + w + " "
1) the accumulator: *res = ""*
2) the list that is looped over: *['phone', 'desk', 'computer']*
3) the body of the loop: *for w in words: res = res + w + ' '*

0.2.3 Problem 3
What value is stored in the variable res once the code snippet from Question 2 has executed?
““

0.2.4 Problem 4
Fill in the accumulator type and description in the function design given below.
def multiply_all(loi: List[int]) -> int:
"""
return the product of all the integers in loi
"""
# return 1 # stub
# template from List[int]
# product ________________________________________________
product = 1 # type: _______
for i in loi:
product = product * i
return product

2
start_testing()
expect(multiply_all([]), 1)
expect(multiply_all([1, 2, 3]), 6)
expect(multiply_all([9, 1, 3]), 27)
expect(multiply_all([4, 1, 2]), 8)
expect(multiply_all([4, 1, 2, 2]), 16)
summary()
Note: The function in this cell is for reference only. Please edit the code in the cell below
[5]: @typecheck
def multiply_all(loi: List[int]) -> int:
"""
return the product of all the integers in loi
"""
# return 1 # stub
# template from List[int]
# product is an accumulator that holds the running product
product = 1 # type: int
for i in loi:
product = product * i
return product

start_testing()
expect(multiply_all([]), 1)
expect(multiply_all([1, 2, 3]), 6)
expect(multiply_all([9, 1, 3]), 27)
expect(multiply_all([4, 1, 2]), 8)
expect(multiply_all([4, 1, 2, 2]), 16)
summary()

5 of 5 tests passed

0.2.5 Problem 5
For each of the examples in the function design below, how many times will the body of the for
loop be executed when the function is called? (The body of the for loop is marked.)
@typecheck
def contains(loi: List[int], x: int) -> bool:
"""
return True if loi contains x and False otherwise
"""
# return False # stub
# template from List[int] with additional parameter
for i in loi:
if i == x: # BODY OF THE
return True # FOR LOOP
return False

3
start_testing()
expect(contains([], 4), False)
expect(contains([2, 3, 4], 4), True)
expect(contains([9, 1, 3], 4), False)
expect(contains([9, 1, 3], 1), True)
expect(contains([4, 1, 2], 4), True)
expect(contains([4, 1, 2, 7], 7), True)
summary()
1. expect(contains([], 4), False) –> 0 times
2. expect(contains([2, 3, 4], 4), True) –> 3 times
3. expect(contains([9, 1, 3], 4), False) –> 3 times
4. expect(contains([9, 1, 3], 1), True) –> 2 times
5. expect(contains([4, 1, 2], 4), True) –> 1 time
6. expect(contains([4, 1, 2, 7], 7), True) –> 4 times

0.2.6 Problem 6
What questions do you still have about for loops? Please make sure to get answers to these questions
via the discussion forum, office hours, or your tutorial before the second lecture on this topic.
N/A

0.3 Part Two


0.3.1 Problem 7
Suppose you want to design a data definition to represent a list of strings.
a. Which of the following is the correct data type definition?
i. # List[strings]
ii. # List
iii. # List[String]
iv. # List[str]
The correct data type definition is iv. # List[str]
b. What is the interpretation for your data definition?
[6]: # interpretation. a list of strings

c. Select the examples from the options below that you would include in your data definition.
Write a justification for choosing each example.
LOS0 = []
LOS1 = [""]
LOS2 = ["a"]
LOS3 = ["a", "cat"]
LOS4 = ["a", "cat", "banana"]
• LOS0 = []

4
• LOS2 = [“a”]
• LOS4 = [“a”, “cat”, “banana”]
Justification: always include an empty box [], and one with an example, and one with multiple
d. Write the template for your data definition. Don’t forget to include the template rules used.
[9]: # arbitrary template rule used
# description of the accumulator
acc = "" # type: str

for x in lox:
acc = ...(s, acc)

return acc

0.3.2 Problem 8
Now you want to design a function that takes a list of strings, as defined in Problem 7.
a. Complete the stub, including signature and purpose, and examples/tests of a function called
any_empty, which returns True if at least one of the strings in the list is empty (i.e. has length 0).
Be careful: an empty list and a list containing an empty string are different things. (The empty
list has 0 elements; the list containing an empty string has 1 element!)

[10]: @typecheck
def list_of_strings(los: List[str]) -> ...:
"""
Take a list of strings and return True if at least one of the string in the␣
↪list is empty

"""
# return True # stub
# template from List[str]

LOS0 = []
LOS1 = [""]
LOS2 = ["cat", "", "dog"]
LOS3 = ["cat", "dog"]

b. Which of the following are correct function bodies for any_empty? (i.e. are consistent with the
template and are correct)
i
@typecheck
def any_empty(los: List[str]) -> bool:
for s in los:
res = res and (len(s) == 0)
return res

ii

5
@typecheck
def any_empty(los: List[str]) -> bool:
# res will be set to True if any of
# the strings in the list are empty
res = False # type: bool
for s in los:
if (len(s) == 0):
res = True
return res

iii
@typecheck
def any_empty(los: List[str]) -> bool:
for s in los:
if len(s) == 0:
return True
return False
ii and iii are correct

0.3.3 Problem 9
Two of the answers to Problem 8b are correct. Decide which solution you think is better and why.
iii is better because it is more efficient and straight to the point

0.3.4 Problem 10
As you look at more and more code, how do you think it will change the way you understand and
apply the CPSC 103 design recipes?
code recipes will be easier!

0.4 Part Three


0.4.1 Problem 11
For each of the kinds of data described, circle the type that would best represent that data. If
you choose Arbitrary-Sized, specify what type of list you would use (i.e., List[str], List[int] etc.). If
you choose compound, specify how many fields you will need. In each case, the description is of a
single value of the kind of data being considered.
a. The names of every student in a school:
Arbitrary-Sized Compound Optional Enumeration
The best Data Type is [ Arbitrary-Sized]
b. A bus stop with its location and stop number:
Arbitrary-Sized Compound Optional Enumeration
The best Data Type is [Compound]

6
c. All the bus stops on a particular bus route.
Arbitrary-Sized Compound Optional Enumeration
The best Data Type is [Arbitrary Sized]
d. A person’s annual salary, with a special representation if they are not currently working:
Arbitrary-Sized Compound Optional Enumeration
The best Data Type is [ Optional]
e. The numbers of every player on a sports team:
Arbitrary-Sized Compound Optional Enumeration
The best Data Type is [ Enumeration]
f. The price and name of an inventory item:
Arbitrary-Sized Compound Optional Enumeration
The best Data Type is [ Compound]
g. The logos of all the stores in a mall (you can assume that there exists some data definition that
represents an image):
Arbitrary-Sized Compound Optional Enumeration
The best Data Type is [Arbitrary Sized]

0.4.2 Problem 12
Below is a data definition for a Course. Design a data definition for a list of courses offered at a
university. Be sure to follow all steps of the HtDD recipe.
[11]: # This cell can be run

Course = NamedTuple('Course', [('name', str),


('num', int), # in range[0,699]
('dept', str), # 4 uppercase letters
('max_stu', int)]) # in range [0, …)
# interp. a course's name, number, department that offers it, and maximum
# number of students

C1 = Course('Shakespeare', 520, 'ENGL', 45)


C2 = Course('Algorithms', 221, 'CPSC', 300)
C3 = Course('Finance', 331, 'COMM', 100)

def fn_for_course(c: Course) -> ...: # template based on compound


return ...(c.name, # str
c.num, # int in range [0, 699]
c.dept, # str 4 uppercase letters
c.max_stu,) # int in rnage [0, ...)

7
[12]: def is_small_class(c: Course) -> bool:
"""
Returns True if the course has fewer than 100 students.
"""
# return True # stub
# template from Course
return c.max_stu < 100

start_testing()

expect(is_small_class(C1), True)
expect(is_small_class(C2), False)
expect(is_small_class(C3), False)

summary()

3 of 3 tests passed

0.4.3 Problem 13
Design a function that takes a list of courses and returns a list of the course codes of the courses.
(The course code includes the department and number, e.g. “CPSC 103”) Be sure to follow the
HtDF recipe and remember to follow the reference rule.
[14]: @typecheck
def course_code(c: Course) -> str:
"""
Return the course code of a course in the format 'DEPT NUM'
"""
# return 'CPSC 103' # stub
# template from Course
return c.dept + " " + str(c.num)

start_testing()

expect(course_code(C1), "ENGL 520")


expect(course_code(C2), "CPSC 221")
expect(course_code(C3), "COMM 331")

summary()

3 of 3 tests passed

0.4.4 Problem 14
Design data definitions to represent a list of shipping containers. Each container has a length,
width, and height and is either empty or full.

8
[16]: from typing import NamedTuple

Container = NamedTuple('Container', [('length', float),


('width', float),
('height', float),
('is_full', bool)])
# interp. a container's length, width, height, and as empty or full
@typecheck
# template based on Compound (4 fields)
def fn_for_container(c: Container) -> ...:
return (c.length, # float
c.width, # float
c.height, # float
c.is_full) # bool

0.4.5 Problem 15
Did you use a Boolean or an Enumeration to represent whether the shipping container was empty
or full? How would your design change if you switched choices? Which choice do you think is
better, and why?
Boolean was the simplest way to answer the question, but if you wanted more information about
the container, enumeration would be better

0.4.6 Problem 16
Design a function that takes a list of shipping containers and returns a list containing the volume of
each of the empty containers. Be sure to follow the HtDF recipe, and design any helper functions
that might be required by the reference rule. The volume of each container can be calculated as
length*width*height.

[17]: # your solution goes here

0.4.7 Problem 17
We could design a single function that takes a Container and returns the volume of an empty
Container or None if the Container is full. Is such a function useful here? Why or why not?
Such a function might not be useful, it might be easier to break it up into two separate functions
for fullness and remaining volume in the container

0.4.8 Problem 18
We could also design a single function that takes a list of Containers and returns a list of only those
Containers that are empty. Is such a function useful here? Why or why not?
Yes! I think such a function would be useful because you could use it to filter out containers that
are empty if you need them for something else

9
0.4.9 Problem 19
Which parts of the course are you finding the most difficult?
understanding how to use an accumulator

0.4.10 Problem 20
What is your strategy for mastering the parts of the course that you are finding to be the most
difficult?
practice practice practice
[18]: # NOTE: You should not be able to edit this cell. Just run it to start the␣
↪process of submiting your code.

from cs103 import submit

COURSE = 147818
ASSIGNMENT = 1965997

submit(COURSE, ASSIGNMENT)

# If something has gone wrong and you still are not able to submit by running␣
↪the code above, SUBMIT ANYWAY

# by downloading your files and uploading them to Canvas. You can learn how on␣
↪the page

# "How to submit your Jupyter notebook" on our Canvas site.

Valid(value=True, description='Token')
SelectMultiple(description='Files', index=(0,), layout=Layout(height='100%',␣
↪width='50%'), options=('module-5-…

Button(description='submit', icon='check', style=ButtonStyle(), tooltip='submit')

[ ]:

[ ]:

10

You might also like