Going fast! #DataquestChallenge Premium Annual Offer:
500 get 50% & the next 1000 get 40% off.
GET OFFER CODE

Combination & map()

Hi
I was studying permutation/combinations and I came across the challenge below:

You have L, a list containing some digits (0 to 9). Write a function solution(L) that finds the largest number that can be made from some or all of these digits and is divisible by 3. If it is not possible, return 0. L contains anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once.

However, I could understand only part of the solution. Would anyone be able to explain:
1- why use the map()?
2- why is a str inside map()?

from itertools import combinations

def answer(nums):
    nums.sort(reverse = True)
    for i in reversed(range(1, len(nums) + 1)):
        for tup in combinations(nums, i):
            if sum(tup) % 3 == 0: return int(''.join(map(str, tup)))
    return 0

examples:
input - [3, 1, 4, 1]
output - 4311

thank you!

Hi @boemer00

Have you been able to understand by now? Just in case this helps.

  • you need to provide an iterator to the join method. If you only provide the list as is, “join” won’t concatenate each element of the list. It will rather take list as one item.
    For example try this:

    a = [1,3,4,1]
    print("".join(str(a)))

  • join takes only string values; to convert each number/digit/element in the give list map function is used. It applies string format to each and every element of the list then passes that an iterator to Join method which then joins each and every element.

    print("".join(map(str, a)))