本文整理汇总了Python中random.randrange函数的典型用法代码示例。如果您正苦于以下问题:Python randrange函数的具体用法?Python randrange怎么用?Python randrange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了randrange函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: draw
def draw(cmds, size=2): #output tree
stack = []
for cmd in cmds:
if cmd=='F':
turtle.forward(size)
elif cmd=='-':
t = random.randrange(0,7,1)
p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"]
turtle.color(p[t])
turtle.left(15) #slope left
elif cmd=='+':
turtle.right(15) #slope right
t = random.randrange(0,7,1) #рандомная пер. для цвета
p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"] #ряд цветов
turtle.color(p[t]) #выбор цвета из ряда
elif cmd=='X':
pass
elif cmd=='[':
stack.append((turtle.position(), turtle.heading()))
elif cmd==']':
position, heading = stack.pop()
turtle.penup()
turtle.setposition(position)
turtle.setheading(heading)
turtle.pendown()
turtle.update()
开发者ID:Papapashu,项目名称:main,代码行数:26,代码来源:python_three.py
示例2: fightClowns
def fightClowns(clowns):
global life
global hit
if clowns != 0:
print(str(clowns) + " clowns stagger towards you. Ready your " + str.lower(myWeapons[0]) + "!\n")
attack = raw_input("Attack, or Run? (A for attack, R for run)\n")
if (str.upper(attack) == "A"):
print(str(clowns) + " clowns attacked you!")
life = life - clownattack*clowns
hit = (hitMultiplier[random.randrange(0, len(hitMultiplier))]*weapon[myWeapons[0]])
if hit != 0:
print("You successfully killed them!")
print("Your life is now: " + str(life))
if (hit == 0):
print("That was a lucky miss. Next time you should attack! (You successfully runned)")
return 0
elif str.upper(attack) == "R":
stumblee = random.randrange(0, 2)
stumble = random.randrange(1, 7)
if stumblee > 0:
print("Run away from the zombies, you have stumbled and lost " + str(stumble) + " hp")
life = life - stumble
else:
print("Nothing was happened.")
elif clowns == 0:
print ("But Nobody Came!")
else:
hit = (hitMultiplier[random.randrange(0, len(hitMultiplier))]*weapon[myWeapons[0]])
if hit > 0:
life = life - clownattack
print (str(clowns) + " attack you, but you killed them\n" "Life health is now " + str(life))
开发者ID:Yuliafag,项目名称:ss-13,代码行数:32,代码来源:ss13.py
示例3: generate_picture
def generate_picture(self, file_name="image.png"):
size = list(self.destination.size)
if size[0] > 700:
aspect = size[1] / float(size[0])
size[0] = 600
size[1] = int(600 * aspect)
self.destination = self.destination.resize(
size, Image.BILINEAR).convert('RGB')
# fit the pallet to the destination image
self.palette = self.palette.resize(size, Image.NEAREST).convert('RGB')
self.destination.paste(self.palette, (0, 0))
# randomly switch two pixels if they bring us closer to the image
for i in xrange(500000):
first = (random.randrange(0, self.destination.size[0]),
random.randrange(0, self.destination.size[1]))
second = (random.randrange(0, self.destination.size[0]),
random.randrange(0, self.destination.size[1]))
original_first = self.original.getpixel(first)
original_second = self.original.getpixel(second)
dest_first = self.destination.getpixel(first)
dest_second = self.destination.getpixel(second)
if color_diff(original_first, dest_first) + \
color_diff(original_second, dest_second) > \
color_diff(original_first, dest_second) + \
color_diff(original_second, dest_first):
self.destination.putpixel(first, dest_second)
self.destination.putpixel(second, dest_first)
self.destination.save(file_name)
return file_name
开发者ID:SpokenBanana,项目名称:PicturePalet,代码行数:35,代码来源:picture_pallet.py
示例4: run_command
def run_command(command, info):
if settings.WORKERS_USE_TOR:
# Initialize and use tor proxy
socks_port = random.randrange(50000, 60000)
control_port = random.randrange(50000, 60000)
directory = '/tmp/%s' % uuid.uuid1()
os.makedirs(directory)
# Port collision? Don't worry about that.
tor_command = "tor --SOCKSPort %s --ControlPort %s --DataDirectory %s" % (socks_port, control_port, directory)
print "Executing tor command: %s" % tor_command
tor_command = shlex.split(tor_command)
proc = subprocess.Popen(tor_command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while proc.poll() is None:
output = proc.stdout.readline()
if 'Bootstrapped 100%: Done.' in output:
print 'We have a working connection!'
break
command += ' --proxy="127.0.0.1:%s" --proxy-type="socks5"' % socks_port
j = Job(run_command.request.id, info)
result = j.run(command)
j.finish(result)
if settings.WORKERS_USE_TOR:
proc.kill()
shutil.rmtree(directory)
开发者ID:nickhs,项目名称:hermes,代码行数:29,代码来源:runner.py
示例5: test_random_addition_and_slicing
def test_random_addition_and_slicing():
seed = random.randrange(10000)
print seed
random.seed(seed)
st = "abc"
curr = LiteralStringNode(st)
last = None
all = []
for i in range(1000):
a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
random.randrange(500))
last = curr
all.append(curr)
c = random.choice([0, 1, 2])
if c == 0:
curr = curr + LiteralStringNode(a)
st = st + a
elif c == 1:
curr = LiteralStringNode(a) + curr
st = a + st
else:
if len(st) < 10:
continue
# get a significant portion of the string
#import pdb; pdb.set_trace()
start = random.randrange(len(st) // 3)
stop = random.randrange(len(st) // 3 * 2, len(st))
curr = getslice_one(curr, start, stop)
st = st[start: stop]
assert curr.flatten_string() == st
curr = curr.rebalance()
assert curr.flatten_string() == st
开发者ID:Darriall,项目名称:pypy,代码行数:32,代码来源:test_rope.py
示例6: specialQuestion
def specialQuestion(oldq):
newq = [oldq[0], oldq[1]]
qtype = oldq[0].upper()
if qtype == "!MONTH":
newq[0] = "What month is it currently (in UTC)?"
newq[1] = time.strftime("%B", time.gmtime()).lower()
elif qtype == "!MATH+":
try:
maxnum = int(oldq[1])
except ValueError:
maxnum = 10
randnum1 = random.randrange(0, maxnum+1)
randnum2 = random.randrange(0, maxnum+1)
newq[0] = "What is %d + %d?" % (randnum1, randnum2)
newq[1] = spellout(randnum1+randnum2)
elif qtype == "!ALGEBRA+":
try:
num1, num2 = [int(i) for i in oldq[1].split('!')]
except ValueError:
num1, num2 = 10, 10
randnum1 = random.randrange(0, num1+1)
randnum2 = random.randrange(randnum1, num2+1)
newq[0] = "What is x? %d = %d + x" % (randnum2, randnum1)
newq[1] = spellout(randnum2-randnum1)
else: pass #default to not modifying
return newq
开发者ID:zonidjan,项目名称:erebus,代码行数:27,代码来源:trivia.py
示例7: createBridge
def createBridge(numOfNodes, edgeProb, bridgeNodes):
'''
numOfNodes: Number of nodes in the clustered part of the Bridge Graph
edgeProb: Probability of existance of an edge between any two vertices.
bridgeNodes: Number of nodes in the bridge
This function creates a Bridge Graph with 2 main clusters connected by a bridge.
'''
print "Generating and Saving Bridge Network..."
G1 = nx.erdos_renyi_graph(2*numOfNodes + bridgeNodes, edgeProb) #Create an ER graph with number of vertices equal to twice the number of vertices in the clusters plus the number of bridge nodes.
G = nx.Graph() #Create an empty graph so that it can be filled with the required components from G1
G.add_edges_from(G1.subgraph(range(numOfNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from 0 to numOfNodes, from G1 and add it to G
G.add_edges_from(G1.subgraph(range(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from (numOfNodes + bridgeNodes) to (2*numOfNodes + bridgeNodes)
A = random.randrange(numOfNodes) #Choose a random vertex from the first component
B = random.randrange(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes) #Choose a random vertex from the second component
prev = A #creating a connection from A to B via the bridge nodes
for i in range(numOfNodes, numOfNodes + bridgeNodes):
G.add_edge(prev, i)
prev = i
G.add_edge(i, B)
StrMap = {}
for node in G.nodes():
StrMap[node] = str(node)
G = nx.convert.relabel_nodes(G,StrMap)
filename = "BG_" + str(numOfNodes) + "_" + str(edgeProb) + "_" + str(bridgeNodes) + ".gpickle"
nx.write_gpickle(G,filename)#generate a gpickle file of the learnt graph.
print "Successfully written into " + filename
开发者ID:vijaym123,项目名称:Bidirectional-Search,代码行数:29,代码来源:AtoB.py
示例8: reset
def reset():
micek[0] = SIRKA//2 - 10
micek[1] = VYSKA//2 - 10
micek[2] = SIRKA//2 + 10
micek[3] = VYSKA//2 + 10
smer[0] = randrange(1,5)
smer[1] = randrange(-5,5)
开发者ID:zzuzzy,项目名称:PyLadies,代码行数:7,代码来源:myPong.py
示例9: test_merge
def test_merge(self):
inputs = []
for i in range(random.randrange(5)):
row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
inputs.append(row)
self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs)))
self.assertEqual(list(self.module.merge()), [])
开发者ID:LinkedModernismProject,项目名称:web_code,代码行数:7,代码来源:test_heapq.py
示例10: say
def say (self, what):
sentences=what.split(".")
for sentence in sentences:
sentence=sentence.strip()
if sentence=="":
continue
print ("SAYING: ", sentence)
path=os.path.dirname(os.path.abspath(__file__))+"/speechcache/"
filename=sentence.lower().replace(" ", "")+".mp3"
if not filename in self.soundCache:
tts=googletts.googleTTS(text=''+sentence,lang='es', debug=False)
tts.save(path+str(self.soundCache["soundIndex"])+".mp3")
self.soundCache[filename]=str(self.soundCache["soundIndex"])+".mp3"
self.soundCache["soundIndex"]=self.soundCache["soundIndex"]+1
song = pyglet.media.load(path+self.soundCache[filename])
song.play()
time_speaking=song.duration-0.5
start_time=time.time()
while time.time()-start_time<time_speaking:
pos=random.randrange(10,20)
self.head.jaw.moveTo(pos)
time.sleep(0.2)
pos=random.randrange(30,50)
self.head.jaw.moveTo(pos)
time.sleep(0.2)
self.head.jaw.moveTo(10)
time.sleep(0.5)
开发者ID:ugogarcia,项目名称:inmoovbrainserver,代码行数:32,代码来源:inmoov.py
示例11: testRun
def testRun():
# For testing
# count = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000, 80000, 85000, 90000, 95000, 100000]
count = 5000
while count < 5000000000:
# for num in testList:
randList = [None] * count
for n in range(0, count):
randNum = random.randrange(0, 101)
if (random.randrange(0, 2) == 0):
randNum = randNum * -1
randList[n] = randNum
startTime = time.clock()
result = linearSearch(randList)
stopTime = time.clock()
resultTime = stopTime - startTime
print("n: " + str(len(randList)))
print("Largest Result: " + str(result[2]))
print("Running Time: " + str(resultTime))
count = count * 10
开发者ID:gariepyt,项目名称:cs325_project1,代码行数:26,代码来源:linear.py
示例12: generate_bodies
def generate_bodies(place, area, body_amount):
delta = 0
bodies = []
for i in range(body_amount):
random.seed(i)
radiusXY = (randrange(2*area) - area)*0.05
radiusZ = (randrange(2*area) - area)*0.05
if (i <= body_amount/4):
shift = (delta, 0)
elif (i <= 2*body_amount/4):
shift = (-delta, 0)
elif (i <= 3*body_amount/4):
shift = (0, -delta)
else:
shift = (0, delta)
bodies.append (
{
'x': place[0] + radiusXY*cos(pi/AMOUNT * i) + shift[0],
'y': place[1] + radiusXY*sin(pi/AMOUNT * i) + shift[1],
'z': place[0] + radiusZ*sin(pi/AMOUNT * i),
'mass': randrange(10**(SUPERMASS//2), 10**(SUPERMASS-5)), #10**(SUPERMASS-4),
'radius': 10
}
)
return bodies
开发者ID:vovkd,项目名称:Simula,代码行数:25,代码来源:gm.py
示例13: main
def main():
l = [random.randrange(-10, 10) for i in range(random.randrange(5, 10))]
print l
# function
print "max value in list:%d" % (max_list(l))
print "min value in list:%d" % (min_list(l))
开发者ID:xiaoy,项目名称:Exercise,代码行数:7,代码来源:max.py
示例14: __init__
def __init__(self,numPlayers):
x = 0
while x < numPlayers:
#set random roles
r = randrange(0,numPlayers,1)
while self.roles[r][1] == True:
r = randrange(0,numPlayers,1)
self.roles[r][1] = True
self.role.append(self.roles[r][0])
#set health
if self.role[x] == "Sheriff":
self.health.append(5)
else: self.health.append(4)
#set horse through jail to false and no card
self.mustang.append([False,None])
self.scope.append([False,None])
self.barrel.append([False,None])
self.dynamite.append([False,None])
self.jail.append([False,None])
#set gun to none and volcanic to false
self.gun.append([1,None])
self.volcanic.append(False)
x += 1
开发者ID:phippene,项目名称:AI_Bang,代码行数:25,代码来源:BoardClass.py
示例15: int_generator
def int_generator(count=1, begin=1, end=101, is_fill=False):
_len = len(str(end))
for _ in range(count):
if is_fill:
yield str(random.randrange(begin,end)).zfill(_len)
else:
yield str(random.randrange(begin,end))
开发者ID:jiahut,项目名称:pipeline,代码行数:7,代码来源:gen_define.py
示例16: new_tile
def new_tile(self):
"""
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time.
"""
# replace with your code
# complete search ....
non_zero_count = 0;
for row in range(self._grid_height):
for col in range(self._grid_width):
if self._grid_tile[row][col] == 0:
non_zero_count += 1
random_choice = random.randrange(0, non_zero_count)
count = 0
# another search ....
generated_new_tile = False
for row in range(self._grid_height):
for col in range(self._grid_width):
if generated_new_tile == False and self._grid_tile[row][col] == 0:
if count != random_choice:
count += 1
else:
if random.randrange(0,100) < 10:
self.set_tile(row, col ,4)
else:
self.set_tile(row, col ,2)
generated_new_tile = True
开发者ID:coremedy,项目名称:Python-Algorithms-DataStructure,代码行数:28,代码来源:full.py
示例17: __init__
def __init__(self, world, player, name):
self.player = player
self.name = name
self.world = world
self.pos = None
self.color = colors[randint(0, len(colors) - 1)]
self.distance_travelled = 0
self.hits = 0
self.kills = 0
while 1:
# Pick a random spot in the maze
rand_x = randrange(len(self.world.world) - 1)
rand_y = randrange(len(self.world.world[0]) - 1)
pos = self.world.world[rand_x][rand_y]
# Is there someone else there?
found = False
for p in self.world.players:
if p.pos == pos:
found = True
break
if not found:
self.pos = pos
self.pos.player = self
break
self.direction = ['n', 's', 'e', 'w'][randint(0,3)]
# Hookup the IO
self.player.set_forward(self.forward)
self.player.set_left(self.left)
self.player.set_right(self.right)
self.player.set_fire(self.fire)
开发者ID:garionphx,项目名称:robots,代码行数:34,代码来源:world.py
示例18: process_buck
def process_buck(L1,L2,D0,D1,D2,ratio,weight,gui_mode):
#CALL NEXT MODULE
#buck0i_1
if os.path.isfile(sys.path[0]+os.sep+"price_skew.txt"):
os.remove(sys.path[0]+os.sep+"price_skew.txt")
target = 60
i = 200
while i > 0:
Length = randrange(L1,L2) #setting tree length
#Tree descriptor vectors
log_vector = [0,Length]
diameter_vector = [D0,randrange(D1,D2)]
# calculations
(Lf,v1,td1,p1,Lf2,v2,td2,p2) = buck2(Length,log_vector,diameter_vector)
set_price_skew(target,ratio,weight)
track_data(Lf,p1,v1)
i = i - 1
# buck_result_display(gui_mode,Lf,v1,td1,p1,Lf2,v2,td2,p2)
graph_data(target)
os.remove(sys.path[0]+os.sep+"data.txt")
开发者ID:dhazel,项目名称:buck,代码行数:30,代码来源:buck.py
示例19: sampleQuizzes
def sampleQuizzes(num_trials):
"""Problem 5.1
You are taking a class that plans to assign final grades based on two
midterm quizzes and a final exam. The final grade will be based on 25% for
each midterm, and 50% for the final. You are told that the grades on the
exams were each uniformly distributed integers:
Midterm 1: 50 <= grade <= 80
Midterm 2: 60 <= grade <= 90
Final Exam: 55 <= grade <= 95
Write a function called sampleQuizzes that implements a Monte Carlo
simulation that estimates the probability of a student having a final
score >= 70 and <= 75. Assume that 10,000 trials are sufficient to provide
an accurate answer.
"""
in_range = 0
# as per spec
mid1_low, mid1_high = 50, 80
mid2_low, mid2_high = 60, 90
fin_low, fin_high = 55, 95
for trials in range(num_trials):
grade = .25 * random.randrange(mid1_low, mid1_high + 1) + \
.25 * random.randrange(mid2_low, mid2_high + 1) + \
.50 * random.randrange(fin_low, fin_high + 1)
if 70 <= grade <= 75:
in_range += 1
# P(totG) with 70 <= totG <= 75 is simply in_range / num_trials ratio
return in_range / float(num_trials)
开发者ID:franzip,项目名称:edx,代码行数:28,代码来源:problem5.py
示例20: generate_prime
def generate_prime(b, k=None):
#Will generate an integer of b bits that is probably prime.
#Reasonably fast on current hardware for values of up to around 512 bits.
bits = int(b)
assert bits > 1
if k is None:
k = 2*bits
k = int(k)
if k < 64:
k = 64
if DEBUG: print "(b=%i, k=%i)"%(bits,k),
good = 0
while not good:
possible = random.randrange(2**(bits-1)+1, 2**bits)|1
good = 1
if DEBUG: sys.stdout.write(';');sys.stdout.flush()
for i in smallprimes:
if possible%i == 0:
good = 0
break
else:
for i in xrange(k):
test = random.randrange(2, possible)|1
if RabinMillerWitness(test, possible):
good = 0
break
if DEBUG: sys.stdout.write('.');sys.stdout.flush()
if DEBUG: print
return possible
开发者ID:bhramoss,项目名称:code,代码行数:30,代码来源:recipe-410681.py
注:本文中的random.randrange函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论