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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With