Start working on the "Hard" problems
Firstly, implement a function that adds two arguments together... without using the `+` operator. I need to drill this problem. Thankfully I took a Coursera course that taught me how to make a half-adder and a full-adder, but the recommended solution for this is a bit more difficult.
This commit is contained in:
parent
30f4d6f4a4
commit
92ab94943e
1 changed files with 22 additions and 0 deletions
22
scratch/facebook/hard/binary-adder.py
Normal file
22
scratch/facebook/hard/binary-adder.py
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
import random
|
||||||
|
|
||||||
|
def add(a, b):
|
||||||
|
"""
|
||||||
|
Return the sum of `a` and `b`.
|
||||||
|
"""
|
||||||
|
if b == 0:
|
||||||
|
return a
|
||||||
|
sum = a ^ b
|
||||||
|
carry = (a & b) << 1
|
||||||
|
return add(sum, carry)
|
||||||
|
|
||||||
|
################################################################################
|
||||||
|
# Tests
|
||||||
|
################################################################################
|
||||||
|
|
||||||
|
for _ in range(10):
|
||||||
|
x, y = random.randint(0, 100), random.randint(0, 100)
|
||||||
|
print("{} + {} = {} == {}".format(x, y, x + y, add(x, y)))
|
||||||
|
assert add(x, y) == x + y
|
||||||
|
print("Pass!")
|
||||||
|
print("Success!")
|
Loading…
Reference in a new issue