#Name: Thomas Hunter #Email: thomas.hunter1870@myhunter.cuny.edu #Date: January 31, 2023 #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 pentadecagon (polygon with fifteen 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 (choose 50 steps for each side so the figure is not too big) :
Repeat 6 times:
Walk forward 50 steps
Turn right 60 degrees
Walk forward 50 steps
Turn left you_it_figure_out degrees
The result should look as follows:
Write a program that draws shape I. The initial part of the code is provided. The colors are green, blue, cyan, and red, respectively.
import turtle
t = turtle.Turtle()
t.pensize(5)
#TODO: finish the rest code
#Start from the left end of bottom line (green line).
#hint: you may use color method of turtle.
#The distance for a long line is 150.
#The distance for a short line is 50.
The result should look as follows:
Write a program that will print "Python is fun." 50 times.
The output of your program should be:
Python is fun. Python is fun. ... Python is fun.
Write a program that prints out the numbers from 20 to 0, decrease by 2 each time. After counting down to zero, print "Done!".
The output of your program should be:
20 18 16 14 12 10 8 6 4 2 0 Done!
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 three-word phrase separated by comma (,). Create a new phrase, where those three words are separated by spaces and in reversed order. That is, the first word in the input phrase is the last word in the new phrase while the third word in the input phrase is the first word in the new phrase. Print new phrase in upper case letters and lower case letters.
A sample run of your program should look like:
Enter three words separated by comma (,): One,Two,Three new string: Three Two One lower case: three two one upper case: THREE TWO ONE
Another run:
Enter three words separated by comma (,): Big,Medium,Small new string: Small Medium Big lower case: small medium big upper case: SMALL MEDIUM BIG
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. You also need to find those three words from the resulting list after applying split method on the input string. Then concatenate those words to get a new phrase.
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 character second to the left of the corresponding character of the string in ASCII table.
A sample run of your program should look like:
Enter a phrase: Hello letter ASCII two_letter_before H 72 F e 101 c l 108 j l 108 j o 111 m
And another sample run:
Enter a phrase: BDE letter ASCII two_letter_before B 66 @ D 68 B E 69 C
Hint: If c is a character, ord(c) returns its ASCII code. For example, if c is 'H', then ord(c) returns 72. See Lab 2.
To right aligned the print out, use print("%6c %5i %17c"%(character, ASCII_code_of_character, two_letter_before_current_character)). You need to find out expression to represent current character, ASCII_code_of_current_character, and two_character_before_current_character.
Explanation: Use 6c since column header "letter" has 6 letters, c means character, for example, letter 'H' in string "Hello". Use 5i since column header "ASCII" has 5 letters, i means int, which is the ASCII code of the current letter. Use 17c since column header "two_letter_before" has 17 letters, c means a letter, which is the character two characters ahead of the current letter.
Note that some characters in ASCII code are not printable. For example, character with ASCII code 27 means ESC key in keyboard, which is not printable. Similarly, ASCII code 30 is record separator, which is not printable. Space character, which has ASCII code 32, is not printable.
When you test your print, do not include space, exclamation symbol ! (ASCII code 33), or double quotes symbol " (ASCII code 34), since the characters two positions before them are non-printable, you cannot check results visually.
Warning: do not forget to print column names "letter ASCII two_letter_before".
(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 upper case letters: 'A',...,'Z'.
A sample run of your program should look like:
Enter an all-big-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-big-letter string: OWQFKA Enter a non-negative int to shift: 6 ciphered string: UCWLQG
Hint: See the example programs from Lecture 2.
This example is an illustration of modular operation and conversion between ASCII code and letter.
We introduce modular operator % using clock. For easy of calculation, we represent 12 as 0. Suppose current time is 7 o'clock, what time is after 6 hours?
Remember a clock has 12 scales, from 0 to 11. Then (7 + 6) % 12 = 13 % 12, meaning 13 divided by 12, the remainder is 1. That is, 6 hours after 7 o'clock is 1 o'clock. This is similar to move the hour hand forward (right) 6 hours.
Imagine we have a clock of letters. Then there are 26 scales, from 'A' to 'Z'.
If only we can have the following clock ...
How to match 'A' to 0, match 'B' to 1, ..., match 'Z' to 25? Hint: suppose the letter is 'A', what is the value of ord('A') - ord('A')? Suppose the letter is 'B', what is the value of ord('B') - ord('A')? Suppose the letter is 'Z', what is the value of ord('Z') - ord('A')?
Then shift right operation is like modular operation. For example, when we shift right 6 from letter 'Z', it like to (25 + 6) % 26 = 5.
It remains to match number in [0, 25] to letter ['A', 'Z']. Hint: you can use chr function.
Write a program that implements the pseudocode below:
For i = 10, 20, ... ,300: Walk forward i steps Turn left 121 degreesYour output should look similar to:
Hint: See examples of range(start,stop,step) in Lecture 2 notes.
Modify the program from Lab 3 to show the following image.
t = turtle.Turtle() t.penup() t.backward(100) t.left(90) t.forward(100) #now t is in (-100, 100), why? t.right(??) #you fill in a degree in ?? t.pendown() #TODO: draw green shade #TODO: move to the start direction of up shade #TODO: draw cyan shade
Warning: for the purpose of grading script, green shade is drawn before cyan shade. They cannot be drawn at the same time.
Hints: you may use one of the following approaches.
Modify the program from Lab 3 to show the shades of green 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. You can move the turtle to (0, 300) before you start to draw so that the figure fits in the screen.
A sample run of your program should look like:
Modify the program from Lab 3 to draw a cornflowerblue turtle (color #6495ED or #6495ed or RGB code 100,149,237), stamp after each turn. The turtle moves forward by 100 in each round.
A sample run of your program should look like:
Hint: See Section 4.3 for setting the background color and Lab 3 for colors.
There can be four ways to set color of turtle.
You can find more colors of Python in python color constants.
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 has only red and blue channel of the original image.
A sample run of your program should look like:
Enter name of the input file: csBridge.png Enter name of the output file: csBridge_purple.png
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, reverse the message, then prints the reversed message out, two copies of each character per line.
A sample run of your program should look like:
Enter a message: I love Python! ! ! n n o o h h t t y y P P e e v v o o l l I I
Hint: See Lab 2 or Lecture 2 notes.
Enter a list of names separated by semicolon. Display each name in a line, started by the first name, followed by a space, and the first letter of 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 George W. James A. Thomas J. James M. James M.
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_6.png
Hint: Here's a way to approach the problem:
Create a program that creates a image of horizontal purple and yellow 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 purple and yellow horizontal 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.
Write a program to convert between gallon and liter. Round the result to 2 decimal numbers.
You may need to use the following information.
1 gallon = 3.79 liters
1 liter = 1 / 3.79 gallon = 0.26 gallon
To round a decimal number
a sample run of program:
(a) convert gallon to liter (b) convert liter to gallon Enter a or b: a Enter number of gallons: 2 2.0 gallons = 7.58 liters
another sample run of program:
(a) convert gallon to liter (b) convert liter to gallon Enter a or b: b Enter number of liters: 2.5 2.5 liters = 0.65 gallons
yet another sample run of program:
(a) convert gallon to liter (b) convert liter to gallon Enter a or b: c Wrong choice, please enter only a or b
Hint: See Section 2.7.
Modify the program in the section Elevation Data & Flood Maps in Lab 4 to color the region as follows.
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 floating point number in [0, 1].
For example, if your file was of the snow pack in the Sierra Nevada mountains in California in September 2014:
then a sample run would be:
Enter file name: caDrought2014.png Enter threshold: 0.1 number of pixels whose rgb are small than threshold in original figure: 863323 percent of those pixels: 51.39 %
The generated complement image is as follows.
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.
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 | 0 |
0 | 0 | 1 | 1 |
0 | 1 | 0 | 1 |
0 | 1 | 1 | 1 |
1 | 0 | 0 | 0 |
1 | 0 | 1 | 1 |
1 | 1 | 0 | 0 |
1 | 1 | 1 | 0 |
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 starting 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 start with '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 starting 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: abc apple banana cat dog elephant number of words: 6 number of words starting with a or b: 3 fraction of words starting with a or b: 0.5Round num by two decimal numbers after the decimal point using
round(num, 2)
Hint
input a string, put in variable string set num to be 0 set base to be the base of hexadecimal number initialize weight to be 1, for the least significant digit set length to be the number of letters of string Get the upper case of string, put in string. All letter are big letter in string. Move i from the rightmost index downto the leftmost index, ie, move from least significant digit to the most significant digit put ith letter of string to variable ch if ch is '0'..'9' increase num by weight * (ord(ch) - ord('0')). For example, if ch is '9', then ord(ch) - ord('0') returns the difference between ASCII code of '9' and ASCII code of '0', that is, 9. Related example, remember in Problem 9, when we match letter 'A' to 0, letter 'B' to 1, ..., by subtract ord('A') from the corresponding ASCII code of current letter? otherwise, if ch is 'A'..'F': value = ord(ch) - ord('A') + 10. For example, if ch is 'C', then ord(ch) - ord('A') + 10 = 12. Note that 'C' is 12 in hexadecimal system. increase number by value * weight othewise: print current Letter ch is not allowed in a hexadecimal string call exit method to exit current program update weight by multiplying it with base since we move to the next significant digit print out num followed by prompt "num ="
some sample input/output are as follows.
Enter a string with 0-9, a-f only: 25 num = 37
When an input string has more than one letter that other than '0'-'9', 'A'-'F', only report the first violation that is closest to the least significant digit in the rightmost position.
Enter a string with 0-9, a-f only: AT0 Letter T is not allowed in hexadecimal string.
Hint: See Lecture 4 notes.
Warning: Python provides int(string, base) to convert a string representation in base to its decimal number. For example, int("1A", 16) returns 26 and int("101", 2) returns 5. You cannot use this function. Must implement the pseudocode.
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 | 1 | 1 | 1 |
1 | 0 | 1 | 0 | 0 | 0 | 0 |
2 | 1 | 0 | 1 | 0 | 0 | 1 |
3 | 1 | 1 | 2 | 0 | 1 | 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: March 2023 #Logical expressions for a 3-bit decrementer out1 = ... out2 = ... out3 = ...Where "..." is replaced by your logical expression (see Lab 5).
Note: here's a quick review of binary numbers.
Download csv file from 2013 to 2018 Demographic Snapshot Borough. Your program should ask the user for the borough, an name for the output file, and then display the fraction of Grade K to 6 enrollment that has lived in that borough, over time. Then print out the minimum, maximum, median, mean, and stand deviation of total enrollment in that borough (round to 3 decimal numbers).
A sample run of the program:
Enter borough name: Bronx Enter output file name: bronxFraction.png minimum of total enrollment for Bronx is 233588 maximum of total enrollment for Bronx is 241986 median of total enrollment for Bronx is 239955.0 mean of total enrollment for Bronx is 239283.0 stand deviation of total enrollment for Bronx is 3407.191
The file bronxFraction.png:
Hint:, first create a column that calculate the fraction of Grade K to 6 vs. Total Enrollment. Then get borough data usig either groupby and get_group function or query method. You can test both approaches. Suppose the original data frame is saved in variable df and the input borough name is put in variable borough.
borough_data = df.query("Borough == '" + borough + "'")
Then borough_data has data for the specific borough. Plot fraction using this data.
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.
Your program should assume that expenses file, expenses.csv is in the same directory as your program.
Content of expenses.csv is as follows.
Date,Store,Amount,Category 10/07/22,MacDonald,24.65,food 10/07/22,MTA,16.85,transportation 10/07/22,Bestbuy,46.39,electronics 10/22/22,Walgreen,15.41,medicine 11/10/22,AT&T,30.87,Internet 11/10/22,Target,30.08,groceries 11/10/22,Target Pharmacy,39.46,medicine 11/21/22,Walmart,15.66,groceries 11/21/22,Bestbuy,68.18,electronics 12/05/22,Bestbuy,42.82,electronics 12/17/22,Walmart,32.55,groceries 12/23/22,Bestbuy,7.31,electronics 12/23/22,Walgreen,8.09,medicine 12/30/22,MTA,44.3,transportation 12/30/22,Bestbuy,30.97,electronics
Write a program do the following. Enter a choice for console.
Before choosing a category, you may want to print out all possible categories. To do so, print grouped_data.groups.keys(), where variable grouped_data holds the return of groupby method of data frame object read from csv file, and groupby method applies to category.
For example, if grouped_data is the return of groupby of Category (check column name, need to match case to case), then grouped_data.groups.keys() are all available categories.
One step in this task is to create a column yyyy-mm from mm/dd/yyyy. The following code creates a column called 'Year Month' to store year and month information extracted from column 'Date'. Refer to link for more details.
df['Year Month'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m')
With the above code, record 12/31/22 in Date column is converted to 2022-12, put in column 'Year Month'.
If we apply groupby on 'Year Month' and put return to grouped_data, then grouped_data.groups.keys() are all available pairs of 'Year Month'.
A sample run of your program:
a. group by category b. group by year-month c. most visited stores Enter a choice: a Category Internet 30.87 electronics 195.67 food 24.65 groceries 78.29 medicine 62.96 transportation 61.15 Name: Amount, dtype: float64 available category: dict_keys(['Internet', 'electronics', 'food', 'groceries', 'medicine', 'transportation']) Choose a category and calculate its minimum, maximum, average, and total: groceries min: 15.66 max: 32.55 mean: 26.1 sum: 78.29
and another run:
a. group by category b. group by year-month c. most visited stores Enter a choice: b Year Month 2022-10 103.30 2022-11 184.25 2022-12 166.04 Name: Amount, dtype: float64 available year-month: dict_keys(['2022-10', '2022-11', '2022-12']) Enter a year-month and calculate minimum, maximum, average, and total in that month: 2022-12 min: 7.31 max: 44.3 mean: 27.67 sum: 166.04
When user chooses c, enter an integer to represent first n most visited stores, and print out those stores.
a. group by category b. group by year-month c. most visited stores Enter a choice: c Choose the first n most-visited stores: 3 The first 3 most visited stores are Bestbuy 5 MTA 2 Walgreen 2 Name: Store, dtype: int64
If a user enters anything other than 'a', 'b', 'c', output "wrong choice".
a. group by category b. group by year-month c. most visited stores Enter a choice: d wrong choice
Hint: to pass gradescope scripts, round average and total by 2 decimal numbers to the decimal point. You may use round(value, 2) to round variable value two decimal numbers to the decimal point.
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.
Ubuntu Terminal Reference Sheet
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: March 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.
Read Lab 7. Download workforce.csv from NYC open data which shows workforce data for NYCHA residents in NYC boroughs from 2017 to 2021. We modified the data from text to number and remove rows with data "< 5".
A sample run of the program:
Enter a year from 2017 to 2021: 2020 maximum acceptance rate in 2020 is 10.55 % from Brooklyn Enter output file name: output_2020.png
which produces an output:
Enter a year from 2017 to 2021: 2021 maximum acceptance rate in 2021 is 13.65 % from Staten Island Enter output file name: output_2021.png
which produces an output:
Note: The grading script is expecting that the label (i.e. name of your new column) is "Acceptance rate".
Hints: since the calculated acceptance rate is based on a borough in a specific year, we first create a column called "Acceptance rate", calculated by dividing column "Were placed into full-time or part-time jobs" by column "Applied for the program" multiplied by 100.
Unlike shelter program in Lab 7, where data are for each day in census, workforce data are based on a year and a borough. We need to run steps to extract data of different boroughs of a given year using either groupby and get_group or loc method (google its usage). Here is a pseudocode.
#TODO: fill in right hand side expression. #Use pandas to read "workforce.csv". df = ... #TODO: fill in right hand side expression. #Create a column called "Acceptance rate" by #dividing column "Were placed into full-time or part-time jobs" #by column "Applied for the program", then #multiplied by 100. df['Acceptance rate'] = ... #TODO: enter a year from 2017 to 2021. year = ... #chosenYear extracts all records in the original dataframe df #for the given year. Each record of chosenYear #represents for a borough in a GIVEN year. chosenYear = df.groupby(...).get_group(...) #To find out which borough has the highest acceptance rate #in that GIVEN year, need to apply idxmax method on #the column 'Acceptance rate' of chosenYear. #Note that if you use df['Acceptance rate'].idxMax(), #the returned value is the highest acceptance rate #among all boroughs in all the years, not just that GIVEN year. maxIdx = chosenYear['Acceptance rate'].idxmax() #TODO: find the maximum acceptance rate among all records #(ie, in this example, a record is for a borough), #in a GIVEN year by #chosenYear['Acceptance rate'][maxIdx] #Print out this value rounded by two decimal numbers #using round function as round(value_to_be_rounded, 2). #TODO: find the borough with highest acceptance rate #in a GIVEN year by #chosenYear["Borough"][maxIdx]. #Print this value out. #TODO: prompt to enter output file name. #TODO: plot acceptance rate by different boroughs #in that GIVEN year. #TODO: save the plot in the given output file.
Refer to the program from Lab 7. Read workforce.csv downloaded from NYC Open Data with slight modifications. Your program will do the following,
grouped_data.get_group(chosen_borough).plot.bar(...) #the first parameter of bar method is the column name representing year, #the second parameter is the number of applicants for the program plt.gcf().subplots_adjust(bottom=0.25) #so that the year label is displayed in full plt.xlabel(...) #The parameter in xlabel should be "Year". plt.ylabel("Applicants for the program")
A sample run of the program:
Borough Bronx 3216.4 Brooklyn 4398.6 Manhattan 3213.8 Queens 1378.6 Staten Island 751.2 Unknown 395.5 Name: Applied for the program, dtype: float64 possible boroughs are: dict_keys(['Bronx', 'Brooklyn', 'Manhattan', 'Queens', 'Staten Island', 'Unknown']) choose a borough: Bronx max number of applicants: 3675 min number of applicants: 2566 number of years record in the borough: 5 Enter output file: bronx_applicants.png
which produces an output:
Another sample run of the code is as follows. There is a value for borough as "Unknown" when borough information is not available.
Borough Bronx 3216.4 Brooklyn 4398.6 Manhattan 3213.8 Queens 1378.6 Staten Island 751.2 Unknown 395.5 Name: Applied for the program, dtype: float64 possible boroughs are: dict_keys(['Bronx', 'Brooklyn', 'Manhattan', 'Queens', 'Staten Island', 'Unknown']) choose a borough: Unknown max number of applicants: 634 min number of applicants: 157 number of years record in the borough: 2 Enter output file: unknown_applicants.png
which produces an output:
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 top left corner Enter 2 to get middle portion Your choice: 1 Enter input file name: magic_logo.png Enter output file name: magic_logo_top_left.png
which would have as input and output:
Another sample run of your program should look like:
Enter 1 to get top left 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 top left 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, using function main() that input an email address in the format of firstName.lastNamedd@myhunter.cuny.edu or firstName.lastNameddd@myhunter.cuny.edu, where dd are 2 digits and ddd are 3 digits. Extract and print out first name and last name. See Lab 7.
A sample input/output is as follows.
Enter an email: john.tyler20@myhunter.cuny.edu first name: john last name: tyler
Write a program, using function main() that input a website url like www.apple.com or hunter.edu. Find out the website name and its top level domain type. If top level domain is com, print "commercial", otherwise, if top level domain is edu, print "education", otherwise, if top level domain is org, print "organization", otherwise, if top level domain is gov, print "government", otherwise, print "other". See Lab 7.
A sample input/output is as follows.
input a website: chat.openai.com website name: openai commercial
Another sample input/output is as follows.
input a website: hunter.edu website name: hunter education
Yet another sample input/output uses air force website as an example.
input a website: www.af.mil website name: af other
Hint: You may need to consider a website can be in either www.websiteName.com or websiteName.com, so use negative index to extract website or domain after split by '.'.
Write a function, rentPrice(), that takes two parameters: borough (string) and room type (string). The function should return an integer for the average rent of a given room type in a given borough. The following data are from average rent for boroughs in NYC. For simplicity, we only concentrate on studio, 1-bedroom and 2-bedroom. Also, I modified the rent of studio in Brooklyn in the original website since it is higher than that of 1-bedroom.
Borough | studio | 1-bedroom | 2-bedroom |
---|---|---|---|
Manhattan | 2795 | 3500 | 3900 |
Brooklyn | 2273 | 2450 | 2750 |
Queens | 1695 | 1900 | 2350 |
Bronx | 1500 | 1700 | 2200 |
Staten Island | 1200 | 1425 | 2000 |
A sample run:
rentPrice("Brooklyn", "1-bedroom") returns 2450
And another:
rentPrice("Queens", "5-bedroom") returns 0
Hint: See Lab 8.
Write function, hexagramRecursion(), in recursive function for the hexagram in Problem 2. Key idea: break the hexagram evenly into six parts. If the number of repetition is larger than zero, draw one part. Call hexagramRecursion to draw the hexagram with remaining parts.
Here is a pseudocode.
def hexagramRecursion(t, n): if n > 0: #draw one part move t forward 100 steps turn t right 60 degrees move t forward 100 steps turn t left 120 degrees call hexagramRecursion with t and n-1. def main(): #call hexagramRecursion function to draw a hexagram if __name__ == '__main__': main()
Warning: You must use recursion to implement the code.
Write three functions, hexagon_recursion, corner_hexagon and nested_hexagon. Function hexagon_recursion takes three parameters: a turtle, edge length, and number of edges. Function corner_hexagon takes two parameters: a turtle and edge length of outermost hexagon. Function nested_hexagon takes three parameters: a turtle, edge length of outermost hexagon, and number of edges.
The pseudocode for hexagon_recursion is as follows:
#recursive function to draw a hexagon, #where n represents number of edges def hexagon_recursion(t, length, n): if n > 0: move the turtle object, t, forward length steps t turn left 60 degrees, where 60 is calculated by 360/6 call hexagon_recursion with t, length, and n-1
pseudocode of corner_hexagon, which draws hexagon nested in bottom left corner.
def corner_hexagon(t, length): if length >= 9: 1. call hexagon_recursion with t, length and 6 2. call corner_hexagon with t and one third of length (use integer division)
pseudocode of nested_hexagon, which draws hexagon nested in each corner.
def nested_hexagon(t, length, n): if length >= 27: if n > 0: 1. move t forward length steps 2. turn t left 60 degrees 3. call nested_hexagon with t, one third of length (use integer division), and 6. 4. call nested_hexagon with t, length, and n-1.Here is how to call the above functions in main function. You can uncomment (remove # before the corresponding line)
def main(): t = turtle.Turtle() #the following three statements are optional, #but with them, the whole figure is shown. #t.penup() #t.goto(-150, -150) #t.pendown() nested_hexagon(t, 243, 6) #length 243 = 3^4 is perfect power of 3, #We would like length divided by 3 each time. #hexagon_recursion(t, 243, 6) #uncomment to test #corner_hexagon(t, 243) #uncomment to test turtle.done() if __name__ == '__main__': main()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).
A sample run with corner_hexagon with length 243 and 6 would produce:
A sample run with edge length 243 and stop with 27 (included) on nested_hexagon would produce
Change if length >= 27 to if length >= 9 in function nested_hexagon would produce:
Change if length >= 27 to if length >= 81 in function nested_hexagon would produce:
Related: this program is similar to fractalTriangle and nestedTriangle in Lecture 8 note.
We rewrite all repetition statements (like for-statement) in fractalTriangle and nestedTriangle by recursion. It is proved that all recursive statements can be rewritten as repetition ones, and vice versa. A proof is beyond the scope of this course and is omitted.
Since we draw hexagons in our program, the length of smaller hexagon is one third of that of the next bigger one. If we use a half of the original figure, the hexagons will overlap -- you can verify this by modify the value of length when you call recursive function.
Write function polygon, which takes four parameters: a turtle, number of edges, edge length, and color as a string. The functionality of polygon uses turtle object to draw a polygon with number of edges, each edge has edge length, the polygon is in color, where color can be specified in name like "red" or using a hexadecimal representation such as "#00ffff" (green + blue = cyan).
The code of function main to test polygon is as follows:
def main(): t = turtle.Turtle() polygon(t, 5, 100, "green") polygon(t, 6, 60, "#ff00ff") polygon(t, 7, 70, "#ff0000") turtle.done() if __name__ == '__main__': main()The above main function produces the following figure.
Mimic the parking ticket program from Lab 8 to do the following:
A sample run:
order of most common violation: 3 Non-food contact surface improperly constructed. Unacceptable material used. Non-food contact surface or equipment improperly maintained and/or not properly sealed, raised, spaced or movable to allow accessibility for cleaning on all sides, above and underneath the unit. 20642 Facility not vermin proof. Harborage or conditions conducive to attracting vermin to the premises and/or allowing vermin to exist. 15787 Food contact surface not properly washed, rinsed and sanitized after each use and following any activity when contamination may have occurred. 14405 Name: VIOLATION DESCRIPTION, dtype: int64 order of most popular cuisine description: 6 American 36576 Chinese 20059 Pizza 12883 Coffee/Tea 11917 Latin American 8675 Mexican 8210 Name: CUISINE DESCRIPTION, 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 New Public Library (warning: case sensitive) at coordinates 40.7531, -73.9823. The HTML file your program creates should be called: ny_public_library.html.
Hint: See Lab 9.
If you want to display the generated html file in a web browser, you can do as follows.
import folium import webbrowser #display html file import os #use to find directory #TODO: code to generate map filename = "ny_public_library.html" nycMap.save(filename) #display html using open method of webbrowser class webbrowser.open('file://' + os.path.realpath(filename))
Using folium, write a program that asks the user to read nyc_wifi_hotspot.csv, which is downloaded from NYC Wi-Fi Hotspot Locations from NYC OpenData.
Choose 1 for "Borough Name", enter the name of a borough, create a map with markers for all wifi hotspots in that region.
Choose 2 for "Postcode", enter a postcode, create a map with markers for all the wifi hotspots for that location. Warning: Postcode is treated as an int in the csv file, so you should use int function to convert input from a string to an integer.
The file name should be saved as xyz_hotspot.html, where xyz is the name of corresponding group key, for example, Manhattan_hotspot.html, or 100065_hotspot.html. Warning: need to convert postcode, an integer, to a string to concatenate with "_hotspot.html" to get the corresponding file name.
Hint: You can use groupby and get_group to consider only the rows for the input borough name or postcode 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 Name, 2 for Postcode 1 dict_keys(['Bronx', 'Brooklyn', 'Manhattan', 'Queens', 'Staten Island']) Enter Borough Name: Bronx
which would produce a html file named Bronx_hotspot.html:
Another sample run of the program, when we chooose postcode.
Enter 1 for Borough Name, 2 for Postcode 2 dict_keys([10001, 10002, 10003, 10004, 10005, 10006, 10007, 10009, 10010, 10011, 10012, 10013, 10014, 10016, 10017, 10018, 10019, 10020, 10021, 10022, 10023, 10024, 10025, 10026, 10027, 10028, 10029, 10030, 10031, 10032, 10033, 10034, 10035, 10036, 10037, 10038, 10039, 10040, 10041, 10044, 10048, 10065, 10075, 10111, 10128, 10282, 10301, 10302, 10304, 10305, 10306, 10307, 10308, 10309, 10310, 10312, 10314, 10451, 10452, 10453, 10454, 10455, 10456, 10457, 10458, 10459, 10460, 10461, 10462, 10463, 10464, 10465, 10466, 10467, 10468, 10469, 10470, 10471, 10472, 10473, 10474, 10475, 11004, 11101, 11102, 11103, 11104, 11105, 11106, 11201, 11203, 11204, 11205, 11206, 11207, 11208, 11209, 11210, 11211, 11212, 11213, 11214, 11215, 11216, 11217, 11218, 11219, 11220, 11221, 11222, 11223, 11224, 11225, 11226, 11228, 11229, 11230, 11231, 11232, 11233, 11234, 11235, 11236, 11237, 11238, 11249, 11354, 11355, 11356, 11357, 11358, 11360, 11361, 11362, 11364, 11365, 11366, 11367, 11368, 11369, 11372, 11373, 11374, 11375, 11377, 11378, 11379, 11385, 11411, 11412, 11413, 11414, 11415, 11416, 11417, 11418, 11419, 11420, 11421, 11422, 11423, 11426, 11428, 11432, 11433, 11434, 11435, 11436, 11691, 11692, 11693, 11694]) Enter Postcode: 10065
which would produce a html file named 10065_hotspot.html:
Sample input/output:
Enter red component... Enter an int in [0, 255]: -1 Enter an int in [0, 255]: 275 Enter an int in [0, 255]: 300 Enter an int in [0, 255]: 35 Enter green component... Enter an int in [0, 255]: 55 Enter blue component: Enter an int in [0, 255]: -5 Enter an int in [0, 255]: 0 0X233700Here are the pseudocode of the program.
def in_range(start, end): #TODO: prompt to enter an integer in range [start, end], #take input as an integer and #put the result in variable num. while num is not in the range of [start, end], that is, either num is smaller than start or num is larger than end, do the following: #TODO: prompt to enter an integer in #range [start, end], #take input as an integer and #put the result in variable num. #That is, re-enter value of num #if it is not in [start, end]. #TODO: return variable num def enter_color(): #TODO: prompt user to enter red component... #call in_range with proper parameters and #put the return in variable r, representing red. #Do similar things for variables #g (for green) and b (for blue). return r, g, b def int_to_hexstring(): #TODO: call enter_color, put the return to r, g, b #TODO: call hex method to convert a decimal number #to hexadecimal string. For example, #hex(0) returns "0x0", hex(10) returns "0xa", and #hex(100) returns "0x64". #call hex on r, put the return to variable r_hex. #TODO: call hex on g, put the return to variable g_hex. #TODO: call hex on b, put the return to variable b_hex. #Create a hexadecimal string starting with "0x" or "0X", #which means this is a hexadecimal string, #followed by 6 digits. #The first two digits represents hexadecimal value of r, #that is, values of r_hex #without its first two letters "0x", ie, #starting from the third letter of r_hex #(hint: use string slicing). #The next two digits represents values of g_hex #without its first two letters "0x". #The last two digits represents values of b_hex #without its first two letters "0x". #Note that r_hex, g_hex, or b_hex might have only #one digit after removing "0x", #we need to use zfill(2) function of string #on the sliced string, so that one zero #will be padded to the left of a one-letter string. #For example, "a".zfill(2) returns "0a", #while "ab".zfill(2) returns "ab", #since "ab" has two digits already, #there is no more zero to fill before it #if we want to have a total length of 2. #TODO: return the above string. def main(): print(int_to_hexstring()) if __name__ == '__main__': main()
The program, errorNames.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 --- lectureSlips |___ programs___ prog1 |___ prog2
Write a simplified machine language program that prints: MIPS is fun!
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 5 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.