How to Create a Nickname Generator in Python


The challenge

Write a nickname generator function, nicknameGenerator that takes a string name as an argument and returns the first 3 or 4 letters as a nickname.

The nickname generator should perform the following tasks.

If the 3rd letter is a consonant, return the first 3 letters.

nickname("Robert") # "Rob"
nickname("Kimberly") # "Kim"
nickname("Samantha") # "Sam"

If the 3rd letter is a vowel, return the first 4 letters.

nickname("Jeannie") # "Jean"
nickname("Douglas") # "Doug"
nickname("Gregory") # "Greg"

If the string is less than 4 characters, return “Error: Name too short”.

Notes:

  • Vowels are “aeiou”, so discount the letter “y”.
  • Input will always be a string.
  • Input will always have the first letter capitalised and the rest lowercase (e.g. Sam).
  • The input can be modified

The solution in Python code

Option 1:

def nickname_generator(name):
    if len(name)<4:
        return "Error: Name too short"
    if name[2] not in ['a','e','i','o','u']:
        return name[:3]
    else:
        return name[:4]

Option 2:

def nickname_generator(name):
    if len(name) < 4:
        return 'Error: Name too short'
    return name[: 4 if name[2] in 'aeiou' else 3]

Option 3:

def nickname_generator(name):
    return "Error: Name too short" if len(name) < 4 else name[:3+(name[2] in "aeiou")]

Test cases to validate our solution

test.describe("Example Test Cases")
test.assert_equals(nickname_generator("Jimmy"), "Jim");
test.assert_equals(nickname_generator("Samantha"), "Sam");
test.assert_equals(nickname_generator("Sam"), "Error: Name too short");
test.assert_equals(nickname_generator("Kayne"), "Kay", "'y' is not a vowel");
test.assert_equals(nickname_generator("Melissa"), "Mel");
test.assert_equals(nickname_generator("James"), "Jam");