# Questions tagged [logical-operators]

654 questions

0

votes

1

answer

27

Views

### How to execute a bitwise logical expression which is a string and the operator isn't known before hand

I have to execute a logical expression which is a string.
For example :
string s = "2

2

votes

2

answer

57

Views

### Numbers greater than 11

I have read in a string with a list of numbers. I then have created an array with the length of 3. My question, is how do i get the numbers from the string into the array (It's okay if there are more than 3, less than, or exactly 3 numbers greater 11).
I have tried going through the string spot by s...

1

votes

5

answer

850

Views

### strlen() with logical and comparison operators not working

Ok I am fairly fairly new in PHP and I am trying to make a contact form. There are some fields which I need to be of certain characters.
if (!empty($_POST['title'])) {
$title = $_POST['title'];
}
elseif (strlen($title)>=1||strlen($title)50 {
$error .= "Length of your Subject must be more than 6 char...

1

votes

1

answer

212

Views

### Generating a logical vector from two numeric vectors - R

I'm very new to R and having difficulty trying to generate a logical vector c from two numeric vectors a and b of the same (arbitrary) size where c contains either TRUE or FALSE depending on whether the corresponding elements of vector b are multiples of a.
Ex.
a

1

votes

2

answer

425

Views

### Logical operator (&&) not working locally in php

I'm still a beginner of php and I have come across a bit of a problem with the logical operator &&. I have a token and secret answer script which are both text boxes. When a user submits the token and there answer , the script goes into the database and if all checks clear (error messages etc), then...

1

votes

2

answer

187

Views

### PHP Bizarre behaviour with switch() and logical or (XOR) in a case declaration

NOTE: I am aware that this is not acceptable code, I am seeking to understand what the interpreter is doing, not advice on how else to achieve the same result!
I've since read up enough to realize that I can't and shouldn't be attempting to use |,|| or XOR in defining a switch case—so please don't...

1

votes

2

answer

171

Views

### How to simplify a leading-NA count function, and generalize it to work on matrix, dataframe

I wrote a leading-NA count function, it works on vectors. However:
a) Can you simplify my version?
b) Can you also generalize it to work directly on matrix, dataframe (must still work on individual vector), so I don't need apply()? Try to avoid all *apply functions, fully vectorize, it must still w...

1

votes

1

answer

489

Views

### Playground execution failed: <EXPR>:15:33: error: type 'Int' does not conform to protocol 'BooleanType'

I am creating a simple Fizz Buzz Generator with Swift.
I receive the following error:
Playground execution failed: :15:33: error: type 'Int' does not conform to protocol 'BooleanType'
} else if (number % 3 == 0) && (number % 5) {
Here is what I have:
for number in 1...100 {
if (number % 3 == 0) {
p...

1

votes

1

answer

630

Views

### Write equivalent of x == y using bit-level and logical operations?

What is a C expression equivalent to x == y that only uses bit-level (|,~,^,&) and logical (&&,||,!) operations? It should return 1 when x and y are equal, 0 otherwise.

1

votes

3

answer

67

Views

### Logical operator with Arithmetic operator in C

I came across a question and I wanted to verify whether my assumptions were correct.
Given the following codes:
1. int i = -2, j = 1, ans;
2. ans = i++ || ++j;
3. printf("%d %d %d", i,j, ans);
The output is: -1 1 1
In C language, it seems that only 0 will be treated as false, any other valu...

1

votes

1

answer

182

Views

### PHP FizzBuzz Logic

When we write the fizzbuzz script, why are we testing to see if it is equal to 0? Or am I misunderstanding?
Example: $i % 3 == 0

1

votes

2

answer

32

Views

### Javascript: Why is a ternary expression result returned when placed after a logical OR? [duplicate]

This question already has an answer here:
Precedence: Logical or vs. Ternary operator
2 answers
I can't find an answer to this, after a little research.
Given this:
'Hello' || true ? true : false
The result is true, which to me, doesn't make sense. Because the first value was truthy, I would expect...

1

votes

3

answer

214

Views

### Can logical operator be used with in ternary operators in PHP

Is this statement correct in PHP
$abc = $x === "" || $y !== $z ? "true" : "false";

1

votes

2

answer

118

Views

### PowerShell: Long list of conditions using logial operators elegantly

I think that there must be a more elegant way to get this done
Readability is a plus, and simplicity is beautiful.
I think what I ended up with is somewhat readable.
Can't help but think there's a better way to do this.
Suggestions?
Reading records from a log to find the records which fall into cert...

1

votes

2

answer

445

Views

### Javascript,if condition works without && logical operator when && is present it doesnt work

I want the error message to display if the length of characters in the #nameT id is less than < 3 or greater

1

votes

1

answer

354

Views

### Trouble getting function to return TRUE

I have some code to check to see if the input to a function is a valid US state. I have a CSV file with a State column and those are the only states I care about. So I made this code with a for loop to check if the input matches any of the states in that list, and if so, to return the value TRUE.
va...

1

votes

1

answer

67

Views

### Javascript: double use with = or == sign

I'm currently new to JavaScript and I will appreciate if somebody will explain to me the logic by using twice the equal sign.
For example, I came across that:
noscroll = pageScroll === 0;
window.onmousewheel = document.onmousewheel = wheel;
This is the full script (used to animate element when scro...

1

votes

2

answer

41

Views

### How do I “or” each column in a DataFrame with a vector?

Let's say I have the data below:
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import pandas as pd
from numpy import uint8
vector = pd.Series([1, 0, 0, 1])
df = pd.read_table(StringIO("""a b c
1 0 0
1 1 1
0 1 1
1 1 0"""), sep="\s+", dtype=uint8,...

1

votes

2

answer

35

Views

### Not expected behavior while setting a string with short-circuit evaluation in Javascript

I want to use this short-circuit evaluation to report a nice status of multiple items in an one liner. But the result is not as expected as shown below:
var items = [{
"id": 1,
"available": true
}, {
"id": 2,
"available": false
}, {
"id": 3,
"error": "Server not found for that TLD"
}];
ite...

1

votes

3

answer

82

Views

### PHP If Statement Logic

I am a bit stuck on an if statement on my PHP code.
I know this is probably a basic question for most of you out there, but i am stuck, and i would like some assistance.
I have 2 variables $max and $ min, which i have to compare with 2 other max and mins called $valor and $minimo in order to check i...

1

votes

1

answer

285

Views

### Java method that returns logical operators

Question first, then backstory, as to not make the question seem completly idiotic if it is infact not possible..
QUESTION: Is there any way to write a method that returns || or && or < or >
depending on which implemented subclass is calling the method
I´m currently learning Java and taking a few c...

1

votes

1

answer

1k

Views

### How to create logical variable based on logical condition?

I have a data frame with factor variables
> a b df df$a df$b df
a b
1 a c
2 b b
3 c a
I create new logical variable based on the similarity of var a and var b.
> df$result df
a b result
1 a c FALSE
2 b b FALSE
3 c a FALSE
When I expected
> df
a b result
1 a c FALSE
2 b b TRUE
3 c a FALSE...

1

votes

1

answer

149

Views

### Replacing Data Frame Logicals [duplicate]

This question already has an answer here:
Replace a value in a data frame based on a conditional (`if`) statement
7 answers
I have a Data Frame called "Data" which looks like this:
Jobs Agency Location Date RXH HS TMM Payed
6 RWC Heineken Lightblue EGC 2015-10-10...

1

votes

2

answer

54

Views

### how to implement logical and on array length?

I need to translate the matlab code
indexSelect0 = a.index1==0 & a.index2==wRange;
into a fast python style. My try is:
idx1=np.array(np.where(a['index2'][:,0]==wIndex2))
idx=np.array(np.where(a['index1'][:,0]==wIndex1))
indexSelect0 = ma.masked_array(idx,mask=[not (i in idx1[0,:]) for i in idx[0,:]...

1

votes

1

answer

32

Views

### Behaviour of characters with relational operators

Can someone explain why R does this? And the reason behind it?
"-1" < 0
#[1] TRUE
# expected [1] FALSE # OR better NA
"-abc" < 0
#[1] TRUE
# expected [1] FALSE # OR better NA
From ?Comparison:
If the two arguments are atomic vectors of different types, one is
coerced to the type of the other, the (d...

-1

votes

1

answer

21

Views

### Why does my test pass, even though it doesn't meet my logic gate?

I'm working on telephone validator on FCC. For some reason this passes 5555555555. Why does my logic gate pass this number? For context, this isn't my first attempt at this code. I've added multiple statements, nested if statements, and it still doesn't catch it. Why does this evaluate to true?
f...

3

votes

4

answer

123

Views

### bool and int types in boolean contexts

I have this code in a boolean context:
True and False or 2
Output: 2
The type check for this expression resulted in int.
Next, I modified the code to:
True and False or True
Output : True
And the type check for this expression resulted in bool
Why is the output in the 1st code 2?
Shouldn't th...

3

votes

2

answer

109

Views

### Applying vectorized subsetting across multiple columns in R

I try to find a straight-forward way to vectorize/generalize the subsetting of a data.frame. Let's assume I have a data.frame:
df

1

votes

3

answer

18.3k

Views

### Multiple OR or AND conditions in IF statement

I am having a basic doubt regarding IF statement.
Let's say I want to match string SUN with a character array(size 3).
if(arr[0]!='S' || arr[1]!='U' || arr[2]!='N')
cout

1

votes

5

answer

64

Views

### Evaluation && operator in C

While I was making a program in C, I came across a problem. && is not evaluating the second operand, if first is false. I know this is known as short circuit behavior. But I want second operand to be executed, see the code below to know why?
while(a-- && b--){
//some statements
}
Please tell me diff...

1

votes

2

answer

287

Views

1

votes

2

answer

213

Views

### Ruby combined comparison operator (<=>) and min / max / minmax functions

I understand #max, #min, #minmax. I understand . But how does it work in a block within one of those functions?
That is, what is happening in the third line below? What is doing in #min?
a = %w(albatross dog horse)
a.min #=> "albatross"
a.min { |a, b| a.length...

1

votes

3

answer

1.3k

Views

### using logical operators with characters

I have a df with three thousand rows and I would like to create a new column with zeros or ones depending on the word written in a different one.
I have a function which assesses the entry in a column, and if it matches the word I'm looking for, then a "1" is returned in a new column. Like this:
on...

1

votes

4

answer

99

Views

### How to understand this example of a logical and ternary operator?

I understand that ternary operators are essentially a shortcut for an if-else statement, and I also understand that && is a logical AND. However, I don't understand how the two are combined in the code below.
I tried playing around with the output as well, but it didn't help. How do I interpret the...

1

votes

3

answer

89

Views

### What is the order of operations for 'and' and 'or'?

In Python is this:
def blackjack_check(hand): # hand is a tuple
winning_cards = [10,'Jack','Queen','King']
if hand[0] in winning_cards and hand[1] == 'Ace':
return True
elif hand[0] == 'Ace' and hand[1] in winning_cards:
return True
else:
return False
the same as this...?
def blackjack_check(hand):...

1

votes

2

answer

136

Views

### Numerical equivalent of TRUE is -1?

I am using Intel Fortran in Visual Studio 2012 to compile a Fortran code.
When I try to use logical operators I have noticed that a standalone logical expression results in T or F as expected. However, if I need the numerical T or F (0 or 1), I get a -1 when logical result is T.
For example:
intege...

2

votes

4

answer

5.3k

Views

### What exactly does || mean?

return (empty($neededRole) || strcasecmp($role, 'admin') == 0 || strcasecmp($role, $neededRole) == 0);
What exactly does the || mean in this statement? Can someone put this in english for me.
I promise I've googled this but I guess I don't know what to google for because I can't find anything.
than...

1

votes

1

answer

63

Views

### Autoit Why is (0 <> “Test”) False

I am fetching a numeric value from an HTML table. If it fails to fetch the value I fill the value "NA" instead. Here is the odd part 0 "NA" is false, 0 = "NA" is true, 0 == "NA" is False. I get that = is not case sensitive, and == is, but I thought was case sensitive... So why does it work like th...

1

votes

3

answer

298

Views

### Evaluating p && *p++

I was reading this can be inferred as short form of
if (p) {
*p++;
}
but not quite understanding the logic behind it.
My understanding is if p is false then the operator results in 0 regardless, but if p is any other value then *p++ can be evaluated, is the second portion dereferencing the va...

1

votes

2

answer

257

Views

### Short-circuit evaluation on C

I'm studying C from A Book on C by Kelley-Pohl, and there's this exercise that I don't understand:
int a = 0, b = 0, x;
x = 0 && (a = b = 777);
printf("%d %d %d\n", a, b, x);
x = 777 || (a = ++b);
printf("%d %d %d\n", a, b, x);
They just say to imagine the output and compare it to the real one. I th...