Hey so I am working on a program that requires a day/night cycle. Here is the function that I made to get it to start working:
def epoch():
for i in range(0,varb.run_number):
print("it is now day")
epoch_state = 1
yield epoch_state
time.sleep(varb.day_night_length)
print("it is now night")
epoch_state = 0
yield epoch_state
time.sleep(varb.day_night_length)
I can find nothing wrong with it, but when I call it I get this:
<generator object epoch at 0x01036670>
Any ideas on how to fix this?
P.S. The idea here is to run the cycle while printing out the state and returning the state
P.P.S. anything with varb. is a global with an unimportant numerical value
There is no error here. The function is working correctly.
You created a generator function by using yield expressions. You now need to iterate over your generator. Until you do, the generator is paused.
You could use list() for that:
result = list(epoch())
or a for loop:
for result in epoch():
print(result)
Related
Can Someone tell me what exactly is happening here.Is the print statement executing after all the draw [3,2,1] are completed or it's happening simultaneously.I tried adding print(n) but still couldn't figure out. Is it unpacking after storing the values of ('#'*n).I am getting what I desired but just needed to understand what is actually happening
def draw(n:int):
if n<0:
return
draw(n-1)
print ('#'*n)
draw(3)
the print comes after executing all the draw calls. if you want to print it in the same order make sure print comes first before calling the draw again
def draw(n:int):
if n<0:
return
print ('#'*n) # this should come first before the next call
draw(n-1)
to understand the sequence of the recursion, follow this visualization tool. just write your provided script and run it.
https://pythontutor.com/visualize.html#mode=edit
So here's my code.
def bubblesort(list):
global step
global oldlist
print("""
ORIGINAL LIST""")
print(list)
for i in range(len(list)):
for j in range(len(list)-1):
if float(list[j])>float(list[j+1]):
list[j], list[j+1] = list[j+1], list[j]
if oldlist==list:
**end(list)**
else:
oldlist=list
step=step+1
print("""
STEP""",step)
print(list)
end(list)
def end(list):
global step
step=step+1
print("""
STEP""",step)
print(list)
step=0
oldlist=[]
list=[]
number=int(input("How many numbers do you want to input to sort? : "))
for i in range(1,number+1):
value=float(input("INPUT NUMBER : "))
list.append(value)
bubblesort(list)
The issue is the bit of code which I have is "end(list)" bare in mind I've included the ** to make it easier to see on here it's not actually in the code. It simply won't call the subroutine when I ask it to. I know it definitely runs through the if since if i put a "print" or "break" in they both work it just won't jump to a sub-routine. Furthermore, the time I call that subroutine later on in the code works and does go to the subroutine. So i'm a bit lost as to what I've done wrong here. Any help? Would be much appreciated :)
There are quite a few things wrong with your code, and your question. Let's go through them:
First of all, the formatting was not great (I've suggested an edit). This might not sound like a big deal ("Hey, as long as it works...") but it's actually crucial: I work with python every day, and I had trouble understanding your code
You're talking about subroutines. In python, we usually refer to those as functions, or methods.
You're using globals variables all over the place. This might work in little toy examples like this one, but it will fall apart VERY fast
As David Buck said, list is one of the basic data structures: 1 in an instance of int and [1,2,3] is an instance of list). It's a really bad idea to override it.
I'm not sure what you're trying to do with the end() function. It seems do very little, and what it does is not related to its name...
You create an oldlist list but never really do anything with it. What is it supposed to to ?
With that in mind, here is my proposition:
def main():
# I like to put the main code in a "main" function, so that it can be at the top
# of the file. We'll call main() from the bottom of the file
# Make our program pretty, with a little branding
print("===== Number Sorter 9000 =====")
# 'numbers' is not the name of anything yet, so we can use it safely
numbers = []
# This will loop forever, unless we tell it to stop. It allows us to skip the
# part where you ask the user for a number of values: Simply enter the values
# one by one, and press enter once last time when done.
while True:
value = input(f"Number {len(numbers)+1} (leave empty to continue): ")
# Decide what to do with the value we received. If it's a number,
# add it to our list, if it's empty, stop collecting numbers
if value:
# Make sure the value is a number ()
value = float(value)
# Add the number to the list
numbers.append(value)
else:
# This will get us out of the number-asking loop
break
print("Number Sorter 9000 will now sort your numbers")
sorted_numbers = bubblesort(numbers)
print("Number Sorter 9000 has sorted your numbers:")
print(sorted_numbers)
def bubblesort(numbers):
# Here I've removed things that were not doing much.
# There are some ways to improve the algorithm itself, but I'll let you do that
for i in range(len(numbers)):
for j in range(0, len(numbers)-i-1):
if numbers[j] > numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
# We 'return' the result from the function, so that code that calls the
# bubblesort() function can use the result
return numbers
# Lastly, we call the "main" function to get everything started. Without this
# line, nothing happens: We've just explained to the computer how to do some
# stuff, but we haven't asked it to *DO* anything
main()
Well, I hope this was not too much information. I've tried to keep things simple, but feel free to ask if something is not clear
So I am playing around in python and I thought:
"Is there a built in list or function that already has infinite numbers, if not how could I build one?"
I did some research and found...
Nothing
That is why I am here!
If you don't know what I mean it would be this but infinite:
b = [1,2,3,4,5,6,7,8,9]
etc;
If there is please tell me! Thank you!
Edit: Thank you!
You can define your own infinite list using a generator function without any module imports.
def infinite_list():
n = 1
while True:
yield n
n += 1
my_list = infinite_list()
Each time you want the next number call the next method:
next(my_list)
You can also iterate over it but it will, of course, be an infinite loop:
for elem in my_list:
//infinite loop
itertools.count produces an iterator over arbitrary, infinite numbers. It's not a sequence (you can't index it, you can only iterate each instance once), but you can keep going forever.
Actually running it to completion will take infinite time of course, so it's typically paired with something that limits it, e.g. itertools.islice, zip-ing with a finite iterable, etc.
from itertools import count
for i in count(1):
print(i)
its infinite though so it might take a while to run
I'm a brand new programming graduate student and am having a bit of trouble. I'm working through a textbook problem that wants me to take a positive integer and print the Collatz sequence of that number.
while num !=1:
print(num)
if num%2==0:
num = num//2
else:
num = 3*num+1
print(1)
Now, this code works. And I get the mathematical logic. But there's parts I don't understand.
Firstly, the print(num), this is done so the code prints the input number since that starts the sequence. But, what is the logic/explanation to having this at the front of the loop?
Second, for num = num//2 and num = 3*num+1, why is that all you need for the code to run? In the end, our goal is to print the whole sequence until the input gets to 1. I thought you'd need an accumulator up top. i.e. lst = [] to append each value into that list and then return the list. Why does just re-labeling them num = work? Each time it iterates, wouldn't the prior value be deleted since it isn't stored anywhere?
Lastly, why do we not need to end the loop with a return? How does it know to print the whole sequence of numbers? It ends with print(1) because every input needs to end with that, and it terminates before 1. However, I have not called upon the function (it's a function on my end, not just a while loop) to take action. It just...did it.
I'm sorry if that's a bit confusing, but I'm trying to understand the correct code answer. I've mostly been doing accumulators and stuff, so I'm not sure why this didn't need one, what the num = did, and how you can just end it with print(1) and the whole sequence appears.
Firstly, the print(num), this is done so the code prints the input number since that starts the sequence. But, what is the logic/explanation to having this at the front of the loop?
It's placed where it is because it's not just there to print the input number. It's there to print whatever num happens to be at that point in the code, each time that point in the code is reached. On the first iteration, num is the first element of the sequence. On the second iteration, num is now the second element of the sequence. On the third iteration, num is the third element, and so on. This print prints every element of the sequence, except 1, because the loop breaks at that point, which is why there's a separate print(1) after the loop.
Second, for num = num//2 and num = 3*num+1, why is that all you need for the code to run? In the end, our goal is to print the whole sequence until the input gets to 1. I thought you'd need an accumulator up top. i.e. lst = [] to append each value into that list and then return the list. Why does just re-labeling them num = work? Each time it iterates, wouldn't the prior value be deleted since it isn't stored anywhere?
print(num) prints each sequence element as it's computed, so the program doesn't need to explicitly save the elements. The program does forget the previous values, but they were already printed. Remembering the printed output is some other tool's job - for example, if you run this with stdout directed to a file, the printed output is written into the file.
Lastly, why do we not need to end the loop with a return? How does it know to print the whole sequence of numbers? It ends with print(1) because every input needs to end with that, and it terminates before 1. However, I have not called upon the function (it's a function on my end, not just a while loop) to take action. It just...did it.
return has two jobs: it ends the current function execution, and it sets the return value. If execution reaches the end of a function without executing a return, execution of the function still ends, with a return value of None. return isn't involved in printing the output. That's print's job, as explained above.
As for not calling the function, we can't answer what's going on with that. We would need to see what you actually ran, including the actual function.
this is how the output "magically appears" without a list
see #1
you always return from a function ... in this case you are returning None, instead you are printing the list
it might help to put a time.sleep in there(inside your loop) to visualize whats happening
this site : python tutor - see how it works
is helpful for visualizing code execution
I have got stuck with a problem.
It goes like this,
A function returns a single result normally. What I want is it to return continuous streams of result for a certain time frame(optional).
Is it feasible for a function to repeatedly return results for a single function call?
While browsing through the net I did come across gevent and threading. Will it work if so any heads up how to solve it?
I just need to call the function carry out the work and return results immediately after every task is completed.
Why you need this is not specified in the question, so it is hard to know what you need, but I will give you a general idea, and code too.
You could return in that way: return var1, var2, var3 (but that's not what you need I think)
You have multiple options: either blocking or non-blocking. Blocking means your code will no longer execute while you are calling the function. Non-blocking means that it will run in parallel. You should also know that you will definitely need to modify the code calling that function.
That's if you want it in a thread (non-blocking):
def your_function(callback):
# This is a function defined inside of it, just for convenience, it can be any function.
def what_it_is_doing(callback):
import time
total = 0
while True:
time.sleep(1)
total += 1
# Here it is a callback function, but if you are using a
# GUI application (not only) for example (wx, Qt, GTK, ...) they usually have
# events/signals, you should be using this system.
callback(time_spent=total)
import thread
thread.start_new_thread(what_it_is_doing, tuple(callback))
# The way you would use it:
def what_I_want_to_do_with_each_bit_of_result(time_spent):
print "Time is:", time_spent
your_function(what_I_want_to_do_with_each_bit_of_result)
# Continue your code normally
The other option (blocking) involves a special kind of functions generators which are technically treated as iterators. So you define it as a function and acts as an iterator. That's an example, using the same dummy function than the other one:
def my_generator():
import time
total = 0
while True:
time.sleep(1)
total += 1
yield total
# And here's how you use it:
# You need it to be in a loop !!
for time_spent in my_generator():
print "Time spent is:", time_spent
# Or, you could use it that way, and call .next() manually:
my_gen = my_generator()
# When you need something from it:
time_spent = my_gen.next()
Note that in the second example, the code would make no sense because it is not really called at 1 second intervals, because there's the other code running each time it yields something or .next is called, and that may take time. But I hope you got the point.
Again, it depends on what you are doing, if the app you are using has an "event" framework or similar you would need to use that, if you need it blocking/non-blocking, if time is important, how your calling code should manipulate the result...
Your gevent and threading are on the right track, because a function does what it is programmed to do, either accepting 1 var at a time or taking a set and returning either a set or a var. The function has to be called to return either result, and the continuous stream of processing is probably taking place already or else you are asking about a loop over a kernel pointer or something similar, which you are not, so ...
So, your calling code which encapsulates your function is important, the function, any function, eg, even a true/false boolean function only executes until it is done with its vars, so there muse be a calling function which listens indefinitely in your case. If it doesn't exist you should write one ;)
Calling code which encapsulates is certainly very important.
Folks aren't going to have enough info to help much, except in the super generic sense that we can tell you that you are or should be within in some framework's event loop, or other code's loop of some form already- and that is what you want to be listening to/ preparing data for.
I like "functional programming's," "map function," for this sort of thing. I think. I can't comment at my rep level or I would restrict my speculation to that. :)
To get a better answer from another person post some example code and reveal your API if possible.