348 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
At this point, the user might want to know which letters are in the top three most likely list for
each subkey. If the SILENT_MODE constant was set to False, then the code on lines 178 to 184
will print out the values in allFreqScores to the screen.
Whenever the print() function is called, it will print the string passed to it on the screen along
with a newline character. If we want something else printed at the end of the string instead of a
newline character, we can specify the string for the print() function’s end keyword argument.
Try typing the following into the interactive shell:
print('HEllo', end='\n')
HEllo
print('Hello', end='\n')
Hello
print('Hello', end='')
Hello>>> print('Hello', end='XYZ')
HelloXYZ>>>
(The above was typed into the python.exe interactive shell rather than IDLE. IDLE will always
add a newline character before printing the >>> prompt.)
The itertools.product() Function
The itertools.product() function produces every possible combination of items in a list
or list-like value, such as a string or tuple. (Though the itertools.product() function
returns a “itertools product” object value, this can be converted to a list by passing it to list().)
This combination of things is called a Cartesian product, which is where the function gets its
name. Try typing the following into the interactive shell:
import itertools
itertools.product('ABC', repeat=4)
<itertools.product object at 0x02C40170>
list(itertools.product('ABC', repeat=4))
[('A', 'A', 'A', 'A'), ('A', 'A', 'A', 'B'), ('A', 'A', 'A', 'C'), ('A', 'A',
'B', 'A'), ('A', 'A', 'B', 'B'), ('A', 'A', 'B', 'C'), ('A', 'A', 'C', 'A'),
('A', 'A', 'C', 'B'), ('A', 'A', 'C', 'C'), ('A', 'B', 'A', 'A'), ('A', 'B',
'A', 'B'), ('A', 'B', 'A', 'C'), ('A', 'B', 'B', 'A'), ('A', 'B', 'B', 'B'),
...skipped for brevity...
('C', 'B', 'C', 'B'), ('C', 'B', 'C', 'C'), ('C', 'C', 'A', 'A'), ('C', 'C',
'A', 'B'), ('C', 'C', 'A', 'C'), ('C', 'C', 'B', 'A'), ('C', 'C', 'B', 'B'),
('C', 'C', 'B', 'C'), ('C', 'C', 'C', 'A'), ('C', 'C', 'C', 'B'), ('C', 'C',
'C', 'C')]