【问题标题】:Bubble Sort not outputting in correct order (float)冒泡排序未按正确顺序输出(浮点数)
【发布时间】:2019-05-07 17:26:33
【问题描述】:

似乎找不到任何关于此的内容,因为我无法正确地用词。基本上,当我将列表从负数排序到最低负数然后读取正数时,假设它是 [1.6397, -2.0215, -0.4933, , -3.4167] 它将排序为 [-0.4933, -2.0215, -3.4167 , 1.6397]

通过算法是

    def bubbleSort(array):
        n=len(array)
         for i in range(n):
            for j in range(0, n-i-1):
                while array[j]>array[j+1]:
                    array[j], array[j+1] = array[j+1], array[j]

我希望这个读起来像 [-3.4167, -2.0215, -0.4933, 1.6397]

提前致谢

补充:

    example=[]
    with open('ex.txt') as f:
        for l in f:
            l=l.strip()
            example.append(l)

    examplesearch=input('select array to sort')
    if (examplesearch == ex1):
    bubbleSort(example)
    print(example)

【问题讨论】:

  • 附带说明,您为什么使用while 而不是if
  • 当我用 [1.6397, -2.0215, -0.4933, -3.4167] 调用这个函数时,我得到了你期望的输出 - [-3.4167, -2.0215, -0.4933, 1.6397]
  • 哎呀,是的,这是我的代码上的“如果”,我只是冲了那个例子,我的错
  • 当我运行这段代码时,它会正确地对数组进行排序。向我们展示调用此函数并打印结果的代码。
  • 我的数字是从 txt 文件中导入的您是在将数字转换为实际的浮点值,还是仍然是字符串?

标签: python python-3.x sorting bubble-sort


【解决方案1】:

由于您从文件中读取输入的数字是字符串,因此 Python 使用字符串比较(您得到的结果很明显)。

您必须先转换为float

example = []
with open('ex.txt') as f:
    for l in f:
        l = float(l.strip())
        example.append(l)

BWT,你不需要预先创建列表:

with open('ex.txt') as f:
    # 'if number' will handle potential empty line at the end of the file
    output = [float(number.strip()) for number in f if number]

【讨论】:

  • 是的,这是我最初尝试的,除了我得到一个 valueerror 'could not convert string to float',因此我认为这是算法的问题
  • @JoeBenson 那么您可能在文件末尾有一个空行。查看更新的代码。
  • 还是一样的错误信息,很奇怪。该文件有一个空行和其他行带有“''”,也许这些行是将所有字符串转换为浮点数的问题
猜你喜欢
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 2022-06-10
相关资源
最近更新 更多