General Notes


Submit the following programs via Gradescope:


    Programming Exercises

    Lecture 1 and Lab 1

  1. Due Date: 12 September 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: 13 September Reading: Think CS: Chapter 4 & Lab 1

    Write a program that draws a dodecagon (polygon with 12 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: 14 September 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:

            
              Repeat 9 times: 
                Walk forward 100 steps
                Turn left 105 degrees 
                Walk forward 52 steps 
                Turn left 105 degrees 
        	    Walk forward 100 steps 
                Turn right 170 degree
             
          
    The result should look as follows:

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

    Write a program that implements the incomplete code (start right from the red spot and return to there). The initial part of the code is provided if you like. The colors are green, blue, cyan, and red, respectively.

            
               import turtle
    
               t = turtle.Turtle()
               t.pensize(5)
               t.shape("circle")
     
               #TODO: finish the rest code
               #hint: you may use color method of turtle.
               #The distance for a long line is 300.
               #The distance for a short line is 100.
            
          
    The result should look as follows:

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

    Write a program that enter an integer for number of repetition, print "Practice makes perfect." that many times.

    A sample run of your code is as follows.

    Enter repetition time: 5
    Practice makes perfect.
    Practice makes perfect.
    Practice makes perfect.
    Practice makes perfect.
    Practice makes perfect.
    

    Hint: you may need to use the following statement to enter an int and put it in variable num, where input function is similar to print function, however, input function can take input from users and convert the input content (ended with a return key) to a string, function int converts an string to an int.

    num = int(input("Enter repetition time: "))
    

    Next, use range(num) inside a for statement to do something num times. In this specific example, something means to print "Practice makes perfect.".


    Lecture 2 and Lab 2

  6. Due Date: 19 September Think CS: Chapter 2 and and Section 4.4

    Write a program that prints out the numbers counts down from 12 to 1. Need to use repetition statement.

    The output of your program should be:

    12
    11
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1
    WOW
    

    Hint: Use a loop and print out the index or loop variable.

  7. Due Date: 20 September Think CS: Chapters 2 & Chapter 9

    Using the string commands introduced in Lab 2, write a Python program that prompts the user for a full name in the format of first name first and last name last, separated by a space. Use split method of string to extract last name and first name, then change last name to upper case using upper method of string. Print the full name in the format of last name first, first name followed, separated by comma. Enter user name, change it to lower case letters, followed by "@hunter.cuny.edu".

    A sample run of your program should look like:

    Enter name in format firstName lastName: John Smith
    name in LASTNAME, firstName format: SMITH, John
    Enter user name of email: Js216
    email: js216@hunter.cuny.edu
    

    Hint: Your program should be able to take any phrase the user enters and prints it, it in upper case letters, and it in lower case letters. To do that, you need to store the phrase in a variable and print variations of the stored variable.

  8. Due Date: 21 September 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 next two letter in ASCII table.

    A sample run of your program should look like:

    Enter a phrase: I love Python!
    letter ASCII next_two_letter
         I    73               K
              32               "
         l   108               n
         o   111               q
         v   118               x
         e   101               g
              32               "
         P    80               R
         y   121               {
         t   116               v
         h   104               j
         o   111               q
         n   110               p
         !    33               #
    

    And another sample run:

    Enter a phrase: ABC
    letter ASCII next_two_letter
         A    65               C
         B    66               D
         C    67               E
    

    Hint: If c is a character, ord(c) returns its ASCII code. For example, if c is 'I', then ord(c) returns 73. See Lab 2.

    To right aligned the print out, use print("%6c %5i %15c"%(character, ASCII_code_of_character, next_two_letter_of_character)). You need to find out expression to represent character, ASCII_code_of_character, and next_two_letter_of_character.

    Explanation: Use 6c since column header "letter" has 6 letters, c means character, for example, letter 'I' in string "I love Python!". Use 5i since column header "ASCII" has 5 letters, i means int, which is the ASCII code of the current letter. Use 15c since column header "next_two_letter" has 15 letters, c means a letter, which is the next_two_letter of the current letter.

    Warning: do not forget to print column names "letter ASCII next_two_letter".

  9. Due Date: 22 September 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 lower case letters: 'a',...,'z'.

    A sample run of your program should look like:

    Enter an all-small-letter string: zebra
    Enter a non-negative int to shift: 13
    ciphered string: mroen
    

    Here is another sample run of your program.

    Enter an all-small-letter string: owqfka
    Enter a non-negative int to shift: 6
    ciphered string: ucwlqg
    

    Hint: See the example programs from Lecture 2.

  10. Due Date: 23 September Think CS: Chapters 2 & 4

    Enter a phrase, reverse it, then capitalize each letter of the reversed string. Afterwards, get an abbreviation of the last letter of each word, starting from the last word to the first one.

    A sample run of your program should look like:

    input: City Univ of New York
    
    user reverse: kroY weN fo vinU ytiC
    user reverse upper: KROY WEN FO VINU YTIC
    user abbreviation: CUONY
    

    Here is another sample run of your program.

    input: Srbkts L Cizyjb
    
    user reverse: bjyziC L stkbrS
    user reverse upper: BJYZIC L STKBRS
    user abbreviation: SLC
    

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


    Lecture 3 and Lab 3

  11. Due Date: 28 September Think CS: Chapters 2 & 4

    Modify the program from Lab 3 to show the shades of cyan.

    Your output should look similar to:

        t = turtle.Turtle()
    
        t.penup()
        t.backward(100)
        t.left(90)
        t.backward(100)
        t.right(??) #you fill in a degree in ??
        t.pendown()
    
        #TODO: draw right shade
    
        #TODO: move to the start direction of up shade
    
        #TODO: draw up shade
    

    Warning: for the purpose of grading script, the right shade is drawn before the up shade.

    Hints: you may use one of the following approaches.

    • Simplest approach: create two turtles, one to draw the right shade and the other to draw the up shade. By default, each turtle starts from the origin -- coordinates x and y are both zero and faces east.
    • Use only one turtle. After drawing the right 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 the up shade.
    • Use only one turle. After drawing the right shade, the turtle go to the start point. You may need use penup, pendown, and pensize methods of the turtle before drawing the up shade.
    • For explanation of turtle commands, read turtle library.

  12. Due Date: 29 September Think CS: Chapters 2 & 4

    Modify the program from Lab 3 to show the shades of pink and then repeat a similar loop where a loop variable goes from 255 (included) down to 0 (not included), gap step is decreased by 10 in each round.

    A sample run of your program should look like:

  13. Due Date: 30 September Think CS: Chapters 2 & 4

    Modify the program from Lab 3 to draw a brown turtle (color #964B00 or RGB code 150, 75, 0), stamp after each turn. The turtle moves forward by 100 in each round.

    A sample run of your program should look like:

    Hint: See Lab 3 for colors.

  14. Due Date: 3 October 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 sets red channel of the original image to be zero.

    A sample run of your program should look like:

    Enter name of the input file:  csBridge.png
    Enter name of the output file:  csBridge_wo_red.png
    

    Sample input and resulting output files:

    As another example, run the above program on shades of purple in a white background, as in the original figure shown in the left. Since purple is combination of red and blue, after setting red channel to be zero, which equals to remove red, the color of shades becomes blue in the modified figure, shown in the right.

    In the original figure, background white is combined of 100% red, 100% blue, and 100% green. After removing red channel, the background has only blue and green, which changes to cyan color in the modified figure.

    In the original figure, black color is combined of 0% red, 0% blue, and 0% green. After removing red channel, black color is still the same in the modified figure.

    Sample input and resulting output files:

    Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

    Hint: See Lab 3.

  15. Due Date: 6 October Think CS: Chapter 2 & Section 8.2

    Write a program that asks the user for a message and then prints the message out, one fewer word a line until there is only one word, then continue to add one word a line until becoming the original message.

    A sample run of your program should look like:

    Enter a phrase: how are you?
    how are you?
    how are
    how
    how are
    how are you?
    

    Hint: See Lab 2 or Lecture 2 notes. Use split method to break the original message by a a list of words. Then use for-loop to display partial of the list. To display a list of words as a string, use ' '.join(list_of_words). For example,

    lst = ['a', 'bc', 'd', 'e']
    print(' '.join(lst[:2])) 
    #display the first 2 elements of lst, joined by a space, 
    #that is, display
    #a bc
    

    Lecture 4 and Lab 4

  16. Due Date: 7 October Reading: Think CS: Chapter 4

    Enter a list of names separated by semicolon. Display each name in a line, started by the first letter of first name, followed by a dot, a space, and last name.

    A sample run of your program should look like:

    Enter a list of names, separated by semicolon: George Washington;James Adam;Thomas Jefferson;James Madison;James Monroe
    G. Washington
    J. Adam
    T. Jefferson
    J. Madison
    J. Monroe
    
  17. Due Date: 11 October 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_t.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 horizontal line runs from 5 to 8 in vertical direction and from 5 to 25 in horizontal direction. Color is blue.
    4. The vertical line runs from 8 to 25 in vertical direction and from 13 to 16 in horizontal direction. Color is green.
    5. Enter an output file name and save it.
    6. Remove any imshow or show statement of plt before submission.
  18. Due Date: 12 October Think CS: Chapter 2 & Section 8.2

    Create a program that creates a image of vertical blue and green stripes. Your program should ask the user for the size of your image, the name of the output file, and create a .png file of stripes. For example, if the user enters 10, your program should create a 10x10 image, alternating between blue and green vertical stripes.

    A sample run of the program:

    Enter the size: 10
    Enter output file: stripes10.png
    

    Another sample run of the program:

    Enter the size: 50
    Enter output file: stripes50.png
    

    Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

    Hint: See notes from Lecture 4.

  19. Due Date: 13 October Reading: Think CS: Section 2.7

    You may need to use the following information. 1 feet = 30.48 centimeters 1 inch = 2.54 centimeters To round a decimal number num by 2 decimal numbers, use round(num, 2). To round num to a whole number, use round(num). Test your code using cm to feet and inch

    Write a program that implements the pseudocode below:

    (a) convert centimeters to feet
    (b) convert centimeters to feet and inches
    (c) convert feet and inches to centimeters
    

    Some sample runs of your program should look like:

    Choose Option a. When converting centimeters to feet, round the result to two decimal numbers after the decimal point.

    (a) convert centimeters to feet
    (b) convert centimeters to feet and inches
    (c) convert feet and inches to centimeters
    Enter a or b or c: a
    Enter height in centimeters: 150
    height is 4.92 feet
    

    Choose Option b. Values of feet and inches are integers (whole numbers).

    (a) convert centimeters to feet
    (b) convert centimeters to feet and inches
    (c) convert feet and inches to centimeters
    Enter a or b or c: b
    Enter height in centimeters: 150
    height is 4 feet and 11 inches
    
    Hints for converting centimeters to feet and inches.
    1. Divide centimeters by 30.48, truncate decimal parts by int(centimeters / 30.48). That is the number of feet.
    2. Calculate the remaining, divide it by 2.54, get the whole number by int((centimeters - num_of_feet * 30.48) / 2.54). That is number of inches.
    3. Optional: consider the possibility that number of inches is zero.

    Choose Option b and the resulting inch is zero. In this situation, display only feet, not inch.

    (a) convert centimeters to feet
    (b) convert centimeters to feet and inches
    (c) convert feet and inches to centimeters
    Enter a or b or c: b
    Enter height in centimeters: 92 
    height is 3 feet
    

    Choose Option c. Round the centimeters to an integer, that is, round to zero decimal number. Note that int(5.5) truncates any decimal numbers after the decimal part and returns 5, while round(5.5, 0) returns 6.0.

    (a) convert centimeters to feet
    (b) convert centimeters to feet and inches
    (c) convert feet and inches to centimeters
    Enter a or b or c: c
    Enter height in feet and inches, separated by a space: 4 11
    height is 150 cm
    
    In this task, take two inputs using
    feet_str, inches_str = input("Enter height in feet and inches, separated by a space: ").split()
    
    #convert feet_str to an int using 
    feet = int(feet_str) 
    

    Choose an option other than a, b, or c.

    (a) convert centimeters to feet
    (b) convert centimeters to feet and inches
    (c) convert feet and inches to centimeters
    Enter a or b or c: 1
    Wrong choice, please enter only a or b or c.
    

    Hint: See Section 2.7.

  20. Due Date: 14 October Reading: Think CS: Chapter 2

    Modify the program in the section Elevation Data & Flood Maps in Lab 4 to color the region just above the Sandy storm surge (6 feet) and less than or equal to 20 feet the color grey (50% red, 50% green, 50% blue). Also, modify your program to not show any graphics windows (plt.show()) but instead just compute and save the map to floodMap.png. Finally, change color red to yellow.

    Generated floodMap.png looks as follows.


  21. Due Date: 17 October 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 threshold, print the number of pixels that are nearly white (the fraction of red, the fraction of green, and the fraction of blue are all above the given threshold). Also, calculate the percentage of those pixels divided by the total number of pixels in the picture.

    For example, if your file was of the snow pack in the Sierra Nevada mountains in California in September 2014:

    Suppose the file is saved as caDrought2014.png, then a sample run would be:

    Enter file name: caDrought2014.png
    Enter threshold: 0.75
    number of white pixels: 38010
    percent of white pixels: 2.26 %
    

    Note: for this program, you only need to compute the snow count. Showing the image will confuse the grading script, since it's only expecting the snow count and its percentage.

  22. Due Date: 18 October 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: 19 October 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 1
    0 0 1 0
    0 1 0 0
    0 1 1 0
    1 0 0 1
    1 0 1 0
    1 1 0 1
    1 1 1 1

    Save your expression to a text file. See Lab 5 for the format for submitting logical expressions to Gradescope.

  24. Due Date: 20 October 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 ending with letter 'a' or 'b', then calculate its fraction rounded by two decimal numbers after the decimal point. Your program should output the total number of words and the fraction that end in 'a' or 'b'. Assume that words are separated by spaces (and ignore the possibility of tabs and punctuation between words.)

    A sample run of the program:

    Enter a list of words, separated by a space: apple banana cantalope durian shrub
    number of words: 5
    number of words ending with a or b: 2
    fraction of words starting with a or b: 0.4
    

    And another sample run of the program:

    Enter a list of words, separated by a space: af bce gdfgb agcg edc dade fggga gb
    number of words: 8
    number of words ending with a or b: 3
    fraction of words ending with a or b: 0.38
    
    Round num by two decimal numbers after the decimal point using
    round(num, 2)
    

    Approach 1

    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 ending in 'a' or 'b' (hint: find out the last letter of a word). Test that this part works before going on to the next step.

    Approach 2

    1. First, count the number of words in the string the user entered (hint: count the number of spaces). Print out the number of words. Make sure this works before going onto the next part.
    2. Next, ignoring the last word (which is a special case and can be dealt with separately), count the number of words ending in 'a' or 'b' (hint: count the number of "a " or "b "). Test that this part works before going on to the next step.
    3. Last, check the last word to see if it ends in "a" or "b".
    Implement (and test!) each part and then go on to the next. See notes from Lecture 3.
  25. Due Date: 21 October Reading: Think CS: Chapter 4 & Section 7.4 Implement the following pseudocode to convert a string to a decimal number. If the string contains any letter other than '0' or '1', exit and report errors.
    input a string, put in variable string
    set num to be 0
    set base to be the base of binary number
    initialize weight to be 1, for the least significant digit
    set length to be the number of letters of string
    
    Move i from the rightmost index downto the leftmost index
        put ith letter of string to variable ch 
        if ch is '1'
             increase num by weight 
        otherwise, if ch is not '0'
             print that Letter ch is not allowed in a binary string
             call exit method to exit current program
        #num is not updated when ch is '0'
    
        update weight by multiplying it with base 
    
    print out num followed by prompt "num ="
    

    some sample input/output are as follows.

    Enter a string with 0 or 1 only: 100101
    num = 37
    

    When an input string has more than one letter that is neither '0' or '1', only report the first violation that is closest to the least significant bit in the rightmost position.

    Enter a string with 0 or 1 only: a20
    Letter 2 is not allowed in binary string.
    

    Hint: See Lecture 4 notes.

  26. Due Date: 24 October 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 1001
    101 2010
    210 3011
    311 4100
    Here is an analysis.

    1. When inputs are 00, 01, 10, 11, the expected output should be 01, 10, 11, 100, 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 when input is 01 or 10, output out2 is 1, otherwise, out2 is 0. Without loss of generality, check the case when input is 01, which means in1 is 0 and in2 is 1, that is, not in1 and in2. Equally, out2 is 1 when in1 and in2 are neither 00 nor 11. Use this approach, you can design a simpler circuit than our current one, with the same functionality.
    4. Finally, work on the most significant digit of output, out1. Only when in1 and in2 are both 1, 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:  August 2022
    #Logical expressions for a 3-bit incrementer
    
    out1 = ...
    out2 = ...
    out3 = ...
    
    Where "..." is replaced by your logical expression (see Lab 5).

    Note: here's a quick review of binary numbers.

  27. Due Date: 25 October Reading: 10-mins to Pandas, DataCamp Pandas

    Modify the program from Lab 6 that displays the NYC Covid-19 Cases. Your program should ask the user for the name of csv file, name of a borough and the name of the output file.
    The program should compute the minimum, maximum, average, median and standard deviation of the covid-19 cases of the borough entered by the user and then display the fraction of the covid-19 daily cases in that borough over time and saves it using the file name entered by the user.
    Note that mean and standard deviation are rounded to 3 decimal numbers after the decimal point. Read the attached csv file to see column names. Use exact the same column name in your program.

    IMPORTANT: The grading script expects the new column to be called 'Fraction'

    A sample run of the program:

    Enter a csv file: covid_daily_cases.csv
    Enter borough (Bronx, Brooklyn, Queens, Manhattan, Staten Island): Queens
    Enter output name: queensCovidFraction.png
    Min: 0
    Max: 15201
    Mean: 728.066
    Median: 329.0
    Standard Deviation: 1552.465
    

    The file queensCovidFraction.png:

    Note: before submitting your program for grading, remove the commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

  28. Due Date: 26 October Reading: 10-mins to Pandas, DataCamp Pandas

    Write a program that analyzes children under six affected by lead in five boroughs of NYC in 2005 to 2016. Data is extracted from open data of NYC and saved in children_lead.csv. Your program should assume that above data file is in the same directory. The file has three columns: borough, year, and affected_children. Each row records the number of children under six whose blood lead level is at least 5 micrograms of lead per deciliter of blood (μg/dL) in the specific borough and year. Choose Option a to group by borough, report average of number of affected children in each borough. Enter a specific borough. Report the minimum, maximum, and average number of affected children in those years. Choose Option b to group by year, report average of number of affected children in each year. Enter a specific year. Report the minimum, maximum, and average number of affected children in the boroughs.

    A sample run of your program to group by borough.

    Enter a choice:
    a. group by borough
    b. group by year
    a
    average number of affected children by borough
    borough
    Bronx            3254.750000
    Brooklyn         6966.333333
    Manhattan        1837.250000
    Queens           3750.500000
    Staten Island     497.166667
    Name: affected_children, dtype: float64
    Enter a borough: Staten Island
    average number of affected children of Staten Island is  497.1666666666667
    min number of affected children of Staten Island is  164
    max number of affected children of Staten Island is  1049
    

    Here is a run to group by year.

    Enter a choice:
    a. group by borough
    b. group by year
    b
    average number of affected children by year
    year
    2005    7467.8
    2006    6924.6
    2007    6095.8
    2008    4080.4
    2009    3043.4
    2010    2790.2
    2011    2287.4
    2012    1635.4
    2013    1440.4
    2014    1310.0
    2015    1073.8
    2016     985.2
    Name: affected_children, dtype: float64
    Enter a year (2005 - 2016): 2014
    average number of affected children in 2014 is 1310.0
    min number of affected children in 2014 is 238
    max number of affected children in 2014 is 2929
    

    A sample run of your program to choose options other than a or b is as follows.

    Enter a choice:
    a. group by borough
    b. group by year
    c
    wrong choice
    

    Hint: See Lab 6.

  29. Due Date: 27 October 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.

  30. Due Date: 28 October 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:  August 2022
    #Account name for my github account
    
    AccountNameGoesHere
    

    Note: it takes a few minutes for a newly created github account to be visible. If you submit to gradescope and get a message that the account doesn't exist, wait a few minutes and try again.


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

    Refer to the program from Lab 7. Read country_internet.csv downloaded from kaggle.com. The file records number of internet users and population in different countries.

    • ask the user to specify the output file,
    • make a plot of the percentage of the internet users over the population of every country, and
    • store the plot in the output file the user specified.

    A sample run of the program:

    Enter output file name:  internet_users_percentage.png
    maximum percentage of all countries:  Faroe Islands 99.18 %
    

    which produces an output:

    Note: The grading script is expecting that the label (i.e. name of your new column) is "Percentage".

  32. Due Date: 1 November Reading: Think CS Section 6.8

    Refer to the program from Lab 7. Read country_internet.csv downloaded from kaggle.com. Your program will do the following,

    • find out print out the average of NO. OF Internet Plans in each Continental region, pay attention to the corresponding column name, need to be strictly case to case, letter to letter.
    • Choose a continental region. You may print grouped_data.groups.keys() to display all possible continental regions, where variable grouped_data holds the return of groupby smethod of data frame object read from csv file.
    • For the chosen region, find out and print the maximum and minimum number of internet plans among all countries and the number of countries in the region.
    • ask the user to specify the output file.
    • make a bar plot of the NO. OF Internet Plans of every country in the chosen region, and
    • store the plot in the output file the user specified.
    You may use the following statements.
    grouped_data.get_group(chosen_region).plot.bar(...)
        #the first parameter of bar method is the column name representing country, the second parameter is the number of internet plans
    plt.gcf().subplots_adjust(bottom=0.25)
        #so that the country name is displayed in full
    plt.xlabel(...)
        #The parameter in xlabel should be "Country in ...", where ... is the name of chosen region. The region name should be exactly the same as the corresponding region the csv file.
    plt.ylabel("NO. OF Internet Plans")
    

    A sample run of the program:

    Continental region
    ASIA (EX. NEAR EAST)    37.964286
    BALTICS                 26.333333
    CARIBBEAN               17.068966
    CENTRAL AMERICA         24.500000
    CIS (FORMER USSR)       23.909091
    EASTERN EUROPE          28.714286
    Europe                        NaN
    NEAR EAST               31.750000
    NORTHERN AFRICA         23.285714
    NORTHERN AMERICA        32.250000
    OCEANIA                 17.318182
    SOUTH AMERICA           32.692308
    SUB-SAHARAN AFRICA      28.391304
    WESTERN EUROPE          24.566667
    Name: NO. OF Internet Plans, dtype: float64
    
    possible regions are
    dict_keys(['ASIA (EX. NEAR EAST)', 'BALTICS', 'CARIBBEAN', 'CENTRAL AMERICA', 'CIS (FORMER USSR)', 'EASTERN EUROPE', 'Europe', 'NEAR EAST', 'NORTHERN AFRICA', 'NORTHERN AMERICA', 'OCEANIA', 'SOUTH AMERICA', 'SUB-SAHARAN AFRICA', 'WESTERN EUROPE'])
    choose a region: NORTHERN AMERICA
    In region NORTHERN AMERICA
    number of countries:  4
    maximum number of internet plans:  60.0
    minimum number of internet plans:  3.0
    Please enter output file name: internet_plans_northern_america.png
    

    which produces an output:

  33. Due Date: 2 NovemberReading: Think CS Chapter 6 and Chapter 7

    Write a program, using a function main() that enter a string and a letter, count the number of occurrence of that letter in the string. See Lab 7.

    Enter a string: Hello, how are you?
    Enter a char: o
    number of 'o' in "Hello, how are you?" is 3
    
  34. Due Date: 3 November Reading: Section 10.25

    Write a program that asks the user for a choice.

    • If the choice is 1, then enter the name of an output file. Your program should then save the upper right 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 upper right corner
    Enter 2 to get middle portion
    Your choice: 1
    Enter input file name: magic_logo.png
    Enter output file name: magic_logo_upper_right.png
    

    which would have as input and output:

    Another sample run of your program should look like:

    Enter 1 to get upper right corner
    Enter 2 to get middle portion
    Your choice: 2
    Enter input file name: magic_logo.png
    Enter output file name: magic_logo_middle.png
    

    which would have as input and output:

    When entering any number other than 1 or 2, here is an output:

         Enter 1 to get upper right corner
         Enter 2 to get middle portion
         Your choice: 3
         wrong choice
       

    Hint: See sample programs from Lectures 4 and 6.

    Hint: When input a choice other than '1' or '2', print "wrong choice" and exit the program. Otherwise, enter the input file name and output file name, then depending on the choice (either '1' or '2'), cut the image and save the portion to the output file.

    Note: before submitting your program for grading, remove any commands that show the image (i.e. the ones that pop up the graphics window with the image). The program is graded on a server on the cloud and does not have a graphics window, so, the plt.show() and plt.imshow() commands will give an error. Instead, the files your program produces are compared pixel-by-pixel to the answer to check for correctness.

  35. Due Date: 4 November Reading: Think CS: Section 7.4

    Write a program that asks the user for the hour of the day (in 24 hour time), and prints

    • "Good Morning" if it is strictly before 12,
    • "Good Afternoon" if it is 12 or greater, but strictly before 17, and
    • "Good Evening" otherwise.

    A sample run:

    Enter hour (in 24 hour time):  11
    Good Morning
    

    Another sample run:

    Enter hour (in 24 hour time):  20
    Good Evening
    

    And another run:

    Enter hour (in 24 hour time):  15
    Good Afternoon
    

  36. Due Date: 7 November

    Write a function, computePrice(), that takes two parameters: liquid (string) and the size type (string). The function should return a float for the price of the liquid of that size.

    • coffee, small, 2.5
    • coffee, medium, 2.75
    • coffee, large, 3.00
    • misto, small, 3.15
    • misto, medium, 3.35
    • misto, large, 3.7
    • mocha, small, 3.5
    • mocha, medium, 3.8
    • mocha, large, 4.25
    • tea, small, 2.35
    • tea medium, 2.45
    • tea large, 2.90
    • any other choice, return -1
    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:

    medium size tea: 2.45
    

    And another:

    medium size wine: -1
    

    Hint: See Lab 8.

  37. Due Date: 8 November Reading: Think CS Chapter 6

    Write function, flowerRecursion(), in recursive function for the flower in Problem 2. Key idea: if the number of petals is larger than zero, draw a petal. Call flowerRecursion to draw the flower with remaining petals.

    Here is a pseudocode.

    def flowerRecursion(t, n):
       if n > 0:
          #draw one petal
          move t forward 100 steps
          turn t left 105 degrees
          move t forward 52 steps
          turn t left 105 degrees
          move t forward 100 steps
    
          #prepare to move direction to draw next petal
          t.right(170)
       
          call flowerRecursion with t and n-1. 
    
    def main():
        #call flowerRecursion function to draw a flower
    
    if __name__ == '__main__':
       main()
    

  38. Due Date: 9 November Reading: Think CS Chapter 6

    Write three functions, drawPantegon(), cornerPantegon() and nestedPantegon(). Function drawPantegon takes three parameters: a turtle, an edge length, and number of edges. Functions cornerPantegon and nestedPantegon take two parameters: a turtle and an edge length. The pseudocode for drawPantegon() is:

    #recursive function to draw a pantegon
    def drawPantegon(t, length, numEdges):
       if numEdges > 0:
          move the turtle object, t, forward length steps
          t turn left 72 degrees
          call drawPantegon with t, length, and numEdges-1
    
    pseudocode of cornerPantegon, which draws pantegon nested in left corner.
    def cornerPantegon(t, length):
       if length >= 25:
          1. call drawPantegon with t, length and 5
          2. reduced length by half (use integer division in this function)
          3. call cornerPantegon with t and length, that is, draw a pantegon with t and updated length
    
    def nestedPantegon(t, length):
        if length >= 25:
           1. call drawPantegon with t, length, and 5
           2. Turtle t moves forward length/2
           3. Turtle t turns left 36 degrees
           4. call nestedPantegon with t, length * math.sin(54/180 * math.pi). To use sin function from math library, need to import math.
    
    The grading script does not run the whole program, but instead tests your function separately ('unit tests') to determine correctness. As such, the function names must match exactly (else, the scripts cannot find it). Make sure to use the function names from the github program (it is expecting cornerPantegon() and nestedPantegon()).

    A sample run with edge length 200 on cornerPantegon would produce:

    A sample run with edge length 50 on nestedPantegon would produce:

    A sample run with edge length 200 on nestedPantegon would produce:

  39. Due Date: 10 November Reading: 10-mins to Pandas, DataCamp Pandas

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

    A sample run:

    order of most popular neighborhoods in movies: 3
    Midtown            39
    Brooklyn           32
    Lower Manhattan    25
    Name: Neighborhood, dtype: int64
    order of directors/filmmakers making most movies in NYC: 5
    Spike Lee          11
    Woody Allen        11
    David Greene        8
    Sidney Lumet        6
    Martin Scorsese     6
    Name: Director/Filmmaker Name, dtype: int64
    
  40. Due Date: 11 November 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

  41. Due Date: 14 November 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 Central Park (warning: case sensitive) at coordinates 40.7812, -73.9665. The HTML file your program creates should be called: nyc_Central_Park.html.

    Hint: See Lab 9.

  42. Due Date: 15 November Reading: Folium Tutorial

    Using folium (see Lab 9), write a program that reads NYC hospitals, which is adapted from NYC Health + Hospitals patient care locations - 2011 from NYC OpenData by removing facilities without latitude and longitude information.

    Input name of the output file, and creates a map with markers for all the hospitals from the input file.

    A sample run:

    Enter output file:  nyc_hospitals.html
    

    which would produce the html file:

  43. Due Date: 16 November Reading: Folium Tutorial & Lab 9

    Using folium, write a program that asks the user to read after_school.csv, which is downloaded from DYCD after-school programs from NYC OpenData. Get rid of records without lagitude and longitude information, change some typos and modify some column names -- for example, change BOROUGH/COMMUNITY to Borough/Community -- for consistence. So make sure to use the above after_school.csv file.

    Choose 1 for "Borough/Community", enter the name of a borough/community, create a map with markers for all after school programs in that region.

    Choose 2 for "Grade Level / Age Group", enter a grade level, create a map with markers for all the after school programs for that group.

    The file name should be saved as lower cases of group_name, replacing every space with a underscore ('_') character and every forward slash ('/') with a underscore ('_'). Forward slash should be replaced, otherwise it will be mistakenas a separator between directories in Linux system.
    Hint: You can use groupby and get_group to consider only the rows for the input borough/community or grade level / age group. You can also use mygroup.groups.keys() to list the keys of mygroup, which holds the return of groupby.

    Note: You can use the value in the "Name" column to label each marker.

    A sample run:

    Enter 1 for Borough/Community,
    2 for Grade Level / Age Group
    Your choice: 1
    dict_keys(['Astoria', 'Bronx', 'Brooklyn', 'Corona', 'Flushing', 'Forest Hills', 'Jackson Heights', 'Jamaica', 'Kew Gardens', 'Long Island City', 'Manhattan', 'New York', 'Queens', 'Staten Island', 'Woodside'])
    Enter Borough/Community name: Jackson Heights 
    

    which would produce a html file named jackson_heights_after_school.html:

    Another sample run of the program, when we chooose grade level MS/HS.

    Enter 1 for Borough/Community,
    2 for Grade Level / Age Group
    Your choice: 2
    dict_keys(['11+', '13 to 21', '14 to 24', '14-Nov', '16 to 21', '16 to 24', '16+', '18+', '20-May', '6 and up', 'A parent 16 Years Old or Older', 'Adults', 'All Ages', 'ESOL/Civics', 'Elem/MS', 'Elem/MS/HS', 'Elementary', 'High School', 'MS/HS', 'Middle School', 'OST', 'Seniors', 'grades 6 to 8'])
    Enter Grade Level / Age Group name: MS/HS
    

    which would produce a html file named ms_hs_after_school.html:

  44. Due Date: 17 November Read Top Down Design in Lab 8. Define functions to draw flower as follows.

    a green flower with nine petals

    a blue flower with six petals

    From the above figures, we can see each flower has petals, and each petal has color and heads in different directions. Drawing of petal can refer to lab 3.

    Here is a blue petal tilting 0 degree from east direction, which is the default facing direction of a turtle.

    Here is a blue petal tilting 60 degrees from east direction. The angle between the central line of this petal and the east direction is 60 degrees.

    Here is a blue petal tilting 120 degrees from the east direction.

    Here is a blue petal tilting 180 degrees from the east direction.

    Here is a blue petal tilting 240 degrees from the east direction.

    Here is a blue petal tilting 300 degree from the east direction.

    It can be seen that a blue flower with 6 petals has petals tilted 0, 60, 120, 180, 240, and 300 degrees.

    In this problem, define petal, flower, and main functions.

    • Define function petal, whose first parameter is color and second parameter is angle. The color can be red, green, blue, yellow, purple, and cyan. If the actual parameter for color is none of the above choices, set the color to be green. Hint: use t = turtle.Turtle(visible=False) #visible=False hides arrow key of turtle when drawing, otherwise, you will see a little arrow key in each petal as follows, where the little arrows are circled out.

    • Define function flower, whose first parameter is color and the second parameter is number of petals. Inside this function, call petal to draw a flower with that color and number of petals. For example, for a flower with 6 petals, the first petal tilts 0 degree, the second petal tilts 60 degrees, where 60 is 360 / number of petals and 360 is the degree of a circle. The third petal tilts 120 degrees, ..., the sixth petal tilts 300 degrees.
    • Define function main, draw a green flower with 9 petals. Change parameters to draw flowers with different colors and different number of petals.
  45. Due Date: 18 November Reading: Think CS: Chapter 3

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

    Hint: See Lab 9.


    Lecture / Lab 10

  46. Due Date: 21 November 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: 22 November 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: 23 November 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 3, 6, 7, 8, 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: 28 NovemberWrite a bash script to do the following, Under current directory, create directory cs127. Under cs127 directory, create two subdirectories: quizzes and assignments. Under quizzes subdirectory, create two subdirectories: quiz1 and quiz2. So the directory structure looks like the following tree:
    cs127  --- assignments
          |___ quizzes ___ quiz1
                      |___ quiz2
    
  50. Due Date: 29 November Reading: MIPS Wikibooks

    Write a simplified machine language program that prints: I use MIPS!

    See Lab 11 for details on submitting the simplified machine language programs.

    Hint: You may find the following table useful:


    (Image from wikimedia commons)

    Hint: The grading scripts are matching the phrase exactly, so, you need to include the spacing and punctuation.

  51. Due Date: 30 November

    Write a simplified machine language program that has register $s0 increase from 0 to 100, increase by 10 each time.

    Your program must use the ADDI instructions and store all numbers in registers for computation.

    See Lab 11 for details on submitting the simplified machine language programs.

  52. Due Date: 1 December 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: 2 December 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: Due Date: 5 December 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: 6 December 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: 7 December 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: 8 December 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: 9 December 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: 12 December 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: 13 December 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:

  • Due Date: 15 November Reading: Think CS: Chapter 6

    Write a function, computeFare(), that takes as two parameters: the zone and the ticket type, and returns the Long Island Railroad fare.

    • If the zone is 1 and the ticket type is "peak", the fare is 8.75.
    • If the zone is 1 and the ticket type is "off-peak", the fare is 6.25.
    • If the zone is 2 or 3 and the ticket type is "peak", the fare is 10.25.
    • If the zone is 2 or 3 and the ticket type is "off-peak", the fare is 7.50.
    • If the zone is 4 and the ticket type is "peak", the fare is 12.00.
    • If the zone is 4 and the ticket type is "off-peak", the fare is 8.75.
    • If the zone is 5, 6, or 7 and the ticket type is "peak", the fare is 13.50.
    • If the zone is 5, 6, or 7 and the ticket type is "off-peak", the fare is 9.75.
    • If the zone is greater than 8, return a negative number (since your calculator does not handle inputs that high).

    A template program, LIRRtransit.py, is available on the CSci 127 repo on github. 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:

    Enter the number of zones: 4
    Enter the ticket type (peak/off-peak): off-peak
    The fare is 8.75
    

    And another:

    Enter the number of zones: 6
    Enter the ticket type (peak/off-peak): peak
    The fare is 13.5
    

    Hint: See Lab 8.

  • Due Date: 14 November Reading: Think CS: Chapter 6

    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:

    A template program, averageImage.py, is available on the CSci 127 repo on github. 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).

    Hint: See notes from Lecture 8.

  • Due Date: 16 November Reading: Folium Tutorial

    Write a program that uses folium to make a map of New York City. Your map should be centered at (40.75, -74.125) and include a marker for the main campus of Hunter College. The HTML file your program creates should be called: nycMap.html

    Hint: See Lab 9.

  • Due Date: 17 November Reading: Folium Tutorial

    Using folium (see Lab 9), write a program that asks the user for the name of a CSV file, name of the output file, and creates a map with markers for all the traffic collisions from the input file.

    A sample run:

    Enter CSV file name:  collisionsThHunterBday.csv
    Enter output file:  thMap.html
    

    which would produce the html file:

    (The demo above is for March 18, 2016 using the time the collision occurred ("TIME") to label each marker and changed the underlying map with the option: tiles="Cartodb Positron" when creating the map.)

    This assignment uses collision data collected and made publicly by New York City Open Data. When creating datasets to test your program, you will need to filter for both date (to keep the files from being huge) and that there's a location entered. The former is explained above; to check the latter, add the additional filter condition of "LONGITUDE is not blank".

    Hint: For this data set, the names of the columns are "LATITUDE" and "LONGITUDE" (unlike the previous map problem, where the data was stored with "Latitude" and "Longitude").

  • Due Date: 18 November Reading: Think CS: Chapter 3

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

    Hint: See Lab 9.

  • Due Date: 21 November Reading: Think CS: Chapter 6 and Folium Tutorial

    Fill in the following functions in a program that maps GIS data from NYC OpenData CSV files and marks the current location and closest point:

    • getData() that asks the user for the name of the CSV and returns a dataframe of the contents.
    • getColumnNames() that asks the user for the exact name of the columns that contains the latitude and longitude and returns those values as a tuple. Since the NYC OpenData files use different names for the columns in different datasets (such as "Lat", "Latitude", "LATITUDE" for latitude), the program asks for the name of the column as well as the name of the data file.
    • getLocale() asks the user for latitude and longitude of the user's current location and returns those floating points numbers.
    • computeDist() that computes the squared distance between two points (x1,y1) and (x2,y2):
      (x1-x2)2 + (y1-y2)2

    A sample run to find the closest CUNY campus to the Brooklyn Navy Yard:

    Enter CSV file name: cunyLocations.csv
    Enter column name for latitude: Latitude
    Enter column name for longitude: Longitude
    Enter current latitude: 40.7021
    Enter current longitude: -73.9708
    Enter output file: closestCUNY.html
    

    which would produce the html file:

    A template program, closestPoint.py, is available on the CSci 127 repo on github. 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).

    Hint: See Lab 9.

  • Due Date: 22 November Reading: Chapter 8

    Modify the program from Lab 10 that makes a turtle walk 100 times. Each "walk" is 10 steps forward and the turtle can turn 0,1,2,...,359 degrees (chosen randomly) at the beginning of each walk.

    A sample run of your program:

  • Due Date: 28 November Reading: Chapter 8

    Write a program that asks the user to enter a string. If the user enters an empty string, your program should continue prompting the user for a new string until they enter a non-empty string. Your program should then print out the string entered.

    A sample run of your program:

    Enter a non-empty string:
    That was empty.  Try again.
    Enter a non-empty string:
    That was empty.  Try again.
    Enter a non-empty string: Mihi cura futuri
    You entered: Mihi cura futuri
    

    Hint: See Lab 10.

  • Due Date: 29 November Reading: Ubuntu Terminal Reference Sheet

    Write an Unix shell script that does the following:

    • Creates a directory, projectFiles.
    • Creates 3 additional directories (as subdirectories of projectFiles): source, data, and results.
    Submit a single text file containing your shell commands. See Lab 10.

    Hint: See Lab 10.

  • Due Date: 30 November Reading: MIPS Wikibooks

    Write a simplified machine language program that prints: I use MIPS!

    See Lab 11 for details on submitting the simplified machine language programs.

    Hint: You may find the following table useful:


    (Image from wikimedia commons)

    Hint: The grading scripts are matching the phrase exactly, so, you need to include the spacing and punctuation.

  • Due Date: 1 December Reading: MIPS Wikibooks

    Write a simplified machine language program that has register $s0 loop through the numbers 0, 5, 10, ..., 50.

    See Lab 11 for details on submitting the simplified machine language programs.

  • Due Date: 2 December Reading: Ubuntu Terminal Reference Sheet

    Using Unix shell commands, write a script that counts the number of .py files in current working directory.

    Hint: See Lab 11.

  • Due Date: 5 December Reading: Cplusplus Tutorial

    Write a C++ program that prints "Hello, World!" and "Hello, C++!" in two separate lines to the screen.

    Hint: See Lab 12 for getting started with C++.

  • Due Date: 6 December Reading: Cplusplus Tutorial

    Write a C++ program that will print "Mihi cura futuri" 10 times.

    The output of your program should be:

    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    Mihi cura futuri
    

    Hint: See Lab 12 for getting started with C++.

  • Due Date: 7 December Reading: Cplusplus Tutorial

    Write a C++ program that converts kilometers to miles. Your program should prompt the user for the number of kilometers and then print out the number of miles.

    A useful formula: miles = 0.621371* kilometers.

    See Lab 4 for designing Input-Process-Output programs and Lab 12 for getting started with C++.

  • Due Date: 8 December Reading: Cplusplus Tutorial

    Write a C++ program program that asks the user for a number and draws a triangle of that height and width using 'character graphics'.

    A sample run:

    Enter a number:  6
    *
    **
    ***
    ****
    *****
    ******
    

    Another sample run:

    Enter a number:  3
    *
    **
    ***
    

  • Due Date: 9 December Reading: Cplusplus Tutorial

    Write a C++ program that asks the user for the month of the year (as a number), and prints

    • "Happy Winter" if it is strictly before 3 or strictly larger than 11,
    • "Happy Spring" if it is 3 or greater, but strictly before 7, and
    • "Happy Summer" if it is 7 or greater, but strictly before 9, and
    • "Happy Fall" otherwise.

    A sample run:

    Enter month (as a number):  12
    Happy Winter
    

    Another sample run:

    Enter month (as a number):  8
    Happy Summer
    

    And another run:

    Enter month (as a number):  11
    Happy Fall
    
  • Due Date: 12 December Reading: Cplusplus Tutorial

    Write a C++ program that asks the user for the year born, and continue asking until the number entered that is 2018 or earlier.

    A sample run:

    Please enter year born: 2023
    Entered a future year
    Please enter year born: 2025
    Entered a future year
    Please enter year born: 2000
    You entered:  2000
    

    Hint: See Lab 10 for similar programs in Python. Rewrite in C++.

  • Due Date: 13 December Reading: Cplusplus Tutorial

    Write a complete C++ program that prints the change in population of the the United States:

        p = p + Bp - Dp
    
    where p is the population, B is the birth rate of 12.4 births for every 1000 people (12.4/1000) each year, and D is the death rate of 8.4 for every 1000 people (8.4/1000). In 2017, the population of United States was 325.7 million. Your program should ask the user for the number of years and print expected population over those years starting from 2017. Each line should have: the year and the population (in millions).

    A sample run:

    Please enter the number of years: 10
    Year 2017  325.70
    Year 2018  327.00
    Year 2019  328.31
    Year 2020  329.62
    Year 2021  330.94
    Year 2022  332.27
    Year 2023  333.60
    Year 2024  334.93
    Year 2025  336.27
    Year 2026  337.61
    

    Note: if you would like to make the output a bit prettier, you can include a command to limit the number of places after the decimal point printed to 2 before you print:

    cout << setprecision(2) << fixed;

  • Due Date: 14 December Reading: Cplusplus Tutorial

    Write a C++ program that asks the user for a whole number between -31 and 31 and prints out the number in "two's complement" notation, using the following algorithm:

    1. Ask the user for a number, n.
    2. If the number is negative, print a 1 and let x = 32 + n.
    3. If the number is not negative, print a 0 and let x = n.
    4. Let b = 16.
    5. While b > 0.5:
      1. If x >= b then print 1, otherwise print 0
      2. Let x be the remainder of dividing x by b.
      3. Let b be b/2.
    6. Print a new line ('\n').

    A sample run:

    Enter a number:  8
    001000
    

    Another run:

    Enter a number: -1
    111111
    
  • Here's xkcd on the simplicity of Python: