Hello there! I'm Cosby

coding diary 1

Birthday Cake Candles Problem

The problem is to find the number of candles on a cake that are the tallest

On attempt:

def birthdayCakeCandles(candles):
    count = 0
    tallest = 0
    for i in range(len(candles)):
        if candles[i] == tallest:
            count += 1
        elif candles[i] > tallest:
            tallest = candles[i]
            count = 1
    return count

On iteration:

def birthdayCakeCandles(candles):
    return candles.count(max(candles))

Key learning: 1) keep functions like .count and max() in the tool box 2) don't unnecessarily use (range(len(list))).


Time Conversion Problem

The problem is to convert 12-hour AM/PM format to 24-hour format

On attempt:

def timeConversion(s):
    hour = int(s[:2])
    minut = int(s[3:5])
    seco = int(s[6:8])
    am_or_pm = s[8:]

    if am_or_pm == "AM":
        if hour >= 12:
            hour -= 12
    elif am_or_pm == "PM":
        if hour != 12:
            hour += 12
    return(f"{hour:02d}:{minut:02d}:{seco:02d}")

On iteration:

def timeConversion(s):
    hour = int(s[:2]) % 12
    if s[8:] == "PM":
        hour += 12
    return f"{hour:02d}{s[2:8]}"

Key learning: 1) usage of modulo 2) f string formatting of :02d (rounding to 2dp), 3) slicing of substring to isolate the problem


Apple and Orange

The problem is to determine how many apples and oranges fall within the distance of the house

On attempt:

def countApplesAndOranges(s, t, a, b, apples, oranges):
    apples_count = 0
    oranges_count = 0
    for i in range(len(apples)):
        apples[i] = apples[i] + a
        if apples[i] >= s and apples[i] <= t:
            apples_count += 1
    for i in range(len(oranges)):            
        oranges[i] = oranges[i] + b
        if oranges[i] >= s and oranges[i] <= t:
            oranges_count += 1
    print(apples_count, oranges_count, sep="\n")

On 1st iteration:

def countApplesAndOranges(s, t, a, b, apples, oranges):
    apples_count = 0
    oranges_count = 0
    for d in apples:
        if s <= a+d <= t:
            apples_count += 1
    for d in oranges:            
        if s <= b+d <= t:
            oranges_count += 1
    print(apples_count, oranges_count, sep="\n")

On 2nd iteration:

def countApplesAndOranges(s, t, a, b, apples, oranges):
    print(sum(1 for d in apples if s <= a + d <= t))
    print(sum(1 for d in oranges if s <= b + d <= t))

on 3rd iteration:

def countApplesAndOranges(s, t, a, b, apples, oranges):
    print(sum(s <= a + d <= t for d in apples))
    print(sum(s <= b + d <= t for d in oranges))

Key learning: 1) using chained operators 2) using list comprehension 3) iteration 2 adds 1 to the list via list comprehension, and iteration 3 adds True or False to the list via list comprehension