#Name: Thomas Hunter #Email: thomas.hunter1870@myhunter.cuny.edu #Date: September 1, 2022 #This program prints: Hello, World! print("Hello, World!")
Submit the following programs via Gradescope:
Write a program that prints "Hello, World!" to the screen.
Hint: See the Lab 1.
Write a program that draws a dodecagon (polygon with 12 sides).
Note: Whenever submitting a turtle program, choose a name for your file that is not turtle.py.
When executing the "import turtle" statement, the computer first looks in the folder where the file is saved for the turtle module and then in the libraries (and other places on the path). So, it thinks the module is itself, causing all kinds of errors. To avoid this, name your program something like "myTurtle.py" or "program2.py".
Hint: See the Lab 1.
Write a program that implements the pseudocode ("informal high-level description of the operating principle of a computer program or other algorithm") below:
Repeat 9 times:
Walk forward 100 steps
Turn left 105 degrees
Walk forward 52 steps
Turn left 105 degrees
Walk forward 100 steps
Turn right 170 degree
The result should look as follows:
Write a program that implements the incomplete code (start right from the red spot and return to there). The initial part of the code is provided if you like. The colors are green, blue, cyan, and red, respectively.
import turtle
t = turtle.Turtle()
t.pensize(5)
t.shape("circle")
#TODO: finish the rest code
#hint: you may use color method of turtle.
#The distance for a long line is 300.
#The distance for a short line is 100.
The result should look as follows:
Write a program that enter an integer for number of repetition, print "Practice makes perfect." that many times.
A sample run of your code is as follows.
Enter repetition time: 5 Practice makes perfect. Practice makes perfect. Practice makes perfect. Practice makes perfect. Practice makes perfect.
Hint: you may need to use the following statement to enter an int and put it in variable num, where input function is similar to print function, however, input function can take input from users and convert the input content (ended with a return key) to a string, function int converts an string to an int.
num = int(input("Enter repetition time: "))
Next, use range(num) inside a for statement to do something num times. In this specific example, something means to print "Practice makes perfect.".
Write a program that prints out the numbers counts down from 12 to 1. Need to use repetition statement.
The output of your program should be:
12 11 10 9 8 7 6 5 4 3 2 1 WOW
Hint: Use a loop and print out the index or loop variable.
Using the string commands introduced in Lab 2, write a Python program that prompts the user for a full name in the format of first name first and last name last, separated by a space. Use split method of string to extract last name and first name, then change last name to upper case using upper method of string. Print the full name in the format of last name first, first name followed, separated by comma. Enter user name, change it to lower case letters, followed by "@hunter.cuny.edu".
A sample run of your program should look like:
Enter name in format firstName lastName: John Smith name in LASTNAME, firstName format: SMITH, John Enter user name of email: Js216 email: js216@hunter.cuny.edu
Hint: Your program should be able to take any phrase the user enters and prints it, it in upper case letters, and it in lower case letters. To do that, you need to store the phrase in a variable and print variations of the stored variable.
Write a program that prompts the user to enter a phrase. Then for each character in the phrase, print out character, its ASCII code, and the next two letter in ASCII table.
A sample run of your program should look like:
Enter a phrase: I love Python! letter ASCII next_two_letter I 73 K 32 " l 108 n o 111 q v 118 x e 101 g 32 " P 80 R y 121 { t 116 v h 104 j o 111 q n 110 p ! 33 #
And another sample run:
Enter a phrase: ABC letter ASCII next_two_letter A 65 C B 66 D C 67 E
Hint: If c is a character, ord(c) returns its ASCII code. For example, if c is 'I', then ord(c) returns 73. See Lab 2.
To right aligned the print out, use print("%6c %5i %15c"%(character, ASCII_code_of_character, next_two_letter_of_character)). You need to find out expression to represent character, ASCII_code_of_character, and next_two_letter_of_character.
Explanation: Use 6c since column header "letter" has 6 letters, c means character, for example, letter 'I' in string "I love Python!". Use 5i since column header "ASCII" has 5 letters, i means int, which is the ASCII code of the current letter. Use 15c since column header "next_two_letter" has 15 letters, c means a letter, which is the next_two_letter of the current letter.
Warning: do not forget to print column names "letter ASCII next_two_letter".
(The cipher disk above shifts 'A' to 'N', 'B' to 'O', ... 'Z' to 'M', or a shift of 13. From secretcodebreaker.com.)
Write a program that prompts the user to enter a word and then prints out the word with each letter shifted right by 13. That is, 'a' becomes 'n', 'b' becomes 'o', ... 'y' becomes 'l', and 'z' becomes 'm'.
Assume that all inputted words are in lower case letters: 'a',...,'z'.
A sample run of your program should look like:
Enter an all-small-letter string: zebra Enter a non-negative int to shift: 13 ciphered string: mroen
Here is another sample run of your program.
Enter an all-small-letter string: owqfka Enter a non-negative int to shift: 6 ciphered string: ucwlqg
Hint: See the example programs from Lecture 2.
Enter a phrase, reverse it, then capitalize each letter of the reversed string. Afterwards, get an abbreviation of the last letter of each word, starting from the last word to the first one.
A sample run of your program should look like:
input: City Univ of New York user reverse: kroY weN fo vinU ytiC user reverse upper: KROY WEN FO VINU YTIC user abbreviation: CUONY
Here is another sample run of your program.
input: Srbkts L Cizyjb user reverse: bjyziC L stkbrS user reverse upper: BJYZIC L STKBRS user abbreviation: SLC
Hint: See examples of range(start,stop,step) in Lecture 2 notes.
Modify the program from Lab 3 to show the shades of cyan.
Your output should look similar to:
t = turtle.Turtle() t.penup() t.backward(100) t.left(90) t.backward(100) t.right(??) #you fill in a degree in ?? t.pendown() #TODO: draw right shade #TODO: move to the start direction of up shade #TODO: draw up shade
Warning: for the purpose of grading script, the right shade is drawn before the up shade.
Hints: you may use one of the following approaches.
Modify the program from Lab 3 to show the shades of pink and then repeat a similar loop where a loop variable goes from 255 (included) down to 0 (not included), gap step is decreased by 10 in each round.
A sample run of your program should look like:
Modify the program from Lab 3 to draw a brown turtle (color #964B00 or RGB code 150, 75, 0), stamp after each turn. The turtle moves forward by 100 in each round.
A sample run of your program should look like:
Hint: See Lab 3 for colors.
Write a program that asks the user for a name of an image .png file and the name of an output file. Your program should create a new image that sets red channel of the original image to be zero.
A sample run of your program should look like:
Enter name of the input file: csBridge.png Enter name of the output file: csBridge_wo_red.png
Sample input and resulting output files:
As another example, run the above program on shades of purple in a white background, as in the original figure shown in the left. Since purple is combination of red and blue, after setting red channel to be zero, which equals to remove red, the color of shades becomes blue in the modified figure, shown in the right.
In the original figure, background white is combined of 100% red, 100% blue, and 100% green. After removing red channel, the background has only blue and green, which changes to cyan color in the modified figure.
In the original figure, black color is combined of 0% red, 0% blue, and 0% green. After removing red channel, black color is still the same in the modified figure.
Sample input and resulting output files:
Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.
Hint: See Lab 3.
Write a program that asks the user for a message and then prints the message out, one fewer word a line until there is only one word, then continue to add one word a line until becoming the original message.
A sample run of your program should look like:
Enter a phrase: how are you? how are you? how are how how are how are you?
Hint: See Lab 2 or Lecture 2 notes. Use split method to break the original message by a a list of words. Then use for-loop to display partial of the list. To display a list of words as a string, use ' '.join(list_of_words). For example,
lst = ['a', 'bc', 'd', 'e'] print(' '.join(lst[:2])) #display the first 2 elements of lst, joined by a space, #that is, display #a bc
Enter a list of names separated by semicolon. Display each name in a line, started by the first letter of first name, followed by a dot, a space, and last name.
A sample run of your program should look like:
Enter a list of names, separated by semicolon: George Washington;James Adam;Thomas Jefferson;James Madison;James Monroe G. Washington J. Adam T. Jefferson J. Madison J. Monroe
Write a program that asks users for output file name to save the following image. A sample run of the program:
Enter output file name: shape_t.png
Hint: Here's a way to approach the problem:
Create a program that creates a image of vertical blue and green stripes. Your program should ask the user for the size of your image, the name of the output file, and create a .png file of stripes. For example, if the user enters 10, your program should create a 10x10 image, alternating between blue and green vertical stripes.
A sample run of the program:
Enter the size: 10 Enter output file: stripes10.png
Another sample run of the program:
Enter the size: 50 Enter output file: stripes50.png
Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.
Hint: See notes from Lecture 4.
You may need to use the following information.
1 feet = 30.48 centimeters
1 inch = 2.54 centimeters
To round a decimal number
Write a program that implements the pseudocode below:
(a) convert centimeters to feet (b) convert centimeters to feet and inches (c) convert feet and inches to centimeters
Some sample runs of your program should look like:
Choose Option a. When converting centimeters to feet, round the result to two decimal numbers after the decimal point.
(a) convert centimeters to feet (b) convert centimeters to feet and inches (c) convert feet and inches to centimeters Enter a or b or c: a Enter height in centimeters: 150 height is 4.92 feet
Choose Option b. Values of feet and inches are integers (whole numbers).
(a) convert centimeters to feet (b) convert centimeters to feet and inches (c) convert feet and inches to centimeters Enter a or b or c: b Enter height in centimeters: 150 height is 4 feet and 11 inchesHints for converting centimeters to feet and inches.
Choose Option b and the resulting inch is zero. In this situation, display only feet, not inch.
(a) convert centimeters to feet (b) convert centimeters to feet and inches (c) convert feet and inches to centimeters Enter a or b or c: b Enter height in centimeters: 92 height is 3 feet
Choose Option c. Round the centimeters to an integer, that is, round to zero decimal number. Note that int(5.5) truncates any decimal numbers after the decimal part and returns 5, while round(5.5, 0) returns 6.0.
(a) convert centimeters to feet (b) convert centimeters to feet and inches (c) convert feet and inches to centimeters Enter a or b or c: c Enter height in feet and inches, separated by a space: 4 11 height is 150 cmIn this task, take two inputs using
feet_str, inches_str = input("Enter height in feet and inches, separated by a space: ").split() #convert feet_str to an int using feet = int(feet_str)
Choose an option other than a, b, or c.
(a) convert centimeters to feet (b) convert centimeters to feet and inches (c) convert feet and inches to centimeters Enter a or b or c: 1 Wrong choice, please enter only a or b or c.
Hint: See Section 2.7.
Modify the program in the section Elevation Data & Flood Maps in Lab 4 to color the region just above the Sandy storm surge (6 feet) and less than or equal to 20 feet the color grey (50% red, 50% green, 50% blue). Also, modify your program to not show any graphics windows (plt.show()) but instead just compute and save the map to floodMap.png. Finally, change color red to yellow.
Generated floodMap.png looks as follows.
Following Lab 5, write a program that asks the user for the name of a png file and a threshold, print the number of pixels that are nearly white (the fraction of red, the fraction of green, and the fraction of blue are all above the given threshold). Also, calculate the percentage of those pixels divided by the total number of pixels in the picture.
For example, if your file was of the snow pack in the Sierra Nevada mountains in California in September 2014:
Suppose the file is saved as caDrought2014.png, then a sample run would be:
Enter file name: caDrought2014.png Enter threshold: 0.75 number of white pixels: 38010 percent of white pixels: 2.26 %
Note: for this program, you only need to compute the snow count. Showing the image will confuse the grading script, since it's only expecting the snow count and its percentage.
Write a logical epxression that is satisfy the following figure.
Save your expression to a text file. See Lab 5 for the format for submitting logical expressions to Gradescope.
in1 | in2 | in3 | output |
---|---|---|---|
0 | 0 | 0 | 1 |
0 | 0 | 1 | 0 |
0 | 1 | 0 | 0 |
0 | 1 | 1 | 0 |
1 | 0 | 0 | 1 |
1 | 0 | 1 | 0 |
1 | 1 | 0 | 1 |
1 | 1 | 1 | 1 |
Save your expression to a text file. See Lab 5 for the format for submitting logical expressions to Gradescope.
Write a program that asks the user for a list of words (separated by spaces), count number of words, and calculate those words ending with letter 'a' or 'b', then calculate its fraction rounded by two decimal numbers after the decimal point. Your program should output the total number of words and the fraction that end in 'a' or 'b'. Assume that words are separated by spaces (and ignore the possibility of tabs and punctuation between words.)
A sample run of the program:
Enter a list of words, separated by a space: apple banana cantalope durian shrub number of words: 5 number of words ending with a or b: 2 fraction of words starting with a or b: 0.4
And another sample run of the program:
Enter a list of words, separated by a space: af bce gdfgb agcg edc dade fggga gb number of words: 8 number of words ending with a or b: 3 fraction of words ending with a or b: 0.38Round num by two decimal numbers after the decimal point using
round(num, 2)
Approach 1
Approach 2
Implement (and test!) each part and then go on to the next. See notes from Lecture 3.
input a string, put in variable string set num to be 0 set base to be the base of binary number initialize weight to be 1, for the least significant digit set length to be the number of letters of string Move i from the rightmost index downto the leftmost index put ith letter of string to variable ch if ch is '1' increase num by weight otherwise, if ch is not '0' print that Letter ch is not allowed in a binary string call exit method to exit current program #num is not updated when ch is '0' update weight by multiplying it with base print out num followed by prompt "num ="
some sample input/output are as follows.
Enter a string with 0 or 1 only: 100101 num = 37
When an input string has more than one letter that is neither '0' or '1', only report the first violation that is closest to the least significant bit in the rightmost position.
Enter a string with 0 or 1 only: a20 Letter 2 is not allowed in binary string.
Hint: See Lecture 4 notes.
Logical gates can be used to do arithmetic on binary numbers. For example, we can write a logical circuit whose output is one more than the inputted number. Our inputs are in1 and in2 and the outputs are stored in out1, out2, and out3.
Here is a table of the inputs and outputs:
Inputs | Outputs | |||||
---|---|---|---|---|---|---|
Decimal Number | in1 | in2 | Decimal Number | out1 | out2 | out3 |
0 | 0 | 0 | 1 | 0 | 0 | 1 |
1 | 0 | 1 | 2 | 0 | 1 | 0 |
2 | 1 | 0 | 3 | 0 | 1 | 1 |
3 | 1 | 1 | 4 | 1 | 0 | 0 |
Toggle the inputs, by clicking on the input boxes for in1 and in2, and observe the output. Then translate the circuit into a logical expression.
Submit a text file (.txt) with each of the outputs on a separate line:
#Name: YourNameHere #Date: August 2022 #Logical expressions for a 3-bit incrementer out1 = ... out2 = ... out3 = ...Where "..." is replaced by your logical expression (see Lab 5).
Note: here's a quick review of binary numbers.
Modify the program from Lab 6 that displays the NYC Covid-19 Cases. Your program should ask the user for the name of csv file, name of a borough and the name of the output file.
The program should compute the minimum, maximum, average, median and standard deviation of the covid-19 cases of the borough entered by the user and then display the fraction of the covid-19 daily cases in that borough over time and saves it using the file name entered by the user.
Note that mean and standard deviation are rounded to 3 decimal numbers after the decimal point. Read the attached csv file to see column names. Use exact the same column name in your program.
IMPORTANT: The grading script expects the new column to be called 'Fraction'
A sample run of the program:
Enter a csv file: covid_daily_cases.csv Enter borough (Bronx, Brooklyn, Queens, Manhattan, Staten Island): Queens Enter output name: queensCovidFraction.png Min: 0 Max: 15201 Mean: 728.066 Median: 329.0 Standard Deviation: 1552.465
The file queensCovidFraction.png:
Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.
Write a program that analyzes children under six affected by lead in five boroughs of NYC in 2005 to 2016. Data is extracted from open data of NYC and saved in children_lead.csv. Your program should assume that above data file is in the same directory. The file has three columns: borough, year, and affected_children. Each row records the number of children under six whose blood lead level is at least 5 micrograms of lead per deciliter of blood (μg/dL) in the specific borough and year. Choose Option a to group by borough, report average of number of affected children in each borough. Enter a specific borough. Report the minimum, maximum, and average number of affected children in those years. Choose Option b to group by year, report average of number of affected children in each year. Enter a specific year. Report the minimum, maximum, and average number of affected children in the boroughs.
A sample run of your program to group by borough.
Enter a choice: a. group by borough b. group by year a average number of affected children by borough borough Bronx 3254.750000 Brooklyn 6966.333333 Manhattan 1837.250000 Queens 3750.500000 Staten Island 497.166667 Name: affected_children, dtype: float64 Enter a borough: Staten Island average number of affected children of Staten Island is 497.1666666666667 min number of affected children of Staten Island is 164 max number of affected children of Staten Island is 1049
Here is a run to group by year.
Enter a choice: a. group by borough b. group by year b average number of affected children by year year 2005 7467.8 2006 6924.6 2007 6095.8 2008 4080.4 2009 3043.4 2010 2790.2 2011 2287.4 2012 1635.4 2013 1440.4 2014 1310.0 2015 1073.8 2016 985.2 Name: affected_children, dtype: float64 Enter a year (2005 - 2016): 2014 average number of affected children in 2014 is 1310.0 min number of affected children in 2014 is 238 max number of affected children in 2014 is 2929
A sample run of your program to choose options other than a or b is as follows.
Enter a choice: a. group by borough b. group by year c wrong choice
Hint: See Lab 6.
Write an Unix shell script that prints: Hello!
Then prints on a new line: Greeting from $USER
where $USER is a built-in variable that stores the name of the user.
A sample run of the program with user laptopuser:
Hello! Greeting from laptopuser
Submit a single text file containing your shell commands. See Lab 6 for details.
Note: The output will not display a username on Gradescope since there is no login on the cloud image where the grading script runs.
In Lab 6, you created a github account. Submit a text file with the name of your account. The grading script is expecting a file with the format:
#Name: Your name #Date: August 2022 #Account name for my github account AccountNameGoesHere
Note: it takes a few minutes for a newly created github account to be visible. If you submit to gradescope and get a message that the account doesn't exist, wait a few minutes and try again.
Refer to the program from Lab 7. Read country_internet.csv downloaded from kaggle.com. The file records number of internet users and population in different countries.
A sample run of the program:
Enter output file name: internet_users_percentage.png maximum percentage of all countries: Faroe Islands 99.18 %
which produces an output:
Note: The grading script is expecting that the label (i.e. name of your new column) is "Percentage".
Refer to the program from Lab 7. Read country_internet.csv downloaded from kaggle.com. Your program will do the following,
grouped_data.get_group(chosen_region).plot.bar(...) #the first parameter of bar method is the column name representing country, the second parameter is the number of internet plans plt.gcf().subplots_adjust(bottom=0.25) #so that the country name is displayed in full plt.xlabel(...) #The parameter in xlabel should be "Country in ...", where ... is the name of chosen region. The region name should be exactly the same as the corresponding region the csv file. plt.ylabel("NO. OF Internet Plans")
A sample run of the program:
Continental region ASIA (EX. NEAR EAST) 37.964286 BALTICS 26.333333 CARIBBEAN 17.068966 CENTRAL AMERICA 24.500000 CIS (FORMER USSR) 23.909091 EASTERN EUROPE 28.714286 Europe NaN NEAR EAST 31.750000 NORTHERN AFRICA 23.285714 NORTHERN AMERICA 32.250000 OCEANIA 17.318182 SOUTH AMERICA 32.692308 SUB-SAHARAN AFRICA 28.391304 WESTERN EUROPE 24.566667 Name: NO. OF Internet Plans, dtype: float64 possible regions are dict_keys(['ASIA (EX. NEAR EAST)', 'BALTICS', 'CARIBBEAN', 'CENTRAL AMERICA', 'CIS (FORMER USSR)', 'EASTERN EUROPE', 'Europe', 'NEAR EAST', 'NORTHERN AFRICA', 'NORTHERN AMERICA', 'OCEANIA', 'SOUTH AMERICA', 'SUB-SAHARAN AFRICA', 'WESTERN EUROPE']) choose a region: NORTHERN AMERICA In region NORTHERN AMERICA number of countries: 4 maximum number of internet plans: 60.0 minimum number of internet plans: 3.0 Please enter output file name: internet_plans_northern_america.png
which produces an output:
Write a program, using a function main() that enter a string and a letter, count the number of occurrence of that letter in the string. See Lab 7.
Enter a string: Hello, how are you? Enter a char: o number of 'o' in "Hello, how are you?" is 3
Write a program that asks the user for a choice.
The logo is from ImageMagick program. A sample run of your program should look like:
Enter 1 to get upper right corner Enter 2 to get middle portion Your choice: 1 Enter input file name: magic_logo.png Enter output file name: magic_logo_upper_right.png
which would have as input and output:
Another sample run of your program should look like:
Enter 1 to get upper right corner Enter 2 to get middle portion Your choice: 2 Enter input file name: magic_logo.png Enter output file name: magic_logo_middle.png
which would have as input and output:
When entering any number other than 1 or 2, here is an output:
Enter 1 to get upper right corner Enter 2 to get middle portion Your choice: 3 wrong choice
Hint: See sample programs from Lectures 4 and 6.
Hint: When input a choice other than '1' or '2', print "wrong choice" and exit the program. Otherwise, enter the input file name and output file name, then depending on the choice (either '1' or '2'), cut the image and save the portion to the output file.
Note: before submitting your program for grading, remove any commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.
Write a program that asks the user for the hour of the day (in 24 hour time), and prints
A sample run:
Enter hour (in 24 hour time): 11 Good Morning
Another sample run:
Enter hour (in 24 hour time): 20 Good Evening
And another run:
Enter hour (in 24 hour time): 15 Good Afternoon
Write a function, computePrice(), that takes two parameters: liquid (string) and the size type (string). The function should return a float for the price of the liquid of that size.
A sample run:
medium size tea: 2.45
And another:
medium size wine: -1
Hint: See Lab 8.
Write function, flowerRecursion(), in recursive function for the flower in Problem 2. Key idea: if the number of petals is larger than zero, draw a petal. Call flowerRecursion to draw the flower with remaining petals.
Here is a pseudocode.
def flowerRecursion(t, n): if n > 0: #draw one petal move t forward 100 steps turn t left 105 degrees move t forward 52 steps turn t left 105 degrees move t forward 100 steps #prepare to move direction to draw next petal t.right(170) call flowerRecursion with t and n-1. def main(): #call flowerRecursion function to draw a flower if __name__ == '__main__': main()
Write three functions, drawPantegon(), cornerPantegon() and nestedPantegon(). Function drawPantegon takes three parameters: a turtle, an edge length, and number of edges. Functions cornerPantegon and nestedPantegon take two parameters: a turtle and an edge length. The pseudocode for drawPantegon() is:
#recursive function to draw a pantegon def drawPantegon(t, length, numEdges): if numEdges > 0: move the turtle object, t, forward length steps t turn left 72 degrees call drawPantegon with t, length, and numEdges-1pseudocode of cornerPantegon, which draws pantegon nested in left corner.
def cornerPantegon(t, length): if length >= 25: 1. call drawPantegon with t, length and 5 2. reduced length by half (use integer division in this function) 3. call cornerPantegon with t and length, that is, draw a pantegon with t and updated length
def nestedPantegon(t, length): if length >= 25: 1. call drawPantegon with t, length, and 5 2. Turtle t moves forward length/2 3. Turtle t turns left 36 degrees 4. call nestedPantegon with t, length * math.sin(54/180 * math.pi). To use sin function from math library, need to import math.The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the function names must match exactly (else, the scripts cannot find it). Make sure to use the function names from the github program (it is expecting cornerPantegon() and nestedPantegon()).
A sample run with edge length 200 on cornerPantegon would produce:
A sample run with edge length 50 on nestedPantegon would produce:
A sample run with edge length 200 on nestedPantegon would produce:
Mimic the parking ticket program from Lab 8 to do the following:
A sample run:
order of most popular neighborhoods in movies: 3 Midtown 39 Brooklyn 32 Lower Manhattan 25 Name: Neighborhood, dtype: int64 order of directors/filmmakers making most movies in NYC: 5 Spike Lee 11 Woody Allen 11 David Greene 8 Sidney Lumet 6 Martin Scorsese 6 Name: Director/Filmmaker Name, dtype: int64
Using the template program, averageImage.py, available on the CSci 127 repo on GitHub, fill in the missing functions:
The functions are part of a program that averages smaller and smaller regions of an image until the underlying scene is visible (inspired by the elegant koalas to the max).
For example, if you inputted our favorite image, you would see (left to right):
and finally:
The grading script does not run the whole program, but instead runs each of your functions separately ('unit tests') to determine correctness. As such, the names of the functions must match exactly the ones listed above (else, the scripts cannot find them).
IMPORTANT Do not remove anything below and including the comment that says:
###################################################################### ### DO NOT CHANGE ANYTHING BELOW AND INCLUDING THIS LINE ### ######################################################################
Hint: See notes from Lecture 8.
Write a program that uses folium to make a map centered in New York City (40.75, -74.125) and add a marker for Central Park (warning: case sensitive) at coordinates 40.7812, -73.9665. The HTML file your program creates should be called: nyc_Central_Park.html.
Hint: See Lab 9.
Using folium (see Lab 9), write a program that reads NYC hospitals, which is adapted from NYC Health + Hospitals patient care locations - 2011 from NYC OpenData by removing facilities without latitude and longitude information.
Input name of the output file, and creates a map with markers for all the hospitals from the input file.
A sample run:
Enter output file: nyc_hospitals.html
which would produce the html file:
Using folium, write a program that asks the user to read after_school.csv, which is downloaded from DYCD after-school programs from NYC OpenData. Get rid of records without lagitude and longitude information, change some typos and modify some column names -- for example, change BOROUGH/COMMUNITY to Borough/Community -- for consistence. So make sure to use the above after_school.csv file.
Choose 1 for "Borough/Community", enter the name of a borough/community, create a map with markers for all after school programs in that region.
Choose 2 for "Grade Level / Age Group", enter a grade level, create a map with markers for all the after school programs for that group.
The file name should be saved as lower cases of group_name, replacing every space with a underscore ('_') character and every forward slash ('/') with a underscore ('_').
Forward slash should be replaced, otherwise it will be mistakenas a separator between directories in Linux system.
Hint: You can use groupby and get_group to consider only the rows for the input borough/community or grade level / age group. You can also use mygroup.groups.keys() to list the keys of mygroup, which holds the return of groupby.
Note: You can use the value in the "Name" column to label each marker.
A sample run:
Enter 1 for Borough/Community, 2 for Grade Level / Age Group Your choice: 1 dict_keys(['Astoria', 'Bronx', 'Brooklyn', 'Corona', 'Flushing', 'Forest Hills', 'Jackson Heights', 'Jamaica', 'Kew Gardens', 'Long Island City', 'Manhattan', 'New York', 'Queens', 'Staten Island', 'Woodside']) Enter Borough/Community name: Jackson Heights
which would produce a html file named jackson_heights_after_school.html:
Another sample run of the program, when we chooose grade level MS/HS.
Enter 1 for Borough/Community, 2 for Grade Level / Age Group Your choice: 2 dict_keys(['11+', '13 to 21', '14 to 24', '14-Nov', '16 to 21', '16 to 24', '16+', '18+', '20-May', '6 and up', 'A parent 16 Years Old or Older', 'Adults', 'All Ages', 'ESOL/Civics', 'Elem/MS', 'Elem/MS/HS', 'Elementary', 'High School', 'MS/HS', 'Middle School', 'OST', 'Seniors', 'grades 6 to 8']) Enter Grade Level / Age Group name: MS/HS
which would produce a html file named ms_hs_after_school.html:
a green flower with nine petals
a blue flower with six petals
From the above figures, we can see each flower has petals, and each petal has color and heads in different directions. Drawing of petal can refer to lab 3.
Here is a blue petal tilting 0 degree from east direction, which is the default facing direction of a turtle.
Here is a blue petal tilting 60 degrees from east direction. The angle between the central line of this petal and the east direction is 60 degrees.
Here is a blue petal tilting 120 degrees from the east direction.
Here is a blue petal tilting 180 degrees from the east direction.
Here is a blue petal tilting 240 degrees from the east direction.
Here is a blue petal tilting 300 degree from the east direction.
It can be seen that a blue flower with 6 petals has petals tilted 0, 60, 120, 180, 240, and 300 degrees.
In this problem, define petal, flower, and main functions.
The program, errorCities.py, has lots of errors. Fix the errors and submit the modified program.
Hint: See Lab 9.
Integer -1 is not a perfect number since it is not positive.
Integer 8 is not a perfect number. It has factors 1, 2, 4, and 8, and the sum of factors of 8 other than itself is 1 + 2 + 4 = 7, which does not equal to 8.
Define function isPerfect for an given integer, test whether it is perfect or not. For example, isPerfect(6) returns True but isPerfect(8) returns False.
Define function main to ask a user to enter an integer until that integer is perfect. Here is a sample input and output.
Enter a perfect number: 8 8 is not a perfect number. Re-enter: -1 -1 is not a perfect number. Re-enter: 6 Congratulations! 6 is a perfect number.Hints: in function isPerfect, do the following:
def isPerfect(num): #if num is not positive, #that is, num is smaller than or equla to 0, return False. #The return statement leaves the current function, isPerfect, #and returns to its caller with value False. #Set total to be zero. This variable holds the sum of all #the factors of num other than itself. #Its value is initialized to be zero in the very beginning. #Now num is positive -- #otherwise, we would have returned False #in the above if-statement. We will check whether #num is perfect or not. #Factors of num other than itself #can be as small as 1 or as big as half of num. #Check each integer in [1, half of num] #to see whether it is actually a factor of num, #that is, whether num can be divided by that integer, #or equavalently, check remainder of num divided #by that integer is zero or not, #if yes, add that integer to total. #Once we finish the loop of checking every integer in #[1, half of num] and add founded factors to total, #check whether total equals sum or not. #If yes, return True, otherwise, return False. #You can use #return total (a-relational-comparison-operator) num #to substitute for an if-else statement, #where relational comparison operators can be #equal, not equal, larger than, larger than or equal, #less than, less than or equal.For function main, here is an outline.
def main(): With prompt "Enter a perfect integer: ", ask user to enter an integer to variable num. This is to initialize num. as long as num is not perfect: print num is not a perfect number and re-enter. enter another integer and put it in num, so num holds the new input. #Once we leave the above loop, num must be a perfect number, #otherwise, we would still be stuck inside the loop. #The condition to leave the loop is num is perfect. print "Congratulations!" and report num is a perfect number.
Challenge (optional): can you use isPerfect function to find all perfect numbers between 1 and 100000? For verification, those numbers are 6, 28, 496, and 8128.
Every time a computer makes a guess, you can only give responses from 1 to 3, where 1 means too small, 2 means too big and 3 is just right. Suppose the number in your mind is 25. When you run your code, you can pick any integer, as long as it is in [0, 100].
Optional: if there are 1000 elements, what is the maximum number of guesses to guess an integer? Hint: 210 = 1024 and 29 = 512.
Pick an integer in [0, 100] in your mind. Guess 1: is it 50? 1: too small 2: too big 3: just right Enter choice 1-3: -1 Enter choice 1-3: 6 Enter choice 1-3: -2 Enter choice 1-3: 2 Guess 2: is it 24? 1: too small 2: too big 3: just right Enter choice 1-3: 1 Guess 3: is it 37? 1: too small 2: too big 3: just right Enter choice 1-3: 2 Guess 4: is it 30? 1: too small 2: too big 3: just right Enter choice 1-3: 2 Guess 5: is it 27? 1: too small 2: too big 3: just right Enter choice 1-3: 2 Guess 6: is it 25? 1: too small 2: too big 3: just right Enter choice 1-3: 3 Congratulations! The answer is 25
Pick an integer in [0, 100] in your mind. Guess 1: is it 50? 1: too small 2: too big 3: just right Enter choice 1-3: 2 Guess 2: is it 24? 1: too small 2: too big 3: just right Enter choice 1-3: 1 Guess 3: is it 37? 1: too small 2: too big 3: just right Enter choice 1-3: 2 Guess 4: is it 30? 1: too small 2: too big 3: just right Enter choice 1-3: 2 Guess 5: is it 27? 1: too small 2: too big 3: just right Enter choice 1-3: 2 Guess 6: is it 25? 1: too small 2: too big 3: just right Enter choice 1-3: 1 Guess 7: the answer must be 26So the key idea is as follows.
initialize start and end make first guess as the mid of start and end get response (1-3 only), where 1 is too small, 2 is too big, and 3 is just right. Put user input as an int in variable feedback initialize numGuesses, variable to trace number of guesses, by 1 while feedback is not 3: #not get the answer yet if feedback is too small: what to update, start or end, and how to update else: #feedback is too large what to update, start or end, and how to update increase numGuesses by 1 update guess as the mid of start and end get a valid feedback 1-3, put to feedback variableA skeleton of the code is as follows.
##name: ##email: #TODO: import necessary library to generate random number #TODO: make sure that user only input choice 1-3. def validFeedback(): #TODO: print prompt "1. too small 2. too big 3. just right" #Ask user to input feedback as an integer in 1-3, #the input prompt MUST be "Enter choice 1-3: " #if you want to see choice chosen in gradescript. feedback = int(input("Enter choice 1-3: ")) while feedback is not 1, 2, or 3: #TODO: prompt user to enter an int in 1-3, #input prompt MUST be "Enter choice 1-3: " #if you want to see choice chosen in gradescript. #TODO: do not forget to return feedback after #we get feedback 1, 2, or 3. def guessGame(): #TODO: set start to be 0 and end to be 100 print("Pick an integer in [" + str(start) + ", " + str(end) + "] in your mind.") #TODO: set guess to be mid of start and end #TODO: set variable numGuesses to be 1 print("Guess " + str(numGuesses) + ": is it " + str(guess) + "?") #TODO: call validFeedback function, put its return to feedback #user does not choose "3. just right" yet while feedback is not 3: if feedback is 1: #too small #TODO: what to update, start or end, and how? else: #feedback cannot be 3, otherwise, #it would not go inside the loop. #By the condition of if-statement, #feedback is not 1, or it would go to #if-statement. Furthermore, due to setting #of variable feedback, it can only take #value 1, 2, or 3, #now it is neither 1 nor 3, #the value of feedback must be 2. #TODO: what to update, start or end, and how? #TODO: put the mid point of start and end to guess #TODO: increase numGuesses by 1 if there is only one element in the [start, end], what does that mean for relationship between start and end? print("Guess " + str(numGuesses) + ": the answer must be", guess) #TODO: leave the current function #by calling return statement, #since we find the answer #and finish guess game now. print("Guess " + str(numGuesses) + ": is it " + str(guess) + "?") #TODO: call validFeedback function, #put its return to feedback #TODO: now we are outside the loop, the number is guessed #print out Congratulations and what the value of guess is. def main(): #TODO: call guessGame function if __name__ == '__main__': main()
Enter only 1-6: -1 Input needs to be in 1-6. Re-enter: Enter only 1-6: 9 Input needs to be in 1-6. Re-enter: Enter only 1-6: 2 user: 2 computer: 5 user winsHere is another sample run.
Enter only 1-6: 3 user: 3 computer: 6 computer wins
To pass gradescope scripts, your output must be in the following format.
Under prompt "user: ", print the integer -- must be in [1, 6] -- entered by a user.
Under prompt "computer: ", print the random integer in [1, 6] generated by the computer. This output is put after "user: your_input_integer".
The result should be one of "draw", "user wins", or "computer wins".
cs127 --- assignments |___ quizzes ___ quiz1 |___ quiz2
Write a simplified machine language program that prints: I use MIPS!
See Lab 11 for details on submitting the simplified machine language programs.
Hint: You may find the following table useful:
(Image from wikimedia commons)
Hint: The grading scripts are matching the phrase exactly, so, you need to include the spacing and punctuation.
Write a simplified machine language program that has register $s0 increase from 0 to 100, increase by 10 each time.
Your program must use the ADDI instructions and store all numbers in registers for computation.
See Lab 11 for details on submitting the simplified machine language programs.
You've now mastered UNIX Scripts.
You will organize some files in a cloned GitHub repository.
Clone the repository https://github.com/HunterCSci127/CSci127 with the git command. (Refer to Lab 8 to refresh on cloning a repository)
Navigate to this repository and make a new directory called projects
Move averageImage.py into projects
Go back to the repository directory, and make another directory called pictures
Move any .png file found in the cloned repo into the pictures directory you just made.
Find out the number of files ended by .py in CSci127 directory.
Hint: See Lab 11.
Write a C++ program that prints "Hello, World!" and "C++ is fun!" in two separate lines to the screen.
Hint: See Lab 12 for getting started with C++.
Write a C++ program that will print "10" 6 times in one row, for 10 rows.
The output of your program should be:
101010101010 101010101010 101010101010 101010101010 101010101010 101010101010 101010101010 101010101010 101010101010 101010101010
Hint: See Lab 12 for getting started with C++.
Extra hint: You can accomplish this very quickly with a nested for loop. Write a for loop for each row, and inside of that for loop write another for loop to iterate through each column.
Write a C++ program that converts Celsius to Farenheit. Your program should prompt the user for the temperature (may contain decimal part) in Celsius and then print out the corresponding degree in Farenheit.
A useful formula: farenheit = 9.0 / 5 * celsius + 32. Note that in C++, expression 9 / 5 is integer division and returns 1, and 9.0 / 5 returns 1.8.
See Lab 4 for designing Input-Process-Output programs and Lab 12 for getting started with C++.
Write a C++ program program that asks the user for two integers, the first variable reprsents the start of an range and the second variable represents the end. The program prints all even integers in [start, end], where both ends are inclued in the range.
A sample run:
Enter start: 6 Enter end: 11 6 8 10
Write a C++ program that asks the user for the current number of credit hours and prints
A sample run:
Enter number of credit hours taken: 12 freshman
Another sample run:
Enter number of credit hours taken: 96 senior
Write a C++ program program that asks the user for a number and a character other than space, draw a triangle of that height and width using 'character graphics'.
A sample run:
Enter an int: 3 Enter a symbol other than space: * * ** ***
Another sample run:
Enter an int: 6 Enter a symbol other than space: $ $ $$ $$$ $$$$ $$$$$ $$$$$$
Write a C++ program that asks the user for their annual budget for a task (for example, foods, movie) and estimated monthly expense. Suppose due to inflation, monthly expense in July to December is 15% than that in January to June.
Print out month, monthly expense, and remaining balance in the budget in the end of a month. The remaining balance can be negative, meaning a user under-estimates the expenses. If the remaining balance after a year is negative, print "need higher budget".
A sample run:
Input your annual budget: 1000 Input your month expense: 60 month expense remaining balance of budget 1 155.00 1845.00 2 155.00 1690.00 3 155.00 1535.00 4 155.00 1380.00 5 155.00 1225.00 6 155.00 1070.00 7 178.25 891.75 8 178.25 713.50 9 178.25 535.25 10 178.25 357.00 11 178.25 178.75 12 178.25 0.50
Another sample run
Input your annual budget: 1000 Input your month expense: 90 month expense remaining balance of budget 1 90.00 910.00 2 90.00 820.00 3 90.00 730.00 4 90.00 640.00 5 90.00 550.00 6 90.00 460.00 7 103.50 356.50 8 103.50 253.00 9 103.50 149.50 10 103.50 46.00 11 103.50 -57.50 12 103.50 -161.00 need higher budget
To right aligned numbers in each column, suppose variables representing month is i, for monthly expense, use monExpense, for remaining balance of budget, use budget. Suppose column headers are "month", "expense", and "remaining balance of budget", respectively.
Use the following print out statement in C++.
printf("%5d\t%7.2f\t%27.2f\n", i, monExpense, budget);
Explanation: %5d in double quotes of printf statement is a place holder for variable i, meaning to display the value of i in a 5-letter column, right aligned. Letter d in %5d means the value to be inserted is an integer and 5 in %5d is width of that column, represented by the maximum number of letters held in that column.
Similarly, %7.2f is place holder for monExpense, where f means floating point number, or number with decimal numbers, and .2f means to display two decimal numbers of monExpense by rounding it to two decimal numbers to the decimal point. If there are not enough decimal numbders, add zero. For example, suppose monExpense is 12.3, then it will be displayed as 12.30. 7 in %7.2f is the number of letters in column header expense.
You can check %27.2f yourself. Hint: how many letters in column header "remaining balance of budget"?
Character \t is tab key, and \n is new line character. They are special characters in ASCII table.
Note that monthly expense and remaining balance must display with two decimal numbers, or gradescope scripts might not accept your submission.
Write a C++ program that asks the user for a whole number between -128 and 127 and prints out the number in "two's complement" notation.
With 3-bit memory, we can represent 8 integers. Reason: each bit has either 0 or 1, and each bit is independent, so there are 2 * 2 * 2 = 23 = 8 integers.
If we represent unsigned integers with 3-bit, the integers are in [0, 7]. Here are some details.
unsigned decimal number | binary representation |
---|---|
0 | 000 |
1 | 001 |
2 | 010 = 1 * 21 |
3 | 011 = 1 * 21 + 1 * 20, where 20 returns 1. |
4 | 100 = 1 * 22 |
5 | 101 = 1 * 22 + 1 * 20 |
6 | 110 = 1 * 22 + 1 * 21 |
7 | 111 = 1 * 22 + 1 * 21 + 1 * 20 |
Two's-complement is a notation to represent signed integers -- integers range from negative, zero, and positive.
To represent signed integers, in the world of binary, we cannot have negative sign, so we will use the leftmost bit as sign bit, where negative is represented by 1 and non-negative is 0.The other bits are used to represent data, while in unsigned integers, every bit is used for data since there is no need to have a sign bit.
With 3-bit, we can also represent 8 signed integers, which are in [-4, 3].
signed decimal number | binary representation |
---|---|
-4 | 100 = -1 * 22 |
-3 | 101 = -1 * 22 + 1 * 20 |
-2 | 110 = -1 * 22 + 1 * 21 |
-1 | 111 = -1 * 22 + 1 * 21 + 1 * 20 |
0 | 000 |
1 | 001 |
2 | 010 = 1 * 21 |
3 | 011 = 1 * 21 + 1 * 20, where 20 returns 1. |
In short, with 3-bit, we can represent 23 = 8 integers. Three-bit can represent unsigned integers in [0, 23-1], that is, [0, 7]. Three-bit can also represent signed integers in [-22, 22-1], that is, [-4, 3]. In signed integers, there are 4 negative integers, one zero, and 3 positive integers. There is one fewer positive integers in the range, this is because zero and positive integers share sign bit 0.
Similarly, with 8-bit, we can represent 28 = 256 integers. Eight-bit can represent unsigned integers in [0, 28-1], that is, [0, 255]. As in the case of signed integer representation, with the leftmost bit used as a sign bit, we have only 7 bits to represent data, so signed integers represented by 8-bit are in range [-27, 27-1], that is, [-128, 127].
In C++, an integer is represented by 4-byte, where a byte is 8-bit. So in C++, we can represent unsigned integers in [0, 232-1]. Or for signed integers in [-231, 231-1]. Type int in C++ represents signed integers. Here is an algorithm to find out Two's complement for an integer in [-128, 127]. We use a string with 8 character to store the result.
for (int i = 0; i < size - len; i++) result = "0" + result;
Warning: cannot replace i < size - len by i < size - result.length() in the above statemen. Reason: after result = "0" + result, the length of result is changed. The following is an example.
Suppose in the beginning, string result has 6 characters, then we are supposed to pad 8 - 6 = 2 zeros to its left.
In the beginning, variable i is 0, size is 8, and result.length() is 6, since i < size - result.length(), we enter the loop and pad one zero to the left of string result. Then i is increased by 1 by i++ statement.
Check condition i < size - result.length() to see whether we need to enter the loop. After we pad the first zero, the length of result is changedfrom 6 to 7, thus size - result.length() returns 1. Now i is 1, so i < size - result.length() does not hold. Exit the loop.
So we only pad one zero, and the length of result is 7, not 8 as we expect.
if (n < 0) //TODO: write code to invert(or flip) each bit of string result. //That is, if the current bit is '0', change it to '1', //otherwise, change the current bit to '0'. //Note that string result has 8 characters now.
A sample run:
Enter an int in [-128, 127]: 8 binary string: 00001000
Another run:
Enter an int in [-128, 127]: -1 binary string: 11111111
Yet another run:
Enter an int in [-128, 127]: -128 binary string: 10000000
Yet another run:
Enter an int in [-128, 127]: -74 binary string: 10110110
Optional: for non-negative integers, its two's complement is the same as its binary representation. In the next, we will illustrate the key idea of calculating two's complement for negative number.
In general, these are steps we calculate Two's complement of a negative integers. Suppose the number is saved in variable num.
We will illustrate the steps using an example. For simplicity, suppose we work with 4-bit, which can represent integers in [-8, 7]. To find out the two's complement of -5, saved in variable num, we do the following.
Let x be two's complement of num. Note that the sum of binary representation of -num and the result in Step 3 -- say y -- is binary number 1111, written as 11112 since base of binary number is 2. That is, binary representation of -num + y = 11112.
By Step 4, we learn that x = y + 1. Thus, binary representation of -num + x = binary representation of -num + y + 1 = 11112 + 1 = 100002. Said differently, x, two's complement of num, is calculated by 100002 - binary representation of -num when we work with 4-bit integers.
It is a little complicate to implement minus operation for binary number, or add 1 to a binary number. so we calculate two's complement of negative integer num as follows.
Two's complement of num = 100002 - binary representation of -num = 100002 -1 - binary representation of -num -1. Note that 100002 -1 is 11112, and 1111 - binary representation of (-num-1) is equivalent to invert the binary representation of (-num-1). So our algorithm is implemented as follows.