python - Passing modified list to each node of binary tree -


i writing function grow tree:

def collect_append(collect,split):  collect.append(split)  return collect            def tree(string,passwords,collect): #collect list , passwords list   matching_list = []  match = 0  if len(string)==0:   print(collect)   return 0  j in passwords:    in range(min(len(j),len(string))):      if string[i]!=j[i]:       break  else :    matching_list.append(j)    match = match + 1  if match == 0:   return 1  else:   split in matching_list:    x =tree(string.strip(split),passwords,collect_append(collect,split))  return x  

my question is, each split in matching_list(say two), want add different strings existing list @ point (i.e. want 2 versions of list).

in case collect_append function use modifying list in first iteration of for loop , using same further iterations. want modify collect list parameter , without permanently changing it. there way this?

i see 2 serious errors in code. first, else clause never executed:

for j in passwords:     in range(...):         if ...:             break else:     ... 

since break in inner for loop, outer for loop never exited via break else never taken. second, doesn't want:

string.strip(split) 

you're trying remove split beginning of string you're removing letters in split both ends of string, bruising badly. here's 1 way correctly:

string[len(split):] 

i'm going go out on limb, , rewrite code think want do:

def tree(string, passwords, collect):      length = len(string)      if length == 0:         return false      matching_list = []      j in passwords:         = min(len(j), length)          if string[:i] == j[:i]:             matching_list.append(j)      if not matching_list:         return false      result = false      split in matching_list:         local_collection = list([split])         if split == string or tree(string[len(split):], passwords, local_collection):             collect.append(local_collection)             result = true      return result  collection = []  print(tree('dogcatcher', ['cat', 'catch', 'cher', 'dog', 'dogcat', 'dogcatcher', 'er'], collection))  print(collection) 

output

% python3 test.py true [['dog', ['cat', ['cher']], ['catch', ['er']]], ['dogcat', ['cher']], ['dogcatcher']] % 

giving tree of ways assemble string words in passwords.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -