1

I have an python example code as:

Input: (x,y)

         if x==0 and y==0:    
            print x+y+1     
         elif x==0 and y==y:    
            print x+y*y+2    
         elif x==x and y==0:    
            print x*x+y+3    
         else:    
            print x*x+y*y+4    

How can I switch directly to the condition as, if my input is (x,y) = (0,0) it will output 1 without checking other conditions?

I tried this using dictionary as,

Input: (x,y)

         def Case1():
               print x+y+1     
         def Case2():      
               print x+y*y+2     
         def Case3():
               print x*x+y+3    
         def Case4():      
               print x*x+y*y+4     

         dict = {(0,0): Case1,
                 (0,y): Case2,
                 (x,0): Case3,
                 (x,y): Case4,
         }  

         dict[(x,y)]()     

When I tried this with input (x,y) = (0,0), this gives me output as 4 instead of 1. It seems like, my code is checking only for the Case4. What I am doing wrong in the dictionary?

Thanks!

4

3 回答 3

2

It seems that you do not quite understand how Python works. A dictionary is not a pattern matching block, as you have in Haskell or Erlang. It is a data structure with concrete values inside. You can try to write print dict after your definition and see what's inside it.

When you create your dict, current concrete values of x and y are used to create the keys. If x and y happen to be 0 at the time, the (0,0) key will be replaced by (x,y) (that's why in your case Case4 is called).

于 2013-10-09T11:33:08.960 回答
1

Say x=0 and y=0. Your final entry in the dict is (x,y):Case4, or 0,0, replacing any previous 0,0. Then you look up dict[x,y], or really dict[0,0] which calls Case4...this will happen regardless of what x,y is.

Stick to your original if. The code is clear, although you can make it simpler:

     if x==0 and y==0:    
        print 1    
     elif x==0:    
        print y*y+2    
     elif y==0:    
        print x*x+3    
     else:    
        print x*x+y*y+4    
于 2013-10-09T11:33:48.750 回答
1

Bogdan explained why you can not use the variables x and y as keys into your dictionary. When they are both zero, all 4 keys will be (0,0) at definition time, so the dictionary only contains one case. You can probably achieve what you want by using the result of the tests on x and y as a key into the dictionary instead (untested):

case_dict = {(True, True): Case1,
             (True, False): Case2,
             (False, True): Case3,
             (False, False): Case4,
            }  

case_dict[(x == 0, y == 0)]() 

Note that you should not call a variable dict, since this is the name of a built-in type.

于 2013-10-09T11:35:10.357 回答