and operator with random - python-3.x

i dont understand why the code bellow doesnt work properly. If both variables a and b < 0 it should print that both numbers are negative,else the last message. But it just dont work so, what am i doing wrong? please help!
import random
while True:
input()
a=random.randint(-9,9)
b=random.randint(-9,9)
print(a,b)
if a and b < 0:
print("2 negative numbers:",a,b)
else:
print("one or both of the numbers are positive!")
I'm running this on python 3.4.

I think you're a little confused about how operators distribute.
When you have
if a and b < 0
it doesn't mean
if (both a and b) < 0
but instead
if (a) and (b < 0)
which is equivalent to
if (a != 0) and (b < 0)
since "numeric zero of all types ... evaluates to false" (see the reference on booleans on docs.python.org)
Instead, you want
if a < 0 and b < 0
which will tell you if both a and b are less than zero.

Evaluating Both Operands will resolve the issue. Here both Operands are expressions which results in true or false, so if both result in true; you will get your required result.
if ((a < 0) and (b < 0)):

You are evaluating just a, not it's relation to 0:
if a < 0 and b < 0:

This:
a and b < 0:
Is equivalent to this:
(a) and (b < 0):
(a) is False when a equals 0 and True otherwise. Therefore, due to short-circuiting b < 0 isn't even evaluated.
As a fix you may use all method:
all(i < 0 for i in (a, b))

Related

Difference between `==` and `and`

def pos_neg(a, b, negative):
if negative:
return (a < 0 and b < 0)
else:
return ((a < 0 == b > 0) or (a > 0 == b < 0))
so basically I tried some basic problems.
I just started out and went to https://codingbat.com/prob/p162058 to try it and don't understand why if I were to replace the '==' with 'and' it would work? Thanks.
Oh, I got it now, thanks guys. :D
(this python community is fire!!!)
Since you're learning, you might be interested in seeing that this is an equivalent function.
basically it does a bit wise & and returns true if the result is < 0
else a bit wise exclusive or and returns true if the result is < 0
def pos_neg(a , b, negative):
if negative:
return (a & b) < 0 # both sign bits set (i.e. neg), return true
else:
return (a ^ b) < 0 # different signs, return true
In both cases, it is the sign bit of the result that is of concern. If the bit is set then the value will be negative (hence the comparison to < 0)
and is a logical operator and returns true only when both the expressions we are using it on are true.
== is used for comparisons and returns true when both expressions are equal; they don't need to be true.
To give you an example False == False will return True but False and False will return False.
This "==" means equals to, belonging to Python Comparison Operators, used to compare two values.
and language keyword "and" it is for Python Logical Operators used to combine conditional statements.
You should check out this, it may solve others doubts you have.
W3Schools
All your relational operator usages (i.e. a < 0, b < 0, etc.) result to a boolean value and thus these are known as boolean expressions.
When you put a < 0, think of it like a test of: "is a less than 0, true or false?".
So, if both a and b are negative (i.e. less than zero), their expressions will return true.
So on the line return a < 0 and b < 0, replacing and with == is like saying return true == true. Without the change it'd be return true and true.
Note: This does not mean == is the same as and. == checks for equality of the left-hand side to the right-hand side (e.g. 1 == 1) and gives a true or false value depending on the result of equality. and checks for if the left-hand side results to a true statement and if the right-hand side results to a true statement in order to result to a true expression.

recursive solution for coin change problem

i need to write an algorithm that receives a number and a list of numbers and returns the number of possible combinations of numbers from the list that can create the sum number. for example: def coin(5,[1,2,5,6] should return the number 4 because there are 4 possible combinations from the list that can create together the number 5. below there is the code that i tried but it does not work. the output is 6 instead of 4 and i would love some help in understanding why.
def coin(n,lst):
if n<=1:
return 1
else:
total=0
for i in range(len(lst)):
change=lst[i]
if change>n:
continue
else:
result=coin(n-change,lst[i:])
if result>0:
total+=result
return total
print(coin(5,[1,2,5,6]))
The mistake is in the base case:
if n<=1:
return 1
This is only valid if 1 is one of the allowed coins. But in your recursive case, you slice the list at lst[i:], so not all coins will be allowed every time. Sometimes, 1 isn't one of the allowed coins, in which case there are zero ways to make a total of 1, not one way. To fix it, write something like:
if n <= 1:
if n == 0 or n in lst:
return 1
else:
return 0
This is correct because you can make change for n in the base case either if n is 0 (we can always make 0), or if n is 1 and 1 is one of the allowed coins.
That said, it would be simpler to let the recursive case handle 1, so the base case only needs to handle 0; this is also correct:
if n == 0:
return 1
int coinCount( int C[], int m, int n )
{
// if n is 0 return 1
if (n == 0)
return 1;
// If n is less than 0 then no solution exists
if (n < 0)
return 0;
// If there are no coins and n is greater than 0, then no solution exists
if (m <=0 && n > 0)
return 0;
return coinCount( C, m - 1, n ) + coinCount( C, m, n-C[m-1] );
}

Can anyone explain this code from "codebat"?

I was solving some beginner problem at "codebat". Then I came up with this problem. I couldn't solve this so I viewed the solution. They showed me this.
Can anyone explain the code?
Problem:Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative.
def pos_neg(a, b, negative):
if negative:
return (a < 0 and b <0)
else:
return((a < 0 and b >0) or (a > 0 and b < 0))
The condition if negative checks whether negative is true or false:
If negative is true, then the function returns the result of (a < 0 and b <0), which is true if and only if both values are negative.
If negative is false, then the function returns the result of (a < 0 and b >0) or (a > 0 and b < 0), which is true if one is negative and the other positive.

If elif one liner

if i == len(a):
tempList.extend(b[j:])
break
elif j == len(b):
tempList.extend(a[i:])
break
I am using this in a mergesort-program in Python. Is there any way to put this into a oneliner?
Maybe, but let's give a dedicated non-answer: don't even try.
You don't write your code to be short. You write it so that:
it gets the job done in a straight forward manner
it clearly communicates its meaning to human readers
The above code does that already.
In other words: of course being precise is a valuable property of source code. So, when you have to equally readable pieces of code doing the same thing, and one version is a one-liner, and the other is way more lengthy - then you go for the short version.
But I very much doubt that the above can be expressed as readable as above - with less code.
You can use and and or boolean operations to make a pretty readable one-liner:
l = []
a = [1,2,3,4]
b = [8,9,10]
i = 4
j = 2
l.extend(i == len(a) and b[j:] or j == len(b) and a[i:] or [])
l == [10]
i = 0
j = 3
l.extend(i == len(a) and b[j:] or j == len(b) and a[i:] or [])
l == [10, 1, 2, 3, 4]
This example uses next properties:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
We have to add or [] to mitigate TypeError: 'bool' object is not iterable exception raised when i == len(a) and j > len(b) (e.g. i == 4 and j == 5).
I'd still prefer an expanded version though.

Comprehension - Nested if-conditions in Haskell

i try to become familiar with the if-condition statements in haskell
assume that i´ve an argument x and i try the following in haskell
functionname x = if x > 0 then x-5
if x-5 == 0 then 1
else if x-5 /= 0 then functionname x-5
else if x-5 < then 0
so, the idea was to subtract 5 from x, check if the result is 0, if yes, then give a 1.
If not then invoke the function again with the expression x-5.
If the result of x-5 is negative then give a 0.
so, my questions: Would that be correct? Because when i try that, i´ve got a message like parse error on input 'functionname'.
how can i fix that problem? Are the if-else conditions wrong ?
programm :: Int -> Bool
programm x | x > 0 =
if z == 0 then True
else if z < 0 then False
else programm z
where
z = z-2
programm x | x < 0 =
if z == 0 then True
else if z > 0 then False
else programm z
where
z = z+2
so, i wanted to have the possibility to decide of a given number is even. So, i modify your solution a little bit. its the same but, at the beginning of the two declarations i said : x > 0 = .... and x < 0 =...
Because i want to say that for example -4 is also even. for that reason: the first declarations should handle the positive even numbers and the second declarations handles the negative even numbers.
when i give that to the compiler, then the message : Exception appears. Where i ve made the mistake?
Use guards to make things clear:
functionname x
| x > 0 = x - 5
| x - 5 == 0 = 1
| x - 5 /= 0 = functionname (x - 5)
| x - 5 < 0 = 0
Every if needs to have an else clause associated with it.
The very first one doesn't and the very last one doesn't either.
This works just fine:
functionname x = if x > 0 then x-5
else if x-5 == 0 then 1
else if x-5 /= 0 then functionname x-5
else if x-5 < 0 then 0 else 1
so, the idea was to subtract 5 from x, check if the result is 0, if
yes, then give a 1. If not then invoke the function again with the
expression x-5. If the result of x-5 is negative then give a 0.
That might be written like this:
functionname x =
if x' == 0 then 1
else if x' < 0 then 0
else functionname x'
where
x' = x - 5
Here, I use a where clause to locally define x' as x - 5 and then use it for the tests and the recursive call. Your first branch, if x > 0 then x-5, does not appear in your description of what function should do (it gives x - 5 results as result whenever x is larger than zero, which is probably not what you want). Also, note that every if needs an else as well as a then.
so, i wanted to have the possibility to decide of a given number is
even. So, i modify your solution a little bit. its the same but, at
the beginning of the two declarations i said : x > 0 = .... and x < 0
=... Because i want to say that for example -4 is also even. for that reason: the first declarations should handle the positive even numbers
and the second declarations handles the negative even numbers.
First of all, in the second version of your function the definition in the where clause should be z = x + 2, as z = z + 2 will not terminate. This being an evenness test, you also want to perform the tests on x rather than z. With that fixed, your solution with nested conditionals should work fine (note, however, that you are not treating the x == 0 case; the first guard should be x >= 0). There is a more elegant way of writing the function, though:
myEven :: Int -> Bool
myEven x = myEven' (abs x)
where
myEven' x
| x == 0 = True
| x < 0 = False
| otherwise = myEven' (x - 2)
abs is the familiar absolute value function, while myEven' amounts to the x > 0 branch of your original definition. Taking the absolute value of x is the easiest way to avoid writing two nearly equal branches to handle the negative and non-negative cases.
N.B.: While this is probably just a learning exercise, if you ever need to find whether a number is even there is an even function available from the Prelude. There is also mod if you need to test divisibility for other numbers.

Resources