DEV Community

loading...

Discussion on: Daily Challenge #48 - Facebook Likes

Collapse
rafaacioly profile image
Rafael Acioly • Edited

At first i've used a lot of if statement then i got excited and tried another point

Python version (using as fewer ifs as possible):

def show_likes(persons: List[str]) -> str:
  messages = {
    0: 'no one likes this',
    1: '%s like this',
    2: '%s and %s like this',
    3: '%s, %s and %s like this',
    4: '%s, %s and %d others like this'
  }

  likes_quantity = len(persons)
  content = messages.get(likes_quantity) or messages[4]

  if likes_quantity > 3:
    return content % (persons[0], persons[1], len(persons[2:]))

  return content % (tuple(persons))
Collapse
idanarye profile image
Idan Arye

Possible improvements: instead of

content = messages.get(likes_quantity) or messages[4]

You can write:

content = messages.get(likes_quantity, messages[4])

Or - if you want to get fancy:

content = messages[min(likes_quantity, 4)]

Or even:

from collections import defaultdict

messages = defaultdict(
    lambda: '%s, %s and %d others like this',
  {
    0: 'no one likes this',
    1: '%s like this',
    2: '%s and %s like this',
    3: '%s, %s and %s like this',
  })

likes_quantity = len(persons)
content = messages[likes_quantity]

But of course - all of this is redundant, since you already check for likes_quantity > 3. So how about this:

def show_likes(persons: List[str]) -> str:
    messages = {
        0: 'no one likes this',
        1: '%s like this',
        2: '%s and %s like this',
        3: '%s, %s and %s like this',
    }

    likes_quantity = len(persons)

    if likes_quantity > 3:
        return '%s, %s and %d others like this' % (
            persons[0], persons[1], len(persons[2:]))

    return messages[likes_quantity] % tuple(persons)
Collapse
rafaacioly profile image
Rafael Acioly

Nice, it was in fact redundant getting the message content, thanks for sharing :D