Reputation:
I have not really used maps
before in my programming experience, so I am having trouble understanding the more complex versions of maps
. So let's say that the problem is you are given an integer in minutes, in this case n = 808
. What you are to do with this number is convert it to 24 hour time
, so hh:mm
. This would give you 13:28
. Once this is done, add up the digits of that time to get the answer. So, the answer would be 14
. I saw a really nice one-liner to this solution and I am trying to understand it because my solution took about 5 more lines of code
.
This is the solution:
sum(map(int, str(n // 60 * 100 + n % 60)))
So I understand that maps apply the same function over an iteration of numbers, but what throws me off is the int,str(...) part
. I am not sure what is going on behind the scenes.
Upvotes: 3
Views: 89
Reputation: 59284
map
,as you stated, applies a function over a iterable.
So, when you do
map(int, str(n // 60 * 100 + n % 60))
You are using the function int
over the iterable str(n // 60 * 100 + n % 60)
. As you probably know, strings are iterables (because, of course, you can iterate over them) - that can be easily checked
for char in "abcd":
print(char)
a
b
c
d
The return from str(n // 60 * 100 + n % 60)
is '1328'
. When you apply int
to each char, you transform each to an integer. You can easily see this by instead of taking the sum
right away, getting a lsit
list(map(int, str(n // 60 * 100 + n % 60)))
[1, 3, 2, 8]
I guess now it is easy to see that the sum
will get the sum of these numbers, which is what you wanted from the beginning :)
Upvotes: 2
Reputation: 164793
There are two mathematical operators used here:
//
represents floor division, i.e. extract the integer portion of the result after division.%
represents modulus, i.e. the remainder after division.Therefore, for n = 808
, the algorithm returns:
str(808 // 60 * 100 + 808 % 60) = str(13 * 100 + 28) = '1328'
map(int, '1328')
then takes each character in the string '1328'
and converts it into an integer, itself returning an iterable. map
requires an iterable as its second (and subsequent) arguments. Strings can be iterated to extract each character one at a time.
Finally, sum
takes each of the integers returned from map
and adds them together.
An equivalent formulation of the logic is possible via sum
with a generator expression:
sum(int(i) for i in str(n // 60 * 100 + n % 60))
Upvotes: 5
Reputation: 619
Both int()
and str()
are functions. In this particular example, when n=808
the argument to the str()
function is calculated as 1328, which when converted to the string becomes '1328'
. A string is iterable, so the map
function is simply applying int
to each character of the string, producing the sequence [1,3,2,8]
.
Upvotes: 0