General Notes


Submit the following programs via Gradescope:


    Programming Exercises

    Lecture 1 and Lab 1

  1. Due Date: February 9 Reading: Think CS: Chapters 1 & 2 & Lab1

    Write a program that prints "Hello, World!" to the screen.

    Hint: See the Lab 1.

  2. Due Date: February 10 Reading: Think CS: Chapter 4 & Lab 1

    Write a program that draws a pentadecagon (polygon with fifteen sides).
    program 2

    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.

  3. Due Date: February 14 Reading: Think CS: Chapter 4 & 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:

  4. Due Date: February 15 Reading: Think CS: Chapter 4 & Lab 1

    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:

  5. Due Date: 16 February Think CS: Chapter 2

    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.
    

  6. Due Date: February 17 Think CS: Chapter 2 and and Section 4.4

    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.

  7. Due Date: February 21 Think CS: Chapters 2 & Chapter 9

    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.

  8. Due Date: February 22 Think CS: Chapters 2 & Chapter 9

    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".

  9. Due Date: February 23 Think CS: Chapters 2 & Chapter 9


    (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.

  10. Due Date: February 24 Think CS: Chapters 2 & 4

    Write a program that implements the pseudocode below:

        For i = 10, 20, ... ,300:
            Walk forward i steps
            Turn left 121 degrees
    
    Your output should look similar to:

    Hint: See examples of range(start,stop,step) in Lecture 2 notes.


  11. Due Date: February 27 Think CS: Chapters 2 & 4

    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.

    • Simplest approach: create two turtles, one to draw green shade and the other to draw cyan shade. By default, each turtle starts from the origin -- coordinates x and y are both zero and faces east. You can use goto method of turtle to move to (-100, 100) so that the shades can be fully displayed in the screen. But that step is optional.
    • Use only one turtle. After drawing green shade, the turtle moves backward appropriate steps to its start point (you may need to calculate the total distance from the turtle's current position to the start point). You may need to penup, pendown and pensize methods of the turtle before drawing cyan shade.
    • Use only one turle. After drawing green shade, the turtle go to the start point. You may need use penup, pendown, and pensize methods of the turtle before drawing cyan shade.
    • For explanation of turtle commands, read turtle library.

  12. Due Date: February 28 Think CS: Chapters 2 & 4

    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:

  13. Due Date: March 1 Think CS: Chapters 2 & 4

    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.

    1. Use color name if avaiable (not every color has a name). Need to enclose name in quotes.
    2. Use hexadecimal numbers as a string (start with #). Need to enclose the string in quotes.
    3. Use float to represent RGB components of a color. That is divide the integer value of RGB by 255.
    4. Use int to represent RGB components of a color. Need to set colormode of turtle to be 255 first. By default, colormode is 1.0, that is, each component of RGB is represented by a floating point number as in the previous approach.

    You can find more colors of Python in python color constants.

  14. Due Date: March 2 Think CS: Chapters 2 & 4

    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.

  15. Due Date: March 3 Think CS: Chapter 2 & Section 8.2

    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.

  16. Due Date: March 6 Reading: Think CS: Chapter 4

    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.
    
  17. Due Date: March 7 Reading: Think CS: Chapter 4

    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:

    1. Create a 3D array with 30 x 30 x 3 using numpy.
    2. Set background color to be yellow, which is a combination of red and green.
    3. The left vertical line runs from 3 (included) to 26 (not included) in vertical direction, that is, height, and from 4 (included) to 7 (not included) in horizontal direction, that is, width. Color is blue.
    4. The middle horizontal line runs from 13 (included) to 16 (not included) in vertical direction, that is, height, and from 4 (included) to 26 (not included) in horizontal direction, that is width.
    5. The bottom horizontal line runs from 24 (included) to 27 (not included) in vertical direction, that is, height, and from 4 (included) to 26 (not included) in horizontal direction, that is, width.
    6. The right vertical line runs from 15 (included) to 27 (not included) in vertical direction, that is, height, and from 23 (included) to 26 (not included) in horizontal direction.
    7. Enter an output file name and save it.
    8. Remove any imshow or show statement of plt before submission.
  18. Due Date: March 8 Think CS: Chapter 2 & Section 8.2

    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.

  19. Due Date: March 9 Reading: Think CS: Section 2.7

    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 num by 2 decimal numbers, use round(num, 2).

    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.

  20. Due Date: March 10 Reading: Think CS: Chapter 2

    Modify the program in the section Elevation Data & Flood Maps in Lab 4 to color the region as follows.

    1. If the elevation is less than or equal to zero, color blue.
    2. For elevation larger than zero but less than or equal to the Sandy storm surge (6 feet), set color to be orange (red 255, green 128, and blue 0). You need to convert these number to be floating number by dividing them by 255.
    3. For elevation just above the Sandy storm surge (6 feet) and less than or equal to 13 feet, set color to be light grey (25% red, 25% green, 25% blue).
    4. For elevation just above 13 feet but less than or equal to 20 feet, set color to be dark grey (75% red, 75% green, 75% blue).
    5. For elevation that is above 20, set color to be green.
    Also, modify your program to not show any graphics windows (plt.show()) but instead just compute and save the map to floodMap.png.

    Generated floodMap.png looks as follows.


  21. Due Date: March 13 Reading: Think CS: Chapter 7 & Section 8.11

    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].

    1. Print the number of pixels whose fraction of red, the fraction of green, and the fraction of blue are all samller than that give threshold.
    2. Print the percentage of such pixels in the original figure.
    3. Generate an image whose color is complement of the original image, that is, suppose a pixel has color r, g, b, then the corresponding pixel in the complement picture is 1-r, 1-g, 1-b.
    4. Save the complement image as the original file name followed by "_complement.png", for example, suppose the original figure is "caDrought2014.png", then the complement file name should be "caDrought2014_complement.png".

    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.

  22. Due Date: March 14 Reading: Burch's Logic & Circuits
    Reading: Burch's Logic & Circuits

    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.

  23. Due Date: March 15 Reading: Burch's Logic & Circuits
    Build a circuit that satisfy the following truth table. The missing gate is either an and or an or gate.

    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.

  24. Due Date: March 16 Reading: Think CS: Section 10.25

    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.5
    
    Round num by two decimal numbers after the decimal point using
    round(num, 2)
    

    Hint

    1. First, count the number of words in the string the user entered (hint: use split method of a string to break the string into a list of words, then use len method of a list to find number of items in the list). Print out the number of words. Make sure this works before going onto the next part.
    2. Next, count the number of words starting with 'a' or 'b' (hint: find out the first letter of a word and compare it with 'a' or 'b'). Test that this part works before going on to the next step.
    3. Calculate fraction of words starting with 'a' or 'b'.
    Implement (and test!) each part and then go on to the next. See notes from Lecture 3.
  25. Due Date: March 17 Reading: Think CS: Chapter 4 & Section 7.4 Implement the following pseudocode to convert a hexadecimal string to a decimal number. If the string contains any letter other than '0'-'9', 'A'-'F' (can be small letter), exit and report errors.
    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.

  26. Due Date: March 20 Reading: Burch's Logic & Circuits

    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:
    InputsOutputs
    Decimal
    Number
    in1in2Decimal
    Number
    out1out2out3
    000 -1111
    101 0000
    210 1001
    311 2010
    Here is an analysis.

    1. When inputs are 00, 01, 10, 11, the expected output should be 111 (two's complement, see Problem 60, where the leftmost bit is sign bit, where 1 means negative, signed number 111 is -1), 000, 001, 010, correspondingly.
    2. First, work on the least significant of output, out3. When input is 00, 01, 10, 11, the output should be 01, 10, 11, 100. The least significant digit of output, out3, is solely depending on the least significant digit of input in2. When in2 is 0, out3 is 1. When in2 is 1, out3 is 0.
    3. Next, work on the second digit of output, out2. Observe that out2 is 1 when in1 and in2 are either 00 or 11, while 00 representing in1 is 0 and in2 is 0, which can be written as neither in1 nor in2 is 1.
    4. Finally, work on the most significant digit of output, out1. Only when in1 and in2 are both 0, can out1 become 1.

    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.

  27. Due Date: March 21 Reading: 10-mins to Pandas, DataCamp Pandas

    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.

  28. Due Date: March 22 Reading: 10-mins to Pandas, DataCamp Pandas

    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.

    1. If choice is a, group by category, print out the total amount of each category. Afterwards, enter a specific category, calculate its minimum, maximum, average, and total of amount for that category.

      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.

    2. If choice is b, group by month of a year (abbreviated as 'Year Month'), print out the total amount of each Year Month. Afterwards, enter a specific Year Month, calculate its minimum, maximum, average, and total of amount for that month.

      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'.

    3. If choice is c, enter an integer, print out the first many most visited stores, that is, the first several stores in the file.
    4. For any other choice, print "wrong choice".

    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.

  29. Due Date: March 23 Reading: Ubuntu Terminal Reference Sheet

    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

  30. Due Date: March 24 Reading: Github Guide

    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.


  31. Due Date: March 27 Reading: 10-mins to Pandas, DataCamp Pandas

    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".

    • ask the user to specify a year from 2017 to 2021.
    • ask the user to specify the output file.
    • report the maximum acceptance rate and the correponding rate in that given year.
    • make a plot of the acceptance rate in percentage by boroughs in that year. Acceptance rate is calculated by the population that Were placed into full-time or part-time jobs over the population that Applied for the program. To represent the value in percentage, multiple the quotient by 100.
    • store the plot in the output file the user specified.

    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.
    
    
  32. Due Date: March 28 Reading: Think CS Section 6.8

    Refer to the program from Lab 7. Read workforce.csv downloaded from NYC Open Data with slight modifications. Your program will do the following,

    • find out print out the average of Applied for the program in each Borough, pay attention to the corresponding column name, need to be strictly case to case, letter to letter.
    • Choose a borough. You may print grouped_data.groups.keys() to display all possible boroughs, where variable grouped_data holds the return of groupby method of data frame object read from csv file.
    • For the chosen borough, find out and print the maximum applicants for the program among all years and the number of (available) year records in the borough.
    • ask the user to specify the output file.
    • make a bar plot of the Applied for the program of every available year in the chosen borough, and
    • store the plot in the output file the user specified.
    You may use the following statements.
    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:

  33. Due Date: March 29Reading: Think CS Chapter 6 and Chapter 7

    Write a program that asks the user for a choice.

    • If the choice is 1, then enter the name of an input and output file. Your program should then save the top left quarter of the image to the output file specified by the user.
    • If the choice is 1, then enter the name of an output file to save the middle portion (from 1/4 of height to 3/4 of height and from 1/4 of width to 3/4 of width) of the original figure.

    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.

  34. Due Date: March 30 Reading: Think CS Section 6.8

    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
    
  35. Due Date: March 31 Reading: Think CS Section 6.8

    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 '.'.


  36. Due Date: April 3 Reading: Think CS Chapter 6

    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.
    Boroughstudio1-bedroom2-bedroom
    Manhattan27953500 3900
    Brooklyn22732450 2750
    Queens16951900 2350
    Bronx15001700 2200
    Staten Island12001425 2000
    The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the name of the function must match exactly (else, the scripts cannot find it).

    A sample run:

    rentPrice("Brooklyn", "1-bedroom") returns 2450
    

    And another:

    rentPrice("Queens", "5-bedroom") returns 0
    

    Hint: See Lab 8.

  37. Due Date: April 4 Reading: Think CS Chapter 6

    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.

  38. Due Date: April 14 Reading: Think CS Chapter 6

    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.

  39. Due Date: April 15Reading: Think CS Chapter 6

    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.

  40. Due Date: April 18 Reading: 10-mins to Pandas, DataCamp Pandas

    Mimic the parking ticket program from Lab 8 to do the following:

    • Read restaurant_inspection.csv which lists NYC restaurant inspection result. The original data is from DOHMH New York City Restaurant Inspection Results.
    • Ask the user for the number of most common VIOLATION DESCRIPTION (need to match column name letter by letter, case by case).
    • Ask the user for the number of most popular CUISINE DESCRIPTION (need to match column name letter by letter, case by case) in these restaurants.

    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
    
  41. Due Date: April 19 Reading: Think CS: Chapter 6 and Section 8.10 & Lab 8

    Using the template program, averageImage.py, available on the CSci 127 repo on GitHub, fill in the missing functions:

    • average(region): Takes a region of an image and returns the average red, green, and blue values across the region.
    • setRegion(region,r,g,b): Takes a region of an image and red, green, and blue values, r, g, b. Sets the region so that all points have red values of r, green values of g, and blue values of b.

    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.

    Lecture / Lab 9

  42. Due Date: April 20 Reading: Folium Tutorial & Lab 9

    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))
    
  43. Due Date: April 21 Reading: Folium Tutorial & Lab 9

    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:

  44. Due Date: April 24 Read Top Down Design in Lab 8. Define functions to convert red, green, blue components, each is an integer between 0 and 255, to a hexadecmial string. For example, if input red as 35, green as 53, and blue as 0, then the return is "0X233500", where 0X means hexadecimal number, hexadecimal number 23 equals decimal number 35, hexadecimal number 35 equals decimal number 53, and hexadecimal number 00 equals decimal number 0. Here are the main steps.
    1. Define function in_range(start, end), which ensures that input an integer in [start, end], both ends included. Return that integer.
    2. Define function enter_color(), which calls in_range function to enter red, green, and blue color component, return these three values. Note that in Python we can return multiple items directly, which is not true in C++. Also, red, green, and blue color component should be in [0, 255].
    3. Define function int_to_hexstring(), which calls enter_color to get red, green, and blue component, then return the corresponding color representation in hexadecimal string.

    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
    0X233700
    
    Here 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()
    
  45. Due Date: April 25 Reading: Think CS: Chapter 3

    The program, errorNames.py, has lots of errors. Fix the errors and submit the modified program.

    Hint: See Lab 9.


    Lecture / Lab 10

  46. Due Date: April 26 A perfect integer is a positive integer which equals to the sum of all its factors other than itself. For example, 6 is a perfect number, since it has factors 1, 2, 3, and 6. The total of all the factors other than itself is 1 + 2 + 3 = 6.

    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.

  47. Due Date: April 27 Write a program to let computer guess an integer between 0 and 100, both ends included. We adopt an approach similar to binary search. Using this approach, we can guarantee that for any int in [0, 100], we can guess it with no more than 7 tries. That is, in the worst case, it takes 7 guesses. Here is how the game is played.

    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].

    1. Let start be the left boundary 0 and end be the right boundary 100 of range [0, 100], where the integer is picked.
    2. For the first guess, we pick the mid of start and end, which is 50. You need to use integer division // to find out the mid point, since the target (ie, answer) is an int.
    3. User can respond with either 1 (too small), 2 (too big), or 3 (just right), since the answer in mind is 25 while the current guess is 50, the user chooses 2, which means the guess is too big.
    4. Since 50 is too big for the answer, we know that the answer cannot be in range [50, 100]. Said differently, we now concentrate on range [0, 49]. That is, when a user gives feedback as 2 (too big), start is still the same but the end is changed to 49. What is the relationship between the recent guess 50 and the modified end 49?
    5. Now start is 0 and end is 49, its mid point is 24 (use integer division!). Use 24 as current guess. Ask feedback from the user, who would respond 1 (too small) since the guess is too small compared with the number in mind, 25.
    6. In the current range [0, 49], 24 is too small, so we need to concentrate on the right half of range, that is, [25, 49]. Said differently, when a user gives feedback as 1 (too small), keep current end, but modify current start. What is the relationship between modified start, 25 in this case, with the recent guess 24?
    7. With the newly narrowed range [25, 49], find its mid point as the new guess. That is, (25 + 49) // 2 returns 37. Compare 37 with answer 25, the guess is too big, so the user gives feedback 2 (too big).
    8. In the current range [25, 49], when 37 is too big compared with answer 25, the answer must be somewhere in [25, 36]. That is, we throw away the right half of [25, 49], the thrown part is [37, 49]. Equivalently, update the right end of the range to be 36. In short, when feedback is 2 (too big), update end. What is the relationship between next end 36 and current guess 37?
    9. In the current range [25, 36], calculate its mid point (25 + 36)//2 = 30, as the current guess. Compare 30 with answer 25, the user would give feedback 2 (too big) since 30 is larger than the answer.
    10. Based on feedback 2 (too big) with current guess 30, narrow current range from [25, 36] to [25, 29]. That is, when feedback is 2 (too big), update current end 36 to 29. What is relationship between to-be-updated end 29 and most recent guess 30?
    11. With newly updated range [25, 29], calculate mid point (25 + 29) // 2 = 27 as current guess. Get feedback from the user, who would respond 2 (too big) since 27 is larger than answer 25.
    12. Based on feedback 2 (too big) and guess 27, update current range from [25, 29] to [25, 26]. What is the relationship between 26 and current guess 27?
    13. With newly updated range [25, 26], calculate mid point (25 + 26) // 2 = 26 as current guess. The user would respond with 3 (just right). The guess game ends.
    14. As a side note, if the answer is 26, then the user would have responded with 1 (too small) in the above step. Then range is updated from [25, 26] to [26, 26]. Since the range has only one integer, we can conclude that the answer must be 26.
    15. Optional: It takes at most 7 tries to guess an integer in range [0, 100]. Here is an explanation. In the very beginning, there are 101 elements in range [0, 100]. After calculating mid point and adjust start and end when answer is not 3, the newly updated range, for example, [0, 49] has only 50 elements, roughly half of the original size. Similarly, the next range to consider is [25, 49]. Note that mid point of [0, 49] is 24, which is smaller than 25. We only need to consider range [25, 49], which has 25 elements, half of the original size. So by this approach, the number of integers in a range is reduced by half each time. That is, the number of elements goes from 101, 50, 25, 12, 6, 3, 1, in 7 rounds. In general, when number of elements is n and we cut the range by half each time, it takes ceiling(log2 n) times to shrink the original range to a range with only one element.

      Optional: if there are 1000 elements, what is the maximum number of guesses to guess an integer? Hint: 210 = 1024 and 29 = 512.

    A sample run of program when answer is 25 is as follows.
    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 26
    
    So 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 variable
    
    A 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()
    
  48. Due Date: April 28 Write a program to do the following:
    1. Define function that ensures a user can only input an integer in [1, 6], where both ends are included. Return that integer.
    2. Define a function.
      • Call the first function, put the return in variable user.
      • Computer generates a random integer in [1, 6], put in variable computer.
      • Compare user and computer. If there are both equal, print "draw", otherwise, if the sum of user and computer is 7, 8, or 9, print "user wins", otherwise, print "computer wins".
    3. Define main function, call the second function.
    4. Call main function.
    A sample output is as follows.
    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 wins
    
    Here 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".

  49. Due Date: May 1Write a bash script to do the following, Under current directory, create directory cs127. Under cs127 directory, create two subdirectories: lectureSlips and programs. Under programs subdirectory, create two subdirectories: prog1 and prog2. So the directory structure looks like the following tree:
    cs127  --- lectureSlips
          |___ programs___ prog1
                      |___ prog2
    
  50. Due Date: May 2 Reading: MIPS Wikibooks

    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.

  51. Due Date: May 3

    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.

  52. Due Date: May 4 Reading: Ubuntu Terminal Reference Sheet & Lab 10 & Lab 11.

    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.


    Lecture / Lab 12

  53. Due Date: May 5 Reading: Cplusplus Tutorial

    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++.

  54. Due Date: May 8 Reading: Cplusplus Tutorial & Lab 12

    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.

  55. Due Date: May 9 Reading: Cplusplus Tutorial

    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++.

  56. Due Date: May 10 Reading: Cplusplus Tutorial & Lab 12

    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
    

    Lecture / Lab 13

  57. Due Date: May 11 Reading: Cplusplus Tutorial & Lab 13

    Write a C++ program that asks the user for the current number of credit hours and prints

    • "freshman" if the given hours is lower than 28.
    • "sophomore" if the given hours is at least 28 and less than 61.
    • "junior" if the given hours is at least 61 and less than 94.
    • "senior" if the given hours is 94 degrees or greater.

    A sample run:

    Enter number of credit hours taken: 12
    freshman
    

    Another sample run:

    Enter number of credit hours taken: 96
    senior
    
  58. Due Date: May 12 Reading: Cplusplus Tutorial

    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: $
         $
        $$
       $$$
      $$$$
     $$$$$
    $$$$$$
    
  59. Due Date: May 15 Reading: Cplusplus Tutorial & Lab 13

    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.

  60. Due Date: May 16 Reading: Cplusplus Tutorial & Lab 13

    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.

    1. Ask the user for an int n in [-128, 127], both ends are included.
    2. Save n in variable num.
    3. If num is negative, set num to be -num -1.
    4. Declare string variable result and initialize it to be an empty string "". This variable stores the binary representation of num.
    5. Declare integer variable rem.
    6. as long as num > 0:
      1. Save the remainder of num divided by 2 to rem.
      2. Concatenate to_string(rem) to the left of string result and save to result. Expression to_string(rem) converts integer rem to a string in C++.
      3. Let num be num/2.
    7. Declare integer variable size and initialize it to be 8. Next, pad zeros to the left of result to make it a 8-letter string.
    8. Put result.length(), which returns the number of letters in string result, to integer variable len. Unlike Python, len is not a function in C++. For comparison, we use len(result) to find out the number of letters in result in Python.
    9. Run the following statement to pad (size - len) zeros to the left of result. We would like string result to have eight letters, which are either '0' or '1'.
      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.

    10. Work with number that is negative. Note that num is modified from original value n by num = n and num = -num-1 in previous steps. Since num has been modified to be non-negative, we need to check whether the original number is negative or not by checking n.
          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.
          
    11. Print the value of result. This is the two's complement we seek.

    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.

    1. Convert the negative integer to a positive by multiplying by -1.
    2. Find out the binary representation of the positive integer -num.
    3. Invert the above binary string. That is, change '0' to '1' and '1' to '0' for each bit.
    4. Add 1 to the above binary number, this is the two's complement of 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.

    1. Multiply num by -1, we get the corresponding positive number.
    2. Find out the binary representation of -num, which is 5. In this example, binary representation of 5 is 0101.
    3. Invert the above string. The result is 1010.
    4. Add 1 to the above binary number, the result is 1011, which is Two's representation of -5. We can verify by calculating -1 * 23 + 1 * 21 + 1 * 20 = -5.

    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.

    1. Find out binary representation of (-num-1).
    2. Pad zeros to the left of binary representation to get 8-letter length string.
    3. Invert the above binary representation by changing '0' to '1' and '1' to '0'.
Here's xkcd on the simplicity of Python: