【问题标题】:Sorting Highest to Lowest using a loop and arrays使用循环和数组从最高到最低排序
【发布时间】:2015-09-22 05:56:06
【问题描述】:
while Checked == False:
for Counter in range(1, NoOfRecords + 1):
    if Test[Counter] < Test[Counter + 1]:
        Temp = Test[Counter]
        Test[Counter] = Test[Counter + 1]
        Test[Counter + 1] = Temp
    if Test[1] > Test[2] > Test[3] > Test[3] > Test[4] > Test[5]:
        Checked = True
print(Test[1], Test[2], Test[3], Test[4], Test[5])

基本上,我的目标是将输入从最低到最高排序。在此之前,要求用户输入 0 到 5 之间的 5 个数字。

但是,在输入了 5 个输入之后,没有任何其他内容出现,没有打印。

您能提出改进建议吗?或用于排序过程的不同类型的循环?谢谢

编辑下面的完整代码

import array
Test = array.array ("f", range(11))
Counter = int(1)
NoOfRecords = int(5)
Checked = False
Temp = int(0)
def Tempurature (Day,Lowest,Highest):
    ok = False
    while ok == False:
        try:
            Input = float(input(Day + " Tempurature:"))
            if Input >= Lowest and Input <= Highest:
                ok = True
                return Input
            else:
                print ("\nPlease enter a number between " + str(Lowest) + " and " + str(Highest))
        except:
            print ("\nPlease enter a valid number")

for Counter in range(1, NoOfRecords + 1):
    Test[Counter] = Tempurature ("Mid-Day", 0, 5)

while Checked == False:
    for Counter in range(1, NoOfRecords + 1):
        if Test[Counter] < Test[Counter + 1]:
            Temp = Test[Counter]
            Test[Counter] = Test[Counter + 1]
            Test[Counter + 1] = Temp
    if Test[1] > Test[2] > Test[3] > Test[3] > Test[4] > Test[5]:
        Checked = True

print(Test[1], Test[2], Test[3], Test[4], Test[5])

【问题讨论】:

  • Test = sorted(Test) 呢? (假设您的列表中有ints;如果您使用用户输入填充列表,则必须首先将字符串转换为int)。

标签: python arrays sorting


【解决方案1】:

这看起来更简单,更 Pythonic。但是,如果您的目标是学习有关排序的知识,那将毫无用处...

Test = []
NoOfRecords = 5


def Tempurature(Day, Lowest, Highest):
    while True:
        try:
            Input = float(input(Day + " Tempurature:"))
            if Highest >= Input >= Lowest:
                return Input
            else:
                print("Please enter a number between {} and {}".format(
                      Lowest, Highest))
        except ValueError as exc:
            print("Please enter a valid number")
            # print(exc)

for Counter in range(NoOfRecords):
    Test.append(float(Tempurature("Mid-Day", 0, 5)))

print(Test)
print(sorted(Test, reverse=True))

【讨论】:

  • 捕获异常时最好是显式的(except ValueError:在这种情况下),裸except:可能会隐藏不相关的异常。
【解决方案2】:

编辑:我的回答错了,订单检查没有倒退,所以我重写了。

这一次,看看这个:

if Test[1] > Test[2] > Test[3] > Test[3] > Test[4] > Test[5]:

哇,哇:

                       Test[3] > Test[3]

永远不会发生。

让我们也 print(Test) 运行一次:

Mid-Day Tempurature: 1
Mid-Day Tempurature: 2
Mid-Day Tempurature: 3
Mid-Day Tempurature: 4
Mid-Day Tempurature: 5
array('f', [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 3.0, 4.0, 5.0, 6.0, 2.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 3.0, 4.0, 5.0, 6.0, 2.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 4.0, 5.0, 6.0, 3.0, 2.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 4.0, 5.0, 6.0, 3.0, 2.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 5.0, 6.0, 4.0, 3.0, 2.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 5.0, 6.0, 4.0, 3.0, 2.0, 1.0, 7.0, 8.0, 9.0, 10.0])
array('f', [0.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 7.0, 8.0, 9.0, 10.0])
6.0 5.0 4.0 3.0 2.0

查看 Test[5+1] 的排序循环,它延伸到您从未输入过的元素并将 6.0 拖到列表的前面。

但是你说“我的目标是,基本上,将输入从最低到最高排序。”这表明你正在将它们从最高到最低排序。

  1. 为什么要使用 11 元素数组来充当 5 元素列表?
  2. 不需要int(0)int(5),0 和 5 已经是整数。而且您不需要在顶部预先编写每个变量,只需一些。
  3. while ok == false 获取数字时的检查没有任何用处,因为您从 while 循环的中间返回函数。
  4. 交换比较以使它们从最低到最高排序。
  5. While Checked == False:While not Checked: 更惯用

所以:

import array
Test = array.array ("f", range(11))
NoOfRecords = 5
Checked = False

def Temperature (Day,Lowest,Highest):
    while True:
        try:
            Input = float(input(Day + " Temperature:"))
            if Input >= Lowest and Input <= Highest:
                return Input
            else:
                print ("\nPlease enter a number between " + str(Lowest) + " and " + str(Highest))
        except ValueError:
            print ("\nPlease enter a valid number")

for Counter in range(1, NoOfRecords + 1):
    Test[Counter] = Temperature ("Mid-Day", 0, 5)

while not Checked:
    for Counter in range(1, NoOfRecords):
        if Test[Counter] > Test[Counter + 1]:
            Test[Counter]
            Test[Counter] = Test[Counter + 1]
            Test[Counter + 1] = Temp

    if Test[1] <= Test[2] <= Test[3] <= Test[4] <= Test[5]:
        Checked = True

print(Test[1], Test[2], Test[3], Test[4], Test[5])

但是,使用列表...

Test = []
NoOfRecords = 5
Checked = False

def Temperature(Day, Lowest, Highest):
    while True:
        try:
            Input = float(input(Day + " Temperature:"))
            if Input >= Lowest and Input <= Highest:
                return Input
            else:
                print("\nPlease enter a number between {0} and {1}".format(Lowest, Highest))
        except ValueError:
            print ("\nPlease enter a valid number")


for i  in range(NoOfRecords):
    Test.append(Temperature ("Mid-Day", 0, 5))


while not Checked:
    for i  in range(NoOfRecords-1):
        if Test[i] > Test[i + 1]:

            Test[i], Test[i+1] = Test[i+1], Test[i]

    if Test[0] <= Test[1] <= Test[2] <= Test[3] <= Test[4]:
        Checked = True

print(Test)

【讨论】:

  • 完全重写的答案。
【解决方案3】:

如果你坚持使用的排序程序,我建议修改如下:

while Checked == False:
    for Counter in range(1, NoOfRecords):
        if Test[Counter] < Test[Counter + 1]:
            Temp = Test[Counter]
            Test[Counter] = Test[Counter + 1]
            Test[Counter + 1] = Temp
    if Test[1] >= Test[2] and Test[2] >= Test[3] and Test[2] >= Test[3] and Test[3] >= Test[4] and Test[4] >= Test[5]:
        Checked = True

这是因为您只想关注被排序的数组部分,因此是for Counter in range(1, NoOfRecords)(考虑到最后一个元素,因为您在for 循环中引用了Test[Counter + 1])。

另外,应该测试if 条件中可能的相等性以避免程序卡在while 循环中的情况

【讨论】:

  • 这对我很有帮助,但是有没有办法让最终检查更短一点? if Test[1] &gt;= Test[2]
  • 当然,可以链接比较,即if Test[1] &gt;= Test[2] &gt;= Test[3] &gt;= Test[4] &gt;= Test[5],或者使用类似if all([Test[i] &gt;= Test[i + 1] for i in range(1, 5)])的东西,因为all返回True如果所有条件都满足
最近更新 更多