csPYTHONcs
csPYTHONcs

Reputation: 187

How am I able to make IF statements more efficient?

I have created a small program that takes user input for 'flight specifications' and outputs details of that flight based on the input. However, it is just a bunch of if statements, I was wondering if there are any useful techniques to reduce the amount of if statements and make the program more efficient.

Code:

import time

def main():

    AMS_DESTINATION = "Schiphol, Amsterdam"
    GLA_DESTINATION = "Glasgow, Scotland"
    AMS_PRICE = 150.00
    GLA_PRICE = 80.00

    # User input [LLL 0 00 L L]
    flightSpecification = str(input("Enter Flight Specification: "))
    flightDestination = flightSpecification[0:3]

    bagCount = int(flightSpecification[4])
    baggageCost = float((bagCount - 1) * 20)

    passengerAge = int(flightSpecification[6:8])

    standardMeal = 10.00  
    vegetarianMeal = 12.00
    mealType = str(flightSpecification[9])

    seatClass = str(flightSpecification[11])

    totalFlightCost = 0
    
    if flightDestination.lower() != 'ams' and flightDestination.lower() != 'gla':
        print("Please enter a valid flight specification! [LLL 0 00 L L]")
        time.sleep(2)
        main()

    if flightDestination.lower() == 'ams':
        print(f"Destination: {AMS_DESTINATION}")  
        print(f"Flight cost: £{AMS_PRICE}")
        totalFlightCost = 150

    elif flightDestination.lower() == 'gla':
        print(f"Destination: {GLA_DESTINATION}")
        print(f"Flight cost: £{GLA_PRICE}")
        totalFlightCost = 80

    print(f"Number of bags: {bagCount}")
    print(f"Baggage Cost: £{baggageCost}")

    if passengerAge > 15:
        print("Child: False")
        
    elif passengerAge <= 15:
        print("Child: True")
        totalFlightCost = totalFlightCost / 2
        standardMeal = standardMeal - 2.50
        vegetarianMeal = vegetarianMeal - 2.50
        
    elif passengerAge < 0:
        print("Age cannot be negative")
        main()

    if mealType == 'S' and seatClass != 'F':
        totalFlightCost = totalFlightCost + standardMeal
        print("Meal: Standard")
        print(f"Meal Cost: £{standardMeal}")
        
    elif mealType == 'V' and seatClass != 'F':
        totalFlightCost = totalFlightCost + vegetarianMeal
        print("Meal: Vegetarian")
        print(f"Meal Cost: £{vegetarianMeal}")

    elif mealType == 'N':
        print("Meal: None")
        print("Meal Cost: £0")

    # THIS COULD DEFINITELY BE DONE MORE EFFICIENTLY
    if seatClass == 'F':
        if mealType == 'S':
            totalFlightCost = totalFlightCost + standardMeal
            print("Meal: Standard")
            print(f"Meal Cost: FREE")
            
        elif mealType == 'V':
            totalFlightCost = totalFlightCost + vegetarianMeal
            print("Meal: Vegetarian")
            print(f"Meal Cost: £{vegetarianMeal}")
            
        print("Seating Class: First")
        totalFlightCost = totalFlightCost * 6

    elif seatClass == 'E':
        print("Seating Class: Economy")

    print(totalFlightCost)
        
        

main()

Thanks

Upvotes: 2

Views: 82

Answers (2)

quamrana
quamrana

Reputation: 39414

For such a simple program its simply not worth considering efficiency. However, going forward, if you were to be validating a batch of data with hundreds of thousands or more items, then efficiency becomes a concern.

Here are some points to consider:

# flightSpecification = str(input("Enter Flight Specification: "))
flightSpecification = input("Enter Flight Specification: ")

Note that input() always returns a str, so the str() around it is redundant.

# mealType = str(flightSpecification[9])
mealType = flightSpecification[9]

Similarly, since flightSpecification is already a str, the str() is again redundant.

#if flightDestination.lower() == 'ams':
flightDestinationLower = flightDestination.lower()
if flightDestinationLower == 'ams':

Since you do similar comparisons, it might be more efficient to perform the lower() once, rather than many times.

flightDestinationLower = flightDestination.lower()
if flightDestinationLower == 'ams':
    print(f"Destination: {AMS_DESTINATION}")  
    print(f"Flight cost: £{AMS_PRICE}")
    totalFlightCost = 150

elif flightDestinationLower == 'gla':
    print(f"Destination: {GLA_DESTINATION}")
    print(f"Flight cost: £{GLA_PRICE}")
    totalFlightCost = 80
else:
    print("Please enter a valid flight specification! [LLL 0 00 L L]")
    time.sleep(2)
    #main()
    continue

Rearrange the order of the ifs so that the else: has no need to do comparisons. Also never use recursion where you mean to use iteration.

Upvotes: 1

MaKaNu
MaKaNu

Reputation: 1018

Code

Apart from the comments already below your question, I changed a small thing in the section you mentioned could be optimized (I also removed the user input because it slows down the process, you will understand at the end):

import time

def main2():

    AMS_DESTINATION = "Schiphol, Amsterdam"
    GLA_DESTINATION = "Glasgow, Scotland"
    AMS_PRICE = 150.00
    GLA_PRICE = 80.00

    # User input [LLL 0 00 L L]
    # flightSpecification = str(input("Enter Flight Specification: "))
    flightSpecification = 'AMS 1 22 V F'
    flightDestination = flightSpecification[0:3]

    bagCount = int(flightSpecification[4])
    baggageCost = float((bagCount - 1) * 20)

    passengerAge = int(flightSpecification[6:8])

    standardMeal = 10.00  
    vegetarianMeal = 12.00
    mealType = str(flightSpecification[9])

    seatClass = str(flightSpecification[11])

    totalFlightCost = 0
    
    if flightDestination.lower() != 'ams' and flightDestination.lower() != 'gla':
        print("Please enter a valid flight specification! [LLL 0 00 L L]")
        time.sleep(2)
        main()

    if flightDestination.lower() == 'ams':
        print(f"Destination: {AMS_DESTINATION}")  
        print(f"Flight cost: £{AMS_PRICE}")
        totalFlightCost = 150

    elif flightDestination.lower() == 'gla':
        print(f"Destination: {GLA_DESTINATION}")
        print(f"Flight cost: £{GLA_PRICE}")
        totalFlightCost = 80

    print(f"Number of bags: {bagCount}")
    print(f"Baggage Cost: £{baggageCost}")

    if passengerAge > 15:
        print("Child: False")
        
    elif passengerAge <= 15:
        print("Child: True")
        totalFlightCost = totalFlightCost / 2
        standardMeal = standardMeal - 2.50
        vegetarianMeal = vegetarianMeal - 2.50
        
    elif passengerAge < 0:
        print("Age cannot be negative")
        main()

    if mealType == 'S' and seatClass != 'F':
        totalFlightCost = totalFlightCost + standardMeal
        print("Meal: Standard")
        print(f"Meal Cost: £{standardMeal}")
        
    elif mealType == 'V' and seatClass != 'F':
        totalFlightCost = totalFlightCost + vegetarianMeal
        print("Meal: Vegetarian")
        print(f"Meal Cost: £{vegetarianMeal}")

    elif mealType == 'N':
        print("Meal: None")
        print("Meal Cost: £0")

    # THIS COULD DEFINITELY BE DONE MORE EFFICIENTLY
    if seatClass == 'F' and mealType is 'S':
        totalFlightCost = totalFlightCost + standardMeal
        print("Meal: Standard")
        print(f"Meal Cost: FREE")

        print("Seating Class: First")
        totalFlightCost = totalFlightCost * 6
            
    elif seatClass is 'F' and mealType == 'V':
        totalFlightCost = totalFlightCost + vegetarianMeal
        print("Meal: Vegetarian")
        print(f"Meal Cost: £{vegetarianMeal}")
            
        print("Seating Class: First")
        totalFlightCost = totalFlightCost * 6

    elif seatClass == 'E':
        print("Seating Class: Economy")

    print(totalFlightCost)

Testing

Changing the input in your main, you will recognize in my test below, that there is no real performance issue:

start = time.time()
main()
print('main() takes: ')
print(time.time() - start)

start = time.time()
main2()
print('main2() takes:') 
print(time.time() - start)

Results

main() takes: 7.319450378417969e-05 sec

main2() takes: 4.935264587402344e-05 sec

Mentionable

In the recursion path which you set (mentioned in the comments) you also use time.sleep(2). Inserting Hardcoded sleeps will always affect your performance.

Upvotes: 1

Related Questions