Skip to content Skip to sidebar Skip to footer

How To Shorten This Code Without Using Bunch Of If Statements

CONSTANTS: NDP_INDEX = 0 GREEN_INDEX = 1 LIBERAL_INDEX = 2 CPC_INDEX = 3 A dist of the indices where each party's data appears in a 4-element list. PARTY_INDICES = [NDP_INDEX, GR

Solution 1:

try this:

for sub_list in range_votes:
   for i in range(4):
       PARTY_INDICES[i] += sub_list[i]
return ( {PARTY_INDICES[0] : 'NDP', PARTY_INDICES[1] : 'GREEN', ...}[max(PARTY_INDICES)], 
         PARTY_INDICES )

That's as short as I'm willing to make it ;-)

Solution 2:

You don't need all those dicts and range variables and define/enum looking things. This is a little less C and a little more python:

votes=[[5, 4, 1, 4], [3, 2, 2, 5], [3, 3, 1, 4,]]
parties=['NDP','GREEN','LIBERAL','CPC']

defvoting_range(v):
  totals = [sum(x) for x inzip(*v)] # transpose row/col of list of lists
  pname = parties[totals.index(max(totals))]
  return (pname,totals)

>>> voting_range(votes)
('CPC',[11, 9, 4, 13])

There are a few magic python things going on here. *v unpacks the list of lists, and feeds them as separate arguments to zip, which returns an iterable that gives the first element of each argument in a list, then the second element of each argument in a list, and so on. This has the effect of transposing the matrix (swapping rows and columns). In this form, simply summing each list will be the vote totals. The for x in syntax wrapped in brackets is a list comprehension, another awesome python feature which efficiently creates lists from iterables. Finally, index is a list method that will return the index of the first element that has the value specified, which in this case is the max. Since the elements of v should have the same length as the number of parties, this will also serve as the index into the parties list.

Post a Comment for "How To Shorten This Code Without Using Bunch Of If Statements"