Question

In: Computer Science

Study and consider the following Python code, which tracks the movement of a balloon given the...

Study and consider the following Python code, which tracks the movement of a balloon given the wind direction and distance

# Establish Balloon Behavior(Parts, Direction, Distance)
n = int(input('Input number of parts: '))
northDistance = 0
eastDistance = 0
balloonOutput = []
for i in range(0, n):
    outputLine = []
    print('Part %d- ' % (i + 1), end='')
    direction = input('What direction is the balloon heading? type N, E, S or W ')
    direction = direction.upper()

    while len(direction) != 1 or \
            not(direction == 'N' \
            or direction == 'E' \
            or direction == 'S' \
            or direction == 'W'):
        direction = input('Bad input, try again- What direction is the balloon heading? type N, E, S or W ')
        direction = direction.upper()

    outputLine += [direction]

    distance = int(input('How many inches did it travel? '))
    while distance <= 0:
        distance = int(input('Bad input, try again- How many inches did it travel? '))

    outputLine += [distance]

    balloonOutput += [outputLine]

    if direction == 'N':
        northDistance = northDistance + distance
    elif direction == 'E':
        eastDistance = eastDistance + distance
    elif direction == 'S':
        northDistance = northDistance - distance
    elif direction == 'W':
        eastDistance = eastDistance - distance

print('Part Direction Distance')
print('____ _________ ________')
for i in range(0, n):
    print('%2d   %s         %d' % (i+1, balloonOutput[i][0], balloonOutput[i][1]))

verticalDirection = ''
verticalLocation = 0
if northDistance > 0:
    verticalDirection = 'N'
    
verticalLocation = northDistance
elif northDistance < 0:
    verticalDirection = 'S'
    
verticalLocation = -northDistance

horizontalDirection = ''
horizontalLocation = 0
if eastDistance > 0:
    horizontalDirection = 'E'
    
horizontalLocation = eastDistance
elif eastDistance < 0:
    horizontalDirection = 'W'
    
horizontalLocation = -eastDistance

finalDirection = ''
print('~~~~~Final Location of Balloon~~~~~~')
if verticalLocation != 0:
    print(' %s %d' % (verticalDirection, verticalLocation), end='')

if horizontalLocation != 0:
    print(' %s %d' % (horizontalDirection, horizontalLocation))

if verticalLocation ==0 and horizontalLocation == 0:
    print('   NO CHANGE')

1) Modify the above code to no longer prompt for input (hence remove prompts and input function calls). Make the assumption that the data file always has valid inputs. Remove all unnecessary (not needed for use with data file) code.

2) Open, read, and close the provided Comma Separated Value (CSV) file “BalloonMovements.csv”, which contains

  1. Number of "parts" (derived from number of rows in the file)
  2. Distance from each part (data in the 1st column before comma in the file)
  3. Direction of each part (data in the 2nd column after comma in the file)

BallonMovements.cvs

4 e
3 n
3 W
11 N
2 w
5 w
5 n
1 s
4 N
3 n

3.) Add more code comments explaining your new code and what the remaining original code does. Using code comments (#), comment each major section and specifically what the following lines do:

  • northDistance = 0 (Why set value to 0?)
  • outputLine = [] (What does this line do?)
  • outputLine += [distance] (What does this line do?)
    balloonOutput += [outputLine] (What does this line do?)
  • for i in range(0, n): (Why does range start at 0?)
  • print('Part %d- ' % (i + 1), end='') (Why i+1 and what does end=’’ do?)
  • direction = direction.upper() (Why convert to upper case?)

Output after running the input file is:

Part Direction Distance

____ _________ ________

1        E                 4

2        N                 3

3        W                3

4        N                11

5        W                2

6        W                5

7        N                 5

8        S                 1

9        N                 4

10      N                 3

~~~~~Final Location of Balloon~~~~~~

   N 25 W 6

Solutions

Expert Solution

Here is your updated code:

import csv

# Establish Balloon Behavior(Parts, Direction, Distance)
# Initialize balloon start position as N = 0 and E = 0
northDistance = 0 
eastDistance = 0

# List to store balloon output
balloonOutput = []

# Open BalloonMovements file
with open("BalloonMovements.csv") as bm:
    # Get values from csv file delimited by tab
    csvReader = csv.reader(bm, delimiter="\t")

    n = csvReader.line_num # Number of lines in file

    # Read each row from file
    for row in csvReader:
        # Declare list of output lines 
        outputLine = []

        # Convert Direction to uppercase letter
        direction = row[1].upper()

        # insert direction in outputLine list
        outputLine += [direction]

        # Read distance from file
        distance = int(row[0])

        # Insert distance in outputLine
        outputLine += [distance]

        # Append outputLine list at the end of balloonOutput list
        balloonOutput += [outputLine]

        if direction == 'N':
            northDistance = northDistance + distance
        elif direction == 'E':
            eastDistance = eastDistance + distance
        elif direction == 'S':
            northDistance = northDistance - distance
        elif direction == 'W':
            eastDistance = eastDistance - distance

print('Part Direction Distance')
print('____ _________ ________')
for i in range(0, n):
    print('%2d   %s         %d' % (i+1, balloonOutput[i][0], balloonOutput[i][1]))

verticalDirection = ''
verticalLocation = 0
if northDistance > 0:
    verticalDirection = 'N'
    verticalLocation = northDistance
elif northDistance < 0:
    verticalDirection = 'S'
    verticalLocation = -northDistance

horizontalDirection = ''
horizontalLocation = 0
if eastDistance > 0:
    horizontalDirection = 'E'
    horizontalLocation = eastDistance
elif eastDistance < 0:
    horizontalDirection = 'W'
    horizontalLocation = -eastDistance

finalDirection = ''
print('~~~~~Final Location of Balloon~~~~~~')
if verticalLocation != 0:
    print(' %s %d' % (verticalDirection, verticalLocation), end='')

if horizontalLocation != 0:
    print(' %s %d' % (horizontalDirection, horizontalLocation))

if verticalLocation ==0 and horizontalLocation == 0:
    print('   NO CHANGE')

Output:

Code Screenshot:


Related Solutions

Study and consider the following Python code, which tracks the movement of a balloon given the...
Study and consider the following Python code, which tracks the movement of a balloon given the wind direction and distance # Establish Balloon Behavior(Parts, Direction, Distance) n = int(input('Input number of parts: ')) northDistance = 0 eastDistance = 0 balloonOutput = [] for i in range(0, n):     outputLine = []     print('Part %d- ' % (i + 1), end='')     direction = input('What direction is the balloon heading? type N, E, S or W ')     direction = direction.upper()     while len(direction) != 1...
I'm working on python code which is substring matching. For example, the given string is input...
I'm working on python code which is substring matching. For example, the given string is input "CTTGTGATCTCGTGTCGTGGGTAG", and a substring we want to find in the main one is "GTGG". So the code will print out the position and the substrings in the main which has exactly one different position. For example, start at position 4 the substring is GTGA since there is only one letter different, and so on. Even though we know that string index starts at 0,...
Write PYTHON CODE to answer the following question: Consider the following data: x = [0, 2,...
Write PYTHON CODE to answer the following question: Consider the following data: x = [0, 2, 4, 6, 9, 11, 12, 15, 17, 19] y = [5, 6, 7, 6, 9, 8, 8, 10, 12, 12] Using Python, use least-squares regression to fit a straight line to the given data. Along with the slope and intercept, compute the standard error of the estimate and the correlation coefficient. Best fit equation y = ___ + ___ x Standard error, Sy/x =...
Write the python code that generates a normal sample with given μ and σ, and the...
Write the python code that generates a normal sample with given μ and σ, and the code that calculates m (sample mean) and s (sample standard deviation) from the sample.
Write the python code that generates a normal sample with given μ and σ, and the...
Write the python code that generates a normal sample with given μ and σ, and the code that calculates m and s from the sample. Do the same using the Bayes’ estimator assuming a prior distribution for μ.
Solve with Python: The following is the color code of the jackets of employees for a...
Solve with Python: The following is the color code of the jackets of employees for a companies annual conference. The Color is determined by the Employee category and the state in which they work. Employee Category Executive (1) Director(2) Manager(3) Worker(4) State Jacket Color State Jacket Color State Jacket Color State Jacket Color NY, NJ, PA Blue NY, NJ, PA Purple NY, NJ, PA Red NY, NJ, PA Black TX, LA, FL White TX, LA, FL Green TX, LA, FL...
Write code in Python that does the following : An anagram is when the order of...
Write code in Python that does the following : An anagram is when the order of a word can be changed to create a new word (evil, live, and vile for example). Using the dictionary provided, find all of the anagram groups. Which words contain the most anagrams? How large is this group? Here is another example: Alert, alter, and later have 3 in their group. Use the provided dict.txt as your word list, solution must also finish in less...
1. Which of the following statement about the CPI is not correct? a. the CPI tracks...
1. Which of the following statement about the CPI is not correct? a. the CPI tracks changes in the price of import goods. b. the CPI tracks changes in the price of export goods. c. the CPI is based on the same set of goods over a multi-year period. d. the CPI only includes consumption goods – it does not include capital investment goods. 2. Suppose 60% of money is held as currency and the reserve ratio is 0.3. The...
Write a python code which prints triangle of stars using a loop ( for loop )...
Write a python code which prints triangle of stars using a loop ( for loop ) Remember what 5 * "*" does The number of lines of output should be determined by the user. For example, if the user enters 3, your output should be: * ** *** If the user enters 6, the output should be: * ** *** **** ***** ****** You do NOT need to check for valid input in this program. You may assume the user...
Write a python code to Design and implement a function with no input parameter which reads...
Write a python code to Design and implement a function with no input parameter which reads a number from input (like 123). Only non-decimal numbers are valid (floating points are not valid). The number entered by the user should not be divisible by 10 and if the user enters a number that is divisible by 10 (like 560), it is considered invalid and the application should keep asking until the user enters a valid input. Once the user enters a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT