Domanda

Is there a function(s) that I can use to find the capital letter in a string with the smallest ASCII value.

For example, given this input string:

"Parker,Peter,Wayne,Bruce,Wilson,Wade"

# I want the function to return Parker,Peter \n Wayne,Bruce \n Wilson,Wade
# I know that I have to use the ord function in some sort of way, 
# and is there a way to accomplish this task using the min function?
# I have tried doing this function with a while loop and it works with 
# two names but not with any more.

def alphabetize(names):
 T = ''
 subscript = 0
 names = names.split(",")
 champ = ord(names[subscript][0])
 while len(names) > 0:
    if ord(names[subscript][0]) < champ:
        T += (names[subscript])
        T += " "
        T += (names[subscript + 1])
        T += "\n"
        del names[subscript]
        del names[subscript]
    elif ord(names[subscript][0]) > champ:
        T += (names[subscript])
        T += " "
        T += (names[subscript + 1])
        T += "\n"
        del names[subscript]
        del names[subscript]
    else:
        T += (names[subscript])
        T += " "
        T += (names[subscript + 1])
        T += "\n"
        del names[subscript]
        del names[subscript]
return T

print alphabetize("Kent,Clark,Wayne,Bruce")

Thanks in advance for any help.

Edit: The sort() function is not allowed.

È stato utile?

Soluzione 3

This is a terrible, awful way to do it - but it works:

def alphabetize(s, delimiter=","):
    values = s.split(delimiter)  # convert to a list
    result = []
    while values:
        # this is effectively select-sort - which is O(n**2) -
        # but even worse because deleting a list item is also
        # O(n), making it O(n**3) overall
        smallest = min(range(len(values)), key=values.__getitem__)
        result.append(values[smallest])
        del values[smallest]
    # rejoin the sorted items to a string
    return delimiter.join(result)

which runs like

>>> alphabetize("Parker,Peter,Wayne,Bruce,Wilson,Wade")
'Bruce,Parker,Peter,Wade,Wayne,Wilson'

Altri suggerimenti

Why not sort the list then take index 0?

e.g.

sorted(filter(lambda x: x.isupper(), list(str)))[0]
s = "Parker,Peter,Wayne,Bruce,Wilson,Wade"
min(x for x in s if ord('A') <= ord(x) <= ord('Z'))

or

min(x for x in s if x in string.ascii_uppercase)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top