How do I run a random method from a class?
You can use getattr()
, in addition your methods must be declared as staticmethod
:
import random
class Calculate():
@staticmethod
def HI_1(x, y):
return x + y
@staticmethod
def HI_2(x, y):
return x - y
@staticmethod
def HI_3(x, y):
return x * y
@staticmethod
def HI_4(x, y):
return x/y
a = random.randint(1, 4)
b = 'HI_' + str(a)
p = getattr(Calculate, b)(15, 7)
print(b, p)
How to call a random function one time in Javascript?
Check this.
If you want to execute only one time , call execute();
only one time. If you want more time, call accordingly.
function func1() { alert("1");}
function func2() { alert("2");}
function func3() { alert("3");}function random(){ var i = Math.floor(Math.random()*20)%4; if(i<=0) return random(); return i;}function execute(){ var i = random(); eval('func'+i+'()');}execute();execute();execute();
Execute a function randomly
Only call the selected function, not both of them:
random.choice([a,b])()
Below is a demonstration:
>>> import random
>>> def a():
... print "a"
...
>>> def b():
... print "b"
...
>>> random.choice([a,b])()
a
>>> random.choice([a,b])()
b
>>>
Your old code called both functions when the list [a(),b()]
was created, causing Python to print both a
and b
. Afterwards, it told random.choice
to choose from the list [None, None]
1, which does nothing. You can see this from the demonstration below:
>>> [a(),b()]
a
b
[None, None]
>>>
The new code however uses random.choice
to randomly select a function object from the list [a,b]
:
>>> random.choice([a,b])
<function b at 0x01AFD970>
>>> random.choice([a,b])
<function a at 0x01AFD930>
>>>
It then calls only that function.
1Functions return None
by default. Since a
and b
lack return-statements, they each return None
.
Syntax to call random function from a list
With the parentheses you call the function. What you want is assigning them to the list and call the choice later:
my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()
How to choose a method randomly in Java
You can use another Math.random() statement to randomly pick between the two methods with an if statement
So instead of just the solo call:
metbu.MetodoBurbujaOptimizada(inputTenThousand);
Try using something like:
if(Math.random() > 0.5){
System.out.println("Using MetodoBurbuja");
metbu.MetodoBurbuja(inputTenThousand);
}
else{
System.out.println("Using MetodoBurbujaOptimizada");
metbu.MetodoBurbujaOptimizada(inputTenThousand);
}
Hopefully I'm interpreting your question correctly!
As for other pointers, you can use System.currentTimeMillis() instead of nanoseconds and you won't have to convert them into milliseconds.
Call random method of random class in java
I think you should probably re-think your design. Using reflection should usually be avoided in most situations. The only times you really need reflection are when you are dynamically loading and executing code (e.g. the JUnit framework dynamically loads and executes tests in a class whose name is passed as a command-line argument).
Instead of randomly executing a method in a class I would suggest creating a collection of Exercise
objects with a common interface, choosing one of them at random and then running it. Here's some skeleton code for what I'm thinking:
import java.util.ArrayList;
import java.util.Random;
/** Common interface for all training classes */
public abstract class TrainingClass {
private Random rand = new Random();
protected ArrayList<Exercise> exercises = new ArrayList<Exercise>();
/** Run a random exercise */
public String[] runRandomExercise() {
int i = rand.nextInt(exercises.size());
return exercises.get(i).run();
}
}
/** Common interface for all exercises */
public interface Exercise {
String[] run();
}
public class MatheMagic extends TrainingClass {
/** Constructor creates all the exercises */
public MatheMagic() {
// Some exercise
exercises.add(new Exercise {
public String[] run() {
// Code for some exercise ...
}
});
// Some other exercise
exercises.add(new Exercise {
public String[] run() {
// Code for some other exercise ...
}
});
// etc ...
}
}
Since all the exercises are of type Exercise
and have a common run()
method there is no need to use reflection. The declaration is a bit more verbose since you need to create an anonymous inner class for each exercise, but the extra bit of verbosity is well worth it for avoiding reflection!
How to Run a Random Function in Python 2
In Python, functions are first class citizens so you can put them in a list and then randomly select one of them at every turn using random.choice
:
>>> import random
>>> functions = [functionA, functionB]
>>> for _ in range(100):
... function = random.choice(functions)
... function()
Related Topics
Ruby Net-Ssh Calling Bash Script with Interactive Prompts
Ruby: How to Dynamically Replace Parameters in Native Pg Gem
How to Schedule a Function to Execute at a Future Time
Calling Protected Class Method from Instance Method in Ruby
I Want to Match All Punctuation in My Regexp Except Apostrophes. How to Do That in Ruby
Unexpected =>, Expecting '}' in Rspec Expect
How Does Rails Know My Timezone
Making a Pie-Chart of the User Age in Rails
Heroku_Can't Upgrade to Cedar-14
Slicing of Arrays in Ruby Returns Different Result - Nil VS. Empty Array
How to Make the Say Command Echo a Variable Value in a Script
How to Make the Days of the Month Be Printed According to Each Day (Ex: Su Mo Tu We...Etc)