Browsing Tag

# functions

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:

1. Brief description of the function
2. Input types
3. Excepted output
4. Notes (if any)
5. Example execution
6. Code
7. Example Output for code
8. 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:

Last time we talked about using functions in Python, this time let us take it a step farther and create a module. Functions are great and you are going to use them everywhere, but what happens when you need to use a function in more than one place? What happens when a function needs to be utilized in different files within one application? In Python, we create modules, which are just your regular .py files. We can use functions (and objects) from other files by using an import statement. Every language has some form of an import statement. In C we use an include statement. The idea is that when you need, you can include code from another code file. For this post, lets assume a scenario. Imagine that you are an entry level programmer at a software company. You are assign to a team that is working on some large scale scientific application in Python. As the newbie on the team, you are giving the task to write functions that will be used for temperature conversation in multiple parts of the program. You are given the following function pseudocode and are requested to write the code for them:

1. c2f(t) will take a float temperature in Celsius and return a float temperature in Fahrenheit
2. c2k(t) will take a float temperature in Celsius and return a float temperature Kelvin
3. f2c(t) will take a float temperature in Fahrenheit and return a float temperature Celsius
4. f2k(t) will take a float temperature in Fahrenheit and return a float temperature Kelvin
5. k2c(t) will take a float temperature in Kelvin and return a float temperature in Celsius
6. k2f(t) will take a float temperature in Kelvin and return a float temperature in Fahrenheit

So these functions are pretty easy to write, they are all 1 line of code. Using some basic formulas from Wikipedia Conversion of units of temperature the code in Python for temperature conversion might look like this:

```
def c2f(t):
return (t*9/5.0)+32

def c2k(t):
return t+273.15

def f2c(t):
return (t-32)*5.0/9

def f2k(t):
return (t+459.67)*5.0/9

def k2c(t):
return t-273.15

def k2f(t):
return (t*9/5.0)-459.67

```

That was simple. Notice that we have included in every calculation an implicate conversion to float, so even if t is not a float, the result will return as a float. That might be useful if at some other part of the application some numeric calculation is required. Especially if the calculation requires higher level of accuracy. Within a couple of minutes you hand your boss (email him/her) a file named temperature.py and you think you are done. In most cases you might be done, but have you tested your code? Rushing code is never a good idea. Take the time to fully test you code and make sure it works the way you think it does. This example might be straight forward, but other examples might be more complicated. It is a good habit to always self test you code. Here is one way you can test the code:

```
def main():

"1. Celsius to Fahrenheit\n"+\
"2. Celsius to Kelvin\n"+\
"3. Fahrenheit to Celsius\n"+\
"4. Fahrenheit to Kelvin\n"+\
"5. Kelvin to Celsius\n"+\
"6. Kelvin to Fahrenheit\n"+\
"7. Quit"

user_input = 0
while user_input != 7:
user_input = raw_input("Please enter a valid selection: ")

try:
user_input = int(user_input)
except:
print user_input + " is not a valid selection, please try again\n"

if user_input == 1:
t = get_user_input()
print str(t) + " degree Celsius is " + str((c2f(t))) + " degree Fahrenheit"
elif user_input == 2:
t = get_user_input()
print str(t) + " degree Celsius is " + str((c2k(t))) + " degree Kelvin"
elif user_input == 3:
t = get_user_input()
print str(t) + " degree Fahrenheit is " + str((f2c(t))) + " degree Celsius"
elif user_input == 4:
t = get_user_input()
print str(t) + " degree Fahrenheit is " + str((f2K(t))) + " degree Kelvin"
elif user_input == 5:
t = get_user_input()
print str(t) + " degree Kelvin is " + str((k2c(t))) + " degree Celsius"
elif user_input == 6:
t = get_user_input()
print str(t) + " degree Kelvin is " + str((k2f(t))) + " degree Fahrenheit"
elif user_input == 7:
quit()
else:
print str(user_input) + " is not a valid selection, please try again\n"

if __name__ == "__main__":
main()

```

The output of the code might look like this: Now this main() function is in a different file called converter.py. The file content has now functions that can convert anything. However, in the very top of the file there is one magical statement:

```
from temperature import *

```

There are different ways to include code from another .py file, but for now, we can use this one. All it is is a small indication for Python to know that if they need to open a temperature.py file as well as the converter.py file. The only requirement is that both files are in the same working directory, that is that they are in the same folder. When you examine the code you may notice that some code was added to account for invalid entries, such as if a user enters a character instead of a number. There is also a hidden function called get_user_input() that looks like this:

```
def get_user_input():

user_input = 0
while type(user_input) != type(1.0):
user_input = raw_input("Enter degrees to convert: ")
try:
user_input = float(user_input)
except:
print user_input + " is not a valid entry"
return user_input

```

This function makes sure the user enters a numeric value to convert. At this point you have all the tools necessary to tell you boss that you have tested you code and it works properly. You might also want to keep this as part of the code in case you want to use it in the future. I have uploaded the code in case you want to test it out for yourself, Temperature Conversation Application in Python.

As you begin to learn programming, sooner or later you will run into the issue of rewriting code. That is one of the many reasons we teach and learn to write functions. Functions are much like the mathematical equivalent, they are machines, with some input and output. Somewhere in school you might have learned that a function f takes a value x and has an output y. Much like that we have functions in programming that can take variables or arguments and have an output of some result. The inner working of a function in math is more technical, like f(x) = 2x + 3. In a similar matter, functions in programming execute statements.

There are 4 different types of functions that we can consider:

1. No variables and no return
2. Variable and no return
3. No variable and a return
4. Variable and return

Let us look at some examples. First let us look at the syntax requirements by Python to write Functions in Python. Like before, we will consider Python 2.7 to be our standard. The same ideas will apply to other versions and even other languages. You can take a look at the Python 2.7 function definition for more reading, but the basic definition of a function in python will look something like this:

```def <function_name>(<Variables>) :
<body>
```

Where <function_name> is a must, <Variables> are optional and <body> can be as minimal as pass. So what is our most minimal function? The useless function:

```
def useless():
pass

```

As you may guess, using this function is pointless, but that brings up another question, how do we use functions? That is simple, we call functions, by name. So if we were to make use of this function we can call it by the statement:

```
useless()

```

Now this is pointless, since nothing will let you know that the function even executed correctly. Computers today are so fast, in a blink of an eye your program will run through the code, and without any output, there is nothing to make the user verify that something actually happened. This brings us to the first kind of functions, functions without variables and without a return. You may think this is pointless by itself, but let’s say you need to do a menu to allow the user to select from 3 options, something that looks like this:

The beginning code can look something like this:

```
print "1. do something"
print "2. do something else"
print "3. quit"

user_input = raw_input("Please make a valid selection: ")

if user_input == "1":
print "doing something..."

elif user_input == "2":
print "doing something else"

elif user_input == "3":
quit()

else:
print "not a valid selection"

```

Now this is nice, but what if we have to repeat this, won’t it be easier in a loop. Sure it will! To change it we will need to add a while statement and set user_input to some initial value. Our code will look now like this:

```
user_input = 1

while user_input != 3:

print "1. do something"
print "2. do something else"
print "3. quit"

user_input = raw_input("Please make a valid selection: ")

if user_input == "1":
print "doing something..."

elif user_input == "2":
print "doing something else"

elif user_input == "3":
quit()

else:
print "not a valid selection"

```

Now that is a little more intuitive. Now our program will execute code, but keep going back to the main loop. It would be helpful if instead of the print statements, we change it to have a single function call, to out function that takes no variables and has no return. That is right, a useless function is perfect for printing out information.

```

print "1. do something"
print "2. do something else"
print "3. quit"

```

You may some other usage for a function of such. I normally use them for printing out user information, such as help instructions and menus. You might find other use to them, such as updating global variables, but that is beyond the scope of this post. Let us look at our code now inside the while loop:

```

user_input = raw_input("Please make a valid selection: ")

if user_input == "1":
print "doing something..."

elif user_input == "2":
print "doing something else"

elif user_input == "3":
quit()

else:
print "not a valid selection"

```

The next type of functions we want to examine are those who take a variable and return now value. Let’s say we want a function that will print out “ho” a given number of times. a function like that might look like this:

```
def ho(n):
for i in range(n):
print "ho",
print

```

Notice that the function is named ho, and that it has a variable name in the parentheses. The variable will receive a value when we call the function. If no value is given, we will get a trace back that looks like this:

We want to try to avoid that. To do so, we can assign a defualt value, just in case we “forget” to give it a value. We do this by adding an equal sign and a value. Like this:

```
def ho(n=3):
for i in range(n):
print "ho",
print

```

So now we can call this function by ethier just the name, or by giving it a number of time to print “ho”. Like this:

```
ho()

ho(5)

```

The output will be:

These types of functions are useful for all sort of things. usually, things that can be computed or executed without any of the results needing to come back to our main program. Let us look at another example that has more than 1 variable, the power function. Let us say that the default value of the power is always 2, but the base has to be given by the user. The result does not need to be stored, it can be printed out to the screen. This function might look like this:

```
def power(base,exp=2):
print base ** exp

```

Notice that we have multiple variables, 1 with no default value and 1 with a default value. In theory, a function can has as many variables as you need. It may also have a dynamic number of variables. As a rule of thumb, if you have over 4-5 variables as arguments for your function, you may want to rethink your logic a little. Let us look at the output of our power function and some function calls:

```
power(2)

power(5)

power(5,3)

```

You may think that this is it, but it is not. Until now we say functions that do something and output to the screen something. What if we actually need the value? What if we are within a bigger program and we need the value of the power function? We will get back to that in a minute. Let us first talk about function with no variables. Such function are getters of values, something like a random number generator. Lets say we need a function that will return 2 every time it is called. I know, it seems pointless, but it is for demonstration only. That function will look like this:

```def rtn_2():
return 2
```

Notice that we use a special reserved keyword return. The values, or variables, after that word is what the function returns. In this case we return the value 2. Now, our function call is the same, but since we return a value, that normally means we want to store it somewhere. So out function call changes from just the name of a function to a variable assignment statements that looks like this:

```value = rtn_2()
```

The value returned from the function rtn_2 will be stored in the variable value for future usage. We can also have multiple return statements and multiple values returns, but that is another topic by itself. Now we are ready to talk about the most common and most useful function type, functions with variables and return types. Let us say that we want to modify our power function from before to return the value, we can modify it to look something like this:

```
def power2(base,exp=2):
return base ** exp

```

That was easy. Now the value computed will be returned tot he calling function for future reference. Cool. Lets see if we can combine all 4 functions to be call from our menu program (Again, just inside the while loop):

```

user_input = raw_input("Please make a valid selection: ")
print

if user_input == "1":
n = input("enter a number: ")
ho(n)

elif user_input == "2":
base = input("enter a number: ")
print str(base) + " to the power of 2 is ",
power(base)
base = input("enter a number: ")
exp = input("enter a number: ")
print str(base) + " to the power of " + str(exp) + " is ",
power(base,exp)

elif user_input == "3":
value = rtn_2()
print "The value is " + str(value)

elif user_input == "4":
base = input("enter a number: ")
res = power2(base)
print str(base) + " to the power of 2 is " + str(res)
base = input("enter a number: ")
exp = input("enter a number: ")
res = power2(base,exp)
print str(base) + " to the power of " + str(exp) +" is " + str(res)

elif user_input == "5":
quit()

else:
print "not a valid selection"

print

```

The full python function example can be viewed here. Some notes about the program and functions in general:

• First, you will notice some print statements, those were added for ease of use.
• Second, the function we discussed here are mostly integer ones. That is not the only case for use of functions, variable can be of any Python data type.
• Return type of function can be of any type. The ones we showed here are not the only one.