First issue in your program, is that you are initializing t
to 0
outside the for loop , hence you you only check the first element of b
with all the elements, for the rest of the iterations of the for
loop , t would always be greater than len(b) , hence it never goes inside the inner loop, from second iteration of for
loop. A simple fix -
for i in b:
t = 0
while t<len(b):
if ''.join(sorted(i))==''.join(sorted(b[t])):
array.append(i)
t+=1
But for finding anagrams, i think you are over-complicating it, you can simple find out sum of ASCII values of the characters of the string, and then compare it with other same sums and lengths , and check if both sum of ASCII value and length of string match, if they do they are anagram.
Example code for this method -
b = ['cat', 'dog', 'god', 'star', 'lap', 'act']
c = list(map(len,b))
d = list(map(lambda x: sum([ord(c) for c in x]), b))
arr= []
for i, s in enumerate(b):
for j, s1 in enumerate(b):
if d[i] == d[j] and c[i] == c[j] and i != j:
if s not in arr:
arr.append(s)
if s1 not in arr:
arr.append(s1)
print(arr)
>> ['cat', 'act', 'dog', 'god']