I have simplified a version of a problem I am attempting to model where I am using Simpy to describe the movement of travellers along a path.
The path is represented by a collection of Node() objects where each node contains a Simpy.Resource. Each node is connected to the next node in the path by the connected_to attribute. In the example code I have created a list of 10 nodes where each node in the list is connected to the preceding node in the list.
When a traveller (represented by an Occupier() object) is instantiated it is allocated the resource of a node. The traveller then moves along the nodes, only taking a step if the next node is available. My aim is for the traveller to simultaneously be allocated its destination node and release the node where it was previously located.
import simpy
class Node(object):
def __init__(self, env):
self.env = env
self.resource = simpy.Resource(self.env)
self.up_connection = None
self.travel_delay = 5
class Occupier(object):
def __init__(self, env):
self.env = env
self.location = None
self.destination = None
self.requests = []
def travel(self, instantiation_loc):
self.requests.append(instantiation_loc.resource.request())
yield(self.requests[-1])
self.location = instantiation_loc
self.destination = instantiation_loc.up_connection
yield self.env.timeout(self.location.travel_delay)
node_occupancy(nodes)
while self.destination.up_connection != None:
self.requests.append(self.destination.resource.request())
yield self.requests[-1]
self.location.resource.release(self.requests[0])
self.requests.pop(0)
self.location = self.destination
self.destination = self.location.up_connection
yield self.env.timeout(self.location.travel_delay)
node_occupancy(nodes)
def node_occupancy(nodes):
print([node.resource.count for node in nodes])
env = simpy.Environment()
nodes = [Node(env) for i in range(10)]
for i in range(len(nodes) - 1):
nodes[i].up_connection = nodes[i + 1]
env.process(Occupier(env).travel(nodes[0]))
env.run()
If I run the above code with one traveller it seems to work fine giving the following output:
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
However, if instantiate a second traveller you can see that there are points in time where one traveller is occupying two resources when it should only occupy one:
env.process(Occupier(env).travel(nodes[3]))
env.process(Occupier(env).travel(nodes[0]))
corresponding output:
[1, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 1, 1, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 1, 1, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 1, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 1, 1, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 1, 1, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 1, 1, 0]
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0]
It is important for my simulation that a traveller only ever occupies one resource as the attributes of the nodes are amended frequently based on this.
Is there any way to prevent this behaviour where a traveller never occupies more than one resource? i.e. a resource is simultaneously released when the traveller is allocated a new resource
In fact, your model is running correctly.
Try to add to the function node_ocupacy, the current execution time and some markers to identify the current stage of the simulation:
def node_occupancy(nodes, node, case):
print(env.now, node, case, [node.resource.count for node in nodes])
Also, I made some changes just to see a better simulation log:
def travel(self, instantiation_loc, loc):
self.requests.append(instantiation_loc.resource.request())
yield(self.requests[-1])
self.location = instantiation_loc
self.destination = instantiation_loc.up_connection
yield self.env.timeout(self.location.travel_delay)
node_occupancy(nodes, loc, 1)
while self.destination.up_connection != None:
self.requests.append(self.destination.resource.request())
node_occupancy(nodes, loc, 2)
yield self.requests[-1]
node_occupancy(nodes, loc, 3)
self.location.resource.release(self.requests[0])
node_occupancy(nodes, loc, 4)
self.requests.pop(0)
self.location = self.destination
self.destination = self.location.up_connection
yield self.env.timeout(self.location.travel_delay)
node_occupancy(nodes, loc, 5)
Now, run the simulation with a marker for the current node:
env.process(Occupier(env).travel(nodes[3], 3))
env.process(Occupier(env).travel(nodes[0], 0))
Look at the results and you will notice that events (request/release) occurs at the same time and the simultaneous resource time occupation is always = 0 (i.e.: the time between stages '3' and '4', for the same entity will be always 0):
5 3 1 [1, 0, 0, 1, 0, 0, 0, 0, 0, 0]
5 3 2 [1, 0, 0, 1, 1, 0, 0, 0, 0, 0]
5 0 1 [1, 0, 0, 1, 1, 0, 0, 0, 0, 0]
5 0 2 [1, 1, 0, 1, 1, 0, 0, 0, 0, 0]
5 3 3 [1, 1, 0, 1, 1, 0, 0, 0, 0, 0]
5 3 4 [1, 1, 0, 0, 1, 0, 0, 0, 0, 0]
5 0 3 [1, 1, 0, 0, 1, 0, 0, 0, 0, 0]
5 0 4 [0, 1, 0, 0, 1, 0, 0, 0, 0, 0]
Related
This is a part of code of John Conway's GAME OF LIFE
import random
height = 100
width = 100
def randomize(grid, width, height):
for i in range(0, height):
for j in range(0, width):
grid[i][j] = random.randint(0,1)
grid_model = [0] * height
next_grid_model = [0] * height
for i in range(height):
grid_model[i] = [0] * width
next_grid_model[i] = [1] * width
def next_gen():
global grid_model, next_grid_model
for i in range(0, height):
for j in range(0, width):
cell = 0
count = count_neighbors(grid_model, i, j)
if grid_model[i][j] == 0:
if count == 3:
cell = 1
elif grid_model[i][j] == 1:
if count == 2 or count == 3:
cell = 1
next_grid_model[i][j] = cell
temp = grid_model
grid_model = next_grid_model
next_grid_model = temp
def count_neighbors(grid, row, col):
count = 0
if row-1 >= 0:
count = count + grid[row-1][col]
if (row-1 >= 0) and (col-1 >= 0):
count = count + grid[row-1][col-1]
if (row-1 >= 0) and (col+1 < width):
count = count + grid[row-1][col+1]
if col-1 >= 0:
count = count + grid[row][col-1]
if col + 1 < width:
count = count + grid[row][col+1]
if row + 1 < height:
count = count + grid[row+1][col]
if (row + 1 < height) and (col-1 >= 0):
count = count + grid[row+1][col-1]
if (row + 1 < height) and (col+1 < width):
count = count + grid[row+1][col+1]
return count
glider_pattern = [[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]]
glider_gun_pattern = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
def load_pattern(pattern, x_offset=0, y_offset=0):
global grid_model
for i in range(0, height):
for j in range(0, width):
grid_model[i][j] = 0
j = y_offset
for row in pattern:
i = x_offset
for value in row:
grid_model[i][j] = value
i = i + 1
j = j + 1
if __name__ == '__main__':
next_gen()
temp = grid_model
grid_model = next_grid_model
next_grid_model = temp
What I want to ask is why we need to swap grid_model and next_grid_model?
Consider this small example
000
111
It should be followed by this grid
010
010
upper corners are 0, and surrounded by two 1, so they remain 0
lower corners are 1, and surrounded by one 1, so they become 0
upper middle pixel is 0 and surrounded by three 1, so it becomes 1.
lower middle pixel is 1 and surrounded by two 1, so it stays 1
Now, what would happen if you were using only one grid, that is compute this in situ:
You would start with grid
000
111
First pixel is 0, surround by two 1, so it stays 0, and grid stays
000
111
Second pixel is 0 surrounded by three 1, so it becomes 1. And grid becomes
010
111
Third pixel is 0, surrounded by three 1, so it becomes 1, and grid becomes
011
111
Fourth pixel (on 2nd line) is 1, surrounded by two 1, it stays 1.
011
111
Fifth pixel is 1, surrounded by four 1, it becomes 0
011
101
At last, sixth pixel is 1, surrounded by two 1, it stays 1
011
101
So, result is completely different from the expected result.
You get grid
011
101
Instead of grid
010
010
That is not directly the answer to your question. It is the answer to "why can't I just compute using a single grid, and why I need to compute a next_grid from a current_grid".
And my answer shows that you need to compute a new grid from a current grid.
Now, you have two options to do so.
Either at each step you allocate and compute a new grid, that, once computed becomes the current grid, and the former current grid is simply forgotten. That force you to redo the next_grid_model = [0] * height and for i in range(height): next_grid_model[i] = [1] * width each time. But it would work
Or, you don't want to bother creating a brand new next_grid_model at each step. So you just reuse the grid_model variable, that still exists, and whose, after all, you don't need any more, since you intend to replace it by next_grid_model.
That is the reason for the swap:
next_grid_model becomes grid_model, because, that is the game (I take you get that part. Again, from the first part of my answer, you probably understand why we need to compute a next_grid_model instead of updating grid_model directly. But then next_grid_model, as its name indicate, becomes the new grid_model.
And we need to create a new 2d-array to be the new next_grid_model. And if we don't want to create it from scratch, one solution is to say that the old grid_model will host the future next_grid_model. Hence the swap.
Note that such a trick is more important in other languages than in python. In C, for example, to allocate both grid, we would have to call malloc.
And calling malloc to create a new grid at each stage, while calling free on the former grids is a little bit stupid (allocating exactly the same amount of memory we are freeing — without free, it is even worse, and a memory leak). So it is quite classical in such case, to swap the "current" and "future" memories, instead of allocating a new one each time.
In python, if you were to just create a new next_grid_model each time, it would also work. Garbage collector would take care of all the former grids that you dropped, and everything would be fine. But even if it would work, that still would mean that you have to to the job of creating a new next_grid_model each time.
So a shorter answer could have been:
at each stage you need either to
next_grid_model = [0] * height
for i in range(height):
next_grid_model[i] = [1] * width
Or to
# Just a swap (I write it that way, because it is more compact,
# but it is the same thing as your 3 lines involving a temp variable)
next_grid_model, grid_model = grid_model, next_grid_model
Both works. They are just two way to create a future next_grid_model. Swap is simply faster.
I am trying to get a List of Lists for all of the combinations with a given Population and a given SubSet.
For this example, say there's a population of 12, and a subset of 3. From the Combinations Formula (nCr) I know there should be 220 combinations. How do I get a list of all of the 220 possible combinations?
Example Result:
[[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
etc.,
etc.,
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]]
You can generate all possible combinations of the 3 indices where you have ones, and build each output accordingly:
from itertools import combinations
def combs(n, r):
for comb in combinations(range(n), r):
yield [1 if i in comb else 0 for i in range(n)]
Sample run with your values:
c = list(combs(12, 3))
print(len(c))
# 220
We have the expected number of combinations, see the first ones:
print(c[:5])
# [[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
# [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
# [1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
# [1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]
I am having a hard time getting the star in the code to move from its start position to its end position in python. I am not looking for they exact answer, but just some help to get me going in the right direction. I also am wondering how to set the code up to choose one out of five set grids and allow you to choose a start and finish path. Would I be able to use if statements for the grids if I have it randomly generate a number. Then use the grid that corresponds with the if statement.
import numpy as np
import heapq
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
# creating a square grid
grid = np.array([
[0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
# start point and goal
start = (0, 0)
goal = (10, 15)
# plot map and path
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(grid, cmap=plt.cm.Dark2)
ax.scatter(start[1], start[0], marker="*", color="yellow", s=200)
ax.scatter(goal[1], goal[0], marker="*", color="red", s=200)
plt.show()
# define Heuristic function
def heuristic(a, b):
return np.sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2)
# define A-star function
def astar(array, start, goal):
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
close_set = set()
came_from = {}
gscore = {start: 0}
fscore = {start: heuristic(start, goal)}
oheap = []
heapq.heappush(oheap, (fscore[start], start))
while oheap:
current = heapq.heappop(oheap)[1]
if current == goal:
data = []
while current in came_from:
data.append(current)
current = came_from[current]
return data
close_set.add(current)
for i, j in neighbors:
neighbor = current[0] + i, current[1] + j
tentative_g_score = gscore[current] + heuristic(current, neighbor)
if 0 <= neighbor[0] < array.shape[0]:
if 0 <= neighbor[1] < array.shape[1]:
if array[neighbor[0]][neighbor[1]] == 1:
continue
else:
# array bound y walls
continue
else:
# array bound x walls
continue
if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):
continue
if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1] for i in oheap]:
came_from[neighbor] = current
gscore[neighbor] = tentative_g_score
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
heapq.heappush(oheap, (fscore[neighbor], neighbor))
# creating route
route = astar(grid, start, goal)
# add the start position
route = route + [start]
# reverse the backward sequence
route = route[::-1]
# print route
print(route)
# extract x and y coordinates from route list
x_coords = []
y_coords = []
for i in(range(0,len(route))):
x = route[i][0]
y = route[i][1]
x_coords.append(x)
y_coords.append(y)
#plot map and path
fig, ax = plt.subplots(figsize=(20,20))
ax.imshow(grid, cmap=plt.cm.Dark2)
ax.scatter(start[1],start[0], marker ="*", color ="yellow", s = 200)
ax.scatter(goal[1],goal[0], marker ="*", color ="red", s = 200)
ax.plot(y_coords,x_coords, color ="black")
plt.show()
Here, i have 6 lists, all of them has same length of data. one is time which contains time from one start point to one end point and another five list contains signals.
time = [11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67]
A = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
B = [0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2]
C = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
D = [0, 0, 0, 0, 0, 0, 0 ,0 ,0 ,0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2]
E = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
Here first i want to compare list A and B. if in list A 0 comes and in the same index 2 comes in B and if it is True then in second condition check in the same index in other three list there C should be 0, D should be 0 and E should be 1. if this condition satisfy then it is passed but in case in some point it comes different value then i need the start time and end time.
or j in range(len(time)):
lis = []
lis2 = []
for i in range(len(A)):
if(A[i] == 0 and B[i] == 2):
if C == 0 and D == 0 and E == 1:
lis.append(time[i])
else:
lis2.append(time[i])
print lis
print lis2
Using this code i've got the time where it is not satisfying but this isn't what i want.
i want the start time and end time like this
OUTPUT - [33,42] or [33,34,35,36,37,38,39,40,41,42]
Because in this time period 1st condition is True and from where it fails 2nd condition from there it should print the time till 1st condition True like i've given in output, then no need to check further.
Thank You In Advance.
I think this is what you want.
or j in range(len(time)):
lis = []
lis2 = []
bool = false
for i in range(len(A)):
if bool:
break
if(A[i] == 0 and B[i] == 2):
if C == 0 and D == 0 and E == 1:
lis.append(time[i])
else:
bool = true
lis2.append(time[i])
print lis
print lis2
Using numpy, you can do the following:
import numpy as np
A = np.array(A)
B = np.array(B)
C = np.array(C)
D = np.array(D)
E = np.array(E)
time = np.array(time)
print time[(A == 0)*(B == 2)*(C == 0)*(D == 0)*(E == 1)]
By the way, your example is wrong. The correct result is [32, 34, 35, 36, 37, 39, 40, 48, 49, 50, 51, 52], thus there are two periods with the correct pattern (from 31 to 40 and from 48 to 52).
I am a relative beginner to python, and in order to strengthen my skills, I am (attempting) to write a compiler for the Brainfu** language. All is good, except for the bracket [] loops. The program I am using to test my code is >++[>++<-]>+, which should set cell 2 to 5. When I run this, however, it does this:
0 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 >
1 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 +
2 [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 +
3 [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 [
4 [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 0 >
5 [0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 +
6 [0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 +
7 [0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 <
8 [0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 -
3 [0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 1 [
10 [0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 >
11 [0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 3 +
[0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
(The lines are formatted in the iteration, then the list at that point, then the value it's focused on and then the character it's running.)
My current code is
def generateArray(code):
array = []
for i in range(0,20):
array.append(0);
return array
def run(code):
print code
data = generateArray(code)
chars = list(code)
pointer = 0
for i in range(0, len(chars)):
current = chars[i]
if(current == "+"):
data[pointer] += 1
if(current == ">"):
pointer += 1
if(current == "-"):
data[pointer] -= 1
if(current == "<"):
pointer -= 1
if(current == "."):
print str(chr(data[pointer]))
if(current == ","):
given = raw_input()
data[pointer] = ord( given )
if(current == "["):
posOfEnd = chars[i:len(chars)].index("]")
if(data[pointer] == 0):
i += posOfEnd+1
if(current == "]"):
posOfBegin = len(chars) - 1 - chars[::-1].index('[')
i = posOfBegin
print i, data, data[pointer], chars[i]
return data
print run(">++[>++<-]>+")
posOfEnd is trying to find out where the next bracket is, and posOfBegin is trying to find out where the previous bracket is.
I suppose the problem is your loop variable i which you modify during the loop:
i += posOfEnd+1
and
i = posOfBegin
However python for loops are different from their C/C++ counterparts. In python the variable i will be set to each element of the iterable you provide it, in this case range. range(n) evaluates to a list containing all numbers from 0 up to n-1. If you modify your loop variable during an iteration then this modification remains for only that iteration but for the next iteration the loop variable will be assigned the next element of the iterable (not preserving your modifications).
You might want to use a while loop instead.