Composite functions in python - dual composeCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonUsing global variables in a functionHow to make a chain of function decorators?Does Python have a string 'contains' substring method?

If the interviewer says "We have other interviews to conduct and then back to you in few days", is it a bad sign to not get the job?

Traveling from Germany to other countries by train?

Our group keeps dying during the Lost Mine of Phandelver campaign. What are we doing wrong?

What does the ISO setting for mechanical 35mm film cameras actually do?

Repeated! Factorials!

Find a text string in a file and output only the rest of the text that follows it?

Is charge point-like or a smear?

Examples of application problems of coordinate geometry in the complex plane?

What is it exactly about flying a Flyboard across the English channel that made Zapata's thighs burn?

Probably terminated or laid off soon; confront or not?

If someone else uploads my GPL'd code to Github without my permission, is that a copyright violation?

Why is the Vasa Museum in Stockholm so Popular?

How can I perform a deterministic physics simulation?

Non-small objects in categories

How do I get the =LEFT function in excel, to also take the number zero as the first number?

Minimum effort to detect a solved Rubik's Cube

What could prevent players from leaving an island?

Find only those folders that contain a File with the same name as the Folder

Why does putting a dot after the URL remove login information?

A verb for when some rights are not violated?

Identify Batman without getting caught

What is the German idiom or expression for when someone is being hypocritical against their own teachings?

Did silent film actors actually say their lines or did they simply improvise “dialogue” while being filmed?

Should I take out a personal loan to pay off credit card debt?



Composite functions in python - dual compose


Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonUsing global variables in a functionHow to make a chain of function decorators?Does Python have a string 'contains' substring method?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I came across the following homework problem:



enter image description here



My code for this problem was marked wrong and when I viewed the suggested solution, I couldn't understand where I went wrong. I ran the codes of both functions in Python IDLE compiler only to see that both functions return the same output as seen below:



>>> def dual_function(f,g,n): #Suggested solution
def helper(x):
f1,g1 = f,g
if n%2==0:
f1,g1=g1,f1
for i in range(n):
x=f1(x)
f1,g1=g1,f1
return x
return helper

>>> def dual_function_two(f,g,n): #My solution
def helper(x):
if n%2==0:
for i in range (n):
if i%2==0:
x = g(x)
else:
x = f(x)
else:
for i in range(n):
if i%2==0:
x = f(x)
else:
x = g(x)
return x
return helper

>>> add1 = lambda x: x+1
>>> add2 = lambda x: x+2
>>> dual_function(add1,add2,4)(3)
9
>>> dual_function_two(add1,add2,4)(3)
9
>>>


I would appreciate it if someone could identify the mistake in my solution. Thank you.










share|improve this question



















  • 2





    Do you know the test cases used to grade your problem? I can't find any case where the two functions differ.

    – Sebastian
    Mar 27 at 4:26






  • 2





    Those aren't good test functions, since addition is commutative -- if you called them in the wrong order you wouldn't notice the difference. But I tried mixing addition and multiplication, and I couldn't find a difference, either.

    – Barmar
    Mar 27 at 4:57






  • 1





    It's probably much slower than the suggested solution due to the constant modulo operations. Swapping is going to be much faster.

    – Rick Teachey
    Mar 27 at 5:02











  • @Sebastian Unfortunately, I do not have the test cases :(

    – Prav
    Mar 27 at 6:19











  • @Barmar Thank you for letting me know about using commutative operators in such functions, will remember them when working on similar problems in the future.

    – Prav
    Mar 27 at 6:20

















2















I came across the following homework problem:



enter image description here



My code for this problem was marked wrong and when I viewed the suggested solution, I couldn't understand where I went wrong. I ran the codes of both functions in Python IDLE compiler only to see that both functions return the same output as seen below:



>>> def dual_function(f,g,n): #Suggested solution
def helper(x):
f1,g1 = f,g
if n%2==0:
f1,g1=g1,f1
for i in range(n):
x=f1(x)
f1,g1=g1,f1
return x
return helper

>>> def dual_function_two(f,g,n): #My solution
def helper(x):
if n%2==0:
for i in range (n):
if i%2==0:
x = g(x)
else:
x = f(x)
else:
for i in range(n):
if i%2==0:
x = f(x)
else:
x = g(x)
return x
return helper

>>> add1 = lambda x: x+1
>>> add2 = lambda x: x+2
>>> dual_function(add1,add2,4)(3)
9
>>> dual_function_two(add1,add2,4)(3)
9
>>>


I would appreciate it if someone could identify the mistake in my solution. Thank you.










share|improve this question



















  • 2





    Do you know the test cases used to grade your problem? I can't find any case where the two functions differ.

    – Sebastian
    Mar 27 at 4:26






  • 2





    Those aren't good test functions, since addition is commutative -- if you called them in the wrong order you wouldn't notice the difference. But I tried mixing addition and multiplication, and I couldn't find a difference, either.

    – Barmar
    Mar 27 at 4:57






  • 1





    It's probably much slower than the suggested solution due to the constant modulo operations. Swapping is going to be much faster.

    – Rick Teachey
    Mar 27 at 5:02











  • @Sebastian Unfortunately, I do not have the test cases :(

    – Prav
    Mar 27 at 6:19











  • @Barmar Thank you for letting me know about using commutative operators in such functions, will remember them when working on similar problems in the future.

    – Prav
    Mar 27 at 6:20













2












2








2


0






I came across the following homework problem:



enter image description here



My code for this problem was marked wrong and when I viewed the suggested solution, I couldn't understand where I went wrong. I ran the codes of both functions in Python IDLE compiler only to see that both functions return the same output as seen below:



>>> def dual_function(f,g,n): #Suggested solution
def helper(x):
f1,g1 = f,g
if n%2==0:
f1,g1=g1,f1
for i in range(n):
x=f1(x)
f1,g1=g1,f1
return x
return helper

>>> def dual_function_two(f,g,n): #My solution
def helper(x):
if n%2==0:
for i in range (n):
if i%2==0:
x = g(x)
else:
x = f(x)
else:
for i in range(n):
if i%2==0:
x = f(x)
else:
x = g(x)
return x
return helper

>>> add1 = lambda x: x+1
>>> add2 = lambda x: x+2
>>> dual_function(add1,add2,4)(3)
9
>>> dual_function_two(add1,add2,4)(3)
9
>>>


I would appreciate it if someone could identify the mistake in my solution. Thank you.










share|improve this question














I came across the following homework problem:



enter image description here



My code for this problem was marked wrong and when I viewed the suggested solution, I couldn't understand where I went wrong. I ran the codes of both functions in Python IDLE compiler only to see that both functions return the same output as seen below:



>>> def dual_function(f,g,n): #Suggested solution
def helper(x):
f1,g1 = f,g
if n%2==0:
f1,g1=g1,f1
for i in range(n):
x=f1(x)
f1,g1=g1,f1
return x
return helper

>>> def dual_function_two(f,g,n): #My solution
def helper(x):
if n%2==0:
for i in range (n):
if i%2==0:
x = g(x)
else:
x = f(x)
else:
for i in range(n):
if i%2==0:
x = f(x)
else:
x = g(x)
return x
return helper

>>> add1 = lambda x: x+1
>>> add2 = lambda x: x+2
>>> dual_function(add1,add2,4)(3)
9
>>> dual_function_two(add1,add2,4)(3)
9
>>>


I would appreciate it if someone could identify the mistake in my solution. Thank you.







python lambda functional-programming higher-order-functions






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 4:02









PravPrav

347 bronze badges




347 bronze badges










  • 2





    Do you know the test cases used to grade your problem? I can't find any case where the two functions differ.

    – Sebastian
    Mar 27 at 4:26






  • 2





    Those aren't good test functions, since addition is commutative -- if you called them in the wrong order you wouldn't notice the difference. But I tried mixing addition and multiplication, and I couldn't find a difference, either.

    – Barmar
    Mar 27 at 4:57






  • 1





    It's probably much slower than the suggested solution due to the constant modulo operations. Swapping is going to be much faster.

    – Rick Teachey
    Mar 27 at 5:02











  • @Sebastian Unfortunately, I do not have the test cases :(

    – Prav
    Mar 27 at 6:19











  • @Barmar Thank you for letting me know about using commutative operators in such functions, will remember them when working on similar problems in the future.

    – Prav
    Mar 27 at 6:20












  • 2





    Do you know the test cases used to grade your problem? I can't find any case where the two functions differ.

    – Sebastian
    Mar 27 at 4:26






  • 2





    Those aren't good test functions, since addition is commutative -- if you called them in the wrong order you wouldn't notice the difference. But I tried mixing addition and multiplication, and I couldn't find a difference, either.

    – Barmar
    Mar 27 at 4:57






  • 1





    It's probably much slower than the suggested solution due to the constant modulo operations. Swapping is going to be much faster.

    – Rick Teachey
    Mar 27 at 5:02











  • @Sebastian Unfortunately, I do not have the test cases :(

    – Prav
    Mar 27 at 6:19











  • @Barmar Thank you for letting me know about using commutative operators in such functions, will remember them when working on similar problems in the future.

    – Prav
    Mar 27 at 6:20







2




2





Do you know the test cases used to grade your problem? I can't find any case where the two functions differ.

– Sebastian
Mar 27 at 4:26





Do you know the test cases used to grade your problem? I can't find any case where the two functions differ.

– Sebastian
Mar 27 at 4:26




2




2





Those aren't good test functions, since addition is commutative -- if you called them in the wrong order you wouldn't notice the difference. But I tried mixing addition and multiplication, and I couldn't find a difference, either.

– Barmar
Mar 27 at 4:57





Those aren't good test functions, since addition is commutative -- if you called them in the wrong order you wouldn't notice the difference. But I tried mixing addition and multiplication, and I couldn't find a difference, either.

– Barmar
Mar 27 at 4:57




1




1





It's probably much slower than the suggested solution due to the constant modulo operations. Swapping is going to be much faster.

– Rick Teachey
Mar 27 at 5:02





It's probably much slower than the suggested solution due to the constant modulo operations. Swapping is going to be much faster.

– Rick Teachey
Mar 27 at 5:02













@Sebastian Unfortunately, I do not have the test cases :(

– Prav
Mar 27 at 6:19





@Sebastian Unfortunately, I do not have the test cases :(

– Prav
Mar 27 at 6:19













@Barmar Thank you for letting me know about using commutative operators in such functions, will remember them when working on similar problems in the future.

– Prav
Mar 27 at 6:20





@Barmar Thank you for letting me know about using commutative operators in such functions, will remember them when working on similar problems in the future.

– Prav
Mar 27 at 6:20












1 Answer
1






active

oldest

votes


















3














The suggested solution is needlessly complex. Countless reassignments of variables and a loop are a recipe for a headache. Here's a simplified alternative -



def dual (f, g, n):
if n == 0:
return lambda x: x
else:
return lambda x: f(dual(g, f, n - 1)(x))

add1 = lambda x: 1 + x
add2 = lambda x: 2 + x

print(dual(add1,add2,4)(3))
# 9
# (1 + 2 + 1 + 2 + 3)

print(dual(add1,add2,9)(3))
# 16
# (1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 3)

print(dual(add1,add2,0)(3))
# 3


The reason this works is because in the recursive branch, we call dual with swapped arguments, dual(g,f,n-1). So f and g change places each time as n decrements down to 0, the base case, which returns the identity (no-op) function.



A slightly less readable version, but works identically -



def dual (f, g, n):
return lambda x:
x if n == 0 else f(dual(g, f, n - 1)(x))





share|improve this answer

























  • Great, never knew I could be this simple. Thanks for the explanation! :)

    – Prav
    Mar 27 at 13:31










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55369615%2fcomposite-functions-in-python-dual-compose%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














The suggested solution is needlessly complex. Countless reassignments of variables and a loop are a recipe for a headache. Here's a simplified alternative -



def dual (f, g, n):
if n == 0:
return lambda x: x
else:
return lambda x: f(dual(g, f, n - 1)(x))

add1 = lambda x: 1 + x
add2 = lambda x: 2 + x

print(dual(add1,add2,4)(3))
# 9
# (1 + 2 + 1 + 2 + 3)

print(dual(add1,add2,9)(3))
# 16
# (1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 3)

print(dual(add1,add2,0)(3))
# 3


The reason this works is because in the recursive branch, we call dual with swapped arguments, dual(g,f,n-1). So f and g change places each time as n decrements down to 0, the base case, which returns the identity (no-op) function.



A slightly less readable version, but works identically -



def dual (f, g, n):
return lambda x:
x if n == 0 else f(dual(g, f, n - 1)(x))





share|improve this answer

























  • Great, never knew I could be this simple. Thanks for the explanation! :)

    – Prav
    Mar 27 at 13:31















3














The suggested solution is needlessly complex. Countless reassignments of variables and a loop are a recipe for a headache. Here's a simplified alternative -



def dual (f, g, n):
if n == 0:
return lambda x: x
else:
return lambda x: f(dual(g, f, n - 1)(x))

add1 = lambda x: 1 + x
add2 = lambda x: 2 + x

print(dual(add1,add2,4)(3))
# 9
# (1 + 2 + 1 + 2 + 3)

print(dual(add1,add2,9)(3))
# 16
# (1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 3)

print(dual(add1,add2,0)(3))
# 3


The reason this works is because in the recursive branch, we call dual with swapped arguments, dual(g,f,n-1). So f and g change places each time as n decrements down to 0, the base case, which returns the identity (no-op) function.



A slightly less readable version, but works identically -



def dual (f, g, n):
return lambda x:
x if n == 0 else f(dual(g, f, n - 1)(x))





share|improve this answer

























  • Great, never knew I could be this simple. Thanks for the explanation! :)

    – Prav
    Mar 27 at 13:31













3












3








3







The suggested solution is needlessly complex. Countless reassignments of variables and a loop are a recipe for a headache. Here's a simplified alternative -



def dual (f, g, n):
if n == 0:
return lambda x: x
else:
return lambda x: f(dual(g, f, n - 1)(x))

add1 = lambda x: 1 + x
add2 = lambda x: 2 + x

print(dual(add1,add2,4)(3))
# 9
# (1 + 2 + 1 + 2 + 3)

print(dual(add1,add2,9)(3))
# 16
# (1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 3)

print(dual(add1,add2,0)(3))
# 3


The reason this works is because in the recursive branch, we call dual with swapped arguments, dual(g,f,n-1). So f and g change places each time as n decrements down to 0, the base case, which returns the identity (no-op) function.



A slightly less readable version, but works identically -



def dual (f, g, n):
return lambda x:
x if n == 0 else f(dual(g, f, n - 1)(x))





share|improve this answer













The suggested solution is needlessly complex. Countless reassignments of variables and a loop are a recipe for a headache. Here's a simplified alternative -



def dual (f, g, n):
if n == 0:
return lambda x: x
else:
return lambda x: f(dual(g, f, n - 1)(x))

add1 = lambda x: 1 + x
add2 = lambda x: 2 + x

print(dual(add1,add2,4)(3))
# 9
# (1 + 2 + 1 + 2 + 3)

print(dual(add1,add2,9)(3))
# 16
# (1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 3)

print(dual(add1,add2,0)(3))
# 3


The reason this works is because in the recursive branch, we call dual with swapped arguments, dual(g,f,n-1). So f and g change places each time as n decrements down to 0, the base case, which returns the identity (no-op) function.



A slightly less readable version, but works identically -



def dual (f, g, n):
return lambda x:
x if n == 0 else f(dual(g, f, n - 1)(x))






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 27 at 6:11









user633183user633183

76.5k21 gold badges149 silver badges190 bronze badges




76.5k21 gold badges149 silver badges190 bronze badges















  • Great, never knew I could be this simple. Thanks for the explanation! :)

    – Prav
    Mar 27 at 13:31

















  • Great, never knew I could be this simple. Thanks for the explanation! :)

    – Prav
    Mar 27 at 13:31
















Great, never knew I could be this simple. Thanks for the explanation! :)

– Prav
Mar 27 at 13:31





Great, never knew I could be this simple. Thanks for the explanation! :)

– Prav
Mar 27 at 13:31








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55369615%2fcomposite-functions-in-python-dual-compose%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript