简体   繁体   English

用Python对字母数字字符串进行排序-选择排序,冒泡排序

[英]sorting an alphanumeric string in Python- selection sort, bubble sort

The question is 问题是
Write a program to sort a string without using built in method. 编写一个不使用内置方法对字符串进行排序的程序。 Input: "a390testai" output: "039aaiest" 输入:“ a390testai”输出:“ 039aaiest”

I have looked at some forums to find answer for this. 我看过一些论坛来找到答案。 I found this forum In Python, how can I naturally sort a list of alphanumeric strings such that alpha characters sort ahead of numeric characters? 在Python中找到了这个论坛,我如何自然地对字母数字字符串列表进行排序,以使字母字符排在数字字符之前? but it does not look like any of the solutions were using selection or bubble sort. 但看起来没有任何解决方案使用选择或冒泡排序。 My questions are: 我的问题是:
1) When dealing with such a problem do I have to 1st convert the string to a list? 1)处理此类问题时,我必须首先将字符串转换为列表吗? For example: str=list("exam123ple") ? 例如:str = list(“ exam123ple”)吗? To avoid "TypeError: 'str' object does not support item assignment" 为了避免“ TypeError:'str'对象不支持项目分配”

2) I tried using selection sort and bubble sort but they are not returning intended result. 2)我尝试使用选择排序和冒泡排序,但它们没有返回预期的结果。

   #Selection sort
s="a390testai"
s=list(s)  # convert to list


for i in range(len(s)):
    min_val=min(s[i:])
    min_val_pos=s.index(min_val)

    s[i],s[min_val_pos]=s[min_val_pos],s[i]

print('s',s)

#Bubble sort
bs="a390testai"

bs=list(bs)
for i in range(0,len(bs)-1):
       if bs[i]>bs[i+1]:
           bs[i], bs[i+1]=bs[i+1],bs[i]

print(bs)

039testaai >> selection sort
390aestait >> bubble sort

Thanks in advance for your help and explanation. 在此先感谢您的帮助和解释。

Bubble sort needs more than one pass. 冒泡排序需要超过一遍。 Each time through, you go through one less element, since the last one has "bubbled" into place. 每次通过,您都要少处理一个元素,因为最后一个已经“冒泡”了。

In your selection sort, s.index returns the index of the first matching item. 在您的选择排序中, s.index返回第一个匹配项的索引。 So if your string has duplicate letters it returns the wrong one. 因此,如果您的字符串中有重复的字母,则会返回错误的字母。 You need to search inside the [i:] range and add i , to find the right instance. 您需要在[i:]范围内搜索并添加i ,以找到正确的实例。

Yes, you have to use list as strings are immutable and you can't change parts of them. 是的,您必须使用列表,因为字符串是不可变的,您无法更改它们的一部分。 Here is an example of bubble sort. 这是气泡排序的示例。

s = list('a390testai')

is_sorted = False
while not is_sorted:
    for i in range(len(s)-1):
        if s[i] > s[i+1]:
            s[i+1], s[i] = s[i], s[i+1]
            break
    else:
        is_sorted=True

print("".join(s))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM