Skip to content

Commit

Permalink
Merge pull request YearOfProgramming#363 from sarcodian/python_9
Browse files Browse the repository at this point in the history
[Python] Challenge 9 (reviewed and merged)
  • Loading branch information
Steven Landau committed Jan 23, 2017
2 parents db4481b + 3858f81 commit 5f337c6
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
12 changes: 12 additions & 0 deletions challenge_9/python/sarcodian/READ.me
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Takes a list of sorted values and squares them, resorting
the resulting list. The algorithm cannot use sort on the
resulting list.

If the first element of the list is greater then 0, we can
just return the list squared as tis already sorted.

Otherwise, we work backwards, but comparing the absolute value
of the first element with the last element and squaring the largest.

We then return the reverse of the squared list to get it sorted from
smallest to largest.
27 changes: 27 additions & 0 deletions challenge_9/python/sarcodian/src/challenge_9.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def square_n_sort(L):
'''
Get an ordered list of ints and square the values, returning a list
of squares ordered from smallest to largest.
'''

L_square = []
L_sorted = []
count = len(L)

if L[0] >= 0:
for i in L:
L_square.append(i**2)
return L_square

while count > 0:
if abs(L[0]) >= abs(L[-1]):
L_square.append(L[0]**2)
L.remove(L[0])
else:
L_square.append(L[-1]**2)
L.remove(L[-1])
count -= 1

L_sorted = L_square[::-1]

return L_sorted
24 changes: 24 additions & 0 deletions challenge_9/python/sarcodian/src/challenge_9_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# we start by importing the unittest module
import unittest

# Next lets import our function that we intend to do testing on
#
# **We could also import all functions by using * or just import the module
# itself but for now lets just import the function
from challenge_9 import square_n_sort

# lets define our suite of tests as a class and lets inherit from unittest.TestCase
class TestBinaryMethods(unittest.TestCase):

def test_squareSort(self):
""" Tests from the READ.me """

self.assertEqual(square_n_sort([0,1,2]), [0,1,4])
self.assertEqual(square_n_sort([-5,-4,-3,-2]), [4,9,16,25])
self.assertEqual(square_n_sort([1,2]), [1,4])
self.assertEqual(square_n_sort([-2,-1,0,1,2]), [0,1,1,4,4])

# if the python file is ran by itself run unittest
# This allows us to import the members of the file without running main if we need to
if __name__ == '__main__':
unittest.main()

0 comments on commit 5f337c6

Please sign in to comment.