Skip to content

Commit e6012cb

Browse files
author
Philip Guo
committed
bah
1 parent fd6faef commit e6012cb

2 files changed

Lines changed: 42 additions & 3 deletions

File tree

cgi-bin/parse_questions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ def processRecord():
5252
# only strip TRAILING spaces and not leading spaces
5353
line = line.rstrip()
5454

55+
# comments are denoted by a leading '//', so ignore those lines.
56+
# Note that I don't use '#' as the comment token since sometimes I
57+
# want to include Python comments in the skeleton code.
58+
if line.startswith('//'):
59+
continue
60+
5561
# special-case one-liners:
5662
if line.startswith('MaxLineDelta:'):
5763
ret['max_line_delta'] = int(line.split(':')[1])

questions/optimize-search.txt

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@ Question:
55

66
The following search function finds the index of the first occurrence of
77
elt in a sorted list lst (or -1 if elt not found). Optimize this
8-
function so that it works on a 64-element sorted list by executing less
9-
than 50 instructions.
8+
function so that it works on any 64-element sorted list by executing
9+
less than 50 instructions.
1010

1111
Hint:
1212
Linear search will never work.
1313

1414
Solution:
15-
Implement binary search instead of linear search.
15+
Implement binary search instead of linear search. A recursive solution
16+
might not be efficient enough, though!
1617

1718
MaxInstructions: 50
1819

@@ -26,6 +27,38 @@ def search(lst, elt):
2627
return -1
2728

2829

30+
// # Iterative solution from stackoverflow
31+
// # http://stackoverflow.com/questions/212358/binary-search-in-python
32+
// def search(lst, elt):
33+
// lo, hi = 0, len(lst)
34+
// while lo < hi:
35+
// mid = (lo+hi)//2
36+
// midval = lst[mid]
37+
// if midval < elt:
38+
// lo = mid+1
39+
// elif midval > elt:
40+
// hi = mid
41+
// else:
42+
// return mid
43+
// return -1
44+
//
45+
// # recursive implementation, which is too slow
46+
// def search(lst, elt):
47+
// return bsearch(lst, elt, 0, len(lst))
48+
//
49+
// def bsearch(lst, elt, lo, hi):
50+
// if lo > hi:
51+
// return -1
52+
// mid = (lo+hi)//2
53+
// midval = lst[mid]
54+
// if midval < elt:
55+
// return bsearch(lst, elt, mid+1, hi)
56+
// elif midval > elt:
57+
// return bsearch(lst, elt, lo, mid)
58+
// else:
59+
// return mid
60+
61+
2962
Test:
3063
haystack = range(64)
3164
needle = 63

0 commit comments

Comments
 (0)