Calculating lists bottom up
I'm trying calculate (using operators) the innermost list then the second innermost list etc. until there is no more lists. I'm also trying to do this so that it should be able to calculate the list no matter how many nested lists that's in it.
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def BINARYEXPR(program, dictionary):
for i in range(len(program)):
if isinstance(program[i],list):
return BINARYEXPR(program[i],dictionary)
operator = operator_dictionary[program[1]]
operand1 = dictionary[program[0]]
print("operand1: ", operand1)
operand2 = dictionary[program[2]]
print("operand2: ", operand2)
return operator(operand1,operand2)
print (BINARYEXPR(lst,dictionary))
So what I wanted to do here was to first calculate x2*x3 (5*7) which should give us 35, then calculate x1*35 (4*35) which should give us 140 and then finally take 140 - x3 (140-7) which should return 133. But instead I only managed to calculate the innermost list and hit return operator(operand1,operand2) which ends the function.
So what I'm stuck at is the recursion as I can't seem to figure out how to move on to the second innermost list whenever the innermost list has been calculated.
python list recursion
add a comment |
I'm trying calculate (using operators) the innermost list then the second innermost list etc. until there is no more lists. I'm also trying to do this so that it should be able to calculate the list no matter how many nested lists that's in it.
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def BINARYEXPR(program, dictionary):
for i in range(len(program)):
if isinstance(program[i],list):
return BINARYEXPR(program[i],dictionary)
operator = operator_dictionary[program[1]]
operand1 = dictionary[program[0]]
print("operand1: ", operand1)
operand2 = dictionary[program[2]]
print("operand2: ", operand2)
return operator(operand1,operand2)
print (BINARYEXPR(lst,dictionary))
So what I wanted to do here was to first calculate x2*x3 (5*7) which should give us 35, then calculate x1*35 (4*35) which should give us 140 and then finally take 140 - x3 (140-7) which should return 133. But instead I only managed to calculate the innermost list and hit return operator(operand1,operand2) which ends the function.
So what I'm stuck at is the recursion as I can't seem to figure out how to move on to the second innermost list whenever the innermost list has been calculated.
python list recursion
add a comment |
I'm trying calculate (using operators) the innermost list then the second innermost list etc. until there is no more lists. I'm also trying to do this so that it should be able to calculate the list no matter how many nested lists that's in it.
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def BINARYEXPR(program, dictionary):
for i in range(len(program)):
if isinstance(program[i],list):
return BINARYEXPR(program[i],dictionary)
operator = operator_dictionary[program[1]]
operand1 = dictionary[program[0]]
print("operand1: ", operand1)
operand2 = dictionary[program[2]]
print("operand2: ", operand2)
return operator(operand1,operand2)
print (BINARYEXPR(lst,dictionary))
So what I wanted to do here was to first calculate x2*x3 (5*7) which should give us 35, then calculate x1*35 (4*35) which should give us 140 and then finally take 140 - x3 (140-7) which should return 133. But instead I only managed to calculate the innermost list and hit return operator(operand1,operand2) which ends the function.
So what I'm stuck at is the recursion as I can't seem to figure out how to move on to the second innermost list whenever the innermost list has been calculated.
python list recursion
I'm trying calculate (using operators) the innermost list then the second innermost list etc. until there is no more lists. I'm also trying to do this so that it should be able to calculate the list no matter how many nested lists that's in it.
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def BINARYEXPR(program, dictionary):
for i in range(len(program)):
if isinstance(program[i],list):
return BINARYEXPR(program[i],dictionary)
operator = operator_dictionary[program[1]]
operand1 = dictionary[program[0]]
print("operand1: ", operand1)
operand2 = dictionary[program[2]]
print("operand2: ", operand2)
return operator(operand1,operand2)
print (BINARYEXPR(lst,dictionary))
So what I wanted to do here was to first calculate x2*x3 (5*7) which should give us 35, then calculate x1*35 (4*35) which should give us 140 and then finally take 140 - x3 (140-7) which should return 133. But instead I only managed to calculate the innermost list and hit return operator(operand1,operand2) which ends the function.
So what I'm stuck at is the recursion as I can't seem to figure out how to move on to the second innermost list whenever the innermost list has been calculated.
python list recursion
python list recursion
asked Nov 19 '18 at 20:56
Programming_ZeusProgramming_Zeus
134
134
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
A recursive function as follows should do the job:
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def calc(lst):
if type(lst) == str:
return dictionary[lst]
if len(lst) != 3:
raise ValueError("Incorrect expression: {}".format(lst))
op = operator_dictionary[lst[1]]
return op(calc(lst[0]), calc(lst[2]))
Since you are using infix notation, each expression has three components: expression, operator, expression. The function works by assuming the 0th and 2nd elements are operands and the 1st element is the operator. We calculate the sub-expressions recursively, and then apply the operation. Also, if at any point our function receives a list with length different than 3, we throw since this cannot be a well-formed expression.
I don't think giving the user a completely different solution is an appropriate answer to their question.
– ritlew
Nov 19 '18 at 21:09
@ritlew What do you mean by a completely different answer? The only main difference between this one and the one OP originally written is that they have forgotten the recursive call to the function, which I provide.
– eozd
Nov 19 '18 at 21:11
You didn't fix the users code, you provided your own to accomplish the same task that the user was trying to code for themselves. Your code looks nothing like OP's.
– ritlew
Nov 19 '18 at 21:15
Great solution, thank you!
– Programming_Zeus
Nov 19 '18 at 21:26
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382502%2fcalculating-lists-bottom-up%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
A recursive function as follows should do the job:
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def calc(lst):
if type(lst) == str:
return dictionary[lst]
if len(lst) != 3:
raise ValueError("Incorrect expression: {}".format(lst))
op = operator_dictionary[lst[1]]
return op(calc(lst[0]), calc(lst[2]))
Since you are using infix notation, each expression has three components: expression, operator, expression. The function works by assuming the 0th and 2nd elements are operands and the 1st element is the operator. We calculate the sub-expressions recursively, and then apply the operation. Also, if at any point our function receives a list with length different than 3, we throw since this cannot be a well-formed expression.
I don't think giving the user a completely different solution is an appropriate answer to their question.
– ritlew
Nov 19 '18 at 21:09
@ritlew What do you mean by a completely different answer? The only main difference between this one and the one OP originally written is that they have forgotten the recursive call to the function, which I provide.
– eozd
Nov 19 '18 at 21:11
You didn't fix the users code, you provided your own to accomplish the same task that the user was trying to code for themselves. Your code looks nothing like OP's.
– ritlew
Nov 19 '18 at 21:15
Great solution, thank you!
– Programming_Zeus
Nov 19 '18 at 21:26
add a comment |
A recursive function as follows should do the job:
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def calc(lst):
if type(lst) == str:
return dictionary[lst]
if len(lst) != 3:
raise ValueError("Incorrect expression: {}".format(lst))
op = operator_dictionary[lst[1]]
return op(calc(lst[0]), calc(lst[2]))
Since you are using infix notation, each expression has three components: expression, operator, expression. The function works by assuming the 0th and 2nd elements are operands and the 1st element is the operator. We calculate the sub-expressions recursively, and then apply the operation. Also, if at any point our function receives a list with length different than 3, we throw since this cannot be a well-formed expression.
I don't think giving the user a completely different solution is an appropriate answer to their question.
– ritlew
Nov 19 '18 at 21:09
@ritlew What do you mean by a completely different answer? The only main difference between this one and the one OP originally written is that they have forgotten the recursive call to the function, which I provide.
– eozd
Nov 19 '18 at 21:11
You didn't fix the users code, you provided your own to accomplish the same task that the user was trying to code for themselves. Your code looks nothing like OP's.
– ritlew
Nov 19 '18 at 21:15
Great solution, thank you!
– Programming_Zeus
Nov 19 '18 at 21:26
add a comment |
A recursive function as follows should do the job:
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def calc(lst):
if type(lst) == str:
return dictionary[lst]
if len(lst) != 3:
raise ValueError("Incorrect expression: {}".format(lst))
op = operator_dictionary[lst[1]]
return op(calc(lst[0]), calc(lst[2]))
Since you are using infix notation, each expression has three components: expression, operator, expression. The function works by assuming the 0th and 2nd elements are operands and the 1st element is the operator. We calculate the sub-expressions recursively, and then apply the operation. Also, if at any point our function receives a list with length different than 3, we throw since this cannot be a well-formed expression.
A recursive function as follows should do the job:
import operator
lst = [['x1', '*', ['x2', '*', 'x3']], '-', 'x3']
dictionary = {'x1': 4, 'x2': 5, 'x3': 7}
operator_dictionary = {"+": operator.add, "-": operator.sub, "*":
operator.mul, "/": operator.truediv}
def calc(lst):
if type(lst) == str:
return dictionary[lst]
if len(lst) != 3:
raise ValueError("Incorrect expression: {}".format(lst))
op = operator_dictionary[lst[1]]
return op(calc(lst[0]), calc(lst[2]))
Since you are using infix notation, each expression has three components: expression, operator, expression. The function works by assuming the 0th and 2nd elements are operands and the 1st element is the operator. We calculate the sub-expressions recursively, and then apply the operation. Also, if at any point our function receives a list with length different than 3, we throw since this cannot be a well-formed expression.
answered Nov 19 '18 at 21:07
eozdeozd
8941515
8941515
I don't think giving the user a completely different solution is an appropriate answer to their question.
– ritlew
Nov 19 '18 at 21:09
@ritlew What do you mean by a completely different answer? The only main difference between this one and the one OP originally written is that they have forgotten the recursive call to the function, which I provide.
– eozd
Nov 19 '18 at 21:11
You didn't fix the users code, you provided your own to accomplish the same task that the user was trying to code for themselves. Your code looks nothing like OP's.
– ritlew
Nov 19 '18 at 21:15
Great solution, thank you!
– Programming_Zeus
Nov 19 '18 at 21:26
add a comment |
I don't think giving the user a completely different solution is an appropriate answer to their question.
– ritlew
Nov 19 '18 at 21:09
@ritlew What do you mean by a completely different answer? The only main difference between this one and the one OP originally written is that they have forgotten the recursive call to the function, which I provide.
– eozd
Nov 19 '18 at 21:11
You didn't fix the users code, you provided your own to accomplish the same task that the user was trying to code for themselves. Your code looks nothing like OP's.
– ritlew
Nov 19 '18 at 21:15
Great solution, thank you!
– Programming_Zeus
Nov 19 '18 at 21:26
I don't think giving the user a completely different solution is an appropriate answer to their question.
– ritlew
Nov 19 '18 at 21:09
I don't think giving the user a completely different solution is an appropriate answer to their question.
– ritlew
Nov 19 '18 at 21:09
@ritlew What do you mean by a completely different answer? The only main difference between this one and the one OP originally written is that they have forgotten the recursive call to the function, which I provide.
– eozd
Nov 19 '18 at 21:11
@ritlew What do you mean by a completely different answer? The only main difference between this one and the one OP originally written is that they have forgotten the recursive call to the function, which I provide.
– eozd
Nov 19 '18 at 21:11
You didn't fix the users code, you provided your own to accomplish the same task that the user was trying to code for themselves. Your code looks nothing like OP's.
– ritlew
Nov 19 '18 at 21:15
You didn't fix the users code, you provided your own to accomplish the same task that the user was trying to code for themselves. Your code looks nothing like OP's.
– ritlew
Nov 19 '18 at 21:15
Great solution, thank you!
– Programming_Zeus
Nov 19 '18 at 21:26
Great solution, thank you!
– Programming_Zeus
Nov 19 '18 at 21:26
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382502%2fcalculating-lists-bottom-up%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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