My friend wrote a code to display all anagrams for "abcdef" in python. But in this code, I couldn't understand how the recursive procedure works anagrams = get_list_of_anagrams(''.join(tmp_list)) How does the function call itself?
def get_list_of_anagrams(s):
if len(s)==0:
return ['']
all_chars = list(s)
unique_chars = list(set(s))
anagrams_list = []
for char in unique_chars:
tmp_list = list(all_chars)
tmp_list.remove(char)
anagrams = get_list_of_anagrams(''.join(tmp_list))
for i in range(len(anagrams)):
anagrams[i] = char+anagrams[i]
anagrams_list += anagrams
return anagrams_list
When I try to print every thing till anagrams = get_list_of_anagrams(''.join(tmp_list)
def get_list_of_anagrams(s):
if len(s)==0:
return ['']
all_chars = list(s)
unique_chars = list(set(s))
anagrams_list = []
for char in unique_chars:
tmp_list = list(all_chars)
tmp_list.remove(char)
anagrams = get_list_of_anagrams(''.join(tmp_list))
print get_list_of_anagrams('abc')
I get the following out put.
For the following code:
def get_list_of_anagrams(s):
if len(s)==0:
return ['']
all_chars = list(s)
unique_chars = list(set(s))
anagrams_list = []
for char in unique_chars:
tmp_list = list(all_chars)
tmp_list.remove(char)
anagrams = get_list_of_anagrams(''.join(tmp_list))
print anagrams
for i in range(len(anagrams)):
anagrams[i] = char+anagrams[i]
anagrams_list += anagrams
return anagrams_list
print get_list_of_anagrams('abc')
I get the following output:
can some one explain me why the above output is of this pattern?