如何解决这个冒泡排序问题?

huangapple go评论57阅读模式
英文:

How can i resolve this bubble sort problem?

问题

我正在尝试制作一个具有5个变量列表的Python冒泡排序。用户将输入5个值,bubble_sort 将按升序排列它们,但当我尝试运行它时,它出现错误:

lista = list(n1, n2, n3, n4, n5)
            ^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: list expected at most 1 argument, got 5

这是我编写的代码:

print('Olá!')
msg = 'Olá!'
n1 = float(input('Digite um número qualquer:'))
n2 = float(input('Digite outro número qualquer:'))
n3 = float(input('Digite outro número qualquer:'))
n4 = float(input('Digite outro número qualquer:'))
n5 = float(input('Digite outro número qualquer:'))
lista = list(n1, n2, n3, n4, n5)
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

print(bubble_sort(lista))
print('Fim')
英文:

I'm trying to make a Python bubble sort with a 5 variable list. The user will input the 5 values and the bubble_sort is going to arrange them in ascending order, but when I try to run it it gives the error:

lista = list(n1, n2, n3, n4, n5)
            ^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: list expected at most 1 argument, got 5

This is the code I wrote:

print('Olá!')
msg = 'Olá!'
n1 = float(input('Digite um número qualquer:'))
n2 = float(input('Digite outro número qualquer:'))
n3 = float(input('Digite outro número qualquer:'))
n4 = float(input('Digite outro número qualquer:'))
n5 = float(input('Digite outro número qualquer:'))
lista = list(n1, n2, n3, n4, n5)
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr


print(bubble_sort(lista))
print('Fim')

答案1

得分: 5

你正试图使用list()函数创建列表lista,但它期望的是一个可迭代对象作为其参数,而不是多个单独的元素!

创建一个包含所有元素的列表,如下所示:

lista = [n1, n2, n3, n4, n5]
英文:

you are trying to create the list lista using the list() function but it expects an iterable as its argument, not multiple individual elements!

create a list containing all the elements like this:

lista = [n1, n2, n3, n4, n5]

huangapple
  • 本文由 发表于 2023年7月23日 22:14:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定