本文整理汇总了Python中random.choices函数的典型用法代码示例。如果您正苦于以下问题:Python choices函数的具体用法?Python choices怎么用?Python choices使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了choices函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: predict
def predict(self, given=None):
if self._pred_distr is None:
self._pred_distr = dict()
keys = self.keys()
for i, k in enumerate(keys):
a = k[:-1]
b = k[-1:]
f = self._ngrams[k]
# print(":", k, a, b, f)
if a not in self._pred_distr:
self._pred_distr[a] = dict()
if b not in self._pred_distr[a]:
self._pred_distr[a][b] = f
for a in self._pred_distr.keys():
# Sum occurences
s = 0
for b in self._pred_distr[a].keys():
s += self._pred_distr[a][b]
# Normalize
for b in self._pred_distr[a].keys():
self._pred_distr[a][b] /= s
# Predict the first element in a predicted sequence
if given is None:
population = self.keys()
return random.choices(population, self.vectorize(population))[0]
else:
# print("given", given)
assert given in self._pred_distr
population = list(self._pred_distr[given].keys())
weights = [self._pred_distr[given][k] for k in population]
# assert np.isclose(np.sum(weights), 1.0)
return random.choices(population, weights)[0]
示例2: test
def test(element_html, data):
element = lxml.html.fragment_fromstring(element_html)
name = pl.get_string_attrib(element, 'answers-name')
weight = pl.get_integer_attrib(element, 'weight', 1)
allow_blank = pl.get_string_attrib(element, 'allow-blank', False)
# Get correct answer
a_tru = data['correct_answers'][name]
# If correct answer is in a format generated by pl.to_json, convert it
# back to a standard type (otherwise, do nothing)
a_tru = pl.from_json(a_tru)
if allow_blank:
# no invalid answer implemented when allow-blank="true"
result = random.choices(['correct', 'incorrect'], [5, 5])[0]
else:
result = random.choices(['correct', 'incorrect', 'invalid'], [5, 5, 1])[0]
if result == 'correct':
data['raw_submitted_answers'][name] = a_tru
data['partial_scores'][name] = {'score': 1, 'weight': weight}
elif result == 'incorrect':
data['raw_submitted_answers'][name] = a_tru + str((random.randint(1, 11) * random.choice([-1, 1])))
data['partial_scores'][name] = {'score': 0, 'weight': weight}
elif result == 'invalid':
data['raw_submitted_answers'][name] = ''
data['format_errors'][name] = 'invalid'
else:
raise Exception('invalid result: %s' % result)
示例3: test_push_func
def test_push_func():
sample_count = 10
push = {
"60": ['60' + ''.join(random.choices(string.hexdigits, k=2)) for _ in range(0, sample_count)],
"63": ['63' + ''.join(random.choices(string.hexdigits, k=8)) for _ in range(0, sample_count)],
"69": ['69' + ''.join(random.choices(string.hexdigits, k=20)) for _ in range(0, sample_count)],
"7f": ['7f' + ''.join(random.choices(string.hexdigits, k=64)) for _ in range(0, sample_count)]
}
l = len(push["7f"])
for key, value in push.items():
for v in value:
computation = comp.Computation(st.Stack())
opcode = opcodes.opcodes[key]
opcode(bc.Bytecode(v), computation.stack)
assert len(computation.stack) == opcode.produce
# test, with invalid bytecode sequence. No item to push
opcode = opcodes.opcodes["60"]
with pytest.raises(opcodes.ExceptionalHalt):
computation = comp.Computation(st.Stack())
bytecode = bc.Bytecode("60")
# we have to increment the idx of bytecode first.
# Otherwse idx is 0 and the push operation will push 60 to the stack
bytecode.__next__()
opcode(bytecode, computation.stack)
示例4: create_random_name
def create_random_name(self):
numbers = ''.join(random.choices(string.digits, k=3))
letters = ''.join(random.choices(string.ascii_uppercase, k=2))
name = letters + numbers
if name not in Robot.used_names:
Robot.used_names.append(name)
return name
return self.create_random_name()
示例5: generate_sequence
def generate_sequence(p_unigrams, p_bigrams, num_words=100, seed_word=None):
"""Generate a random sequence of words, given unigram and bigram probabilities."""
# If seed_word is not given, pick one randomly based on unigram probabilities
if seed_word is None:
seed_word = random.choices(list(p_unigrams.keys()), weights=list(p_unigrams.values()))[0]
seq = [seed_word]
for i in range(num_words):
seq.append(random.choices(list(p_bigrams[seq[-1]].keys()), weights=list(p_bigrams[seq[-1]].values()))[0])
return seq
示例6: test_find_it
def test_find_it(xs):
v1, v2 = (0, 0)
if len(xs) > 1:
t = list(xs)
v1 = choices(t)[0]
t.remove(v1)
v2 = choices(t)[0]
k = v1 + v2
if len(xs) > 1:
assert find_it(xs, k)
else:
assert not find_it(xs, k)
示例7: generateActivityMapFile
def generateActivityMapFile(self, template = 'activity.map'):
'''Build mapfile for activity from template. Write it to a location that mapserver can see it.
The mapfile performs direct SQL queries, so we must pass all of the connection parameters for the dbAlias.
'''
filename, ext = os.path.splitext(template)
if 'mappath' in self.request.session:
logger.debug("Reusing request.session['mappath'] = %s", self.request.session['mappath'])
else:
self.request.session['mappath'] = __name__ + '_' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) + '.map'
logger.debug("Setting new request.session['mappath'] = %s", self.request.session['mappath'])
# mapserver_host: Hostname where 'http://<mapserver_host>/cgi-bin/mapserv?file=<url_mappath>' works
# With Apache RewriteBase rule this pattern also works for cleaner URLs:
# Allow WMS requests to any file in /dev/shm by providing a URL like /wms/ADFASDFASDF (where /dev/shm/ADFASDFASDF.map is the name of the mapfile)
# this means that the "?map=" need not be provided as part of the URL
# <Location /wms>
# Options Indexes FollowSymLinks
# RewriteEngine On
# RewriteBase '/wms/'
# RewriteRule .*/(.*) /cgi-bin/mapserv?map=/dev/shm/$1.map [QSA]
# </location>
##import pprint
##logger.debug(pprint.pformat(settings.DATABASES[self.request.META['dbAlias']]))
response = render(self.request, template, context={'mapserver_host': settings.MAPSERVER_HOST,
'list': self.itemList,
'trajectory_union_layer_string': self.trajectory_union_layer_string,
'station_union_layer_string': self.station_union_layer_string,
'wfs_title': 'WFS title for an Activity',
'map_debug_level': self.map_debug_level,
'layer_debug_level': self.layer_debug_level,
'copyright_string': 'MBARI %d' % datetime.today().year,
'dbconn': settings.MAPSERVER_DATABASES[self.request.META['dbAlias']],
'mappath': self.url_mappath,
'imagepath': settings.MAPFILE_DIR,
'STATIC_ROOT': settings.STATIC_ROOT})
try:
fh = open(self.file_mappath, 'w')
except IOError:
# In case of accessed denied error, create a new mappath and store it in the session, and open that
self.request.session['mappath'] = __name__ + '_' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) + '.map'
self.file_mappath = os.path.join(settings.MAPFILE_DIR, self.request.session['mappath'])
self.url_mappath = os.path.join(settings.URL_MAPFILE_DIR, self.request.session['mappath'])
fh = open(self.file_mappath, 'w')
for line in response:
##logger.info(line.decode("utf-8"))
fh.write(line.decode("utf-8"))
示例8: test
def test(element_html, data):
element = lxml.html.fragment_fromstring(element_html)
name = pl.get_string_attrib(element, 'answers-name')
weight = pl.get_integer_attrib(element, 'weight', 1)
correct_key = data['correct_answers'].get(name, {'key': None}).get('key', None)
if correct_key is None:
raise Exception('could not determine correct_key')
number_answers = len(data['params'][name])
all_keys = [chr(ord('a') + i) for i in range(number_answers)]
incorrect_keys = list(set(all_keys) - set([correct_key]))
result = random.choices(['correct', 'incorrect', 'invalid'], [5, 5, 1])[0]
if result == 'correct':
data['raw_submitted_answers'][name] = data['correct_answers'][name]['key']
data['partial_scores'][name] = {'score': 1, 'weight': weight}
elif result == 'incorrect':
if len(incorrect_keys) > 0:
data['raw_submitted_answers'][name] = random.choice(incorrect_keys)
data['partial_scores'][name] = {'score': 0, 'weight': weight}
else:
# actually an invalid submission
data['raw_submitted_answers'][name] = '0'
data['format_errors'][name] = 'INVALID choice'
elif result == 'invalid':
data['raw_submitted_answers'][name] = '0'
data['format_errors'][name] = 'INVALID choice'
# FIXME: add more invalid choices
else:
raise Exception('invalid result: %s' % result)
示例9: test
def test(element_html, data):
element = lxml.html.fragment_fromstring(element_html)
name = pl.get_string_attrib(element, 'answers-name')
weight = pl.get_integer_attrib(element, 'weight', 1)
result = random.choices(['correct', 'incorrect', 'invalid'], [5, 5, 1])[0]
if result == 'correct':
data['raw_submitted_answers'][name] = str(pl.from_json(data['correct_answers'][name]))
data['partial_scores'][name] = {'score': 1, 'weight': weight}
elif result == 'incorrect':
data['raw_submitted_answers'][name] = str(pl.from_json(data['correct_answers'][name])) + ' + {:d}'.format(random.randint(1, 100))
data['partial_scores'][name] = {'score': 0, 'weight': weight}
elif result == 'invalid':
invalid_type = random.choice(['float', 'complex', 'expression', 'function', 'variable', 'syntax', 'escape', 'comment'])
if invalid_type == 'float':
data['raw_submitted_answers'][name] = 'x + 1.234'
s = 'Your answer contains the floating-point number ' + str(1.234) + '. '
s += 'All numbers must be expressed as integers (or ratios of integers). '
s += '<br><br><pre>' + phs.point_to_error('x + 1.234', 4) + '</pre>'
data['format_errors'][name] = s
elif invalid_type == 'complex':
data['raw_submitted_answers'][name] = 'x + (1+2j)'
s = 'Your answer contains the complex number ' + str(2j) + '. '
s += 'All numbers must be expressed as integers (or ratios of integers). '
s += '<br><br><pre>' + phs.point_to_error('x + (1+2j)', 7) + '</pre>'
data['format_errors'][name] = s
elif invalid_type == 'expression':
data['raw_submitted_answers'][name] = '1 and 0'
s = 'Your answer has an invalid expression. '
s += '<br><br><pre>' + phs.point_to_error('1 and 0', 0) + '</pre>'
data['format_errors'][name] = s
elif invalid_type == 'function':
data['raw_submitted_answers'][name] = 'atan(x)'
s = 'Your answer calls an invalid function "' + 'atan' + '". '
s += '<br><br><pre>' + phs.point_to_error('atan(x)', 0) + '</pre>'
data['format_errors'][name] = s
elif invalid_type == 'variable':
data['raw_submitted_answers'][name] = 'x + y'
s = 'Your answer refers to an invalid variable "' + 'y' + '". '
s += '<br><br><pre>' + phs.point_to_error('x + y', 4) + '</pre>'
data['format_errors'][name] = s
elif invalid_type == 'syntax':
data['raw_submitted_answers'][name] = 'x +* 1'
s = 'Your answer has a syntax error. '
s += '<br><br><pre>' + phs.point_to_error('x +* 1', 4) + '</pre>'
data['format_errors'][name] = s
elif invalid_type == 'escape':
data['raw_submitted_answers'][name] = 'x + 1\\n'
s = 'Your answer must not contain the character "\\". '
s += '<br><br><pre>' + phs.point_to_error('x + 1\\n', 5) + '</pre>'
data['format_errors'][name] = s
elif invalid_type == 'comment':
data['raw_submitted_answers'][name] = 'x # some text'
s = 'Your answer must not contain the character "#". '
s += '<br><br><pre>' + phs.point_to_error('x # some text', 2) + '</pre>'
data['format_errors'][name] = s
else:
raise Exception('invalid invalid_type: %s' % invalid_type)
else:
raise Exception('invalid result: %s' % result)
示例10: username_from_repo
def username_from_repo(self, repo):
"""Generate a username for a git repo url
e.g. minrk-binder-example-abc123
from https://github.com/minrk/binder-example.git
"""
# start with url path
print
if '://' not in repo and _ssh_repo_pat.match(repo):
# ssh url
path = repo.split(':', 1)[1]
else:
path = urlparse(repo).path
prefix = path.strip('/').replace('/', '-').lower()
if prefix.endswith('.git'):
# strip trailing .git
prefix = prefix[:-4]
if len(prefix) > 32:
# if it's long, truncate
prefix = '{}-{}'.format(prefix[:15], prefix[-15:])
# add a random suffix to avoid collisions for users on the same image
return '{}-{}'.format(prefix, ''.join(random.choices(SUFFIX_CHARS, k=SUFFIX_LENGTH)))
示例11: test
def test(element_html, data):
element = lxml.html.fragment_fromstring(element_html)
name = pl.get_string_attrib(element, 'answers-name')
weight = pl.get_integer_attrib(element, 'weight', 1)
# Get correct answer
a_tru = data['correct_answers'][name]
# If correct answer is in a format generated by pl.to_json, convert it
# back to a standard type (otherwise, do nothing)
a_tru = pl.from_json(a_tru)
result = random.choices(['correct', 'incorrect', 'invalid'], [5, 5, 1])[0]
if result == 'correct':
data['raw_submitted_answers'][name] = str(a_tru)
data['partial_scores'][name] = {'score': 1, 'weight': weight}
elif result == 'incorrect':
data['raw_submitted_answers'][name] = str(a_tru + (random.randint(1, 11) * random.choice([-1, 1])))
data['partial_scores'][name] = {'score': 0, 'weight': weight}
elif result == 'invalid':
# FIXME: add more invalid expressions, make text of format_errors
# correct, and randomize
if random.choice([True, False]):
data['raw_submitted_answers'][name] = '1 + 2'
else:
data['raw_submitted_answers'][name] = '3.4'
data['format_errors'][name] = 'invalid'
else:
raise Exception('invalid result: %s' % result)
示例12: random_word
def random_word(N):
return ''.join(
random.choices(
string.ascii_uppercase + string.ascii_lowercase + string.digits,
k=N
)
)
示例13: openpmd_file
def openpmd_file():
random_id = "".join(random.choices(string.ascii_uppercase + string.digits, k=N))
path = f"/tmp/testfile{random_id}.hdf5"
f = create_openpmd_hdf5(path)
yield path, f
f.close()
os.remove(path)
示例14: generate_one
def generate_one(self):
"""Generate a single element.
Returns
-------
element
An element from the domain.
Examples
-------
>>> generator = RepellentGenerator(['a', 'b'])
>>> gen_item = generator.generate_one()
>>> gen_item in ['a', 'b']
True
"""
# Get the weights for all items in the domain
weights = [self.probability_func(self.generated[element])
for element in self.domain]
# Sample from the domain using the weights
element = random.choices(self.domain, weights=weights)[0]
# Update the generated values and return
self.generated[element] += 1
return element
示例15: setUp
def setUp(self):
"""Define the test client and other test variables."""
self.email = '{}@ungleich.ch'.format(''.join(random.choices(string.ascii_uppercase, k=10)))
self.password = ''.join(random.choices(string.ascii_uppercase + string.digits, k=20))
self.user = CustomUser.objects.create(name='test', email=self.email,
password=self.password)
self.vm_specs = {}
self.vm_specs['cpu'] = 1
self.vm_specs['memory'] = 2
self.vm_specs['disk_size'] = 10
self.manager = OpenNebulaManager()