The code is being executed but the output is not shown nor the variables are created
import numpy as np
def magicsquares():
n=input('enter the order of squares')
n=int(n)
m=np.zeros((n,n))
s=n*(n**2+1)/2 #sum of each row or diagonal
p=int(n/2)
q=(n-1)
for i in range(n**2):
m[p][q]=1 #assigning postion of 1
P=p-1
Q=q+1
if(i>=2): #assigning remaining positions
if(P==-1):
P=n-1
if(Q==n):
Q=0
there is not output showing because you are just declaring the function but not calling the function and there is no print/return inside the function. Here is a solution which you can use to see the output and work on:
import numpy as np
def magicsquares():
n = input('enter the order of squares')
n = int(n)
m = np.zeros((n, n))
s = n*(n**2+1)/2 # sum of each row or diagonal
p = int(n/2)
q = (n-1)
for i in range(n**2):
m[p][q] = 1 # assigning postion of 1
P = p-1
Q = q+1
if i >= 2: # assigning remaining positions
if P == -1:
P = n-1
if Q == n:
Q = 0
print(m)
magicsquares()
It is not the ultimate solution to find magic_square. It's just an updated version of your code so that you can see the outputs and work on.
Related
I would like to solve the above formulation in Scipy and solve it using milp(). For a given graph (V, E), f_ij and x_ij are the decision variables. f_ij is the flow from i to j (it can be continuous). x_ij is the number of vehicles from i to j. p is the price. X is the available number vehicles in a region. c is the capacity.
I have difficulty in translating the formulation to Scipy milp code. I would appreciate it if anyone could give me some pointers.
What I have done:
The code for equation (1):
f_obj = [p[i] for i in Edge]
x_obj = [0]*len(Edge)
obj = f_obj + v_obj
Integrality:
f_cont = [0 for i in Edge] # continous
x_int = [1]*len(Edge) # integer
integrality = f_cont + x_int
Equation (2):
def constraints(self):
b = []
A = []
const = [0]*len(Edge) # for f_ij
for i in v: # for x_ij
for e in Edge:
if e[0] == i:
const.append(1)
else:
const.append(0)
A.append(const)
b.append(self.accInit[i])
const = [0]*len(Edge) # for f_ij
return A, b
Equation (4):
[(0, demand[e]) for e in Edge]
I'm going to do some wild guessing, given how much you've left open to interpretation. Let's assume that
this is a maximisation problem, since the minimisation problem is trivial
Expression (1) is actually the maximisation objective function, though you failed to write it as such
p and d are floating-point vectors
X is an integer vector
c is a floating-point scalar
the graph edges, since you haven't described them at all, do not matter for problem setup
The variable names are not well-chosen and hide what they actually contain. I demonstrate potential replacements.
import numpy as np
from numpy.random._generator import Generator
from scipy.optimize import milp, Bounds, LinearConstraint
import scipy.sparse
from numpy.random import default_rng
rand: Generator = default_rng(seed=0)
N = 20
price = rand.uniform(low=0, high=10, size=N) # p
demand = rand.uniform(low=0, high=10, size=N) # d
availability = rand.integers(low=0, high=10, size=N) # X aka. accInit
capacity = rand.uniform(low=0, high=10) # c
c = np.zeros(2*N) # f and x
c[:N] = -price # (1) f maximized with coefficients of 'p'
# x not optimized
CONTINUOUS = 0
INTEGER = 1
integrality = np.empty_like(c, dtype=int)
integrality[:N] = CONTINUOUS # f
integrality[N:] = INTEGER # x
upper = np.empty_like(c)
upper[:N] = demand # (4) f
upper[N:] = availability # (2) x
eye_N = scipy.sparse.eye(N)
A = scipy.sparse.hstack((-eye_N, capacity*eye_N)) # (3) 0 <= -f + cx
result = milp(
c=c, integrality=integrality,
bounds=Bounds(lb=np.zeros_like(c), ub=upper),
constraints=LinearConstraint(lb=np.zeros(N), A=A),
)
print(result.message)
flow = result.x[:N]
vehicles = result.x[N:].astype(int)
I have been working on recursion and tried to solve the Knapsack problem [https://en.wikipedia.org/wiki/Knapsack_problem]. I came up with the algorithm below which works just fine:
cost_array = [2,3,4,5,9]
value_array = [3,4,8,8,10]
def KP(Weight, C, V):
if Weight < 2:
return 0
q = 0
for i in range(len(C)):
q = max(q, (KP(Weight-C[i], [x for j,x in enumerate(C) if j!=i], \
[x for j,x in enumerate(V) if j!=i]) + V[i]*(Weight-C[i] >= 0)))
return q
print(KP(25,cost_array,value_array))
However when I change the value of q to q < 0 and call print(KP(25,cost_array,value_array)) the result I get is 33 - q. With 33 being the max value the knapsack can have.
What is weird here is that I only get this behavior if I call the initial function with a Weight > 23 and here 23=2+3+4+5+9.
I can't figure out at what point the negative q gets added to my result for me this line never performs such an operation, can you guys enlighten me ?
q = max(q, (KP(W-C[i], [x for j,x in enumerate(C) if j!=i], [x for j,x in enumerate(V) if j!=i]) + V[i]*(W-C[i] >= 0)))
Thanks,
d_darric
Suppose q=-2 (a negative value)
Therefore you are filling your base cases with -2 . That is -2 is returned for base cases of your function which is then getting added to the answer on each step in recursion. Try a bottom up approach with a 2D array. You can look at that here https://www.youtube.com/watch?v=8LusJS5-AGo . In your case you are filling matrix base cases with -2.
def knapSack(W, wt, val, n):
K = [[0 for x in range(W+1)] for x in range(n+1)]
q=-2 #Make it zero for correct answer
# Build table K[][] in bottom up manner
for i in range(n+1):
for w in range(W+1):
if i==0 or w==0:
K[i][w] = q #Here you are assigning negative value
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]
return K[n][W]
# Driver program to test above function
value_array = [3,4,8,8,10]
cost_array = [2,3,4,5,9]
Weight = 25
n = len(val)
print(knapSack(Weight, cost_array, value_array, n))
I wrote a python program that has as input a matrix, in which, each element appears in each row and column once. Elements are only positive integers.
e.g.
0,2,3,1
3,1,0,2
1,3,2,0
2,0,1,3
Then i find all possible traversals. They are defined as such:
choose an element from the first column
move on to the next column and
choose the element that is not in the same line from previous elements in traversal and the element has not the same value with previous elements in traversal.
e.g.
0,*,*,*
*,*,*,2
*,3,*,*
*,*,1,*
I have constructed the code that finds the traversals for matrices 4x4, but i have trouble generalizing it for NxN matrices. My code follows below. Not looking for a solution, any tip would be helpful.
import sys # Import to input arguments from cmd.
import pprint # Import for a cool print of the graph
import itertools # Import to find all crossings' combinations
# Input of arguments
input_filename = sys.argv[1]
# Create an empty graph
g = {}
# Initialize variable for the list count
i = 0
# Opens the file to make the transfer into a matrix
with open(input_filename) as graph_input:
for line in graph_input:
# Split line into four elements.
g[i] = [int(x) for x in line.split(',')]
i += 1
# Initialize variable
var = 0
# Lists for the crossings, plus rows and cols of to use for archiving purposes
f = {}
r = {}
c = {}
l = 0
# Finds the all the crossings
if len(g) == 4:
for x in range (len(g)):
for y in range (len(g)):
# When we are in the first column
if y == 0:
# Creates the maximum number of lists that don't include the first line
max_num = len(g) -1
for z in range (max_num):
f[l] = [g[x][y]]
r[l] = [x]
c[l] = [y]
l += 1
# When on other columns
if y != 0:
for z in range(len(g)):
# Initializes a crossing archive
used = [-1]
for item in f:
# Checks if the element should go in that crossing
if f[item][0] == g[x][0]:
if g[z][y] not in f[item] and z not in r[item] and y not in c[item] and g[z][y] not in used:
# Appends the element and the archive
f[item].append(g[z][y])
used.append(g[z][y])
r[item].append(z)
c[item].append(y)
# Removes unused lists
for x in range (len(f)):
if len(f[x]) != len(g):
f.pop(x)
#Transfers the value from a dictionary to a list
f_final = f.values()
# Finds all the combinations from the existing crossings
list_comb = list(itertools.combinations(f_final, i))
# Initialize variables
x = 0
w = len(list_comb)
v = len(list_comb[0][0])
# Excludes from the combinations all invalid crossings
while x < w:
# Initialize y
y = 1
while y < v:
# Initialize z
z = 0
while z < v:
# Check if the crossings have the same element in the same position
if list_comb[x][y][z] == list_comb[x][y-1][z]:
# Removes the combination from the pool
list_comb.pop(x)
# Adjust loop variables
x -= 1
w -= 1
y = v
z = v
z += 1
y += 1
x += 1
# Inputs the first valid solution as the one to create the orthogonal latin square
final_list = list_comb[0]
# Initializes the orthogonal latin square matrix
orthogonal = [[v for x in range(v)] for y in range(v)]
# Parses through the latin square and the chosen solution
# and creates the orthogonal latin square
for x in range (v):
for y in range (v):
for z in range (v):
if final_list[x][y] == g[z][y]:
orthogonal[z][y] = int(final_list[x][0])
break
# Initializes the orthogonal latin square matrix
gr_la = [[v for x in range(v)] for y in range(v)]
# Creates the greek-latin square
for x in range (v):
for y in range (v):
coords = tuple([g[x][y],orthogonal[x][y]])
gr_la[x][y] = coords
pprint.pprint(gr_la)
Valid traversals for the 4x4 matrix above are:
[[0123],[0312],[3210],[3021],[1203],[1032],[2130],[2301]]
Further to my previous, helpfully addressed, question here
How to centre the origin in the centre of an imshow() plot
after some fiddling about with the some parameters, spyder now consistently shows a blank blue output. It is baffling!!
I've forced the dtype to be uint8 (I read this on a related question that this may be the cause) but to no avail.
EDIT: (Thanks to the rapid responses) here is the relevant code (from a larger program for modelling diffraction through a square aperture):
import numpy as np
import matplotlib.pyplot as plt
def expo(x,y,z,xp,yp,k):
"""
Function of the integrand in Eq. 5
"""
return np.exp((1j*k/(2*z))*(((x-xp)**2) + ((y-yp)**2)))
def square_2dsimpson_eval(a,b,n):
simp_eval = np.zeros((n+1,n+1))
deltap = (b-a)/n
xp = 0
yp = 0
w = np.zeros((n+1,n+1))
x=0
y=0
for h in range(n+1): #the first two for loops produce the 2d Simpson matrix of coeffecients
if h == 0 or h==n:
w[0,h] = 1
elif h%2 != 0:
w[0,h]=4
elif h%2 == 0:
w[0,h]=2
for g in range(n+1):
if g ==0 or g==n:
w[g,0]=1
elif g%2 != 0:
w[g,0]=4
elif g%2 == 0:
w[g,0]=2
for h in range(1,n+1):
for g in range(1,n+1):
w[h,g]=w[0,h]*w[g,0]
for h in range(0,n+1):
xp = h*deltap
for g in range(0,n+1):
yp = g*deltap
simp_eval[h,g] = expo(x,y,z,xp,yp,k) #the integrand
return (k/(2*np.pi*z))*((deltap**2)/9)*(np.sum(simp_eval*w))
n = 3.3
#this loop checks that user's N is even as required for Simpson's rule
while n % 2 != 0:
n = int(input("Type an even N value: "))
if n % 2 == 0:
break
else:
print("n must be even you noob!")
lam=float(input("Type light wavelength in mm: "))
k=(2*np.pi)/lam
z=float(input("Type screen distance, z in mm: "))
rho=float(input("Type rho in mm: "))
delta = 2/n
intensity = np.zeros((n+1,n+1),dtype='uint8')
for i in range(n+1):
x=-1+(i*delta)
for j in range(n+1):
y =-1+(j*delta)
intensity[i,j] = (abs(square_2dsimpson_eval(-rho/2,rho/2,n)))**2
print(intensity.dtype)
plt.imshow(intensity)
plt.show()
The plot has gone from this:
to this:
Thanks in advance.
Without Even knowing the code that produces either image, I can only say that the second image seems to be a cutout of the first image in a region where there is no data or data is close to or equal the minimum value.
Instructions: Compute and store R=1000 random values from 0-1 as x. moving_window_average(x, n_neighbors) is pre-loaded into memory from 3a. Compute the moving window average for x for the range of n_neighbors 1-9. Store x as well as each of these averages as consecutive lists in a list called Y.
My solution:
R = 1000
n_neighbors = 9
x = [random.uniform(0,1) for i in range(R)]
Y = [moving_window_average(x, n_neighbors) for n_neighbors in range(1,n_neighbors)]
where moving_window_average(x, n_neighbors) is a function as follows:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
# To complete the function,
# return a list of the mean of values from i to i+width for all values i from 0 to n-1.
mean_values=[]
for i in range(1,n+1):
mean_values.append((x[i-1] + x[i] + x[i+1])/width)
return (mean_values)
This gives me an error, Check your usage of Y again. Even though I've tested for a few values, I did not get yet why there is a problem with this exercise. Did I just misunderstand something?
The instruction tells you to compute moving averages for all neighbors ranging from 1 to 9. So the below code should work:
import random
random.seed(1)
R = 1000
x = []
for i in range(R):
num = random.uniform(0,1)
x.append(num)
Y = []
Y.append(x)
for i in range(1,10):
mov_avg = moving_window_average(x, n_neighbors=i)
Y.append(mov_avg)
Actually your moving_window_average(list, n_neighbors) function is not going to work with a n_neighbors bigger than one, I mean, the interpreter won't say a thing, but you're not delivering correctness on what you have been asked.
I suggest you to use something like:
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
mean_values = []
for i in range(n):
temp = x[i: i+width]
sum_= 0
for elm in temp:
sum_+= elm
mean_values.append(sum_ / width)
return mean_values
My solution for +100XP
import random
random.seed(1)
R=1000
Y = list()
x = [random.uniform(0, 1) for num in range(R)]
for n_neighbors in range(10):
Y.append(moving_window_average(x, n_neighbors))