[英]Transform Python dictionary from {'a': ['A', 'B'], 'b': ['B', 'C']} --> {'A': ['a'], 'B': ['a', 'b'], 'C': ['b']}
[英]Python backtracking strings lenght n from alphabet {a,b,c} with #a=#b
我想做一個算法,查找給定n個字母{a,b,c}上的字符串,其中數字“ a”出現與“ b”相同的次數
我出來這個
n=3 #length String
h=-1 #length prefix
L=['a','b','c'] #alphabet
S=['','','',''] #solution
par=0 # it's zero if a and b have same occurence
def P(n,h,par,L,S):
if h==n:
if par==0:
print(S)
else:
for i in L:
if i=='a':
par+=1
if i=='b':
par-=1
S[h+1]=i
P(n,h+1,par,L,S)
#Update the stack after recursion
if S[h+1]=='a':
par-=1
if S[h+1]=='b':
par+=1
P(n,h,par,L,S)
我為糟糕的字符串實現表示歉意,但它只能用於研究目的,問題是:有什么方法可以避免算法的某些工作? 因為它僅在為該字母表生成所有n長度的字符串后才檢查#a和#b。 我的目標是達到O(n *(要打印的字符串數))
這是您要執行的操作:
from itertools import combinations_with_replacement
alphabet = "abc"
def combs(alphabet, r):
for comb in combinations_with_replacement(alphabet, r):
if comb.count('a') == comb.count('b'):
yield comb
為了這,
list(combs(alphabet, 3)) == [('a', 'b', 'c'), ('c', 'c', 'c')]
和
list(combs(alphabet, 4)) == [('a', 'a', 'b', 'b'),
('a', 'b', 'c', 'c'),
('c', 'c', 'c', 'c')]
這將產生所有組合並拒絕某些組合; 根據combinations_with_replacement
的文檔 :
返回的項目數為
(n+r-1)! / r! / (n-1)!
(n+r-1)! / r! / (n-1)!
當n > 0
。
其中n == len(alphabet)
您可以通過更改以下內容來消除浪費的工作:
if i=='a':
par+=1
if i=='b':
par-=1
至
oldpar = par
if i=='a':
par+=1
if i=='b':
par-=1
# there are n-h-1 characters left to place
# and we need to place at least abs(par) characters to reach par=0
if abs(par)>n-h-1:
par = oldpar
continue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.