Upload
virgil-robinson
View
213
Download
1
Embed Size (px)
Citation preview
StreamsStreamsUsing Python
ByBy Tim WalshTim Walsh
What is a What is a streamstream??Called a “generator” in PythonSimilar to a listFirst made available in Python
2.2, all newer versions make use of this feature
Application of StreamsApplication of StreamsA common application of streams
in other languages is for input/output.
The sys module is where the standard input, output, and error streams can be found in Python:
sys.stdinsys.stdoutsys.stderr
Application of StreamsApplication of StreamsUsing the input and output streams
one can read/write text from/to a file.
At the command line:
~\testFile.py < input.txt~\testFile.py > output.txt
On some windows machines you must specify “python before the file name as in:
~\python testFile.py > input.txt
Application of StreamsApplication of StreamsSimilarly, python programs can be
chained together so that the output from one program is the input to another
~\write.py | read.py
Now the programs are connected, read will take the output from write as its input.
Applications of StreamsApplications of Streamsknown as ‘generators’known as ‘generators’
A stream is similar to a list◦Allows a user to deal with very large
problems without waiting for the entire range of the list to be constructed first
A function that contains a yield statement is called a generator function
A generator function is able to construct the list as needed (specified by the user)
The The Yield Yield StatementStatementYield is a keyword in Python
Yield replaced the required declaration that made generators possible
from __future__ import generators
(No longer needed, just use yield)
Yield can be thought of as a ‘future statement’ and makes generators possible in Python
Applications of StreamsApplications of Streamsknown as ‘generators’known as ‘generators’
A generator is a function which can:◦stop whatever it is doing at an
arbitrary point (the yield statement)◦Return a value back to the function◦Resume from the point it had `yielded
at' later on in the function This is accomplished because ‘yield’
automatically will call the .next() function .next() will get the next element from the
generator-iterator
ExampleExampleProblem:
◦Find the first few prime numbers between a large interval of numbers
Conventional methods require a long list of primes to be generated
Solution◦Using a stream or generator in Python
the problem requires very few calculations, focusing only on the pieces of the computation desired