Skip to content

Instantly share code, notes, and snippets.

@bwestergard
Created January 11, 2012 15:18
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 bwestergard/1595141 to your computer and use it in GitHub Desktop.
Save bwestergard/1595141 to your computer and use it in GitHub Desktop.
A python script to let you read a book (e.g. a dictionary, an encyclopedia) in random order, keeping track of which pages have already been read.
import sys,random
'''
USAGE
Let's say you want to read The Oxford Companion to Lulz, which has 819 pages. You would create a file with one line, "1:819", and save it as lulz.txt. Then you would run:
python bookmark.py lulz.txt
This would return a random page that you haven't yet read. Let's say it was 42. You then read from 42 to 50. You record this fact by running:
python bookmark.py lulz.txt 42 50
Which would alter lulz.txt to read:
1:41
51:819
That is to say, a listing of all the ranges of pages you haven't yet read.
Running the first command again would give you a random page in one of these ranges. Repeat until finished or bored.
'''
class R(object):
def __init__(self, low, high=None):
self.low = low
if (high):
self.high = high
else:
self.high = low
def __sub__(b,a): # (B "minus" A)
if (a == None):
return b
if (b == None):
return None
if ((b.high < a.low) or (a.high < b.low)):
return b
if (b.low == a.low):
if (b.high <= a.high):
return None
else:
return R(a.high+1,b.high)
if (b.low < a.low):
if (b.high <= a.high):
return R(b.low,a.low-1)
else:
return [R(b.low,a.low-1),R(a.high+1,b.high)]
if (b.low > a.low):
if (b.high <= a.high):
return None
else:
return R(a.high+1,b.high)
def __str__(self):
return str(self.low) + ":" + str(self.high)
### MAIN ###
filename = sys.argv[1]
unread = []
f = open(filename, 'r')
lines = f.readlines()
for line in lines:
bounds = line.split(":")
unread.append(R(
int(bounds[0]),
int(bounds[1])
))
f.close()
if len(sys.argv) > 2: # I've read something, now I want to cross those pages off my list.
low = int(sys.argv[2])
if len(sys.argv) > 2:
high = int(sys.argv[3])
else:
high = low
justread = R(low,high)
remaining = map(lambda x: x - justread, unread)
flattened = []
for item in remaining:
if isinstance(item, list):
for r in item:
flattened.append(r)
elif (item != None):
flattened.append(item)
f = open(filename,"w")
for x in flattened:
print x
f.write(str(x) + "\n")
else: # Pick a page for me
page_total = 0
for r in unread:
page_total += (r.high - r.low) + 1
page = random.randrange(0,page_total+1)
for r in unread:
if ((page + r.low) <= r.high):
print r.low + page
print str(page_total) + " pages left in " + str(len(lines)) + " parts"
break
else:
page -= (r.high - r.low) + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment