[Tutor] collections and mappings

Alan Gauld alan.gauld at yahoo.co.uk
Fri Jun 21 04:11:03 EDT 2019


On 21/06/2019 01:01, mhysnm1964 at gmail.com wrote:

> I have reviewed the collection module and do not understand mappings. I have
> seen this in other languages and have never got the concept. Can someone
> explain this at a very high level.  

OK. You are a master of the open ended question so I'm
not sure what aspect you don't understand.
But I'll start at the beginning and take it as far as Python.
But you are opening a vary large can of worms...

Mappings, in programming terms, are related to a mathematical concept.
See Wikipedia for a more detailed account of math mapping.

In simplistic terms a mapping comprises two sets of data, one an input
the other an output. The map is the set of relationships between input
and output. Thus given input of {a, b, c} and output of {1,2,3,4,5}
We might have any of several mappings between these. A simple 1:1
mapping might be

{a,1}, {b,2}, {c,3}

But we can have 1:N or N:1 or N:M mappings too:

{a,1,2} {b,3} {c,4}     - a 1:N mapping
{a,1} {b,1}, {c,3}      - an N:1 mapping
{a,1,2} {b,2},{c,1,3}   - a N:M mapping

Note that the mapping does not have to include all of
the output elements.

The mapping may be arbitrary, as above or it may be defined
as a function:

{a, f(a)} {b,f(b)} {c,f(c)}

Or even as a set of functions...

In programming, and particularly in Python, this tends to
be represented as a dictionary (or sometimes a class).

So the mappings above could be shown as:

input = ['a','b','c']
output = [1,2,3]
1_1 = {'a':1,'b':2,'c':3}
1_N = {'a':(1,2)'b':(1,),'c':(3,)}
N_1 = {'a':1,'b':1,'c':3}
N_M = {'a':(1,2),'b':(2,),'c:(1,3)}

def f(x): return x*2
1_f = {'a':f('a'),'b':f('b'),'c':f('c')}

List comprehensions and generator expressions are also
commonly used to create mappings, especially the functional
sort.

I have no idea if the addressed any of your questions
but if not please ask again, but with something more specific.

PS. To the real mathematicians on the list. My math
is very rusty, if I've made any major gaffes please
feel free to correct/amend my scribblings.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list