I was thinking why the '=' in '+=' is considered as assignment while '=' in '>=' is not considered as such. There is no importance behind this question but some random thought of a beginner. For example purpose, you can consider that
a = np.array([1,2,3,4,5])
a += 2 # array updated and assigned to a
a>=2 # becomes a boolean indexing filter
a += 2 changes the value of a. It reassigns it's value to be two more than it was before. By the way, += as a whole is the assignment operator, not just the =.
a>=2 does not change the value of a. Yes, it becomes true or false. But 'true' or 'false' is all it is. It does not get assigned to anything. The value of a is as it was before.
You can do b = a>=2. But in that case, = is the assignment operator because it is what assigns the value to b.
Related
I doubt whether it is appropriate to use input variables in functions in cases where the input variable will always be the same.
mynum = int(datetime.today().weekday())
def somefuncion():
result = 3 + mynum
return result
optionA = somefuncion()
def somefunction2(number):
result = 3 + number
return result
optionB = somefunction2(mynum)
print(optionA == optionB) # true
Is there good practice in this respect ? or is it indifferent ?
In your case, it would probably be more appropriate to create constant variables.
MYNUM = 12
MYNUM_PLUS_TREE = MY_NUM + 3
That way, when you modify the value of MYNUM in your development, it automatically modifies the value of all the constant values that are generated from it (here it is MYNUM_PLUS_TREE).
The logic I apply here is the following: if a function always return the same value, then it is a "constant function", as in mathematics. Therefore, using a constant variable is preferable.
If you are sure that you are not going to modify the value of the variable anywhere in the code then you should declare it as a constant and use it that way within the code. i.e. not include it as an input variable.
Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.
i.e
CONSTANT = "Whatever"
in your example:
MYNUM = int(datetime.today().weekday())
def somefuncion():
result = 3 + MYNUM
return result
I'm learning groovy to work on smartthings and found a relatively common command among the various examples and existing code (see below).
Reading the function of the && operator I would think the "&& cmd.previousMeterValue" is superfluous. Or is there some code shortcut I'm missing?
Thanks
John
if (cmd.previousMeterValue && cmd.previousMeterValue != cmd.meterValue) {
do something
}
Not knowing what type previousMeterValue has, this answer is somewhat generic.
Groovy follows common operator precedence, i.e. != is evaluated before &&.
To show it explicitly, the full expression is the same as:
(cmd.previousMeterValue) && (cmd.previousMeterValue != cmd.meterValue)
cmd.previousMeterValue is testing the value for the Groovy-Truth.
Depending on value type, the following might be applicable:
Non-null object references are coerced to true.
Non-zero numbers are true.
So if the value is null or 0, the expression is false.
If the first part of the expression evaluated to false, then the second part is skipped.
The logical && operator: if the left operand is false, it knows that the result will be false in any case, so it won’t evaluate the right operand. The right operand will be evaluated only if the left operand is true.
If the first part of the expression evaluated to true, then cmd.previousMeterValue != cmd.meterValue is evaluated, using the following rule:
In Groovy == translates to a.compareTo(b)==0, if they are Comparable, and a.equals(b) otherwise.
So if value is a number object, then it is evaluated as:
cmd.previousMeterValue.compareTo(cmd.meterValue) != 0
This means that BigDecimal values are compared by value, ignoring specific scale.
I would like to perform a simple increment operation on specific array elements:
Minimal Not-Working Example:
array[1..2] of var 0..1: a = [0, 0];
constraint forall (i in 1..2) (
a[i] = a[i] + 1
);
output ["\(a)"];
solve satisfy;
This produces the minizinc output
WARNING: model inconsistency detected
stack.mzn:3:
in call 'forall'
in array comprehension expression
with i = 1
stack.mzn:4:
in binary '=' operator expression
=====UNSATISFIABLE=====
% stack.fzn:1: warning: model inconsistency detected before search.
Why is this an inconsistency in the model -- why can't I reference the old value of the current array element? Is there some other way to increase the current array element by 1?
I'm new to constraint solving, so I hope this is not a terribly stupid question.
It is important to know that MiniZinc is a declarative language. In a constraint you're not stating an instruction, but you're stating the "truth" as know to the solvers.
That means that an instruction like a = a + 1 will not work because you are stating that we're looking for a value for a that is its own value + 1. Since no such value exist we call the model inconsistent since no solutions can be found.
The idea of the constraint items is to express relations between different variables and parameters. You could for example write: constraint forall(i in N) (a[i] = a[i-1] + 1). This will mean we will look for a value a[i] which is 1 more than a[i-1] for all i in N. (Note that we should probably add an if-statement to make sure i-1 stays within the given bounds)
As a general rule: if there is a literal on one side of an equals signs, using that literal on the other side will create an inconsistent model.
If you still wanted to create a MiniZinc model that increases the values of a given array by one, you could use the following model:
set of int: N = 1..2
array[N] of int: a = [0,1];
array[N] of var int: b;
constraint forall(i in N) (
b[i] = a[i] + 1
);
Since the variables a are now expressed in terms of b, this doesn't violate our rule.
This question has somehow to do with an earlier post from me. See here overlap-of-nested-lists-creates-unwanted-gap
I think that I have found a solution but i can't figure out how to implement it.
First the relevant code since I think it is easier to explain my problem that way. I have prepared a fiddle to show the code:
PYFiddle here
Each iteration fills a nested list in ag depending on the axis. The next iteration is supposed to fill the next nested list in ag but depending on the length of the list filled before.
The generell idea to realise this is as follows:
First I would assign each nested list within the top for-loop to a variable like that:
x = ag[0]
y = ag[1]
z = ag[2]
In order to identify that first list I need to access data_j like that. I think the access would work that way.
data_j[i-1]['axis']
data_j[i-1]['axis'] returns either x,y or z as string
Now I need to get the length of the list which corresponds to the axis returned from data_j[i-1]['axis'].
The problem is how do I connect the "value" of data_j[i-1]['axis'] with its corresponding x = ag[0], y = ag[1] or z = ag[2]
Since eval() and globals() are bad practice I would need a push into the right direction. I couldn't find a solution
EDIT:
I think I figured out a way. Instead of taking the detour of using the actual axis name I will try to use the iterator i of the parent loop (See the fiddle) since it increases for each element from data_j it kinda creates an id which I think I can use to create a method to use it for the index of the nest to address the correct list.
I managed to solve it using the iterator i. See the fiddle from my original post in order to comprehend what I did with the following piece of code:
if i < 0:
cond = 0
else:
cond = i
pred_axis = data_j[cond]['axis']
if pred_axis == 'x':
g = 0
elif pred_axis == 'y':
g = 1
elif pred_axis == 'z':
g = 2
calc_size = len(ag[g])
n_offset = calc_size+offset
I haven't figured yet why cond must be i and not i-1 but it works. As soon as I figure out the logic behind it I will post it.
EDIT: It doesn't work for i it works for i-1. My indices for the relevant list start at 1. ag[0] is reserved for a constant which can be added if necessary for further calculations. So since the relevant indices are moved up by the value of 1 from the beginning already i don't need to decrease the iterator in each run.
I'm pretty new to haskell, but if you make an if statement:
function a b c
| (a+b == 0) = True
| --etc.
| otherwise = False
Is the second if statement the same as an else if in other languages, or is it just another if. I assume its the former as you can only have one output, but I just want to make sure.
The construct you used is called a guard. Haskell checks the given alternatives one after another until one condition yields True. It then evaluates the right hand side of that equation.
You could pretty well write
function n
| n == 1 = ...
| n == 2 = ...
| n >= 3 = ...
thus the guard kinds of represents an if/elseif construct from other languages. As otherwise is simply defined as True, the last
| otherwise =
will always be true and therefore represents a catch-all else clause.
Nontheless, Haskell has a usual a = if foo then 23 else 42 statement.
What you have here is not really an if statement, but rather a guard. But you are right that the second case gets "executed" only if the previous cases (by cases here I mean the expressions between the | and =) did not match (evaluate to True). otherwise is just a synonyme to True (that way it always "matches").
It must be like an else if.
The bottom pattern otherwise is really just True, so if the first match didn't win, you would always get the more specific value and the otherwise value.
Correct. Though you've used guards, the way you've expressed it is more or less identical to using an if-statement. The flow of testing the conditional to yield a result will fall through the guard you've written in the order they were listed in your guard.
(a+b == 0)
Will be checked first
etc.
Will be checked second and so forth, provided no preceding conditional is true.
otherwise
Will be checked last, provided no preceding conditional is true.