To wrap up our last 2 discussions about functions, namely how to use functions in Python and the temperature convertor, let us take a look at some functions that you may find useful in the future. We are going to start off easy and stack up. As before, we are going to be using Python 2.7. Before we get started let me remind every one, yes there are other ways, perhaps even better ways to code these functions. This is How I did it. It does not mean this is how you should do it. In fact, I would lover it if you left your version in the comments bellow! If you think it is too long for the comment section, send me an email and I will make it into a post. Lastly, these function are meant as an exercise, please be patient even if some of them do not make sense.

For each function (There are 22) we are going to look at the following:

- Brief description of the function
- Input types
- Excepted output
- Notes (if any)
- Example execution
- Code
- Example Output for code
- Final Notes (if any)

This is going to be long, so hang on. Let’s get started!

**1. Even numbers: **

Return a boolean value representing whether x is even or not.

input: number (integer)

output: True or False (boolean)

Example execution:

is_even(5) => False

is_even(42) => True

Code:

def is_even(n): return (n % 2) == 0

Code Output:

Final notes: Be aware the although the function is excepting an integer, a float might be passed in as the value of *n*. The result would always be False unless *n* is an even integer.

**2. Remove evens:
**Given a list of integers, remove all even values from the list and return an odd list of numbers.

input: a list of integers (list)

output: a list of odd numbers (list)

Example execution:

remove_evens([1,2,3,4,5,6]) => [1,3,5]

Code:

* Edited thanks to Eric Wilson (See comments)

def remove_evens(alist): res = [] for n in alist: if not is_even(n): res.append(n) return res

Code Output:

Final Note: You will notice that in this function we are calling another function within the module.

**3. Min Value:**

Accepts a list of numbers, and returns a copy of the smallest value in it.

input: a list if integers (list)

output: the minimum number (integer)

Example execution:

minval([104,22,31,4,54,61]) => 4

Code:

def minval(alist): return min(alist)

Code Output:

Final notes: Although in the input section we assumed that the function should only accept a list of integers. The function, as coded above, will also work for a mixed valued list. Python will use simple comparison to make sense and determine what the *min* value is.

Final notes 2: I am aware that that this function is useless since all it does is called the built in function *min()*.

**4. Index of Min Value:
**Accepts a list of numbers, and returns the index (zero based) where the smallest value can be found. It must return the earliest index, in case of ties.

input: a list if integers (list)

output: the minimum number’s index in the list (integer)

Example execution:

min_index([104,22,31,4,54,61]) => 3

Code:

def min_index(alist): return alist.index(minval(alist))

Code Output:

Final Note: You will notice that in this function we are calling another function within the module.

**5. Remove Value:**

Finds the first instance of a value, and removes it from the list. Return a boolean, True when the value was removed, and False when the value wasn't found.

input: an integer value and a list of integer numbers

output: True or False (boolean)

Example execution:

remove_a_value(22,[104,22,31,4,54,61]) => True

remove_a_value(105,[104,22,31,4,54,61]) => False

Code:

def remove_a_value(val, alist): try: alist.remove(val) return True except: return False

Code Output:

**6. Simple Sort:**

Given a list of numbers, you will return a copy of the list with all elements in sorted (ascending) order. You must implement the following algorithm:

make a copy of the list make an empty result list

LOOP as long as the copylist isn't empty:

find the minimum value in the copylist, remove it

add that minval to the end of the resultlist return the result list

input: a list if integers (list)

output: a list of sorted integers (list)

Example execution:

simple_sort([104, 22, 31, 4, 54, 61]) => [4, 22, 31, 54, 61, 104]

Code:

def simple_sort(alist): copy = alist[:] res = [] while len(copy) > 0: x = minval(copy) res.append(x) copy.remove(x) return res

Code Output:

Final Note: Although the function is assuming to work on integers, it may also work on other data types. Try it out.

**7. Destructive Sort:
**This behaves the same as

*Simple Sort*, except that it must modify the original.

input: a list if integers (list)

output: *NONE*.

NOTE: In this function we will be modifying the original list, meaning it is a destructive function to the arguments passed in. Also note that the function does not have any return statements or a return value.

Example execution:

list_a = [33,94,1,92,54,12]

distraction_sort(list_a)

Code:

#The code uses simple_sot(alist) to sort the list and then rewrites the original list values def distraction_sort(xs): temp = simple_sort(xs) for i in range(len(temp)): xs[i] = temp[i]

Code Output:

**8. Middle Sort:**

Without modifying the original list, find out what the middle element would be when all the elements are sorted. If the length is even (and thus no true 'middle' element), then out of the two elements closest to the middle, prefer the left one.

input: a list if integers (list)

output: the middle number if the list was sorted (an integer)

Example execution:

median_value([5,34,29,91,102,44,1,4]) => 29

Code:

def median_value(xs): temp = simple_sort(xs) mid = int(len(xs)/2) if is_even(len(xs)): mid -= 1 return temp[mid]

Code Output:

**9. Kth Sorted:**

Like *Middle Sort*, only we seek the Kth spot, not the middle spot. K is a zero-based integer index into the sorted version of list.

input: a list if integers (list)

output: the kth number if the list was sorted (an integer)

Example execution:

kth(2,[71,43,67,10,4,3,87,103s]) => 10

Code:

def kth(k,xs): temp = simple_sort(xs) return temp[k]

Code Output:

**10. Zip List:**

Given two lists of values, create and return a list of tuples that "zip" up the values from the two lists together - first items in a pair, second items in a pair, and so on.

input: 2 lists of integers (lists)

output: a single list of tuples with values from both lists (a list)

Example execution:

zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']) => [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

Code:

def zip(xs,ys): res = [] i = 0 while i < len(xs) and i < len(ys): res.append((xs[i],ys[i])) i += 1 return res

Code Output:

**11. Multiply Lists:**

Given two lists of numbers, create a new list of numbers by multiplying the same-indexed values. As soon as one list runs out of values, the resulting list ends.

input: 2 lists of integers (lists)

output: a single list with the values from both list multiplied, while both lists have values (a list)

Example execution:

pairwise_multiply([2, 3, 10, 11], [35, 10, 29, 3]) => [70, 30, 290, 33]

Code:

def pairwise_multiply(xs,ys): res = [] i = 0 while i < len(xs) and i < len(ys): res.append(xs[i]*ys[i]) i += 1 return res

Code Output:

**12. Dot Product:**

Given two lists of numbers, return a single number found by multiplying each same-indexed pair of numbers, and adding the results together.

input: 2 lists of integers (lists)

output: the sum of each pair of elements multiplied (an integer)

Example execution:

dot_product([1, 2, 3], [3, 2, 1]) => 10

Code:

def dot_product(alist, blist): return sum(pairwise_multiply(alist,blist))

Code Output:

**13. N Copies:**

Return a list with n copies of val.

input: a number and a value (integer,*any*)

output: a list with n copies of a given value (a list)

Example execution:

n_copy(5,3) => [5, 5, 5]

Code:

def n_copy(val,n): res = [] for i in range(n): res.append(val) return res

Code Output:

**14. Interleave:**

Given two lists of values, create (and return) the interleaved version by making a new list with the first value of list_a, then the first value of list_b, then the second value of list_a, second value of list_b, and so on. Once a list is done the rest of the values from the other list are added to the resulting list.

input: 2 lists of integers (lists)

output: A single list with the values from both lists interleaved (a list)

NOTE: Etra valuees for either list are added to the end of the result list

Example execution:

interleave(['a', 'b', 'c'], [1, 2, 3]) => ['a', 1, 'b', 2, 'c', 3]

Code:

def interleave(alist,blist): res = [] i = 0 while i<len(alist) and i<len(blist): res.append(alist[i]) res.append(blist[i]) i += 1 for j in range(i,len(alist)): res.append(alist[j]) for j in range(i,len(blist)): res.append(blist[j]) return res

Code Output:

**15. Riffle Shuffle:**

Imagine we were shuffling cards with the standard "riffle" shuffle (just interleaving two halves of the deck together). For many card games, we need to perform multiple shuffling in order to get enough apparent randomness in the order of cards. List represents the 'deck' to be shuffled, and n represents how many "riffle" shuffling need to be performed.

input: a single list (a list)

output: a shuffled list (a list)

NOTE: Like function 7, *distraction_sort*, this function modifies the original values given

Example execution:

list_a = ['a','b','c','d','e','f','g']

riffle_shuffle(list_a)

Code:

def riffle_shuffle(alist): temp = alist mid = int(len(alist)/2) temp = interleave(temp[0:mid],temp[mid:len(alist)]) for i in range(len(alist)): alist[i] = temp[i]

Code Output:

**16. Pairs:**

Create and return a list of all possible pairs from values in list_a and values in list_b. The order of elements is important! all of the pairs of list_a first element must appear before all pairs involving list_a second element; similarly, when pairing with a specific element from list_a, these pairs must include list_b elements in the same order as original.

input: 2 lists of integers (lists)

output: a single list with pairs of values from both lists (a list)

Example execution:

all_pairs([1, 2, 3], ['a', 'b', 'c']) => [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]

Code:

def all_pairs(alist,blist): res = [] for x in alist: for y in blist: res.append((x,y)) return res

Code Output:

**17. Build Deck:
**Create a fresh, organized deck. You must generate the result from these two strings: one representing all the pips (card values) "23456789TJQKA", and another representing the suits, "CDHS".

input: 2 strings, “23456789TJQKA” and “CDHS” (strings)

output: a list of cards (a list)

NOTE: each card will be repressed by a value and suit. For example: 4C is 4 of clubs, TS is ten of spades and QH is queen of heats.

Example execution:

new_deck()

Code:

def new_deck(): val = "23456789TJQKA" shapes = "CDHS" return (all_pairs(val,shapes))

Code Output:

**18. Reduce Dimension:**

Given a list of more than one dimension, create and return a new list by collapsing that outermost dimension.

input: a multidimensional list (a list)

output: the list without the outmost dimension (a list)

NOTE: This function only reduces the original list dimension by 1, not a full flatten.

Example execution:

flatten([[[1, 2, 3], 4], [5]]) => [[1, 2, 3], 4, 5]

Code:

def flatten(alist): res = [] for i in alist: for j in i: res.append(j) return res

Code Output:

**19. Map:
**Given a python function and a sequence of values, create and return a new list by calling the function on each value in the sequence and placing the results into the returned list.

input: a function name and a sequence of values (string,tuple/list)

output: the results from the mapped function onto the sequence of values (a list)

Example execution:

map(ord,”Hello World”) => [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

Code:

def map(f,alist): res = [] for x in alist: res.append(eval(str(f(x)))) return res

Code Output:

**20. Zip With:
**Combine elements of list_a and list_b together while using the operator, generating a new list.

input: a function and 2 lists (string,lists)

output: a list with the values from applying the function on the lists values (a list)

Example execution:

zip_with(add, [1, 2, 3], [4, 5, 6]) => [5, 7, 9]

Code:

def zip_with(f,alist,blist): res = [] i = 0 while i<len(alist) and i<len(blist): res.append(eval(str(f(alist[i],blist[i])))) i += 1 return res

Code Output:

Pingback: Python Functions, Learning by doing: - Khadir Zavareh's personal website- Khadir Zavareh's personal website()