Question

This program will provide the user the tools to make up trains from a file of...

This program will provide the user the tools to make up trains from a file of available cars. The car data will be the reporting identifier, car type, weight (in tons) and length (in feet) for each car. The user can select to make up a train by total weight, total length or car type. The user will be able to display any train’s consist, and will be able to delete a train (returning the cars to the pool of available cars.)

General algorithm

Read the data file, storing to list of lists ( one car per sublist )

If file did not open or is empty, display message and exit

As long as quit option not selected:

Display menu, get choice

Make train by weight – pick first available cars that do not cause total weight to exceed desired weight. Some cars may be skipped. Total weight may be less than desired weight if not enough available cars.

Make train by length – pick first available cars that do not cause total length to exceed desired length. Some cars may be skipped. Total length may be less than the desired length if not enough available cars.

Make train by car type – pick first available cars of a specified type, up the maximum number of cars specified. Number of cars may be less than the desired number if not enough available cars.

Display train – present the range of train numbers (1 to highest assigned), display each cars’ data. If train is empty, display message.

Delete train – present range of train numbers (1 to highest assigned ). Delete cars in train’s list and reset all cars in pool to indicate available.

Quit – display message, end program.

Making up a train

Start by making an empty list for the current train.

You will make a train by looking through the car lists, one at a time, checking the type, weight or length field to determine if it can be added the train being built and if the car is available.

If building by weight or length, you’ll add a car’s weight or length to a total as you go along. Test each car that its value, when added to the total, does not exceed the desired total. If it can be added without exceeding the desired total, set the last field (the 0) to the train number, then append that car to the train. (It will remain in the master list, but now is marked as in a train.)

If building by car type, you won’t be concerned about weight or length. Keep adding available cars of the desired type until the maximum number of cars is reached, or there are no more cars.

In either type of train building, continue examining all cars until either the maximum value (weight, length, number of cars) has been reached, or there are no more cars to check.

When the new train is complete, return it to main( ).

Functions:

Your program must have the following functions:

main( ) starts the program. Opens and checks the data file, calls the read_file, loops as long as quit option not chosen, executing the selected option.

read_file( ) given open file handle, reads data into list of lists. Returns list, empty list if no data

choose_option( ) displays menu of options, gets and validates option. Return choice as an integer

choose_car_type( ) displays list of car types, get user selection. Validate selection, return car type as string

make_train_wt( ) given list of cars, limit and train number, selects cars to make selected train type. Marks cars with train number in main car list. Return train as a list

make_train_len( ) given list of cars, limit and train number, selects cars to make selected train type. Marks cars with train number in main car list. Return train as a list

make_train_type( ) given list of cars, limit, car type and train number, selects cars to make selected train type. Marks cars with train number in main car list. Return train as a list

display_train( ) given a list that holds one train, display the cars’ information in formatted form

delete_train( ) given list of cars and train number, marks all of trains cars as available (0)

I'm writing this in Python Geany.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

Code as text:

''' read data from a file into list of lits and return it '''

def read_file(f):

car_list = []

for line in f.readlines():

car = [x for x in line.strip().split(' ')]

car.append(0)

car_list.append(car)

return car_list

''' display menu of options, return choice as integer. '''

def choose_option():

print("1. Make train by weight")

print("2. Make train by length")

print("3. Make train by car type")

print("4. Display train")

print("5. Delete train")

print("0. Quit")

option = int(input("Enter option: "))

while option < 0 or option > 5:

print("Invalid option! Try again.")

option = int(input("Enter option: "))

return option

'''' displays list of car types, get user selection and return it '''

def choose_car_type():

car_types = ['boxcar', 'flatcar', 'goods', 'wagon']

print("Available car types are: ")

for car in car_types:

print(car, end=' ')

print("")

choice = input("Choose car type: ")

while choice not in car_types:

print("Invalid choice! Try again.")

choice = input("Choose car type: ")

return choice

''' makes a train by weight '''

def make_train_wt(cars_list, limit, train_num):

total_wt = 0.0

train = []

for car in cars_list:

car_wt = float(car[1])

if (car[3] == 0) and (total_wt + car_wt < limit):

total_wt += car_wt

car[3] = train_num

train.append(car)

return train

''' makes train by length '''

def make_train_len(cars_list, limit, train_num):

total_len = 0

train = []

for car in cars_list:

car_len = float(car[2])

if (car[3] == 0) and (total_len + car_len < limit):

total_len += car_len

car[3] = train_num

train.append(car)

return train

''' makes train by car type '''

def make_train_type(cars_list, limit, cartype, train_num):

total_cars = 0

train = []

for car in cars_list:

car_type = car[0]

if (car[3] == 0) and (car_type == cartype):

total_cars += 1

car[3] = train_num

train.append(car)

if total_cars == limit:

break

return train

''' display the cars in a train '''

def display_train(train):

if len(train) == 0:

print("The train is empty!")

return

print("The train is: ")

i = 0

for car in train:

i += 1

print("Car #", i)

print("Type: %s\t Weight: %stons\t Length: %sfeets" % (car[0], car[1], car[2]))

''' mark cars as available '''

def delete_train(cars_list, train_num):

for car in cars_list:

if car[3] == train_num:

car[3] = 0

''' main driver function '''

def main():

try:

carsfile = open('cars.txt', 'r')

cars_list = read_file(carsfile)

carsfile.close()

except IOError:

print("Error! File not found.")

return

trains = []

train_num = 0

while True:

option = choose_option()

if option == 1:

weight = float(input("Enter desired weight: "))

train_num += 1

trains.append(make_train_wt(cars_list, weight, train_num))

print('Train Created! Train number is', train_num)

if option == 2:

length = float(input("Enter desired length: "))

train_num += 1

trains.append(make_train_len(cars_list, length, train_num))

print('Train Created! Train number is', train_num)

if option == 3:

cartype = choose_car_type()

limit = int(input("Enter number of cars: "))

train_num += 1

trains.append(make_train_type(cars_list, limit, cartype, train_num))

print('Train Created! Train number is', train_num)

if option == 4:

num = int(input("Enter train number: "))

display_train(trains[num - 1])

if option == 5:

num = int(input("Enter train number: "))

delete_train(cars_list, num)

if option == 0:

print("Exiting...")

return

# call to main function

if __name__ == "__main__":

main()

Sample run:

Input file: cars.txt

Output:

Add a comment
Know the answer?
Add Answer to:
This program will provide the user the tools to make up trains from a file of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Using the following definition (List.h file) for a list, implement the member functions (methods) for the...

    Using the following definition (List.h file) for a list, implement the member functions (methods) for the List class and store the implementation in a List.cpp file. Use a doubly linked list to implement the list. Write the client code (the main method and other non-class methods) and put in file driver.cpp. file: List.h typedef int ElementType; class node{ ​ElementType data; ​node * next; node* prev; }; class List { public: List(); //Create an empty list bool Empty(); // return true...

  • Create a java program that reads an input file named Friends.txt containing a list 4 names...

    Create a java program that reads an input file named Friends.txt containing a list 4 names (create this file using Notepad) and builds an ArrayList with them. Use sout<tab> to display a menu asking the user what they want to do:   1. Add a new name   2. Change a name 3. Delete a name 4. Print the list   or 5. Quit    When the user selects Quit your app creates a new friends.txt output file. Use methods: main( ) shouldn’t do...

  • Write a contacts database program that presents the user with a menu that allows the user...

    Write a contacts database program that presents the user with a menu that allows the user to select between the following options: (In Java) Save a contact. Search for a contact. Print all contacts out to the screen. Quit If the user selects the first option, the user is prompted to enter a person's name and phone number which will get saved at the end of a file named contacts.txt. If the user selects the second option, the program prompts...

  • C++ program Write a C++ program to manage a hospital system, the system mainly uses file...

    C++ program Write a C++ program to manage a hospital system, the system mainly uses file handling to perform basic operations like how to add, edit, search, and delete record. Write the following functions: 1. hospital_menu: This function will display the following menu and prompt the user to enter her/his option. The system will keep showing the menu repeatedly until the user selects option 'e' from the menu. Arkansas Children Hospital a. Add new patient record b. Search record c....

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

  • Assignment #2: List - Array Implementation Review pages 6-7 in "From Java to C++" notes. Due...

    Assignment #2: List - Array Implementation Review pages 6-7 in "From Java to C++" notes. Due Friday, February 9th, 2017 @ 11:59PM EST Directions Create a List object. Using the following definition (List.h file is also in the repository for your convenience) for a list, implement the member functions (methods) for the List class and store the implementation in a file called List.cpp. Use an array to implement the list. Write the client code (the main method and other non-class...

  • Write the following program in C++. Review structures, pointers and dynamic memory allocation from CSIT 839....

    Write the following program in C++. Review structures, pointers and dynamic memory allocation from CSIT 839. Also, review pointers and dynamic memory allocation posted here under Pages. For sorting, you can refer to the textbook for Co Sci 839 or google "C++ sort functions". I've also included under files, a sample C++ source file named sort_binsearch.cpp which gives an example of both sorting and binary search. The Bubble sort is the simplest. For binary search too, you can refer to...

  • DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to...

    DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to add new phone contacts, display a list of all contacts, search for a specific contact by name, delete a specific contact. The program should provide the user with a console or command line choice menu about possible actions that they can perform. The choices should be the following: 1. Display list of all contacts. 2. Add a new contact. 3. Search for a contact...

  • The language is C++ for visual studio express 2013 for windows create a TicketManager class and...

    The language is C++ for visual studio express 2013 for windows create a TicketManager class and a program that uses the class to sell tickets for a performance at a theater. Here are all the specs. This is an intense program, please follow all instructions carefully. -I am only creating the client program that uses the class and all it's functions -The client program is a menu-driven program that provides the user with box office options for a theater and...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT