i need some help with this code please :)

when i run this code the output after each time the nested loop runs should look like this:
{'gender': 'Female', 'age': 9, 'fur': 'Brown', 'name': 'Savannah'}
{'gender': 'Male', 'age': 9, 'fur': 'White', 'name': 'Thumper'}
{'gender': 'Male', 'age': 8, 'fur': 'Brown', 'name': 'Ian'}
{'gender': 'Female', 'age': 8, 'fur': 'Brown', 'name': 'Natalie'}
{'gender': 'Male', 'age': 7, 'fur': 'White', 'name': 'Sebastian'}

with the bunnies ordered by age

however what is happening is that after the initial 5 bunnies created are deleted
the 6th bunny seems to be removed from the dict for one loop and it looks like this:

{'gender': 'Female', 'age': 9, 'fur': 'Brown', 'name': 'Savannah'}
{'gender': 'Male', 'age': 9, 'fur': 'White', 'name': 'Thumper'}
{'gender': 'Female', 'age': 8, 'fur': 'Brown', 'name': 'Natalie'}
{'gender': 'Male', 'age': 7, 'fur': 'White', 'name': 'Sebastian'}

the issue is that while its not in the dict the age of the key wont increase so on the next loop it looks like this:


{'gender': 'Male', 'age': 9, 'fur': 'Brown', 'name': 'Ian'}
{'gender': 'Female', 'age': 8, 'fur': 'Brown', 'name': 'Natalie'}
{'gender': 'Male', 'age': 8, 'fur': 'White', 'name': 'Sebastian'}

instead of this:

{'gender': 'Male', 'age': 9, 'fur': 'Brown', 'name': 'Ian'}
{'gender': 'Female', 'age': 9, 'fur': 'Brown', 'name': 'Natalie'}
{'gender': 'Male', 'age': 8, 'fur': 'White', 'name': 'Sebastian'}

what i need help with if finding out where that dict key is going and why.
thanks for the help :)

P.S

sorry if the code isn't in the blue code box i kept getting this msg
"You do not have permission to create tags. You may only use existing tags."
so if anyone knows anything about that you can post that too :) unless my code is formatted properly afterall

import random
FemaleBunnyName = open("BunnyFemaleName.txt").read().strip().split(".")
MaleBunnyName = open("BunnyMaleName.txt").read().strip().split(".")
del FemaleBunnyName[-1]
del MaleBunnyName[-1]
i=0
MaleBunnyPopulation=0
FemaleBunnyPopulation=0
FemaleBreedingAge=0
BunnyDict={}
BunnyKey=[]
class Bunny:

    def _init_(self,Name,Fur,Gender,Age):
        self.Name = Name
        self.Fur = Fur
        self.Gender = Gender
        self.Age = Age


    def BunnyFur(self):
        Fur = open("BunnyFur.txt").read().strip('\n').split(".")
        del Fur[-1]
        self.Fur=Fur[random.randrange(0,3)]
        return self.Fur
    def BunnyName(self,Name):
        global FemaleBunnyName
        global MaleBunnyName
        self.Name=Name
        if self.Name=='Male':
            vv=random.randrange(0,len(MaleBunnyName))
            self.Name=MaleBunnyName[vv]
            del MaleBunnyName[vv]
            return self.Name

        elif self.Name=='Female':
            vv=random.randrange(0,len(FemaleBunnyName))
            self.Name=FemaleBunnyName[vv]
            del FemaleBunnyName[vv]
            return self.Name

    def BunnyGender(self):
        self.Gender = random.randrange(0,2)
        if self.Gender == True:
            return 'Male'
        else:
            return 'Female'


def BunnyAgeIncrement(x):
    global FemaleBunnyPopulation
    global MaleBunnyPopulation
    global BunnyDict
    i=0

    while i<x:

        age=0
        BunnyFur=B.BunnyFur()
        BunnyGender=B.BunnyGender()
        BunnyName=B.BunnyName(BunnyGender)
        BunnyKey.append(BunnyName)
        i+=1
        BunnyDict.update({BunnyName:{'age':age,'gender':BunnyGender,'fur':BunnyFur,'name':BunnyName}})
        if BunnyGender=='Male':
            MaleBunnyPopulation+=1

        elif BunnyGender=='Female':
            FemaleBunnyPopulation+=1
    return BunnyDict






B=Bunny()
BunnyAgeIncrement(5)

while MaleBunnyPopulation>0 and FemaleBunnyPopulation>0 and MaleBunnyPopulation<50 and FemaleBunnyPopulation<50 :
    a = len(BunnyKey)
    i=0
    print '\n'
    while i<a:
        if BunnyDict[BunnyKey[i]]['age']<10:
            print BunnyDict[BunnyKey[i]]
            BunnyDict[BunnyKey[i]]['age'] +=1
            if BunnyDict[BunnyKey[i]]['age']>2 and BunnyDict[BunnyKey[i]]['gender']=='Female' and MaleBunnyPopulation>0:
                FemaleBreedingAge+=1

            i+=1
        elif BunnyDict[BunnyKey[i]]['age']==10:
            if BunnyDict[BunnyKey[i]]['gender']=='Male':
                MaleBunnyPopulation-=1
                MaleBunnyName.append(BunnyDict[BunnyKey[i]]['name'])
            elif BunnyDict[BunnyKey[i]]['gender']=='Female':
                FemaleBunnyPopulation-=1
                FemaleBunnyName.append(BunnyDict[BunnyKey[i]]['name'])
            a-=1
            del BunnyDict[BunnyKey[i]]
            del BunnyKey[i]
            i+=1

        BunnyAgeIncrement(FemaleBreedingAge)
        FemaleBreedingAge = 0
print FemaleBunnyPopulation
print len(FemaleBunnyName)
print MaleBunnyPopulation
print len(MaleBunnyName)
print 'done'

You are creating only one instance of bunny at line 77, also only class namesshould be capitalized You should make list of Bunny instances. Your code I do not understand.

You are creating only one instance of bunny at line 77, also only class namesshould be capitalized You should make list of Bunny instances. Your code I do not understand.

I've only just started to program (self taught) and the whole idea of a class and instances are still a bit blurred. what i want to do is get the program to generate new bunnies every year (equal to the amount of females bunnies in breeding age) and to continue until i have 50+ male or female bunnies. the instance I'm using currently
automatically generates a new bunny (name,fur,gender)which is then added to a dictionary using its (unique) name as the dict key. if you think it would be more practical for me to use multiple instances could you please give me an example of how i would do that as well as reasons for why its better :) as i said earlier instances and classes confuse me so it will be much appreciated.


I don't know if you tried to run the program but i just realized that you will need these two blocks of text for it to work (need to be saved as "BunnyMaleName.txt" and "BunnyFemaleName.txt" in teh same folder as the rest of the program is saved.

BunnyFemaleName<<<(do not copy)

Fufu.Ophelia.OryctolagusCuniculus.puddles.Nidoran.Cherry.Holly.Stacy.Lucy.Rona.Mel.Coral.Misty.Sandy.Karla.Diana.Roxy.Skye.Maui.Dori.Lotus.Minnie.Curly.Socks.Erin.Elwyn.Leah.Astropos.Zoe.Angel.Brooke.Trinity.Molly.Dazzle.Flora.Clara.Viola.Lanaya.Bunnsy.Foofoo.Emily.Emma.Madison.Isabella.Ava.Abigail.Olivia.Hannah.Sophia.Samantha.Elizabeth.Ashley.Mia.Alexis.Sarah.Natalie.Grace.Chloe.Alyssa.Brianna.Ella.Taylor.Anna.Lauren.Hailey.Kayla.Addison.Victoria.Jasmine.Savannah.Julia.Jessica.Lily.Sydney.Katherine.Destiny.Lillian.Alexa.Alexandra.Kaitlyn.Kaylee.Nevaeh.Makayla.Allison.Maria.Angelina.Rachel.Gabriella.Carla.Elisabeth.Lisa.Athena.Krystal.Maia.Joy.Helena.Kiersten.Harper.Virginia.Jaqueline.Norah.Marilyn.Marlene.Luna.Carolyn.Danna.Amari.Lexie.Lia.Saniya.Kenya.Sylvia.Kaitlynn.Martha.Ayanna.Rihanna.Willow.Pamela.Whitney.Deanna.Jazlyn.Tabitha.Teresa.Yazmin.Aileen.Nathalie.Quinn.Yadira.Kali.Elisa.

BunnyMaleName<<<<<(do not copy)


Bill.Fred.Tex..Max.Fluffy.Thumper.Harvey.Romeo.Chocolate.Pebbles.Hercules.Tiny.Yoda.Calvin.Lex.Zeus.Yogi.Spot.Buzz.Bouncer.Cody.Dusty.Diesel.Brandy.Axle.Bronx.Harly.Sean.Meepo.Alejandro.Raph.Rhasta.Io.Rincewind.Vimes.Nobby.Detritus.Jacob.Aidan.Ethan.Ryan.Matthew.Michael.Tyler.Joshua.Nicholas.Connor.Zachary.Andrew.Dylan.Jack.Jayden.Logan.Caden.Caleb.Alexander.Nathan.NoahWilliam.Jackson.Joseph.ChristopherJames.Daniel.Benjamin.Anthony.Cameron.Austin.Evan.Luke.Gavin.Brayden.Brandon.Christian.John.David.Gabriel.Jonathan.Samuel.Elijah.Colin.Justin.Alex.Mason.Jordan.Thomas.Hunter.Lucas.Kyle.Owen.Jake.Devin.Jason.Liam.Cole.Adam.Dominic.Aaron.Ian.Hayden.Isaac.Robert.Carter.Isaiah.Chase.Landon.Riley.Eric.Nathaniel.Tristan.Brian.Ashton.Brendan.Carson.Julian.Wyatt.Blake.Seth.Sebastian.Xavier.Will.Bryce.Garrett.Kevin.Sam.Patrick.Brady.Charlie.Parker.Trevor.Charles.Cooper.Timothy.Henry.

here it is again

male names
Bill.Fred.Tex..Max.Fluffy.Thumper.Harvey.Romeo.Chocolate.Pebbles.Hercules.Tiny.Yoda.
Calvin.Lex.Zeus.Yogi.Spot.Buzz.Bouncer.Cody.Dusty.Diesel.Brandy.Axle.Bronx.Harly.
Sean.Meepo.Alejandro.Raph.Rhasta.Io.Rincewind.Vimes.Nobby.Detritus.Jacob.Aidan.
Ethan.Ryan.Matthew.Michael.Tyler.Joshua.Nicholas.Connor.Zachary.Andrew.Dylan.
Jack.Jayden.Logan.Caden.Caleb.Alexander.Nathan.NoahWilliam.Jackson.Joseph.
ChristopherJames.Daniel.Benjamin.Anthony.Cameron.Austin.Evan.Luke.Gavin.Brayden.
Brandon.Christian.John.David.Gabriel.Jonathan.Samuel.Elijah.Colin.Justin.Alex.Mason.
Jordan.Thomas.Hunter.Lucas.Kyle.Owen.Jake.Devin.Jason.Liam.Cole.Adam.Dominic.Aaron.
Ian.Hayden.Isaac.Robert.Carter.Isaiah.Chase.Landon.Riley.Eric.Nathaniel.Tristan.
Brian.Ashton.Brendan.Carson.Julian.Wyatt.Blake.Seth.Sebastian.Xavier.Will.Bryce.
Garrett.Kevin.Sam.Patrick.Brady.Charlie.Parker.Trevor.Charles.Cooper.Timothy.
Henry.


female names
Fufu.Ophelia.OryctolagusCuniculus.puddles.Nidoran.Cherry.Holly.Stacy.Lucy.Rona.Mel.
Coral.Misty.Sandy.Karla.Diana.Roxy.Skye.Maui.Dori.Lotus.Minnie.Curly.Socks.Erin.
Elwyn.Leah.Astropos.Zoe.Angel.Brooke.Trinity.Molly.Dazzle.Flora.Clara.Viola.Lanaya.
Bunnsy.Foofoo.Emily.Emma.Madison.Isabella.Ava.Abigail.Olivia.Hannah.Sophia.Samantha.
Elizabeth.Ashley.Mia.Alexis.Sarah.Natalie.Grace.Chloe.Alyssa.Brianna.Ella.Taylor.
Anna.Lauren.Hailey.Kayla.Addison.Victoria.Jasmine.Savannah.Julia.Jessica.Lily.Sydney.
Katherine.Destiny.Lillian.Alexa.Alexandra.Kaitlyn.Kaylee.Nevaeh.Makayla.Allison.
Maria.Angelina.Rachel.Gabriella.Carla.Elisabeth.Lisa.Athena.Krystal.Maia.Joy.Helena
.Kiersten.Harper.Virginia.Jaqueline.Norah.Marilyn.Marlene.Luna.Carolyn.Danna.Amari.
Lexie.Lia.Saniya.Kenya.Sylvia.Kaitlynn.Martha.Ayanna.Rihanna.Willow.Pamela.Whitney.
Deanna.Jazlyn.Tabitha.Teresa.Yazmin.Aileen.Nathalie.Quinn.Yadira.Kali.Elisa.


thanks again :)

I took the main thing, but you had only single _ in your init.

import random

names = {'female': open("BunnyFemaleName.txt").read().strip().split("."),
         'male': open("BunnyMaleName.txt").read().strip().split(".")
         }

class Bunny(object):
    def __init__(self, name, fur, gender, age):
        self.name = name
        self.fur = fur
        self.gender = gender
        self.age = age

    def __str__(self):
         return 'Bunny({name}, {fur}, {gender}, {age})'.format(name=self.name, fur=self.fur, gender=self.gender, age=self.age)
    __repr__ = __str__
    
print(Bunny('test', 'white', 'male', 3))

bunnys = [[Bunny(name, fur=random.choice(('brown', 'white', 'black')), gender=gender, age=0)for name in random.sample(names[gender], 10)
           ] for gender in ('male', 'female') ]

for b in bunnys:
    print(b)

Edited 5 Years Ago by pyTony: n/a

sorry can you please explain the code to me, i understand some of it and i think i could modify it to suit my needs but I'm not sure how it would benefit me to use this as opposed to the class I created.

oh and if you want to know what the program is for

Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) arrays pseudo random number generation strings & string functions functions structures/classes enumerated data file input/output pointers sorting linked lists advanced classes
Untitled
Write a program that creates a linked list of bunny objects. Each bunny object must have Sex: Male, Female (random at creation 50/50) color: white, brown, black, spotted age : 0-10 (years old) Name : randomly chosen at creation from a list of bunny names. radioactive_mutant_vampire_bunny: true/false (decided at time of bunny creation 2% chance of true)
At program initialization 5 bunnies must be created and given random colors. Each turn afterwards the bunnies age 1 year. So long as there is at least one male age 2 or older, for each female bunny in the list age 2 or older; a new bunny is created each turn. (i.e. if there was 1 adult male and 3 adult female bunnies, three new bunnies would be born each turn) New bunnies born should be the same color as their mother. If a bunny becomes older than 10 years old, it dies. If a radioactive mutant vampire bunny is born then each turn it will change exactly one non radioactive bunny into a radioactive vampire bunny. (if there are two radioactive mutant vampire bunnies two bunnies will be changed each turn and so on...) Radioactive vampire bunnies are excluded from regular breeding and do not count as adult bunnies. Radioactive vampire bunnies do not die until they reach age 50. The program should print a list of all the bunnies in the colony each turn along w/ all the bunnies details, sorted by age. The program should also output each turns events such as "Bunny Thumper was born! Bunny Fufu was born! Radioactive Mutant Vampire Bunny Darth Maul was born! Bunny Julius Caesar died! The program should write all screen output to a file. When all the bunnies have died the program terminates. If the bunny population exceeds 1000 a food shortage must occur killing exactly half of the bunnies (randomly chosen)

Write a program that creates a linked list of bunny objects

This is just a list of objects, because to create a linked list you have to link one to the other in some way but the link was not given (and I did not read it carefully so may have missed it). Please read and observe the Python Style Guide. It makes someone else's code that much easier to read and increases your chances of getting some help. There are other ways to do this, like keeping track of the total males and females to create an equal number, so experiment if you wish. This is a subset of what you want to do, and is not tested.

import random

class Bunny:
 
    def __init__(self, female, male, fur, tot_males, tot_females):
        ## all of these are filled in by the functions
        self.gender = self.bunny_gender(tot_males, tot_females)
        self.name = self.bunny_name(female, male)
        self.fur = random.choice(fur)
        self.age = random.choice(range(0,11))
 
        print "Created", self.name, self.gender, self.fur, self.age
   
    def bunny_name(self, female, male):
        if 'Male' == self.gender:
            return random.choice(male)
        return random.choice(female)
 
    def bunny_gender(self, tot_males, tot_females):
        choice = random.choice([0,1])
        if choice:
            if tot_males < 5:
                return 'Male'
            else:
                return 'Female'
        elif tot_females < 5:
            return 'Female'
        return 'Male'
        
female_names_list = \
"Fufu.Ophelia.Oryctolagus.puddles.Nidoran.Cherry.Holly.Stacy.Lucy.Rona".split(".")
male_names_list = \
"Bill.Fred.Tex..Max.Fluffy.Thumper.Harvey.Romeo.Chocolate.Pebbles".split(".")

#fur = open("BunnyFur.txt").read().strip('\n').split(".")
fur = ["white", "brown", "spotted", "black"]

bunny_class_instances=[]
total_males=0
total_females=0
for b in range(10):
    BY = Bunny(female_names_list, male_names_list, fur, total_males, total_females)
    if 'Male' == BY.gender:
        total_males += 1
        male_names_list.remove(BY.name)
    else:
        total_females += 1
        female_names_list.remove(BY.name)
    bunny_class_instances.append(BY)


for instance in bunny_class_instances:
    print "%15s %6s %2d, %8s " % \
          (instance.name, instance.gender, instance.age, instance.fur)

## sorted on name
print "-"*50
names = sorted([(instance.name.lower(), instance) for instance in bunny_class_instances])
for name, instance in names:
    print "%15s %6s %2d, %8s " % \
          (instance.name, instance.gender, instance.age, instance.fur)

Edited 5 Years Ago by woooee: n/a

thank you everyone for all the help you gave me. looks like im going to have to learn quite a bit more before this project is going to take off :) and thanks for the python style link i'll check it out now

This question has already been answered. Start a new discussion instead.