You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
defworld_as_string(world):
'''Create a string representation of object `world` using #s and Os'''output=''forslotinworld:
ifslot==0:
output+='O'else:
output+='#'return(output)
print(world_as_string(world))
O#OOO#OO######OOOO##
Proportion of like neighbors
defproportion_same(i,world,distance=2):
'''Given a world object and an index `i`, return the proportion of world[i]'s neighbors that are the same type as world[i] itself.'''neighbors= []
# get left neighborsleftIndex=max(0,i-distance)
neighbors+=world[leftIndex:i]
# get right neighborsrightIndex=min(len(world),i+distance+1)
neighbors+=world[i+1:rightIndex]
num1s=sum(neighbors)
num0s=len(neighbors) -num1sifworld[i]==0:
return( float(num0s)/(num0s+num1s) )
elifworld[i]==1:
return( float(num1s)/(num0s+num1s) )
Unhappy agents
defunhappy_agents(world,threshold=.5,distance=2):
'''Return a list of indices i for which less than `threshold` of world[i]'s neighbors are of the same type as world[i] itself'''unhappy= []
foriinrange(len(world)):
ifproportion_same(i,world,distance) <threshold:
unhappy.append(i)
return(unhappy)
Random move
defrandomMove(i,world):
'''move item at index `i` in `world` to a random (possibly identical) index'''agent=world.pop(i)
insertAt=random.randint(0,len(world))
world.insert(insertAt,agent)
Putting it together
# parametersthreshold=0.5nbhd_distance=5size=40numXs=20numOs=size-numXsworld= []
world.extend( [0]*numOs )
world.extend( [1]*numXs )
random.shuffle(world)
whileunhappy_agents(world,threshold,nbhd_distance):
# get list of unhappy agents:cur_unhappy=unhappy_agents(world,threshold,nbhd_distance)
# pick one at random:index=random.choice(cur_unhappy)
# move that agent to a new slot:randomMove(index,world)
print(world_as_string(world))