blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
97e83e7830a67a8d5b1734c286b23ca7da3e2d82
gioruffa/cognitive_systems_10_10_17
/assignment.py
3,904
3.859375
4
#!/usr/bin/evn python # Assignment 10/10/17 Cognitive Systems # Team members (alphabetical order): # Mauro Comi, Eva Gil San Antonio, # Carlos Lopez Gomez, Giorgio Ruffa, Yirui Wang # import csv def inches_to_meter(x): return x * 0.0254 def pounds_to_kilos(x): return x * 0.453592 #remove white spaces and put lowercase def sanitize_string(x): return x.replace(" ","").lower() #clear the height field, including interpretation of the possible unit of measure #will return either a float expressed in meters or None def sanitize_height(x): sanitized_height = x #maybe the user enterd "1.5m" or "1.6 m" #assume default in meter sanitized_height = sanitized_height.replace('m','') #is it explicitly in inches? #like "100in" is_in_inches = True if 'in' in sanitized_height else False sanitized_height = sanitized_height.replace('in','') #is empty? if len(sanitized_height) == 0: return None #get the number! #we use the exception to consider the encoding invalid try: height = float(sanitized_height) except: return None #check if the range is absurd #easier with inches, we do not need external factors is_in_inches = True if height > 2.5 else is_in_inches #convert if needed height = inches_to_meter(height) if is_in_inches else height return height #clear the weight field, including interpretation of the possible unit of measure #will return either a float expressed in kilograms or None def sanitize_weight(x): sanitized_weight = x #assume default in kg sanitized_weight = sanitized_weight.replace('kg','') #is it explicitly in inces is_in_pounds = True if 'lb' in sanitized_weight else False sanitized_weight = sanitized_weight.replace('lb','') #is empty? if len(sanitized_weight) == 0: return None #get the number! try: weight = float(sanitized_weight) except: return None #check if the range is more complicated because is 0.45 is_in_pounds = True if weight > 180 else is_in_pounds #convert if needed weight = pounds_to_kilos(weight) if is_in_pounds else weight return weight def categorize(age, boundaries): #boundaries = [26, 36, 56, 56, 66, 76] final_category = len(boundaries) #with enumerate the category is goin to range from 0 to (len(boundaries) -1) for category, upper_edge in enumerate(boundaries): if age < upper_edge : final_category = category break return final_category def compute_BMI(weight, height): if weight == None or height == None: return None return weight/(height **2) with open("infile.csv",'r') as infile, open("outfile.csv",'w') as outfile: csvreader = csv.DictReader(infile) fieldnames = ['age','height', 'weight', 'age_class', 'BMI' , 'BMI_category'] csvwriter = csv.DictWriter(outfile, fieldnames) csvwriter.writeheader() #iterate over any line in the infile #every line is a map for line in csvreader: #clean and convert line['height'] = sanitize_height(line['height']) line['weight'] = sanitize_weight(line['weight']) #categorize age age_boundaries = [26, 36, 56, 56, 66, 76] line["age_class"] = categorize(int(line['age']), age_boundaries) #compute BMI line['BMI'] = compute_BMI(line['weight'], line['height']) bmi_boundaries = [18.50001, 25, 30,40] bmi_names= ["thin", "healthy", "overweight", "obese", "high obese"] #assign a name to the BMI category if line['BMI'] is not None : line["BMI_category"] = bmi_names[categorize(line['BMI'], bmi_boundaries)] else: line["BMI_category"] = None #write the new line one by one -> no need to keep the table in memory #using kernel and fs caching csvwriter.writerow(line) #print
c65e4ac440b3067310e4d3d480eb70a3c344b281
wecchi/univesp_com110
/Sem2-Texto26.py
707
4.5
4
''' Conceitos e aplicações – uma abordagem didática (Ler: seções 2.3, 2.4 e 4.1) | Sérgio Luiz Banin Atribuição múltipla de variáveis Atribuição posicional de variáveis identificador da variável id() ''' A = B = C = 34 print('A = B = C = 34 id(A)', id(A) == id(B), id(C)) D, E, F = 500, 600, 700 print('\n', D, E, F) # Usando atribuição incremental de variável print('\n A = ',A) A += 56 print('A += 56 ... ',A) A -= 8 print('A -= 8 ... ',A) A *=152 print('A *=152 ... ',A) A **=3 print('A **=3 ... ',A) A /=6 print('A /=6 ... ',A) A //=3 print('A //=3 ... ',A) A %=5 print('A %=5 ... ',A) from math import sqrt y = 81 print('\n', y, sqrt(y))
6a25708cd34375a160bcc18defc6618e575b4981
Vissureddy2b7/must-do-coding-questions
/trees/15_check_if_bt_is_height_balanced_or_not.py
770
3.734375
4
class Node: def __init__(self, k): self.data = k self.left = None self.right = None def height(root): if root is None: return 0 return 1 + max(height(root.left), height(root.right)) def checkForBalance(root): if root is None: return True return abs(height(root.left) - height(root.left)) <= 1 and checkForBalance(root.left) and checkForBalance(root.right) if __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.left.left.left = Node(7) root.left.left.left.left = Node(8) root.left.left.left.left.left = Node(9) print(checkForBalance(root))
c6010983e1ecc7053c8f285e700d7fc2a0c4b8bd
Pabitra145/Angry-Bird
/maps.py
25,154
3.640625
4
#angry bird pygame by gangster sittu import pygame import sys import physics_engine import objects import interface pygame.init() width = None height = None display = None clock = pygame.time.Clock() ground = 50 d_velocity = 2.0 def init(screen): global width, height, display display = screen (width, height) = display.get_rect().size height -= ground interface.init(display) def all_rest(pigs, birds, blocks): threshold = 0.15 for pig in pigs: if pig.velocity.magnitude >= threshold: return False for bird in birds: if bird.velocity.magnitude >= threshold: return False for block in blocks: if block.velocity.magnitude >= threshold: return False return True def close(): pygame.quit() sys.exit() class Maps: def __init__(self): self.level = 1 self.max_level = 15 self.color = {'background': (51, 51, 51)} self.score = 0 def wait_level(self): time = 0 while time < 3: for event in pygame.event.get(): if event.type == pygame.QUIT: close() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: close() time += 1 clock.tick(1) return def check_win(self, pigs, birds): if pigs == []: print("WON!") return True if (not pigs == []) and birds == []: print("LOST!") return False def pause(self): pause_text = interface.Label(700, 200, 400, 200, None, self.color['background']) pause_text.add_text("GAME PAUSED", 70, "Fonts/Comic_Kings.ttf", (236, 240, 241)) replay = interface.Button(350, 500, 300, 100, self.draw_map, (244, 208, 63), (247, 220, 111)) replay.add_text("RESTART", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) resume = interface.Button(750, 500, 300, 100, None, (88, 214, 141), (171, 235, 198)) resume.add_text("RESUME", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) exit = interface.Button(1150, 500, 300, 100, close, (241, 148, 138), (245, 183, 177)) exit.add_text("QUIT", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) mandav = interface.Label(width - 270, height + ground - 70, 300, 100, None, self.color['background']) mandav.add_text("MANDAV", 60, "Fonts/arfmoochikncheez.ttf", ( 113, 125, 126 )) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: close() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: close() if event.key == pygame.K_p: return if event.key == pygame.K_ESCAPE: return if event.type == pygame.MOUSEBUTTONDOWN: if replay.isActive(): replay.action() if resume.isActive(): return if exit.isActive(): exit.action() replay.draw() resume.draw() exit.draw() pause_text.draw() mandav.draw() pygame.display.update() clock.tick(60) def draw_map(self): birds = [] pigs = [] blocks = [] walls = [] self.score = 0 if self.level == 1: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 40, 20)) pigs.append(physics_engine.Pig(1500, height - 40, 20)) blocks.append(physics_engine.Block(1300, height - 60, 60)) elif self.level == 2: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1000, height - 40, 20)) pigs.append(physics_engine.Pig(1400, height - 40, 20)) blocks.append(physics_engine.Block(1200, height - 60, 60)) blocks.append(physics_engine.Block(1200, height - 2*35, 60)) blocks.append(physics_engine.Block(1500, height - 60, 60)) elif self.level == 3: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1200, height - 60, 30)) pigs.append(physics_engine.Pig(1300, height - 60, 30)) blocks.append(physics_engine.Block(1000, height - 100, 100)) blocks.append(physics_engine.Block(1000, height - 2*60, 100)) blocks.append(physics_engine.Block(1500, height - 100, 100)) blocks.append(physics_engine.Block(1500, height - 2*60, 100)) elif self.level == 4: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1200, 500 - 60, 30)) pigs.append(physics_engine.Pig(1300, height - 60, 30)) walls.append(objects.Slab(1000, 450, 500, 20)) blocks.append(physics_engine.Block(1100, height - 100, 100)) elif self.level == 5: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1300, 500 - 60, 25)) pigs.append(physics_engine.Pig(1300, height - 60, 25)) walls.append(objects.Slab(500, 400, 100, height - 400)) walls.append(objects.Slab(1000, 450, 500, 30)) blocks.append(physics_engine.Block(1150, 500 - 100, 100)) blocks.append(physics_engine.Block(1100, height - 100, 100)) elif self.level == 6: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1300, 500 - 60, 25)) pigs.append(physics_engine.Pig(1300, height - 60, 25)) walls.append(objects.Slab(1000, 0, 30, 450)) walls.append(objects.Slab(1000, 450, 500, 30)) blocks.append(physics_engine.Block(1150, 500 - 100, 100)) blocks.append(physics_engine.Block(1100, height - 100, 100)) elif self.level == 7: for i in range(4): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, 500 - 60, 25)) pigs.append(physics_engine.Pig(1300, 500 - 60, 25)) pigs.append(physics_engine.Pig(1200, height - 60, 25)) walls.append(objects.Slab(1200, 250, 30, 200)) walls.append(objects.Slab(1000, 450, 500, 30)) elif self.level == 8: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 60, 25)) pigs.append(physics_engine.Pig(1200, height - 60, 25)) walls.append(objects.Slab(700, 250, 30, height - 250)) elif self.level == 9: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 60, 25)) pigs.append(physics_engine.Pig(1450, height - 60, 25)) blocks.append(physics_engine.Block(1250, height - 100, 100)) blocks.append(physics_engine.Block(1250, height - 2*60, 100)) walls.append(objects.Slab(700, 400, 30, height - 400)) elif self.level == 10: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 60, 25)) pigs.append(physics_engine.Pig(1450, height - 60, 25)) blocks.append(physics_engine.Block(1250, height - 100, 100)) blocks.append(physics_engine.Block(1250, height - 2*60, 100)) blocks.append(physics_engine.Block(900, height - 100, 100)) walls.append(objects.Slab(900, 400, 500, 30)) elif self.level == 11: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 60, 25)) pigs.append(physics_engine.Pig(1450, height - 60, 25)) blocks.append(physics_engine.Block(1250, height - 100, 100)) blocks.append(physics_engine.Block(1250, height - 2*60, 100)) walls.append(objects.Slab(900, 400, 500, 30)) walls.append(objects.Slab(900, 400, 30, height - 400)) elif self.level == 12: for i in range(3): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 60, 25)) pigs.append(physics_engine.Pig(1450, height - 60, 25)) walls.append(objects.Slab(900, 400, 500, 30)) walls.append(objects.Slab(1200, 500, 30, height - 500)) elif self.level == 13: for i in range(4): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 60, 25)) pigs.append(physics_engine.Pig(1200, 400 - 60, 25)) pigs.append(physics_engine.Pig(1450, height - 60, 25)) blocks.append(physics_engine.Block(900, height - 100, 100)) blocks.append(physics_engine.Block(900, height - 2*60, 100)) walls.append(objects.Slab(900, 400, 500, 40)) walls.append(objects.Slab(1200, 500, 30, height - 500)) elif self.level == 14: for i in range(4): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(1100, height - 60, 25)) pigs.append(physics_engine.Pig(1100, 400 - 60, 25)) pigs.append(physics_engine.Pig(1450, height - 60, 25)) blocks.append(physics_engine.Block(900, height - 100, 100)) blocks.append(physics_engine.Block(1300, 400 - 100, 100)) walls.append(objects.Slab(900, 400, 500, 40)) walls.append(objects.Slab(900, 0, 30, 400)) elif self.level == 15: for i in range(5): new_bird = physics_engine.Bird(40*i + 5*i, height - 40, 20, None, "BIRD") birds.append(new_bird) pigs.append(physics_engine.Pig(900, height - 60, 25)) pigs.append(physics_engine.Pig(width - 400, 400 - 60, 25)) pigs.append(physics_engine.Pig(1700, height - 60, 25)) walls.append(objects.Slab(800, 400, 30, height - 400)) walls.append(objects.Slab(1000, 500, 30, height - 500)) walls.append(objects.Slab(width - 500, 400, 500, 40)) walls.append(objects.Slab(width - 500, 150, 60, 400 - 150)) self.start_level(birds, pigs, blocks, walls) def replay_level(self): self.level -= 1 self.draw_map() def start_again(self): self.level = 1 self.draw_map() def level_cleared(self): self.level += 1 level_cleared_text = interface.Label(700, 100, 400, 200, None, self.color['background']) if self.level <= self.max_level: level_cleared_text.add_text("LEVEL " + str(self.level - 1) + " CLEARED!", 80, "Fonts/Comic_Kings.ttf", (236, 240, 241)) else: level_cleared_text.add_text("ALL LEVEL CLEARED!", 80, "Fonts/Comic_Kings.ttf", (236, 240, 241)) score_text = interface.Label(750, 300, 300, 100, None, self.color['background']) score_text.add_text("SCORE: " + str(self.score), 55, "Fonts/Comic_Kings.ttf", (236, 240, 241)) replay = interface.Button(350, 500, 300, 100, self.replay_level, (244, 208, 63), (247, 220, 111)) replay.add_text("PLAY AGAIN", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) if self.level <= self.max_level: next = interface.Button(750, 500, 300, 100, self.draw_map, (88, 214, 141), (171, 235, 198)) next.add_text("CONTINUE", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) else: next = interface.Button(750, 500, 300, 100, self.start_again, (88, 214, 141), (171, 235, 198)) next.add_text("START AGAIN", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) exit = interface.Button(1150, 500, 300, 100, close, (241, 148, 138), (245, 183, 177)) exit.add_text("QUIT", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) mandav = interface.Label(width - 270, height + ground - 70, 300, 100, None, self.color['background']) mandav.add_text("MANDAV", 60, "Fonts/arfmoochikncheez.ttf", ( 113, 125, 126 )) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: close() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: close() if event.type == pygame.MOUSEBUTTONDOWN: if replay.isActive(): replay.action() if next.isActive(): next.action() if exit.isActive(): exit.action() replay.draw() next.draw() exit.draw() level_cleared_text.draw() score_text.draw() mandav.draw() pygame.display.update() clock.tick(60) def level_failed(self): level_failed_text = interface.Label(700, 100, 400, 200, None, self.color['background']) level_failed_text.add_text("LEVEL FAILED!", 80, "Fonts/Comic_Kings.ttf", (236, 240, 241)) score_text = interface.Label(750, 300, 300, 100, None, self.color['background']) score_text.add_text("SCORE: " + str(self.score), 55, "Fonts/Comic_Kings.ttf", (236, 240, 241)) replay = interface.Button(500, 500, 300, 100, self.draw_map, (244, 208, 63), (247, 220, 111)) replay.add_text("TRY AGAIN", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) exit = interface.Button(1000, 500, 300, 100, close, (241, 148, 138), (245, 183, 177)) exit.add_text("QUIT", 60, "Fonts/arfmoochikncheez.ttf", self.color['background']) mandav = interface.Label(width - 270, height + ground - 70, 300, 100, None, self.color['background']) mandav.add_text("MANDAV", 60, "Fonts/arfmoochikncheez.ttf", ( 113, 125, 126 )) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: close() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: close() if event.type == pygame.MOUSEBUTTONDOWN: if replay.isActive(): replay.action() if exit.isActive(): exit.action() replay.draw() exit.draw() level_failed_text.draw() score_text.draw() mandav.draw() pygame.display.update() clock.tick(60) def start_level(self, birds, pigs, blocks, walls): loop = True slingshot = physics_engine.Slingshot(200, height - 200, 30, 200) birds[0].load(slingshot) mouse_click = False flag = 1 pigs_to_remove = [] blocks_to_remove = [] score_text = interface.Label(50, 10, 100, 50, None, self.color['background']) score_text.add_text("SCORE: " + str(self.score), 25, "Fonts/Comic_Kings.ttf", (236, 240, 241)) birds_remaining = interface.Label(120, 50, 100, 50, None, self.color['background']) birds_remaining.add_text("BIRDS REMAINING: " + str(len(birds)), 25, "Fonts/Comic_Kings.ttf", (236, 240, 241)) pigs_remaining = interface.Label(110, 90, 100, 50, None, self.color['background']) pigs_remaining.add_text("PIGS REMAINING: " + str(len(pigs)), 25, "Fonts/Comic_Kings.ttf", (236, 240, 241)) mandav = interface.Label(width - 270, height + ground - 70, 300, 100, None, self.color['background']) mandav.add_text("MANDAV", 60, "Fonts/arfmoochikncheez.ttf", ( 113, 125, 126 )) while loop: for event in pygame.event.get(): if event.type == pygame.QUIT: close() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: close() if event.key == pygame.K_r: self.draw_map() if event.key == pygame.K_p: self.pause() if event.key == pygame.K_ESCAPE: self.pause() if event.type == pygame.MOUSEBUTTONDOWN: if birds[0].mouse_selected(): mouse_click = True if event.type == pygame.MOUSEBUTTONUP: mouse_click = False if birds[0].mouse_selected(): flag = 0 if (not birds[0].loaded) and all_rest(pigs, birds, blocks): print("LOADED!") birds.pop(0) if self.check_win(pigs, birds) == 1: self.score += len(birds)*100 self.level_cleared() elif self.check_win(pigs,birds) == 0: self.level_failed() if not birds == []: birds[0].load(slingshot) flag = 1 if mouse_click: birds[0].reposition(slingshot, mouse_click) if not flag: birds[0].unload() #display.fill(self.color['background']) color = self.color['background'] for i in range(3): color = (color[0] + 5, color[1] + 5, color[2] + 5) pygame.draw.rect(display, color, (0, i*300, width, 300)) pygame.draw.rect(display, (77, 86, 86), (0, height, width, 50)) slingshot.draw(birds[0]) for i in range(len(pigs)): for j in range(len(blocks)): pig_v, block_v = pigs[i].velocity.magnitude, blocks[j].velocity.magnitude pigs[i], blocks[j], result_block_pig = physics_engine.collision_handler(pigs[i], blocks[j], "BALL_N_BLOCK") pig_v1, block_v1 = pigs[i].velocity.magnitude, blocks[j].velocity.magnitude if result_block_pig: if abs(pig_v - pig_v1) > d_velocity: blocks_to_remove.append(blocks[j]) blocks[j].destroy() if abs(block_v - block_v1) > d_velocity: pigs_to_remove.append(pigs[i]) pigs[i].dead() for i in range(len(birds)): if not (birds[i].loaded or birds[i].velocity.magnitude == 0): for j in range(len(blocks)): birds_v, block_v = birds[i].velocity.magnitude, blocks[j].velocity.magnitude birds[i], blocks[j], result_bird_block = physics_engine.collision_handler(birds[i], blocks[j], "BALL_N_BLOCK") birds_v1, block_v1 = birds[i].velocity.magnitude, blocks[j].velocity.magnitude if result_bird_block: if abs(birds_v - birds_v1) > d_velocity: if not blocks[j] in blocks_to_remove: blocks_to_remove.append(blocks[j]) blocks[j].destroy() for i in range(len(pigs)): pigs[i].move() for j in range(i+1, len(pigs)): pig1_v, pig2_v = pigs[i].velocity.magnitude, pigs[j].velocity.magnitude pigs[i], pigs[j], result = physics_engine.collision_handler(pigs[i], pigs[j], "BALL") pig1_v1, pig2_v1 = pigs[i].velocity.magnitude, pigs[j].velocity.magnitude result = True if result: if abs(pig1_v - pig1_v1) > d_velocity: if not pigs[j] in pigs_to_remove: pigs_to_remove.append(pigs[j]) pigs[j].dead() if abs(pig2_v - pig2_v1) > d_velocity: if not pigs[i] in pigs_to_remove: pigs_to_remove.append(pigs[i]) pigs[i].dead() for wall in walls: pigs[i] = wall.collision_manager(pigs[i]) pigs[i].draw() for i in range(len(birds)): if (not birds[i].loaded) and birds[i].velocity.magnitude: birds[0].move() for j in range(len(pigs)): bird_v, pig_v = birds[i].velocity.magnitude, pigs[j].velocity.magnitude birds[i], pigs[j], result_bird_pig = physics_engine.collision_handler(birds[i], pigs[j], "BALL") bird_v1, pig_v1 = birds[i].velocity.magnitude, pigs[j].velocity.magnitude result = True if result_bird_pig: if abs(bird_v - bird_v1) > d_velocity: if not pigs[j] in pigs_to_remove: pigs_to_remove.append(pigs[j]) pigs[j].dead() if birds[i].loaded: birds[i].project_path() for wall in walls: birds[i] = wall.collision_manager(birds[i]) birds[i].draw() for i in range(len(blocks)): for j in range(i + 1, len(blocks)): block1_v, block2_v = blocks[i].velocity.magnitude, blocks[j].velocity.magnitude blocks[i], blocks[j], result_block = physics_engine.block_collision_handler(blocks[i], blocks[j]) block1_v1, block2_v1 = blocks[i].velocity.magnitude, blocks[j].velocity.magnitude if result_block: if abs(block1_v - block1_v1) > d_velocity: if not blocks[j] in blocks_to_remove: blocks_to_remove.append(blocks[j]) blocks[j].destroy() if abs(block2_v - block2_v1) > d_velocity: if not blocks[i] in blocks_to_remove: blocks_to_remove.append(blocks[i]) blocks[i].destroy() blocks[i].move() for wall in walls: blocks[i] = wall.collision_manager(blocks[i], "BLOCK") blocks[i].draw() for wall in walls: wall.draw() score_text.add_text("SCORE: " + str(self.score), 25, "Fonts/Comic_Kings.ttf", (236, 240, 241)) score_text.draw() birds_remaining.add_text("BIRDS REMAINING: " + str(len(birds)), 25, "Fonts/Comic_Kings.ttf", (236, 240, 241)) birds_remaining.draw() pigs_remaining.add_text("PIGS REMAINING: " + str(len(pigs)), 25, "Fonts/Comic_Kings.ttf", (236, 240, 241)) pigs_remaining.draw() mandav.draw() pygame.display.update() if all_rest(pigs, birds, blocks): for pig in pigs_to_remove: if pig in pigs: pigs.remove(pig) self.score += 100 for block in blocks_to_remove: if block in blocks: blocks.remove(block) self.score += 50 pigs_to_remove = [] blocks_to_remove = [] clock.tick(60)
d2b2a942b4045db8990eac476d793f33ace4733f
amitfld/amitpro1
/if_targilim/tar6.py
253
4
4
num1 = int(input('enter number: ')) #מקבל שני מספרים ובודק אם סכומם 10. מדפיס הודעות בהתאם num2 = int(input('enter number: ')) if num1+num2 == 10: print('num1 + num2 = 10') else:print('num1 + num2 != 10')
93873c5fd5fc7af936061b7beed14a344e2e4a2c
wangyendt/LeetCode
/Hard/10. Regular Expression Matching/try.py
3,446
3.515625
4
# encoding: utf-8 class Solution: def check(self, s1, s2): return sum(map(lambda ch: s1.count(ch), s2)) def isMatch(self, s: str, p: str) -> bool: if len(p) > 1 and len(s) > 1: if p[0] == '.' and p[1] != '*': s, p = s[1:], p[1:] return self.recursive(s, p) def recursive(self, s, p): print(s, p) if '.*' in p and self.check('*', p) >= len(p) / 2: return True if (not '.' in p) and (not '*' in p) and p != s: return False if len(p) == 2: if p == '.*': return True if s == p: return True if not s and p: if len(p) == 2: if p[1] == '*': return True else: if all([t == '*' for t in p[1::2]]) and len(p) % 2 == 0: return True return False if (not s and p) or (not p and s): return False if not (p or s): return True if s[-1] == p[-1]: return self.recursive(s[:-1], p[:-1]) else: if p[-1] != '.' and p[-1] != '*': return False elif p[-1] == '.': return self.recursive(s[:-1], p[:-1]) else: # p[-1] == '*' if len(p) == 1: return False else: if p[-2] == '.': ind = 0 while ind < len(s): ret = self.recursive(s[:len(s) - ind], p[:-2]) if ret: return ret ind += 1 return False else: if p[-2] != s[-1]: return self.recursive(s, p[:-2]) ind = 0 while ind < len(s): if ind >= 1 and s[len(s) - 1 - ind] != s[len(s) - 1 - ind + 1]: break if p[-2] == s[len(s) - 1 - ind]: ret1 = self.recursive(s[:len(s) - ind], p[:-1]) ret2 = self.recursive(s[:len(s) - ind], p[:-2]) if ret1 or ret2: return True ind += 1 return False if __name__ == '__main__': so = Solution() # print(so.isMatch('aa','a')) # print(so.isMatch('aa','a*')) # print(so.isMatch('ab','.*')) # print(so.isMatch('aab','c*a*b')) # print(so.isMatch('mississippi', 'mis*is*p*.')) # print(so.isMatch('aaa', 'ab*ac*a')) # print(so.isMatch('mississippi', 'mis*is*p*.')) # print(so.isMatch('mississippi', 'mis*is*ip*.')) # print(so.isMatch('aa', 'a*')) # print(so.isMatch('aaa', 'ab*a')) # print(so.isMatch('aaa', 'ab*ac*a')) # print(so.isMatch('aasdfasdfasdfasdfas', 'aasdf.*asdf.*asdf.*asdf.*s')) # print(so.isMatch('bbbba', '.*a*a')) # print(so.isMatch('a', 'ab*a')) # print(so.isMatch('a', '.*..')) # print(so.isMatch("baabbbaccbccacacc", "c*..b*a*a.*a..*c")) # print(so.isMatch("cbbbaccbcacbcca", "b*.*b*a*.a*b*.a*")) print(so.isMatch('aababcacabccbacaaba', 'ab*c*c*b..*a*c*a*b*')) # print(so.isMatch("ccacbcbcccabbab",".c*a*aa*b*.*b*.*"))
1282f76557dff2e54a93626c8fea60577a495337
zdexter/TwitterWordcount
/TwitterWordcount.py
4,134
3.53125
4
# Twitter Wordcount library. __author__ = 'Zach Dexter' import urllib import urllib2 import json import re import sys class WordCounter: def __init__(self,words): self._words = words def _addToDict(self, item, myDict): """ Append a word to the dictionary passed in (if seen for the first time) or increases the counter for that word (if already seen). """ if item in myDict: myDict[item] = myDict[item] + 1 else: myDict[item] = 1 def add_words(self, data): """ Get a list of all 'words,' defined for our purposes to be any strings of alphanumeric characters. """ for s in re.findall(r'\w+', data): self._addToDict(s, self._words) return self._words class TweetGetter: """ Class for printing a list of the most frequently-used words in someone's tweets. Usage: t = TweetGetter('MyTwitterUsername') t.wordsByFrequency() """ _resourceURL = "http://api.twitter.com/1/statuses/user_timeline.format" def __init__(self, username, limit=1000): self._username = username self._limit = limit self._tweets = [] # See how many tweets the user has, so we don't try to retrieve more than that later on. values = { 'screen_name': self._username, } data = urllib.urlencode(values) try: response = urllib2.urlopen("http://api.twitter.com/1/users/show.json?"+data) except urllib2.HTTPError as e: sys.stderr.write('Invalid API request. The screen name you entered may not exist.\n') sys.exit() json_response = json.loads(response.read()) self._num_tweets = json_response['statuses_count'] def _getTweets(self,last_tweet_id): """ Append the user's last tweets to our internal list of tweets, up to the maximum number allowed by twitter, descending, starting at tweet with id /last_tweet_id/. Returns number of tweets actually grabbed, as well as the ID of the last tweet grabbed, so that callers know where to start at next time. """ values = { 'screen_name': self._username, 'count': 200, 'include_rts': 1, } if last_tweet_id > 0: values['max_id'] = last_tweet_id data = urllib.urlencode(values) response = urllib2.urlopen("http://api.twitter.com/1/statuses/user_timeline.json?"+data) json_response = json.loads(response.read()) for tweet in json_response: self._tweets.append(tweet['text']) last_tweet_id = json_response[-1]['id_str'] return len(json_response), last_tweet_id def _getTweetsToLimit(self): """ Call _getTweets to fetch the user's last /_limit/ tweets, account for Twitter's per-request limit with a loop. Returns our internal list of tweets. """ currentCount = len(self._tweets) num_tweets_added = 0 last_tweet_id = 0 while (currentCount < self._num_tweets) and (currentCount < self._limit): num_tweets_added, last_tweet_id = self._getTweets(last_tweet_id) currentCount += num_tweets_added return self._tweets def _uniqueWordsInStatuses(self): """ Returns a dictionary of every: {unique word in the user's last /_limit/ statuses, # of occurences of that word}. """ data = self._getTweetsToLimit() data = ' '.join(data) # Make list of tweets into a string words = {} word_counter = WordCounter(words) word_counter.add_words(data) return words def wordsByFrequency(self): """ Print a list of words used in the user's last /_limit/ statuses, sorted by frequency descending. """ unsorted_word_dict = self._uniqueWordsInStatuses() for k, v in sorted(unsorted_word_dict.iteritems(), key=lambda (k,v): (v,k),reverse=True): print k
70b487d593d31e07a3f860428e5e8549afa78083
abhr1994/Python-Challenges
/Python3_Programs/Bike_Racing.py
2,602
3.890625
4
# -*- coding: utf-8 -*- ''' A Bike race is to be organized. There will be N bikers. You are given initial Speed of the ith Biker by Hi and the Acceleration of ith biker as Ai KiloMeters per Hour. The organizers want the safety of the bikers and the viewers.They monitor the Total Speed on the racing track after every Hour. A biker whose Speed is 'L' or more, is considered a Fast Biker. To Calculate the Total speed on the track- They Add the speed of each Fast biker ,at that Hour. As soon as The total speed on the track is 'M' KiloMeters per Hour or more, The safety Alarm buzzes. You need to tell what is the minimum number of Hours after which the safety alarm will buzz. Input: The first Line contains T- denoting the number of test cases. The first line of each test case contains three space-separated integers N, M and L denoting the number of bikers and speed limit of the track respectively, and A fast Biker's Minimum Speed. Each of next N lines contains two space-separated integers denoting Hi and Ai respectively. Output: For each test case-Output a single integer denoting the minimum number of Hours after which alarm buzzes. Constraints: 1<=T<=100 1<=N<=1e5 1 ≤ M,L ≤ 1e10 1 ≤ Hi, Ai ≤ 1e9 Explanation: Sample Input: 1 3 400 120 20 20 50 70 20 90 Sample Output: 3 Explanation: Speeds of all the Bikers at ith Minute Biker1= 20 40 60 80 100 120 Biker2= 50 120 190 260 330 Biker3= 20 110 200 290 380 Total Initial speeds = 0 (Because none of the biker's speed is fast enough) total Speed at 1st Hour= 120 total Speed at 2nd Hour= 190+200=390 total Speed at 3rd Hour= 260+290=550 Alarm will buzz at 3rd Hour. ''' #code import math def f(u_a,t): v = u_a[0] + u_a[1]*t return v for _ in range(int(input())): N_M_L = list(map(int,input().split())) threshold = N_M_L[-1] i_a = [] t = [] for i in range(N_M_L[0]): i_a.append(list(map(int,input().split()))) t.append(math.ceil((threshold - i_a[-1][0])/i_a[-1][1])) start_time = min(t) print(t) while True: stack = [] if start_time >= max(t): print('here') print(math.ceil((N_M_L[1]-sum([i[0] for i in i_a]))/sum([i[1] for i in i_a]))) break else: for i in range(N_M_L[0]): if start_time >= t[i]: stack.append(f(i_a[i],start_time)) #operation if sum(stack) >= N_M_L[1]: print(start_time) break start_time+=1
930ff1030c723e77e2a65b0cf0993a9f52dc7dc9
tainenko/Leetcode2019
/python/29.divide-two-integers.py
1,808
3.90625
4
''' [29] Divide Two Integers https://leetcode.com/problems/divide-two-integers/description/ * algorithms * Medium (16.15%) * Source Code: 29.divide-two-integers.py * Total Accepted: 200.1K * Total Submissions: 1.2M * Testcase Example: '10\n3' Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero. Example 1: Input: dividend = 10, divisor = 3 Output: 3 Example 2: Input: dividend = 7, divisor = -3 Output: -2 Note: Both dividend and divisor will be 32-bit signed integers. The divisor will never be 0. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows. ''' class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ MAX_INT = 2147483647 if dividend==0: return 0 if dividend ==MAX_INT and divisor==(-1): return MAX_INT if (dividend>0 and divisor<0) or (dividend<0 and divisor>0): sign=-1 else: sign=1 dividend = abs(dividend) divisor=abs(divisor) res=0 while dividend>=divisor: shift=0 tmp=divisor while dividend>=tmp: dividend-=tmp res+=1<<shift shift += 1 tmp <<= 1 res*=sign if res>MAX_INT: return MAX_INT return res
84531e859a231c1e9086bd34fb295666097a2878
Bobrsson/SkillFactory
/practice_C1/python_practice/rectangle_2.py
738
3.875
4
from practice_C1.Restangle import Rectangle, Square, Circle #далее создаем два прямоугольника rect_1 = Rectangle(3,4) rect_2 = Rectangle(12,5) #вывод площади наших двух прямоугольников print(rect_1.get_area()) print(rect_2.get_area()) square_1 = Square(5) square_2 = Square(10) circle1 = Circle(3) circle2 = Circle(6) print(square_1.get_area_square(), square_2.get_area_square()) figures = [rect_1, rect_2, square_1, square_2, circle1, circle2] for figure in figures: if isinstance (figure, Square): print(figure.get_area_square()) elif isinstance (figure, Circle): print(figure.get_area_circle()) else: print(figure.get_area())
7eb99e530aaf24325a4c77798c3997be44c13543
Fabaladibbasey/MITX_6.00.1
/isIn_recursively
835
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 16 19:57:26 2021 @author: suspect-0 """ def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' # Your code here if aStr == "": return False right = len(aStr) left = 0 middle = (right + left) // 2 print(aStr[middle]) if len(aStr) <= 1: return aStr[middle] == char elif aStr[middle] == char: return True else: if aStr[middle] < char: # right half return isIn(char, aStr[middle + 1:]) else: #left half return isIn(char, aStr[:middle]) string = 'abcdefghiw' print( isIn('n', 'cfffijkknnopqsstuuvw')) # print(isIn('d', string))
2e7acd87f386ba21499140a20c32f881c36583df
RiyaChhadva-2411/python-basic-codes
/tuple1.py
1,442
3.578125
4
#problem 1 on tuples #This is called the packing of the tuple #practice=('y','h','z','x') #print(practice) #problem 2 on tuples lst_tups=[('Artjcuno','Moltres','Zaptos'),('Beedrill','Metapod','Charizard','Venasaur','Squirtle'),('Oddish','Ploiwag','Diglett','Bellsprout'),('Pontya','Farfetch','Tauros','Dragonite'),('Hoothoot','Chikorita','Lanturn','Flaaffy','Unown','Teddiursa','Phanpy'),('Loudred','Volbeat','Wailord','Seviper','Sealeo')] t_check=list() for i in lst_tups: t_check.append(i[2]) print(t_check) print("#####################################################################") #problem 3 on tuples tups=[('a','b','c'),(8,7,6,5),('blue','green','yellow','orange','red'),(5.6,9.99,2.5,8.2),('squirrel','chipmunk')] seconds=list() for i in tups: print(i) for i in tups: seconds.append(i[1]) print("List of tuples containing only the second element:\n",seconds) #problem 4 on tuples: With only one line of code, assign four variables, v1, v2, v3, and v4, to the following four values: 1, 2, 3, 4.
 (v1,v2,v3,v4)=(1,2,3,4) print(v1,v2,v3,v4) print("###########################################") #problem 5 on tuples:With only one line of code, assign the variables water, fire, electric, and grass to the values “Squirtle”, “Charmander”, “Pikachu”, and “Bulbasaur”
 (water,fire,electric,grass)=('Squirtle','Charmander','Pikachu','Bulbasaur') print(water) print(fire) print(electric) print(grass)
3c0c83f6815358e853c8a01c1cbe2c5659870969
SenthilKumar009/100DaysOfCode-DataScience
/Python/Concepts/returnfun.py
1,845
3.703125
4
''' def greet(lang): if(lang == 'es'): return('Holo') elif(lang == 'fr'): return('Bonjur') else: return('Hello') print(greet('en'), 'Maxwell') print(greet('es'), 'Steffy') print(greet('fr'), 'Senthil') list = ['a', 'b', 'c', 'd', 'e'] def list(lst): del lst[3] lst[3] = 'x' print(list(list)) def fun(x): x += 1 return x x = 2 x = fun(x+1) print(x) tup = (1,2,3,4) tup[1] = tup[1] + tup [0] #tup = tup[0] print(tup) def fun(x): global y y = x * x return y fun(2) print(y) dct = {} dct['1'] = (1,2) dct['2'] = (2,1) for x in dct.keys(): print(dct[x][1], end='') def fun(x): if x % 2 == 0: return 1 else: return 2 print(fun(fun(2))) x = float(input()) y = float(input()) print(y ** (1/x)) print(1//5 + 1/5) lst = [[x for x in range(3)] for y in range(3)] for r in range(3): for c in range(3): print(lst[r][c]) if lst[r][c] % 2 != 0: print('#') lst = [1,2] for v in range(2): lst.insert(-1, lst[v]) print(lst) def fun(inp=2, out=2): return inp * out print(fun(out=2)) x = 1 y = 2 x,y,z = x,x,y z,y,z = x,y,z print(x,y,z) i = 0 while i < i + 2: i += 1 print('*') else: print('*') a = 1 b = 0 a = a^b b = a^b c = a^b print(a,b) def fun1(a): return None def fun2(a): return fun1(a) * fun1(a) #print(fun2(2)) print(1//2) nums = [1,2,3] vals = nums del vals[:] print(nums) print(vals) lst = [i for i in range(-1,-2)] print(lst) dd = {'1':'0', '0':'1'} for x in dd.values(): print(x, end='') def func(a,b=0): return a**b print(func(b=2)) lst = [x*x for x in range(5)] def fun(lst): del lst[lst[2]] return lst print(fun(lst)) tup = (1,2,4,8) tup[1] = tup[1] + tup[0] #print(tup) #tup = tup[-1] print(tup) ''' #print(float("1, 3")) print(len('\''))
1774f670dad1304662c5d106ae25c5c59d3eaadc
shrayasr/leprechaun
/leprechaun/leprechaun.py
3,638
3.59375
4
#!/usr/bin/env python3 import argparse import glob import hashlib import os import sys from .generator import wordlist_generator from .rainbow import create_rainbow_table def main(): """Main function.""" # Create the command line arguments. parser = argparse.ArgumentParser(prog="leprechaun") group_wordlist = parser.add_argument_group("wordlist arguments") group_wordlist.add_argument("wordlist", type=str, help="The file name of the wordlist to hash") group_wordlist.add_argument("-f", "--wordlist-folder", action="store_true", help="Hash all of the plaintext files in a folder, rather than a single\ file. The name of the folder will be given by the WORDLIST argument") group_wordlist.add_argument("-g", "--generate-wordlist", action="store_true", help="Generate a wordlist dynamically instead of using a prebuilt one") group_wordlist.add_argument("-l", "--word-length", type=int, default=8, help="Maximum word length for generated wordlist") group_output = parser.add_argument_group("output arguments") group_output.add_argument("-o", "--output", default="rainbow", help="The name of the output file (default=rainbow)") group_output.add_argument("-d", "--use-database", action="store_true", help="Rainbow table will be an sqlite database, not a plaintext file") group_hashing = parser.add_argument_group("hashing arguments") group_hashing.add_argument("-m", "--md5", action="store_true", help="Generate MD5 hashes of given passwords (default)") group_hashing.add_argument("-s", "--sha1", action="store_true", help="Generate SHA1 hashes of given passwords") group_hashing.add_argument("-s2", "--sha256", action="store_true", help="Generate SHA256 hashes of given passwords") group_hashing.add_argument("-s5", "--sha512", action="store_true", help="Generate SHA512 hashes of given passwords") # Parse the command line arguments. args = parser.parse_args() # Generate a wordlist for the user if they request one. if args.generate_wordlist: wordlist_generator("wordlist.txt", args.word_length) # We just want to generate a wordlist, so exit the program when that's done. # Maybe in the future we'll hash the wordlist, but for now I don't really # want to. sys.exit(0) # Figure out the user's choice in hashing algorithms and create the # appropriate hashlib object for the job. if args.sha1: hashing_algorithm = hashlib.sha1() elif args.sha256: hashing_algorithm = hashlib.sha256() elif args.sha512: hashing_algorithm = hashlib.sha512() else: hashing_algorithm = hashlib.md5() # Because this program is intended to be distributed, we need to update the # paths for both the included wordlists and the outputted rainbow table. output = os.getcwd() + "/" + args.output if args.wordlist_folder: # If the user wants to use a bunch of wordlists within a folder, gather a # list of the names of the files. for wordlist in sorted(glob.glob(os.path.abspath(args.wordlist) + "/*.txt")): if args.use_database: # Save the rainbow table as an SQLite DB. create_rainbow_table(wordlist, hashing_algorithm, output, use_database=True) else: # Save the rainbow table as a plaintext file. create_rainbow_table(wordlist, hashing_algorithm, output) else: # The user will only be using one wordlist file. if args.use_database: create_rainbow_table(args.wordlist, hashing_algorithm, output, use_database=True) else: create_rainbow_table(args.wordlist, hashing_algorithm, output) if __name__ == "__main__": main()
939cc17db37e326794ad074605576019fb89719a
gsnaider/modelos-y-optimizacion-i
/tp-heuristica/heuristica/mejoramiento/k_opt.py
1,855
3.75
4
''' Created on Jun 21, 2016 @author: gaston ''' from heuristica.construccion.nearest_neighbor import * def calculate_distance(route): distance = 0 idx = 1 for bank in route[1:]: previous_bank = route[idx - 1] dist_from_previous_bank = DISTANCES[previous_bank][bank] distance += dist_from_previous_bank idx += 1 return distance def swap(route, i, j): if(i < j): min = i max = j else: min = j max = i new_route = [] new_route.extend(route[:min]) new_route.extend(list(reversed(route[min:max+1]))) new_route.extend(route[max+1:]) return new_route def is_route_possible(route): money = 0 for bank in route: movement = MOVEMENTS[bank] money += movement if ((money < 0) or (money >= MAX_MONEY)): return False return True def k_opt(route): done = False distance = calculate_distance(route) while not done: i = 1 change = False while (i <= N - 1) and not change: j = i + 1 while (j <= N) and not change: new_route = swap(route, i, j) new_distance = calculate_distance(new_route) if ((is_route_possible(new_route)) and (new_distance < distance)): change = True distance = new_distance route = new_route print "Intercambiando",BANKS[route[j]],"y",BANKS[route[i]] print "Nueva distancia: ", new_distance print "" j += 1 i += 1 if(i == N): print "No hay mas intercambios posibles." print "" done = True return route
1aa0267561beb4baef9ff1e40355e02471f2c327
Zorro30/Udemy-Complete_Python_Masterclass
/Data Analysis/Broadcasting.py
495
3.90625
4
#Broadcasting refers to the ability of numpy to treat arrays of different shapes doing arithmetic operations. import numpy as np #multiplication when two arrays have same dimension a = np.array([1,2,3,4]) b = np.array([10,20,30,40]) c = a*b print (c) #Broadcasting comes into picture when dimensions of two arrays are different a = np.array ([[1,2,3],[4,5,6],[7,8,9]]) b = np.array ([1,2,3]) #broadcasting expands the smaller array, hence here b becomes [1,2,3],[1,2,3],[1,2,3] print (a+b)
b83e53c9ca4f61d285c1c6f31cab871dee24f439
SAM1363/TH-Python
/List/itrate.py
557
3.90625
4
all_restaurants = [ "Taco City", "Burgertown", "Tacovilla", "Hotdog station", "House of tacos", ] def tacos_only(restaurants): taco_joints = restaurants.copy() for taco_joint in taco_joints.copy(): if "taco" not in taco_joint.lower(): taco_joints.remove(taco_joint) return taco_joints print(tacos_only(all_restaurants)) print(all_restaurants) # 'taco' というキーワードがあるものだけプリントしたい for each in all_restaurants: if each == 'taco'.lower(): print(each)
1fa0fbb741597648a40b041ed482bc8e5db8c1ea
kyleniemeyer/ecabc
/examples/test_abc.py
2,430
4.5
4
''' Simple sample script to demonstrate how to use the artificial bee colony, this script is a simple example, which is just used to demonstrate how the program works. If an ideal day is 70 degrees, with 37.5% humidity. The fitness functions takes four values and tests how 'ideal' they are. The first two values input will be added to see how hot the day is, and the second two values will be multiplied to see how much humidity there is. The resulting values will be compared to 70 degrees, and 37.5% humidity to determine how ideal the day those values produce is. The goal is to have the first two values added up to as close to 70 as possible, while the second two values multiply out to as close to 37.5 as possible. ''' from ecabc.abc import * import os import time def idealDayTest(values, args=None): # Fitness function that will be passed to the abc temperature = values[0] + values[1] # Calcuate the day's temperature humidity = values[2] * values[3] # Calculate the day's humidity cost_temperature = abs(70 - temperature) # Check how close the daily temperature to 70 cost_humidity = abs(37.5 - humidity) # Check how close the humidity is to 37.5 if args: print(args) time.sleep(1) print(cost_temperature + cost_humidity) return cost_temperature + cost_humidity # This will be the cost of your fitness function generated by the values if __name__ == '__main__': # First value # Second Value # Third Value # Fourth Value values = [('int', (0,100)), ('int', (0,100)), ('float',(0,100)), ('float', (0, 100))] start = time.time() abc = ABC(fitness_fxn=idealDayTest, value_ranges=values ) abc.create_employers() while True: abc.save_settings('{}/settings.json'.format(os.getcwd())) abc._employer_phase() abc._calc_probability() abc._onlooker_phase() abc._check_positions() abc._cycle_number = abc._cycle_number + 1 if (abc.best_performer[0] < 2): break if (abc._cycle_number == 10): break idealDayTest(abc.best_performer[1], abc.best_performer[1]) print(abc.best_performer[0]) print(str(abc.best_performer[1][0] + abc.best_performer[1][1]) + ", " + str(abc.best_performer[1][2] * abc.best_performer[1][3])) print("execution time = {}".format(time.time() - start))
c38a7697c46f6ed2ce865619cc33a204d5749465
howinator/CS303E
/2-15.py
187
4.03125
4
import math def main(): side = eval(input("Please enter the length of the side: ")) area = 3 / 2 * math.sqrt(3) * side ** 2 print("The area of the hexagon is", area) main()
849c1a233cc014ef2c374f204e34f2ee436f5989
SreeshaKS/ds_algorithms
/DS_Algo_Python/clim_stairs.py
285
3.546875
4
class Solution: def climbStairs(self, n: int) -> int: map = {0:0, 1:1, 2:2 } for i in range(n+1): if i > 2: map[i] = 0 for i in range(n+1): if i > 2: map[i] = map[i-1] + map[i-2] return map[n]
0a427e257c79dabe8ead41c507391aee105a46c1
devMEremenko/Coding-Challenges
/Python/LeetCode/20. Valid Parentheses.py
1,240
3.515625
4
# https://leetcode.com/problems/valid-parentheses/ class Solution: # ---- In-place Solution def isMatch(self, s1: str, s2: str) -> bool: if s1 == "(" and s2 == ")": return True if s1 == "[" and s2 == "]": return True if s1 == "{" and s2 == "}": return True return False def solve_inplace(self, s: str): l = list(s) top = -1 for i in range(len(s)): if top < 0 or not self.isMatch(l[top], l[i]): top += 1 l[top] = l[i] else: top -= 1 return top == -1 # ---- Stack Solution def isOpened(self, s: str): return s == '(' or s == '{' or s == '[' def solve_using_stack(self, s: str): stack = [] for item in s: if self.isOpened(item): stack.append(item) else: if not stack or not self.isMatch(stack.pop(), item): return False return not stack def isValid(self, s: str) -> bool: # Input: # [()] # ()[]{} # {()[]} # return self.solve_inplace(s) return self.solve_using_stack(s)
7f2233320d1cc16190e7ae1de84e16ab3ab30b21
Prashant-Surya/Python-Projects
/myzip(2).py
854
3.890625
4
from zipfile import ZipFile import zipfile import sys import os l=len(sys.argv) def file_accessible(filepath, mode): try: f = open(filepath, mode) f.close() except IOError as e: return False return True if l<2: print("GIVE AT LEAST ONE FILE") exit() f=input("ENTER NAME OF ZIP FILE WITHOUT .ZIP EXTENSION ") dir=os.getcwd() dir=dir+'\\'+f+'.zip' if file_accessible(dir,'r'): ch=input("FILE ALREADY THERE,PRESS E TO EXIT O TO OVERWRITE OTHERWISE APPENDS TO IT ") if(ch.lower()=='e'): exit() elif (ch.lower()=='o'): os.remove(dir) for x in range(1,l): with ZipFile(dir, 'a') as myzip: try: print(os.getcwd()) myzip.write(sys.argv[x]) print(sys.argv[x]+" IS COMPRESSED") except IOError as e: print(sys.argv[x]+" NOT FOUND") s=input("ENTER exit TO EXIT ") if s.lower()=='exit': exit()
b1c9e2c8a00a4629e172218fe03d8b85f7f02283
LexGalante/Python.Lang
/funcoes/definicao.py
2,501
3.53125
4
def minha_funcao_sem_parametro(): """Documentação Docsstring, utilize print(help(minha_funcao_sem_parametro))""" return "Teste testando testamento...." def minha_funcao_com_parametro(texto): return texto.upper() def soma(numeros): if type(numeros) is not list: return 0 return sum(numeros) def quadrado(numero): if type(numero) is not int: return 0 return numero * numero def exponencial(numero, potencia=2): return numero ** potencia def funcao_com_parametro_callback(text, func=lambda text: text.title()): text += " testando..." return func(text) def usuario(login, password, active): """ Cria um usuário :login do usuário :password do usuário :active usuário está ativo """ return { "login": login, "password": password, "active": active } def nome_programa(nome="Python.Lang"): return nome teste = 42 def funcao_usando_parametro_global(): global teste return teste def funcoes_aninhadas(): numero = 42 def funcao_interna(): nonlocal numero return numero return funcao_interna() # utilizar *args como o ultimo parametro antes dos opicionais # transforma o *args em uma tupla def funcao_com_varios_parametros(*args): return print(sum(args)) # utilizar o **kwargs como ultimo parametro de uma funcao # tranforma o **kwargs em uma tupla def funcao_com_varios_parametros_2(**kwargs): if 'nome' in kwargs: print(f'achei o nome: {kwargs["nome"]}') print(kwargs) print(help(print)) print(help(minha_funcao_sem_parametro())) print(minha_funcao_sem_parametro()) print(minha_funcao_com_parametro(minha_funcao_sem_parametro())) print(soma([5, 5, 5, 6])) print(quadrado(5)) print("parametros nomeados") print(usuario(active=False, password="teste", login="teste")) print("parametros com valores default") print(nome_programa()) print(exponencial(5)) print(funcao_com_parametro_callback("Teste")) print(funcao_usando_parametro_global()) print(funcoes_aninhadas()) funcao_com_varios_parametros(1) funcao_com_varios_parametros(1, 2) funcao_com_varios_parametros(1, 2, 3) funcao_com_varios_parametros(1, 2, 3, 4) funcao_com_varios_parametros(1, 2, 3, 4, 5) numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9] # usando o * pedimos ao python que realize o desempactamento da variavel antes de usar funcao_com_varios_parametros(*numeros) funcao_com_varios_parametros_2(nome='Alex', sobrenome='Galante', idade=18)
a251908fc8dbd56a817ab7764fdff1a9be4377c5
niksanand1717/TCS-434
/28 april/second.py
207
4.1875
4
"""Print wether the email ID is valid or not""" import re pattern = '.+@gmail.com$' email = input("Enter email ID to check: ") print("Valid Email") if re.match(pattern, email) else print("Invalid Email")
0777eb06db001421ace880f17faa4e99a84ed849
liamlee/Coursera_Python
/mini-project5-memory.py
2,753
3.625
4
# implementation of card game - Memory # 2013-05-24 import simplegui import random #global values pos_list = [] card_list = [] exposed = [] num_list = range(0,8) + range(0,8) unmatch_num = 0 unmatch_list = [] Moves = 0 # helper function to initialize globals def set_list(): global pos_list,card_list,exposed i = 0 pos_start = 12.5 step = 50 while i < 16: #set the position of each numner pos_list.append([pos_start+i*step,65]) #set the position of each card card_list.append([(0+i*step,100),(0+i*step,0),(50+i*step,0),(50+i*step,100)]) # exposed.append(False) i+=1 def init(): global mun_list,pos_list,card_list,exposed,Moves random.shuffle(num_list) Moves = 0 label.set_text("Moves = " + str(Moves)) i = 0 while i < 16: exposed[i] = False i+=1 # define event handlers def mouseclick(pos): # add game state logic here global exposed,unmatch_num,unmatach_list,num_list,Moves temp = pos[0] - 50 index = 0 while int(temp) > 0: index += 1 temp -= 50 if ~exposed[index]: #no unmatch card before,set the current to be the first unmatch card. if unmatch_num == 0: exposed[index] = True unmatch_list.append(index) unmatch_num += 1 Moves += 1 # elif unmatch_num == 1: if num_list[unmatch_list[0]] == num_list[index]: exposed[index] = True unmatch_list.pop() unmatch_num = 0 else: exposed[index] = True unmatch_list.append(index) unmatch_num += 1 #no more than two unmatched card should be display else: exposed[index] = True exposed[unmatch_list.pop()] = False exposed[unmatch_list.pop()] = False unmatch_list.append(index) unmatch_num = 1 Moves += 1 label.set_text("Moves = " + str(Moves)) # cards are logically 50x100 pixels in size def draw(canvas): i = 0 for em in num_list: if exposed[i]: canvas.draw_text(str(em),pos_list[i],50,"white") else: canvas.draw_polygon(card_list[i],1,"black","green") i+=1 # create frame and add a button and labels frame = simplegui.create_frame("Memory", 800, 100) frame.add_button("Restart", init) label = frame.add_label("Moves = 0") # initialize global variables set_list() init() # register event handlers frame.set_mouseclick_handler(mouseclick) frame.set_draw_handler(draw) # get things rolling frame.start() # Always remember to review the grading rubric
ea5e9bfbfe17e73d257d69b47cc964a6d24de342
AlbertoParravicini/AI-Library-Python
/AI-Library/Adversarial Search Engines/MinimaxAlphaBeta.py
7,052
3.8125
4
from AdversarialSearchEngine import AdversarialSearchEngine import random as random class MinimaxAlphaBeta(AdversarialSearchEngine): """ Implementation of the Minimax algorithm with alpha-beta pruning. The algorithm works for zero-sum, two-players, turn-based games, with perfect knowledge and deterministic moves. Given an initial node, it will look for the best move that the current player can perform, under the assumption that both players will play rationally (i.e optimally). Alpha-beta pruning optimizes the search by discarding branches which are guaranteed to return values worse than the current result. Minimax with alpha-beta pruning should be preferred over the standard minimax in every case but the simplest problems, as it doesn't pose any practical disadvantage over the standard Minimax; Parameters: ------------- search_depth: the new maximum depth of the search tree; by default it is equal to 1; order_moves: boolean flag which tells if the successors should be ordered based on their immediate value; ordering them takes time but can reduce the number of visited states, and improve the performances of the search; by default it is set ot False; """ def __init__(self, problem, **kwargs): super().__init__(problem, **kwargs) self.order_moves = kwargs.get("order_moves", False) def perform_search(self, initial_node): """ Perform a search from the provided initial_node, by using the rules expressed in the associated problem. The result of the search will be stored in obtained_result and obtained_successor. If the initial_node has no successors, the obtained_successor will be None, and obtained_result will be calculated on the initial_node; Parameters: ------------- initial_node: the node from which the search starts; """ self.obtained_successor = None self.obtained_value = alpha if initial_node.is_max() else beta # If the maximum depth is set to 0, return a random successor node; if self.search_depth == 0: self.obtained_successor = random.choice(self.problem.get_successors(initial_node)) self.obtained_value = self.problem.value(self.obtained_successor) return # Generates the immediate successors of the initial node, # then apply a minimax search to each of them: # their values, along with alpha and beta, are passed up to the highest level; # The moves are ordered based on their immediate value, # which reduces the number of visited states; successors = self.problem.get_successors(initial_node) if self.order_moves: successors.sort(key=lambda n: self.problem.value(n), reverse = initial_node.is_max()) for curr_succ in successors: self.num_of_visited_states += 1 # A certain player might play more than one turn in a row, # so no assumptions are made with respect to the turn alternation; if curr_succ.is_max(): result = self.__minimax_ab(curr_succ, 1, self.problem.min_value, self.obtained_value) else: result = self.__minimax_ab(curr_succ, 1, self.obtained_value, self.problem.max_value) # If a new best move was found, save it along with the value provided by the search; if (initial_node.is_max() and result > self.obtained_value) or (initial_node.is_min() and result < self.obtained_value): self.obtained_value = result self.obtained_successor = curr_succ self.search_performed = True def __minimax_ab(self, node, depth, alpha, beta): if depth >= self.search_depth or self.problem.is_end_node(node): return self.problem.value(node) if node.is_max(): value = alpha for curr_succ in self.problem.get_successors(node): self.num_of_visited_states += 1 # Update the current value of the node; Max will always take the node with highest value; # beta remains fixed, as it won't be allowed to get a value higher than it; value = max(value, self.__minimax_ab(curr_succ, depth + 1, alpha, beta)) # If the value found is outside the window, the branch is cut, # and the value of the node returned to its parent; if value >= beta: return value # The window is restricted by Max from left to right, # by increasing the value of alpha, the higher lowest bound. # It means that max will always be able to perform a move # whose value is equal to alpha; alpha = max(alpha, value) # If all the successors have been visited, return the value of the node, # which is guaranteed to be between alpha and beta; return value else: value = beta for curr_succ in self.problem.get_successors(node): self.num_of_visited_states += 1 # Update the current value of the node; Min will always take the node with lowest value; # alpha remains fixed, as it won't be allowed to get a value lower than it; value = min(value, self.__minimax_ab(curr_succ, depth + 1, alpha, beta)) # If the value found is outside the window, the branch is cut, # and the value of the node returned to its parent; if value <= alpha: return value # The window is restricted by Min from right to left, # by increasing the value of beta, the lower highest bound. # It means that min will always be able to perform a move # whose value is equal to beta; beta = min(beta, value) # If all the successors have been visited, return the value of the node, # which is guaranteed to be between alpha and beta; return value def set_order_moves(self, choice): """ Set if the successors of a node should be ordered based on their immediate value; Parameters: ------------- choice: boolean variable, it tells if the moves should be ordered or not; """ try: if not isinstance(choice, bool): raise TypeError assert not self.search_performed self.order_moves = choice except TypeError: print("ERROR: ", choice, " isn't a boolean variable!") except AssertionError: print("ERROR: serach already performed!")
beee6a81f9091463fb65c6071d0f5041aeb93837
overlord1781/lesson2
/HomeWork/Practic2. For_3.py
1,154
3.578125
4
''' Оценки Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] Посчитать и вывести средний балл по всей школе. Посчитать и вывести средний балл по каждому классу. ''' all_marks = [{'school_class': '4a', 'scores': [3,4,4,5,2]}, {'school_class': '4б', 'scores': [3,2,2,5,2]}, {'school_class': '4в', 'scores': [5,5,5,5,2]},] mid_scores_scholl = 0 mid_scores_class = 0 for mid_scores in all_marks: mid_scores_scholl += sum(mid_scores['scores'])/len(mid_scores['scores']) # Расчет среднего бала по школе mid_scores_class = sum(mid_scores['scores'])/len(mid_scores['scores']) # Расчет среднего бала по каждому классу print(f'Средний бал класса {mid_scores["school_class"]} составялет {mid_scores_class}') print(f'Средний бал по школе составляет {mid_scores_scholl/len(all_marks)}')
acef83d9fad5f531466471e480a22a32d7551b59
barath99/TN-CS-ErrorCorrections
/page63.py
233
3.5
4
# Demo Program to test String Literals boolean_1 = True boolean_2 = False print ("Demo Program for Boolean Literals") print ("Boolean Value1 :",boolean_1) print ("Boolean Value2 :",boolean_2) # End of the Program
388116e140a8fc33a38d19de5d7f7bbef1de7a48
hm-thg/machine-learning-and-data-mining
/Exercises/Exercise/Session #4 Error Handling and File Handling/Session #5 Exercises/2_capitalizeLines.py
1,401
4.4375
4
''' Program that takes data to be stored in the file file1 as interactive input from the user until he responds with nothing as input. Each line (or paragraph) taken as input from the user should be capitalized, and stored in the file file1. ''' def takeFileInput(file1): ''' Obective: To take data to be stored in the file file1 interactively from the user and capitalize it until (s)he responds with empty string Input Parameter: file1 : output file name - string value Return Value: None ''' ''' Approach: Iteratively, read lines as input from the user until he responds with nothing as the input 1.Capitalize each line 2.Add a newline at the end before writing it to file file1 ''' f=open(file1,'w') print("Please enter the data to be stored in file \'", file1, "\' : ") line=input() while line!='': l = line.capitalize() file1.write(l) line = input() print("The file is successfully created!!") ''' Close the file ''' f.close() def main(): ''' Objective: To take data to be stored in the file file1 interactively from the user and capitalize it until (s)he responds with empty string Input Parameter: None Return Value: None ''' file=input('Enter the destination file name : ') takeFileInput(file) if __name__ == '__main__': main()
7d8ad4948ac82557ed5ddc840cc7d0131a771a70
Trent-Dell/Refresh
/Group/overtime_calc.py
792
4.3125
4
#!/usr/bin/env python3 # US Federal Law requires that hourly employees be paid “time-and-a-half” for work in excess of 40 hours in one week. # User inputs hours worked in a week and the wage per hour. Displays gross pay. print( f"***********************************************************************\n" f"This program calculates weekly based on user inputs for wage and hours.\n" f"***********************************************************************\n\n" ) wage = float(input("What is your hourly rate? ")) print() weeklyHours = float(input("How many hours did you work? ")) print() if weeklyHours < 40: grossPay = weeklyHours * wage else: grossPay = (weeklyHours - 40) * wage * 1.5 + (wage * 40) print(f"Your gross pay for the week is ${grossPay:.2f}\n")
73751b3a30296897b50de4e80552e375385107d7
bhanutezz/machine-learning-a-z
/Part 2 - Regression/Section 5 - Multiple Linear Regression/multiple_linear_regression.py
2,753
3.90625
4
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder = LabelEncoder() X[:, 3] = labelencoder.fit_transform(X[:, 3]) onehotencoder = OneHotEncoder(categorical_features = [3]) X = onehotencoder.fit_transform(X).toarray() # Avoiding the Dummy Variable Trap X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # No need of feature scaling as there is no big difference in column values in terms of scaling # Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train)""" # Fitting Multiple Linear Regression to the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the Test set results y_pred = regressor.predict(X_test) # Building the optimal model using Backward Elimination with highest statistical significance import statsmodels.formula.api as sm # Note: status model does not take constant variable in multiple linear equation y = b0+b1x1+b2x2+...+bnxn # to overcome this, we have to add some value as X0 = 1 beside b0 X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1) # Note: axis paramteter of append function takes 0/1 values where 1 is for adding column 0 is for row X_opt = X[:, [0, 1, 2, 3, 4, 5]] # optimal least square model regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() # p value is greater for x2 than significant value(p = 0.05), remove it and re-create the model and re-run X_opt = X[:, [0, 1, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() # p value is greater for x1, remove it and re-create the model and re-run X_opt = X[:, [0, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() # p value is greater for x2, remove it and re-create the model and re-run X_opt = X[:, [0, 3, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() # p value of x2 is greater 0.06 than 0.05 X_opt = X[:, [0, 3]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() # therefore R&D spend is the most significant variable in gaining profit
5cc185aa1e766b313f5f4920403c977bb8f31b96
CSant04y/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
927
4.5
4
#!/usr/bin/python3 """creates class Square with private instance attribute size""" class Square: """defines class and instantiates private instance attribute size""" def __init__(self, size=0): self.__size = size @property def size(self): return(self.__size) @size.setter def size(self, val): if type(val) is not int: raise TypeError("size must be an integer") elif val < 0: raise ValueError("size must be >= 0") self.__size = val def area(self): """This calcs len * width = area of square""" return self.__size * self.__size def my_print(self): """Prints square using # signs""" if self.__size > 0: for column in range(self.__size): for row in range(self.__size): print("#", end="") print() else: print()
812bed317b4c68bb60f698d76a3bba46efd10d04
tribadboy/algorithm-homework
/week1/旋转数组.py
809
3.5625
4
# -*- coding:utf-8 -*- from typing import List class Solution: def getGcd(self, a: int, b: int) -> int: if a > b: return self.getGcd(b, a) while a: a, b = b % a, a return b def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ total = len(nums) k = k % total count = self.getGcd(k, total) for i in range(count): temp = nums[i] pos = i next_pos = (pos + k) % total while True: temp, nums[next_pos] = nums[next_pos], temp pos = next_pos next_pos = (pos + k) % total if pos == i: break return nums
d1aa3b228052ffa8477143a2b50e624582d44565
UditKapadia/Applications-of-Linear-Algebra-in-Linear-Programming
/Main Project/SimplexMethod.py
4,707
3.890625
4
import numpy as np from fractions import Fraction as f # Input and Table formation n_variable=int(input("Enter the number of variables:")) #no. of variables n_equation = int(input("Enter the number of equations:")) #no. of equations #Coeficient of Objective function print("Enter the maximizing equation coefficient separated by space: ") obj_fun=list(map(float,input().split())) print(obj_fun) for i in range(n_equation): obj_fun.append(float(0)) print(obj_fun) # Basic variable column B=list() coefficient_matrix=list() #Cost of Basic variable matrix CB=list() constraint=[] # Coefficient Matrix print("Enter the equations coefficient separated by space: e.g (a*x1 + b*x2 +c*x3 >= d, then write a b c d)") for i in range(n_equation): entries=list(map(float,input().split())) constraint.append(entries.pop(-1)) coefficient_matrix.append(entries) A =np.array(coefficient_matrix) print(constraint) print(A) #Making of tableu for i in range(n_equation): CB.append(0) B.append(i+n_variable) CB= np.array(CB) CB=np.transpose([CB]) c= np.array(obj_fun) c=np.transpose([c]) B = np.array(B) B=np.transpose([B]) tableu = np.hstack((B, CB)) tableu = np.hstack((tableu, A)) slack=np.identity(n_equation) tableu=np.append(tableu,slack,axis=1) constraint=np.transpose([constraint]) tableu = np.hstack((tableu, constraint)) tableu = np.array(tableu, dtype ='float') #Minimum Theta Calculation def pivot_test(tableu,col_index): t=0 row_index=0 i=0 minimum=99999 l=list(tableu[:,col_index]) while i < n_equation: if l[i] != 0.0: value=tableu[i,2+n_variable+n_equation]/l[i] if value >= 0: if minimum > value: minimum= value row_index=i t=1 i=i+1 return row_index,t # Table display and Iteration s="" itr=0 for i in range(n_equation+n_variable): s=s+("\tx" +str(i+1)) while True: itr=itr+1 print("Table iteration: " + str(itr)) print("B \tCB "+s+" \tRHS") i=0 for row in tableu: for element in row: if i%(n_equation+n_variable+3)== 0: print('x'+str(int(element)+1), end ='\t') else: print(f(str(element)).limit_denominator(100), end ='\t') i=i+1 print() print() i=0 maximize=[] theta=[] while i<len(obj_fun): maximize.append(obj_fun[i] - np.sum(tableu[:, 1]*tableu[:, 2 + i])) i = i + 1 print("maximize",end='\t') for element in maximize: print(f(str(element)).limit_denominator(100), end ='\t') if max(maximize)<=0: break col_index=maximize.index(max(maximize))+2 row_index,t=pivot_test(tableu,col_index) if t==0: print("Unboundedness occured") break pivot=tableu[row_index,col_index] tableu[row_index, 2:n_equation+5] = tableu[row_index, 2:n_equation+5] / pivot i=0 while i<n_equation: if i != row_index: tableu[i, 2:n_equation+5] = tableu[i,2:n_equation+5] - tableu[i][col_index]*tableu[row_index][2:n_equation+5] i=i+1 # Assign the new basic variable tableu[row_index][0] = col_index-2 tableu[row_index][1] = obj_fun[col_index-2] print() print() # Alternate Solution if not np.any(tableu[:,0]== 0): col_index=2 elif not np.any(tableu[:,0]== 1): col_index=3 else: col_index=-1 if (col_index == 2 or col_index == 3): row_index,t=pivot_test(tableu,col_index) pivot=tableu[row_index,col_index] tableu[row_index, 2:n_equation+5] = tableu[row_index, 2:n_equation+5] / pivot i=0 while i<n_equation: if i != row_index: tableu[i, 2:n_equation+5] = tableu[i,2:n_equation+5] - tableu[i][col_index]*tableu[row_index][2:n_equation+5] i=i+1 # Assign the new basic variable tableu[row_index][0] = col_index-2 tableu[row_index][1] = obj_fun[col_index-2] print("\n\n \t\t Alternate Solution") itr=itr+1 print("Table iteration: " + str(itr)) print("B \tCB "+s+" \tRHS") i=0 for row in tableu: for element in row: if i%(n_equation+n_variable+3)== 0: print('x'+str(int(element)+1), end ='\t') else: print(f(str(element)).limit_denominator(100), end ='\t') i=i+1 print() print() print() print() # Maximum Possible Value Z= np.sum(tableu[:, 1]*tableu[:,n_equation+n_variable+2]) print("Maximum Z= ",Z)
135a9a25ccd366ec04aab2d0a6b2936ba2023203
yashwanth312/ML-model---Salary-Prediction-
/model.py
1,284
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas # In[2]: dataset = pandas.read_csv("SalaryData.csv") # In[3]: dataset.info() # In[4]: y = dataset["Salary"] # In[5]: x = dataset["YearsExperience"] # In[6]: x = x.values # In[7]: x = x.reshape(30,1) # In[8]: x.shape # In[9]: from sklearn.linear_model import LinearRegression # In[10]: model = LinearRegression() # In[11]: from sklearn.model_selection import train_test_split # # Splitting the data into training and testing data # In[12]: x_train , x_test , y_train , y_test = train_test_split(x, y, test_size=0.2, random_state=42) # In[13]: model.fit(x_train , y_train) # In[14]: y_pred = model.predict(x_test) # In[15]: y_pred # In[16]: y_test # # Comparing the test values and predicted values graphically # In[17]: import matplotlib.pyplot as plt # In[18]: plt.scatter(x_test , y_test) # In[19]: plt.plot(x_test , y_pred) # In[20]: import seaborn as sns # In[21]: sns.set() # In[22]: plt.scatter(x_test , y_test , color="red") plt.plot(x_test , y_pred) plt.xlabel("Years of Experience") plt.ylabel("Salary Expected") # In[ ]: # In[23]: import joblib # In[24]: joblib.dump(model , "trained_model.h5") # In[ ]:
ea5e835967500117f1976e9e8d0b50f228182c47
YunsongZhang/lintcode-python
/Twitter OA/Balanced Sales Array.py
312
3.515625
4
class Solution: """ @param sales: a integer array @return: return a Integer """ def BalancedSalesArray(self, sales): # write your code here for index in range(len(sales)): if sum(sales[0:index]) == sum(sales[index + 1: len(sales)]): return index
34feb96a3f71644dfc7218e69f0d517a50f561c8
o-netzer/operations1
/scattergun.py
18,229
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 17 16:42:29 2019 @author: netzer Sometimes IT-operations work is hard, especially if the amount of information provided to solve a problem is minimal. This script takes a card number (and optionally country) as only input information. It then searches for all the information available in each of the relevant databases and displays the information in the console window. It was designed as the basis for the project called "The Matrix" - the endeavour to analyze all available information in the entire system given 1 card number - and present it nicely. The script is highly repetitive, thus not in accordance with Python's DRY principle This is partly desired to be so because it enables the user to control the information displayed in the Spyder console window by simply commenting out unwanted lines of code. """ from mytoolbox import selectCountryConnection, select_online_CountryConnection, \ ekonto_connect, db_lookup, Maggenta_anmeldung from selects import cards2, eServ_protoc, eGs_transactions, eGs_transaktfehler, \ eKo_single_crd, eKobewegung, eGs_det, prod_det, Maggenta_cardact, ekontocheckout_ekontopayment import sys ################# I N P U T ############################################## card_no = '009024000180938000' #Kartenlaenge egal countries = ['DEU'] #e.g. ['DEU','AUT'] kann mehrere Elemente beinhalten ################# I N P U T ############################################## print(3*'\n') laenge = len(card_no) print('card length = ' + str(laenge)) print(3*'\n') print((30*'#') + ' eCoupon cards Tabelle ' + (30*'#')) #####################eCoupon cards######################################## query = cards2.replace("k_num", card_no) ean_liste = [] for c in countries: cursor = selectCountryConnection(c) #<type 'OracleCursor'> eGs = db_lookup(cursor, query) print('eCoupon ' + c) if eGs <> []: # get column names from cursor description col_names = [x[0] for x in cursor.description] for entry in range(len(eGs)): d = dict(zip(col_names, [val for val in eGs[entry]] )) print('card number found: ' + str(d['KRT_CARD_NO'])) print('EAN ' + str(d['KRT_EAN'])) ean_liste.append(d['KRT_EAN']) print('Status ' + str(d['STATUS'])) print('') if len(eGs) > 1: print('WARNING: There is more than 1 (card_no,EAN) pair in the DB !!!!') print(ean_liste) print('This means that the following results must be read very CAREFULLY!!!') print('') print((30*'#') + ' eCoupon cards Details ' + (30*'#')) ###################### eGs_Details ############################# for e in ean_liste: query = (eGs_det.replace('euro_pro', e)).replace('k_num', card_no) eGs = db_lookup(cursor, query) col_names = [x[0] for x in cursor.description] d = dict(zip(col_names, [val for val in eGs[0]] )) print('KART_ID: ' + str(d['CARD_ID'])) print('LAOD_ID: ' + str(d['LAOD_ID'])) print('CARDNUMBER: ' + str(d['CARDNUMBER'])) print('PIN: ' + str(d['PIN'])) print('STATUS: ' + str(d['STATUS'])) print('DII_UPD_TIME: ' + str(d['DII_UPD_TIME'])) print('CARD_UPDATE_TIME: ' + str(d['CARD_UPDATE_TIME'])) print('DII_DELIVERY_NO: ' + str(d['DII_DELIVERY_NO'])) print('DLJ_INS_DATE: ' + str(d['DLJ_INS_DATE'])) print('DLJ_CANCELLED: ' + str(d['DLJ_CANCELLED'])) print('DII_UPD_DATE: ' + str(d['DII_UPD_DATE'])) print('VEN: ' + str(d['VEN'])) print('PACKETNUMMER: ' + str(d['PACKETNUMMER'])) print('EAN: ' + str(d['EAN'])) print('PARTNERCODE: ' + str(d['PARTNERCODE'])) print('VALUE: ' + str(d['VALUE'])) print('PRODUKTCODE: ' + str(d['PRODUKTCODE'])) print('PRODUKTNAME: ' + str(d['PRODUKTNAME'])) print('DELIVERY_PARTNER: ' + str(d['DELIVERY_PARTNER'])) print('DELIVER_POS: ' + str(d['DELIVER_POS'])) print('SELLER_POS: ' + str(d['SELLER_POS'])) print('MAX_VALUE: ' + str(d['MAX_VALUE'])) print('KARTE_WOCHE: ' + str(d['KARTE_WOCHE'])) print('KARTE_JAHR: ' + str(d['KARTE_JAHR'])) print('CARD_INSERT_TIME: ' + str(d['CARD_INSERT_TIME'])) # print('DELIVERY_LIST_ITEM_ID: ' + str(d['DELIVERY_LIST_ITEM_ID'])) print('DLJ_INS_DATE: ' + str(d['DLJ_INS_DATE'])) # print('DLJ_DII_ID: ' + str(d['DLJ_DII_ID'])) print('DELIVERY_LIST_ID: ' + str(d['DELIVERY_LIST_ID'])) print('DII_UPD_DATE: ' + str(d['DII_UPD_DATE'])) query = prod_det.replace('euro_pro', e) eGp = db_lookup(cursor, query) col_names = [x[0] for x in cursor.description] d = dict(zip(col_names, [val for val in eGp[0]] )) print('PARTNERLANGNAME: ' + str(d['PARTNERLANGNAME'])) print('Routing Type: ' + str(d['Routing Type'])) print('Unbekannte Kartennummer erlauben: ' + str(d['UNKNOWN_ERL'])) print(3*'\n') ###################### eGs_Details ############################# print((30*'#') + ' eCoupon cards Details ' + (30*'#')) else: print('card number not found \n') #cursor.close() #####################eCoupon cards######################################## print((30*'#') + ' eCoupon cards Tabelle ' + (30*'#')) print(3*'\n') print((30*'+') + ' eCoupon transactions Tabelle ' + (30*'+')) #####################eCoupon transactions######################################## for c in countries: query = (eGs_transactions.replace('country', c+'001')).replace('k_num', card_no) # cursor = selectCountryConnection(c) eGs = db_lookup(cursor, query) print('eCoupon transactions ' + c + " (Verkaufte Karten)") if eGs <> []: # get column names from cursor description col_names = [x[0] for x in cursor.description] for entry in range(len(eGs)): d = dict(zip(col_names, [val for val in eGs[entry]] )) print('card number found: ' + str(d['TRNAS_KRT'])) print('TRNAS_DATE ' + str(d['TRNAS_DATE'])) print('TRNAS_POS ' + str(d['TRNAS_POS'])) print('TRNAS_RP ' + str(d['TRNAS_RP'])) print('TRNAS_BP ' + str(d['TRNAS_BP'])) print('TRNAS_BRAND_CODE ' + str(d['TRNAS_BRAND_CODE'])) print('TRNAS_BRAND_NAME ' + str(d['TRNAS_BRAND_NAME'])) print('TRNAS_EAN ' + str(d['TRNAS_EAN'])) print('TRNAS_KRT ' + str(d['TRNAS_KRT'])) print('TRNAS_POS_DATE ' + str(d['TRNAS_POS_DATE'])) print('TRNAS_VALUE ' + str(d['TRNAS_VALUE'])) print('TRNAS_ACT_DATE ' + str(d['TRNAS_ACT_DATE'])) print('') else: print('card number not found \n') #####################eCoupon transactions######################################## print((30*'+') + ' eCoupon transactions Tabelle ' + (30*'+')) print(3*'\n') print((30*':') + ' eCoupon transaction errors ' + (30*':')) #####################eCoupon transaction errors################################## for c in countries: query = eGs_transaktfehler.replace('k_num', card_no) # cursor = selectCountryConnection(c) eGs = db_lookup(cursor, query) print('eCoupon Transaktionsfehler der Karte ' + c) if eGs <> []: # get column names from cursor description col_names = [x[0] for x in cursor.description] for entry in range(len(eGs)): d = dict(zip(col_names, [val for val in eGs[entry]] )) print('card number found: ' + str(d['TRNAS_KRT'])) print('TRNAS_DATE ' + str(d['TRNAS_DATE'])) print('TRNAS_RP ' + str(d['TRNAS_RP'])) print('TRNAS_POS ' + str(d['TRNAS_POS'])) # print('TRNAS_BP ' + str(d['TRNAS_BP'])) print('TRNAS_BRAND_CODE ' + str(d['TRNAS_BRAND_CODE'])) print('TRNAS_BRAND_NAME ' + str(d['TRNAS_BRAND_NAME'])) print('TRNAS_EAN ' + str(d['TRNAS_EAN'])) print('TRNAS_KRT ' + str(d['TRNAS_KRT'])) print('TRNAS_POS_DATE ' + str(d['TRNAS_POS_DATE'])) print('TRNAS_VALUE ' + str(d['TRNAS_VALUE'])) print('TRNAS_ERROR_CODE ' + str(d['TRNAS_ERROR_CODE'])) print('TRNAS_ERROR ' + str(d['TRNAS_ERROR'])) print('Unbekannte KN erl ' + str(d['UNB_KN_ERL'])) print('') else: print('card number not found \n') cursor.close() #####################eCoupon transaction errors################################## print((30*':') + ' eCoupon transaction errors ' + (30*':')) print(3*'\n') print((30*'~') + ' eDienst cards table ' + (30*'~')) #####################eDienst######################################## query = cards2.replace("k_num", card_no) #print(query) #sys.exit() for c in countries: cursor = select_online_CountryConnection(c) eServ = db_lookup(cursor, query) print('eDienst ' + c) if eServ <> []: # get column names from cursor description col_names = [x[0] for x in cursor.description] for entry in range(len(eServ)): d = dict(zip(col_names, [val for val in eServ[entry]] )) print('card number found: ' + str(d['KRT_CARD_NO'])) print('EAN ' + str(d['KRT_EAN'])) print('Status ' + str(d['STATUS'])) print('') if len(eServ) > 1: print('WARNING: There is more than 1 (card_no,EAN) pair in the DB !!!!') print('This means that the following results must be read very CAREFULLY!!!') print('') else: print('card number not found \n') #cursor.close() #####################eDienst######################################## print((30*'~') + ' eDienst cards table ' + (30*'~')) print(3*'\n') print((30*'-') + ' eDienst Verkaufsversuche ' + (30*'-')) #####################eDienst Protocols############################## query = eServ_protoc.replace('%%',"%" + card_no + "%") #print(query) for c in countries: #cursor = select_online_CountryConnection(c) eServ_pro = db_lookup(cursor, query) print('eDienst protocols ' + c) if eServ_pro <> []: # get column names from cursor description col_names = [x[0] for x in cursor.description] for entry in range(len(eServ_pro)): d = dict(zip(col_names, [val for val in eServ_pro[entry]] )) # print(d) print('XXX_ID: ' + str(d['XXX_ID'])) print('XXX_DATE: ' + str(d['XXX_DATE'])) print('YYY_VALUE: ' + str(d['YYY_VALUE'])) print('XXX_DESCRIPTION: ' + str(d['XXX_DESCRIPTION'])) print('') else: print('card number not found \n') cursor.close() #####################eDienst Protocols############################## print((30*'-') + ' eDienst Verkaufsversuche ' + (30*'-')) print(3*'\n') print((30*'=') + ' eKorso Karten ' + 30*'=') ##################### eKorso Einzelkartenabfrage ############################## query = eKo_single_crd.replace('k_num', card_no) for c in countries: try: cursor = ekonto_connect(c) eKo = db_lookup(cursor, query) print('eKorso Einzelkartenabfrage ' + c) if eKo <> []: # get column names from cursor description col_names = [x[0] for x in cursor.description] for entry in range(len(eKo)): d = dict(zip(col_names, [val for val in eKo[entry]] )) print('MONDINT_CODE: ' + str(d['MONDINT_CODE'])) print('MONDINT_NAME: ' + str(d['MONDINT_NAME'])) print('PRODUCT_CODE: ' + str(d['PRODUCT_CODE'])) print('PRODUCT_NAME: ' + str(d['PRODUCT_NAME'])) print('PRODUCT_VALUE: ' + str(d['PRODUCT_VALUE'])) print('PROCUCT_VALUE_MAX: ' + str(d['PROCUCT_VALUE_MAX'])) print('EAN: ' + str(d['EAN'])) print('CARDNUMBER: ' + str(d['CARDNUMBER'])) print('STATUS: ' + str(d['STATUS'])) print('PIN: ' + str(d['PIN'])) print('KRT_PIN_FAILURE_COUNT:' + str(d['KRT_PIN_FAILURE_COUNT'])) print('KRT_PIN_FAILURE_DATE: ' + str(d['KRT_PIN_FAILURE_DATE'])) print('KRT_INS_DATE: ' + str(d['KRT_INS_DATE'])) print('KRT_UPD_DATE: ' + str(d['KRT_UPD_DATE'])) print('') if len(eKo) > 1: print('WARNING: There is more than 1 (card_no,EAN) pair in the DB !!!!') print('This means that the following results must be read very CAREFULLY!!!') print('') else: print('card number not found \n') except AttributeError: print('There is no eKorso DB for country ' + c) #cursor.close() ##################### eKorso Einzelkartenabfrage ############################## print((30*'=') + ' eKorso Karten ' + 30*'=') print(3*'\n') print((30*'<') + ' eKorso Bewegungen ' + 30*'<') ##################### eKorso Kontenbewegungen ############################## query = eKobewegung.replace('k_num', card_no) for c in countries: try: cursor = ekonto_connect(c) eKobew = db_lookup(cursor, query) print('eKorso Kontobewegungen ' + c) if eKobew <> []: # get column names from cursor description col_names = [x[0] for x in cursor.description] for entry in range(len(eKobew)): d = dict(zip(col_names, [val for val in eKobew[entry]] )) print('TX_DATE: '+ str(d['TX_DATE'])) print('CLOSING_DATE: '+ str(d['CLOSING_DATE'])) print('MDT_CODE: '+ str(d['MDT_CODE'])) print('KRT_EAN: '+ str(d['KRT_EAN'])) print('KRT_CARD_NO: '+ str(d['KRT_CARD_NO'])) print('Maggenta Order Nr: '+ str(d['BTR_TX_REFERENCE_TEXT'])) print('BTR_TX_ORIG_ID: '+ str(d['BTR_TX_ORIG_ID'])) print('BTR_POS_CODE: '+ str(d['BTR_POS_CODE'])) print('ACT_DESCRIPTION: '+ str(d['ACT_DESCRIPTION'])) print('VALUE: '+ str(d['VALUE'])) print('ACE_VALUE: '+ str(d['ACE_VALUE'])) print('ACB_OPENING_BALANCE_VALUE: '+ str(d['ACB_OPENING_BALANCE_VALUE'])) print('ACB_CLOSING_BALANCE_VALUE: '+ str(d['ACB_CLOSING_BALANCE_VALUE'])) print('') else: print('card number not found \n') except AttributeError: print('There is no eKorso DB for country ' + c) ##################### eKorso Kontenbewegungen ############################## print((30*'<') + ' eKorso Bewegungen ' + 30*'<') print(3*'\n') if 'DEU' in countries: print((30*'°') + ' Maggenta Bestellungen mit dieser Kartennummer ' + 30*'°') ##################### Maggenta Bestellungen mit dieser Kartennummer ########### cursor = Maggenta_anmeldung() query = Maggenta_cardact.replace('k_num', card_no) mag_cardact = db_lookup(cursor,query) col_names = [x[0] for x in cursor.description] for entry in range(len(mag_cardact)): d = dict(zip(col_names, [val for val in mag_cardact[entry]] )) print('activation_id: ' + str(d['activation_id'])) print('item_id: ' + str(d['item_id'])) print('order_id: ' + str(d['order_id'])) print('Maggenta Order ID: ' + str(d['increment_id'])) print('store_id: ' + str(d['store_id'])) print('user: ' + str(d['user'])) print('aktivierungsdatum: ' + str(d['aktivierungsdatum'])) print('status: ' + str(d['status'])) print('shipping_description: ' + str(d['shipping_description'])) print('referenznummer: ' + str(d['referenznummer'])) ##################### Maggenta Bestellungen mit dieser Kartennummer ########### print((30*'°') + ' Maggenta Bestellungen mit dieser Kartennummer ' + 30*'°') print(3*'\n') print((15*'%') + ' Info from eKorsocheckout_eKorsopayment - "Alle Bestellungen zu einem UniversalCoupon" ' + 15*'%') query = ekontocheckout_ekontopayment.replace('k-num', card_no) ekocheckpay = db_lookup(cursor,query) col_names = [x[0] for x in cursor.description] for entry in range(len(ekocheckpay)): d = dict(zip(col_names, [val for val in ekocheckpay[entry]] )) print('Bestellnummer: ' + str(d['Bestellnummer'])) print('created_at: ' + str(d['created_at']) ) print('Status: ' + str(d['Status']) ) print('Saldo: ' + str(d['Saldo']) ) print('bezahlt: ' + str(d['bezahlt']) ) print('ausstehend: ' + str(d['ausstehend']) ) print('Kunden-eMail: ' + str(d['Kunden-eMail']) ) print('\n') print((15*'%') + ' Info from ekontocheckout_ekontopayment - "Alle Bestellungen zu einem UniversalCoupon" ' + 15*'%') cursor.close() print('done searching')
ee2e7e4d51e077c3f290269af207d36f75d28a69
Lmuxin/pythonTest
/pythontestprogramming/绑定事件.py
273
3.6875
4
from tkinter import * root=Tk() def callback(event): print("点击位置:",event.x,event.y) frame=Frame(root,width=200,height=20) frame.bind('<Button-1>',callback) #鼠标点击事件 1是左键 2是中间 3是右键 frame.pack() mainloop()
5d3cd5c31d954c67d160433a6f3dfb08cd2aae28
shankar7791/MI-10-DevOps
/Personel/pooja/python/datastructure/7june/delete_operation.py
1,159
4.03125
4
def deleteNode(root, key): if root is None: return root if key < root.key: root.left = deleteNode(root.left, key) elif(key > root.key): root.right = deleteNode(root.right, key) else: if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp temp = minValueNode(root.right) root.key = temp.key root.right = deleteNode(root.right, temp.key) return root root = None root = insert(root, 50) root = insert(root, 30) root = insert(root, 20) root = insert(root, 40) root = insert(root, 70) root = insert(root, 60) root = insert(root, 80) print "Inorder traversal of the given tree" inorder(root) print "\nDelete 20" root = deleteNode(root, 20) print "Inorder traversal of the modified tree" inorder(root) print "\nDelete 30" root = deleteNode(root, 30) print "Inorder traversal of the modified tree" inorder(root) print "\nDelete 50" root = deleteNode(root, 50) print "Inorder traversal of the modified tree" inorder(root)
28895b1fcc9e10d060739c62fe99a6f9438b038c
faramarz-hosseini/leetcode
/1436. Destination City.py
409
3.578125
4
class Solution(object): def destCity(self, paths): """ :type paths: List[List[str]] :rtype: str """ p = {} for path in paths: p[path[0]] = path[1] for path in paths: city1, city2 = path if city1 not in p.keys(): return city1 elif city2 not in p.keys(): return city2
ab9f4449f9167fce471c977e4df3303512bf03c6
sethrylan/Udacity
/CS212/src/cs212.py
407
3.96875
4
def allmax(iterable, key=None): "Return a list of all items equal to the max of the iterable." result, maxval = [], None k = key or (lambda x: x) for x in iterable: xval = k(x) if not result or xval > maxval: result, maxval = [x], xval elif xval == maxval: result.append[x] return result if __name__ == "__main__": allmax([1,1])
ef8a01b05b1309b4a633267b7de834c5c5fef4ee
Jaydanna/practice
/collated.py
362
4.0625
4
#! usr/bin/env python def bubble(bubblelsit): lenth = len(bubblelsit) for i in range(lenth-1) : if bubblelsit[i+1]>bubblelsit[i]: bubblelsit[i],bubblelsit[i+1] = bubblelsit[i+1] ,bubblelsit[i] i+=1 return bubblelsit if __name__ == '__main__': quenue = raw_input('input a list:') bubblelsit = quenue.split() print bubble(bubblelsit)
60f3309e1b8debf81658b96875c33df54265faae
itzsoumyadip/study-repo-
/python/OPP/Class .py
1,151
4.125
4
class Computer: # class def config(self): ## attributes # self is the object which are passing # The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. # it does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: print('from class computer') # behaviour or method com=Computer() ##com is the instance of class computer ,and computer() com2=Computer() ##com2 is the instance of class computer com.config() # behind the scene config() will take com as parameter and pass it like config(com) # from class computer ## another way of calling class function Computer.config(com) #oject com is pass as argument #from class computer com2.config() #from class computer print(type(com)) # <class '__main__.Computer'> # The pass Statement ## class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error. class Person: pass
011236218db597df3708a653b67385d389071090
nmap1208/2016-python-oldboy
/Day7/method.py
1,060
3.5625
4
# __author__ = '111' # -*- coding: utf-8 -*- class Animal(object): hobby = 'meat' def __init__(self, name): self.name = name self.__num = None @classmethod def talk(cls): print('hobby is ', cls.hobby) @property def habit(self): print('%s habit is xxoo' %self.name) @staticmethod # 静态方法不能访问类变量和实例变量,除非Animal.hobby def think(x, y): print('hobby is %s' % (x+y)) @property def total_players(self): return self.__num @total_players.setter def total_players(self, num): self.__num = num @total_players.deleter def total_players(self): self.__num = None d = Animal('Sanjiang') d.habit d.talk() d.think(5, 6) print(d.total_players) d.total_players = 5 print(d.total_players) del d.total_players print(d.total_players) d.__num = 9 d.total_players = 5 print('out', d.__num) print(d.total_players) print('out', d._Animal__num) # 特例访问私有变量
0413dfc6736d21b84c6e43c0729ac526161ad653
greciavm/python-challenge
/PyPoll/main.py
2,647
3.6875
4
#import modules import os import csv #set path for file pypoll_csv = os.path.join('.','election_data.csv') #set initial values and list votes = 0 dict = {} #open the csv to read with open (pypoll_csv, newline='') as csvfile: #specify delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') #read the header row first csv_header = next(csvreader) #create dictionary from file with unique candidates names as keys. for row in csvreader: #The total number of votes cast votes += 1 #counts votes for each candidate as values #keeps a total vote count by counting up 1 for each row if row[2] in dict.keys(): dict[row[2]] += 1 else: dict[row[2]] = 1 #create empty list for candidates and their votes count candidates = [] cand_votes = [] #take dictionary keys and values and adds them to the lists for key, value in dict.items(): candidates.append(key) cand_votes.append(value) #create percent list percent = [] for i in cand_votes: percent.append(round(i/votes*100, 3)) #group candidates, cand_votes and percent into tuples group = list(zip(candidates, cand_votes, percent)) #create winner list winner_list= [] for candidate in group: if max(cand_votes) == candidate[1]: winner_list.append(candidate[0]) # makes winner_list a str with the first entry winner = winner_list[0] print("Election Results") print("-------------------------") #The total number of votes cast print(f"Total Votes: {votes}") print("-------------------------") #A complete list of candidates who received votes #The percentage of votes each candidate won #The total number of votes each candidate won for j in range(len(candidates)): print(candidates[j],": ",percent[j],"% (",cand_votes[j],")") print("-------------------------") #The winner of the election based on popular vote. print("Winner: ",winner) print("-------------------------") #create text file in this path text_file = os.path.join("Election Results.txt") #write this in text with open("Election Results.txt", "w") as text_file: print("Election Results", file = text_file) print("-------------------------", file = text_file) print(f"Total Votes: {votes}", file = text_file) print("-------------------------", file = text_file) for j in range(len(candidates)): print(candidates[j],": ",percent[j],"% (",cand_votes[j],")", file = text_file) print("-------------------------", file = text_file) print("Winner: ",winner, file = text_file) print("-------------------------", file = text_file)
76f2d4f841432b97bf2ff61e3579b32fb241a829
maiwen/LeetCode
/Python/53. Maximum Subarray.py
925
3.75
4
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ result, subsum = nums[0], 0 for num in nums: subsum += num result = max(result, subsum) if subsum < 0: subsum = 0 return result def maxSubArray1(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 dp = [0] * len(nums) dp[0] = nums[0] result = dp[0] for i in range(1, len(nums)): if dp[i - 1] > 0: dp[i] = dp[i - 1] + nums[i] else: dp[i] = nums[i] result = max(result, dp[i]) return result
1a9560bee44950ed44564d33de8faa5b73e9b3fd
kirankunapuli/python-scripts
/numpy_ex.py
566
3.84375
4
import sys import numpy as np welcomeString = input('Enter one of the following\n Mean, Median, Mode, Range\n') welcomeString = welcomeString.lower() numbers = input("Enter numbers to calculate: ") numbers = list(map(float, numbers.split(' '))) average_function = {"mean": np.average, "median": np.median, # "mode": np.mode, "range": np.arange, } try: print(average_function[welcomeString](numbers)) except KeyError: sys.exit("You entered invalid average type!") # input()
a6928909dfba0e695a59abe0a1eedb59f6844180
SomethingRandom0768/PythonBeginnerProgramming2021
/Chapter 9 ( Classes )/Exercises/Import Exercises/Imported Restaurant/restaurant.py
503
3.875
4
# Used for 9-10 class Restaurant: """Model of a restaurant""" def __init__(self, name, type_cuisine): self.name = name self.type_cuisine = type_cuisine def describe_restaurant(self): print(f"The name of the restaurant is {self.name} and the type of cuisine is {self.type_cuisine}") def open_restaurant(self): print(f"{self.name} is opening! ") restaurant = Restaurant("Monkey Barz", "Banana") restaurant.describe_restaurant() restaurant.open_restaurant()
6de3584c23ad09919b6bf1d88c313aff72dd87de
andrei406/Meus-PycharmProjects-de-Iniciante
/PythonExercicios/ex113/funçoes.py
794
3.8125
4
def leiaint(valor): while True: try: n = int(input(valor)) except (ValueError, TypeError): print('\33[31mVocê não informou corretamente o valore pedido\33[m') continue except KeyboardInterrupt: print(' \33[32mO usuário preferiu não informar o número\33[m') return 0 else: return n def leiafloat(valor): while True: try: n = float(input(valor)) except (ValueError, TypeError): print('\33[31mVocê não informou corretamente o valore pedido\33[m') continue except KeyboardInterrupt: print(' \33[32mO usuário preferiu não informar o número\33[m') return 0 else: return n
7e38c743901ee481812c76be88f0e85629f5b2e2
liangliannie/LeetCode
/148. Sort list.py
2,298
3.875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head: return head cur = head mem = [] while cur: mem.append(cur) cur = cur.next l = len(mem) for i in range(l/2): mem[i].next = mem[l-i-1] mem[l-i-1].next = mem[i+1] mem[l/2].next = None # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # class Solution2(object): # def sortList(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ # def BreakTwoList(head): # pre = head # slow = head # fast = head # while fast and fast.next: # pre = slow # slow = slow.next # fast = fast.next.next # pre.next = None # Break the two link! # return head, slow # # # def merge(list1,list2): # pre = ListNode(0) # head = pre # while list1 and list2: # if list1.val<=list2.val: # head.next = list1 # list1 = list1.next # else: # head.next = list2 # list2 = list2.next # head = head.next # if list1: # head.next = list1 # if list2: # head.next = list2 # return pre.next # # if not head or not head.next: # return head # # l1,l2 = BreakTwoList(head) # return merge(self.sortList(l1), self.sortList(l2)) Node1 = ListNode(4) Node2 = ListNode(2) Node3 = ListNode(1) Node4 = ListNode(3) Node1.next= Node2 Node2.next = Node3 Node3.next = Node4 f=Solution() # n=(f.sortList(Node1)) # while n: # print(n.val) # n=n.next
476430f2f0b355de305de09fe5784a34adc12722
benzi314/Py_exercises
/list_overlap.py
481
4.09375
4
#This program illustrates the concept of lists overlap import random x = int (input("Enter the length of first list:")) y = int (input("Enter the length of second list:")) a = (random.sample(range(1,100),x)) b = (random.sample(range(1,100),y)) c = set(a) d = set(b) print("The first list is: %s" %c) print("The second list is: %s" %d) new_list = [] for x in a: for y in b: if x==y: new_list.append(x) print("The overlapped elements are:") print(new_list)
72d161065d18711936ff8e6f041c078c4f09b821
ballib/2020-1-T-111-PROG
/projects/flight_rules.py
1,730
3.890625
4
flight_altitude_int = int(input('Input flight altitude (ft): ')) airspace_class = input('Input airspace class: ') visibility_int = int(input('Input visibility (km): ')) horizontal_cloud_int = int(input('Input horizontal cloud separation (ft): ')) vertical_cloud_int = int(input('Input vertical cloud separation (ft): ')) is_valid_bool = True is_vfr = False if (airspace_class != 'A' and \ airspace_class != 'B' and \ airspace_class != 'C' and \ airspace_class != 'D' and \ airspace_class != 'E' and \ airspace_class != 'F' and \ airspace_class != 'G') or \ flight_altitude_int < 0 or \ visibility_int < 0 or \ horizontal_cloud_int < 0 or \ vertical_cloud_int < 0: is_valid_bool = False if is_valid_bool: if airspace_class != 'A': if flight_altitude_int >= 10000: if horizontal_cloud_int >= 1500 and \ vertical_cloud_int >= 1000 and \ visibility_int >= 8: is_vfr = True elif flight_altitude_int > 3000: if horizontal_cloud_int >= 1500 and \ vertical_cloud_int >= 1000 and \ visibility_int >= 5: is_vfr = True else: if airspace_class == 'F' or \ airspace_class == 'G': if visibility_int >= 5: is_vfr = True else: if horizontal_cloud_int >= 1500 and \ vertical_cloud_int >= 1000 and \ visibility_int >= 5: is_vfr = True if is_valid_bool: if is_vfr: print('Visual Flight Rules') else: print('Instrument Flight Rules') else: print('Invalid input')
c9efc02108bcc92b4bbd78e3e7421cf20bff1e01
wangande/test-question
/sub_string_search.py
2,696
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class SubStringSearchKmp(object): """ 根据kmp实现的字符串查找算法,时间复杂度o(m+n) """ def generate_next_list(self, sub_str): """ 生成next列表 :param sub_str: 子字符串 :return: """ next_list = list() next_list.append(-1) # 将-1添加到list中 i = 0 j = -1 # 注意:这里比较的对象是ss的长度减去1 # 如果是 while( i < lenOfSs) 会导致NEXT的长度比实际长度多1 # 因为在一开始时已经将-1放入了list_next中,作为第一个字符的跳转值 while i < len(sub_str) - 1: if j == (-1) or sub_str[i] == sub_str[j]: # 如果满足条件 print (i, j, sub_str[i], sub_str[j]) i += 1 j += 1 next_list.append(j) else: # 如果不满足字符相等的条件,执行该语句,而不是从0开始寻找最长相等的前缀与后缀的长度!!!简化计算 j = next_list[j] return next_list def sub_string_match(self, sub_str, org_string): """ 字符串查找,若存在子字符串,返回匹配段的起点下标,否则返回-1 :param sub_str: 子字符串 :param org_string: 原始字符串 :return: sub_string,在 org_string里面起点下标 """ sub_str_len = len(sub_str) # 计算子字符串的长度 next_list = self.generate_next_list(sub_str) # 构造next跳转表 org_string_index = 0 # 指向主串 main_ss sub_string_index = 0 # 指向模式串 ss while (sub_string_index < sub_str_len) and (org_string_index < len(org_string)): if org_string[org_string_index] == sub_str[sub_string_index]: sub_string_index += 1 org_string_index += 1 elif org_string_index == 0: # 如果第一个模式串的字符就不匹配,则移动指向主串的指针 org_string_index += 1 else: # 否则将指向模式串的指针移动至 list_next[sub_string_index]处 sub_string_index = next_list[sub_string_index] if sub_string_index == sub_str_len: # 如果完成匹配时, sub_str_len指向模式串的串尾,则匹配成功 return org_string_index - sub_str_len else: return -1 if __name__ == "__main__": mp = SubStringSearchKmp() r = mp.sub_string_match("abce", "aabcabcebafabcabceabcaefabcacdabcababce") print r
46cda8e21ce9634d53cf19849b9a8f41e990f5d0
junha6316/Algorithm
/0810_가사검색_프로그래머스.py
1,284
3.875
4
class Node(object): def __init__(self, key, count=0): self.key = key self.child ={} class Trie(object): def __init__(self): self.head = Node(None) def insert(self, word): cur = self.head for ch in word: if ch not in cur.child: cur.child[ch] = Node(ch) cur = cur.child[ch] cur.child['*'] =True def search(self, word): cur= self.head for ch in word: if ch not in cur.child: return False cur = cur.child[ch] if '*' in cur.child: return True a = Trie() a.insert('abc') class Node(object): def __init__(self, key, data=None): self.key = key self.data = data self.children= {} class Trie(object): def __init__(self): self.head =Node(key=None, data=None) def insert_string(self, input_string): cur_node = self.head for c in input_string: if c not in cur_node.children.keys(): cur_node.children[c]= Node(key=c) cur_node = cur_node.children[c] cur_node.data = input_string def dic ={} for word in words: for c in word: if not dic.get[c]: dic[c] = c.
6368c1ea29a23133b91bba96c5f07110f7cbd6f3
prathamesh-collab/python_tutorials-pratham-
/cal_revision.py
246
3.78125
4
def add(): a = int(input("Enter 1st number here")) b = int(input("Enter 2nd number here")) print(a, "+", b, "=", a+b) def sub(): a = int(input("Enter 1st number here")) b = int(input("Enter 2nd number here")) print(a-b)
56adca4843cdddcba55c9f2f4b8b5468f5caeddb
SLKyrim/vscode-leetcode
/0021.合并两个有序链表.py
1,408
3.875
4
# # @lc app=leetcode.cn id=21 lang=python3 # # [21] 合并两个有序链表 # # https://leetcode-cn.com/problems/merge-two-sorted-lists/description/ # # algorithms # Easy (58.82%) # Likes: 895 # Dislikes: 0 # Total Accepted: 205.6K # Total Submissions: 340.6K # Testcase Example: '[1,2,4]\n[1,3,4]' # # 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。  # # 示例: # # 输入:1->2->4, 1->3->4 # 输出:1->1->2->3->4->4 # # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 if l1.val < l2.val: res = ListNode(l1.val) l1 = l1.next else: res = ListNode(l2.val) l2 = l2.next tmp = res while l1 and l2: if l1.val < l2.val: tmp.next = ListNode(l1.val) l1 = l1.next else: tmp.next = ListNode(l2.val) l2 = l2.next tmp = tmp.next if l1: tmp.next = l1 else: tmp.next = l2 return res # @lc code=end
9045c70be5657ce71998ac1a63d8381bd07bf6a2
chakrarases/cultist_sim_mod
/core_zh-hans/Extract_charset.py
1,997
3.71875
4
import os import itertools from tkinter import Tk ## ## Function pulls all unique characters from the localiseds string in a .PO (Portable Object) file ## and returns them sorted into order. Used for determining what characters are actually used ingame ## def ExtractCharSet( filename ): charset = '' with open(filename, encoding="utf8") as fp: line = fp.readline() cnt = 1 while line: ##if line.find("msgstr") == 0: for ch in line: if ord(ch) > 32: if charset.find(ch) == -1: charset = charset + ch ##print("Line {}: {}".format(cnt, line.strip())) ##print(charset) line = fp.readline() cnt += 1 #Bubble sort resulting charset into code order charset = ''.join(sorted(charset)) return charset gcharset = '' print("Extracting unique chars...") print("NOTE: easiest way to extract UI strings is to make a temp copy of content/strings.csv in the target folder, and remove all the unwanted language columns.") for root, dirs, files in os.walk("."): path = root.split(os.sep) print((len(path) - 1) * '---', os.path.basename(root)) for file in files: if (file.endswith(".json") or file.endswith(".JSON") or file.endswith(".csv") or file.endswith(".CSV")): print(len(path) * '---', file) fcharset = ExtractCharSet(os.path.join(root, file)) gcharset += fcharset; #Bubble sort into order and remove duplicate characters gcharset = ''.join(sorted(gcharset)) gcharset = ''.join(ch for ch, _ in itertools.groupby(gcharset)) print("Gathered unique characters to Charset.txt - list below:") print(gcharset) with open("Charset.txt", "w", encoding="utf8") as text_file: text_file.write(gcharset) wait = input("PRESS ENTER TO CONTINUE.") #Tried to get it to copy results into clipboard but no joy :/ #Have to copy them from the cmd line window instead.. from tkinter import Tk r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append('i can has clipboardz?') r.update() # now it stays on the clipboard after the window is closed r.destroy()
b8e4c74cfed63936759d1f865e3256473a71d5b4
Gab13/Multi-Agent-RL-SIM
/MultiAgentReinforcementLearningSimulator- GabrielaRivas/Random.py
3,759
3.515625
4
# ------------------------------------------------------------------------------------------------------ # Gabriela Rivas # ID: 201155263/u5gra # Final Year Project 2018 # ------------------------------------------------------------------------------------------------------ # Random class for an agent. It finds and returns the next state the agent should go to based on # random values. # ------------------------------------------------------------------------------------------------------ from random import randint from copy import copy, deepcopy import World class Random(object): state = 0 initialState = 0 totalStates = 0 def __init__(self, width, height, initialState, world, agent): self.width = width self.height = height self.state = initialState self.initialState = initialState self.world = world self.agent = agent self.totalStates = self.width*self.height self.impassable = 4 if agent == 1: self.objective = 5 if agent == 2: self.objective = 1 def move(self): self.random() # ------------------------------------------------------------------------------------------------------ # MOVE TO A RANDOM REACHABLE STATE # ------------------------------------------------------------------------------------------------------ def random(self): rand = randint(0, self.totalStates) while not self.reachable(self.state,rand) and not self.checkImpassable(rand): rand = randint(0, self.totalStates) nextState = rand self.world.updateGrid(nextState, self.agent) self.state = nextState # ------------------------------------------------------------------------------------------------------ # Checking if a state is passable # ------------------------------------------------------------------------------------------------------ def checkImpassable(self, r): count = 0 for i in range(self.height): for j in range(self.width): if count == r: if self.world.getGrid()[i][j] == self.impassable: return False count+=1 # ------------------------------------------------------------------------------------------------------ # Checking if a state is reachable # ------------------------------------------------------------------------------------------------------ def reachable(self, state, action): if state == action: return True elif state + self.width == action: return True elif state - self.width == action: return True else: if (state+1)%self.width == 0: if action == state-1: return True elif(state)%self.width == 0: if action == state+1: return True elif state+1 == action: return True elif state-1 == action: return True else: return False def getState(self): return self.state def getAgent(self): return self.agent # ------------------------------------------------------------------------------------------------------ # Resetting the agent to it's original position # ------------------------------------------------------------------------------------------------------ def resetState(self): self.state = self.initialState self.world.updateGrid(self.initialState, self.agent) def caughtHandling(self): pass def resetLearning(self): pass def getPolicy(self, state): return 0
133cb33220520dc724126e4d8fbf47453c082d0b
david-e-cox/aoc2020
/day06/d06.py
1,217
3.53125
4
#!/usr/bin/python3 import numpy as np from collections import defaultdict # Open input file, read map f=open('input.txt'); fileRaw=f.read().split('\n\n'); f.close(); # Generate list of all groups, with people as 2nd dimension in list groups=[]; for entry in fileRaw: groups.append(entry.split()) # Initialize lists (will be entry for each group) totals=[] totalAllYes=[] # For every group for grp in groups: # Create set with any question which someone answered # And dictionary with total yes answers for each question ansYes=set(); ansCnt=defaultdict(lambda: 0) for person in grp: for ques in person: ansYes.add(ques) ansCnt[ques]+=1 # Length of set is total questions with Yes answers # Append to group list totals.append(len(ansYes)) # Look through answer count dictionary and # flag questions everyone answered yes to allYes=0 for k in ansCnt: if ansCnt[k]==len(grp): allYes+=1 # Append all-yes question total to group list totalAllYes.append(allYes) print("The solution to part A is {0:d}".format(np.sum(totals))) print("The solution to part B is {0:d}".format(np.sum(totalAllYes)))
03c6c087d523f5e9eb20a802ef44704e91a5a28e
AliceZhang2017/display-data
/Guess_Number.py
710
3.890625
4
# coding: utf-8 # In[5]: from random import randint def guess_number(): def ask_num(message): try: value= int(input(message)) except ValueError as e: print("You put a bad number", e) return value start_num = ask_num("Input the start number ") Stop_num = ask_num("Input the stop number ") m = ask_num("Guess a number ") g = randint(start_num,Stop_num) for i in range(20): if m > g: print("Your number is large than the random number") elif m==g: print("You are right!") break else: print("Your number is less than the random number") guess_number() # In[ ]:
9525fa2af336020611333f6425e04efb62140ae9
yuninje/Algorithm_Solve
/Data Structure & Algorithm/[ AL ] Merge Sort.py
849
3.890625
4
def swap(arr, a, b): temp = arr[a] arr[a] = arr[b] arr[b] = temp def merge_sort(arr, si, ei): if si == ei-1: return [arr[si]] mi = (si + ei) // 2 # Devide left = merge_sort(arr, si, mi) right = merge_sort(arr, mi, ei) li = 0 li_max = mi - si ri = 0 ri_max = ei - mi result = [] # Combine while li != li_max and ri != ri_max: if left[li] < right[ri]: result.append(left[li]) li += 1 else: result.append(right[ri]) ri += 1 for i in range(li,li_max): result.append(left[i]) for i in range(ri,ri_max): result.append(right[i]) return result arr = [1,3,4,2,5,7,6] print('Merge Sort !') print('before : ' + str(arr)) result = merge_sort(arr, 0, len(arr)) print('after : ' + str(result))
99da214613218c07bc9e2fd11d47b5b44fd8b8d1
t-lane/tabula-rasa_project-euler
/problems/TLane_solutions/problem_002.py
775
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 15 12:56:54 2018 Problem 2: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Answer: 4613732 @author: tlane """ #Form the Finonacci sequence fib = [1,2,3] n = fib[len(fib)-1] while n: n = fib[len(fib)-1] + fib[len(fib)-2] if n > 4000000: break fib.append(n) #Sum the even valued terms evenFib = list() for n in fib: if n % 2 == 0: evenFib.append(n) sumEvenFib = sum(evenFib) print(sumEvenFib)
800f0713174b4d1dac9a3f6ce601bc8329c4d0b6
S8001023456/Python_Practice
/work_for_python/start_with_'a'/a038.py
540
3.59375
4
while True: try: number = int(input()) numlist = [] all_zero = True while number > 0: restnum = number % 10 numlist.append(restnum) number //= 10 for i in numlist: if i != 0: all_zero = False if all_zero == True: print("0") while numlist[0] == 0: numlist.pop(0) for i in numlist: print(i, end = "", sep = "") print() except: break
0abe640bcff2c05f25737bff7726c8c6733c4e98
sinegami301194/Python-HSE
/7 week/sinonyms.py
171
3.734375
4
N = int(input()) myDict = {} for i in range(N): f_word, s_word = input().split() myDict[f_word] = s_word myDict[s_word] = f_word print(myDict[input()])
f608054233eaee54aca03a73559005a3256ad2b8
fernandez-matt/backend-interview
/mfWeightingAlgorithm.py
6,905
3.578125
4
import json import math import random from flask import Flask, request, jsonify app = Flask(__name__) app.config["DEBUG"] = True @app.route("/results") def getBestCandidates(): ''' Runs the Weighting Algorithm to determine the top 10 candidates for the hospital to reach out Parameters: None. Location is passed in via the api Returns: JSON list of the top 10 candidates and their information in ranked order ''' lat = request.args.get('lat') lon = request.args.get('lon') #error checking that a location is provided try: facilityLocation = [float(lat),float(lon)] except: return "ERROR: please provide facility location as lat and lon in valid number format" #error checking that the latitude and longitude values are on solid ground (or water) if abs(float(lat)) > 90.0: return "ERROR: latitude value is not on earth" if abs(float(lon)) > 180.0: return "ERROR: longitude value is not on earth" fullList = getScoredandSortedList(facilityLocation) return jsonify(fullList[:10]) def getScoredandSortedList(location): ''' Takes the facility's location and returns the list of all patients in order most likely to be served NOTE: behavioralDataAmountCutoff and behavioralDataChance are below and can be adjusted based on desired number of patients who have little behavior data to be added to the top of the list Parameters: location(list of two floats) - facility location Returns: sortedPatientData(List of Dicts) - a list of all patients in patients.json ordered by their score as determined by the weighting algorithm ''' with open("patients.json") as jsonData: patientData = json.load(jsonData) for patient in patientData: patientLon = float(patient['location']['longitude']) patientLat = float(patient['location']['latitude']) distanceToClinic = getDistance([patientLat, patientLon],location) patient['distanceToClinic'] = distanceToClinic featureScaledPatientData = featureScaling(patientData) for patient in featureScaledPatientData: patientScore = getPatientScore(patient,location) patient['score'] = patientScore normalizedPatientData = normalizeScores(patientData) behavioralDataAmountCutoff = 20 #number of interactions to quality for bumping to the top of the Line behavioralDataChance = .5 #chance to be selected and put on the top of the list for patient in normalizedPatientData: behavioralScore = patient['acceptedOffers'] + patient['canceledOffers'] if behavioralScore < behavioralDataAmountCutoff: if random.random() <= behavioralDataChance: patient['score'] = 10.1 #with more time would make a flag for being a behavioral data choice and then update the key function to automatically put those people first sortedPatientData = sorted(patientData, reverse = True, key = lambda a: a['score']) return sortedPatientData def featureScaling(patientData): ''' Takes the patient data and and adds features to each patient for their normalized value between 0 and 1. This means the weighting algorithm will not be biased by the scale of the input features Parameters: patientData(List of Dicts) - a list of all patients and their information Returns: patientData(List of Dicts) - a list of all patients and their information with added key and values for their normalized features. ''' for feature in ['age','distanceToClinic','acceptedOffers','canceledOffers','averageReplyTime']: newFeature = 'normalized' + feature highValue = -10000.0 lowValue = 10000.0 #find the highest and lowest Values for patient in patientData: currentValue = patient[feature] if currentValue > highValue: highValue = currentValue if currentValue < lowValue: lowValue = currentValue for patient in patientData: currentValue = patient[feature] #normalize from 0-1 newValue = (currentValue - lowValue)/(highValue-lowValue) patient[newFeature] = newValue return patientData def getPatientScore(patient,location): ''' Generates a score for a given patient based on their data and the location of the facility being quereied Parameters: patient(Dict) - Patients information in key-value pairs location(List of two floats) - facility location Returns: score(float) - score represents the likelihood of coming to the clinic based on the weighting algorithm ''' # patientLon = float(patient['location']['longitude']) # patientLat = float(patient['location']['latitude']) # distanceToClinic = getDistance([patientLat, patientLon],location) score = patient['normalizedage']*.1 #postively correlated score -= patient['normalizeddistanceToClinic']*.1 #negatively correlated score += patient['normalizedacceptedOffers']*.3 #positively correlated score -= patient['normalizedcanceledOffers']*.3 #negatively correlated score -= patient['normalizedaverageReplyTime']*.2 #negatviely correlated return score def getDistance(patient, clinic): ''' Provides the distance between two locations based on their latitude and longitude Parameters: patient(list of two floats) - patient location clinic(list of two floats) - facility location Returns: distance(float) - distance between the two locations ''' pLon = float(patient[1]) pLat = float(patient[0]) cLat = float(clinic[0]) cLon = float(clinic[1]) distance = math.sqrt(((pLon-cLon)**2)+((pLat-cLat)**2)) return distance def normalizeScores(patientData): ''' Adjusts the scores for each patient to be normalized 1-10 based on the likelihood to come to the clinic Parameters: patientData(List of Dicts) - a list of all patients and their information Returns: patientData(List of Dicts) - a list of all patients with their scores normalized ''' highScore = -10000.0 lowScore = 10000.0 #find the highest and lowest scores for patient in patientData: currentScore = patient['score'] if currentScore > highScore: highScore = currentScore if currentScore < lowScore: lowScore = currentScore for patient in patientData: currentScore = patient['score'] #normalize from 0-1 newScore = (currentScore - lowScore)/(highScore-lowScore) #normalize from 1-10 newScore = (newScore * 9) +1 patient['score'] = newScore return patientData # Consider adding more complex weighting if I have time if __name__ == '__main__': app.run(debug=True)
98d17f7d89119cb40c3c1fbcee3d9850840b4794
AnneLivia/ICCP-USP
/trianguloClass.py
1,649
3.828125
4
class Triangulo: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def perimetro(self): return self.a + self.b + self.c def tipo_lado(self): if (self.a == self.b) and (self.a != self.c) or (self.a == self.c) and (self.a != self.b) or (self.c == self.b) and (self.b != self.a): return "isósceles" elif (self.a == self.b and self.a == self.c): return "equilátero" else: return "escaleno" def retangulo(self): if self.a > self.b and self.a > self.c: h = self.a c1 = self.b c2 = self.c elif self.b > self.a and self.b > self.c: h = self.b c1 = self.a c2 = self.c else: h = self.c c1 = self.a c2 = self.b if (h ** 2) == ((c1 ** 2) + (c2 ** 2)): return True else: return False def semelhantes(self, triangulo): if((self.a * 2) == triangulo.a) or (self.a == (triangulo.a * 2)) and ((2 * triangulo.b) == self.b) or ((2 * self.b) == triangulo.b) and ((2 * triangulo.c) == self.c) or ((2 * self.c) == triangulo.c): return True elif(self.a == triangulo.a and self.b == triangulo.b and self.c == triangulo.c): return True else: return False def main(): t = Triangulo(3,4,5) t2 = Triangulo(3,4,5) print("Retangulo: ", t.retangulo()) print("Tipo de triângulo: ", t.tipo_lado()) print("t == t2 ?", t.semelhantes(t2)) # print("%d %d %d: perimetro: %d"%(t.a,t.b,t.c,t.perimetro()))
7513fce03d6334ea3c559f3ab2d22dabbd1a9331
Ryan-Karanja/Learn-Pyhton-The-Hard-Way
/webDev/ex5.py
536
3.65625
4
my_name = 'Zed A. Shaw' my_age = 15 # not a lie my_height = 71 # inches my_weight = 235 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print("Let's talk about Ryan.") print("He's 67 inches tall.") print("He's 235 pounds heavy.") print("Actually that's not too heavy.") print("He's got brown eyes and black hair.") print("His teeth are usually white depending on the coffee.") # this line is tricky, try to get it exactly right total = my_age + my_height + my_weight print("If I add 15, 71, and 235 I get" , total)
b50db45b3af5f1a3cd2874dece1ca70405eecff7
leetking/leetcode
/algorithms/python3/001/two-sum.py
574
3.515625
4
#!/usr/bin/env python class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ table = {} for idx, num in enumerate(nums): rest = target - num if rest in table: return [table[rest], idx] table[num] = idx # not found return [-1, -1] if __name__ == '__main__': target = int(input()) nums = [int(x) for x in input().split()] ret = Solution().twoSum(nums, target) print(ret)
dc56dc1f50b5fdfd5a70ae2854aa32e4c72cfa93
bgoonz/UsefulResourceRepo2.0
/_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/strings/check_pangram.py
254
4.28125
4
""" Algorithm that checks if a given string is a pangram or not """ def check_pangram(input_string): alphabet = "abcdefghijklmnopqrstuvwxyz" for ch in alphabet: if ch not in input_string.lower(): return False return True
cea36aa73c82b975db8b217dc0e099ac8c3c2137
ayushpantpp/practice_python
/check_element_exists.py
248
3.8125
4
import sys arr = [22,2,3,2,3,4,5,6] def check_if_element_exist(arr): cnt = 0; n = int(input()) for i in arr: if(i == n): cnt = cnt + 1; print cnt print "Element %s, is repeated %s times!" % (n , cnt) check_if_element_exist(arr)
940de78426edb725d3d3711939af38c9dffdab47
DnTo/MisionTIC_Dnto
/Semana 2/Clase 2/identificarCuadrado.py
325
3.96875
4
# pedirle al usuario el ancho y el alto de un rectángulo y decirle si es cuadrado ancho = int(input("Por favor ingrese el ancho del rectángulo: ")) alto = int(input("Por favor ingrese el alto del rectángulo: ")) if ancho == alto: print("El rectángulo es cuadrado") else: print("El rectángulo no es cuadrado")
9b97ff57d8ae3747baeb3f8e49be562e63111123
dlcarterjr/python-functions
/only_odds.py
609
4.25
4
## Accepts a list of numbers as an argument and returns a new list that includes only the odd numbers. number_list = [11, 20,42, 97, 23, 10] ## Define a list of numbers for input. odd_list = [] ## Define a new list for the even numbers "odd_list". ## Define a function that takes the list as an argument. def get_odds(list): for number in list: ## Loop that iterates through the list. if number % 2 != 0: ## Check to see if current number is even. odd_list.append(number) ## If its even, append to the new list. return odd_list print(f'\n{get_odds(number_list)}\n')
70171098f09d4ee27e8384e3bc3d95e0be2ac74b
sny-tanaka/practicePython
/Practice/su-gaku.net/2017_grade1/problem4.py
578
3.59375
4
# coding: utf-8 ''' 問題冊子は以下 https://www.su-gaku.net/common/pdf/support_sample/question/1q_q_1ji.pdf ''' from sympy import * def main(): # A^3 A, B, x = symbols('A B x') A = Matrix(([3, 0, 2], [-4, 1, -3], [1, 5, -2])) B = Matrix(([3-x, 0, 2], [-4, 1-x, -3], [1, 5, -2-x])) A3 = expand(det(B))+x**3 print(A3) # A^5 - 5A^4 + 16A^3 - 24A^2 A4 = expand(A3*x) fn = expand((x**2)*A3 - 5*x*A3 + 16*A3 - 24*(x**2)) fn = fn.replace('x**4', A4) fn = fn.replace('x**3', A3) print(fn) if __name__ == '__main__': main()
63baa0c75948d78424d07cc862ba4781b8bb3b35
ilkeryaman/learn_python
/pandas/pandas7.py
1,553
3.71875
4
import pandas as pd from introduction.modules.printer_module import pretty_print dataset1 = { "A": ["A1", "A2", "A3", "A4"], "B": ["B1", "B2", "B3", "B4"], "C": ["C1", "C2", "C3", "C4"] } dataset2 = { "A": ["A5", "A6", "A7", "A8"], "B": ["B5", "B6", "B7", "B8"], "C": ["C5", "C6", "C7", "C8"] } df1 = pd.DataFrame(dataset1, index=[1, 2, 3, 4]) df2 = pd.DataFrame(dataset2, index=[5, 6, 7, 8]) pretty_print(df1) pretty_print(df2) pretty_print(pd.concat([df1, df2])) # works based on index pretty_print(pd.concat([df1, df2], axis=1)) dataset1 = { "A": ["A1", "A2", "A3", "A4"], "B": ["B1", "B2", "B3", "B4"] } dataset2 = { "X": ["X1", "X2", "X3"], "Y": ["Y1", "Y2", "Y3"] } df1 = pd.DataFrame(dataset1, index=[1, 2, 3, 4]) df2 = pd.DataFrame(dataset2, index=[1, 2, 3]) pretty_print(df1) pretty_print(df2) pretty_print(df1.join(df2)) # join works like left-join (works based on index) pretty_print(df2.join(df1)) dataset1 = { "A": ["A1", "A2", "A3"], "B": ["B1", "B2", "B3"], "key": ["K1", "K2", "K3"] } dataset2 = { "X": ["X1", "X2", "X3", "X4"], "Y": ["Y1", "Y2", "Y3", "Y4"], "key": ["K1", "K2", "K3", "K4"] } df1 = pd.DataFrame(dataset1, index=[1, 2, 3]) df2 = pd.DataFrame(dataset2, index=[1, 2, 3, 4]) pretty_print(df1) pretty_print(df2) pretty_print(df1.merge(df2)) # merges according to key (automatically) (works like an inner-join) pretty_print(pd.merge(df1, df2, on=["key"])) # outer join etc. can be applied by changing 'how' parameter
0c77f52182a7367a4b31ef94143fe86bc9f6cb95
chrisxue815/leetcode_python
/problems/test_0273.py
2,027
3.71875
4
import unittest _digits = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', ] _ten_sth = [ 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', ] _tens = [ '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety', ] def _to_words(words, nums): before_len = len(words) if nums[2] > 0: words.append(_digits[nums[2]]) words.append('Hundred') if nums[1] == 1: words.append(_ten_sth[nums[0]]) else: if nums[1] != 0: words.append(_tens[nums[1]]) if nums[0] != 0: words.append(_digits[nums[0]]) return before_len != len(words) class Solution: def numberToWords(self, num): """ :type num: int :rtype: str """ if num == 0: return 'Zero' words = [] nums = [0] * 12 i = 0 while num > 0: num, nums[i] = divmod(num, 10) i += 1 if _to_words(words, nums[9:]): words.append('Billion') if _to_words(words, nums[6:9]): words.append('Million') if _to_words(words, nums[3:6]): words.append('Thousand') _to_words(words, nums[:3]) return ' '.join(words) class Test(unittest.TestCase): def test(self): self._test(123, 'One Hundred Twenty Three') self._test(12345, 'Twelve Thousand Three Hundred Forty Five') self._test(1234567, 'One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven') self._test(0, 'Zero') self._test(10000000, 'Ten Million') self._test(10000001, 'Ten Million One') def _test(self, num, expected): actual = Solution().numberToWords(num) self.assertEqual(expected, actual) if __name__ == '__main__': unittest.main()
c13c39846e843267bc73b5388123e8970ee69050
emccann3/PythonExamples
/tags.py
271
3.5
4
from urllib.request import urlopen from bs4 import BeautifulSoup url = input('Enter: ') html = urlopen(url).read() soup = BeautifulSoup(html, "html.parser") tag = soup("span") sum=0 count=0 for i in tag: x=int(i.text) count+=1 sum = sum + x print (count) print (sum)
2fcab3d02338443bf9efc866cd877eb24392a24a
bplank/cog-sci-1-2014
/ex1-nn/nn.py
1,436
3.75
4
#!/usr/bin/env python ## nearest neighbor classifier import numpy as np import sys def train(X,y,distance): # what does it mean to train a NN model? # ... model=[X,y,distance] return model def predict(testInst,model): # get info from model (later we will use a class rather than this way) labels=model[1] instances=model[0] d=model[2] # compare ... distances=np.array([computeDistance(testInst,instance,d) for instance in instances]) print >>sys.stderr, distances idx_argmin=np.argmin(distances) return labels[idx_argmin] def computeDistance(inst1,inst2,d): if d=="euclidean": return np.sqrt(np.sum((inst1-inst2)**2)) elif d=="manhattan": return np.sum(np.abs(inst1-inst2)) else: raise Exception("invalid distance") def main(): # toy example 0=spam, 1=non-spam labelNames = ["spam","non-spam"] # training data: trainInstances = np.array([[0,1,0],[1,0,0],[1,0,1]]) trainLabels = np.array([0, 1, 1]) # test data: testInstance = np.array([0,1,1]) # hyper-parameters #distance="euclidean" distance="manhattan" # train model model = train(trainInstances,trainLabels,distance) # predict label for test point pred = predict(testInstance,model) # print model and prediction print model print "predicted:", pred, labelNames[pred] if __name__=="__main__": main()
0cf8dabae652848b5d0ac46fd753e0ee977630ee
AjayMistry29/pythonTraining
/Extra_Task_Data_Structure/ETQ8.py
831
4.1875
4
even_list=[] odd_list=[] while True: enter_input = int(input("Enter a number from from 1 to 50: ")) if enter_input>=1 and enter_input<=50 and (enter_input % 2) != 0 and len(odd_list)<5: odd_list.append(enter_input) print("Odd List :" ,odd_list) continue elif enter_input>=1 and enter_input<=50 and (enter_input % 2) == 0 and len(even_list)<5: even_list.append(enter_input) print("Even List :" ,even_list) else: print("Entered Number is out of range") break print("Sum of Even Numbers List is :", sum(even_list)) print("Sum of Odd Numbers List is :", sum(odd_list)) print("Maximum number from Even List is :", max(even_list)) print("Maximum number from Odd List is :", max(odd_list))
9678287474bd5346fe6f3db4944da7ac79eb4a14
ZaighumRajput/pythonPractice
/fileSearch/old/filesearchfl.py
479
3.53125
4
#!/usr/bin/python3 #not python3 compatiable... import click @click.command() @click.option('--text') @click.option('--folder', default=__file__) def folder_search(folder, text): pass def file_search(filename, search_text): pass @click.command() @click.option('--count', default=1) @click.option('--name', prompt='Your name') def hello(count, name): for x in range(count): click.echo("Hello {}".format(name)) if __name__ == '__main__': folder_search()
d6aa7f525117837ed2f7e1c7951510e7a08486ea
gbjuno/coreprogramming
/chapter6/6-8.py
2,810
3.640625
4
#!/usr/bin/env python def singleBase(numToEngMap,numStr): return numToEngMap[numStr] def tenBase(numToEngMap,numStr): if numToEngMap.has_key(numStr[-2:]): numToEng = "%s" % numToEngMap[numStr[-2:]] else: numToEng = "%s-%s" % (numToEngMap[numStr[-2]+'0'],numToEngMap[numStr[-1]]) return numToEng def hundredBase(numToEngMap,numStr): numToEng_ten = tenBase(numToEngMap,numStr) numToEng_hundred = numToEngMap[numStr[-3]] if numToEng_ten and numToEng_hundred != 'zero': numToEng = "%s hundred and %s" % (numToEng_hundred,numToEng_ten) elif numToEng_hundred != 'zero': numToEng = "%s hundred" % numToEng_hundred elif numToEng_ten: numToEng = "%s" % numToEng_ten else: numToEng = '' return numToEng def thousandBase(numToEngMap,numStr): numToEng_hundred = hundredBase(numToEngMap,numStr) numToEng_thousand = numToEngMap[numStr[-4]] if numToEng_hundred: numToEng = "%s thousand and %s" % (numToEng_thousand,numToEng_hundred) else: numToEng = "%s thousand" % numToEng_thousand return numToEng def transToEng(number): numToEngMap = {'0':'zero','00':'', '1':'one','01':'one', '2':'two','02':'two', '3':'three','03':'three', '4':'four','04':'four', '5':'five','05':'five', '6':'six','06':'six', '7':'seven','07':'seven', '8':'eight','08':'eight', '9':'nine','09':'nine', '10':'ten', '11':'eleven', '12':'twelve', '13':'thirteen', '14':'fourteen', '15':'fifteen', '16':'sixteen', '17':'seventeen', '18':'eighteen', '19':'nineteen', '20':'twenty', '30':'thirty', '40':'forty', '50':'fifty', '60':'sixty', '70':'seventy', '80':'eighty', '90':'ninty'} numStr = str(number) if len(numStr) == 1: numToEng = singleBase(numToEngMap,numStr) elif len(numStr) == 2: numToEng = tenBase(numToEngMap,numStr) elif len(numStr) == 3: numToEng = hundredBase(numToEngMap,numStr) elif len(numStr) == 4: numToEng = thousandBase(numToEngMap,numStr) print "the number in English : %s " % numToEng return def main(): userInput = raw_input("input number : ") try: transToEng(int(userInput)) except Exception as e: print e print "Input is not a valid Integer" if __name__ == '__main__': main()
9f2156a0e6b22a3d71531d6e2aa826e82213c858
nbvc1003/python
/ch04_5/bit.py
276
3.578125
4
a = 17 # 0000 1100 b = 61 # 0011 1101 # and 의 의미 & 하나는 bit 연산자 print(a & b) # or 연산 print (a | b) # xor 연산 print (a ^ b) print( a and b) # 1100 print( a or b) # 111101 a = 12 print(a << 2) print(a >> 2) # if a and b : # print("true")
95c59bc81003ce277870739f37870b0c2751a951
Harini-32/NA1-p2
/socketclient.py
1,047
3.578125
4
import socket def client_messages(filename,client_socket): while True: if filename == "bye from client-harini": client_socket.send(str.encode(filename)) data=str(client_socket.recv(1024).decode()) print(data) if(data == "Bye from Server"): break else: filename=input('send another message --> ') filename=filename.lower() elif filename == "hello from client-harini": client_socket.send(str.encode(filename)) data=str(client_socket.recv(1024).decode()) print(data) filename=input("send another message -->") filename=filename.lower() else: client_socket.send(str.encode(filename)) data=str(client_socket.recv(1024).decode()) print(data) filename=input("Enter standard messages -->") filename=filename.lower() def main(): client_socket=socket.socket() client_socket.connect((socket.gethostname(),1234)) filename=input("Enter message here -->") filename=filename.lower() client_messages(filename,client_socket) client_socket.close() if __name__== "__main__": main()
8e4264dc028b3ddc0cb88b525c87d1bbfda39e19
aabarbosa/python
/.py/17.py
126
3.734375
4
x = int(raw_input()) y = int(raw_input()) if x>y: print 'Campinense' elif x==y: print 'Empate' else: print 'Treze'
8fd3d799debaa06676b2549c25b1769df7d3e188
27629678/python_tutorial
/12_random_walk.py
2,559
3.90625
4
import random def random_walk(n): """return coordinates after 'n' block random walk.""" x = 0 y = 0 for i in range(n): step = random.choice(['N', 'S', 'E', 'W']) if step == 'N': y += 1 elif step == 'S': y -= 1 elif step == 'E': x += 1 else: x -= 1 return (x, y) def random_walk2(n): x, y = 0, 0 for i in range(n): (dx, dy) = random.choice([(0, 1), (1, 0), (0, -1), (-1, 0)]) x += dx y += dy return (x, y) # for i in range(25): # walk = random_walk2(10) # print(walk, " Distance from home = ", abs(walk[0]) + abs(walk[1])) # Monte Carlo Simulation number_of_walks = 10000 for walk_length in range(1, 31): no_transport = 0 for i in range(number_of_walks): (x, y) = random_walk2(walk_length) distance = abs(x) + abs(y) if distance <= 4: no_transport += 1 no_transport_percentage = float(no_transport) / number_of_walks print("Walk size: {0} / no_transport: {1} = {2}".format(walk_length, no_transport, no_transport_percentage*100)) # Walk size: 1 / no_transport: 100000 = 1.0 # Walk size: 2 / no_transport: 100000 = 1.0 # Walk size: 3 / no_transport: 100000 = 1.0 # Walk size: 4 / no_transport: 100000 = 1.0 # Walk size: 5 / no_transport: 87843 = 0.87843 # Walk size: 6 / no_transport: 93725 = 0.93725 # Walk size: 7 / no_transport: 76385 = 0.76385 # Walk size: 8 / no_transport: 86185 = 0.86185 # Walk size: 9 / no_transport: 67186 = 0.67186 # Walk size: 10 / no_transport: 79278 = 0.79278 # Walk size: 11 / no_transport: 59784 = 0.59784 # Walk size: 12 / no_transport: 72947 = 0.72947 # Walk size: 13 / no_transport: 53868 = 0.53868 # Walk size: 14 / no_transport: 67373 = 0.67373 # Walk size: 15 / no_transport: 48942 = 0.48942 # Walk size: 16 / no_transport: 62278 = 0.62278 # Walk size: 17 / no_transport: 44657 = 0.44657 # Walk size: 18 / no_transport: 58020 = 0.5802 # Walk size: 19 / no_transport: 41256 = 0.41256 # Walk size: 20 / no_transport: 54370 = 0.5437 # Walk size: 21 / no_transport: 38283 = 0.38283 # Walk size: 22 / no_transport: 51049 = 0.51049 # Walk size: 23 / no_transport: 35522 = 0.35522 # Walk size: 24 / no_transport: 48130 = 0.4813 # Walk size: 25 / no_transport: 33394 = 0.33394 # Walk size: 26 / no_transport: 45604 = 0.45604 # Walk size: 27 / no_transport: 31010 = 0.3101 # Walk size: 28 / no_transport: 42921 = 0.42921 # Walk size: 29 / no_transport: 29343 = 0.29343 # Walk size: 30 / no_transport: 40598 = 0.40598
85b382fb8c489c23ba1084c2b8216449bb1a61db
srp2210/PythonBasic
/dp_w3resource_solutions/tuple/6_tuple_to_string.py
273
3.734375
4
""" * @author: Divyesh Patel * @email: pateldivyesh009@gmail.com * @date: 03/06/20 * @decription: Write a Python program to convert a tuple to a string. """ friends_tup = 'divyesh', 'preet', 'sagar', 'fantyo' final_str = '' for each in friends_tup: final_str += ' ' + each print(final_str)
212e99002335891c4ba0e1ebb23d711ecb22ec07
tseiiti/curso_em_video
/mundo_2/ex043.py
768
3.734375
4
from os import system, name system('cls' if name == 'nt' else 'clear') dsc = ('''DESAFIO 043: Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule o IMC e mostre seu status, de acordo com a tabela abaixo: - Abaixo de 18.5: Abaixo do Peso - Entre 18.5 e 25: Peso ideal - 25 até 30: Sobrepeso - 30 até 40: Obesidade - Acima de 40: Obesidade mórbida ''') n1 = float(input('Digite sua altura: ')) n2 = float(input('Digite seu peso: ')) # converte centimetro em metros if n1 > 100: n1 = n1 / 100 imc = n2 / n1 ** 2 print('Seu IMC é {:.2f}'.format(imc)) if imc < 18.5: print('Abaixo do Peso') elif imc <= 25: print('Peso ideal') elif imc <= 30: print('Sobrepeso') elif imc <= 40: print('Obesidade') else: print('Obesidade mórbida')
9e03f91762f50188951bc9b47c2f26e5ff305974
dannyfraser/advent-of-code-2020
/day-2/solution.py
1,239
3.578125
4
import re with open("inputs.txt") as f: inputs = f.readlines() test_inputs = [ "1-3 a: abcde", "1-3 b: cdefg", "2-9 c: ccccccccc" ] pattern = r"(\d+)\-(\d+) (.)\: (.*)" def solve_1(inputs, pattern): valid_passwords = 0 for i in inputs: match = re.search(pattern, i) if match: lower = int(match.groups()[0]) upper = int(match.groups()[1]) letter = match.groups()[2] password = match.groups()[3] if lower <= password.count(letter) <= upper: valid_passwords += 1 return(valid_passwords) assert solve_1(test_inputs, pattern) == 2 print(solve_1(inputs, pattern)) def solve_2(inputs, pattern): valid_passwords = 0 for i in inputs: match = re.search(pattern, i) if match: position_1 = int(match.groups()[0]) - 1 position_2 = int(match.groups()[1]) - 1 letter = match.groups()[2] password = match.groups()[3] # XOR if (password[position_1]==letter) ^ (password[position_2]==letter): valid_passwords += 1 return(valid_passwords) assert solve_2(test_inputs, pattern) == 1 print(solve_2(inputs, pattern))
3de729581b17913f716697b21a352141f8a9fe56
miguelrivas/mithras
/python/tutorials/helloworld.py
425
3.78125
4
#!/usr/bin/python total_cats = raw_input('How many cats do you have? ') boy_cats = raw_input('How many of your cats are boys? ') girl_cats = raw_input('How many of your cats are girls? ') total_cats_calculated = int(boy_cats) + int(girl_cats) if int(total_cats) != (total_cats_calculated): print ('You made a counting error') else: print ('Good counting! You have a total of ' + str(total_cats_calculated) +' cats!')
4f3de968c15b3e831480e078ac1718267ce758ff
starrye/LeetCode
/探索/中级算法/数组和字符串/矩阵置零.py
1,621
3.9375
4
# encoding: utf-8 """ @Project : @File: 矩阵置零.py @Author: liuwz @time: 2022/1/10 5:51 下午 @desc: """ from typing import List """ 给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。   示例 1: 输入:matrix = [[1,1,1],[1,0,1],[1,1,1]] 输出:[[1,0,1],[0,0,0],[1,0,1]] 示例 2: 输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]   提示: m == matrix.length n == matrix[0].length 1 <= m, n <= 200 -231 <= matrix[i][j] <= 231 - 1   进阶: 一个直观的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。 你能想出一个仅使用常量空间的解决方案吗? """ class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rows, cols = len(matrix), len(matrix[0]) zeros = set() for row in range(rows): for col in range(cols): if matrix[row][col] == 0: zeros.add((row, col)) for i, j in zeros: begin = 0 while begin < rows: matrix[begin][j] = 0 begin += 1 begin = 0 while begin < cols: matrix[i][begin] = 0 begin += 1 return matrix a = Solution().setZeroes([[1,1,1],[1,0,1],[1,1,1]]) print(a)
cfa42c401004026267e9ef145587afddff6d8390
gabriellaec/desoft-analise-exercicios
/backup/user_195/ch49_2019_03_19_20_31_07_827305.py
169
4.0625
4
numero=int(input("Diga um número inteiro")) i=1 L=[numero] while numero>0: L.append(numero) numero=int(input("Diga outro número inteiro")) L.reverse() print(L)
0f7397eb97fdd47f81c9dd2f01737ec484c1e126
terencesll/AdventOfCode
/2020/01b.py
352
3.5
4
file = open("01.txt") seen = set() requiredSumEntry = 2020 for line in file: entry = int(line) for seenEntry in seen: supplement = requiredSumEntry - entry - seenEntry if supplement in seen: print("{} {} {} {}".format(entry, seenEntry, supplement, entry*seenEntry*supplement)) break seen.add(entry)
f04cc83a73838a7b879bee8f723d95eb181eee20
henryxian/leetcode
/add_two_numbers.py
1,052
3.828125
4
# Add Two Numbers # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ def getNum(l): base = 1 sum = 0 while l != None: # sum = sum * base + l.val sum = sum + l.val * base base = base * 10 l = l.next return sum def genLinkedList(str): dummy = ListNode(None) for s in str: node = ListNode(int(s)) node.next = dummy.next dummy.next = node return dummy.next if l1 == None or l2 == None: return None else: num1 = getNum(l1) num2 = getNum(l2) num = num1 + num2 return genLinkedList("".join((str(num))))
eaea5ef07c1a7bea954edc2ab1f2ebc1ab68caab
ayeungturtle/hashTables_python
/hashTables.py
664
3.90625
4
def assignIndex(input): myHash=0 for char in input: myHash+=ord(char) myHash %= 5; return myHash myList = [[],[],[],[],[]] def addToHash(key,value): index = assignIndex(key) global myList myList[index].append([key,value]) addToHash('app',345) addToHash('no',3140) addToHash('bab',223) addToHash('tookeymeister',333) addToHash('biblebelt',223) addToHash('man',222) addToHash('woman',923) addToHash('booger',999) # print(myList) def find(key): index = assignIndex(key) global myList for entry in myList[index]: if (entry[0] == key): return entry[1] return "entry not found" print(find('boogery')) print(find('biblebelt'))
2a63c5018cedaaa16f08ce627f0ececa8b8a1930
whlkw/python-learn
/control.py
418
3.609375
4
words = ['cat', 'window', 'defenestrate'] for item in words: print(item) myList = list(range(5)) print(type(myList), myList) for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n//x) break else: print(n, 'is a prime') #while loop count = 10 while count < 100: if count % 10 == 0: print(count, 'can be devidied by 10') count = count + 1
830fcc1215ffeea495947ab961d5ff92b3f34d1f
OgnyanPenkov/Programming0-1
/week3/2-Resolve-with-Functions/solutions/is_perfect.py
547
3.78125
4
def divisors(n): result = [] start = 1 end = n - 1 while start <= end: if n % start == 0: result = result + [start] start += 1 return result def sum_ints(numbers): result = 0 for number in numbers: result += number return result def sum_divisors(n): return sum_ints(divisors(n)) def is_perfect(n): return sum_divisors(n) == n n = input("Enter n: ") n = int(n) if is_perfect(n): print(str(n) + " is perfect!") else: print(str(n) + " is not perfect!")
6a7815e74d6708b1363315eb995f99adc9cf0f79
Jtonna/Intro-Python-I
/src/14_cal.py
2,193
4.5625
5
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py month [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar from datetime import datetime # If the user doesnt pass any argument in it just returns the calendar for their current year and month if len(sys.argv) == 1: theMonth = datetime.now().month theYear = datetime.now().year print(calendar.month(theYear, theMonth)) quit() # If the user passes in the month, we shall assume the year they want is the current calendar year elif len(sys.argv) == 2: theMonth = int(sys.argv[1]) theYear = datetime.now().year print(calendar.month(theYear, theMonth)) quit() # If the user passes in a month and year, we give them what they want. elif len(sys.argv) == 3: theMonth = int(sys.argv[1]) theYear = int(sys.argv[2]) print(calendar.month(theYear, theMonth)) quit() # If the user passes in more than 3 arguments we give them a usage statement elif len(sys.argv) > 3: print("****USAGE**** \n This program will do one of three things \n 1. If it is ran it will return the current calendar for your month & year \n 2. It will accept you passing in a month in the format of [01] without brackets, and will assume the year you want is the current year \n 3. you can pass in a month in the format of [01] and a year in the format of [1999]. ex [02 1999] but without brackets. It will return the celandar for the respective monthand year. ")
240120b0a448509680ba92eee0cae2b59ecde9c6
Bgumel/Automate-The-Boring-Stuff
/Practice-Projects/Ch 13 - Custom Invitations as Word Documents
2,164
3.671875
4
#! python3 # invitations.py - Will import a txt file with a list of names then # generate a Word document with a specific invitation style """ We need to make some syntax changes here for the program to work. In order to add a page break, you first need to import WD_BREAK from docx.enum.text Then, after a run, type .add_break(break_type=WD_BREAK.PAGE) There are more breaks, but this is all we need for this program. I believe Automate The Boring Stuff has older info that is outdated for this feature """ import docx from docx.enum.text import WD_BREAK doc = docx.Document('invitation.docx') # When you open your guest file you need to open it with read() to read each line # Then, split each line with a new line so you can run a for loop with each name names = open('guests.txt') names = names.read() names = names.split(sep='\n') # If you are following through with the chapter, this stuff should be fairly easy. Way easier # than the last couple of projects we have been working on. You will have to guess the style # that he wants you to have since it's not written down. The part of this program you may forget # is that you need to first create the a style in the word document, then open the document so # you can use them. My 'invitation.docx' document is blank, but I have styles saved # You'll end up saving it to a new document (Note my new name is plural) # Your style names will be different than mine most likely, so make sure you keep it the same # as your specific word document. If your document doesn't look like it should but you think your # program is correct, check the default settings on your Word. I had to adjust mine to make # it look correct. for name in names: doc.add_paragraph('It would be a pleasure to have the company of').style = 'inviteStyleLine1' doc.add_paragraph(name).style = 'Name' doc.add_paragraph('at 11010 Memory Lane on the Evening of').style = 'inviteStyleLine2' doc.add_paragraph('April 1st').style = 'invitedate' date_line = doc.add_paragraph('at 7 o\'clock') date_line.runs[0].add_break(break_type=WD_BREAK.PAGE) date_line.style = 'inviteStyleLine2' doc.save('invitations.docx')
41aeac28dcbfd65a68bcda38b7b5ba602a1c23b1
PaulJoshi/hospital_management_system
/core/patients.py
3,773
3.5
4
import pickle import datetime class Patient : def __init__(self): self.name = "" self.age = None self.gender = "" def create_user(self,age,gender) : ''' Adds a new patient to "/database/patients.pkl" in database ''' self.age = age self.gender = gender patient = [self.name, self.age, self.gender] with open("database/patients.pkl", "rb") as file: all_patients = pickle.load(file) all_patients.append(patient) with open("database/patients.pkl", "wb") as file: pickle.dump(all_patients, file) def patient_exists(self) : ''' Returns 1 if patient already exists, else, returns 0 ''' with open("database/patients.pkl", "rb") as file: all_patients = pickle.load(file) for patient in all_patients: if patient[0].lower() == self.name.lower(): return 1 return 0 def get_doctors(self, specialization) : ''' Returns list of doctors with specified specialization ''' doctors = [] with open("database/doctors.pkl", "rb") as file : all_doctors = pickle.load(file) for doctor in all_doctors: if doctor[1].lower() == specialization.lower() : doctors.append(doctor) if len(doctors) == 0: return 0 return doctors def make_appointment(self, doctor, date) : ''' Adds an appointment to "/database/appointments.pkl" in database ''' if date == 1: a = datetime.datetime.today() current_date = a.day, a.month, a.year appointment = [doctor, self.name, current_date] elif date == 2: b = datetime.datetime.today() next_date = b.day + 1, b.month, b.year appointment = [doctor, self.name, next_date] elif date == 3: c = datetime.datetime.today() next_next_date = c.day + 2, c.month, c.year appointment = [doctor, self.name, next_next_date] else: return 0 with open("database/appointments.pkl", "rb") as file : appointments=pickle.load(file) with open("database/appointments.pkl", "wb") as file : appointments.append(appointment) pickle.dump(appointments, file) return 1 def update_user(self,name, age) : ''' Changes the details of given user in "/database/patients.pkl" in database ''' with open("database/patients.pkl", "rb") as file: patients = pickle.load(file) for patient in patients: if patient[0].lower() == self.name.lower(): patient[0] = name patient[1] = age with open("database/patients.pkl", "wb") as file: pickle.dump(patients,file) with open("database/appointments.pkl", "rb") as file: appointments = pickle.load(file) for appointment in appointments: if appointment[1].lower() == self.name.lower(): appointment[1] = name with open("database/appointments.pkl", "wb") as file: pickle.dump(appointments, file) self.name = name self.age = age def get_appointments(self) : ''' Get all appointments of given patient name ''' appointments = [] with open("database/appointments.pkl", "rb") as file: all_appointments = pickle.load(file) for appointment in all_appointments: if appointment[1].lower() == self.name.lower(): appointments.append(appointment) return appointments
e7a40496373d45af0d449f2606c5e31c95170637
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/171/48542/submittedfiles/testes.py
253
3.78125
4
# -*- coding: utf-8 -*- import math #COMECE AQUI ABAIXO n=int(input('digite n:')) atual=int(input('digite atual:')) cont=0 for i in range(2,n,1): prox=int(input('digite prox:')) if atual!=prox: cont=cont+1 atual=prox print(cont)
473f15fae818bf66714016a867afed89890c1b04
peltierchip/the_python_workbook_exercises
/chapter_3/exercise_82.py
536
4.40625
4
## #Determine the corresponding binary number #Read the decimal number from the user decimal_number=input("Enter the decimal number :\n") result="" q=int(decimal_number) #Check if q is greater or equal than 0 if q>=0: r=q%2 result=str(r)+result q=q//2 #Keep looping while q is not equal to 0 while q!=0: r=q%2 result=str(r)+result q=q//2 #Display the result print("The corresponding binary number is %s."%result) else: print("The decimal number entered isn't valid.\n")