问题描述
Stack Overflow、Python 和一般编码的新手。
= = = = =
我已阅读并尝试过:
permutations with unique values
Unique permutations of a list without repetition
Generating unique permutations
Generating Unique Permutations in Python
我认为这些都不满足以下条件。
当“名称”列表变大时,我的代码要么遇到递归限制,要么需要很长时间。再说一次,我是新来的。
= = = = =
排列/组合规则:
给定列表 A B C D; (最终名单会更长) A不能有A等;
如果 A:x 那么 A 不能再次用作 A:x;
如果 x:B 则 B 不能再次用作 x:B;
只需要 len(list) 可能的排列/组合,其中列表中的每个字母每个位置只使用一次;
后续的排列/组合不能包含之前的任何一个;
不能使用itertools;
= = = = =
问题:有没有更好的编码方法,不用 itertools?
额外问题:有没有办法“告诉”脚本将达到递归限制并安全退出?
from random import seed,shuffle
import os
import sys
from datetime import datetime
#= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
new_seed_num = datetime.Now().strftime("%f")
seed(int(new_seed_num))
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
dict_list = []
blocked_tuple = ("A","B")
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# Convert all dictionaries into a list of unique tuples
# This would use a list built from file IO and an earlier list
# Lists not in example
def pairs_exractor(dict_list,blocked_tuple):
tuple_pairs = []
if len(blocked_tuple) > 0:
for blocked_t in blocked_tuple:
tuple_pairs.append(blocked_t)
for dct in dict_list:
temp_pairs_view = dct.items()
temp_pairs = list(temp_pairs_view)
for tup_pair in temp_pairs:
if tup_pair not in tuple_pairs:
tuple_pairs.append(tup_pair)
else:
pass
return tuple_pairs
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# Generate dict of unique pairs that does not match any pairs in any of the lists
def pairs_comparator():
abcd_list = ["A","B","C","D"]
shuffle(abcd_list)
new_pairs_dict = {}
pop_list_1 = abcd_list[:]
pop_list_2 = abcd_list[:]
p_list = pairs_exractor(dict_list,blocked_tuple)
print(f"Blocked tuple: {p_list}\n")
# p_list empty in this example except for blocked tuple
# p_list would be the list of all tuples prevIoUsly used,from file IO
for num in range(0,len(abcd_list)):
shuffle(pop_list_1)
shuffle(pop_list_2)
pop_1_name = pop_list_1.pop()
pop_2_name = pop_list_2.pop()
popped_tup = (pop_1_name,pop_2_name)
if pop_2_name != pop_1_name and popped_tup not in p_list:
new_pairs_dict[pop_1_name] = pop_2_name
else:
return pairs_comparator()
return new_pairs_dict
# User can assign a "name" in list to be blocked in an iteration
# User can assign a "name-pair" to be blocked in an iteration
# Script runs and saves most recent dict to file
# Script then reads file and builds list of dicts from which "name-pairs" cannot match
# In the above example the "names" are "A","D"
# File IO and list building works and assistance for them is not needed
print(pairs_comparator())
谢谢, 标记
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)