Cracking The Code Interview CH1.2


In [34]:
# Input
s1 = 'asttf'
s2 = 'ftast'

In [30]:
def is_permutation(string1, string2):
    sort1 = sorted(list(s1))
    sort2 = sorted(list(s2))
    if sort1 == sort2:
        return True
    else:
        return False

In [31]:
is_permutation(s1,s2)


Out[31]:
True

In [39]:
def is_permutation1(s1, s2): 
    d = {}
    for i in s1:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1

    for j in s2:
        if j not in d:
            return False
        d[j] -= 1
        if d[j] == 0:
            del d[j]
    return len(d) == 0

In [40]:
is_permutation1(s1, s2)


Out[40]:
True