i have two functions with while loop, the results from the first loop is used in the second one as an until condition, but when calling the two functions in the main it execute only the first one and it doesn't even enter the second function it just give me the results of the first loop.
in the first function self.user_association() there is a linear optimization using PULP i though it is the one causing the problem but it was not because when calling the loop function block_estimated_access_link() in the second one it works just fine but my program does not work that way because as i said i use the results from the first loop in the second one. Here is the code, can someone tell me what am i doing wrong or what is the problem exactly?
def block_Estimation_ACCESS_LINK(self):
while (self.iteration < self.Iter_max):
self.User_association()
self.estimated_access_power()
self.calcul_alpha()
self.calcul_rate_am()
self.User_association()
self.iteration += 1
def block_bg_power_allocation(self):
EPS = 0.0000000000001
RamTot = 0
while (self.iteration < self.Iter_maxB):
self.calcul_power_backhaul()
print('backhaul Pok=', self.p_ok)
self.calcul_delta()
self.calcul_rok()
for i in self.station:
for j in self.users:
self.Ram = numpy.delete(self.Ram, self.Ram[0])
RamTot = sum(self.Ram)
if EPS <= (self.Rok[i] - sum(self.Ram[i])):
self.iteration += 1
def main(self):
self.block_Estimation_ACCESS_LINK()
self.block_bg_power_allocation()
In the first function you're doing this:
self.iteration += 1
And then, in the second function your stop condition is:
while (self.iteration < self.Iter_maxB):
So the first function would increment self.iteration to self.Iter_max. Now, if self.Iter_maxB is the same value as self.Iter_max, your second functions loop will never execute. I suspect that's what's happening here. Check those two varaibles.
Fix would be something like this if you want to execute both those loops the same number of time:
def main(self):
self.block_Estimation_ACCESS_LINK()
self.iteration = 0
self.block_bg_power_allocation()
Related
I might be asking a simple question. I have a python program that runs every minute. But I would like a block of code to only run once the condition changes? My code looks like this:
# def shortIndicator():
a = int(indicate_5min.value5)
b = int(indicate_10min.value10)
c = int(indicate_15min.value15)
if a + b + c == 3:
print("Trade posible!")
else:
print("Trade NOT posible!")
# This lets the processor work more than it should.
"""run_once = 0 # This lets the processor work more than it should.
while 1:
if run_once == 0:
shortIndicator()
run_once = 1"""
I've run it without using a function. But then I get an output every minute. I've tried to run it as a function, when I enable the commented code it sort of runs, but also the processing usage is more. If there perhaps a smarter way of doing this?
It's really not clear what you mean, but if you only want to print a notification when the result changes, add another variable to rembember the previous result.
def shortIndicator():
return indicate_5min.value5 and indicate_10min.value10 and indicate_15min.value15
previous = None
while True:
indicator = shortIndicator()
if previous is None or indicator != previous:
if indicator:
print("Trade possible!")
else:
print("Trade NOT possible!")
previous = indicator
# take a break so as not to query too often
time.sleep(60)
Initializing provious to None creates a third state which is only true the first time the while loop executes; by definition, the result cannot be identical to the previous result because there isn't really a previous result the first time.
Perhaps also notice the boolean shorthand inside the function, which is simpler and more idiomatic than converting each value to an int and checking their sum.
I'm guessing the time.sleep is what you were looking for to reduce the load of running this code repeatedly, though that part of the question remains really unclear.
Finally, check the spelling of possible.
If I understand it correctly, you can save previous output to a file, then read it at the beginning of program and print output only if previous output was different.
I have a pretty specific problem. I want to measure execution time of the generator loop (with the yield keyword). However, I don't know in what intervals next() will be called on this generator. This means I can't just get the timestamp before and after the loop. I thought getting the timestamp at the beginning and end of each iteration will do the trick but I'm getting very inconsistent results.
Here's the test code:
import time
def gen(n):
total = 0
for i in range(n):
t1 = time.process_time_ns()
# Something that takes time
x = [i ** i for i in range(i)]
t2 = time.process_time_ns()
yield x
total += t2 - t1
print(total)
def main():
for i in gen(100):
pass
for i in gen(100):
time.sleep(0.001)
for i in gen(100):
time.sleep(0.01)
if __name__ == '__main__':
main()
Typical output for me looks something like this:
2151918
9970539
11581393
As you can see it looks like the delay outside of the loop somehow influences execution time of the loop itself.
What is the reason of this behavior? How can I avoid this inconsistency? Maybe there's some entirely different way of doing what I'm trying to achieve?
You can switch the yield x and total += t2 - t1 lines to only count the time it takes to create x.
For more in dept also see: Behaviour of Python's "yield"
I'm trying to increase the count of an integer given that an if statement returns true. However, when this program is ran it always prints 0.I want n to increase to 1 the first time the program is ran. To 2 the second time and so on.
I know functions, classes and modules you can use the global command, to go outside it, but this doesn't work with an if statement.
n = 0
print(n)
if True:
n += 1
Based on the comments of the previous answer, do you want something like this:
n = 0
while True:
if True: #Replace True with any other condition you like.
print(n)
n+=1
EDIT:
Based on the comments by OP on this answer, what he wants is for the data to persist or in more precise words the variable n to persist (Or keep it's new modified value) between multiple runs times.
So the code for that goes as(Assuming Python3.x):
try:
file = open('count.txt','r')
n = int(file.read())
file.close()
except IOError:
file = open('count.txt','w')
file.write('1')
file.close()
n = 1
print(n)
n += 1
with open('count.txt','w') as file:
file.write(str(n))
print("Now the variable n persists and is incremented every time.")
#Do what you want to do further, the value of n will increase every time you run the program
NOTE:
There are many methods of object serialization and the above example is one of the simplest, you can use dedicated object serialization modules like pickle and many others.
If you want it to work with if statement only. I think you need to put in a function and make to call itself which we would call it recursion.
def increment():
n=0
if True:
n+=1
print(n)
increment()
increment()
Note: in this solution, it would run infinitely.
Also you can use while loop or for loop as well.
When you rerun a program, all data stored in memory is reset. You need to save the variable somewhere outside of the program, on disk.
for an example see How to increment variable every time script is run in Python?
ps. Nowadays you can simply do += with a bool:
a = 1
b = True
a += b # a will be 2
My code is really simple:
import numpy
def f(x):
return x**2 +1
f_min=10
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
else:
print (x_min)
It gives me the correct result (x-->0) but not only once but alot of times. Why is that and how can I keep it from doing so?
Because you told it to. :-)
Your if statement reads:
if I have a new minimum, record the value and position;
otherwise, print the existing minimum.
Any time you don't find a new minimum, you print. Since this function has its minimum early in your range, you get a lot of output.
If you want the global minimum printed only once, then do it only once: move it outside of the loop.
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
print (x_min)
To fix this, move the print statement out of the for loop:
import numpy
def f(x):
return x**2 +1
f_min=10
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
print (x_min)
Why do this? Well, before, when you had the print statement in the for loop, each time the for loop went through, whenever the if statement was not true, it printed, so you got a bunch of printed things. Now, when you move it out of the for loop, it can only be printed once, and the program works as you expect.
I am quering a database for some paramaters which depend on a attribute called count! count can be incremented incase the 1st query does not return anything. Here is a sample code
sls = {(213.243, 55.556): {}, (217.193, 55.793): {}, (213.403, 55.369): {}}
for key in sls.keys:
if not sls[key]:
ra, dec = key[0], key[1]
search_from_sourcelist(sl, ra,dec)
count = 1
def search_from_sourcelist(sl, ra,dec):
dist = count/3600.0
sls[(ra,dec)] = sl.sources.area_search(Area=(ra,dec,dist))
return
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This is to be done for all keys in sls dictionary, untill all the keys have a value!!
Here is the most fundamental recursive function
def countdown(n):
if n == 0:
return "Blastoff"
else:
print "T minus %s" % n
return countdown(n-1)
You will notice that countdown returns itself with a modified argument, in this case n but -1, so if you actually followed this all the way through you would get
(-> indicates a call)
countdown(5) -> countdown(4) -> countdown(3) -> countdown(2) -> countdown(1) -> countdown(0) #stop
So now you understand what a recursive function looks like you realize you never actually return a call of your own function, thus your code is not recursive
We use recursion because we want to boil a task down to its simplest form then work from there, so a good example of this would be the mcnuggets problem. So you need to tell us what you are trying to achieve and how it can be made a smaller problem (or more importantly why.) Are you sure you cannot do this iteratively? remember you don't want to blow your stack depth because python is NOT tail recursive by standard
Recursion is useful when you find a way to reduce the initial problem to a "smaller version of itself".
The standard example is the factorial function
def fac(n):
return n * fac(n-1) if n > 1 else 1
Here you reduce the problem of calculating the factorial of n to calculating the factorial of n-1.
In your code there is no such "reduction". You just increment a value and start the same problem over again. Thus, I recommend you solve it iteratively.
I'm not sure that you need a recursive algorithm for this.
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This can be done with a while loop as follows:
for key, value in sls.iteritems():
if not value:
ra, dec = key[0], key[1]
count = 1
while not search_from_sourcelist(sls, ra, dec):
count += 1
But if you really do want to do this recursively, you can do it as follows, leave a comment and I'll write it up.
Further, you should look into your search_from_sourcelist function, as it always returns None