Skip to content

Who is going to pay for the wall? in Python

The challenge

Don Drumphet lives in a nice neighborhood, but one of his neighbors has started to let his house go. Don Drumphet wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it. He begins to solicit his neighbors to petition to get the association to build the wall. Unfortunately for Don Drumphet, he cannot read very well, has a very limited attention span, and can only remember two letters from each of his neighbors’ names. As he collects signatures, he insists that his neighbors keep truncating their names until two letters remain, and he can finally read them.

Your code will show Full name of the neighbor and the truncated version of the name as an array. If the number of the characters in name is less than or equal to two, it will return an array containing only the name as is”

Test cases

Test.describe("Basic tests") Test.assert_equals(who_is_paying("Mexico"),["Mexico", "Me"]) Test.assert_equals(who_is_paying("Melania"),["Melania", "Me"]) Test.assert_equals(who_is_paying("Melissa"),["Melissa", "Me"]) Test.assert_equals(who_is_paying("Me"),["Me"]) Test.assert_equals(who_is_paying(""), [""]) Test.assert_equals(who_is_paying("I"), ["I"]) Test.describe("Random tests") from random import randint base="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sol=lambda s: [s] if len(s)<3 else [s,s[:2]] for _ in range(40): s="".join(base[randint(,len(base)-1)] for q in range(randint(1,20))) Test.assert_equals(who_is_paying(s),sol(s),"It should work for random tests too")
Code language: Python (python)

The solution in Python

Initially we can write it out like this:

def who_is_paying(name): if name=="": return [""] if len(name)<=2: return [name] return [name, name[:2]]
Code language: Python (python)

But this is not very pythonic. We can always shorten it to a single line!

See also  How to append to an Array in Elasticsearch using elasticsearch-py
def who_is_paying(name): return ([""] if name=="" else ([name] if len(name)<=2 else [name, name[:2]]))
Code language: Python (python)

Another alternative is to do it with a lambda:

who_is_paying = lambda n: [n, n[:2]] if len(n)>2 else [n]
Code language: Python (python)

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x