Last active
August 29, 2015 14:25
-
-
Save jhaubrich/717de2b9e60d66bdebf7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
matrix = [] | |
arr = ['a', 'b', 'c', 'd'] | |
rows = arr.length/size // can't have this in loop declaration because it changes size every time we pop | |
for (row = 0; row < 2; row++) { | |
matrix[row] = [] | |
for (col = 0; col < size; col++) { | |
console.log(row, col, matrix) | |
matrix[row][col] = arr.shift() // pop gives us the last element and makes a transposed array, we need shift | |
} | |
} | |
// Sometime I hate JS. We could have done this in python with much less pain. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my_list = ['a', 'b', 'c', 'd'] | |
size = 2 | |
def chunk(arr, size): | |
''' This is a closest equivalent of the JS we worked out. ''' | |
matrix = [] | |
index = 0 | |
for row in range(size): | |
new_list = [] | |
for col in range(size): | |
new_list.append(my_list[index]) | |
index += 1 | |
matrix.append(new_list) | |
return matrix | |
def chunk2(arr, size): | |
'''This one is more pythonic. It uses a python feature called | |
slicing. e.g. | |
>>> arr = ['a', 'b', 'c', 'd'] | |
>>> arr[2:4] | |
['c', 'd'] | |
>>> this_string = "this string" | |
>>> this_string[2:4] | |
"hi" | |
''' | |
matrix = [] | |
for i in range(0, len(arr), size): | |
matrix.append(arr[i:i+size]) | |
return matrix | |
# Though, the real beauty of python is all this stuff is already | |
# done. They like to call it 'batteries included.' | |
import numpy | |
numpy.reshape(my_list, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment