difference between a == 10 || 20 and a == 10 || a == 20 these two - logical-operators

let s = 10;
if(s == 10 || s == 20){
console.log(s)
}
if( s == 10 || 20){
console.log(s)
}
// What is the defrence between these two conditions
I tried both condition and the output were the same. So what's the difference between them. It may be the stupid question but i want to konw the difference. Thanks in advance

In the first one IF (s == 10 || s == 20) the entire IF condition is TRUE if either boolean expression s == 10 OR s == 20 is TRUE. As this is processed, once the first boolean expression is TRUE the condition is met so the s==10 triggered that and console.log(s) was called.
In the second condition ( s == 10 || 20) the entire condition is TRUE if either boolean expression s==10 OR 20 is TRUE. It succeeds for the same reason as stated above. Typically a non-zero value means TRUE so in your programming language having a value of twenty there is the same as if you had the keyword TRUE there so no syntax error was thrown, even though it really does not make any sense and is indeed a logic error in the code (assuming you meant it to work the same as the first example).
This is why code reviews are a good idea.

Related

What's the difference between & vs && and | vs || in R? [duplicate]

According to the R language definition, the difference between & and && (correspondingly | and ||) is that the former is vectorized while the latter is not.
According to the help text, I read the difference akin to the difference between an "And" and "AndAlso" (correspondingly "Or" and "OrElse")...
Meaning:
That not all evaluations if they don't have to be (i.e. A or B or C is always true if A is true, so stop evaluating if A is true)
Could someone shed light here?
Also, is there an AndAlso and OrElse in R?
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.
The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.
One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.
When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.
> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3
The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.
Update: The most recent edition of news(“R”) says that supplying vectors of length greater than 1 to && or || is deprecated with a warning and the intent of RCore is to make it an error in a subsequent version of R.
&& and || are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.
For example if the first operand to && is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true and false && false are both false). The same goes for || when the first operand is true.
You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that && is equivalent to AndAlso in VB.NET, which I assume you are referring to.
There are three relevant differences between the operators &&/|| and &/|, which are explained in the official documentation. Here’s a summary:
1. & and | are vectorised
This means that if you want to perform element-wise logical operations on vectors you should use & and |:
a = c(TRUE, TRUE, FALSE, FALSE)
b = c(TRUE, FALSE, TRUE, FALSE)
a | b
# [1] TRUE TRUE TRUE FALSE
a || b
# [1] TRUE
For &&/|| all elements after the first are discarded. Recent versions of R generate a helpful warning when using &&/|| on vectors longer than 1:
In a || b : 'length(x) = 4 > 1' in coercion to 'logical(1)'
2. && and || are short-circuited
Short-circuiting means that the right-hand side of the expression is only evaluated if the left-hand side does not already determine the outcome. Pretty much every programming language does this for conditional operations, since it leads to handy idioms when writing if conditions, e.g.:
if (length(x) > 0L && x[1L] == 42) …
This code relies on short-circuiting: without it, the code would fail if x is empty, since the right-hand side attempts to access a non-existent element. Without short-circuiting, we would have to use nested if blocks, leading to more verbose code:
if (length(x) > 0L) {
if (x[1L] == 42) …
}
As a general rule, inside a conditional expression (if, while) you should always use && and ||, even if short-circuiting isn’t required: it’s more idiomatic, and leads to more uniform code.
3. & and | can perform bitwise arithmetic
In many (most?) programming languages, & and | actually perform bitwise arithmetic instead of Boolean arithmetic. That is, for two integers a and b, a & b calculates the bitwise and, and a | b calculates the bitwise or. For Boolean values there’s no difference between bitwise and logical operations; but for arbitrary integers, the result differs. For instance, 1 | 2 == 3 in most programming languages.
However, this is not true for R: R coerces numeric arguments of & and | to logical values and performs Boolean arithmetic.
… except when both arguments are of type raw:
c(1, 3) | c(2, 4)
# [1] TRUE TRUE
as.raw(c(1, 3)) | as.raw(c(2, 4))
# [1] 03 07
It is worth noting that the operations ! (logical negation) and xor also perform bitwise arithmetic when called with raw arguments.

Time Complexity for the given Tree Recursion problem

I was looking at the first Recursive solution for this problem on Leetcode. Here is the code for the proposed solution.
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
The part of the solution that I do not understand is why the writer of the solution says the time complexity is O(n). Let's say I had the input:
1
/ \
2 2
This is how I trace the call stack in this case:
isMirror(1, 1)
(t1.val == t2.val) returns true
isMirror(2, 2) returns true
(t1.val == t2.val) returns true
isMirror(null, null) return true
isMirror(null, null) return true
isMirror(2, 2) returns true
(t1.val == t2.val) returns true
isMirror(null, null) return true
isMirror(null, null) return true
In the call stack above, isMirror() is called 7 times while n is 3. For the time complexity to be O(n), should isMirror() have only been called 3 times? Or am I looking at this the wrong way? Is it the fact that the call stack only went 3 levels deep that shows that the time complexity is O(n)?
Thank you for the help.
You call the mirror on the null nodes too. So your elements are actually not 3 they are 7. Think the next level on the binary tree and you will see.
Solutions;
Try to check the nullity before calling the function.
it will be still constant factor to your cost. Approximately 2 times. By big O rules you are still O(n).

If statement structure in R - when to use & and && [duplicate]

According to the R language definition, the difference between & and && (correspondingly | and ||) is that the former is vectorized while the latter is not.
According to the help text, I read the difference akin to the difference between an "And" and "AndAlso" (correspondingly "Or" and "OrElse")...
Meaning:
That not all evaluations if they don't have to be (i.e. A or B or C is always true if A is true, so stop evaluating if A is true)
Could someone shed light here?
Also, is there an AndAlso and OrElse in R?
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.
The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.
One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.
When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.
> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3
The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.
Update: The most recent edition of news(“R”) says that supplying vectors of length greater than 1 to && or || is deprecated with a warning and the intent of RCore is to make it an error in a subsequent version of R.
&& and || are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.
For example if the first operand to && is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true and false && false are both false). The same goes for || when the first operand is true.
You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that && is equivalent to AndAlso in VB.NET, which I assume you are referring to.
There are three relevant differences between the operators &&/|| and &/|, which are explained in the official documentation. Here’s a summary:
1. & and | are vectorised
This means that if you want to perform element-wise logical operations on vectors you should use & and |:
a = c(TRUE, TRUE, FALSE, FALSE)
b = c(TRUE, FALSE, TRUE, FALSE)
a | b
# [1] TRUE TRUE TRUE FALSE
a || b
# [1] TRUE
For &&/|| all elements after the first are discarded. Recent versions of R generate a helpful warning when using &&/|| on vectors longer than 1:
In a || b : 'length(x) = 4 > 1' in coercion to 'logical(1)'
2. && and || are short-circuited
Short-circuiting means that the right-hand side of the expression is only evaluated if the left-hand side does not already determine the outcome. Pretty much every programming language does this for conditional operations, since it leads to handy idioms when writing if conditions, e.g.:
if (length(x) > 0L && x[1L] == 42) …
This code relies on short-circuiting: without it, the code would fail if x is empty, since the right-hand side attempts to access a non-existent element. Without short-circuiting, we would have to use nested if blocks, leading to more verbose code:
if (length(x) > 0L) {
if (x[1L] == 42) …
}
As a general rule, inside a conditional expression (if, while) you should always use && and ||, even if short-circuiting isn’t required: it’s more idiomatic, and leads to more uniform code.
3. & and | can perform bitwise arithmetic
In many (most?) programming languages, & and | actually perform bitwise arithmetic instead of Boolean arithmetic. That is, for two integers a and b, a & b calculates the bitwise and, and a | b calculates the bitwise or. For Boolean values there’s no difference between bitwise and logical operations; but for arbitrary integers, the result differs. For instance, 1 | 2 == 3 in most programming languages.
However, this is not true for R: R coerces numeric arguments of & and | to logical values and performs Boolean arithmetic.
… except when both arguments are of type raw:
c(1, 3) | c(2, 4)
# [1] TRUE TRUE
as.raw(c(1, 3)) | as.raw(c(2, 4))
# [1] 03 07
It is worth noting that the operations ! (logical negation) and xor also perform bitwise arithmetic when called with raw arguments.

What does "&&" do?

I can't seem to find the resource I need. What does && do in a code that is comparing variables to determine if they are true? If there is a link with a list of the symbol comparisons that would be greatly appreciated.
example: Expresssion 1: r = !z && (x % 2);
In most programming languages that use &&, it's the boolean "and" operator. For example, the pseudocode if (x && y) means "if x is true and y is true."
In the example you gave, it's not clear what language you're using, but
r = !z && (x % 2);
probably means this:
r = (not z) and (x mod 2)
= (z is not true) and (x mod 2 is true)
= (z is not true) and (x mod 2 is not zero)
= (z is not true) and (x is odd)
In most programming languages, the operator && is the logical AND operator. It connects to boolean expressions and returns true only when both sides are true.
Here is an example:
int var1 = 0;
int var2 = 1;
if (var1 == 0 && var2 == 0) {
// This won't get executed.
} else if (var1 == 0 && var2 == 1) {
// This piece will, however.
}
Although var1 == 0 evaluates to true, var2 is not equals to 0. Therefore, because we are using the && operator, the program won't go inside the first block.
Another operator you will see ofter is || representing the OR. It will evaluate true if at least one of the two statements are true. In the code example from above, using the OR operator would look like this:
int var1 = 0;
int var2 = 1;
if (var1 == 0 || var2 == 0) {
// This will get executed.
}
I hope you now understand what these do and how to use them!
PS: Some languages have the same functionality, but are using other keywords. Python, e.g. has the keyword and instead of &&.
It is the logical AND operator
(&&) returns the boolean value true if both operands are true and returns false otherwise.
boolean a=true;
boolean b=true;
if(a && b){
System.out.println("Both are true"); // Both condition are satisfied
}
Output
Both are true
The exact answer to your question depends on the which language your are coding in. In R, the & operator does the AND operation pairwise over two vectors, as in:
c(T,F,T,F) & c(T,T,F,F)
#> TRUE FALSE FALSE FALSE
whereas the && operator operated only on the first element of each vector, as in:
c(T,F,T,F) && c(T,T,F,F)
#> TRUE
The OR operators (| and ||) behave similarly. Different languages will have different meanings for these operators.
In C && works like a logical and, but it only operates on bool types which are true unless they are 0.
In contrast, & is a bitwise and, which returns the bits that are the same.
Ie. 1 && 2 and 1 && 3 are true.
But 1 & 2 is false and 1 & 3 is true.
Let's imagine the situation:
a = 1
b = 2
if a = 1 && b = 2
return "a is 1 and b is 2"
if a = 1 && b = 3
return "a is 1 and b is 3"
In this situation, because a equals 1 AND b = 2, the top if block would return true and "a is 1 and b is 2" would be printed. However, in the second if block, a = 1, but b does not equal 3, so because only one statement is true, the second result would not be printed. && Is the exact same as just saying and, "if a is 1 and b is 1".

Boolean operators && and ||

According to the R language definition, the difference between & and && (correspondingly | and ||) is that the former is vectorized while the latter is not.
According to the help text, I read the difference akin to the difference between an "And" and "AndAlso" (correspondingly "Or" and "OrElse")...
Meaning:
That not all evaluations if they don't have to be (i.e. A or B or C is always true if A is true, so stop evaluating if A is true)
Could someone shed light here?
Also, is there an AndAlso and OrElse in R?
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.
The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.
One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.
When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.
> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3
The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.
Update: The most recent edition of news(“R”) says that supplying vectors of length greater than 1 to && or || is deprecated with a warning and the intent of RCore is to make it an error in a subsequent version of R.
&& and || are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.
For example if the first operand to && is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true and false && false are both false). The same goes for || when the first operand is true.
You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that && is equivalent to AndAlso in VB.NET, which I assume you are referring to.
There are three relevant differences between the operators &&/|| and &/|, which are explained in the official documentation. Here’s a summary:
1. & and | are vectorised
This means that if you want to perform element-wise logical operations on vectors you should use & and |:
a = c(TRUE, TRUE, FALSE, FALSE)
b = c(TRUE, FALSE, TRUE, FALSE)
a | b
# [1] TRUE TRUE TRUE FALSE
a || b
# [1] TRUE
For &&/|| all elements after the first are discarded. Recent versions of R generate a helpful warning when using &&/|| on vectors longer than 1:
In a || b : 'length(x) = 4 > 1' in coercion to 'logical(1)'
2. && and || are short-circuited
Short-circuiting means that the right-hand side of the expression is only evaluated if the left-hand side does not already determine the outcome. Pretty much every programming language does this for conditional operations, since it leads to handy idioms when writing if conditions, e.g.:
if (length(x) > 0L && x[1L] == 42) …
This code relies on short-circuiting: without it, the code would fail if x is empty, since the right-hand side attempts to access a non-existent element. Without short-circuiting, we would have to use nested if blocks, leading to more verbose code:
if (length(x) > 0L) {
if (x[1L] == 42) …
}
As a general rule, inside a conditional expression (if, while) you should always use && and ||, even if short-circuiting isn’t required: it’s more idiomatic, and leads to more uniform code.
3. & and | can perform bitwise arithmetic
In many (most?) programming languages, & and | actually perform bitwise arithmetic instead of Boolean arithmetic. That is, for two integers a and b, a & b calculates the bitwise and, and a | b calculates the bitwise or. For Boolean values there’s no difference between bitwise and logical operations; but for arbitrary integers, the result differs. For instance, 1 | 2 == 3 in most programming languages.
However, this is not true for R: R coerces numeric arguments of & and | to logical values and performs Boolean arithmetic.
… except when both arguments are of type raw:
c(1, 3) | c(2, 4)
# [1] TRUE TRUE
as.raw(c(1, 3)) | as.raw(c(2, 4))
# [1] 03 07
It is worth noting that the operations ! (logical negation) and xor also perform bitwise arithmetic when called with raw arguments.

Resources