Python > Assignment #3: Catalogue 2.0

Deadline: Wed 12. 10. 2016, 07:47 CET

Assignment [2pts]: Write a better cataloguing script that can handle multiple names at once. First off, the user is prompted to enter the names, one name per each line. When an empty line is read, the names are printed sorted by the surname and the programs ends.

Enter names, one per line; a blank line signals the end of the list:
> Adam Green
> Bob Gray
> Charles Black
> Daniel Blue
>

Catalogue listing:
 Black, Charles
 Blue, Daniel
 Gray, Bob
 Green, Adam

Solution:

print('Enter names, one per line; a blank line signals the end of the list:')

names = []

while True:
    words = input('> ').split()

    if not words:
        break

    names.append(words[1] + ', ' + words[0])


print()
print('Catalogue listing:')

for name in sorted(names):
    print('  ' + name)

Bonus [1pts]: Output the names numbered and shortened, correctly handling middle names.

Enter names, one per line; a blank line signals the end of the list:
> Adam Green
> Bob Gray
> Particularly Annoying Orange
> Charles Black
> Daniel Blue
>

Catalogue listing:
 1: Black, C.
 2: Blue, D.
 3: Gray, B.
 4: Green, A.
 5: Orange, P. A.

Solution:

print('Enter names, one per line; a blank line signals the end of the list:')

names = []

while True:
    words = input('> ').split()

    if not words:
        break

    initials = [ x[0]+'.' for x in words[:-1] ]

    names.append(words[-1] + ', ' + ' '.join(initials))


print()
print('Catalogue listing:')

i = 1
for name in sorted(names):
    print('  ' + str(i) + ': ' + name)
    i += 1

Note: Partial points will be awarded for partially implemented or partially working solutions (e.g. forcing the user to only enter the surnames nets -0.5pts). Not to overcomplicate the program, normalization of letter case is not required.