2014-05-06 52 views
-4

是否有一個函數可用於查找具有最小ASCII值的字符串中的大寫字母。列表中的最小ASCII值

例如,假設該輸入字符串:

"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") 

預先感謝任何幫助。

編輯:sort()函數是不允許的。

回答

0

這是一個可怕,可怕做到這一點的方式 - 但它的工作原理:

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) 

它運行像

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

爲什麼不排序列表,然後採取索引0?

例如

sorted(filter(lambda x: x.isupper(), list(str)))[0] 
+0

此問題的規範之一是不允許使用sort()函數。 –

+4

然後做你自己的家庭作業。然而,你的老師可能希望你實現你自己的排序算法 - 所以看看那些。 https://en.wikipedia.org/wiki/Sort_algorithm Quicksort,mergesort,heapsort可能對你非常有用 – teambob

1
s = "Parker,Peter,Wayne,Bruce,Wilson,Wade" 
min(x for x in s if ord('A') <= ord(x) <= ord('Z')) 

min(x for x in s if x in string.ascii_uppercase)