为什么我的while命令不起作用?

时间:2018-08-16 14:23:34

标签: python

我不明白为什么我的代码无法在> set.seed(42) > df <- data.frame(x = runif(10), y = runif(10)) > AddNewCol( df ,"result") x y result 1 0.9148060 0.4577418 0.191677054 2 0.9370754 0.7191123 0.484582715 3 0.2861395 0.9346722 0.249974991 4 0.8304476 0.2554288 0.054181629 5 0.6417455 0.4622928 0.137150421 6 0.5190959 0.9400145 0.458687354 7 0.7365883 0.9782264 0.704861206 8 0.1346666 0.1174874 0.001858841 9 0.6569923 0.4749971 0.148232064 10 0.7050648 0.5603327 0.221371155 处工作

为什么不将8与5、8、12、18、22进行比较?

print "start with 8"

我的代码的输出:

#Sum of two lowest integers
numbers = [5,8,12,18,22]
keep_ans = []
limit = len(numbers)
for i in numbers:
    print("Start with "+str(i))
    run = 0
    check_in = 0
    Done = False #It's stop here, when i = 8
    while Done == False:
        if i <= numbers[check_in]:
            print("Compare "+str(i)+" with "+str(numbers[check_in])+" round:"+str(run))
            run += 1
            check_in += 1
        if run == limit-1:
            keep_ans.append(i)
            Done = True
ans = sum(keep_ans)
print(ans)

2 个答案:

答案 0 :(得分:3)

您陷入while循环中,因为在第二次迭代中您没有输入第一个if条件,因此永远不要在runcheck_in上加1。

要解决此问题,您需要更改缩进:

while Done == False:
    if i <= numbers[check_in]:
        print("Compare "+str(i)+" with "+str(numbers[check_in])+" round:"+str(run))
    run += 1
    check_in += 1

使用此算法,您的算法将终止。

答案 1 :(得分:0)

我得到了答案!,谢谢。

numbers = [5,8,12,18,22]
keep_ans = []
print("Number => "+str(numbers))
for i in numbers:
    print("Start with  >  "+str(i)+"  <")
    point = 0
    round = 0
    limit = len(numbers)
    for i2 in numbers:
        print("     Compare with :"+str(numbers[point]))
        if i < i2:
            round += 1
            #print("     get")
        point += 1
        if round == limit-2:
            #print("Added!!!!!")
            keep_ans.append(i)
            break
    #print(keep_ans)
print("Two lowest numbers = "+str(keep_ans))
print("Sum of two lowest numbers = "+str(sum(keep_ans)))

### Output ###
Number => [5, 8, 12, 18, 22]
Start with  >  5  <
     Compare with :5
     Compare with :8
     Compare with :12
     Compare with :18
     Compare with :22
Start with  >  8  <
     Compare with :5
     Compare with :8
     Compare with :12
     Compare with :18
     Compare with :22
Start with  >  12  <
     Compare with :5
     Compare with :8
     Compare with :12
     Compare with :18
     Compare with :22
Start with  >  18  <
     Compare with :5
     Compare with :8
     Compare with :12
     Compare with :18
     Compare with :22
Start with  >  22  <
     Compare with :5
     Compare with :8
     Compare with :12
     Compare with :18
     Compare with :22
Two lowest numbers = [5, 8]
Sum of two lowest numbers = 13