RESOURCES

COMP150: Practice Exercises

Progression 6: Practice exercises

Download the files you need for these exercises: Progression 6 support files

There are many possible approaches and solutions. If you are not sure about the solution you developed, check it with a demonstrator.

Question 1

Write a function that takes an int. The function should ask the user to enter a word longer than the int and continue asking until the user successfully does so. It should then return the word.

The function should behave as shown below when it is called from main with the number 12 passed in.

Remember to have all the required files in the same directory as the python file.

>>> 
Please enter a word longer than 12: this is not one word
Try again
Please enter a word longer than 12: 123456798765432123456
Try again
Please enter a word longer than 12: supralapsarianism
supralapsarianism
>>>

def get_word_longer_than(x):
    user_in = '' 

    while len(user_in) <= x or not user_in.isalpha():
        user_in = raw_input("Please enter a word longer than " + str(x) + ": ")

        if len(user_in) <= x or not user_in.isalpha():
            print "Try again" 
    return user_in 

Question 2

Write a function that takes 2 arguments - a file name and an int, x. The function should, using a while loop, return a string containing the first x vowels found in the file. You may assume the file is not overly large.

Remember to have all the required files in the same directory as the python file.

Your function should pass the doctests below:

           
def first_x_vowels(file_name, x):
    """
    >>> first_x_vowels('test.txt', 10)
    'aouieieiie'
    >>> first_x_vowels('russia.txt', 50)
    'ioouiaoiieiaeeeeoeiaeioouiaeiiaoeEaeaaeioUieoeeaeo'
    >>> first_x_vowels('antigua.txt', 15)
    'iooAiuaaauaoiie'
    """

    
def first_x_vowels(file_name, x):
    """
    >>> first_x_vowels('test.txt', 10)
    'aouieieiie'
    >>> first_x_vowels('russia.txt', 50)
    'ioouiaoiieiaeeeeoeiaeioouiaeiiaoeEaeaaeioUieoeeaeo'
    >>> first_x_vowels('antigua.txt', 15)
    'iooAiuaaauaoiie'
    """
    file_in = open(file_name)
    text = file_in.read()

    i = 0
    result = ''
    while i < len(text) and len(result)< x:

        if text[i].lower() in "aeiou":
            result += text[i]

        i +=1
    file_in.close()
    return result