本文整理汇总了Python中random.rr函数的典型用法代码示例。如果您正苦于以下问题:Python rr函数的具体用法?Python rr怎么用?Python rr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_random_bytes
def get_random_bytes(lrange=None, skip=None):
if lrange is None:
v = bytearray(rr(2**rr(10)))
else:
v = bytearray(rr(*lrange))
for i in range(len(v)):
v[i] = rr(256)
while v[i] == skip:
v[i] = rr(256)
return bytes(v)
示例2: run
def run(n):
ans = [rr(0, 2) for _ in range(n)]
x_0 = [rr(0, 2) for _ in range(n)]
if x_0 == ans:
return 1
iterations = 1
x_1 = [1 - x_i for x_i in x_0]
while x_1 != ans:
r = random()
distance = min([i for i in range(1, n) if prob[i] >= r])
x_1 = mutate(x_0, distance)
iterations += 1
return iterations
示例3: bogo_sort
def bogo_sort(items):
num_items = len(items)
# Cheating :)
correct = sorted(items)
while correct != items:
rand_swap_a = rr(0, num_items)
rand_swap_b = rr(0, num_items)
if items[rand_swap_a] > items[rand_swap_b]:
copy_a = items[rand_swap_a]
copy_b = items[rand_swap_b]
items[rand_swap_a] = copy_b
items[rand_swap_b] = copy_a
print(items)
return items
示例4: madlib
def madlib():
d={
'pn':['the girl','she','it'],
'v':['walking','gliding','flying'],
'pl':['dark alley','basement','subway tracks'],
'adj':['fat','sweaty','ugly'],
'noun':['boy','monster','thing']
}
return render_template(
"madlib.html",
pn =d['pn'] [rr(0, len(d['pn']) ) ],
v =d['v'] [rr(0, len(d['v']) ) ],
pl =d['pl'] [rr(0, len(d['pl']) ) ],
adj =d['adj'] [rr(0, len(d['adj']) ) ],
noun=d['noun'][rr(0, len(d['noun']) ) ]
)
示例5: people
def people(param_num):
people = []
# Create people
for ii in range(PEOPLE):
new_person = Person(PSHARE[param_num], PCREATE[param_num], DOI, param_num)
new_person.reset() # Init
people.append(new_person)
# Create quotas
quotas = []
for ii, topic in enumerate(TOPICS):
quotas.append(int(math.ceil(PEOPLE * I_CONF[ii])))
# Distribute interests
for ii, quota in enumerate(quotas):
for nn in range(quota):
# Interested or very interested
d = DOI[0] if rr() < DOI_PREF else DOI[1]
# Pick a suitable person. Pick any person after 3 tries.
person = 0 # Init
for jj in range(3): # HARDCODE 3
person = ri(0, PEOPLE - 1)
# Count previus topics of interest
num = 0
for interest in people[person].interests.values():
if interest != 0:
num += 1
# Give new interest if few previous interests
if num < 2: # HARDCODE 2
people[person].interests[TOPICS[ii]] = d
break
# Smaller chance to get many interests
elif rr() < 0.3: # HARDCODE 0.3
people[person].interests[TOPICS[ii]] = d
break
# Anyone goes
else:
person = ri(0, PEOPLE -1)
people[person].interests[TOPICS[ii]] = d
# Split topic
if (ii == 0):
# Preferences go half and half
people[person].preference = 1 if nn % 2 == 0 else 2
return people
示例6: experiment
def experiment(N):
cnt = [0 for i in xrange(365)]
for i in xrange(N):
cnt[rr(365)] += 1
for x in cnt:
if x > 1:
return 1
return 0
示例7: MakeGraph
def MakeGraph(self, RandomGraph = True,UserTable = True):
if RandomGraph:
self.Random_Matrix = [
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]
]
for _ in range(2):
dir = [0,1]
dir.shuffle()
while True:
x = rr(1,5)
y = rr(1,5)
if self.Random_Matrix[x][y] == self.Random_Matrix[x+dir[0]][y+dir[1]] == 0:
break
self.Random_Matrix[x][y] = rr(1,3)
if self.Random_Matrix[x][y] == 1:
self.Random_Matrix[x+dir[0]][y+dir[1]] = 2
else:
self.Random_Matrix[x+dir[0]][y+dir[1]] = 1
for _ in range(2):
while True:
x = rr(1,5)
y = rr(1,5)
if self.Random_Matrix[x][y] == self.Random_Matrix[x][y+1] == \
self.Random_Matrix[x+1][y] == self.Random_Matrix[x+1][y+1] == 0:
break
self.Random_Matrix[x][y] = self.Random_Matrix[x+1][y+1] = 1
self.Random_Matrix[x][y+1] = self.Random_Matrix[x+1][y] = 2
self.User_Matrix=[
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]
]
示例8: random_timesequence
def random_timesequence(start, end, steps=3):
seq = []
for n in range(start, end):
# Randomize the number of sub-steps,
# but maintain the bounds and monotonicity
# (e.g. 0, 0, 1, 1, 1, 2, 3, 3, 3)
for i in range(rr(0, steps)):
seq.append(n)
return seq
示例9: rationals
def rationals(max_nums):
"""Doesn't cover entirety of the rationals, just an example subset"""
for n in range(0, max_nums):
try:
rand_example = rr(0, max_nums ** n) # Make things interesting
yield float(n) / float(rand_example), n, Fraction(n, rand_example)
except ZeroDivisionError:
yield 0,
raise StopIteration
示例10: make_person
def make_person():
return {
'name': faker.name(),
'email': faker.email(),
'address': faker.address(),
'url': faker.url(),
'created': dt.now(),
'age': rr(1, 99)
}
示例11: emit
def emit(routing_key='info'):
count = 0
# Randomize to mimic "authenticity"
time.sleep(float(rr(1, 10)) * 0.1)
start.channel.basic_publish(
exchange=start.EXCHANGE_NAME,
routing_key=routing_key,
body='MOAL Message! #{}'.format(count),
properties=pika.BasicProperties(delivery_mode=2))
count += 1
示例12: compute
def compute(self, recipe=1):
"""Don't be confused: the notion of a recipe is just for fun here.
It has nothing to do with lightmaps -- it's just to experiment
with example 'ascii lighting' for more interesting visualizations.
"""
self.lighting = []
pixels = self.height * self.width
if recipe == 1:
for k in xrange(pixels):
self.lighting.append(rr(0, 255))
elif recipe == 2:
for k in xrange(pixels):
self.lighting.append(rr(0, (k + 1) * 5))
elif recipe == 3:
for k in xrange(pixels):
if self.width < self.height:
self.lighting.append(rr(self.width, self.height))
else:
self.lighting.append(rr(self.height, self.width))
示例13: friends
def friends(people, param_num):
for ii, person in enumerate(people):
# Send friend requests
for nn in range(int(gauss(F_MEAN[param_num], F_DEVIATION[param_num]))):
# Pick a person
id = ri(0, PEOPLE - 1)
# Skip self
if id == ii:
continue
other_person = people[id]
# Logic of accepting a friend request
# Amount of previous friends
# HARDCODE All numbers
if len(other_person.friends) < 8 or (len(other_person.friends) < 12 and rr() < 0.7) or rr() < 0.3:
prob = 0.6 - F_PROB_BONUS[param_num]
# Mutual interests
for jj, topic in enumerate(TOPICS):
# Split topic
if jj == 0:
# No preference
if other_person.preference == 0 or person.preference == 0:
pass
# Same preference
elif person.preference == other_person.preference:
# Shared interest
prob += F_PROB_BONUS[param_num]
# Bonus
prob += 0.1
# Different preference
else:
# Penalty
prob -= 0.1
# Rest
else:
# Shared interest
if other_person.interests[topic] > 0 and person.interests[topic] > 0:
prob += F_PROB_BONUS[param_num]
# Accept of decline friend request
if rr() < prob:
person.friends.append(id)
other_person.friends.append(ii)
示例14: _divvy_ram
def _divvy_ram(self, ram):
"""This is an arbitrary, somewhat meaningless method, to simulate
the notion of free blocks of ram that must be allocated and
referenced via pointer. A given program may require X ram, but
the location of available ram may be disparate, so various blocks have
to be stored as a free linked list, or similar data structure.
Since we've already covered linked lists, association lists, etc...,
there isn't much value outside learning the context of this data
structure, which tends to be in memory management."""
subdivisions = rr(2, 20) # Arbitrary number
flist = []
while subdivisions > 0:
diff = rr(0, ram)
# Store ram as [current block of memory, location]
flist.append([diff, str(self.last_block).zfill(4)])
ram = ram - diff
self.last_block += 1
subdivisions -= 1
if DEBUG:
print_info('Ram: {} / diff: {}'.format(ram, diff))
return flist
示例15: make_person
def make_person(omit=[]):
val = {
'name': faker.name(),
'address': faker.address(),
'url': faker.url(),
'is_married': choice([True, False]),
'created': '{}'.format(dt.now()),
'age': rr(1, 99)
}
for _val in omit:
if _val in val:
val.pop(_val)
return val