CS50 Lesson 3

CS50
code
lesson
Author

Ryan curtis

Published

March 21, 2023

I thought it would be fun to track all of my progress learning python, even the VERY humble beginnings. Any of the posts with the CS50 tag are simply copy/pastes of my code from lessons, along with a copy/paste of what the assignment actually wanted me to do for context.

Nutrition Facts

The U.S. Food & Drug Adminstration (FDA) offers downloadable/printable posters that “show nutrition information for the 20 most frequently consumed raw fruits … in the United States. Retail stores are welcome to download the posters, print, display and/or distribute them to consumers in close proximity to the relevant foods in the stores.”

In a file called nutrition.py, implement a program that prompts consumers users to input a fruit (case-insensitively) and then outputs the number of calories in one portion of that fruit, per the FDA’s poster for fruits, which is also available as text. Capitalization aside, assume that users will input fruits exactly as written in the poster (e.g., strawberries, not strawberry). Ignore any input that isn’t a fruit.

```{{python}}
def main():
    #Create dictionary of fruits along with caloric values
    fruits = {
        "apple": "130",
        "avocado": "50",
        "banana": "110",
        "cantaloupe": "50",
        "grapefruit": "60",
        "grapes": "90",
        "honeydew melon": "50",
        "kiwifruit": "90",
        "lemon": "15",
        "lime": "20",
        "nectarine": "60",
        "orange": "80",
        "peach": "60",
        "pear": "100",
        "pineapple": "50",
        "plums": "70",
        "strawberries": "50",
        "sweet cherries": "100",
        "tangerine": "50",
        "watermelon": "80"
    }

    #Get user input
    user_input = input("Item: ").lower()

    #if user input is in dictionary, print the calories, otherwise return nothing
    try:
        print(fruits[user_input])
    except KeyError:
        pass


main()
```

Vanity Plates

In Massachusetts, home to Harvard University, it’s possible to request a vanity license plate for your car, with your choice of letters and numbers instead of random ones. Among the requirements, though, are:

  • “All vanity plates must start with at least two letters.”

  • “… vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters.”

  • “Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable … vanity plate; AAA22A would not be acceptable. The first number used cannot be a ‘0’.”

  • “No periods, spaces, or punctuation marks are allowed.”

In plates.py, implement a program that prompts the user for a vanity plate and then output Valid if meets all of the requirements or Invalid if it does not. Assume that any letters in the user’s input will be uppercase. Structure your program per the below, wherein is_valid returns True if s meets all requirements and False if it does not. Assume that s will be a str. You’re welcome to implement additional functions for is_valid to call (e.g., one function per requirement).

```{python}
def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def is_valid(s):
    #Create an interation tracker that tells me how many characters have been iterated through at each step & create number tracker to determine if these is a number in the string
    chr_tracker = 0
    nbr_tracker = 0
    #Determine length of string and return false if less than 2 or more than 6
    if 2 <= len(s) <= 6:
        #Begin to iterate through string
        for iteration in s:
            #If string is a letter, add 1 to iteration tracker, then move onto next iteration
            if iteration.isalpha() == True and nbr_tracker == 0:
                chr_tracker = chr_tracker + 1

            #If string is a number, ensure that we are at least two iterations through (first two iterations were letters) AND first number is not 0.
            elif iteration.isnumeric() == True:
                #If number is not 0, then continue iteration and assign 1 to nbr tracker as we now know that there is a non-zero number before 0
                if chr_tracker >= 2 and int(iteration) != 0:
                    nbr_tracker = 1

                #If number is 0, check that we are 2, iterations through and there is a value of 1 for nbr_tracker, which only is 1 if a different number has already been entered
                elif chr_tracker >= 2 and int(iteration) == 0 and nbr_tracker == 1:
                    pass

                else:
                    return False
                chr_tracker = chr_tracker + 1

            #Return false if any of the above is false
            else:
                return False

    #Return false if string is less than 2 or more than 6 characters
    else:
        return False

    return True



main()
```

Just setting up my twttr

When texting or tweeting, it's not uncommon to shorten words to save time or space, as by omitting vowels, much like Twitter was originally called twttr. In a file called twttr.py, implement a program that prompts the user for a str of text and then outputs that same text but with all vowels (A, E, I, O, and U) omitted, whether inputted in uppercase or lowercase.

```{{python}}
def main():
    user_input = input("Input: ").strip()

    twttr_sentence = []

    for letter in user_input:
        match letter.lower():
            case "a" | "e" | "i" | "o" | "u":
                pass
            case _:
                twttr_sentence.append(letter)

    twttr_sentence = "".join(twttr_sentence)
    print(twttr_sentence)


main()
```

Coke Machine

Suppose that a machine sells bottles of Coca-Cola (Coke) for 50 cents and only accepts coins in these denominations: 25 cents, 10 cents, and 5 cents.

In a file called coke.py, implement a program that prompts the user to insert a coin, one at a time, each time informing the user of the amount due. Once the user has inputted at least 50 cents, output how many cents in change the user is owed. Assume that the user will only input integers, and ignore any integer that isn't an accepted denomination.

``` {{python}}
def main():
    amount_due = 50

    while amount_due > 0:
        #Define amount for coke, print amount owed, recieve payment
        print("Amount Due:", amount_due)
        payment = int(input("Insert Coin: "))
        match payment:
            case 5 | 10 | 25:
                amount_due = amount_due - payment
            case _:
                pass
            
    print("Change Owed:", -amount_due)


main()
```

camelCase

In some languages, it's common to use camel case (otherwise known as "mixed case") for variables' names when those names comprise multiple words, whereby the first letter of the first word is lowercase but the first letter of each subsequent word is uppercase. For instance, whereas a variable for a user's name might be called name, a variable for a user's first name might be called firstName, and a variable for a user's preferred first name (e.g., nickname) might be called preferredFirstName.

Python, by contrast, recommends snake case, whereby words are instead separated by underscores (_), with all letters in lowercase. For instance, those same variables would be called name, first_name, and preferred_first_name, respectively, in Python.

In a file called camel.py, implement a program that prompts the user for the name of a variable in camel case and outputs the corresponding name in snake case. Assume that the user's input will indeed be in camel case.

```{{python}}
def main():
    #Get user input
    user_input = input("camelCase: ").strip()

    #Iterate through each letter in for loop
    for letter in user_input:
        #Check to see if letter is capitalized
        capital_check = letter.isupper()
        if capital_check == True:
            #if capitalized, lowercase it and print an underscore and the letter
            letter = letter.lower()
            print("_", end="")
            print(letter, end="")
        else:
            #if lowercase, just print letter
            print(letter, end="")
    print()


main()
```