本文整理匯總了Python中random.choice方法的典型用法代碼示例。如果您正苦於以下問題:Python random.choice方法的具體用法?Python random.choice怎麽用?Python random.choice使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類random
的用法示例。
在下文中一共展示了random.choice方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: add_prod_goods
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def add_prod_goods(self):
"""
Add who produces which good, and
make them a vendor of that good in the market.
"""
my_good = None
for agent in self.agents:
for good in self.market.goods_iter():
if not self.market.has_vendor(good):
my_good = good
break
if my_good is None:
my_good = random.choice(list(self.market.goods_iter()))
agent.prod_good = my_good
self.market.add_vendor(my_good, agent)
print("Market = " + str(self.market))
示例2: discourage
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def discourage(unwanted):
"""
Discourages extra drinkers from going to the bar by decreasing motivation.
Chooses drinkers randomly from the drinkers that went to the bar.
"""
discouraged = 0
drinkers = get_group(DRINKERS)
while unwanted:
if DEBUG:
user_tell("The members are: " + drinkers.members)
rand_name = random.choice(list(drinkers.members))
rand_agent = drinkers[rand_name]
if DEBUG:
user_tell("drinker ", rand_agent, " = "
+ repr(drinkers[rand_agent]))
rand_agent[MOTIV] = max(rand_agent[MOTIV] - DISC_AMT,
MIN_MOTIV)
discouraged += 1
unwanted -= 1
return discouraged
示例3: get_rand_good
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def get_rand_good(goods_dict, nonzero=False):
"""
What should this do with empty dict?
"""
# print("Calling get_rand_good()")
if goods_dict is None or not len(goods_dict):
return None
else:
if nonzero and is_depleted(goods_dict):
# we can't allocate what we don't have!
print("Goods are depleted!")
return None
goods_list = list(goods_dict.keys())
good = random.choice(goods_list)
if nonzero:
# pick again if the goods is endowed (amt is 0)
# if we get big goods dicts, this could be slow:
while goods_dict[good][AMT_AVAIL] == 0:
good = random.choice(goods_list)
return good
示例4: initial_solution
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def initial_solution(self):
"""
Greedy algorithm to get an initial solution (closest-neighbour).
"""
cur_node = random.choice(self.nodes) # start from a random node
solution = [cur_node]
free_nodes = set(self.nodes)
free_nodes.remove(cur_node)
while free_nodes:
next_node = min(free_nodes, key=lambda x: self.dist(cur_node, x)) # nearest neighbour
free_nodes.remove(next_node)
solution.append(next_node)
cur_node = next_node
cur_fit = self.fitness(solution)
if cur_fit < self.best_fitness: # If best found so far, update best fitness
self.best_fitness = cur_fit
self.best_solution = solution
self.fitness_list.append(cur_fit)
return solution, cur_fit
示例5: colorize_output
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def colorize_output(output: str, color: str) -> str:
"""Color output for the terminal display as either red or green.
Args:
output: string to colorize
color: choice of terminal color, "red" vs. "green"
Returns:
colorized string, or original string for bad color choice.
"""
colors = {
"red": f"\033[91m{output}\033[0m", # Red text
"green": f"\033[92m{output}\033[0m", # Green text
"yellow": f"\033[93m{output}\033[0m", # Yellow text
"blue": f"\033[94m{output}\033[0m", # Blue text
}
return colors.get(color, output)
示例6: gen_dummy_object
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def gen_dummy_object(class_title, doc):
"""Create a dummy object based on the definitions in the API Doc.
:param class_title: Title of the class whose object is being created.
:param doc: ApiDoc.
:return: A dummy object of class `class_title`.
"""
object_ = {
"@type": class_title
}
for class_path in doc.parsed_classes:
if class_title == doc.parsed_classes[class_path]["class"].title:
for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
if isinstance(prop.prop, HydraLink) or prop.write is False:
continue
if "vocab:" in prop.prop:
prop_class = prop.prop.replace("vocab:", "")
object_[prop.title] = gen_dummy_object(prop_class, doc)
else:
object_[prop.title] = ''.join(random.choice(
string.ascii_uppercase + string.digits) for _ in range(6))
return object_
示例7: setUpClass
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def setUpClass(self):
"""Database setup before the CRUD tests."""
print("Creating a temporary datatbsse...")
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = scoped_session(sessionmaker(bind=engine))
self.API_NAME = "demoapi"
self.HYDRUS_SERVER_URL = "http://hydrus.com/"
self.session = session
self.doc = doc_maker.create_doc(
doc, self.HYDRUS_SERVER_URL, self.API_NAME)
test_classes = doc_parse.get_classes(self.doc.generate())
# Getting list of classes from APIDoc
self.doc_collection_classes = [
self.doc.collections[i]["collection"].class_.title for i in self.doc.collections]
print(self.doc_collection_classes)
print(random.choice(self.doc_collection_classes))
test_properties = doc_parse.get_all_properties(test_classes)
doc_parse.insert_classes(test_classes, self.session)
doc_parse.insert_properties(test_properties, self.session)
print("Classes and properties added successfully.")
print("Setup done, running tests...")
示例8: test_delete
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def test_delete(self):
"""Test CRUD delete."""
object_ = gen_dummy_object(random.choice(
self.doc_collection_classes), self.doc)
id_ = str(uuid.uuid4())
insert_response = crud.insert(
object_=object_, id_=id_, session=self.session)
delete_response = crud.delete(
id_=id_, type_=object_["@type"], session=self.session)
assert isinstance(insert_response, str)
response_code = None
try:
get_response = crud.get(
id_=id_,
type_=object_["@type"],
session=self.session,
api_name="api")
except Exception as e:
error = e.get_HTTP()
response_code = error.code
assert 404 == response_code
示例9: test_delete_type
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def test_delete_type(self):
"""Test CRUD delete when wrong/undefined class is given."""
object_ = gen_dummy_object(random.choice(
self.doc_collection_classes), self.doc)
id_ = str(uuid.uuid4())
insert_response = crud.insert(
object_=object_, id_=id_, session=self.session)
assert isinstance(insert_response, str)
assert insert_response == id_
response_code = None
try:
delete_response = crud.delete(
id_=id_, type_="otherClass", session=self.session)
except Exception as e:
error = e.get_HTTP()
response_code = error.code
assert 400 == response_code
示例10: test_delete_id
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def test_delete_id(self):
"""Test CRUD delete when wrong/undefined ID is given."""
object_ = gen_dummy_object(random.choice(
self.doc_collection_classes), self.doc)
id_ = str(uuid.uuid4())
insert_response = crud.insert(
object_=object_, id_=id_, session=self.session)
response_code = None
try:
delete_response = crud.delete(
id_=999, type_=object_["@type"], session=self.session)
except Exception as e:
error = e.get_HTTP()
response_code = error.code
assert 404 == response_code
assert isinstance(insert_response, str)
assert insert_response == id_
示例11: test_delete_ids
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def test_delete_ids(self):
objects = list()
ids = "{},{}".format(str(uuid.uuid4()), str(uuid.uuid4()))
for index in range(len(ids.split(','))):
object = gen_dummy_object(random.choice(
self.doc_collection_classes), self.doc)
objects.append(object)
insert_response = crud.insert_multiple(objects_=objects,
session=self.session, id_=ids)
delete_response = crud.delete_multiple(
id_=ids, type_=objects[0]["@type"], session=self.session)
response_code = None
id_list = ids.split(',')
try:
for index in range(len(id_list)):
get_response = crud.get(
id_=id_list[index],
type_=objects[index]["@type"],
session=self.session,
api_name="api")
except Exception as e:
error = e.get_HTTP()
response_code = error.code
assert 404 == response_code
示例12: generate
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def generate(self, gstate):
if gstate.instances[self.ref]:
gstate.output.append(random.choice(gstate.instances[self.ref]))
else:
pass # TODO, no instances yet, what now? generate one?
# dharma generates content first, then reference definitions after (which must be created before the content)
# this makes the testcases much cleaner ... but how to work with the cracker?
# IDEA:
# we know which variables are tracked .. (ie references are possible, added to Grammar.tracked)
# so whenever a tracked variable could occur, don't generate it, but keep track of where it could be
# - if it's in a choice, set the weight to 0
# - if it's somewhere else ?? error?
# if a reference to the tracked variable is used, go back and generate the tracked variable in one of the preceding places
# it could have occurred.
#
# simpler:
# don't mess with the weights, but do keep track of the first place one could have occurred but didn't
# if a reference is needed before one is actually generated, go back and generate it where it could have occurred.
# - might be complicated (might violate repeat conditions, might need a reference before we find a place to generate the declaration)
#
# alternate: go dharma style and don't allow reference variables to be declared except when called for, then defined in a specific place
# - how does this work with parsing?
示例13: __getitem__
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def __getitem__(self, idx):
length = self.n_frames_input + self.n_frames_output
if self.is_train or self.num_objects[0] != 2:
# Sample number of objects
num_digits = random.choice(self.num_objects)
# Generate data on the fly
images = self.generate_moving_mnist(num_digits)
else:
images = self.dataset[:, idx, ...]
if self.transform is not None:
images = self.transform(images)
input = images[:self.n_frames_input]
if self.n_frames_output > 0:
output = images[self.n_frames_input:length]
else:
output = []
return input, output
示例14: step
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def step(self, amt=1):
amt = 1 # anything other than 1 would be just plain silly
if self._step > self.layout.numLEDs:
self._step = 0
self.layout.all_off()
for i in range(self._count):
pixel = random.randint(0, self.layout.numLEDs - 1)
color = random.choice(self.palette)
for i in range(self._width):
if pixel + i < self.layout.numLEDs:
self.layout.set(pixel + i, color)
self._step += amt
示例15: step
# 需要導入模塊: import random [as 別名]
# 或者: from random import choice [as 別名]
def step(self, amt=1):
self.layout.all_off()
for i in range(self._growthRate):
newTail = random.randrange(0, 360, self._angleDiff)
color = random.choice(self.palette)
self._tails[newTail].append((0, color))
for a in range(360):
angle = self._tails[a]
if len(angle) > 0:
removals = []
for r in range(len(angle)):
tail = angle[r]
if tail[0] <= self.lastRing:
self._drawTail(a, tail[0], tail[1])
if tail[0] - (self._tail - 1) <= self.lastRing:
tail = (tail[0] + amt, tail[1])
self._tails[a][r] = tail
else:
removals.append(tail)
for r in removals:
self._tails[a].remove(r)
self._step = 0