1

I have several variables that I need to permute with each other.

Simple example with four variables: UP, DOWN, LEFT, RIGHT:

#when variable UP is max
if UP > RIGHT > LEFT > DOWN or UP > RIGHT > DOWN > LEFT or UP > LEFT > RIGHT >DOWN or UP > LEFT > DOWN > RIGHT or UP > DOWN > RIGHT > LEFT or UP > DOWN > LEFT > RIGHT:
     some action ...

#when variable RIGHT is max
if RIGHT > UP > LEFT > DOWN or RIGHT > UP > DOWN > LEFT or RIGHT > LEFT > UP > DOWN or RIGHT > LEFT > DOWN > UP or RIGHT > DOWN > UP > LEFT or RIGHT > DOWN > LEFT > UP:
     some action ...

.
.
.

Is there any way to create permutations without so long if condition ?

Alechandro
  • 300
  • 1
  • 2
  • 11

1 Answers1

1

I think you'd be better off finding which one is highest, and then making one or more decisions off of that:

maxIndex = 0
values = [UP, DOWN, RIGHT, LEFT]
for curIndex in range(len(values))
    if values[curIndex] > values[maxIndex]:
        maxIndex = curIndex

if maxIndex == 0: #Up is highest
    ...
else if maxIndex == 1: #down is highest
    ...
else if...

There are always alternative approaches. The if/elseif/elsif chain could be replaced with a dictionary full of lamdas, or several other constructs. There's probably a math library out there that has a "find the highest value and return its index" function out there.

Mark Storer
  • 15,672
  • 3
  • 42
  • 80