Skip to content

Instantly share code, notes, and snippets.

@oliverseal
Created January 12, 2019 22:43
Show Gist options
  • Save oliverseal/13da7af8cde16a98f06052123db25822 to your computer and use it in GitHub Desktop.
Save oliverseal/13da7af8cde16a98f06052123db25822 to your computer and use it in GitHub Desktop.
array pancakes (testable with python3 -m unittest test)
def flatten(array):
"""
Drop in an array of a arrays (ex: [[1,2,[3]],4]) and get back a flattened array (ex: [1,2,3,4]).
"""
new_array = []
for i in array:
if not isinstance(i, list):
new_array.append(i)
else:
[new_array.append(j) for j in flatten(i)]
return new_array
import unittest
import random
from flatten import flatten
class FlattenUnitTest(unittest.TestCase):
def test_a_basic_array(self):
test_arr = [1, 2, 3, 4]
correct_arr = [1, 2, 3, 4]
pancake = flatten(test_arr)
self.assertSequenceEqual(pancake, correct_arr)
def test_a_complex_array(self):
test_arr = [[1, 2, [3]], 4]
correct_arr = [1, 2, 3, 4]
pancake = flatten(test_arr)
self.assertSequenceEqual(pancake, correct_arr)
def test_a_ridiculous_array(self):
start = random.randint(0, 10)
test_arr = []
correct_arr = []
for i in range(start, start + 10):
spot_array = list(range(i, i + random.randint(4, 40)))
use_array = random.randint(0, 1) == 0
if use_array:
test_arr.append(spot_array)
for j in spot_array:
correct_arr.append(j)
if not use_array:
test_arr.append(j)
pancake = flatten(test_arr)
self.assertSequenceEqual(pancake, correct_arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment