The challenge

Write a hashtag generator function that takes a string and returns a #HashCodeString of it.

The hashtag generator should perform the following tasks.

Follow these rules:

  • It must start with a hashtag (#).
  • All words must have their first letter capitalized.
  • If the final result is longer than 140 chars it must return false.
  • If the input or the result is an empty string it must return false.


"    Hello     World   "                  =>  "#HelloWorld"
""                                        =>  false

The solution in Python code

Option 1:

def generate_hashtag(s):
    output = "#"
    for word in s.split():
        output += word.capitalize()
    return False if (len(s) == 0 or len(output) > 140) else output

Option 2:

def generate_hashtag(s):
    ans = '#'+ str(s.title().replace(' ',''))
    return s and not len(ans)>140 and ans or False

Option 3:

generate_hashtag=lambda d:(lambda b:d>''<b==b[:139]and'#'+b)(d.title().replace(' ',''))

Test cases to validate our solution

test.describe("Basic tests")
test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False')
test.assert_equals(generate_hashtag('Do We have A Hashtag')[0], '#', 'Expeted a Hashtag (#) at the beginning.')
test.assert_equals(generate_hashtag('c i n'), '#CIN', 'Should capitalize first letters of words even when single letters.')
test.assert_equals(generate_hashtag('this  is  nice'), '#ThisIsNice', 'Should deal with unnecessary middle spaces.')
test.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Should return False if the final word is longer than 140 chars.')