【问题标题】:Sort a user input list of numbers using python bubble sort使用 python 冒泡排序对用户输入的数字列表进行排序
【发布时间】:2014-12-15 20:24:57
【问题描述】:

我刚开始学习 python,我决定尝试做一个冒泡排序。我使用了下面的代码,如果要排序的数字是 0 到 9,它就可以正常工作。之后,它不能正确地对它们进行排序。我认为,据我所知,这是因为它是一个“列表”。

我希望用户能够输入数字,但无论数字的长度如何,程序都会对它们进行排序。任何帮助将不胜感激。

def bubble_sort(items):
    changes=0

    for i in range(len(items)):
        for j in range(len(items)-1-i):#-i = optimised??
            if items[j] > items[j+1]:
                items[j], items[j+1] = items[j+1], items[j]  # Swap
                changes=changes+1

    print(items)
    print("Number of passes =",i)
    print("Number of swaps =",changes)

print("Welcome to a Bubble Sort Algorithm in Python!")

while True:

    print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
    numbers=input()
    items=numbers.split()

【问题讨论】:

    标签: python-3.x bubble-sort


    【解决方案1】:

    试试这个:

    print('welcome to the automatic bubble sorter')
    inputted_list = input('please enter a list of numbers seperated by commas: ')
    list = inputted_list.split(',')
    number_of_items = int(len(list))
    
    sorting_method = input('if you would like your list to be sorted in ascending order, press 1, if you would like it to be sorted in descending order, press 2')
    print(list)
    
    if sorting_method == '1':
        position = 0
        Pass = 0
        counter = 1
        while counter == 1:
            number_of_swaps = 1
            counter2 = 0
            permanent_numbers = []
            while number_of_swaps > 0:
                counter2 = counter2 + 1
                number_of_swaps = 0
                while position < number_of_items - 1:
                    if int(list[position]) > int(list[position + 1]):
                        number_of_swaps = number_of_swaps + 1
                        item1 = int(list[position])
                        item2 = int(list[position + 1])
                        list[position] = item2
                        list[position + 1] = item1
                    position = position + 1
                Pass =  Pass + 1
                print('pass',Pass,':',list)
                position = 0
                if Pass == number_of_items - 1:
                    number_of_swaps = 0
                permanent_numbers.append(list[number_of_items - counter2])
            if number_of_swaps == 0:
                counter = 0
    
    
        print('total number of passes:', Pass)
    
        elif sorting_method == '2':
        position = 0
        Pass = 0
        counter = 1
        while counter == 1:
            number_of_swaps = 1
            while number_of_swaps > 0:
                number_of_swaps = 0
                while position < number_of_items - 1:
                    if int(list[position]) > int(list[position + 1]):
                        number_of_swaps = number_of_swaps + 1
                        item1 = int(list[position])
                        item2 = int(list[position + 1])
                        list[position] = item2
                        list[position + 1] = item1
                    position = position + 1
                Pass =  Pass + 1
                print('pass',Pass,':',list)
                position = 0
                if Pass == number_of_items - 1:
                    number_of_swaps = 0
    
            if number_of_swaps == 0:
                counter = 0
    
    
        print('total number of passes:', Pass)  
    

    【讨论】:

      【解决方案2】:

      试试map:

      我之前建议使用 map,但我只记得 python 3.x* 中的 map 产生一个生成器而不是一个列表,所以这就是为什么你不能取它的长度。更新的答案如下

      numbers = input("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
      items = [int(num) for num in numbers.split()]
      

      修改现有代码:

      #!/usr/bin
      def bubble_sort(items):
          changes = passes = 0
          last = len(items)
          swapped = True
      
          while swapped:
              swapped = False
              passes += 1
              for j in range(1, last):
                  if items[j - 1] > items[j]:
                      items[j], items[j - 1] = items[j - 1], items[j]  # Swap
                      changes += 1
                      swapped = True
                      last = j
      
      
          print(items)
          print("Number of passes =",passes)
          print("Number of swaps =",changes)
      
      
      print("Welcome to a Bubble Sort Algorithm in Python!")
      
      while True:
          print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
          numbers = input()
          items = [int(num) for num in numbers.split() if num.isdigit()]
          if items: bubble_sort(items)
      

      【讨论】:

      • 一个使用示例可能会有所帮助
      • 谢谢。我想我明白为什么这会奏效。我唯一的问题是,现在我收到“TypeError:'map' 类型的对象没有 len()”任何想法将不胜感激。
      • @stacksth 你能展示一下你是如何在你的代码中使用地图的吗?
      • @stacksth,我想我知道问题出在哪里了,请看我更新的帖子
      【解决方案3】:
      def b_sort(list):
      
      for iter_num in range(len(list)-1,0,-1):
          for idx in range(iter_num):
      
              if list[idx] > list[idx+1]:
                  temp = list[idx]
                  list[idx] = list[idx+1]
                  list[idx+1] = temp
      
      str_input= input("Enter numbers:  ")
      list = [int(x) for x in str_input.split()]
      
      b_sort(list)
      print('sorted elements are: ')
      print(list)
      

      【讨论】:

        【解决方案4】:
        def sort():
            try:
                n = [1,8,6]
                l = len(n)
                print("Original list:", n)
                for i in range(l - 1):
                    for j in range(0,l - i - 1):
                        if n[j] > n[j + 1]:
                            n[j], n[j + 1] = n[j + 1], n[j]
                print("List after sorting is:", n)
            except:
                print("Error in inputing values")
        
        
        sort()
        

        【讨论】:

        • 请不要添加简单的代码,而是尝试解释为什么这是解决OP问题的正确方法
        猜你喜欢
        • 2014-09-17
        • 2017-09-27
        • 2014-03-13
        • 1970-01-01
        • 2018-09-22
        • 1970-01-01
        • 1970-01-01
        • 2013-10-31
        • 2019-05-10
        相关资源
        最近更新 更多