Social Media

Set, Lambda, and Filter in Python

What is the output of this code snippet?

# popular instagram accounts
# (millions followers)
inst = {"@instagram": 232,
        "@selenagomez": 133,
        "@victoriassecret": 59,
        "@cristiano": 120,
        "@beyonce": 111,
        "@nike": 76}

# popular twitter accounts
# (millions followers)
twit = {"@cristiano": 69,
        "@barackobama": 100,
        "@ladygaga": 77,
        "@selenagomez": 56,
        "@realdonaldtrump": 48}

inst_names = set(filter(lambda x: inst[x]>60, inst.keys()))
twit_names = set(filter(lambda x: twit[x]>60, twit.keys()))

superstars = inst_names.intersection(twit_names)

You will use or have already used the operations introduced in this puzzle. They are elementary pieces of knowledge for any Python programmer.

First, we have the two dictionaries mapping an account name to the number of followers. For example, Cristiano Ronaldo (key: "@cristiano") has 120 million Instagram followers. Dictionaries allow fast data access. You can retrieve each item in constant runtime without having to iterate over the whole data structure.

Second, the filter function returns a new sequence where each item matches a defined characteristic. The function takes two arguments. The first argument is a function that returns a boolean value whether a sequence element should be included into the new sequence. The second argument is the sequence to be filtered.

Third, intersecting two sets s1 and s2 returns a new set that contains elements that are in both s1 and s2.

The only star that has more than 60 million Instagram AND twitter followers is Cristiano Ronaldo.

Related Video



Are you a master coder?

Test your skills now!

Leave a Comment

Your email address will not be published. Required fields are marked *