Weekly Graded Assignment (6)

Since a string is just a sequence of characters, they can be sorted from least to greatest. Sorting can be hard so we’re just going to check if a string is sorted. Write a function which returns a boolean indicating if the string is sorted or not.

Here’s an example of how your function should behave. (Recall that the order operators are case-sensitive, so that "A" < "a" evaluates to True.)

def is_sorted(string):
    """Returns True if string is sorted from least to greatest
       False otherwise.
    """
    # TODO: Fill in details
    idx = 0
    for idx in range(len(string) - 1):
        if string[idx] > string[idx+1]:
            return False   
    return True

print(is_sorted("ABC") == True)
print(is_sorted("aBc") == False)
print(is_sorted("dog") == False)

Bonus Missions

Write a function that takes in a float and returns the number of digits that occur after the decimal point. For example, 3.14 should return 2, 9.876543 should return 6, and 9825 should return 0.

def digit_count(num):
    num = str(num)    
    idx = num.find(".")
    if idx == -1:
        return 0
    else:
        num = num[idx+1:]
        return len(num)

print(digit_count(1.))
print(digit_count(3.4556))
print(digit_count(3.4556236))
print(digit_count(37))

>>> 1
>>> 4
>>> 7
>>> 0

Bonus Missions 2

Write a function that takes in a string and converts that string to pig latin. Pig latin involves moving the first letter of a word to the end, then appending “ay.” For example, the phrase “python code wins” would turn into “ythonpay odecay insway.”

For an extra challenge, handle the case where a word starts with a vowel. In this case, the word should be unmodified except for adding “ay” at the end. For example, “all open androids” would become “allay openay androidsay.”

def pig_latin(text):
    text_list = text.split(" ")
    vowels = "AEIOUaeiou"
    translated = []
    ending = "ay"

    for word in text_list:
        if word[0] in vowels:
            word = word + ending
        else:
            word = word[1:] + word[0] + ending
        translated.append(word)

    return " ".join(translated)

print(pig_latin("python code wins"))
print(pig_latin("all open androids"))

>>> ythonpay odecay insway
>>> allay openay androidsay

results matching ""

    No results matching ""