Why is my conditional expression != ignored? - conditional-statements

Here's my Fibonacci code using python 3.5
z = 0
x = 0
y = 1
while z != 317811:
x = x + y
z = x
print (z)
y = x + y
z = y
print (z)
I am wondering why this prints to infinity when setting the condition to
z != 317811
but works when it is below this number like
z != 196418
or a number greater than this like
z!= 514229
I tried a different approach (z <= 317811) but it prints up to 514229.
Thank you for your time.
KD

You're only testing alternate Fibonnaci numbers as the stopping condition: 317811 is getting missed.
One fix would be to test both x and y.

this is just logical problem
you are printing two
z != 317811
for this condition
"z"
is updated twice once in first z assignment i.e z = x
but "z" again get updated at second assignment z = y and then "z" is not sutisfying the condition(z != 317811) and not equal to 317811 but it is now 514229
Note: it will always work for number being printed at the second steps as this value of Z will be compared in while condition in loop

You are increasing z value twice a loop, but only checking once.
What actually is happening is that z is increasing with the fibonacci serie. Last values of z are:
196418
317811
514229
But you are only checking the stop condition once every two assignment. In this case you are checking that 196418 != 317811 and 514229 != 317811, thus never matching it.
One possible fix could be to test if z != 317811 after the first print. Even if in this case I would prefer testing "<" instead of "!="

Related

i am new, program gives error "there are no type variables left in list"

How the game works is that there is a 3-digit number, and you have to guess it. If you guess a digit in the right spot, you get a strike, and if you guess a digit but in the wrong spot you get a ball. I've coded it like this.
x = random.randint(1, 9)
y = random.randint(1, 9)
z = random.randint(1, 9)
userguessunlisted = input('What number do you want to guess?')
numbertoguess = list[x, y, z]
userguess = list(userguessunlisted)
b = 0
s = 0
while 0 == 0:
if userguess[0] == numbertoguess[0]:
s = s + 1
if userguess[0] == numbertoguess[1]:
b = b + 1
if userguess[0] == numbertoguess[2]:
b = b + 1
if userguess[1] == numbertoguess[0]:
b = b + 1
if userguess[1] == numbertoguess[1]:
s = s + 1
if userguess[1] == numbertoguess[2]:
b = b + 1
if userguess[2] == numbertoguess[0]:
b = b + 1
if userguess[2] == numbertoguess[1]:
b = b + 1
if userguess[2] == numbertoguess[2]:
s = s + 1
print(s + "S", b + "B")
if s != 3:
b = 0
s = 0
else:
print('you win!')
break
When you said list[x, y, z] on line 5, you used square brackets, which python interprets to be a type annotation. For example, if I wanted to specify that a variable is a list of ints, I could say
my_list_of_ints: list[int] = [1, 2, 3]
I think what you meant to do is create a new list from x, y, and z. One way to do this is
numbertoguess = list([x, y, z])
which is probably what you meant to write. This is valid because the list function takes an iterable as its one and only argument.
However, the list portion is redundant; square brackets on the right-hand side of an assignment statement already means "create a list with this content," so instead you should simply say
numbertoguess = [x, y, z]
A few other notes:
input will return a string, but you are comparing that string to integers further down, so none of the comparisons will ever be true. What you want to say is something like the following:
while True:
try:
userguessunlisted = int(input('What number do you want to guess?'))
except:
continue
break
What this code does is attempts to parse the string returned from input into an int. If it fails to do so, which would happen if the user inputted something other than a valid integer, an exception would be thrown, and the except block would be entered. continue means go to the top of the loop, so the input line runs repeatedly until a valid int is entered. When that happens, the except block is skipped, so break runs, which means "exit the loop."
userguessunlisted is only ever going to contain 1 number as written, so userguess will be a list of length 1, and all of the comparisons using userguess[1] and userguess[2] will throw an IndexError. Try to figure out how to wrap the code from (1) in another loop to gather multiple guesses from the user. Hint: use a for loop with range.
It might also be that you meant for the user to input a 3-digit number all at once. In that case, you can use a list comprehension to grab each character from the input and parse it into a separate int. This is probably a bit complicated for a beginner, so I'll help you out:
[int(char) for char in input('What number do you want to guess?')]
print(s + "S", b + "B") will throw TypeError: unsupported operand type(s) for +: 'int' and 'str'. There are lots of ways to combine non-string types with strings, but the most modern way is using f-strings. For example, to combine s with "S", you can say f"{s}S".
When adding some amount to a variable, instead of saying e.g. b = b + 1, you can use the += operator to more concisely say b += 1.
It's idiomatic in python to use snake_case for variables and Pascal case for classes. So instead of writing e.g. numbertoguess, you should use number_to_guess. This makes your code more readable and familiar to other python programmers.
Happy coding!

How to convert the following if conditions to Linear integer programming constraints?

These are the conditions:
if(x > 0)
{
y >= a;
z <= b;
}
It is quite easy to convert the conditions into Linear Programming constraints if x were binary variable. But I am not finding a way to do this.
You can do this in 2 steps
Step 1: Introduce a binary dummy variable
Since x is continuous, we can introduce a binary 0/1 dummy variable. Let's call it x_positive
if x>0 then we want x_positive =1. We can achieve that via the following constraint, where M is a very large number.
x < x_positive * M
Note that this forces x_positive to become 1, if x is itself positive. If x is negative, x_positive can be anything. (We can force it to be zero by adding it to the objective function with a tiny penalty of the appropriate sign.)
Step 2: Use the dummy variable to implement the next 2 constraints
In English: if x_positive = 1, then y >= a
However, if x_positive = 0, y can be anything (y > -inf)
y > a - M (1 - x_positive)
Similarly,
if x_positive = 1, then z <= b
z <= b + M * (1 - x_positive)
Both the linear constraints above will kick in if x>0 and will be trivially satisfied if x <=0.

Multy If Not Statment VB

If x = y And Not (z(0) = w(0) And z(1) = w(1) And z(2) = w(2)) then .....
I want to test if x = y and z(0) is not equal to w(0) and z(1) is not equal to w(0) and z(2) is not equal to w(2). Basicly if x=y and any of the rest is not equal to the other it should do the code in the if-statement
Will one And Not (....) work ?
Let me know if you have alternative solutions or if this will work thanks for the help
Your code is not doing what you say you want. It is checking if x = y and any of the other terms are unequal. Think about it, your if statement is asking if two things are true, the first is that x = y and the second is that the expression in parentheses is not true (and the expression in parentheses will not be true if and of the z and w terms are unequal).
If you want to check that all the other terms are unequal, you need
If x = y And z(0) <> w(0) And z(1) <> w(1) And z(2) <> w(2) then ...

What is the difference between == and <= in this case

I was working on making a game, and I was wondering why the construct with the == operator doesn't work while the lower one does. I used an NSLog message afterwards to test.
if (pipe.position.x == bird.position.x){ no idea why this doesn't work
if ((pipe.position.x <= bird.position.x) & (pipe.position.x > bird.position.x - 1)){
This is because one (or both) of the position.x's are a floating-point2 value with a non-zero difference1 between the two position values such that only the second condition is true.
Since p <= b is true for all values that make p == b true, to see why this works "unexpectedly" let's choose some values such that the expression p == b is false2 yet p < b is true and p > b - 1 is true.
Given p = 3.2 (pipe) and b = 3.7 (bird), as an example, then
p == b
-> 3.2 == 3.7
-> false
but
(p <= b) & (p > b - 1)
-> (3.2 <= 3.7) & (3.2 > 3.7 - 1)
-> (3.2 <= 3.7) & (3.2 > 2.7)
-> true & true
-> true
Instead, to detect when the bird "is crossing" the pipe, assuming that x increases to the right, consider
// The bird's head to the "right" of the pipe leading edge..
bird_x >= pipe_x
// ..but bird's butt is not to the "right" of the pipe trailing edge.
// (Also note use of the &&, the logical-AND operator)
&& (bird_x - bird_width <= pipe_x + pipe_width)
Of course, using a non-rectangle (or forgiving overlap) collision detection would lead to less frustrating flapping!
1 This issue occurs because there are some particular floating-point values (but there are no integer values) which can cause the observed effect.
First, reiterate the assumption that p is not equal to b, given that the first condition does not succeed. Let's suppose then that p <= b is written as p == b || p < b but since p == b is false , we can write it as p < b by tautology.
Since both clauses in the second condition are true (such that true && true -> true), we have the rules: 1) p < b is true, and 2) p > b - 1 is true.
Rewriting p < b as p - b < 0 and p > b - 1 as p - b > -1, and then replacing p - b with x yields: x < 0 and x > -1. However, there is no integer value of x which satisfies -1 < x < 0.
(In first section, where p = 3.2 and b = 3.7, x = (p - b) = 0.5 which satisfies the given constraints when x is not restricted to an integer value.)
2 With all above aside, it is possible for p and b to be "very close but different" floating-point values such that there is a non-zero difference between them - due to rounding, they may even be displayed as the same integer value! See How dangerous is it to compare floating point values? and related questions for the cause and "odd" behavior of such when using ==.
If this is the case then round to integer values and use an integer comparison, or; rely entirely on relational comparison such as shown in the proposed condition, or; use epsilon comparison for "nearly equal" of floating-point values.
if you choose abs(pipe.position.x) == abs(bird.position.x) the first condition may satisfy.

Not Equal to This OR That in Lua

I am trying to verify that a variable is NOT equal to either this or that. I tried using the following codes, but neither works:
if x ~=(0 or 1) then
print( "X must be equal to 1 or 0" )
return
end
if x ~= 0 or 1 then
print( "X must be equal to 1 or 0" )
return
end
Is there a way to do this?
Your problem stems from a misunderstanding of the or operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1, but I'll go into a little more detail about why your attempted solution doesn't work.
When you read x ~=(0 or 1) or x ~= 0 or 1 it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.
However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or has a lower precedence than ~=, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.
As a result, when evaluating x ~=(0 or 1), the interpreter will first compute 0 or 1 (because of the parentheses) and then x ~= the result of the first computation, and in the second example, it will compute x ~= 0 and then apply the result of that computation to or 1.
The logical operator or "returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~= is the inverse of the equality operator ==; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.
Using these rules, x ~=(0 or 1) will decompose to x ~= 0 (after applying the or operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1 will first evaluate x ~= 0 (which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1 or true or 1. In the first case, the statement will return 1, and in the second case, the statement will return true. Because control structures in Lua only consider nil and false to be false, and anything else to be true, this will always enter the if statement, which is not what you want either.
There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:
if x ~= 1 and x ~= 0 then
print( "X must be equal to 1 or 0" )
return
end
Alternatively, you can use a loop to check these values:
local x_is_ok = false
for i = 0,1 do
if x == i then
x_is_ok = true
end
end
if not x_is_ok then
print( "X must be equal to 1 or 0" )
return
end
Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)
if not (x >= 0 and x <= 1 and math.floor(x) == x) then
print( "X must be equal to 1 or 0" )
return
end
Note that I wrote x >= 0 and x <= 1. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1, and what this erroneous expression would return!
For testing only two values, I'd personally do this:
if x ~= 0 and x ~= 1 then
print( "X must be equal to 1 or 0" )
return
end
If you need to test against more than two values, I'd stuff your choices in a table acting like a set, like so:
choices = {[0]=true, [1]=true, [3]=true, [5]=true, [7]=true, [11]=true}
if not choices[x] then
print("x must be in the first six prime numbers")
return
end
x ~= 0 or 1 is the same as ((x ~= 0) or 1)
x ~=(0 or 1) is the same as (x ~= 0).
try something like this instead.
function isNot0Or1(x)
return (x ~= 0 and x ~= 1)
end
print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )