Python Sheet
Python Sheet
Pairs = {}
Frog earliest jump
For ele in arr:
#try using enumerate to limit for loops
If ele in, increase
Jumps = set()
Else set ele to 1
To_jump = set(range(1, X + 1))
Keys = list(pairs.keys())
For I, leaf in enumerate(A):
Vals = list(pairs.values())
Jumps.add(leaf)
Single = vals.index(1)
If jumps == to_jump:
Ind = [x for x in vals if x % 2 != 0]
Return i
Odd = vals.index(ind[0])
Return -1
Return keys[odd]
for i in A:
S = set(A) zeros += 1
Count = 1 else:
While count in S: passing += zeros
count += 1
return passing
Return count
range divisible by K
Absolute difference between sum of parts
#reduce sum as much as possible via adding as you div = [I for I in range(A, B+1) if i%K == 0]
go
return len(div)
#write out all steps to see how to simplify
Fish += 1
Ind += 1
Return fish
Dominator
from collections import Counter
return -1
left = 0
right = len(A)
max sum of sub array
large_sum = sum(A)
def solution(A):
if len(A) <= 2 and K <= 2:
# Implement your solution here
return max(A)
pass
max_sum += A[i]
elif sum(A[left:right - 1]) < large_sum:
right -= 1
return max_sum
large_sum = sum(A[left:right])
#print(A[left:right])
return large_sum
Data Structures
Here is the general strategy behind binary search, which is applicable to a variety of problems:
1. Come up with a condition to determine whether the answer lies before, after or at a given
position
2. Retrieve the midpoint and the middle element of the list.
3. If it is the answer, return the middle position as the answer.
4. If answer lies before it, repeat the search with the first half of the list
5. If the answer lies after it, repeat the search with the second half of the list.
Note that binary_search accepts a function condition as an argument. Python allows passing
functions as arguments to other functions, unlike C++ and Java.
We can now rewrite the locate_card function more succinctly using the binary_search function.
def locate_card(cards, query):
def condition(mid):
if cards[mid] == query:
if mid > 0 and cards[mid-1] == query:
return 'left'
else:
return 'found'
elif cards[mid] < query:
return 'left'
else:
return 'right'
def solution(A):
pass
west_count = sum(A)
for i in range(len(A)):
if A[i] == 0:
west_count += 1
return -1
return west_count