请考虑以下问题:我有一定的排列西格玛:
<extension
id="de.mdsd.xtext.sponsorrun.application.joggathon.editor.perspectives"
name="Joggathon Editor Perspectives"
point="org.eclipse.ui.perspectives">
<perspective
class="de.mdsd.xtext.sponsorrun.application.PerspectiveFactory1"
icon="icons/Joggathon-Group16.png"
id="de.mdsd.xtext.sponsorrun.application.joggathon.editor"
name="Joggathon">
</perspective>
</extension>
期望的结果是产生以下循环符号:
sigma = [4,1,6,2,3,5]
我的尝试按照下面的代码进行,但似乎我只能达到第一个周期,但似乎无法重新进入第二个周期:
my_row_cycle函数背后的想法是采取一定的排列sigma,设置一种称为标记的断路器(当标记== 0时crcuit关闭),并迭代置换直到我完成一个循环,一旦循环完成后我将其存储在一个列表中。
然后我通过再次迭代西格玛来验证是否还有其他循环从排列中提取,直到我在之前提取的循环中找到西格玛中的数字。如果找到这样的数字,我重新启动该过程。如果不是我跳闸我的断路器,标记== 1结束整个过程并输出我的周期符号的西格玛排列。但这对我来说似乎仍然是乌托邦。 :)
my_cycles_perm = [[4,2,1],[6,5,3]]
评估后:
def my_row_cycle(sigma):
aux_sigma = list(sigma)
init_ref = aux_sigma.index(aux_sigma[0]) +1 #First antecedent of aux_sigma
init_image = aux_sigma[init_ref-1] #Image of the antecedent
jumper_image = init_image
row_cycle = []
row_cycle.append(init_image)
my_cycles_perm = []
marker = 0
while marker == 0: #Circuit breaker
while jumper_image != init_ref: #establishes if cycle complete
for x in aux_sigma: #iterates sigma while cycle incomplete
jumper_ref = aux_sigma.index(x) + 1
if jumper_ref == jumper_image: #Condition to append to cycle
row_cycle.append(x)
jumper_image = x #Changing the while loop condition
my_cycles_perm.append(row_cycle)
for a in aux_sigma:
for a in my_cycles_perm:
cycle = a
for a in cycle: #looking for match in aux_sigma and cycle
if a not in cycle:
row_cycle = []
init_image = a
init_ref = aux_sigma.index(init_image) + 1
marker = 0
break
else:
marker = 1
return init_ref, init_image, jumper_image, jumper_ref, row_cycle, marker, my_cycles_perm
我似乎无法理解为什么我的标记会绊倒价值&#34; 1&#34;但我的循环符号不完整。 如果您有任何建议或更正,我会提前感谢您。
答案 0 :(得分:3)
我相信这个功能符合您的要求:
def to_cycles(perm):
pi = {i+1: perm[i] for i in range(len(perm))}
cycles = []
while pi:
elem0 = next(iter(pi)) # arbitrary starting element
this_elem = pi[elem0]
next_item = pi[this_elem]
cycle = []
while True:
cycle.append(this_elem)
del pi[this_elem]
this_elem = next_item
if next_item in pi:
next_item = pi[next_item]
else:
break
cycles.append(cycle)
return cycles
print(to_cycles([]))
# []
print(to_cycles([1]))
# [[1]]
print(to_cycles([4,1,6,2,3,5]))
# [[4, 2, 1], [6, 5, 3]]
答案 1 :(得分:0)
可能是因为您在嵌套循环中多次意外使用变量a
:
for a in aux_sigma :
for a in my_cycles_perm :
cycle = a
for a in cycle : # <<-- a iterates ovr cycles, so
if a not in cycle : # <<-- a in cycle is alsways true
# [...]
marker = 1
else :
marker = 0
将单独的变量名称分配给所有不同的迭代。