xralf
xralf

Reputation: 3642

Shorten sequence of if statements

I have this code.

c = getch()
if c == "r":                                                                   
  return randrange(101, len(mylist) - 1) 
if c == "u":                                                        
  return 100               
if c == "b":      
  return -2                
if c == "w":    
  return -3                
if c == "m":
  return -4                
if c == "d":
  return -5                
if c == "e":
  return -6                
if c == "k":
  return -7
if c == "g":
  return -8
if c == "p":
  return -9
if c == "o":
  right = center - 1       
else:                      
  left = center + 1

Can I make this code snippet more compact? How would you write it better?

thank you

Upvotes: 1

Views: 285

Answers (3)

Austin Marshall
Austin Marshall

Reputation: 3107

You should strongly consider renaming your list variable to something that isn't already used.

...
c=getch()
if c=="r":
    return randrange(101, len(mylist) - 1)

return dict(u=100, b=-2, w=-3, m=-4, d=-5, e=-6, k=-7, g=-8, p=-9, o=center-1).get(c, center+1)

Upvotes: 1

japreiss
japreiss

Reputation: 11251

I agree that a dictionary is the way to go. The problem with Mark's answer is that the dictionary gets rebuilt for every function call. The way around is to define the dict outside the function:

def foo():
    c = getch()
    if c in foo.mydict:
        return foo.mydict[c]
    else:
        # TODO: special cases

foo.mydict = {'u':100, ... , 'p':-9}

# foo is now ready to use

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838106

You can use a dictionary:

# Special case.
if c == "r":                                                                   
    return randrange(101, len(list) - 1) 

# This is constant. It could be generated once at program start.
d = { 'u' : 100, ...., 'p' : -9 }

# This covers the majority of the cases.
if c in d:
    return d[c]

# Some more special cases.
if c == "o":
   right = center - 1       
else:                      
   left = center + 1

Upvotes: 8

Related Questions