[Tutor] Converting integers into digit sum (Python 3.3.0)
Oscar Benjamin
oscar.j.benjamin at gmail.com
Tue Dec 10 10:55:41 CET 2013
On 10 December 2013 09:39, Rafael Knuth <rafael.knuth at gmail.com> wrote:
>
>>>>> def DigitSum(YourNumber):
>> ... return sum(map(int, YourNumber))
>> ...
>>>>> DigitSum('55')
>> 10
>
> I don't understand yet what the "map" function does - can you explain?
> I read the Python 3.3.0 documentation on that topic but I frankly
> didn't really understand it
> http://docs.python.org/3/library/functions.html#map. My search for
> simple code examples using "map" wasn't really fruitful either.
The map function is easier to understand in Python 2. It takes a
function and a list (or any sequence/iterable) and calls the function
on each element of the list. The values returned from the function are
placed in a new list that is returned by map:
$ python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x * x
...
>>> values = [1, 3, 2, 4]
>>> map(square, values)
[1, 9, 4, 16]
In Python 3 the situation is slightly more complicated since map
returns an iterator rather than a list:
$ python3
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x * x
...
>>> values = [1, 3, 2, 4]
>>> map(square, values)
<map object at 0x00E2AEB0>
To get the values out of the iterator we have to loop over it:
>>> for x in map(square, values):
... print(x)
...
1
9
4
16
Or if you just want a list you can call list in the map object:
>>> list(map(square, values))
[1, 9, 4, 16]
Oscar
More information about the Tutor
mailing list