Skip to content

Instantly share code, notes, and snippets.

@rajatscode
Created October 29, 2020 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajatscode/c0422052aa803545449c59afa4b4439d to your computer and use it in GitHub Desktop.
Save rajatscode/c0422052aa803545449c59afa4b4439d to your computer and use it in GitHub Desktop.
Python 2 code for Leetcode 765
def convert_to_couples(row):
return [n // 2 for n in row]
def trim_couples(couples):
return [
couples[i] for i in xrange(len(couples))
if couples[i//2*2] != couples[i//2*2+1]
]
def reindex_by_appearance(sequence):
seen = dict()
result = list()
index = 0
for val in sequence:
if val in seen:
result.append(seen.get(val))
else:
result.append(index)
seen[val] = index
index += 1
return result
def get_diff_count(seq_a, seq_b):
return sum(1 for i in xrange(len(seq_a)) if seq_a[i] != seq_b[i])
def min_swaps(seq):
couples = convert_to_couples(seq)
trimmed_couples = trim_couples(couples)
reindexed_couples = reindex_by_appearance(trimmed_couples)
sorted_couples = sorted(reindexed_couples)
return int(round(get_diff_count(reindexed_couples, sorted_couples) / 2.0))
def decouple(couples):
seen = set()
result = list()
for member in couples:
if member in seen:
result.append(2*member+1)
else:
result.append(2*member)
seen.add(member)
return result
@rajatscode
Copy link
Author

rajatscode commented Oct 29, 2020

Not sure what Leetcode problem #765 is, what this does, what the main method is (I think min_swaps, not sure what decouple does), or whether the solution above works.

I just know I worked on this a while ago (in a conversation with a friend), have this file on my computer (clarification: this is my own solution, and my own code, I just don't remember any of the context), and want to free up the space so I'm just putting it it a gist.

Enjoy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment