blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
dfc14297ca445802ff7bedce07bebaecf903231c
Beebkips/UWTCodingDojo
/Beginner - Python, Pygame/Lesson 1 - My first game/mygame.py
1,691
3.859375
4
""" One step movement of ball object """ import pygame pygame.init() run = True # background screen = pygame.display.set_mode((640,480)) screenrect = screen.get_rect() background = pygame.Surface(screen.get_size()) background.fill((255,255,255)) background = background.convert() # ball ballsurface = pygame.Surface((50,50)) ballsurface.set_colorkey((0,0,0)) pygame.draw.circle(ballsurface, (0,0,255), (25, 25), 25) ballsurface = ballsurface.convert_alpha() ballrect = ballsurface.get_rect() x = 550 y = 240 # blank surface blanksurface = pygame.Surface((50,50)) blanksurface.fill((255, 255, 255)) screen.blit(background, (0,0)) screen.blit(ballsurface, (x, y)) pygame.display.flip() while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # pygame window closed by user """ Add this section here to check what direction the users has moved and then draw the ball moving in that direction. Talk about how the graphics grid works in relation to x and y coordinates. """ elif event.type == pygame.KEYDOWN: # draw blank surface to erase ball screen.blit(blanksurface, (x, y)) if event.key == pygame.K_ESCAPE: run = False if event.key == pygame.K_UP: y = y - 10 if event.key == pygame.K_DOWN: y = y + 10 if event.key == pygame.K_LEFT: x = x - 10 if event.key == pygame.K_RIGHT: x = x + 10 # draw ball and update screen screen.blit(ballsurface, (x, y)) pygame.display.flip() pygame.quit()
373bbd7975453f2177a1959128af6bb066437440
FaridWaid/sms4-kuliah-komputasinumerik
/simpson13.py
702
4.0625
4
# Mendefinisikan fungsi agar menjadi integral def f(x): return 1/(1 + x**2) def simpson(a,b,n): # mencari nilai h h = (b - a) / n # Mencari jumlah sementara integrasi = f(a) + f(b) for i in range(1,n): k = a + i*h if i%2 == 0: integrasi = integrasi + 2 * f(k) else: integrasi = integrasi + 4 * f(k) # mendapatkan nilai akhir perhitungan integrasi = integrasi * h/3 return integrasi a = float(input("Masukkan Batas bawah: ")) b = float(input("Masukkan Batas atas: ")) n = int(input("Masukkan Jumlah interval n: ")) hasil = simpson(a, b, n) print("Hasil Integrasi= %0.6f" % (hasil) )
72554c4c493e46952747b4efa7ce8b8578f6e436
ParkerCM/csci1133-python
/lab4.py
2,478
3.5625
4
import turtle import random def mul(a, b): count = 0 product = 0 if a < b: limit = a num = b else: limit = b num = a while count < limit: product += num count += 1 print(product) def race(): def distance(): return random.randint(1, 15) def winner(): turtle.hideturtle() turtle.penup() turtle.goto(700, 200) if redTurtle.xcor() >= 1950: turtle.write('Red Wins', font=('Arial', 36)) elif blueTurtle.xcor() >= 1950: turtle.write('Blue Wins', font=('Arial', 36)) elif greenTurtle.xcor() >= 1950: turtle.write('Green Wins', font=('Arial', 36)) turtle.setworldcoordinates(0, 0, 2000, 400) turtle.penup() turtle.hideturtle() redTurtle = turtle.Turtle() redTurtle.penup() redTurtle.hideturtle() redTurtle.goto(10, 100) redTurtle.shape('turtle') redTurtle.color('red') redTurtle.showturtle() blueTurtle = turtle.Turtle() blueTurtle.penup() blueTurtle.hideturtle() blueTurtle.goto(10, 200) blueTurtle.shape('turtle') blueTurtle.color('blue') blueTurtle.showturtle() greenTurtle = turtle.Turtle() greenTurtle.penup() greenTurtle.hideturtle() greenTurtle.goto(10, 300) greenTurtle.shape('turtle') greenTurtle.color('green') greenTurtle.showturtle() while redTurtle.xcor() < 1950 and blueTurtle.xcor() < 1950 and greenTurtle.xcor() < 1950: redTurtle.forward(distance()) blueTurtle.forward(distance()) greenTurtle.forward(distance()) winner() turtle.exitonclick() def checkerboard(): def drawSquare(): turtle.begin_fill() turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.end_fill() turtle.setworldcoordinates(0, 0, 800, 800) turtle.speed(0) turtle.bgcolor('red') turtle.hideturtle() turtle.penup() xnum = 0 ynum = 0 while ynum < 8: while xnum < 4: drawSquare() turtle.forward(200) xnum += 1 if ynum % 2 == 0: turtle.left(90) turtle.forward(200) turtle.left(90) else: turtle.right(180) ynum += 1 xnum = 0 turtle.exitonclick()
dc3e6a8b1df43a62c035a38c49e86d37ad07a898
Ast3risk-ops/My-Stuff
/list_input.py
195
3.859375
4
grocery = [] while True: item = input("What item would you like to add to your list? > ") grocery.append(item) if item == "": grocery.remove(item) break print(grocery)
713009979001d667357fbc357a84e78c74b51ba2
Cassidyyan/sorting-_algirithms
/merge_sort.py
1,376
4.5
4
# merge sort algorithm # divide and conquer algorithm, once broken down, compares indexes and merges back into one array # recursive function, calls itself to keep dividing itself till size becomes one def merge_sort(arr): # this whole chunk breaks down the array if len(arr) > 1: # finds the mid of the array mid = len(arr) // 2 # break the list into 2 halves left = arr[:mid] right = arr[mid:] # calling itself to divide even further left = merge_sort(left) right = merge_sort(right) arr = [] # copying data to temp arrays while len(left) > 0 and len(right) > 0: # checking if left index is smaller, if it is I want to remove from original array and place it as the # first thing on my new array if left[0] < right[0]: arr.append(left[0]) left.pop(0) else: # if the right index was smaller arr.append(right[0]) right.pop(0) # forming the array with a for loop by iterating it for i in left: arr.append(i) for i in right: arr.append(i) return arr # Input list a = [12, 11, 13, 5, 6, 7] print("Given array is") print(*a) a = merge_sort(a) # Print output print("Sorted array is : ") print(*a)
8e6ffaab5667566004c127a873d6fae4cd90c768
hoshinotsuki/DataStructures_Algorithms
/interviewcake/balanced_binary_tree.py
3,366
3.96875
4
import unittest # TODO: better to use DFS as it reaches to a leaf easier than BFS def is_balanced(root): # BFS nodes = [root] children = [] min_depth = None depth = 0 while len(nodes) > 0: current = nodes.pop(0) if not min_depth: if not current.left and not current.right: min_depth = depth else: if depth > min_depth + 1: return False if current.left: children.append(current.left) if current.right: children.append(current.right) # Go to next depth if len(nodes) == 0: nodes = children children = [] depth += 1 return True class Test(unittest.TestCase): class BinaryTreeNode: def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = Test.BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = Test.BinaryTreeNode(value) return self.right def test_full_tree(self): tree = Test.BinaryTreeNode(5) left = tree.insert_left(8) right = tree.insert_right(6) left.insert_left(1) left.insert_right(2) right.insert_left(3) right.insert_right(4) result = is_balanced(tree) self.assertTrue(result) def test_both_leaves_at_the_same_depth(self): tree = Test.BinaryTreeNode(3) left = tree.insert_left(4) right = tree.insert_right(2) left.insert_left(1) right.insert_right(9) result = is_balanced(tree) self.assertTrue(result) def test_leaf_heights_differ_by_one(self): tree = Test.BinaryTreeNode(6) left = tree.insert_left(1) right = tree.insert_right(0) right.insert_right(7) result = is_balanced(tree) self.assertTrue(result) def test_leaf_heights_differ_by_two(self): tree = Test.BinaryTreeNode(6) left = tree.insert_left(1) right = tree.insert_right(0) right_right = right.insert_right(7) right_right.insert_right(8) result = is_balanced(tree) self.assertFalse(result) def test_three_leaves_total(self): tree = Test.BinaryTreeNode(1) left = tree.insert_left(5) right = tree.insert_right(9) right.insert_left(8) right.insert_right(5) result = is_balanced(tree) self.assertTrue(result) def test_both_subtrees_superbalanced(self): tree = Test.BinaryTreeNode(1) left = tree.insert_left(5) right = tree.insert_right(9) right_left = right.insert_left(8) right.insert_right(5) right_left.insert_left(7) result = is_balanced(tree) self.assertFalse(result) def test_only_one_node(self): tree = Test.BinaryTreeNode(1) result = is_balanced(tree) self.assertTrue(result) def test_linked_list_tree(self): tree = Test.BinaryTreeNode(1) right = tree.insert_right(2) right_right = right.insert_right(3) right_right.insert_right(4) result = is_balanced(tree) self.assertTrue(result) unittest.main(verbosity=2)
9ede6aece473b6ce865a8a05acde5e9f28c720ec
drylynch/garfieldtextadventure
/garfield.py
29,242
4
4
# why am i doing this """ TODO maybe do * make in pygame ? """ import os import platform import collections """ text based clone of garfield, released pc and ps2, 2004 by hip games garfield has to clean the house up cause odie fucked it or something move garfield around the house with his trusty vacuum cleaner and put items back where they belong can suck up stray items and blow them back to their rightful place, or store them in save boxes for later max of 3 items in the vacuum at any one time, max of 20 items in each save box """ # ---------------------------------------- class Junk: """ an item that sits in a room, to be sucked up or blown """ def __init__(self, junk_id, junk_name): """ :param int junk_id: unique junk id :param str junk_name: readable name for display """ self._id = junk_id # int self._name = junk_name # str def __str__(self): # main reason why junk is a class: can just print each object and get a nice string return "[{_id}] {_name}".format(**self.__dict__) @property def id(self): return self._id @property def name(self): return self._name class Room: """ a room, with some loose junk, and some ghosts of junk that need to be filled """ def __init__(self, room_id, room_name, loose_junk, ghost_junk, doors, my_key, rewards_key, has_savebox, savebox_capacity): """ :param int room_id: unique room id :param str room_name: readable name for display :param list loose_junk: junk ids, items to be sucked up :param list ghost_junk: junk ids, items to be put back :param list doors: room ids, adjacent rooms :param Room or None my_key: require this Room to be complete to unlock, or always unlocked (None) :param bool rewards_key: true if room rewards a key upon completion :param bool has_savebox: true if room has a savebox :param int savebox_capacity: max items for this rooms savebox (irrelevant if room has no savebox) """ self._id = room_id self._name = room_name self._loose_junk = ChunkyTrunk(loose_junk, ALLJUNKS) self._ghost_junk = ChunkyTrunk(ghost_junk, ALLJUNKS) self._doors = doors self._my_key = my_key self._rewards_key = rewards_key self._has_savebox = has_savebox if has_savebox: self._savebox = SimpleTrunk(savebox_capacity) else: self._savebox = None def __str__(self): if self.unlocked(): string_id = self._id string_name = self._name else: # locked doors are mysteries string_id = '?' string_name = 'LOCKED' return "[{0}] {1}".format(string_id, string_name) def create_obj_references(self): """ must be called after /all/ rooms created converts doors from a list of room ids to dict with items (room_id: Room obj) converts room's key from room_id to Room obj with that id """ self._doors = {room_id: ALLROOMS[room_id] for room_id in self._doors} if self._my_key: # just for rooms that have keys self._my_key = ALLROOMS[self._my_key] def unlocked(self): """ true if room is unlocked, duh """ if self._my_key is None: # no key needed return True return self._my_key.needs_complete() # doors are unlocked when their keygivers are complete def place_in_room(self, junk): """ add an item to the room in it's ghostly place """ self._ghost_junk.remove(junk) def still_needs(self, junk): """ true if room still needs junk """ return self._ghost_junk.contains(junk) def get_needs(self, junk_id): """ return ghost junk with given id, None if not found """ return self._ghost_junk.get(junk_id) def all_junk_needs(self): """ return list of all items a room still needs """ return self._ghost_junk.contents() def needs_complete(self): """ return true if no more ghost items (room is complete) """ return self._ghost_junk.is_empty() def take_from_room(self, junk): """ remove a loose item from the room """ self._loose_junk.remove(junk) def has_loose(self, junk): """ true if room has junk lying around """ return self._loose_junk.contains(junk) def all_junk_loose(self): """ return all items a room has lying around """ return self._loose_junk.contents() def get_loose(self, junk_id): """ return loose junk with given id, None if not found """ return self._loose_junk.get(junk_id) def loose_complete(self): """ true if no more loose objects """ return self._loose_junk.is_empty() @property def id(self): return self._id @property def name(self): return self._name @property def doors(self): return self._doors @property def rewards_key(self): return self._rewards_key @property def has_savebox(self): return self._has_savebox @property def savebox(self): return self._savebox class Player: """ you! """ def __init__(self, player_name, starting_room, vacuum_capacity): """ :param str player_name: cool name :param Room starting_room: room the player begins in :param int vacuum_capacity: how much stuff the player can hold at once """ self._name = player_name self._location = starting_room self._vacuum = SimpleTrunk(vacuum_capacity) def __str__(self): return self._name def vacuum_full(self): """ true if vacuum is at capacity """ return self._vacuum.is_full() def vacuum_empty(self): """ true if vacuum is empty """ return self._vacuum.is_empty() def vacuum_contains(self, junk): """ true if vacuum contains junk """ return self._vacuum.contains(junk) def vacuum_contents(self): """ return list of junk in vacuum """ return self._vacuum.contents() def vacuum_get(self, junk_id): """ get junk obj with junk_id from vacuum, None if not found """ return self._vacuum.get(junk_id) def move(self, room): """ moves the player's current location to given Room """ self._location = room def suck(self, junk): """ suck up an item from the current room to vacuum """ self._location.take_from_room(junk) # take from room self._vacuum.insert(junk) # give to vacuum def blow(self, junk): """ blow an item from vacuum to the current room """ self._vacuum.remove(junk) # take from vacuum self._location.place_in_room(junk) # give to room def drop(self, junk): """ drop an item in the savebox of the current room """ self._vacuum.remove(junk) # take from vacuum self._location.savebox.insert(junk) # give to savebox def grab(self, junk): """ grab an item out of the savebox in the current room """ self._location.savebox.remove(junk) # take from savebox self._vacuum.insert(junk) # give to vacuum @property def location(self): return self._location class _BaseTrunk: """ dict-based item container to map an object to its corresponding id, eg (obj.id: obj) requires object to have id attribute to be used as key """ def __init__(self): self._contents = {} def get(self, obj_id): """ return obj with the given id, or None if not found """ return self._contents.get(obj_id, None) def contents(self): """ return list of objs """ return self._contents.values() def contains(self, obj): """ return true if contains obj """ return obj.id in self._contents def remove(self, obj): """ yank something out """ del self._contents[obj.id] def is_empty(self): return self.length() == 0 def length(self): return len(self._contents) class SimpleTrunk(_BaseTrunk): """ small, limited, user-interactable Trunk holds only junk objects can insert and remove items used for player vacuum and saveboxes """ def __init__(self, capacity): """ :param int capacity: max number of items that can be held by this trunk """ super().__init__() self._capacity = capacity def is_full(self): """ true if at capacity """ return self.length() == self._capacity def insert(self, junk): """ plop something in """ self._contents[junk.id] = junk class ChunkyTrunk(_BaseTrunk): """ large, unlimited, pre-filled Trunk holds both junk and room objects can only remove items used to reflect room state and doors """ def __init__(self, contents_keys, contents_map): """ :param list contents_keys: keys to map onto values :param dict contents_map: map of (key: value) to use for lookup """ super().__init__() self._contents = {key: contents_map[key] for key in contents_keys} def prompt_input_both(): """ ask user for input and return (action, choice) if they're valid: action | str, len 1 | eg 'm' choice | int, len 1+ | eg '13' both | str+int, len2+ | eg 'm13' only returns just action or both, not just choice (that's what prompt_input_choice() is for) missing choice is replaced with None return (None, None) on completely invalid input """ s = input(INPUT_PROMPT).strip() if s: if not is_int(s): # make sure it's not just choice if len(s) == 1: return s, None # is just action else: first = s[0] # should be action second = s[1:] # should be choice if not is_int(first) and is_int(second): return first, int(second) # is both return None, None def prompt_input_choice(question): """ like prompt_input_both() but just gets a choice, asks a question, and loops until the user gives a valid answer """ if question: # just print once print(question + ' (back: [{0}])'.format(INPUT_QUIT_CHAR)) # let user know they can back out while True: s = input(INPUT_PROMPT).strip() if s: if s == INPUT_QUIT_CHAR: return INPUT_QUIT_CHAR # return quit char so game loop knows to go back elif is_int(s): return int(s) def prompt_continue(message=None): """ customisable continue prompt given no message, will print default msg given a message, will print that followed by the default msg """ default = '[enter] continue... ' if message is None: input(default) else: input(INPUT_PROMPT + message + '\n' + default) def is_int(s): """ true if int, false otherwise """ try: int(s) return True except ValueError: return False def game_is_finished(): """ return true if all rooms are complete, else false """ for room in ALLROOMS.values(): if not room.needs_complete(): # any room is incomplete, not done return False return True # all rooms complete, game is finished def get_clearcmd(): """ returns the command to clear the screen on the current os """ if platform.system() == 'Windows': return 'cls' return 'clear' def init(): """ start her up boys """ savebox_cap = 20 RoomData = collections.namedtuple('RoomData', ['name', 'loose_junk', 'ghost_junk', 'doors', 'my_key', 'rewards_key', 'has_savebox', 'savebox_capacity']) junk = {100: '10kg Weight', # id: name 101: 'Alarm Clock', 102: 'Animal Bed', 103: 'Barbell', 104: 'Baseball', 105: 'Bathroom Scales', 106: 'Beef', 107: 'Birdhouse', 108: 'Bongo', 109: 'Boomerang', 110: 'Boots', 111: 'Box of Apples', 112: 'Box of Detergent', 113: 'Bucket', 114: 'Bunny Slipper', 115: 'Bunny Trophy', 116: 'Buzzsaw', 117: 'Candlebra', 118: 'Car Jack', 119: "Catcher's Mitt", 120: 'Cheese', 121: 'Chess Board', 122: 'Clock', 123: 'Computer Screen', 124: 'Conditioner', 125: 'Cookie Jar', 126: 'Cushion', 127: 'DVD Player', 128: 'Dart', 129: 'Desk Lamp', 130: 'Disco Trophy', 131: 'Egg Basket', 132: 'Fertilizer', 133: 'Fish Bowl', 134: 'Fish Decoration', 135: 'Flowerpot', 136: 'Fruit Bowl', 137: 'Fuse', 138: 'Globe', 139: 'Gramophone', 140: 'Green Plate', 141: 'Guitar', 142: 'Hose Nozzle', 143: 'Hot Water Bottle', 144: 'Jar of Peppers', 145: 'Kitchen Scales', 146: 'Lamp', 147: 'Large Pumpkin', 148: 'Laundry Basket', 149: 'Lei', 150: 'Magazine Rack', 151: 'Magic 8-Ball', 152: 'Mailbox', 153: 'Maraca', 154: 'Neck Vase', 155: "Odie's Bowl", 156: 'Oil Can', 157: 'Pasta Sauce', 158: 'Patio Light', 159: 'Phone', 160: 'Photo of Garfield', 161: 'Piggy Bank', 162: 'Pinata', 163: 'Pool Cue', 164: 'Power Drill', 165: 'Power Sander', 166: 'RC Car', 167: 'Radio', 168: 'Red Book', 169: 'Red Hat', 170: 'Remote', 171: 'Roller Blade', 172: 'Round Picture Frame', 173: 'Rubber Duck', 174: 'Shampoo', 175: 'Sheet Pasta', 176: 'Sombrero', 177: 'Spare Tire', 178: 'Speaker', 179: 'Stereo', 180: 'Stretch the Chicken', 181: 'Tie', 182: 'Tissue Box', 183: 'Toaster', 184: 'Toilet Brush', 185: 'Towel', 186: 'Toy Car', 187: 'Trash Bin', 188: 'Trumpet', 189: 'Vase', 190: 'Video Game', 191: 'Vinyl Record', 192: 'Waste Paper Basket', 193: 'Water Valve'} rooms = {1: RoomData(name='Living Room', loose_junk=[110, 130, 136, 140, 160, 186], # list of int junk ids ghost_junk=[126, 127, 133, 150, 160, 170, 178], # list of int junk ids doors=[2, 5], # list of int room ids my_key=None, # int room id, or None rewards_key=True, # just to show notification to player that they got a key when they complete this room has_savebox=False, savebox_capacity=None), 2: RoomData(name='Kitchen', loose_junk=[120, 123, 133, 135, 149, 153, 168, 184, 192], ghost_junk=[106, 120, 125, 131, 136, 140, 144, 145, 157, 167, 175, 183], doors=[1, 4, 3, 9], my_key=None, rewards_key=False, has_savebox=False, savebox_capacity=None), 3: RoomData(name='Downstairs Hallway', loose_junk=[141, 148, 178, 182], ghost_junk=[122, 168, 172, 182], doors=[5, 2, 12, 6], my_key=None, rewards_key=False, has_savebox=True, savebox_capacity=savebox_cap), 4: RoomData(name='Utility Room', loose_junk=[112, 113, 159, 172], ghost_junk=[102, 110, 112, 113, 148], doors=[12, 2, 11], my_key=None, rewards_key=True, has_savebox=False, savebox_capacity=None), 5: RoomData(name='Den', loose_junk=[102, 115, 138, 146, 185], ghost_junk=[115, 123, 129, 130, 138, 192], doors=[1, 3], my_key=None, rewards_key=True, has_savebox=False, savebox_capacity=None), 6: RoomData(name='Upstairs Landing', loose_junk=[117, 129, 187, 191], ghost_junk=[117, 146, 154, 189], doors=[12, 3, 7, 8, 10, 14, 13], my_key=None, rewards_key=True, has_savebox=False, savebox_capacity=None), 7: RoomData(name='Master Bedroom', loose_junk=[108, 114, 122, 126, 143, 170, 176], ghost_junk=[101, 114, 143, 159, 179, 181, 187], doors=[6], my_key=5, rewards_key=True, has_savebox=False, savebox_capacity=None), 8: RoomData(name='Small Bedroom', loose_junk=[127, 145, 150, 151, 154, 188], ghost_junk=[108, 141, 149, 153, 162, 176], doors=[6], my_key=4, rewards_key=True, has_savebox=False, savebox_capacity=None), 9: RoomData(name='Basement', loose_junk=[101, 106, 121, 161, 162, 166, 180, 189], ghost_junk=[100, 103, 137, 171, 188, 193], doors=[2], my_key=1, rewards_key=True, has_savebox=True, savebox_capacity=savebox_cap), 10: RoomData(name='Games Room', loose_junk=[107, 137, 144, 156, 179, 181], ghost_junk=[121, 128, 151, 161, 163, 186, 190, 191], doors=[6], my_key=6, rewards_key=True, has_savebox=True, savebox_capacity=savebox_cap), 11: RoomData(name='Garage', loose_junk=[128, 132, 142, 169, 171, 183], ghost_junk=[116, 118, 156, 164, 165, 166, 177], doors=[4], my_key=7, rewards_key=True, has_savebox=False, savebox_capacity=None), 12: RoomData(name='Gardens', loose_junk=[100, 103, 111, 116, 124, 131, 139, 157, 163, 165, 174, 175, 190, 193], ghost_junk=[107, 132, 135, 142, 147, 152, 155, 158], doors=[3, 4, 15, 6], my_key=8, rewards_key=False, has_savebox=False, savebox_capacity=None), 13: RoomData(name='Bathroom', loose_junk=[109, 118, 119, 147, 152, 167], ghost_junk=[105, 124, 134, 173, 174, 184, 185], doors=[6], my_key=9, rewards_key=False, has_savebox=False, savebox_capacity=None), 14: RoomData(name='Attic', loose_junk=[105, 125, 134, 155, 158, 164, 177], ghost_junk=[104, 109, 119, 139, 169, 180], doors=[6], my_key=10, rewards_key=False, has_savebox=False, savebox_capacity=None), 15: RoomData(name='Greenhouse', loose_junk=[104, 173], ghost_junk=[111], doors=[12], my_key=11, rewards_key=False, has_savebox=False, savebox_capacity=None)} # fill the big dicts of junks and rooms for (jid, name) in junk.items(): # each = (junk_id, name) ALLJUNKS[jid] = Junk(jid, name) for (rid, r) in rooms.items(): # each = (room_id, rdata(name, loose_junk, ghost_junk, doors, key, has_seedbox)) ALLROOMS[rid] = Room(rid, r.name, r.loose_junk, r.ghost_junk, r.doors, r.my_key, r.rewards_key, r.has_savebox, r.savebox_capacity) for room in ALLROOMS.values(): # swap lists of room ids for lists of room objects, after all rooms are created room.create_obj_references() # constants accessed by functions above, can't be in init() or main() INPUT_PROMPT = '>>> ' INPUT_QUIT_CHAR = 'x' ALLJUNKS = {} ALLROOMS = {} # ---------------------------------------- def main(): init() clearcmd = get_clearcmd() player = Player('garfield', ALLROOMS[1], 3) # start room 1 # tutorial time print(""" THE YEAR IS 2004. you are garfield. you gotta clean the house. use your vacuum cleaner to move items around. suck up loose items, and blow them into their proper place (their 'ghost'). you can only hold 3 items at a time. you can store items in saveboxes for later, though. select choices by typing commands in the square brackets. eg: to [m]ove, type >>> m to [s]uck up this item: [69] Cool Shades >>> s >>> 69 or, all at once >>> s69 -> suck up item 69 >>> m13 -> move to room 13 not many rooms are open to start with. some rooms may reward keys when they're completed... god speed. """) prompt_continue() while not game_is_finished(): # game loop thisroom = player.location # for convenience room_has_savebox = thisroom.has_savebox # instead of calling 3 times nicelinelen = 20 + len(thisroom.name) os.system(clearcmd) # description of room and player state # gross but concise print('=' * nicelinelen) print('| you are in the {0}'.format(thisroom.name), end='') print('\n| connected rooms: ', end='') print(*thisroom.doors.values(), sep=', ') print('-' * nicelinelen) print('| your vacuum: ', end='') if player.vacuum_empty(): print('- empty -') else: print(*player.vacuum_contents(), sep=', ') if room_has_savebox: print('| savebox: ', end='') if thisroom.savebox.is_empty(): print('- empty -') else: print(*thisroom.savebox.contents(), sep=', ') print('-' * nicelinelen) print('| loose items:', end='\n|\t') print(*thisroom.all_junk_loose(), sep='\n|\t') print('| ghost items:', end='\n|\t') if thisroom.needs_complete(): if thisroom.rewards_key: print('- room complete! you found a KEY! -') else: print('- room complete! -') else: print(*thisroom.all_junk_needs(), sep='\n|\t') print('-' * nicelinelen) # print actions print("you can:\n", "\t[m]ove to another room\n", "\t[s]uck up a loose item\n", "\t[b]low an item to it's correct place") if room_has_savebox: print("\t[d]rop something in the savebox\n", "\t[g]rab something from the savebox") # get action and choice action, choice = prompt_input_both() if action is None: # nothing entered continue # pretend it didn't happen and ask again # move room elif action == 'm': if choice is None: # get choice if user didn't give it already choice = prompt_input_choice('where do you want to go?') if choice == INPUT_QUIT_CHAR: # quit, return to top of gameloop continue room = thisroom.doors.get(choice, None) # doors is still just a dict (for now) if room is not None: if room.unlocked(): player.move(room) else: prompt_continue("LOCKED: you don't have the key for that room...") else: prompt_continue("NOPE: that rooms isn't connected to this one!") # suck up item elif action == 's': if player.vacuum_full(): # too much succ prompt_continue('NOPE: you have no room for items! blow or drop what you have first.') elif thisroom.loose_complete(): # nothing to succ prompt_continue('NOPE: there are no items here to suck up! there must be some elsewhere...') else: if choice is None: choice = prompt_input_choice('what item do you want to suck up?') if choice == INPUT_QUIT_CHAR: continue junk = thisroom.get_loose(choice) if junk is not None: player.suck(junk) # ;^) else: prompt_continue("NOPE: that item isn't in the room!") elif action == 'b': if player.vacuum_empty(): # nothing to blow prompt_continue('NOPE: you have no items! suck some up first.') elif thisroom.needs_complete(): # room doesn't need any items prompt_continue('NOPE: this room is complete! there must be other rooms that need items...') else: if choice is None: choice = prompt_input_choice('what item do you want to blow down?') if choice == INPUT_QUIT_CHAR: continue junk = player.vacuum_get(choice) if junk is not None: # choice in vacuum if thisroom.still_needs(junk): # choice has ghost in room player.blow(junk) # ;^)))) else: prompt_continue("NOPE: this room doesn't need that item!") else: prompt_continue("NOPE: you don't have that item!") elif room_has_savebox: if action == 'd': if player.vacuum_empty(): # nothing to drop prompt_continue('NOPE: you have no items! suck some up first.') elif thisroom.savebox.is_full(): # no room to drop prompt_continue('NOPE: this savebox is full! grab some items from it first, or find another box.') else: if choice is None: choice = prompt_input_choice('what item do you want to drop into the savebox?') if choice == INPUT_QUIT_CHAR: continue junk = player.vacuum_get(choice) if junk is not None: player.drop(junk) # :^( ? else: prompt_continue("NOPE: you don't have that item!") elif action == 'g': if player.vacuum_full(): # no room for items prompt_continue("NOPE: your vacuum is full! drop some off first.") elif thisroom.savebox.is_empty(): # nothing to grab prompt_continue("NOPE: this savebox is empty! drop some items in first.") else: if choice is None: choice = prompt_input_choice('what item do you want to grab from the savebox?') if choice == INPUT_QUIT_CHAR: continue junk = thisroom.savebox.get(choice) if junk is not None: player.grab(junk) # :o) else: prompt_continue("NOPE: that item isn't in this savebox!") # win os.system(clearcmd) print('\n\n\n\t\tcongratz {0}, u did it yahoo'.format(player)) input('\n\n\t\tpress enter to exit') if __name__ == '__main__': main()
299ded98a59a3b5693d9527df8de9e4a2b7503ba
mikelitoluistro/python-scripting
/Class.py
728
3.625
4
class character: name = "Name" hp = 100 mp = 50 atk = 12 lvl = 1 characterOne = character() characterOne.name = "Miki" characterOne.hp = 150 characterOne.mp = 80 characterOne.atk = 50 characterOne.lvl = 8 characterTwo = character() characterTwo.name = "yssa" characterOne.hp = 150 characterOne.mp = 80 characterOne.atk = 55 characterOne.lvl = 10 characterThree = character() print(characterOne.name, characterOne.hp) print(characterTwo.name) print(character.name) class product: id = 1 name = "name" price = 20 qty = 10 productOne = product() productOne.id = 3 productOne.name = "milk" productOne.price = 40 productOne.qty = 3 print(productOne)
0f817cc81829eb1de9821697e2de5cd538ed055b
lt910702lt/python
/day02/02 作业讲解.py
907
3.84375
4
# 9题:输入12个月份,对应12种输出 mounth = input("请输入对应月份: ") if mounth == '一月': print("一月") if mounth == '二月': print("二月") if mounth == '三月': print("三月") if mounth == '四月': print("四月") if mounth == '五月': print("五月") if mounth == '六月': print("六月") if mounth == '七月': print("七月") if mounth == '八月': print("八月") if mounth == '九月': print("九月") if mounth == '十月': print("十月") if mounth == '十一月': print("十一月") if mounth == '十二月': print("十二月") ''' # 10题 a = int(input("请输入你的分数: ")) if a < 0: print("请输入合法数字") elif a > 100: print("请输入合法数字") elif a >= 90: print("A") elif a >= 80: print("B") elif a >= 70: print("C") elif a >= 60: print("D") else: print("E") '''
9bbec1ea854e21164b920c638c50610351d15656
ShaoboZhang/CS6601
/Assignment3/probability_tests.py
6,655
3.8125
4
import unittest from Assignment3.submission import * """ Contains various local tests for Assignment 3. """ class ProbabilityTests(unittest.TestCase): #Part 1a def test_network_setup(self): """Test that the power plant network has the proper number of nodes and edges.""" power_plant = make_power_plant_net() nodes = power_plant.nodes() self.assertEqual(len(nodes), 5, msg="incorrect number of nodes") total_links = power_plant.number_of_edges() self.assertEqual(total_links, 5, msg="incorrect number of edges between nodes") #Part 1b def test_probability_setup(self): """Test that all nodes in the power plant network have proper probability distributions. Note that all nodes have to be named predictably for tests to run correctly.""" # first test temperature distribution power_plant = set_probability(make_power_plant_net()) T_node = power_plant.get_cpds('temperature') self.assertTrue(T_node is not None, msg='No temperature node initialized') T_dist = T_node.get_values() self.assertEqual(len(T_dist), 2, msg='Incorrect temperature distribution size') test_prob = T_dist[0] self.assertEqual(round(float(test_prob*100)), 80, msg='Incorrect temperature distribution') # then faulty gauge distribution F_G_node = power_plant.get_cpds('faulty gauge') self.assertTrue(F_G_node is not None, msg='No faulty gauge node initialized') F_G_dist = F_G_node.get_values() rows, cols = F_G_dist.shape self.assertEqual(rows, 2, msg='Incorrect faulty gauge distribution size') self.assertEqual(cols, 2, msg='Incorrect faulty gauge distribution size') test_prob1 = F_G_dist[0][1] test_prob2 = F_G_dist[1][0] self.assertEqual(round(float(test_prob2*100)), 5, msg='Incorrect faulty gauge distribution') self.assertEqual(round(float(test_prob1*100)), 20, msg='Incorrect faulty gauge distribution') # faulty alarm distribution F_A_node = power_plant.get_cpds('faulty alarm') self.assertTrue(F_A_node is not None, msg='No faulty alarm node initialized') F_A_dist = F_A_node.get_values() self.assertEqual(len(F_A_dist), 2, msg='Incorrect faulty alarm distribution size') test_prob = F_A_dist[0] self.assertEqual(round(float(test_prob*100)), 85, msg='Incorrect faulty alarm distribution') # gauge distribution # can't test exact probabilities because # order of probabilities is not guaranteed G_node = power_plant.get_cpds('gauge') self.assertTrue(G_node is not None, msg='No gauge node initialized') [cols, rows1, rows2] = G_node.cardinality self.assertEqual(rows1, 2, msg='Incorrect gauge distribution size') self.assertEqual(rows2, 2, msg='Incorrect gauge distribution size') self.assertEqual(cols, 2, msg='Incorrect gauge distribution size') # alarm distribution A_node = power_plant.get_cpds('alarm') self.assertTrue(A_node is not None, msg='No alarm node initialized') [cols, rows1, rows2] = A_node.cardinality self.assertEqual(rows1, 2, msg='Incorrect alarm distribution size') self.assertEqual(rows2, 2, msg='Incorrect alarm distribution size') self.assertEqual(cols, 2, msg='Incorrect alarm distribution size') try: power_plant.check_model() except: self.assertTrue(False, msg='Sum of the probabilities for each state is not equal to 1 or CPDs associated with nodes are not consistent with their parents') #Part 2a Test def test_games_network(self): """Test that the games network has the proper number of nodes and edges.""" games_net = get_game_network() nodes = games_net.nodes() self.assertEqual(len(nodes), 6, msg='Incorrect number of nodes') total_links = games_net.number_of_edges() self.assertEqual(total_links, 6, 'Incorrect number of edges') # Now testing that all nodes in the games network have proper probability distributions. # Note that all nodes have to be named predictably for tests to run correctly. # First testing team distributions. # You can check this for all teams i.e. A,B,C (by replacing the first line for 'B','C') A_node = games_net.get_cpds('A') self.assertTrue(A_node is not None, 'Team A node not initialized') A_dist = A_node.get_values() self.assertEqual(len(A_dist), 4, msg='Incorrect distribution size for Team A') test_prob = A_dist[0] test_prob2 = A_dist[2] self.assertEqual(round(float(test_prob*100)), 15, msg='Incorrect distribution for Team A') self.assertEqual(round(float(test_prob2*100)), 30, msg='Incorrect distribution for Team A') # Now testing match distributions. # You can check this for all matches i.e. AvB,BvC,CvA (by replacing the first line) AvB_node = games_net.get_cpds('AvB') self.assertTrue(AvB_node is not None, 'AvB node not initialized') AvB_dist = AvB_node.get_values() [cols, rows1, rows2] = AvB_node.cardinality self.assertEqual(rows1, 4, msg='Incorrect match distribution size') self.assertEqual(rows2, 4, msg='Incorrect match distribution size') self.assertEqual(cols, 3, msg='Incorrect match distribution size') flag1 = True flag2 = True flag3 = True for i in range(0, 4): for j in range(0,4): x = AvB_dist[:,(i*4)+j] if i==j: if x[0]!=x[1]: flag1=False if j>i: if not(x[1]>x[0] and x[1]>x[2]): flag2=False if j<i: if not (x[0]>x[1] and x[0]>x[2]): flag3=False self.assertTrue(flag1, msg='Incorrect match distribution for equal skill levels') self.assertTrue(flag2 and flag3, msg='Incorrect match distribution: teams with higher skill levels should have higher win probabilities') #Part 2b Test def test_posterior(self): posterior = calculate_posterior(get_game_network()) self.assertTrue(abs(posterior[0]-0.25)<0.01 and abs(posterior[1]-0.42)<0.01 and abs(posterior[2]-0.31)<0.01, msg='Incorrect posterior calculated') if __name__ == '__main__': unittest.main()
a5d9baacbfcc4aa95451e5123c8417d632f0e6a1
bijenderk82/py
/start.py
280
3.9375
4
import random num = random.randint num = random.randint(1,100) while True: print("guess a number between 1 and 100!") guess = input() i = int(guess) if i == num: print("you guess right!!!") break elif i < num: print("try higher") elif i > num: print("try lower")
b6a4bc56253c82493045d22e5f3c4aeea7d8e95e
wsapiens/PyCodeChallenge
/test/Encircle.py
1,332
3.9375
4
# !/bin/python3 import math import os import random import re import sys # # Complete the 'doesCircleExist' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts STRING_ARRAY commands as parameter. # N = 0 E = 1 S = 2 W = 3 # N 0 # W 3 + E 1 # S 2 def doesCircleExist(commands): # Write your code here result = [] for command in commands: print(command) d = N x = 0 y = 0 for c in command: if c == 'L': d = (d-1) if d > 0 else 3 elif c == 'R': d = (d+1) if d <3 else 0 else: if d == N: y+=1 elif d == E: x+=1 elif d == S: y-=1 else: x-=1 if x == 0 and y == 0: result.append('YES') else: result.append('NO') return result if __name__ == '__main__': fptr = open('test_out.txt', 'w') commands_count = int(input().strip()) commands = [] for _ in range(commands_count): commands_item = input() commands.append(commands_item) result = doesCircleExist(commands) fptr.write('\n'.join(result)) fptr.write('\n') fptr.close()
0203b4307611073fcc7d6f5ee8fa1f3b40cdfc26
peck94/LinodeProjects
/pycfg/Grammar.py
7,245
3.578125
4
import random class Rule(object): """ General rule object. Rules can be executed. """ def __init__(self): pass # execute this rule in the context of a given grammar def execute(self): pass class TextNode(Rule): """ Text nodes just return strings when executed. """ def __init__(self, text): super(TextNode, self).__init__() self.text = text # text rules simply return their given text def execute(self): return self.text def __repr__(self): return self.text class SequentialNode(Rule): """ Sequential nodes call their given rules in sequence. """ def __init__(self, others): super(SequentialNode, self).__init__() self.others = others def execute(self): result = '' for other in self.others: result = '{0}{1}'.format(result, other.execute()) return result def add_other(self, other): self.others.append(other) def __repr__(self): result = '' for other in self.others: result = '{0}{1}'.format(result, other) return result class GrammarRule(Rule): def __init__(self, grammar, label): self.grammar = grammar self.label = label def execute(self): return self.grammar.get(self.label).execute() def __repr__(self): return '`{0}`'.format(self.label) def to_cnf(self): return [self] class Grammar(object): """ Context-free grammar. Associates labels with rules. """ def __init__(self): self.rules = {} # add a rule with a name def add_rule(self, name, rule): # check if it exists if name not in self.rules: self.rules[name] = [] # add to list self.rules[name].append(rule) # get a rule def get(self, name): # check if it exists if name not in self.rules: raise ValueError('Rule not found: {0}'.format(name)) # randomly choose a rule from the list index = random.randrange(0, len(self.rules[name])) return self.rules[name][index] # convert to string def __repr__(self): result = '' for name in self.rules: for rule in self.rules[name]: result = '{0} -> {1}\n{2}'.format(name, rule, result) return result # start derivation def derive(self, start): return self.get(start).execute() # convert to Chomsky normal form def to_cnf(self): # CNF equivalent of current grammar g_cnf = Grammar() # START: Eliminate the start symbol from right-hand sides g_cnf.add_rule('S0', GrammarRule(g_cnf, 'S')) # TERM: Eliminate rules with nonsolitary terminals counter = 0 for name in self.rules: for rule in self.rules[name]: # check size if len(rule.others) > 1: # replace all TextNodes nodes = [] for i in range(0, len(rule.others)): other = rule.others[i] # terminal if isinstance(other, TextNode): # new rule g_cnf.add_rule('T{0}'.format(counter), other) # replace current rule nodes.append(GrammarRule(g_cnf, 'T{0}'.format(counter))) counter += 1 else: # add to nodes nodes.append(other) # replace rule g_cnf.add_rule(name, SequentialNode(nodes)) else: # just add it g_cnf.add_rule(name, rule) # BIN: Eliminate right-hand sides with more than 2 nonterminals counter = 0 rules_copy = g_cnf.rules.copy() for name in rules_copy: for rule in rules_copy[name]: # check type if not isinstance(rule, SequentialNode): continue # check size if len(rule.others) > 2: first = True current = rule.others[0:] while len(current) > 0: # add link to grammar parts = [current[0]] if len(current) > 1: parts.append(GrammarRule(g_cnf, 'B{0}'.format(counter+1))) new_name = name if not first: new_name = 'B{0}'.format(counter) g_cnf.add_rule(new_name, SequentialNode(parts)) # next rule current = current[1:] counter += 1 first = False # clean-up for name in g_cnf.rules: g_cnf.rules[name] = [rule for rule in g_cnf.rules[name] if not isinstance(rule, SequentialNode) or len(rule.others) <= 2] # DEL: Eliminate eps-rules # UNIT: Eliminate unit rules return g_cnf class Parser(object): """ Parser for CFGs. The format of a rule is A -> B where A is an alphanumeric name and B is any string. One can refer to a rule named S by typing `S` in the right-hand side. """ def __init__(self, grammar): # store grammar self.grammar = grammar # parse a single rule def parse_rule(self, rule): # split into left and right parts tmp = rule.split(' -> ') if len(tmp) != 2: raise ValueError('Invalid rule definition: {0}'.format(rule)) left = tmp[0] right = tmp[1] # create nodes nodes = [] in_rule = False buffer = '' for i in range(0, len(right)): if right[i] == '`': result = None if in_rule: # create call to rule result = GrammarRule(self.grammar, buffer) else: # create text node result = TextNode(buffer) # add to nodes nodes.append(result) # invert flag in_rule = not in_rule # clear buffer buffer = '' else: # add to buffer buffer = '{0}{1}'.format(buffer, right[i]) # check remainder if len(buffer) > 0: # verify rule if in_rule: raise ValueError('Unterminated rule `{0}` in {1}'.format(buffer, left)) # add text node nodes.append(TextNode(buffer)) # create sequential node result = SequentialNode(nodes) # register in grammar self.grammar.add_rule(left, result) # parse multiple rules def parse_rules(self, rules): for rule in rules: self.parse_rule(rule) # return grammar def get_grammar(self): return self.grammar
c5e246d80d913609178a0b8a4cdabd9f91458b3e
theminer3746/2110101_Com_Prog
/String/String_P5.py
128
3.90625
4
bit = input() count = 0 for x in bit: count += int(x) if count % 2 == 0: print(bit + '0') else: print(bit + '1')
7b2eb7c75eac0a380e9896673b9278330aa54db5
hstabelin/Python-cursoC0d-r
/manipulacao_arquivos/desafio.py
984
3.875
4
import csv from urllib import request def read(url): with request.urlopen(url) as entrada: # guarda o arquivo da url na variavel entrada with open('cidades.txt', 'w') as saida: # criei o arquivo de saida e dei permissão print('Baixando CSV....') dados = entrada.read().decode('latin1') # pegou o arquivo da variavel entrada, leu e salvou em dados print('Download Completo!') for cidade in csv.reader(dados.splitlines()): # Roda o for a ler os dados do csv armazenados # na variavel dados print(f'{cidade[8]}: {cidade[3]}', file=saida) # printa os dados armazenados em cidade, # das colunas 9[8] e 3[4] read(r'http://files.cod3r.com.br/curso-python/desafio-ibge.csv') # informei na função a url onde está o arquivo # o r na frente, é para que ele não intreprete o url, seja literal print('Arquivo salvo')
e79c322446b8ff41d76a4a5b4c9c70df16db1285
CharmSun/my-leetcode
/py/235.lowest-common-ancestor-of-a-binary-search-tree.py
779
3.765625
4
# # @lc app=leetcode id=235 lang=python3 # # [235] Lowest Common Ancestor of a Binary Search Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if not root: return None low = min(p.val, q.val) high = max(p.val, q.val) if root.val <= high and root.val >= low: return root elif root.val > high: return self.lowestCommonAncestor(root.left, p, q) elif root.val < low: return self.lowestCommonAncestor(root.right, p, q) # @lc code=end
297093bcf18617d725d529d7e302480361a74c84
alu-rwa-prog-1/assignment-7-code-masters
/classses_sudoku.py
1,414
4.28125
4
#Authors: Marthely237 and Sammyiel # Importing unittest to help in the class Test import unittest class Sudoku: """method init: initialize the game with n x n number of spaces in grid""" ## Instance variables # self.value = 0 # self.row = row # self.column = column # self.block = (row // 3) * 3 + column // 3 # self.permitted_values = set([]) class Board: """Sudoku board consisting of an ordered list of field objects dictionaries which link row/column/block number to the associated ordered list of field objects a filled attributed which tracks how many fields are already filled, later used for breaking the solve loop""" ## Instance variables # self.fields = [] # self.rows = {i: [] for i in range(9)} # self.columns = {i: [] for i in range(9)} # self.blocks = {i: [] for i in range(9)} # self.filled = 0 # To test the using assertions in unittest class TestSudoku(unittest.TestCase): ## Instance variables # self.assertEqual(no_rows + no_columns, 18) # self.assertEqual(no_rows, 9) # self.assertEqual(no_rows + no_columns, 81) """Apply assertNotEqual so that a number is not repeated in a row or column Apply assertRaisesValueError when the value input is out of range Test whether the input is a number and nothing else Testing that the input is just one digit"""
92e333d4da83bf9fc876ab1e4225817f6491a5bb
rahulraj9/udemy-python-bootcamp
/DAY3/bmi2.py
679
4.21875
4
height = float(input("Enter the height in m:- ")) weight = float(input("Enter the weight in kg:- ")) body_mass_index = round(weight / height ** 2) if body_mass_index < 18.5: print(f"your body mass index is {body_mass_index} and you are underweight") elif body_mass_index < 25: print(f"your body mass index is {body_mass_index} and you have normal weight") elif body_mass_index < 30: print(f"your body mass index is {body_mass_index} and you have overweight") elif body_mass_index < 35: print(f"your body mass index is {body_mass_index} and you are obeses") else: print(f"your body mass index is {body_mass_index} and you are clinically obeses")
4494ed25642104537112687dbeac64e133542fa8
Stevewho/Computational-Learning
/BNN/Tensorflow_NN.py
2,311
3.671875
4
''' 1. nomalize data 2. Testing data is for course submittion ''' import tensorflow as tf import numpy as np # normalize https://stackoverflow.com/questions/21030391/how-to-normalize-array-numpy def normalized_one(a, axis=-1, order=2): l2 = np.linalg.norm(a, order, axis) l2[l2==0] = 1 return a / np.expand_dims(l2, axis) #data import and processing traindata= np.loadtxt("train-a2-449.txt") testdata = np.loadtxt("test-a2-449.txt") y = np.array(traindata[:,-1]).reshape(900,1) x_test_raw=np.array(testdata).reshape(100,1000) #normalize data x=normalized_one(traindata[:,0:1000]) x_test=normalized_one(x_test_raw) num_neuron=2 #tensorflow variable of weight and bias for 2 layer w1= tf.Variable(tf.random_uniform([1000,num_neuron], -1.0, 1.0)) # 1000*3 matrix w0=tf.Variable(tf.random_uniform([num_neuron,1], -1.0, 1.0)) # 3*1 matrix b1 = tf.Variable(tf.zeros([num_neuron])+0.01) b0 = tf.Variable(tf.zeros([1])+0.01) #training example data frame #https://stackoverflow.com/questions/36693740/whats-the-difference-between-tf-placeholder-and-tf-variable Xholder= tf.placeholder(tf.float32, shape=(900,1000)) Yholder= tf.placeholder(tf.float32, shape=(900,1)) textholder=tf.placeholder(tf.float32, shape=(100,1000)) #output in each layer y1 = tf.tanh(tf.matmul(Xholder,w1)+b1) y0 = tf.tanh(tf.matmul(y1,w0)+b0) #loss function loss=tf.reduce_mean(tf.square(y-y0)) #optimizer optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) #initalize Tensorflow init=tf.initialize_all_variables() sess =tf.Session() sess.run(init) #training for step in range(10000): sess.run(train, feed_dict={Xholder:x, Yholder:y}) if step %100 ==0: print(step, sess.run(loss, feed_dict={Xholder:x, Yholder:y})) #inspecting training result y_hat=sess.run(y0,feed_dict={Xholder:x, Yholder:y}) y_convert=np.sign(y_hat) compare=np.column_stack((y_convert,y)) # np.savetxt('TFresult.txt', compare, delimiter=' ') #counting error in training result n=0 k=0 for i in compare: if i[0]==i[1]: k+=1 n+=1 print("correct=",k ,"\ntotal=",n,'\nrate of correct =',k/n) #testing result: y1_test=tf.tanh(tf.matmul(textholder,w1)+b1) y0_test=tf.tanh(tf.matmul(y1_test,w0)+b0) ytest=sess.run(y0_test, feed_dict={textholder: x_test}) np.savetxt("TestDataOutput.txt", np.sign(ytest))
b9fa0bebeb312c75277c5a2106d75ec27bcf618a
lucianoww/Python
/pybrexer0013.py
1,058
3.921875
4
''' #13) Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: a) Para homens: (72.7*h) - 58 b) Para mulheres: (62.1*h) - 44.7 ''' erro = 0 texto = '' pesoideal = 0.00 altura = 0.00 sexo = input('Informe sexo M (masculino) ou F (feminino): ').strip().upper() #consistências if not sexo.__eq__('M') and not sexo.__eq__('F'): erro = 1 print('Só pode informar as letras M ou F') if erro == 0: altura = float(input('Digite a altura: ')) if erro == 0 and altura == 0.00: erro = 1 print('Altura deve ser maior que 0') #fim consistencias if erro == 0: if sexo.__eq__('F'): texto = 'Feminino' pesoideal = int((62.1*altura) - 44.7) if sexo.__eq__('M'): texto = 'Masculino' pesoideal = int((72.7 * altura) - 58) print('O peso ideal de uma pessoa do sexo {}, cuja altura é de {} é {} Kg.'.format(texto, altura, pesoideal))
febd24e1d2b430a54c3a63a1f2088c1dc23e8cf0
akoichig/Hackerrank
/WorldCodeSprint/WorldCodeSprint6_BeautifulSet.py
1,791
3.59375
4
def comm(): n=3 for d in range(n): print("\td = {}".format(d)) for x in range(1+int((n-d)/2)): y = x+d z = n-y-x print("{} {} {}".format(x, y, z)) N=1 T = [['x'], ['x', 1]] loc = [[1,1]] def L(d): T = d[0] loc = d[1] new = [[0]] newloc = [] for i in range(len(T)): new.append([0]+T[i]) for i in range(len(loc)): lx = loc[i][0] ly = loc[i][1] new[lx-ly][0]='x' new[lx+1][0]='x' newloc.append([lx+1, ly+1]) nl = sum([1 for t in new if t[0]==0]) return new, newloc #, nl def D(d): T = d[0] loc = d[1] new = T + [[0]*(len(T)+1)] for i in range(len(loc)): lx = loc[i][0] ly = loc[i][1] new[len(T)][len(T)-lx+ly]='x' new[len(T)][ly]='x' nl = sum([1 for t in new[len(T)] if t==0]) return new, loc #, nl def U(d): T = d[0] loc = d[1] new = [[0]] newloc = [] for i in range(len(T)): new.append(T[i]+[0]) for i in range(len(loc)): lx = loc[i][0] ly = loc[i][1] new[lx+1][lx+1]='x' new[ly][ly]='x' newloc.append([lx+1, ly]) nl = sum([1 for i in range(len(new)) if new[i][i]==0]) return new, newloc #, nl def fill(d): T = d[0] loc = d[1] i=0 for i in range(len(T)): for j in range(len(T[i])): if T[i][j] == 0: break else: continue break T[i][j] = 1 loc.append([i, j]) return T, loc def pr(d): T = d[0] for i in T: sti = [str(j) for j in i] print(' '.join(sti)) d = [T, loc] for n in range(2): print("\t NEXT ITERATION:") d = L(d); pr(d) d = fill(d); pr(d)
1cbd367cec132648de78b9bacec88146553c705b
WAT36/procon_work
/procon_python/src/atcoder/arc/past/A_020.py
126
3.640625
4
a,b=map(int,input().split()) if(abs(a)<abs(b)): print("Ant") elif(abs(a)>abs(b)): print("Bug") else: print("Draw")
c6b27267368339eee12117d8e626365ff1b5b452
kevynfg/estudos-geral
/estudos-python/estaciopy.py
775
4.15625
4
print("Hello World") #importar função do próprio Python import math, random, smtplib, time, tkinter #Operações matemáticas e random raizquadrada = math.sqrt(5) fatorial = math.factorial(10) print(fatorial) print(raizquadrada) print(random.randrange(20)) #gera um número aleatorio de 0 a 19 print(random.uniform(0.0, 10.0)) #gera floats aleatórios entre um e outro print(random.choice(['vitória', 'derrota', 'empate'])) #escolhe um elemento aleatório baralho = 'ás dois três quatro cinco seis sete oito nove dez valete dama rei'.split() random.shuffle(baralho) #embaralha uma lista [] print(baralho) #Time tempoLocal = time.ctime() #Se passar o valor, ele calcula o numero de segundos passados desde 00:00:00 do dia 1 de janeiro de 1970. print(tempoLocal)
d64bc83dcbfb1e546ed17914fcb3162352f08148
thespacewa1ker/2_Machine_N_jobs_problem
/job_sequence.py
2,156
3.875
4
# Here i'm solving using johnson's Algorithm #User Input : the total number of jobs jobs = int(input("Enter the Number of Jobs :")) # Here i'm solving for 2 machines and n jobs # taking user input of Machine -1 and Machine-2 machine_1 = [] machine_2 = [] # Creating the empty list to store the shortest job of machine-1 and machine-2 time_1 = [] time_2 = [] for i in range(jobs): x = int(input("FOR Machine_1---Enter the job "+str(i+1)+" time duration :")) machine_1.append(x) print("-------------------------------------") for i in range(jobs): x = int(input("FOR Machine_2---Enter the job "+str(i+1)+" time duration :")) machine_2.append(x) for i in range(jobs): #Finding the minimum time duration m_1 = min(machine_1) m_2 = min(machine_2) # Checking which machine has least element # If both machine contains the least element then obtain the maximum differnece and proceed if m_2 < m_1: m2_index =machine_2.index(m_2) time_2.append(m2_index+1) machine_1[m2_index] = 10000 machine_2[m2_index] = 10000 if m_1 == m_2: m1_index = machine_1.index(m_1) m2_index = machine_2.index(m_2) m1_max_diff = abs(machine_1[m1_index]-machine_2[m1_index]) m2_max_diff = abs(machine_1[m2_index]-machine_2[m2_index]) shortest = max(m1_max_diff,m2_max_diff) if shortest == m1_max_diff: time_1.append(m1_index+1) machine_1[m1_index] = 10000 machine_2[m1_index] = 10000 else: time_2.append(m2_index+1) machine_2[m2_index] = 10000 machine_1[m2_index] = 10000 if m_1 < m_2: m1_index = machine_1.index(m_1) time_1.append(m1_index+1) machine_1[m1_index] = 10000 machine_2[m1_index] = 10000 # reversing the machine-2 job sequence and then appending with machine-1 job sequence time_2.reverse() jobs_Sequence = time_1+time_2 for i in jobs_Sequence: print("Job-"+str(i) +">",end =" ")
17b63310fd71172a49d617821b2c7b948a0157f8
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/vhyros001/question3.py
1,862
3.828125
4
"""Assignment 9 question 3 check if a sudoku grid is valid Ross van der Heyde VHYROS001 14 May 2014""" def checkRows(grid): """Checks if the rows of the grid are valid""" valid = True for i in range(9): for j in range(0, 10): if grid[i].count(str(j)) > 1: valid = False return valid def checkCols (grid): """Checks if the columns are valid""" col = "" valid = True for j in range(len(grid)): col="" for i in range(len(grid)): col+= grid[i][j] #print(col) for i in range(10): if col.count(str(i)) >1: valid = False return valid def checkSmall(grid): """Checks if the 9 small grids are valid""" valid = True line = "" indexes =[[0,1,2],[3,4,5],[6,7,8]] for k in range(3): for i in [0,3,6]: line="" for j in indexes[k]: line+= grid[j][i:i+3] #print(line) for l in range(10): if line.count(str(l))>1: valid= False #print(valid) return valid grid = []# read in lines of grid for i in range(9): line = input() grid.append(line) #cols = checkCols(grid) #rows = checkRows(grid) #small = checkSmall(grid) #print("R", rows, "C", cols, "SG", small) if checkCols(grid) and checkRows(grid) and checkSmall(grid): print("Sudoku grid is valid") else: print("Sudoku grid is not valid") #359716482 #867345912 #413928675 #398574126 #546281739 #172639548 #984163257 #621857394 #735492861 #Sudoku grid is not valid #Sample I/O: #259716483 #867345912 #413928675 #398574126 #546281739 #172639548 #984163257 #621857394 #735492861 #Sudoku grid is valid
980bc5c71e9273f39333377b69d7e964289c4ab3
m-amoit/Python-recap
/BuildingSkills/flowers.py
785
3.90625
4
from swampy.TurtleWorld import * from mypolygon import * world = TurtleWorld() bob = Turtle() bob.delay = 0.001 def petal(t, r, angle): ''' draw a single petal using 2 arcs t: turtle r: radius of arc angle: angle that subtends the arc ''' for i in range(2): arc(t, r, angle) lt(t, 180-angle) def flower(t, n, r, angle): ''' draw a flower with n petals ''' for i in range(n): petal(t, r, angle) lt(t, 360/n) def move(t, length): ''' Define movement of turtle without leaving trail. t: turtle length: distance the turtle moves pu: pen up (inactive) pd: pen down (active) ''' pu(t) fd(t, length) pd(t) move(bob, -100) flower(bob, 10, 140, 45) move(bob, 200) flower(bob, 24, 140, 45) move(bob, 200) flower(bob, 21, 180, 27) die(bob) wait_for_user()
59d324d9ebb9b38fa56f9ce33fa7f1f716606097
eryykr/Python-Projects
/Project 2 - Noughts and Crosses/n_and_c.py
2,378
3.765625
4
import time import os #function for converting state of game into displayed output def display(state): output = (''' | | {} | {} | {} ______|______|______ | | {} | {} | {} ______|______|______ | | {} | {} | {} | | '''.format(state[0][0], state[0][1], state[0][2], state[1][0], state[1][1], state[1][2], state[2][0], state[2][1], state[2][2])) return output #function for checking whether there is a winner def result(state): #checking diagonals if state[0][0] == state[1][1] == state[2][2] or state[2][0] == state[1][1] == state[0][2]: winner = state[1][1] else: winner = False #checking horizontal and vertical stripes for i in range(len(state)): if state[i][0] == state[i][1] == state[i][2]: winner = state[i][0] elif state[0][i] == state[1][i] == state[2][i]: winner = state[0][i] else: continue return winner #function for finding other player's symbol def other(k): return list(set(('x', 'o')).difference(set(k)))[0] #function for partitioning list into sublists def sub(l): return [l[0:3], l[3:6], l[6:9]] #function for checking whether square is taken def taken(brd, inp): if inp in brd: return False else: return True #CODE FOR MAIN GAME board = [1,2,3,4,5,6,7,8,9] print("WELCOME TO NOUGHTS AND CROSSES\n") p1 = input("Player 1, would you like to be noughts or crosses? Enter x or o:\n") p2 = other(p1) now = p1 #instructions print("Player 1 is "+p1+" and player 2 is "+p2+"\n") time.sleep(2) print("When it is your turn, enter a number from 1 to 9 to place a nought or cross\n") time.sleep(2) print("Player 1 starts. Game starting in 3 seconds.") time.sleep(3) os.system('cls') #starting a game turns = 0 while result(sub(board)) == False and turns < 9: print("Current player is "+now.upper()) print(display(sub(board))) legal = False while legal == False: pos = int(input("Enter choice: ")) if taken(board, pos) == False: legal = True else: print("Position taken") board[pos-1] = now now = other(now) os.system('cls') turns+=1 if result(sub(board)) != False: print(other(now).upper()+" has won!") print(display(sub(board))) time.sleep(3) else: print("It's a draw.") print(display(sub(board))) time.sleep(3)
d88b44f90a5ea46ab6079d88a802f78978f54ce1
vstadnytskyi/auxiliary
/ubcs_auxiliary/os.py
7,258
3.78125
4
def find(topdir, name=[], exclude=[]): """A list of files found starting at 'topdir' that match the patterns given by 'name', excluding those matching the patterns given by 'exclude'. Parameters ---------- topdir (string) name (list) exclude (list) Returns ------- file_list (list) Examples -------- >>> res = anfinrud_auxiliary.os.walk('ubcs_auxiliary/') >>> for i in res: print(i[0]) ...: ubcs_auxiliary/ ubcs_auxiliary/tests ubcs_auxiliary/tests/__pycache__ ubcs_auxiliary/__pycache__ Python 3.7.4 (v3.7.4:e09359112e, Jul 8 2019, 14:54:52) Type 'copyright', 'credits' or 'license' for more information IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from time import time In [2]: import auxiliary In [3]: res = auxiliary.os.walk('/') In [4]: t1 = time(); lst = list(res); t2 = time(); print(t2-t1, len(lst)) 3.9815242290496826 1346 Python 2.7.16 (v2.7.16:413a49145e, Mar 2 2019, 14:32:10) Type "copyright", "credits" or "license" for more information. IPython 5.8.0 -- An enhanced Interactive Python. In [1]: from time import time In [2]: import anfinrud_auxiliary In [3]: res = auxiliary.os.walk('') In [4]: t1 = time(); lst = list(res); t2 = time(); print(t2-t1, len(lst)) (0.77646803855896, 1346) """ def glob_to_regex(pattern): return "^"+pattern.replace(".", "\\.").replace("*", ".*").replace("?", ".")+"$" try: from scandir import walk except ImportError: from os import walk import re if type(name) == str: name = [name] if type(exclude) == str: exclude = [exclude] name = [re.compile(glob_to_regex(pattern)) for pattern in name] exclude = [re.compile(glob_to_regex(pattern)) for pattern in exclude] file_list = [] for (directory, subdirs, files) in walk(topdir): for file in files: pathname = directory+"/"+file match = any([pattern.match(pathname) for pattern in name]) and\ not any([pattern.match(pathname) for pattern in exclude]) if match: file_list += [pathname] return file_list def exclude(): """Returns a list of patterns to exclude from a search. Add terms as required.""" exclude = ['*/alignment*', '*/trash*', '*/_Archived*', '*/backup*', '*/Commissioning*', '*/Test*', '*/.AppleDouble*', '*LaserX*', '*LaserZ*', '*Copy*', '*._*', '.DS_Store'] return exclude def image_file_names_from_path(beamtime,path_name): """Returns image file names found under path_name. Typically used with 'Reference_*() , which specifies which directories contain data for which zinger-free-statistics are to be acquired. The zinger-free-statistics include Imean and Ivar, which are used to construct UC_psi.npy.""" from db_functions import find,exclude from numpy import sort data_dir,analysis_dir = data_dir_analysis_dir(beamtime) terms = ['*.mccd','*.rx'] image_files = sort(find(data_dir+path_name, name=terms, exclude=exclude())) return image_files def N_files_in_dir(folder = '', match = '*'): import os import fnmatch integer = len(fnmatch.filter(os.listdir(folder), match)) return integer def listdir(root, include = ['.hdf5'], exclude = [], sort = ''): """ returns list of files from a 'source' directory that have terms listed in 'include' and doesn't terms listed in 'exclude'. Extra parameter 'sort' can be used to sort the output list. If left blank, no sorting will be performed. Parameters ---------- source (string) include (list) exclude (list) sort (string) Returns ------- file_list (list) Examples -------- >>> res = ubcs_auxiliary.os.get_list_of_files('/',['.hdf5']) """ import os from numpy import argsort, array files = [os.path.join(root,file) for file in os.listdir(root)] selected = [] [selected.append(file) for file in files if ((all([term in file for term in include])) and (all([term2 not in file for term2 in exclude])))] return selected def find_recent_filename(root, include, exclude, newest_first = True): """ find the list of files or folders that have any terms specified in the list 'include' and do not have terms specified in 'exclude'. The extra parameter reverse_order specified whether return the newest or oldest one. Parameters ---------- source (string) include (list) exclude (list) sort (string) Returns ------- file_list (list) """ from os import listdir,path from os.path import getmtime from numpy import argsort, array files = [path.join(root,file) for file in listdir(root)] selected = [] [selected.append(file) for file in files if ((all([term in file for term in include])) and (all([term2 not in file for term2 in exclude])))] path_names = selected.copy() if len(path_names) > 0: creation_times = [getmtime(file) for file in path_names] sort_order = argsort(creation_times) if newest_first: return array(path_names)[sort_order][-1] else: return array(path_names)[sort_order][0] else: return '' def get_current_pid_memory_usage(units = 'GB',verbose = False): """ returns current process memory footprint. """ import os import psutil pid = os.getpid() py = psutil.Process(pid) coeff = 1 if units == 'GB': coeff = 2.**30 elif units == 'MB': coeff = 2.**20 elif units == 'KB': coeff = 2.**10 elif units == 'B': coeff = 2.**0.0 elif units == 'b': coeff = 1.0/8.0 memoryUse = py.memory_info()[0]/coeff # memory use in GB...I think if verbose: print('memory use:', memoryUse) else: pass return memoryUse def does_filename_have_counterpart(src_path,dst_root = None, counterpart_extension = ''): """ checks if the 'src_path' has counterpart with extension 'counterpart_extension'. Parameters ---------- filename (string) counterpart_extension (string) Returns ------- boolean (boolean) """ import os src_root, src_name = os.path.split(src_path) if dst_root is None: dst_root, dst_name = os.path.split(src_path) splitted = src_name.split('.') src_base = splitted[0] src_extension = ''.join(splitted[1:]) counterpart = os.path.join(dst_root,src_base + counterpart_extension) flag = os.path.exists(counterpart) return flag def read_config_file(filename): """ read yaml config file Parameters ---------- filename (string) Returns ------- dict (dictionary) boolean (boolean) """ import yaml import os flag = os.path.isfile(filename) if flag: with open(filename,'r') as handle: config = yaml.safe_load(handle.read()) # (2) else: config = {} return config, flag
88e961bd5ea7de5fd3060075a99cc2bb42b04014
corenel/lintcode
/algorithms/112_remove_duplicates_from_sorted_list.py
1,678
4.15625
4
""" Remove Duplicates from Sorted List ---------------------------------- Given a sorted linked list, delete all duplicates such that each element appear only once. Example 1: - Input: 1->1->2 - Output: 1->2 Example 2: - Input: 1->1->2->3->3 - Output: 1->2->3 Reference: - https://algorithm.yuanbin.me/zh-hans/linked_list/remove_duplicates_from_sorted_list.html - https://leetcode.com/problems/remove-duplicates-from-sorted-list/ - https://www.lintcode.com/problem/remove-duplicates-from-sorted-list/ """ from utils import ListNode, LinkedList import unittest def delete_duplicates(head): """ Remove all duplicates in given linked list :param head: head node of given linked list :type head: ListNode :return: head node of operated linked list :rtype: ListNode """ if head is None: return head curr = head while curr.next is not None: if curr.val == curr.next.val: tmp = curr.next.next del curr.next curr.next = tmp else: curr = curr.next return head class TestRemoveDuplicatesFromSortedList(unittest.TestCase): def test_remove_duplicates_from_sorted_list(self): def assert_operation(val_list, result_list): linked_list = LinkedList(singly=True) linked_list.append_val_list(val_list) delete_duplicates(linked_list.get_head()) self.assertListEqual(result_list, linked_list.to_list()) assert_operation([], []) assert_operation([1, 1, 2], [1, 2]) assert_operation([1, 1, 2, 3, 3], [1, 2, 3]) if __name__ == '__main__': unittest.main()
f9694d4ea13ce1e7d067f829f2c1a6cec5e6db6d
Absurd1ty/week_4_problems
/min_to_visit_all.py
778
3.75
4
"""On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. You can move according to the next rules: In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second). You have to visit the points in the same order as they appear in the array.""" class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: travel_time = 0 for i in range(1, len(points)): travel_time += max(abs(points[i-1][0] - points[i][0]), abs(points[i-1][1] - points[i][1])) return travel_time
72040b8282790a44b6e017cf4257a196378cb8f9
dainst/cilantro
/service/utils.py
1,174
3.65625
4
import os def get_all_file_paths_from_dir(dir_path: str): """ Return a list of the paths of files in a given directory with sub-dirs. :param str dir_path: The directory to get the paths from :return: list of the file paths. """ file_list = [] for entry in os.scandir(dir_path): if entry.is_file(): file_list.append(os.path.join(dir_path, entry.name)) else: file_list.extend(get_all_file_paths_from_dir(entry)) return file_list def list_dir(dir_path: str): """ Return a dictionary tree that represents the directory file structure. :param str dir_path: the path to the directory that needs to be serialized :return: The dictionnary structure of the directory """ tree = [] for entry in os.scandir(dir_path): if entry.is_file(): tree.append({ "type": "file", "name": entry.name }) else: tree.append({ "type": "directory", "name": entry.name, "contents": list_dir(os.path.join(dir_path, entry.name)) }) return tree
9368127280c27260ef3f94bf625d9010d12a2c17
ghazamu/mycode
/challenges/thursday.py
379
3.921875
4
#!/usr/bin/env python3 def sortList(list): short = 0 medium = 0 long = 0 for i in list: if len(i) < 5: short += 1 elif ((len(i) > 5) and (len(i) < 10)): medium += 1 elif (len(i) >= 10): long += 1 print ("Short: " + str(short)) print ("Medium: " + str(medium)) print ("long: " + str(long)) mylist = ['banana','blueberries','nuts','acorns'] sortList(mylist)
47e64fba735d30e6cedc2cc7ff8c104090c0f7ff
ammumal/-algorithmPractice
/10872 팩토리얼.py
147
3.859375
4
n = int(input()) def recursion (n) : fac = 1 if n == 1: return 1 else: return n * recursion(n-1) print(recursion(n))
fd8acd9f26ea80553099e8f0b3a682cfcd7ab962
Atuan98/Demo_py1
/Lession_6/btvn_6.py
329
3.75
4
import string def nhap(): str = input("Hay nhap chuoi de kiem tra: ") return str def is_pangram(str, alphabet): i = 0 for ky_tu in alphabet: if ky_tu in str: i += 1 if i == 26: print(f"Chuoi {str} la pangram") else: print(f"Chuoi {str} khong la pangram") b = string.ascii_lowercase a = nhap() is_pangram(a,b)
01628e740b8f827fed27a8b8546bcfc1dd278d62
Alqahybi-512/Projects4Workshop
/ATM solution/atm.py
1,632
3.828125
4
class ATM: def __init__(self, balance, bank_name): self.balance = balance self.bank_name = bank_name self.withdrawals_list = [] def withdraw(self, request): print("Welcome to " + str(self.bank_name)) print("Current balance = " + str(self.balance)) print "=========================================" if request > self.balance: print "Sorry, Can't give you all this money !!" print "=========================================" elif request < 0: print "Must be more than 0 ,TRY more plz!" print "=========================================" else: self.withdrawals_list.append(request) self.balance -= request self.process_request(request) @staticmethod def process_request(request): allowed_papers = [100, 50, 10, 5, 1] for x in allowed_papers: while request >= x: print "Give:", x request -= x print "=========================================" return request def show_withdrawals(self): for withdrawal in self.withdrawals_list: print("Mony Withdrawl is " + str(withdrawal)) print("=========================================") balance1 = 500 balance2 = 1000 atm1 = ATM(balance1, "Smart Bank") atm2 = ATM(balance2, "Baraka Bank") atm1.withdraw(277) atm1.withdraw(800) atm1.show_withdrawals() atm2.withdraw(100) atm2.withdraw(2000) atm2.show_withdrawals() ###################################################
6254903dc8dcb8c79e4435cb9882f5145fe03499
MishalKumar/Python_Assignments
/country_code.py
688
4.28125
4
# Problem statement ''' Given a Phone number in the format +91-0431-2503333 split them and store in a tuple and identify the country. ''' def countrycode(phone_number): tuplelist = tuple(phone_number.split('-')) print(tuplelist) for k, v in country_n_codes.items(): if v in tuplelist: print(f'country: {k} and code: {v}') if __name__== '__main__': country_n_codes = {'India': '+91', 'Pakistan': '+92', 'China': '+86', 'Nepal': '+977', 'Bhutan': '+975', 'Myanmar': ' +95', 'Bangladesh': '+880', 'Srilanka': '+94'} phonenumber = input('enter phone number: \n') countrycode(phonenumber)
eaf5e488d89befa5ebc83a3f22908fd3ee524a10
AndersonANascimento/PythonExercicios
/desafio025.py
245
3.9375
4
# Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome NOME = 'SILVA' nome = input('Informe o nome: ') check = '' if (NOME in nome.upper()) else 'não' print('{}, {} possui {} no nome.'.format(nome, check, NOME))
d748f319ef478b80ef39cedfc23097fc438edccb
Aranccar/Code
/Solway/KRSUORIG29 BB-коды.py
3,046
3.734375
4
# Выдает Wrong Answer; пока не знаю почему name = input("") name=name.replace('[b]', '_eldiiar_[b]_eldiiar_') name=name.replace('[B]', '_eldiiar_[b]_eldiiar_') name=name.replace('[/b]', '_eldiiar_[/b]_eldiiar_') name=name.replace('[/B]', '_eldiiar_[/b]_eldiiar_') name=name.replace('[i]', '_eldiiar_[i]_eldiiar_') name=name.replace('[I]', '_eldiiar_[i]_eldiiar_') name=name.replace('[/i]', '_eldiiar_[/i]_eldiiar_') name=name.replace('[/I]', '_eldiiar_[/i]_eldiiar_') name=name.replace('[u]', '_eldiiar_[u]_eldiiar_') name=name.replace('[U]', '_eldiiar_[u]_eldiiar_') name=name.replace('[/u]', '_eldiiar_[/u]_eldiiar_') name=name.replace('[/U]', '_eldiiar_[/u]_eldiiar_') name = name.split("_eldiiar_") while "" in name: name.remove("") a='m' while '[b]' in name and '[/b]' in name and a=='m': for i in range(len(name)): if name[i] == '[b]': a=i elif name[i] == '[/b]' and a!='m': name[a]='<b>' name[i]='</b>' a='m' break a='m' while '[i]' in name and '[/i]' in name and a=='m': for i in range(len(name)): if name[i] == '[i]': a=i elif name[i] == '[/i]' and a!='m': name[a]='<i>' name[i]='</i>' a='m' break a='m' while '[u]' in name and '[/u]' in name and a=='m': a=0 for i in range(len(name)): if name[i] == '[u]': a=i elif name[i] == '[/u]' and a!='m': name[a]='<u>' name[i]='</u>' a='m' break print(''.join(name).lower()) # VER 2.0 text=list(input("")) list4=["i","b","u","I","B","U"] i=0 while i < len(text): if text[i]=="[": if text[i+1]=='/' and text[i+3]=="]" and ((text[i+2]) in list4): text[i]=(text[i]+text[i+1]+text[i+2]+text[i+3]) text.pop(i+1) text.pop(i+1) text.pop(i+1) elif text[i+2]=="]" and (text[i+1] in list4): text[i]=(text[i]+text[i+1]+text[i+2]) text.pop(i+1) text.pop(i+1) i +=1 else: i+=1 #Start to work b=-1 i=-1 u=-1 t=4 while t!=0: for k in range(len(text)): if text[k]=="[b]" or text[k]=="[B]": b=k elif (text[k]=="[/b]" or text[k]=="[/B]") and b> -1: text[b]="<b>" text[k]="</b>" b=-1 i=-1 u=-1 break elif text[k]=="[i]" or text[k]=="[I]": i=k elif (text[k]=="[/i]" or text[k]=="[/I]") and i> -1: text[i]="<i>" text[k]="</i>" b=-1 i=-1 u=-1 break elif text[k]=="[u]" or text[k]=="[U]": u=k elif (text[k]=="[/u]" or text[k]=="[/U]") and u> -1: text[u]="<u>" text[k]="</u>" b=-1 i=-1 u=-1 break elif k==len(text)-1: t=0 print("".join(text))
c50bc86999e805641191ab1a517ea8f6ee334d20
EPkravec/python_base
/lesson_006/mastermind.py
706
3.5
4
from mastermind_engine import generate_number, valid, process print(' Ну что же сыграем в игру ') print(' ------------------------------- ') print(' Введите четырех значное число') print(' ------------------------------- ') generate_number() while True: number = input(" Введите число") if not valid(number): print("Число не валидно, введите заново") continue bulls, cows = process(number) if bulls == 4: print("Поздравляю, вы отгадали") break else: print(f" Быков - {bulls} \n " f"Коров - {cows}") # зачет!
55af13edf5fcb6fa248479c3a42a9f5737565de7
sabs773/Python
/RandomGenerator.py
417
3.921875
4
import numpy as np # arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) # print('2nd element on 1st dim: ', arr[0,0,2]) #slicing 2-D arrays # arr = np.array([1, 2, 3,4,5,6,7]) # print(arr[::2]) # arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) # print(arr[0:2,1:4]) #slicing 3-D arrays with # arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) # print(arr[0:2,0:2,0:2])
68b6263391698ca5df71f4047cb9afcaa3d58d9b
Prdcc/manim-Student-Shapers
/RealFunctions/InvertibilityIntro.py
14,237
3.625
4
from manimlib.imports import * import numpy as np def doubling_line(x): return 2*x def hidden_flat_line(x): return 0 def parabola(x): return x**2 def cubic(x): return (0.5*x)**3 def invCubic(x): x*=8 if(x >= 0): return x**(1./3.) else: return -((-x)**(1./3.)) class CubicIsFunction(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -5.5, "y_max" : 5.5, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=True) graph = self.get_graph(cubic,self.function_color) vert_line = self.get_vertical_line_to_graph(2,graph,color=YELLOW) #this might be made to go to graph_obj if you use ReplacementTransform in previous line hori_line = self.get_graph(lambda x : 1, color = YELLOW, x_min = 2, x_max = 0) #reversing axes works exactly the way i want here hori_line2 = self.get_graph(lambda x : 1, color = YELLOW, x_min = 0, x_max = 2) #reversing axes works exactly the way i want here line =Line(self.coords_to_point(2,1),self.coords_to_point(2,0 ),color=YELLOW) reflectLine = self.get_graph(lambda x: x,YELLOW) cubeRoot = self.get_graph(invCubic,self.function_color) self.wait(4) self.play(ShowCreation(graph)) self.play(ShowCreation(vert_line)) self.wait() self.play(ShowCreation(hori_line)) self.wait(1.5) self.play(FadeOut(vert_line),FadeOut(hori_line)) self.play(ShowCreation(hori_line2)) self.wait(0.5) self.play(ShowCreation(line)) self.wait() self.play(FadeOut(line),FadeOut(hori_line2)) self.wait(2) self.play(ShowCreation(reflectLine)) self.wait(1) self.play(Transform(graph, cubeRoot)) self.wait(15) class LinearIsInvertible(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -5.5, "y_max" : 5.5, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=False) graph_object = self.get_graph(hidden_flat_line,self.function_color) line_obj = self.get_graph(doubling_line,self.function_color) vert_lines = self.get_vertical_lines_from_graph(line_obj,-2.5,2.5,6,color=YELLOW) #this might be made to go to graph_obj if you use ReplacementTransform in previous line hori_lines = VGroup(*[ self.get_graph(lambda y : 2*x, color = YELLOW, x_min = 0, x_max = x) for x in np.linspace(-2.5, 2.5, 6) ]) definition=TextMobject("\\begin{align*}f:\\mathbb{R}&\\rightarrow\\mathbb{R}\\\\x&\\mapsto 2x \\end{align*}").move_to(DR*2) definitionInj=TextMobject("I. Surjectivity\\\\$\\forall y\\in Y\\exists x\\in X:f(x)=y$").move_to(UP*3+LEFT*3) self.play(ShowCreation(graph_object)) self.play(Transform(graph_object,line_obj),ShowCreation(definition)) self.wait(5) self.play(ShowCreation(hori_lines)) self.play(ShowCreation(vert_lines)) self.play(ShowCreation(definitionInj)) self.wait(6) class LinearIsBijective(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -5.5, "y_max" : 5.5, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=False) graph_object = self.get_graph(doubling_line,self.function_color) line_obj = self.get_graph(doubling_line,self.function_color) vert_lines = self.get_vertical_lines_from_graph(line_obj,-2.5,2.5,6,color=YELLOW) #this might be made to go to graph_obj if you use ReplacementTransform in previous line hori_line = self.get_graph(lambda x : 4, color = YELLOW, x_min = 2, x_max = 0) #reversing axes works exactly the way i want here hori_lines = VGroup(*[ self.get_graph(lambda y : 2*x, color = YELLOW, x_min = 0, x_max = x) for x in np.linspace(-2.5,2.5,6) ]) vertLinesInj= self.get_vertical_lines_to_graph(line_obj,1,2,2,color=YELLOW) #this might be made to go to graph_obj if you use ReplacementTransform in previous line horiLinesInj = VGroup(*[ self.get_graph(lambda y : 2*x, color = YELLOW, x_min = x, x_max = 0) for x in np.linspace(1, 2, 2) ]) text = TextMobject("I+II $\\Rightarrow$ Bijective / Invertible").move_to(UL*3+LEFT*0.5) definition=TextMobject("\\begin{align*}f:\\mathbb{R}&\\rightarrow\\mathbb{R}\\\\x&\\mapsto 2x \\end{align*}").move_to(DR*2) self.add(graph_object,definition) self.play(ShowCreation(vertLinesInj)) self.play(ShowCreation(horiLinesInj)) self.play( FadeOut(vertLinesInj), FadeOut(horiLinesInj), run_time=0.5 ) self.play(ShowCreation(hori_lines)) self.play(ShowCreation(vert_lines)) self.play(ShowCreation(text)) invText = TextMobject("$f^{-1}$").next_to(text,direction=DOWN) self.wait(2) self.play(ShowCreation(invText)) self.wait(6) class LinearIsInjective(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -5.5, "y_max" : 5.5, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=False) graph_object = self.get_graph(hidden_flat_line,self.function_color) line_obj = self.get_graph(doubling_line,self.function_color) vert_lines = self.get_vertical_lines_to_graph(line_obj,1,2,2,color=YELLOW) #this might be made to go to graph_obj if you use ReplacementTransform in previous line hori_lines = VGroup(*[ self.get_graph(lambda y : 2*x, color = YELLOW, x_min = x, x_max = 0) for x in np.linspace(1, 2, 2) ]) definition=TextMobject("\\begin{align*}f:\\mathbb{R}&\\rightarrow\\mathbb{R}\\\\x&\\mapsto 2x \\end{align*}").move_to(DR*2) definitionInj=TextMobject("II. Injectivity\\\\\\small{$\\forall x_1,x_2\\in X:f(x_1)=f(x_2)$\\\\ $\\Rightarrow x_1=x_2$}").move_to(UP*3+LEFT*3) self.play(ShowCreation(graph_object),run_time=0.5) self.play(Transform(graph_object,line_obj),ShowCreation(definition)) self.play(ShowCreation(vert_lines)) self.play(ShowCreation(hori_lines)) self.wait(3.5) self.play(ShowCreation(definitionInj)) self.wait(6) class ParabolaNotInjective(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -5.5, "y_max" : 5.5, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=False) graph_object = self.get_graph(hidden_flat_line,self.function_color) parabola_obj = self.get_graph(parabola,self.function_color) #vert_line = self.get_vertical_line_to_graph(2,line_obj,color=YELLOW) hori_line_to_right = self.get_graph(lambda x : 4, color = YELLOW, x_min = 2, x_max = 0) hori_line_to_left = self.get_graph(lambda x : 4, color = YELLOW, x_min = -2, x_max = 0) #vert_line_right = self.get_vertical_line_to_graph(2,sneaky_line_obj) vertLines = self.get_vertical_lines_to_graph(parabola_obj,-2,2,2,color=YELLOW) definition=TextMobject("\\begin{align*}f:\\mathbb{R}&\\rightarrow\\mathbb{R}\\\\x&\\mapsto x^2 \\end{align*}").move_to(DL*2) self.play(ShowCreation(graph_object)) self.play(Transform(graph_object,parabola_obj),ShowCreation(definition)) self.play(ShowCreation(vertLines)) self.play( ShowCreation(hori_line_to_left), ShowCreation(hori_line_to_right) ) self.wait(6) class PossibleTypes(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -5.5, "y_max" : 5.5, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): dt=0.3 self.setup_axes(animate=False) cubic = lambda x: 3*((0.5*x)**3-2*(0.5*x)) graphObj = self.get_graph(lambda x: 0,self.function_color) cubicObj = self.get_graph(cubic,self.function_color) vert_lines = self.get_vertical_lines_from_graph(cubicObj,-3, 3, 6,color=YELLOW) #this might be made to go to graph_obj if you use ReplacementTransform in previous line self.play(ShowCreation(graphObj)) self.play(Transform(graphObj,cubicObj)) hori_lines = VGroup(*[ self.get_graph(lambda y: cubic(x), color = YELLOW, x_min = 0, x_max = x) for x in np.linspace(-3, 3, 6) ]) self.play(ShowCreation(hori_lines),ShowCreation(vert_lines),runtime =0.2) root1 = (1-5**0.5) root2 = (1+5**0.5) hori_line_to_right = self.get_graph(lambda x : 3, color = YELLOW, x_min = root2, x_max = 0) hori_line_to_left = self.get_graph(lambda x : 3, color = YELLOW, x_min = root1, x_max = 0) vertLines = self.get_vertical_lines_to_graph(cubicObj,root1,root2,2,color=YELLOW) self.play(FadeOut(hori_lines), FadeOut(vert_lines),ShowCreation(vertLines), ShowCreation(hori_line_to_left), ShowCreation(hori_line_to_right),runtime =dt ) self.wait(dt) arctan = lambda x: 2.5*np.arctan(x) arctanObj = self.get_graph(arctan, self.function_color) self.play( FadeOut(hori_line_to_left), FadeOut(hori_line_to_right), FadeOut(vertLines), Transform(graphObj,arctanObj),runtime =dt ) root = np.tan(2/2.5) horiRight = self.get_graph(lambda x : 2, color = YELLOW, x_min = root, x_max = 0) horiLeft = self.get_graph(lambda x : -2, color = YELLOW, x_min = -root, x_max = 0) vertLines = self.get_vertical_lines_to_graph(arctanObj,-root,root,2,color=YELLOW) self.play(ShowCreation(vertLines),ShowCreation(horiLeft), ShowCreation(horiRight),runtime =dt) self.play(FadeOut(horiLeft),FadeOut(horiRight),FadeOut(vertLines),runtime =dt) hori_line_to_right = self.get_graph(lambda x : -4, color = YELLOW, x_min = 0, x_max = 7) hori_line_to_left = self.get_graph(lambda x : -4, color = YELLOW, x_min = 0, x_max = -7) question_marks = TexMobject("???") label_coord = self.coords_to_point(4,-5) question_marks = question_marks.next_to(label_coord,DR) self.play(ShowCreation(hori_line_to_right),ShowCreation(hori_line_to_left),ShowCreation(question_marks),runtime =dt) parabolaObj = self.get_graph(lambda x: x**2, self.function_color) self.play(FadeOut(question_marks),FadeOut(hori_line_to_left),FadeOut(hori_line_to_right),Transform(graphObj,parabolaObj),runtime =dt) hori_line_to_right = self.get_graph(lambda x : -2, color = YELLOW, x_min = 0, x_max = 7) hori_line_to_left = self.get_graph(lambda x : -2, color = YELLOW, x_min = 0, x_max = -7) horiRight = self.get_graph(lambda x : 4, color = YELLOW, x_min = 2, x_max = 0) horiLeft = self.get_graph(lambda x : 4, color = YELLOW, x_min = -2, x_max = 0) #vert_line_right = self.get_vertical_line_to_graph(2,sneaky_line_obj) vertLines = self.get_vertical_lines_to_graph(parabolaObj,-2,2,2,color=YELLOW) self.play( ShowCreation(hori_line_to_right),ShowCreation(hori_line_to_left),ShowCreation(question_marks.next_to(label_coord,DR + 2.5*UP)), ShowCreation(horiRight),ShowCreation(horiLeft),ShowCreation(vertLines),runtime =dt ) self.wait(6) class ParabolaNotSurjective(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -5.5, "y_max" : 5.5, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=False) graph_object = self.get_graph(hidden_flat_line,self.function_color) parabola_obj = self.get_graph(parabola,self.function_color) definition=TextMobject("\\begin{align*}f:\\mathbb{R}&\\rightarrow\\mathbb{R}\\\\x&\\mapsto x^2 \\end{align*}").move_to(DL*2) hori_line_to_right = self.get_graph(lambda x : -1, color = YELLOW, x_min = 0, x_max = 7) hori_line_to_left = self.get_graph(lambda x : -1, color = YELLOW, x_min = 0, x_max = -7) question_marks = TexMobject("???") label_coord = self.coords_to_point(4,-1) question_marks = question_marks.next_to(label_coord,DR) self.play(ShowCreation(graph_object)) self.play(Transform(graph_object,parabola_obj),ShowCreation(definition)) self.wait() self.play(ShowCreation(hori_line_to_right),ShowCreation(hori_line_to_left),ShowCreation(question_marks)) self.wait(2.5) self.play(FadeOut(question_marks),FadeOut(hori_line_to_left),FadeOut(hori_line_to_right),FadeOut(definition)) functions = [lambda x: 4*np.cos(x), lambda x: x**3, lambda x: 5*np.exp(-x**2)] funcGraphs = [self.get_graph(f,self.function_color) for f in functions] for f in funcGraphs: self.play(Transform(graph_object,f)) self.wait() self.wait(4)
c946c230e197900cdd516033377402f440b07545
MarceloGomez92/Proyectos
/03_personal-info.py
418
3.59375
4
# -*- coding: utf-8 -*- """ Created on Mon May 4 15:02:12 2020 @author: dell """ nombre=input("Cual es tu nombre? ") print("\n") apellido=input("Cual es tu apellido? ") print("\n") lugar=input("Donde vives? ") print("\n") edad=input("Cual es tu edad? ") space=" " print("\n") print("Buenas tardes"+space+nombre+space+apellido+space+"vives en"+space+lugar+space+"y tienes"+space+edad+space+"años")
cffa7221e9102fa5912c21a909e0f00087e12b36
grassyboulder/Quadratic-function-solver
/quadratic.py
925
3.828125
4
import math def testplot(a=-1,b=0,c=0): import matplotlib.pyplot as plt xz = [x for x in range(-10,11,1)] yz = [a*x**2+b*x+c for x in xz] oz = [0]*len(xz) plt.plot(xz,oz,'k-') plt.plot(xz,yz,'o-') plt.show() def quadratic(a,b,c): if b**2-4*a*c < 0: return "no real solutions" if b**2-4*a*c == 0: return (-b/(2*a)) sroot = math.sqrt(b**2-4*a*c) x1 = (-b + sroot)/(2*a) x2 = (-b - sroot)/(2*a) return x1, x2 def ask(): y = '' while y not in ['yes','Yes','y','Y']: print("give give a") a = float(input()) print("give give b") b = float(input()) print("give give c") c = float(input()) print('you inputed',a,',',b,',',c,", type yes if correct.") y = input() print() print('the answer is',quadratic(a,b,c)) testplot(a,b,c) ask()
22d9bcc12bdb08a56a0e311324a6e23c13c037ad
NithyaBharathy/Python-beginner-code_snippets
/inputs.py
317
3.890625
4
# input a single string in python i = input("Enter input here: ") print(i) # typecast input - replace int with float, bool if required i = int(input("Enter number here: ")) print(i) # input list l=[] n= int(input("Enter number of elements: ")) for i in range(0, n): ele = int(input()) l.append(ele) print(l)
0f8fa1ace0beb8ae83bd5617afa8a19c86b8e4cf
santosli/python_datamining
/leventest.py
444
3.828125
4
s = raw_input("First string:") t = raw_input("Second string:") def lev(s,t): s,t,d=' '+s,' '+t,{} for i in xrange(len(s)): d[i,0]=i for j in xrange(len(t)): d[0,j]=j for j in xrange(1,len(t)): for i in range(1,len(s)): if s[i] == t[j]: d[i,j]=d[i-1,j-1] else: d[i,j]=min(d[i-1,j],d[i,j-1],d[i-1,j-1])+1 return d[len(s)-1,len(t)-1] distance = lev(s,t) print 'The levenshtein-distance of',s,'and',t,'is',distance
f108fa359155ccfe7fe0957df09ed912d0ba7fc4
DarkTyr/python_work
/python_doxygen_examples/multi_file/classA.py
1,536
3.75
4
class ClassA(): def __init__(self, instantA, instantB=0x1C): '''!@brief Creates a ClassA object This ClassX object is being used as a DoxyGen/Docstring/Python example @param instantA An integer value @param instantB An integer value with a default of 0x8BAD ''' self.instA = instantA self.instB = instantB def var_print(self): ''' !@brief Method that prints the current value of the two internal variables This method prints to the console the current value of all internal variables with no formatting ''' print(self.instA) print(self.instB) def var_reset(self): ''' !@brief Method resets all internal variables to zero ''' self.var_set_A(0x0) self.var_set_B(0x0) def var_set_A(self, variable): ''' !@brief Set the vale of the internal variable instA This method will set the value of the internal variable, instA, to the value passed in to this method @param variable Interger value that instA will be set to ''' self.instA = variable def var_set_B(self, variable): ''' !@brief Set the vale of the internal variable instB This method will set the value of the internal variable, instB, to the value passed in to this method @param variable Interger value that instB will be set to ''' self.instB = variable
8012f76c6cf3f3d5dcbe799fb094aca32b91358e
chinnychin19/l3y-lossy-text-compression
/ngram_decoder.py
6,704
4.25
4
""" Note: An n-gram is a sequence of n words. In this training, we want to train based on n-grams. We'll match each n-gram of encodings to the original final word in the encoding Example: string: "Hello there I am a robot" encoded string: "h3o t3e i a0m a r3t" 3-gram 1: "h3o t3e i" --> i 3-gram 2: "t3e i a0m" --> am 3-gram 3: "i a0m a" --> a 3-gram 4: "a0m a r3t" --> robot """ #! /usr/bin/env python import sys import re PARSE_ALL_WORDS_RE_STRING = "([^\w\s]*\w(?:\d+\w)?[^\w\s]*|\S+|[\n\r\t\f]+)" WORD_GROUPS_RE_STRING = "([^\w\s]*)(\w(?:\d+\w)?)([^\w\s]*)" STATS = {} N = 1 # overridden in __main__ # performs training for n = [1,2,3,...N] def do_training(text): text = text.lower() words = re.findall("\w\S*\w|\w", text) for n in xrange(1,N+1): # [1,2,...,N] for i in xrange(len(words) + 1 - n): ngram_words = words[i:i+n] the_word = ngram_words[-1] encoded_ngram_words = [] for word in ngram_words: if len(word) is 1: encoded_ngram_words.append(word) else: encoded_ngram_words.append(word[0] + str(len(word)-2) + word[-1]) key = " ".join(encoded_ngram_words) if key not in STATS: STATS[key] = [[1, the_word]] else: poss_words = STATS[key] already_in_poss_words = False for poss_word_tuple in poss_words: if the_word == poss_word_tuple[1]: poss_word_tuple[0] += 1 already_in_poss_words = True break if not already_in_poss_words: poss_words.append([1, the_word]) def read_file(file_name): with open(file_name, 'r') as f: return f.read() # TODO: update this to work with ngrams def decode(text): # note: encoded_words might include things that aren't words encoded_words = re.findall(PARSE_ALL_WORDS_RE_STRING, text) decoded_words = [] # the first few words don't get picked up because # we haven't reached a long enough ngram yet for i in xrange(N-1): leading_word = encoded_words[i] word_groups_match = re.match(WORD_GROUPS_RE_STRING, leading_word) if not word_groups_match: # the target word does not contain a real word if re.match("\w+", leading_word): # this is just whitespace decoded_words.append(leading_word) else: # this is just punctuation decoded_words.append(leading_word + " ") else: word_groups = word_groups_match.groups() leading = word_groups[0] trailing = word_groups[2] # just decodes it using a 1-gram. Whatever. Less code. the_decoded_word = decodeNGram(word_groups[1]) decoded_word = leading + the_decoded_word + trailing + " " decoded_words.append(decoded_word) # Now the fun part :) for i in xrange(len(encoded_words)): encoded_ngram_words = encoded_words[i:i+N] the_encoded_word = encoded_ngram_words[-1] word_groups_match = re.match(WORD_GROUPS_RE_STRING, the_encoded_word) if not word_groups_match: # the target word does not contain a real word if re.match("\w+", the_encoded_word): # this is just whitespace decoded_words.append(the_encoded_word) else: # this is just punctuation decoded_words.append(the_encoded_word + " ") else: # the target contains a real word # First, prune the ngram to be only real words encoded_ngram_words = prune_to_real_word_list(encoded_ngram_words) encoding_ngram = " ".join(encoded_ngram_words) # note: encoding_ngram may be less than N elements # that's why we trained for all n in [1,2,...N] word_groups = word_groups_match.groups() leading = word_groups[0] trailing = word_groups[2] the_decoded_word = decodeNGram(encoding_ngram) decoded_word = leading + the_decoded_word + trailing + " " decoded_words.append(decoded_word) return "".join(decoded_words) # encoding is an encoded ngram def decodeNGram(encoding_ngram): last_word = encoding_ngram.split()[-1] if len(last_word) is 1: return last_word if encoding_ngram in STATS: return STATS[encoding_ngram][0][1] # if we reach here, we haven't encountered this # encoding in the training. So we just fill the # blanks with underscores num_between = int(last_word[1:-1]) return last_word[0] + ("_"*num_between) + last_word[-1] def prune_to_real_word_list(ngram): ret = [] for super_word in ngram: word_groups_match = re.match(WORD_GROUPS_RE_STRING, super_word) if word_groups_match: word_groups = word_groups_match.groups() ret.append(word_groups[1]) if len(ret) is 0: print "pruned the word list to be empty. whoops. ERROR!" quit(1) return ret if __name__ == "__main__": if len(sys.argv) != 3: print "Expected a book title and a value for N (length of n-gram)!" quit(1) # Read in the encoded file title = sys.argv[1] title_file_name = "output_texts/{}.encoded.txt".format(title) full_encoded_text = read_file(title_file_name) # Train your algorithm! N = int(sys.argv[2]) training_text_titles = ["dorian", "earnest", "frankenstein", "tarzan", "alice", "beowulf", "sawyer"] for training_title in training_text_titles: if training_title == title: continue training_file_name = "original_texts/{}.full.txt".format(training_title) training_text = read_file(training_file_name) do_training(training_text) # After training, sort all the word counts in descending order to quickly get the max for key in STATS: STATS[key] = list(reversed(sorted(STATS[key]))) print "Number of keys in training dictionary:", len(STATS.keys()) # Decode the encoded file based on the training! decoded = decode(full_encoded_text) with open("output_texts/{}.decoded.{}.txt".format(title, N), 'w') as output_file: output_file.write(decoded) # Analyze our performance! full_original_file_name = "original_texts/{}.full.txt".format(title) full_original_text = read_file(full_original_file_name) original_words = full_original_text.split() decoded_words = decoded.split() num_original_words = len(original_words) num_decoded_words = len(decoded_words) if num_original_words != num_decoded_words: print "Error in analysis! Expected {} to equal {}".format(num_original_words, num_decoded_words) quit(1) num_correct = 0 for i in xrange(num_original_words): original_word = original_words[i].lower() decoded_word = decoded_words[i].lower() if original_word == decoded_word: num_correct += 1 # else: # print "Mismatch: '{}' != '{}'".format(original_word, decoded_word) print "Percent correct: {}%".format(num_correct*10000/num_original_words/100.)
08b975612fb77f943800b1c7496c0ef8f1b3bd01
jrog20/8ball
/8ball.py
823
4.21875
4
""" File: 8ball.py Write a program to simulate a magic eight ball. The program should let the user type a yes or no question and pick a random answer from a set of 6 predetermined answers. """ import random PROMPT = "Ask a yes or no question: " def main(): question = input(PROMPT) while question != "": randnum = random.randint(1, 6) if randnum == 1: print("I think that it shall be!") if randnum == 2: print("Ask me again later") if randnum == 3: print("That's right") if randnum == 4: print("The answer is blowing in the wind!") if randnum == 5: print("A hard no") if randnum == 6: print("Absolutely!") question = input(PROMPT) if __name__ == '__main__': main()
ef5e845ae59203ee4baa4c6c760d59db294ebac3
pradeep-528/pradeep
/append_nm.py
151
4.09375
4
#!/usr/bin/python # appending names def append(): x=raw_input("enter first name:") y=raw_input("enter second name:") print x+y append()
ca2a0f68b3c8db8e57eb5f6d68123722a44c1ceb
gustanik/CNA340_Python
/turtlesWoComments.py
1,010
3.890625
4
import turtle import random wn = turtle.Screen() wn.bgcolor('lightblue') wn.title("Turtle Race") lance = turtle.Turtle() andy = turtle.Turtle() lance.color('red') andy.color('blue') lance.shape('turtle') andy.shape('turtle') andy.up() lance.up() andy.goto(-100, 20) lance.goto(-100, -20) start = turtle.Turtle() # OPTIONAL- start.hideturtle() for i in range(150): andyDistance = random.randrange(1, 5) lanceDistance = random.randrange(1, 5) andy.forward(andyDistance) lance.forward(lanceDistance) andyTotalDistance = andyTotalDistance + andyDistance lanceTotalDistance = lanceTotalDistance + lanceDistance for eachInt in range(145): if andyTotalDistance > lanceTotalDistance: start.write("Andy is the winner!", move=False, align="center", font=("Arial", 25, "normal")) elif lanceTotalDistance > andyTotalDistance: start.write("Lance is the winner!", move=False, align="center", font=("Arial", 25, "normal")) else: print("Tie Game") wn.exitonclick()
21648b4c978560ff5ee35b36d248ccfa2353234c
666sempron999/Abramyan-tasks-
/Integer(30)/9.py
411
4.0625
4
''' Integer9 ◦ . Дано трехзначное число. Используя одну операцию деления нацело, вывести первую цифру данного числа (сотни). ''' A = int(input("Введите А: ")) while A > 999 or A < 100: print(A) A = int(input("Введите А: ")) a,b = divmod(A,100) print('Новое число - ',a)
9c3de80466678b31a4e895357250f54d825207d8
RichardRuth/Python_Rectangle_Calculator
/rectangles.py
1,763
4.59375
5
#!/usr/bin/env python3 #COP2002.0M1 Programming Logic #Module 13 Project 13-1 Rectange Calculator Program #Submitted by Richard Ruth # Program obtains rectangle height and width data from user, and # and calculates and displays duration of travel, as well as estimated date of arrival and time of arrival # Rectangle class stores height and width attributes of rectangle user data, and provides methods # that calculate perimeter and area of rectangle, and draws string representation of rectangle class Rectangle: def __init__(self, height, width): self.height = height self.width = width def getArea(self): return self.height * self.width def getPerimeter(self): return (2 * self.height) + (2 * self.width) def printRectangle(self): edge_row = "* " * self.width center_row = "*" + ' '*(self.width - 2) + " *" rectangle_rows = [edge_row] + [center_row]*(self.height - 2) + [edge_row] print('\n'.join(rectangle_rows)) def main(): # Main module obtains user data for rectangle and creates userRectangle object from Rectangle class # to display perimter, area, and string representation of user's rectangle print("\nRectangle Calculator\n") choice = "y" while choice.lower() == "y": height = int(input("Height: ")) width = int(input("Width: ")) userRectangle = Rectangle(height, width) print("Perimeter:", userRectangle.getPerimeter()) print("Area: ", userRectangle.getArea()) userRectangle.printRectangle() print() choice = input("Continue? (y/n): ") print() # If this module is the main module, call the main() function if __name__ == "__main__": main()
0e72a5edc26bc7daf1aeb0f6c32ac873cf7354c6
garimasinghgryffindor/holbertonschool-machine_learning
/unsupervised_learning/0x02-hmm/2-absorbing.py
937
3.875
4
#!/usr/bin/env python3 """ Determines if a markov chain is absorbing """ import numpy as np def absorbing(P): """ Determines if a markov chain is absorbing :param P: square 2D numpy.ndarray of shape (n, n) representing the transition matrix :return: True if it is absorbing, or False on failure """ if type(P) is not np.ndarray: return False if len(P.shape) != 2: return False n, n_t = P.shape if n != n_t: return False sum_test = np.sum(P, axis=1) for elem in sum_test: if not np.isclose(elem, 1): return False diagonal = np.diag(P) if (diagonal == 1).all(): return True absorb = (diagonal == 1) for row in range(len(diagonal)): for col in range(len(diagonal)): if P[row, col] > 0 and absorb[col]: absorb[row] = 1 if (absorb == 1).all(): return True return False
122e4ea963bf710e9accfae8fc7a726d6a501de7
google238/coder
/jianzhioffer/二维数组中的查找.py
506
3.640625
4
# -*- coding: utf-8 -*- """ 在一个二维数组中(每个一维数组的长度相同), 每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 """ class Solution: # array 二维列表 def Find(self, target, array): for item in array: if target in item: return True return False
7cf73f2928c0ec9032b67a26a08ccf46b3664ac0
serhiistr/Python-test-telegram
/classmethod.py
1,581
4.0625
4
# Class # Название класса пишутся с большой буквы class Dog(): # __init__ специальный метод, который автоматически выполняется при создании # каждого нового экземпляра класса. Т.е. отвечает за базовый функционал, # который будет отрабатываться каждый раз при создании нашего обьекта (собака :)) # self - указывает, что мы работаем конкретно с экземпляром класса Dog # self нужен только внутри класса, а при создании обьекта мы его не указываем def __init__(self, name, age): #Инициализируем аттрибуты имя и возраст self.name = name self.age = age print("Собака", name, "создана") def sit(self): print(self.name.title() + " села на место") def jump(self): print(self.name.title() + " подпрыгнула") # Теперь создаем обьект по инструкции нашей (class Dog()). Этот обьект называется экземпляр класса my_dog_1 = Dog('archi', 5) # это создали экземпляр класса Dog my_dog_2 = Dog('ben', 2) my_dog_1.sit() # обращаемся напрямую к методу, через точку my_dog_2.jump() # print(my_dog.age)
d3329492b3a0c76c3770ec0b4848471117bf0e37
Muthu123456789/muthukiller
/fact.py
182
4.0625
4
num = int(input()) factorial = 1 if num < 0: print("invalid") elif num == 0: print( 1) else: for i in range(1,num + 1): factorial = factorial*i print(factorial)
5d7b2839f9b27995a998c01fe32688ac8c744d66
fancent/CSC311
/A2/q3_materials/nn.py
14,405
4.5625
5
""" Instruction: In this section, you are asked to train a NN with different hyperparameters. To start with training, you need to fill in the incomplete code. There are 3 places that you need to complete: a) Backward pass equations for an affine layer (linear transformation + bias). b) Backward pass equations for ReLU activation function. c) Weight update equations with momentum. After correctly fill in the code, modify the hyperparameters in "main()". You can then run this file with the command: "python nn.py" in your terminal. The program will automatically check your gradient implementation before start. The program will print out the training progress, and it will display the training curve by the end. You can optionally save the model by uncommenting the lines in "main()". """ from __future__ import division from __future__ import print_function from util import LoadData, Load, Save, DisplayPlot, DisplayPlot2 import sys import numpy as np import matplotlib.pyplot as plt def InitNN(num_inputs, num_hiddens, num_outputs): """Initializes NN parameters. Args: num_inputs: Number of input units. num_hiddens: List of two elements, hidden size for each layer. num_outputs: Number of output units. Returns: model: Randomly initialized network weights. """ W1 = 0.1 * np.random.randn(num_inputs, num_hiddens[0]) W2 = 0.1 * np.random.randn(num_hiddens[0], num_hiddens[1]) W3 = 0.01 * np.random.randn(num_hiddens[1], num_outputs) b1 = np.zeros((num_hiddens[0])) b2 = np.zeros((num_hiddens[1])) b3 = np.zeros((num_outputs)) model = { 'W1': W1, 'W2': W2, 'W3': W3, 'b1': b1, 'b2': b2, 'b3': b3, 'V_W1': 0, 'V_W2': 0, 'V_W3': 0, 'V_b1': 0, 'V_b2': 0, 'V_b3': 0 } return model def Affine(x, w, b): """Computes the affine transformation. Args: x: Inputs (or hidden layers) w: Weights b: Bias Returns: y: Outputs """ # y = np.dot(w.T, x) + b y = x.dot(w) + b return y def AffineBackward(grad_y, h, w): """Computes gradients of affine transformation. hint: you may need the matrix transpose np.dot(A,B).T = np.dot(B,A) and (A.T).T = A Args: grad_y: gradient from last layer h: inputs from the hidden layer w: weights Returns: grad_h: Gradients wrt. the inputs/hidden layer. grad_w: Gradients wrt. the weights. grad_b: Gradients wrt. the biases. """ ########################### # Insert your code here. # grad_h = ... # grad_w = ... # grad_b = ... # return grad_h, grad_w, grad_b ########################### grad_h = grad_y @ w.T grad_w = h.T @ grad_y grad_b = np.sum(grad_y, axis=0) return grad_h, grad_w, grad_b def ReLU(z): """Computes the ReLU activation function. Args: z: Inputs Returns: h: Activation of z """ return np.maximum(z, 0.0) def ReLUBackward(grad_h, z): """Computes gradients of the ReLU activation function wrt. the unactivated inputs. Returns: grad_z: Gradients wrt. the hidden state prior to activation. """ ########################### # Insert your code here. # grad_z = ... # return grad_z ########################### grad_z = grad_h * np.vectorize(lambda ReLU: 1 if ReLU > 0 else 0)(z) return grad_z def Softmax(x): """Computes the softmax activation function. Args: x: Inputs Returns: y: Activation """ return np.exp(x) / np.exp(x).sum(axis=1, keepdims=True) def NNForward(model, x): """Runs the forward pass. Args: model: Dictionary of all the weights. x: Input to the network. Returns: var: Dictionary of all intermediate variables. """ z1 = Affine(x, model['W1'], model['b1']) h1 = ReLU(z1) z2 = Affine(h1, model['W2'], model['b2']) h2 = ReLU(z2) y = Affine(h2, model['W3'], model['b3']) var = { 'x': x, 'z1': z1, 'h1': h1, 'z2': z2, 'h2': h2, 'y': y } return var def NNBackward(model, err, var): """Runs the backward pass. Args: model: Dictionary of all the weights. err: Gradients to the output of the network. var: Intermediate variables from the forward pass. """ dE_dh2, dE_dW3, dE_db3 = AffineBackward(err, var['h2'], model['W3']) dE_dz2 = ReLUBackward(dE_dh2, var['z2']) dE_dh1, dE_dW2, dE_db2 = AffineBackward(dE_dz2, var['h1'], model['W2']) dE_dz1 = ReLUBackward(dE_dh1, var['z1']) _, dE_dW1, dE_db1 = AffineBackward(dE_dz1, var['x'], model['W1']) model['dE_dW1'] = dE_dW1 model['dE_dW2'] = dE_dW2 model['dE_dW3'] = dE_dW3 model['dE_db1'] = dE_db1 model['dE_db2'] = dE_db2 model['dE_db3'] = dE_db3 pass def NNUpdate(model, eps, momentum): """Update NN weights. Args: model: Dictionary of all the weights. eps: Learning rate. momentum: Momentum. """ ########################### # Insert your code here. # Update the weights. # model['W1'] = ... # model['W2'] = ... # model['W3'] = ... # model['b1'] = ... # model['b2'] = ... # model['b3'] = ... ########################### model['V_W1'] = momentum * model['V_W1'] + (1 - momentum) * model['dE_dW1'] model['V_W2'] = momentum * model['V_W2'] + (1 - momentum) * model['dE_dW2'] model['V_W3'] = momentum * model['V_W3'] + (1 - momentum) * model['dE_dW3'] model['V_b1'] = momentum * model['V_b1'] + (1 - momentum) * model['dE_db1'] model['V_b2'] = momentum * model['V_b2'] + (1 - momentum) * model['dE_db2'] model['V_b3'] = momentum * model['V_b3'] + (1 - momentum) * model['dE_db3'] model['W1'] = model['W1'] - eps * model['V_W1'] model['W2'] = model['W2'] - eps * model['V_W2'] model['W3'] = model['W3'] - eps * model['V_W3'] model['b1'] = model['b1'] - eps * model['V_b1'] model['b2'] = model['b2'] - eps * model['V_b2'] model['b3'] = model['b3'] - eps * model['V_b3'] pass def plot_uncertain_images(x, t, prediction, threshold=0.5): """ """ low_index = np.max(prediction, axis=1)< threshold class_names = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral'] if np.sum(low_index)>0: for i in np.where(low_index>0)[0]: plt.figure() img_w, img_h = int(np.sqrt(2304)), int(np.sqrt(2304)) #2304 is input size plt.imshow(x[i].reshape(img_h,img_w)) plt.title('P_max: {}, Predicted: {}, Target: {}'.format(np.max(prediction[i]), class_names[np.argmax(prediction[i])], class_names[np.argmax(t[i])])) plt.show() input("press enter to continue") return def Train(model, forward, backward, update, eps, momentum, num_epochs, batch_size): """Trains a simple MLP. Args: model: Dictionary of model weights. forward: Forward prop function. backward: Backward prop function. update: Update weights function. eps: Learning rate. momentum: Momentum. num_epochs: Number of epochs to run training for. batch_size: Mini-batch size, -1 for full batch. Returns: stats: Dictionary of training statistics. - train_ce: Training cross entropy. - valid_ce: Validation cross entropy. - train_acc: Training accuracy. - valid_acc: Validation accuracy. """ inputs_train, inputs_valid, inputs_test, target_train, target_valid, \ target_test = LoadData('./toronto_face.npz') rnd_idx = np.arange(inputs_train.shape[0]) train_ce_list = [] valid_ce_list = [] train_acc_list = [] valid_acc_list = [] num_train_cases = inputs_train.shape[0] if batch_size == -1: batch_size = num_train_cases num_steps = int(np.ceil(num_train_cases / batch_size)) for epoch in range(num_epochs): np.random.shuffle(rnd_idx) inputs_train = inputs_train[rnd_idx] target_train = target_train[rnd_idx] for step in range(num_steps): # Forward prop. start = step * batch_size end = min(num_train_cases, (step + 1) * batch_size) x = inputs_train[start: end] t = target_train[start: end] var = forward(model, x) prediction = Softmax(var['y']) plot_uncertain_images(x, t, prediction) train_ce = -np.sum(t * np.log(prediction)) / x.shape[0] train_acc = (np.argmax(prediction, axis=1) == np.argmax(t, axis=1)).astype('float').mean() print(('Epoch {:3d} Step {:2d} Train CE {:.5f} ' 'Train Acc {:.5f}').format( epoch, step, train_ce, train_acc)) # Compute error. error = (prediction - t) / x.shape[0] # Backward prop. backward(model, error, var) # Update weights. update(model, eps, momentum) valid_ce, valid_acc = Evaluate( inputs_valid, target_valid, model, forward, batch_size=batch_size) print(('Epoch {:3d} ' 'Validation CE {:.5f} ' 'Validation Acc {:.5f}\n').format( epoch, valid_ce, valid_acc)) train_ce_list.append((epoch, train_ce)) train_acc_list.append((epoch, train_acc)) valid_ce_list.append((epoch, valid_ce)) valid_acc_list.append((epoch, valid_acc)) # DisplayPlot(train_ce_list, valid_ce_list, 'Cross Entropy', number=0) # DisplayPlot(train_acc_list, valid_acc_list, 'Accuracy', number=1) # DisplayPlot2(train_ce_list, valid_ce_list, 'Cross Entropy', number=0) # DisplayPlot2(train_acc_list, valid_acc_list, 'Accuracy', number=1) # print() train_ce, train_acc = Evaluate( inputs_train, target_train, model, forward, batch_size=batch_size) valid_ce, valid_acc = Evaluate( inputs_valid, target_valid, model, forward, batch_size=batch_size) test_ce, test_acc = Evaluate( inputs_test, target_test, model, forward, batch_size=batch_size) # print('CE: Train %.5f Validation %.5f Test %.5f' % # (train_ce, valid_ce, test_ce)) # print('Acc: Train {:.5f} Validation {:.5f} Test {:.5f}'.format( # train_acc, valid_acc, test_acc)) stats = { 'train_ce': train_ce_list, 'valid_ce': valid_ce_list, 'train_acc': train_acc_list, 'valid_acc': valid_acc_list } return model, stats def Evaluate(inputs, target, model, forward, batch_size=-1): """Evaluates the model on inputs and target. Args: inputs: Inputs to the network. target: Target of the inputs. model: Dictionary of network weights. """ num_cases = inputs.shape[0] if batch_size == -1: batch_size = num_cases num_steps = int(np.ceil(num_cases / batch_size)) ce = 0.0 acc = 0.0 for step in range(num_steps): start = step * batch_size end = min(num_cases, (step + 1) * batch_size) x = inputs[start: end] t = target[start: end] prediction = Softmax(forward(model, x)['y']) ce += -np.sum(t * np.log(prediction)) acc += (np.argmax(prediction, axis=1) == np.argmax( t, axis=1)).astype('float').sum() ce /= num_cases acc /= num_cases return ce, acc def CheckGrad(model, forward, backward, name, x): """Check the gradients Args: model: Dictionary of network weights. name: Weights name to check. x: Fake input. """ np.random.seed(0) var = forward(model, x) loss = lambda y: 0.5 * (y ** 2).sum() grad_y = var['y'] backward(model, grad_y, var) grad_w = model['dE_d' + name].ravel() w_ = model[name].ravel() eps = 1e-7 grad_w_2 = np.zeros(w_.shape) check_elem = np.arange(w_.size) np.random.shuffle(check_elem) # Randomly check 20 elements. check_elem = check_elem[:20] for ii in check_elem: w_[ii] += eps err_plus = loss(forward(model, x)['y']) w_[ii] -= 2 * eps err_minus = loss(forward(model, x)['y']) w_[ii] += eps grad_w_2[ii] = (err_plus - err_minus) / 2 / eps np.testing.assert_almost_equal(grad_w[check_elem], grad_w_2[check_elem], decimal=3) def main(): """Trains a NN.""" model_fname = 'nn_model.npz' stats_fname = 'nn_stats.npz' # Hyper-parameters. Modify them if needed. num_hiddens = [16, 32] eps = 0.01 momentum = 0. num_epochs = 1000 batch_size = 100 # Input-output dimensions. num_inputs = 2304 num_outputs = 7 # Initialize model. model = InitNN(num_inputs, num_hiddens, num_outputs) # Uncomment to reload trained model here. # model = Load(model_fname) # Check gradient implementation. print('Checking gradients...') x = np.random.rand(10, 48 * 48) * 0.1 CheckGrad(model, NNForward, NNBackward, 'W3', x) CheckGrad(model, NNForward, NNBackward, 'b3', x) CheckGrad(model, NNForward, NNBackward, 'W2', x) CheckGrad(model, NNForward, NNBackward, 'b2', x) CheckGrad(model, NNForward, NNBackward, 'W1', x) CheckGrad(model, NNForward, NNBackward, 'b1', x) # Train model. model, stats = Train(model, NNForward, NNBackward, NNUpdate, eps, momentum, num_epochs, batch_size) # Uncomment if you wish to save the model. Save(model_fname, model) # Uncomment if you wish to save the training statistics. Save(stats_fname, stats) if __name__ == '__main__': main()
104bd40e38b212aa8d52362d86bd06e221e5d39a
alveraboquet/Class_Runtime_Terrors
/Students/tom/Lab 10/lab_10_peaks_valleys.py
913
4.03125
4
data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] # length is 21 peak_location = 0 peak_value = 0 data_length = len(data) def peak (data, data_length): peaks = {} x = 0 while x < data_length-3: if data[x] < data[x + 1] and data[x + 1] > data[x + 2]: peaks.update({x + 1 : data[x + 1]}) x += 1 return peaks def valley (data): data_length = len(data) valleys = {} x = 0 while x < data_length-3: if data[x] > data[x + 1] and data[x + 1] < data[x + 2]: valleys.update({x + 1 : data[x + 1]}) x += 1 return valleys def print_text_results(data): for key in data: print (f'A peak was located at index location {key} with a value of {data[key]}') def main(): peaks = peak(data, data_length) valleys = valley(data) print_text_results(peaks) print_text_results(valleys) main()
866e5dc298dd20c0c1be74d10d676a53b3216632
HubblEDev1/Ejercicios-de-python
/pf_03.py
1,034
3.671875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 27 00:35:55 2019 @author: HiramGC 3. Given a text message containing only letters (lowercase) and spaces, write a Python program to returns the minimum click distance to produce the message. To calculate the distance, you can only move in the keyboard up, down, right and left (not in diagonal), and cannot go directly to the space bar. Consider that the keyboard has a QWERTY distribution, with the space bar located next to the letter ‘m’, as follows: Keyboard = [‘qwertyuiop’, ‘asdfghjkl’, ‘zxcvbnm ‘] """ keyboard = ['qwertyuiop','asdfghjkl','zxcvbnm '] s = 'q e' l = [] for c in s: for i,v in enumerate(keyboard): if c in v: x = i y = v.index(c) break l.append(x) l.append(y) print(keyboard[x][y]) count = 0 print(l) n = len(l) for i in range(2,n,2): x1 = l[i] x2 = l[i-2] y1 = l[i+1] y2 = l[i-1] count += abs(x1 - x2) + abs(y1 - y2) # print(keyboard[x][y]) print(count)
6ebf7fe253333f896dd6d6c7bf3f9f7a25be6d76
Jungeol/algorithm
/leetcode/easy/155_min_stack/django.py
1,039
3.796875
4
""" https://leetcode.com/problems/min-stack/ Runtime: 48 ms, faster than 99.36% of Python3 online submissions for Min Stack. Memory Usage: 16.2 MB, less than 100.00% of Python3 online submissions for Min Stack. """ class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.minVal = None def push(self, x: int) -> None: self.stack.append(x) if self.minVal is None: self.minVal = x else: self.minVal = min(self.minVal, x) def pop(self) -> None: popVal = self.stack.pop() if not self.stack: self.minVal = None elif popVal == self.minVal: self.minVal = min(self.stack) def top(self) -> int: return self.stack[-1] def getMin(self) -> int: return self.minVal # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
ded8f9ba743df9d4a77022099e4b98fb0f335cb2
sharkseba/taller-progra
/EjerciciosGuía1/ejercicio8.py
274
4.0625
4
#Escriba un algoritmo que solicite dos números y calcule la función f(x, y) = 2x + 3y2. # Entradas x = float(input('Ingrese el valor de x: ')) y = float(input('Ingrese el valor de y: ')) # Proceso resultado = 2*x + 3*y**2 # Salidas print('El resultado es',resultado)
ca999a37bbfc582c756ee59e21638daaff0d5e36
maxotar/algorithms
/tests/test_insertionSort.py
192
3.546875
4
from algorithms.insertionSort import insertionSort def test_insertionSort(): alist = [4, 6, 8, 7, 5, 1, 2, 3, 9] insertionSort(alist) assert alist == [1, 2, 3, 4, 5, 6, 7, 8, 9]
a5aace972d0792ee05e4e41204bbd28d47d45fc9
Jocelyn9090/CS1301xII_extra_ex
/RemoveCapitals.py
3,857
4.78125
5
#Write a function called remove_capitals. remove_capitals #should accept one parameter, a string. It should return a #string containing the original string with all the capital #letters removed. Everything else should be in the same #place and order as before. # #For example: # # remove_capitals("A1B2C3D") -> "123" # remove_capitals("WHAT") -> "" # remove_capitals("what") -> "what" # #Remember, capital letters have ordinal numbers between 65 #("A") and 90 ("Z"). You may use the ord() function to get #a letter's ordinal number. # #Your function should be able to handle strings with no #capitals (return the original string) and strings with all #capitals (return an empty string). You may assume we'll #only use regular characters (no emojis, formatting #characters, etc.). #Write your function here! def remove_capitals(string): #Create string with value "" res = "" #Looping through each character of the input s for i in string: #Check the character is not an upper case if (not i.isupper()): #Add non upper res += i #return result return res #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #123 #eorgia nstitute of echnology print(remove_capitals("A1B2C3D")) print(remove_capitals("Georgia Institute of Technology")) ORRRR #We first write a function called remove_capitals as told in the #instructions with the parter of a string. def remove_capitals(String): #We are asked to remove all the capitals and are given #the range 65 and 95. We take advantage of this as we #know that each character in python has an ordinal number. # #There are two ways of going about this problem. You could #either compare the characters or compare ordinal numbers # #Note: It is easier to compare characters since you do not have #to memorize any values! # #You can check solution 2 if you want to see how the problem #can be solved using ordinal numbers. For this solution, I’ll be #using characters. # #The way we want to approach this is to traverse through #the given string, and only have characters which are not #capital letters remaining. # #We MUST create an empty string because strings are #immutable! ans = "" #We use a for-loop because we know exactly the #number of times we want to iterate. for char in String: #Within this for-loop we write an if-statement to filter out #which character is a capital letter or not. if char < "A" or char > "Z": #Notice that we are looking for characters that are less than #”A” and greater than “Z”. This is because everything in between #is a capital letter. (Pretty logical) #If the condition passes, then we know we can concatenate it to our #empty string. ans += char #Once we are done traversing through the entire #string and have filtered out the character we want, we #write a return statement with the answer! return ans ORRRRR #The thought process is the same as solution 1, but the one #thing that is different is how we write our conditional in order #to determine whether the character we are traversing through #in the string is a capital letter or not. def remove_capitals(String): ans = "" for char in String: #Notice that we have to use ord(char) in order to #have python know that we are going to be using the ordinal number #of the character. If you write: #char < 65 #you will error since you are comparing a string with an int. #If you know your ordinal numbers, you can take this approach, but #visually, I would say that it is easier to see what you are comparing #when you are simply comparing strings. if ord(char) < 65 or ord(char) > 90: ans += char return ans
3421fa2c157c8ac9681819a6858df7fa482ecc4a
qnadeem/solutions_to_some_programming_puzzles
/ninth/prB.py
2,565
3.890625
4
x = raw_input() while( x!= "#"): x = x.split() N = int(x[0]) A = int(x[1]) B = int(x[2]) pos = [] for i in range(N): x = raw_input() pos.append(int(x)) pos.sort() cost = 0 index = 0 #till N WIFI = [] while index != N: atcow = index if atcow+1 == N: #at end.. cost += A index += 1 #print "WiFi at " + str(pos[atcow]) + "because last cow" else: # first check if can NOT install wifi between the cows. that is separate on point wifis for the first cow. midcost = ((pos[atcow+1]-pos[atcow])/2.0)*B if midcost >= A: cost += A index += 1 #print "WiFi at " + str(pos[atcow]) + "because midcost is >= A" else: # should install wifi between these 2, or these 3, or these 4 etc.. prevmidcost = midcost endcow = atcow+1 midcost = ((pos[endcow]-pos[atcow])/2.0)*B while midcost < prevmidcost+A and (endcow < N-1): endcow += 1 prevmidcost = midcost midcost = ((pos[endcow]-pos[atcow])/2.0)*B if endcow< N-1: # make wifi between all these cows. midcost = ((pos[endcow-1]-pos[atcow])/2.0)*B cost += A + midcost index = endcow #print "WiFi at " + str(pos[atcow]+(pos[endcow-1]-pos[atcow])/2.0) + " which is a midpoint which looks good" else: if midcost < prevmidcost+A: midcost = ((pos[endcow]-pos[atcow])/2.0)*B cost += A + midcost index = endcow+1 #print "WiFi at " + str(pos[atcow]+(pos[endcow]-pos[atcow])/2.0) + " which is a midpoint which looks good" else: midcost = ((pos[endcow-1]-pos[atcow])/2.0)*B cost += A + midcost index = endcow #print "WiFi at " + str(pos[atcow]+(pos[endcow-1]-pos[atcow])/2.0) + " which is a midpoint which looks good" print cost x = raw_input()
153e8acc663f1899927b538baecc4c509a546c0f
wangyunpengbio/LeetCode
/146-LRUCache.py
1,112
3.953125
4
class LRUCache: # 自己的python 3 写法,超时 def __init__(self, capacity: int): self.queue = [] self.queuecapacity = capacity def get(self, key: int) -> int: # print("get",self.queue) curLen = len(self.queue) i = curLen - 1 while i >= 0: item = self.queue.pop(i) res = item.get(key) if res != None: self.queue.append(item) return res else: self.queue.insert(i,item) i = i - 1 return -1 def put(self, key: int, value: int) -> None: for i in range(len(self.queue)): if key in self.queue[i].keys(): del self.queue[i] break if len(self.queue) < self.queuecapacity: self.queue.append({key:value}) else: self.queue.pop(0) self.queue.append({key:value}) # print("put",self.queue) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
08f1e1f9f7d0572fbd280d61e238a9332cff095e
deinoo/python
/flyNerd/zad7_04.py
949
4.3125
4
''' Write a simple program that will execute a user-specified number of times. Each time the loop is started, it will ask for natural number and then display information: - is the number a multiple of 3? - is the number a multiple of 4 - 'Yay' if the number is divided by both 3 and 4 - display an asterisk if none of the above conditions are met ''' counter = int(input('How many times you would like to check number?: ')) for i in range (counter): a3 = a4 = a12 =0 number=int(input('Enter number to check: ')) if number % 3 ==0: print ('Number {} is divisible by 3'.format(number)) a3 = 1 if number % 4 == 0: print('Number {} is divisible by 4'.format(number)) a4 = 1 if a3 == a4 == 1: print('Yay! Number {} is divisible by 12'.format(number)) a12 = 1 if a3 == 0 or a4 == 0 or a12 ==0: print ('*') print ('We end here, we did {} checks for you'.format(counter))
a538527157c8a90292b49c45cef2bd42caf89fa7
mmveres/python05_12_2020
/ua/univer/lesson04/recursion.py
260
3.78125
4
# n! = n*(n-1)! 5! = 5*4*3*2*1 def fact_rec(n): if n==0 or n==1: return 1 return n * fact_rec(n-1) def fact_iter(n): fact = 1 for i in range(2,n+1): fact*=i return fact if __name__ == '__main__': print(fact_iter(5))
105555e6d57e3453ed6ebf96f8405e6cf231f28b
lizchow/CodeITSuisseEntryChallenge2021
/robot.py
2,257
3.65625
4
from datetime import timedelta class Robot: HOURS_PER_SHIFT = 8 BREAK_HOUR = 1 def __init__(self, standard_day, standard_night, extra_day, extra_night): self.std_day_rate = standard_day self.std_night_rate = standard_night self.extra_day_rate = extra_day self.extra_night_rate = extra_night # Returns true if the shift_date is a weekday, false otherwise def is_weekday(self, shift_date): return shift_date.weekday() < 5 # Returns the chargeable rate for a given datetime def get_rate(self, shift_date): if self.is_weekday(shift_date) and self.std_day_rate.time_in_range( shift_date): return self.std_day_rate elif self.is_weekday(shift_date): return self.std_night_rate elif (not self.is_weekday(shift_date) and self.extra_day_rate.time_in_range(shift_date)): return self.extra_day_rate else: return self.extra_night_rate # Returns the total cost of the robot given that the robot is # continuously working from the start_time to the end_time def value_of_interval(self, start_time, end_time): temp_start_time = start_time total_value = 0 while (temp_start_time < end_time): rate = self.get_rate(temp_start_time) value, lapsed_time = rate.calculate_value(temp_start_time, end_time) total_value += value temp_start_time += timedelta(minutes=lapsed_time) return total_value # Returns the total cost of the robot when the robot works from # the start time to end time with breaks in between def get_total_value(self, start_time, end_time): temp_start_time = start_time total_value = 0 while (temp_start_time < end_time): temp_end_time = min( end_time, temp_start_time + timedelta(hours=self.HOURS_PER_SHIFT)) total_value += self.value_of_interval(temp_start_time, temp_end_time) temp_start_time = temp_end_time + timedelta(hours=self.BREAK_HOUR) return total_value
2c15e83a07b09281f4e7fdfdccd19913153307b8
bus1029/HackerRank
/ProblemSolving/Implementation/DesignerPDFViewer.py
613
3.546875
4
#!/bin/python3 import math import os import random import re import sys # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): word = word.upper() # Using ASCII heights = [h[ord(w)-65] for w in word] # for w in word: # if height <= h[ord(w)-65]: # height = h[ord(w)-65] return len(word) * max(heights) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') h = list(map(int, input().rstrip().split())) word = input() result = designerPdfViewer(h, word) fptr.write(str(result) + '\n') fptr.close()
c1433e9aced160aad6ff8e1c6bdd929f9c16ac6b
positroncascade/StochasticTurbulenceGeneration
/updater.py
4,821
3.9375
4
# Make the code agnostic to python version # In Python 2 the print function is special and called without parenthesis # also '/' is used for integer division (5/2 == 2) while in Python 3 that # role is reserved for '//' (5/2 == 2.5 and 5//2 == 2) from __future__ import print_function,division import sys if sys.version_info < (3,): # Python 2 automatically executes text passed in input() input = raw_input # In Python 2 range is a full blown list instead of a generator range = xrange import numpy as np from generator import wavenumbers def frequencyToAvoidPeriodicity(gen, wind_x, wind_y): """Uses a the same decorrelation frequency for all modes, chosen such that one decorrelation time passes in the time it takes for a frozen field to loop back on itself. """ tx = gen.Lx/wind_x ty = gen.Ly/wind_y return lambda K: 1/min(tx,ty) def KolmogorovFrequency(gen, k0): """Uses dimensional analysis in the Kolmogorov way to compute characteristic decorrelation frequencies for each wavenumber. k0 -- The wavenumber at which the decorrelation time is one time unit """ return lambda K: (K/k0)**(2/3) def KraichnanFrequency(gen, w0): """Uses the approach of Kraichnan (1970): All frequencies are independent gaussians with given variance. Furthermore, the time evolution is deterministic. k0 -- The wavenumber at which the decorrelation time is one time unit """ return lambda K: 1j*w0*np.random.standard_normal(K.shape) def frequencyToAvoidPeriodicityAndKolmogorov(gen,wind_x,wind_y,k0): tx = gen.Lx/wind_x ty = gen.Ly/wind_y w_min = 1/min(tx,ty) return lambda K: w_min*(1 + (K/k0)**2)**(1/3) class IndependentUpdater: """Computes an independent realization when called""" def update(self, gen, dt): gen.independent_realization() #def __init__(self): # Nothing class IntrinsicUpdater: def compute_frequencies(self, gen, frequency): """Compute the frequencies of intrinsic variation. The supplied function takes a 3D numpy array of spatial frequencies and returns temporal frequencies for each. They are allowed to be complex. The real part is used as a decorrelation frequency while the imaginary part represents an oscillation. frequency -- Temporal frequency from wavenumber function handle """ # Generate a 3D grid (by broadcasting) kx = wavenumbers(gen.Nx,gen.Lx).reshape((gen.Nx,1,1)) ky = wavenumbers(gen.Ny,gen.Ly).reshape((1,gen.Ny,1)) kz = wavenumbers(gen.Nz,gen.Lz).reshape((1,1,gen.Nz)) # Compute the magnitude of the wavevector at each point K = np.sqrt(kx**2 + ky**2 + kz**2) # Compute and store the frequencies self.W = frequency(K) def update(self, gen, dt): """Update each wavemode as an Ornstein-Uhlenbeck process nk(t+dt) = b*nk(t) + a*sqrt(1-b*conj(b))*xi """ # Split the calculation in an effort to reduce memory requirements dN = np.random.randn(gen.Nx,gen.Ny,gen.Nz) + 0j dN += 1j*np.random.randn(gen.Nx,gen.Ny,gen.Nz) # Note that having unit variance on both the imaginary and real # parts is correct. Because that is how 'N' is generated in the # first place. No 1/sqrt(2) "correction" should be applied. dN *= gen.A dN *= np.sqrt((1-np.exp(-2*dt*np.real(self.W)))) gen.N *= np.exp(-dt*self.W) gen.N += dN def __init__(self, gen, frequency): if callable(frequency): self.compute_frequencies(gen, frequency) else: self.W = frequency class FrozenFieldUpdate: def compute_wind_induced_phase(self, gen, dt): # Generate 2D grid that can be broadcast to 3D when needed kx = wavenumbers(gen.Nx,gen.Lx).reshape((gen.Nx,1,1)) ky = wavenumbers(gen.Ny,gen.Ly).reshape((1,gen.Ny,1)) # Note that all factors of 2pi are already included in the k's return np.exp(1j*dt*(kx*self.wind_x + ky*self.wind_y)) def update(self, gen, dt): # Translate the field by Fourier interpolation gen.N *= self.compute_wind_induced_phase(gen, dt) def __init__(self, wind_x=0, wind_y=0): self.wind_x = wind_x self.wind_y = wind_y class DynamicWindUpdate: def compute_wind_phase_from_velocity(self, gen, wind_x, wind_y): kx = wavenumbers(gen.Nx,gen.Lx).reshape((gen.Nx,1,1)) ky = wavenumbers(gen.Ny,gen.Ly).reshape((1,gen.Ny,1)) z = np.linspace(0, gen.Lz, gen.Nz) self.windPhasePerTime = kx*self.wind_x(z) + ky*self.wind_y(z) def update(self, gen, dt): # Transform to n(z,k)-space n = np.fft.fft(gen.N, axis=2) # Apply wind n *= np.exp(1j*dt*self.windPhasePerTime) # Transform back to use in next iteration gen.N = np.fft.ifft(n, axis=2) def __init__(self, gen, wind_x, wind_y): self.compute_wind_phase_from_velocity(self, gen, wind_x, wind_y)
eb47f050d4a93ab710d2849648fb122ba3362370
Jthami05/Artificial-Intelligence
/Project4/population.py
1,090
3.59375
4
from Tour import Tour class Population: # passing populationSize won't change the actual population size, b/c we use populationSize() which gets the length of the tour. def __init__(self, populationSize, initialize, numCities): self.tours = [] for i in range(0, populationSize): self.tours.append(None)#*populationSize if (initialize == True): for i in range(0, populationSize): #print "generating tour " + str(i) + "..." newTour = Tour(numCities, i) # pass i as id of this tour newTour.generateIndividual() self.saveTour(i, newTour) def saveTour(self, index, tour, elite = False): #self.tours.append(tour) self.tours[index] = tour def getTour(self, index): return self.tours[index] def getFittest(self): fittest = self.tours[0] #print fittest.__class__ for i in range(1, self.populationSize()): # this uses index of 1, if there's an indexing error it could be this if (fittest.getFitness() <= self.getTour(i).getFitness()): fittest = self.getTour(i) return fittest def populationSize(self): return len(self.tours)
f345e85a421862125d5d0a758e4397c1ca4e9746
Iigorsf/Python
/ex038.py
454
3.953125
4
#Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem: #O primeiro valor é maior #O Segundo valor é maior #Não existe valor maior, os dois são iguais num= int(input("Digite um número: ")) num2= int(input("Digite outro número: ")) if num > num2: print("O primeiro valor é maior") elif num < num2: print("O segundo valor é maior") else: print("Não existe valor maior, os dois são iguais")
5cdc4fe57eadb539fab1d76aa3b42906a39cff95
mengdage/practices
/monotone/next.py
924
3.59375
4
def next_smaller(nums): ns = [-1] * len(nums) stack = [] stack.append(len(nums) - 1) for i in range(len(nums) - 2, -1, -1): # pop invalid indexes while stack and nums[stack[-1]] > nums[i]: stack.pop() # check if a vlaid index exists if stack and nums[stack[-1]] < nums[i]: ns[i] = stack[-1] # the current index is always a candidate stack.append(i) return ns def next_greater(nums): l = len(nums) ng = [-1] * l stack = [] stack.append(l-1) for i in range(l-2, -1, -1): while stack and nums[stack[-1]] <= nums[i]: stack.pop() if stack and nums[stack[-1]] > nums[i]: ng[i] = stack[-1] stack.append(i) return ng if __name__ == '__main__': n1 = [4, 8, 5, 7, 3, 2] n2 = [91, 10, 3, 22, 40] print(next_smaller(n1)) print(next_greater(n2))
c707d967ac3009fa72490788a7f10614feec3a2d
willwearing/cs-guided-project-graphs-ii
/src/lesson.py
2,509
3.8125
4
class GraphNode: def __init__(self, value): self.value = value self.edges = [] def __repr__(self): return f"GraphNode({repr(self.value)})" # Build this by hand here a = GraphNode("A") b = GraphNode("B") c = GraphNode("C") d = GraphNode("D") e = GraphNode("E") f = GraphNode("F") g = GraphNode("G") a.edges = [c, d, b] b.edges = [e, a] c.edges = [d] d.edges = [f, e] e.edges = [f] f.edges = [g] from collections import deque def bft(starting_node): # Init: add the first node to the queue queue = deque() queue.append(starting_node) # enqueue # Keep track of visited nodes visited = set() # Loop while queue isn't empty while len(queue) != 0: # dequeue first node n = queue.popleft() # dequeue # if already visited: continue if n in visited: continue # visit it print(n.value) # add to visited set visited.add(n) # enqueue all the neighbors for neighbor in n.edges: queue.append(neighbor) # enqueue bft(a) def bfs(starting_node, ending_node): # Keep track of paths so far paths = {} # Init: add the first node to the queue queue = deque() queue.append(starting_node) # enqueue paths[starting_node] = [starting_node.value] # Keep track of visited nodes visited = set() # Loop while queue isn't empty while len(queue) != 0: # dequeue first node n = queue.popleft() # dequeue # if already visited: continue if n in visited: continue # visit it #print(n.value, paths[n]) # add to visited set visited.add(n) # enqueue all the neighbors for neighbor in n.edges: # Update path to this neighbor """ path_to_n = paths[n] path_to_neighbor = path_to_n + [neighbor.value] paths[neighbor] = path_to_neighbor """ if neighbor not in paths: paths[neighbor] = paths[n] + [neighbor.value] # These are the droids we're looking for if neighbor == ending_node: return paths[neighbor] #print(f"Going from {n.value} to {neighbor.value}") queue.append(neighbor) # enqueue #print(f"queue: {queue}") # If we got here, didn't find anything return None print(bfs(a,a)) # shortest path from a to f
0c83c9d54c0e6c8063386586dbb3d0f17217b53c
odysseus/rl_blackjack
/blackjackgame.py
8,326
4.125
4
from deck import * class Hand: """A list of cards representing a single hand in blackjack""" def __init__(self, cards=[]): """Initializes the cards list""" self._cards = cards self._soft = False def __str__(self): """The string representation of the list and contained cards""" return str(self._cards) def __repr__(self): """Same as __str__""" return str(self) def __len__(self): """Length of the cards list""" return len(self._cards) def __iter__(self): """Iterator over the cards list""" return iter(self._cards) def __add__(self, other): """Add a card or cards to the hand using `+` Args: other: The cards to add, can be either an array of Card objects, a Hand object, or a single Card Raises: TypeError: When `other` is an invalid type """ if type(other) == list: self._cards = self._cards + other elif type(other) == Hand: self._cards = self._cards + other._cards elif type(other) == Card: self._cards.append(other) else: raise TypeError("Invalid type for <Hand> + <Type>") @property def contains_ace(self): """Returns True if the hand contains an Ace""" for card in self: if card.value == 1: return True return False @property def soft(self): """Checks the current total and returns True on soft totals A soft total is an Ace being counted as 11 but could count as 1 """ self.total return self._soft @property def cards(self): """Readonly access to the cards list""" return self._cards @property def total(self): """Returns the (Blackjack) total for the hand Aces are handled automatically """ total = 0 for card in self._cards: total += card.value if total <= 11 and self.contains_ace: self._soft = True return total + 10 else: self._soft = False return total @property def bust(self): """True if the hand total is > 21""" return self.total > 21 class BlackjackGame: def __init__(self): """Creates a game with a deck, one player, and dealer""" self._deck = Deck() self._deck.shuffle() self._dealer = Hand() self._player = Hand() self._player_standing = False self._prevstate = None @property def dealer(self): """Readonly access to the dealer's hand""" return self._dealer @property def player(self): """Readonly access to the player's hand""" return self._player @property def active(self): """Returns True if the player can still choose to Hit""" return (not self.player_standing and not self.player_bust) @property def player_standing(self): """True if the player has chosen to stand during the current hand""" return self._player_standing @property def dealer_upcard(self): """Returns the face value of the dealer's upcard""" upcard = self.dealer.cards[0].value if upcard == 1: return 11 else: return upcard @property def dealer_total(self): """Returns the dealer's total hand value""" return self.dealer.total @property def player_total(self): """Returns the player's total hand value""" return self.player.total @property def player_bust(self): """True if the player has busted""" return self.player.bust @property def dealer_bust(self): """True if the dealer has busted""" return self.dealer.bust @property def prevstate(self): return self._prevstate def prevstate_tup(self, action): """Returns a string summarizing the previous state The information is from the player's perspective so includes only the players hand total and dealer's upcard, along with the action chosen. self._prevstate will be None on new hands where the player has not chosen an action (setting to None is handled in self.deal()) Args: action: The action chosen, either 'Hit' or 'Stand' EG: 'S17-8 Hit'-- Player had a soft 17, dealer upcard was 8, player chose to hit """ soft = 'S' if self.player.soft else 'H' return (f"{soft}{self.player_total}-{self.dealer_upcard}", action) def deal(self): """Removes old hands and deals new ones""" self._prevstate = None self._player_standing = False self._dealer = Hand(self.safe_draw(2)) self._player = Hand(self.safe_draw(2)) def safe_draw(self, n): """Draws cards without raising an EmptyDeckError If not enough cards remain to be drawn, creates and shuffles a new deck before drawing. Args: n: Number of cards to draw Returns: A list of Card objects """ cards = [] try: cards = self._deck.draw(n) except EmptyDeckError: self._deck = Deck() self._deck.shuffle() cards = self._deck.draw(n) return cards def player_hit(self): """Adds one card to the players hand from the top of the deck""" self._prevstate = self.prevstate_tup('hit') self.player + self.safe_draw(1) def dealer_hit(self): """Adds one card to the dealer's hand from the top of the deck""" self.dealer + self.safe_draw(1) def player_stand(self): """Action method used when the player chooses to stand""" self._prevstate = self.prevstate_tup('stand') self._player_standing = True def outcome_str(self): """Returns a string describing the outcome ['Win'|'Loss'|'Push']""" if not self.player_bust and self.player_total > self.dealer_total: return "Win" elif not self.player_bust and self.dealer_bust: return "Win" elif self.player_total == self.dealer_total: return "Push" else: return "Loss" def outcome_descr(self): """Describes the outcome in more detail For 'Win' mentions whether this is a result of the dealer busting or the player having a higher total. For 'Loss' whether the player busted or the dealer had a higher total. """ outcome = self.outcome_str() if outcome == 'Win': if self.dealer_bust: return 'Dealer busted' else: return 'Player won' elif outcome == 'Loss': if self.player_bust: return 'Player busted' else: return 'Dealer won' else: return 'Tie' def state(self): """Returns a dictionary with the current state of the game Different keys are returned depending on whether the game is 'active', ie: The player still has decisions to make, versus 'not active' where the player has either busted or chosen to stand. When called on a 'not active' game it returns the outcome (Win|Push|Loss) as well as a more detailed description of the outcome (eg: 'Player busted') """ state = {} if self.active: state["active"] = True state["player_total"] = self.player_total state["dealer_upcard"] = self.dealer_upcard state['player_soft'] = self.player.soft state['dealer_soft'] = self.dealer.soft state['prevstate'] = self.prevstate else: state["active"] = False state["player_total"] = self.player_total state["dealer_total"] = self.dealer_total state["player_bust"] = self.player_bust state["dealer_bust"] = self.dealer_bust state['prevstate'] = self.prevstate state["outcome"] = self.outcome_str() state["description"] = self.outcome_descr() return state
347188cbfae2505c4b0b283ce43ba29a630aa914
mangeshii/hackerrank-python-practice
/Strings/door_mat.py
978
4.21875
4
''' Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: Mat size must be N*M. (N is an odd natural number, and M is 3 times N.) The design should have 'WELCOME' written in the center. The design pattern should only use |, . and - characters. Input Format A single line containing the space separated values of and . Output Format Output the design pattern. Sample Input 9 27 Sample Output ------------.|.------------ ---------.|..|..|.--------- ------.|..|..|..|..|.------ ---.|..|..|..|..|..|..|.--- ----------WELCOME---------- ---.|..|..|..|..|..|..|.--- ------.|..|..|..|..|.------ ---------.|..|..|.--------- ------------.|.------------ ''' n, m = map(int, input().split()) s = '.|.' p = 'WELCOME' # upper half for i in range(n//2): print((s*((i*2)+1)).center(m, '-')) # middle print(p.center(m, '-')) # lower half for i in range(n//2-1, -1, -1): print((s*((i*2)+1)).center(m, '-'))
09e4402734181f8e3834c373b7e9f375bb9dc217
dhrumil-shah/leetcode-python
/19-removeNthNodeFromEndOfList.py
727
3.65625
4
""" 19. Remove Nth Node From End of List """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: nodeArray = [] node = head while (node is not None): nodeArray.append(node) node = node.next length = len(nodeArray) if (n == length): return head.next prevNode = nodeArray[length-(n+1)] if (n>1): nextNode= nodeArray[length-(n-1)] prevNode.next = nextNode else: prevNode.next = None return head
7735804b50d69a9cba755209863a766e5bb46df3
pranavgarg/algorithms
/ik/strings/binary_search_recursion.py
432
3.875
4
''' binary search using recursion ''' def binary_search(s,t): l = len(s)-1 print find(s,t,0,l) def find(s,t, start, end): if start > end: return -1 mid = start + (end - start) / 2 if s[mid] == t: return mid elif t < s[mid]: return find(s, t, start, mid-1) else: return find(s, t, mid+1, end) assert binary_search("abcd","k") == -1 assert binary_search("abcd","a") == 0
6d38c97f0dc2e4799b42a5175907ca96f8651846
mh70cz/py
/misc/pyr.py
329
3.96875
4
'''build a pyramid via recursive funcion''' def pyr_rec(height, right_shift=0): '''recursive pyramid''' if height == 1: return right_shift * " " + "*" else: line = right_shift * " " + ((height -1) * 2 + 1) * "*" return pyr_rec(height - 1, right_shift + 1) + "\n" + line print(pyr_rec(6, 2))
e4a3f89debc0811970e92f94e670aefb7a44b2f8
uma-c/CodingProblemSolving
/hash/is_happy.py
1,043
4.03125
4
''' Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy. Return true if n is a happy number, and false if not. Example 1: Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 Example 2: Input: n = 2 Output: false Constraints: 1 <= n <= 2**31 - 1 ''' def sum_of_sq_of_digits(n : int) -> int: result = 0 while n != 0: d = n % 10 result += d * d n //= 10 return result def isHappy(n: int) -> bool: s = set() while n != 1: sd = sum_of_sq_of_digits(n) if sd in s: return False s.add(sd) n = sd return True if __name__ == "__main__": print(isHappy(2))
d755a66589c50124ce117861a6ce6ad2a7c085c2
fossabot/SchoolProjects_v2
/22_is_prime.py
633
4.15625
4
"Write a Program to show whether the entered number is prime or not" def is_prime(number:int) -> bool: # Edge Cases if number == 1: return False # loop through all numbers from 2 to number and check remainder for i in range(2, number): if number % i == 0: return False return True def main(): __input = int(input("Enter number to check: ")) if is_prime(__input): print(f"Number {__input} is Prime") else: print(f"Number {__input} is not Prime") if __name__ == "__main__": main() __OUTPUT__ = """ Enter number to check: 13 Number 13 is Prime """
ffe4c4a614ad3ae36d02531ed69bcdb13f0d2ef5
jonstrutz11/AdventOfCode2020
/08.py
2,895
3.828125
4
"""Advent of Code - Problem 8""" from typing import List def read_instructions(filepath: str) -> List[str]: """Read instructions from file.""" with open(filepath, 'r') as infile: instructions = [line.strip() for line in infile.readlines()] return instructions class BootCode(): """Store and process instructions from game console boot code.""" def __init__(self) -> None: self.instructions = [] self.accumulator = 0 self.current_instruction_i = 0 def load_instructions(self, instructions) -> None: """Parse a list of instructions.""" for instruction in instructions: operation, argument = instruction.split(' ') argument = int(argument) self.instructions.append({'op': operation, 'arg': argument, 'run': False}) def run_next_instruction(self) -> bool: """Run next instruction. If it has already been run, return True.""" current_instruction = self.instructions[self.current_instruction_i] op = current_instruction['op'] arg = current_instruction['arg'] already_run = current_instruction['run'] if already_run: return True current_instruction['run'] = True if op == 'acc': self.accumulator += arg self.current_instruction_i += 1 elif op == 'jmp': self.current_instruction_i += arg elif op == 'nop': self.current_instruction_i += 1 else: raise ValueError(f'Operation {op} not recognized.') will_be_on_last_line = self.current_instruction_i == len(self.instructions) # Wrap around if needed if not will_be_on_last_line: self.current_instruction_i = self.current_instruction_i % len(self.instructions) else: print('Part B - Program terminating - accumulator value:', self.accumulator) return True return False if __name__ == '__main__': DATA_FILEPATH = '08.txt' instruction_list = read_instructions(DATA_FILEPATH) # Part A boot_code = BootCode() boot_code.load_instructions(instruction_list) infinite_loop = False while not infinite_loop: infinite_loop = boot_code.run_next_instruction() print('Part A - Accumulator Value:', boot_code.accumulator) # Part B for index, instruction in enumerate(instruction_list): new_instruction_list = instruction_list.copy() op, arg = instruction.split(' ') if op == 'jmp': new_instruction_list[index] = f'nop {arg}' elif op == 'nop': new_instruction_list[index] = f'jmp {arg}' boot_code = BootCode() boot_code.load_instructions(new_instruction_list) infinite_loop = False while not infinite_loop: infinite_loop = boot_code.run_next_instruction()
a3f473e0dee8485f7fbf23c38f769381251a8deb
SurajPatil314/Leetcode-problems
/Binary Tree/balance_BST.py
1,269
3.984375
4
''' Given a binary search tree, return a balanced binary search tree with the same node values. A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1. If there is more than one answer, return any of them. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: if root == None: return root li = [] self.inorder(root, li) # create sorted list using inorder traversal le = len(li) ana = self.buildBST(li, 0, le - 1) return ana def inorder(self, root1, li): if root1 == None: return None self.inorder(root1.left, li) li.append(root1) self.inorder(root1.right, li) def buildBST(self, li, mina, maxa): if mina > maxa: # base case return None mid = (mina + maxa) // 2 treenode = li[mid] # Get the middle element and make it root treenode.left = self.buildBST(li, mina, mid - 1) treenode.right = self.buildBST(li, mid + 1, maxa) return treenode
6248dcac9712dd23122b89ec9bafdc42748a15b5
zzerr0/Neural_Network
/3neurons_layer.py
426
3.875
4
#neural network with 3 layers of neurons import numpy as np; inputs = [ 1.0, 2.0, 3.0, 2.5 ] #no. of inputs given to a Neuron weights = [ [ 0.2, 0.8, -0.5, 1 ], [ 0.5, -0.9, 0.26, -0.5 ], [ -0.26, -0.27, 0.17, 0.87 ] ] #each list of weight is for a particular neuron biases = [ 2.0, 3.0, 0.5] #one bias for each neuron layer_output = np.dot( weights, inputs ) + biases print(layer_output)
0dedf97398814068cc8b8f93d07c41525c67a46c
shakibusman/python-course
/Day2.py
2,423
3.8125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #work hours done by employees workhours = [('Johann',100),('Ben',200),('Anant',300)] # In[2]: #employee of the highest salary def eotf(wh): current_max = 0 eotm = '' for e,h in wh: if h>current_max: current_max=h eotm = e else: pass return(eotm,current_max) # In[3]: eotf(workhours) # In[ ]: #shuffle function ex = [1,2,3,4,5,6,7] # In[ ]: from random import shuffle # In[ ]: shuffle(ex) # In[ ]: ex # In[ ]: #shuffles the list def shuffle_list(mylist): shuffle(mylist) return mylist # In[ ]: result = shuffle_list(ex) # In[ ]: result # In[ ]: #guessing game mylist = ['','O',''] # In[ ]: shuffle_list(mylist) # In[ ]: def player_guess(): guess='' while guess not in ['0','1','2']: guess = input("Pink a number 0,1,2") return int(guess) # In[ ]: player_guess() # In[ ]: def check_guess(mylist,guess): if mylist[guess] == 'O': print('Correct!') else: print('wrong guess :(') print(mylist) # In[ ]: #initial list mylist = [' ','O',' '] #SHUFFLE LIST mixeduplist = shuffle_list(mylist) #USER GUESS guess = player_guess() #CHECK GUESS check_guess(mixeduplist,guess) # In[ ]: #args def myfunc(*args): #returns 5% of the sum of a and b return sum(args) * 0.05 # In[ ]: myfunc(40,60,100,200,900,758,42,98,2,20) # In[ ]: #kwargs def func(**kwargs): if 'jojo' in kwargs: print('My jojo of choice is {}'.format(kwargs['jojo'])) else: print('I did not find any fruit here') # In[ ]: func(jojo = 'johnny joestar',veggie = 'lettuce') # In[ ]: #game: if the number 007 comes in that right order, return True def spy_game(mylist): code = [0,0,7,'x'] for n in mylist: if n == code[0]: code.pop(0) return len(code) == 1 # In[ ]: spy_game([1,3,4,0,7,7,0]) # In[ ]: def square(num): return num**2 # In[ ]: nums = [1,2,3,4,5] # In[ ]: list(map(square,nums)) # In[ ]: #returns the even number def splicer(mystring): if len(mystring)%2==0: return 'Even' else: return mystring[0] # In[ ]: name = ['Ant','Jozu','Hayyan'] # In[ ]: list(map(splicer,name)) # In[ ]:
f9796d98a8ffb85ee6cfb8dc4fe3451e2e4c4d2e
csal90/CSC-243
/dictPractice2.py
1,077
4.03125
4
# names() prompts users to enter names of students repeatedly until the user # presses ENTER without typing in a name, at this point this function prints out # for each name the number of times when the name has been entered. # names() # Enter a name: Valirie # Enter a name: Johnson # Enter a name: Tommy # Enter a name: Johnson # Enter a name: Tommy # Enter a name: Jennifer # Enter a name: # Valirie has been entered 1 times # Johnson has been entered 2 times # Tommy has been entered 2 times # Jennifer has been entered 1 times def names(): namedict = {} while True: studentname = str(input('Enter a name: ')) if studentname == '': break elif studentname in namedict: namedict[studentname] = namedict[studentname] + 1 else: namedict[studentname] = 1 for keyvalue in namedict: if namedict[keyvalue] > 1: print(keyvalue + ' has been entered ' + str(namedict[keyvalue]) + ' times') if namedict[keyvalue] == 1: print(keyvalue + ' has been entered 1 time')
34157ee78617ce9e241e6ba5406340af3535e591
SergioKulyk/Stepic
/Математика и Python для анализа данных/4 Неделя 2 - Векторы, Матрицы/4.2 ПРАКТИКУМ - Сходство текстов (кошачья задача) в Python/4.2.1.py
376
3.953125
4
# Шаг 1.1 - открытие файла # Откройте файл text.txt и выведите его содержимое на печать. # # Sample Input: # # Text about cats # Text about Anacondas # Sample Output: # # Text about cats # Text about Anacondas with open('text.txt', 'r') as file: text = file.readlines() for line in text: print(line.strip())
f823ac1bccfa039126562b209cda9c2ac501b60b
alexmorenoec/turing-test-v2
/helper.py
2,738
3.578125
4
import re from random import random def chat_tag(display_name): return "{:<5} >> ".format(display_name) def info_message(message): return "INFO: " + message def normalize_text(text): """ Remove all punctuation and lower the text. Also, strip whitespace off the ends of the text. Args: text (str): The text to be normalized. Returns: str: The normalized text. """ return re.sub("([^\w\s]|_)", "", text).lower().strip() KEYBOARD = [['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['z', 'x', 'c', 'v', 'b', 'n', 'm']] def get_keyboard_neighbors(c): for keyboard_row in KEYBOARD: for j, k in enumerate(keyboard_row): if c != k: continue neighbors = [] if j > 0: neighbors.append(keyboard_row[j-1]) if j < len(keyboard_row) - 1: neighbors.append(keyboard_row[j+1]) return neighbors return [] def humanize_text(text): """ Add some normal spelling mistakes to the text like: - Letters swapped - Letters replaced with neighboring keyboard letter Args: text (str): The text to be humanized. Returns: str: The humanized text. """ text_humanized = "" i, n = 0, len(text) swaps = 0 while i < n: if i > 0: # Swap letters. Note: Only letters 'inside' a word are considered if i < n - 2 and random() < 0.005 and swaps < 2: text_humanized += text[i+1] + text[i] i += 2 swaps += 1 continue # Swap letter with letter close on keyboard if text[i] != " " and random() < 0.005 and swaps < 2: keyboard_neighbors = get_keyboard_neighbors(text[i]) if len(keyboard_neighbors) == 1 or random() < 0.5: text_humanized += keyboard_neighbors[0] else: text_humanized += keyboard_neighbors[1] i += 1 swaps += 1 continue text_humanized += text[i] i += 1 return text_humanized def get_header(): header = """ ______ _ ______ __ /_ __/_ _______(_)___ ____ _ /_ __/__ _____/ /_ / / / / / / ___/ / __ \/ __ `/ / / / _ \/ ___/ __/ / / / /_/ / / / / / / / /_/ / / / / __(__ ) /_ /_/ \__,_/_/ /_/_/ /_/\__, / /_/ \___/____/\__/ /____/ By Peter Sandberg """ return header def get_chat_line_separator(): return "-"*70
e999218da467bf8f8329c0dce841922a4f7314cf
burrelle/CS325-FinalProject
/fp.py
4,843
4.09375
4
#!/usr/bin/env python3 import sys from math import sqrt, pow import time MAX_MINUTES = 3 # make sure we received the right number of arguments if len(sys.argv) < 2: print("error, no file name specified") print("correct usage: python3 fp.py [filename.txt]") sys.exit() # this function creates an initial tour using nearest neighbor def neighbor(c): return c # this function returns the euclidean distance between cities a and b def distance(a, b): return int(round(sqrt(pow(a[1]-b[1],2) + pow(a[2]-b[2],2)))) # this function computes the total length of a given tour def tourLength(t): length = 0 for n in range(len(t) - 1): length += distance(t[n], t[n+1]) length += distance(t[len(t) - 1], t[0]) return length # this function performs a 'swap' between cities a and b in tour t def swap(t, a, b): n = [] # the new tour that will contain the the swapped edges # the path from 0 until a - 1 is added to the new tour n += t[:a] # the path from a to b is added in reverse order n += t[b:a-1:-1] # the rest of the path after b is added to n n += t[b+1:] return n; # this function checks whether two edges are crossing each other before performing a swap # def crossing(t, i, j): # a = t[i] # first point in first edge # b = t[i + 1] # second point in first edge # c = t[j - 1] # first point in second edge # d = t[j] # second point in second edge # # # 1) Find the small rectangle in which a crossig could occur. # # 1.a) Find the left side of the rectangle. # left = max(min(a[1], b[1]), min(c[1], d[1])) # # 1.b-d) Find the other sides. # right = min(max(a[1], b[1]), max(c[1], d[1])) # top = min(max(a[2], b[2]), min(c[2], d[2])) # bottom = max(min(a[2], b[2]), min(c[2], d[2])) # # # 2) Find the intersection of the two lines, if it exists: # # 2.a) Find the standard equation of the line passing through the two # # points of each edge. # # 2.a.i) Find the slope of the first line using m = (y2-y1)/(x2-x1) # if a[1]-b[1] == 0: # return True # m1 = (a[2]-b[2])/(a[1]-b[1]) # # 2.a.ii) Find the standard equation of the line, ax + by = c and store # # the coefficients a, b, c. This requires some algebra wrangling to # # understand where everything comes from. # a1, b1, c1 = m1, 1, a[2]-m1*a[1] # # 2.a.iii) Do it again for the second line. # if c[1]-d[1] == 0: # return True # m2 = (c[2]-d[2])/(c[1]-d[1]) # a2, b2, c2 = m2, 1, c[2]-m2*c[1] # # # 3) Solve using numpy. # # 3.a) Form the matrices representing the coefficient matrix and # # constant vector. # A = np.matrix([[a1,b1], [a2,b2]]) # c = np.matrix([[c1], [c2]]) # # 3.b) Compute the inverse of A. If it doesn't exist, the lines are # # parallel and don't cross. # try: # Ai = np.linalg.inv(A) # # 3.c) Compute the intersection of the lines. # sol = Ai.dot(c) # # # 4) Check that the solution lies inside of the rectangle from part 1. # if (left <= sol[0] <= right) and (bottom <= sol[0] <= top): # return True # return False # except: # # Numpy's inverse function raises an exception if the inverse doesn't # # exist, in which case the lines are parallel and don't cross. # return False # this function contains the 2-opt algorithm that optimizes our tour def twoOpt(t): n = [] # a new temp tour bestLength = tourLength(t) # get tour length of initial tour startTime = time.clock() # start function timer found = True # bool to test whether a better tour was found while found and time.clock() - startTime < 60 * MAX_MINUTES: found = False for i in range(1, len(t) -1): for j in range(i+1, len(t)): n = swap(t, i, j) l = tourLength(n) if l < bestLength: bestLength = l; t = n found = True break if found: break return t # read input file into an array startTime = time.clock() # start function timer inputfile = open(str(sys.argv[1])) lines = inputfile.readlines() inputfile.close() # read all cities and store them in an array cities = [] for line in lines: city = [int(n) for n in line.split()] # 0 is the city identifier, 1 is x, 2 is y cities.append(city) # construct the initial tour cities = neighbor(cities) # optimize it with twoOpt cities = twoOpt(cities) # output results print(str(tourLength(cities)) + ' | ' + str(time.clock() - startTime) + '\n') outputfile = open(sys.argv[1] + ".tour", 'w') outputfile.write(str(tourLength(cities)) + '\n') for city in cities: outputfile.write(str(city[0]) + "\n") outputfile.close()
aac74859970ef2694b17ee0a5220bc87ab7019be
lawy623/Algorithm_Interview_Prep
/Algo/Leetcode/010RegularExpressionMatching.py
781
3.84375
4
# do not waste time in hard problem class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ res = re.search(p,s) if res and res.group() == s: return True return False # ok recursion class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ n = len(s) m = len(p) if m == 0: return n == 0 firstMat = n != 0 and (s[0] == p[0] or p[0] == '.') if (m >= 2 and p[1] == '*'): return self.isMatch(s, p[2:]) or (firstMat and self.isMatch(s[1:], p)) else: return firstMat and self.isMatch(s[1:], p[1:])
4f82d0041eca111e037aa72db9de40523a91c0c5
RAJANNITCS/Pyhton_practice
/func_extra_useful_stuff.py
199
3.5
4
# def add(a,b): # '''this function takes 2 number and return their sum''' # return a+b # print(add.__doc__) # print(len.__doc__) # print(max.__doc__) # print(sum.__doc__) print(help(len))
8a04fe87fb45732924c71a5da4792d1f051a254c
abjola/PSSP_notebook
/_build/jupyter_execute/Slurry_Adsorption.py
7,075
3.625
4
# 8. Batch Slurry Adsorption In this notes we will use an example problem to introduce material balances in slurry adsorption processes. We will consider a Batch, process configuration and then its extension to a continuous process configuration. ## 8.1 Problem Statement A water purification process is carried out via batch adsorption. The initial concentration of the pollutant is 0.1 $[mol l^{-1}]$, and it needs to be lowered by at least an order of magnitude. The process is carried out in batches characterised by a water volume $V_{\ell}$ of 2 $m^3$, in which $100\,kg$ of adsorbent are dispersed to form a slurry. The adsorbent is characterised spherical particles with an average radius of 1 $mm$ and density of $700 kg\,m^{-3}$. The pollutant adsorption on the surface of the stationary phase particles is well described by a linear isotherm $q=Hc^*$ with $H=1\times{10^{-1}} [dm]$. The liquid-side mass transfer coefficient is $k_{\ell}=1\times{10^{-5}}\,[m s^{-1}]$. - Is it possible to carry out the requested purification with the operation parameters described in the problem statment? - If this is the case how much time does it take to lower the pollutant concetration to the target specification? ## 8.2 Material Balance in a Batch Slurry adsorption process Let us begin by writing the material balance for a batch membrane separator. Since we have a batch system, no inlet or outlet streams are present and we can write: $$ V_\ell{c_0}=V_\ell{c}+S_pq $$(slurryeq1) Where $V_{\ell}$ is the volume of the liquid phase (it can be considered constant), $c_0$ is the initial concentration of pollutant in solution, $c$ is the instantaneous concentration of pollutant in solution, $q$ the instantaneous surface concentration of pollutant adsorbed on the stationary phase and $S_p$ the total surface exposed by the stationary phase particles. Mass transfer in these cases is dominated by bulk transport on the liquid side, thus the flux $J$ of the pollutant leaving the fluid phase to be incorporated in the stationary phase can be written as: $$ J=-k_\ell(c-c^*) $$(slurryeq2) where $k_\ell$ is the mass transfer coefficient on the liquid side, and $c^*$ is the equilibrium concentration, reached at the solid/liquid interface. $J$ has the units of number of moles per unit time per unit surface. The differential material balance on the solute concentration can thus be written as: $$ \frac{dc}{dt}=-k_\ell\frac{S_p}{V_\ell}(c-c^*)=-k_\ell{a}(c-c^*) $$(slurryeq3) Where $a$ represents the particles surface area per unit of fluid volume. The equilibrium of the adsorption process is well captured by a linear isotherm: $$ c^*=\frac{q}{H} \label{eq:equilibrium} $$(slurryeq4) Using Eq. {eq}`slurryeq1` and {eq}`slurryeq4`, Eq. {eq}`slurryeq2` can be rewritten as: $$ \frac{dc}{dt}=-k_\ell{a}\left(c-\frac{q}{H}\right) = -k_\ell{a}\left(c-\frac{(c_0-c)V_\ell}{HS_p}\right) = $$ $$ =-k_\ell{a}c\left(1+\frac{V_\ell}{HS_p}\right)+k_\ell{a}c_0\frac{V_\ell}{HS_p} $$(slurryeq5) Defining: $\beta=\left(1+\frac{V_\ell}{HS_p}\right)$, and $\alpha=\frac{V_\ell}{HS_p}$, one gets: $$ \frac{dc}{dt}+k_\ell{a}\beta\,c=k_\ell{a}c_0\alpha $$(slurryeq6) which is a first order, non homogeneous ODE in the form $y^\prime+C_1y=C_2$ with constant $C_1$ and $C_2$ coefficients. In order to solve our problem Eq. {eq}`slurryeq6` should either numerically or analytically. In this case the analytical solution can be obtained from the general solution for ODEs in the form: $$ y(t)=e^{-A(t)}\left[k_1+\int{be^{A(t)}dt}\right] $$(slurryeq7) where $A(t)=\int{C_1dt}$ In our case: - $C_1=k_\ell{a\beta}$, thus $A(t)=k_\ell{a\beta}\,t$ - $C_2=k_\ell{a\alpha}c_0$, thus: $$ \int{be^{A(t)}dt}=\int{k_\ell{a\alpha}e^{k_\ell{a\beta}\,t}dt}=\frac{k_\ell{a\alpha}c_0}{k_\ell{a\beta}}e^{k_\ell{a\beta}\,t}=\frac{\alpha{c_0}}{\beta}e^{k_\ell{a\beta}\,t} $$(slurryeq8) putting everything together: $$ c(t)=k_1e^{-k_\ell{a\beta}\,t}+\frac{\alpha{c_0}}{\beta} $$(slurryeq9) The constant $C_1$ can be computed from the initial conditions: at $t=0$ $c(t)=c_0$, therefore: $$ k_1=c_0\left(1-\frac{\alpha}{\beta}\right)=\frac{c_0}{\beta} $$(slurryeq10) The final solution for the time-dependent concentration profile $c(t)$ is: $$ c(t)=\frac{c_0}{\beta}\left(e^{-k_\ell{a\beta}\,t}+\alpha\right) $$(slurryeq11) The performance of a batch slurry process in removing the concentration in the fluid phase is limited, i.e. the concentration has an asymptotic behavior in time $\lim_{t\to\infty} c(t) = \frac{\alpha{c_0}}{\beta}$. import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import cm #Plotting figure=plt.figure() axes = figure.add_axes([0.1,0.1,1.2,1.2]) plt.xticks(fontsize=14) plt.yticks(fontsize=14) N = 500 #number of points time = np.linspace(0,24, N) #particles mass pm=100; #kg #particles volume pV=100/700; #m^3 #single particle volume radius=1E-3; uV=(4/3)*np.pi*np.power(radius,3); uS=4*np.pi**np.power(radius,2); #number_of particles NP=pV/uV; Sp=NP*uS; #particles surface #Batch volume Vl=2; #m^3 #Mass transfer kl=1E-5 / 3600; #m/s #Equilibrium H=1E-1; # #Analytical solution 1 C0=0.1; #mol/l alpha=Vl/H/Sp; beta=1+alpha; a=Sp/Vl; C_inf= np.ones(np.size(time)) * C0*alpha/beta C = C0/beta * (np.exp(-kl*a*beta*time)+alpha) color=iter(cm.coolwarm(np.linspace(0,1,2))) c=next(color) axes.plot(time,C, marker=' ',c=c) c=next(color) axes.plot(time,C_inf,marker=' ',linestyle='dotted',c=c) plt.title('', fontsize=18); axes.set_xlabel('$time\,\,[hours]$', fontsize=18); axes.set_ylabel('$C\,\,[mol / l]$',fontsize=18); axes.legend(['$C(t)$','$C_{inf}$'], fontsize=18); ## 8.3 Continuous Slurry Adsorption The slurry adsorption process can be carried out in a continuous mode. In this mode both the adsorbent and the fluid phase are continuously fed into and removed from a stirred tank. In a continuous process it is convenient to define $a$ as: $$ a={S}\sigma/Q $$(slurryeq13) where $Q$ is the volumetric flowrate of the liquid phase, ans $S$ is the mass flowrate of the solid adsorpbent phase, and $\sigma$ is the surface area per unit mass of the adsorbent. In this context the differential material balance on the solute concentration used to solve the unsteady state batch process should be rewritten as: $$ \frac{dc}{dt}=-k_\ell{a}(c-c^*) \rightarrow \frac{{c_{in}-c_{out}}}{\tau}=k_\ell{a}(c_{out}-c^*) $$(slurryeq12) where $\tau$ is the residence time, $c_{out}$ the concentration in the liquid phase in the unit, $c_{in}$ the concentration in the feed, and $a$ the amount of surface of the stationary phase particles per unit volume of the liquid phase. This expression should solved with the adsorption isotherm $q=kc^*$, where $q$ is the amount adsorbed per kg of stationary phase, $c$ is the molar concentration in solution and $k$ is the partition coefficient typically expressed in [l kg$^{-1}$], and with the global material balance at steady state, which reads: $$ c_{in}Q=qS+c_{out}Q $$(slurryeq14) ## Contributions Salar Rahbari Namin, 8 Feb 2021 Nikita Gusev, 9 Feb 2021
22bd36b96cf1017e564f7774afc46992f47f209b
Rago-Mateus/Python
/Exercicios/ex013.py
318
3.84375
4
salario = float(input('Qual o salário do funcionário?')) dissidio = float(input('Qual foi o dissídio deste ano (em decimais separado por ponto):')) salario_aumento = salario * (1+dissidio) print('O salário original do funcionário era {} e com dissídio de {} ficou {}.'.format(salario,dissidio,salario_aumento))
44acce80c1da1121f2180673d588c31466a57f6c
marketmodelbrokendown/1
/notebook/mit/allinone/student.py
2,062
3.921875
4
import datetime from dateutil.relativedelta import relativedelta class Person: def __init__(self, name): """Create a person:common attributes name and birthdate""" self.name = name # 1 fullname:firstname lastname or 2 lastname try: lastBlank = name.rindex(' ') # ' 'lastName self.lastName = name[lastBlank+1:] except: self.lastName = name self.birthday = None def getName(self): """Returns self's full name""" return self.name def getLastName(self): """Returns self's last name""" return self.lastName def setBirthday(self, birthdate): """Assumes birthdate is of type datetime.date Sets self's birthday to birthdate""" self.birthday = birthdate def getAge(self): """Returns self's current age in years""" if self.birthday == None: raise ValueError relatyears = relativedelta(datetime.date.today(), self.birthday) return relatyears.years+round(relatyears.months/12, 1) def __lt__(self, other): """Returns True if self's name is lexicographically less than other's name, and False otherwise""" if self.lastName == other.lastName: return self.name < other.name return self.lastName < other.lastName def __str__(self): """Returns self's name""" return self.name class MITPerson(Person): nextIdNum = 0 # identification number - class def __init__(self, name): Person.__init__(self, name) self.idNum = MITPerson.nextIdNum MITPerson.nextIdNum += 1 # identification number def getIdNum(self): return self.idNum def __lt__(self, other): return self.idNum < other.idNum class Student(MITPerson): pass class UG(Student): def __init__(self, name, classYear): MITPerson.__init__(self, name) self.year = classYear def getClass(self): return self.year class Grad(Student): pass
6247085684c24327a1589951c1557668ca5490cd
bmiraski/deadball
/baseball.py
2,851
3.640625
4
from player import Player import dice class Base(): """ defines the state of the bases """ def __init__(self, occupied = False): """ creates a base """ self.occupied = occupied self.runner = 0 first = Base() second = Base() third = Base() charles = Player(6, 34, "R") parker = Player(1, 12, "L", 2) print(charles.id) print(charles.bt) print(charles.power) print(charles.position) print(parker.era) print(parker.position) def pitchdie(pitcher): """ Returns the pitch die for a pitcher """ era = pitcher.era if era < 1: return 20 elif era < 2: return 12 elif era < 3: return 8 elif era < 4: return 4 elif era < 5: return 8 elif era < 6: return 12 else: return 20 print(pitchdie(parker)) def defroll(hitroll, hit): """ Determines the result of a defensive roll """ roll = dice.die_roll(6) if roll == 1: if hit == "single": return "single, error" if hit == "double": return "double, error" if hit == "triple": return "triple, error" elif roll <=4: return hit elif roll <=5: if hit == "single": return hit if hit == "double": return "single, runners +2" if hit == "triple": return "double, runners +3" else: return outtype(hitroll) def outtype(roll): """ Returns the out type """ outtype = roll % 10 if outtype <= 2: return "strikeout" if outtype == 3: return "G3" if outtype == 4: return "G4" if outtype == 5: return "G5" if outtype == 6: return "G6" if outtype == 7: return "F7" if outtype == 8: return "F8" else: return "F9" def atbat(batter, pitcher): """ defines an atbat between a batter and a pitcher """ pm = 1 if pitcher.era >= 3.5: pm = -1 roll = dice.die_roll(100) + pm * dice.die_roll(pitchdie(pitcher)) if roll <= batter.bt: hitroll = dice.die_roll(20) if hitroll <=2: return "single" if hitroll <=7: return defroll(roll, "single") if hitroll <=12: return "single, runners +2" if hitroll <=15: return defroll(roll, "double") if hitroll <=17: return "double, runners +3" if hitroll <=18: return defroll(roll, "triple") else: return "Home Run" elif roll < (batter.bt + 5): return "walk" else: return outtype(roll) for x in range(20): print(atbat(charles,parker)) def main(): """ Runs the baseball game """
c1f041b94ba6e2116c26d7dd81ff1c0cc27752bd
icharki/testGit
/san_antonio.py
826
4.0625
4
# -*- coding: utf8 -*- import random quotes = ["Ecoutez-moi, Monsieur Shakespeare, nous avons beau être ou ne pas être, nous sommes !", "On doit pouvoir choisir entre s'écouter parler et se faire entendre."] characters = ["alvin et les Chipmunks", "Babar", "betty boop", "calimero", "casper", "le chat potté", "Kirikou"] def show_random_quote(my_list): rand_namb = random.randint(0, len(my_list) - 1) item = my_list[rand_namb] return(item) user_answer = input("Tapez entrée pour connaître une autre citation ou B pour quiter le programme.") while user_answer != "B": print(show_random_quote(quotes)) user_answer = input("Tapez entrée pour connaître une autre citation ou B pour quiter le programme.") for character in characters: n_character = character.capitalize() print(n_character) print(show_random_quote(quotes))
8d2d3cd8dfade712f9667a691883de16a4f23474
Prabhat2002/Python_based_game_begineer
/Python_Based_Game.py
2,424
4.03125
4
import random import math def guess_game(): low = int(input("Enter Lower Range:- ")) up = int(input("Enter Upper Range:- ")) random_number = random.randint(low, up) chance=round(math.log(up - low)) print("You've only " , chance , " chances to guess the integer!\n") temp=0 count = 0 while(count < chance): count += 1 guess = int(input("Guess a number:- ")) if (random_number == guess): print("Congratulations!! you did it in ", count , " Chance") break elif (random_number > guess): print("You guessed a number smaller than the real one!!") else: print("You guessed a number greater than the real one!!") if (count >= chance): print("\nThe number is " , random_number) print("\tBetter Luck Next time!!") def alphabet_guess(): random_number = random.randint(65,90) c=chr(random_number) chance=6 print("You've only " , chance , " chances to guess the right Alphabet!\n") count = 0 while(count < chance): count += 1 guess = str(input("Guess an Alphabet- ")) if (c == guess): print("Congratulations!! you did it in ", count , " Chance") break else: print("MISSED !!") if (count >= chance): print("\nThe Alphabhet is " , c) print("\tBetter Luck Next time!!") def alphabet_guess2(): random_number = random.randint(97,122) c=chr(random_number) chance=6 print("\n\nYou've only " , chance , " chances to guess the right Alphabet!\n\n") count = 0 while(count < chance): count += 1 guess = str(input("Guess an Alphabet- ")) if (c == guess): print("Congratulations!! you did it in ", count , " Chance") break else: print("MISSED !!") if (count >= chance): print("\nThe Alphabhet is " , c) print("\tBetter Luck Next time!!") if __name__ == '__main__': print("\n\n**************************************************\n") print("Enter 1- for Playing with Numbers") print("Enter 2- for Playing with Capital Letter") print("Enter 3- for Playing with Small Letter") print("\n**************************************************\n\n") select = int(input("Enter your choice : ")) if(select==1): guess_game() elif(select==2): alphabet_guess() elif(select==3): alphabet_guess2() else: print("********************************Thank You********************************") print("********************************Thank You********************************")
be6b3f1dcf763edeca761b1a52f5f1d32ae73cda
PrzemyslawPiotrowski/PythonBootcamp
/kurs4/kartkowka.py
574
4
4
class Animal: def __init__(self, name, age): self.name = name self.age = age def sound(self): return "Knock Knock" animal = Animal("Turtle", 1000) print(animal.name) print(animal.age) print(animal.sound()) class Dog(Animal): def sound(self): return "How How" class Cat(Animal): def sound(self): return ".... (Sorry that is a cat!)" animal2 = Dog("DOG", 12) print(animal2.name) print(animal2.age) print(animal2.sound()) animal3 = Cat("CAT", 13) print(animal3.name) print(animal3.age) print(animal3.sound())
a32462ef7b4b353a43f74418870fe6c8b9d1af03
thekaleidoscope/PyProject
/gui.py
3,719
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 14 01:26:40 2018 @author: Parv , Yadhu """ from tkinter import * #import tkinter as Tk from MovieBooking import * def admin_window(): window = Toplevel(root) #l=Label(window,text="test") #l.pack() global id_entry,name_entry,tseats_entry,price_entry,id_rem def addinput(): mid =int(id_entry.get()) mname = name_entry.get() mseats=int(tseats_entry.get()) mprice=int(price_entry.get()) newmovie(mid,mname,mseats,mprice) print("Movie:{} Added with {} seats at {} INR ".format(mname,mseats,mprice)) def remmovie(): rem_id=id_rem.get() print("Movie {} Removed.".format(fetchmovie(rem_id))) removemovie(rem_id) label1=Label(window,text="New Movie") label2=Label(window,text="ID") label3=Label(window,text="Name") label4=Label(window,text="Total Seats") label5=Label(window,text="Price") id_entry=Entry(window) name_entry=Entry(window) tseats_entry=Entry(window) price_entry=Entry(window) label1.grid(row=0) label2.grid(row=1) label3.grid(row=2) label4.grid(row=3) label5.grid(row=4) id_entry.grid(row=1,column=1) name_entry.grid(row=2,column=1) tseats_entry.grid(row=3,column=1) price_entry.grid(row=4,column=1) b1=Button(window, text="submit", fg="red",command=addinput) b1.grid(row=5, column=1) label5=Label(window,text="Remove Movie") id_rem=Entry(window) b2=Button(window, text="submit", fg="blue",command=remmovie) label5.grid(row=0,column=3) id_rem.grid(row=1,column=3) b2.grid(row=2, column=3) def user_window(): window = Toplevel(root) def showall(): showmoviesall() def showmovieinfo(): sid = int(id_show.get()) showmovie(sid) def bookmovie(): mid=int(book_mov_id.get()) seat=int(book_mov_seat.get()) book(mid,seat) print("\nMovie {} is booked with {} seats.".format(fetchmovie(mid),seat)) print("\nCurrent status of Movie {} ".format(fetchmovie(mid))) showmovie(mid) def refundmovie(): mid=int(ref_mov_id.get()) seat=int(ref_mov_seat.get()) refundseat(mid,seat) print("{} Seats of Movie {} is refunded".format(seat,fetchmovie(mid))) print("\nCurrent status of Movie {} ".format(fetchmovie(mid))) showmovie(mid) global id_show,book_mov_id,book_mov_seat,ref_mov_id,ref_mov_seat b1=Button(window, text="Show All Movies", fg="red",command=showall) b1.grid(row=0, column=1) showmov=Label(window,text="Show Movie") showmov.grid(row=1) id_show=Entry(window) id_show.grid(row=1,column=1) showbutton=Button(window,text="submit",command=showmovieinfo).grid(row=1,column=2) bookl=Label(window,text="Book Movie").grid(row=2) book_mov_id=Entry(window) book_mov_id.grid(row=2,column=1) book_mov_seat=Entry(window) book_mov_seat.grid(row=2,column=2) bookbutton=Button(window,text="book",command=bookmovie).grid(row=2,column=3) refl=Label(window,text="Refund Movie").grid(row=3) ref_mov_id=Entry(window) ref_mov_id.grid(row=3,column=1) ref_mov_seat=Entry(window) ref_mov_seat.grid(row=3,column=2) refbutton=Button(window,text="refund",command=refundmovie).grid(row=3,column=3) root=Tk() l=Label(root,text="Welcome to Movie Booking").pack(side=TOP) topFrame = Frame(root) topFrame.pack() bottomFrame=Frame(root) bottomFrame.pack(side=BOTTOM) button1=Button(topFrame, text="ADMIN", fg="red",command=admin_window) button2=Button(topFrame, text="USER", fg="blue",command=user_window) button1.pack(side=LEFT) button2.pack() root.mainloop()
56f8b0b349a9deb12ef0b21fa64038a08cc5d139
ByteCommander/AdventOfCode
/2016/aoc2016_3a.py
371
3.546875
4
# Advent Of Code 2016, day 3, part 1 # http://adventofcode.com/2016/day/3 # solution by ByteCommander, 2016-12-03 data = open("inputs/aoc2016_3.txt").read() counter = 0 for line in data.splitlines(): a, b, c = map(int, line.split()) if a + b > c and a + c > b and b + c > a: counter += 1 print("Answer: there are {} possible triangles".format(counter))