Check if two variables are equal from three choices [duplicate] - python

This question already has answers here:
Python: determining whether any item in sequence is equal to any other
(5 answers)
Closed 3 years ago.
I have three integers, and I need to check if two of them are equal. The code I have is quite ugly:
a = 5
b = 7
c = 5
if a == b or b == c or a == b:
pass
I wonder if there is a better alternative to this kind of comparation.

You could just build a set and check the resulting length:
a = 5
b = 7
c = 5
if len({a,b,c}) < 3:
pass
Since you mention in your real case the variables are lists, you could convert them to tuples which are hashable and hence can build a set from them. So instead you could do:
a = [5, 2]
b = [7, 2]
c = [5, 2]
if len(set(map(tuple, [a,b,c]))) < 3:
pass

Because you are having lists, you won't be able to use a set directly. If so, you will get an error:
TypeError: unhashable type: 'list'
Convert your lists to tuples, then use the following:
if len(set([tuple(a),tuple(b), tuple(c)])) < 3:
pass

Related

Changing a collection.Counter during enumeration? [duplicate]

This question already has answers here:
How does a for loop evaluate its argument
(3 answers)
Closed 6 years ago.
counter = Counter()
// fill data into counter
for a, b in counter.most_common():
if (b > 1):
counter[a] = np.log(b)
else:
counter[a] = -np.log((1 / (b+0.01)))
As I see, this is safe, based on my trial. No bad thing happens when I change the collection while I am enumerating it. In other languages, in each cycle of the for, the counter.most_common() value is evaluated.
Doesn't this happen in Python as well?
No, it doesn't. A more illustrative example:
def example():
print("Ping")
return [1,2,3,4]
for x in example():
print(x)
Output:
Ping
1
2
3
4

Find which variable equals a value [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 years ago.
I have a list of variables in Python:
a = 1
b = 0
c = 0
These come from part of a script that gets user input for certain fields to process, so 1 means "do something to 'a'" and 0 means "do not include." So it would be useful to know which fields need to be used later in the script, i.e. which of them equal 1.
What's the best way to find which of a, b or c is equal to 1?
I tried this method (from here):
test_list = [a,b,c]
next((x for x in test_list if x == 1), None)
Which returns 1, but I'm looking for it to return a. This is precondition, the next step in the script takes the variables that equal 1 and does something with them, by variable name rather than value.
I could do it long-hand like this:
if a == 1:
print "a"
if b == 1:
...
but I suspect there's a nice Pythonic way to find the name of a variable from a list of variables that equals a specific value.
You should consider using a dictionary (a mapping) instead of a list, as names only reference objects but are not the objects themselves:
d = dict(a = 1, b = 2, c = 0)
print(next((k for k, v in d.items() if v == 1), None))
# a

what is difference between [None] and [] in python? [duplicate]

This question already has answers here:
What is a None value?
(9 answers)
Is there a difference between "==" and "is"?
(13 answers)
Closed 6 years ago.
I think [None] is same as [], but in my test , maybe there is something...
>>>print len([])
0
>>>print len([None])
1
when should i use the None ? and []
and another interesting question
>>>c= []
>>>d= []
>>>print c is d
False
>>>a= 1
>>>b=1
print a is b
True
why empty list's id granting that is different?
[] is an empty list
[None] is a list with one element. That one element is None
is checks for reference equality. If both objects refer to the same object by reference then is will return true.
a = []
b = a
a is [] #false
a is b #true
[None] does not mean that there is nothing in the list. None is a keyword in python which has a special meaning. It is like NIL or NULL in other languages.
When you say [None], you are saying "I would like to have a list which contains the special object called None". This is different than saying "I would like a list which contains no elements" (by typing []).
Question 1:
None is an object. It is of type "NoneType".
This can be seen by doing something like this in the terminal:
>>> type(None)
<type 'NoneType'>
So, when you put this object in a list, the list has one element.
Question 2:
The assignment operator in Python, =, is used to attach a name to an object. In the case of immutable objects, like integers, multiple names can be attached to the same object. That is what you are doing with a and b. So, when you test their identity, using the is operator, you see that the two names point to the identical object.
Alternatively, when you attach a name to a newly created list (which you created with the [] operator) it is a different list each time.
None is a valid element, but you can treat it like a stub or placeholder. So it counts as an element inside the list even if there is only a None.
For (equality) comparisons you shouldn't use is. Use ==!
Because is can lead to strange behaviour if you don't know exactly when and how to use it. For example:
>>> 1900 is 1900
True
>>> a = 1900
>>> b = 1900
>>> a is b
False
>>> a, b = 1900, 1900
>>> a is b
True
This rather strange behaviour is explained for example in this question: Why does Python handle '1 is 1**2' differently from '1000 is 10**3'?
This won't happen when you use ==:
>>> a == b
True
>>> 1900 == 1900
True
like one would expect.
You want to use None to imply that there is no valid object. You want to use [] to imply an object that is of type list and has no elements.
[None] is a list with one element which is None
>>>c= [] # This is a new list object
>>>d= [] # This is another new list object
In Python , x is y is used to check whether x and y are the same objects.
Here, c and d point to different list objects.
so,
>>>print c is d
False
is expected.
On the other hand,
>>>c= [] # This is a new list object
>>>d = c # This is the same object as c
>>>print c is d
True
Here, a and b are primitives, not objects
>>>a= 1
>>>b=1
So, this is expected:
print a is b
True

Need help to understand code in python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
first = int(input('first int: '))
second = int (input('second int: '))
result =0
if first and second:
result =1
elif not first:
result =2
elif first or second:
result=3
else:
result=4
print(result)
when I enter 1 and 0, the result is 3. I would appreciate if anyone could add some explanation.
You are using or- it means the statement will return True when it first finds True.
When you say 5 or 9, both 5 and 9 represent truism (as does any non-zero value). So it returns the first - 5 in this case. When you say 9 or 5, it returns 9.
EDIT: k = 1 or 0 would evaluate to True since 1 represents truism. Thus, as per your code, result is 3
In many program languages, the boolean operations only evaluate their second argument if needed for their outcome. These called short-circuit operator. And in python, according the docs, it returns:
x or y : if x is false, then y, else x
x and y : if x is false, then x, else y

Python "++" operator doesn't work [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Python: Behaviour of increment and decrement operators
Hi, I've tried this.
++num
and the num doesn't change at all, always show the value when initialized
if I change ++num to num+=1 then it works.
So, my question is how that ++ operator works?
There isn't a ++ operator in python. You're applying unary + twice to the variable.
Answer: there is no ++ operator in Python. += 1 is the correct way to increment a number, but note that since integers and floats are immutable in Python,
>>> a = 2
>>> b = a
>>> a += 2
>>> b
2
>>> a
4
This behavior is different from that of a mutable object, where b would also be changed after the operation:
>>> a = [1]
>>> b = a
>>> a += [2]
>>> b
[1, 2]
>>> a
[1, 2]

Categories

Resources