Skip to content

Commit 88c4c61

Browse files
committed
Find integer in sorted list.
1 parent 7d263df commit 88c4c61

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

README renamed to README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ String matching
2121
- Knuth-Morris-Pratt
2222
- Boyer-Moore-Horspool
2323

24+
Generators
25+
- Permutations.
26+
27+
Lists
28+
- Subset with highest sum.
29+
- Find integer in sorted list.
30+
2431
### Installation
2532
Get the source and run
2633

algorithms/list.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,28 @@
1+
def find_int(i, l):
2+
"""
3+
Find integer in a sorted list.
4+
5+
Example: 4 in [1, 3, 4, 6, 7, 9] -> 2
6+
@param i integer to find.
7+
@param l sorted list.
8+
@returns index if found, None if not.
9+
"""
10+
if l:
11+
p_idx = len(l) / 2
12+
p = l[p_idx]
13+
if i == p:
14+
return p_idx
15+
elif len(l) == 1:
16+
return
17+
elif i < p:
18+
res = find_int(i, l[:p_idx])
19+
if res:
20+
return res
21+
elif i > p:
22+
res = find_int(i, l[p_idx:])
23+
if res:
24+
return res + p_idx
25+
126
def find_max_sub(l):
227
"""
328
Find subset with higest sum

algorithms/tests/test_list.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,30 @@ class List(unittest.TestCase):
66
def setUp(self):
77
pass
88

9-
def test_list(self):
9+
def test_find_max_sub(self):
1010
bounds, m = [e for e in list.find_max_sub([-2, 3, -4, 5, 1, -5])]
1111
self.assertEqual(bounds, (3, 4))
1212
self.assertEqual(m, 6)
1313

14+
def test_find_int_first_half(self):
15+
idx = list.find_int(4, [1, 2, 4, 5, 7, 9])
16+
self.assertEqual(idx, 2)
17+
18+
def test_find_int_second_half(self):
19+
idx = list.find_int(7, [1, 2, 4, 5, 7, 9])
20+
self.assertEqual(idx, 4)
21+
22+
def test_find_int_not_found(self):
23+
idx = list.find_int(3, [1, 2, 4, 5, 7, 9])
24+
self.assertIsNone(idx)
25+
26+
def test_find_int_single_element_list(self):
27+
idx = list.find_int(3, [3,])
28+
self.assertEqual(idx, 0)
29+
30+
def test_find_int_empty_list(self):
31+
idx = list.find_int(3, [])
32+
self.assertIsNone(idx)
1433

1534
if __name__ == '__main__':
1635
unittest.main()

0 commit comments

Comments
 (0)