Text
stringlengths
1
9.41k
This service itself requires a seed, which the OS gets from a variety of hardware sources.
The objective is for the seed to be as unpredictable as possible. ----- sequence of random numbers generated or the sequence of choices made is the same.
For example, ``` >>> import random >>> random.seed(42) # Set the seed. >>> random.random() 0.6394267984578837 >>> random.random() 0.025010755222666936 >>> random.random() 0.27502931836911926 >>> random.seed(42) # Set the seed again, to the same value. >>> random.random() 0.6394267984578837 >>> r...
results.append(random.choice(['a', 'b', 'c'])) ... >>> results ['b', 'a', 'c', 'b', 'a', 'a', 'a', 'c', 'a', 'b'] >>> results = [] >>> random.seed('walrus') >>> for _ in range(10): ...
results.append(random.choice(['a', 'b', 'c'])) ... >>> results ['b', 'a', 'c', 'b', 'a', 'a', 'a', 'c', 'a', 'b'] ``` Notice that the results are identical in both instances.
If we were to perform this experiment 1,000,000 with the same seed, we’d always get the same result.
It looks random, but deep down it isn’t. By setting the seed, we can make the behavior of calls to random methods entirely predictable.
As you might imagine, this allows us to test programs that incorporate pseudo-random number generation or choices. Try something similar with random.shuffle().
Start with a short list, set the seed, and shuffle it. Then re-initialize the list to its original value, set the seed again—with the same value—and shuffle it.
Is the shuffled list the same in both cases? ----- ###### 12.4 Exercises **Exercise 01** Use random.choice() to simulate a fair coin toss.
This method takes an iterable, and at each call, chooses one element of the iterable at random. For example, ``` random.choice([1, 2, 3, 4, 5]) ``` will choose one of the elements of the list, each with equal probability. In a loop simulate 10 coin tosses.
Then report the number of heads and the number of tails. **Exercise 02** Use `random.random() to simulate a fair coin toss.
Remember that` ``` random.random() returns a floating point number in the interval [0.0, 1.0). ``` In a loop simulate 10 coin tosses.
Then report the number of heads and the number of tails. **Exercise 03** Simulate a biased coin toss. You may assume that, in the limit, the biased coin comes up heads 51.7% of the time.
Unlike Exercise 01, ``` random.choice() won’t work because outcomes are not equally probable. ``` In a loop simulate 10 such biased coin tosses.
Then report the number of heads and the number of tails. **Exercise 04** ``` random.shuffle() takes some list as an argument and shuffles the list in ``` _place.
(Remember, lists are mutable, and shuffling in place means that_ ``` random.shuffle() will modify the list you pass in and will return None.) ``` Write a program that shuffles the list ``` ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2'] ``` and then using .pop() in a while loop “deal the cards...
Print each card as it is popped from the list. **Exercise 05** The gambler’s ruin simulates a gambler starting with some amount of money and gambling until they run out.
Probability theory tells us they will always run out of money—it’s just a matter of time. Write a program which prompts the user for some amount of money and then simulates the gambler’s ruin by betting on a fair coin toss.
Use an integer value for the money, and wager one unit on each coin toss. Your program should report the number of coin tosses it took the gambler to go bust. ----- **Exercise 06** Write a program that simulates the throwing of two six-sided dice. In a loop, simulate the throw, and report the results.
For example, if the roll is a two and a five, print “2 + 5 = 7”.
Prompt the user, asking if they want to roll again or quit. **Exercise 07 (challenge!)** Write a program that prompts the user for a number of throws, 𝑛, and then simulates 𝑛 throws of two six-sided dice.
Record the total of dots for each throw. To record the number of dots use a list of integers.
Start with a list of all zeros. ``` counts = [0] * 13 # This gets you a list of all zeros like this: # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # We're going to ignore the element at index zero ``` Then, for each throw of the dice, calculate the total number of dots and increment the corresponding element in th...
For example, if the first three throws are five, five, and nine, then counts should look like this ``` [0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0] ``` After completing 𝑛 rolls, print the result (again, ignoring the element at index 0) and verify with an assertion that the sum of the list equals 𝑛. **Exercise 08** In...
Always. For example, the square of 2 is always 4. You can’t check back later and find that it’s 4.1, or 9, or something else. Applying a function to the same argument will always yield the same result.
If this is not the case, then it’s not a function. Question: Are the functions in the random module truly functions? If so, why?
If not, why not? **Exercise 09 (challenge!)** Revisit the gambler’s ruin from Exercise 05. Modify the program so that it runs 1,000 simulations of the gambler’s ruin, and keeps track of how many times it took for the gambler to run out of money.
However—and this is important—always start with the same amount of money (say 1,000 units of whatever currency you like). Then calculate the mean and standard deviation of the set of simulations. The mean, written 𝜇, is given by ----- 𝜇= [1] 𝑁 𝑁−1 ∑ 𝑥𝑖 𝑖= 0 where we have a set of outcomes, 𝑋, indexed b...
How about the standard deviation? What does all this tell you about gambling? Hint: It makes sense to write separate functions for calculating mean and standard deviation. ----- #### Chapter 13 ### File I/O So far all of the input to our programs and all of the output from our programs has taken place in the conso...
That is, we’ve used input() to prompt for user input, and we’ve used print() to send output to the console. Of course, there are a great many ways to send information to a program and to receive output from a program: mice and trackpads, audio data, graphical user interfaces (“GUIs”, pronounced “gooeys”), temperature s...
We call this “file i/o” which is short for “file input and output.” This is particularly useful when we have large amounts of data to process. In order to read from or write to a file, we need to be able to open and close a file.
We will do this using a context manager. We will also see new exceptions which may occur when attempting to read from or write to a file, specifically FileNotFoundError. **Learning objectives** - You will learn how to read from a file. - You will learn some of the ways to write to a file. - You will learn som...
Context managers relieve some of the burden placed on programmers.
For example, if we open a file, and for some reason something goes wrong and an exception is raised, we still want to ensure that the file is closed.
Before the introduction of the ``` with statement (in Python 2.5, almost twenty years ago), programmers ``` often used try/finally statements (we’ll see more about try when we get to exception handling). We introduce with and context managers in the context of file i/o, because this approach simplifies our code and en...
The idiom we’ll follow is: ``` with open("somefile.txt") as fh: # read from file s = fh.read() ``` When we exit this block (that is, when all the indented code has executed), Python will close the file automatically.
Without this context manager, we’d need to call .close() explicitly, and failure to do so can lead to unexpected and undesirable results. ``` with and as are Python keywords.
Here, with creates the context man ``` ager, and as is used to give a name to our file object.
So once the file is opened, we may refer to it by the name given with as—in this instance ``` fh (a common abbreviation for “file handle”). ###### 13.2 Reading from a file ``` Let’s say we have a .txt file called hello.txt in the same directory as a Python file we just created.
We wish to open the file, read its content and assign it to a variable, and print that variable to the console. This is how we would do this: ``` >>> with open('hello.txt') as f: ...
s = f.read() ... >>> print(s) Hello World! ``` It’s often useful to read one line at a time into a list. ``` >>> lines = [] >>> with open('poem.txt') as f: ... for line in f: ...
lines.append(line) ... ``` ----- ``` >>> print(lines) ["Flood-tide below me!\n", "I see you face to face\n", "Clouds of the west--\n", "Sun there half an hour high--\n", "I see you also face to face.\n"] ``` Now, when we look at the data this way, we see clearly that newline characters are included at the...
Sometimes we wish to remove this. For this we use the string method .strip(). ``` >>> lines = [] >>> with open('poem.txt') as f: ... for line in f: ...
lines.append(line.strip()) ... >>> print(lines) ["Flood-tide below me!", "I see you face to face", "Clouds of the west--", "Sun there half an hour high--", "I see you also face to face."] >>> ``` The string method .strip() without any argument removes any leading or trailing whitespace, newlines, or return...
This is fine, as far as it goes, but often we have more output than we wish to read at the console, or we wish to store output for future use, distribution, or other purposes.
Here we will learn how to write data to a file. With Python, this isn’t difficult. Python provides us with a built-in function open() which returns a file object.
Then we can read from and write to the file, using this object. The best approach to opening a file for writing is as follows: ``` with open('hello.txt', 'w') as f: f.write('Hello World!') ``` Let’s unpack this one step at a time. The open() function takes a file name, an optional mode, and other optional argume...
You may have already guessed that 'w' means “write”, and if so, you’re correct! Python allows for other ways to specify the file, and open() will accept any “path-like” object.
Here we’ll only use strings, but be aware that there are other ways of specifying where Python should look for a given file. ----- There are a number of different modes, some of which can be using in combination.
Quoting from the Python documentation:[1] Character Meaning `'r'` open for reading (default) `'w'` open for writing, truncating the file first `'x'` open for exclusive creation, failing if the file already exists `'a'` open for writing, appending to the end of the file if it exists `'b'` binary mode `'t'` text mode (...
We could have written: ``` with open('hello.txt', 'wt') as f: f.write('Hello World!') ``` explicitly specifying text mode, but this is somewhat redundant.
We will only present reading and writing text data in this text.[2] The idiom with open('hello.txt', 'w') as f: is the preferred approach when reading from or writing to files.
We could write ``` f = open('hello.txt', 'w') f.write('Hello World') f.close() ``` but then it’s our responsibility to close the file when done.
The idiom ``` with open('hello.txt', 'w') as f: will take care of closing the file ``` automatically, as soon as the block is exited. Now let’s write a little more data.
Here’s a snippet from a poem by Walt Whitman (taking some liberties with line breaks): ``` fragment = ["Flood-tide below me!\n", "I see you face to face\n", "Clouds of the west--\n", "Sun there half an hour high--\n", "I see you also face to face.\n"] with open('poem.txt', 'w') a...
Notice that we include newline characters '\n' to end each line. ###### Writing numeric data The .write() method requires a string, so if you wish to write numeric data, you should use str() or f-strings.
Example: ``` import random # Write 10,000 random values in the range [-1.0, 1.0) with open('data.txt', 'w') as f: for _ in range(10_000): x = (random.random() - 0.5) * 2.0 f.write(f"{x}\n") ###### Always use with ``` From the documentation: Warning: Calling f.write() without using the with ke...
Try the above code snippets to write to files `hello.txt and` ``` poem.txt. ``` 2.
Write a program that writes five statements about you to a file called about_me.txt. ###### 13.4 Keyword arguments Some of what we’ll do with files involves using keyword arguments. Thus far, when we’ve called or defined functions, we’ve only seen po_sitional arguments.
For example, math.sqrt(x) and list.append(x) each_ take one positional argument. Some functions take two or more positional arguments.
For example, math.pow(x, y), takes two positional arguments. The first is the base, the second is the power. So this function returns x raised to the y power (𝑥[𝑦]).
Notice that what’s significant here is not the names of the formal parameters but their order. It matters how we supply arguments when calling this function.
Clearly, 2[3] (8) is not the same as 3[2] (9). How does the function know which argument should be used as the base and which argument should be used as the exponent?
It’s all ----- based on their position. The base is the first argument. The exponent is the second argument. Some functions allow for keyword arguments.
Keyword arguments follow positional arguments, and are given a name when calling the function.
For example, print() allows you to provide a keyword argument ``` end which can be used to override the default behavior of print() which ``` is to append a newline character, \n, with every call.
Example: ``` print("Cheese") print("Shop") ``` prints “Cheese” and “Shop” on two different lines, because the default is to append that newline character.
However… ``` print("Cheese", end=" ") print("Shop") ``` prints “Cheese Shop” on a single line (followed by a newline), because in the first call to print() the end keyword argument is supplied with one blank space, " ", and thus, no newline is appended.
This is an example of a keyword argument. In the context of file input and output, we’ll use a similar keyword argument when working with CSV files (comma separated values). ``` open('my_data.csv', newline='') ``` This allows us to avoid an annoying behavior in Python’s CSV module in some contexts.
We’ll get into more detail on this soon, but for now, just be aware that we can, in certain cases, use keyword arguments where permitted, and that the syntax is as shown: positional arguments come first, followed by optional keyword arguments, with keyword arguments supplied in the form keyword=value.
See: The newline='' keyword argument, below. ###### 13.5 More on printing strings Specifying the ending of printed strings By default, the print() function appends a newline character with each call.
Since this is, by far, the most common behavior we desire when printing, this default makes good sense.
However, there are times when we do not want this behavior, for example when printing strings that are terminated with newline characters ('\n') as this would produce two newline characters at the end.
This happens often when reading certain data from a file. In this case, and in others where we wish to override the default behavior of print(), we can supply the keyword argument, ``` end.
The end keyword argument specifies the character (or characters) if ``` any, we wish to append to a printed string. ----- ###### The .strip() method Sometimes—especially when reading certain data from a file—we wish to remove whitespace, including spaces, tabs, and newlines from strings. One approach is to use the...
Without any argument supplied, .strip() removes all leading and trailing whitespace and newlines. ``` >>> s = '\nHello \t \n' >>> s.strip() 'Hello' ``` Or you can specify the character you wish to remove. ``` >>> s = '\nHello \t \n' >>> s.strip('\n') 'Hello \t ' ``` This method allows more complex behavio...
For more on .strip() see: https://docs.python.org/3/library/stdt](https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip) [ypes.html?highlight=strip#str.strip](https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip) ###### 13.6 The csv module There’s a very common format in use f...
Many on-line data sources publish data in this_ format, and all spreadsheet software can read from and write to this format.
The idea is simple: columns of data are separated by commas. That’s it! Here’s an example of some tabular data: Year FIFA champion 2018 France 2014 Germany 2010 Spain 2006 Italy 2002 Brazil Here’s how it might be represented in CSV format: ``` Year,FIFA champion 2018,France 2014,Germany 2010,Spain 2006,Ita...
Usually numbers don’t include comma separators when in CSV format. Instead, commas are ----- added only when data are displayed.
So, for example, we might have data like this (using format specifiers): Country 2018 population China 1,427,647,786 India 1,352,642,280 USA 327,096,265 Indonesia 267,670,543 Pakistan 212,228,286 Brazil 209,469,323 Nigeria 195,874,683 Bangladesh 161,376,708 Russia 145,734,038 and the CSV data would look like this: `...
Oh, OK. Here are cousin David’s favorite bands of all time: ----- Band Rank Lovin’ Spoonful 1 Sly and the Family Stone 2 Crosby, Stills, Nash and Young 3 Earth, Wind and Fire 4 Herman’s Hermits 5 Iron Butterfly 6 Blood, Sweat & Tears 7 The Monkees 8 Peter, Paul & Mary 9 Ohio Players 10 Now there’s no way around co...
For this we wrap the data including commas in quotation marks. ``` Band,Rank Lovin' Spoonful,1 Sly and the Family Stone,2 "Crosby, Stills, Nash and Young",3 "Earth, Wind and Fire",4 Herman's Hermits,5 Iron Butterfly,6 "Blood, Sweat & Tears",7 The Monkees,8 "Peter, Paul & Mary",9 Ohio Players,10 ``` (We’ll save the cas...
We _instantiate this object by calling the constructor function, csv.reader(),_ and we pass to this function the file object we wish to read.
Notice also that we read each row of our data file into a list, where the columns are separated by commas.
That’s very handy! We can write data to a CSV file as well. ``` import csv bands = [['Deerhoof', 1], ['Lightning Bolt', 2], ['Radiohead', 3], ['Big Thief', 4], ['King Crimson', 5], ['French for Rabbits', 6], ['Yak', 7], ['Boygenius', 8], ['Tipsy', 9], [...
However, omitting it could cause problems on a Windows machine and so it’s probably best to include it for maximum portability.
The Python documentation recommends using it. ----- ###### Iterating CSV reader objects Unlike a list, tuple, or string, a CSV reader object can only be iterated once.
This is because a CSV reader object is a type of iterator (which is different from an iterable).[3] An iterator can be iterated only once. Accordingly, if you wish to iterate over a CSV file more than once, you’ll need to create a new CSV reader object each time. ###### 13.7 Exceptions ``` FileNotFoundError ``` This ...
This is almost always due to a typo or misspelling in the filename, or that the correct path is not included. Suppose there is no file in our file system with the name ``` some_non-existent_file.foobar.
Then, if we were to try to open a file ``` without creating it, we’d get a FileNotFoundError. ``` >>> with open("some_non-existent_file.foobar") as fh: ...
s = fh.read() ... Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'some_non-existent_file.foobar' ``` Usually we can fix this by supplying the correct filename or a complete path to the file. 3When iterating over a static i...
However it does not do this when iterating over an iterator, since the iterator itself already exists. ----- ###### 13.8 Exercises Exercise 01 Write a program which writes the following lines (including blank lines) to a file called bashos_frog.txt. ``` Basho's Frog The old pond A frog jumped in, Kerplunk...
If not, go back and revise your program until it works as intended. ###### Exercise 02 [Download the text file at https://www.uvm.edu/~cbcafier/cs1210/b](https://www.uvm.edu/~cbcafier/cs1210/book/data/random_floats.txt) [ook/data/random_floats.txt, and write a program which reads it and](https://www.uvm.edu/~cbcafier...
You may assume that the file is well-formed CSV, with item description in the first field and price in USD in the second field.
What’s wrong, and how can you fix it? ----- ###### Exercise 04 Write a program which writes 10 numbers to a file, closes the file, then reads the 10 numbers from the file, and verifies the correct result.
(Feel free to use assertions to verify.) ###### Exercise 05 Here’s a poem, which is saved with the filename doggerel.txt. ``` Roses are red. Violets are blue. I cannot rhyme. Have you ever seen a wombat? ``` There’s a bug in the following program, which is supposed to read the file containing a poem. ``` w...
This is not intended to be a substitute for a course in statistics.
There are plenty of good textbooks on the subject (and plenty of courses at any university), so what’s presented here is just a little something to get you started in Python. **Learning objectives** - You will gain a rudimentary understanding of two important descriptive statistics: the mean and standard deviation....