示例#1
0
def roll_dice(number_of_sides): #define possible value combinations
  first_roll = randomint(1, number_of_sides)
  second_roll = randomint(1, number_of_sides)
  max_val = number_of_sides * 2
  #provide user with max value possible
  print "Maximum possible value rolled is: " + str(max_val)
  sleep(1) #simulate thinking
  user_guess = get_user_guess()
  if user_guess > max_val: #pervent user from entering invalid guess
    print "No guessing higher than the maximum possible value!"
    return
    else:
      print "Rolling..."
      sleep(2) #simulate rolling dice
      print "The first value is: %d" %first_roll
      sleep(1)
      print "Rolling again..."
      sleep(2)
      print "The second value is: %d" %second_roll
      sleep(1)
      total_roll = first_roll + second_roll
      print total_roll
      print "Result..."
      sleep(1)
      if user_guess > total_roll:
        print "Congratulations, you've won!"
        return
      else:
        print "Sorry, you've lost."
        return
示例#2
0
    def choose_random(self, root, N):
        # Total number of Nodes
        # Probability of choosing root = 1/N
        # Probability of choosing left child = Left_SIZE * 1/N
        # Probability of choosing right child = RIGHT_SIZE * 1/N
        # Total probability = 1/N (1 + LEFT_SIZE + RIGHT_SIZE)
        probability_dict = \
            {
                root.left.size / N : root.left,
                root.right.size / N : root.right,
                1/N : root
            }
        probT = (1 + root.left.size + root.right.size) / N
        # Roll the dice now
        choice = random.randomint(0,probT)
        # This is to sort all the probabilities in
        # increasing order.

        ordered_p = sorted(probability_dict.keys())
        if choice < ordered_p[0]:
            final = probability_dict[ordered_p[0]]
        elif choice < ordered_p[1]:
            final = probability_dict[ordered_p[1]]
        else:
            final = probability_dict[ordered_p[-1]]

        if final == root:
            return root
        else:
            self.choose_random(final, N)
def random_msg():
  date = random_date()
  sys.stderr.write('date: %s\n' % date)
  return met_hydro.MetHydro31(
      source_mmsi=random.randomint(100000, 999999999),
      lon=random.randint(-180000, 180000) / 1000.,
      lat=random.randint(-90000, 90000) / 1000.,
      pos_acc=random.choice(0, 1), day=date.day, hour=date.hour,
      minute=date.minute, wind=random.randint(0, 127),
      gust=random.randint(0, 127), wind_dir=random.randint(0, 360),
      gust_dir=random.randint(0, 360),
      air_temp=random.randint(-600, 60) / 10.,
      humid=random.randint(0, 101), dew=random.randint(-200, 501) / 10.,
      air_pres=random.randint(800, 1201),
      air_pres_trend=random.choice((0, 1, 2, 3)),
      vis=random.randint(0, 127) / 10.,
      wl=random.randint(-100, 300) / 10.,
      wl_trend=random.choice((0, 1, 2, 3)),
      cur_1=random.randint(0, 251) / 10., cur_dir_1=random.randint(0, 360),
      cur_2=random.randint(0, 251) / 10., cur_dir_2=random.randint(0, 360),
      cur_level_2=random.randint(0, 31),
      cur_3=random.randint(0, 251) / 10., cur_dir_3=random.randint(0, 360),
      cur_level_3=random.randint(0, 31),
      wave_height=random.randint(0, 251) / 10.,
      wave_period=random.randint(0, 60), wave_dir=random.randint(0, 360),
      swell_height=random.randint(0, 251) / 10.,
      swell_period=random.randint(0, 60), swell_dir=random.randint(0, 360),
      sea_state=random.choice(met_hydro.beaufort_scale.keys()),
      water_temp=random.randint(-100, 501) / 10.,
      precip=random.choice(met_hydro.precip_types.keys()), salinity=50.1,
      ice=random.choice(0, 1, 3))
示例#4
0
def mutateColor(rgbTuple = None):
	"""creates a random color based on provided tuple"""
	if rgbTuple is None:
		x = [random.randomint(0,255) for x in range(3)]
		return tuple(x)
	amounts	= []
	amount 	= [0,0,0]
	rgbList	= list(rgbTuple)
	fullMutate = settings.getValue('COLORS', 'allChange', 1)
	changeMagnitude = settings.getValue('COLORS', 'magnitude', 1)
	if changeMagnitude != 0:
		for value in amount:
			while value is 0: value = random.randint(-changeMagnitude,changeMagnitude)
		amounts.append(value)
	'''
	decides whether or not each value changes
	#0-2: single color change - (0-r,   1-g,   2-b)
	#3-5: double color change - (3-rg,  4-rb,  5-gb)
	#6-8: single color change - (6-r,   7-g,   8-b)
	#9-?: triple color change - (9-? - rgb)
	'''
	mutate = random.randint(0,8+fullMutate)
	if   (mutate >= 0) and (mutate <= 2): rgbList[mutate]	+= amounts[mutate]
	elif (mutate >= 6) and (mutate <= 8): rgbList[mutate-6] += amounts[mutate-6]
	elif (mutate == 3) or  (mutate == 4): rgbList[0] += amounts[0]
	elif (mutate == 3) or  (mutate == 5): rgbList[1] += amounts[1]
	elif (mutate == 4) or  (mutate == 5): rgbList[2] += amounts[2]
	elif (mutate >=9): rgbList = [rgbList[x]+amounts[x] for x in range (3)]
	rgbList = [0 if value < 0 else 255 if value > 255 else value for value in rgbList]
	return tuple(rgbList)
示例#5
0
def test_build_coder():
    """Test the build coder method in ps4.py"""
    shift = random.randomint(1, 27)
    coder = build_coder(shift)
    self.assertTrue(isinstance(coder, dict))
    random_letter = random.choice(string.letters[:25])
    self.assertEqual(coder[random_letter], chr(ord(random_letter) + shift))
示例#6
0
 def mkdir_list(input):
     list = []
     for count in input:
         # 0から100の数値をランダムで格納
         data = random.randomint(0, 100)
         list.append(data)
     
     # ランダムに格納されたリストの中身を表示する
     print list
def full_matrix():
	Matrix = []
	for index in range(DISCHARGE):
		String = []
		for j_ind in range(DISCHARGE):
			String.append(randomint(MODULE))
		Matrix.append(String)
			
	return Matrix		
def weighted_choice(value_list, weight_list):
    counter = 0
    sum_weight = sum(weight_list)
    random_weight = random.randomint(0, sum_weight)
    for i, weight in enumerate(weight_list):
        if random_weight >= counter:
            counter += weight
        else:
            return val_list[i]
def main():
	mininum=raw_input("What is the minimum number?:")
	maximum=raw_input("What is the maximum number?:")
	print "I'm thinking of a number from {} to {}.".format(int(minimum),int(maximum))
	g=raw_input("What do you think it is?:")
	n=random.randomint(int(minimum),int(maximum))
	print "The target was {}".format(int(n))
	print "Your guess was {}".format(int(g))
	if g == n
		print "You guessed right! You must be psychic!"\
示例#10
0
 def __init__(self, roomnumber=-1):
     self.number = GenericItem.number
     GenericItem.number += 1
     World.items[self.number] = self
     if roomnumber == -1:
         self.roomnumber = random.randomint(0, 2)  ###fixme
     else:
         self.roomnumber = roomnumber
     self.farbe = random.choice(["rot", "blau", "gruen"])
     self.eigen = random.choice(["gross", "klein", "stinkig"])
示例#11
0
def crawlDownTree(starterNode):
	# print "CRAWLING"

	reachedNewNode = False
	currNode = starterNode
	url = ''


	# For every othe rcase:
	while True:
		# Restart crawl down if a site is off topic.
		if currNode.offTopic:
			currNode = starterNode
		else:
			startOver = False
			useLinks = True
			# You must treat search query pages specially
			if currNode.isQuery:
				if random.random() < PROBABILITY_RELATED_QUERY:
					useLinks = False
			# In both cases, you may draw from traditional links. 
			# This includes traditional links or search results:
			if useLinks:
				index = random.randint(0, len(currNode.links) - 1)
				if currNode.links[index][1] == None:
					reachedNewNode = True
					newNode = Node()
					newNode.isQuery = False
					currNode.links[index][1] = newNode
					url = currNode.links[index][0]
				if startOver:
					currNode = starterNode
				else:
					currNode = currNode.links[index][1]
			else:
				index = random.randomint(0, len(currNode.relatedQueries) - 1)
				if currNode.relatedQueries[index][1] == None:
					reachedNewNode = True
					newNode = Node()
					newNode.isQuery = True
					currNode.relatedQueries[index][1] = newNode
					url = currNode.relatedQueries[index][0]
					startOver = (regexValidation.search(url) is not None)
				if startOver:
					currNode = starterNode
				else:
					currNode = currNode.relatedQueries[index][1]
		if reachedNewNode:
			break

	
	currNode.hasNotBeenRead = True
	return url, currNode
示例#12
0
文件: node_test.py 项目: joegle/7exy
def getNormalMatrixAddress(shape,n):
    """Throw normal"""
    limit=4
    std=2
    address=[]
    center=[]
    for axi in shape:
        center.append(r.randomint(0,axi-1))
    address.append(center)
    c=[]
    x=0
    for axi in shape:
        if axi<=limit:
            c.append(np.random.randint(0,axi-1,n-1))
        else:
            c.append(np.random.normal(center[x],std,n-1))
        x+=1
示例#13
0
def fuzzer(maxlength=1024,t = str):
  if t == str:
    string_length = int(random.random() * maxlength)   
    out = ""
    for i in range(0, string_length):
      out += chr(int(random.random() * 96 + 32)) 
  elif t == int:
    out = random.randomint(0,maxlength)
  elif t == float:
    out = random.random()
  elif t == list:
    #nesting not supported
    #random list
    #recursive
    length = random.random * maxlength 
    gentypes = [random.choice(str,int,float) for i in range(length)]
    out = [fuzzer(maxlength,ty) for I,ty in zip(length,gentypes)]
  return out
 def walk(self):
     for node in self.table:
         node.freq_to_prob()
     start_index = random.randomint(0, len(self.starts) - 1)
     starter = self.starts[start_index]
     go = True
     final_string = starter + " "
     hash_val = hash(starter)
     hash_val = hash_val % self.size
     while go:
         prob_index = random.random()
         prob_sum = 0
         for key, value in self.table[hash_val].keys.items():
             prob_sum += value
             if prob_sum >= prob_index:
                 final_string += key + " "
                 next_word = key
                 break
         hash_val = hash(next_word)
         hash_val = hash_val % self.size
示例#15
0
    countWave = 0
    countDance = 0
    initDone = False
    while not rospy.is_shutdown():
        # call function to get sensor value
        port = 1

                # Initialize
                if not initDone:
                        initRobotPosition()
                        initDone = True

                # Waves when it senses something in front of it // TEST THIS WITH THE NEW FIRMWARE WRAPPER
		if somethingInFront():
                        waveHand()

                # Dances random dance
                whichDance = random.randomint(1, 3)
                if whichDance == 1:
                    danceMotionOne()
                elif whichDance == 2:
                    danceMotionTwo()
                elif whichDance == 3;
                    danceMotionThree()

	
                # sleep to enforce loop rate
                r.sleep()

示例#16
0
         txd=0; tyd=0
 tx+=txd; ty+=tyd
 
 # This part stops Tux from leaving the edges of screen
 if tx<0: tx=0
 if tx>=540: tx=540
 if ty<=0: ty=0
 if ty>=330: ty=330
 
 # Make the ball chase Tux
 if bx>=tx: bx=bx-1
 else: bx=bx+1
 if by>=ty: by=by-1
 else: by=by+1
 fx = fx-4
 if fx<=-10: fx=600; fy=random.randomint(0,370)
 
 # Collision Detection (Tux & Fish, Tux & Ball)
 if fx<=tx+50 and fx>=tx and fy>=ty-30 and fy<=ty+70:
     toy.play(); fx=600;fy=random.randint(0,370); score+=1
 if bx<=tx+40 and bx>=tx-40 and by>=ty-50 and by<ty+60:
     burp.play(); bx=600; by=-15; lives -=1; tx=280; ty=180
 
 screen.fill(bkcol);
 screen.blit(tuxsurf,[tx,ty])
 screen.blit(fishsurf,[fx,fy])
 screen.blit(ballsurf,[bx,by])
 font = pygame.font.Font(None,20)
 text = font.render("Score: "+str(score), 1, (0,0,0))
 screen.blit(text,[5,5])
 text = font.render("Lives: "+str(lives), 1, (0,0,0))
    raise ZeroDivisionError
finally:
    print("We're done")

# Oops
# We're done

#############
# Importing #
#############
# imports are done with the 'import' keyword, if 'from' is used then there is no
# need to specify the namespace.
import random
from time import sleep

sleep(random.randomint(1, 100))

############
# File I/O #
############
# File I/O are very easy in python, but there are two methodes that can be
# used. We'll see the two and prefer the later.

myfile = open(r"./myfile", "w")    # "w" to write, the r"" is the path
myfile.write("coucou\n")
myfile.writelines(["Ahaha\n", "Ohoho\n"])
myfile.close()

myfile = open(r"./myfile")    # default is read, "r" to do it explicitely
print(myfile.readline())
# coucou