1

I currently just use something like this:

def match9(a,b,c,d,e,f,g,h,i):
if a==b and b==c and c==d and d==e and e==f and f==g and g==h and h==i:
    return 1
else:
    return 0

in conjunction with

temp = match9(d1s1,d1s2,d1s3,d1s4,d1s5,d1s6,d1s7,d1s8,d1s9)
if temp == 1:
    codeToBeActivated()
Dave Dave
  • 46
  • 1
  • 6
  • More efficient in terms of what? Time? Space? Or code? – sberry Jun 27 '16 at 13:45
  • 5
    You shouldn't be using `==` to compare `float`s in the first place. – chepner Jun 27 '16 at 13:45
  • 1
    Well, it seems that you want to check if all the items are equal, so you simply `set()` in order to preserve the unique items and count the length of result. – Mazdak Jun 27 '16 at 13:45
  • 1
    `def match9(*args): return functools.reduce(lambda x, y: x == y, args)` – though, yes, `==` and floats don't mix well. – deceze Jun 27 '16 at 13:47
  • 1
    [What is the best way to compare floats for almost-equality in Python?](https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python) – Cory Kramer Jun 27 '16 at 13:47
  • @Kasramvd: Comparing floats for **exact** equality is rarely useful; please see CoryKramer's link. – PM 2Ring Jun 27 '16 at 13:52
  • @PM2Ring Yeah I saw it, but since OP doesn't mentioned anything about the quality of equality and also he is looking for a alternative for `==`, I preferred this duplicate. – Mazdak Jun 27 '16 at 13:54
  • Another option (not great on efficiency, but still): collect all variable to a list x = (a, b, c, d, e, f, g, h, i). Then check if max([abs(x[k]-x[k+1]) for k in range(len(x)-1)])==0 – Aguy Jun 27 '16 at 14:00

1 Answers1

4

You can use a shortcut

if a == b == c == d == e == f == g == h == i:

or use a set to eliminated duplicates, then check the length:

if len({a,b,c,d,e,f,g,h,i}) == 1:

That being said, using == to compare floats can lead to errors because of floating point precision. You can try checking the differences between elements. Here is an example for Python >= 3.4:

from statistics import stdev
if stdev([a, b, c, d, e, f, g, h, i]) < 1e-6:  # Or some other threshold
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • the trick with the set probably checks for equality as well which is an issue with floats especially when they come from different sources. – Ma0 Jun 27 '16 at 13:48