Monday, March 17, 2014

*Any Number of Arguments

*Any Number of Arguments


Something really cool that I came across today is putting a "*" in the argument in a function. It allows for you use any number of arguments for that function which is really cool and useful!

The the following example:

def add_all_values(*values):
    total = 0
    for x in values:
        total += x
    return total

add_all_values can take any number of  arguments:

>>> add_all_values()
0
>>> add_all_values(1)
1
>>> add_all_values(1, 2)
3
>>> add_all_values(1, 2, 3)
6
>>> add_all_values(1, 2, 3, 4)
10
>>> add_all_values(1, 2, 3, 4, 5)
15
>>> add_all_values(1, 2, 3, 4, 5, 6)
21
>>> add_all_values(1, 2, 3, 4, 5, 6, 7)
28
>>> add_all_values(1, 2, 3, 4, 5, 6, 7, 8)
36
>>> add_all_values(1, 2, 3, 4, 5, 6, 7, 8, 9)
45
>>> add_all_values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

55

What is really fascinating is that this can be used to increase the versatility of higher order functions. Take the following examples:

def test_values(func, *values):
    a = []
    for x in values:
        a.append(func(x))
    return a

def square_value(value):
    return (value**2)

def cube_value(value):
    return (value**3)

def value_to_power_of_value(value):
    return (value**value)

So what's really cool is that now, we can use different number of arguments in the higher order function when we call the various lower order ones!

>>> test_values(square_value, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> test_values(cube_value, 1, 2, 3, 4, 5)
[1, 8, 27, 64, 125]
>>> test_values(value_to_power_of_value, 1, 2, 3, 4)
[1, 4, 27, 256]

Higher Order Functions!

Higher Order Functions

I think higher order function (functions of functions) are very cool!

For example, you can make a function that test a function with various variables and returns all the answers in a list! Look at the following example:

def square_value(value:int) -> int:
    """
    >>> square_value(5)
    25
    """
    return (value**2)

def function_tester(func:object, values:list) -> list:
    """
    >>> function_tester(square_value, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    """
    result = []
    for x in values:
        result.append(func(x))
    return result 

>>> function_tester(square_value, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Very cool! I am very curious where this can be applied and how I can use this new trick in my code! I'm sure they can help me reduce the amount of code I need to write, especially when I need to write very similar functions, or when I need to write functions that have a combination of previously defined methods.

__eq__


__repr__


__init__

__init__

1. subjective reaction
2. steps you took to leviate events