In this post I will show how to solve the problems from topic 2 - Loops of CS50’s - Introduction to Python course.

Table of Contents

camelCase

The first problem asks to snake_case every camelCased variable name as input from user.

Here are the steps to solve this problem:

  1. First we need to take user’s input, so we will use the command input. As per documentation the input command in python returns a string.
  2. The second step is to verify each letter of user’s input using the for loop. If it is an uppercased letter it will print the underscore. To verify if it is a uppercased letter I used the method (isupper from str class. And it is a uppercased letter it will be printed in lowercase after the underscore using the method lower from str class.

The end="" parameter in print is to not break the line after printing the caracter/phrase.

The solution will then be:

camel = input("camelCase: ")
print("snake_case: ", end="")

for char in camel:
    if char.isupper():
        print("_", end="")
        char = str.lower(char)
    print(char, end="")

print()

GitHub repository

Coke Machine

This problems asks to 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, we must output how many cents in change the user is owed. It says to assume that the user will only input integers, and to ignore any integer that isn’t an accepted denomination.

Here are the steps to solve this problem:

  1. First I crated a variable called sum and gave it the value 50.
  2. I used the value in sum to verify how much is still missing, while the value is greater than 0 it will ask for a coin value from user.
  3. The values that user the input will be transformed into a integer variable using the int method.
  4. If the value matches any value of acceptable for coins (25, 10 or 5) it will be subtracted from the sum variable.
  5. When the value for sum is equal to zero we exit the program, but if sum is lower then zero it will returns the amount owed by the user before exiting.

The solution will then be:

sum = 50

while sum > 0:
    print(f"Amount Due: {sum}")
    value = int(input("Insert Coin: "))

    match value:
        case 25:
            sum -= value
        case 10:
            sum -= value
        case 5:
            sum -= value

sum = -1 * sum
print(f"Change Owed: {sum}")

GitHub repository

Just setting up my twttr

This problem brings that on twitter is common to shorten words by omitting vowels. For this problem we mas implement a program that prints to user the same text he inputs but without the vowels.

The objective here is to remove the caracters A, E, I, O and U from user’s input.

For this problem we will use the for loop to run through every character on user’s input and verify if it is a vowel, if its not a vowel it will be printed.

def main():
    text = input("Input: ")

    for char in text:
        if (isVowel(char) != True):
            print(char, end="")

    print()


def isVowel(c):
    c = c.lower()

    for vowel in "aeiou":
        if c == vowel:
               return True

    return False

main()

GitHub repository

Vanity Plates

For the problem Vanity Plates we must 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. We will assume that any letters in the user’s input will be uppercase.

Among the requirements for the vanity plate, 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.”

This problem give us a structure to work with. The function main is already done, only need to work on the is_valid function.

  1. The function is_valid first verifies the length of the string with method len if its less than two or bigger than 6 it is invalid.
  2. The second step is to verify if the first two characters to see if they are letters, I used the range function to set the range for the for loop. To verify if the character is a leeter I used the isalpha method.
  3. The next for loop verify if there is any punctuation, spaces or periods with the isalnum method and if there is a letter after a number with isnumeric and isalpha methods.
  4. The while loop verifies if the first number is the numer zero (0).
def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(s):
    size = len(s)

    if size < 2 or size > 6:
        return False

    for i in range(2):
        if (s[i].isalpha() != True):
            return False

    for i in range(size):
        if i < size - 1:
            j = i + 1

        if s[i].isalnum() != True:
            return False

        # Verify if after the number has a letter
        if s[i].isnumeric() and s[j].isalpha():
            return False

    # Verify if the first number is zero
    count = 1
    while s[count].isnumeric() != True and count < size - 1:
        if s[count + 1] == '0':
            return False
        count += 1

    return True

main()

GitHub repository

Nutrition Facts

The objective here is to implement a program that prompts the user for a fruit and output its calories based on the FDA’s poster for fruits.

To solve this I constructed a dictionary reffering to each fruit on the poster to its calories.

To make it case-insensitive I used the method lower to turn every character on input into lowercase. Then printed the calories value according to the fruit the user inputs.

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,
}

key = str.lower(input("Item: "))
if key in fruits:
    print(fruits[key])

GitHub repository

This is all for week two - Loops, set of problems of CS50’s Introduction to Programming with Python course.