Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare strings based on alphabetical ordering

Tags:

Write a function that takes two strings as arguments and returns the one which is longer. If the strings have equal length, return the one that comes first alphabetically.

This is what i have so far:

    def strings(x,y):         if len(x) > len(y):             return x         if len(x)==len(y):             return          else:             return y 

I am wondering how i would write the code so it would choose the string that comes first alphabetically for the second if statement.

like image 420
user1698174 Avatar asked Nov 12 '12 21:11

user1698174


People also ask

How do you compare strings in alphabetical order?

If you are truly comparing Strings alphabetically to arrange them in order, use compareTo() method from Comparable interface in Java. It also compare String based upon there value, and can be used to sort String alphabetically, if they are stored in List using Collections.

Does compareTo compare alphabetically?

The Java String compareTo() method compares two strings lexicographically (alphabetical order). It returns a positive number, negative number, or zero. if s1 < s2 , it returns negative number.

How do you compare two string and sort it?

We can compare strings with the help of CompareTo() method in C#. You can compare a string with another string to know if it precedes, follows, or appears in the position as the other in the sort order. An integer value is returned when the CompareTo() method is used.


2 Answers

You can compare strings directly. x<y means "does x come before y alphabetically?" So you can replace your second block with:

if len(x) == len(y) and x < y:     return x 
like image 168
AlwaysBTryin Avatar answered Nov 11 '22 09:11

AlwaysBTryin


this should work:

if len(x)==len(y):    return min(x,y) 
like image 27
gefei Avatar answered Nov 11 '22 08:11

gefei