As the title says i need help reducing the execution time of the code I've written as the online judge I'm compiling it on gives me a time limit exceeded error even though the code seems to work and gives the correct answer when I compile it.
The question:
Compare a list of string and find the number of distinct strings, where two strings are considered to be "identical" (not distinct) if they're exactly the same, or the same but reversed. The strings only contain the letters a-z, are all lowercase, and have at most 10 characters. Each set provided will have at most 5000 strings in it.
For example, the string "abc" is identical to "cba" as well as "abc." The string "cba" is identical to "abc" as well as "cba." The list ["abc," "cba," "bac"] has 2 distinct strings in it.
Write a function answer(x) which takes a list of strings, x, and returns the number of distinct strings using this definition of identical.
My code:
def answer(x):
b=0
ph=[]
rand=0
for y in x:
comp=list(y)
ph.append(comp)
while b<len(ph)-1:
j=b+1
while j<len(ph):
if(len(ph[b])==len(ph[j])):
i=0
while(i<len(ph[b])):
if ph[b][i]==ph[j][i]:
rand+=1
elif ph[b][i]==ph[j][len(ph[b])-1-i]:
rand+=1
i+=1
if rand==len(ph[b]):
ph.pop(j)
rand=0
j+=1
b+=1
return len(ph)