Presentation is loading. Please wait.

Presentation is loading. Please wait.

Streams Using Python ByTim Walsh. What is a stream? Called a “generator” in Python Similar to a list First made available in Python 2.2, all newer versions.

Similar presentations


Presentation on theme: "Streams Using Python ByTim Walsh. What is a stream? Called a “generator” in Python Similar to a list First made available in Python 2.2, all newer versions."— Presentation transcript:

1 Streams Using Python ByTim Walsh

2 What is a stream? Called a “generator” in Python Similar to a list First made available in Python 2.2, all newer versions make use of this feature

3 Application of Streams A 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.stdin sys.stdout sys.stderr

4 Application of Streams Using 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

5 Application of Streams Similarly, 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.

6 Applications of Streams 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)

7 The Yield Statement Yield 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

8 Applications of Streams 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

9 Example Problem: ◦ 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


Download ppt "Streams Using Python ByTim Walsh. What is a stream? Called a “generator” in Python Similar to a list First made available in Python 2.2, all newer versions."

Similar presentations


Ads by Google