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 need this code to be written in Python: Given a dataset, D, which consists of...
I need this code to be written in Python: Given a dataset, D, which consists of (x,y) pairs, and a list of cluster assignments, C, write a function centroids(D, C) that computes the new (x,y) centroid for each cluster. Your function should return a list of the new cluster centroids, with each centroid represented as a list of x, y: def centroid(D, C):
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,...
Based on the following Python code, write a Python statement which outputs “December” when the value...
Based on the following Python code, write a Python statement which outputs “December” when the value of the Month is 12 or “November” when the value of the Month is 11 or “Neither” when value of the Month is neither 11 or 12. The user enters the value which is store in the variable namedMonth. Month = int(input("Please enter the value of the month in numerical format such as 11 for November, or 12 for December: " )) sing Python
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 =...
In Python Which initial value of x will make the following piece of code leave a...
In Python Which initial value of x will make the following piece of code leave a 9 in the final value of x? x = ____? if x < 7:    x = x + 1 x = x + 2 a. 11 b. 9 c. 7 d. None of the above Which initial value of x will make the following piece of code leave a 20 in the final value of x? x = ____? if x * 2...
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 μ.
Python! Modify the following code to include countries name which should be displaying onto the console...
Python! Modify the following code to include countries name which should be displaying onto the console from countries with the lowest population to the highest Morroco :38,964, china:1000000000, usa:400,000,000, England:55,000,000.    class Node: def __init__(self,value): self.value=value self.right=None self.left=None class BinarySearchTree: def __init__(self): self.root=None #adding the element to the bst def add(self,value): node=Node(value) temp=self.root flag=1 while(temp): flag=0 if(node.value>temp.value): if(temp.right): temp=temp.right else: temp.right=node break else: if(temp.left): temp=temp.left else: temp.left=node break if(flag): self.root=node #pre order traversing def preOrder(self,root): if(root): print(root.value) self.preOrder(root.left) self.preOrder(root.right) #in...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT