Skip to content

Instantly share code, notes, and snippets.

@thisiswei
Created March 16, 2014 06:32
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 thisiswei/9579369 to your computer and use it in GitHub Desktop.
Save thisiswei/9579369 to your computer and use it in GitHub Desktop.
def append(val, p):
last = p[-1]
p[-1] = val
insert(-1, last, p)
def insert(idx, val, iterable):
tmp = None
if idx < 0:
idx = len(iterable) + idx
for j, item in enumerate(iterable):
if j >= idx:
iterable[j] = tmp or val
tmp = item
#Cheat. Can't figure out how to implement append
#by modifying the original iterable
iterable.append(tmp)
def reverse_iterative(p):
"""
docstring for reverse
"""
L = len(p) / 2
for i in range(L):
p[i], p[-i-1] = p[-i-1], p[i]
return p
def reverse_recursive(p):
if len(p) == 1:
return p
head, rest = p[0], p[1:]
front, tail = p[:-1], p[-1]
return [tail] + reverse_recursive(front)
def bubble_sort(lis):
if len(lis) == 1 or not lis:
return lis
while True:
cnt = 0
for i, current in enumerate(lis[1:], 1):
pre = lis[i-1]
if current < pre:
lis[i], lis[i-1] = pre, current
cnt += 1
if not cnt:
break
return lis
lis = [7, 8, 1, 6, 5, 4, 2, 3, 0, 9]
print lis
print bubble_sort(lis)
R = range(10)
import random
for _ in range(100):
random.shuffle(R)
reversed_R = list(reversed(R))
assert reversed_R == reverse_recursive(R)
assert reversed_R == reverse_iterative(R)
@daniyalzade
Copy link

Awesome man!

A few things:

L30: I guess you dont need that

Good that you implemented reverse for a list, but i wanted them for linkedlist. Let me know if you get a chance to look into that.

L8-9: This is kind of hacky. What if len(x) was 5 and I wanted to insert at -100, in the pythonic sense. Can you make that more generic?

L14: What is your question here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment