New book Algorithms: Competitive Programming, co-authored by Antonio, is just published! The book helps you prepare for your incoming programming contest or coding interview. This book contains detailed explanations and source code for algorithms used in competitive programing.
PRIZE: You can get a free digital copy if you get a final score of 85% in the exercises.
1. Review: While Loop
while loop is used to make an indefinite iteration. That is, the loop repeats an unknown number of times apriori. A
while loop ends when the condition for the
while loop is false.
for loop iterates for a definite number of times. For example,
for i in range(5) repeats 5 times.
Example: Finding the nearest square of a number.
Given an integer number limit, find the largest square number less than that integer limit. A square number is a number with a square root, that is, the product of an integer with itself.
For instance, 36 is a square number because 36 = 6 x 6.
2. Review: For Loop
When to use
for loop vs
forloop when the number of iterations is known or finite
whileloop when the iterations need to continue until a certain condition is met
For loops are used for definite iteration. That is, the loop body is run a predetermined number of times. In a
while loop, however, the loop repeats an unknown number of times and ends only when some condition is met. This is called indefinite iteration.
For example, if you have an iterable (e.g. list, set, tuple, or dictionary), use
for loop. If you want to use comparison operator to break the loop, consider using the
while loop instead. For more information, see https://wiki.python.org/moin/WhileLoop
If we need more control over when a loop should be ended or skipped, we can use the
continue keywords, respectively.
breakterminates a loop
continueskips one iteration of a loop
3. Python Pro Tools for Looping
We will discuss two handy built-in functions and one trick to elegantly handle loops:
enumerate, and list comprehension.
zipreturns an iterator that combines multiple iterables into one sequence of tuples. Each tuple contains the elements in that position from all the iterables.
enumeratereturns an iterator of tuples containing indices and values of a list. You will find this useful when you need the index and value of each element of the iterable.
zip returns an iterator of tuples, combining multiple iterables that are given as arguments.
zip can take mulitple arbitrary number of arguments.
Since the return value of
zip is an iterator, you need to convert it to a list to see the values, or use it in a
enumerate if you want to iterate through an iterator along with the index. That is, at each iteration you want to get not just the element of the iterable but also the index of that element.
Given these two lists
cast = ["Andy", "Bobby", "Cindy", "Deborah"] heights = [184, 177, 168, 172]
Create a new list, using
enumerate, such that the elements in the new list are strings containing name of the cast and his/her height separated by colon as follows.
['Andy: 184', 'Bobby: 177', 'Cindy: 168', 'Deborah: 172']
Task: Sum the first five odd numbers.
Given a list, find the arithmetic sum of the first five odd numbers in the list. As you go through each number in the list, you have to check if it's even or odd.
Use a for loop to convert a list of strings into unordered (bulleted) list in HTML. For example, the list
items = ['Hello World', 'World Hello']
should be converted into a single string that prints
<ul> <li>Hello World</li> <li>I am the best</li> </ul>
Task: use a while/for loop to compute the factorial of a number
The factorial of a number is the product of all whole numbers between itself and one. For example, 4! = 4 x 3 x 2 x 1 = 24
- if using a for loop, you can use the
rangefunction to create the iterable
- if using a while loop, you can decrement the number by 1 as long as it's greater than 1