Repetition - Exercises
Now, let us practice writing loops.
Many thanks to the following people for contributing to these exercises: Joe Stacey, Oana Cocarascu
Ex1: Given a list of integers, create a program that outputs a list of tuples where the first element in the tuple is the number itself, and the second element in the tuple is the number squared.
- For example inputting [1, 2, 3] would return [(1, 1), (2, 4), (3, 9)]
Ex2: Write a program that takes a list of integers, and returns the same list, except squaring any numbers divisible by 3
- For example inputting [1, 2, 3] would return [1, 2, 9]
Ex3: Iterate over the following list: words = [‘Imperial’, ‘College’, ‘London’], and print the item number as well as each item in the list.
Ex4: Given two lists of integers with the same length, add the values in the first list to the corresponding values in the second list.
- For example inputting [1, 2, 3] and [5, 4, 3] would return [6, 6, 6]
Ex5: Write a program that replaces every 3rd element of a list with the string ‘I-Love-Imperial’
- For example [1, 2, 3] would become [1, 2, ‘I-Love-Imperial’]
Ex6: Write a program that takes a string as an input, and replaces every other word by ‘not’
Ex7: Write a program to count the number of upper case and lower case characters in a string
Ex8: Write a program which finds all of the numbers between 100 and 1000 which are divisible by 7 but not divisible by 3.
- Print the numbers on a single line, each separated by a comma
Ex9: Write a program which takes as an input the date someone was born and the number of years they are likely to live for, and the program returns all of the years they will live through which contain at least two digits that are the same
- Examples of years that have at least two digits that are the same include: 1998, 2012, 2011, 2000 or 2007
Ex10: Write a program that takes two lists, and creates a new list with each different combination of elements from the list. In each case the elements should be concatenated, with the element from the first list coming first. The order of elements in the list does not matter.
- For example, inputting [‘a’, ‘b’, ‘c’] and [‘d’, ‘e’] would produce [‘ad’, ‘bd’, ‘cd’, ‘ae’, ‘be’, ‘ce’]
- Can you include an error check to make sure the outputted list has the right length?
Ex11: Using the ‘break’ statement, write a loop that computes the sum of all integers until a zero is found in a list
- For example, for my_list = [1, 2, 5, 12, 0, 7, 12] , the output should be 20.
Challenge questions:
Ex12: Write a program that prints a list containing only the items that appear more than once in a given list.
Ex13: Given a string consisting of comma separated words, print each word on a new line in reverse (descending) alphabetical order.
- For example the strong ‘order words alphabetically’ would output: ‘words’ ‘order’ ‘alphabetically’