Python 如何跳出多重循環


今晚在寫歐拉題目的時候就碰到這樣的問題,需要跳出一個三重循環,但是真的很無奈,沒有太好的辦法,下面的是代碼:

import time
def isPrime(n):
    """This function return a number is a prime or not"""
    from math import sqrt
    for i in range(2, int(sqrt(n))+1):
        if n % i == 0:
            return False
    return True

def permu(m, n):
    """This function return if two numbers has the same digits."""
    ms = list(str(m))
    ms.sort()
    ns = list(str(n))
    ns.sort()
    if ms == ns:
        return True
    else:
        return False
    
start = time.clock()    
primelist = [i for i in range(1000, 9999) if isPrime(i)]
primeset = set(primelist)
n = len(primelist)
count = 0

while count != 2:
    for i in range(0, n-2):
        for j in range(i+1, n-1):
            b = (primelist[i]+primelist[j])/2
            if b in primeset:
                if permu(primelist[i],primelist[j]) and permu(primelist[i], int(b)):
                    count += 1
                    if count == 2: print(str(primelist[i])+str(int(b))+str(primelist[j]))
                        
print(time.clock() - start)

 

本意是打算在count==2的時候,跳出這個三重循環的,結果發現不管怎么寫都不行。所以只能無奈的在while上做了一個限制才跳出來的。

 

下面的是網上看到的其他人的關於跳出多重循環的辦法

一,可以插入exception跳出。

class FoundException(Exception): pass

try:
    for row,record in enumerate(table):
         for columu,field in enumerate(record):
               for index,item in enumerate(field):
                       if item == target:
                                 raise FoundException()
except FoundException:
      print ("found at ({0},{1},{2})".format(row,column,index))
else:
       print ('not found')

 

二,就是放在函數體里,用return 語句返回。

def test():
    for x in range(9,0,-1):
         for y in range(9,-1,-1):
                for z in range(9,-1,-1):
                   s = 100001*x+10010*y+1100*z
                   s1 = int((round((s**0.5),0))) + 1
                   for i in range(s1,100,-1):
                      if s % s1 ==0:
                         print s,i
                         return s

 

當然如果是while循環你也可以像我那樣在最頂層加入flag判定,然后跳出。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM