How to Run a Function Multiple Times and Return Different Result Python

How to run a function multiple times and return different result python

The way you using * 4 in print() just make it print the same result from the function 4 times. You can use something simple from python as a loop to run it x times:

for k in range(4):
print(random_number_generator())

Because the number range so large there less likely to have repeat results, but you can use this to remove duplicate results

output = []
expected_results = []
for k in range(4):
output.append(random_number_generator())

expected_results = list(dict.fromkeys(output))

print(expected_results)

Run a function multiple times and then return all the different results?

The problem is that currently you have put the return statement inside the for loop. So as soon as you generate the first name, you return and leave the function.

You need a slight modification: Move the function call inside the for loop. Alternatively, follow the suggestion of @Jon Clements in the comments below.

import random
def name_generator():
color = ["Red", "Green", "Blue", "White", "Black", "Yellow", "Purple", "Orange", "Pink"]
animal = ["Cat", "Dog", "Snake", "Mouse", "Tiger", "Leopard", "Moose", "Wolf", "Bear"]
number = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]

randomColor = random.randrange(0, len(color))
randomAnimal = random.randrange(0, len(animal))
randomNumber = random.randrange(0, len(number))

name = "Username: " + color[randomColor] + animal[randomAnimal] + number[randomNumber]
return name

for x in range (0, 11):
print (name_generator())

# Username: PinkMouse3
# Username: GreenCat8
# Username: GreenMoose2
# Username: BlackTiger14
# Username: BlackSnake11
# Username: PurpleMoose13
# Username: GreenMouse2
# Username: RedBear5
# Username: BlueBear2
# Username: WhiteDog2
# Username: WhiteTiger3

How to store result of function run multiple times in different variables? (Python)

You can unpack a list comprehension like this to get the results in different variables:

freq_a, freq_b, freq_c = [getFreq(group) for group in all_groups]

Combining the output of a function that runs multiple times into a list

Assemble your results and return them from the function:

def getEmails():
results = []

# lots of code...

if sender == 'Cryptocurrency Alerting <alerts@mail.cryptocurrencyalerting.com>':
site = site.replace("has been listed on ", "")
s = list(Convert((str(site))))
results.append(s)

return results


# retrieve the results
results = getEmails()

How to call a function multiple times in Python?

Use a loop:

import random


def random_gen():
return f".type('GGI{random.randint(1, 50)}-{random.randint(1000000, 9999999)}')"


for _ in range(100):
print(random_gen())

Out:

.type('GGI45-5220704')
.type('GGI37-3996932')
.type('GGI2-6482051')
.type('GGI36-2371399')
.type('GGI9-6880645')
.type('GGI12-1733716')
...

Executing one function multiple times simultaneously

  • target=func1() calls func1 and passes its return value (in this case None) as the target argument for Process instead of passing the function func1 itself.

  • Process(...) just creates a Process object. You never really spawn/execute any of the created Process objects. You need to add a call to .start. Depending on the OS (ie if os.fork is used to spawn the new process), this will also require us to add __main__ guard (which is a best-practice anyway regardless of the used OS).

  • You are using p1 twice.

Try this:

from multiprocessing import Process
import time

def func1():
time.sleep(1)
print('Finished sleeping')

if __name__ == '__main__':
t1_start = time.perf_counter()
p1 = Process(target=func1) # note no ()
p2 = Process(target=func1) # note no ()

p1.start()
p2.start()

t1_stop = time.perf_counter()

print("elapsed time: {} sec".format(round(t1_stop - t1_start), 1))

This gives the output

elapsed time: 0 sec
Finished sleepingFinished sleeping

which makes sense. If the function is executed 2 times in separated processes then the main process, the main process would not execute time.sleep(1) at all.

However, if we add .join() then the main process will be forced to wait for the child processes:

p1.start()
p2.start()

p1.join()
p2.join()

Now the output is the same as your required output:

Finished sleeping
Finished sleeping
elapsed time: 1 sec

EDIT: If you want an arbitrary number of processes with a loop:

...
times = 3
processes = []
for _ in range(times):
p = Process(target=func1)
p.start()
processes.append(p)

for p in processes:
p.join()
...

Run python function multiple times with different arguments

The problem you're encountering is that random.randint(1,UPPER_BOUND) is being evaluated once at the time the inner() function returned by runner() is called. What you need is to delay the evaluation until later.

You could try something like this:

>>> def runner(f, callable):
... def inner():
... for i in xrange(1000):
... f(*callable())
... return inner
...
>>> runner(f, lambda: (random.randint(1, 1000),))()
603
385
321
etc.

Note that callable is called each time the original function f is called. Also note that callable must return a sequence type, like a tuple or list.

Edit: if you need to pass other arguments to f you can do it with something like this:

>>> def runner(f, callable):
... def inner(*args, **kwds):
... for i in xrange(1000):
... pos = list(callable())
... pos.extend(args)
... f(*pos, **kwds)
... return inner
...
>>> def f(a, b, c, d = 3):
... print a, b, c, d
...
>>> runner(f, lambda: (random.randint(1,1000),))(3, 5, d = 7)
771 3 5 7
907 3 5 7
265 3 5 7

When running a function multiple times how do i save the data after each time it is run?

I fixed it all i had to do is add a variable outside of the functoin called new_amount and make this the while loop:

 while times != random_percentage:
overworld_choose()
times += 1
amount1 = amount
new_amount += amount```


Related Topics



Leave a reply



Submit