0

I was wondering if someone could tell me the pythonic way to check out the following.

I have a 6 bit binary number and want to check with its decimal values. Using mathematical function is one way but still it would require that I write around 2**6 if constructs.

So I wanted to know if there's an easier statement to write it.

Also assume that lets say it's not binary then what's the better way to check for 2**6 values in python.

if(a==1):
    ....
else:
    if(a==2)
.....

One way is saving it in a list and checking it with the indexes but still that would require that many if-else I guess.....

Thanks ....

  • 2
    Do those `.....` have anything in common? – kennytm Nov 18 '10 at 07:15
  • it just means that writing the same thing again and again for the rest of the values a==3 , a==4 and so on.... –  Nov 18 '10 at 07:16
  • 1
    What's a "binary number"? A number is a number, "binary" in this context is simply a representation you use when converting it to a string. – detly Nov 18 '10 at 07:16
  • Also, what is `a`? Where does it come from? What is its type? How is it used? – detly Nov 18 '10 at 07:17
  • The first question is, what will you do for each of those different cases? Will you do one thing if a==3 and something else if a==4? If you really need to do 2**6 different things, then maybe you do need the if construct .... but I can't quite believe that. Maybe you could provide a little more context? – aptwebapps Nov 18 '10 at 07:24
  • How does the action taken depend on `a`?. That's what KennyTM was asking. What do the different cases have in common. If it's 32 different outcomes then it's 32 different `if`'s or dict entries. Otherwise, you can reduce a lot of the work. __what are you trying to do?__! – aaronasterling Nov 18 '10 at 07:26
  • Did you mean you need to check the values of the individual bits? If so, http://en.wikipedia.org/wiki/Bitwise_operation will get you started with the general concepts. – aptwebapps Nov 18 '10 at 07:26
  • a is just a number. Guys don't fix on just the code. Its just a simple question that if I have to check the value of a variable whose values can be 2 ** 6 will I have to write that many if-else or is there small line code that will do the trick in python.... and no they are completely different functionality for different values... –  Nov 18 '10 at 07:27
  • @user you could do `elif` instead of nested `if`s. But without more detail, I have to vote to close as not a real question. You could use a dict, a higher order function, some combination. I bet you could probably cut out any overt branching. But what you do depends on the goal. – aaronasterling Nov 18 '10 at 07:29
  • What does it mean to 'check 2 ** 6' values? Like if (a > 0 and a < 2 ** 6) then:... would be sufficient? – ondra Nov 18 '10 at 07:31
  • @aaronasterling Its just that I perform different functions for different values of a ie a =1 , a = 2 till a = 64 and I was thinking writing so many elif does'nt make sense. If there's nothing else then I guess I will have to write all the elif.... –  Nov 18 '10 at 07:31
  • @user. Writing so many elif statements doesn't make sense. You are right about that. What also doesn't make sense is not showing us an example of these functions that you want to run and expecting us to be able to solve the problem. This is _not a real question._ – aaronasterling Nov 18 '10 at 07:35
  • I am not showing it because I have'nt written it up till now... I want you to answer my problem so I am trying out to do the best here. I asked this way because I was thinking of a menu driven value and I just thought that if there was something better in python for a switch construct or if-else. The number 64 too was not random as I have to club 64 different functions for all those values in a single program.... –  Nov 18 '10 at 07:42
  • The problem is not knowing even vaguely what's meant to happen in these 64 cases. To repeat aaronasterling, **what are you trying to do?**! There could be any number of ways of doing it, various completely different ideal solutions for different problems. – Chris Morgan Nov 18 '10 at 08:05

5 Answers5

4

Use a dictionary mapping values into outcomes (which can be functions in Python).

For example:

d = {}
d[0] = ....
d[1] = ....
d[2] = ....

outcome = d[a]

Naturally, how this works depends on your ...., but this construct can be very flexible. The most important feature of this approach is that this dictionary can be populated programmatically, and you don't need to write a lot of manual assignments. It's of course also much more efficient than going over many values with nested if statements (or elsif)

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • It's worth pointing out that functions and other callables are first class objects in Python. Thus the values you assign to your dictionary keys can be functions or tuples of functions and argument or partial argument lists or curries, etc. – Jim Dennis Nov 18 '10 at 08:51
2

To add to the responses of the others, you should read about the recommended Python style in PEP 8.

With your if version, the brackets are undesirable and spacing is desirable:

if a == 1:
    pass
elif a == 2:
    pass
elif a == 3:
    pass
else:
    pass
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
0

I would use a decorator to map into a dictionary based dispatch:

_dispatch_table = {}

def dispatch_on(*values):
    def dec(f):
        _dispatch_table.update((v, f) for v in values)
        return f
    return dec

@dispatch_on(0, 2, 47)
def one():
    foo()
    bar()

@dispatch_on(2, 23, 89)
def two():
    bar()
    baz()

x = some_number
_dispatch_table[x]()    
aaronasterling
  • 68,820
  • 20
  • 127
  • 125
-1

Personally I prefer a if/elif if I am understanding your ...

so your:

if(a==1):
    ....
else:
    if(a==2)
.....

Becomes this if you use if elif ladder:

if a==1:
    ....
elif a==2:
    .....
else:
    default

You can also use Python's version of a conditional expression for simple ladders:

def one():
   print("option 1 it is\n")

def two():
   print("option 2 it is\n")

def three():
   print("not one or two\n")

one() if a==1 else two() if a==2 else three()

Or even dictionaries:

def one():
   print("option 1 it is\n")

def two():
   print("option 2 it is\n")

def three():
   print("not one or two\n")

options = {1:one,
           2:two,
           3:three,
}

options[2]()

There is a great discussion on Python forms of switch-case in this SO post.

Community
  • 1
  • 1
the wolf
  • 34,510
  • 13
  • 53
  • 71
-3

Based on the somewhat vague information in the question and what I've been able to gather from the OP's comments, here's my guess:

def func1(): pass
def func2(): pass
def func3(): pass
#     ...
def func62(): pass
def func63(): pass

if 0 < a < 64:
    globals()['func'+str(a)]()
else:
    print 'a is out of range'
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    A dictionary-based dispatch table is a much better solution than this, particularly if some of the cases have shared behavior. – Russell Borogove Nov 18 '10 at 19:14
  • @Russell Borogove: I think that's an unfair assessment. FWIW, this *is* a dictionary-based dispatch and represents a low-cost solution what little is know intially. I don't think the OP yet knows if there's any "shared behavior". Even if it turns out later there is some, this approach can easily accommodate it at least a couple of different ways just like a separate dispatch dictionary or list could. Initially just doing the "simplest thing that could possibly work" is a completely valid strategy to proceed with without attempting to optimize code you haven't even written yet. – martineau Nov 18 '10 at 19:50
  • 1
    It would be trivial, and just as simple, to convert this to use a designated dict instead of dumping it all in the global namespace. – detly Nov 18 '10 at 22:45
  • @detly: Likewise for converting it to use one later *IF* necessary and/or worth the effort. If everything is put its own module and its built-in dict used as shown, there's no clear advantage to an explicit one...just extra effort and work. – martineau Nov 19 '10 at 02:55
  • @martineau - it's not "likewise" trivial, because it will be the OP doing it, not you, and they clearly don't know how. – detly Nov 19 '10 at 04:20
  • @detly: Maybe by then they would be more skilled with Python. Regardless, so far neither you nor anyone else criticizing my answer has clearly stated any clear advantages to having a separate dispatching mechanism. On the other hand, designing and implementing one up-front would most definitely entail more time and effort. My answer simply takes advantage of a mapping the exists by default anyway with essentially two lines of code. I think putting certain design decisions off until you have more information or are more skilled, is an example of working smarter, not harder than they need to be. – martineau Nov 19 '10 at 11:19