繁体   English   中英

如果条件在第一级满足,如何停止循环

[英]how to stop the looping if the condition satisfies in the first level

如果我的列表中任意两个元素的差值等于 n,那么我将输出显示为 True else False

我已在“显示某些代码”区域更新了代码详细信息。请参考

my_list = [1,3,4,9]
n = len(my_list) 
z = 3
def checking(my_list,z): 
    count = 0
    for i in range(0, n):           
        for j in range(i+1, n):         
            if my_list[i] - my_list[j] == z or my_list[j] - my_list[i] == z: 
                print('yes')
            else:
                print('No')
print(checking(my_list,z))

期待:如果我的列表是-[1,3,4,9] 和 Z=3,那么我期待与我的 output 一样正确(因为 4-1=3)我使用了 2 个循环。我可以只用一个循环解决这个问题吗

实际:在上面的同一示例中,我得到以下 output 否 是 否 否 否 否 无

您可以使用itertools模块中的combinations来生成列表对,如果满足条件则返回 True,否则返回 false。 我添加了一条打印线,以便您可以查看它处理的组合。 我也使用了TrueFalse ,因为这就是你所说的

from itertools import combinations


def checking(my_list, z):
    for i, j in combinations(my_list, 2):
        print("Checking pair: i=",  i,  ", j=", j)
        if i - j == z or j - i == z:
            return True
    print("no matches found")
    return False


my_list = [1, 3, 4, 9]
my_list2 = [1, 3, 5, 9]
z = 3
print(checking(my_list, z))
print(checking(my_list2, z))

OUTPUT

Checking pair: i= 1 , j= 3
Checking pair: i= 1 , j= 4
True
Checking pair: i= 1 , j= 3
Checking pair: i= 1 , j= 5
Checking pair: i= 1 , j= 9
Checking pair: i= 3 , j= 5
Checking pair: i= 3 , j= 9
Checking pair: i= 5 , j= 9
no matches found
False
import sys

def checking(my_list,z): 
    for i in range(0, n):           
        for j in range(i+1, n):
            if abs(my_list[i] - my_list[j]) == z : 
                return 'yes' # return ends the loop, by ending the entire function call
            # else: # comment out if you don't want the "no"s printed
            #     print('No. (Iteration i={}, j={})'.format(i,j)) # comment out if you don't want the "no"s printed
    # if it reaches here, then the both the loops finished 
    # without finding a True condition. 
    # So simply return the No (no reason for an else.)
    return ("No") 

my_list = [1,3,4,9]
n = len(my_list) 
z = 3
print("First run with [{}]".format(my_list))
print(checking(my_list,z))

my_list = [1,1,1,1]
n = len(my_list) 
z = 3
print("First run with [{}]".format(my_list))
print(checking(my_list,z))

OUTPUT:

First run with [[1, 3, 4, 9]]
yes
First run with [[1, 1, 1, 1]]
No

尝试在条件中的 print 语句之后使用 break 语句。 这用于退出您所处的任何条件或循环。这是假设您没有在方法中执行此操作,在这种情况下,我建议返回“yes”,它会自动退出 function。 要么或应该工作。

使用一个标志。 当条件为真时,只需将标志设置为 1 并中断循环。 如果标志未设置为 1,则继续检查。

my_list = [1,3,4,9]
n = len(my_list) 
z = 3
flag = 0
def checking(my_list,z): 
    for i in range(0, n) and flag is 0:           
        for j in range(i+1, n) and flag is 0:         
            if my_list[i] - my_list[j] == z or my_list[j] - my_list[i] == z: 
                flag = 1
if flag is 1:
  print("True")
else:
  print("False")

对于:“期待:如果我的列表是-[1,3,4,9] 和 Z=3,那么我期待与我的 output 一样正确(因为 4-1=3)我使用了 2 个循环。我可以用只有一个循环

这是使用二进制搜索的解决方案 [IMP:要执行二进制搜索,您的列表应该排序]:

def checking(my_list, z):
    low = 0
    high = len(my_list)-1
    while low < high:
        find = my_list[high] - my_list[low]
        if find == z:
            return True
        else:
            if find > z:
                high -=1
            else:
                low +=1
    return False

print(checking([1,3,4,9],3))
print(checking([1,2,2,3],9))

访问此链接有关使用 Python 的数据结构的大量资源: https://runestone.academy/runestone/books/published/pythonds/SortSearch/TheBinarySearch.ZFC35FDC70D5FC69D2368C

还有另一种方法可以提高效率,即散列。 将留给您研究解决方案。

这是使用list comprehensions实现目标的另一种方法。

在这里,我使用绝对差abs() 真正的差异版本如下(在更新部分)。

my_list = [1,3,4,9]
z = 3

def checking(my_list,z):
    outputs = [abs(i-j) for i in my_list for j in my_list if i != j and abs(i-j) == z]

    if len(outputs):
        print("Yes") # you can delete this line
        return True
    else:
        print("No") # you can delete this
        return False

# testing
print(checking(my_list, z)) 

Output:

Yes
True

更新:下面的版本使用真正的差异,而不是绝对的差异。

my_list = [1,3,4,9]
z = 3

def checking(my_list,z):
    outputs = [(i-j) for i in my_list for j in my_list if i != j and (i-j) == z]

    if len(outputs):
        print("Yes") # you can delete this line
        return True
    else:
        print("No") # you can delete this
        return False

# testing
print(checking(my_list, z)) 

Output:

Yes
True

在这个版本中,如果z = -3 ,结果将是:

Yes
True

暂无
暂无

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

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