Skip to content

Instantly share code, notes, and snippets.

View imedadel's full-sized avatar
🏗️
Building something

Imed Adel imedadel

🏗️
Building something
View GitHub Profile
def minimumAbsoluteDifference(arr):
uniq = sorted(list(set(arr)))
minVal = uniq[-1]
for i in range(len(uniq)-1):
newMin = min([abs(x-uniq[i]) for x in uniq[i+1:]])
if minVal > newMin:
minVal = newMin
return minVal
frstWord = list(input().strip())
scndWord = list(input().strip())
def longestChild(frst, scnd):
grid = [[0 for _ in range(len(scnd)+1)] for _ in range(len(frst)+1)]
result = 0
for i in range(len(frst)+1):
for j in range(len(scnd)+1):
if i == 0 or j == 0:
from collections import Counter
word = input().strip()
def sherlock(word):
freq = Counter(word)
freqFreq = Counter(freq.values())
hasVarFreq = len(freqFreq.values()) > 2 or min(freqFreq.values()) != 1
if hasVarFreq:
return "NO"
from collections import Counter
q = int(input().strip())
def anagrams(word):
count = 0
freq = Counter()
for i in range(len(word)):
for j in range(i+1, len(word)+1):
letters = list(word[i:j])
from collections import Counter
def makeAnagram(a, b):
freqA = Counter(a)
freqB = Counter(b)
intersection = freqA & freqB
return sum(freqA.values()) + sum(freqB.values()) - sum(intersection.values()) * 2
from collections import Counter
def freqQuery(queries):
items = Counter()
checks = Counter()
res = []
for couple in queries:
query, item = couple
if query == 1:
checks[items[item]] -= 1
items[item] += 1
from collections import Counter
# Imagine this as three boxes or stages, each number "graduates" from the first stage to the second one, then, to the final stage.
# Instead of having a final stage object, having an integer that's incremented each time a number reaches the final stage, is more performant
def countTriplets(arr, r):
finalStage = 0
firstStage = Counter()
secondStage = Counter()
for i in reversed(arr):
@imedadel
imedadel / finding-the-first-occurrence.md
Created November 3, 2019 09:10
Finding the first occurrence of an item in a filtered Python list

Finding the first occurrence

If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use

next(x for x in lst if ...)

which will return the first match or raise a StopIteration if none is found. Alternatively, you can use

from collections import deque
def search(name, graph):
search_queue = deque()
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft()
if not person in searched:
if person_is_seller(person): # or any other function
def quicksort(arr):
if len(arr) < 2:
return arr
pivot = arr[0]
less = [i for i in arr[1:] if i <= pivot]
greater = [i for i in arr[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)