0

So essentially what I'm doing is making a shipyard class that has the attribute "_containers" which is a singly linked list of container objects. Each container has the attribute "_destination" which is where it's going.

The shipyard._containers list has to be arranged alphabetically by destination. I know how to accomplish all of this except comparing the two destinations.

How can I compare two strings and figure out which one goes first based on alphabetical order? I'm not allowed to use any python lists at all.

Jeff H
  • 386
  • 1
  • 3
  • 16

2 Answers2

3

When x and y are variables naming Python objects that are strings,

x < y

is True if and only if x is alphabetically before y.

This may or may not match what you mean by "alphabetically before". For example, all uppercase characters do come alphabetically before lowercase ones, so if x='Zebra' and y='aardvark', x < y will be True. To specifically ignore upper/lower case distinctions, use

x.lower() < y.lower()

More generally, Unicode can present several such traps, whereby code points that are in a certain order do not mean they must be compared in that order. For a completely general approach to the Unicode Collation Algorithm, you can look at various alternatives discussed at How do I sort unicode strings alphabetically in Python? .

Community
  • 1
  • 1
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
0
containers = sorted(containers, key = lambda i: i.desitination)
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70