python中outside loop_Python:无法使用“SyntaxError:'break”outside loop打破while循环

我正在为一个因子分解问题开发一个广度优先的搜索算法,在试图打破while循环时遇到了一个有趣/令人困惑的bug。如果您运行以下代码,它将在“构造路径”方法内失败,说明:

“文件”主.py“,第96行

打破

SyntaxError:“break”外部循环

但我在一个while循环中!如果有人能在这个问题上给我一些建议,我将非常感激。提前谢谢。在from numpy import random

import itertools

import Queue

#Finding multiples, BFS problem

#Given input of list with unique integers 0 - 9 and n = range(0,1000000), calculate smallest multiple of n and unique combination of values in the list

#Example : Input : list = {0,1,2} , n = 3,

# output = 12

# Input : list = {0,1,2} , n = 50

# Output = 200

class Problem:

def __init__(self):

self.n = random.randint(0,10000000)

listSize = random.randint(1,9)

mainSet = set()

self.mainList = []

while True:

toAdd = random.randint(0,9)

if(toAdd not in self.mainList):

self.mainList.append(toAdd)

if(len(self.mainList) == listSize):

break

def get_start_state(self):

s = ''.join(map(str, self.mainList))

return int(s)

def is_goal(self, state):

return True

def get_sucessors(self):

print "Getting successors"

def breadth_first_search(problem):

# a FIFO open_set

open_set = Queue.Queue()

# an empty set to maintain visited nodes

closed_set = set()

# a dictionary to maintain meta information (used for path formation)

meta = dict() # key -> (parent state, action to reach child)

# initialize

start = problem.get_start_state()

meta[start] = (None, None)

open_set.put(start)

while not open_set.empty():

parent_state = open_set.get()

print "{} {}".format("parent_state is ", parent_state)

if problem.is_goal(parent_state):

return construct_path(parent_state, meta)

for (child_state, action) in problem.get_successors(parent_state):

if child_state in closed_set:

continue

if child_state not in open_set:

meta[child_state] = (parent_state, action)

open_set.put(child_state)

closed_set.add(parent_state)

#collect path to desired answer

def construct_path(state, meta):

action_list = list()

while True:

row = meta[state]

if (len(row) == 2):

state = row[0]

action = row[1]

action_list.append(action)

else:

break

return action_list.reverse()

x = Problem()

breadth_first_search(x)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值