Oh, pshaw!

 

cs490_august27

Page history last edited by pshaw 1 year, 2 months ago
Python's Dictionaries


List Comprehension

List Comprehension is an odd syntax for generating list that was taken straight from a language called Haskell. (Dr. Cunningham is a big fan of Haskell.) The syntax for list comprehension works like this:

[expressionforiterator valueinlistifconditional statement]

>>> [i for i in range(3)]
[0, 1, 2]
>>> [i+1 for i in range(3)]
[1, 2, 3]
>>> [i**2 for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [i for i in range(100) if i % 2 == 1]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
>>>
>>>
>>> binary = "00101010"
>>> [2**i for i in range(7,-1,-1)]
[128, 64, 32, 16, 8, 4, 2, 1]
>>> times = [2**i for i in range(7,-1,-1)]
>>> [i for i in range(8)]
[0, 1, 2, 3, 4, 5, 6, 7]
>>> [2**i for i in range(7,-1,-1)]
[128, 64, 32, 16, 8, 4, 2, 1]
>>> times = [2**i for i in range(7,-1,-1)]
>>>
>>> [int(binary[i])*times[i] for i in range(8)]
[0, 0, 32, 0, 8, 0, 2]
>>> sum([int(binary[i])*times[i] for i in range(8)])
42
>>> sum([int(binary[i])*(2**(len(binary)-1-i)) for i in range(len(binary))])
42
>>> [int(binary[i])*(2**(len(binary)-1-i)) for i in range(len(binary))]
[0, 0, 32, 0, 8, 0, 2, 0]

Prime numbers with List Comprehension using the Sieve of Eratosthenes technique:

>>> primes = range(2,120)
>>> i = 0
>>> while i < len(primes):
...     primes = [x for x in primes if x % primes[i] != 0 or x == primes[i]]
...     i = i + 1
...
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]

For extremely large list, this technique is slow. This is a less elegant, but more efficient method:

def seive(count):
primes = range(2,count)
i = 0
while i < len(primes):
j = i+1
while j < len(primes):
if primes[j] % primes[i] == 0:
del primes[j]
j = j + 1
i = i + 1
return primes

Python's Dictionaries

A dictionary is the Python word for associative arrays or hash tables. A dictionary is used to look up definitions of words. The definition of a word themselves are found based on how the word is spelled and nothing more. A dictionary is different from a list in that a list is a sequential ordering of values, where as a dictionary is a random-ordering of values. The ordering of the values appears random to us (similar to the groupings of words in a real dictionary), but Python decides the ordering based on how quickly the value can be accessed based on the input key.

Dictionaries require keys to be mapped to values. In Python...

  • a dictionary is declared using {} symbols.
  • vales are called from the dictionary using the [] notation (which is identical to list).
  • A key-value pair is defined by two pieces of data separated by the : (colon) symbol.
  • key-value pairs is separated by the , (comma) symbol.
  • The value of a key-value pair are normal containers, meaning they can hold any normal data structure.
  • The key of a key-value pair is limited to holding hashable types, such as numbers or strings. Data structures such as list and dictionaries are not hashable, therefore they can not be made the key inside a key-value pair.
>>> dict = {}
>>> dict
{}
>>>
>>> single = {"planet":"Earth"}
>>> single["planet"]
'Earth'
>>>
>>> pets = {"dog":"Fido.", "cat":"Mittens."}
>>> pets
{'dog': 'Fido.', 'cat': 'Mittens.'}
>>> pets['dog']
'Fido.'
>>> pets['cat']
'Mittens.'
>>>
>>> numbers
{64: 'squares on a checkerboard', 3: 'Stooges', 12: 'items in a dozen'}
>>> numbers[3]
'Stooges'
>>> numbers[12]
'items in a dozen'
>>> numbers[64]
'squares on a checkerboard'
>>> numbers[0]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 0
>>> len(numbers)
3

Even after a key-value pair has been set, it can be updated and modified:

>>> pets
{'dog': 'Fido.', 'cat': 'Mittens.'}
>>> pets["mouse"] = "Squeak" # Add a new pet "mouse"
>>> pets
{'mouse': 'Squeak', 'dog': 'Fido.', 'cat': 'Mittens.'}
>>> del pets["cat"] # Delete the pet "cat"
>>> pets
{'mouse': 'Squeak', 'dog': 'Fido.'}

There are several built-in functions that assist with working with Dictionaries.

>>> numbers
{64: 'squares on a checkerboard', 3: 'Stooges', 12: 'items in a dozen'}
>>> len(numbers)
3
>>> numbers.keys()
[64, 3, 12]
>>> numbers.values()
['squares on a checkerboard', 'Stooges', 'items in a dozen']

Working with a dictionary in real problems:

>>> hhga = """And Saint Attila raised the hand grenade up on high, saying, "O Lord, bless this Thy hand grenade that with it Thou mayest blow Thine enemies to tiny bits, in Thy mercy." And the Lord did grin and the people did feast upon the lambs and sloths and carp and anchovies and orangutans and breakfast cereals, and fruit bats and large chu... [At this point, the friar is urged by Brother Maynard to "skip a bit, brother"]... And the Lord spake, saying, "First shalt thou take out the Holy Pin, then shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thy foe, who being naughty in my sight, shall snuff it." Amen"""
>>>
>>>
>>>
>>> words = {}
>>> for w in hhga.lower().split():
...     if w in words:
...         words[w] += 1
...     else:
...         words[w] = 1
...
>>> words
{'being': 2, 'lobbest': 1, 'four': 1, 'more,': 1, 'blow': 1, 'to': 4, 'lord': 2, 'then': 3, 'sight,': 1, 'five': 1, 'not': 1, 'grin': 1, 'attila': 1, 'did': 2, 'feast': 1, 'brother': 1, 'large': 1, 'friar': 1, 'right': 1, 'people': 1, '"first': 1, 'mayest': 1, 'enemies': 1, 'maynard': 1, 'excepting': 1, 'chu...': 1, 'bless': 1, 'neither': 1, 'carp': 1, 'foe,': 1, 'be': 3, 'orangutans': 1, 'amen': 1, '"skip': 1, 'antioch': 1, 'sloths': 1, 'by': 1, 'on': 1, 'less.': 1, 'thou': 8, 'of': 2, 'urged': 1, 'brother"]...': 1, 'thine': 1, 'spake,': 1, 'out.': 1, 'raised': 1, 'naughty': 1, 'snuff': 1, 'number': 3, 'bats': 1, 'two,': 1, 'proceed': 1, 'three': 1, 'tiny': 1, 'saint': 1, 'count,': 2, 'holy': 2, 'that': 2, 'three.': 2, 'three,': 2, 'with': 1, 'count': 2, 'bit,': 1, 'third': 1, 'this': 2, 'pin,': 1, 'cereals,': 1, 'anchovies': 1, 'my': 1, 'grenade': 3, 'and': 12, 'bits,': 1, 'up': 1, 'is': 2, '"o': 1, 'it': 1, 'high,': 1, 'in': 2, 'lambs': 1, 'counting': 1, 'breakfast': 1, 'mercy."': 1, 'no': 2, 'point,': 1, 'it."': 1, 'take': 1, 'out': 1, 'towards': 1, 'shall': 3, 'number,': 1, 'who': 1, 'upon': 1, 'hand': 3, 'fruit': 1, 'lord,': 1, 'shalt': 4, 'a': 1, 'thy': 4, '[at': 1, 'reached,': 1, 'the': 12, 'saying,': 2, 'once': 1}

Comments (0)

You don't have permission to comment on this page.