Compare commits

..

3 Commits

Author SHA1 Message Date
58683f4cce Completed product question 2026-05-28 21:15:08 -07:00
5e655f67f3 Add System Design Interview book. 2026-05-27 21:23:58 -07:00
123f880c86 Added #dcp 567 - implementing cons/car/cdr. 2026-05-27 21:23:44 -07:00
3 changed files with 74 additions and 0 deletions

31
problems/cons_car_cdr.py Normal file
View File

@@ -0,0 +1,31 @@
"""
cons(a, b) constructs a pair, and car(pair) and cdr(pair) return the first
and last element of that pair.
car(cons(3, 4)) == 3
cdr(cons(3, 4)) == 4
Given this implementation of cons, implement car and cdr.
"""
def cons(a, b):
return lambda f: f(a, b)
def car(pair):
return pair(lambda a, b: a)
def cdr(pair):
return pair(lambda a, b: b)
# --- tests ---
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4
assert car(cons("a", "b")) == "a"
assert cdr(cons("a", "b")) == "b"
print("All tests passed!")

43
problems/product.py Normal file
View File

@@ -0,0 +1,43 @@
"""
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if the input is [1, 2, 3, 4, 5], the expected output is [120, 60, 40, 30, 24].
Follow-up: What if you can't use division?
"""
def product(arr: list[int]) -> list[int]:
# first we calculate prefix/suffix. We add a spot with multiplicative identity (1) for convenience.
prefix = [1]*len(arr)
suffix = [1]*len(arr)
p = 1
for i in range(0, len(arr)-1):
p *= arr[i]
prefix[i+1] = p
p = 1
for i in range(len(arr)-1, 0, -1):
p *= arr[i]
suffix[i-1] = p
ans = [1]*len(arr)
for i in range(len(ans)):
ans[i] = prefix[i] * suffix[i]
return ans
# --- tests ---
assert product([2, 3, 4, 5]) == [60, 40, 30, 24]
assert product([1, 2, 3, 4, 5]) == [120, 60, 40, 30, 24]
assert product([1, 2]) == [2, 1]
# zero cases
assert product([0, 1, 2, 3]) == [6, 0, 0, 0]
assert product([0, 0, 2, 3]) == [0, 0, 0, 0]
# single element
assert product([5]) == [1]
print("All tests passed!")

Binary file not shown.