Skip to content

Instantly share code, notes, and snippets.

@pkulev
Created November 15, 2016 16:50
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 pkulev/d6a7e027c06ed701d3d9ce507a29dfc1 to your computer and use it in GitHub Desktop.
Save pkulev/d6a7e027c06ed701d3d9ce507a29dfc1 to your computer and use it in GitHub Desktop.
""" """
# Tuple functions
def append(tup, elem): return tup + (elem,)
def ainit(length, func):
return reduce(append, map(func, range(length)), ())
def amake(length, elem):
return ainit(length, lambda _: elem)
# DB related functions
def nobody(): return {"name": "", "phone_number": (0, 0, 0, 0)}
def make(max_num):
return dict(
number_of_contacts=0,
contacts=amake(max_num, nobody()))
def search(db, contact):
def aux(idx):
if idx >= db["number_of_contacts"]:
return (False, db, contact)
elif db["contacts"][idx]["name"] == contact["name"]:
return (True, db, contact)
else:
return aux(idx + 1)
return aux(0)
def insert(db, contact):
if db["number_of_contacts"] >= len(db["contacts"]):
return (False, db, nobody())
else:
(status, db, _) = search(db, contact)
if status:
return (False, db, contact)
else:
def cells(i):
if i == db["number_of_contacts"]:
return contact
else:
db["contacts"][i]
db_ = dict(
number_of_contacts=db["number_of_contacts"] + 1,
contacts=ainit(len(db["contacts"]), cells))
return (True, db_, contact)
def delete(db, contact):
(status, db, contact) = search(db, contact)
if not status:
return (False, db, contact)
else:
def cells(i):
if db["contacts"][i]["name"] == contact["name"]:
return nobody()
else:
return db["contacts"][i]
db_ = dict(
number_of_contacts=db["number_of_contacts"] - 1,
contacts=ainit(len(db["contacts"]), cells))
return (True, db_, contact)
def engine(db, query):
code, contact = query
if code == 0:
return insert(db, contact)
elif code == 1:
return delete(db, contact)
elif code == 2:
return search(db, contact)
else:
return (False, db, nobody())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment