Home > Software engineering >  Python, while loop stops after one iteration [closed]
Python, while loop stops after one iteration [closed]

Time:09-17

When the program receives input for "cubes", I want to first check if the maximum value is on one end of the sequence. If yes, delete the max value, if not, exit and print no. As long as 'd' is not empty, keep on looping, till 'd' is empty. Then print yes, or exit the program in one of the loops.

I can input 'T' number of test sequences. Suppose I give a sequence [4, 3 ,1, 3 ,4]. It only does one iteration, but it should keep on and delete 4, 3, 3, 1. Thank you for help! I am kind of not very experienced.

from collections import deque
T=int(input())#number of test cases

for i in range(T):
    n=int(input())
    cubes=map(int, input().split())
    d=deque(cubes)       
    while len(d)!=0:
        a=max(d)
        if d.index(a)==0 or d.index(a)==-1:
            d.remove(a)
        else:
            break
            
     if len(d)==0:
         print('yes')
     else:
         print ('no')

CodePudding user response:

I think you compare the wrong indexes here:

if d.index(a)==0 or d.index(a)==-1:

If element is the last, index returns len(d) - 1, not -1
https://docs.python.org/3/library/collections.html#collections.deque.index

You should write something like:

if d.index(a) == 0 or d.index(a) == len(d)-1:

CodePudding user response:

While reading your code, I noticed :

cubes=map(int, input().split())

input() imports your input as a string, while String#split with no argument splits using space.

So if you provide the string [4, 3 ,1, 3 ,4], you get the following array:

['[4,', '3', ',1,', '3', ',4]']

Try 4 3 1 3 4 as input?

  • Related