【问题标题】:Is there a way to use selection sort with randomized captalized letters?有没有办法使用随机大写字母的选择排序?
【发布时间】:2021-03-11 07:57:22
【问题描述】:

所以我一直在研究将十六进制转换为 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))

【问题讨论】:

  • 有什么问题?逗号?
  • 请提供预期输出
  • 为什么要编写自己的排序例程和十六进制转换器? Python 已经拥有这两者。
  • 我自己的代码的原因是,如果这是一个项目,我的老师不允许我们使用内置函数。只是我们自己的代码。

标签: python selection-sort


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2018-12-04
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    相关资源
    最近更新 更多