Permalink
Browse files

Cleanup, pythonic code

Strip trailing space on line ends, pep8 cleanup

Improve bubblesort
- Inline swap
- hoist constant out of loop
- avoid unused variable 'x'

Conflicts:
	algorithms/shuffling/knuth.py
	algorithms/sorting/bogo_sort.py
  • Loading branch information...
1 parent fc4820d commit fa705db0f510054ff7b50cff4910bb0254259c3b Hugh Brown committed Sep 30, 2012
View
11 algorithms/searching/bmh_search.py
@@ -25,16 +25,13 @@
def search(text, pattern):
- m = len(pattern)
- n = len(text)
+ m, n = len(pattern), len(text)
offsets = []
if m > n:
return offsets
- bmbc = []
- for k in range(256):
- bmbc.append(m)
- for k in range(m - 1):
- bmbc[ord(pattern[k])] = m - k - 1
+ bmbc = [m] * 256
+ for k, p in enumerate(pattern[:-1]):
+ bmbc[ord(p)] = m - k - 1
bmbc = tuple(bmbc)
k = m - 1
while k < n:
View
14 algorithms/shuffling/knuth.py
@@ -1,22 +1,22 @@
"""
knuth.py
Implementation of the Fisher-Yates/Knuth shuffle
-
+
Pre: Takes any list, unshuffled
Post: Returns list shuffled randomly
-
+
Time Complexity: n
Space Complexity: n
-
+
Pseudocode: http://en.wikipedia.org/wiki/Fisher%E1%80%93Yates_shuffle
"""
-import random
+from random import seed, randint
def shuffle(li):
- random.seed()
- for i in xrange(len(li) - 1, 0, -1):
- j = random.randint(0, i)
+ seed()
+ for i in reversed(range(len(li))):
+ j = randint(0, i)
li[i], li[j] = li[j], li[i]
return li
View
9 algorithms/sorting/bogo_sort.py
@@ -1,9 +1,9 @@
"""
bogo_sort.py
-
+
This module implements bogo sort on an unsorted list and
returns the list in sorted order.
-
+
Bogo Sort Overview:
-------------------
If list is not in order, picks two elements at random and swaps them.
@@ -41,7 +41,4 @@ def sort(seq):
def is_sorted(seq):
- for i in xrange(1, len(seq)):
- if seq[i - 1] > seq[i]:
- return False
- return True
+ return all(seq[i - 1] <= seq[i] for i in xrange(1, len(seq)))
View
9 algorithms/sorting/bubble_sort.py
@@ -25,10 +25,9 @@
def sort(seq):
- for x in seq:
- for n in range(1, len(seq)):
+ L = len(seq)
+ for _ in range(L):
+ for n in range(1, L):
if seq[n] < seq[n - 1]:
- temp = seq[n]
- seq[n] = seq[n - 1]
- seq[n - 1] = temp
+ seq[n - 1], seq[n] = seq[n], seq[n - 1]
return seq

0 comments on commit fa705db

Please sign in to comment.