I am creating python code for the Timed Event Graph as in the following screenshot.
The rule for the combination of A6 is as follows in order to get the respective p or c.
For example: p_4 , c_1 , c_2
Here is the respective values from the respective list of p and c.
p_4 = 50
c_1 = 7
c_2 = 140
Then, according to the rule, the combination for the token is z_4 , (m_1 - z_1) , z_2.
Here is the calculation from the respective list of m and z.
z_4 = 0
m_1 - z_1 = 3 - 2 = 1
z_2 = 1
The set of p and c as well as m and z are parameters.
All of the possible combination is listed on the Table 1 under the Timed Event Graph.
Then, I created code as follows.
import numpy as np
from itertools import combinations
m = [3,4,2,1]
z = [2,1,2,0]
p = [100,120,3,50]
c = [7,140,80,220]
n = len(m)
S = np.arange(1,n+1)
comb = combinations(S, 5)
only_odd = [num for num in S if num % 2 == 1]
len_A = [num for num in only_odd if num !=1]
storage_j = []
for x in len_A:
comb = combinations(S,x)
for j in list(comb):
storage_j.append(j)
storage_i = []
for A_j in storage_j:
temp_i = []
for j in A_j:
if j ==1:
i = n-1 #minus 1 to adjust into the python index
if j != 1:
i = j-1-1 #minus 1 to adjust into the python index
temp_i.append(i)
storage_i.append(temp_i)
The storage_i indicates the respective index for each combination in Table 1.
storage_i = [[3, 0, 1], [3, 0, 2], [3, 1, 2], [0, 1, 2]]
Then, I created the code for A6 in Table 1 as follows.
final_A6 = []
for ida in storage_i:
temp = []
for i in ida:
if i == (n-1):
AC = ((i+1)%2)*c[i] + (1-((i+1)%2))*p[i] #np.remainder(i,2) #AC for R6
if i != (n-1):
if (len(temp)==0) or (len(temp)%2 ==0):
AC = ((i+1)%2)*p[i] + (1-((i+1)%2))*c[i] #AC for R6
if (len(temp)%2!=0) and (len(temp)!=0):
AC = ((i+1)%2)*c[i] + (1-((i+1)%2))*p[i] ##ACC for R6
temp.append(AC)
final_A6.append(temp)
final_A6
According to Table 1, the result of A6 is correct as follows.
final_A6 =[[50, 7, 140], [50, 7, 3], [50, 120, 3], [100, 120, 3]]
I used the similar approach for creating the code for Token in Table 1 as follows:
storage_token_A6 = []
for ida in storage_i:
temp_token_A6 = []
for i in ida:
if i == (n-1):
token_A6 = z[i]
if i != (n-1):
if (len(temp_token_A6)==0) or (len(temp_token_A6)%2 ==0):
token_A6 = z[i]
if (len(temp)%2!=0) and (len(temp)!=0):
token_A6 = m[i] - z[i]
temp_token_A6.append(token_A6)
storage_token_A6.append(temp_token_A6)
However the following result is incorrect.
storage_token_A6 = [[0, 1, 3], [0, 1, 0], [0, 3, 0], [1, 3, 0]]
The correct result of token according to the Table 1 is as follows.
expected result = [[0, 1, 1], [0, 1, 1], [0, 3, 1], [2, 3, 1]]
Can anyone let me know what's wrong with the code for Token?
If you have other suggestion or questions, please let me know.
Thank you in advance.
Related
I have this method which returns the max sum of the path from top left to bottom right (can move only to the right or bottom).
def max_path(grid):
N = len(grid)
M = len(grid[0])
sum = [[0 for i in range(M + 1)] for i in range(N + 1)]
for i in range(1, N + 1):
for j in range(1, M + 1):
sum[i][j] = (max(sum[i - 1][j], sum[i][j - 1]) + grid[i - 1][j - 1])
return sum[N][M]
matrix = [[1, 2, 3], [3, 4, 5]]
print(max_path(matrix))
output : 1 + 3 + 4 + 5 = 13
But what I want to get is also the coordinates of the points of the path:
[(0,0) (1,0) (1,1) (1,2)]
You can try the below code to get your job done.
from itertools import permutations, product
def get_max_sum(table):
height, width = len(table), len(table[0])
sum_, *pos = max((sum(table[x][y] for x, y in zip(*pairs)), *zip(*pairs))
for pairs in product(
permutations(range(height)),
([*range(i, width), *range(i)] for i in range(width))))
return (sum_, *sorted(pos))
sum_, *pos = get_max_sum(
[[1, 2, 3],
[2, 3, 5],
[4, 9, 16]]
)
Output:
20 #maximum sum
(0, 1) (1, 0) (2, 2) #co -ordinates
The variable sum after the nested-for loops (as written in your code) is
[0, 0, 0, 0],
[0, 1, 3, 6],
[0, 4, 8, 13]
You can work out the coordinates of the max sum by having a initial "pointer" at the bottom right corner (i=1, j =2, ignoring the zeros), and comparing the values that is on the top (i=0, i=2) and on the left (i=1, j=1). Since 8 is larger than 6, we move the "pointer" to the left, and now i=1, j=1.
4 is larger than 3, so we move the pointer to 4 (i=1, j=0)
1 is larger than 0, so we move the pointer to 1 (i=0, j=0)
A basic (untested) implementation of the algorithm is as follows:
def max_path(grid):
N = len(grid)
M = len(grid[0])
sum = [[0 for i in range(M + 1)] for i in range(N + 1)]
for i in range(1, N + 1):
for j in range(1, M + 1):
sum[i][j] = (max(sum[i - 1][j], sum[i][j - 1]) + grid[i - 1][j - 1])
j = M
i = N
path = []
while i > 0 and j > 0:
path.append((i-1,j-1))
if sum[i-1][j] <= sum[i][j-1]:
j -= 1
else:
i -= 1
path.reverse()
return sum[N][M],path
matrix = [[1, 2, 3], [3, 4, 5]]
print(max_path(matrix))
Imagine a matrix A having one column with a lot of inequality/equality operators (≥, = ≤) and a vector b, where the number of rows in A is equal the number of elements in b. Then one row, in my setting would be computed by, e.g
dot(A[0, 1:], x) ≥ b[0]
where x is some vector, column A[,0] represents all operators and we'd know that for row 0 we were suppose to calculate using ≥ operator (e.i. A[0,0] == "≥" is true). Now, is there a way for dynamically calculate all rows in following so far imaginary way
dot(A[, 1:], x) A[, 0] b
My hope was for a dynamic evaluation of each row where we evaluate which operator is used for each row.
Example, let
A = [
[">=", -2, 1, 1],
[">=", 0, 1, 0],
["==", 0, 1, 1]
]
b = [0, 1, 1]
and x be some given vector, e.g. x = [1,1,0] we wish to compute as following
A[,1:] x A[,0] b
dot([-2, 1, 1], [1, 1, 0]) >= 0
dot([0, 1, 0], [1, 1, 0]) >= 1
dot([0, 1, 1], [1, 1, 0]) == 1
The output would be [False, True, True]
If I understand correctly, this is a way to do that operation:
import numpy as np
# Input data
a = [
[">=", -2, 1, 1],
[">=", 0, 1, 0],
["==", 0, 1, 1]
]
b = np.array([0, 1, 1])
x = np.array([1, 1, 0])
# Split in comparison and data
a0 = np.array([lst[0] for lst in a])
a1 = np.array([lst[1:] for lst in a])
# Compute dot product
c = a1 # x
# Compute comparisons
leq = c <= b
eq = c == b
geq = c >= b
# Find comparison index for each row
cmps = np.array(["<=", "==", ">="]) # This array is lex sorted
cmp_idx = np.searchsorted(cmps, a0)
# Select the right result for each row
result = np.choose(cmp_idx, [leq, eq, geq])
# Convert to numeric type if preferred
result = result.astype(np.int32)
print(result)
# [0 1 1]
I'm working on A star algorithm and as my code below shown the gird is written manually and I'm thinking to make a grid with 100* 100 size. So, it will be so awful to write them manually. I need to put my starting point at (0,0) location and my goal point at (99,99) location.
I'm trying to make the grid with this line below
grid1 = [[0 for i in range(100)]for j in range(100)]
But how could I assign obstacles to this grid randomly or not randomly without touching the location of starting point and goal point?
This is below my code:
from __future__ import print_function
import random
grid = [[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0]]
'''
heuristic = [[9, 8, 7, 6, 5, 4],
[8, 7, 6, 5, 4, 3],
[7, 6, 5, 4, 3, 2],
[6, 5, 4, 3, 2, 1],
[5, 4, 3, 2, 1, 0]]'''
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x]
cost = 1
drone_h = 60
#the cost map which pushes the path closer to the goal
heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
#if grid[i][j] == 1:
#heuristic[i][j] = 99 #added extra penalty in the heuristic map
print(heuristic)
elevation = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
elevation[i][j] = random.randint(1,100)
else:
elevation[i][j] = 0
#the actions we can take
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
#function to search the path
def search(grid,init,goal,cost,heuristic):
closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]# the referrence grid
closed[init[0]][init[1]] = 1
action = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]#the action grid
x = init[0]
y = init[1]
g = 0
f = g + heuristic[init[0]][init[0]] + elevation[init[0]][init[0]]
cell = [[f, g, x, y]]
found = False # flag that is set when search is complete
resign = False # flag set if we can't find expand
while not found and not resign:
if len(cell) == 0:
resign = True
return "FAIL"
else:
cell.sort()#to choose the least costliest action so as to move closer to the goal
cell.reverse()
next = cell.pop()
x = next[2]
y = next[3]
g = next[1]
f = next[0]
if x == goal[0] and y == goal[1]:
found = True
else:
for i in range(len(delta)):#to try out different valid actions
x2 = x + delta[i][0]
y2 = y + delta[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0 and elevation[x2][y2] < drone_h :
g2 = g + cost
f2 = g2 + heuristic[x2][y2] + elevation[x2][y2]
cell.append([f2, g2, x2, y2])
closed[x2][y2] = 1
action[x2][y2] = i
invpath = []
x = goal[0]
y = goal[1]
invpath.append([x, y])#we get the reverse path from here
while x != init[0] or y != init[1]:
x2 = x - delta[action[x][y]][0]
y2 = y - delta[action[x][y]][1]
x = x2
y = y2
invpath.append([x, y])
path = []
for i in range(len(invpath)):
path.append(invpath[len(invpath) - 1 - i])
print("ACTION MAP")
for i in range(len(action)):
print(action[i])
return path
a = search(grid,init,goal,cost,heuristic)
for i in range(len(a)):
print(a[i])
You could assign the grid randomly and afterwards make sure both starting and end point don't contain obstacles. For neighboring fields you could just do the same as for those two.
import random
grid1 = [[random.randint(0,1) for i in range(100)]for j in range(100)]
# clear starting and end point of potential obstacles
grid1[0][0] = 0
grid1[99][99] = 0
I am trying to work out a program that would calculate the diagonal coefficients of pascal's triangle.
For those who are not familiar with it, the general terms of sequences are written below.
1st row = 1 1 1 1 1....
2nd row = N0(natural number) // 1 = 1 2 3 4 5 ....
3rd row = N0(N0+1) // 2 = 1 3 6 10 15 ...
4th row = N0(N0+1)(N0+2) // 6 = 1 4 10 20 35 ...
the subsequent sequences for each row follows a specific pattern and it is my goal to output those sequences in a for loop with number of units as input.
def figurate_numbers(units):
row_1 = str(1) * units
row_1_list = list(row_1)
for i in range(1, units):
sequences are
row_2 = n // i
row_3 = (n(n+1)) // (i(i+1))
row_4 = (n(n+1)(n+2)) // (i(i+1)(i+2))
>>> def figurate_numbers(4): # coefficients for 4 rows and 4 columns
[1, 1, 1, 1]
[1, 2, 3, 4]
[1, 3, 6, 10]
[1, 4, 10, 20] # desired output
How can I iterate for both n and i in one loop such that each sequence of corresponding row would output coefficients?
You can use map or a list comprehension to hide a loop.
def f(x, i):
return lambda x: ...
row = [ [1] * k ]
for i in range(k):
row[i + 1] = map( f(i), row[i])
where f is function that descpribe the dependency on previous element of row.
Other possibility adapt a recursive Fibbonachi to rows. Numpy library allows for array arifmetics so even do not need map. Also python has predefined libraries for number of combinations etc, perhaps can be used.
To compute efficiently, without nested loops, use Rational Number based solution from
https://medium.com/#duhroach/fast-fun-with-pascals-triangle-6030e15dced0 .
from fractions import Fraction
def pascalIndexInRowFast(row,index):
lastVal=1
halfRow = (row>>1)
#early out, is index < half? if so, compute to that instead
if index > halfRow:
index = halfRow - (halfRow - index)
for i in range(0, index):
lastVal = lastVal * (row - i) / (i + 1)
return lastVal
def pascDiagFast(row,length):
#compute the fractions of this diag
fracs=[1]*(length)
for i in range(length-1):
num = i+1
denom = row+1+i
fracs[i] = Fraction(num,denom)
#now let's compute the values
vals=[0]*length
#first figure out the leftmost tail of this diag
lowRow = row + (length-1)
lowRowCol = row
tail = pascalIndexInRowFast(lowRow,lowRowCol)
vals[-1] = tail
#walk backwards!
for i in reversed(range(length-1)):
vals[i] = int(fracs[i]*vals[i+1])
return vals
Don't reinvent the triangle:
>>> from scipy.linalg import pascal
>>> pascal(4)
array([[ 1, 1, 1, 1],
[ 1, 2, 3, 4],
[ 1, 3, 6, 10],
[ 1, 4, 10, 20]], dtype=uint64)
>>> pascal(4).tolist()
[[1, 1, 1, 1], [1, 2, 3, 4], [1, 3, 6, 10], [1, 4, 10, 20]]
I want to convert the given matrices a, b into square matrices by inserting zeros wherever necessary
a = [[1,2],[3,4],[5,6],[7,8]]
b = [[1,2,3,4],[5,6,7,8]]
I want the output to be
a1 = [[1,2,0,0],[3,4,0,0],[5,6,0,0],[7,8,0,0]]
b1 = [[1,2,3,4],[5,6,7,8][0,0,0,0],[0,0,0,0]]
I have trouble installing numpy package on my machine. Any solution without the use of numpy would greatly help.
Thanks
>>> a = [[1,2], [3,4], [5,6], [7,8]]
>>> b = [[1,2,3,4], [5,6,7,8]]
>>>
>>> def matrix(a, n):
... for row in a:
... yield row + [0] * (n - len(row))
... for i in range(len(a), n):
... yield [0] * n
...
>>> list(matrix(a, 4))
[[1, 2, 0, 0], [3, 4, 0, 0], [5, 6, 0, 0], [7, 8, 0, 0]]
>>> list(matrix(b, 4))
[[1, 2, 3, 4], [5, 6, 7, 8], [0, 0, 0, 0], [0, 0, 0, 0]]
This little function ought to do the trick:
def squarify(lst, n):
for sublist in lst:
while len(sublist) < n:
sublist.append(0)
while len(lst) < n:
lst.append([0]*n)
You need two pieces of information: the longest row, and the most number of columns. To get longest row, assuming that you can assume that each matrix has a set number of rows, you need to do something like
rowAlen = len(a[0])
rowBlen = len(b[0])
longestRow = 0;
if rowAlen > rowBlen:
longestRow = rowAlen
else:
longestRow = rowBlen
Then you'll need to get the number of columns of the matrix with the most columns.
colAlen = len(a)
colBlen = len(b)
maxCol = 0;
if colAlen > colBlen:
maxCol = colAlen
else:
maxCol = colBlen
Now that you have longestRow and maxCol, you can manipulate matrices.
for x in range(0,maxCol):
if colAlen <= x:
a.append([])
if colBlen <= x:
b.append([])
for y in range(0, longestRow):
if len(a[x]) <= y:
a[x].append(0)
if len(b[x]) <= y:
b[x].append(0)
This will return the output you are looking for, as well as alter the original list if it was stored in a variable.
def matrize(L):
msize = max(len(L), max([len(subL) for subL in L]))
for item in L:
while len(item)<msize: item.append(0)
zrow = [0]*msize
while len(L)< msize: L.append(zrow)
return L