Skip to content

Instantly share code, notes, and snippets.

@patterns
Created October 24, 2016 20:45
Show Gist options
  • Save patterns/d705f9ded4f2ef68e10016badc4f4f9e to your computer and use it in GitHub Desktop.
Save patterns/d705f9ded4f2ef68e10016badc4f4f9e to your computer and use it in GitHub Desktop.
My very first Python script ever!
README for test.py
This script requires Python 2.7.10
It is launched by invoking the command line from a terminal shell:
python lru.py
======
ISSUES
The expected ERROR result for the second to last operation is incorrect. This is just after GOT third and before GOT four in the expected output.
There is no validation on the SIZE value input.
ASSUMPTIONS
The GET/SET/EXIT commands are not case-sensitive.
The keys must be unique.
The delimiter between the format [command] [key] [val] is whitespace.
LIMITATIONS
=====
All inputs and outputs exist on their own line:
The first input line should set the max number of items for the cache using the keyword SIZE. The program should respond with ‘SIZE OK’. This must only occur as the first operation.
Set items with a line giving the key and value, separated by a space,
your program should respond with 'SET OK'.
Get items with a line giving the key requested, your program should respond with the previously stored value, for example “GOT foo”. If the the key is not in the cache, it should reply with “NOTFOUND”.
‘EXIT’ should cause your program to exit.
If the input is invalid, your program should respond with ‘ERROR’
Sample Input
SIZE 3
GET foo
SET foo 1
GET foo
SET foo 1.1
GET foo
SET spam 2
GET spam
SET ham third
SET parrot four
GET foo
GET spam
GET ham
GET ham parrot
GET parrot
EXIT
Expected Output
SIZE OK
NOTFOUND
SET OK
GOT 1
SET OK
GOT 1.1
SET OK
GOT 2
SET OK
SET OK
NOTFOUND
GOT 2
GOT third
ERROR
GOT four
#lru.py
#loop input until 'EXIT'
read_line = ""
data = []
while read_line.lower() != "exit":
read_line = raw_input()
if read_line.lower() != "exit":
data.append(read_line)
#expect 'SIZE n' once
size_val = 0
size_line = data[0]
del data[0]
size_kv = size_line.split()
if size_kv[0].lower() == "size":
try:
size_val = int(size_kv[1])
print "SIZE OK"
except ValueError:
exit("ERROR")
else:
exit("ERROR")
#track fifo keys
keys = []
m = {}
input_line = ""
for input_line in data:
input_kv = input_line.split()
op = input_kv[0].lower()
if op == "set":
#add item
if input_kv[1] not in keys:
if len(keys) >= size_val:
#bookmark oldest key
stale = keys[0]
#release oldest val
if m.has_key(stale):
del m[stale]
#release oldest key
del keys[0]
#keep new key
keys.append(input_kv[1])
#keep new val
m[input_kv[1]] = input_kv[2]
print "SET OK"
elif op == "get":
#retreive item
if m.has_key(input_kv[1]):
print "GOT %s" % (m[input_kv[1]])
else:
print "NOTFOUND"
elif input_line == "exit":
break
else :
print "ERROR"
####print "finished"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment