Text
stringlengths
1
9.41k
The numbers are called pseudo_random numbers because, coming from a mathematical process, they are not truly random, though,_ for all intents and purposes, they appear random.
Anyone who knows the process can recreate the numbers.
This is good for scientific and mathematical applications, where you want to be able to recreate the same random numbers for testing purposes, but it is not suitable for cryptography, where you need to generate truly random numbers. **Seeds** For mathematical and scientific applications, you may want to reproduce the ...
You can do this by specifying the seed.
Examples are shown below: random.seed(1) **print("Seed 1:", [random.randint(1,10) for i in range(5)])** random.seed(2) **print("Seed 2:", [random.randint(1,10) for i in range(5)])** random.seed(1) **print("Seed 1:",[random.randint(1,10) for i in range(5)])** ###### Seed 1: [2, 9, 8, 3, 5] Seed 2: [10, 10, 1, 1, 9] Se...
If we just use random.seed(), then the seed will be more or less randomly selected based off of the system clock. **The random function** Most of the functions in the random module are based off of the random function, which uses the Mersenne Twister to generate random numbers between 0 and 1.
Mathematical transformations are then used on the result of random to get some of the more interesting random number functions. **Other functions in the random module** The random module contains functions that return random numbers from various distributions, like the Gaussian or exponential distributions.
For instance, to generate a Gaussian (normal) random variable, use the gauss function.
Here are some examples: random.gauss(64,3.5) [round(random.gauss(64,3.5),1) for i in range(10)] ###### 61.37965975173485 [58.4, 61.0, 67.0, 67.9, 63.2, 65.0, 64.5, 63.4, 65.5, 67.3] The first argument of gauss is the mean and the second is the standard deviation.
If you’re not familiar with normal random variables, they are the standard bell curve. Things like heights and SAT scores and many other real-life things approximately fit this distribution.
In the example above, the random numbers generated are centered around 64. Numbers closer to 64 are more likely to be generated than numbers farther away. ----- 228 _CHAPTER 22.
MATH_ There are a bunch of other distributions that you can use. The most common is the uniform distribution, in which all values in a range are equally likely.
For instance: random.uniform(3,8) See the Python documentation [1] for information on the other distributions. **A more random randint function** One way to generate cryptographically safe random numbers is to use some fairly random physical process.
Examples include radioactive decay, atmospheric phenomena, and the behavior of certain electric circuits.
The os module has a function urandom that generates random numbers from a physical process whose exact nature depends on your system.
The urandom function takes one argument telling it how many bytes of random data to produce. Calling urandom(1) produces one byte of data, which we can translate to an integer between 0 and 255.
Calling urandom(2) produces two bytes of data, translating to integers between 0 and 65535.
Here is a function that behaves like randint, but uses urandom to give us nondeterministic random numbers: **from os import urandom** **from math import log** **def urandint(a,b):** x = urandom(int(log(b-a+1)/log(256))+1) total = 0 **for (i,y) in enumerate(x):** total += y*(2**i) **return total%(b-a+1)+a** The ...
We then loop through the bytes generated and convert them to an integer.
Finally, modding that integer by b-a+1 reduces that integer to a number between 0 and b-a+1, and adding a to that produces an integer in the desired range. ###### 22.9 Miscellaneous topics **Hexadecimal, octal, and binary** Python has built-in functions hex, oct, and bin for converting integers to hexadecimal, octal,...
The int function converts those bases to base 10. Here are some examples: **hex(250)** **oct(250)** **bin(250)** **int(0xfa)** ----- _22.10.
USING THE PYTHON SHELL AS A CALCULATOR_ 229 '0o372' '0b11111010' ###### 250 Hexadecimal values are prefaced with 0x, octal values are prefaced with 0o and binary values are prefaced with 0b. **The int function** The int function has an optional second argument that allows you to specify the base you are converting f...
Here are a few examples: **int('101101', 2)** _# convert from base 2_ **int('121212', 3)** _# convert from base 3_ **int('12A04', 11)** _# convert from base 11_ **int('12K04', 23)** _# convert from base 23_ **The pow function** Python has a built-in function called pow, which raises numbers to powers.
It behaves like the ** operator, except that it takes an optional third argument that specifies a modulus. Thus pow(x,y,n) returns (x**y)%n.
The reason you might want to use this is that the pow way is much quicker when very large numbers are involved, which happens a lot in cryptographic applications. ###### 22.10 Using the Python shell as a calculator I often use the Python shell as a calculator.
This section contains a few tips for working at the shell. **Importing math functions** One good way to start a session at the shell is to import some math functions: **from math import *** **Special variable** There is a special variable _ which holds the value of the previous calculation. Here is an example: ---...
MATH_ **Logarithms** I use the natural logarithm a lot, and it is more natural for me to type ln instead of log.
If you want to do that, just do the following: ln = log **Summing a series** Here is a way to get an approximate sum of a series, in this case �∞n=1 _n[2]1−1_ [:] ###### >>> sum([1/(n**2-1) for n in range(2,1000)]) 0.7489994994995 **Another example:** Say you need the sine of each of the angles 0, 15, 30, 45, 60,...
Here is a quick way to do that: ###### >>> [round(sin(radians(i)),4) for i in range(0,91,15)] [0.0, 0.2588, 0.5, 0.7071, 0.866, 0.9659, 1.0] **Third-party modules** There are a number of other third-party modules that you might find useful when working in the Python shell.
For instance, there is Numpy and Scipy, which we mentioned [in Section 22.7.
There is also Matplotlib, a versatile library for plotting things, and there is Sympy,](http://sympy.org/en/index.html) which does symbolic computations. ----- ### Chapter 23 ## Working with functions This chapter covers a number of topics to do with functions, including some topics in functional programming. ###...
WORKING WITH FUNCTIONS_ Here is another example. Say you have a program with ten different functions and the program has to decide at runtime which function to use.
One solution is to use ten if statements. A shorter solution is to use a list of functions.
The example below assumes that we have already created functions f1, f2, ..., f10, that each take two arguments. funcs = [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10] num = eval(input('Enter a number: ')) funcs[num]((3,5)) **Functions as arguments to functions** Say we have a list of 2-tuples.
If we sort the list, the sorting is done based off of the first entry as below: L = [(5,4), (3,2), (1,7), (8,1)] L.sort() ###### [(1, 7), (3, 2), (5, 4), (8, 1)] Suppose we want the sorting to be done based off the second entry.
The sort method takes an optional argument called key, which is a function that specifies how the sorting should be done. Here is how to sort based off the second entry: **def comp(x):** **return x[1]** L = [(5,4), (3,2), (1,7), (8,1)] L.sort(key=comp) ###### [(8, 1), (3, 2), (5, 4), (1, 7)] Here is another examp...
Here is the code again: **def comp(x):** **return x[1]** L.sort(key=comp) If we have a really short function that we’re only going to use once, we can use what is called an anonymous function, like below: ----- _23.3.
RECURSION_ 233 L.sort(key=lambda x: x[1]) The lambda keyword indicates that what follows will be an anonymous function.
We then have the arguments to the function, followed by a colon and then the function code.
The function code cannot be longer than one line. We used anonymous functions back when working with GUIs to pass information about which button was clicked to the callback function.
Here is the code again: **for i in range(3):** **for j in range(3):** b[i][j] = Button(command = lambda x=i,y=j: function(x,y)) ###### 23.3 Recursion Recursion is the process where a function calls itself.
One of the standard examples of recursion is the factorial function. The factorial, n!, is the product of all the numbers from 1 up to n. For instance, 5! = 5·4·3·2·1 = 120. Also, by convention, 0!
= 1. Recursion involves defining a function in terms of itself. Notice that, for example, 5! = 5 _·_ 4!, and in general, n! = n _·_ (n _−_ 1)!.
So the factorial function can be defined in terms of itself.
Here is a recursive version of the factorial function: **def fact(n):** **if n==0:** **return 1** **else:** **return n*fact(n-1)** We must specify the n = 0 case or else the function would keep calling itself forever (or at least until Python generates an error about too many levels of recursion). Note that the ...
Note also that there is a non-recursive way to do the factorial, using a for loop. It is about as straightforward as the recursive way, but faster.
However, for some problems the recursive solution is the more straightforward solution.
Here, for example, is a program that factors a number into prime factors. **def factor(num, L=[]):** **for i in range(2,num//2+1):** **if num%i==0:** **return L+[i]+factor(num//i)** **return L+[num]** The factor function takes two arguments: a number to factor, and a list of previously found factors.
It checks for a factor, and if it finds one, it appends it to the list.
The recursive part is that it divides the number by the factor that was found and then appends to the list all the factors of that value.
On the other hand, if the function doesn’t find any factors, it appends the number to the list, as it must be a prime, and returns the new list. |tance, 5! = 5·4·3·2·1 = 120. Also, by convention, 0!
= 1. Recursion involves defining a function erms of itself. Notice that, for example, 5! = 5·4!, and in general, n! = n·(n−1)!. So the factorial ction can be defined in terms of itself.
Here is a recursive version of the factorial function:|Col2| |---|---| ||| |def fact(n): if n==0: return 1 else: return n*fact(n-1)|| |te that the math module has a function called factorial, so this version here is just for demon- ation.
Note also that there is a non-recursive way to do the factorial, using a for loop. It is about straightforward as the recursive way, but faster.
However, for some problems the recursive so- on is the more straightforward solution.
Here, for example, is a program that factors a number o prime factors.|Col2| |---|---| ||| |def factor(num, L=[]): for i in range(2,num//2+1): if num%i==0: return L+[i]+factor(num//i) return L+[num]|| ----- 234 _CHAPTER 23.
WORKING WITH FUNCTIONS_ ###### 23.4 map, filter, reduce, and list comprehensions map and filter Python has a built-in functions called map and filter that are used to apply functions to the contents of a list.
They date back to before list comprehensions were a part of Python, but now list comprehensions can accomplish everything these functions can.
Still, you may occasionally see code using these functions, so it is good to know about them. The map function takes two arguments—a function and an iterable—and it applies the function to each element of the iterable, generating a new iterable.
Here is an example that takes a list of strings a returns a list of the lengths of the strings.
The first line accomplishes this with map, while the second line uses list comprehensions: L = list(map(len, ['this', 'is', 'a', 'test'])) L = [len(word) for word in ['this', 'is', 'a', 'test']] The function filter takes a function and an iterable and returns an iterable of all the elements of the list for which the ...
Here is an example that returns all the words in a list that have length greater than 2.
The first line uses filter to do this, and the second line does it with a list comprehension: L = list(filter(lambda x: len(x)>2, ['this', 'is', 'a', 'test'])) L = [word for word in ['this', 'is', 'a', 'test'] if len(word)>2] Here is one approach to finding the number of items in a list L that are greater than 60: c...
It used to be a built-in function, but in Python 3 it has also been moved to the functools module. This function cannot be easily replaced with list comprehensions.
To understand it, first consider a simple example that adds up the numbers from 1 to 100. total = 0 **for i in range(1,101):** total = total + i The reduce function can be used to do this in a single line: total = reduce(lambda x,y: x+y, range(1,101)) In general, reduce takes a function and an iterable, and appl...
As another simple example, the factorial function could be implemented using reduce: ----- _23.5.
THE OPERATOR MODULE_ 235 **def fact(n):** **return reduce(lambda x,y:x*y, range(1,n+1))** ###### 23.5 The operator module In the previous section, when we needed a function to represent a Python operator like addition or multiplication, we used an anonymous function, like below: total = reduce(lambda x,y: x+y, ...
These will run faster than anonymous functions.
We can rewrite the above example like this: **from operator import add** total = reduce(add, range(1,101)) The operator module has functions corresponding arithmetic operators, logical operators, and even things like slicing and the in operator. ###### 23.6 More about function arguments You may want to write a func...
An example is the print function where you can enter however many things you want to print, each separated by commas. Python allows us to declare a special argument that collects several other arguments into a tuple. This syntax is demonstrated below: **def product(*nums):** prod = 1 **for i in nums:** prod*=i **r...
Here is a simple example: **def f(**keyargs):** **for k in keyargs:** **print(k, '**2 : ', keyargs[k]**2, sep='')** f(x=3, y=4, z=5) ###### y**2 : 16 ----- 236 _CHAPTER 23.
WORKING WITH FUNCTIONS_ ###### x**2 : 9 z**2 : 25 You can also use these notations together with ordinary arguments.
The order matters—arguments collected by * have to come after all positional arguments and arguments collected by ** always come last.
Two example function declarations are shown below: **def func(a, b, c=5, *d, **e):** **def func(a, b, *c, d=5, **e):** **Calling functions** The * and ** notations can be used when calling a function, too.
Here is an example: **def f(a,b):** **print(a+b)** x=(3,5) f(*x) This will print 8. In this case we could have more simply called f(3,5), but there are situations when that is not possible.
For example, maybe you have several different sets of arguments that your program might use for a function.
You could have several if statements, but if there are a lot of different sets of arguments, then the * notation is much easier.
Here is a simple example: **def f(a,b):** **print(a+b)** args = [(1,2), (3,4), (5,6), (7,8), (9,10)] i = eval(input('Enter a number from 0 to 4: ')) f(*args[i]) One use for the ** notation is simplifying Tkinter declarations.
Suppose we have several widgets that all have the same properties, say the same font, foreground color, and background color.
Rather than repeating those properties in each declaration, we can save them in a dictionary and then use the ** notation in the declarations, like below: args = {'fg':'blue', 'bg':'white', 'font':('Verdana', 16, 'bold')} label1 = Label(text='Label 1', **args) label2 = Label(text='Label 2', **args) ###### apply Pytho...
You may see it in older code. **Function variables that retain their values between calls** Sometimes it is useful to have variables that are local to a function that retain their values between function calls.
Since functions are objects, we can accomplish this by adding a variable to the function as if it were a more typical sort of object. In the example below the variable f.count keeps track of how many times the function is called. **def f():** f.count = f.count+1 **print(f.count)** f.count=0 ----- ### Chapter 24...
We will start with some functions in itertools. ###### 24.1 Permutations and combinations **Permutations** The permutations of a sequence are rearrangements of the items of that sequence. For example, some permutations of [1,2,3] are [3,2,1] and [1,3,2].
Here is an example that shows all the possibilities: **list(permutations([1,2,3]))** We can find the permutations of any iterable.
Here are the permutations of the string '123': [''.join(p) for p in permutations('123')] The permutations function takes an optional argument that allows us to specify the size of the permutations.
For instance, if we just want all the two-element substrings possible from '123', we can do the following: [''.join(p) for p in permutations('123', 2)] Note that permutations and most of the other functions in the itertools module return an iterator.
You can loop over the items in an iterator and you can use list to convert it to a list. 237 ----- 238 _CHAPTER 24.
THE ITERTOOLS AND COLLECTIONS MODULES_ **Combinations** If we want all the possible k-element subsets from a sequence, where all that matters is the elements, not the order in which they appear, then what we want are combinations. For instance, the 2-element subsets that can be made from 1,2,3 are 1,2, 1,3 and 2,3 .
We _{_ _}_ _{_ _}_ _{_ _}_ _{_ _}_ consider 1,2 and 2,1 as being the same because they contain the same elements.
Here is an _{_ _}_ _{_ _}_ example showing the combinations of two-element substrings possible from '123': [''.join(c) for c in combinations('123', 2)] **Combinations with replacement** For combinations with repeated elements, use the function combinations_with_replacement. [''.join(c) for c in combinations_wit...
The Cartesian product of two sets X and Y consists of all pairs (x, y) where x is in X and y is in Y .
Here is a short example: [''.join(p) for p in product('abc', '123')] **Example** To demonstrate the use of product, here are three progressively shorter, and clearer ways to find all one- or two-digit Pythagorean triples (values of (x, y, _z) satisfying x_ [2] + y [2] = z[2]). The first way uses nested for loops: ...
GROUPING THINGS_ 239 ###### 24.3 Grouping things The groupby function is handy for grouping things.
It breaks a list up into groups by tracing through the list and every time there is a change in values, a new group is created.
The groupby function returns ordered pairs that consist of a list item and groupby iterator object that contains the group of items. L = [0, 0, 1, 1, 1, 2, 0, 4, 4, 4, 4, 4] **for key,group in groupby(L):** **print(key, ':', list(group))** ###### 0 : [0, 0] 1 : [1, 1, 1] 2 : [2] 0 : [0] 4 : [4, 4, 4, 4, 4] Notice t...
This is because groupby returns a new group each time there is a change in the list.
In the above example, if we instead just wanted to know how many of each number occur, we can first sort the list and then call groupby. L = [0, 0, 1, 1, 1, 2, 0, 4, 4, 4, 4, 4] L.sort() **for key,group in groupby(L):** **print(key, ':', len(list(group)))** Most of the time, you will want to sort your data before c...
When using this, you usually have to first sort the list with that function as the sorting key.
Here is an example that groups a list of words by length: L = ['this', 'is', 'a', 'test', 'of', 'groupby'] L.sort(key = len) **for key,group in groupby(L, len):** **print(key, ':', list(group))** ###### 1 : ['a'] 2 : ['is', 'of'] 4 : ['test', 'this'] 7 : ['groupby'] **Examples** We close this section with two examp...
THE ITERTOOLS AND COLLECTIONS MODULES_ First, suppose L is a list of zeros and ones, and we want to find out how long the longest run of ones is.