简体   繁体   English

什么时候应该使用while循环和if语句?

[英]When should I use while loop and if statement?

I was trying out a question where you have to swap the adjacent elements in an array based on the number of swaps given.我正在尝试一个问题,您必须根据给定的交换次数交换数组中的相邻元素。 For example:例如:

Suppose, no of swaps = 2, and the array is [5,3,1].假设交换次数为 2,数组为 [5,3,1]。 Then the sorted array after two successful swaps will be [3,5,1] --> 1st swap, [3,1,5] --> 2nd swap.那么两次成功交换后的排序数组将是 [3,5,1] --> 1st swap, [3,1,5] --> 2nd swap。 So sorted array is [1,3,5].所以排序后的数组是 [1,3,5]。

This is my code on achieving the above result:这是我实现上述结果的代码:

T = int(input())                 # This is the number of testcases
l = 0
for i in range(T):
    N, K = input().split()       # N is the size of array, K is the number of swaps needed to be done
    N, K = int(N), int(K)
    A = input().split(" ", N)    # A is the array of elements
    for j in range(len(A)):
        A[j] = int(A[j])

    while K != 0:
        for k in range(l+1, N):
            if A[l] > A[k]:
                A[l], A[k] = A[k], A[l]
                K -= 1
                l = 0
            else:
                l += 1
            break
    
    for j in A:
        print(j, end=" ")
    l = 0
    print()

At first, when I tried out if K!=0 only 1 swap was done.起初,当我尝试if K!=0只完成了 1 次交换。 Only after using while K!=0 , the code worked perfectly.只有在使用while K!=0 ,代码才能完美运行。 So,my question is why didn't it work for the if statement?所以,我的问题是为什么它不适用于if语句? When is it appropriate to use if and while ?什么时候使用ifwhile合适?

  T=int(input()) 
  for _ in range(T):
                        [N,K]=list(map(int, input().rstrip().split()))
                        arr = list(map(int, input().rstrip().split()))
                        
                        for i in range(K):
                                            arr[i],arr[i+1]=arr[i+1],arr[i]
                                           
                        print(*arr)

在此处输入图片说明

Is this what are you trying to get?这是你想要得到的吗? Swap as you iterate through the list and stop when you have reached the swapping limit.遍历列表时进行交换,并在达到交换限制时停止。

if will only check the value of k once, while will continue(like a loop) what in the scope till your condition is false you can use while if you are waiting for a specific action to stop/break, and if when need to check something at a time. if只检查ķ一次的值, while将继续(如环)什么范围,直到你的条件是false ,你可以使用while如果你在等待一个具体行动,停止/休息, if当需要检查一次某事。 I hope that was clear.我希望这很清楚。 in your case for will works well.在你的情况下, for will 运作良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM