Counter doesn't count up - counter

while True:
def update():
global counter
global points
counter = points
counter = 0
points = counter + 1
print(points)
First off I am very new to this I am wonder my simple counter only print 1 instead of counting up.

Your indentation is off. Also some of your code seems to not be of use for what you're outputting.
Try this:
counter = 0
while True:
counter = counter + 1
print(counter)
I'm not sure why you are using two variables. The points variable isn't doing anything. Also you never call the update() function if you were trying to do that.
Maybe go read the Python Tutorial? Because you seem a little lost.
Happy Coding!

When posting Python please take care to maintain the indents (the spaces before each line of your code), because they are critical to how Python programs work.
You have placed the definition of the update() function inside the while loop. Defining a function is not the same as running it, so the update would not actually be carried out as part of the loop. There is pretty much no reason to put a function definition inside a while loop.
It would also be better for update() not to be a function, since it depends on both variables being global and does not really have any useful function once parameterized.
The reset of counter to 0 is also inside the loop. This means that the counter resets every time around the loop, which is why it keeps printing 1.
This will work, although unless you have a reason for using the variable points it would be better not to since you only actually need counter:
counter = 0
while True:
points = counter + 1
counter = points
print(points)

A python program,print a number starting from 0.
def update():
counter = 0
while(True):
print(counter)
counter = counter + 1
update()

Related

In CoffeeScript, is it possible to increment a for loop manually?

My CoffeeScript is as follows:
for i in [1..3]
i++ if i is 1
console.log i
Expected output is
2
3
Generated output is
2
2
3
The issue is that CoffeeScript keeps a private variable to keep track of the iteration, _i, but if I try to increment that _i++, then the private variable changes to _j and constantly evades me.
So how can I increment the loop manually using CoffeeScript?
You can't manually increment the loop's counting variable. Instead, you need to use continue to skip one or more iterations.
for i in [1..3]
continue if i is 1
console.log i
You should never attempt to access or modify CoffeeScript's generate variables, those are an implementation detail and you cannot rely on them being present.

clearer explanation of function level scope for recursion

This is an example from the book 'Matlab for Neuroscientists'. I don't understand the order in which, or why, g gets assigned a new value after each recursion. Nor do I understand why "factorial2" is included in the final line of code.
here is a link to the text
Basically, I am asking for someone to re-word the authors explanation (circled in red) of how the function works, as if they were explaining the concept and processes to a 5-year old. I'm brand new to programming. I thought I understood how this worked from reading another book, but now this authors explanation is causing nothing but confusion. Many thanks to anyone who can help!!
A recursive method works by breaking a larger problem into smaller problems each time the method is called. This allows you to break what would be a difficult problem; a factorial summation, into a series of smaller problems.
Each recursive function has 2 parts:
1) The base case: The lowest value that we care about evaluating. Usually this goes to zero or one.
if (num == 1)
out = 1;
end
2) The general case: The general case is what we are going to call until we reach the base case. We call the function again, but this time with 1 less than the previous function started with. This allows us to work our way towards the base case.
out = num + factorial(num-1);
This statement means that we are going to firstly call the function with 1 less than what this function with; we started with three, the next call starts with two, the call after that starts with 1 (Which triggers our base case!)
Once our base case is reached, the methods "recurse-out". This means they bounce backwards, back into the function that called it, bringing all the data from the functions below it!It is at this point that our summation actually occurs.
Once the original function is reached, we have our final summation.
For example, let's say you want the summation of the first 3 integers.
The first recursive call is passed the number 3.
function [out] = factorial(num)
%//Base case
if (num == 1)
out = 1;
end
%//General case
out = num + factorial(num-1);
Walking through the function calls:
factorial(3); //Initial function call
//Becomes..
factorial(1) + factorial(2) + factorial(3) = returned value
This gives us a result of 6!

Matlab: recursive algorithm to return the run count easily without profiler?

I would like to get the number of iterations that the recursive mlfnonneg requires. Currently, I use profiler for this but it would be more useful to get the number as a return value from the function. Is there any easy way to get it?
I measure the running time of a function like this
h=#() mlfnonneg(lb,ub,mlfBinCor,method);
tElapsed=timeit(h);
and now the function mlfnonneg should return the number of iterations. I have considered adding a ticker that the function always returns but I don't know how to get the return value after using timeit. How to get the running time and the running count of the recursive algorithm elegantly?
You can always add an optional return value to a function which you can use as a counter. Something like this:
[... count] = f(...)
% Do stuff here
if <some condition>
% Recurse
[... count] = f(...);
count = count + 1;
else
% Terminal condition
count = 1;
end
You should just call your function one more time to get the count. This should not be a significant problem, since timeit actually performs multiple calls to your function to get an average metric.
I don't know if this is an option for you - but you could create a global variable IT_COUNT that you declare both at the top level, and inside your function.
Before calling timeit() you set the variable to zero; inside the routine you increment it for every loop. When the function returns you print out the result - and there is your answer.
It does depend on you being able to modify the code to mlfnonneg to include the counter. I don't see an easy way around that, but maybe others have a better idea.
update inspired by Luis Mendo's (now deleted) answer that basically says the same thing, a bit more information.
In your mlfnonneg routine, add the following two lines (in a place where they are executed "once per iteration"):
global IT_COUNT;
if numel(IT_COUNT)==0, IT_COUNT = 1; else IT_COUNT = IT_COUNT + 1; end
This ensures that if you forget to create the variable at the top level, the code will not crash (you will thank me in the future, when you re-use this code and don't remember that you need a global variable...)
At the top level, add
global IT_COUNT
IT_COUNT = 0;
Then run your timeit() routine; finally use
fprintf(1, "The number of iterations was %d\n", IT_COUNT);
to get the answer you were looking for.

How can I get a persistent counter in a Matlab function without an `isempty` hack?

I would like to add a counter to a function so it knows how many times it has been called.
Here is what I am currently using.
function Foo ()
persistent counter;
if (isempty(counter))
counter = 0
end
counter = counter + 1
end
Line 3-5 looks like a hack.
How can I directly initialize counter to 0 without having it reset or using isempty?
Merlin, isempty(marker) should be isempty(counter) but I'm sure that's what you meant. The code you have is what the matlab documentation recommends if you look here and here. Additionally, this is also what Loren uses as well. So what you have is correct (sorry if this answer is not satisfying).

return NOT exiting function properly in MATLAB

I'm running a recursive function which searches a room for an object. This code is working in conjunction with another process essentially running the same code. The first thing the code does is check to see if the other one has found the object and, if so, it is supposed to break out of the function.
When I do the check to see if the other process has found the object, if it has, I use "return" to break out of that function at which time it's supposed to move onto other lines of code...However, for some reason it doesn't fully break out but instead just runs the function again and again.
Any ideas on how I can get it to break out?
I would and can provide the code but it's kind of long
EDIT
Parent script
!matlab -r "zz_Mock_ROB2_Find" & distT = 0.3;
Rob1_ObjFound = 0;
matrix = search_TEST_cam(rob, vid, 0.3, XYpos, 'north', stack, matrix, 0);
disp('I"M OUT')
Recursive code
function matrix = search_TEST_cam(rob1, vid, distT, startingPos, currentDir, stack, matrix, bT)
Rob1_ObjFound = 0;
Rob2_ObjFound = 0;
try
load('Rob2_ObjFound.mat', 'Rob2_ObjFound');
catch
end
if(Rob2_ObjFound == 1)
setDriveWheelsCreate(rob1, 0, 0);
disp('ROB_2 FOUND THE OBJECT')
pause(0.5)
BeepRoomba(rob1)
pause(0.5)
setDriveWheelsCreate(rob1, 0, 0);
return
end
Use break to break out of a for or a while loop and terminate execution, i.e., statements after that are ignored. For e.g.,
for i=1:5
if i==3
break
else
fprintf('%u,',i)
end
end
outputs 1,2, and the code terminates when i=3. If you have nested loops, break will only break out of its current loop and move on to the parent loop.
To skip only the current iteration and move on to the next, use continue. Using the same example,
for i=1:5
if i==3
continue
else
fprintf('%u,',i)
end
end
outputs 1,2,4,5,.
Using return in a function just returns control to the parent function/script that called it.
It seems like you're using the wrong one in your code. However, it's hard to tell without knowing how you're using them. Anyway, you can try one of these three and see if it makes a difference.
It's hard to say without seeing your code, but I doubt it's a problem with the RETURN statement. It's more likely a problem with how you've set up your recursion. If your recursive function has called itself a number of times, then when you finally invoke a RETURN statement it will return control from the current function on the stack to the calling function (i.e. a previous call to your recursive function). I'm guessing the calling function doesn't stop the recursion properly and ends up calling itself again, continuing the recursion.
My advice: check the exit conditions for your recursive function to make sure that, when the object is found and the most recent call returns, every previous call is properly informed that it should return as well.