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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With