【问题标题】:Day 20: Sorting in Hackerrank, Python第 20 天:在 Hackerrank、Python 中进行排序
【发布时间】:2017-06-02 04:26:34
【问题描述】:

最近我一直在做 HackerRank 30 天的代码挑战,并使用 Python 解决挑战。但是在第 20 天(关于冒泡排序算法)我无法解决它。这是 Hackerrank 中任务的link,下面是我的代码。

import sys

n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
numSwap = 0

for first in a:
    b = a[a.index(first)+1:]
    for second in b:
        if first > second:
            a[a.index(first)] = second
            a[a.index(second)] = first
            numSwap += 1

firstElement = a[0]
lastElement = a[len(a)-1]
print "Array is sorted in %d swaps\nFirst Element: %s\nLast Element: %d " %(numSwap, firstElement, lastElement)

这段代码的输入是:

3
3 2 1

代码的结果是:

Array is sorted in 3 swaps  
First Element: 3  
Last Element: 1

预期结果:

Array is sorted in 3 swaps.
First Element: 1
Last Element: 3 

问题是为什么它没有像预期的那样工作?代码的哪一部分是错误的?谢谢。

【问题讨论】:

  • 不幸的是,交换是错误的部分

标签: python python-2.7 bubble-sort


【解决方案1】:

您的代码存在问题以及它无法按预期工作的原因是:

for first in a:
b = a[a.index(first)+1:]
for second in b:
    if first > second:
        a[a.index(first)] = second
        a[a.index(second)] = first
        numSwap += 1

您正在交换第一个数组 a 中的元素,但没有更新第二个数组 b 中的元素。

这是一个可以完美运行的解决方案:

import sys

n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
# Write Your Code Here
numberOfSwaps = 0
for i in xrange(n):
    for j in xrange(n-1):
        if a[j] > a[j+1]:
            a[j], a[j+1] = a[j+1], a[j]
            numberOfSwaps += 1
    if not numberOfSwaps:
        break


print "Array is sorted in", numberOfSwaps, "swaps."
print "First Element:", a[0]
print "Last Element:", a[n-1]

干杯:)

【讨论】:

  • 我没有更新b 列表,以便first 变量仍将与列表中的其他元素进行比较。谢谢你的解决方案,我已经知道了,但我仍然很困惑为什么我的不起作用。
  • 如果我提供的解决方案有效,请投票并接受它作为答案:)
  • 我仍然很困惑,为什么我的代码实际上无法正常工作,而您的解释却令我不满意。我不明白为什么要更新您提到的b 列表,因为b 列表应该使first 变量与b 列表中的其他元素相比。
【解决方案2】:

我终于知道我的代码有什么错误了。

for first in a:
    b = a[a.index(first)+1:]
    for second in b:
        if first > second:
            a[a.index(first)] = second
            a[a.index(second)] = first
            numSwap += 1

所以下面的这些代码将元素交换回原来的位置:

a[a.index(first)] = second
a[a.index(second)] = first

应该创建一个变量来包含其中一个元素。

smaller = a.index(first)
bigger = a.index(second)
a[smaller] = second
a[bigger] = big

我的第二个错误是第一个 for 不会从新更新的列表中重复算法,导致 2 作为第一个元素。

正确的代码由 TheDarkKnight 编写。

这是一个可以完美运行的解决方案:

import sys

n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
# Write Your Code Here
numberOfSwaps = 0
for i in xrange(n):
    for j in xrange(n-1):
        if a[j] > a[j+1]:
            a[j], a[j+1] = a[j+1], a[j]
            numberOfSwaps += 1
    if not numberOfSwaps:
        break


print "Array is sorted in", numberOfSwaps, "swaps."
print "First Element:", a[0]
print "Last Element:", a[n-1]

干杯:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    相关资源
    最近更新 更多