【问题标题】:How do I alphabetically sort an array of strings without any sort functions? Python如何在没有任何排序功能的情况下按字母顺序对字符串数组进行排序? Python
【发布时间】:2020-02-25 08:11:08
【问题描述】:

解决以下问题时: “假设你有一个随机的字符串列表(例如:a、b、c、d、e、f、g),编写一个程序,按字母顺序对字符串进行排序。 你不能使用排序命令。”

我遇到了通过以下代码运行字符串的问题,这有时会让我在最终列表中出现重复的字符串

我对 python 还很陌生,我们的班级刚刚开始研究 numpy,以及该模块中的函数,我不确定代码中是否使用了任何函数(任何排序函数除外)。

import numpy as np

list=[]
list=str(input("Enter list of string(s): "))
list=list.split()
print() # for format space purposes
listPop=list
min=listPop[0]
newFinalList=[]

if(len(list2)!=1):
    while(len(listPop)>=1):
        for i in range(len(listPop)):
            #setting min=first element of list
            min=listPop[0]
            if(listPop[i]<=min):
                min=listPop[i]
                print(min)    
        listPop.pop(i)
        newFinalList.append(min)
    print(newFinalList)
else:
    print("Only one string inputted, so already alphabatized:",list2)

["a","y","z"]的预期结果

["a","y","z"]

实际结果...

输入字符串列表:a y z

一个 一种 一种 ['a', 'a', 'a']

输入字符串列表:d e c

d C d d ['c', 'd', 'd']

【问题讨论】:

  • 这对于初学者来说绝对不是一件容易的事,但是您可以做一些事情。制作一个字母 letters = ['a', 'b', 'c'...] 的 Numpy 数组。然后,当你得到一个字符串时,使用np.where()np.argwhere() 来获取字母的索引('a' 将是 0,'z' 将是 25)。然后,在得到两个字母的索引后,您可以确定哪个更小。如果你不需要使用 Numpy,你可以使用一个字符串来代替:letters = 'abcdef...'。然后,使用letters.find('a') 获取字母的索引('b' 将是第二个位置)。再次比较索引。
  • 我不确定这是否允许,但将其转换为 ascii code 并使用数字
  • 他们是否希望您在此排序中使用numpy?还是这个排序任务是你之前学过的某个单元遗留下来的?

标签: python arrays string list numpy


【解决方案1】:

您可以实现快速排序:

def partition(arr,low,high): 
    i = ( low-1 )        
    pivot = arr[high]
    for j in range(low , high):     
        if arr[j] <= pivot:         
            i = i+1
            arr[i],arr[j] = arr[j],arr[i]
    arr[i+1],arr[high] = arr[high],arr[i+1] 
    return ( i+1 ) 

def quickSort(arr,low,high): 
    if low < high:      
        pi = partition(arr,low,high)        
        quickSort(arr, low, pi-1) 
        quickSort(arr, pi+1, high) 

arr = ['a', 'x', 'p', 'o', 'm', 'w'] 
n = len(arr) 
quickSort(arr,0,n-1) 
print ("Sorted list is:") 
for i in range(n): 
    print ("%s" %arr[i]),

输出:

Sorted array is:
a m o p w x

【讨论】:

    【解决方案2】:

    选择排序:对于列表的每个索引i,选择i或之后的最小项,并将其交换到ith位置。这是一个三行的实现:

    # For each index i...
    for i in range(len(list)):
        # Find the position of the smallest item after (or including) i.
        j = list[i:].index(min(list[i:])) + i
        # Swap it into the i-th place (this is a no-op if i == j).
        list[i], list[j] = list[j], list[i]
    
    • list[i:]list 的切片(子集),从 ith 元素开始。
    • min(list) 为您提供list 中最小的元素。
    • list.index(element)list 中为您提供element 的(第一个)索引。
    • a, b = b, a 自动交换 ab 的值。

    这个实现中最棘手的部分是,当您使用index 查找最小元素的索引时,您需要在找到该元素的同一list[i:] 切片中找到索引,否则您可能会在列表的较早部分中选择一个重复的元素。由于您要找到与list[i:] 相关的索引,因此您需要将i 添加回它以获取整个list 中的索引。

    【讨论】:

    • 您能否再解释一下您是如何实现的?
    【解决方案3】:

    合并排序:

    from heapq import merge
    from itertools import islice
    
    def _ms(a, n):
        return islice(a,n) if n<2 else merge(_ms(a,n//2),_ms(a,n-n//2))
    
    def mergesort(a):
        return type(a)(_ms(iter(a),len(a)))
    
    # example
    
    import string
    import random
    
    L = list(string.ascii_lowercase)
    random.shuffle(L)
    print(L)
    print(mergesort(L))
    

    示例运行:

    ['h', 'g', 's', 'l', 'a', 'f', 'b', 'z', 'x', 'c', 'r', 'j', 'q', 'p', 'm', 'd', 'k', 'w', 'u', 'v', 'y', 'o', 'i', 'n', 't', 'e']
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    

    【讨论】:

      猜你喜欢
      • 2014-11-13
      • 1970-01-01
      • 2023-02-18
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多