首页 > 解决方案 > 有没有办法使用随机大写字母的选择排序?

问题描述

因此,我一直在研究将十六进制转换为 ASCII 的代码,然后使用选择排序对字母进行排序。但是当我得到一个输入比如 HBbmYa 时,它输出为 B,H,Y,a,b,m。它应该输出为 a,B,b,H,m,Y 或 a,B,b,H,m,y。有没有办法解决这个问题?这是我现在拥有的代码。

#ask for input
hex_str = input("Write hexadecimal string here without spaces: ")
#format the input so it doesn't have any spaces or commas for the code to work
hex_str = hex_str.replace("," , "")
hex_str = hex_str.replace(" " , "")
#convert input to ASCII
def hexToASCII(hexx): 
    # initialize the ASCII code string as empty. 
    asci = "" 
    for i in range(0, len(hexx), 2): 
        # extract two characters from hex string 
        part = hexx[i : i + 2] 
        # change it into base 16 and 
        # typecast as the character  
        ch = chr(int(part, 16)) 
        # add this char to final ASCII string 
        asci += ch 
    return asci 
#function call
ascii_output = hexToASCII(hex_str)
# print the ASCII string.
print("ASCII output is: {}".format(ascii_output))


def selectionSort(u):
    sortedarry = []
    def findSmallest(l):
        x = l[0]
        for i in l:
            [ascii_output.lower() for ascii_output in u]
            if i < x:
                x = i
        return l.index(x)
    while len(u) > 0:
        x = findSmallest(u)
        sortedarry.append(u.pop(x))
    return sortedarry

u = list(ascii_output)
sortedarry = selectionSort(u)

# print the sorted array
print("The sorted array is: {}".format(sortedarry))

标签: pythonselection-sort

解决方案


在您的findSmallest函数中,您可以通过小写您比较的两个元素来使用不区分大小写的比较:

def findSmallest(l):
    x = l[0]
    for i in l:
        if i.lower() < x.lower():
            x = i
    return l.index(x)

推荐阅读