2

I'm reading an exercise out of a Python book, here is what it says:

Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.

Write a more general version of print_spam, called print_twice, that takes a string as a parameter and prints it twice.

Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.

Heres what I wrote:

def do_twice(f, g):
    f(g)
    f(g)

def print_spam(s):
    print (s)

do_twice(print_spam('lol'))

What is the way it is supposed to be written? I'm totally stumped on this one.

4 Answers 4

7

Just give the string as a second argument to do_twice. The do_twice functions calls the print_spam and supplies the string as an argument:

def do_twice(f, g):
    f(g)
    f(g)

def print_spam(s):
    print (s)

do_twice(print_spam,'lol')

prints:

lol
lol
Sign up to request clarification or add additional context in comments.

Comments

1

If for some reason you wanted to repeat the function n amount of times, you could also write something like this...

def do_n(f,g,n):
    for i in range(n):
        f(g)

do_n(print_spam,'lol',5)

lol
lol
lol
lol
lol

Comments

0
def do_twice(func, arg):
    """Runs a function twice.

    func: function object
    arg: argument passed to the function
    """
    func(arg)
    func(arg)


def print_twice(arg):
    """Prints the argument twice.

    arg: anything printable
    """
    print(arg)
    print(arg)


def do_four(func, arg):
    """Runs a function four times.

    func: function object
    arg: argument passed to the function
    """
    do_twice(func, arg)
    do_twice(func, arg)


do_twice(print_twice, 'spam')
print('')

do_four(print_twice, 'spam')

1 Comment

Your answer should contain some explanations! Please read How to Answer!
0

In my opinion ,according to the question from book thinkpython it had four various parts and hence each part had different code snippet in regards to the instruction provided. The second part would have print_twice as function not print_spam . Also in third part "spam" would be the argument provided not "lol". So you could try this instead. All the best.

Here is the code

def do_twice(f,g):
f(g) 
f(g)

def print_twice(s):
print(s)
print(s)

do_twice(print_twice,'spam')

def do_four(do_twice,g):
do_twice(g)
do_twice(g)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.