CS50P Problem Set 3 Solution

Fuel Gauge

def main():
    while True:
        try:
            fuel = input("Fraction: ")
            x,y = fuel.split('/')
            x = int(x)
            y = int(y)
            if x>y:
                print("x should be less than y")
            else:
                result = round((x/y)*100)
                if result<=1:
                    print("E")
                elif result>=99:
                    print("F")
                else:
                    print(f"{result}%")
                break
        except ValueError:
            print("Input Integer")
        except ZeroDivisionError:
            print("Cannot Divide by zero")

if __name__=="__main__":
    main()

Felipe’s Taqueria

def main():
    items = {
        "Baja Taco": 4.25,
        "Burrito": 7.50,
        "Bowl": 8.50,
        "Nachos": 11.00,
        "Quesadilla": 8.50,
        "Super Burrito": 8.50,
        "Super Quesadilla": 9.50,
        "Taco": 3.00,
        "Tortilla Salad": 8.00
    }



    try:
        price = 0
        while True:
            item = input("Item: ").title()

            for i in items:
                if i == item:
                    price += items[i]
                    print(f"Total: ${price:.2f}")

    except KeyboardInterrupt:
        print("")
    except EOFError:
        print("")


if __name__ == "__main__":
    main()

Grocery List

def main():
    items={}
    counter_dict={}
    key = 1
    while True:
        try:
            item = input().upper()
            items[key]=item
            key += 1
        except EOFError:
            for value in items.values():
                if value in counter_dict:
                    counter_dict[value] +=1
                else:
                    counter_dict[value] = 1
            for count, value in sorted(counter_dict.items()):
                print(value, count)
            break

if __name__=="__main__":
    main()

Outdated

def main():
    months = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
        ]
    while True:
        input_date = input("Date:")
        try:
            if ',' in input_date:
                month, day, year = input_date.split(' ')
                if month in months:
                    month = (months.index(month))+1
                    day = int(day.strip(","))

            else:
                month, day, year = input_date.split('/')
                year = int(year)
                month = int(month)
                day = int(day)
            if 1<=month<=12 and 1<=day<=31:
                print(f"{year}-{month:02}-{day:02}")
                break
        except (ValueError, TypeError):
            pass

if __name__ =="__main__":
    main()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.