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

46 lines
1.5 KiB
Python
Raw Normal View History

2020-09-07 12:24:30 +02:00
# 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
2020-08-26 14:47:36 +02:00
def getName():
while True:
name = input('Jeg heter: ')
if (' ' in name):
2020-09-07 12:24:30 +02:00
names = name.split(' ')
if not (len(names) == 2 and (hasSuffix(names[-1]) or hasRomanNumerals(names[-1]))):
return names
2020-08-26 14:47:36 +02:00
print('Putt et mellomrom mellom fornavn og etternavn')
names = list(map(capitalize, getName()))
2020-09-07 12:24:30 +02:00
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)
2020-08-26 14:47:36 +02:00
2020-09-07 12:24:30 +02:00
print(f'The name is {lastNamesString}, {firstNamesString} {lastNamesString}')