huskerfly
huskerfly

Reputation: 83

Codefights areSimilar challenge in python3

I have a problem with the "areSimilar" problem on CodeFights using python3.

The prompt states "Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.

Given two arrays a and b, check whether they are similar."

For example, [1,1,2] and [1,2,1] would pass the test because you could swap two elements within either list to emulate the other.

However, [3,4,5] and [4,5,3] does not pass the test because you could not swap two elements in either list to make it look like the other.

The lengths of the two lists will always be the same and have a length greater than 2.

My current code passes all tests except for one hidden test, and I was wondering if someone could guide me through a process to help me get past this question.

Thanks!

Upvotes: 8

Views: 5593

Answers (10)

Aravind R
Aravind R

Reputation: 1283

Got the answer but timed out :(

def solution(a, b): 
     def permutation(lst):
         if len(lst) == 0:
             return []
         if len(lst) == 1:
             return [lst]
         l = []
         for i in range(len(lst)):
             m = lst[i]
             remLst = lst[:i] + lst[i+1:]
             for p in permutation(remLst):
                 l.append([m] + p)
         return l
        
     values = []
     for b in permutation(b):
         if b == a: 
             values.append(True)
        
     if True in values: 
         return True 
     else: 
         return False

Upvotes: 0

GUNJAN HALDAR
GUNJAN HALDAR

Reputation: 1

Simple Python 3:

def areSimilar(a, b):
    import numpy as np
    if a == b:
        return True
    diff = np.array(a) - np.array(b)
    return [False, True][list(diff).count(0) == len(diff) - 2 and sum(list(diff)) == 0 and set(a) == set(b)]

Upvotes: 0

Kishor
Kishor

Reputation: 4096

C# Solution

bool areSimilar(int[] a, int[] b) 
{
    int n = a.Length;
    int differences = 0;
    
    for(int i=0; i<n; i++)
    {
        if(a[i] != b[i]) differences++;
    }
    
    if(differences == 0) return true;
    
    Array.Sort(a);
    Array.Sort(b);
    
    bool same = a.SequenceEqual(b);
    
    return (differences <= 2) && same;
    
}

Upvotes: 0

Jayanth Kumar T
Jayanth Kumar T

Reputation: 317

One liner python solution

from collections import Counter as C

def areSimilar(A, B):
    return C(A) == C(B) and sum(a != b for a, b in zip(A, B)) < 3

Upvotes: 0

Vineet Jain
Vineet Jain

Reputation: 1575

Below is my code which is self-explanatory and Passed All test cases.

1 st Approach

def areSimilar(a, b):
    if set(a) != set(b):
        return False

    if sorted(a) != sorted(b):
        return False

    diffs = [ix for ix,val in enumerate(list(zip(a,b))) if val[0] != val[1]]

    if len(diffs) not in(0,2):
        return False

    return True

2nd Approach

def areSimilar(A, B):
    return sorted(A)==sorted(B) and sum([a!=b for a,b in zip(A,B)])<=2

Upvotes: 1

Ashwin Pandey
Ashwin Pandey

Reputation: 125

def areSimilar(a, b):
i = 0
i_val = []
while i < len(a):
    if a[i] != b[i]:
        i_val.append(i)
    i += 1
if not i_val:
    return True
if len(i_val) != 2:
    return False
return a[i_val[0]] == b[i_val[1]] and a[i_val[1]] == b[i_val[0]]

Passed all the tests...

Upvotes: 4

Gaurav Sitaula
Gaurav Sitaula

Reputation: 216

You can try this code. I passed all the cases.

def areSimilar(a, b):
    count = 0
    list_a = []
    list_b = []
    for i in range(len(a)):
        if (a[i]!= b[i]):
            count +=1
            list_a.append(a[i])
            list_b.append(b[i])

    if (count ==0):
        return True 

    elif count ==2: 
        return set(list_a)==set(list_b)

    else:
        return False

Upvotes: 2

seansio1995
seansio1995

Reputation: 1

def areSimilar(a, b):
tmp1=list()
tmp2=list()
for i in range(len(a)):
    if a[i]!=b[i]:
        tmp1.append(a[i])
        tmp2.append(b[i])
if len(tmp1)==0:
    return True
elif len(tmp1)>2:
    return False
else:
    return tmp1==list(reversed(tmp2))

My code passed all the tests

Upvotes: 0

Daniel Restrepo
Daniel Restrepo

Reputation: 73

This is my code, but I don't know that more I can do for get a little more of velocity..

def areSimilar(a, b):

    swap = False
    for i, x, y in zip(range(len(a)), a, b):  
        if x == y:
            pass

        elif (x != y) and (swap == False):

            try:
                k = b.index(x)
            except:
                return False

            b[k] = y
            swap = True

        else:
            return False

    return True

Upvotes: 0

Mohamed Abu ElGheit
Mohamed Abu ElGheit

Reputation: 59

My old code also failed to pass the last hidden test and I realized the the swap function had a problem my old swap function was:

def swp(i,a,b):
    s = 0
    item = a[i]
    if item in b:
        indx = b.index(item)
        s = b[i]
        b[i] = b[indx]
        b[indx] = s
        return -1
    else:
        return -2

think that if:

a = [2,9,6,8,9,5]
b = [2,5,6,8,9,9]

if I swap 5 with the first 9 it won't be correct...

and this is my new code after changing the swap function

def swp(i,a,b):
        s = 0
        item = a[i]
        if item in b:
            for j in range(len(b)):
                if b[j] == a[i] and b[j] != a[j]:
                    indx = j
                    s = b[i]
                    b[i] = b[indx]
                    b[indx] = s
                    return -1
        else:
            return -2


    def check(a,b):
        for i in range(len(a)):
            if a[i] != b[i]:
                return i
        return -1

    def areSimilar(a, b):
        if check(a,b) != -1:
            i = check(a,b)
            if swp(i,a,b) == -1:
                swp(i,a,b)
                if check(a,b) != -1:
                    return False
            else:
                return False
        return True

Upvotes: 4

Related Questions