本文整理汇总了Python中random.Random.choice方法的典型用法代码示例。如果您正苦于以下问题:Python Random.choice方法的具体用法?Python Random.choice怎么用?Python Random.choice使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类random.Random
的用法示例。
在下文中一共展示了Random.choice方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RuleGenerator
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
class RuleGenerator(object):
def __init__(self, number_of_states, number_of_symbols):
if number_of_states < 2 or number_of_symbols < 2:
raise ValueError(
"number of states and symbols must be greater than "
"or equal to 2.")
self.number_of_states = number_of_states
self.number_of_symbols = number_of_symbols
self.rand_gen = Random()
self.possible_rule_options = [
list(range(self.number_of_states)),
list(range(self.number_of_symbols)),
list(range(self.number_of_symbols)),
[True, False],
list(range(self.number_of_states))]
def make_rule(self):
rule_args = [self.rand_gen.choice(o)
for o in self.possible_rule_options]
return Rule(*rule_args)
def modify_rule(self, rule):
field_to_modify = self.rand_gen.randrange(5)
while True:
new_option = self.rand_gen.choice(
self.possible_rule_options[field_to_modify])
if new_option != rule[field_to_modify]:
break
return rule._replace(**{rule._fields[field_to_modify]:new_option})
示例2: get_puzzle
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def get_puzzle(s, difficulty, seed=None):
global SUDOKU_DEBUG
global SUDOKU_EASY
global SUDOKU_MEDIUM
global SUDOKU_HARD
global SUDOKU_VHARD
global SUDOKU_INSANE
take_out_ranges = {}
take_out_ranges[SUDOKU_DEBUG] = (1,2)
take_out_ranges[SUDOKU_EASY] = (20,30)
take_out_ranges[SUDOKU_MEDIUM] = (30,40)
take_out_ranges[SUDOKU_HARD] = (40,45)
take_out_ranges[SUDOKU_VHARD] = (45,55)
take_out_ranges[SUDOKU_INSANE] = (55,60)
random_ = Random(s.seed)
got_sudoku = False
if s.seed != None:
start_time = time.time()
count = 0
while not got_sudoku:
count += 1
print count
solution = s.get_solved_board()
seeds = [i[:] for i in solution]
is_fixed = [[True] * 9 for i in range(9)]
take_out_no = random_.choice(range(*take_out_ranges[difficulty]))
i = 0
while i < take_out_no:
r,c = random_.choice(range(9)), random_.choice(range(9))
if seeds[r][c] != None:
seeds[r][c] = None
is_fixed[r][c] = False
i += 1
cur = [i[:] for i in seeds]
nums_available = {}
nums_available['rows'] = [9*[True] for i in range(9)]
nums_available['cols'] = [9*[True] for i in range(9)]
nums_available['subs'] = [9*[True] for i in range(9)]
for i in range(9):
for j in range(9):
if cur[i][j] != None:
nums_available['rows'][i][cur[i][j]] = False
nums_available['cols'][j][cur[i][j]] = False
nums_available['subs'][i/3*3 + j/3][cur[i][j]] = False
got_sudoku = (solution == s.solve(solution, cur, nums_available, is_fixed, 0, -1))
if s.seed != None:
print '%.3f' % (time.time() - start_time)
solution = s.cells_to_strings(solution)
seeds = s.cells_to_strings(seeds)
return solution, seeds
示例3: __init__
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def __init__(self):
self.valid_consts = range(1, 10)
rand = Random()
self.a = rand.choice(self.valid_consts)
self.b = rand.choice(self.valid_consts)
self.c = rand.choice(self.valid_consts)
示例4: use_options
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def use_options(self, location, addrs, total_range):
rand = Random()
if len(addrs) < 4:
# get list of the next part of the addrs that is not routed
# based on the location(addrs part number and previous addrses)
if type(location) == dict:
not_routed = location["all"]
elif type(location) == list:
not_routed = location
# perform set difference on the list and total_range to
# get an addrs element, then append
addrs.append(rand.choice(list_diff(total_range, not_routed)))
# if location is a dict, change location to the value for the
# key in the dict that equals the last element of addrs
if type(location) == dict:
if addrs[-1] in location.keys():
location = location[addrs[-1]]
# if location is a list, there are no more nested dicts, so choose
# next addrs element from whole range
elif type(location) == list:
addrs.append(rand.choice(total_range))
# calls use_options again until there are four elements
self.use_options(location, addrs, total_range)
# four elements, addrs completed
else:
pass
示例5: palette_color_func
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def palette_color_func(word=None, font_size=None, position=None,
orientation=None, font_path=None, random_state=None,
palette=None):
"""Color generation using color palettes.
Additional coloring method. Can be called using a predefined color palette,
or you can provide your own color palette.
Parameters
----------
word, font_size, position, orientation : ignored.
random_state : random.Random object or None, (default=None)
If a random object is given, this is used for generating random numbers.
palette : integer, a list of RGB tuples or None.
If an integer i is given, we take the i-th color palette in the palettes dict.
If a list of RGB values is given, we use that.
If None, we take the 0-th palette in the palettes dict.
"""
# Set defaults:
if random_state is None:
random_state = Random()
if palette is None:
palette = 0
# If palette is an index (that should be in the palettes dictionary)
if isinstance(palette, int):
# We'll assume that the index is in the dictionary:
try:
colors = palettes[palette]
# But if it's not, then the resulting KeyError is caught and we'll use a
# random palette (and print a warning instead):
except KeyError:
print('Warning: Palette not found! Using random palette.')
colors = random_state.choice(palettes.values())
# If palette is not an index, but rather a list of RGB color values
elif isinstance(palette, list):
# If the list is a valid rgb palette
if Palettes.valid_rgb_palette(palette):
# Use the colors provided
colors = palette
# Else (if the RGB tuples are not valid)
else:
# Raise a ValueError with a relevant error message.
raise ValueError("Not all RGB tuples have the correct format, "
"should be 3-tuples with integer values between 0 and 255.")
# Else (if the input has an unexpected type):
else:
# Raise a TypeError with a relevant error message.
raise TypeError("Palette should be an int between 0 and " +
str(max(palettes.keys())) +
", or a list of RGB values.")
# Return a random color from the chosen palette.
return random_state.choice(colors)
示例6: CardTests
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
class CardTests(unittest.TestCase):
def setUp(self):
self.random = Random()
self.value = self.random.randint(1,13)
self.suit = self.random.choice(Card.suits)
def test_static_suits(self):
self.assertTrue("spades" in Card.suits)
self.assertTrue("clubs" in Card.suits)
self.assertTrue("hearts" in Card.suits)
self.assertTrue("diamonds" in Card.suits)
self.assertTrue(len(Card.suits) == 4)
def test_init_valid(self):
card = Card(self.value, self.suit)
self.assertEqual(card.suit, self.suit)
self.assertEqual(card.index, self.value)
def test_init_invalid(self):
invalid_suits = [self.suit, None, "spade", "diamond", "club", "heart", "abracadabra"]
invalid_values = [self.value, None, 0, Card.KING_INDEX + 1, random.randint(-100, -1), random.randint(15,100)]
# Test the cross product of all the invalid suits and invalid values
for invalid_suit, invalid_value in itertools.product(invalid_suits, invalid_values):
if not (invalid_suit == self.suit and invalid_value == self.value):
self.assertRaises(ValueError, Card, invalid_value, invalid_suit)
def test_face_card(self):
face_card = Card(self.random.randint(Card.JACK_INDEX,Card.KING_INDEX), self.random.choice(Card.suits))
self.assertTrue(face_card.is_face())
self.assertEqual(face_card.value, ["J", "Q", "K"][face_card.index - Card.JACK_INDEX])
def test_normal_card(self):
normal_card = Card(self.random.randint(1,9), self.random.choice(Card.suits))
self.assertFalse(normal_card.is_face())
self.assertEqual(normal_card.value, str(normal_card.index))
def test_str(self):
normal_card = Card(7, "spades")
face_card = Card(12, "clubs")
self.assertEqual(str(normal_card), "7 of spades")
self.assertEqual(str(face_card), "Q of clubs")
def test_unicode(self):
normal_card = Card(8, "hearts")
face_card = Card(11, "diamonds")
self.assertEqual(unicode(normal_card), u'8\u2665')
self.assertEqual(unicode(face_card), u'J\u2666')
def tearDown(self):
self.value = None
self.suit = None
self.random = None
示例7: random_seeded_phrase
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def random_seeded_phrase(seed):
adjs = init_db('adjectives.db')
nouns = init_db('nouns.db')
rand = Random()
rand.seed(seed)
adj = rand.choice(adjs)
noun = rand.choice(nouns)
return "%s %s"%(adj.strip(), noun.strip())
示例8: generate_pass
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def generate_pass(length = 5, althands = True):
righthand = '23456qwertasdfgzxcvb'
lefthand = '789yuiophjknm'
allchars = righthand + lefthand
rng = Random()
if not althands:
return ''.join([rng.choice(allchars) for i in range(length)])
else:
return ''.join([rng.choice(righthand) if i % 2 == 0 else rng.choice(lefthand) for i in range(length)])
示例9: test_7_box_monkey_test
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def test_7_box_monkey_test():
rand = Random(8799)
for i in range(100):
x = rand.choice(range(350))
y = rand.choice(range(350))
key = rand.choice(["a", "r", "e", "x", "b", "d"])
add_cursor_position(x, y, key)
add_cursor_position(0.0, 0.0, "q")
ret = main(["gacq_test", testutil.get_data_file_name("N20111123S0033.fits")])
示例10: GeneratePwd
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def GeneratePwd(leng=8, alt=False):
rng = Random()
pwd=""
for i in range(leng):
if not alt:
pwd+=rng.choice(allchars)
else:
if i%2:
pwd+=rng.choice(lefthand)
else:
pwd+=rng.choice(righthand)
return pwd
示例11: start
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def start(self):
self.execute_command(SetState(self, GameState.InProgress))
random = Random()
empty_tiles = self.board.get_empty_tiles()
if empty_tiles:
first_empty = random.choice(empty_tiles)
tile = self.create_random_tile()
add_first = AddTile(self.board, first_empty, tile)
self.execute_command(add_first)
empty_tiles.remove(first_empty)
if empty_tiles:
second_empty = random.choice(empty_tiles)
tile = self.create_random_tile()
add_second = AddTile(self.board, second_empty, tile)
self.execute_command(add_second)
示例12: make_small_dataset
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def make_small_dataset():
pairs = (zip(WOMEN, ['women']*len(WOMEN)) +
zip(EMPLOYEES, ['employees']*len(EMPLOYEES)))
pattern = "%s %s like the sun"
random = Random(1)
dataset = []
for text_noun, hypothesis_noun in pairs:
alternative_noun = 'employees' if hypothesis_noun == 'women' else 'women'
for text_quantifier, hypothesis_quantifier in QUANTIFIERS:
if text_quantifier in INCREASING or hypothesis_quantifier in INCREASING:
if random.choice([True,False]):
dataset.append( (pattern % (text_quantifier, text_noun),
pattern % (hypothesis_quantifier, hypothesis_noun),
True) )
else:
if text_quantifier not in DECREASING and hypothesis_quantifier not in DECREASING:
dataset.append( (pattern % (text_quantifier, hypothesis_noun),
pattern % (hypothesis_quantifier, text_noun),
False) )
else:
dataset.append( (pattern % (text_quantifier, text_noun),
pattern % (hypothesis_quantifier, alternative_noun),
False) )
if text_quantifier in DECREASING or hypothesis_quantifier in DECREASING:
if random.choice([True,False]):
dataset.append( (pattern % (text_quantifier, hypothesis_noun),
pattern % (hypothesis_quantifier, text_noun),
True) )
else:
if text_quantifier not in INCREASING and hypothesis_quantifier not in INCREASING:
dataset.append( (pattern % (text_quantifier, text_noun),
pattern % (hypothesis_quantifier, hypothesis_noun),
False) )
else:
dataset.append( (pattern % (text_quantifier, alternative_noun),
pattern % (hypothesis_quantifier, text_noun),
False) )
if text_quantifier in NONINCREASING:
assert text_quantifier != hypothesis_quantifier
if random.choice([True,False]):
dataset.append( (pattern % (text_quantifier, text_noun),
pattern % (hypothesis_quantifier, text_noun),
True) )
else:
dataset.append( (pattern % (text_quantifier, hypothesis_noun),
pattern % (text_quantifier, text_noun),
False) )
return dataset
示例13: secret_key
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def secret_key():
"""Generates a new SECRET_KEY."""
from random import Random
import string
r = Random()
return "".join(r.choice(string.printable) for i in range(64))
示例14: post
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
def post(self):
email = self.session.get(EMAIL_KEY)
users = User.gql('WHERE email = :1', email)
template_params={
}
if (users.count(1) == 1):
word = ''
random = Random()
for i in range(1,8):
word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
user = users.get()
user.password = word
m = hashlib.md5()
encodedString = word.encode('ascii', errors='replace')
m.update(encodedString)
user.passwordHash = str(m.hexdigest())
user.put()
template_values = {
"password":word
}
messageTemplate = jinja_environment.get_template('templates/userForms/changePassMail.html')
message = mail.EmailMessage(sender="Diet Futar <[email protected]>")
message.subject="Diet-futar, uj jelszo"
message.to = email
message.html = messageTemplate.render(template_values)
message.send()
template_params[EMAIL_KEY] = email
template = jinja_environment.get_template('templates/userForms/changePassSuccess.html')
self.printPage("Uj jelszo", template.render(template_params), True, True)
示例15: __init__
# 需要导入模块: from random import Random [as 别名]
# 或者: from random.Random import choice [as 别名]
class DatasetAccess:
def __init__(self, name, localisation, random=None):
self.name = name
self.localisation = localisation
if random:
self.random = random
else:
self.random = Random()
self.dataset_instance = self._get_dataset_instance()
def _get_dataset_instance(self):
ds_modules = [f for f in os.listdir(os.path.dirname(__file__)) if
f.endswith(".py") and not f.startswith("__")]
ds_modules = [x.replace(".py", "") for x in ds_modules]
for module_to_imp in ds_modules:
module = importlib.import_module("pymockdata.datasets." + module_to_imp)
for dataset_name in dir(module):
dataset = getattr(module, dataset_name)
if isinstance(dataset,
tuple) and dataset.name == self.name and (dataset.localisation == self.localisation or dataset.localisation is None):
return dataset
raise ValueError(
"No suitable dataset found for name='{}' and localisation='{}'".format(self.name, self.localisation))
def get_one(self):
return self.random.choice(self.dataset_instance.items)
def get_many(self, count):
return [self.get_one() for _ in range(count)]