Text
stringlengths
1
9.41k
For each iteration of the outer loop, there’s an iteration of the inner loop, again: Anne, Bojan, Carlos, and Doris.
If the element assigned to white in the outer loop does not equal the element assigned to black in the inner loop, we print the pairing.
In this way, all possible pairings are generated. Here’s another example—performing multiplication using a nested loop.
(What follows is inefficient, and perhaps a little silly, but hopefully it illustrates the point.) Let’s say we wanted to multiply 5 × 7 without using the * operator. We could do this with a nested loop! ``` answer = 0 for _ in range(5): for __ in range(7): answer += 1 print(answer) # prints 35 ``` Ho...
Five. How many times does the inner loop execute for each iteration of the outer loop? Seven. How many times do we increment answer?
5 × 7 = 35. ###### Using nested loops to iterate a two-dimensional list Yikes! What’s a two-dimensional list?
A two-dimensional list is just a list containing other lists! Let’s say we have the outcome of a game of tic-tac-toe encoded in a two-dimensional list: ``` game = [ ['X', ' ', 'O'], ['O', 'X', 'O'], ['X', ' ', 'X'] ] ``` To print this information in tabular form we can use a nested loop. ----- ``` ...
You’ll see that implementing these in Python is almost trivial—we use a list for both, and the only difference is how we use the list. ###### Stacks A stack is what’s called a last in, first out data structure (abbreviated LIFO and pronounced life-o).
It’s a linear data structure where we add elements to a list at one end, and remove them from the same end. The canonical example for a stack is cafeteria trays.
Oftentimes these are placed on a spring-loaded bed, and cafeteria customers take the tray off the top and the next tray in the stack is exposed.
The first tray to be put on the stack is the last one to be removed. You’ve likely seen chairs that can be stacked. The last one on is the first one off. Have you ever packed a suitcase?
What’s gone in last is the first to come out. Have you ever hit the ‘back’ button in your web browser? Web browsers use a stack to keep track of the pages you’ve visited.
Have you ever used ctrl-z to undo an edit to a document? Do you have a stack of dishes or bowls in your cupboard? Guess what?
These are all everyday examples of stacks. We refer to appending an element to a stack as pushing.
We refer to removing an element to a stack as popping (this should sound familiar). ----- Stacks are very widely used in computer science and stacks are at the heart of many important algorithms.
(In fact, function calls are managed using a stack!) The default behavior for a list in Python is to function as a stack. Yes, that’s right, we get stacks for free!
If we append an item to a list, it’s appended at one end. When we pop an item off a list, by default, it pops from the same end.
So the last element in a Python list represents the top of the stack. Here’s a quick example: ``` >>> stack = [] >>> stack.append("Pitchfork") >>> stack.append("Spotify") >>> stack.append("Netflix") >>> stack.append("Reddit") >>> stack.append("YouTube") >>> stack[-1] # see what's on top YouTube >>> st...
The only difference between a stack and a queue is that with a stack we push and pop items from the same end, and with a queue we add elements at one end and remove them from the other.
That’s the only difference. What are some real world examples? The checkout line at a grocery store—the first one in line is the first to be checked out.
Did you ever wait at a printer because someone had sent a job before you did? That’s another queue.
Cars through a toll booth, wait lists for customer service chats, and so on—real world examples abound. The terminology is a little different. We refer to appending an element to a queue as enqueueing.
We refer to removing an element to a queue as _dequeueing.
But these are just fancy names for appending and popping._ Like stacks, queues are very widely used in computer science and are at the heart of many important algorithms. There’s one little twist needed to turn a list into a queue.
With a queue, we enqueue from one end and dequeue from the other. Like a stack, we can use append to enqueue.
The little twist is that instead of ``` .pop() which would pop from the same end, we use .pop(0) to pop from ``` the other end of the list, and voilà, we have a queue. Here’s a quick example: ``` queue = [] >>> queue.append("Fred") # Fred is first in line >>> queue.append("Mary") # Mary is next in line >>> que...
Usually, stacks and queues are used within a loop.
We’ll see a little more about this in a later chapter. ###### 11.15 A deeper dive into iteration in Python What follows is a bit more detail about iterables and iteration in Python. You can skip this section entirely if you wish.
This is presented here for the sole purpose of demonstrating what goes on “behind the scenes” when we iterate over some object in Python.
With that said, let’s start with the case of a list (it works the same with a tuple or any other iterable). ``` >>> m = ['Greninja', 'Lucario', 'Mimikyu', 'Charizard'] ``` When we ask Python to iterate over some iterable, it calls the function ``` iter() which returns an iterator for the iterable (in this case a lis...
This is done (behind the scenes) by calls to the iterator’s __next__() method. ``` >>> iterator.__next__() 'Greninja' >>> iterator.__next__() 'Lucario' >>> iterator.__next__() 'Mimikyu' >>> iterator.__next__() 'Charizard' ``` Now what happens if we call __next__() one more time? We get a StopIteration ...
Python does_ not create a new iterator for these objects automatically, as it does when iterating sequences or range objects.
(We’ll see something similar later on when we get to csv.reader objects, but that’s for another time.) ----- ###### 11.16 Exercises **Exercise 01** Write a while loop that adds all numbers from one to ten.
Do not use ``` for. What is the sum? Check your work. (See: section 11.2) ``` **Exercise 02** _Without a loop but using range(), calculate the sum of all numbers from_ one to ten. Check your work.
(See: section 11.5) **Exercise 03** a. Write a for loop that prints the numbers 0, 2, 4, 6, 8, each on a separate line. b.
Write a for loop that prints some sentence of your choosing five times. **Exercise 04** Write a for loop that calculates the sum of the squares of some arbitrary list of numerics, named data (make up your own list, but be sure that it has at least four elements). For example, if the list of numerics were [2, 9, 5, -1...
That is, if the number is even, add it to the total; if the number is odd, subtract it from the total. What is the sum? Check your work.
Double-check your work. (See: section 11.11) **Exercise 06** Write a for loop which iterates over a string and capitalizes every other letter.
For example, with the string “Rumplestiltskin”, the result should be “RuMpLeStIlTsKiN”.
With the string “HELLO WORLD!”, the result ----- should be “HeLlO WoRlD!” With the string “123456789”, the result should be “123456789”. What happens if we capitalize a space or punctuation or number? **Exercise 07** Create some list of your own choosing.
Your list should contain at least five elements. Once you’ve created your list, write a loop that uses ``` enumerate() to iterate over your list, yielding both index and element ``` at each iteration.
Print the results indicating the element and its index. For example, given the list ``` albums = ['Rid Of Me', 'Spiderland', 'This Stupid World', 'Icky Thump', 'Painless', 'New Long Leg"] ``` your program would print ``` "Rid Of Me" is at index 0. "Spiderland" is at index 1. "This Stupid World" is at i...
So, for example, the next number is 1 because 0 + 1 = 1, the number after that is 2 because 1 + 1 = 2, the number after that is 3 because 1 + 2 = 3, the number after that is 5 because 2 + 3 = 5, and so on. Write a program that uses a loop (not recursion) to calculate the first 𝑛 terms of the Fibonacci sequence.
Start with this list: ``` fibos = [0, 1] ``` You may use one call to input(), one if statement, and one while loop. You may not use any other loops. You may not use recursion.
Examples: ``` Enter n for the first n terms in the Fibonacci sequence: 7 [0, 1, 1, 2, 3, 5, 8] Enter n for the first n terms in the Fibonacci sequence: 10 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` ----- ``` Enter n for the first n terms in the Fibonacci sequence: 50 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
How you modify the list is up to you, but you should use at least two different list methods.
Include code that calls the function, passing in a list variable, and then demonstrates that the list has changed, once the function has returned. **Exercise 10** Write a function which takes two integers, 𝑛 and 𝑘 as arguments, and produces a list of all odd multiples of 𝑘 between 1 and 𝑛.
E.g., given input 𝑛= 100 and 𝑘= 7, the function should return ``` [7, 21, 35, 49, 63, 77, 91] ``` **Exercise 11 (challenge!)** The modulo operator partitions the integers into equivalence classes based on their residues (remainders) with respect to some modulus.
For example, with a modulus of three, the integers are partitioned into three equivalence classes: those for which 𝑛 mod 3 ≡0, 𝑛 mod 3 ≡1, and 𝑛 mod 3 ≡2. Write and test a function which takes as arguments an arbitrary list of integers and some modulus, 𝑛, and returns a tuple containing the count of elements in the...
So, for example, if the input list were [1, 5, 8, 2, 11, 15, 9] and the modulus were 3, then the function should return the tuple (2, 1, 4), because there are two elements with residue 0 (15 and 9), one element with residue 1, (1), and four elements with residue 2 (5, 8, 2, 11). Notice also that if the modulus is 𝑛, t...
Start with an empty list: ``` stack = [] ``` 1. push ‘teal’ 2. push ‘magenta’ 3. push ‘yellow’ 4. push ‘viridian’ 5. pop 6. pop 7. push ‘amber’ 8. pop 9. pop 10. push ‘vermilion’ Print your stack.
Your stack should look like this ``` ['teal', 'vermilion'] ``` If it does not, start over and try again. See: Section 11.14 Stacks and queues **Exercise 13** At the Python shell, create a list and use it as a queue.
At the start, the queue should be empty. ``` >>> queue = [] ``` Now perform the following operations: 1. enqueue ‘red’ 2. enqueue ‘blue’ 3. dequeue 4. enqueue ‘green’ 5. dequeue 6.
enqueue ‘ochre’ 7. enqueue ‘cyan’ 8. enqueue ‘umber’ 9. dequeue 10. enqueue ‘mauve’ Now, print your queue.
Your queue should look like this: ``` ['ochre', 'cyan', 'umber', 'mauve'] ``` If it doesn’t, start over and try again. ----- #### Chapter 12 ### Randomness, games, and simulations Here we will learn about some of the abundant uses of randomness.
Randomness is useful in games (shuffle a deck, roll a die), but it’s also useful for modeling and simulating a staggering variety of real world processes. **Learning objectives** - You will understand why it is useful to be able to generate pseudorandom numbers or make pseudo-random choices in a computer program. ...
Games like this are fun in part because of the element of chance. We don’t know how many dots will come up when we throw the dice. We don’t know what the next card to be dealt will be.
If we knew all these things in advance, such games would be boring! Outside of games, there’s a tremendous variety of applications which require randomness. Simulations of all kinds make use of this—for example, modeling biological or ecological phenomena, statistical mechanics and physics, physical chemistry, modeling...
Randomness is also used in cryptography, artificial intelligence, and many other domains.
For example, the Monte Carlo method (named after the famous casino in Monaco) is a widely used technique which repeatedly samples data from a random distribution, and has been used in science and industry since the 1940s. Python’s random module gives us many methods for generating “random” numbers or making “random” ch...
These come in handy when we want to implement a game of chance (or game with some chance element) or simulation. But think: how would you write code that simulates the throw of a die or picks a “random” number between, say, one and ten?
Really. Stop for a minute and give it some thought. This is where the random module comes in.
We can use it to simulate such events. I put “random” in quotation marks (above) because true randomness cannot be calculated.
What the Python random module does is generate _pseudo-random numbers and make pseudo-random choices. What’s the_ difference? To the casual observer, there is no difference.
However, deep down there are deterministic processes behind the generation of these pseudo-random numbers and making pseudo-random choices. That sounds rather complicated, but using the random module isn’t. If we wish to use the random module, we first import it (just like we’ve been doing with the math module). ``` ...
This is useful when selecting from a fixed set of possibilities.
For example: ``` >>> import random >>> random.choice(['heads', 'tails']) 'tails' ``` Each time we call choice this way, it will make a pseudo-random choice between ‘heads’ and ‘tails’, thus simulating a coin toss. ----- This works with any iterable. ``` >>> random.choice((1, 2, 3, 4, 5)) 2 >>> random.ch...
'5', '4', '3', '2']) '7' >>> random.choice(['rock', 'paper', 'scissors']) 'rock' >>> random.choice(range(10)) 4 ``` It even works with a string as an iterable! ``` >>> random.choice("random") 'm' ###### Comprehension check ``` 1.
How could we use random.choice() to simulate the throw of a sixsided die? 2.
How could we use random.choice() to simulate the throw of a twelvesided die? ###### Using random.choice() for a random walk The random walk is a process whereby we take steps along the number line in a positive or negative direction, at random. Starting at 0, and taking five steps, choosing -1 or +1 at random, a walk...
At each step, we move one to the left (negative) or one to the right (positive).
In a walk like this there are 2[𝑛] possible outcomes, where 𝑛 is the number of steps taken. Here’s a loop which implements such a walk: ``` >>> position = 0 >>> for _ in range(5): ...
position = position + random.choice([-1, 1]) ... random.random() ``` This method returns the next pseudo-random floating point number in the interval [0.0, 1.0).
Note that the interval given here is in mathematical notation and is not Python syntax.
Example: ``` x = random.random() ``` Here x is assigned a pseudo-random value greater than or equal to zero, and strictly less than 1. ----- What use is this?
We can use this to simulate events with a certain probability, 𝑝. Recall that probabilities are in the interval [0.0, 1.0], where 0.0 represents impossibility, and 1.0 represents certainty.
Anything between these two extremes is interesting. ###### Comprehension check 1.
How would we generate a pseudo-random number in the interval [0.0, 10.0)? ###### Using random.random() to simulate the toss of a biased coin Let’s say we want to simulate the toss of a slightly biased coin—one that’s rigged to come up heads 53% of the time.
Here’s how we’d go about it. ``` if random.random() < 0.53: print("Heads!") else: print("Tails!") ``` This approach is commonly used in simulations in physical or biological modeling, economics, and games. What if you wanted to choose a pseudo-random floating point number in the interval [−100.0, 100.0).
No big deal.
Remember random.random() gives us a pseudo-random number in the interval [0.0, 1.0), so to get a value in the desired interval we simply subtract 0.5 (so the distribution is centered at zero) and multiply by 200 (to “stretch” the result). ``` x = (random.random() - 0.5) * 200 ###### Comprehension check ``` 1.
How would we simulate an event which occurs with a probability of 1/4? 2.
How would we generate a pseudo-random floating point number in the interval [−2.0, 2.0)? ``` random.randint() ``` As noted, we can use random.choice() to choose objects from some iterable.
If we wanted to pick a number from one to ten, we could use ``` n = random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ``` This is correct, but it can get cumbersome.
What if we wanted to choose a pseudo-random number between 1 and 1000? In cases like this, it’s better to use random.randint().
This method takes two arguments representing ----- the upper and lower bound (inclusive).
Thus, to pick a pseudo-random integer between 1 and 1000: ``` n = random.randint(1, 1000) ``` Now we have, 𝑛, such that 𝑛 is an integer, 𝑛≥1, and 𝑛≤1000. ``` random.shuffle() ``` Sometimes, we want to shuffle values, for example a deck of cards. ``` random.shuffle() will shuffle a mutable sequence (for example,...
Example: ``` cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] random.shuffle(cards) ``` Now the cards are shuffled. ###### Comprehension check 1.
random.shuffle() works with a list. Why wouldn’t it work with a tuple? Would it work with a string? 2.
Where’s the bug in this code? ``` >>> import random >>> cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', ...
'10', 'J', 'Q', 'K'] >>> cards = random.shuffle(cards) >>> print(cards) None >>> ###### Other random methods ``` The random module includes many other methods which include generating random numbers sampled from various distributions, and other nifty tools! If you are so inclined—especially if you have some p...
They can’t pluck a random number out of thin air.
You might think that computation by your computer is deterministic and you’d be right. So how do we use a deterministic computing device to produce something that appears random, something that has all the statistical properties we need? Deep down, the random module makes use of an algorithm called the _Mersenne twiste...
This input is called a seed, and from this, the algorithm produces a sequence of pseudo-random numbers.
At each request, we get a new pseudo-random number. ``` >>> import random >>> random.random() 0.16558225561225903 >>> random.random() 0.20717009610984627 >>> random.random() 0.2577426786448077 >>> random.random() 0.5173312574262303 >>> ``` Try this out.
(The sequence of numbers you’ll get will differ.) So where does the seed come in? By default, the algorithm gets a seed from your computer’s operating system.
Modern operating systems provide a special source for this, and if a seed is not supplied in your code, the random module will ask the operating system to supply one.[2] ###### 12.3 Using the seed Most of the time we want unpredictability from our pseudo-random number generator (or choices).
However, sometimes we wish to control the process a little more, for comparability of results. For example, it would be difficult, if not impossible, to test a program whose output is unpredictable.
This is why the random module allows us to provide our own seed. If we start the process from the same seed, the 1M. Matsumoto and T.
Nishimura, 1998, “Mersenne Twister: A 623dimensionally equidistributed uniform pseudorandom number generator”, ACM _Transactions on Modeling and Computer Simulation, 8(1)._ 2If you’re curious, try this: ``` >>> import os # interface to the operating system >>> os.urandom(8) # request a bytestring of size 8 b'\...