You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决选择排序对大小写字母排序不符合预期的问题?

解决大小写不敏感的选择排序问题

问题根源

你的选择排序函数目前是直接按字符的原始ASCII值进行比较的,而ASCII编码中大写字母(A-Z,码值65-90)的数值小于小写字母(a-z,码值97-122),所以排序后所有大写字母会排在小写字母前面,这就是为什么你得到B,H,Y,a,b,m而不是预期的按字母顺序排列的结果。

另外,你在findSmallest函数里写的列表推导式[ascii_output.lower() for ascii_output in u]只是创建了一个临时列表,并没有实际用于比较逻辑,所以完全没起到作用。

解决方案

要实现不区分大小写的排序,但保留原字符的大小写,核心是在比较元素大小的时候,统一将字符转换为小写(或大写)后再比较,但最终排序的还是原字符。

修改你的selectionSort和findSmallest函数即可:

#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):
        # 初始化最小元素为第一个元素,同时记录其小写形式用于比较
        smallest_char = l[0]
        smallest_index = 0
        for i in range(1, len(l)):
            # 比较当前元素和最小元素的小写形式
            if l[i].lower() < smallest_char.lower():
                smallest_char = l[i]
                smallest_index = i
        return smallest_index
    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))

关键修改说明

  1. 重构了findSmallest函数:
    • 不再直接用原字符比较,而是通过lower()方法将字符转为小写后再比较大小
    • 全程跟踪原字符和对应的索引,确保最终返回的是原字符的位置,保留原始大小写
  2. 移除了原来无效的列表推导式,替换为实际参与比较的逻辑

测试结果

当你输入HBbmYa(对应转ASCII后是['H','B','b','m','Y','a']),运行修改后的代码会输出:

ASCII output is: HBbmYa
The sorted array is: ['a', 'B', 'b', 'H', 'm', 'Y']

完全符合你的预期需求。

内容的提问来源于stack exchange,提问作者Wan Yoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:33:22