Assignments
-
Work 27: Help A Brother Out!
Due: Thursday 4/24 10:00 am
Submission Name: w27_towers.py
Write a function that will print out instructions on how to solve the Towers of Hanoi problem, so the monks won’t need to think so much, and can focus on enlightenment instead.
hanoi(n, start, middle, end)
- e.g.
hanoi(4, 0, 1, 2)
- e.g.
- Assume there are three towers, numbered 0, 1 and 2.
- The goal is to get all the disks from tower 0 to tower 2.
- Each printed line should be of the form:
tower_a to tower_b
denoting moving the top disk fromtower_a
totower_b
. For example, the solution for n=1 would be:0 to 2
-
The solution for n=3 would be:
0 to 2 0 to 1 2 to 1 0 to 2 1 to 0 1 to 2 0 to 2
- In order to test your solution you can use this website: http://homer.stuy.edu/~dw/hanoi/
- Select the number of disks and towers you want.
- Click the Re-initialize button.
- Paste your printed out instructions into the text box.
- Click the play moves button.
- To make them move faster, set the speed slider to a smaller value (it’s more of a delay between moves slider, so the bigger the value, the longer it takes.).
-
Lab 02: Fractal Function Flaunting
Due: Friday 4/25 10:00 am
GH Classroom Links:
- Period 9: https://classroom.github.com/a/osKw8OOb
- Period 10: https://classroom.github.com/a/6Cgndmjw
Fractal Function Flair
You will demonstrate your understanding of fractals by creating various of the three fractals we have made in class.
Fractal Functions (python)
You will have a single python program with (at least) 6 functions:
- 3 functions will be the standard versions of the fractals we made last week (koch curve, sierpinski triangle, tree).
- You will make a modified version of each fractal. A modified version means that something should change as the depth decreases. Here are some options to consider (though you may try others as well):
- Changing the length of the lines.
- Changing the width of the lines.
- Changing the color of the lines.
- Changing the angles used.
- Adding/removing lines.
- Adding/removing recursive steps.
- Each modified version should have at least 2 modifications.
- Amongst all your modifications, at least 2 should involve randomness.
- You can also have extra functions if needed (like
triangle
). - Further instructions provided in the lab python file.
Showing Off (HTML/CSS)
You will create a webpage to show off your fractals. Your page should have 3 sections (on the same page), 1 for each fractal. Each section should include:
- A picture of an example of the standard version of the fractal:
koch_curve(t, 4, 20)
sierpinski(t, 5, 200)
tree(t, 4, 50, 20)
- An explanation of your modified version.
- A picture of an example of your modified version.
- The code for your modified version.
- In HTML
<code>
is an inline element used to represent code. If you want to include multiple lines of code into a block element, you can put the<code>
element inside a<pre>
element. like this:
<pre><code> def foo(x): return x**7 </code></pre>
- In HTML
- You should have some amount of custom CSS styling. But make sure the style does not get in the way of the page itself.
- You can see a simple example (with no CSS) here: http://homer.stuy.edu/~jadw/fractal/
- The entire project (html file, css, images) should be in a subfolder of your
public_html
folder calledfractal
. With the following required parts:index.html
: Your html fileimages/
: a further subfolder containing all the image files used by your site.
- Include this folder and its contents in your submission repository.
- Here is an example of what the structure of your site folder should look like:
~/public_html dw$ tree fractal/ fractal/ ├── fractal.css ├── images │ ├── koch-basic.png │ ├── koch.png │ ├── sierpinski-basic.png │ ├── sierpinski.png │ ├── tree-basic.png │ └── tree.png └── index.html
-
Work 26: Arbor Day!
Due: Thursday 4/10 10:00 am
Submission Name: w26_tree.py
A fractal tree creates a pattern of branches recursively. Like the sierpinski triangle, it is important to keep track of the position of your turtle while drawing a tree.
- The turtle should always end is the same position as where it started. This includes the location and heading.
- At depth 1, a “tree” is just a trunk (straight line).
- At depth 2, a tree is a trunk followed by 2 depth-1 trees. One tree to the right of the trunk and one to the left. The angle between the trunk a the subtrees can be provided as a parameter.
Write
tree(t, depth, length, angle)
, which will instruct turtlet
to draw a fractal tree triangle where each branch islength
long and each subtree is separated byangle
degrees from its trunk.Here are some examples with a provided depth, each uses 30 for
angle
:- 1:
- 2:
- 3:
Here is an animation of a turtle drawing a fractal tree with depth 5.
-
Work 25: Power of the Triforce
Due: Wednesday 4/9 10:00 am
Submission Name: w25_sierpinski.py
The Sierpinski triangle is another fractal that can be drawn in a similar way to the koch curve.
- At depth 1, it is one equilateral triangle.
- At depth 2, it is 3 triangles, each with a side length that is half of the full triangle, positioned next to and on top of each other.
- As with the koch curve, think recursively. Instead of drawing a simple triangle, think of what you’re drawing as another sierpinski triangle of one less depth level.
- Unlike the koch curve, you need to pay attention to the position and heading of your turtle at the start and end of each depth level. In general, the turtle should end in the exact same position as when it started.
Write
draw_sierpinski(t, depth, length)
, which will instruct turtlet
to draw a sierpinski triangle where each side islength
long.Here are some examples with a provided depth:
- 1:
- 2:
- 6:
Here is an animation of a turtle drawing a sierpinski triangle with depth 5. Notice the way the turtles moves after finishing each triangle.
(If you’ve been enjoying these, you can look at this list of fractals and see if you can recreate any others).
Here is a simple triangle drawing function:
def triangle(t, size): t.lt(60) t.fd(size) t.rt(120) t.fd(size) t.rt(120) t.fd(size) t.rt(180)
-
Work 24: Fractal Fun!
Due: Tuesday 4/8 10:00 am
Submission Name: w24_koch.py
The Koch Curve is a type of fractal. It can be drawn by a turtle as follows:
- At depth 1, the curve is a straight line
- At depth 2, the curve is:
- A straight line (aka koch curve),
- followed by a rotation of 60 degrees to the left,
- followed by another straight line (aka koch curve)
- followed by a rotation of 120 degrees to the right
- followed by another straight line (aka koch curve)
- followed by a rotation of 60 degrees to the left
- followed by one more straight line. (aka koch curve)
- At depth 3…
- This gets confusing fast, but look back at the depth 2 description and think recursively.
- Instead of drawing a straight line, think of what you’re drawing as another koch curve of one less depth level.
Write
draw_koch(t, depth, length)
, which will instruct turtlet
to draw a koch curve where each line islength
long. It is useful to start the turtle at the left end of the screen before drawing.Here are some examples with a provided depth:
- 1:
- 2:
- 3:
- 6:
-
Work 23: Turtle Power!
Due: Tuesday 4/9 10:00 am
Submission Name: w23_turtle.py
Reminder
Check yesterday’s post for information about Monday’s special Eclipse class.
Write the following functions in python.
draw_square(t, size)
- Takes a turtle and a number as parameters.
- Have the turtle draw a square with side length equal to the number parameter.
- Exaple usage:
leonardo = turtle.Turtle() draw_square(leonardo, 200)
- Exaple usage:
draw_spiral0(t, size)
- Write a funtion that draws a stright spiral given a turtle and the length of the initial side.
- A stright spiral is a sprial like shape made of sides that are straight lines at 90 degree angles to each other. Each side is shorter than the previous side.
- A square spiral might look like this:
draw_spiral1(t, size, angle)
- Write a more generic
spiral
function, that will make a turtle draw a sprial shape given an initial side length and the angle it should turn each time.
For reference, here’s a list of basic
turtle
commands. They’re here as comments so you can paste them to the top of your code, if desired. You can also look at the official turtle documentation.# t = turtle.Turtle() # make a new turlte # t.fd(<length>) # t.fd(100) # t.bk(<length>) # t.bk(100) # t.rt(<angle>) # t.rt(45) # t.lt(<length>) # t.lt(45) # t.position() # returns (x, y) coordinates of the turtle # t.setx(<x coordinate>) # t.setx(0) # t.sety(<y coordinate>) # t.sety(0) # t.color((<red>, <green>, <blue>)) # t.color((255, 255, 0))
Note for mac users:
You may see the following warning in Thonny when running turtle code:
WARNING: Secure coding is not enabled for restorable state! Enable secure coding by implementing NSApplicationDelegate.applicationSupportsSecureRestorableState: and returning YES.
You don’t need to worry about this. It’s a known issue but will not cause any problems.
-
Test Prep 02: Answering
Due: Thursday 4/3 10:00am
Submission name: w22.py
You can find all the submitted test questions here: https://github.com/mks22-dw/thesource/tree/main/test2
Pick 4 of the short answer questions to complete. At the beginning of each question you answer, include the question number as a comment.
You are encouraged to work on more problems to prepare for the exam. You should also take a look at the multiple choice questions. I have not vetted all the questions, so there may be mistakes.
-
Test Prep 02: Questioning
Due: Wednesday 4/2 10:00 am
Submission Name: t02.py
Write Possible Test Questions
With your write three potential test questions.
- The first two should be multiple choice questions with 4 options.
- The third should be a function to program.
- This should be similar to the programming work you have had so far. Include all the information needed to write the function (formulas, etc).
Put both questions, and the answers in a python file. You can put multiple lines together in a single comment using
""" .... """
. Use this format:""" MC Question0: skill: Options: Answer ======================= MC Question1: skill: Options: Answer ======================= Programming question: skill: Description Possible solution: ======================= """
Here is a filled in Example:
""" MC Question0: What is the air speed of an unladen swallow? skill:9001 Options: A) 2 mph B) 20 mph C) 200 mph D) African or European? Answer: D ======================= MC Question: Why? skill:9001 Options: A) Because B) Yes C) Z D) When Answer: Z ======================= Programming question: skill: Write a function that returns the ones digit of an integer. Possible solution: ======================= """ def one_dig(n): return n % 10
Skill Minimal Competency Developing Competency Competency Mastery 3. Writing functions/procedures. Can write the contract for a function. Can write simple functions given a contract. Can write complex functions given a contract and can write contracts for functions given a specified task. Can write contracts for complex functions, implement those functions and create effective test cases for them. 8. Data Types Demonstrates an understanding of numeric data types. Can work with numeric and boolean data types. Can work with multiple data types. Can work with multiple data types, including null/None values. 11. Iteration Can describe iteration. Can use one built in language structure or feature to write an iterative process. Can use multiple built in language structures/features to write an iterative process. Can control iterative processes using counters and non-counter based boolean conditions. 30. Strings Can create string literals in code, and combine strings using +
.Can use []
to access individual characters of strings.Can build new strings over time using a combination of variables and literals. Can use the unicode values of characters to transform strings. 31. Lists Can use []
to access elements in a list.Can iterate over the elements of a list. Can create lists pragmatically using list methods and +
.Can create and work with lists that contain sublists.
-
Work 21: Play Ball!
Due: Tuesday 4/2 10:00 am
Submission Name: w21_baseball.py
Reminder: Test Thursday 4/4
At the bottom of this assignment you will see a long python string definition. Each line of the string contains statistics for a New York Yankees hitter form the 2024 baseball season. The lines will look like this:
Aaron Judge,CF,559,122,180,36,1,58,144
The first line provides the description of each value in the player string:
Player,Position,At Bats,Runs,Hits,2B,3B,HR,RBI
Write a python program that uses the provided string to create an HTML table based on that string (see work 17 for more details on tables). Your table should contain:
- A header row based on the first line of the string.
- Rows for each player.
- In addition to the provided values, include each player’s batting average, which can be computed by dividing the
Hits
by theAt Bats
.
- In addition to the provided values, include each player’s batting average, which can be computed by dividing the
- An extra row at the bottom which includes the total values for the team for all the statistics. Calculate a team batting average.
yankees='''Player,Position,At Bats,Runs,Hits,2B,3B,HR,RBI Austin Wells,C,354,42,81,18,1,13,55 Anthony Rizzo,1B,337,38,77,12,0,8,35 Gleyber Torres,2B,587,80,151,26,0,15,63 Anthony Volpe,SS,637,90,155,27,7,12,60 Oswaldo Cabrera,3B,299,47,74,11,0,8,36 Alex Verdugo,LF,559,74,130,28,1,13,61 Aaron Judge,CF,559,122,180,36,1,58,144 Juan Soto,RF,576,128,166,31,4,41,109 Giancarlo Stanton,DH,417,49,97,20,0,27,72 Jose Trevino,C,209,26,45,5,0,8,28 DJ LeMahieu,CI,201,19,41,5,0,2,26 Trent Grisham,CF,179,21,34,8,0,9,31 Jazz Chisholm Jr.,3B,176,28,48,7,0,11,23 Ben Rice,1B,152,20,26,6,0,7,23 Jon Berti,3B,66,10,18,0,0,1,6 Jasson Domínguez,OF,56,8,10,1,0,2,4 Jahmai Jones,UT,42,8,10,1,1,1,4 J.D. Davis,1B,19,1,2,1,0,0,1 Carlos Narváez,C,13,0,3,0,0,0,0 Oswald Peraza,3B,10,2,2,0,0,1,1 Taylor Trammell,OF,1,2,1,0,0,0,0 Duke Ellis,LF,1,0,1,0,0,0,0'''
-
Work 20: Joining Forces
Due: Thursday 3/27 10:00 am
Submission Name: w20_join.py
Write the following python functions
make_csv_string
- This function will take a list of numbers, and return a string where each value is separated by a comma.
- example
make_csv_string([90, 99, 97, 89])
==>'90,99,97,89'
make_csv_table
- Take a list of lists, where each individual element may not be a string.
- Returns a string where each sublist form the original becomes a comma separated string (like what
make_csv_string
creates), and each csv string is on its own line. - example
g = [[90, 99, 97, 89], [91, 94, 99, 89], [81, 94, 100, 100], [90, 99, 79, 81], [50, 79, 49, 41], [90, 99, 94, 94]] print(make_csv_table(g))
==>
90,99,97,89 91,94,99,89 81,94,100,100 90,99,79,81 50,79,49,41 90,99,94,94
combine_data
-
Will take a string that looks like this:
s = """90,99,97,89 91,94,99,89 81,94,100,100 90,99,79,81 50,79,49,41 90,99,94,94"""
- Returns a string where the values for each line are separated by
,
followed by a:
and the averages value for that line. - example
print(combine_data(s))
==>90,99,97,89: 93.75 91,94,99,89: 93.25 81,94,100,100: 93.75 90,99,79,81: 87.25 50,79,49,41: 54.75 90,99,94,94: 94.25
-
Work 19: What's in a Name?
Due: Wednesday 3/26 10:00 am
Submission Name: w19_names.py
Here is a string of the names of all the Major League Baseball teams, copy this into a python program:
teams = '''Los Angeles Angels Oakland Athletics Los Angeles Dodgers San Diego Padres San Francisco Giants Tampa Bay Rays Miami Marlins Chicago Cubs Chicago White Sox Kansas City Royals St. Louis Cardinals New York Mets New York Yankees Cincinnati Reds Cleveland Guardians Philadelphia Phillies Pittsburgh Pirates Houston Astros Texas Rangers Arizona Diamondbacks Colorado Rockies Washington Nationals Atlanta Braves Baltimore Orioles Boston Red Sox Detroit Tigers Minnesota Twins Seattle Mariners'''
Write a program that performs the following tasks:
- Create a list of team names.
- Create a list that contains the length of each of the team names.
- Find the average team name length.
- Create a list containing only the team names less than the average length.
- Create a list containing only the team names longer than the average length.
- Create a list that contains the number of words in each team name.
- So
New York Yankees
would be 3, whileDetroit Tigers
would be 2 s.count(' ')
will return the number of times a space appears in strings
. This will be helpful
- So
- Find the number of teams with 2 word names.
- Find the number of teams with 3 word names.
- Create a random team name by taking any of the two word team names and combining a random city/state with a random title i.e. “Minnesota Pirates”
-
Work 18: Make Like a Banana and Split!
Due: Tuesday 3/25 10:00 am
Submission Name: w18_split.py
Write the following python functions
get_values
- This function will take a string containing numbers separated by spaces (
' '
) and return a list where each value is a number from the string, but represented as numbers, strings. - example:
get_values('90 99 97 89')
==>[90, 99, 97, 89]
get_vals_list
- This function will take a string with numbers, spaces, and newlines like this:
s = """90 99 97 89 91 94 99 89 81 94 100 100 90 99 79 81 50 79 49 41 90 99 94 94"""
- It should return a list of lists, where each sublist corresponds to a line in the original string, and each value is an number represented as a number, not a string.
- example
gat_vals_list(s)
==>[[90, 99, 97, 89], [91, 94, 99, 89], [81, 94, 100, 100], [90, 99, 79, 81], [50, 79, 49, 41], [90, 99, 94, 94]]
get_averages
- This function will take a list of lists of numbers (like what
get_vals_list
returns) and return a list of averages for each sublist. - protip: there is a function
sum(g)
that will return the sum of the elements ing
, as long asg
only contains numbers. - example
get_averages(get_vals_list(s))
==>[93.75, 93.25, 93.75, 87.25, 54.75, 94.25]
- This function will take a string containing numbers separated by spaces (
-
Lab 01: Lists
Due: Tuesday 3/25 10:00am
Submission name: New GH Classroom Link
All the instructions for this assignment can be found in list.py after you click the link below to make a new repository.
- Period 9: https://classroom.github.com/a/LyHXpblg
- Period 10: https://classroom.github.com/a/vmbJpTQZ
As always, you only need the tools we’ve discussed in class to solve these problems. If you use anything from outside of class, it should not trivialize (do the entire problem) for you. For example, Problem 2 involves finding the average of a list of value, there is a python function that does this, don’t use it.
Sample output:
==========Problem 0========== list a: 10 [4, 7, 4, 1, 7, 9, 9, 7, 5, 5] list b: 10 [0, 7, 9, 4, 2, 3, 8, 9, 9, 5] ==========Problem 1========== test list: 0: ========= 1: ===== 2: ===== 3: === 4: = 5: ===== 6: ========= 7: ===== 8: ======= 9: ======== list a: 0: ==== 1: ======= 2: ==== 3: = 4: ======= 5: ========= 6: ========= 7: ======= 8: ===== 9: ===== list b: 0: 1: ======= 2: ========= 3: ==== 4: == 5: === 6: ======== 7: ========= 8: ========= 9: ===== ==========Problem 2========== test list (5.7): 5.7 list a: 5.8 list b 5.6 ==========Problem 3========== test list (4): 4 ==========Problem 4========== test list (5): 5 list a: 7 list b: 9 ==========Problem 5========== test list ([0, 1, 0, 1, 0, 4, 0, 1, 1, 2]): [0, 1, 0, 1, 0, 4, 0, 1, 1, 2] list a: [0, 1, 0, 0, 2, 2, 0, 3, 0, 2] list b: [1, 0, 1, 1, 1, 1, 0, 1, 1, 3] list c (values [0, 5) ): [3, 4, 1, 3, 3, 3, 4, 0, 0, 2] list c counts: [2, 1, 1, 4, 2] ==========Problem 6========== 0: ===== 1: ====== 2: = 0: ======== 1: ================================= 2: ============================== 3: ========================== 4: ==================================== 5: =================== 6: ======== 7: 8: ================ 9: ===================================== ==========Problem 7========== <solution not posted>
-
Work 17: The Return of HTML
Due: Thursday 3/20 10:00 am
Submission Name: w17_html.py
Python + HTML
You have written full web pages in html, but often, especially for larger websites, people don’t write all the html. Instead, they focus on writing the content and providing some information about its structure, and then rely on a computer program to generate the actual HTML. Today, you will write some functions that generate HTML. In order to make sure they are correct, you can paste the output into this HTML “playground”.
make_link(url, anchor)
- Assume
url
is a string containing a valid link, andanchor
is a string. - Return a string containing a complete
<a>
tag usingurl
andanchor
print(make_link('http://xkcd.com', 'xkcd'))
-><a href="http://xkcd.com">xkcd</a>
html_list(g)
- Assume
g
is a list. - Return a string containing a full HTML unordered list
<ul>
containing the elements ing
. - While not necessary for HTML, put newlines between each list item.
print(html_list(['cat', 'dog', 47]))
->-
<ul> <li>cat</li> <li>dog</li> <li>47</li> </ul>
-
link_list(links, anchors)
- Assume
links
is a list containing valid urls. - Assumer
anchors
is a list the same size aslinks
containing strings. - Return a string containing a full HTML unordered list
<ul>
where each item is a link using the corresponding elements from each list.- i.e.
anchors[0]
should be the text forlinks[0]
- i.e.
- While not necessary for HTML, put newlines between each list item.
us = ['https://www.stuycs.org/fcs00-dw/', 'https://github.com/mks22-dw/thesource', 'https://www.stuycs.org/dwlessons/fcs/selector.html'] ts = ['class site', 'source code', 'slides'] print(html_link_list(us, ts))
<ul> <li><a href="https://www.stuycs.org/fcs00-dw/">class site</a></li> <li><a href="https://github.com/mks21-dw/solutions">source code</a></li> <li><a href="https://www.stuycs.org/dwlessons/fcs/selector.html">slides</a></li> </ul>
make_table(data)
- An HTML table organizes information in rows. The basic building blocks of tables are the
table
,tr
, andtd
elements:table
: container for the entire table.tr
: container for a single row of a tabletd
: container for actual data in the table- here is a sample table with 2 rows:
<table> <tr><td>a</td><td>b</td><td>c</td></tr> <tr><td>e</td><td>f</td><td>g</td></tr> </table>
- Assume
data
is a list of lists, where each sublist is the same length. make_table
should return a string containing the full HTML for atable
element. Each row of the table should be a single sublist ofdata
.d = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] print(make_table(d))
<table> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>4</td><td>5</td><td>6</td></tr> <tr><td>7</td><td>8</td><td>9</td></tr> <tr><td>10</td><td>11</td><td>12</td></tr> </table>
- Assume
-
Work 16: Lists!
Due: Wednesday 3/19 10:00 am
Submission Name: w16_list.py
Write the following functions in python.
For all of these functions, only use methods/structures we’re covered in class.
make_list_to_n(n)
- Make and return a list of integers of all integers from
1
ton
inclusive. They should be in increasing order.make_list_to_n(0)
→[]
make_list_to_n(1)
→[1]
make_list_to_n(3)
→[1, 2, 3]
- Make and return a list of integers of all integers from
power_list(b, n)
- Make and return a list of the powers of
b
from1
ton
, inclusive. power_list(2, 5)
->[2, 4, 8, 16, 32]
- Make and return a list of the powers of
make_sentence(g)
- Assume
g
is a list containing strings that are non-empty and do not start or end with space - Take all of the strings in
g
, and combine them into one string, separated by spaces. Return that string make_sentence([])
→''
make_sentence(['bob'])
→'bob'
make_sentence(['hot', 'dog'])
→'hot dog'
- Assume
join_list(g, s)
- Assume
g
is a list ands
is a string. - Return a string containing all the elements of
g
, separated bys
. join_list([4, 18, 2], '-')
->'4-18-2'
join_list([1, 2, 3, 4], ' potato ')
->'1 potato 2 potato 3 potato 4'
<!– makeFibList- Make a list of the Fibonacci numbers up to the nth term. The 0’th element is 0, the 1st is 1.
- makeFibList(0) → [0]
- makeFibList(1) → [0, 1]
- makeFibList(2) → [0, 1, 1] –>
- Assume
-
Work 15: Cut it Out
Due: Wednesday 3/20 10:00 am
Submission Name: w15_slice.py
Write the following python functions using STRING SLICING
Do not use any loops in these functions. Instead, use string slicing to solve each.
split_name
- Takes a string representing a name as a parameter. Assume the string has a first and last name, separated by spaces, like
"Eddie Vedder"
- Should return a string with each part of the name on its own line
- Example:
>>> print(split_name("John Shaft")) John Shaft
- Takes a string representing a name as a parameter. Assume the string has a first and last name, separated by spaces, like
bondify
- Names sound cooler the way James Bond says them (“Bond… James Bond”), so we’ll write a python program to do that!
- Takes a single parameter representing a name, the same format as splitName.
- Should return a new string with the input name written Bond style.
- Example:
bondify("Mr DW") ==> "DW... Mr DW"
find_last
- Takes 2 parameters, one representing a string and the second representing a character.
- Returns the index of the last occurrence of the character in the string, or -1 if the character is not in the string.
- Examples
find_last( 'hello', 'l') ==> 3 find_last('hello', 'h') ==> 0 find_last('hello', 'z') ==> -1
replace
- This function will take a string and replace part of it with something new
- Takes 3 string parameters, The first represents the original string, the second represents the part you want to take out (key), and the last represents the replacement string.
- Returns a new string that is a copy of the original except that the replacement string is located where the key use to be.
- If the key is not in the original string, you should return the original, unmodified.
- the
.find()
method will work with multi-character strings. - Example:
replace("I abhor cs!", "abhor", "love") ==> "I love cs!"
-
Test Prep 01: Answering
Due: Friday 3/14 10:00am
Submission name: w14.py
You can find all the submitted test questions here: https://github.com/mks22-dw/thesource/tree/main/test1
Pick 4 of the short answer questions to complete. At the beginning of each question you answer, include the question number as a comment.
You are encouraged to work on more problems to prepare for the exam. You should also take a look at the multiple choice questions. I have not vetted all the questions, so there may be mistakes.
-
Test Prep 01: Questioning
Due: Thursday 3/13 10:00 am
Submission Name: t01.py
Test Description
The exam on Friday will cover the following major topics (skill list at the bottom of this post):
- Python basics (variables, types, operators, functions)
- Conditional statements (
if
,else
,elif
) - While loops
- String basics (
len
,find
, indexing,ord
,chr
) - The exam will have multiple choice questions and functions to write. It may have other short-answer type questions as well.
Write Possible Test Questions
With your write three potential test questions.
- The first two should be multiple choice questions with 4 options.
- The third should be a function to program.
- This should be similar to the programming work you have had so far. Include all the information needed to write the function (formulas, etc).
Put both questions, and the answers in a python file. You can put multiple lines together in a single comment using
""" .... """
. Use this format:""" MC Question0: skill: Options: Answer ======================= MC Question1: skill: Options: Answer ======================= Programming question: skill: Description Possible solution: ======================= """
Here is a filled in Example:
""" MC Question0: What is the air speed of an unladen swallow? skill:9001 Options: A) 2 mph B) 20 mph C) 200 mph D) African or European? Answer: D ======================= MC Question: Why? skill:9001 Options: A) Because B) Yes C) Z D) When Answer: Z ======================= Programming question: skill: Write a function that returns the ones digit of an integer. Possible solution: ======================= """ def one_dig(n): return n % 10
Skill Minimal Competency Developing Competency Competency Mastery 3. Writing functions/procedures. Can write the contract for a function. Can write simple functions given a contract. Can write complex functions given a contract and can write contracts for functions given a specified task. Can write contracts for complex functions, implement those functions and create effective test cases for them. 5. Working with Boolean Values Understands the purpose of boolean values. Demonstrates the appropriate use of comparison operators. Demonstrates the appropriate use of comparison and boolean operators. Writes functions that take in boolean values and/or return boolean values. 6. Using Conditional Statements Can trace the result of a single conditional statement. Can write conditional statements with one or two results. Can write nested conditional statements. Can use at least two different kinds of conditional statements, and understand the benefits of each. 8. Data Types Can use the unicode values of characters to transform strings. Can work with numeric and boolean data types. Can work with multiple data types. Can work with multiple data types, including null/None values. 11. Iteration Can describe iteration. Can use one built in language structure or feature to write an iterative process. Can use multiple built in language structures/features to write an iterative process. Can control iterative processes using counters and non-counter based boolean conditions. 30. Strings Can create string literals in code, and combine strings using +
.Can use []
to access individual characters of strings.Can build new strings over time using a combination of variables and literals. Can use the unicode values of characters to transform strings.
-
Lab 00: Rot13
Due: Wednesday 3/12 10:00am
Submission name: New GH Classroom Link
All the instructions for this assignment can be found in rot13_lab.py after you click the link below to make a new repository.
- Period 9: https://classroom.github.com/a/938Cefhf
- Period 10: https://classroom.github.com/a/wCPycmcV
Sample output (I’ve truncated some of the output, which you can see from
...
):==========Problem 0========== a: 97 b: 98 c: 99 ... x: 120 y: 121 z: 122 ==========Problem 1========== An actual answer should go here. ==========Problem 2========== b: o q: d ?: ? ==========Problem 3========== a -> n b -> o c -> p ... x -> k y -> l z -> m ==========Problem 4========== skywalker -> fxljnyxre An actual answer should go here ==========Problem 5========== b: o q: d B: O Q: D ?: ? ==========Problem 6========== Red 5 standing by! -> Erq 5 fgnaqvat ol! Erq 5 fgnaqvat ol! -> Red 5 standing by!
-
Work 13: Casing the Joint
Due: Wednesday 3/13 10:00 am
Submission Name: w13_case.py
Write the following python functions
upcase
- Takes a single character string as an argument and returns the upper case version of it.
- If the string does not contain a letter, or it already is upper case, return the original string.
- Examples:
upcase('C') ==> 'C' upcase('3') ==> '3'
upstring
- Takes a string as an argument, and returns a copy of the string where all the lower case letters are capitalized.
- Examples:
upstring('hello') ==> 'HELLO' upstring("What's up?") ==> "WHAT'S UP?"
-
Work 12: I've Got the World on a String
Due: Friday 3/7 10:00 am
Submission Name: w12_string.py
Write the following python functions
split_name
- Takes a string representing a name as a parameter. Assume the string has a first and last name, separated by spaces, like
"Eddie Vedder"
- Should return a string with each part of the name on its own line
- Example:
>>> print(split_name("John Shaft")) John Shaft
- Takes a string representing a name as a parameter. Assume the string has a first and last name, separated by spaces, like
bondify
- Names sound cooler the way James Bond says them (“Bond… James Bond”), so we’ll write a python program to do that!
- Takes a single parameter representing a name, the same format as splitName.
- Should return a new string with the input name written Bond style.
- Example:
bondify("Mr DW") ==> "DW... Mr DW"
find_last
- Takes 2 parameters, one representing a string and the second representing a character.
- Returns the index of the last occurrence of the character in the string, or -1 if the character is not in the string.
- Examples
find_last( 'hello', 'l') ==> 3 find_last('hello', 'h') ==> 0 find_last('hello', 'z') ==> -1
-
Work 11: Pythons can be Eul-y
Due: Wednesday 3/5 10:00 am
Submission Name: w11_euler.py
Task
- Go to http://projecteuler.net/problems
- Use python to solve problems 1, 6 and 5
- Make note of the order, question 5 is harder than question 6.
- If you’ve completed them, work on more.
Sample output:
problem 1 23: 23 233168: 233168 problem 6 2640: 2640 25164150: 25164150
Important Notes
- Your completed assignment should have functions and test cases in it, at least one function per question.
- The functions you write should return the answer.
- Some of these problems are simple, many of them are difficult.
- For some of these problems it will be quite helpful to write multiple functions.
- SUPER HELPFUL CODING TIP
- Use
print
statements inside your loops to see what is happening to your variables - Some of your loops may intentionally go on for a while
- Use
Here are solutions for the first 50 problems:
Problem 001: 233168 Problem 002: 4613732 Problem 003: 6857 Problem 004: 906609 Problem 005: 232792560 Problem 006: 25164150 Problem 007: 104743 Problem 008: 40824 Problem 009: 31875000 Problem 010: 142913828922 Problem 011: 70600674 Problem 012: 76576500 Problem 013: 5537376230 Problem 014: 837799 Problem 015: 137846528820 Problem 016: 1366 Problem 017: 21124 Problem 018: 1074 Problem 019: 171 Problem 020: 648 Problem 021: 31626 Problem 022: 871198282 Problem 023: 4179871 Problem 024: 2783915460 Problem 025: 4782 Problem 026: 983 Problem 027: -59231 Problem 028: 669171001 Problem 029: 9183 Problem 030: 443839 Problem 031: 73682 Problem 032: 45228 Problem 033: 100 Problem 034: 40730 Problem 035: 55 Problem 036: 872187 Problem 037: 748317 Problem 038: 932718654 Problem 039: 840 Problem 040: 210 Problem 041: 7652413 Problem 042: 162 Problem 043: 16695334890 Problem 044: 5482660 Problem 045: 1533776805 Problem 046: 5777 Problem 047: 134043 Problem 048: 9110846700 Problem 049: 296962999629 Problem 050: 997651
-
Work 10: While I Have Your Attention
Due: Tuesday 3/4 10:00 am
Submission Name: w10_while.py
Write the following functions in python using
while
.fizz_buzz(limit)
- Loops through the integers in the range [1, limit]
- If a number is a multiple of 3, print the number and
fizz
. - If a number is a multiple of 5, print the number and
buzz
- If a number is a multiple of 3 and 5, print the number and
fizzbuzz!
(this should not also printfizz
andbuzz
) - Sample output:
fizz_buzz(22) 3 fizz 5 buzz 6 fizz 9 fizz 10 buzz 12 fizz 15 fizzbuzz! 18 fizz 20 buzz 21 fizz
fizz_what(limit, fizz_num, buzz_num)
- Works like
fizz_buzz
, but instead of 3 and 5, usefizz_num
andbuzz_num
- Sample output:
fizz_what(50, 6, 9) 6 fizz 9 buzz 12 fizz 18 fizzbuzz! 24 fizz 27 buzz 30 fizz 36 fizzbuzz! 42 fizz 45 buzz 48 fizz
- Works like
sum_digs(n)
- Returns the sum of the digits in
n
. - Example:
sum_digs(87243)
==>24
- Returns the sum of the digits in
-
Work 09: Conditional Responses
Due: Monday 3/3 10:00 am
Submission Name: w09_if.py
Write the following functions in python.
max3
- Has three parameters representing numbers.
- Returns the largest value of the three parameters.
distance
- Takes 4 parameters representing 2
(x, y)
points. - Assume the order is
(x0, y0, x1, y1)
- You can find a working
distance
function in the solution to last nights work on thesource. - Returns the distance between the two points.
- Use the distance formula: sqrt( (x1 - x0)2 + (y1 - y0)2)
- Takes 4 parameters representing 2
closer_point
- Takes 6 inputs, each pair of inputs represents the (x, y) coordinates of a point on the cartesian plane.
- Assume the order is
(x0, y0, x1, y1, x2, y2)
- Assume the order is
- Prints out which of the first two points is closer to the third point.
- If both points are equidistant, print a message stating they are the same distance.
- Sample output:
(10, 10) is closer to (0, 0)
- Takes 6 inputs, each pair of inputs represents the (x, y) coordinates of a point on the cartesian plane.
is_leap_year
- Takes one parameter representing a year. Prints out if the provided year is a leap year or not.
- Years divisible by 4 are leap years except if they are divisible by 100 but not divisible by 400.
- Samples output:
2024 is a leap year
.
-
Work 08: Funky Pythons
Due: Friday 2/28 10:00 am
Submission Name: w08_funcs.py
RESET YOUR BRAIN
- This is your first python assignment.
- While there are many ways to write/run ptyhon code, I strongly suggest your download and install Thonny.
Write the following functions in python.
distance
- Calculate and return the Euclidean distance between the coordinates given as parameters.
- Distance Formula (To calculate square root use:
a**0.5
):
- Examples:
distance(3, 0, 0, 4) → 5.0 distance(1, 0, 2, 0) → 1.0 distance(0, 0, 8, 15) → 17.0
f_to_c
- Write a function to convert Fahrenheit temperatures into Celsius.
- Celsius = (f - 32) * (5/9)
- Examples
f_to_c(32.0) → 0.0 f_to_c(212.0) → 100.0 f_to_c(-40) → -40.0
eval_quadratic
- Write a function that evaluates a quadratic equation in the form Y = aX2 + bX + C.
- It accepts the parameters in the order a b c x, and returns the y value.
- Examples
eval_quadratic(1, 0, 3, 1) → 4 eval_quadratic(1, 2, 3, 1) → 6 eval_quadratic(1, 0, 3, 2) → 7
is_even
- Determine if n is even, return
True
when it is,False
otherwise. - Examples
is_even(12) → True is_even(11) → False is_even(0) → True
- Determine if n is even, return
-
Project 00: Further Enlightenment'
Due: Friday 2/28 10:00am
Submission Name: See below for instructions
Sample of different CSS styles and site layout: http://homer.stuy.edu/~jadw/site/
Project Overview
- This is an extension of w05_subject.
- If you would prefer to change the subject of this website, you may.
- You’re going to turn your subject specific page into a larger web site! At a minimum, your site should have the following files:
- A main landing page:
- This page should explain what your site is about, a general overview of the subject.
- A page for each section from your original subject page
- This means you should have at least 3 such pages.
- You should add more detail to each section.
- A single css file used by all your pages.
- A main landing page:
Implementation Specifics
- The list at the beginning of your subject html page should turn into a horizontal or vertical menu where each list item is a link to the respective page.
- You should put this list inside a nav element.
- The position, layout, coloring etc of the menu should be all done using css.
- The navigational menu should indicate in some way what page is currently being viewed.
- The navigational menu should also contain a link to the main landing page.
- All image sources should be image files instead of links.
- The entire project (html files, css, images) should be in a subfolder of your
public_html
folder calledsite
. With the following required parts:index.html
: The main landing page for your site.- All other html files, and your css file.
images/
: a further subfolder containing all the image files used by your site.- Here is an example of what the structure of your site folder should look like:
~/public_html dw$ tree site/ site/ ├── images │ ├── img0.png │ ├── img1.jpg │ ├── img2.png │ └── img3.gif ├── index.html ├── mystyle.css ├── p0.html ├── p1.html └── p2.html
Evaluation
You will be evaluated on the following:
- Technical aspects
- appropriate use of html and css
- correct directory structure
- correct use of
public_html
for publication as well as submission in your GitHub repository.
- Styling
- Content
- You must be the author of all the content, html and css for your website. You cannot use any web authoring tools that automatically generate html or css code.
- Do not include any javascript.
Further Resources
You will want to go back over the HTML and CSS links from the previous 2 assignments. You may also find the following resources helpful:
Skills
Skill Minimal Competency Developing Competency Competency Mastery 27. Using a Web Server Can use public_html
to serve a single web page.Can use public_html
to serve multiple web pages.Can use public_html
to serve multiple connected pages with media resources using relative paths.Can write python programs that dynamically generate web pages via public_html
28. Writing web pages with HTML Can write HTML element tags for at least 2 different elements. Can use the required html tags to make a minimally valid HTML document. Can create HTML pages that contain the required tags, hyperlinks and multiple other HTML elements and use attributes correctly. Can create HTML pages that use elements like div
andspan
to organize content and provide links to CSS styling files.29. Styling web pages with CSS Can use CSS to modify a single element using in-line styling. Can use CSS in the head of a webpage to modify multiple elements. Can use CSS in an external file to provide multiple style options for multiple elements. Can use CSS to modify the layout of a webpage.
- This is an extension of w05_subject.
-
Test Prep 00: Answering
Due: Friday 2/14 10:00am
Submission name: w07.txt
You can find all the submitted test questions here: https://github.com/mks22-dw/thesource/tree/main/test0
Pick 4 of the short answer questions to complete. At the beginning of each question you answer, include the question number above. Since this will be a mix of command line instructions, html and css, put your answers in a plain text file.
You are encouraged to work on more problems to prepare for the exam. You should also take a look at the multiple choice questions. I have not vetted all the questions, so there may be mistakes.
Important Notes:
- You can see sample html and css here: https://github.com/mks22-dw/thesource/tree/main/web
- Even though they are present on the notes slides, you can ignore the following concepts:
div
andspan
elements- The
overflow
css property
-
Test Prep 00: Questioning
Due: Thursday 2/13 10:00am
Submission name: test00.txt
Write Possible Test Questions
Write three potential test questions.
- The first two should be multiple choice questions with 4 options.
- The third one should be a more open-ended question.
Put all questions, and the answers in a plain text file. Use this format:
#| MC Question: Skill: Options: Answer |# #| MC Question: Options: Skill: Answer |# #| Open Ended Question: Skill: Description Possible solution: |# ANSWER GOES HERE
Here is a filled in Example:
#| MC Question: What is the air speed of an unladen swallow? Skill: 9001 Options: A) 2 mph B) 20 mph C) 200 mph D) African or European? Answer: D |# #| MC Question: Who you gonna call? Skill: 9001 Options: A) Transformers B) Ghostbusters C) Thundercats D) Teenage Mutant Ninja Turtles Answer: B |# #| Open Ended Question: Skill: 9002 What is 1 in binary? Possible solution: |# 1
Test Skills
Skill Minimal Competency Developing Competency Competency Mastery 26. Using The Command Line Interface Understands the purpose of the command line and can identify information present in the default bash prompt. Can navigate the file hierarchy using cd
,ls
andpwd
.Can view and modify files using cp
,mv
,cat
, andless
.Can effectively use the command line to navigate the file system, including using command line and keyboard shortcuts. 27. Using a Web Server Can use public_html
to serve a single web page.Can use public_html
to serve multiple web pages.Can use public_html
to serve multiple connected pages with media resources using relative paths.Can write python programs that dynamically generate web pages via public_html
28. Writing web pages with HTML Can write HTML element tags for at least 2 different elements. Can use the required html tags to make a minimally valid HTML document. Can create HTML pages that contain the required tags, hyperlinks and multiple other HTML elements and use attributes correctly. Can create HTML pages that use elements like div
andspan
to organize content and provide links to CSS styling files.29. Styling web pages with CSS Can use CSS to modify a single element using in-line styling. Can use CSS in the head of a webpage to modify multiple elements. Can use CSS in an external file to provide multiple style options for multiple elements. Can use CSS to modify the layout of a webpage.
-
Work 06: Stuylin' and Profilin'
Due: Wednesday 2/12 10:00 am
Submission Name: hello_style.css
Skills For Friday’s Exam: 26, 27, 28, 29
CSS Time
Create a css file called
hello_style.css
in your web repository. This will be a style file used on your webpage forhello.html
(from work_04).- In this file you must set at least one css property for each element in
hello.html
(except forhead
and anything inhead
). - This file should have at least one example for each of the properties in this table.
- Add your css file to the html file
hello.html
.
Notes About Working From Home
- Your home computer is probably not set up as a webserver, this is fine, but it means you’ll have to work a little differently than at school. First off, you will need a text editor and a web browser. I suggest pulsar as your text editor. You must use a plain text editor, so something like word or google docs is NOT acceptable.
- Open your HTML and CSS files in your text editor, this is where you will edit them.
- Also open your HTML (not the CSS, it will be included via the HTML file) in your web browser. Open it via the Open File option in the File menu of your browser. The address bar will start with:
file:///
followed by the path to your HTML file. - As you edit your CSS, reload the HTML file in the browser. You may need to do a force reload (on firefox, that’s ctrl-shift-r)
- In this file you must set at least one css property for each element in
-
Work 05: Enlighten Us
Due: Monday 2/10 10:00 am
Submission Name: subject.html
Helpful resources:
Make a web page for something about which you are knowledgeable (could be anything, an academic subject, sport, music, theater, movie, comic …). The page should not be an exhaustive report on the subject, but provide some information in a coherent framework. Your page should include the following parts:
- A main title/heading
- heading element:
<h1>
- heading element:
- A table of contents made of an unordered list.
- list element:
<ul>
and<li>
- You should have at least 3 sections listed.
- list element:
- Sections of text that correspond to each element in the table of contents.
Notes:
- You may be tempted to do things to modify the look of your page. Do not. Focus on the structure of the page, for that is what HTML is designed to do. We will work on making pages look fancy using CSS, at which point you can go nuts
- A main title/heading
-
Work 04: Hello Again
Due: Friday 2/7 10:00 am
Submission Name: hello.html
Helpful resources:
- Table of common elements from notes
- I’ve also included links to documentation for each tag you need to use below.
- Best practices for writing html from notes
- The default text editor (which works well for html) on the school computers can be opened using
$ xed
.
Write a real Web Page
Write a simple html file, properly formatted (which means include the non-visible html tags like
DOCTYPE
html
head
andbody
), that uses the following elements (you can include others if you’d like):- heading:
<h1>
- anchor (link):
<a>
- list:
<ul>
and<li>
- image:
<img>
Submission Notes
Make sure your page is in your
public_html
directory on your school computer and added to your github repository as well. If you work on this from home, you’ll need to get your work intopublic_html
at school. How can you do that? Via the command line of course!scp
stands for secure copy and can be used to send files over the internet using the ssh protocol.- Open your terminal program (extra tip for those using gitbash below).
- Use
cd
to navigate to the directory that contains your file. - Use
scp
to send the file.$ scp FILE USERNAME@homer.stuy.edu:public_html/
Will uploadFILE
into yourpublic_html
directory.- Example:
$ scp hello.html dw@homer.stuy.edu:public_html/
- If this is the first time you are using
scp
orssh
to connect to homer (which it probably is), you will get a warning that starts with:The authenticity of host 'homer.stuy.edu (149.89.150.100)' can't be established.
, respond to the question withyes
. - Next you will be prompted for your password.
- Then the file will be transferred.
- You can test that the transfer was successful by loading your webpage in a browser.
- You can also do this processs in reverse to copy the file from school to your home computer.
$ scp USERNAME@homer.stuy.edu:public_html/FILE ./
Will downloadFILE
into your current directory (./
).- Example:
$ scp dw@homer.stuy.edu:public_html/hello.html ./
If you’re using gitbash, the easiest way to make sure you’re in the correct directory is to right click on the directory in your GUI and select “Open in gitbash”. This should open a new Gitbash terminal and immediately set your working directory correctly.
-
Work 03: Hello
Due: Wednesday 2/5 10:00 am
Submission Name: hello.html
Make a Web Page
- Create a file called
hello.html
. Try using some of the following html elements in this file:- heading:
<h1>
- anchor (link):
<a>
- list:
<ul>
and<li>
- image:
<img>
- heading:
- Put this file in your
public_html
directory. If successful, you should be able to access the page athttp://homer.stuy.edu/~YOUR_USERNAME/hello.html
- Upload this file to your github repository as well.
- Create a file called
-
Work 01: Commanding Authority
Due: Friday 2/2 10:00 am
Submission Name: w01_commands.txt
Create your work repository
All Assignments will be submitted via GitHub classroom. Labs and projects will have their own assignment links, all homeworks should be submitted in the homework repository. Create your homework repository by following the appropriate link:
- Period 9 GH Classroom link: https://classroom.github.com/a/A7KVeMuv
- Period 10 GH Classroom link: https://classroom.github.com/a/xcmaMfow
Create a directory structure
On school computers, create the following directory structure starting in your home directory.
$ tree marvel/ marvel/ ├── heroes │ ├── avengers │ │ ├── black_widow.txt │ │ └── hulk.txt │ └── xmen │ ├── storm.txt │ └── wolverine.txt └── villains ├── hydra │ └── red_skull.txt └── thanos.txt 5 directories, 6 files
- In a plain text file, write down the exact sequence of commands you used to do this, putting each command on its own line. Upload that file to your github repository.
-
Work 01: Highway to the Danger Zone
Due: Monday 2/03 10:00 am
Unfortunately, I will be out today, but have no fear! You can continue getting used to the command line by following theses easy steps:
- Open up the terminal on your computer.
- If you’re at home, you can do the following to get a terminal:
- MacOS: You should already have a program called
terminal
, search for it on your computer and open it. It will look very much like the terminal program on the school computers. - Windows: Download and install gitbash. It will provide you with a program that will also work very much like the terminal on the school computers.
- ChromeOS (I only just discovered this and have not tested it out yet). Looks like you can enable a terminal if you follow the instructions here: https://chromeos.dev/en/productivity/terminal
- Read the first two chapters (
BasicsandManipulating Files) in Learn Enough Command Line to Be Dangerous. As you read you will learn about a number of command line features and utilities, some of which you used while playing bashcrawl. Try things out! If you feel like you’ve ended up in a strange place in the terminal you can always try the following:$ cd
: This will change you into your home directory, useful if you runcd
too many times and you don’t know where you are anymore.- CTRL-c: This should immediately quit the current active command, useful if it seems like the terminal is no longer responding.
- Quit the terminal program: If all else fails, start anew!
- Open up the terminal on your computer.
-
Work 00: Getting to know you
Due: Thursday 1/30 10:00 am
- Please fill out the student info form found here: https://forms.gle/F92MtZNBsgV3WwWv7
- You will need a GitHub account in order to submit work for this class. If you don’t have one already, go to https://github.com/ and create one.