Functional Python Programming by Steven F. Lott

Functional Python Programming by Steven F. Lott

Author:Steven F. Lott [Steven F. Lott]
Language: eng
Format: epub
Tags: COM051210 - COMPUTERS / Programming / Object Oriented, COM051360 - COMPUTERS / Programming Languages / Python, COM051440 - COMPUTERS / Software Development and Engineering / Tools
Publisher: Packt Publishing
Published: 2018-04-12T11:54:35+00:00


Repeating a single value with repeat()

The repeat() function seems like an odd feature: it returns a single value over and over again. It can serve as an alternative for the cycle() function when a single value is needed.

The difference between selecting all of the data and selecting a subset of the data can be expressed with this. The function (x==0 for x in cycle(range(size))) emits a [True, False, False, ...] pattern, suitable for picking a subset. The function (x==0 for x in repeat(0)) emits a [True, True, True, ...] pattern, suitable for selecting all of the data.

We can think of the following kinds of commands:

all = repeat(0) subset = cycle(range(100)) choose = lambda rule: (x == 0 for x in rule)

# choose(all) or choose(subset) can be used

This allows us to make a simple parameter change, which will either pick all data or pick a subset of data. This pattern can be extended to randomize the subset chosen. The following technique adds an additional kind of choice:

def randseq(limit):

while True:

yield random.randrange(limit)

randomized = randseq(100)

The randseq() function generates a potentially infinite sequence of random numbers over a given range. This fits the pattern of cycle() and repeat().

This allows code such as the following:

[v for v, pick in zip(data, choose(all)) if pick]

[v for v, pick in zip(data, choose(subset)) if pick]

[v for v, pick in zip(data, choose(randomized)) if pick]

Using chose(all), chose(subset), or chose(randomized) is a succinct expression of which data is selected for further analysis.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.