Python - global variable inside a while loop - python-3.x

I have this code, where:
last_price - is a variable that gets data from a price feed.
the code, does not work as intended. it shows this output "2 test line Y", but it should show 'test line success Y'
EDIT: I cannot use "continue", because last_price is changing every second, and (Y = 'test line Y') will become (Y = 'some other command') and the code will continue execute order_succeeded_1 indefinitely.
How can I fix this code?
last_price = 230
SL = 100
SL1 = 200
SL2 = 300
SL3 = 400
X = 'yes X'
Y = 'yes Y'
Z = 'yes Z'
def addvar (A, B):
while True:
global X, Y, Z
if X == 'test line X':
print ('test line success X')
break
if Y == 'test line Y':
print ('test line success Y')
break
if Z == 'test line Z':
print ('test line success Z')
break
if SL < last_price <= SL1 : # 100 --- 200
order_succeeded = A+B # 10
X = 'test line X'
print (order_succeeded, X)
break
if SL1 < last_price <= SL2 : # 200 --- 300
order_succeeded_1 = A-B # 2
Y = 'test line Y'
print (order_succeeded_1, Y)
break
if SL2 < last_price <= SL3 : # 300 --- 400
Z = 'test line Z'
order_succeeded_2 = A * B # 24
print (order_succeeded_2, Z)
break
addvar (6, 4)

You need to use continue instead of break here, when you use break you get out of your while and Y == 'test line Y' is not executed for the second time:
if SL1 < last_price <= SL2: # 200 --- 300
order_succeeded_1 = A - B # 2
Y = 'test line Y'
print(order_succeeded_1, Y)
continue

Related

Why my function always show me the same error?

def formater_un_gobblet(gobblet):
if gobblet == []:
return None
w = [1,2]
for i in w:
x = GOBBLET_REPRÉSENTATION[int(i)]
z = [0,1,2,3]
for l in z:
y = x[int(l)]
gobblet = [x,y]
return (x,y)
This is my Gobblet_representation:
GOBBLET_REPRÉSENTATION = {1: ["▫", "◇", "◯", "□"],2: ["▪", "◆", "●", "■"],}
And when I made my test : gobblet[1,3], it is supposed to be ["▫", "◇", "◯", "□"] for x and "□" for y but it shows me ["▪", "◆", "●", "■"] for x and "■" for y all the time - same for gobblet[1,2]. What am I doing wrong?
you can use one of those
def formater_un_gobblet(gobblet):
if gobblet == []:
return None
w = [1,2]
for i in w:
x = GOBBLET_REPRÉSENTATION[int(i)]
if i == gobblet[0]:
break
z = [0,1,2,3]
for l in z:
y = x[int(l)]
if l == gobblet[1]:
break
gobblet = [x,y]
return (x,y)
or
def formater_un_gobblet2(gobblet):
if gobblet == []:
return None
x= GOBBLET_REPRÉSENTATION[int(gobblet[0])]
y=x[gobblet[1]]
return (x,y)

Get a certain combination of numbers in Python

Is there a efficient and convenient solution in Python to do something like -
Find largest combination of two numbers x and y, with the following conditions -
0 < x < 1000
0 < y < 2000
x/y = 0.75
x & y are integers
It's easy to do it using a simple graphing calculator but trying to find the best way to do it in Python
import pulp
My_optimization_prob = pulp.LpProblem('My_Optimization_Problem', pulp.LpMaximize)
# Creating the variables
x = pulp.LpVariable("x", lowBound = 1, cat='Integer')
y = pulp.LpVariable("y", lowBound = 1, cat='Integer')
# Adding the Constraints
My_optimization_prob += x + y #Maximize X and Y
My_optimization_prob += x <= 999 # x < 1000
My_optimization_prob += y <= 1999 # y < 2000
My_optimization_prob += x - 0.75*y == 0 # x/y = 0.75
#Printing the Problem and Constraints
print(My_optimization_prob)
My_optimization_prob.solve()
#printing X Y
print('x = ',pulp.value(x))
print('y = ',pulp.value(y))
Probably just -
z = [(x, y) for x in range(1, 1000) for y in range(1, 2000) if x/y==0.75]
z.sort(key=lambda x: sum(x), reverse=True)
z[0]
#Returns (999, 1332)
This is convenient, not sure if this is the most efficient way.
Another possible relatively efficient solution is -
x_upper_limit = 1000
y_upper_limit = 2000
x = 0
y = 0
temp_variable = 0
ratio = 0.75
for i in range(x_upper_limit, 0, -1):
temp_variable = i/ratio
if temp_variable.is_integer() and temp_variable < y_upper_limit:
x = i
y = int(temp_variable)
break
print(x,y)

Why is the result of this division "inf"?

I have the following code to compute a desired quantity:
import numpy as np
N = 2
lamda = 2
mu = 1
a = 0.5
St_Sp = np.arange(- N, N + 1)
Card = St_Sp.shape[0]
#%% Define infintesimal generator
def In_Ge(x, y):
if x == N or x == - N:
re = 0
elif x - y == - 1:
re = lamda
elif x - y == 1:
re = mu
elif x - y == 0:
re = - (mu + lamda)
else: re = 0
return re
x = St_Sp[0]
y = In_Ge(x, x) / (In_Ge(x, x) + np.log(a))
b = - 1 / y
print(b)
The result is inf. I checked and see that the value of y is non-zero, so I could not understand why such phenomenon happens. Could you elaborate on this issue?
#pinegulf's comment solves my question:
Your 'In_Ge(x,x)' retruns 0, thus y= 0 and 1/0 is pretty badly defined. Edit: You say it's not, but your x==--2 and functions first if is invoked.

Calculate the number of paths in a grid from top left to bottom right

I need to calculate the number of paths from top left to right bottom where a valid path is path that crosses all the squares in the grid (and exactly once for every square)
I'm using the backtracking technique. Unfortunately, count is 0 in the end of the calculation. Printing t, I see that it never gets to n-1.
What's wrong with my algorithm?
n = 4
count = 0
m = [[False for x in range(n)] for y in range(n)]
def num_of_paths(m, x, y, t):
print(t)
global count
# check if we reached target
if x == (n - 1) and y == (n - 1):
if t < (n * n):
# not on time, prune the tree here
return
elif t == n * n:
# completed a full path in the grid and on time
count += 1
if t > n * n:
return
# Right
if x + 1 < n and m[x + 1][y] == False:
m[x + 1][y] = True
num_of_paths(m, x + 1, y, t + 1)
m[x + 1][y] = False
# Left
if x - 1 > 0 and m[x - 1][y] == False:
m[x - 1][y] = True
num_of_paths(m, x - 1, y, t + 1)
m[x - 1][y] = False
# Down
if y + 1 < n and m[x][y + 1] == False:
m[x][y + 1] = True
num_of_paths(m, x, y + 1, t + 1)
m[x][y + 1] = False
# Up
if y - 1 > 0 and m[x][y - 1] == False:
m[x][y - 1] = True
num_of_paths(m, x, y - 1, t + 1)
m[x][y - 1] = False
num_of_paths(m, 0, 0, 0)
print(count)
There are the following issues:
The starting cell is not marked with m[0][0] = True, so after going right, the algorithm will go left again, and actually visit that cell twice. To resolve this, you can move the code for managing the m values away from where you have it now (4 times) and apply it to the current cell (once). This includes the if m[..][..] check, and the assignments of True and False.
The if conditions that relate to the left and up directions should compare the coordinate with >= 0, not with > 0: a zero value for a coordinate is still within range.
t should start with 1, since you compare its value with n * n. Or else you should compare with n * n - 1. In my correction below I will start with t = 1.
Not a real problem, but after doing count += 1 it would make sense to immediately return, since there is no possibility anymore to extend the path further.
Some other remarks:
When n is even, there is no valid path, so even when corrected, the function is bound to return 0 in that case
The number of paths this algorithm visits is exponential, O(2n²). For n > 6, don't wait for it...
Here is a corrected version of your code. Comments should clarify what was changed and why:
n = 5
count = 0
m = [[False for x in range(n)] for y in range(n)]
def num_of_paths(m, x, y, t):
global count
# Moved the "visited" check to here. No need to add `== True`.
if m[x][y]:
return
if x == (n - 1) and y == (n - 1):
if t < (n * n):
return
else: # Removed the unnecessary condition here
count += 1
# Added a return here
return
# Removed an if-block of which the condition could never be true
# Moved the "visited" marking to here:
m[x][y] = True
if x + 1 < n:
num_of_paths(m, x + 1, y, t + 1)
# Corrected "> 0" to ">= 0"
if x - 1 >= 0:
num_of_paths(m, x - 1, y, t + 1)
if y + 1 < n:
num_of_paths(m, x, y + 1, t + 1)
# Corrected "> 0" to ">= 0"
if y - 1 >= 0:
num_of_paths(m, x, y - 1, t + 1)
# Moved the "visited" unmarking to here:
m[x][y] = False
# Corrected the last argument
num_of_paths(m, 0, 0, 1)
print(count)
this code is working
n = 3
count=0
m = [[False for x in range(n)] for y in range(n)]
def num_of_paths(m,x,y):
# setting (x,y) position in m = True as we have crossed this square now
m[y][x]=True
global count
# check if we reached target
if x == (n - 1) and y == (n - 1):
# check if we haven't missed any square
for i in m:
if False in i:
m[y][x]=False
return
# increment count if we visited all squares
count+=1
m[y][x]=False
return
# setting up legel directions in which current point(x,y) should head next
dir={'up','down','left','right'}
if x==0:
dir-={'left'}
if x==n-1:
dir-={'right'}
if y==0:
dir-={'up'}
if y==n-1:
dir-={'down'}
# now we have all legal directions that (x,y) could go to
# now iterate over all possible directions of (x,y)
for i in dir:
if i=='left': # left means (x,y) will change to (x-1,y) i.e. change is (-1,0)
if m[y][x-1]==False: # it means left of (x,y) havent yet crossed i.e. it is legel to visit now
num_of_paths(m,x-1,y)
# similiarly for other possible directions
if i=='right':
if m[y][x+1]==False:
num_of_paths(m,x+1,y)
if i=='up':
if m[y-1][x]==False:
num_of_paths(m,x,y-1)
if i=='down':
if m[y+1][x]==False:
num_of_paths(m,x,y+1)
num_of_paths(m,0,0)
print(count)
let me know if there is some issue

What is the reason behind the output?

Input:
x, y = 20, 60
y, x, y = x, y-10, x+10
print(x, y)
Output:
50 30
What I expected?
x = 20
y = 60
y = x = 20
x = y - 10 = 20 - 10 = 10
y = x + 10 = 20
Expected output:
10 20
Why Isn't this the case? Is it because the expressions are evaluated first then the variable are assigned the value?
The right side is evaulated COMPLETELY before the left. Then the left hand side is evaluated left to right.
x, y = 20, 60
# x = 20, y = 60
# ----------------------
y, x, y = x, y-10, x+10
# Evaulate the right first:
# x, y-10, x+10 = 20, 50, 30
# So now we have
# y, x, y = 20, 50, 30
# Now it goes left to right so:
# y = 20
# x = 50
# y = 30 --> note this overwrote the first y assignment
print(x, y)
Thus
50 30

Resources