Simpy: How to catch the return value of a simpy process - simpy

Imagine that I have this scenario:
def my_process(env, run_length):
count = 0
while True:
env.timeout(1)
count += 1
if env.now >= run_length:
break
return count
my_env = simpy.Environment()
count = my_env.process(my_process(my_env, 100))
my_env.run(100)
If I print the value of count it will return the the generator itself and not the count of the number of events triggered by the generator which is what I want. I could pass an object to my_process and change its state according to count, but isn't there another way?
Thank you very much in advance!!

You should use yield and another process for getting return value. (Environment's run time should be more than 100).
import simpy
def my_process(env, run_length):
count = 0;
while True:
yield env.timeout(1);
count += 1;
if env.now >= run_length:
break;
return count;
def first_process(env, run_length):
return_value = yield env.process(my_process(env, run_length));
print("return value: ", return_value);
my_env = simpy.Environment();
my_env.process(first_process(my_env, 100));
my_env.run(101);
output in simpy 4:
return value: 100

Related

CODEFORCES 1744B, how could I fix runtime error?

I'm trying to solve the next problem: https://codeforces.com/contest/1744/problem/B
When I run the code in my terminal, it works with the example given in the exercise; but it doesn't when I submit it in CodeForces, it cause a runtime error which I cannot figure out.
def increment(arr, length, option, add):
for i in range(length):
if(option == '0') and (arr[i]%2 == 0):
arr[i] += add
elif(option == '1') and (arr[i]%2 != 0):
arr[i] += add
else:
pass
return arr
def main():
quantityOperation = int(input())
while quantityOperation > 0:
length, times = input().split()
length = int(length)
times = int(times)
arr = [int(x) for x in input().split()]
while times > 0:
opt, add = input().split()
add = int(add)
res = sum(increment(arr, length, opt, add))
print(res)
times -= 1
quantityOperation -= 1
main()
The loop inside your main function doesn't end. You should put quantityOperation -= 1 inside the while loop.
However, your code will still become time limit exceeded after fixing this. The correct idea is to precalculate odd and even sum and modify them according to the queries instead of looping all elements inside increment function every time. You can check the editorial for this problem.

Character Countdown

I'm trying to create a function. Function; it will simply be designed to increase the last letter sequence from its position in the alphabet or letter list.
import time
def CountDown(text,reply=3):
abc = list("ABCDEFGHIJ")
c = 1
text_list = list(text)
while 1:
Index = abc.index(text_list[-c])
if not list(filter(lambda a: a!=abc[-1], text_list)):
return "".join(text_list)
if text_list[-c] == abc[-1]:
text_list[-c] = abc[0]
c += 1
continue
else:
s=1
while 1:
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
if text_list.count(abc[(Index+s) if (Index+s)<len(abc) else 0])+1<reply:
break
s+=1
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
return "".join(text_list)
if __name__ == "__main__":
code="ABHD"
while 1:
code=CountDown(code)
time.sleep(0.5)
print(code)
OUTPUT:
ABHE
ABHF
ABHG
ABHI
ABHJ
ABIA
ABIC
ABID
ABIE
ABIF
ABIG
ABIH
ABIJ
ABJA
ABJC
ABJD
ABJE
ABJF
ABJG
ABJH
ABJI
....(idling)
The code doesn't give an output after a while. I think there is something wrong.
How can I fix this code sample?

Is this assigning a function to a variable?

In the Codecademy Dice Game, I want to understand this part: guess = get_user_guess(), what does it mean? Turn function to a variable?
from random import randint
from time import sleep
def get_user_guess():
guess = int(input("Guess a number: "))
return guess
def get_user_guess():
guess = int(input("Guess a number: "))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print('%d is the max roll' % max_val)
guess = get_user_guess()
if guess > max_val:
print("INVALID : Not supposed to roll greater than maximum rolls")
else:
print("Rolling...")
sleep(2)
get_user_guess is a function that returns an int value from the user's input.
In that code, guess will equal whatever the input is, so if I enter 10, your condition below will equate to
if 10 > max_val
Therefore, you're not assigning the function to the variable, you're assigning the result of the function to the variable.
It is possible to assign a function to a variable, like so
def test():
return "OK"
myFunct = test
print(myFunct())
Prints OK

Python: Roll a dice for 12 times, calculate the probability if each number equally shows up twice

I've drafted the below code for the captioned question, but the return result is always 0. Could anyone please help me figure out what's the problem here?
Thanks a lot!
import random
dice_sides = 6
frequency_list = []
def roll_dice(times):
results = []
for roll_num in range(times):
result = random.randint(1,dice_sides)
results.append(result)
for i in range(dice_sides):
if results.count(i) != 2:
frequency = 0
break
else:
frequency = 1
return frequency
def occurrence(N,times):
for j in range(N):
frequency_list.append(roll_dice(times))
prob = frequency_list.count(1)
return prob
print(occurrence(10000,12))
You can try something like this
Code
import random
from collections import Counter
def roll_dice(n_sides, times):
if n_sides % times:
return 0
results = []
for roll_num in range(times):
result = random.randint(1, n_sides)
results.append(result)
# I'm using set here and will check its length,
# Counter(results) returns a dict of items (item, count)
# and if every item has the same count it should have length 1.
# More generic statement not only for (2 in this case)
res_dict = set(Counter(results).values())
if len(res_dict) == 1:
return 1
return 0
def mean(ar):
return sum(ar)/len(ar)
def occurrence(N, n_sides, times):
frequency_list = []
for j in range(N):
frequency_list.append(roll_dice(n_sides, times))
prob = mean(frequency_list)
return prob
if __name__ == '__main__':
N = 100000 # I intentionally made it 100k
n_sides = 6
times = 12
res_prob = occurrence(N, times)
print(res_prob)
Output
0.00604
[Finished in 3.6s]

Count not incrementing properly in python while loop

Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.

Resources