gpt4 book ai didi

python - 排列 : producing cycle notation

转载 作者:行者123 更新时间:2023-11-30 22:57:20 25 4
gpt4 key购买 nike

请考虑以下问题:我有一定的排列西格玛:

sigma = [4,1,6,2,3,5]

期望的结果是产生如下循环符号:

my_cycles_perm = [[4,2,1],[6,5,3]]

我的尝试按照下面的代码进行,但是似乎我只达到了第一个周期,但似乎无法重新进入第二个周期:

my_row_cycle 函数背后的想法是采用一定的排列西格玛,设置一种称为标记的断路器(当标记 == 0 时 crcuit 关闭),并迭代排列直到我完成一个循环,一旦循环完成后我将其存储到列表中。

然后,我通过再次迭代 sigma 来验证是否还有其他循环可以从排列中提取,直到在 sigma 中找到不在之前提取的循环中的数字。如果找到这样的数字,我将重新启动该过程。如果不是,我会触发断路器,标记 == 1 来结束整个过程并输出西格玛排列的循环符号。

但这对我来说似乎仍然是乌托邦。 :)

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

评估后:

(1, 4, 1, 6, [4, 2, 1], 1, [[4, 2, 1]])

我似乎无法理解为什么我的标记会跳到值“1”,但我的循环符号不完整。如果您有任何建议和或更正,我先谢谢您。

最佳答案

我相信这个函数可以满足您的要求:

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]]

关于python - 排列 : producing cycle notation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36683413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com