Python WS19PB02 Answers

  1. Wednesday, April 24, 2019:
  2. Monday, April 29, 2019
    """
    Enter your weight and length of time you train a day.
    Your weight and time will give us your total calories burned.
    """
    
    time = int(input('HOW MANY MINTUES TO YOU TRAIN A DAY?'))
    weight = int(input('HOW MUCH DO YOU WEIGH?'))
    calories = time * 13.2
    
    if weight <= 150:
        print(calories)
    else:
        calories = time * 17.9
        print(calories)
    
    HOW MANY MINTUES TO YOU TRAIN A DAY?10
    HOW MUCH DO YOU WEIGH?200
    179.0
    

    The multiplication by 13.2 is wasted effort if the user weighs more than 150 pounds. Put the two multiplications side by side.

    """
    Enter your weight and length of time you train a day.
    Your weight and time will give us your total calories burned.
    """
    import sys
    
    time = int(input('How many minutes do you train a day? '))
    weight = int(input('How much do you weigh? '))
    
    if weight <= 150:
        calories = 13.2 * time
    else:
        calories = 17.9 * time   #Heavy people burn more calories per minute.
    
    print(f'You burn {calories} calories per day.')
    sys.exit(0)
    

    explode_seq.py

    """
    This is a function that takes in a natural number n.  It assumes the user will
    enter an integer, but not necessarily a natural number.
    """
    
    def explode_seq(n):
    
        cond = True
    
        while cond:
            if n > 0:
                cond = False
            else:
                n = int(input('Enter an integer greater than 0: '))
    
        if n == 1:
            return 1
        elif n == 2:
            return 2
        else:
            return explode_seq(n-1) + explode_seq(n-2)
    
    i = int(input('Enter an integer greater than 0: '))
    print(f'explode_seq({i}) = {explode_seq(i)}')
    
    Enter an integer greater than 0: 4
    explode_seq(4) = 5
    
    """
    This is a function that takes in a natural number n.  It assumes the user will
    enter an integer, but not necessarily a natural number.
    """
    
    import sys
    
    def explode_seq(n):
    
        while n <= 0:
            n = int(input('Enter an integer greater than 0: '))
    
        if n < 3:
            return n
        else:
            return explode_seq(n-1) + explode_seq(n-2)
    
    i = int(input('Enter an integer greater than 0: '))
    print(f'explode_seq({i}) = {explode_seq(i)}')
    sys.exit(0)
    
        return n if n < 3 else explode_seq(n-1) + explode_seq(n-2)
    

    If we do all the input before the explode_seq function is called, the first number printed by the print statement can be correct.

    """
    This function takes in a natural number n and returns the Fibonacci number.
    """
    
    import sys
    
    def explode_seq(n):
        return n if n < 3 else explode_seq(n - 1) + explode_seq(n - 2)
    
    #Assume the user will enter an integer.
    #Keep looping until the integer is a natural number.
    
    while True:
        i = int(input('Enter an integer greater than 0: '))
        if i > 0:
            break
    
    print(f'explode_seq({i}) = {explode_seq(i)}')
    sys.exit(0)
    

    HW_4_24_2019

    Look up each season in a dictionary.

    '''
    smalltalk.py
    
    brief conversation
    '''
    
    import sys
    
    name = input("Hello, my name is Py. What is your name? ")
    print(f"Hello, {name}! It is a pleasure to make your acquaintance.")
    
    author = input("Let's take a moment to get to know one another. I am curious, who is your favorite author? ")
    print("I love their work.")
    
    musician = input("Who is your favorite musician? ")
    print(f"What a coincidence. We both like {author} and {musician}!")
    
    season = input("We are really getting to know one another. Tell me, what is your favorite season? ")
    season = season.lower()   #Change season to lowercase.
    
    comments = {   #a dictionary
        "spring": "Spring is very unpredictable here in New York, but anything is better than winter.",
        "summer": "Now we are cooking with gas! Summer is definitely number 1 on my list. Let's be sure to chat again in the near future. Goodbye for now.",
        "fall":   "Aaah, the calm before the storm. I must say, the autumn foliage is a thing of beauty.",
        "winter": "Ewww! We are not as compatible as I once thought. This is where I leave you. Goodbye."
    }
    
    try:
        print(comments[season]);
    except KeyError:
        print(f'Sorry, I don\'t know the season "{season}".')
        sys.exit(1)
    
    sys.exit(0)
    
  3. Wednesday, May 1, 2019:

    position.py

    pip3 list
    pip3 install --user numpy
    pip3 install --user matplotlib
    pip3 list
    
    for i in range(len(t_vals)):
        print(f" {round(t_vals[i], 2):.2f} | {round(y_vals[i], 2):.2f}")
    

  4. Thursday, May 2, 2019:
    """
    Print graph paper to user specifications.
    """
    
    import sys
    
    brows = int(input("How many rows of boxes? "))
    bcols = int(input("How many columns of boxes? "))
    srows = int(input("How many rows of spaces in each box? "))
    scols = int(input("How many columns of spaces in each box? "))
    
    for brow in range(brows):
        for bcol in range(bcols):
            print("+", end = "")
            for srow in range(scols):
                print("-", end = "")
        print("+")
    
        for srow in range(srows):
            for bcol in range(bcols):
                print("|", end = "")
                for srow in range(scols):
                    print(" ", end = "")
            print("|")
    
    for bcol in range(bcols):
        print("+", end = "")
        for srow in range(scols):
            print("-", end = "")
    print("+")
    
    sys.exit(0)
    
    """
    Print graph paper to user specifications using string multiplication.
    """
    
    import sys
    
    brows = int(input("How many rows of boxes? "))
    bcols = int(input("How many columns of boxes? "))
    srows = int(input("How many rows of spaces in each box? "))
    scols = int(input("How many columns of spaces in each box? "))
    
    dashes = "+" + scols * "-"
    spaces = "|" + scols * " "
    
    horizontalLine = bcols * dashes + "+\n"
    horizontalJail = bcols * spaces + "|\n"
    
    rowOfBoxes = horizontalLine + srows * horizontalJail
    graphPaper = brows * rowOfBoxes + horizontalLine
    
    print(graphPaper, end = "")
    sys.exit(0)
    
  5. Monday, May 6, 2019:
  6. Wednesday, May 8, 2019:
  7. Thursday, May 9, 2019:
    listhw.py
    Checking to see if 3 exists in the list
    The Element Exists
    

    See the in operator here.

    # Check element existence.
    
    checklist = [1, 4, 5, 9, 7, 2, 3]
    
    print("Checking to see if 3 exists in the list.")
    
    if 3 in checklist:
        print("The element 3 exists.")
    

    heat_equation.py

    """
    
    heat_equation.py
    
    This file uses the finite difference method to solve the one-dimensional
    heat equation.  A rod of length 10 is discretized uniformly with steps of
    0.1.  The left endpoint is at -5, the right endpoint at 5.  Alpha is set
    at 0.5.  The initial condition has temperature 20 at the left endpoint and
    zero everywhere else.  The boundary conditions fix the left endpoint at 20 and
    the right endpoint at 0.  The results are plotted after 0.10 seconds.
    The problem is from a Numerical Methods class I took where we were
    coding in Mathematica.  I wanted to recode it using Python.
    """
    
    import sys
    import numpy as np
    import matplotlib.pyplot as plt
    
    ### Calculate lamd based off of given values of alpha, deltax, deltat.
    
    alpha = 0.5
    deltax = 0.1
    deltat = 0.01
    lamd = alpha * deltat / (deltax * deltax)
    
    ### list of x values from -5 to 5 in steps of deltax
    x0 = -5.0
    
    #Divide the rod into 100 intervals.  Each interval is of length 1/10
    n = 101
    xvec = [round(i / 10 + x0, 2) for i in range(n)] #list comprehension
    
    """
    temperature along rod at time t = 0, 20 at left endpoint,
    0 everywhere else
    """
    
    uvec = [0.0] * n
    uvec[0] = 20.0
    
    ### construct matrix A
    #Initially A is a two-dimensional list (101 by 101) of zeroes.
    
    A = [[0.0 for col in range(n)] for row in range(n)] #list comprehension
    A[0][0] = A[n-1][n-1] = 1.0
    
    # construct rows 2 through second-to-last row
    #Diagonal stripe from upper left corner to lower right.
    
    for i in range(1, n - 1):
        A[i][i] = 1 - 2 * lamd
        A[i][i - 1] = A[i][i + 1] = lamd
    
    A = np.array(A)
    uvec = np.array(uvec)
    xvec = np.array(xvec)
    
    nt = 10   #number of time intervals
    for i in range(nt):
        uvec = A.dot(uvec)
    
    plt.scatter(xvec, uvec, color = 'red', s = 7)
    plt.title(f'Temperature along rod at t = {nt * deltat} s')
    plt.xlabel('position')
    plt.ylabel('temperature')
    plt.show()
    
    sys.exit(0)
    
  8. Monday, May 13, 2019
  9. Wednesday, May 15, 2019

    vowel.py

    Put a docstring at the top of the Python program. The program fails to run because there are no variables named fileContent and o (lowercase O). Check for exceptions when you open an input file.

    "Print each vowel in an input file, followed by the vowel's index in the file."
    
    import sys
    
    filePath = input("Enter File Path: ")
    print()
    
    try:
        fileObject = open(filePath)
    except FileNotFoundError:
        print(f"Sorry, could not find file \"{filePath}\".")
        sys.exit(1)
    except PermissionError:
        print(f"Sorry, no permission to open file \"{filePath}\".")
        sys.exit(1)
    
    fileContent = fileObject.read()
    fileObject.close()
    
    print("""\
    CONTENTS OF THE FILE:
    {fileContent}
    LIST OF VOWELS AND ITS INDICES:""")
    
    for i, c in enumerate(fileContent):
        if c in "aeiou":
            print(f"{c}:{i},", end = "")
    
    sys.exit(0)
    

    new.py

    import sys
    import urllib.request
    import csv
    
    url = "https://data.cityofnewyork.us/api/views/32y8-s55c/rows.csv"
    
    try:
        fileFromUrl = urllib.request.urlopen(url)
    except urllib.error.URLError as error:
        print(error, file = sys.stderr)
        sys.exit(1)
    
    sequenceOfBytes = fileFromUrl.read() #Read whole file into one big sequenceOfBytes.
    fileFromUrl.close()
    
    try:
        s = sequenceOfBytes.decode("utf-8")    #s is a string
    except UnicodeError as unicodeError:
        print(unicodeError, file = sys.stderr)
        sys.exit(1)
    
    lines = csv.reader(s.splitlines())
    print("FDNY NY DEATHS")
    
    for line in lines:
        rank, name, unit, date = line[:4] #the 1st 4 strings in the list of strings
        print(f"{rank:18} {name:22} {unit:12} {date}")
    
    sys.exit(0)
    
  10. Thursday, May 16, 2019:

    Meter.py

    """List the parking meters in Jamacia Queens"""
    
    import sys
    import urllib.request
    import csv   #Comma-Separated Values
    
    #Database is at
    #https://data.cityofnewyork.us/Transportation/Parking-Meters-GPS-Coodinates-and-Status/5jsj-cq4s
    url = "https://data.cityofnewyork.us/api/views/82u8-6npn/rows.csv"
    
    try:
        fileFromUrl = urllib.request.urlopen(url)
    except urllib.error.URLError as error:
        print("urllib.error.URLError", error)
        sys.exit(1)
    
    sequenceOfBytes = fileFromUrl.read() #Read whole file into one big sequenceOfBytes.
    fileFromUrl.close()
    
    try:
        s = sequenceOfBytes.decode("utf-8")    #s is a string
    except UnicodeError as unicodeError:
        print(unicodeError)
        sys.exit(1)
    
    lines = csv.reader(s.splitlines())
    
    
    print(next(lines))   #Print the first line
    
    for line in lines:
        MeterType = line[0]
        LONG = float(line[1])     #longitude
        the_geom = line[2]
        MeterNo = int(line[3])
        LAT = float(line[4])   #latitude
        Status = line[5]                               #type of meter
    
        print(f"{MeterType} {LONG:12.8f} {the_geom} {MeterNo} {LAT:11.8f} {Status}")
    
    fileFromString.close()
    sys.exit(0)
    
    ['MeterType', 'LONG', 'the_geom', 'MeterNo', 'LAT', 'Status']
    Strada -73.86517020 POINT (-73.86517020266234 40.6770120488885) 3773004 (40.67701205) Active
    Strada -73.92504068 POINT (-73.9250406819429 40.76123920493658) 4953003 (40.76123920) Active
    Strada -73.85479441 POINT (-73.85479441192734 40.727926680024865) 4173077 (40.72792668) Active
    
  11. Monday, May 20, 2019:

    tictactoegame.py

    """
    tictactoegame.py
    
    This is a complete tictactoegame.  It needs to be edited/consolidated for efficiency.
    """
    
    import sys
    
    def display_board1(m):   #m is a list of strings
        print(f"""\
           |       |
       {m[6]}   |   {m[7]}   |   {m[8]}
           |       |
    - - - - - - - - - - - -
           |       |
       {m[3]}   |   {m[4]}   |   {m[5]}
           |       |
    - - - - - - - - - - - -
           |       |
       {m[0]}   |   {m[1]}   |   {m[2]}
           |       |""")
    
    def display_board(my_list):
        #Each line of the board is 24 characters, including the invisible newline.
        board = """\
    .......|.......|.......
    .......|.......|.......
    .......|.......|.......
    - - - - - - - - - - - -
    .......|.......|.......
    .......|.......|.......
    .......|.......|.......
    - - - - - - - - - - - -
    .......|.......|.......
    .......|.......|.......
    .......|.......|......."""
    
        positions = [
           9 * 24 +  3, #my_list[0]
           9 * 24 + 11, #my_list[1]
           9 * 24 + 19, #my_list[2]
    
           5 * 24 +  3, #my_list[3]
           5 * 24 + 11, #my_list[4]
           5 * 24 + 19, #my_list[5]
    
           1 * 24 +  3, #my_list[6]
           1 * 24 + 11, #my_list[7]
           1 * 24 + 19  #my_list[8]
        ]
    
        boardList = list(board)   #Convert the immutable string to a mutable list.
    
        for i in range(len(my_list)):
            boardList[positions[i]] = my_list[i]
    
        print("".join(boardList).replace(".", " "))
    
    # Greeting
    print('Welcome to Tic Tac Toe.')
    
    #Keep looping as long as the user wants to play another game.
    while True:
    
        # initial empty board
        board_list = (3 * 3) * [' ']
    
        #The user will think the players are numbered 1 and 2
        #(people like to count starting at 1),
        #but for internal purposes they will be numbered 0 and 1
        #(computers like to count starting at 0).
    
        while True:
            choose_sides = input('Player 1, do you want to be x or o? ').lower()
            if choose_sides in "xo":
                break
    
        if choose_sides == 'x':
            names = ['x', 'o'] #player 0 is 'x', player 1 is 'o'
        else:
            names = ['o', 'x'] #player 0 is 'o', player 1 is 'x'
    
        #Keep looping as long as this game is not yet finished.
        #It's player 0's turn to move when turn is even.
    
        for turn in range(3 * 3):
            #Invite player number turn % 2 to make a move.
            while True:
                try:
                    position = int(input(f'Player {turn % 2 + 1}, choose a position: '))
                except ValueError:
                    continue
                break
    
            position -= 1
            while position not in range(len(board_list)):
                position = int(input(f'Player {turn % 2 + 1}, choose a position '
                    'in the range 1 to {len(board_list)} inclusive: '))
    
            while board_list[position] != ' ':
                position = int(input(f'Player {turn % 2 + 1}, that position is filled.\n\
    Pick an empty position: '))
    
            board_list[position] = names[turn % 2]
            print(5 * '\n')
            display_board(board_list)
            print(5 * '\n')
            line = 3 * [names[turn % 2]]   #a list of 3 strings
    
            if (
                board_list[0:3] == line or #rows
                board_list[3:6] == line or
                board_list[6:9] == line or
    
                board_list[0::3] == line or #columns
                board_list[1::3] == line or
                board_list[2::3] == line or
    
                board_list[0::4] == line or #diagonals
                board_list[2:7:2] == line):
                break;
    
        #Arrive here when someone has won.
    
        print(f'Player {turn % 2 + 1} (a.k.a. "{names[turn % 2]}") wins!!!')
        choice = input('Would you like to play again? Enter Y or N: ').lower()
        if choice != 'y':
            break
    
    print('Goodbye!')
    sys.exit(0)
    
  12. Wednesday, May 22, 2019
  13. Thursday, May 23, 2019. No class on Monday, May 27 (Memorial Day).
  14. Wednesday, May 29, 2019
  15. Thursday, May 30, 2019
  16. Monday, June 3, 2019
  17. Wednesday, June 5, 2019
  18. Thursday, June 6, 2019
  19. Monday, June 10, 2019
  20. Wednesday, June 12, 2019
  21. Thursday, June 13, 2019
  22. Monday, June 17, 2019
  23. Wednesday, June 19, 2019
  24. Thursday, June 20, 2019
  25. Monday, June 24, 2019