Why is the loop altering the if else stmt. after completing every second for loop and displays the same values as those were set in the beginning - python-3.4

matrix = 10 * [10 * [0]]
print("Before")
for x in range(10):
for y in range(10):
print(matrix[x][y])
for x in range(10):
for y in range(10):
print("X, Y", x, y)
if matrix[x][y]== 0:
print("Inside If")
print("Before Changing", matrix[x][y])
matrix[x][y] = 1
print("After Changing", matrix[x][y])
else:
print("Inside Else")
print("Before Changing", matrix[x][y])
matrix[x][y] = 0
print("After Changing", matrix[x][y])
print("--------------------------------------------------------")
print("After")
for x in range(10):
for y in range(10):
print(matrix[x][y])

the declaration of matrix causes the object to copy the sublist 10 times. That means, matrix is a list of 10 copies of a list of 10 zeroes.
Each iteration over x will set the values of all lists. Each iteration over y addresses the same value, but in different copies.
For sake of clarity, assume matrix=2*[2*[0]]
This looks like matrix=[[0,0],[0,0]]
If you set matrix[0][1]=1, it will set not only the second value of the first sublist, but also (because it is a copy) the second value of the second list:
matrix=[[0,1],[0,1]]
Because your iteration over y is an even number, it will set values to 1 first, then set them to 0 back. If y were uneven, you would end up with only 1's everywhere.
I think what you wanted is
matrix = [10*[0],10*[0],10*[0],10*[0],10*[0],10*[0],10*[0],10*[0],10*[0],10*[0]]
This will end up with a matrix filled with 1's

Related

CVXPY violates constraints when it solves SDP

Let's say that I want to solve the following problem.
minimize Tr(CY)
s.t. Y = xxT
x is 0 or 1.
where xxT indicates an outer product of n-1 dimension vector x. C is a n-1 by n-1 square matrix. To convert this problem to a problem with a single matrix variable, I can write down the code as follows by using cvxpy.
import cvxpy as cp
import numpy as np
n = 8
np.random.seed(1)
S = np.zeros(shape=(int(n), int(n)))
S[int(n-1), int(n-1)] = 1
C = np.zeros(shape=(n,n))
C[:n-1, :n-1] = np.random.randn(n-1, n-1)
X = cp.Variable((n,n), PSD=True)
constraints=[]
constraints.append(cp.trace(S # X) == 1)
for i in range(n-1):
Q = np.zeros(shape=(n,n))
Q[i,i] = 1
Q[-1,i] = -0.5
Q[i,-1] = -0.5
const = cp.trace(Q # X) == 0
constraints.append(const)
prob = cp.Problem(cp.Minimize(cp.trace(C # X)),constraints)
prob.solve(solver=cp.MOSEK)
print("X is")
print(X.value)
print("C is")
print(C)
To satisfy the binary constraint that the entries of the vector x should be one or zero, I added some constraints for the matrix variable X.
X = [Y x; xT 1]
Tr(QX) == 0
There are n-1 Q matrices which are forcing the vector x's entries to be 0 or 1.
However, when I ran this simple code, the constraints are violated severely.
Looking forward to see any suggestion or comments on this.

What is the inefficiency in this cairo code using alloc_locals

The following code:
func pow4(n) -> (m : felt):
alloc_locals
local x
jmp body if n != 0
[ap] = 0; ap++
ret
body:
x = n * n
[ap] = x * x; ap++
ret
end
func main():
pow4(n=5)
ret
end
is declared inefficient in the doc because of non-continuous memory.
I ran it and could not see any hole in the memory table:
Addr Value
-----------
⋮
###
⋮
1:0 2:0
1:1 3:0
1:2 5
1:3 1:2
1:4 0:21
1:5 25
1:6 625
so I don't understand where the problem is. I do see a hole with n=0 though:
Addr Value
-----------
⋮
###
⋮
1:0 2:0
1:1 3:0
1:2 0
1:3 1:2
1:4 0:21
⋮
1:6 0
that I can fix using:
jmp body if n != 0
x = 0
ret
but it's not what's suggested:
Move the instruction alloc_locals.
or Use tempvar instead of local.
You are correct that the inefficiency is due to the memory hole, and correct that it appears only for n=0. Holes do not cause an inefficiency just by existing, but rather, their existence usually means that an equivalent code could have executed using fewer memory cells in total (in this case, 6 instead of 7, in the memory section "1:"). To make it more efficient, one should aim to remove the hole (so that the parts before and after it become continuous), whereas your suggested solution just fills it (which the prover does anyway). So your solution would still use 7 memory cells in the memory segment; and will in fact also use 2 additional cells in the program section (for the x=0 command), so it is actually less efficient than leaving the hole empty: compile and check!
The inefficiency in the original code arises from the local variable x being assigned a memory cell even in the case n=0, despite not being used. To make it more efficient we would simply not want to declare and allocate x in this case.
This can be done by moving the alloc_locals command inside "body", so that it isn't executed (and the locals aren't allocated) in the n=0 case, as in the first suggestion: this saves one memory cell in the n=0 case and doesn't affect the n!=0 case. Note that alloc_locals does not have to appear right at the beginning of the code.
The second suggestion is to make x a tempvar instead of a local (and remove alloc_locals entirely). This again means no local variable is allocated in the n=0 case, thus again only 6 memory cells will be used instead of 7. And in fact, because the code is so simple, using the tempvar is also more efficient that declaring it as a local, at least when used as tempvar x = n * n, as it skips merges the ap += 1 command (which is what alloc_locals does in this case) with the x = n * n command, rather than run them separately.
Beyond discussing the theory, you should compile each of these options and compare the lengths of the code and memory segments obtained, and see what is really the most efficient and by how much: this is always true when optimizing, you should always check the actual performance.
So following #dan-carmon answer and for the sake of completeness, here is a summary of the possible implementations and their memory table "1" when n = 0 & n > 0
# n = 0 n = 5
1:0 2:0 1:0 2:0
1:1 3:0 1:1 3:0
1:2 0 1:2 5
1:3 1:2 1:3 1:2
1:4 0:14 1:4 0:14
1:5 0 1:5 25
1:6 625
Note however that the implementation using tempvar uses 2 slots less than the others in the program table "0".
Implementations tested
func pow4_reuse_slot(n) -> (m : felt):
alloc_locals
local x
jmp body if n != 0
x = 0
ret
body:
x = n * n
[ap] = x * x; ap++
ret
end
func pow4_alloc_in_body(n) -> (m : felt):
jmp body if n != 0
[ap] = 0; ap++
ret
body:
alloc_locals
local x
x = n * n
[ap] = x * x; ap++
ret
end
func pow4_use_tempvar(n) -> (m : felt):
jmp body if n != 0
[ap] = 0; ap++
ret
body:
tempvar x = n * n
[ap] = x * x
ret
end

Python recursive function recurSum(x, y)

This is my code:
def recurSum(x, y):
if x <= 1:
return x
return x + recurSum(x - 1)
if y <= 1:
return y
xxwjhefbhwjbfwjh efjehwbf ebrfe
print(recurSum(5, 10))
You can use the following:
def recurSum(x, y):
if x==0:
return y
return recurSum(x - 1, y) + x
In essence, the base case is when the first number has reached 0. If so, you return the other number. Otherwise, you perform once again the recursive sum.
This is another way to do this.
def recurSum(x, y):
return y if x < 1 else recurSum(x-1, x + y)
The expanded form of the above is:
def recurSum(x, runningSum):
if x < 1:
return runningSum;
else:
return recurSum(x-1, x + runningSum)
Does the function need to be recursive? I think you might be over complicating this a bit;
def sums(x,y):
output = y + sum(range(0,x+1))
return output
Here in one line you can add the values between 1 and x to y

Find number of iterations until a value reaches a limit

I have two numbers X and Y and the following pseudocode:
i = 0
While X < Y:
X = X + complex_formula
i += 1
Print i
complex_formula is independent from the X and its previous value.
So, I was wondering if there is any way to calculate the i without doing the iterations.
Is complex_formula also independent of i and timing? If so then it's a constant and this is just simple math:
i = Ceiling( (Y - X)/complex_formula)
X = X + i*complex_formula

How can I show that a function is always not commutative

I have the following vexing problem.
I have implemented the following function:
function bool less(nat x, nat y) {
if (y<>0) then
if (x<>0) then
return less(x-1,y-1);
else
return true;
end;
else
return false;
end;
end;
How can I show that for all x,y the following
less(x,y) and less(y,x) are not possible at the
same time?
Bye
Well, first of all I would ask you to consider the case of less(-1, -2), so we will have to define the function to be on the bounds of n ≥ 0. Also when the first input is equal to the second it will return true for both orderings, so we will have to assume that x ≠ y.
I would use Proof by Contradiction.
Assume that for some x and some y where x and y are both ≥ 0 and x≠y, that less(x,y) and less(y,x) are both true.
This would imply that while x and y are both nonzero, you subtract one from them n times until one of them is zero, checking x first. The function returns true when the first operand reaches zero, false when the second operand reaches zero while the first is nonzero.
There are two cases for this:
x reaches zero first. In this case n = x, because 0 = x - n(1).
y reaches zero first. In this case n = y, because 0 = y - n(1).
By our assumption, less(x,y) returned true, meaning that the function iterated x times, after which x - x(1) = 0 and y - x(1) > 0 (because y ≠ x, and the function didn't return false before hand).
Similarly, less(y,x) returned true, meaning that the function iterated y times, after which y- y(1) = 0 and x - y(1) > 0 (same reasons as before).
This gives us two useful relations: y - x > 0 and x - y > 0. rearranged: y > x and x > y (the semantic meaning of the function, but we have achieved this from the definition of how the function works and we have reduced it to the pure mathematics which we can work with certain axioms for).
From y > x and x > y, you can rearrange as x > x and y > y (If x is greater than y, then it is greater than all things y is greater than. y is greater than x, therefore x is greater than x).
This is a logical contradiction, and therefore our assumption (that they were both true) is incorrect.
Therefore, by Proof by Contradiction, when x ≠ y, and x,y ≥ 0, the function less cannot return true for both less(x,y) and less(y,x).
(it's been a while since I had to do a proof (though I'm going to have to do some coming up so it is good practice) so I might be a bit rusty. If any one sees an error, please point it out and I will try to fix it)

Resources