Forked from elkym/recur_even_odd_list_split.py
Last active
November 24, 2020 00:10
-
-
Save jamesona/20541e3800d9cb05ead1e8340810ba38 to your computer and use it in GitHub Desktop.
Python-thing-recursion-wonderings.py
This file contains 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
l1 = [1,3,9,10,4,3,2,5,17,14,11] | |
def splitIt(x): | |
''' | |
This recursive function takes a list of positive integers | |
x as argument and returns a tuple of two lists: a list of the even integers | |
in x followed by a list of the odd integers in x. | |
E.g. x = [3,2,1,5,4,6] gives [1,3,5] [2,4,6] | |
x = [1,3,9] gives [1,3,9] [] | |
''' | |
# base case: 1 item in list. | |
# if check and generate list with that item, and append this to a new list ([odd],[even]) | |
even_list = [] | |
odd_list = [] | |
splitHelper(x, even_list, odd_list) | |
return (even_list, odd_list) | |
def numberIsEven(x): | |
return x % 2 == 0 | |
def splitHelper(x, even_list, odd_list): | |
# check to see if position 1 (or list[0]) is even or odd. If even, append to even_list. Else append to odd_list. | |
if numberIsEven(x[0]): | |
print("item is even" + str(x)) | |
# add to even list | |
even_list.append(x[0]) | |
print("even list " + str(even_list)) | |
else: | |
print("item is odd" + str(x)) | |
# add to odd list | |
odd_list.append(x[0]) | |
print("odd list " + str(odd_list)) | |
if len(x) == 1: | |
return x | |
return (splitHelper(x[1:], even_list, odd_list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment