Iterate through a list and delete certain elements

2024/11/9 5:52:48

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 willtake the role of the queen who's duty it will be to manage the healthof the colony. The simulation will proceed in a turn-based fashion,where each turn the user can choose to spend precious food resourceson more ants.

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

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

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

breedWorker() creates a new Ant and adds it to the colony's list ofworker ants. Creating a worker costs 5 of the colony's food. If thereis insufficient food, a message should be printed to the user and noant 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 thecolony. Each turn each ant should eat one food from the colony's foodsupply. If there is not enough food, the ant will lose one point ofhealth 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 searchingfor 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 a50% chance that the ant finds no food.
  • And there is a 5% chance thatthe ant finds sweet nectar! Her health is replenished (i.e., set to10) and she brings back 10 food to the colony! The results of eachant's foraging should be both printed for the user and returned.

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

This is my code:

import randomclass Colony(object):def __init__(self):Colony.food = 10Colony.numWorkerAnts = 0Colony.workerAnts = []      def breedWorker(self):     print ("Breeding worker...")Colony.numWorkerAnts += 1Colony.food -= 5Colony.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 -= 1class Ant(object):def __init__self(self):Ant.health = 10def 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 = 10Ant.health = 10 Colony.food = amountFood + Colony.fooddef 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()
Answer

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 = 10self.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]
https://en.xdnf.cn/q/120531.html

Related Q&A

How to count numbers in a list via certain rules?

Just to say I have a str and a list of strs and I want to count how many strs in the list that is contained in a str. Is there an elegant way to do that?For example, l = {"foo", "bar&qu…

Count character occurrences in a Python string

I want to get the each character count in a given sentence. I tried the below code and I got the count of every character but it displays the repeated characters count in the output. How to delete repe…

The Concept Behind itertoolss product Function

so basically i want to understand the concept of product() function in itertools. i mean what is the different between yield and return. And can this code be shorten down anyway.def product1(*args, **k…

how to read data from multiple sheets in a single csv file using python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking for code must demonstrate a minimal understanding of the problem being solved. Incl…

Quality Center: Set a Step Field in Python

I have a very simple problem here. I want to achieve the following VB script Code in Python:- dim objSfact dim objOrun dim mystep Set objOrun = QCutil.CurrentRun Set objSfact = objOrun.StepFactory…

Convert for loop from Python to C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Storing values in a CSV file into a list in python

Id like to create a list that stores all values of a single column. For example lets say my file has a column called FirstNames and for the first 3 rows, the names column has Merry, Pippin, Frodo.Id l…

Python arithmetic quiz task 1

I have no idea why this code is not working, as you can see Im trying to ask the user 10 questions display their score at the end. Everything works except that the score will always appear as a 0 or 1 …

Using Python to split long string, by given ‘separators’ [duplicate]

This question already has answers here:Split Strings into words with multiple word boundary delimiters(31 answers)Closed 9 years ago.Environment: Win 7; Python 2.76I want to split a long string into pi…

How do I return the number of unique digits in a positive integer

Example: unique_dig(123456) All unique 6Im trying to write code to have a function return how many unique numbers there are in a positive integer.count = 0for i in unique_digits:if count.has_key(i):cou…