TDT4109/Exercise 1/11 - James Bond and Operati.../task11c.py

46 lines
1.5 KiB
Python

# Known bug:
# The program will not accept a name consisting of a single name and a single surname
# when the surname only consists of the capital letters IVXLCDM and it will wrongly accept
# a surname consisting of those letters as Roman numerals. In order to fix, some more
# complex regex logic is needed.
import re
capitalize = lambda name: name.capitalize()
PREPOSITION_LIST = ['von', 'van', 'de', 'di']
PREPOSITION_LIST.extend(list(map(capitalize, PREPOSITION_LIST)))
SUFFIX_PATTERN = '[sj]r\.?'
ROMAN_NUMERAL_PATTERN = '[IVXLCDM]+\.?'
hasSuffix = lambda word: re.match(SUFFIX_PATTERN, word, re.IGNORECASE) is not None
hasRomanNumerals = lambda word: re.match(ROMAN_NUMERAL_PATTERN, word) is not None
def getName():
while True:
name = input('Jeg heter: ')
if (' ' in name):
names = name.split(' ')
if not (len(names) == 2 and (hasSuffix(names[-1]) or hasRomanNumerals(names[-1]))):
return names
print('Putt et mellomrom mellom fornavn og etternavn')
names = list(map(capitalize, getName()))
firstNames = names[:-1]
lastNames=[names[-1]]
moveLastFirstNameToLastNames = lambda: lastNames.insert(0, firstNames.pop())
if hasSuffix or hasRomanNumerals:
moveLastFirstNameToLastNames()
hasPreposition = firstNames[-1] in PREPOSITION_LIST and len(firstNames) != 1
if hasPreposition:
moveLastFirstNameToLastNames()
lastNamesString = ' '.join(lastNames)
firstNamesString = ' '.join(firstNames)
print(f'The name is {lastNamesString}, {firstNamesString} {lastNamesString}')