Python 代码示例,用于模拟传染病的传播
时间: 2023-01-31 15:08:22 浏览: 72
下面是一个用 Python 模拟传染病传播的示例代码:
```
import random
class Person:
def __init__(self, name, infected=False):
self.name = name
self.infected = infected
self.immune = False
def infect(self):
self.infected = True
def heal(self):
self.infected = False
self.immune = True
class Population:
def __init__(self, size):
self.people = [Person(f"Person {i}") for i in range(size)]
self.infected_count = 0
def infect(self, person):
person.infect()
self.infected_count += 1
def simulate(self, transmission_probability, healing_probability):
next_round_infected = []
for person in self.people:
if person.infected:
if random.random() < healing_probability:
person.heal()
self.infected_count -= 1
else:
next_round_infected.append(person)
if not person.infected and not person.immune:
if random.random() < transmission_probability:
next_round_infected.append(person)
self.infected_count += 1
person.infect()
self.people = [person for person in self.people if not person.immune]
for person in next_round_infected:
person.infect()
pop = Population(100)
pop.infect(pop.people[0])
for i in range(10):
pop.simulate(0.1, 0.2)
print(f"Round {i}: {pop.infected_count} infected")
```
在这个代码中,我们定义了两个类:`Person` 和 `Population`。
`Person` 类表示一个人,有两个属性:`infected` 和 `immune`。`infected` 表示这个人是否感染了传染病,`immune` 表示这个人是否已经康复并拥有了免疫力。这个类还有两个方法:`infect` 和 `heal`。`infect` 方法将 `infected` 设为 `True`,`heal` 方法将 `infected` 和 `immune` 设为 `True`。
`Population` 类表示一个人群,有一个属性 `people`,表示这个人