def ShootBubble(player): bubble = player.AddProjectile(player.Direction * 0.3, 0.3, 0.1, 0.1); bubble.SetVelocity(player.Direction * 2 * (Random.NextDouble() + 1), 0); bubble.CollisionMask = 0x0001; bubble.SetSkeleton("Moves/Bubble/Bubble"); bubble.SetAnimation("idle", True); bubble.Mass = 0.001; bubble.Scale = 0.005; bubble.Duration = Random.NextDouble() + 0.5; def Hit(self, other): other.TakeSpecialDamage(1, player); self.Unload(); bubble.OnCollidePlayer = Hit; def Earth(self): self.Unload(); bubble.OnCollideEarth = Earth; def Float(self, time): self.ApplyForce(0, 0.008 + (Random.NextDouble() * 0.004)); bubble.OnUpdate = Float; return bubble;
def initialiseAgents(self): if self.active_agent_1 == True: if self.algorithmAgent1 == "Qlearning": self.agent1 = Qlearn.Qlearning(self.width, self.height, self.initState1, self.world, 1, self.alphaAgent1, self.gammaAgent1, self.epsilonAgent1) if self.algorithmAgent1 == "BFS": self.agent1 = BFS.shortestPath(self.width, self.height, self.initState1, self.world, 1) if self.algorithmAgent1 == "Random": self.agent1 = Random.Random(self.width, self.height, self.initState1, self.world, 1) if self.active_agent_2 == True: if self.algorithmAgent2 == "Qlearning": self.agent2 = Qlearn.Qlearning(self.width, self.height, self.initState2, self.world, 2, self.alphaAgent2, self.gammaAgent2, self.epsilonAgent2) if self.algorithmAgent2 == "BFS": self.agent2 = BFS.shortestPath(self.width, self.height, self.initState2, self.world, 2) if self.algorithmAgent2 == "Random": self.agent2 = Random.Random(self.width, self.height, self.initState2, self.world, 2)
def Attack(player): if (player.OnGround): player.SetAnimation("ember", False) player.Disable(1.0) player.Cooldown = 4.0 Hit = player.AddDamageBox(0, 0.2, 2.0, 2.0) Hit.Duration = 0.5 for i in range(10): Fire = player.AddProjectile(0, 0, .5, .5) Fire.SetVelocity((Random.NextDouble() - 0.5) * 10, Random.NextDouble() + 3) Fire.SetSkeleton("Moves/Flameburst/Flameburst") Fire.SetAnimation("idle", False) Fire.CollisionMask = 0x0001 def Destroy(self): self.Unload() Fire.OnCollideEarth = Destroy def FireParticle(self, other): other.TakeSpecialDamage(5, player) Fire.OnCollidePlayer = FireParticle def Explosion(self, other): other.SetVelocity(player.Direction * 2, 3) other.Disable(1.0) other.TakeSpecialDamage(15, player) Hit.OnCollidePlayer = Explosion
def Attack(player): player.SetAnimation("ember", False) player.Disable(0.5) player.Cooldown = 1 for i in range(Random.Next(3) + 6): fire = player.AddProjectile(player.Direction * 0.3, 0.3, 0.1, 0.1) fire.SetVelocity(player.Direction * (Random.NextDouble() + 4), 2 + (Random.NextDouble() / 3)) fire.CollisionMask = 0x0001 fire.SetSkeleton("Moves/Ember/Ember") fire.SetAnimation("idle", True) fire.Z = Random.NextDouble() - 0.5 fire.Permanent = True def Hit(self, other): other.TakeSpecialDamage(2, player) self.SetAnimation("burn", True) self.Duration = 0.5 self.Permanent = False fire.OnCollidePlayer = Hit def Earth(self): self.Permanent = False self.Unload() fire.OnCollideEarth = Earth
def generate_code(self): func = Random.from_dict(KERNEL_RETVALS_300) x0 = Random.get_u32() self.secret = KERNEL_RETVALS_300[func](x0) return 'u32 {0} = {1}; // Returns 0x{2:08x}\n'.format( self.var_name, '((u32(*)(u32))0x%xull)(0x%x)' % (func, x0), self.secret)
class LatencySimulator(object): """ 这个类的代码不能修改 class Tcp只能通过 vnet.send() vnet.recv()和这个虚拟网络收发数据 """ def __init__(self, from_, to, lost_ratio=10, min_rtt=60, max_rtt=125, nmax=1000): self.from_ = from_ self.to = to self.from_to = [] self.to_from = [] self.lost_ratio = lost_ratio self.min_rtt = min_rtt / 2 self.max_rtt = max_rtt / 2 self.rtt = self.max_rtt - self.min_rtt self.nmax = nmax print "min rtt", self.min_rtt print "max rtt", self.max_rtt print "rtt", self.rtt self.from_random = Random() self.to_random = Random() def send(self, who, data): if who is self.from_: if self.from_random.random() < self.lost_ratio: log("%s lost %s", who, hexlify(data)) return l = self.from_to else: if self.to_random.random() < self.lost_ratio: log("%s lost %s", who, hexlify(data)) return l = self.to_from if len(l) >= self.nmax: return l.append( (data, u(clock() + self.min_rtt + self.rtt * random.random()))) def recv(self, who): if who is self.from_: l = self.to_from else: l = self.from_to if l and l[0][1] < clock(): return l.pop(0)[0] return None
def quicksort(list, left, right): if left < right: # get a pivot index pivotIndex = Random.getRandomInt(len(listToSort)) while pivotIndex < left or pivotIndex > right: pivotIndex = Random.getRandomInt(len(listToSort)) pivotNewIndex = partition(list, left, right, pivotIndex) # Recursively sort elements on each side quicksort(list, left, pivotNewIndex - 1) quicksort(list, pivotNewIndex + 1, right)
def Random_dummy(atomlist, box): max_index = Rebuild.Max_index(atomlist) other_index = Random.Return_index_Other(atomlist) num_dummy = Calc_dummy(atomlist) choose_index, choose_list = [], [] while len(choose_index) < num_dummy: new_index = nr.choice(other_index, 1) monoindex = atomlist.search_index(new_index).Monomer_print_index() for index in monoindex: if index in other_index: other_index.remove(index) choose_index.append(new_index) choose_list.append(atomlist.search_index(new_index)) choose_list = Init.Atomlist(choose_list) dummylist = [] for atom in choose_list.value: bx, by, bz = box.x, box.y, box.z carbon = atom.neighbour[0] rx, ry, rz = atom.x * bx, atom.y * by, atom.z * bz Rx, Ry, Rz = carbon.x * bx, carbon.y * by, carbon.z * bz vect1 = np.array([Rx - rx, Ry - ry, Rz - rz]) vect1 = vect1 / np.linalg.norm(vect1) * 5 #Estimated Radii qx, qy, qz = (np.array([Rx, Ry, Rz]) + vect1).tolist() dummy = Dummy(qx / bx, qy / by, qz / bz, 'X' + str(max_index + 1) + 'x', max_index + 1) max_index = max_index + 1 atomlist.value.append(dummy) dummylist.append(dummy) dummylist = Init.Atomlist(dummylist) print('Successful Creat Dummy Atoms') return atomlist, dummylist
def generate_scramble(self): if DISABLE_SCRAMBLE: return 'u32 {0} = {1};\n'.format(self.var_name, self.constant) ret = '' ret += '// Scrambling constant %d (0x%x)\n' % (self.constant, self.constant) secrets = SecretGenerators.get_N_random_secrets(5 + Random.get_u32()%3) for s in secrets: ret += s.generate_code() ret += '// Beginning scramble\n' op = secrets[0] for i in range(1, len(secrets)): OpType = Operators.get_random_op() op = OpType(op, secrets[i]) ret += op.generate_code() ret += '// Ending scramble\n' last_op_name = op.get_var_name() last_op_val = op.get_result() ret += 'u32 {0} = {1} ^ 0x{2:08x};\n'.format(self.var_name, last_op_name, last_op_val ^ self.constant) ret += '// %s == %d\n' % (self.var_name, self.constant) if TEST: ret += 'if (%s != %d) fatalSimple(MAKERESULT(222, %d));\n' % (self.var_name, self.constant, Variable.alloc_err()) ret += '\n' return ret
def joueplsr(): nbrepartie = 0 j1 = 0 j2 = 0 eg = 0 tj1 = 0 tj2 = 0 tt = time.time() while (nbrepartie < NBPARTIE): if (nbrepartie == (NBPARTIE / 2)): global joueur2 global joueur1 print("score mi-temps(" + str(nbrepartie) + " partie):\nj1: " + str(j1) + " \nscore j2: " + str(j2) + "\nnb d'equalite : " + str(eg) + "\n") s = joueur1 joueur1 = joueur2 joueur2 = s a = j1 j1 = j2 j2 = a a = tj1 tj1 = tj2 tj2 = a jeu = game.initialiseJeu() it = 0 while ((it < 100) and (not (game.finJeu(jeu)))): if (it < 4): coup = Random.saisieCoup(game.getCopieJeu(jeu)) game.joueCoup(jeu, coup) else: t1 = time.time() coup = saisieCoup(jeu) if game.getJoueur(jeu) == 1: tj1 += time.time() - t1 else: tj2 += time.time() - t1 game.joueCoup(jeu, coup) it += 1 g = game.getGagnant(jeu) tj1 = tj1 / it tj2 = tj2 / it if (g == 1): j1 += 1 if (g == 2): j2 += 1 if (g == 0): eg += 1 nbrepartie += 1 tt = time.time() - tt print("score final :\nj1: " + str(j2) + "temps/coup=" + str(tj2) + "\nj2: " + str(j1) + "temps/coup=" + str(tj2) + "\nnb d'equalite : " + str(eg))
def evaluationPoints(object, n, smallest = 0.3, largest = 0.5): """Returns a list of |n| points suitable for the evaluation of the electrostatic potential around |object|. The points are chosen at random and uniformly in a shell around the object such that no point has a distance larger than |largest| from any atom or smaller than |smallest| from any non-hydrogen atom. """ atoms = object.atomList() p1, p2 = object.boundingBox() margin = Vector(largest, largest, largest) p1 = p1 - margin p2 = p2 + margin a, b, c = tuple(p2-p1) offset = 0.5*Vector(a, b, c) points = [] while len(points) < n: p = p1 + Random.randomPointInBox(a, b, c) + offset m = 2*largest ok = 1 for atom in atoms: d = (p-atom.position()).length() m = min(m, d) if d < smallest and atom.symbol != 'H': ok = 0 if not ok: break if ok and m <= largest: points.append(p) return points
def create(size, start, end): #middle = [[0 for i in range(size[1])] for i in range(size[0])] middle = Random.create(size, start, end) markedY = 0 markedX = start # Edit the values to connect the maze while markedY != size[1] - 2 and markedX != end: [top, right, bottom, left] = boundcheck(size, markedY, markedX) if right and random.randrange(5) == 0: middle[markedY][markedX + 1] = 0 else: right = False if bottom and random.randrange(5) == 0: middle[markedY + 1][markedX] = 0 else: bottom = False if left and random.randrange(5) == 0: middle[markedY][markedX - 1] = 0 else: left = False #Follow the new path if right: markedX = markedX + 1 elif bottom: markedY = markedY + 1 elif left: markedX = markedX - 1 return middle
def update(i, x): i.n = i.n + 1 r = R.r() if len(i._all) < i.most: i._all.append(x) elif r < len(i._all) / i.n: i._all[math.floor(1 + r * len(i._all))] = x return x
def get_tests(config={}): tests = [] import Cipher; tests += Cipher.get_tests(config=config) import Hash; tests += Hash.get_tests(config=config) import Protocol; tests += Protocol.get_tests(config=config) import PublicKey; tests += PublicKey.get_tests(config=config) import Random; tests += Random.get_tests(config=config) import Util; tests += Util.get_tests(config=config) return tests
def Build_one(inputfile='PVDF-model.cif'): box, atomlist = Init.Split_file(inputfile) #oldatomlist=atomlist #print('A Good Thing is that We Successfully Initialize the File!') build_index = Random.Randomlize(atomlist) atomlist, Good_random, count = Rebuild.Rebuild_H_to_CF3( atomlist, build_index, box) if not Good_random: while Good_random != True: print('Starting Regeneration, this would be time-consuming') box, atomlist = Init.Split_file(inputfile) #atomlist=oldatomlist build_index = Random.Randomlize(atomlist) atomlist, Good_random, count = Rebuild.Rebuild_H_to_CF3( atomlist, build_index, box) print('Luckily We have a Good Random Number! Though Still ' + str(count) + ' Warning was Made. Forget it.') return box, atomlist
def data_generate(self, b, c, d, file_name): with open(file_name + '.csv', 'w') as csvFile: writer = csv.DictWriter(csvFile, fieldnames=self.headers) writer.writeheader() for i in range(self.records): writer.writerow({ "PERSON_ID": PatientRecord_RB.person_id, "Patient Name": rd.person_name(), "BIRTH_DATETIME": self.dob_time(b, c, d), "Age": self.age_dist, "Phone Number": rd.phone_num(), "Address": self.address(), "City": self.city, "Postcode": self.postcode }) PatientRecord_RB.person_id += 1 csvFile.close() print(m2)
def getRandVal(self, targetList): randNumObj = Random.Random() try: if type(targetList) is not list: raise Exception except: print("Enter a value of type list.") else: randNum = randNumObj.randNumMaker(0, len(targetList)) return targetList[randNum]
class run_manager: def __init__(self, foam): ''' ''' self.foam = foam self.lld = 0.0 self.phs = [] self.energy_deposition = [] self.counts = 0 self.interactions = 0 self.escapes = 0 self.histories = 10 self.rng = Random() self.iteration = 0 def set_histories(self, n): ''' ''' self.histories = n def set_lld(self, lld): ''' ''' self.lld = lld def execute_history(self, iteration): ''' ''' #Initialize the history with a vector of random numbers self.rng.initialize_history(iteration) hist = history(self.rng, self.foam) #Transport a neutron for this history interaction = hist.transport_neutron() if interaction: self.energy_deposition.append(hist.ionization) self.interactions += 1 if hist.ionization >= self.lld: self.phs.append(hist.ionization*1E-6) self.counts += 1 else: self.escapes += 1 self.iteration += 1
def Attack(player): player.SetAnimation("leech_seed", False); player.Disable(1); player.Cooldown = 1.5; seed = player.AddProjectile(0, 0, 0.1, 0.1); seed.SetVelocity((Random.NextDouble() + 1) * player.Direction, 3 + (Random.NextDouble() * 2)); seed.CollisionMask = 0x0001; seed.SetSkeleton("Moves/LeechSeed/LeechSeed"); seed.SetAnimation("seed", False); seed.Z = Random.NextDouble() - 0.5; seed.Permanent = True; def Leech(self, other): amount = other.HP / 10; other.HP -= amount; player.HP += amount; seed.OnCollidePlayer = Leech; def Earth(self): self.SetAnimation("plant", False); seed.OnCollideEarth = Earth;
def playgame(self): winners = None while len(winners) != 0: myScore = sum([Random.random() for x in range(0, 10)]) myScore = "<transmission><source>" + self.identifier + "</source><score>" + myScore + "</score></transmission>" for aPDS in self.cloud: ## TODO: make sure that you add a callback for this - everyone needs to have responded before the winner can be assigned. ## TODO: sendTo(aPDS(myScore)) ## TODO: tallyResults(score, aPDS) ## TODO: self.coordinator = assignWinner(game) pass return winners[0]
def __init__(self, foam): ''' ''' self.foam = foam self.lld = 0.0 self.phs = [] self.energy_deposition = [] self.counts = 0 self.interactions = 0 self.escapes = 0 self.histories = 10 self.rng = Random() self.iteration = 0
def __init__(self, from_, to, lost_ratio=10, min_rtt=60, max_rtt=125, nmax=1000): self.from_ = from_ self.to = to self.from_to = [] self.to_from = [] self.lost_ratio = lost_ratio self.min_rtt = min_rtt / 2 self.max_rtt = max_rtt / 2 self.rtt = self.max_rtt - self.min_rtt self.nmax = nmax print "min rtt", self.min_rtt print "max rtt", self.max_rtt print "rtt", self.rtt self.from_random = Random() self.to_random = Random()
def jouentrainement(ev): global joueur2 global joueur1 nbrepartie = 0 j1 = 0 j2 = 0 eg = 0 switch = 1 while (nbrepartie < NBPARTIE): if (nbrepartie == (NBPARTIE / 2)): s = joueur1 joueur1 = joueur2 joueur2 = s a = j1 j1 = j2 j2 = a switch = 2 jeu = game.initialiseJeu() it = 0 while ((it < 100) and (not (game.finJeu(jeu)))): if (it < 4): coup = Random.saisieCoup(game.getCopieJeu(jeu)) game.joueCoup(jeu, coup) else: if (game.getJoueur(jeu) == switch): coup = saisieCoupTr(jeu, ev) else: coup = saisieCoup(jeu) game.joueCoup(jeu, coup) it += 1 g = game.getGagnant(jeu) if (g == 1): j1 += 1 if (g == 2): j2 += 1 if (g == 0): eg += 1 nbrepartie += 1 if (nbrepartie == NBPARTIE): s = joueur2 joueur2 = joueur1 joueur1 = s return j2 - j1
def get_tests(config={}): tests = [] import Cipher tests += Cipher.get_tests(config=config) import Hash tests += Hash.get_tests(config=config) import Protocol tests += Protocol.get_tests(config=config) import PublicKey tests += PublicKey.get_tests(config=config) import Random tests += Random.get_tests(config=config) import Util tests += Util.get_tests(config=config) return tests
def joue(ev1, ev2): it = 0 jeu = game.initialiseJeu() while ((it < 100) and (not (game.finJeu(jeu)))): if (it < 4): coup = Random.saisieCoup(game.getCopieJeu(jeu)) game.joueCoup(jeu, coup) else: if (game.getJoueur(jeu) == 1): coup = Alpha_Beta_Train.saisieCoup(jeu, ev1) else: coup = Alpha_Beta_Train.saisieCoup(jeu, ev2) game.joueCoup(jeu, coup) it += 1 return game.getGagnant(jeu)
def __init__(self, data): key = [] for i in range(4): key.append(Random.get_u32()) self.key = key self.data = data self.var_name = Variable.alloc_name('chunk') if (len(data) % 32) != 0: raise NotImplementedError() self.op_types = [] for i in range(64): self.op_types.append(Operators.get_random_op()) self.encrypt_data()
def initializeVelocitiesToTemperature(self, temperature): """Generate random velocities for all atoms from a Boltzmann distribution at the given |temperature|.""" self.configuration() masses = self.masses() if self._atom_properties.has_key('velocity'): del self._atom_properties['velocity'] fixed = self.getParticleBoolean('fixed') np = self.numberOfPoints() velocities = Numeric.zeros((np, 3), Numeric.Float) for i in xrange(np): m = masses[i] if m > 0. and not fixed[i]: velocities[i] = Random.randomVelocity(temperature, m).array self._atom_properties['velocity'] = \ ParticleProperties.ParticleVector(self, velocities) self.adjustVelocitiesToConstraints()
def generate(self): if self.dialog_save_name(): if Manager.dt == 0 and Manager.df == 0: rd.PatientRecord(gen.s_row, rd.PatientRecord.header_list).data_generate(gen.name) MessageWindow().gen_window('Successful', rd.m2) elif Manager.dt == 0 and Manager.df == 1: OMOP_RD(gen.p_row, gen.s_row, gen.m_row, gen.o_row, gen.name) MessageWindow().gen_window('Successful', person.m2) elif Manager.dt == 1 and Manager.df == 0: rb.PatientRecord_RB(gen.s_row, rb.PatientRecord_RB.header_list).data_generate(gen.b, gen.c, gen.d, gen.name) MessageWindow().gen_window('Successful', rb.m2) elif Manager.dt == 1 and Manager.df == 1: OMOP_RB(gen.p_row, gen.s_row, gen.m_row, gen.o_row, gen.name) MessageWindow().gen_window('Successful', person_rb.m2) sys.exit()
def GenerateBiome(self, model): for p in self.poslist: if p not in self.generated: self.generated.append(p) x, z = p high = self.getHight(model, x, z) model.add_block((x, 0, z), "minecraft:bedrock", save=False, immediate=False) for y in range(1, 5): if round(Random.randint(self.seed, (x, y, z)) * 4) == 1: model.add_block((x, y, z), "minecraft:bedrock", save=False, immediate=False) else: model.add_block( (x, y, z), self.getMaterial(x, y, z, high), save=False, immediate=False, ) for y in range(5, high): if not self.hasOre(x, y, z, high): model.add_block( (x, y, z), self.getMaterial(x, y, z, high), save=False, immediate=False, ) else: model.add_block((x, y, z), self.getOre(x, y, z), save=False, immediate=False) struct = self.getStructur((x, y, z), high) if struct and not (x, y, z) in self.structurblocked: struct.past(model, x, high, z)
def findThreshold(data): randomized = Random.shuffle(data) split = math.ceil(len(randomized)/10.0) trainData = randomized.drop(split) testData = randomized.take(split) classifier = LinkClassifer(trainData) scores = [(f.label, classifier.score(f.item)) for f in testData] rankedAnswer = scores.sortBy(f._2).reverse total = 0 correct = 0 totalCorrect = len([x for x in rankedAnswer if x._1]) thresholds = [] for r in rankedAnswer: total += 1 if r._1: correct += 1 recall = correct/totalCorrect precision = correct/total fscore = 2*recall*precision/(recall + precision) thresholds.append((r._2, fscore)) thresholds.sortBy(fscore)
def encrypt(key, filename): chunksize = 64 * 1024 outputFile = "(encrypted)" + filename filesize = str(os.path.getsize(filename)).zfill(16) IV = Random.new().read(16) encryptor = AES.new(key, AES.MODE_CBC, IV) with open(filename, 'rb') as infile: with open(outputFile, 'wb') as outfile: outfile.write(filesize.encode('utf-8')) outfile.write(IV) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += b' ' * (16 - len(chunk) % 16) outfile.write(encryptor.encrypt(chunk))
def __init__(self): self._rnd = Random()
def __init__(self, rate, sigma): self.sigma = sigma self.r0 = rate self.rnd = Random.randMC(False, False)
def get_random_op(): return g_list[Random.get_u32() % len(g_list)]
def randomPoint(self): return Random.randomPointInBox(self.data[0], self.data[1], self.data[2])
while True: """ MOVE START 1 0 7 0 4 2 6 5 5 5 6 7 0 5 7 3 6 1 8 3 3 2 5 8 2 7 1 -1 -1 -1 MOVE END ['6 7 7', '7 2 4', '5 0 6', '5 7 9', '2 3 5', '-1 -1 -1'] """ data = s.recv(1024) #print data data = data.split('\n')[1:-2] #print data boardInfo = [] for strInfo in data: boardInfo += [[int(p) for p in strInfo.split(' ')]] #print boardInfo board = Random(boardInfo) mymove = board.makeMove() print "my choice: ", mymove s.send(msg(mymove)) s.close()
def get_N_random_secrets(num): secrets = [] for i in range(num): SecretGeneratorType = g_list[Random.get_u32() % len(g_list)] secrets.append(SecretGeneratorType()) return secrets
def Rand(self): import Random Random.spawnRand()
class Dice(object): def __init__(self): self._rnd = Random() def roll(self): return self._rnd.nextInt(6) + 1
# # Bubblesort # Time: O(n) best case, O(n2) average and worst-case # Space: O(1) # # Very simple and largely useless algorithm # Works through the list checking pairs of elements, # if left is bigger than right, swap. # The biggest elements 'bubble' to the end of the list # import Random # the list to sort listToSort = Random.createRandomList(20) # swaps the two elements in the passed list def swap(list, index1, index2): index1Val = list[index1] index2Val = list[index2] list[index1] = index2Val list[index2] = index1Val # sort the list def bubblesort(list): while True: swapped = False for index in range(len(list)): if index == 0:
print(f'Connecting...') # Load Environment Variables load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD_NAME = os.getenv('DISCORD_GUILD') # Sets the command prefix to be a / in Discord bot = commands.Bot(command_prefix='/') # Set up all the cogs needed for the bot to run # https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html # bot.add_cog(Greetings.Greetings(bot)) bot.add_cog(Random.Random(bot)) @bot.event async def on_message(message): content = message.content.lower() print(message) print(message.author) if message.author == bot.user: return if 'party' in content and 'politic' not in message.channel.name: author = str(message.author.nick) await message.channel.send( f"Did someone say party? I like to party. Want to get this party started {author}?"
def Djikstra_all(G): """ Run Djikstra on all the vertices """ vertices = G.vertices.keys() v = len(vertices) dist = np.full((v, v), np.inf) closest = np.full((v, v), np.inf) for i in range(v): vertex = vertices[i] vdist = Djikstra(G, vertex) dist[i][i] = 0 for j in range(v): othervertex = vertices[j] if dist[i][j] > vdist[othervertex][0] and vdist[othervertex][ 1] != None: dist[i][j] = vdist[othervertex][0] closest[i][j] = vdist[othervertex][1] return dist, closest if __name__ == "__main__": G = Random.random_skew_graph(10, 0.2) np.set_printoptions(precision=2) print G distfw, closestfw = FloydWarshall(G) distdj, closestdj = Djikstra_all(G) print closestfw == closestdj print closestfw print closestdj
# # Basic Quicksort # Time: O(n log n) O(n2) worst-case # Space: O(n) # # List is split into two at a pivot point half way through the list # Items smaller than the pivot go into one list, larger items in the other # The algorithm is called recursively on the two lists # import Random # the list to sort list = Random.createRandomList(10) sorted = [] # sort the list def quicksort(toSort): if len(toSort) <= 1: return toSort # no need to sort an empty list pivotIndex = len(toSort)/2 pivot = toSort[pivotIndex] toSort.pop(pivotIndex) # partition the list lower = [] higher = [] for i in range(len(toSort)): item = toSort[i] if item <= pivot: lower.append(item) else: higher.append(item)
def main(): #first we start with analyzing the demographic information mean_age, num_male, num_female, mean_edu_level, mean_edu_years, mean_marital, num_disabled, num_not_disabled = demographic_read('Demographic Info Numbers.csv') # print 'Mean age: ', mean_age # print 'Number of males: ', num_male # print 'Number of females: ', num_female # print 'Mean education level: ', mean_edu_level # print 'Mean years of education: ', mean_edu_years # print 'Mean number of spouses: ', mean_marital # print 'Number of disabled persons: ', num_disabled # print 'Number of not disabled persons: ', num_not_disabled #then we analyze the independent variables IV, IV_mean, IV_med, IV_low, IV_high, low_index, high_index = IV_read('IV_final.csv') # pyplot.figure() # pyplot.hist(IV, 20) # pyplot.title('Probability distribution for IV score') # pyplot.show() #Then we analyze the dependent variables CUDIT = cudit_read('CUDIT_final.csv') IDAS = idas_read('IDAS_final.csv') CEQ = ceq_read('CEQ_final.csv') #First we observe the correlation between IV and DV's # pyplot.figure() # pyplot.scatter(IV, CUDIT) # pyplot.title('Scatterplot of CUDIT vs. IV') # pyplot.xlabel('IV Score') # pyplot.ylabel('CUDIT Score') # pyplot.show() # # pyplot.figure() # pyplot.scatter(IV, IDAS) # pyplot.title('Scatterplot of IDAS vs. IV') # pyplot.xlabel('IV Score') # pyplot.ylabel('IDAS Score') # pyplot.show() # # pyplot.figure() # pyplot.scatter(IV, CEQ) # pyplot.title('Scatterplot of CEQ vs. IV') # pyplot.xlabel('IV Score') # pyplot.ylabel('CEQ Score') # pyplot.show() CUDIT_corr = pearsonr(IV,CUDIT) IDAS_corr = pearsonr(IV,IDAS) CEQ_corr = pearsonr(IV,CEQ) print "Correlation between independent variable and CUDIT is: ", CUDIT_corr[0] print "Correlation between independent variable and IDAS is: ", IDAS_corr[0] print "Correlation between independent variable and CEQ is: ", CEQ_corr[0] CUDIT_low = [CUDIT[i] for i in low_index] CUDIT_high = [CUDIT[i] for i in high_index] IDAS_low = [IDAS[i] for i in low_index] IDAS_high = [IDAS[i] for i in high_index] CEQ_low = [CEQ[i] for i in low_index] CEQ_high = [CEQ[i] for i in high_index] test_CUDIT = np.mean(CUDIT_high) - np.mean(CUDIT_low) test_IDAS = np.mean(IDAS_high) - np.mean(IDAS_low) test_CEQ = np.mean(CEQ_high) - np.mean(CEQ_low) # pyplot.figure() # pyplot.hist(CUDIT_low, 20) # pyplot.title('Probability Distribution for CUDIT_low Score') # pyplot.xlabel('CUDIT_low Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(CUDIT_high, 20) # pyplot.title('Probability Distribution for CUDIT_high Score') # pyplot.xlabel('CUDIT_high Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(IDAS_low, 20) # pyplot.title('Probability Distribution for IDAS_low Score') # pyplot.xlabel('IDAS_low Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(IDAS_high, 20) # pyplot.title('Probability Distribution for IDAS_high Score') # pyplot.xlabel('IDAS_high Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(CEQ_low, 20) # pyplot.title('Probability Distribution for CEQ_low Score') # pyplot.xlabel('CEQ_low Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(CEQ_high, 20) # pyplot.title('Probability Distribution for CEQ_high Score') # pyplot.xlabel('CEQ_high Score') # pyplot.ylabel('Frequency') # pyplot.show() #CUDIT data shows skewed right, IDAS shows roughly normal, and CEQ data shows skewed left #We use the log transform for CUDIT, and the square transform for CEQ log_CUDIT_low = np.log(CUDIT_low) log_CUDIT_high = np.log(CUDIT_high) fifth_CEQ_low = np.power(CEQ_low,5) fifth_CEQ_high = np.power(CEQ_high,5) # # pyplot.figure() # pyplot.hist(log_CUDIT_low, 20) # pyplot.title('Probability Distribution for log(CUDIT_low) Score') # pyplot.xlabel('log(CUDIT_low) Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(log_CUDIT_high, 20) # pyplot.title('Probability Distribution for log(CUDIT_high) Score') # pyplot.xlabel('log(CUDIT_high) Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(fifth_CEQ_low, 20) # pyplot.title('Probability Distribution for Transformed CEQ_low Score') # pyplot.xlabel('Transformed CEQ_low Score') # pyplot.ylabel('Frequency') # pyplot.show() # # pyplot.figure() # pyplot.hist(fifth_CEQ_high, 20) # pyplot.title('Probability Distribution for Transformed CEQ_high Score') # pyplot.xlabel('Transformed CEQ_high Score') # pyplot.ylabel('Frequency') # pyplot.show() #Calculating descriptive statistics CUDIT_low_mean = np.mean(CUDIT_low) CUDIT_high_mean = np.mean(CUDIT_high) CUDIT_low_var = np.var(CUDIT_low) CUDIT_high_var = np.var(CUDIT_high) log_CUDIT_low_mean = np.mean(log_CUDIT_low) log_CUDIT_high_mean = np.mean(log_CUDIT_high) log_CUDIT_low_var = np.var(log_CUDIT_low) log_CUDIT_high_var = np.var(log_CUDIT_high) CEQ_low_mean = np.mean(CEQ_low) CEQ_high_mean = np.mean(CEQ_high) CEQ_low_var = np.var(CEQ_low) CEQ_high_var = np.var(CEQ_high) fifth_CEQ_low_mean = np.mean(fifth_CEQ_low) fifth_CEQ_high_mean = np.mean(fifth_CEQ_high) fifth_CEQ_low_var = np.var(fifth_CEQ_low) fifth_CEQ_high_var = np.var(fifth_CEQ_high) IDAS_low_mean = np.mean(IDAS_low) IDAS_high_mean = np.mean(IDAS_high) IDAS_low_var = np.var(IDAS_low) IDAS_high_var = np.var(IDAS_high) print "Mean/Variance for CUDIT_low: ", CUDIT_low_mean, CUDIT_low_var print "Mean/Variance for CUDIT_high: ", CUDIT_high_mean, CUDIT_high_var print "Mean/Variance for log(CUDIT_low): ", log_CUDIT_low_mean, log_CUDIT_low_var print "Mean/Variance for log(CUDIT_high): ", log_CUDIT_high_mean, log_CUDIT_high_var print "Mean/Variance for CEQ_low: ", CEQ_low_mean, CEQ_low_var print "Mean/Variance for CEQ_high: ", CEQ_high_mean, CEQ_high_var print "Mean/Variance for transformed CEQ_low: ", fifth_CEQ_low_mean, fifth_CEQ_low_var print "Mean/Variance for transformed CEQ_high: ", fifth_CEQ_high_mean, fifth_CEQ_high_var print "Mean/Variance for IDAS_low: ", IDAS_low_mean, IDAS_low_var print "Mean/Variance for IDAS_high: ", IDAS_high_mean, IDAS_high_var #Welch's t-test, 2-sided, assumes unequal variance t_CUDIT, p_CUDIT_ttest = ttest_ind(log_CUDIT_low, log_CUDIT_high, equal_var = False) t_IDAS, p_IDAS_ttest = ttest_ind(IDAS_low, IDAS_high, equal_var = False) t_CEQ, p_CEQ_ttest = ttest_ind(fifth_CEQ_low, fifth_CEQ_high, equal_var = False) print "p-value for CUDIT under Welch's t-test is: ", p_CUDIT_ttest / 2 print "p-value for IDAS under Welch's t-test is: ", p_IDAS_ttest / 2 print "p-value for CEQ under Welch's t-test is: ", p_CEQ_ttest / 2 #Mann-Whitney rank test U_CUDIT, p_CUDIT_MWU = mannwhitneyu(CUDIT_low,CUDIT_high,True,'less') U_IDAS, p_IDAS_MWU = mannwhitneyu(IDAS_low,IDAS_high,True,'greater') U_CEQ, p_CEQ_MWU = mannwhitneyu(CEQ_low,CEQ_high,True,'greater') print "p-value for CUDIT under Mann-Whitney U test is: ", p_CUDIT_MWU print "p-value for IDAS under Mann-Whitney U test is: ", p_IDAS_MWU print "p-value for CEQ under Mann-Whitney U test is: ", p_CEQ_MWU #Randomization null_CUDIT, null_IDAS, null_CEQ = Random(IV, CUDIT, IDAS, CEQ) pyplot.figure() pyplot.hist(null_CUDIT,20) pyplot.axvline(test_CUDIT, color = 'r') pyplot.title('Null Distribution For CUDIT With Test Statistic') pyplot.xlabel('Difference In Mean') pyplot.ylabel('Frequency') pyplot.show() pyplot.figure() pyplot.hist(null_IDAS, 20) pyplot.axvline(test_IDAS, color='r') pyplot.title('Null Distribution For IDAS With Test Statistic') pyplot.xlabel('Difference In Mean') pyplot.ylabel('Frequency') pyplot.show() pyplot.figure() pyplot.hist(null_CEQ, 20) pyplot.axvline(test_CEQ, color='r') pyplot.title('Null Distribution For CEQ With Test Statistic') pyplot.xlabel('Difference In Mean') pyplot.ylabel('Frequency') pyplot.show() p_CUDIT_rand = pval(null_CUDIT, test_CUDIT) p_IDAS_rand = 1-pval(null_IDAS, test_IDAS) p_CEQ_rand = 1-pval(null_CEQ, test_CEQ) #Need to adjust in accordance to the different alternative hypothesis print "p-value for CUDIT under randomization is: ", p_CUDIT_rand print "p-value for IDAS under randomization is: ", p_IDAS_rand print "p-value for CEQ under randomization is: ", p_CEQ_rand