Share
Explore BrainMass

Intro CS Using Python Program

Consider the following function definitions:

def y():
""" y does this function exist?
** just to illustrate a 0-input function...
"""
return 1

def w(x):
""" w computes thrice its input plus one
** plus it offers a chance to use the word "thrice"
input x: any number (int or float)
"""
return 3*(x+1)

def t(x):
""" t computes thrice its input plus one
** and shows how python is more precise than English
input x: any number (int or float)
"""
return 3*x + 1

def r(x,y):
""" r shows some less-common arithmetic operators
input x: any number (int or float)
input y: any number (int or float, more likely int)
"""
return ( x**2 % y ) + 2

def f(a,b):
""" f demonstrates the use of conditionals (if/elif/else)
** and that input parameters' names don't matter
input a: any number (int or float)
input b: any number (int or float)
"""
if a < b:
return (b-1) * (b-2)
else:
return (a+42) * (b+42)

Compositions
Here is an example of the kind of function composition that the following problems will ask you to create:

What composition of the functions w and t (above), along with the the literal value 0 will return the value 6? (No other literal values may be used.)

Solution to this example: w(t(0))

USE WORDS TO DESCRIBE THE SOLUTION STEPS

PROBLEM 1

Note that no literal numeric values ("numbers you type") other than 0 are allowed for these questions. Allowing any input takes away all the fun... not to mention that it would remove the need to compose funtions at all!

1i What composition of the functions w and t (above), along with the the literal value 0 will return the value 10?

1j Is it possible to compose the functions w and t (above), along with the literal value 0, to return any positive integer? Explain why or why not in a sentence or two.

1k What composition of all the functions above, along with the the literal value 0 will return the value 42?

1e For that last problem, what is the shortest composition, in terms of the number of functions called, that yields 42? (You'll know it when you see it -- in fact, you might have already come up with it for your answer to 1k.) Explain in a sentence or two why your answer is the shortest possible.

Solution Preview

"1i What composition of the functions w and t (above), along with the the literal value 0 will return the value 10? "

t(w(0))

First w(0) will be called which will return 3 * (0 + 1) which is equal to 3.
Then t(3) will be called which will return 3 * 3 + 1 which is equal to 10.

"1j Is it possible to compose the functions w and t (above), along with the literal value 0, to ...

$2.19