I have this code here, it is supposed to remove the common letters from both the lists n1 and n2. But when i run this code it only runs once as in it removes only ‘a’ from both n1 and n2 and doesnt remove ‘k’.
Just to clarify this code should always work on only 2 words.
name1 = "abdjek"
name2 = "doarhsnk"
n1l = list(name1)
n2l = list(name2)
for i in range(len(n1l)):
for j in range(len(n2l)):
if n1l[i] == n2l[j]:
n1l.pop(i)
n2l.pop(j)
n1l.append('0')
n2l.append('1')
Ok wait, it seems to work for the above 2 names but when i have name1 = “naveen” and name2 = “darshana” it doesnt work!
A more pythonic approach would be to use
sets and list comprehensions.setgives us O(1) lookups, thus making the whole process faster by making it O(N) instead of O(N^2).EDIT: In light of your later comment that the number of occurrences matter, this is the updated version that takes that into account.
It uses
dicts to keep counts of occurrences. Whenever a character is removed, the corresponding count for the other name is decremented. Complexity is still O(N).It prints
['v', 'e', 'e', 'n', '0', '0']and['d', 'r', 's', 'h', 'a', 'a', '1', '1']. Is that what you wanted?