Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- from random import randint
- class Snake(object):
- def __init__(self, genotype, gender, population):
- assert type(genotype) == np.ndarray and len(genotype) == 4,"Invalid genotype. It must be np.array with 4 elements"
- assert isinstance(population, int), "Population must be integer"
- check = (genotype >= 0) & (genotype <= 10)
- assert population > 0, "Invalid population. It must be > 0"
- assert check.all(), "Invalid genotype values. It must be between 0 and 10"
- assert gender in ['Male', 'Female'], "Invalid gender. Gender should be 'Male' or 'Female'"
- self.genotype = genotype
- self.gender = gender
- self.population = population
- def __repr__(self):
- return f'Snake({self.genotype} x {self.population})'
- def __str__(self):
- text = f'{self.population} Snakes of genotype {self.genotype}. Closest to the {self.guess_breed()}.'
- return text
- def __add__(self, second):
- if isinstance(second, Snake):
- assert self.gender != second.gender, "Error, you can't crossbreed the same genders"
- genom = np.array((self.genotype + second.genotype) / 2, dtype=int)
- return Snake(genom, ['Male', 'Female'][randint(0, 1)], self.population + second.population)
- elif isinstance(second, int):
- assert second >= 0, "Use '-' for this operation"
- self.population += second
- return self
- def __sub__(self, num):
- assert isinstance(num, int) and num < self.population, "Error. Population <= 0"
- self.population -= num
- return self
- def __mul__(self, num):
- assert isinstance(num, int) and num >= 1, "You can only multiply Snake by integer"
- self.population *= num
- return self
- def __eq__(self, second):
- assert isinstance(second, Snake), "Error. One of parameters isn't a Snake"
- return list(self.genotype) == list(second.genotype) and self.gender == second.gender
- def __ne__(self, second):
- assert isinstance(second, Snake), "Error. One of parameters isn't a Snake"
- return not (self == second)
- def guess_breed(self):
- Samples = np.array([[9, 2, 8, 6], [1, 10, 5, 4], [0, 8, 6, 4], [0, 5, 3, 2]])
- types = {0: 'Cobra', 1: 'Anaconda', 2: 'Python', 3: 'Boa'}
- diff = abs(Samples - self.genotype)
- res = sorted(np.arange(4), key=lambda x: sum(diff[x]))[0]
- return types[res]
- # Samples:
- # Pure_Cobra = [9, 2, 8, 6]
- # Pure_Anaconda = [1, 10, 5, 4]
- # Pure_Python = [0, 8, 6, 4]
- # Pure_Boa = [0, 5, 3, 2]
- New_Snake = Snake(np.array([0, 7, 2, 4]), 'Male', 1)
- An_Snake = Snake(np.array([9, 2, 8, 6]), 'Female', 4)
- N_Snake = Snake(np.array([0, 7, 6, 4]), 'Female', 6)
- print(An_Snake + New_Snake)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement