python - 如何调试选择排序输出中的逻辑错误?

标签 python python-3.x

n = int(input("Enter no of elements "))
A = []

for i in range(n):
    A.append(input())

for i in range(len(A)):
    min_idx = i
    for j in range(i + 1, len(A)):
        if A[min_idx] > A[j]:
            min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]

print("Sorted array")
for i in range(len(A)):
    print(A[i])

示例输入:

Enter no of elements 4
11
55
22
3

输出:

Sorted array
11
22
3
55

输出中有一个元素保留在未排序的位置。代码有什么问题?

最佳答案

您有一个缩进错误:

排序代码:

A = [11, 55, 22, 3]
for i in range(len(A)):
    min_idx = i
    for j in range(i + 1, len(A)):
        if A[min_idx] > A[j]:
            min_idx = j
    A[i], A[min_idx] = A[min_idx], A[i]  # <== this line was not indented enough

输出代码:

print("Sorted array")
for i in range(len(A)):
    print(A[i])

产品:

Sorted array
3
11
22
55

但是,Python 很棒:

Python 有一些很棒的工具可以处理此类事情,强烈建议您使用它们。这将提供与上述所有代码相同的输出:

A = [11, 55, 22, 3]
print("Sorted array")
for number in sorted(A):
    print(number)

这说明了两件事。

  1. 迭代列表本身,这里不需要索引。
  2. 让 Python 为您排序。

关于python - 如何调试选择排序输出中的逻辑错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331282/

相关文章:

python - 在 Python 中重新启动当前迭代

python - Azure 表单识别器 - "TrainingContentMissing",训练数据丢失 : Could not find any training data at the given path

python - 如何创建要在 Pipeline 中使用的自定义 Python 类以删除高度相关的功能?

python-3.x - Pandas :删除缺少数据的行

Python:GIL 上下文——切换

python - 如何将矩阵从 Matlab 转换为 Python?

python - matplotlib 存储和删除艺术家

python - 无法在 TensorFlow 中转换部分转换的张量

python-3.x - 使用 keras 扩充数据时如何修改标签

python - 当有人单击自定义按钮时,我可以触发什么输入事件?