今晚在寫歐拉題目的時候就碰到這樣的問題,需要跳出一個三重迴圈,但是真的很無奈,沒有太好的辦法,下面的是代碼:
import timedef 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 Truedef 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 = 0while 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): passtry: 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判定,然後跳出。