Wednesday, July 5, 2017

Summer of code 2017: Python, Day 18 Iterables


As explained in my Summer of code 2017: Python post I decided to pick up Python

This is officially day 18. today I will take a look at iterables


Comprehensions

A comprehension is a list, a set or a dictionary that is computed via a set of looping and filtering instructions. The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses

List Comprehensions

The basic syntax for list comprehensions looks like this

[expr(item) for item in iterable]

Here is an example in code, the code below returns the length for each item in the list

>>> words= "A comprehension is a list, a set or a dictionary that is computed via a set
 of looping and filtering instructions".split()
>>> words
['A', 'comprehension', 'is', 'a', 'list,', 'a', 'set', 'or', 'a', 'dictionary', 'that',
 'is', 'computed', 'via', 'a', 'set', 'of', 'looping', 'and', 'filtering', 'instructions']
>>> [len(word) for word in words]
[1, 13, 2, 1, 5, 1, 3, 2, 1, 10, 4, 2, 8, 3, 1, 3, 2, 7, 3, 9, 12]
>>> 

Pretty simple stuff, nothing too complicated here


Set Comprehensions

The basic syntax for set comprehensions looks like this

{expr(item) for item in iterable}

Here is an example in code, the code below returns the length as well as the max character for each item of the set

>>> x = {'abc','def','vvv','nnn'}
>>> type(x)
<class 'set'>
>>> {len(str(x)) for x in x}
{3}
>>> {max(str(x)) for x in x}
{'f', 'v', 'n', 'c'}
>>> 

As you can see the set is distinct, the number 3 is only returned once. Also the set is unordered



Dictionary Comprehensions


The basic syntax for dictionary comprehensions looks like this

{ key_expr:value_expr  for item in iterable }

Here is an example in code, the code below will swap the key value pair

>>> stocks ={
'TGT' :  '51.33', 
'AAPL': '147.48',
'MSFT':  '71.49',
'F'   :  '11.12', 
'INTC':  '34.37'}
>>> stocks
{'TGT': '51.33', 'AAPL': '147.48', 'MSFT': '71.49', 'F': '11.12', 'INTC': '34.37'}
>>> price_to_stock = {ticker: price for price, ticker in stocks.items()}
>>> price_to_stock
{'51.33': 'TGT', '147.48': 'AAPL', '71.49': 'MSFT', '11.12': 'F', '34.37': 'INTC'}
>>> 


We can make it more interesting by using a condition and only return the key value pair if the price is the max price for that ticker. I added a price of 1000 for AAPL and a price of 5000 for F. As you can see in the code below, I have used a filtering predicate if max(price)

>>> stocks ={
'TGT' :  '51.33', 
'AAPL': '147.48',
'AAPL': '1000',
'MSFT':  '71.49',
'F'   :  '11.12', 
'F'   :  '5000',
'INTC':  '34.37'}
>>> price_to_stock = {price: ticker for ticker, price in stocks.items() if max(price)}
>>> price_to_stock
{'51.33': 'TGT', '1000': 'AAPL', '71.49': 'MSFT', '5000': 'F', '34.37': 'INTC'}
>>> 

As you can see for Apple (AAPL), we return the pair with the price of 1000, for F (Ford), we return the pair with the price of 5000, the other prices for AAPL and F are not returned

Generators

Iterator

An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream.

>>> i = ['a', 'b', 'c', 'd' ]
>>> iterator =iter(i)
>>> next(iterator)
'a'
>>> next(iterator)
'b'
>>> next(iterator)
'c'
>>> 

When no more data is available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again.

Here is what that looks like

>>> next(iterator)
'd'
>>> next(iterator)
Traceback (most recent call last):
  File "", line 1, in 
    next(iterator)
StopIteration
>>> 

We can trap this by checking for the StopIteration exception, here is an example

>>> try:
 next(iterator)
except(StopIteration):
    print ('max value reached')

    
max value reached
>>> 



I also looked at itertools, itertools  implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.

Here are some of these iterators

count()
cycle()
repeat()

accumulate()
chain()
chain.from_iterable()
compress()
dropwhile()
filterfalse()
groupby()
islice()
starmap()
takewhile()
tee()
zip_longest()


That was all for today, next I will look at classes

No comments: