blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
0145516901db83e2d3f6d3e4962212eb8c2c27d8
sangianpatrick/hacktiv8-python-datascience
/day_02/task3.py
134
3.578125
4
pangkat = 3 for x in range(11): a = x**pangkat print("Hasil dari {x} pangkat {pangkat} adalah {a}".format(x=x,pangkat=pangkat,a=a))
546e3058dab3aec1e7aeac1c12d7a96ae404b1bd
ahilgenkamp/Pi_projects
/Boggle_AI/word_distribution.py
741
3.65625
4
#word distribution graph import string import matplotlib from nltk.corpus import words #load dictionary word_list = words.words() print('Total Words: '+str(len(word_list))) low = string.ascii_lowercase ''' for i in range(len(low)): num_letters = sum(a.lower() == low[i] for a, *_ in word_list) #for notes on *_ --> https://www.python.org/dev/peps/pep-3132/ print(low[i].upper()+': '+str(num_letters)) ''' two_letters = [] for i in low: for j in low: two_letters.append(i+j) for i in range(len(two_letters[0:35])): num_letters = sum(a[0:2].lower() == two_letters[i] for a in word_list) #for notes on *_ --> https://www.python.org/dev/peps/pep-3132/ print(two_letters[i].upper()+': '+str(num_letters))
a7a25c301bdd9cf4cfea71458868d1aa7d20b548
hannes1903/Homework-and-Exercises
/count.py
409
3.6875
4
import collections words = ['a', 'b', 'a', 'c', 'b', 'k'] c = collections.Counter(words) print (c) print (c.most_common(2)) print (c['i']) def count_1 (a): a = collections.Counter(words).most_common(2) return (a) print (count_1 (words)) ## d={} for word in words: if word in ('a', 'b', 'h'): if word in d: d [word] += 1 else: d[word] = 1 print(d)
61a6ef3a2803175b7082beb408ba794a4980c9b4
hannes1903/Homework-and-Exercises
/even the last.py
309
3.5625
4
import math import statistics b = [1,2,4,5,6,7,8,9,6,6,4,5,] print(len(b)) list2=b[0::2] print (list2) list3=sum(list2)*b[-1] print (list3) def checkio(V): a=len(V) if a==0: return (0) else: list2=V[0::2] list3=sum(list2)*V[-1] return (list3) print (checkio(b))
3b75c81b02d0b18839a1ed43429119fc0a3d05af
J-man21/Python_Basics
/107_for_loops.py
595
3.84375
4
# For Loops # syntax # for item in iterable: # block of code import time cool_cars = ['Ferrari', 'Fiat', 'Skoda','Mk7','VW', 'focus'] #for car in cool_cars: # print(car) # time.sleep(1) count = 1 for car in cool_cars: print(count, '-', car) count += 1 time.sleep(1) # For loop for dictionaries boris_dict = { 'name': 'boris', 'l_name': 'johnson', 'phone': '07939527648', 'address': 'Aymz', } for key in boris_dict: print(key) print(boris_dict['phone']) for key in boris_dict: print(boris_dict['phone']) print(boris_dict['name'])
94d019ad93368584495f832b72ccc2c0230526c8
kyleo83/EscapeTheKonigsberg
/bridge.py
3,923
3.75
4
from scene import Scene from textwrap import dedent from stats_inventory import Person, Inventory import numpy as np class Bridge(Scene): def enter(self): print(dedent(""" You find yourself on bridge #7 and you are not alone. The captain of the ship 'Dicey Roll' is blocking your path to the podbay, your only hope of escape. Do you 'flee' or 'fight'? """)) choice = input('> ') if 'flee' in choice: print(dedent("""Looking around the bridge you see four doors to the 'port', 'forward', 'starboard' and 'aft'. As the 'forward' door is block you choose another.""")) choice = input("> ") while choice.lower() != "quit": choice = choice.lower() if "port" in choice or choice == 'p': return 'communication' elif "starboard" in choice or choice == 's': return 'armory' elif "aft" in choice or choice == 'a': return 'engineroom' else: print(dedent("""You stand frozen in place trying to decide which door to open. You can go 'port', 'startboard' or 'aft'. This is a ship afterall.""")) choice = input("> ") else: print("Get ready to fight!") capHealth = 10 bonusDamage = 0 choice = input("If you have a weapon now would be good time to 'use' it > ") if "use" in choice and ("stick" in choice or "buzz" in choice): myRoot = Inventory.item.insertKey("Lincoln Head Penny 1909 VBS") foundNode = Inventory.item.searchBST("Buzz Stick", myRoot) if foundNode is not None: bonusDamage = 3 else: print("You were unable to pull it out in time if you actually have one.") print(dedent("""At first you attempt to throw him off-guard with vast knowledge discrete mathmatics""")) if Person.earthling.euler < 8: print(dedent("""(The captain is not amused by anecdotes on 'Finite State Machines and gets in the first hit.""")) Person.earthling.health -= np.random.randint(1,3) else: print(dedent("""Your knowledge of graphs and set theory stuns him, allowing you the first strike.""")) while capHealth > 0: damage = np.random.randint(1,5) + bonusDamage + (Person.earthling.strength - 8) capHealth -= damage if bonusDamage != 0: print("You swing at him with your Buzz Stick and hit him hard!\n") else: print("You swing at him with your fist and make contact.\n") if capHealth > 0: print("The captain swings at you\n") Person.earthling.health -= np.random.randint(1,4) if Person.earthling.health <= 0: return 'disaster' print(dedent("""You have defeated the captain! You find a small manual labeled 'Launch codes for the escape pod Joj. You add this to your inventory. You can go 'port', 'aft', 'starboard' or 'forward' to the podbay.""")) myRoot = Inventory.item.insertKey("Launch Codes for Joj") print("\nCurrent Inventory: ") Inventory.item.inOrder(myRoot) choice = input("> ") while choice.lower() != "quit": choice = choice.lower() if "port" in choice or choice == 'p': return 'communication' elif "starboard" in choice or choice == 's': return 'armory' elif "aft" in choice or choice == 'a': return 'engineroom' elif "forward" in choice or choice == 'f': return 'podbay' elif "inventory" in choice or choice == 'i': myRoot = Inventory.item.insertKey("Lincoln Head Penny 1909 VBS") print("Your inventory:") Inventory.item.inOrder(myRoot) print(dedent("""\nYou stand frozen in place trying to decide which door to open. You can go 'port', 'startboard' or 'aft'. This is a ship afterall.""")) choice = input("> ")
4766351a150037e894e98ccb190c9386af39a5a0
slackbot115/calculadora_lei_de_ohm
/lei de ohm.py
1,253
3.859375
4
op = input("Digite qual lei de ohm voce deseja efetuar as contas: \n1 - Primeira Lei de Ohm (digite 1)\n2 - Segunda Lei de Ohm (digite 2)\n\n") if op == "1": conta = input("Digite o valor que voce deseja encontrar: \nR - Resistencia\nV - Tensao\nI - Intensidade Corrente\nDigite a respectiva letra que voce deseja efetuar a conta: ") if conta.lower() == "r": v = int(input("Digite a tensao (volts): ")) i = int(input("Digite a intensidade (amperes): ")) r1 = v / i print("A resistencia ficou: ", int(r1)) elif conta.lower() == "v": i = int(input("Digite a intensidade (amperes): ")) r = int(input("Digite a resistencia (ohm): ")) v = r * i print("A tensao calculada ficou: ", int(v)) elif conta.lower() == "i": v = int(input("Digite a tensao (volts): ")) r = int(input("Digite a resistencia (ohm): ")) i = v / r print("A intensidade calculada ficou: ", int(i)) ''' l: m p: ohm por m a: mm2 ''' if op == "2": l = int(input("Digite o comprimento do fio: ")) a = int(input("Digite a area transversal: ")) p = int(input("Digite a resistividade do material: ")) r2 = (p * l) / a print("A resistencia final ficou: ", int(r2))
cf716a695460503ee0dbc131e3569d60f2669393
jsrawan-mobo/samples
/python/ce/tictactoe.py
1,567
3.703125
4
# To go faster m = 1000 # So avoid going through 1M squares. We would need to do 4 types. So could be 4 * 1000 # This is pretty fast, so i don't think it be a problem # We know the sum of any board is M class TicTacToe(object): def __init__(self, m): self.the_board = [[False for x in xrange(m)] for y in xrange(m)] def is_game_over(self, x, y): m = len(self.the_board) is_done = all([self.the_board[xi][y] for xi in xrange(m)]) if is_done: return True is_done = all([self.the_board[x][yi] for yi in xrange(m)]) if is_done: return True if x / y == 1: is_done = all([self.the_board[pos][pos] for pos in xrange(m)]) if ((x - 1 - m) / y) == 1: is_done = all([self.the_board[pos - 1 - m][pos] for pos in xrange(m)]) if is_done: return True return False def make_move(self, x, y): if not self.the_board[x][y]: self.the_board[x][y] = True else: raise Exception("Already taken") return True if __name__ == '__main__': ttt = TicTacToe(3) ttt.make_move(0, 0) ttt.make_move(1, 1) ttt.make_move(2, 2) if ttt.is_game_over(2, 2): print "Finished game" ttt = TicTacToe(3) ttt.make_move(0, 0) ttt.make_move(1, 1) ttt.make_move(1, 2) if not ttt.is_game_over(1, 2): print "Not Done" ttt.make_move(0, 2) ttt.make_move(2, 2) if ttt.is_game_over(2, 2): print "Finished game"
c88ca226b26c7b77b58a6181dc36031c6d31d7fd
jsrawan-mobo/samples
/python/ce/baybridges2.py
11,010
3.734375
4
from copy import copy from itertools import permutations, chain from sys import argv # # Two sequences where the greatest subsequence, which is NON continguous # assume only one unique # Create a recursive sequence, that basically takes the left, and walks through all possibilities # Its recursive # This below will two strings and find the maximal possible sequence # Starting at first leter import re import itertools def slope(cc): return (cc['yr'] - cc['yl']) / (cc['xr'] - cc['xl']) def is_overlapping_box(c1, c2): """ The simple approximatation will turn the lines into 2D boxes, that we can easily computer overlap. This is for set assignment :param c1: dict of xl,yl,xr,yr :param c2: dict of xl,yl,xr,yr :return: the overlapping box or None """ # figure out the slope and reverse the logic if slopes are not the same sign m1 = slope(c1) m2 = slope(c2) reverse = False if m1 * m2 < 0: reverse = True if (c1['xl'] <= c2['xr'] and c2['xl'] <= c1['xr']): if ((not reverse and (c1['yl'] <= c2['yr'] and c2['yl'] <= c1['yr'])) or (reverse and (c1['yl'] >= c2['yr'] and c2['yl'] >= c1['yr']))): return { 'xl': min(c1['xl'], c2['xl']), 'xr': max(c2['xr'], c2['xr']), 'yl': max(c1['yl'], c2['yl']), 'yr': min(c1['yr'], c2['yr']) } return None def is_colliding_line(c1, c2): """ Using line to line intersection described here: http://en.wikipedia.org/wiki/Line%E2%80%93line_intersection x = (b2.- b1) / (m1 - m2) y = (b2*m1 - b1*m2) (m1 - m2) Take l1, and make that intercept = 0 Take l2 and find its y intercept = 0 then we can find point of instersection using equations :return : None if no overlap or the coordinate of the x,y point (its a line as a point) """ y_f = lambda m, x, b: m * x + b x_f = lambda m, y, b: (y - b) / m def swap_if(c): if c['xr'] < c['xl']: return {'xl': c['xr'], 'yl': c['yr'], 'xr': c['xl'], 'yr': c['yl']} else: return c # This works only if the first point is on the left, we swap the points if required c1 = swap_if(c1) c2 = swap_if(c2) # Setup the m and b for the linear equation. The number represent the number degrees of y # over x. # to get the number of degree slop of line # >> math.degrees(math.atan(c1m) c1m = slope(c1) c2m = slope(c2) # Now we set up the b valuea to represent the at x=x0 (like x=0). We pick x0 = c1['xl'] c1b = c1['yl'] c2b = y_f(c2m, x0 - c2['xl'], c2['yl']) # Now find the x,y point that overlaps. If m are equal (parallel lines) # then we get infinite answer try: x_i = (c2b - c1b) / (c1m - c2m) + x0 y_i = (c2b * c1m - c1b * c2m) / (c1m - c2m) except Exception: return None # Now the easy part, make sure the xi,yi is in the bounding box for both lines eps = 1e-6 c_i = {'yl': y_i - eps, 'xl': x_i - eps, 'yr': y_i + eps, 'xr': x_i + eps} if is_overlapping_box(c1, c_i) and is_overlapping_box(c2, c_i): return {'yl': y_i, 'xl': x_i} return None # Second do def group_by_overlapping_2(groups): """ # Another option is just to find a random overlap, and remove # The one that has less overlaps. # Prune operation can be recursive :param groups: :return: """ if len(groups) <= 1: return groups # 1. initialize empty list of conflicting nodes groups_o = [(x[0], x[1], set()) for x in groups] # 2. For each coordinate, check all others for overlap for (idl, coordl, tl), (idr, coordr, tr) in itertools.product(groups_o, repeat=2): if idl == idr: continue if is_colliding_line(coordl, coordr): tl.add(idr) # 3. sort by number of overlaps # 4. while overlaps are not empty while True: groups_o = sorted(groups_o, key=lambda x: len(x[2]), reverse=True) clen = len(groups_o[0][2]) all_index = [groups_o[0][0]] for id, coord, t in groups_o[1:]: if len(t) == clen: all_index.append(id) else: break # 5. Remove all k overlaps, and check if we are free #group_copy = copy(groups_o) for ki in all_index: for id, coord, t in groups_o[1:]: t.discard(ki) del groups_o[0:len(all_index)] sumc = sum([len(t) for id, coord, t in groups_o]) if sumc == 0: #groups_o = group_copy break # 6. Optimize the lines to remove. assume k may not be optimal # we have to remove k-1 overlaps, and check if we are free. If so do k-2 final_id = set([id for id, coord, t in groups_o]) groups_final = [x for x in groups if x[0] in final_id] return groups_final def group_by_overlapping(groups): """ Simply keep adding to a group if anything matches :param groups: :return: a list of of list of groups that overlap """ def is_group_colliding(coord, groups): for id, coordg in groups: if is_colliding_line(coord, coordg): return True return False # This is n^2 to find interesection sub_groups = [] for id, coord in groups: found_groups = [] found_group_index = [] for k, sgroups in enumerate(sub_groups): if is_group_colliding(coord, sgroups): found_groups += sgroups found_group_index.append(k) if len(found_groups) > 0: for k, ind in enumerate(found_group_index): del sub_groups[ind - k] found_groups.append((id, coord)) sub_groups.append(found_groups) else: sub_groups.append([(id, coord)]) return sub_groups def gcdf(groups): """ Take the permutations at the top level, then for each permutation, do a recursion to find the gc subgroup :param groups_list: :return: a list of of list of groups that overlap """ def is_group_colliding(coord, groups): for id, coordg in groups: if is_colliding_line(coord, coordg): return True return False def gcfd_recurse(groups): """ Left tree is the group, right tree :param groups: :return: """ n = len(groups) gcfd_ret = [] for id, coord in groups: if not is_group_colliding(coord, gcfd_ret): gcfd_ret.append((id, coord)) return gcfd_ret all_perms = permutations(groups, len(groups)) longest = [] for perm in all_perms: gcfd_group = gcfd_recurse(perm) if len(gcfd_group) > len(longest): longest = gcfd_group if len(longest) >= len(groups) - 1: return gcfd_group return longest def hsv_to_rgb(h, s, v): if s == 0.0: v *= 255 return [v, v, v] # XXX assume int() truncates! h = h / 60 i = int(h) f = h - i v *= 255 p = int(v * (1. - s)) q = int(v * (1. - s * f)) t = int(v * (1. - s * (1. - f))) i %= 6 if i == 0: return [v, t, p] if i == 1: return [q, v, p] if i == 2: return [p, v, t] if i == 3: return [p, q, v] if i == 4: return [t, p, v] if i == 5: return [v, p, q] if __name__ == "__main__": file_name = argv[1] debug = False input = file(file_name) flist = [tuple([y for y in x.replace("\n", '').split(':')]) for x in input.readlines() if len(x.strip()) > 0 and x[0] != '#'] coords = dict() floatre = re.compile( '([\-\+]?\d+\.\d+)[\s,\]\[]*([\-\+]?\d+\.\d+)[\s,\]\[]*([\-\+]?\d+\.\d+)[\s,' '\]\[]*([\-\+]?\d+\.\d+)') for id, val in flist: res = floatre.search(val) if not res: raise Exception("Invalid input line {}".format(val)) coords[id] = {'yl': float(res.group(1).strip()), 'xl': float(res.group(2).strip()), 'yr': float(res.group(3).strip()), 'xr': float(res.group(4).strip())} # for id1, coord1 in coord.iteritems(): # for id2, coord2 in coord.iteritems(): # # box = is_overlapping_box(coord1, coord2) # line = is_colliding_line(coord1, coord2) # # print "{}-{}-{}-{}".format(id1, id2, box, line) # groups_list = group_by_bounding_box(coords) # groups_only = [idb_groups['groups'] for idb_groups in groups_list] # tHIS OVERLAPS ALL OF THEM groups_only = [[(id, coord) for id, coord in coords.iteritems()]] intersect_groups = [] for groups in groups_only: intersect_groups += group_by_overlapping(groups) if debug: import matplotlib.pyplot as pyplot for k, groups in enumerate(intersect_groups): for id, coord in groups: h, s, v = (int(k) * 60, 1, 1) r, g, b = hsv_to_rgb(h, s, v) color = '#{:02x}{:02x}{:02x}'.format(r, g, b) pyplot.plot([coord['xl'], coord['xr']], [coord['yl'], coord['yr']], color=color, linestyle='-', linewidth=2, label=id) pyplot.text(coord['xl'], coord['yl'], '{}[{}]'.format(k, id), size=9, rotation=12, color=color, ha="center", va="center", bbox=dict(ec='1', fc='1')) pyplot.legend() pyplot.title("Groups") pyplot.show() final_groups = [] for groups in intersect_groups: final_groups += group_by_overlapping_2(groups) coord_dict = dict([(int(groups[0]), groups[1]) for groups in chain(final_groups)]) for key in sorted(coord_dict.keys()): print key if debug: import matplotlib.pyplot as pyplot for id, coord in coords.iteritems(): h, s, v = (int(id) * 50, 1, 1) if int(id) in coord_dict else (360, 0, 0) r, g, b = hsv_to_rgb(h, s, v) color = '#{:02x}{:02x}{:02x}'.format(r, g, b) pyplot.plot([coord['xl'], coord['xr']], [coord['yl'], coord['yr']], color=color, linestyle='-', linewidth=2, label=id) rotation = 0 pyplot.text(coord['xl'], coord['yl'], '{}-{}\n{}'.format(id, coord['xl'], coord['yl']), size=6, rotation=rotation, color=color, ha="center", va="center", bbox=dict(ec='1', fc='1')) pyplot.text(coord['xr'], coord['yr'], '{}-{}\n{}'.format(id, coord['xr'], coord['yr']), size=6, rotation=rotation, color=color, ha="center", va="center", bbox=dict(ec='1', fc='1')) pyplot.legend() pyplot.title("Non-Intersecting lines") pyplot.show()
a6622d0573a5ead8200ba2ffb9eb5d736d0b7cb3
easontm/Cinemagraphs
/scripts/note_refresh.py
726
3.515625
4
import urllib.request import fileinput from os import system localNotePath = "/home/pi/Cinemagraphs/notes/Notes.txt" remoteNotePath = "https://www.dropbox.com/s/nh8o4gou047td5m/Notes.txt?dl=1" # Download the notes from remoteNotePath and save it locally under localNotePath: with urllib.request.urlopen(remoteNotePath) as response, open(localNotePath, 'wb') as out_file: data = response.read() # a `bytes` object out_file.write(data) # fixing line end chars with fileinput.FileInput(localNotePath, inplace=True, backup='.bak') as file: for line in file: print(line, end='') fileinput.close() # backs up and updates html files system("python3 /home/pi/Cinemagraphs/scripts/update_html.py")
9d723b583cec6a1c2ec2aea6497eec0d6dd6d27f
ageinpee/DaMi-Course
/1/Solutions/Solution-DAMI1-Part3.py
2,024
4.15625
4
''' Solution to Part III - Python functions. Comment out the parts you do not wish to execute or copy a specific function into a new py-file''' #Sum of squares, where you can simply use the square function you were given def sum_of_squares(x, y): return square(x) + square(y) print sum_of_squares(3, 5) # Try out yourself #Increment by 1 x = 0 y = 0 def incr(x): y = x + 1 return y print incr(5) # Try out yourself # Increment by any n; quite straightforward, right? x = 0 y = 0 def incr_by_n(x, n): y = x + n return y print incr_by_n(4,2) # Try out yourself #Factorial of a number def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) n=int(input("The number you want to compute the factorial of: ")) # User input print "Result:", factorial(4) # Try out yourself #Display numbers between 1 and 10 using 'for' ... for a in range(1, 11): print a #... and 'while' a=1 while a<=10: print a a+=1 #Test if a number is between 1 and 10 (can be of any range though) def number_in_range(n): if n in range(1,10): print( " %s is in the range"%str(n)) else : print "The number is outside the given range." test_range(8) # Try out yourself '''Multiple if-conditionals Note, that no keyword 'end' is needed! Instead, program blocks are controlled via indentation. For beginners, indentation errors are most likely to occur, so playing around and extending smaller code snippets to bigger program code can better help understanding the underlying Python interpretation process''' def chain_conditions(x,y): if x < y: print x, "is less than", y elif x > y: print x, "is greater than", y else: print x, "and", y, "are equal" chain_conditions(50, 10) # Try out yourself #Prime number def test_prime(n): if (n==1): return False elif (n==2): return True; else: for x in range(2,n): if(n % x==0): return False return True print(test_prime(7)) # Try out yourself
3abbabd95a1f0b3d2cc6f91659af0231d9d9b112
sejinwls/2018-19-PNE-practices
/session-17/client2.py
1,771
3.921875
4
# -- Example of a client that uses the HTTP.client library # -- for requesting a JSON object and printing their # -- contents import http.client import json import termcolor PORT = 8001 SERVER = 'localhost' print("\nConnecting to server: {}:{}\n".format(SERVER, PORT)) # Connect with the server conn = http.client.HTTPConnection(SERVER, PORT) # -- Send the request message, using the GET method. We are # -- requesting the main page (/) conn.request("GET", "/listusers") # -- Read the response message from the server r1 = conn.getresponse() # -- Print the status line print("Response received!: {} {}\n".format(r1.status, r1.reason)) # -- Read the response's body data1 = r1.read().decode("utf-8") # -- Create a variable with the data, # -- form the JSON received person = json.loads(data1) print("CONTENT: ") # Print the information in the object print() print("Total people in the database: {}".format(len(person["people"]))) for i, num in enumerate(person["people"]): termcolor.cprint("Name: ", 'green', end="") print(person["people"][i]['Firstname'], person["people"][i]['Lastname']) termcolor.cprint("Age: ", 'green', end="") print(person["people"][i]['age']) # Get the phoneNumber list phoneNumbers = person["people"][i]['phoneNumber'] # Print the number of elements int the list termcolor.cprint("Phone numbers: ", 'green', end='') print(len(phoneNumbers)) # Print all the numbers for i, num in enumerate(phoneNumbers): termcolor.cprint(" Phone {}:".format(i), 'blue') # The element num contains 2 fields: number and type termcolor.cprint(" Type: ", 'red', end='') print(num['type']) termcolor.cprint(" Number: ", 'red', end='') print(num['number'])
6f4e6fe5a6989ddd065712fe1e9d917d31648b6b
sejinwls/2018-19-PNE-practices
/Session-7/client.py
426
3.546875
4
# Programming our first client import socket # Create a socket for communicating with the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Socket created") PORT = 8080 IP = "212.128.253.108" # Connect to the server s.connect((IP, PORT)) # Send a message s.send(str.encode("HELLO FROM MY CLIENT")) msg = s.recv(2048).decode("utf-8") print("Mesaage from server: ") print(msg) s.close() print("The end")
45fc9452f03b169869eb753bf3ffc017540dd052
sejinwls/2018-19-PNE-practices
/session-5/ex-1.py
620
4.1875
4
def count_a(seq): """"THis function is for counting the number of A's in the sequence""" # Counter for the As result = 0 for b in seq: if b == "A": result += 1 # Return the result return result # Main program s = input("Please enter the sequence: ") na = count_a(s) print("The number of As is : {}".format(na)) # Calculate the total sequence lenght tl = len(s) # Calculate the percentage of As in the sequence if tl > 0: perc = round(100.0 * na/tl, 1) else: perc = 0 print("The total lenght is: {}".format(tl)) print("The percentage of As is {}%".format(perc))
3e282477d9c87ed3371cec434b14c76908e72b91
ElonRM/DataScienceBuch
/Kapitel_5_Statistik/Lagemaße.py
1,223
3.609375
4
from typing import Counter, List import numpy num_friends = numpy.random.binomial(100, 0.06, 206) def mean(xs: List[float]) -> float: return sum(xs)/len(xs) # Die Unterstriche zeigen, dass dies "private" Funktionen sind, da sie nur # von unserer median Funktion, nicht aber von anderen Nutzern unserer Statistik # Bibliotek verwendet werden sollen def _meadian_even(xs: List[float]) -> float: """Liefert den Mittelwert die zwei mittleren Einträge""" return (sorted(xs)[len(xs)//2-1] + sorted(xs)[len(xs)//2])/2 def _median_odd(xs: List[float]) -> float: """Liefert den Median""" return sorted(xs)[len(xs)//2] def median(v: List[float]) -> float: """Lifert den Median abhängig von gerade/ungeraden Anzahlen""" return _median_odd(v) if len(v) % 2 == 1 else _meadian_even(v) def quantile(xs: List[float], p: float) -> float: """Liefert den Wert des p-ten Perzentils""" return sorted(xs)[int(len(xs)*p)] def mode(xs: List[float]) -> List[float]: """Liefert eine Liste, denn es kann mehr als einen Modus geben""" counts = Counter(xs) max_count = max(counts.values()) return [x_i for x_i, count in counts.items() if count == max_count]
4e8419fba8837646ac89192407d2f4fcf9c74fa0
ElonRM/DataScienceBuch
/Kapitel_5_Statistik/Einen_einzelnen_Datensatz_beschreiben.py
790
3.625
4
import numpy as np from collections import Counter from matplotlib import pyplot as plt import math num_friends = np.random.binomial(100, 0.08, 204) friends_counter = Counter(num_friends) plt.bar(friends_counter.keys(), friends_counter.values(), edgecolor=(0, 0, 0)) #plt.xticks([20*i for i in range(6)]) #plt.yticks([i*5 for i in range(math.ceil(max(friends_counter.values())//5+2))]) plt.axis([0, 101, 0, max(friends_counter.values())+1]) plt.xlabel("# of friends") plt.ylabel("# of people") plt.title("Histogram of friends count") plt.show() num_points = len(num_friends) largest_value = max(num_friends) smallest_value = min(num_friends) sorted_values = sorted(num_friends) smallest_value = sorted_values[0] largest_value = sorted_values[-1] second_largest_number = sorted_values[-2]
e152129339f29660b810322076c088030a59ff0d
ElonRM/DataScienceBuch
/kapitel_3_Daten_Visualisierung/Balkendiagramme.py
2,264
3.8125
4
from matplotlib import pyplot as plt from collections import Counter plots = ["movies", "grades", "mentions"] # Funktioniert nicht wirklich... selected_plot = plots[2] #grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0] x_values = { "movies": ["Annie Hall", "Ben-Hur", "Casablanca", "Gandhi", "West Side Story"], "grades": [x + 5 for x in Counter(min((grade) // 10 * 10, 90) for grade in [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]).keys()], "mentions": [2017, 2018], } y_values = { "movies": [5, 11, 3, 8, 10], "grades": Counter(min((grade) // 10 * 10, 90) for grade in [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]).values(), "mentions": [500, 505], } x_labels = { "movies": None, "grades": "Decile", "mentions": None, } y_labels = { "movies": "# of Academy Awards", "grades": "# of students", "mentions": "# of times I heard someone say 'data science'", } axis_ranges = { "movies": None, "grades": [-5, 105, 0, max(y_values["grades"])+1], "mentions": [min(x_values["mentions"])-0.5, max(x_values["mentions"])+0.5, 0, max(y_values["mentions"])+50], } x_ticks = { "movies": [range(len(x_values["movies"])), x_values["movies"]], "grades": [10 * i for i in range(11)], "mentions": x_values["mentions"], } y_ticks = { "movies": None, "grades": None, "mentions": [100 * i for i in range((max(y_values["mentions"])//100)+1)], } bar_width = { "movies": [False], "grades": [True, 10], "mentions": [False], } edge_color = { "movies": None, "grades": (0, 0, 0), "mentions": None, } titles = { "movies": "My Favorite Movies", "grades": "Distribution of Exam 1 grades", "mentions": "Not so huge anymore", } plt.bar(x_values[selected_plot], # gibt jedem Balken die korrekte Höhe (Anzahö, wie oft die Note vorkam) y_values[selected_plot], # bar_width[selected_plot][1] if bar_width[selected_plot][0] == True else pass, edgecolor=edge_color[selected_plot] ) plt.xticks(x_ticks[selected_plot]) plt.yticks(y_ticks[selected_plot]) plt.axis(axis_ranges[selected_plot]) plt.xlabel(x_labels[selected_plot]) plt.ylabel(y_labels[selected_plot]) plt.title(titles[selected_plot]) plt.show()
468fc754315c516757a5e679e03e13d97d69f3f5
Sergey-Shulnyaev/my_python
/graphics/moodle/1/15.py
3,969
3.828125
4
from math import sqrt import math class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(%.2f, %.2f)" % (self.x, self.y) def distanceTo(self, point): return math.sqrt((self.x - point.x) ** 2 + (self.y - point.y) ** 2) def __sub__(self, other): return Point(math.floor((self.x - other.x) * 10000) / 10000, math.floor((self.y - other.y) * 10000) / 10000) class Line: def __init__(self, a, b, c): if abs(a) < 0.0001: self.a = 0 else: self.a = a if abs(b) < 0.0001: self.b = 0 else: self.b = b if abs(c) < 0.0001: self.c = 0 else: self.c = c def __str__(self): if self.a < 0: a = "-%.2fx" % (-self.a) else: a = "%.2fx" % (self.a) if self.b < 0: b = " - %.2fy" % (-self.b) else: b = " + %.2fy" % (self.b) if self.c < 0: c = " - %.2f" % (-self.c) else: c = " + %.2f" % (self.c) return a + b + c + " = 0" @staticmethod def fromCoord(x1, y1, x2, y2): return Line(y1 - y2, x2 - x1, x1 * y2 - x2 * y1) def distanceToZero(self): return abs(self.c) / sqrt(self.a ** 2 + self.b ** 2) def distanceToPoint(self, point): return abs(self.a * point.x + self.b * point.y + self.c) / sqrt(self.a ** 2 + self.b ** 2) def isParallel(self, line): if abs(self.b * line.a - self.a * line.b) < 0.001: return True else: return False def intersection(self, line): if self.isParallel(line): return None else: x = (line.c * self.b - self.c * line.b)/(line.b * self.a - self.b * line.a) y = (line.c * self.a - self.c * line.a)/(self.b * line.a - self.a * line.b) if abs(x) < 0.001: x = 0 if abs(y) < 0.001: y =0 p = Point(x, y) return p def nearPoint(self, point): oLine = Line(self.b, -self.a, self.a * point.y - self.b * point.x) return self.intersection(oLine) def oneSide(self, p1, p2): nearP1 = self.nearPoint(p1) nearP2 = self.nearPoint(p2) v1 = nearP1 - p1 v2 = nearP2 - p2 if v1.x * v2.x >= 0: return True else: return False def normalize(self): if self.c !=0: self.a = self.a/self.c self.b = self.b/self.c self.c = 1 elif self.a != 0: self.b = self.b/self.a self.a = 1 elif self.b != 0: self.b = 1 return 0 def perpendicularLine(self, point): return Line(self.b, -self.a, self.a * point.y - self.b * point.x) def parallelLine(self, point): return Line(self.a, self.b, -self.a * point.x - self.b * point.y) def projectionLength(self, p1, p2): nearP1 = self.nearPoint(p1) nearP2 = self.nearPoint(p2) return sqrt((nearP1.x - nearP2.x)**2 + (nearP1.y - nearP2.y)**2) def middlePoint(self, p1): nearP1 = self.nearPoint(p1) v1 = nearP1 - p1 return Point(p1.x + v1.x/2, p1.y + v1.y/2) def symmetricPoint(self, p1): nearP1 = self.nearPoint(p1) v1 = nearP1 - p1 return Point(p1.x + v1.x*2, p1.y + v1.y*2) def insideTreug(self, p1): nearP1 = self.nearPoint(p1) v1 = nearP1 - p1 if (v1.x * nearP1.x >= 0 and v1.y * nearP1.y >= 0) and(p1.x * nearP1.x >= 0 and p1.y * nearP1.y >= 0): return True else: return False p2 = Point(0,1) p1 = Point(7.62, 1.11) x = Line.fromCoord(0, 1, 1, 0) y = Line.fromCoord(1, 0, 0, 1) z = Line.fromCoord(0, 6, 0, -7.25) print(y) print(y.nearPoint(p2)) print(y.nearPoint(p2)- p2) print(y.insideTreug(p2))
29f58b769d226b4790169e5730c7a9075b8b0451
Sergey-Shulnyaev/my_python
/HomeWork_10.09.19/Third.py
2,353
3.640625
4
import tkinter class GaloConverter: def __init__(self): # Создать главное окно. self.main_window = tkinter.Tk() # Создать три рамки, чтобы сгруппировать элементы интерфейса. self.top_frame = tkinter.Frame() self.mid1_frame = tkinter.Frame() self.mid2_frame = tkinter.Frame() self.bottom_frame = tkinter.Frame() self.galo_label = tkinter.Label(self.top_frame, text='Введите количество галлонов:') self.galo_entry = tkinter.Entry(self.top_frame, width=10) self.galo_label.pack(side='left') self.galo_entry.pack(side='left') self.mile_label = tkinter.Label(self.mid1_frame, text='Введите количество миль:') self.mile_entry = tkinter.Entry(self.mid1_frame, width=20) self.mile_label.pack(side='left') self.mile_entry.pack(side='left') self.descr_label = tkinter.Label(self.mid2_frame, text='Мили на галлон (MPG):') self.value = tkinter.StringVar() self.mpg_label = tkinter.Label(self.mid2_frame, textvariable=self.value) self.descr_label.pack(side='left') self.mpg_label.pack(side='left') self.calc_button = tkinter.Button(self.bottom_frame, text='Преобразовать', command=self.convert) self.quit_button = tkinter.Button(self.bottom_frame, text='Выйти', command=self.main_window.destroy) self.calc_button.pack(side='left') self.quit_button.pack(side='left') self.mid1_frame.pack() self.top_frame.pack() self.mid2_frame.pack() self.bottom_frame.pack() tkinter.mainloop() def convert(self): galo = float(self.galo_entry.get()) miles = float(self.mile_entry.get()) MPG = miles / galo self.value.set(MPG) # Создать экземпляр класса KiloConverterGUI. Galo = GaloConverter()
4d7589abe594f6a22e9d308214666b90054a23c4
Sergey-Shulnyaev/my_python
/graphics/moodle/1/4.py
818
4.0625
4
from math import sqrt class Line: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __str__(self): if self.a < 0: a = " - %.2fx" % (-self.a) else: a = "%.2fx" % (self.a) if self.b < 0: b = " - %.2fx" % (-self.b) else: b = " + %.2fx" % (self.b) if self.c < 0: c = " - %.2fx" % (-self.c) else: c = " + %.2fx" % (self.c) return a + b + c + " = 0" @staticmethod def fromCoord(x1, y1, x2, y2): return Line(y1 - y2, x2 - x1, x1 * y2 - x2 * y1) def distanceToZero(self): return abs(self.c) / sqrt(self.a ** 2 + self.b ** 2) s = Line(3,4,5) x = Line.fromCoord(1, 0, 0, 1) print(s) print(x.distanceToZero())
18fc474590f1def29690c55bd15232b983edba25
Sergey-Shulnyaev/my_python
/HomeWork_1/cinema_price.py
1,448
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 19 14:37:06 2019 """ def vibor_film(film,time): if film == 'Пятница': if time == 12: return 250 elif time == 16: return 350 elif time == 20: return 450 elif film == 'Чемпионы': if time == 10: return 250 elif time == 13: return 350 elif time == 16: return 350 elif film == 'Пернатая банда': if time == 10: return 350 elif time == 14: return 450 elif time == 18: return 450 else: return 0 def skidka(data,numbil): a = 1 if data == 'Завтра' or data == 'завтра': a -= 0.05 elif data != 'сегодня' or data != 'Сегодня': return 0 if numbil >= 20: a -= 0.2 return a film = input('Сейчас в кино фильмы:"Пятница", "Чемпионы", "Пернатая банда"\nВыберите фильм:\t') data = input('Введите дату сеанса:\t') time = int(input('Введите время сеанса:\t')) numbil = int(input('Укажите количество билетов:\t')) a = vibor_film(film,time) b = skidka(data,numbil) * numbil if a * b == 0: print('Ошибка ввода') else: print('Стоимость булетов будет:',a*b)
38285d586d40592a3a00bace74aa4166960e6b03
moreira-matheus/math-fun
/exp_pow.py
513
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 4 13:58:42 2018 @author: USP """ import random import matplotlib.pyplot as plt def exp_pow_num(x): return x**x def exp_pow_den(x): return x**(1./x) N = 20000 x_low, x_high = 10**(-6), 2 x = sorted([random.uniform(x_low, x_high) for _ in range(N)]) y_num = [exp_pow_num(i) for i in x] y_den = [exp_pow_den(i) for i in x] plt.figure(1) plt.plot(x,y_num, label='$ f(x) = x^{x} $') plt.plot(x,y_den, label='$ f(x) = x^{1/x} $') plt.legend() plt.show()
7b5046099a1e06aa79d090d9f2d3fee33da48946
aratik711/100-python-programs
/my_exception_2.py
456
3.859375
4
""" Define a custom exception class which takes a string message as attribute. Hints: To define a custom exception, we need to define a class inherited from Exception. """ class myError(Exception): """My own exception class Attributes: msg -- explanation of the error """ def __init__(self, msg): self.msg = msg try: raise myError("Something went wrong") except myError as err: print(err.msg)
dbe164b35c75b08ccfca88cf63db48220b7ffafc
aratik711/100-python-programs
/number_add.py
386
4.09375
4
""" Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. Suppose the following input is supplied to the program: 9 Then, the output should be: 11106 """ num = int(input()) num1 = int("%s" % num) num2 = int("%s%s" % (num, num)) num3 = int("%s%s%s" % (num, num, num)) num4 = int("%s%s%s%s" % (num, num, num, num)) print(num1+num2+num3+num4)
30ee27670b91ef7aa6bfc727131e6d2271c00f6c
aratik711/100-python-programs
/frequency.py
692
4.09375
4
""" Question: Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. Suppose the following input is supplied to the program: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. Then, the output should be: 2:2 3.:1 3?:1 New:1 Python:5 Read:1 and:1 between:1 choosing:1 or:2 to:1 Hints In case of input data being supplied to the question, it should be assumed to be a console input. """ sentence = input() freq = {} for word in sentence.split(): freq[word] = freq.get(word, 0) + 1 words = sorted(freq.keys()) for word in words: print(word + ":" + str(freq[word]))
e14736ccc657561a7db0a6653d64f05953b85d30
aratik711/100-python-programs
/eval_example.py
320
4.28125
4
""" Please write a program which accepts basic mathematic expression from console and print the evaluation result. Example: If the following string is given as input to the program: 35+3 Then, the output of the program should be: 38 Hints: Use eval() to evaluate an expression. """ exp = input() print(eval(exp))
0e38a128a6b075c53e090d701674e4ff4b32026d
aratik711/100-python-programs
/isogram.py
516
3.859375
4
""" Determine if a word or phrase is an isogram. An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times. Examples of isograms: lumberjacks background downstream six-year-old The word isograms, however, is not an isogram, because the s repeats. """ def is_isogram(string): string = list(filter(str.isalpha, string.lower())) return len(set(string)) == len(string) print(is_isogram("lumberjacks"))
d33e36b0734802ce63caaa7310a21ecb2b6081d6
aratik711/100-python-programs
/subclass_example.py
382
4.125
4
""" Question: Define a class named American and its subclass NewYorker. Hints: Use class Subclass(ParentClass) to define a subclass. """ class American: def printnationality(self): print("America") class NewYorker: def printcity(self): American.printnationality(self) print("New York") citizen = NewYorker() citizen.printcity()
f3744e80c43703b02eab678c8b9e4b5d9569f3fb
ValeriiaGW/IntroPython_Bakanova_Valeriia
/HW4/hw_test.py
1,361
3.890625
4
values = [1, 2, 3, 4, 5] print(type(values)) values = (1, 2, 3, 4, 5) print(type(values)) values = (1, 2, 3, 4, 5) values = list(values) print(type(values)) values = [1, 2, 3, 4, 5] values = tuple(values) print(type(values)) values = [1, 2, 3, 4, 5] result = [] for value in values: result.append(value) print(result) values = [1, 2, 3, 4, 5] result = [] for value in values[::-1]: result.append(value) print(result) values = [1, 2, 3, 4, 5] print(len(values)) values = [1, 2, 3, 4, 5] new_value = values + values[::-1] print(new_value) values = [1, 2, 3, 4, 5] new_value = values new_value.append(6) print(values) values = [1, 2, 3, 4, 5] new_value = values.copy() new_value.append(6) print(values) values = [0] * 6 values[0] = 1 print(values) value = 0 values = [value] * 6 value = 1 print(values) my_list = [0] values = [my_list] * 3 print(values) my_list = [0] values = [my_list] * 3 my_list.append(1) print(values) my_list = [0] values = [my_list.copy()] * 3 my_list.append(1) print(values) my_list = ["a", "b", "c", "d", "e", "f"] my_str = " ".join(my_list) print(my_str) my_list = ["a", "b", "c", "d", "e", "f"] my_str = "_".join(my_list) print(my_str) my_list = ["a", "b", "c", "d", "e", "f"] my_str = "_".join(my_list[::-1]) print(my_str) my_list = ["a", "b", "c", "d", "e", "f"] my_str = "".join(my_list[::2]) print(my_str)
86977ffec84ee264f4dbf4c17e374611ca7ef533
ValeriiaGW/IntroPython_Bakanova_Valeriia
/HW_8/hw_8.py
2,845
3.640625
4
# 1) Дан список словарей persons в формате [{"name": "John", "age": 15}, ... ,{"name": "Jack", "age": 45}] # а) Напечатать имя самого молодого человека. Если возраст совпадает - напечатать все имена самых молодых. # б) Напечатать самое длинное имя. Если длина имени совпадает - напечатать все имена. # в) Посчитать среднее количество лет всех людей из списка. # persons = [ {"name": "Jon", "age": 15}, {"name": "Mike", "age": 35}, {"name": "Anna", "age": 15}, {"name": "Samanta", "age": 75}, {"name": "Jack", "age": 45}, ] age_list = [] names_length = [] for person in persons: age = person.get("age") age_list.append(age) long_name = len(person.get("name")) names_length.append(long_name) min_age = min(age_list) for person in persons: if person.get("age") == min_age: print(person.get("name")) max_name_length = max(names_length) for person in persons: if len(person.get("name")) == max_name_length: print(person.get("name")) avg_age = sum(age_list) / len(age_list) print(avg_age) # 2) Даны два словаря my_dict_1 и my_dict_2. # а) Создать список из ключей, которые есть в обоих словарях. # б) Создать список из ключей, которые есть в первом, но нет во втором словаре. # в) Создать новый словарь из пар {ключ:значение}, для ключей, которые есть в первом, но нет во втором словаре. # г) Объединить эти два словаря в новый словарь по правилу: # если ключ есть только в одном из двух словарей - поместить пару ключ:значение, # если ключ есть в двух словарях - поместить пару {ключ: [значение_из_первого_словаря, значение_из_второго_словаря]}, # # {1:1, 2:2}, {11:11, 2:22} ---> {1:1, 11:11, 2:[2, 22]} my_dict1 = {"key1": 1, "key2": 2, "key5": 5} my_dict2 = {"key1": 1, "key3": 3, "key4": 4} keys_1 = set(my_dict1.keys()) keys_2 = set(my_dict2.keys()) my_list_a = list(keys_1.intersection(keys_2)) my_list_b = list(keys_1.difference(keys_2)) new_dict_c = {} for key, value in my_dict1.items(): if key in my_list_b: new_dict_c[key] = value new_dict_g = my_dict1.copy() for key, value in my_dict2.items(): if key in new_dict_g: new_dict_g[key] = [new_dict_g[key], value] else: new_dict_g[key] = value
b02b74b30fa5db9a2c53d84dae858543ef2e3e00
S-Cardenas/Chess_Python_FP
/Pawn.py
3,416
3.546875
4
#location has to be the index of the list board def Pawn(piece, location, board, active_indx): if piece > 0: if location >= 9 and location <= 16: a = location + 1 * 9 b = location + 2 * 9 c = location + (1 * 9) + 1 d = location + (1 * 9) - 1 new_indxs = [a, b, c, d] #Check if new location is an active index i = 0 for item in new_indxs: if item not in active_indx: new_indxs[i] = 'null' i += 1 #Define which piece ID is in the new_indxs piece_ID = [] for indx in new_indxs: if indx == 'null': piece_ID.append('null') else: piece_ID.append(board[indx]) this = [] if piece_ID[0] == 0 and piece_ID[1] == 0: this.extend(new_indxs[0:2]) elif piece_ID[0] == 0 and piece_ID[1] != 0: this.append(new_indxs[0]) if piece_ID[2] < 0 and piece_ID[2] != 'null': this.append(new_indxs[2]) if piece_ID[3] < 0 and piece_ID[3] != 'null': this.append(new_indxs[3]) return this elif location >= 18 and location <= 61: a = location + 1 * 9 c = location + (1 * 9) + 1 d = location + (1 * 9) - 1 new_indxs = [a, c, d] #Check if new location is an active index i = 0 for item in new_indxs: if item not in active_indx: new_indxs[i] = 'null' i += 1 #Define which piece ID is in the new_indxs piece_ID = [] for indx in new_indxs: if indx == 'null': piece_ID.append('null') else: piece_ID.append(board[indx]) this = [] if piece_ID[0] == 0: this.append(new_indxs[0]) if piece_ID[1] != 'null' and piece_ID[1] < 0: this.append(new_indxs[1]) if piece_ID[2] != 'null' and piece_ID[2] < 0: this.append(new_indxs[2]) return this else: this = [] return this elif piece < 0: if location >= 54 and location <= 61: a = location - 1 * 9 b = location - 2 * 9 c = location - (1 * 9) + 1 d = location - (1 * 9) - 1 new_indxs = [a, b, c, d] #Check if new location is an active index i = 0 for item in new_indxs: if item not in active_indx: new_indxs[i] = 'null' i += 1 #Define which piece ID is in the new_indxs piece_ID = [] for indx in new_indxs: if indx == 'null': piece_ID.append('null') else: piece_ID.append(board[indx]) this = [] if piece_ID[0] == 0 and piece_ID[1] == 0: this.extend(new_indxs[0:2]) elif piece_ID[0] == 0 and piece_ID[1] != 0: this.append(new_indxs[0]) if piece_ID[2] < 0 and piece_ID[2] != 'null': this.append(new_indxs[2]) if piece_ID[3] < 0 and piece_ID[3] != 'null': this.append(new_indxs[3]) return this elif location >= 9 and location <= 52: a = location - 1 * 9 c = location - (1 * 9) + 1 d = location - (1 * 9) - 1 new_indxs = [a, c, d] #Check if new location is an active index i = 0 for item in new_indxs: if item not in active_indx: new_indxs[i] = 'null' i += 1 #Define which piece ID is in the new_indxs piece_ID = [] for indx in new_indxs: if indx == 'null': piece_ID.append('null') else: piece_ID.append(board[indx]) this = [] if piece_ID[0] == 0: this.append(new_indxs[0]) if piece_ID[1] != 'null' and piece_ID[1] < 0: this.append(new_indxs[1]) if piece_ID[2] != 'null' and piece_ID[2] < 0: this.append(new_indxs[2]) return this else: this = [] return this
e4d60aa8dc63871a3076ef785a7aabab78806d79
SudeepNadgambe/cv
/Guess_game.py
812
3.96875
4
import random print("Welcome to the Number Guessing Game\nI am thinking of a number between 1 and 100") guessed_number=random.randint(1,100) print(guessed_number) level=input("Type 'e' for easy level\nType 'h' for hard level\n") if level == 'e': chances = 10 elif level == 'h': chances = 5 else: print("Invalid input") end = False while not end: print(f"You have {chances} live left") user_guess=int(input("Make a guess")) if user_guess==guessed_number: print("You won") end = True else: chances-=1 if user_guess > guessed_number: print("Too high") elif user_guess < guessed_number: print("Too low") if chances==0: print("Your lives ended \nYou lose") end = True
a3863e7f034ce25c3b0803c0230e732508e90d98
jordwhit3288/PTO-App
/PTO_Calculator_v4.0.py
10,363
3.859375
4
from datetime import date import datetime from datetime import datetime import time import pandas as pd import numpy as np def hours_current_balance(nurse_or_not): if nurse_or_not == 'yes': nurse_hours_num = accruing_pto_hours() nurse_hours_pto = input('Are you going to use PTO?') if nurse_hours_pto == 'yes': num_of_hours = input('How many hours?') num_of_hours_num = float(num_of_hours) hours_remaining = nurse_hours_num - num_of_hours_num days_remaining = float(hours_remaining / 12) days_remaining = float(round(days_remaining, 2)) print('You have ' , hours_remaining , 'hours', ', that is ' , days_remaining ,' days') if nurse_hours_pto == 'no': no_pto_days = round(float(nurse_hours_num) / 12,2) print('You have ' , nurse_hours_num , 'hours' ', that is' , no_pto_days , ' days') if nurse_or_not == 'no': hours_balance_num = accruing_pto_hours() norm_shift_pto = input('Are you going to use PTO?') if norm_shift_pto == 'yes': num_of_hours = input('How many hours of PTO?') pto_hours = float(num_of_hours) hours_remaining = hours_balance_num - pto_hours days_remaining = hours_remaining / 8 days_remaining = float(round(days_remaining,2)) print('You have ' , hours_remaining , 'hours' , ', that is ', days_remaining, ' days') if norm_shift_pto == 'no': no_pto_days = round(float(hours_balance) / 8,2) print('You have ' , hours_balance , 'hours' , ', that is ', no_pto_days, ' days') def hours_total_pto(nurse_or_not): if nurse_or_not == 'yes': hours_balance = input('How many hours do you have?') hours_balance_num = float(hours_balance) norm_shift_pto = input('Are you going to use PTO?') if norm_shift_pto == 'yes': num_of_hours = input('How many hours of PTO?') pto_hours = float(num_of_hours) hours_remaining = hours_balance_num - pto_hours days_remaining = hours_remaining / 12 days_remaining = float(round(days_remaining,2)) print('You have ' , hours_remaining , 'hours' , ', that is ', days_remaining, ' days') if norm_shift_pto == 'no': no_pto_days = round(float(hours_balance) / 12,2) print('You have ' , hours_balance , 'hours' , ', that is ', no_pto_days, ' days') if nurse_or_not == 'no': hours_balance = input('How many hours do you have?') hours_balance_num = float(hours_balance) norm_shift_pto = input('Are you going to use PTO?') if norm_shift_pto == 'yes': num_of_hours = input('How many hours of PTO?') pto_hours = float(num_of_hours) hours_remaining = hours_balance_num - pto_hours days_remaining = hours_remaining / 8 days_remaining = float(round(days_remaining,2)) print('You have ' , hours_remaining , 'hours' , ', that is ', days_remaining, ' days') if norm_shift_pto == 'no': no_pto_days = round(float(hours_balance) / 8,2) print('You have ' , hours_balance , 'hours' , ', that is ', no_pto_days, ' days') def days_current_balance(nurse_or_not): if nurse_or_not == 'yes': nurse_days_num = accruing_pto_days() nurse_days_pto = input('Are you going to use PTO?') if nurse_days_pto == 'yes': num_of_days = input('How many days?') num_of_days_num = float(num_of_days) days_remaining = nurse_days_num - num_of_days_num days_remaining = float(days_remaining) hours_remaining = float(days_remaining * 12) hours_remaining = float(round(hours_remaining, 2)) print('You have ' , days_remaining , 'days', ', that is ' , hours_remaining ,' hours') if nurse_days_pto == 'no': no_pto_hours = 0 no_pto_hours = float(nurse_days) * 12 print('You have ' , nurse_days_num, ',that is' , no_pto_hours ,' hours') if nurse_or_not == 'no': days_balance_num = accruing_pto_days() norm_shift_pto = input('Are you going to use any PTO?') if norm_shift_pto == 'yes': num_of_days = input('How many days?') pto_days = float(num_of_days) days_remaining = days_balance_num - pto_days hours_remaining = days_remaining * 8 hours_remaining = float(round(hours_remaining,2)) print('You have ' , days_remaining , 'days' , ', that is ', hours_remaining, ' hours') if norm_shift_pto == 'no': no_pto_hours = float(days_balance) * 8 print('You have ' , days_balance , 'days' , ', that is ', no_pto_hours, ' hours') def days_total_pto(nurse_or_not): if nurse_or_not == 'yes': nurse_days = input('How many days do you have?') nurse_days_num = float(nurse_days) nurse_days_pto = input('Are you going to use PTO?') if nurse_days_pto == 'yes': num_of_days = input('How many days?') num_of_days_num = float(num_of_days) days_remaining = nurse_days_num - num_of_days_num days_remaining = float(days_remaining) hours_remaining = float(days_remaining * 12) hours_remaining = float(round(hours_remaining, 2)) print('You have ' , days_remaining , 'days', ', that is ' , hours_remaining ,' hours') if nurse_days_pto == 'no': no_pto_hours = 0 no_pto_hours = float(nurse_days) * 12 print('You have ' , nurse_days_num, ',that is' , no_pto_hours ,' hours') if nurse_or_not == 'no': days_balance = input('How many days do you have?') days_balance_num = float(days_balance) norm_shift_pto = input('Are you going to use any PTO?') if norm_shift_pto == 'yes': num_of_days = input('How many days?') pto_days = float(num_of_days) days_remaining = days_balance_num - pto_days hours_remaining = days_remaining * 8 hours_remaining = float(round(hours_remaining,2)) print('You have ' , days_remaining , 'days' , ', that is ', hours_remaining, ' hours') if norm_shift_pto == 'no': no_pto_hours = float(days_balance) * 8 print('You have ' , days_balance , 'days' , ', that is ', no_pto_hours, ' hours') def accruing_pto_hours(): current_balance = input('How many hours do you currently have?') current_balance = float(current_balance) hours_per_check = input('How many hours do you accrue per check?') hours_per_check = float(hours_per_check) end_of_year = date(2020, 12, 31) current_date = date.today() date_diff = (end_of_year - current_date) date_diff = date_diff.days weeks_left = float(round(date_diff / 7)) checks_left = (weeks_left / 2) remaining_pto_accrual = (checks_left * hours_per_check) total_remaining_pto = remaining_pto_accrual + current_balance total_remaining_pto = round(total_remaining_pto,2) print('Remaining pto hours for the year ' , total_remaining_pto) return total_remaining_pto def accruing_pto_days(): current_balance = input('How many days do you currently have?') current_balance = float(current_balance) current_balance_to_hours = (current_balance * 8) hours_per_check = input('How many hours do you accrue per check?') hours_per_check = float(hours_per_check) end_of_year = date(2020, 12, 31) current_date = date.today() date_diff = (end_of_year - current_date) date_diff = date_diff.days weeks_left = float(round(date_diff / 7)) checks_left = (weeks_left / 2) remaining_pto_accrual = (checks_left * hours_per_check) remaining_pto_to_days = (remaining_pto_accrual / 8) total_remaining_pto = remaining_pto_to_days + current_balance total_remaining_pto = round(total_remaining_pto,2) print('Remaining pto days for the year ' , total_remaining_pto) return total_remaining_pto; ##MAIN METHOD## def main(): hours_or_days_list = ['hours', 'days'] hours_or_days_list = [element.lower() for element in hours_or_days_list] hours_or_days = input('Do you have your PTO in hours or days?') while hours_or_days not in hours_or_days_list: print('---Enter hours or days---') hours_or_days = input('Do you have your PTO in hours or days?') know_total_or_balance_list = ['Total PTO', 'Current Balance'] know_total_or_balance_list = [element.lower() for element in know_total_or_balance_list] know_total_or_balance = input('Do you know your total PTO for the year, or just current balance?') while know_total_or_balance not in know_total_or_balance_list: print('---Enter Total PTO or Current Balance---') know_total_or_balance = input('Do you know your total PTO for the year, or just current balance?') if know_total_or_balance == know_total_or_balance_list[0]: #total pto if hours_or_days == hours_or_days_list[0]: #hours nurse_or_not = input('Do you work 12 hour shifts?') hours_total_pto(nurse_or_not) if hours_or_days == hours_or_days_list[1]: #days nurse_or_not = input('Do you work 12 hour shifts?') days_total_pto(nurse_or_not) if know_total_or_balance == know_total_or_balance_list[1]: #current balance if hours_or_days == hours_or_days_list[0]: #hours nurse_or_not = input('Do you work 12 hour shifts?') hours_current_balance(nurse_or_not) if hours_or_days == hours_or_days_list[1]: #days nurse_or_not = input('Do you work 12 hour shifts?') days_current_balance(nurse_or_not) print() input('Press X to Exit or Hit Enter for Another Simulation') print() print() print('Another PTO Simulation Will Begin Now..') print() return; #Calling main method while True: main()
4e86f5a5a42e92bae21d418e4e7e29718ca47ec9
ncrafa/infosatc-lp-avaliativo-03
/exercicio 3.py
327
3.921875
4
numero=int(input("Insira um numero de 1 a 12: "))-1 meses=["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"] for x in range(1,12): if x==numero: print(" mês de: ",meses[numero]) if x != numero : print(" mês não encontrado")
58694ea2088a17fc1bff58cc191519bb5277daf3
ryan-ghosh/Python-Projects
/ESC180_Labs/LAB!.py
866
3.625
4
def find_euclidean_distance(x1, y1, x2, y2): """ (float,float,float,float) -> float """ def is_cow_within_bounds(cow_position, boundary_points): """ Your docstring here """ def find_cow_distance_to_boundary(cow_position, boundary_point): """ Your docstring here """ def find_time_to_escape(cow_speed, cow_distance): """ Your docstring here """ def report_cow_status(cow_position1, cow_position2, delta_t, boundary_points): """ Your docstring here """ if __name__ == '__main__': # Test your code by running your functions here, and printing the # results to the terminal. # This code will not be marked print('Testing functions...') # test_distance = find_euclidian_distance(3.0, 3.0, 2.0, 5.0) # print(test_distance) # test_distance should be 2.24
eb63a6c9cc749b10b0d18785e756048bee6b0dde
ryan-ghosh/Python-Projects
/scheduler.py
1,465
3.6875
4
class Node: def __init__(self, date:int, schedule:dict): self.date = date self.schedule = schedule def add_task(self, time:int, task:str): self.schedule[time] = task def print_task(self, time:int): print(self.schedule[time]) def print_schedule(self): for i in self.schedule: print("{}:".format(i), self.schedule[i]) class Queue: def __init__(self, list: list, capacity: int): self.list = list self.capacity = capacity def isEmpty(self): if self.list == []: return True return False def isFull(self): length = len(self.list) if length == self.capacity: return True else: return False def enqueue(self, data): if self.isFull(): print("Max capacity reached") else: self.list.append(data) def dequeue(self): if self.isEmpty(): print("Empty") else: self.list.pop(0) def print_Nodes(self): for i in self.list: i.print_schedule() ## initializing schedule sunday = Node(26, {}) sunday.add_task(9, "wake up") sunday.add_task(9.30, "eat breakfast") sunday.add_task(10.30, "exercise") sunday.add_task(13, "scholarships, Corona funding, Wealthsimple") sunday.print_schedule() ## initialize Queue days = []
944dbd5c7aa1cb0f5543c61e7a44dd2507eb8274
Macro1989/cp1404practicals
/prac_02/randoms.py
652
3.953125
4
import random print(random.randint(5, 20)) # line 1 print(random.randrange(3, 10, 2)) # line 2 print(random.uniform(2.5, 5.5)) # line 3 #What did you see on line 1? 13 #What was the smallest number you could have seen, what was the largest? 5 and 20 #What did you see on line 2? 3 #What was the smallest number you could have seen, what was the largest? 3 and 9 #Could line 2 have produced a 4? no #What did you see on line 3? 4.582393345338769 #What was the smallest number you could have seen, what was the largest? 2.5 and 5.5 #Write code, not a comment, to produce a random number between 1 and 100 inclusive. print(random.randint(1, 100))
26b320e3ef9c264c91eceb6661117ec9356d117a
JoCGM09/AlgorithmsAndDataStructuresPython
/Algorithms/Search/binary_Search.py
1,484
4.03125
4
""" - Search algorithm who search a value in a given list by looking for the middle of it. If we get a match return the index, else if we do not get a match check whether the element is less or greater than the middle element. If is greater pick the elements on the right and start again, if is less pick the left. - Is applied on sorted lists with a lot of elements. - It has a time comlexity of O(logn). - It is very simple to implementate. """ # min and max -> Pointers at the beginning and the end of the list zone to check # step -> Number of steps to catch the target # middle -> Middle index at the list def binary_search(list, target): min = 0 max = len(list) - 1 step = 0 while min <= max: middle = (min + max) // 2 if list[middle] == target: step+=1 return middle, step elif list[middle] < target: step+=1 min = middle + 1 else: step+=1 max = middle - 1 return -1, 0 def validate(index, step): if index != -1: print(f'Target found at index {index}, number of steps for search: {step}') else: print('Target not found') ############ Test ############ numbers = [2,4,6,7,8,13,16] numbers2 = [3,4,6,7,8,11] result1, index1 = binary_search(numbers,7) result2, index2 = binary_search(numbers, 4) result3, index3 = binary_search(numbers2, 8) result4, index4 = binary_search(numbers2, 5) validate(result1, index1) validate(result2, index2) validate(result3, index3) validate(result4, index4)
5e0fc9b783390cb732bee5f5cba05f87a75591eb
julianandrews/adventofcode
/2019/python/utils/pq.py
1,325
3.796875
4
import heapq class UpdateableQueue: def __init__(self): self.count = 0 self.values = [] self.entries = {} def push(self, value, priority): """Add a new value or update the priority of an existing value.""" if value in self.entries: self.remove(value) entry = self.QueueEntry(value, priority, self.count) self.entries[value] = entry self.count += 1 heapq.heappush(self.values, entry) def remove(self, value): """Remove a value from the queue.""" entry = self.entries.pop(value) entry.removed = True def pop(self): """Remove and return the lowest priority value.""" while self.values: entry = heapq.heappop(self.values) if not entry.removed: del self.entries[entry.value] return entry.value raise KeyError("Pop from empty queue") def __len__(self): return len(self.entries) class QueueEntry: def __init__(self, value, priority, counter): self.value = value self.priority = priority self.counter = counter self.removed = False def __lt__(self, other): return (self.priority, self.counter) < (other.priority, other.counter)
d21fe1c61458bf07a2f42d8236972c5073bc4286
julianandrews/adventofcode
/2015/python/day13.py
1,050
3.5
4
import collections import fileinput import itertools def happy_sum(people, happy_map): neighbors = itertools.cycle(people) next(neighbors) return sum( happy_map[a][b] + happy_map[b][a] for a, b in zip(people, neighbors) ) def part1(happy_map): return max( happy_sum(people, happy_map) for people in itertools.permutations(happy_map.keys()) ) def part2(happy_map): happy_map["Me"] = {} for person in happy_map.keys(): happy_map["Me"][person] = 0 happy_map[person]["Me"] = 0 return max( happy_sum(people, happy_map) for people in itertools.permutations(happy_map.keys()) ) if __name__ == "__main__": lines = [line.strip() for line in fileinput.input()] happy_map = collections.defaultdict(dict) for line in lines: words = line[:-1].split() happy_map[words[0]][words[-1]] = (1 if words[2] == "gain" else -1) * int(words[3]) print("Part 1: %s" % part1(happy_map)) print("Part 2: %s" % part2(happy_map))
190b8e36d82e4d4e8b6f90f3f31b44981f1906f2
imudiand/recipes
/Python/decorators/decorators.py
2,107
3.9375
4
from functools import wraps # Why use functools.wraps ?? # When you print get_text.__name__ doesnt return get_text # without using wraps; you'l see that the name is overridden # to the wrapper functions name - func_wrapper. # Hence, use this @wraps decorator on the wrapper_function # and pass the func as an argument to this decorator so that # it sets these attributes correctly. It helps a lot in debugging # when you want to know what the name of the function is. # With using @wraps; the name is correctly set to "get_text" # Simple decorator example def tags_decor(func): @wraps(func) def wrapper(name): # wrapper func can do verifications on arguments before calling func(name) return "<p>%s</p>" % (func(name)) # wrapper func can do verifications/operations on the result after calling func(name) return wrapper @tags_decor def get_text(name): return "Hello %s" % (name) # Multiple Decorators example def p_tags_decor(func): @wraps(func) def wrapper(name): return "<p>%s</p>" % (func(name)) return wrapper def div_tags_decor(func): @wraps(func) def wrapper(name): return "<div>%s</div>" % (func(name)) return wrapper def h1_tags_decor(func): @wraps(func) def wrapper(name): return "<h1>%s</h1>" % (func(name)) return wrapper @p_tags_decor @div_tags_decor @h1_tags_decor def get_text2(name): return "Hello %s" % (name) # Passing Arguments to Decorators def tags(tagname): def tags_decor(func): @wraps(func) def wrapper(name): # wrapper func can do verifications on arguments before calling func(name) return "<{0}>{1}</{0}>".format(tagname, func(name)) # wrapper func can do verifications/operations on the result after calling func(name) return wrapper return tags_decor @tags("p") @tags("div") @tags("h1") def get_text3(name): return "Hello %s" % (name) # testing code here def main(): #import pdb; pdb.set_trace() # print get_text.__name__ return get_text if functools.wraps is used else returns wrapper print get_text("Harshit") print get_text2("Hemant") print get_text3("Hemant") if __name__ == "__main__": main()
6e137cdf18daa271370c51ee89fb3f3d05e1cbda
imudiand/recipes
/Python/generators/non-generator_prime_nums.py
666
3.96875
4
import math # Non-Generator Implementation - Get prime Numbers def get_primes(input_list): prime_numbers_list = [] for item in input_list: if is_prime(item): prime_numbers_list.append(item) return prime_numbers_list def get_primes2(input_list): return [ item for item in input_list if is_prime(item) ] def is_prime(number): if number > 1: if number == 2: return True if number % 2 == 0: return False for current in range(3, int(math.sqrt(number) + 1), 2): if number % current == 0: return False return True return False def main(): print get_primes(range(100)) print get_primes2(range(100)) if __name__ == "__main__": main()
a8f29d0c4f9adb25af4ff18d596b2f5301801bdc
imudiand/recipes
/Python/tuts/recursion/recursive_sum.py
312
3.8125
4
def r_sum(num_list): sum = 0 for item in num_list: if type(item) == type([]): sum += r_sum(item) else: sum += item return sum def main(): list1 = [3, 5, 9, 20, 100] print r_sum(list1) list2 = [3, [4, 2, 4], 2, [3, 4, [5, 3], 12], 2, 9] print r_sum(list2) if __name__ == "__main__": main()
52c361e776fc68c64270961259066b5e6eac6364
rootwiz/colorful_hexagon
/Hexagon.py
1,683
3.625
4
# screen size S_HIGHT = 500 S_WIDTH = 500 # 正六角形クラス class Hexagon: ''' ---- / \ \ / ---- ''' size = 40 def __init__(self, x, y, color, wall): self.width = Hexagon.size self.height = Hexagon.size * 3 // 4 pos_x = self.size // 3 pos_y = S_HIGHT * 2 // 3 tmp_x = pos_x + self.width * 2 // 3 * x tmp_y = pos_y - self.height * y + self.height // 2 * x vertexes_offset = [[0, 0], [self.width//3, 0], [self.width*2//3, -self.height//2], [self.width//3, -self.height], [0, -self.height], [-self.width//3, -self.height//2]] self.vertexes = [None]*6 for i in range(6): self.vertexes[i] = [tmp_x+vertexes_offset[i][0], tmp_y+vertexes_offset[i][1]] self.x = x self.y = y self.color = color self.wall = wall self.active = True self.point = 1 def find_coordinates(self, c_x, c_y, v1, v2): # y = ax + b ; x = (y - b) / a a = (v1[1] - v2[1]) / (v1[0] - v2[0]) b = v1[1] - (a * v1[0]) return [(c_y - b) / a, c_y] def is_in_area(self, c_x, c_y): d_y = self.vertexes[0][1] # yの最大値(下) u_y = self.vertexes[3][1] # yの最小値(上) l_x = self.vertexes[5][0] # xの最小値(左) r_x = self.vertexes[2][0] # xの最大値(右) #print(d_y, u_y, l_x, r_x) if c_y > d_y or c_y < u_y: return False elif c_x > r_x or c_x < l_x: return False else: pass # 正六角形内かを判定する処理を記述予定 return True
ab158012359b50275f2adabb082830fb37bfd103
joeycarter/atlas-plot-utils
/examples/random_hist.py
1,151
3.5
4
#!/usr/bin/env python """ Random Histogram ================ This module plots a random histogram using the ATLAS Style. .. literalinclude:: ../examples/random_hist.py :lines: 12- """ from __future__ import absolute_import, division, print_function import ROOT as root from atlasplots import atlas_style as astyle def main(): # Set the ATLAS Style astyle.SetAtlasStyle() # Construct the canvas c1 = root.TCanvas("c1", "The FillRandom example", 0, 0, 800, 600) # Define a distribution form1 = root.TFormula("form1", "abs(sin(x)/x)") sqroot = root.TF1("sqroot", "x*gaus(0) + [3]*form1", 0, 10) sqroot.SetParameters(10, 4, 1, 20) # Randomly fill the histrogram according to the above distribution hist = root.TH1F("hist", "Test random numbers", 100, 0, 10) hist.FillRandom("sqroot", 10000) hist.Draw() # Set axis titles hist.GetXaxis().SetTitle("x axis") hist.GetYaxis().SetTitle("y axis") # Add the ATLAS Label astyle.ATLASLabel(0.2, 0.87, "Internal") # Save the plot as a PDF c1.Update() c1.Print("random_hist.pdf") if __name__ == '__main__': main()
544d131948f0580166fee32c23c6c936795fb419
Kelsey2018/Algorithm_2020HIT
/algorithm/quickSort/main.py
3,207
3.640625
4
# -*- coding: utf-8 -*- # @Author: Xiang xi # @Date: 2020-05-05 10:32:35 import random import copy import random import time import math def quickSort(A,p,r): if p < r: q = rand_partition(A,p,r) quickSort(A,p,q-1) quickSort(A,q+1,r) return A def swap(A,i,j): temp = A[i] A[i] = A[j] A[j] = temp return A[i],A[j] def rand_partition(A,p,r): # key = A[p] #基准元素 # while p < r: # while p<r and A[r]>=key: # r = r - 1 # A[p] = A[r] # while p<r and A[p]<=key: # p = p +1 # A[r] = A[p] # A[p] = key # return p i = random.randint(p,r) A[i], A[r] = A[r], A[i] key = A[r] i = p - 1 for j in range(p,r): if A[j] <= key: i = i + 1 A[i], A[j] = A[j], A[i] A[i+1], A[r] = A[r], A[i+1] return i+1 def generateA(length): random_list = [] for i in range(length): random_list.append(random.randint(1,100)) return random_list def generateNewA(length,i): dup_num = int(length * 10 * i * 0.01) #第i个数据集重复元素的个数 random_dup_list = [] if dup_num > 0: dup_number = random.randint(1,math.pow(10,6)) print("重复元素为:",dup_number) print("重复次数:",dup_num) for i in range(dup_num): random_dup_list.append(dup_number) while len(random_dup_list) <= length: random_dup_list.append(random.randint(1, math.pow(10,6))) # random.shuffle(random_dup_list[1:]) print(random_dup_list) return random_dup_list else: while len(random_dup_list) <= length: random_dup_list.append(random.randint(1, math.pow(10,6))) return random_dup_list def three_partition(A,p,r): if (p >= r): return pivot = A[p] gt = r lt = p i = p + 1 while i <= gt: if A[i] > pivot: A[i],A[gt] = swap(A,i,gt) gt = gt - 1 elif A[i] < pivot: # A[i], A[lt] = A[lt], A[i] A[i], A[lt] = swap(A,i,lt) lt = lt + 1 i = i + 1 else: i = i + 1 three_partition(A,p,lt-1) three_partition(A,gt+1,r) return A if __name__ == '__main__': start = time.time() #=================单个数据集=================== # A = generateA(length = 20) # print("排序前:",A) # p = 0 # r = len(A) - 1 # print("排序后:",quickSort(A,p,r)) # =================单个数据集=================== # =================11个数据集=================== length = math.pow(10,6) # length = 5000 for i in range(7,11): start = time.time() A = generateNewA(length,i) # print("第{}个数据集------排序前:".format(i), A) p = 0 r = len(A) - 1 print("第{}个数据集------排序后:".format(i), three_partition(A,p,r)) end = time.time() print("Running Time(ms):{:.4f}".format((end - start) * 1000)) # =================11个数据集=================== # end = time.time() # print("Running Time(ms):{:.4f}".format((end - start) * 1000))
025ec86f422233e500aeaf2b9c6f6432db4585b4
ssanusi/Data-Structure
/Stack/Python/Stack.py
574
3.90625
4
class Stack(object): def __init__(self): self.data = [] self.count = 0 def push(self, item): self.data.append(item) self.count += 1 def pop(self): if self.count == 0: return "Stack is Empty" data = self.data[-1] del self.data[-1] self.count -= 1 return data def peek(self): if self.count == 0: return "Stack is Empty" return self.data[-1] def isEmpty(self): return self.count == 0 def size(self): return self.count
933e0974e486a9710bb592955f206300485b798f
CodeupClassroom/bayes-python-exercises
/pandas_exercises.py
5,254
3.75
4
import numpy as np import pandas as pd from pydataset import data ## Exercise 1 # On average, which manufacturer has the best miles per gallon? # How many different manufacturers are there? # How many different models are there? # Do automatic or manual cars have better miles per gallon? mpg = data('mpg') mpg["mpg"] = (mpg.hwy + mpg.cty) / 2 automatic = mpg[mpg.trans.str.contains("auto")] manual = mpg[mpg.trans.str.contains("manual")] auto_avg = automatic.mpg.mean() manual_avg = manual.mpg.mean() print("automatic", auto_avg) print("manual:", manual_avg) # On average, which manufacturer has the best miles per gallon? city_and_hwy = mpg.groupby("manufacturer").hwy.agg("mean") + mpg.groupby("manufacturer").cty.agg("mean") average_mpg = city_and_hwy / 2 best_mpg_manufacturer = average_mpg.idxmax() best_mpg_manufacturer # How many different manufacturers are there? number_of_different_manufacturers = len(mpg.manufacturer.unique()) number_of_different_manufacturers # How many di fferent models are there? number_of_different_models = mpg.model.nunique() number_of_different_models # Do automatic or manual cars have better miles per gallon? mpg.head() mpg["transmission"] = mpg.trans.str.partition("(")[0] mpg = mpg.drop(columns = ["trans"]) mpg["average_mpg"] = (mpg.cty + mpg.hwy) / 2 mpg_and_transmission_type = mpg[["average_mpg", "transmission"]] mpg_and_transmission_type.head() mpg_and_transmission_type.groupby("transmission").mean() best_mpg_transmission_type = mpg_and_transmission_type.groupby("transmission").mean().idxmax() best_mpg_transmission_type # another approach to the above problem without grouping by # mpg["mpg"] = (mpg.hwy + mpg.cty) / 2 # automatic = mpg[mpg.trans.str.contains("auto")] # manual = mpg[mpg.trans.str.contains("manual")] # auto_avg = automatic.mpg.mean() # manual_avg = manual.mpg.mean() ## Exercise 2 # Copy the users and roles dataframes from the examples above. # What do you think a right join would look like? # An outer join? # What happens if you drop the foreign keys from the dataframes and try to merge them? users = pd.DataFrame({ 'id': [1, 2, 3, 4, 5, 6], 'name': ['bob', 'joe', 'sally', 'adam', 'jane', 'mike'], 'role_id': [1, 2, 3, 3, np.nan, np.nan] }) roles = pd.DataFrame({ 'id': [1, 2, 3, 4], 'name': ['admin', 'author', 'reviewer', 'commenter'] }) right_join = pd.merge(users, roles, left_on="role_id", right_on="id", how="right") right_join outer_join = pd.merge(users, roles, left_on="role_id", right_on="id", how="outer") outer_join ## Exercise 3 # Create a function named get_db_url. It should accept a username, hostname, password, and database name and return a url formatted like in the examples in this lesson. def get_db_url(user, host, password, database_name): url = f'mysql+pymysql://{user}:{password}@{host}/{database_name}' return url # Use your function to obtain a connection to the employees database. from env import host, user, password employees_db_url = get_db_url(user, host, password, "employees") employees_db_url query = "select * from employees limit 10" pd.read_sql(query, employees_db_url) # Once you have successfully run a query: # Intentionally make a typo in the database url. What kind of error message do you see? # Intentionally make an error in your SQL query. What does the error message look like? # Read the employees and titles tables into two separate dataframes query = "SELECT * from employees" employees = pd.read_sql(query, employees_db_url) query = "SELECT * FROM titles" titles = pd.read_sql(query, employees_db_url) # Visualize the number of employees with each title. unique_titles = titles.groupby("title").count() unique_titles.rename(columns={"emp_no": "number_with_title"}, inplace=True) unique_titles = unique_titles.drop(columns=["from_date", "to_date"]) unique_titles = unique_titles.reset_index() unique_titles.plot(x ='title', y='number_with_title', kind = 'bar') # Join the employees and titles dataframes together. employee_titles = pd.merge(employees, titles, how="inner", left_on="emp_no", right_on="emp_no") employee_titles.head() # Visualize how frequently employees change titles. df = employee_titles.groupby("emp_no").count() df.head() df = df.reset_index() df = df.rename(columns={"title":"number_of_titles"}) df = df[["number_of_titles", "emp_no"]] df.head() df = df.rename(columns={"emp_no":"number_of_employees"}) title_counts = df.groupby("number_of_titles").count() title_counts = title_counts.reset_index() title_counts df.plot(x ='number_of_titles', y='number_of_employees', kind = 'bar') # For each title, find the hire date of the employee that was hired most recently with that title. employee_titles.groupby("title").hire_date.max() # create a cross tabulation of the number of titles by department. # (Hint: this will involve a combination of SQL and python/pandas code) query = """ select * from departments join dept_emp using(dept_no) join titles using(emp_no) where titles.to_date > now() and dept_emp.to_date > now() """ df = pd.read_sql(query, employees_db_url) df.head() # number of titles per department number_of_titles_per_dept = pd.crosstab(df.title, df.dept_name) number_of_titles_per_dept
0fbfa0dc00e79f42281e3829b339f181bc801cd1
jmcq89/code
/ProjectEuler/Project Euler 12.py
506
3.796875
4
from math import sqrt def factors(n): fact=[1,n] check=2 rootn=sqrt(n) while check<rootn: if n%check==0: fact.append(check) fact.append(n/check) check+=1 if rootn==check: fact.append(check) fact.sort() return fact def triangleFactors(max): n=6 triangle=21 while len(factors(triangle))<max+1: triangle=(n*(n+1))/2 n+=1 if len(factors(triangle))>max: print triangle triangleFactors(500)
799e4ea0240a9b0a49f66d7cd959dc1b4132a221
jmcq89/code
/ProjectEuler/Project Euler 67.py
607
3.5
4
def _reduce_triangle(to_reduce): last_row=to_reduce[-1] for index in xrange(len(to_reduce)-1): to_reduce[-2][index]+=max(last_row[index:index+2]) del to_reduce[-1] def find_max_sum(triangle): while len(triangle)>1: _reduce_triangle(triangle) return triangle[0][0] def _parse_triangle_from_file(data_file): triangle=[] with open(data_file,'r')as triangle_file: for line in triangle_file: triangle.append([int(x) for x in line.split()]) return triangle triangle=_parse_triangle_from_file('triangle_67.txt') print find_max_sum(triangle)
448e960d5310146600fcd81d8210ba68c5071fa1
dknitk/programs
/python/projects/KWPythonSample/KWHelloWord.py
404
3.890625
4
num1 = input("Enter the first Number:") num2 = input("Enter the first Number:") result1 = int(num1) + int(num2) result2 = float(num1) + float(num2) print(result1) print(result2) cordinates = (4, 5) print(cordinates[0]) print(cordinates[1]) def sayHi(): print("Hello") sayHi() # Function and class declaration def addition(a, b): return a + b result = addition(10, 30) print(result)
dc8cd70b3df76eec86889021b5d8ca1bf329b79f
webclinic017/machinelearning
/Artificial_Intelligence_with_Python/legacy/chap_6.py
564
3.53125
4
import sys def logic_programming(option=1): if option == 1: ''' Matching mathematical expressions ''' print("Example: I say Hello world") pass elif option == 2: ''' Validating primes ''' pass elif option == 3: ''' Parsing a family tree ''' pass elif option == 4: ''' Analyzing geography ''' pass elif option == 5: ''' Building a puzzle solver ''' pass pass def main(): logic_programming(int(sys.argv[1])) if __name__ == "__main__": main()
1b2f0f743c907d65b09cebaa80561cb3fb920ef3
pinruic/CSC361
/lab3/smtpclient.py
1,939
3.609375
4
from socket import * msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailserver mailserver = "smtp.uvic.ca" portnumber = 25 # Create socket called clientSocket and establish a TCP connection with mailserver clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((mailserver, portnumber)) recv = clientSocket.recv(1024).decode() print(recv) if recv[:3] != '220': print('220 reply not received from server.') # Send HELO command and print server response. heloCommand = 'HELO Alice\r\n' clientSocket.send(heloCommand.encode()) recv1 = clientSocket.recv(1024).decode() print(recv1) if recv1[:3] != '250': print('250 reply not received from server.') # Send MAIL FROM command and print server response. command1 = "MAIL FROM: <[email protected]>\r\n" clientSocket.send(command1.encode()) recv2 = clientSocket.recv(1024).decode() print(recv2) if recv2[:3] != "250": print("250 reply not received from server.") # Send RCPT TO command and print server response. command2 = "RCPT TO: <[email protected]>\r\n" clientSocket.send(command2.encode()) recv3 = clientSocket.recv(1024).decode() print(recv3) if recv3[:3] != "250": print("250 reply not received from server.") # Send DATA command and print server response. command3 = "DATA\r\n" clientSocket.send(command3.encode()) recv4 = clientSocket.recv(1024).decode() print(recv4) if recv4[:3] != "354": print("354 reply not received from server.") # Send message data. clientSocket.send(msg) # Message ends with a single period. clientSocket.send(endmsg) recv5 = clientSocket.recv(1024) print(recv5) if recv5[:3] != "250": print("250 reply not received from server.") # Send QUIT command and get server response. command4 = "QUIT\r\n" clientSocket.send(command4.encode()) recv6 = clientSocket.recv(1024).decode() print(recv6) if recv6[:3] != '221': print('221 reply not received from server.')
840b38a9c037abbe972948fe8facd628b05c1617
nishthabhatia/bmi210_final_project
/app.py
7,019
3.6875
4
from owlready2 import * #Load the ontology and present the introduction. def setup(): #Load the existing ontology onto = get_ontology('ProjectOntology.owl') onto.load() convo_running = True #TO DO --> ADD COLOR! header = """ ███████╗██╗████████╗███╗ ██╗███████╗███████╗███████╗ ██╔════╝██║╚══██╔══╝████╗ ██║██╔════╝██╔════╝██╔════╝ █████╗ ██║ ██║ ██╔██╗ ██║█████╗ ███████╗███████╗ ██╔══╝ ██║ ██║ ██║╚██╗██║██╔══╝ ╚════██║╚════██║ ██║ ██║ ██║ ██║ ╚████║███████╗███████║███████║ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝╚══════╝╚══════╝╚══════╝ █████╗ ██████╗ ██╗ ██╗██╗███████╗ ██████╗ ██████╗ ██╔══██╗██╔══██╗██║ ██║██║██╔════╝██╔═══██╗██╔══██╗ ███████║██║ ██║██║ ██║██║███████╗██║ ██║██████╔╝ ██╔══██║██║ ██║╚██╗ ██╔╝██║╚════██║██║ ██║██╔══██╗ ██║ ██║██████╔╝ ╚████╔╝ ██║███████║╚██████╔╝██║ ██║ ╚═╝ ╚═╝╚═════╝ ╚═══╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝ """ print(header) print ("Welcome! We are so excited to have you here. Today, we will discuss your goals and health, and use them to determine a set of physical fitness activities that may be good for you.\n") start_convo(onto) #return the individual, based on user input def returnGoalFromNumber(number): number = int(number) if (number == 1): return "toImproveHeart" elif (number == 2): return "toGetStronger" elif (number == 3): return "toImproveFlexibility" elif (number == 4): return "toBuildEndurance" elif (number == 5): return "toLoseWeight" elif (number == 6): return "toStrengthenMuscles" else: return "" #return a list of health data information, based on user input def returnHealthDataFromNums(nums): health_data = [] for num in nums: num = int(num) if (num == 1): health_data.append("pregnant") elif (num == 2): health_data.append("soreMuscles") elif (num == 3): health_data.append("asthma") elif (num == 4): health_data.append("backPain") elif (num == 5): health_data.append("overFifty") elif (num == 6): health_data.append("injuredLimbs") elif(num == 7): health_data.append('heartDisease') return health_data # def iterateThroughProperties(individual): # for prop in individual.get_properties(): # for value in prop[individual]: # print (".%s == %s" % (prop.python_name, value)) # def printInstancesOfClass(class_name): # print ('Instances of ' + class_name +':') # for i in ontology.class_name.instances(): # print(i) #find the exercises a user should not do, based on their health data def findNonRecommendedExercises(ontology, health_data): nonRecExercises = [] exercisesOfInterest = ontology.search(hasHarmfulHealthData="*") for ex in exercisesOfInterest: if len(set(ex.hasHarmfulHealthData).intersection(set(health_data))) > 0: nonRecExercises.append(ex.name) return nonRecExercises def findRecommendedExercises(ontology, goal, nr_ex): recExercises = [] exercisesOfInterest = ontology.search(hasEffectOfExercise="*") for ex in exercisesOfInterest: sameIndividuals = ex.hasEffectOfExercise[0].equivalent_to if sameIndividuals[0] == goal[0]: if ex.name not in nr_ex: recExercises.append(ex.name) return recExercises def start_convo(ontology): convo_running = True # for thing in ontology.individuals(): # print (thing) while (convo_running): #1. Create a new Person instance name = input("First things, first. What is your name? \n") new_person = ontology.Person(name) print ("\n") #2. Determine the Goal instance that applies to them --> #you can create a new goal. #and then it must be set equivalent to an existing effect of exercise. goal_num = input("Awesome! Hi " + name + """! Which of the following goals do you align with most? 1: Improve Heart 2: Get Stronger 3: Improve Flexibility 4: Build Endurance 5: Lose Weight 6: Strengthen Muscles \n Please type the number corresponding to your selected goal: \n""") print("\n") goal = returnGoalFromNumber(goal_num) #3. Use hasGoal property to link Person to Goal new_person.hasGoal = [ontology.Goal(goal)] # print('HAS GOAL') # print(new_person.hasGoal) #4. Ask for health data. This is important for linking to exercise health data. health_data_nums = input("""Great! Just a few more questions. Do any of the following health conditions apply to you? 1: Pregnant 2: Sore Muscles 3: Asthma 4: Back Pain 5: Over 50 Years Old 6: Injured Limbs 7: Heart Disease \n Please type a list of numbers corresponding to conditions that apply to you, separated by a single space. If none apply, please type 0: \n""") health_data_nums = health_data_nums.split() health_data_list = returnHealthDataFromNums(health_data_nums) i = 0 hasHealthDataArr = [] for i in range(len(health_data_list)): # print (i) health_data = health_data_list[i] hasHealthDataArr.append(ontology.HealthData(health_data)) new_person.hasHealthData = hasHealthDataArr nr_exercises = findNonRecommendedExercises(ontology, hasHealthDataArr) r_exercises = findRecommendedExercises(ontology, new_person.hasGoal, nr_exercises) print ('\n') if (len(r_exercises)>0): print ("Thank you! These are the exercises that we recommend for you:") else: print("Currently, we do not have any recommended exercises for you!") for ex in r_exercises: ex = ''.join(' ' + char if char.isupper() else char.strip() for char in ex).strip() print (ex.lower()) print('\n') if (len(nr_exercises)>0): print ("...and these are the exercises that we don't recommend for you:") for ex in nr_exercises: ex = ''.join(' ' + char if char.isupper() else char.strip() for char in ex).strip() print (ex.lower()) else: print ("Currently, we do not have any non-recommended exercises for you!") print('\n') print('Thanks for using the Fitness Advisor! Good luck with your health journey. \n') convo_running = False setup()
7ffcf00691eee8175109679f13106cc2f9e72497
rafajob/Python-beginner
/ordenada.py
324
3.671875
4
def ordenada(lista): fim = len(lista) for i in range(fim): pos = i if len(lista) != 1: for j in range(i + 1, fim): if lista[j] < lista[pos]: return False else: return True else: return True
5409cb2ddb690e2bdc967850ca25651155358714
rafajob/Python-beginner
/contanumero.py
173
3.875
4
numero = int(input("Digite o valor de n: ")) soma = 0 while (numero != 0) : resto = numero % 10 soma = soma + resto numero = numero // 10 print(soma)
8be521fba75c13d82fe0e3715c432ea3d0402293
rafajob/Python-beginner
/adjacente.py
282
4.09375
4
numero = float(input("Digite um numero: ")) teste = 1 teste2 = 0 while (teste != teste2) and (numero != 0) : teste = numero % 10 numero = numero // 10 teste2 = numero % 10 if teste == teste2: print("Adjacente") else: print("Não Adjacente")
255e13684231f6258958b6da62ff4a8548a13ac0
Olumuyiwa19/aws_restart
/Moisture_Estimator_Script.py
1,665
3.78125
4
#This code estimate the Yes = True while Yes: Grain_Type = str(input("Enter the type of your grain: ")) Wg = float(input("What is the weight of your grain? ")) MC_Wg = int(input("what is the moisture content of your wet grain? ")) MC_Dg = int(input("what is your desired final moisture content for the grain? ")) #Determine the standard measuring system in Bushel Initial_Bu = Wg / 56 print(f"The weight of your grain in Bushel is: {Initial_Bu:1.2f}") MC_Shrinkage_Dict = {16.0:1.190, 15.5:1.183, 15.0:1.176, 14.5:1.170, 14.0:1.163, 13.5:1.156, 13.0:1.149, 12.5:1.143, 12.0:1.136} #Determine mositure points which is same as moisture difference moisture_pt = MC_Wg - MC_Dg #Determine the percentage shrinkage and amount of shrinkage shrinkage_percent = moisture_pt * MC_Shrinkage_Dict[13.0] print(str(shrinkage_percent) + "%") shrinkage_decimal = shrinkage_percent / 100 #Determine the amount of shrinkages in the grain after drying shrinkage_Amt = Initial_Bu * shrinkage_decimal print("The amount of shrinkages in Bushel is: " + str(f"{shrinkage_Amt: 1.2f}")) #Determine the final weight of grain after drying Final_Bu = Initial_Bu - shrinkage_Amt print("The weight of your grain in Bushel after drying to 13% moisture content is: " + str(f"{Final_Bu: 1.2f}")) #Determine the final price of grain at $3.50/Bushel Final_Price = Final_Bu * 3.5 print("The price for your grain is: " + "$" + str(f"{Final_Price:1.2f}")) Yes = input("Do you want to carryout another grain moisture estimate? yes or no: ").lower() if Yes != "yes": print("Goodbye for now") quit
776209f54c8a436bcde8099db7e82855cc7a6adf
sureshpodeti/Algorithms
/dp/slow/no_of_subsets_to_sum.py
972
3.703125
4
''' Given a weight array 'A'. we need to figureout no.of subsets of elements in 'A' will sum up to weight't' psudo code: brute-force algorithm: 1. Let f(A, m, t) (where m =|A|) denote no_of solutions 2. we can pick any element from the A and check if how many solutions it forms, or how many solutions include this element in solution subset eg: A =[3,4,7,2,1], t = 7 possible solutions are: 1. {3,4} 2. {7} 3. {2,1,4} so, we can write: total_no_of solutions = solutions where '4' included + solutions where '4' do not include time complexicity: O(2^n) ''' def no_of_subsets(A, m,t): if t ==0: return 1 if m ==0: return 0 if A[m-1] > t: return no_of_subsets(A, m-1, t) return no_of_subsets(A, m-1, t-A[m-1]) + no_of_subsets(A, m-1, t) A = [3,4,7,2,1] t = 7 print "no_of_subsets:{}".format(no_of_subsets(A, len(A), t))
12f63228c0b4b788891c84edb85d49ef248090c8
sureshpodeti/Algorithms
/dp/efficient/maximum_sum_path_divisibilty_condition.py
708
3.6875
4
''' Maximum path sum for each position with jumps under divisibility condition: Given an array of n positive integers. Initially we are at first position. We can jump position y to position x if y divides x and y < x. The task is to print maximum sum path ending with every position x where 1 <= x <= n. Here position is index plus one assuming indexes begin with 0. dynamic programming solution: time complexicity: O(n^2) space complexicity: O(n) ''' def max_sum_path(A, m): s = [0]*(m+1) s[1] = A[0] for j in range(2, m+1): for i in range(1, j): if j%i == 0: s[j] = max(s[j], s[i]+ A[j-1]) return s[1:] A = [2,3,1,4,6,5] print "max_sum_path:{}".format(max_sum_path(A, len(A)))
0306359920877c74481047b9a0c113f04392e5ce
sureshpodeti/Algorithms
/dp/efficient/min_edits.py
3,043
3.625
4
''' Given string s1, and s2 . we have following operations each of same cost: 1. insert 2. remove 3. replace we can perform above three operations on string s1 to make it string s2. eg: s1 = Geek , s2= Gesek Here, we should insert s into s1 to make it s2. so we need 1 operation. hence, answer: 1. brute force solution: Let us say, f(s1, s2, m,n) denote the min #of operations perform to get s2. where m = |s1| , n = |s2| f(s1, s2, m-1, n-1) if s1[m-1] == s2[n-1] f(s1, s2, m, n) = 1 + min{ f(s1, s2, m, n-1), # insert otherwise f(s1, s2, m-1, n), # remove f(s1, s2, m-1, n-1), # replaced } # if the characters are not same, it means we have found one operation need, and which could have been resulted from either insert, remove , or replacement. base case: if m == 0 then return n if n == 0 then reuturn m time complexicity: O(3^n) Dynamic programing technique: better understanding demonstration: --------- |G|e|e|k| --------- i --------- |G|e|s|k| --------- j we come from the last index, we check if last character in both are same if yes means no edit was made to s1 in making last character. now, the problem looks: ------- |G|e|e| ------- i ------- |G|e|s| ------- j Now, last characters are different, question: what operation could have resulted in different characters?? it means we must have done any of the operation: we could have done : insertion 's' into s1 ----- |G|e| ----- i ------- |G|e|s| ------- j we could have done: replacement ------ |G|e|e ------ i ------- |G|e|s| ------- j we could have done: remove -------- |G|e|s|x -------- i ------- |G|e|s| ------- j any of these operation must have taken place, thats why we are getting different last characters as mentioned. hence, if last characters are differnent f(s1,s2,m,n) = 1 + min{f(s1,s2,m-1,n), f(s1,s2,m,n-1), f(s1,s2,m-1,n-1)} , for insertion, remove,and replacement ''' def min_operations(s1, s2, m,n): s = [[0 for i in range(n+1)] for x in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0: s[i][j] = j elif j == 0: s[i][j] = i elif s1[i-1] == s2[j-1]: s[i][j] = s[i-1][j-1] else: s[i][j] = 1 + min(s[i][j-1], s[i-1][j-1], s[i-1][j]) return s[m][n] s1, s2 = raw_input().split(' ') print "min_operations:{}".format(min_operations(s1,s2, len(s1), len(s2)))
f3953a4b15af2cef12066243c8c760dfe7b5ae61
sureshpodeti/Algorithms
/dp/efficient/longest_increasing_subsequence.py
609
3.953125
4
''' Given an array, we need to return the length of longest increasing subsequence in that. eg: A = [50, 3, 10, 7, 4, 0,80] The idea is, if we know the longest increasing subsequence which at index i. can we found LIS which ends at i+1 ???? Yes, we need to follow the below algorithm to do that. time complexicity : O(n^2 space complexicity: O(n) ''' def lis(A): s = [1]*len(A) for j in range(1, len(A)): for i in range(0, j): if A[i] < A[j] and s[i]>=s[j]: s[j] += 1 return s[len(s) -1] A = raw_input().split(',') A = map(int, A) print "LIS:({}):{}".format(A, lis(A))
2f133b9e5687578ca73e329c24c3197512b7d790
sureshpodeti/Algorithms
/dp/slow/min_steps_to_minimize_num.py
740
4.15625
4
''' Minimum steps to minimize n as per given condition Given a number n, count minimum steps to minimize it to 1 according to the following criteria: If n is divisible by 2 then we may reduce n to n/2. If n is divisible by 3 then you may reduce n to n/3. Decrement n by 1. brute-force solution: time complexicity: O(3^n) ''' def min_steps(n): if n == 0 or n==1: return n if n == 2 or n == 3: return 1 if n%3 ==0 and n%2 ==0: return 1+min(min_steps(n/3), min_steps(n/2), min_steps(n-1)) elif n%3 == 0: return 1 + min(min_steps(n/3), min_steps(n-1)) elif n%2 == 0: return 1+min(min_steps(n/2), min_steps(n-1)) return 1+min_steps(n-1) n = int(raw_input()) print "no.of steps:{}".format(min_steps(n))
b451c8b81268bfa225e669f9532971a2a6ebf3d9
sureshpodeti/Algorithms
/dp/slow/longest_sum_contiguous_subarray.py
719
3.71875
4
''' Longest sum contigous subarray: Given an one-dimensional array. we need to find the logest contigous subarray which gives the maximum sum eg: A = [a,b,c] brute-force algorithm: Generate and test a1= [a] a2= [a, b] a3= [a,b,c] b1 = [b] b2 = [b,c] c1 = [c] so, we need to return the max(a1,a2,a3,b1,b2,c1) time complexicity of the brute-force algorithm is O(n^2) ''' from sys import maxint def longest_sum(A): max_value = - maxint for i in range(0, len(A)): sum = A[i] for j in range(i+1, len(A)): sum += A[j] max_value = max(max_value, sum) return max_value A =raw_input().split(' ') A = map(int, A) print "longes_sum({}):{}".format(A, longest_sum(A))
f7b05c070eb88efe3ea889c2d77647a6e9cf6b4d
sureshpodeti/Algorithms
/dp/slow/min_cost_path.py
1,157
4.125
4
''' Min cost path: Given a matrix where each cell has some interger value which represent the cost incurred if we visit that cell. Task is found min cost path to reach (m,n) position in the matrix from (0,0) position possible moves: one step to its right, one step down, and one step diagonally brute-force : generate and test Let f(i,j) denote the min cost path needed to reach (i,j) position from (0,0) position Suppose, if we have f(i-1,j), f(i-1, j-1), and f(i, j-1) , Is it possible to find f(i,j) from know values ??? answer: yes, we can as shown below f(i,j) = A[i][j]+min{f(i-1, j-1), f(i-1,j), f(i, j-1)} base condition : if i<0 or j<0 then return 0 if i ==j and i==0 then return A[i][j] ''' from sys import maxint def min_cost_path(A, m,n): if m<0 or n<0: return maxint if m==n and m==0: return A[m][n] return A[m][n]+ min(min_cost_path(A, m-1, n), min_cost_path(A, m-1, n-1), min_cost_path(A, m, n-1)) A = [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ] inp = raw_input().split(' ') m,n = map(int, inp) print "min_cost_path({}):{}".format(A, min_cost_path(A, m, n))
70d8adee68755bbc2b792c471c2ce8bd0aa04205
oway13/project-presentation
/WebScraper PYTHON3/hearthpwn_scraper.py
4,806
3.5
4
from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import re import json def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None. """ try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: log('error: Error during requests to {0} : {1}'.format(url, str(e))) return None def is_good_response(resp): """ Returns True if the response seems to be HTML, False otherwise. """ content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1) def log(e): """ Simple logging function. Currently Prints to Console. """ print(e) def top_user_decks(pages): """ Gets the hearthpwn.com urls for pages worth of top-rated user-created decks Returns a list of urls """ top_decks = [] main_url = "https://www.hearthpwn.com/" search_url = "decks?filter-deck-tag=1&filter-show-constructed-only=y&filter-show-standard=1&page=" deck_link_re = re.compile('^\/decks\/[0-9].*') for i in range(pages): raw_html = simple_get(main_url+search_url+str(i)) if raw_html is not None: html = BeautifulSoup(raw_html, 'html.parser') top_decks = get_links(html, deck_link_re, top_decks) else: log("error: top_user_decks simple_get returned None") log("Found {0} user decks over {1} pages".format(len(top_decks), pages)) return top_decks def top_general_decks(pages): """ Gets the hearthpwn.com urls for pages worth of top-rated generalized meta decks Returns a list of urls """ top_decks = [] main_url = "https://www.hearthpwn.com/" page_1_url = "top-decks?page=1&sort=-rating" page_2_url = "top-decks?page=2&sort=-rating" deck_link_re = re.compile('^\/top-decks\/[0-9].*') for i in range (1, pages+1): page_url = "top-decks?page={0}&sort=-rating".format(i) raw_html = simple_get(main_url+page_url) if raw_html is not None: html = BeautifulSoup(raw_html, 'html.parser') top_decks = get_links(html, deck_link_re, top_decks) else: log("error: top_general_decks simple get returned None on page {0}.".format(i)) log("Found {0} general decks over {1} pages".format(len(top_decks), pages)) return top_decks def get_links(html, regex, deck_list): """ Parses html, finding all matches of regex for all anchor elements appends the hearthpwn.com urls it finds to the deck_list, and returns deck_list """ for link in html.find_all('a'): href = str(link.get('href')) if regex.match(href): deck_list.append(href) return deck_list def card_list(search_url): """ Given a hearthpwn.com deck url, gets the url of each card in the deck If two of the same card are in the deck, a duplicate url will be appended to the list Returns the list of these urls. """ card_list = [] card_link_re = re.compile('^\/cards\/[0-9].*') main_url = "https://www.hearthpwn.com" raw_html = simple_get(main_url+search_url) if raw_html is not None: html = BeautifulSoup(raw_html, 'html.parser') for link in html.aside.find_all('a'): href = str(link.get('href')) if card_link_re.match(href): try: count = int(link['data-count']) if count == 2: card_list.append(href) except: log("data-count error. Likely extraneous card. Skipping...") continue card_list.append(href) #log(href) else: log("error: card_list simple_get returned None") log("Found {0} cards in deck.".format(len(card_list))) return card_list def test_full_card_list(): deck_list = top_user_decks(2) deck_list.extend(top_general_decks(2)) full_card_list = [] for url in deck_list: log(url) full_card_list.extend(card_list(url)) #log(full_card_list) with open("cards.json", 'w') as cards: json.dump(full_card_list, cards) #card_list("/decks/1140105-up-mill-warlock-top-100-by-illness") #card_list("/decks/1142643-the-light-wills-it") test_full_card_list() #log(str(card_list("/decks/1267668-tokens-will-get-shreked")))
b1173a7eeb9e3fffefa507594125fea06e7a5a74
zhangli1229/gy-1906A
/demo/day-03/tupel.py
209
3.6875
4
#列表和元组的区别 #1.元组中只有一个数据的时候,后边必须带一个逗号,列表就不需要 a = [1] b = (1,) print(a) print(b) #2.元组中的数据不可修改 # a[0] = 2 # print(a)
25bd2d75157436ba58f2a472ee71080438a28c25
hiyamgh/Forecasting-Demand-Primary-Health-Care
/initial_input/helper_codes/data_subset.py
5,111
3.625
4
from pandas import DataFrame import pandas as pd import numpy as np import os.path import sys sys.path.append('..') from initial_input.helper_codes.data_set import DataSet class DataSubset: def __init__(self, df): self.original_df = df def copy_df(self): return self.original_df.copy(deep=True) def agg_count(self, group_elements): """ This method aggregates a dataframe by the count of all other rows :param group_elements: array of labels to group by :return: """ df = self.copy_df() return DataFrame({'count': df.groupby(group_elements).size()}).reset_index() def agg_mean(self, group_elements): """ This method aggregates a dataframe by the mean of a row :param group_elements: array of labels to group by :return: """ df = self.copy_df() return df.groupby(group_elements).agg('mean') def categorize_demand(self, groupby=['date'], mohafaza='north', service='General Medicine'): """ 1- will aggregate the initial dataframe by the count of the date 2- get the 1s1,2nd,3rd, and 4th quartile put into an array 3- categorize the demand column ('here called: count') according to the count value :return: df with the categorization column added, called: 'demand_class' """ df = self.agg_count(groupby) df = data_set.DataSet.add_external_data(df) if len(mohafaza): df = self.filter(df, 'mohafaza', [mohafaza]) if len(service): df = self.filter(df, 'service_name', [service]) desc = df.describe() min = desc.loc['min', 'count'] fq = desc.loc['25%', 'count'] sq = desc.loc['50%', 'count'] tq = desc.loc['75%', 'count'] max = desc.loc['max', 'count'] nums = [min, fq, sq, tq, max] print(nums) classf = [] for (i, row) in df.iterrows(): dmnd = row['count'] if dmnd <= fq: classf.append(0) elif dmnd >= tq: classf.append(2) else: classf.append(1) df['demand_class'] = classf return df def split_groups(self, df, group): """ This method splits an aggregated dataframe into multiple dataframes :param df: dataframe :param group: array of labels to groupby :return: """ groupped_df = df.groupby(group) return [groupped_df.get_group(group) for group in groupped_df.groups] def partition(self, df, column, num_partions): """ Split a dataframe into partitions based on the number of unique values in a column :param df: dataframe :param column: the column to partition on :param num_partions: the number of partitions to split the dataframe into :return: list of partitions """ column_partition = np.array_split(df[column].unique(), num_partions) return [self.filter(df, column, values) for values in column_partition] @staticmethod def filter(df, column, values): """ Returns a dataframe who's entries in a given column are only in a list of values :param df: dataframe :param column: column to apply filtering to :param values: list of values to include :return: dataframe who's entries in a given column are only in a list of values """ return df[df[column].isin(values)] def generate_subsets(self, subset): """ subsets dataframe :param subset: dict from column to list of values to use, put None instead of a list to use all values """ df = self.copy_df() for column, values in subset.items(): if values is not None: df = self.filter(df, column, values) return self.split_groups(df, list(subset.keys())) def save_subsets(self, subset, dir=""): """ subsets dataframe and writes them to file as csv :param subset: dict from column to list of values to use, put None instead of a list to use all values """ subset_list = self.generate_subsets(subset) for data_subset in subset_list: name = "ministry_of_health_subset_" subset_values = [data_subset[column].iloc[0] for column in subset.keys()] name += '_'.join(subset_values) + ".csv" name = name.replace(" ", "_") data_subset.to_csv(os.path.join(dir, name)) if __name__ == "__main__": data_set_holder = DataSet() # full_df = data_set_holder.copy_df() full_df = pd.read_csv('input/FaourProcessed.csv') full_df = data_set_holder.clean(full_df, sex=True, age=True, nationality=True, average_age=True) data_subsetter = DataSubset(full_df) data_subsetter.save_subsets({"nationality" : ["Lebanon", "Syria"], "mohafaza": ["north", "south", "beirut"], "service_name": ["General Medicine", "Pharmacy", "Pediatrics"]})
48f13070c13aa87c81d705e51481278336cf1c19
hossainlab/statsandpy
/book/_build/jupyter_execute/descriptive/m3-demo-01-ReadingFromAndWritingToFilesUsingPandas.py
2,348
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: get_ipython().system('python --version') # #### Installation of pandas # In[2]: get_ipython().system('pip install pandas') # In[3]: get_ipython().system('pip install numpy') # #### Installation of matplotlib # In[4]: get_ipython().system('pip install matplotlib') # In[5]: get_ipython().system('pip install seaborn') # #### Pandas version # In[6]: import pandas as pd pd.__version__ # #### Matplotlib version # In[7]: import matplotlib matplotlib.__version__ # #### Numpy version # In[8]: import numpy as np np.__version__ # ### Seaborn Version # In[9]: import seaborn seaborn.__version__ # <b>Dataset</b> https://www.kaggle.com/vjchoudhary7/customer-segmentation-tutorial-in-python # * Gender - Gender of the customer # * Age - Age of the customer # * Annual Income (k$) - Annual Income of the customee # * Spending Score (1-100) - Score assigned by the mall based on customer behavior and spending nature # #### Reading data using pandas python # In[10]: ## TODO: While recording please show the file structure first # In[11]: mall_data = pd.read_json('datasets/Mall_Customers.json') mall_data.head(5) # In[12]: average_income = mall_data['annual_income'].mean() average_income # In[13]: mall_data['above_average_income'] = (mall_data['annual_income'] - average_income) > 0 mall_data.sample(5) # * We can save it in any forms like normal text file, csv or json. It will save it in the location where you prefer as well # In[14]: mall_data.to_csv('datasets/mall_data_processed.csv', index=False) # In[15]: get_ipython().system('ls datasets/') # #### Read the csv file for the clarification # In[16]: mall_data_updated = pd.read_csv('datasets/mall_data_processed.csv', index_col=0) mall_data_updated.head(5) # In[17]: ## TODO: While recording please show the files after each save # In[18]: mall_data.to_json('datasets/mall_data_column_oriented.json', orient='columns') # In[19]: mall_data.to_json('datasets/mall_data_records_oriented.json', orient='records') # In[20]: mall_data.to_json('datasets/mall_data_index_oriented.json', orient='index') # In[21]: mall_data.to_json('datasets/mall_data_values_oriented.json', orient='values') # In[22]: get_ipython().system('ls datasets/') # In[ ]:
72b8750a3c41dca8a93cea4edc0cb704fb79b175
ertugrul-dmr/automate-the-boring-stuff-projects
/comma-code/comma-alt.py
366
3.71875
4
# Another variation to automate the Boring Stuff With Python Ch. 4 Project spam = ['apples', 'bananas', 'tofu', 'cats', 'coconuts'] def comma(items): # Combines list into a string of the form item1, item2, item 3 and item 4 if len(items) == 1: print(items[0]) print('{} and {}'.format(', '.join(items[:-1]), items[-1])) comma(spam)
8f83e4e958303fca9387b8697e8a9f83c38356e3
ertugrul-dmr/automate-the-boring-stuff-projects
/spreadsheet-cell-inverter/inverter.py
538
3.90625
4
# A program to invert the row and column of the cells in the spreadsheet. import openpyxl inputwb = openpyxl.load_workbook('produceSales.xlsx', data_only=True) inputSheet = inputwb.active maxRow = inputSheet.max_row maxColumn = inputSheet.max_column outputwb = openpyxl.Workbook() outputSheet = outputwb.active for r in range(1, maxRow + 1): for c in range(1, maxColumn + 1): outputSheet.cell(row=c, column=r).value = inputSheet.cell( row=r, column=c).value outputwb.save('inverted.xlsx')
c6e2d36b530c166448f12701ef4017d89b1667b4
ertugrul-dmr/automate-the-boring-stuff-projects
/rockpaperscissors/rockpaperscissors.py
2,665
4
4
# This is a game tries to simulate rock, paper, scissors game. import random import sys def maingame(): # Start's the game if player chooses to play. wins = 0 losses = 0 draws = 0 while True: # Main loop print(f'Wins: {wins}, Losses: {losses}, Draws: {draws}') if wins == 5: print(f'You beat the ai!') break if losses == 5: print(f'Ai has beaten you!') break if draws == 5: print(f'It\'s a draw between you and ai!') break playerMove = str( input('Plese make your move. r(ock),p(aper),s(scissors): ')) aiMove = random.randint(1, 3) # 1 rock, 2 paper, 3 scissor if playerMove == 'r': if aiMove == 1: print('Ai move is: Rock.' + f' Your move was: {playerMove}.') print('Draw') draws += 1 elif aiMove == 2: print('Ai move is: Paper.' + f' Your move was: {playerMove}.') print('Lose') losses += 1 else: print('Ai move is: Scissor.' + f' Your move was: {playerMove}.') print('Win') wins += 1 if playerMove == 'p': if aiMove == 2: print('Ai move is: Paper.' + f' Your move was: {playerMove}.') print('Draw') draws += 1 elif aiMove == 3: print('Ai move is: Scissor.' + f' Your move was: {playerMove}.') print('Lose') losses += 1 else: print('Ai move is: Rock.' + f' Your move was: {playerMove}.') print('Win') wins += 1 if playerMove == 's': if aiMove == 3: print('Ai move is: Scissor.' + f' Your move was: {playerMove}.') print('Draw') draws += 1 elif aiMove == 1: print('Ai move is: Rock.' + f' Your move was: {playerMove}.') print('Lose') losses += 1 else: print('Ai move is: Paper.' + f' Your move was: {playerMove}.') print('Win') wins += 1 k = input(f'Enter R to restart and press Q to quit\nR/Q? ') k.lower() if k == 'r': maingame() else: sys.exit k = input(f'Enter S to restart and press Q to quit\nS/Q? ') k.lower() if k == 's': maingame() else: sys.exit
ffd91a476007794992ffedccc592bbc3685c864a
themaddoctor/BritishNationalCipherChallenge
/2020 special edition/forum/gantun/encrypt.py
987
3.609375
4
#!/usr/bin/env python # based on Gantun from https://susec.tf/tasks/gantun_229621efd1dcc01ef8851254affd1326887ec58e.txz #from random import randint randint = [] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def encrypt(p): global randint numbers = [] for char in p.upper(): numbers.append(alphabet.index(char)+26) while len(numbers) > 1: n = randint[0]; randint = randint[1:] # randint(0,len(numbers)-2) x = numbers[n] y = numbers[n+1] if x > y: z = x*x + x + y else: z = y*y + x numbers = numbers[:n] + [z] + numbers[n+2:] return numbers[0] p = open("plaintext.txt","r").read().upper().replace(" ","").replace("\n","").replace("\r","") # the random choices made in encryption have been stored in random.txt, so that you can reproduce the ciphertext random = open("random.txt","r").read().replace("\n","").replace("\r","").split(",") randint = [int(x) for x in random] print encrypt(p)
c6c138a068df67112091256c4491e3ea2b539a39
blairg23/files-in-folder
/files_in_folder.py
15,406
3.78125
4
#-*- coding: utf-8 -*- ''' Description: Checks existence of files from one given folder in the other given folder. - If the left folder is larger than the right folder, it will return the filenames and hashes of the remaining files. - If the right folder is larger than the left folder, it will return a True if all files from the left folder exist in the right folder and a False with the filenames and hashes of the non-existence files. ''' import os # Operating System functions import sys # System Functions import shutil # File copy operations import hashlib # Hashing functions import json # JSON stuff from time import localtime as clock # Time a function # Filenames we don't want to check: PROTECTED_FILENAMES = ['contents.csv', 'missing.txt'] class FilesInFolder: def __init__( self, left_folder=None, right_folder=None, write_mode=None, hash_algorithm='md5', hash_type='contents', contents_filename='contents.json', missing_files_filename='missing.txt', fix_missing_files=False, verbose=False ): self.verbose = verbose self.action_counter = 0 self.write_mode = write_mode self.hash_algorithm = hash_algorithm self.hash_type = hash_type self.left_folder = left_folder self.right_folder = right_folder self.contents_filename = contents_filename self.missing_files_filename = missing_files_filename self.fix_missing_files = fix_missing_files try: # If valid directories have not been provided: if self.left_folder == None or self.right_folder == None or not os.path.exists(self.left_folder) or not os.path.exists(self.right_folder): raise IOError('[ERROR] Please provide valid right and left directories.') else: print('[{action_counter}] Left Directory: {left_folder}'.format(action_counter=self.action_counter, left_folder=self.left_folder)) print('[{action_counter}] Right Directory: {right_folder}'.format(action_counter=self.action_counter, right_folder=self.right_folder)) print('\n') except Exception as e: print(e) def find_filenames(self, directory=None): ''' Finds all the filenames in a given directory. ''' filenames = [] try: if directory == None or not os.path.exists(directory): raise IOError('[ERROR] Please provide a valid directory to search.') else: if self.verbose: print('[{action_counter}] Finding files in {directory}.\n'.format(action_counter=self.action_counter, directory=directory)) filenames = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory,f))] self.action_counter += 1 except Exception as e: print(e) return filenames def hash_file_contents(self, filepath=None, hash_algorithm='md5'): ''' Uses given hashing algorithm to hash the binary file, given a full filepath. ''' BLOCKSIZE = 65536 # In case any file is bigger than 65536 bytes hash_value = 0x666 try: if self.verbose: print('[{action_counter}] Hashing file contents of {filepath}.\n'.format(action_counter=self.action_counter, filepath=filepath)) if filepath == None or not os.path.exists(filepath): raise IOError('[ERROR] Please provide a valid filepath to hash.') with open(filepath, 'rb+') as inFile: h = hashlib.new(hash_algorithm) buf = inFile.read(BLOCKSIZE) while len(buf) > 0: h.update(buf) buf = inFile.read(BLOCKSIZE) hash_value = h.hexdigest() except Exception as e: print(e) return hash_value def hash_filename(self, filename=None, hash_algorithm='md5'): ''' Uses given hashing algorithm to hash the given filename. ''' hash_value = 0x666 try: if self.verbose: print('[{action_counter}] Hashing filename {filename}.\n'.format(action_counter=self.action_counter, filename=filename)) if filename == None: raise IOError('[ERROR] Please provide a filename to hash.') else: h = hashlib.new(hash_algorithm) h.update(filename) hash_value = h.hexdigest() except Exception as e: print(e) return hash_value def get_hashes(self, directory=None, hash_algorithm='md5', hash_type='contents'): ''' Populate a dictionary with filename:hash_value pairs, given a directory and list of filenames. ''' hashlist = {} hashlist['headers'] = ['hash_value', 'filepath'] try: if directory == None or not os.path.exists(directory): raise IOError('[ERROR] Please provide a valid directory to hash.') else: filenames = self.find_filenames(directory=directory) for filename in filenames: if filename not in PROTECTED_FILENAMES: filepath = os.path.join(directory, filename) if hash_type == 'contents': hash_value = self.hash_file_contents(filepath=filepath, hash_algorithm=hash_algorithm) elif hash_type == 'filenames': hash_value = self.hash_filename(filename=filename, hash_algorithm=hash_algorithm) hashlist[str(hash_value)] = str(filepath) self.action_counter += 1 except Exception as e: print(e) return hashlist def write_dictionary_contents(self, dictionary_contents={}, write_mode=None, contents_filepath=None): ''' Writes contents of a given dictionary, using the specified write mode (JSON or CSV). ''' valid_write_modes = ['json', 'csv'] try: if dictionary_contents == {}: raise Exception('[ERROR] Need to provide a valid dictionary with contents.') elif write_mode == None or not write_mode.lower() in valid_write_modes: raise Exception('[ERROR] Need to provide a write mode from: {valid_write_modes}'.format(valid_write_modes=valid_write_modes)) elif contents_filepath == None: raise Exception('[ERROR] Need to provide a valid file to write contents.') else: with open(contents_filepath, 'a+') as outfile: if write_mode.lower() == 'json': json.dump(dictionary_contents, outfile) elif write_mode.lower() == 'csv': headers = ','.join(dictionary_contents['headers']) outfile.write(headers + '\n') for key,value in dictionary_contents.items(): if key != 'headers': output_line = key + ',' + value + '\n' outfile.write(output_line) else: raise Exception('[ERROR] Need to provide a write mode from: {valid_write_modes}'.format(valid_write_modes=valid_write_modes)) except Exception as e: print(e) def compare_hash_lists(self, left_hash_dict=None, right_hash_dict=None): ''' Given two hash lists, will compare them to ensure all hashes from left list exist in right list, then will return the list of all hashes that are missing. ''' missing_hash_value_filepaths = [] for hash_value, filepath in left_hash_dict.items(): if not hash_value in right_hash_dict.keys(): missing_hash_value_filepaths.append(filepath) return missing_hash_value_filepaths def write_list_contents(self, list_contents=[], missing_files_filepath=None): ''' Writes contents of a given list to a file. ''' try: if list_contents == []: raise Exception('[ERROR] Need to provide a valid list with contents.') else: with open(missing_files_filepath, 'a+') as outfile: for value in list_contents: outfile.write(value + '\n') except Exception as e: print(e) def write_missing_files(self, missing_filepaths=[], destination_directory=None): ''' Writes missing files to the destination filepath. ''' try: if missing_filepaths == []: raise Exception('[ERROR] Need to provide a valid list of missing files.') else: for missing_filepath in missing_filepaths: missing_filename = os.path.basename(missing_filepath) # Use copy2 to retain metadata such as creation and modification times of the file destination_filepath = os.path.join(destination_directory, missing_filename) shutil.copy2(missing_filepath, destination_filepath) except Exception as e: print(e) def cleanup(self): ''' Cleans up metadata files like contents.csv and missing.txt ''' self.action_counter += 1 for filename in PROTECTED_FILENAMES: left_file_to_delete = os.path.join(self.left_folder, filename) right_file_to_delete = os.path.join(self.right_folder, filename) if os.path.exists(left_file_to_delete): if self.verbose: print(f'[{self.action_counter}] Deleting {left_file_to_delete}.\n') os.remove(left_file_to_delete) self.action_counter += 1 if os.path.exists(right_file_to_delete): if self.verbose: print(f'[{self.action_counter}] Deleting {right_file_to_delete}.\n') os.remove(right_file_to_delete) self.action_counter += 1 def run(self): ''' Runs all the required functions to check whether two folders have identical content. ''' left_hash_dict = self.get_hashes(directory=self.left_folder, hash_algorithm=self.hash_algorithm, hash_type=self.hash_type) right_hash_dict = self.get_hashes(directory=self.right_folder, hash_algorithm=self.hash_algorithm, hash_type=self.hash_type) missing_hash_value_filepaths = self.compare_hash_lists(left_hash_dict=left_hash_dict, right_hash_dict=right_hash_dict) if self.write_mode != None: # Missing files: if len(missing_hash_value_filepaths) == 0: print('All files from left folder exist in right folder.') print('Left Folder:' ,self.left_folder) print('Right Folder:', self.right_folder) print('\n') # Left side: left_outfilepath = os.path.join(self.left_folder, self.contents_filename) self.write_dictionary_contents(dictionary_contents=left_hash_dict, write_mode=self.write_mode, contents_filepath=left_outfilepath) if self.verbose: print('[{action_counter}] Writing contents to {contents_filepath}.\n'.format(action_counter=self.action_counter, contents_filepath=left_outfilepath)) self.action_counter += 1 # Right side: right_outfilepath = os.path.join(self.right_folder, self.contents_filename) self.write_dictionary_contents(dictionary_contents=right_hash_dict, write_mode=self.write_mode, contents_filepath=right_outfilepath) if self.verbose: print('[{action_counter}] Writing contents to {contents_filepath}.\n'.format(action_counter=self.action_counter, contents_filepath=right_outfilepath)) self.action_counter += 1 else: missing_files_filepath = os.path.join(self.left_folder, missing_files_filename) if self.verbose: print('[{action_counter}] Writing missing file info to {missing_files_filepath}.\n'.format(action_counter=self.action_counter, missing_files_filepath=missing_files_filepath)) self.write_list_contents(list_contents=missing_hash_value_filepaths, missing_files_filepath=missing_files_filepath) self.action_counter += 1 if self.fix_missing_files: if self.verbose: print(f'[{self.action_counter}] Writing missing files to {self.right_folder}.\n') self.write_missing_files(missing_filepaths=missing_hash_value_filepaths, destination_directory=self.right_folder) self.action_counter += 1 if self.verbose: print(f'[{self.action_counter}] Cleaning up metadata files.\n') self.cleanup() if self.verbose: print(f'[{self.action_counter}] Rerunning file checker.\n') self.action_counter += 1 self.run() else: print('Files missing from left folder that exist in right folder:') print(missing_hash_value_filepaths) if __name__ == '__main__': # Until I use arg parse: left_folder = '' right_folder = '' hash_algorithm = 'md5' hash_type = 'contents' # Other option is "filenames" write_mode = 'csv' contents_filename = 'contents.csv' missing_files_filename = 'missing.txt' fix_missing_files = True file_checker = FilesInFolder( left_folder=left_folder, right_folder=right_folder, write_mode=write_mode, hash_algorithm=hash_algorithm, hash_type=hash_type, contents_filename=contents_filename, missing_files_filename=missing_files_filename, fix_missing_files=fix_missing_files, verbose=True ) # Some calls you can use to test (until I write good unit tests): # filenames = file_checker.find_filenames(directory=left_folder) #hashlist = file_checker.get_hashes(directory=left_folder, hash_algorithm=hash_algorithm, hash_type=hash_type) #contents_filepath = os.path.join(left_folder, contents_filename) #file_checker.write_dictionary_contents(dictionary_contents=hashlist, write_mode=write_mode, contents_filepath=contents_filepath) file_checker.run()
99226eef5a94c5a5394dc4d6cb645b7334d271a0
cs-summercrew/Summer19-SeedSystems
/OpenCV-Examples/Image Detection/cam.py
4,474
3.546875
4
# Authors: CS-World Domination Summer19 - CB ''' Simply display the contents of the webcam with optional mirroring using OpenCV via the new Pythonic cv2 interface. Press <esc> to quit. NOTE: Key bindings: g: BGR->RGB f: vertical flip d: horizontal flip esc: quit ''' import cv2 import numpy as np cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) def demo1(): """ just run it to see the video from the built-in webcam if CAPTURE_NUM = 0 doesn't work, try -1, 1, 2, 3 (if none of those work, the webcam's not supported!) """ CAPTURE_NUM = 0 cam = cv2.VideoCapture(CAPTURE_NUM) mirror=False VERTICAL_FLIP=False BGR=False while True: ret_val, orig = cam.read() #shrink image to half size (.5) #"None" argument refers to the size in pixels, which we don't care about since we're scaling img=cv2.resize(orig, None, fx=.5, fy=.5) #NOTE: if the image is original size, it will be very slow and laggy, and will miss some keypresses. #adjust size as desired if your machine is powerful enough """ key-press handling """ k = cv2.waitKey(20) & 0xFF k_char = chr(k) if k_char == 'g': BGR = not BGR # fun! if k_char == 'f': VERTICAL_FLIP = not VERTICAL_FLIP # fun! if k_char == 'd': mirror = not mirror # fun! if mirror: img = cv2.flip(img, 1) if VERTICAL_FLIP: img = cv2.flip(img, 0) if BGR: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) if k == 27: break # esc to quit #facial recognition handling faces = faceCascade.detectMultiScale( img, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE ) #print("Found {0} faces!".format(len(faces))) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow('my webcam', img) cv2.destroyAllWindows() def demo3(): """ to demo: click to bring focus to the messi image move mouse around and hit 'r' (lowercase r) a cyan rectangle should appear at your mouse hit spacebar to clear drawing reference: http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html """ # Create a black image, a window and bind the function to window # this is from here: FILE_NAME = "messi5.jpg" image_orig = cv2.imread(FILE_NAME, cv2.IMREAD_COLOR) #image_orig = cv2.cvtColor(image_orig, cv2.COLOR_BGR2RGB) image = image_orig.copy() current_mouse_pos = [0,0] # not true yet... def mouse_handler(event,x,y,flags,param): """ a function that gets called on mouse events reference: """ current_mouse_pos[0] = x current_mouse_pos[1] = y #print("The mouse is currently at", current_mouse_pos) if event == cv2.EVENT_LBUTTONDOWN: print("Left button clicked!") if event == cv2.EVENT_RBUTTONDOWN: print("Right button clicked!") cv2.namedWindow('image') cv2.setMouseCallback('image',mouse_handler) while True: cv2.imshow('image',image) """ key-press handling """ k = cv2.waitKey(20) & 0xFF k_char = chr(k) if k_char == 'm': print('mmmm!') # fun! if k_char == 'r': x, y = current_mouse_pos # adjusted by the mouse_handler! DELTA = 42 UL = (x-DELTA,y-DELTA) # Upper Left LR = (x+DELTA,y+DELTA) # Lower Right CLR = (255,255,0) # color WIDTH = 1 # rectangle width cv2.rectangle( image, UL, LR, CLR, WIDTH ) # draw a rectangle if k_char == ' ': image = image_orig.copy() # clear by re-copying! if k == 27: # escape key has value 27 (no string represetation...) print("Quitting!") break """ end of key-press handling """ # outside of the while True loop... cv2.destroyAllWindows() def main(): #demo3() #demo2() demo1() if __name__ == '__main__': main()
cb2cab044509d2dc344c4a3faa162ef432233bdc
brendon977/programas_Python
/imc_comstatus.py
1,335
4
4
#Desenvolva uma lógica que leia o peso e altura # de uma pessoa, calcule seu IMC e mostre seu status #de acordo com a tabela abaixo: #-Abaixo de 18.5: Abaixo do peso # Entre 18.5 e 25: Peso ideal #25 ate 30: Sobrepeso #30 ate 40: Obesidade mórbida #Validação de dados inclusa valid_peso= False while valid_peso == False: peso= input("Digite seu peso: ") try: peso = float(peso) if peso <0: print('Insira apenas numeros maiores que 0') else: valid_peso = True except: print('Insira apenas números!') valid_peso = False valid_altura = False while valid_altura == False: altura = input("Digite sua altura: ") try: altura = float(altura) if altura == str: print("Insira apenas números e separando apenas usando ponto(.)") else: valid_altura= True except: print("Insira apenas números e separando apenas usando ponto'(.)'") valid_altura= False iMC= peso/(altura*altura) if iMC<18.5: print("Seu imc {:.2f}. Abaixo do peso!".format(iMC)) elif iMC>=18.5 and iMC<=25: print("Seu imc {:.2f}. Peso ideal!".format(iMC)) elif iMC>25 and iMC<=30: print("Seu imc {:.2f}. Sobrepeso!".format(iMC)) elif iMC>30 and iMC<=40: print("Seu imc {:.2f}. Obesidade mórbida!".format(iMC))
037f40f144c471fe6ac96b6ac387d2ff2d6eb242
brendon977/programas_Python
/jogo_jokenpo.py
1,599
3.921875
4
#Crie um programa que faça o computador #jogar jokenpo com voce. from random import randint from time import sleep # para colocar timer no programa valid_jogador = False itens = ('Pedra', 'Papel','Tesoura') computador = randint(0,2) print('''Suas opções: [0] PEDRA [1] PAPEL [2] TESOURA''') while valid_jogador == False: jogador= input('Qual sua jogada? ') try: jogador = int(jogador) if jogador <0 or jogador >2: print("Escolha entre as opções de 0 a 2") else: valid_jogador = True except: print('Insira apenas números') valid_jogador = False print('JO') sleep(1) # sleep de 1 segundo print('KEN') sleep(1) print('PO') sleep(1) print("-="*11) print('O computador escolheu{}'.format(itens[computador])) #com itens[computador] ele passa a escrever o nome dos itens que cair em vez dos numeros. print('O jogador jogou{}'.format(itens[jogador])) print("-="*11) if computador == 0: if jogador ==0: print("Empate") elif jogador ==1: print("Jogador venceu") elif jogador ==2: print("Computador venceu") else: print("Jogada inválida") elif computador ==1: if jogador ==0: print("Computador venceu") elif jogador ==1: print("Empate") elif jogador ==2: print("Jogador venceu") else: print("Jogada inválida") elif computador ==2: if jogador ==0: print("Jogador venceu") elif jogador ==1: print("Computador venceu") elif jogador ==2: print("Empate") else: print("Jogada inválida")
c41b853bc0869c6cbda8438edbbed46954673d47
Ping-ChenTsai417/Astroid-impact-armageddon-itokawa-acse4
/armageddon/Optimisation.py
4,854
3.671875
4
import scipy.interpolate as intpl import pandas as pd import matplotlib.pyplot as plt import numpy as np ''' Optimization problem ''' def meteor_data(file): """ The given results of the meteor event. Parameter ----------- file: file path """ data_csv = pd.read_csv(file) df=pd.DataFrame(data=data_csv) altitude_ = np.array(df.iloc[1:,0]) energy = np.array(df.iloc[1:,1]) #* 4.184 * 1e12 # convert to joules return altitude_, energy def RMSE(energy_guess, energy_target): """ Calculate the root mean square error of the optimized energy and target energy Parameter ------------ energy_guess: array energy_arget: array """ return np.sqrt(np.mean((energy_guess-energy_target)**2)) # loop through each possible r and Y def get_opt_radius_Y(earth, rad, Y, height_ori, energy_ori, target_func): '''Optimize r and Y by looping guessed parameters within possible range. Possible range can be tuned manually. Parameters ---------- earth: object of class Planet in solver.py rad: array Guessed radian Y: array Guessed strength height_ori: array Given heights of the event energy_ori: array Given energy of the event target_func: function Interpolated function of the event data Returns ------- outcome : 'radius_opt', 'strength_opt','rmse','height_guess_s' and 'energy_guess_s' are the optimized radius, optimized strength, rmse between optimised energy and target energy, array of optimized height, array of optimized strength. ''' rmse_all = [] tol = 5 for r in rad: for s in Y: result = earth.solve_atmospheric_entry(radius = r, angle=18.3, strength = s, velocity=1.92e4, density=3300) outcome = earth.calculate_energy(result) energy_guess = outcome.dedz height_guess = outcome.altitude/1000 # Slice optimized function to the same range as target one lower_bound = np.where(height_guess <= height_ori[0])[0][0] upper_bound = np.where(height_guess >= height_ori[-1])[0][-1] height_guess_s = height_guess[lower_bound:upper_bound] energy_guess_s = energy_guess[lower_bound:upper_bound] # Calculate optimal energy energy_ori_s = target_func(height_guess_s) # Output energy rmse difference, put error into an array rmse = RMSE(energy_guess_s, energy_ori_s) rmse_all.append(rmse) if rmse < np.amin(rmse_all[:]) or np.allclose(rmse, np.amin(rmse_all[:])): radius_opt = r strength_opt = s elif rmse<tol: radius_opt = r strength_opt = s break return radius_opt, strength_opt,rmse, height_guess_s, energy_guess_s def plot_Optimisation_radius_strength(filepath_, earth): ''' Plot the optimized function vs. the target function of the event Parameter ------------ filepath_: file path earth: object of the class Planet() in solver ''' height_ori, energy_ori = meteor_data(filepath_) # insert filename target_func = intpl.interp1d(height_ori, energy_ori) fig = plt.figure(figsize=(18, 6)) ax = fig.add_subplot(121) # Interpolate function target_func = intpl.interp1d(height_ori, energy_ori) # Plot target function ax.plot(height_ori, target_func(height_ori),'r',label = 'Target func') #Guess energy and height result = earth.solve_atmospheric_entry(radius=8.21, angle=18.3, strength=5e6, velocity=1.92e4, density=3300) outcome = earth.calculate_energy(result) energy_guess = outcome.dedz height_guess = outcome.altitude/1000 # Plot guess function ax.plot(height_guess, energy_guess,label = 'Guess func') ax.legend() ax.grid(True) ax.set_ylabel('Energy Loss per Unit Height (kt TNT)') ax.set_xlabel('Altitude (km)') # Change guessed range for radius and strength radius_ = np.linspace(8.1, 8.3, 3) strength_ = np.linspace(4.9e6,5.3e6, 3) radius_opt, strength_opt, rmse_opt, height_guess_s, energy_guess_s = get_opt_radius_Y(earth, radius_, strength_ ,height_ori, energy_ori, target_func) ax1 = plt.subplot(122) ax1.plot(height_guess_s, energy_guess_s, label = 'Guess func') ax1.plot(height_ori, target_func(height_ori),'r', label = 'Target func') ax1.grid(True) ax1.legend() ax1.set_ylabel('Energy Loss per Unit Height (kt TNT)') ax1.set_xlabel('Altitude (km)') print('radius_opt:') print(radius_opt) print('strength_opt: ') print(strength_opt) return
7afbbb718239098a4f64aacab5efd56b45c27370
u-ever/JavaScript_Guanabara
/aula14ex/ex017/testetabuada.py
109
3.703125
4
mult = int(input('Digite um número: ')) for c in range (1,11): print(f'{mult} x {c} = {mult * c}') c += 1
e8019a0d7da90f1633bd139a32ca191887b08c10
naroladhar/MCA_101_Python
/mulTable.py
1,074
4.125
4
import pdb pdb.set_trace() def mulTable(num,uIndexLimit): ''' Objective : To create a multiplication table of numbers Input Variables : num : A number uIndexLimit: The size of the multiplication table Output Variables: res : The result of the product return value:none ''' for i in range(0,uIndexLimit+1): res=num*i print("%d X %d = %d" %(num,i,res)) def main(): ''' Objective : To create a multiplication table of numbers Input Variables : num : A number uIndexLimit: The size of the multiplication table Output Variables: res : The result of the product return value:none ''' start=int(input(" Enter a start: ")) finish = int(input(" Enter a finish: ")) uIndexLimit = int(input(" Enter size of the table: ")) for start in range(start,finish+1): print("*******Time Table for ",start,"*********") mulTable(start,uIndexLimit) if __name__=='__main__': main()
56a61400c185d2b677c984d5d480e7bdddc17ec0
ottotexschang96/Login-with-Password-Setting
/20210326Chapter3LoginwithPasswordSetting.py
391
3.953125
4
# Login with Password Setting i = 0 while i < 3: password = input('Please input password:') if password == 'a123456': print('Successful login') break elif password != 'a123456': print('Wrong password') if 2-i > 0: print('and you still have remaining chance(s):', 2-i) else: print('Your account has been locked, and please contact the customer service.') i = i + 1
92aca135af4da75cb0cd32b9bfac71515384e04d
hakanguner67/class2-functions-week04
/exact_divisor.py
376
4.125
4
''' Write a function that finds the exact divisors of a given number. For example: function call : exact_divisor(12) output : 1,2,3,4,6,12 ''' #users number number = int(input("Enter a number : ")) def exact_divisor(number) : i = 1 while i <= number : # while True if ((number % i )==0) : print (i) i = i + 1 exact_divisor(number)
89aa00e1cd5480b1e976fe94a3bbd044f8f671de
hakanguner67/class2-functions-week04
/counter.py
590
4.21875
4
''' Write a function that takes an input from user and than gives the number of upper case letters and smaller case letters of it. For example : function call: counter("asdASD") output: smaller letter : 3 upper letter : 3 ''' def string_test(s): upper_list=[] smaller_list=[] for i in s: if i.isupper(): upper_list.append(i) elif i.islower(): smaller_list.append(i) else : pass print("Smaller Letter : ",len(smaller_list)) print("Upper Letter :",len(upper_list)) s = input("Enter a word : ") string_test(s)
6e94f15c2c7d358cccbbc52a8cb6e10fa2fb4b23
dpew/advent2017
/2017/day13/day13p2-brute.py
2,592
3.546875
4
#!/usr/bin/env python import sys import pprint import re class Layer(object): def __init__(self, name, depth): self.name = name self.depth = int(depth) self.position = 0 self.direction = 1 def iterate(self): ''' >>> l = Layer(0, 3) >>> l.iterate().position 1 >>> l.iterate().position 2 >>> l.iterate().position 1 >>> l.iterate().position 0 >>> l.iterate().position 1 ''' self.position += self.direction if (self.position >= self.depth): self.direction = -self.direction self.position += (2 * self.direction) elif (self.position < 0): self.direction = -self.direction self.position += (2 * self.direction) return self def hit(self, depth): #print self.name, self.position == depth return self.position == depth def reset(self): self.position = 0 self.direction = 1 class EmptyLayer(object): def __init__(self, name): self.name = name def hit(self, depth): # print self.name, False return False def iterate(self): pass def reset(self): pass class Firewall(object): def __init__(self): self.layers = [] def add_layer(self, num, depth): l = Layer(num, depth) while len(self.layers) <= num: self.layers.append(EmptyLayer(len(self.layers))) self.layers[num] = l def iterate(self): for l in self.layers: l.iterate() def reset(self): for l in self.layers: l.reset() def hit(self, layer, depth): return self.layers[layer].hit(depth) def severity(self, layer, depth): return (layer * self.layers[layer].depth) if self.hit(layer, depth) else 0 def __len__(self): return len(self.layers) import doctest doctest.testmod() firewall = Firewall() with open(sys.argv[1]) as f: for l in f.readlines(): x = re.split("[: ]*", l.strip()) firewall.add_layer(int(x[0]), int(x[1])) severity=0 depth=0 delay=0 bad=False while True: firewall.reset() print "delaying", delay for x in xrange(delay): firewall.iterate() for layer in xrange(len(firewall)): if firewall.hit(layer, depth): bad = True break firewall.iterate() if not bad: print delay sys.exit(0) bad = False delay += 1
2447be15084e1fd907a18e81c26ed3a864dcb4d3
dpew/advent2017
/2017/day14/day14.py
4,675
3.5625
4
#!/usr/bin/env python import sys def rotate(lst, count): ''' >>> rotate([0, 1, 2, 3, 4], 3) [3, 4, 0, 1, 2] >>> rotate([0, 1, 2, 3, 4], 0) [0, 1, 2, 3, 4] >>> rotate([0, 1, 2, 3, 4], -3) [2, 3, 4, 0, 1] >>> rotate([0, 1, 2, 3, 4], 5) [0, 1, 2, 3, 4] >>> rotate([0, 1, 2, 3, 4], -5) [0, 1, 2, 3, 4] >>> rotate([0, 1, 2, 3, 4], 7) [2, 3, 4, 0, 1] >>> rotate([0, 1, 2, 3, 4], -7) [3, 4, 0, 1, 2] >>> rotate([0, 1, 2, 3, 4], -12) [3, 4, 0, 1, 2] ''' count = ((count % len(lst)) + len(lst)) % len(lst) return lst[count:] + lst[:count] def densify(iterable, density=16): ''' >>> list(densify(xrange(6), density=3)) [3, 2] >>> list(densify(xrange(7), density=3)) [3, 2, 6] >>> list(densify([65, 27, 9, 1, 4, 3, 40, 50, 91, 7, 6, 0, 2, 5, 68, 22])) [64] ''' val = 0 i = 0 for x in iterable: i += 1 val = val ^ x if not i % density: yield val val = 0 if i % density: yield val def hexify(iterable): ''' >>> hexify([64, 7, 255]) '4007ff' >>> hexify([0, 15, 16, 255]) '000f10ff' ''' return "".join(('0' + hex(x)[2:])[-2:] for x in iterable) def countbits(val): ''' >>> countbits(0) 0 >>> countbits(1) 1 >>> countbits(2) 1 >>> countbits(15) 4 ''' count=0 while val: count += val & 1 val = val >> 1 return count class CircularList(object): def __init__(self, iterable): self.position = 0 self.items = [ x for x in iterable] def reverse(self, count): ''' >>> CircularList(range(10)).reverse(5) [[4], 3, 2, 1, 0, 5, 6, 7, 8, 9] >>> CircularList(range(10)).reverse(1) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).reverse(0) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).reverse(10) [[9], 8, 7, 6, 5, 4, 3, 2, 1, 0] ''' if count == 0: return self assert count >= 0 assert count <= len(self.items) tmplist = rotate(self.items, self.position) reversed = tmplist[count-1::-1] + tmplist[count:] self.items = rotate(reversed, -self.position) return self def skip(self, count): ''' >>> CircularList(range(10)).skip(2) [0, 1, [2], 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).skip(12) [0, 1, [2], 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).skip(0) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> CircularList(range(10)).skip(10) [[0], 1, 2, 3, 4, 5, 6, 7, 8, 9] ''' self.position = (self.position + count) % len(self.items) return self def hashoper(self, iterable, skip=0): ''' Runs a single knothash function returns self, skip >>> CircularList(range(5)).hashoper([3, 4, 1, 5])[0] [3, 4, 2, 1, [0]] >>> l = CircularList(range(5)).hashoper([3, 4, 1, 5])[0] >>> l[0] * l[1] 12 ''' for i in iterable: self.reverse(i) self.skip(skip + i) skip += 1 return self, skip def __iter__(self): return iter(self.items) def __getitem__(self, x): return self.items[x] def __repr__(self): return repr([x[1] if x[0] != self.position else [x[1]] for x in enumerate(self.items)]) def knothash(iterable, repeat=64): ''' >>> knothash('') 'a2582a3a0e66e6e86e3812dcb672a272' >>> knothash('AoC 2017') '33efeb34ea91902bb2f59c9920caa6cd' >>> knothash('1,2,3') '3efbe78a8d82f29979031a4aa0b16a9d' >>> knothash('1,2,4') '63960835bcdc130f0b66d7ff4f6a5a8e' ''' return hexify(knothashraw(iterable, repeat=repeat)) def knothashraw(iterable, repeat=64): counts = [ ord(x) for x in iterable ] + [17, 31, 73, 47, 23] c = CircularList(range(256)) skip = 0 for x in xrange(repeat): skip = c.hashoper(counts, skip)[1] return densify(c) def hashmatrix(key): return [ knothashraw("%s-%d" % (key, x)) for x in xrange(128)] if __name__ == '__main__': if len(sys.argv) <= 1: import doctest doctest.testmod(verbose=False) else: print sum((sum((countbits(b) for b in x)) for x in hashmatrix(sys.argv[1])))
ebd015860a3051d40b0bc1b7f43c9938e4fb354b
ddvalim/TrabalhoI-ED
/Fila.py
2,760
3.8125
4
from Elemento import Elemento class Fila: def __init__(self, limite:int): self.__limite = limite self.__fim = None self.__inicio = None self.__numero_de_elementos = 0 def get_inicio(self): return self.__inicio def get_fim(self): return self.__fim def fila_vazia(self): return self.__numero_de_elementos == 0 def fila_cheia(self): return self.__numero_de_elementos == self.__limite def retira_elemento(self): if self.fila_vazia() == True: raise Exception("A fila está vazia!") else: if self.__inicio == self.__fim: self.__inicio = None self.__fim = None self.__numero_de_elementos -= 1 return self.__inicio else: element = self.__inicio self.__inicio = element.get_anterior() self.__numero_de_elementos -= 1 return self.__fim.get_numero() def insere_elemento(self, elemento:object): if isinstance(elemento, Elemento): if self.fila_cheia() != True: if self.__numero_de_elementos == 0: #Significa que a fila esta vazia self.__inicio = elemento self.__fim = elemento self.__numero_de_elementos += 1 return self.__inicio.get_numero() else: elemento.set_anterior(self.__fim) self.__numero_de_elementos += 1 self.__fim = elemento return else: raise Exception("A fila está cheia, impossível adicionar um novo elemento!") else: raise Exception("O parâmetro passado não é do tipo Elemento!") # TESTES # e = Elemento(9) f = Fila(10) f.insere_elemento(e) print(f.fila_cheia()) print(f.fila_vazia()) f.retira_elemento() print(f.fila_vazia()) # ------------- # d = Elemento(5) f.insere_elemento(d) print(f.get_inicio()) print(f.get_fim()) f.retira_elemento() # ------------- # y = Elemento(2) a = Elemento(6) u = Elemento(7) i = Elemento(4) k = Elemento(23) p = Elemento(89) q = Elemento(13) l = Elemento(22) f.insere_elemento(e) f.insere_elemento(d) f.insere_elemento(y) f.insere_elemento(a) f.insere_elemento(u) f.insere_elemento(i) f.insere_elemento(k) f.insere_elemento(p) f.insere_elemento(q) f.insere_elemento(l) print(f.fila_cheia()) print(f.fila_vazia()) print(f.retira_elemento()) elemento_final = Elemento(76) print(f.insere_elemento(elemento_final)) #print(f.insere_elemento(48))
2842fcc1c1a4c7ebd6bf69f7fc736a91e757f019
danicon/MD2-Curso_Python
/Aula13/ex10.py
249
3.765625
4
print(20*'=') print('10 TERMOS DE UMA PA') print(20*'=') prim = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) decimo = prim + (10 - 1) * razao for p in range(prim, decimo + razao, razao): print(p,end = ' \032 ') print('ACABOU')
4b80822b081642692f6d48f2354f1dc4f0aeb784
danicon/MD2-Curso_Python
/Aula12/ex05.py
290
3.96875
4
num1 = float(input('Digite a primeira nota: ')) num2 = float(input('Digite a segunda nota: ')) media = (num1 + num2) / 2 print(f'Sua média foi de {media:.1f}') if media < 5: print('REPROVADO!') elif media >= 5 and media <= 6.9: print('RECUPERAÇÃO!') else: print('APROVADO!')
b21508fdbec9795884be2b668a436c51b68d8183
danicon/MD2-Curso_Python
/Aula14ex/ex08.py
447
3.9375
4
c = 'S' soma = 0 cont = 0 maior = 0 menor = 0 while c == 'S': num = int(input('Digite um número: ')) soma += num if cont == 0: maior = num menor = num else: if num > maior: maior = num if num < menor: menor = num c = str(input('Deseja continuar? ')).strip().upper()[0] cont += 1 print(f'A media é de {soma / cont}, o maior número é {maior} e o menor é {menor}')
6af41e3ebf12ac657bf8383115e63be162a1282e
danicon/MD2-Curso_Python
/Aula12/ex01.py
435
3.875
4
casa = float(input('Qual é o valor da casa? R$')) salario = float(input('Qual é o seu salário? R$')) anos = float(input('Em quanto você vai pagar a casa? ')) emprestimo = casa / (anos * 12) parcela = (salario * 30) / 100 if emprestimo > parcela: print(f'Infelizmente o emprestimo de R${emprestimo:.2f} excedeu os 30% do seu salário') else: print(f'Você vai pagar o emprestimo mensalmente no valor de R${emprestimo:.2f}')
3bee3ad2a12712f8426b3eb36fd113063f439327
jbial/convolution
/visualization.py
3,081
3.53125
4
"""Utilities for visualizing convolution outputs """ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def visualize_conv1d_gif(f, g, response, filepath): """Plots gif of convolution output over each timestep WARNING: This function can be very taxing on your computer Args: f (np.array): one of the signals g (np.array): the other signal response (np.array): convolution output of f and g filepath (string): filepath for saving the gif file """ fig, axes = plt.subplots(3, 1, sharex=True, figsize=(12, 8)) # plot appearance fig.suptitle("Convolution of $f$ and $g$", size=20, y=0.95) for i, label in enumerate(("$f$", "$g$", "$f*g$")): axes[i].set_ylabel(label, size=15) axes[i].set_xlim(0, len(response)) axes[i].set_xlim(0, len(response)) axes[-1].set_xlabel("t") # pad input signals length = len(response) x = range(length) f_rem = length - len(f) g_rem = length - len(g) f_padding = (0, f_rem) g_padding = (g_rem, 0) f_pad = np.pad(f, f_padding) g_pad = np.pad(g[::-1], g_padding) # init animation f_line, = axes[0].plot(x, f_pad) g_line, = axes[1].plot(x, np.zeros(length)) fg_line, = axes[-1].plot(x, np.zeros(length)) lines = [f_line, g_line, fg_line] # plot convolution def animate(i): # translate g to the right for the gif animation g_subset = g_pad[-(i + 1):] if length - len(g_subset) >= 0: g_subset = np.pad(g_subset, (0, length - len(g_subset))) else: g_subset = g_subset[:length] lines[1].set_data(x, g_subset) # plot the response r_subset = response[:(i + 1)] r_padded = np.pad(r_subset, (0, length - len(r_subset))) lines[-1].set_data(x, r_padded) return lines axes[0].set_ylim(f.min(), f.max()) axes[1].set_ylim(g.min(), g.max()) axes[-1].set_ylim(response.min(), response.max()) anim = animation.FuncAnimation(fig, animate, frames=np.arange(length), interval=40, blit=True) anim.save(filepath, dpi=150, writer="imagemagick") plt.close() def visualize_conv2d(img, kernel, response): """Visualizes the convolution of an image with a kernel Args: img (np.ndarray): grayscale image kernel (np.ndarray): filter or kernel response (np.ndarray): convolution output """ fig, axes = plt.subplots( nrows=1, ncols=3, gridspec_kw={ 'width_ratios': [4, 1, 4] }, figsize=(10, 5) ) plt.rcParams['image.cmap'] = 'bone' # plot images axes[0].set_title("Original Image") axes[0].imshow(img) axes[0].axis('off') axes[1].set_title("Filter") axes[1].set_xticks([]) axes[1].set_yticks([]) axes[1].imshow(kernel, vmin=min(kernel.min(), 0), vmax=kernel.max()) axes[2].set_title("Filtered Image") axes[2].imshow(response) axes[2].axis('off') plt.show() plt.close()
595ed60c0537d7fa84b5cb63572bd781acbc5dd1
vishaljudoka/python_learning
/Datatypes/Range.py
285
4.03125
4
#Range sequence representing an arthmetic progression of integar """ range(5) #stop range(1,5) #start ,Stop range(1,10,2) #start stop step """ for i in range(1,10,2): print(i) ###Enumerate (Index and value) a=[3,4,5,8,'a'] for i,v in enumerate(a) : print (f' i={i}, v={v}')
c9b09cff1cd7dd62be942f65b16582ba1fb1fe34
DYEkanayake/CO324
/Lab01/ex3.py
1,081
3.828125
4
from ex1 import * def load_course_registrations_dict(filename: str) -> List[Student]: #Dictionary of Student Objects studentDetails=dict() #To keep the read data of the line being read details=[] with open(filename) as f: for line in f: details= line.strip().split(",") #given_name=details[0],surname=details[1],registered_courses=details[2:len(details)] #key=(surname, given_name) i.e. key=(details[1],details[0]) ## studentDetails[details[1],details[0]]=Student(details[0],details[1],details[2:len(details)]) keyTuple=(details[1],details[0]) studentDetails[keyTuple]=Student(details[0],details[1],details[2:len(details)]) """ Returns a dictionary of Student objects read from filename""" return studentDetails #print(load_course_registrations("data.txt")) print("Eg for searching by a key: key is ('Kariyawasam','Nimali') ") print(load_course_registrations_dict("data.txt")['Kariyawasam','Nimali'])
7d2426812e648d9541c3b3a5c8b970539769d3ba
elf-deedlit/wxCalender
/ds/_Struct.py
1,699
3.65625
4
#!/usr/bin/python # vim:set fileencoding=utf-8: # # python で 構造体みたいなやつ # __all__ = ['Struct'] class Struct(): def __init__(self, *items, **attrs): for item in items: assert instance(item, (tuple, list)) assert len(item) == 2 name, value = item self.__dict__[name] = value self.__dict__.update(attrs) def __iter__(self): for name, value in self.__dict__.items(): if name.startswith('_'): continue yield name, value def __len__(self): l = [name for name in list(self.__dict__.keys()) if not name.startswith('_')] return len(l) def __setitem__(self, name, value): self.__dict__[name] = value return value def __getitem__(self, name): return self.__dict__[name] def __contains__(self, value): return value in self.__dict__ def get(self, name, default): return self.__dict__.get(name, default) def setdefault(self, name, value): if name not in self.__dict__: self.__dict__[name] = value return self.__dict__[name] def test_struct(): s = Struct() s = Struct(foo = 1, bar = 2) assert s.bar == 2 assert len(s) == 2 ls = list(iter(s)) assert len(ls) == 2 try: nothing = s.nothing assert False except AttributeError: pass s.hoge = 3 assert len(s) == 3 assert s.get('foooo', -1) == -1 if __name__ == '__main__': try: test_struct() print('%s ok' % __file__) except: print('%s fault' % __file__) import traceback traceback.print_exc()
38ed49911be4adb634aa662aed898a56c244c5ac
mariadiaz-lpsr/class-samples
/5-4WritingHTML/primeListerTemplate.py
944
4.125
4
# returns True if myNum is prime # returns False is myNum is composite def isPrime(x, myNum): # here is where it will have a certain range from 2 to 100000 y = range(2,int(x)) # subtract each first to 2 primenum = x - 2 count = 0 for prime in y: # the number that was divided will then be divided to find remainder rem_prime = int(x) % int(prime) if rem_prime != 0: count = count + 1 # if it is prime it will print it and append it to the ListOfPrime if count == primenum: print(x) myNum.append(x) ListOfPrime = [] # the file numbers.txt will open so it can be append the numbers that are prime only prime = open("numbers.txt", "w") # the range is from 2 to 100000 r = range(2, 100000) for PList in r: numberss = isPrime(PList, ListOfPrime) for y in ListOfPrime: # the prime numbers will be written in a single list prime.write(str(y) + "\n") # the file that was open "numbers.txt" will close prime.close()
120526d1004799d849367a701f6fa9c09c6bbe05
mariadiaz-lpsr/class-samples
/quest.py
1,314
4.15625
4
print("Welcome to Maria's Quest!!") print("Enter the name of your character:") character = raw_input() print("Enter Strength (1-10):") strength = int(input()) print("Enter Health (1-10):") health = int(input()) print("Enter Luck (1-10):") luck = int(input()) if strength + health + luck > 15: print("You have give your character too many points! ") while strength + health + luck < 15: print(character , "strength" + strength + "health" + health + "luck" + luck) if strength + health + luck == 15: print(character," you've come to a fork in the road. Do you want to go right or left? Enter right or left. ") if right or left == "left": print("Sorry you lost the game.") # if user chooses right and has strength over 7 if strength >= 7: print(character,"you're strength is high enough you survived to fight the ninjas that attacked you. You won the game!") else: print("You didn't have sufficient strength to defeat the ninjas. Sorry you lost the game :(. ") # if health is greater than 8 if health >= 8: print("You had enough energy to pass by the ninjas." else: print("Sorry your health was not enough to survive the spriral ninja stars wound. ") # if the number of luck is greater than 5 it wil print out the first line if not it will directly go to the else line if luck >= 5: print("You had ")
7251ebc79e8c4968588276efb33d05320b032750
mariadiaz-lpsr/class-samples
/names.py
1,010
4.3125
4
# it first prints the first line print("These are the 5 friends and family I spend the most time with: ") # these are the 2 list name names and nams names = ['Jen', 'Mom', 'Dad', 'Alma', 'Ramon'] nams = ['Jackelyn', 'Judy', 'Elyssa', 'Christina', 'Cristian'] # it is concatenating both of the lists names_nams = names + nams # its changing the word in that number to another thing to print out instead for nms in names: names[0] = "1. Jen" for nms in names: names[1] = "2. Mom" for nms in names: names[2] = "3. Dad" for nms in names: names[3] = "4. Alma" for nms in names: names[4] = "5. Ramon" for nms in names: names[5] = "6. Jackelyn" for nms in names: names[6] = "7. Judy" for nms in names: names[7] = "8. Elyssa" for nms in names: names[8] = "9. Christina" for nms in names: names[9] = "10. Cristian" # it will print out both the names and nams lists print(names_nams) # it will reverse the list names.reverse() # it will print out the list been in reverse order print(names_nams)
a902676d106ef956530f77d114a30d5cd1f0dc58
mariadiaz-lpsr/class-samples
/guess.py
313
4.0625
4
import random guessnumber = random.randint(1, 5) print("I'm thinking of a number between 1 and 5. Enter your guess!") guess = input() if guess < guessnumber: print("Nope, too low! Guess again.") if guess > guessnumber: print("Nope, to high! Guess again.") if guess == guessnumber: print("Hooray, you won!")
434182c9ca2fa8b73c4f2fd0b4d9197720b7d406
pktippa/hr-python
/basic-data-types/second_largest_number.py
430
4.21875
4
# Finding the second largest number in a list. if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) # Converting input string into list by map and list() new = [x for x in arr if x != max(arr)] # Using list compressions building new list removing the highest number print(max(new)) # Since we removed the max number in list, now the max will give the second largest from original list.
3c09d0c67801c8748794d163a275a6c6f5b88378
pktippa/hr-python
/itertools/permutations.py
678
4.15625
4
# Importing permutations from itertools. from itertools import permutations # Taking the input split by space into two variables. string, count = input().split() # As per requirement the given input is all capital letters and the permutations # need to be in lexicographic order. Since all capital letters we can directly use # sorted(str) and join to form string string = ''.join(sorted(string)) # Calling permutations to get the list of permutations, returns list of tuples permutation_list = list(permutations(string, int(count))) # Looping through all elements(tuples) for element in permutation_list: print(''.join(element)) # forming string from a tuple of characters