mercredi 29 novembre 2017

Condensing if loops that are affected by outcome of previous if loops

I have a program for a pet shop. I have a nested list where each column corresponds to an animal and the numbers in the columns show the number of that animal in each cage:

cages=[[1,5,2,3],[2,1,1,5],[0,4,1,1]]

So I have a list l containing 4 variables which contain the number of each animal, calculated with sum:

    dogs=sum(i[0] for i in cages)
    hamsters=sum(i[1] for i in cages)
    cats=sum(i[2] for i in cages)
    birds=sum(i[3] for i in cages)

    l=[dogs,hamsters,cats,birds]

So the variables are equal to: dogs=3, hamsters=10, cats=4, birds=9

The scenario is that a customer wants to buy all of one type of animal, for example they want to buy all of birds or all of hamsters, but we don't know which one of the four animals they will buy. The only thing I know it that they will buy two of the animals smallest in numbers (that will be dogs and cats). I need to update the list l so the program deletes the animal from the list since the animal is not in the shop now. Here is how I did it:

smallest=[]
for animal in l:
  smallest.append(min(l))
  break

for animal in smallest:
  while len(l)>3:
    if animal==dogs:
        l=[hamsters,cats,birds]

    elif animal==hamsters:
        l=[dogs,cats,birds]

    elif animal==cats:
        l=[dogs,hamsters,birds]

    elif animal==birds:
        l=[dogs,hamsters,cats]

Then I empty smallest to find the new smallest animal:

smallest.clear()

Then I try to do the same thing for the second smallest animal:

smallest=[]
for animal in l:
    smallest.append(min(l))
    break

for animal in smallest:
    while len(l)>2:

This is where I get stuck. Since I'm not supposed to know which animal was bought at first (the numbers in cages can vary each time I run the program because the pet store sells and buys animals all the time), I don't know how to define the l now. I will now need multiple if statements for example:

if animal(deleted before)==dogs and animal(being deleted now)==cats:
  l=[hamsters,birds]

elif animal(deleted before)==dogs and animal(being deleted now)==hamsters:
  l=[cats,birds]

and so on, and if I am not mistaken I will need four times as many if statements as before. Is there a way to condense this so that I only have four if loops like in the previous bit of code?

Aucun commentaire:

Enregistrer un commentaire