Saturday, March 28, 2015

3/28/15 - Permutations in Ruby and Python

Right at the end of class on Friday I finished my ruby permutations implementation, but didn't get a chance to blog it.
def permutations(list)
return [list] if list.size == 1
result = []
list.each do |locked|
list_copy = list.dup
list_copy.delete locked
permutations(list_copy).each do |permutation|
result << permutation.insert(0, locked)
end
end
result # this implicitly returns result. Initially I forgot to add it in and got weird results until I realized this was missing
end
if __FILE__ == $0
p permutations %w[a b c] # %w is ruby shorthand for an array of strings, this example creates the array: ['a', 'b', 'c']
p permutations %w[d e f g]
end

Sam also wrote a python version and explained the yield statement to me. I even wrote about it in Thursday's post, but I still don't really understand what is happening here. I'll try to get around to looking a bit more closely at the code and figure out how it works.
# Sam's python implementation
def permutations(listt): # apparently 'list' is a reserved keyword in python (or at least is a different color in the editor)
if len(listt) == 1:
yield listt
return
else:
for i, o in enumerate(listt):
listt_copy = listt.copy()
del listt_copy[i]
for perm in permutations(listt_copy):
yield [o] + perm # still not quite clear on how the yield statements work here

No comments:

Post a Comment