Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

python - Iterate through a list and delete certain elements

I'm working on an assignment in my computer class, and I'm having a hard time with one section of the code. I will post the assignment guidelines (the bolded part is the code I'm having issues with):

You are going to create a simulated ant colony, in which the user will take the role of the queen who's duty it will be to manage the health of the colony. The simulation will proceed in a turn-based fashion, where each turn the user can choose to spend precious food resources on more ants.

Begin by creating a python file Ants.py with two classes: Colony and Ant.

The Colony class will have a list of worker ants (initially empty), an amount of food (initially 10), and 3 methods:

  • breedWorker()
  • step()
  • purge()

breedWorker() creates a new Ant and adds it to the colony's list of worker ants. Creating a worker costs 5 of the colony's food. If there is insufficient food, a message should be printed to the user and no ant should be created.

step() handles the automatic behaviour of the colony for each turn. Namely, this method will control the behaviour of each ant in the colony. Each turn each ant should eat one food from the colony's food supply. If there is not enough food, the ant will lose one point of health instead. Each ant will then forage for food (described below), and any food found will be added back into the colony's food supply.

purge() scans the list of worker ants, and any ants with 0 health are removed from the list. For each dead ant add 1 to the food supply, because ants recycle!

I'm having trouble with understanding how to make sure that all the ants in the list have health, and I'm unsure about how to delete the ants with zero health from the list.

The Ant class will have

  • Health (initially set to 10)
  • A forage() method

forage() determines randomly the luck an ant has while out searching for food each turn.

  • There is a 5% chance that the ant dies in a horrible accident (health = 0, return no food)
  • There is a 40% chance that the ant finds food. The amount found should be a random number between 1 and 5.
  • There is a 50% chance that the ant finds no food.
  • And there is a 5% chance that the ant finds sweet nectar! Her health is replenished (i.e., set to 10) and she brings back 10 food to the colony! The results of each ant's foraging should be both printed for the user and returned.

Finally, you will need to write a main() method to start the simulation and repeatedly prompt the user for their choices. Each turn the user should have the option to breed a new worker (for a cost of 5 food), or do nothing (no new ants). Your code should check the user's input for errors and ask again if it was invalid. Following the user's action (breed or not), the colony will take one 'step' as described above, and lastly, all dead ants should be purged from the colony. Simulation should repeat like this until the colony is out of both ants and enough food to make more ants.

This is my code:

import random

class Colony(object):

    def __init__(self):
        Colony.food = 10
        Colony.numWorkerAnts = 0
        Colony.workerAnts = []      

     def breedWorker(self):     
         print ("Breeding worker...")
         Colony.numWorkerAnts += 1
         Colony.food -= 5
         Colony.workerAnts.append(1)
         if (Colony.food < 5):
            print ("Sorry, you do not have enough food to breed a new worker ant!")

     def step(self):
         for i in range(0,len(Colony.workerAnts)):
            Colony.food -= 1

class Ant(object):

    def __init__self(self):
    Ant.health = 10

    def forage(self):
    foodFound = random.random()
    if (foodFound <= 0.05):
       print("Ant has died in an accident!")
       Ant.health = 0 
    if (foodFound > 0.05 and foodFound < 0.40):
       amountFood = random.randint(1,5)
       print("Ant finds "+str(amountFood)+" food.") 
       Colony.food += amountFood    
    if (foodFound >= 0.40 and foodFound < 0.95):
       print("Ant worker returns empty handed.")
    if (foodFound >= 0.95):
       print("Your ant finds sweet nectar! Ant returns "+str(amountFood)+" to the colony and health is restored to "+str(self.health)+"!")
       amountFood = 10
       Ant.health = 10 
       Colony.food = amountFood + Colony.food

def main():
    colony = Colony()
    ant = Ant()
    while (Colony.numWorkerAnts >= 1 or Colony.food >= 5):
    print ("Your colony has "+str(Colony.numWorkerAnts)+" ants and "+str(Colony.food)+" food, Your Majesty.")
    print ("What would you like to do?")
    print ("0. Do nothing")
    print ("1. Breed worker (costs 5 food)")
    prompt = '> '
    choice = int(raw_input(prompt))

    if (choice == 1):
        colony.breedWorker()
        colony.step()
        for i in range(0, len(Colony.workerAnts)):
            ant.forage()    
    else:
        for i in range(0, len(Colony.workerAnts)):
            ant.forage()    
            colony.step()
main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

At the moment, you are making everything a class attribute, shared amongst all instances of the class, as you use ClassName.attr. Instead, you should use the self.attr to make everything an instance attribute:

class Colony(object):

    def __init__(self):
        self.food = 10
        self.workerAnts = [] # numWorkerAnts is just len(workerAnts)

Note that you should alter breedWorker to actually add a new Ant instance to the list of self.workerAnts; at the moment, it only increments the count.

To reduce the colony to ants with health, you can use a list comprehension:

self.workerAnts = [ant for ant in self.workerAnts if ant.health]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...