ANAGRAMS!

In [1]:
def isAna(w1,w2):
    if (sorted(w1) == sorted(w2)):
        return True
    else:
        return False

def stringAnagram(dictionary, query):
    total = []
    for q in query:
        count = 0
        for d in dictionary:
            result = isAna(q,d)
            if result == True:
                count += 1
            else:
                pass
        total.append(count)
    return total
In [6]:
dic = ['listen', 'tow', 'silent', 'lisent', 'two', 'abc', 'no', 'on']
que = ['two', 'bca', 'no', 'listen']
In [7]:
stringAnagram(dic,que)
Out[7]:
[2, 1, 2, 3]
In [8]:
def testing(q,d):
    print(q,d)
In [25]:
count = 0
In [31]:
 
In [22]:
arr = [sorted(q) == sorted(d) for q in que for d in dic]
In [23]:
for a in len(q):
    arr.split( )
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-4f4c6efbf8e9> in <module>
----> 1 arr/len(q)

TypeError: unsupported operand type(s) for /: 'list' and 'int'
In [33]:
from collections import Counter

arr = [(q) for q in que for d in dic if ((sorted(q) == sorted(d)) == True)]
c_a = list(Counter(arr).values())
c_a
Out[33]:
[2, 1, 2, 3]
In [54]:
dq = dict(Counter(que))
In [55]:
type(dq)
Out[55]:
dict
In [66]:
[{q: += 1} for q in que for d in dic if ((sorted(q) == sorted(d)) == True)]
  File "<ipython-input-66-02bb1e2b54e1>", line 1
    [{q: +=1} for q in que for d in dic if ((sorted(q) == sorted(d)) == True)]
          ^
SyntaxError: invalid syntax
In [63]:
dq
Out[63]:
{'two': 1, 'bca': 1, 'no': 1, 'listen': 1}
In [67]:
for q in que:
    for d in dic:
        if sorted(q) == sorted(d):
            dq[q] += 1
        else:
            pass
In [68]:
dq
Out[68]:
{'two': 3, 'bca': 2, 'no': 3, 'listen': 4}
In [69]:
dq = dict(zip(que, [0]*len(que)))
In [70]:
dq
Out[70]:
{'two': 0, 'bca': 0, 'no': 0, 'listen': 0}
In [71]:
def stringAnagram(dictionary, query):
    dq = dict(zip(query, [0]*len(query)))
    for q in query:
        for d in dictionary:
            if len(q) == len(d):
                if sorted(q) == sorted(d):
                    dq[q] +=1
                # else:
                #     pass
                # print(q,d)
            # 
            #     pass
            # elif sorted(q) == sorted(d):
            #     dq[q] += 1
            # else:
            #     pass
    return list(dq.values())
In [ ]: