blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f9b052a355ee2f7ee5acf0bac6bd11a04df7c9eb
boltnev/Exercises
/strings/isomorphic.py
890
3.5625
4
import unittest # O(N) def is_isomorphic(a, b): if len(a) == len(b): def get_unified_mapping(a): mapping = {} unified_arr = [] counter = 0 for l in a: if l not in mapping: mapping[l] = counter counter += 1 unified_arr.append(mapping[l]) return unified_arr return get_unified_mapping(a) == get_unified_mapping(b) return False class IsIsomorphicTest(unittest.TestCase): def test_is_isomorphic(self): a = "abba" b = "geeg" c = "abeg" d = "abbba" f = "isssi" self.assertTrue(is_isomorphic(a, b)) self.assertFalse(is_isomorphic(a, c)) self.assertFalse(is_isomorphic(a, d)) self.assertTrue(is_isomorphic(d, f)) if __name__=="__main__": unittest.main()
75b0e9718708251a750c76256d6318ab80f4d6b1
jameswmccarty/AdventOfCode2017
/day22.py
10,298
3.5
4
#!/usr/bin/python """ --- Day 22: Sporifica Virus --- Diagnostics indicate that the local grid computing cluster has been contaminated with the Sporifica Virus. The grid computing cluster is a seemingly-infinite two-dimensional grid of compute nodes. Each node is either clean or infected by the virus. To prevent overloading the nodes (which would render them useless to the virus) or detection by system administrators, exactly one virus carrier moves through the network, infecting or cleaning nodes as it moves. The virus carrier is always located on a single node in the network (the current node) and keeps track of the direction it is facing. To avoid detection, the virus carrier works in bursts; in each burst, it wakes up, does some work, and goes back to sleep. The following steps are all executed in order one time each burst: If the current node is infected, it turns to its right. Otherwise, it turns to its left. (Turning is done in-place; the current node does not change.) If the current node is clean, it becomes infected. Otherwise, it becomes cleaned. (This is done after the node is considered for the purposes of changing direction.) The virus carrier moves forward one node in the direction it is facing. Diagnostics have also provided a map of the node infection status (your puzzle input). Clean nodes are shown as .; infected nodes are shown as #. This map only shows the center of the grid; there are many more nodes beyond those shown, but none of them are currently infected. The virus carrier begins in the middle of the map facing up. For example, suppose you are given a map like this: ..# #.. ... Then, the middle of the infinite grid looks like this, with the virus carrier's position marked with [ ]: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . #[.]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The virus carrier is on a clean node, so it turns left, infects the node, and moves left: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . .[#]# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The virus carrier is on an infected node, so it turns right, cleans the node, and moves up: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .[.]. # . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Four times in a row, the virus carrier finds a clean, infects it, turns left, and moves forward, ending in the same place and still facing up: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #[#]. # . . . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Now on the same node as before, it sees an infection, which causes it to turn right, clean the node, and move forward: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # .[.]# . . . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . After the above actions, a total of 7 bursts of activity had taken place. Of them, 5 bursts of activity caused an infection. After a total of 70, the grid looks like this, with the virus carrier facing up: . . . . . # # . . . . . . # . . # . . . . # . . . . # . . # . #[.]. . # . . # . # . . # . . . . . . # # . . . . . . . . . . . . . . . . . . . . By this time, 41 bursts of activity caused an infection (though most of those nodes have since been cleaned). After a total of 10000 bursts of activity, 5587 bursts will have caused an infection. Given your actual map, after 10000 bursts of activity, how many bursts cause a node to become infected? (Do not count nodes that begin infected.) --- Part Two --- As you go to remove the virus from the infected nodes, it evolves to resist your attempt. Now, before it infects a clean node, it will weaken it to disable your defenses. If it encounters an infected node, it will instead flag the node to be cleaned in the future. So: Clean nodes become weakened. Weakened nodes become infected. Infected nodes become flagged. Flagged nodes become clean. Every node is always in exactly one of the above states. The virus carrier still functions in a similar way, but now uses the following logic during its bursts of action: Decide which way to turn based on the current node: If it is clean, it turns left. If it is weakened, it does not turn, and will continue moving in the same direction. If it is infected, it turns right. If it is flagged, it reverses direction, and will go back the way it came. Modify the state of the current node, as described above. The virus carrier moves forward one node in the direction it is facing. Start with the same map (still using . for clean and # for infected) and still with the virus carrier starting in the middle and facing up. Using the same initial state as the previous example, and drawing weakened as W and flagged as F, the middle of the infinite grid looks like this, with the virus carrier's position again marked with [ ]: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . #[.]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This is the same as before, since no initial nodes are weakened or flagged. The virus carrier is on a clean node, so it still turns left, instead weakens the node, and moves left: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . .[#]W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The virus carrier is on an infected node, so it still turns right, instead flags the node, and moves up: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .[.]. # . . . . . . F W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This process repeats three more times, ending on the previously-flagged node and facing right: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . W W . # . . . . . W[F]W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Finding a flagged node, it reverses direction and cleans the node: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . W W . # . . . . .[W]. W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The weakened node becomes infected, and it continues in the same direction: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . W W . # . . . .[.]# . W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Of the first 100 bursts, 26 will result in infection. Unfortunately, another feature of this evolved virus is speed; of the first 10000000 bursts, 2511944 will result in infection. Given your actual map, after 10000000 bursts of activity, how many bursts cause a node to become infected? (Do not count nodes that begin infected.) """ infected = set() weak = set() flagged = set() class Carrier: # Directions # 0 - Up ( y -= 1 ) # 1 - Down ( y += 1 ) # 2 - Left ( x -= 1 ) # 3 - Right( x += 1 ) def __init__(self, x, y): self.x = x self.y = y self.dir = 0 self.infections = 0 def move(self): # Part 1 Mover # if current node is infected if (self.x, self.y) in infected: # Turn Right if self.dir == 0: self.dir = 3 elif self.dir == 1: self.dir = 2 elif self.dir == 3: self.dir = 1 elif self.dir == 2: self.dir = 0 # Clean the Node infected.remove((self.x, self.y)) else: # Turn Left if self.dir == 0: self.dir = 2 elif self.dir == 1: self.dir = 3 elif self.dir == 3: self.dir = 0 elif self.dir == 2: self.dir = 1 # Infect the Node infected.add((self.x, self.y)) self.infections += 1 # Move forward if self.dir == 0: self.y -= 1 elif self.dir == 1: self.y += 1 elif self.dir == 3: self.x += 1 elif self.dir == 2: self.x -= 1 def adv_move(self): # Part 2 Mover # If currnt is clean if (self.x, self.y) not in weak and (self.x, self.y) not in flagged and (self.x, self.y) not in infected: # Turn Left if self.dir == 0: self.dir = 2 elif self.dir == 1: self.dir = 3 elif self.dir == 3: self.dir = 0 elif self.dir == 2: self.dir = 1 # Weaken the Node weak.add((self.x, self.y)) # no direction change for Weakened elif (self.x, self.y) in weak: infected.add((self.x, self.y)) weak.remove((self.x, self.y)) self.infections += 1 # if current node is infected elif (self.x, self.y) in infected: # Turn Right if self.dir == 0: self.dir = 3 elif self.dir == 1: self.dir = 2 elif self.dir == 3: self.dir = 1 elif self.dir == 2: self.dir = 0 # Flag the Node flagged.add((self.x, self.y)) infected.remove((self.x, self.y)) # Reverse if flagged node elif (self.x, self.y) in flagged: if self.dir == 0: self.dir = 1 elif self.dir == 1: self.dir = 0 elif self.dir == 3: self.dir = 2 elif self.dir == 2: self.dir = 3 # clean the node flagged.remove((self.x, self.y)) # Move forward if self.dir == 0: self.y -= 1 elif self.dir == 1: self.y += 1 elif self.dir == 3: self.x += 1 elif self.dir == 2: self.x -= 1 if __name__ == "__main__": # Part 1 Solution row_width = 0 row_idx = 0 with open("day22_input", "r") as infile: for line in infile.readlines(): for x, char in enumerate(line.strip()): if char == "#": infected.add((x,row_idx)) row_idx += 1 row_width = len(line) mover = Carrier(row_width / 2, row_idx / 2) # map center for i in range(10000): mover.move() print mover.infections # Part 2 Solution infected = set() # Reset row_width = 0 row_idx = 0 with open("day22_input", "r") as infile: for line in infile.readlines(): for x, char in enumerate(line.strip()): if char == "#": infected.add((x,row_idx)) row_idx += 1 row_width = len(line) mover = Carrier(row_width / 2, row_idx / 2) # map center for i in range(10000000): mover.adv_move() print mover.infections
a6a408ed86b69c6aac3a5b1d27fa0cb46a64e6dc
AlexandraFil/Geekbrains_2.0
/Python_start/lesson_5/lesson_5.1.py
521
4.09375
4
# 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. # Об окончании ввода данных свидетельствует пустая строка. while True: line = input("Введите строку: ").split() if len(line) == 0: break with open("new_1.txt", "a") as f: for i in range(len(line)): print(line[i], file=f)
5b946a75f1bda29059f2e1b6719c3a2438e4e40a
Botgar-Org/assignment-2-afriendsmoq
/listserv.py
1,014
3.9375
4
import csv, os, sys def create_lists(csv_file): with open(csv_file, 'rU') as f: reader = csv.reader(f, delimiter= ',') for row in reader: #get grade level initials from col 4 (BA, BFA, MFA, etc.) grade_level = row[4].split('.') #concatenate first and last name from col 2 and 3 name = row[2] + " " + row[3] #concatenate username from col 5 with "@artists.sfai.edu" email = row[5] + "@artists.sfai.edu" #creates email adress + full name as required by listserv bulk import full_info = email + " " + name + '\n' #creates a txt file named whatever grade_level in that row is, i.e. BA.txt text_file = grade_level[0] + ".txt" #prevent creating a file based on csv header 'grade_level' if grade_level[0] == 'grade_level': continue #writes to a text file named grade_level, the email adress and full name for that row with open(text_file, 'a') as t: t.write(full_info) #test this shit out def main(args): create_lists(args[1]) if __name__=='__main__': main(sys.argv)
e427d1d8f8f57c9696b27388f88cea1d4f117e09
amarmulyak/Python-Core-for-TA
/hw05/akhomi/Task1.py
486
4.09375
4
# # # Генерується список випадкових цілих чисел. Визначається, скільки в ньому парних чисел, а скільки непарних. import random a = [] pair_a = 0 not_pair = 0 for i in range(10): a.append(int(random.random() * 100)) print(a) even = 0 odd = 0 for number in a: if number%2 == 0: even += 1 else: odd += 1 print(f'Even numbers: {even}') print(f'Odd numbers: {odd}')
2ad8e0c96c3ff2a27ad6c2c4bd065146bee6b1e3
BrandConstantin/python
/Beginner/08_functions/Calculator.py
1,145
4.25
4
#Calculator # add def add(num1, num2): return num1 + num2 # substract def substract(num1, num2): return num1 - num2 # multiply def multiply(num1, num2): return num1 * num2 # divide def divide(num1, num2): return num1 / num2 ## Operations num1 = int(input("What is the first number that you wanna use? ")) num2 = int(input("What is the second number that you wanna use? ")) result = 0 operationString = "" operation = input("What operation you wanna do? (A. add / S. substract / M. multiply / D. divide) ").upper() if operation == "A": result = add(num1, num2) operationString = "+" print(f"Result: {num1} {operationString} {num2} = {result}") elif operation == "S": result = substract(num1, num2) operationString = "-" print(f"Result: {num1} {operationString} {num2} = {result}") elif operation == "M": result = multiply(num1, num2) operationString = "*" print(f"Result: {num1} {operationString} {num2} = {result}") elif operation == "D": result = divide(num1, num2) operationString = "/" print(f"Result: {num1} {operationString} {num2} = {result}") else: print("It\'s not a valid option!")
f759d12f98b50c6c430ab5e98c037a3cff52778f
AnnaGeorge-J/FST-M1
/Python/Activities/Activity2.py
162
4.28125
4
number = int(input("Enter a number: ")) mod = number % 2 if mod > 0: print("The number you entered is odd") else: print("The number you entered is even")
120517a5539a044db7bda92fceebd5fc59ff2c9e
dsasse07/learning-python
/assignment-2/q3-subtract.py
542
4.1875
4
''' Write a program in the file subtract_numbers.py that reads two real numbers from the user and prints the first number minus the second number. $ python subtract_numbers.py This program subtracts one number from another. Enter first number: 5.5 Enter second number: 2.1 The result is 3.4 ''' def main(): print('This program subtracts one number from another.') num1 = float(input('Enter first number: ')) num2 = float(input('Enter second number: ')) answer = round( num1 - num2, 1) print('The result is ' + str(answer)) main()
eefb5effbb12b148676e9e8e298141dfa214653c
jeanettehead/easy-functional-python-materials
/map.py
318
4.125
4
#map def square(x): return x**2 print square(5) #print square of every number between 0 and 10 print map(square, range(10)) print map(lambda n: n**2, range(10)) #print square of every number that is a multiple of 3 or 5 between 0 and 20 print map(lambda n: n**2, filter(lambda n: n%3==0 or n%5==0, range(20)))
dfbca3d7033f633002771dc498355ee1778b00c8
davidjuliancaldwell/ScientificSupercomputing
/astro598algorithms/davidcaldwell_hw5/priorityQueue.py
1,719
3.890625
4
#!/usr/bin/python class priorityQueue: def __init__(self,M): self.N = 0 self.MAX = M self.a = [0]*M def insert(self,i): self.N = self.N + 1 if(self.N >= self.MAX): raise Exception("Would exceed size of array") self.a[self.N] = i k = self.N while ((k>1) and (self.a[k//2]>self.a[k])): temp = self.a[k//2] self.a[k//2] = self.a[k] self.a[k] = temp k = k//2 def delMin(self): if (self.N == 0): raise Exception("Empty PriorityQueue!") minimum = self.a[1] self.a[1] = self.a[self.N] self.a[self.N] = 0 self.N = self.N -1 k = 1 while (2*k <= self.N): if ((2*k == self.N) or (self.a[2*k]<self.a[(2*k)+1])): j = 2*k else: j = (2*k)+1 if(self.a[k]>self.a[j]): temp = self.a[k] self.a[k] = self.a[j] self.a[j] = temp k = j else: break return minimum def minimum(self): if (self.N == 0): raise Exception("Empty PriorityQueue!") minimum = self.a[1] return minimum def size(self): return self.N def isEmpty(self): if self.N == 0: return True else: return False def isFull(self): if self.MAX == self.N: return True else: return False
7eac60394bf614f18634c5ca15d38ae3f856188d
shchun/udacity_work
/eulerian_tour.py
4,638
3.71875
4
#!/usr/bin/env python def get_all_node(graph): allnode = set([]) for edge in graph: allnode.add(edge[0]) allnode.add(edge[1]) return allnode def find_eulerian_tour(graph): eulpath = [] odd_node = [] tour = [] allnode = get_all_node(graph) #print 'allnode = ', allnode # make node - degree dictionary degrees = get_degree(graph) print 'degrees = ', degrees # for each odd degree node for node in allnode: if degrees[node] % 2 == 1: # odd odd_node.append(node) #print 'odd node = ', odd_node if len(odd_node) == 0: # all even degree node # if no odd degree -> make tour starting node_0 to_visit_set = set(graph) allnode_list = list(allnode) start = allnode_list[0] return get_path_for_nodes(graph, start, \ to_visit_set, [start]) elif len(odd_node) == 2: # 2 odd degree node print '### odd node = ', odd_node # if 2 odd degree -> make tour starting one of odd degreed node to_visit_set = set(graph) allnode_list = list(allnode) start = odd_node[0] return get_path_for_nodes(graph, start, \ to_visit_set, [start]) else: # if >2 odd degree -> None return None def get_path_for_nodes(graph, current, to_visit_set, path): a_path = [] peer = 0 ret = [] print 'get_path current=', current, ', \ to_visit = ', to_visit_set, ', path =', path if len(to_visit_set) == 0: print 'finish path=', path if get_all_node(graph) == set(path): return path # get adj edge adj = set([]) for t in to_visit_set: if current in t: adj.add(t) print 'adj = ', adj # no adj and len(to_visit_set) > 0: if len(adj) == 0: # dead end return [] # for edge in adj: # get peer node if edge[0] == current: peer = edge[1] else: peer = edge[0] ret = get_path_for_nodes(graph, peer, \ to_visit_set.difference(set([edge])), path + [peer]) print 'ret_a!! =', ret if len(ret) > 0: # found print 'found', a_path = ret print 'ret_aa!! a_path =',a_path return a_path print 'ret_b!! =', ret return a_path def get_degree(tour): degree = {} for x, y in tour: degree[x] = degree.get(x, 0) + 1 degree[y] = degree.get(y, 0) + 1 return degree def check_edge(t, b, nodes): """ t: tuple representing an edge b: origin node nodes: set of nodes already visited if we can get to a new node from `b` following `t` then return that node, else return None """ if t[0] == b: if t[1] not in nodes: return t[1] elif t[1] == b: if t[0] not in nodes: return t[0] return None def create_tour(nodes): # your code here print 'nodes = ', nodes tour = [] nodes_len = len(nodes) for i in range(nodes_len): tour.append( (nodes[i], nodes[(i+1)% nodes_len]) ) print 'tour = ', tour return tour def connected_nodes(tour): """return the set of nodes reachable from the first node in `tour`""" a = tour[0][0] nodes = set([a]) explore = set([a]) while len(explore) > 0: # see what other nodes we can reach b = explore.pop() for t in tour: node = check_edge(t, b, nodes) if node is None: continue nodes.add(node) explore.add(node) return nodes def is_eulerian_tour(nodes, tour): # all nodes must be even degree # and every node must be in graph degree = get_degree(tour) for node in nodes: try: d = degree[node] if d % 2 == 1: print "Node %s has odd degree" % node return False except KeyError: print "Node %s was not in your tour" % node return False connected = connected_nodes(tour) if len(connected) == len(nodes): return True else: print "Your graph wasn't connected" return False def test(): #a_graph = [(1, 2), (2, 3), (3, 1)] #a_graph = [(1, 2), (2, 3), (3, 1), (3, 4)] a_graph = [(0, 1), (1, 5), (1, 7), (4, 5), (4, 8), (1, 6), (3, 7), (5, 9), (2, 4), (0, 4), (2, 5), (3, 6), (8, 9)] #a_graph = [(1, 13), (1, 6), (6, 11), (3, 13), (8, 13), (0, 6), (8, 9),(5, 9), (2, 6), (6, 10), (7, 9), (1, 12), (4, 12), (5, 14), (0, 1), (2, 3), (4, 11), (6, 9), (7, 14), (10, 13)] #a_graph = [(8, 16), (8, 18), (16, 17), (18, 19), (3, 17), (13, 17), (5, 13),(3, 4), (0, 18), (3, 14), (11, 14), (1, 8), (1, 9), (4, 12), (2, 19),(1, 10), (7, 9), (13, 15), (6, 12), (0, 1), (2, 11), (3, 18), (5, 6), (7, 15), (8, 13), (10, 17)] #a_graph = [(1, 2), (2, 3), (3, 1), (3, 4)] return find_eulerian_tour(a_graph) print 'result = ', test()
7db6c4f113609bd0e88a2391b14d38326b516243
Shamsdamani21/CIS106-Jack-Samson
/Assignment 6/Activity 2.py
1,333
3.921875
4
# A simple program that tells you your age in months days and seconds yearsinayear = 1 monthsinayear = 12 daysinayear = 365 hoursinayear = 365 * 24 secondsinayear = 365 * (24 * (60 * 60)) def input_func(): print("input age in years") age = float(input()) return age def processing_func1(age): yearsold = age * yearsinayear return yearsold def processing_func2(age): monthsold = age * monthsinayear return monthsold def processing_func3(age): daysold = age * daysinayear return daysold def processing_func4(age): hoursold = age * hoursinayear return hoursold def processing_func5(age): secondsold = age * secondsinayear return secondsold def print_func(yearsold, monthsold, daysold, hoursold, secondsold): print(str(yearsold) + " Years old") print(str(monthsold) + " months old") print(str(daysold) + " days old") print(str(hoursold) + " hours old") print(str(secondsold) + " Seconds old") def main(): age = input_func() yearsold = processing_func1(age) monthsold = processing_func2(age) daysold = processing_func3(age) hoursold = processing_func4(age) secondsold = processing_func5(age) print_func(yearsold, monthsold, daysold, hoursold, secondsold) main()
21a8061852b730df752a97db4697f5bbca84891d
Semisvetiiik/My_python
/1.syntax/3.collection.py
2,712
4
4
# *** list *** # сощдание пстого списка my_list = [] my_list_2 = list() # добавление объекта (в конец списка) my_list.append(100) my_list.append(77) my_list.append("A") my_list.append([1,2,3]) # обращение к элементам списка my_list[0] = 5 my_list[-2] = 'B' # чиение значений element_value = my_list[1] # удаление значений # del my_list[-1] # my_list.remove(5) # a = my_list.pop(0) # создание заполненного списка my_list_2 = [10, 20, 30, 'A', "hello", True, 3.14, [1,2,3]] # "длина" списка - количество элементов # print(len(my_list_2)) # создание списка из строки s = "Привет, мир!" listFromStr = list(s) # print(listFromStr) # методы списка # исходный список x = [1,2,3,4,5] # представление y = x # y[2] = 100 # копия z = x.copy() z[2] =100 # print(f"x: {x}; z: {z}") # срез списка my_list = [10,20,30,40,50,60,70] # прямой срез slice_f = my_list[1:4] # с 1 индекса до 4 не вкл slice_f = my_list[2:] # с 2 индекса до конца slice_f = my_list[::2] # с самого начала до конца списка с шагом=2 slice_f = my_list[1:6:2] # с 1 индекса до 6 не вкл с шагом=2 # обратный срез slice_b = my_list[-1::-1] # с -1 индек до конца с шагом - одтн в обратном направл slice_b = my_list[-3:-6:-1] # print(slice_b) # *** кортеж (tuple) *** # неизменяемая (immutable) коллекция my_tuple = (10, 20, 30) # чтение данных el = my_tuple[-1] # можно делать срез кортежи el = my_tuple[-1:-3:-1] # нельзя удалять значения # del my_tuple[0] # нельзя менять значения # my_tuple[1] = 100 # нельзя добавлять элемент # print(el) # *** Словарь (dictionary) *** # Создание словаря my_dict = {1 : 100, 2:200, 3:777} my_dict_2 = {'a':10, 'b':"hello", 'c':[1,2,3], 10:1000} item = my_dict_2[10] item = my_dict_2['a'] # пример с ловаря в кач.альтернативы condition = 'key_2' d = {'key_1':100, 'key_2':200} my_dict_2['b'] = "python" del my_dict_2[10] my_dict_2["newKey"] = 777 # val = my_dict_2["key_2"] # val = my_dict_2.get("newKey") val = my_dict_2.get("Key_2", 0) # print(val) d_1 = {'a':10, 'b':20, 'c':30, 'd':40} u_d_1 = {'b':200, 'd':1000} u_d_2 = {'b':777, 'e':888} # d_1.update(u_d_1) d_1.update(u_d_2) print(d_1)
051d43fe1efe36f09f5b8bd6eee99528124995d7
harshsri2208/Machine-Learning-Lab-7th-Sem
/ML Assign 7/ML Assign 7/Assign7.py
7,962
3.875
4
#!/usr/bin/env python # coding: utf-8 # # Comparing Distance Based Classifiers # ## Submitted By Harsh Srivastava # ## 117CS0755 # ### importing libraries # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import normalize # ### function to calculate euclidean distance between two vectors # In[2]: def euclidean(a, b) : dist = a - b sq_dist = np.dot(np.transpose(dist), dist) sq_dist = np.sqrt(sq_dist) return sq_dist # ### function to calculate city block distance between two vectors # In[3]: def city_block(a, b) : dist = np.abs(a - b) return np.sum(dist) # ### function to calculate chess board distance between two vectors # In[4]: def chess_board(a, b) : dist = np.abs(a - b) return max(dist) # ### function to calculate cosine distance between two vectors # In[5]: def cos_dist(a, b) : dot_product = np.dot(a, b.T) norm_a = np.linalg.norm(a) norm_b = np.linalg.norm(b) return 1 - (dot_product / (norm_a * norm_b)) # ### function to calculate bray curtis distance between two vectors # In[6]: def bray_curtis(a, b) : d1 = np.sum(np.abs(a - b)) d2 = np.sum(np.abs(a + b)) return d1 / d2 # ### function to calculate canberra distance between two vectors # In[7]: def canberra(a, b) : dist = np.abs(a - b) / (np.abs(a) + np.abs(b)) return np.sum(dist) # ### function to calculate mahalonobis distance between two vectors # In[8]: def mahalonobis(a, b, input_space) : cov = np.cov(input_space.T) cov_inv = np.linalg.inv(cov) diff = a - b dist = np.dot(np.dot(diff.T, cov_inv), diff) return dist # ### function to calculate correlation distance between two vectors # In[9]: def correlation(a, b) : dev_a = a - np.mean(a) dev_b = b - np.mean(b) norm_a = np.linalg.norm(dev_a) norm_b = np.linalg.norm(dev_b) dist = 1 - (np.dot(dev_a, dev_b.T) / (norm_a * norm_b)) return dist # ### function to calculate minkowski distance between two vectors # In[10]: def minkowski(a, b, p) : diff = np.abs(a - b) dist = pow(np.sum(pow(diff, p)), (1 / p)) return dist # ### fucntion to select a distance type # In[11]: def distance(a, b, input_space, dist_type = 0) : if dist_type == 0 : return euclidean(a, b) elif dist_type == 1 : return city_block(a, b) elif dist_type == 2 : return chess_board(a, b) elif dist_type == 3 : return cos_dist(a, b) elif dist_type == 4 : return bray_curtis(a, b) elif dist_type == 5: return canberra(a, b) elif dist_type == 6: return mahalonobis(a, b, input_space) elif dist_type == 7: return correlation(a, b) elif dist_type == 8: return minkowski(a, b, np.random.randint(1, 10)) # ### distance types dictionary # In[12]: dist_dict = {0: 'Euclidean', 1: 'City Block', 2: 'Chess Board', 3: 'Cosine', 4: 'Bray Curtis', 5: 'Canberra', 6: 'Mahalonobis', 7: 'Correlation', 8: 'Minkowski'} dist_nums = len(dist_dict) # ### splitting dataset into 3 classes # In[13]: dataset = pd.read_csv('IRIS.csv') dataset_class1 = dataset.loc[0:49, :] dataset_class2 = dataset.loc[50:99, :] dataset_class3 = dataset.loc[100:149, :] # ### Iris-setosa # In[14]: dataset_class1 # ### Iris-versicolor # In[15]: dataset_class2 # ### Iris-virginica # In[16]: dataset_class3 # ### creating a dictionary to map class name with our defined labels # ### 'Iris-setosa' --> 0 # ### 'Iris-versicolor' --> 1 # ### 'Iris-virginica' --> 2 # In[17]: iris_dict = {0: 'Iris-setosa', 1: 'Iris-versicolor', 2: 'Iris-virginica'} iris_dict # ### splitting features and classes # In[18]: features = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] X1 = dataset_class1[features] X2 = dataset_class2[features] X3 = dataset_class3[features] X1 = normalize(X1, 'l2') X2 = normalize(X2, 'l2') X3 = normalize(X3, 'l2') # ### splitting dataset into training and test # In[19]: from sklearn.model_selection import train_test_split x_train1_pd, x_test1_pd = train_test_split(X1, test_size=.4) x_train2_pd, x_test2_pd = train_test_split(X2, test_size=.4) x_train3_pd, x_test3_pd = train_test_split(X3, test_size=.4) num_test = 20 num_train = 50 - num_test total_num_test = 60 total_num_train = 150 - total_num_test x_train1_pd # ### converting training and test datasets to numpy arrays for easy calculations # In[20]: x_train = [] x_test = [] x_train.append(x_train1_pd)#.to_numpy()) x_train.append(x_train2_pd)#.to_numpy()) x_train.append(x_train3_pd)#.to_numpy()) x_test.append(x_test1_pd)#.to_numpy()) x_test.append(x_test2_pd)#.to_numpy()) x_test.append(x_test3_pd)#.to_numpy()) print(x_train[0]) print(x_test[0]) print(x_train[0].shape) print(x_test[0].shape) # ### calculating mean of features of classes in training dataset # In[21]: mean = [] mean.append(np.mean(x_train[0], axis = 0)) mean.append(np.mean(x_train[1], axis = 0)) mean.append(np.mean(x_train[2], axis = 0)) print(mean[0]) print(mean[1]) print(mean[2]) # ### predicting classes for iris-setosa test data using euclidean distance # In[22]: def prediction_distance_types(dist_type = 0) : correct_count = 0 # variable to count number of training examples correctly classified pred = [] error = [] for i in range(3) : train = x_train[i] # for covariance matrix test = x_test[i] for j in range(num_test) : min_dist = distance(test[j], mean[0], train, dist_type) min_idx = 0 for k in range(len(mean)) : dist = distance(test[j], mean[k], train, dist_type) if dist < min_dist : min_dist = dist min_idx = k pred.append(iris_dict[min_idx]) error.append(min_dist) if min_idx == i : correct_count += 1 MER = 1.0 - (correct_count / total_num_test) return MER, correct_count, pred, error # ### predicting using different distance methods # In[23]: MER_vals = [] correct_count_vals = [] error_vals = [] for i in range(dist_nums) : MER, correct_count, pred, error = prediction_distance_types(i) print("MER for {} distance = {}".format(dist_dict[i], MER)) print("Number of Correct classifications out of {} = {}\n".format(total_num_test, correct_count)) MER_vals.append(MER) correct_count_vals.append(correct_count) error_vals.append(error) # ### Plotting MER vs distance type classifier # In[24]: print("Plotting MER vs Classifier Type") plt.bar(list(dist_dict.values()), MER_vals) plt.xlabel('Classifier Type') plt.ylabel('MER') plt.xticks(rotation=90) plt.yticks(np.arange(0, 0.2, 0.02)) plt.show() # ### Mean Error and plot # In[25]: error_vals = np.array(error_vals) mean_error = np.mean(error_vals, axis = 1) print("Plotting Mean Error vs Classifier Type") plt.bar(list(dist_dict.values()), mean_error) plt.xlabel('Classifier Type') plt.ylabel('Mean Error') plt.xticks(rotation=90) plt.show() # ### Mean Squared Error and plot # In[26]: mean_squared_error = np.mean(np.square(error_vals), axis = 1) print("Plotting Mean Squared Error vs Classifier Type") plt.bar(list(dist_dict.values()), mean_squared_error) plt.xlabel('Classifier Type') plt.ylabel('Mean Squared Error') plt.xticks(rotation=90) plt.show() # ### Mean absolute Error and plot # In[27]: mean_absolute_error = np.mean(np.abs(error_vals), axis = 1) print("Plotting Mean Absolute Error vs Classifier Type") plt.bar(list(dist_dict.values()), mean_absolute_error) plt.xlabel('Classifier Type') plt.ylabel('Mean Absolute Error') plt.xticks(rotation=90) plt.show() # In[ ]:
2394fcc45de5036a702479771840d78471881474
hectormanfredi/PythonExercicios
/ex006.py
275
3.828125
4
# Crie um algoritimo que leia um número e mostre o seu dobro, triplo e a raiz quadrada n = int(input('Digite um número: ')) print('O dobro de {} é {}.\n O triplo de {} é {}.\n E a raiz quadrada de {} é {:.2f}.' .format(n, n * 2, n, n * 3, n, pow(n, (1/2))))
d1303d03bd2776feaf3767ded4cead39f96d80e9
SomyaBansal1998/pythoncode.repo
/leastfrequentchar.py
138
3.78125
4
from collections import Counter str1=input() res=Counter(str1) res=min(res,key=res.get) print("Least frequent character is:"+ str(res))
032e19aec5dabed82e2a7a5b792a3463853cbd5b
dhita-irma/miniprojects
/numbers/change_return/change_return.py
1,336
4.3125
4
# Change Return Program - The user enters a cost and then the amount of money given. # The cost has to be lower than 2000. # The program will figure out the change and the number of # 100, 200, and 500, and 1000 needed for the change. cost = int(input("Enter the cost: ")) money_given = int(input("Enter the money given: ")) def change(cost, money_given): change_amount = money_given - cost one_thousand_bill = 0 five_hundred_bill = 0 two_hundred_bill = 0 one_hundred_bill = 0 print(f"The change amount would be {change_amount}:") if change_amount > 0: while change_amount >= 1000: change_amount -= 1000 one_thousand_bill += 1 while change_amount >= 500: change_amount -= 500 five_hundred_bill += 1 while change_amount >= 200: change_amount -= 200 two_hundred_bill += 1 while change_amount >= 100: change_amount -= 100 one_hundred_bill += 1 print(f"{one_thousand_bill} one thousand bill(s).") print(f"{five_hundred_bill} five hundred bill(s).") print(f"{two_hundred_bill} two hundred bill(s).") print(f"{one_hundred_bill} one hundred bill(s).") else: print("Your money isn't enough to pay the cost.") change(cost, money_given)
ab9a3ae65aa420321b63bb6a724fd88359cfb628
JonDGS/Intro-y-Taller
/Recursion de pila/repetidosconlambda.py
426
3.703125
4
def lista(lista1, num): if isinstance(lista1 ,list) and isinstance(num, int): x = lambda num1, num2: num1 == num2 return detectar(lista1,num, x) else: return 'No se digito una lista' def detectar(lista1,num1,esto): if lista1 == []: return 0 if esto(lista1[0], num1): return 1 + detectar(lista1[1:],num1, esto) else: return detectar(lista1[1:],num1, esto)
48f87f9ec791cbbf110f9552337ad5ad7ed13116
ronniebm/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
1,936
3.984375
4
#!/usr/bin/python3 """ square.py module""" from models.rectangle import Rectangle class Square(Rectangle): """ Rectangle Rectangle. Inheritance: from Base Rectangle. ----------- """ def __init__(self, size, x=0, y=0, id=None): """ This function create instances of an square Class. """ super().__init__(size, size, x, y, id) @property def size(self): """ return the size (width) """ return self.width @size.setter def size(self, value): """ set the size (width and height) """ self.width = value self.height = value def __str__(self): """overriding the __str__ method""" s = self.size x = self.x y = self.y _id = self.id return("[Square] ({0}) {1}/{2} - {3}".format(_id, x, y, s)) def update(self, *args, **kwargs): """update method""" _len = len(args) if not args: if kwargs.get('id') is not None: self.id = kwargs.get('id') if kwargs.get('size') is not None: self.size = kwargs.get('size') if kwargs.get('x') is not None: self.x = kwargs.get('x') if kwargs.get('y') is not None: self.y = kwargs.get('y') else: if _len >= 1 and args[0] is not None: self.id = args[0] if _len >= 2 and args[1] is not None: self.size = args[1] if _len >= 3 and args[2] is not None: self.x = args[2] if _len >= 4 and args[3] is not None: self.y = args[3] def to_dictionary(self): """to_dictionary method""" dict1 = { 'id': self.id, 'x': self.x, 'size': self.size, 'y': self.y, } return (dict1)
a4569633e9f170ae7bc98711be014b9bb77980bd
hansenliman/Fun-Coding-Challenges
/Implement a Sparse Array.py
924
3.8125
4
""" Problem taken from Daily Coding Problems. You have a large array, most of whose elements are zero. Create a more space-efficient data structure, SparseArray, that implements the following interface: - init(arr, size): initialie with the original arge array and size. - set(i, val): update index at i to be val. - get(i): get the value at index i. """ # Implement a Sparse Array class SparseArray: def __init__(self, arr, size): # Initialize with the original large array and size. self.dict = {} self.size = size for i in range(self.size - 1): if i != 0: self.dict[i] = arr[i] def set(self, i, val): # Update index at i to be val. self.dict[i] = val def get(self, i): # Get the value at index i. if i not in self.dict: return 0 else: return self.dict[i]
7fb0d815060c0c18c4a5c4e1ff465dc54f324d61
vilem-nachtmann/malgym_programovani
/fibonacci.py
280
3.546875
4
seq = [] n = 0 F = 0 nMax = int(input("Nejvyšší počítaná pozice v posloupnosti: ")) while n <= nMax: if n == 0: F = 0 elif n == 1: F = 1 else: F = seq[n - 1] + seq[n - 2] seq.append(F) print(str(F)) n = len(seq)
7611f5aaef6fa332b6e272b2bcaef14bf547e3d0
pawarspeaks/HackFest21
/Patterns/leftArrowPattern.py
263
3.75
4
#left-arrow pattern n=int(input()) st=2*n for i in range(n): for j in range(st): print("*",end=" ") if i!=n-1: print() st=st-2 for i in range(n+1): for j in range(st): print("*",end=" ") print() st=st+2
1a32f1ec8f48b7764b6f88e612eb328a4c3b47b5
gheckojuandup/WB372
/neville.py
678
3.75
4
def neville(x_data, y_data, x): """p = neville(x_data, y_data, x) Evaluate the polynomial interpolant p(x) that passes through the specified data points by Neville's method.""" n = len(x_data) p = n*[0] for k in range(n): for i in range(n-k): if k == 0: p[i] = y_data[i] else: p[i] = ((x-x_data[i+k])*p[i]+ \ (x_data[i]-x)*p[i+1])/ \ (x_data[i]-x_data[i+k]) return p[0] if __name__ == "__main__": x_data = [8.1, 8.3, 8.6, 8.7] y_data = [16.9446, 17.56492, 18.50515, 18.82091] x = 8.4 print(neville(x_data, y_data, x))
f7acaf9db8a709cce08d508e872d765a2fd97490
kid1988/ands
/ands/algorithms/dp/rod_cut.py
7,379
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author: Nelson Brochado Creation: 30/08/15 Last update: 18/11/2016 ## References: - http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html - Introduction to Algorithms (3rd edition) by CLSR - Slides by prof. E. Papadopoulou """ import sys def recursive_rod_cut(prices, n): """Returns the maximum revenue of cutting a rod of length n. It does not return which rod pieces you need to pick to obtain the maximum revenue. The rod cutting problem is the following: given a rod of length n, and a table of prices p_i, for i = 0, 1, 2, 3, ..., determine the maximum revenue r_n obtainable by cutting up the rod and selling the pieces. Note that if the price p_n for a rod of length n is large enough, an optimal solution may require no cutting at all. We can cut up a rod of length n in 2^{n - 1} different ways, since we have an independent option of cutting, or not cutting, at distance i inches from the left end, for i = 1, 2, ... , n - 1. prices contains the prices for each rod of different length. prices[0] would be the price of the rod of length 0 (not useful). prices[1] would be the price of the rod of length 1, prices[2] would be the price for a rod of length 2, and so on. Running time complexity: O(2^n) :type prices : list | tuple :type n : int """ if n == 0: # Base case return 0 max_revenue = -sys.maxsize for i in range(1, n + 1): # Last i is n. max_revenue = max(max_revenue, prices[i] + recursive_rod_cut(prices, n - i)) return max_revenue def _memoized_rod_cut_aux(prices, n, revenues, s): """Auxiliary function for the memoized_rod_cut function. :type prices : list | tuple :type n : int :type revenues : list | tuple """ # If the following condition is true, # that would mean that the revenue # for a rod of length n has already been "memoised", # and we don't need to recompute it again, # but we simply return it. if revenues[n] >= 0: return revenues[n] max_revenue = -sys.maxsize if n == 0: # If the size of the rod is 0, then max_revenue is 0. max_revenue = 0 else: for i in range(1, n + 1): q = _memoized_rod_cut_aux(prices, n - i, revenues, s) if prices[i] + q > max_revenue: max_revenue = prices[i] + q s[n] = i # Memoising the maximum revenue for sub-problem with a rod of length n. revenues[n] = max_revenue return max_revenue def memoized_rod_cut(prices, n): """_Top-down_ dynamic programming version of `recursive_rod_cut`, using _memoisation_ to store sub problems' solutions. _Memoisation_ is basically the name to the technique of storing what it's been computed previously. In this algorithm, as opppose to the plain recursive one, instead of repeatedly solving the same subproblems, we store the solution to a subproblem in a table, the first time we solve the subproblem, so that this solution can simply be looked up, if needed again. The disadvantge of this solution is that we need additional memory, i.e., a table, to store intermediary solutions. Running time complexity: theta(n^2) :type prices : list | tuple :type n : int :rtype : int """ # Initialing the revenues list f # or the sub-problems length i = 0, 1, 2, ... , n # to a small and negative number, # which simply means that we have not yet computed # the revenue for those sub-problems. # Note that revenue values are always nonnegative, # unless prices contain negative numbers. revenues = [-sys.maxsize] * (n + 1) # optimal first cut for rods of length 0..n s = [0] * (n + 1) return _memoized_rod_cut_aux(prices, n, revenues, s), s def bottom_up_rod_cut(prices, n): """_Bottom-up_ dynamic programming solution to the rod cut problem. Running time complexity: theta(n^2) :type prices : list | tuple :type n : int """ revenues = [-sys.maxsize] * (n + 1) revenues[0] = 0 # Revenue for rod of length 0 is 0. for i in range(1, n + 1): max_revenue = -sys.maxsize for j in range(1, i + 1): # Find the max cut position for length i max_revenue = max(max_revenue, prices[j] + revenues[i - j]) revenues[i] = max_revenue return revenues[n] def extended_bottom_up_rod_cut(prices, n): """Dynamic programming solution to the rod cut problem. This dynamic programming version uses a bottom-up approach. It returns a tuple, whose first item is a list of the revenues and second is a list containing the rod pieces that are used in the revenue. Running time complexity: O(n^2) :type prices : list :type n : int :rtype : tuple """ revenues = [-sys.maxsize] * (n + 1) s = [[]] * (n + 1) # Used to store the optimal choices revenues[0] = 0 s[0] = [0] for i in range(1, n + 1): max_revenue = -sys.maxsize for j in range(1, i + 1): # Note that j + (i - j) = i. # What does this mean, or why should this fact be useful? # Note that at each iteration of the outer loop, # we are trying to find the max_revenue for a rod of length i # (and we want also to find which items we are including to obtain that max_revenue). # To obtain a rod of size i, we need at least 2 other smaller rods, # unless we do not cut the rod. # Now, to obtain a rod of length i, # we need to insert together a rod of length j < i and a rod of length i - j < j, # because j + (i - j) = i, as we stated at the beginning. if max_revenue < prices[j] + revenues[i - j]: max_revenue = prices[j] + revenues[i - j] if revenues[i - j] != 0: s[i] = [j] + s[i - j] else: # revenue[i] (current) uses a rod of length j # left most cut is at j s[i] = [j] revenues[i] = max_revenue return revenues, s def rod_cut_solution_print(prices, n, s): """prices is the list of initial prices. n is the number of those prices - 1. s is the solution returned by memoized_rod_cut.""" while n > 0: print(s[n], end=" ") n = n - s[n] print() if __name__ == "__main__": p1 = [0, 1, 5, 8, 9, 10, 17, 17, 20] def test0(): r = recursive_rod_cut(p1, len(p1) - 1) print("Revenue:", r) print("--------------------------------------------") def test1(): r, s = memoized_rod_cut(p1, len(p1) - 1) print("Revenue:", r) print("s:", s) rod_cut_solution_print(p1, len(p1) - 1, s) print("--------------------------------------------") def test2(): r = bottom_up_rod_cut(p1, len(p1) - 1) print("Revenue:", r) print("--------------------------------------------") def test3(): r, s = extended_bottom_up_rod_cut(p1, len(p1) - 1) print("Revenues:", r) print("s:", s) print("--------------------------------------------") test0() test1() test2() test3()
f4f4a9fc92a67ea250e36f5ef3e86435d5ba9f91
KeiSoto/Agenda
/agenda.py
1,028
3.671875
4
import csv class agenda: def __init__(self): print 'Menu\n' print '1 Ver Agenda' print '2 Insertar' print '3 Salir' self.opcion = int(raw_input('Ingrese la opcion que desee:\t')) if self.opcion == 1: with open('data.csv','r') as file: data = csv.reader(file, delimiter = '|') for line in data: print line elif self.opcion == 2: self.nombre = str(raw_input('Ingrese el nombre: ')) self.email = str(raw_input('Ingrese el email: ')) self.telefono = str(raw_input('Ingresa el numero de telefono: ')) with open('data.csv', 'a') as file: data = csv.writer(file, delimiter = '|') data.writerow([self.nombre, self.email, self.telefono]) elif self.opcion == 3: exit() agenda = agenda()
4346dafdec6049ae47d53c3c51fe7998280a32e8
Sen2k9/Algorithm-and-Problem-Solving
/leetcode_problems/110_Balanced_Binary_Tree.py
1,405
4.15625
4
""" Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1. Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isBalanced(self, root): # # Solution 1: Bottom - up approach return self.depth(root) != -1 def depth(self, root): if not root: return 0 left = self.depth(root.left) right = self.depth(root.right) if abs(left - right) > 1 or left == -1 or right == -1: return - 1 return 1 + max(left, right) # Solution 2: iterative """ corner case: 1. not looking for leaf node who do not have any left or right subtree [1,null,2,null,3] [1] [1,2,2,3,3,3,3,4,4,4,4,4,4,null,null,5,5] reference: https://leetcode.com/problems/balanced-binary-tree/discuss/35708/VERY-SIMPLE-Python-solutions-(iterative-and-recursive)-both-beat-90 """
6ace197ae9a8f78d22a41af5cfd77c2f69516635
KritoCC/Sword
/ex14.py
1,258
3.875
4
# 习题十四 from sys import argv script, user_name = argv prompt = "> " # 我们将用户提示符设置为变量prompt,这样就不需要在每次用到input时反复输入提示用户的字符了。 # 而且,如果要将提示符修改成别的字符串,只要改一个位置就可以了。 print("Hi %s, I'm the %s script" % (user_name, script)) print("I'd like to ask you a few question.") print("Do you like me %s?" % user_name) likes = input(prompt) print("Where do you live %s?" % user_name) lives = input(prompt) print("Where kind of computer do you have?") computer = input(prompt) print(""" Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer)) # 运行结果 # PS C:\Users\12409> cd C:\Users\12409\AppData\Local\atom\file # PS C:\Users\12409\AppData\Local\atom\file> python ex14.py Krito # Hi Krito, I'm the ex14.py script # I'd like to ask you a few question. # Do you like me Krito # > Yes # Where do you live Krito # > Sword Art Online # Where kind of computer do you have? # > Apple # Alright, so you said 'Yes' about likeing me. # You live in 'Sword Art Online'. Not sure where that is. # And you have a 'Apple' computer. Nice.
b2d35e79ad9bb35a98c23ac5046734259f6c092c
colinrodney/python
/codingbat/string-1/make_abba.py
171
3.625
4
def make_abba(a, b): ''' function returns strings concatenated together in following order: abba, Ex. make_abba('hi','bye') --> hibyebyehi ''' return (a+b) + (b+a)
60ce64c026c5a3038907174f24fe51dfdad8a94b
LeonMac/Principles-of-Data-Science_forPython3
/P111_SND.py
734
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #import random import numpy as np #import pandas as pd from matplotlib import pyplot as plt def normal_pdf(x, mu=0, sigma=1): return (1./np.sqrt(2*3.14159*sigma**2) )* 2.718**( -(x-mu)**2/(2*sigma**2) ) x_values = np.linspace(-5,5,100) y_values = [normal_pdf(x) for x in x_values] plt.plot(x_values, y_values) plt.show() ''' from scipy.stats import norm import numpy as np import matplotlib.pyplot as plt def normal_pdf(x, mean, sigma): return (1./np.sqrt(2*3.14159*sigma**2) )* 2.718**( -(x-mean)**2/(2*sigma**2) ) x=np.arange(-5,5,0.01) mean=0 sigma=1 y=normal_pdf(x, mean, sigma) #y=norm.pdf(x,mean,sigma) plt.plot(x,y) plt.xlabel('x') plt.ylabel('y') plt.show() '''
f69ac671207c7f9fa80d078e0b53e963ab629b87
Shogo-Sakai/everybodys_ai
/math_training/exponential_functions.py
192
3.546875
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(-5, 5, 0.1) # y = 2^x y_2 = 2**x # y = 3^x y_3 = 3**x print (x) print (y_2) plt.plot(x, y_2) plt.plot(x, y_3) plt.show()
c932b0be176a29ed44a91c6c5cc9de6b1308ff10
yaoyuan0553/BertContextBasedEmbedding
/main.py
2,451
3.5
4
""" A program to load dictionary txt file and extract similarity between given words Usage: main.py --dict-src=<file> --bert-src=<dir> [options] Options: -h, --help show this message --dict-src=<file> file path to the dictionary file to be read from --bert-src=<dir> directory path to pretrained BERT model used for embedding --layers=<list> index/indices of the bert encoding layer to be used [default: -1,-2,-3,-4] """ import sys import SimilarityFunction as sf from docopt import docopt from BertEmbedder import BertEmbedder from EmbeddingDictionary import EmbeddingDictionary, EntryKey, EmbeddingConfig from DictionaryLoader import DictionaryLoader from SimilarityFunction import cosineSimilarity from SimilarityDictionary import SimilarityDictionary def main(): args = docopt(__doc__) EmbeddingConfig.DefaultEmbedder = BertEmbedder(args['--bert-src'], args['--layers']) # construct and load dictionary embedDict = EmbeddingDictionary() loader = DictionaryLoader(embedDict) loader.load(args['--dict-src']) simDict = SimilarityDictionary(embedDict, cosineSimilarity) print("Dictionary loaded: %s" % embedDict) helpMsg = 'Help:\n\t-h, --help\t\tshow this help message\n' \ '\texit, quit\t\texit program' initialHelp = 'Enter -h or --help for additional help' print(initialHelp) while True: try: request = input('Request format: <N> <word> [category]: ') if request == '-h' or request == '--help': print(helpMsg) elif request == 'exit' or request == 'quit': break else: wc = request.strip().split(' ') if len(wc) == 2: key = EntryKey(wc[1]) elif len(wc) == 3: key = EntryKey(wc[1], wc[2]) else: print('wrong request format!', file=sys.stderr) continue try: sims = simDict.rankedSimilarity(key, top=int(wc[0])) # sims = embedDict.getOrderedSimilarityForWord(key, sf.cosineSimilarity) except KeyError: print(sys.exc_info()[1]) continue print(sims) except BaseException: print(sys.exc_info()) continue if __name__ == "__main__": main()
8a32b559983080b6997082c139d16a143845c923
YounessTayer/Tk-Assistant
/squirts/boxes/combo_box.py
1,261
3.84375
4
"""Combobox demo. Stand-alone example from Tk Assistant. Updated March 2021 By Steve Shambles stevepython.wordpress.com """ import tkinter as tk from tkinter import messagebox from tkinter.ttk import Combobox root = tk.Tk() root.title('Combobox demo') # Callback def clkd_btn(): """Display selection.""" sel_item = combo_bx.get() if sel_item == 'Select an item': return if sel_item == 'Quit combobox demo': root.withdraw() root.destroy() return tk.messagebox.showinfo('User choice', 'You Selected:\n\n'+str(sel_item)) # Frame. combo_frame = tk.LabelFrame(root) combo_frame.grid(padx=20, pady=8) # Combobox. combo_bx = Combobox(combo_frame) combo_bx['values'] = ('Select an item', 'Art', 'Cats', 'Celeb', 'Dogs', 'Quit combobox demo') combo_bx.current(0) combo_bx.grid(padx=5, pady=5) # Button. clk_btn = tk.Button(combo_frame, bg='gold', text='Click Me', command=clkd_btn) clk_btn.grid(sticky=tk.W+tk.E, padx=5, pady=5) root.mainloop()
bcbf333e5af318b8fd88269b39cffa340f265798
WuLC/LeetCode
/Algorithm/Python/215. Kth Largest Element in an Array.py
1,421
3.5625
4
# -*- coding: utf-8 -*- # @Author: WuLC # @Date: 2016-06-07 15:24:56 # @Last modified by: WuLC # @Last Modified time: 2016-06-07 15:25:08 # @Email: liangchaowu5@gmail.com class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ return self.helper(nums, 0, len(nums)-1, k) def helper(self, nums, left, right, k): if left > right: return i, j = left, right while i < j: while i<j and nums[j] >= nums[left]: j -= 1 while i<j and nums[i] <= nums[left]: i += 1 if i < j: nums[i], nums[j] = nums[j], nums[i] nums[i], nums[left] = nums[left], nums[i] if i == len(nums)-k: return nums[i] elif i< len(nums)-k: return self.helper(nums, i+1, right, k) else: return self.helper(nums, left, i-1, k) # solution 2, use heap to keep the k largest numbers import heapq class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ heap = [] for num in nums: if len(heap) < k: heapq.heappush(heap, num) else: heapq.heappushpop(heap, num) return heap[0]
3fb2b5b841f6f113b80519af83709ee0e63e77b1
georgezouq/Python-Algorithm
/TP-Growth/tree_building.py
1,752
3.578125
4
#coding=utf-8 class Node(object): """Node类 作用:开辟一个树节点""" def __init__(self,data=-1,count=0,parent=None): """Node类的初始化,一个节点信息包括:项的值,计数,父亲节点,所有孩子节点""" self.data = data self.count = count self.parent = parent self.children = {} class Tree(object): """tree_growth 类 作用:建造树""" def __init__(self,data=-1,parent=None,itemTable=None): """tree_growth类的初始化,开辟一个树根""" self.root = Node(data='null',parent=self) self.itemTable = itemTable def addRoutine(self,routine,Rroot,count): """功能:根据实物routine 递归构造树,Rroot是树的根节点,count是routine出现的次数(构造条件FP_Tree的时候有用)""" if len(routine) <= 0: #如果书屋为空,则终止 return elem = routine.pop(0) if elem in Rroot.children: #如果实物中的元素在树的已有路径上 nextNode = Rroot.children[elem] #如果实物中的元素在树的已有路径上,则不用新建路径 else: newNode = Node(data=elem,parent=Rroot) #新建一个节点 Rroot.children.setdefault(elem,newNode) #新节点的路径放在当前节点的孩子列表中 nextNode = newNode nextNode.count += count #更新路径上节点的计数,即加上当前节点的计数 if nextNode not in self.itemTable[elem]: #如果下一个节点是新建的,则把他压入头节点表中 self.itemTable[elem].append(nextNode) self.addRoutine(routine=routine,Rroot=nextNode,count=count) #递归构造树 return
70ee75995e82d89c626fcf96f05e070db3340b3c
Achyut21/BasicStudentClass_python
/main.py
1,307
3.953125
4
class student: def __init__(self, id, name, mid1_marks, mid2_marks, quiz_marks): self.id = id self.name = name self.mid1_marks = mid1_marks self.mid2_marks = mid2_marks self.quiz_marks = quiz_marks def result(self): if self.total() >= 80: print("Your Grade is A") elif 80 > self.total() >= 60: print("Your Grade is B") elif 60 > self.total() >= 50: print("Your Grade is C") def total(self): return self.mid1_marks + self.mid2_marks + self.quiz_marks def display(self): print("\n================================================") print(f"ROLL NO: {self.id}") print(f"Student name: {self.name}") print(f"Mid1 marks: {self.mid1_marks}") print(f"Mid2 marks: {self.mid2_marks}") print(f"Total Marks: {self.total()}") print(f"Result: {self.result()}") print("================================================") if __name__ == '__main__': name = input("Enter your name: ") id = int(input("Enter your roll no: ")) mid1 = int(input("Enter your mid marks: ")) mid2 = int(input("Enter your md 2 marks: ")) quiz = int(input("Enter your quiz marks: ")) s1 = student( id, name, mid1, mid2, quiz) s1.display()
de999010fc9a642d72bfef624778d48104efbae2
sevgibayansalduzz/Algorithm-Design-and-Analysis
/hw4/part4.py
2,222
3.796875
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 28 09:43:08 2018 @author: sevgi """ # takes as input the list of n people and the list of pairs who know each other, and outputs the best choice of party invitees. def partyInvitees(people,pairs): output=[] known=[] #take a person and calculate that how many people he/she knows. for i in range (len(people)): count=0#reset count for j in range(len(pairs)):#search this person in pairs if(people[i] in pairs[j]):#if this person is in pair[j] ,increase count by 1 count=count+1 known.append(count)#append 'count' into the array known.(this person is in the ith index and known[i] represents the number of people whohe/she knows) for i in range(len(people)):#Take a person and make a decision to invite this person to the party or not #if this person should have at least five other people whom they know #and five other people whom they don't know,add this person into the array output . if(known[i]>=5 and (len(people)+1 -known[i]) >=5): output.append(people[i])#this array includes people who will ne inviteed to the party. return output #Standard form for people people=["Jane","Bill","Susan","Tom","Jim","Mary","Will","Mick","Rory","Lindsay", "Kate","Karen","Joe","Martha","Arthur","Taylor","Connor"] #standard form for pairs pairs=[("Jane","Bill"),("Jane","Susan"),("Jane","Tom"),("Jane","Jim"),("Jane","Will"),("Jane","Connor"), ("Bill","Kate"),("Bill","Susan"),("Bill","Martha"),("Bill","Arthur"),("Bill","Karen"), ("Susan","Will"),("Susan","Tom"),("Susan","Jim"),("Susan","Taylor"), ("Tom","Will"),("Tom","Rory"),("Tom","Kate"), ("Jim","Joe"), ("Mary","Rory"),("Mary","Kate"),("Mary","Lindsay"), ("Will","Kate"),("Will","Rory"), ("Mick","Rory"),("Mick","Kate"),("Mick","Connor"),("Mick","Arthur"),("Mick","Martha"), ("Rory","Kate"), ("Lindsay","Kate"), ("Karen","Martha"),("Karen","Arthur"), ("Joe","Martha"),("Joe","Taylor"),("Joe","Connor"),("Joe","Arthur"), ("Arthur","Connor") ] print(partyInvitees(people,pairs))
132877f639e5a0ca0ae3c78d5b930af3dc2e7236
XiancaiTian/Leetcode
/q88.py
921
3.78125
4
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ if m == 0: nums1[:n] = nums2 elif n == 0: nums1 else: j1, j2 = m-1, n-1 for i in range(m+n-1,-1,-1): # want to update nums1[i] if nums1[j1]>=nums2[j2]: nums1[i]=nums1[j1] j1-=1 else: nums1[i]=nums2[j2] j2-=1 if j1 <0: nums1[:i] = nums2[:j2+1] break elif j2<0: nums1[:i] = nums1[:j1+1] break # Note: what if input is empty list....
7b3bd0c249b8f4599732a6792c33aa6016dd73ae
PSFREITASUEA/padroes-de-projeto
/Line Up - Padroes/Flyweight/main.py
1,715
4.125
4
from abc import ABC, abstractmethod class Object(ABC): @abstractmethod def display(self): pass class Tree(Object): def __init__(self, x_cord, y_cord, age): self.x_cord = x_cord self.y_cord = y_cord self.age = age def get_x_cord(self): return self.x_cord def get_y_cord(self): return self.y_cord def get_age(self): return self.age def display(self): print(f'displaying tree {self.age} at {self.x_cord}/{self.y_cord}') class TreeManager: @property def tree_list(self) -> list[Tree]: return self._tree_list def __init__(self): self._tree_list = [] def get_tree(self, x_cord, y_cord, age): for i in range(len(self.tree_list)): if self.tree_list[i].get_x_cord() == x_cord and \ self.tree_list[i].get_y_cord() == y_cord and \ self.tree_list[i].get_age() == age: tree = self.tree_list[i] print(f'Found tree {age} at {x_cord}/{y_cord}') return self.add_tree(x_cord, y_cord, age) def add_tree(self, x_cord, y_cord, age): tree = Tree(x_cord, y_cord, age) self.tree_list.append(tree) print(f'Adding tree {age} at {x_cord}/{y_cord}') def display_all_trees(self): for i in range(len(self.tree_list)): self.tree_list[i].display() def main(): tree_manager = TreeManager() tree_manager.add_tree(10,10, 10) tree_manager.add_tree(9, 9, 9) tree_manager.get_tree(10, 10, 10) tree_manager.display_all_trees() if __name__ == "__main__": main()
b4ee969d73b69351044266531e345326397d51be
FabrizioFubelli/py-math-sequences
/fibonacci.py
1,101
3.765625
4
#!/usr/bin/env python2 """ Calculates the nth number of Fibonacci sequence Reference: https://github.com/Dvd848/CTFs/blob/master/2018_picoCTF/be-quick-or-be-dead-2.md """ from ctypes import * import numpy as np, sys np.seterr(all="ignore") class Memoize(object): def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): if args in self.cache: return self.cache[args] ret = self.func(*args) self.cache[args] = ret return ret @Memoize def fib(n): if n == 0: return np.uint32(0) elif n == 1: return np.uint32(1) return fib(n-2) + fib(n-1) def usage(): print("Usage: ./fibonacci.py <int> # Calculates the nth number of Fibonacci sequence") def main(): if len(sys.argv) != 2: usage() exit(1) try: requested_number = int(sys.argv[1]) # Es. 1067 => 781077913 except: usage() exit(2) for i in range(requested_number): fib(i) print(fib(requested_number)) exit(0) if __name__ == "__main__": main()
a1d40dc66340262213219edcfb6092f778d8583e
Yuhsuant1994/leetcode_history
/solutions/set_mismatch.py
977
3.828125
4
""" You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array. """ class Solution(object): def findErrorNums(self, nums): """ :type nums: List[int] :rtype: List[int] """ result = list() for i in range(len(nums)): # missing if i+1 not in nums: result = result + [i+1] # check duplicated if nums[i] in nums[i+1:]: result = [nums[i]] + result # stop if found if len(result) == 2: return result
36507b00b4c438782f262509518890af94c634a9
itsparth20/Data-structure-and-Algorithms
/Python/findsortestdist/findsortestdist.py
1,231
3.96875
4
# Q1. Given a string. Find distance of all characters from a target character. # For example, "Google", target character= 'g', then result will be [0,1,1,0,1,2] import sys def find_sortest_dist(input, ch): if input is None or input.strip() == '': return [] lower_ch = ch.strip().lower() lower_input = input.strip().lower() sum_from_left = find_total_count(lower_input, lower_ch) sum_from_right = find_total_count(lower_input[::-1], lower_ch)[::-1] arr = [] for i in range(0, len(sum_from_left)): arr.append(min(sum_from_left[i], sum_from_right[i])) print (arr) return arr def find_total_count(lower_input, lower_ch): count_from_left = [] if lower_input[0] == lower_ch: count_from_left.append(0) else: count_from_left.append(sys.maxsize) for x in range(1, len(lower_input)): if lower_input[x] == lower_ch: count_from_left.append(0) else: count_from_left.append(count_from_left[x-1]+1) return count_from_left actual_1 = find_sortest_dist('Google', 'g') expected_1 = [0, 1, 1, 0, 1, 2] if actual_1 != expected_1: raise ValueError("find_sortest_dist('Google', 'g') answer is wrong")
5e71b7765a962e8ef392cba580df8c74357916bd
bangoc123/PythonPractice
/theme.py
406
3.5625
4
# 3.5 from tkinter import * from Tkinter import * root = Tk() #create new window root.wm_title("Training X Team") label = Label(root,text="username") label.pack() nameInput = Entry(root) nameInput.pack() name = "Ngoc" password = "123" def login(): if nameInput.get() == name: print "Successfully" button = Button(root, text="Log in", command=login) button.pack() login() root.mainloop()
c642156dc16d9673ff5b1da0c8432711333c508f
theTijesuni/Simple-Stock-Calculator
/simple_stock_calculator.py
1,069
3.953125
4
#features coming soon # go back # quit # add GUI def stock_diff(): print("a. Calculate price difference") print("b. Increase by x percent\n") user_input = input("A or B:\n>..") while (user_input != "q"): if (user_input.lower() == "a" ): print("Press to \"go back\"\n") price1 = input("Price 1\n>..") price2 = input("Price 2\n>..") price1, price2 = float(price1), float(price2) output = ((price2 - price1)/ price1) * 100 message = ("Difference = %{}").format(output) print(message,"\n") elif(user_input.lower() == "b"): num = input("Increase what no?%:\n >..") margin = input("By how many percent?%:\n >..") num, margin = float(num), float(margin) output = margin/100 * num + num message = ("Value = %{}").format(output) print(message,"\n") else: print("Please choose A or B") stock_diff() stock_diff()
f1462bc609066c7ec29481e1a299798e59a5887a
djtorel/python-crash-course
/Chapter 08/Try It/Try07/album.py
1,158
4.71875
5
# Write a function called make_album() that builds a dictionary # describing a music album. The function should take in an artist name # and an album title, and it should return a dictionary containing these # two pieces of information. Use the function to make three dictionaries # representing different albums. Print each return value to show that # the dictionaries are storing the album information correctly. # Add an optional parameter to make_album() that allows you to store the # number of tracks on an album. If the calling line includes a value for # the number of tracks, add that value to the album’s dictionary. Make # at least one new function call that includes the number of tracks on # an album. def make_album(artist, title, num_tracks=''): """Returns a dictionary with information about an album""" album = {'artist': artist, 'title': title} if num_tracks: album['number of tracks'] = num_tracks return album print(make_album('NIN', 'Fragile')) print(make_album('Pink Floyd', 'Dark Side of the Moon')) print(make_album('foo', 'bar', 27)) print(make_album('bizz', 'bazz', 12))
d97d7c1be02b1cc8c921f6f68e45685160426bd9
tanasin-vivitvorn/platformx
/fullstack/test3.py
2,465
3.6875
4
import unittest import math #from memory_profiler import profile class Node: def __init__(self, value): self.value = value self.parent = None #@profile def setup(): nodes = [11] for i in range(1, 10): nodes.append(Node(i)) parent_value = int(math.floor(i/2)) if parent_value >= 1: nodes[i].parent = nodes[parent_value] return nodes #This solution use for finds LCA in O(n) time #using single traversal of Binary Tree and without extra storage for path arrays. @profile def lca(node1, node2): #if it has no parent then it is root node. #it no needs to do anything more just return the root. if node1.parent is None: return node1.value elif node2.parent is None: return node2.value #if they are equal then return any one of them #because each of them is LCA itself. if node1.value == node2.value: return node1.value #if they have same root then the root is LCA #but if it is not then we need to tracking from lowest node. #the lowest node is the node that has maximum value #example node1.value > node2.value that means node1 is in the same or lower level than node2 if node1.parent.value == node2.parent.value: return node1.parent.value elif node1.value > node2.value: return lca(node1.parent, node2) elif node1.value < node2.value: return lca(node1, node2.parent) nodes = setup() print "LCA(6, 7) = ", lca(nodes[6], nodes[7]) print "LCA(3, 7) = ", lca(nodes[3], nodes[7]) print "LCA(8, 5) = ", lca(nodes[8], nodes[5]) class TestNode(unittest.TestCase): def test(self): nodes = setup() # Test node setup self.assertEqual(nodes[9].value, 9) self.assertEqual(nodes[9].parent.value, 4) self.assertEqual(nodes[9].parent.parent.value, 2) self.assertEqual(nodes[9].parent.parent.parent.value, 1) self.assertIsNone(nodes[9].parent.parent.parent.parent) self.assertEqual(nodes[6].value, 6) self.assertEqual(nodes[6].parent.value, 3) self.assertEqual(nodes[6].parent.parent.value, 1) self.assertIsNone(nodes[6].parent.parent.parent) self.assertEqual(lca(nodes[9], nodes[1]), 1) self.assertEqual(lca(nodes[9], nodes[8]), 4) self.assertEqual(lca(nodes[6], nodes[7]), 3) self.assertEqual(lca(nodes[3], nodes[7]), 3) if __name__ == '__main__': unittest.main()
71d28d3efd2adc3003610b9ef5243e18b2fc9e71
turing4ever/codesnippets
/leetcode/1.two-sum.python3.py
376
3.53125
4
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ diff = {} for i in range(len(nums)): if (target - nums[i]) in diff: return [diff[target-nums[i]], i] elif nums[i] not in diff: diff[nums[i]] = i
e649cf77c3e51527e4dd863f3b80e1fe7fb180d7
kopair/code-python
/day-01-20190714/investment.py
314
3.953125
4
# -*- coding: utf-8 -*- amount = float(input('Enter a amount:')) inrate = float(input('Enter a inrate:')) period = int(input('Enter a period:')) value = 0 year = 1 while year <=period: value = amount + (amount * inrate) print('every year {} rate {:.2f}'.format(year,value)) amount = value year += 1
599a567eda2ab3dd22281a709dc093515a4e4975
YuriiKhomych/ITEA_course
/DarinaLeliuk/4_iterations/2.py
211
3.5625
4
series=[2, 3, 4, 5, 7, 11, 22] counteven=0 countodd=0 for myelement in series: if myelement % 2 != 0: counteven += 1 elif myelement % 2 == 0: countodd +=1 print(countodd) print(counteven)
2326b1b2192c04af5b35126f7e8a24b1c9392faf
okanbskn/ALP2-Uebungen
/U1/A1.py
110
3.515625
4
def sum(a): res = 0 for n in a: res += n return res print sum([11,11]) print sum([1,2,3,4,5,6,7,8,9,10])
93d7ba45ab2c5fae3e234d8f3afb8c67bbde7ebc
schehat/python_snippets
/default_parameters.py
511
4.03125
4
def append_number_wrong(num, numbers=[]): numbers.append(num) print(num) print(numbers) # behaves not like expected due to mutable parameteter # the function share the same list print("wrong:") append_number_wrong(1) append_number_wrong(2) # always use immutable data structure def append_number_correct(num, numbers=None): numbers = [] numbers.append(num) print(num) print(numbers) print("\ncorrect:") append_number_correct(1) append_number_correct(2)
dc97b214cbb5eda911b0d907710ce8cc167dfdcc
Lee-3-8/CodingTest-Study
/level2/압축/정한.py
1,126
3.5625
4
# 2018 KAKAO BLIND RECRUITMENT [3차] 압축 # chr, ord 을 이용해 아스키 코드 이용 # 뇌절 파티한 문제 (꼭 다시 풀자) def solution(msg): answer = [] indexing = dict() idx = 26 max_len = 1 for i in range(0, idx): indexing[i + 1] = f"{chr(ord('A')+i)}" i = 0 while i < len(msg): attach = "" for j in range(max_len, 0, -1): for key, value in indexing.items(): if msg[i : i + j] == value: answer.append(key) if i + j < len(msg): attach = msg[i + j] else: return answer break if attach != "": break idx += 1 indexing[idx] = f"{indexing[answer[-1]]+attach}" i += len(indexing[idx]) - 1 if max_len < len(indexing[idx]): max_len = len(indexing[idx]) return answer # msg = "KAKAO" # msg = "TOBEORNOTTOBEORTOBEORNOT" msg = "ABABABABABABABAB" print(solution(msg)) # 기댓값 [11, 1, 27, 15] # 알파벳 # print(f"{chr(ord('a')+1)}")
808bd73ed737ca5120b19ec47390c5768d8961fd
mrnglory/Programming-Linguistics
/1. Python/PL_SOL_04.py
965
3.859375
4
class Node: def __init__(self,data): self.left = None self.right = None self.data = data class Tree: def Preorder(self, root): if root: print(root.data) self.Preorder(root.left) self.Preorder(root.right) def Inorder(self, root): if root: self.Inorder(root.left) print(root.data) self.Inorder(root.right) def Postorder(self, root): if root: self.Postorder(root.left) self.Postorder(root.right) print(root.data) root = Node(15) root.left = Node(1) root.right = Node(37) root.left.left = Node(61) root.left.right = Node(26) root.right.left = Node(59) root.right.right = Node(48) tree = Tree() print('Preorder Traverse') print(tree.Preorder(root)) print('Inorder Traverse') print(tree.Inorder(root)) print('Postorder Traverse') print(tree.Postorder(root))
e0971fccc41eab35412f7c71c9b90f24e23a258d
wulinlw/leetcode_cn
/leetcode-vscode/147.对链表进行插入排序.py
2,564
3.921875
4
# # @lc app=leetcode.cn id=147 lang=python3 # # [147] 对链表进行插入排序 # # https://leetcode-cn.com/problems/insertion-sort-list/description/ # # algorithms # Medium (63.00%) # Likes: 136 # Dislikes: 0 # Total Accepted: 22.6K # Total Submissions: 35.7K # Testcase Example: '[4,2,1,3]' # # 对链表进行插入排序。 # # # 插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。 # 每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。 # # # # 插入排序算法: # # # 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。 # 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。 # 重复直到所有输入数据插入完为止。 # # # # # 示例 1: # # 输入: 4->2->1->3 # 输出: 1->2->3->4 # # # 示例 2: # # 输入: -1->5->3->4->0 # 输出: -1->0->3->4->5 # # # # @lc code=start # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def initlinklist(self, nums): head = ListNode(nums[0]) re = head for i in nums[1:]: re.next = ListNode(i) re = re.next return head def printlinklist(self, head): re = [] while head: re.append(head.val) head = head.next print(re) def insertionSortList(self, head: ListNode) -> ListNode: if not head:return None dummy = ListNode('-inf') dummy.next = head cur, nxt = head, head.next while nxt: if nxt.val>cur.val: cur = cur.next nxt = nxt.next else: cur.next = nxt.next p1, p2 = dummy, dummy.next while nxt.val > p2.val: p1 = p2 p2 = p2.next p1.next = nxt #p1->nxt->p2 nxt.next = p2 nxt = cur.next return dummy.next # 4,2,1,3 # p1 p2 # 4 2 1 3 # 4 1 3 cur.next = nxt.next # 2 p1.next = nxt # 2 4 1 3 nxt.next = p2 # @lc code=end nums = [4,2,1,3] o = Solution() head = o.initlinklist(nums) o.printlinklist(head) h = o.insertionSortList(head) o.printlinklist(h)
1ec11351a0fb272855ff4b0d7283916fb70c87de
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/prtnic017/mymath.py
347
3.828125
4
# Student Number: PRTNIC017 # Date: 4/13/14 def get_integer(message): n = input("Enter " + message + ":\n") while not n.isdigit(): n = input("Enter " + message + ":\n") return eval(n) def calc_factorial(value): factorial = 1 for i in range(1, value + 1): factorial *= i return factorial
7a7930b1e6c93caca2b4b4019aae559bd4cbeca7
MBagdal/Linguagem_Programacao
/Python/Marco/Registro com SQLite - Procedural/Exemplo1.py
2,931
3.6875
4
import sqlite3 import time tipo_ingresso = {'Vip': 70, 'Normal': 50,'Estudante': 25}; connection = sqlite3.connect('ExemplosPython.db') cursor = connection.cursor() def CreateTable(): cursor.execute('CREATE TABLE IF NOT EXISTS Clientes (id integer, nome_cliente text, tipo_ingresso text, valor_ingresso real, data_compra date)') def InsertData(id,nome_cliente, tipo_ingresso,Valor_ingresso, data_compra): cursor.execute('INSERT INTO Clientes (id,nome_cliente,tipo_ingresso,valor_ingresso, data_compra) VALUES (?,?,?,?,?)', (id,nome_cliente,tipo_ingresso,Valor_ingresso, data_compra)) connection.commit() def CadastrarCliente(): i = 0 date = time.strftime("%d-%m-%y") while True: nome_cliente = input('Digite o nome do cliente: ... s para voltar ao menu principal: ') if nome_cliente == 's': break else: tipo_ingresso_cliente = int(input('Digite o Tipo do ingresso: 1 - Vip, 2 - Normal, 3 - Estudante: ')) if tipo_ingresso_cliente == 1: InsertData(i,nome_cliente, "VIP",tipo_ingresso['Vip'],date) i = i + 1 elif tipo_ingresso_cliente == 2: InsertData(i,nome_cliente, "Normal",tipo_ingresso['Normal'],date) i = i + 1 elif tipo_ingresso_cliente == 3: InsertData(i,nome_cliente, "Estudante",tipo_ingresso['Estudante'],date) i = i + 1 def BuscarCliente(keyWord): sql = 'SELECT * FROM Clientes WHERE Clientes.nome_cliente = ? OR Clientes.tipo_ingresso = ? OR Clientes.valor_ingresso = ?' cursor.execute(sql, (keyWord,keyWord,keyWord,)) #Tambem pode ser usado desse jeito para verificar se tem dados Gravados no BD #data = cursor.fetchall() #if len(data) == 0: dados = cursor.fetchone() if dados is None: print('Usuario não encontrado em nosso sistema.') else: print("Nome do Cliente: ", dados[1] ," - Tipo do Ingresso: ", dados[2] ," - Valor do Ingresso: ", str(dados[3]) ," - Data da Reserva: ", str(dados[4])) return False def DeletarCliente(nome_cliente): sql = 'DELETE FROM Clientes WHERE Clientes.nome_cliente = ?' cursor.execute(sql,(nome_cliente,)) connection.commit() print('Usuario {} Deletado com sucesso'.format(nome_cliente)) def ReadAll(): sql = 'SELECT * FROM Clientes ' cursor.execute(sql) dados = cursor.fetchall() if len(dados) == 0: print('Ainda nao temos usuarios cadastrado no sistema.') else: for info in dados: print("Nome do Cliente: ", info[1] ," - Tipo do Ingresso: ", info[2] ," - Valor do Ingresso: ", info[3] ," - Data da Reserva: ", info[4]) while True: CreateTable() opc = int(input('Digite 1 - Cadastrar, 2 - Excluir, 3 - Procurar Cliente no sistema: - 4 - Buscar todos os clientes ')) if opc == 1: CadastrarCliente() elif opc == 2: deletar = input('Digite o nome do cliente para deletar: ') DeletarCliente(deletar) elif opc == 3: while True: buscar = input('Digite Nome do cliente, ou tipo de Ingresso ou seu Valor: ') BuscarCliente(buscar) elif opc == 4: ReadAll()
574d04a55201422a5386851eb21679531e775afd
Ayaz-75/Black_jack-Guessing_number-highest_bid-nested_dict
/grading_program_using_dictionary.py
492
3.671875
4
student_score = { "ayaz": 81, "wassi": 78, "Muzi": 99, "zahoor": 74, "asifil": 62 } student_grades = {} for student in student_score: score = student_score[student] if score >= 90: student_grades[student] = "Outstanding" elif score > 80: student_grades[student] = "Exceeds expectations" elif score > 70: student_grades[student] = "Acceptable" elif score < 70: student_grades[student] = "Fail" print(student_grades)
717a9b4c4ac6718b4e596128e1aaca2b6d04d715
Descent098/PYTH-101
/7. Extras/challenge.py
499
3.953125
4
""" =========== Challenge 1 ============= Below is a game in which you specify how many cookies there are at the beginning. on each 'turn' a random amount between 1-10 of cookies are removed. Once there are no cookies use an f-string to print if player 1 (an even number of turns) or player 2 (an odd number of turns) won. """ import random cookies = int(input("How many cookies?: ")) turns = 0 while cookies < 0: cookies -= random.randint(0,10) turns += 1
b6fc237f6996114eda218578d778a114aaeaa1c9
Luolingwei/LeetCode
/Heap/Q703_Kth Largest Element in a Stream.py
556
3.625
4
from heapq import * class KthLargest: def __init__(self, k: int, nums): heapify(nums) self.large,self.small=nums,[] self.k=k def add(self, val: int): heappush(self.small,-heappushpop(self.large,val)) while len(self.large)>self.k-1: heappush(self.small,-heappop(self.large)) return -self.small[0] # Your KthLargest object will be instantiated and called as such: obj = KthLargest(3, [4,5,8,2]) print(obj.add(3)) print(obj.add(5)) print(obj.add(10)) print(obj.add(9)) print(obj.add(4))
5257a95f81e1a2808fc39c039c9f2779d8189981
GSvensk/OpenKattis
/LowDifficulty/busnumbers.py
766
3.71875
4
def make_chain(bus_lines, total_buses, counter): print(bus_lines[counter], end="") while counter+2 < total_buses: if (bus_lines[counter+1] == bus_lines[counter]+1) & (bus_lines[counter+2] == bus_lines[counter]+2): counter += 1 else: break print("-" + str(bus_lines[counter+1]) + " ", end="") return counter+2 buses = int(input()) bus_numbers = list(map(int, input().split())) bus_numbers.sort() k = 0 while k < buses-2: if (bus_numbers[k+1] == bus_numbers[k] + 1) & (bus_numbers[k+2] == bus_numbers[k] + 2): k = make_chain(bus_numbers, buses, k) else: print(str(bus_numbers[k]) + " ", end="") k += 1 while k < buses: print(str(bus_numbers[k]) + " ", end="") k += 1
f1a7f3efefb242121d327e558919a8d1b3882921
tang1323/Ing_Interview
/tools/interview-two.py
5,925
4
4
# 41、举例说明异常模块中try except else finally的相关意义 # try..except..else没有捕获到异常,执行else语句 # try..except..finally不管是否捕获到异常,都执行finally语句 # try: # num = 100 # print(num) # except NameError as errorMsg: # print('产生错误了 :%s' % errorMsg) # else: # print('没有捕获到异常,则执行这个语句') # # # try: # num = 100 # print(num) # except NameError as errorMsg: # print('产生错误了:%s' % errorMsg) # finally: # print('不管是否捕获到异常, 都执行这个语句') # ------------------------------------------------------------------- # 43、举例说明zip()函数用法 # a = [1, 2] # b = [3, 4] # res = [i for i in zip(a, b)] # print(res) # print(type(res)) # # a = (1, 5) # b = (3, 4) # res = [i for i in zip(a, b)] # print(res) # print(type(res)) # # a = "ab" # b = "xyz" # res = [i for i in zip(a, b)] # print(res) # print(type(res)) # ------------------------------------------------------------------- # 44、a="张明 98分",用re.sub,将98替换为100 # import re # a = "张明 98分" # ret = re.sub(r"\d+", "100", a) # print(ret) # ------------------------------------------------------------------- # 45、写5条常用sql语句 # show databases; # show tables; # desc 表名 # select * from 表名 # delete from 表名 where id = 5 # update students set gender=0, hometown='北京' where id = 5 # ------------------------------------------------------------------- # 46、a="hello"和b="你好"编码成bytes类型 # encode是编码,decode是解码 # 只用encode的话,那就是bytes类型码 # 一个编码一个解码,就成字符串 # a = "hello".encode() # print(a) # # b = "你好".encode().decode() # print(b) # # print(type(a), type(b)) # ------------------------------------------------------------------- # 47、[1,2,3]+[4,5,6]的结果是多少? # a = [1, 2, 3] # b = [4, 5, 6] # res = a+b # print(res) # ------------------------------------------------------------------- # 48 .提高python运行效率的方法 # 1、使用生成器,因为可以节约大量内存 # # 2、循环代码优化,避免过多重复代码的执行 # # 3、核心模块用Cython PyPy等,提高效率 # # 4、多进程、多线程、协程 # # 5、多个if elif条件判断,可以把最有可能先发生的条件放到前面写,这样可以减少程序判断的次数,提高效率 # ------------------------------------------------------------------- # 49、简述mysql和redis区别 # redis: 内存型非关系数据库,数据保存在内存中,速度快 # # mysql:关系型数据库,数据保存在磁盘中,检索的话,会有一定的Io操作,访问速度相对慢 # ------------------------------------------------------------------- # 50、遇到bug如何处理 # 1、细节上的错误,通过print()打印,能执行到print()说明一般上面的代码没有问题,分段检测程序是否有问题,如果是js的话可以alert或console.log # # 2、如果涉及一些第三方框架,会去查官方文档或者一些技术博客。 # # 3、对于bug的管理与归类总结,一般测试将测试出的bug用teambin等bug管理工具进行记录,然后我们会一条一条进行修改,修改的过程也是理解业务逻辑和提高自己编程逻辑缜密性的方法,我也都会收藏做一些笔记记录。 # # 4、导包问题、城市定位多音字造成的显示错误问题 # ------------------------------------------------------------------- # 51、正则匹配,匹配日期2018-03-20 # import re # url = 'https://sycm.taobao.com/bda/tradinganaly/overview/get_summary.json?dateRange=2018-03-20%7C2018-03-20&dateType=recent1&device=1&token=ff25b109b&_=1521595613462' # result = re.findall(r"dateRange=(.*?)%7C(.*?)&", url) # print(result) """ (1)re.match用法是返回一个对象,要加上print(res1.group(1)) (2)re.findall是返回一个列表,里面包含很多东西,直接print(res1) """ # ------------------------------------------------------------------- # list=[2,3,5,4,9,6],从小到大排序,不许用sort,输出[2,3,4,5,6,9] # # 利用min()方法求出最小值,原列表删除最小值,新列表加入最小值,递归调用获取最小值的函数,反复操作 # list = [2, 3, 5, 4, 9, 6] # new_list = [] # def get_min(list): # # 获取列表最小值 # a = min(list) # # # 删除最小值 # list.remove(a) # # # 将最小值加入新列表 # new_list.append(a) # print(new_list) # # # # 保证最后列里面有值,递归调用获取最小值 # # # 直到所有值获取完, 并加入新列表返回 # if len(list) > 0: # get_min(list) # return new_list # # new_list = get_min(list) # print(new_list) # ------------------------------------------------------------------- # 53、写一个单列模式 # 因为创建对象时__new__方法执行,并且必须return # 返回实例化出来的对象所cls.__instance是否存在, # 不存在的话就创建对象,存在的话就返回该对象, # 来保证只有一个实例对象存在(单列),打印ID,值一样,说明 # 对象同一个 # class Singleton(object): # __instance = None # # def __new__(cls, age, name): # """ # 如果类属性__instance的值为None # 那么就创建一个对象,并且赋值为这个对象的引用, # 保证下次调用这个方法时 # 能够知道之前已经创建过对象了,这样就保证了只有一个对象 # """ # if not cls.__instance: # cls.__instance = object.__new__(cls) # print(cls.__instance) # return cls.__instance # # # a = Singleton(18, "dongGe") # b = Singleton(8, "dongGe") # # print(id(a)) # print(id(b)) # # a.age = 19 # print(b.age)
1d987a61e179ea7b51385d1ce4afdf2c0dcf142d
saravey2021/homework-week-11
/Homework week 11/thur1.py
394
4.25
4
def sumFromTo(startValue,endValue): sum = 0 for i in range(startValue , endValue+1): if endValue > startValue: sum = sum + i else: sum = sum + 0 return sum startValue=int(input("Start Value:")) endValue=int(input("End Value:")) print("The sum of number between"+str(startValue)+"and"+str(endValue)+"is:"+str(sumFromTo(startValue,endValue)))
573f10f82adc17f902e1af2d5c628d1897cc0565
bimri/learning-python
/chapter_34/raise-exceptions.py
1,725
4.3125
4
"Raising Exceptions" ''' the following two forms are equivalent—both raise an instance of the exception class named, but the first creates the instance implicitly: ''' raise IndexError # Class (instance created) raise IndexError() # Instance (created in statement) ''' We can also create the instance ahead of time—because the raise statement accepts any kind of object reference, the following two examples raise IndexError just like the prior two: ''' exc = IndexError() # Create instance ahead of time raise exc excs = [IndexError, TypeError] raise excs[0] ''' When an exception is raised, Python sends the raised instance along with the exception. If a try includes an except name as X: clause, the variable X will be assigned the instance provided in the raise: The as is optional in a try handler (if it’s omitted, the instance is simply not assigned to a name), but including it allows the handler to access both data in the instance and methods in the exception class. ''' try: ... except IndexError as X: # X assigned the raise instance object ... # model works the same for user-defined exceptions class MyExc(Exception): pass ... raise MyExc('spam') # Exception class with constructor args ... try: ... except MyExc as X: # Instance attributes in handler print(X.args) """ Regardless of how you name them, exceptions are always identified by class instance objects, and at most one is active at any given time. Once caught by an except clause anywhere in the program, an exception dies (i.e., won’t propagate to another try), unless it’s reraised by another raise statement or error. """
f76f2bf4ad107332e6bc9e134b42f88fb2c02ab4
kevokvr/PythonPractice
/Assignment3/Assignment3.py
2,993
4.40625
4
import unittest ''' Write a recursive method that takes 1) a string to find, 2) a string to replace the found string with, and 3) an initial string. Return the initial string with all the found strings replaced with the replacement string. You may not use loops or the built-in string methods except comparison, length, and slicing. Here is an outline. ''' ''' Description: Assignment 3 Author: Kevin Valenzuela # Version: 15+ tries Help received from: -https://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python -https://www.pythoncentral.io/cutting-and-slicing-strings-in-python/ -https://www.python-course.eu/recursive_functions.php -https://www.youtube.com/results?search_query=python+recursion Help provided to: Makda and I sat at the library and learned recursion with slide examples. Over the due weekend, we talked about what we were planning to do and our roadblocks. ''' def findandreplace(find, replace, string): ''' Replace all instances of find with replace in string. Recursive approach: If the string starts with find return replace and call findandreplace with the rest of the string else return the first character of the string and call findandreplace with the rest of the string ''' if not string: # Base cases up here return string elif not find: return string elif replace is None: return string # Base cases end else: string1 = string[:len(find)] # This make a string by slicing the original string by the lenght of find if string1 == find: # It helps because I don't need to iterate through each array slot return replace + findandreplace(find, replace, string[len(find):]) # this passes the remainder of the string else: return string[0] + findandreplace(find, replace, string[1:]) class TestFindAndReplace(unittest.TestCase): def test_all_none(self): self.assertEqual(findandreplace(None, None, None), None) def test_find_none(self): self.assertEqual(findandreplace(None, "a", "aabb"), "aabb") def test_find_empty(self): self.assertEqual(findandreplace("", "a", "aabb"), "aabb") def test_replace_none(self): self.assertEqual(findandreplace("a", None, "aabb"), "aabb") def test_string_none(self): self.assertEqual(findandreplace("a", "b", None), None) def test_simple(self): self.assertEqual(findandreplace("a", "b", "aabb"), "bbbb") def test_remove(self): self.assertEqual(findandreplace(" ", "", " a abb"), "aabb") def test_anotherone(self): self.assertEqual(findandreplace("dog", "cat", "My dog is cool"), "My cat is cool") def test_gettysburg(self): self.assertEqual(findandreplace("Four score", "Twenty", \ "Four score and seven years ago"), "Twenty and seven years ago") if __name__ == '__main__': unittest.main()
1eca59a003b42e6f286acd2eac74d6be07592bba
ruzguz/python-stuff
/7-loops/numbers.py
785
4.3125
4
import random def run(): number_found = False # generating random range from user input min = int(input('Introduce the min value: ')) max = int(input('Introduce the max value: ')) while max <= min: max = int(input('max value have to be greater than min value: ')) random_number = random.randint(min, max) while not number_found: number = int(input('Try: ')) if number == random_number: print('Congratulation, you rock!!!') number_found = True elif number < min or number > max: print('number out of range >:(') elif number > random_number: print('<') elif number < random_number: print('>') if __name__ == '__main__': run()
b2ea5410416669ddf83d801789bf4c4d19ece798
acmduzhuo/python
/Python_homework_2019-11-15/第六章/课后习题/6.2.py
1,094
3.921875
4
class Vecter3: def __init__(self, x=0, y=0, z=0): self.X = x self.Y = y self.Z = z def __add__(self, n): r = Vecter3() r.X = self.X + n.X r.Y = self.Y + n.Y r.Z = self.Z + n.Z return r def __sub__(self, n): r = Vecter3() r.X = self.X - n.X r.Y = self.Y - n.Y r.Z = self.Z - n.Z return r def __mul__(self, n): r = Vecter3() r.X = self.X * n r.Y = self.Y * n r.Z = self.Z * n return r def __truediv__(self, n): r = Vecter3() r.X = self.X / n r.Y = self.Y / n r.Z = self.Z / n return r def __floordiv__(self, n): r = Vecter3() r.X = self.X // n r.Y = self.Y // n r.Z = self.Z // n return r def show(self): print((self.X,self.Y,self.Z)) v1 = Vecter3(1,2,3) v2 = Vecter3(4,5,6) v3 = v1+v2 v3.show() v4 = v1-v2 v4.show() v5 = v1*3 v5.show() v6 = v1/2 v6.show()
31879e7f1edfb15544d3274e0c20bf0f02366d48
AnatoliyChabanenko/lesson2
/lesson6_2.py
198
3.65625
4
#первая v= [1 , 2, 3, 4,5,1 ,3 ,5, 7 ,7] k=[] for i in range (len(v)): k.append(i) dicor = dict(zip(v, k)) print(dicor) # последняя #d = {a: a ** 2 for a in range(1,11)} #print(d)
4e980d0e51b15fcfc69e71ebb8e53e10b474a1ca
iceljc/Green-Taxi-NYC-Analysis
/code/question1.py
959
3.71875
4
""" This code solves for Question 1 """ import pandas as pd import numpy as np import urllib.request import os, ssl # fix the error when using urllib.request.urlretrieve if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context # Download the Trip Record Data print("######################## Downloading data... #######################") url = 'https://s3.amazonaws.com/nyc-tlc/trip+data/green_tripdata_2015-09.csv' filename = '/Users/lujicheng/Desktop/capitalone/green_tripdata_2015-09.csv' urllib.request.urlretrieve(url, filename) # read the data green_data = pd.read_csv("green_tripdata_2015-09.csv") print('Green Taxi data size: ') print('Number of rows:', green_data.index.size) print('Number of columns:', green_data.columns.size) print("########################## Done ! ###################################") print('')
f2056ff46ce6e38c3b6ca553bbdec7f59d60b198
vtsartas/ejpython
/ejpy/ejElenaPY/28_hoja-VI-5_nota-ponderada-60-40.py
716
3.953125
4
# Ejercicio 28 - Hoja VI (5) - Indicar la nota ponderada según el criterio dado # (parte teórica 60%, práctica 40%) de cada uno de un número determinado de alumnos numalumnos=int(input("Introduce el número total de alumnos:\n")) print("Usa el punto '.' para los decimales") for contador in range(1,numalumnos+1): print(f"\nDatos del alumno número {contador} de {numalumnos}:") teorica=float(input("- Introduce la nota de la parte teórica: ")) practica=float(input("- Introduce la nota de la parte practica: ")) nota=(teorica*60/100)+(practica*40/100) print(f"La nota final del alumno número {contador} es {nota:.2f}.\n") print("Ya se han calculado todas las notas.")
b1a1d4dc8c091c5263b7daa270c1019fc7775bfd
alejo8591/dmk-django
/lab2/lab2_8.py
402
3.671875
4
# -*- coding: utf-8 -*- class A(object): def __init_(self): print("A") super(A, self).__init__() class B(A): def __init__(self): print("B") super(B, self).__init__() class C(A): def __init__(self): print("C") super(C, self).__init__() class D(C, B): def __init__(self): print("D") super(D, self).__init__() print("__mro__:", [x.__name__ for x in D.__mro__]) instance = D()
9725311d82d1ad171b26f12fa0fa5b3377a628a7
yuweichen1008/leetcode-1
/222_CountComplete/222_CountComplete2.py
610
3.546875
4
class Solution(object): def countNodes(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 node=root depth=0 while node: node=node.left depth+=1 num=(1<<depth-1) -1 level=depth-2 while level>-1: node=root.left for i in range(level): node=node.right if not node: root=root.left else: num+=1<<level root=root.right level-=1 if root: num+=1 return num
23ac644229e19ab1d030a2da559641cf53d263fc
morluna/Elements-of-Software-Design
/Assignment 1/Bowling.py
3,038
3.71875
4
# File: Bowling.py # Description: Program that reads a file with bowling scores and prints a scoreboard for each game # Student's Name: Marcos J. Ortiz # Student's UT EID: mjo579 # Course Name: CS 313E # Unique Number: 51320 # # Date Created: September 4, 2016 # Date Last Modified: September 8, 2016 def isstrike(val): return val == 10 def isspare(val): return val == "/" def iszero(val): return val == 0 def main(): #Open file for reading in_file = open("./scores.txt", "r") #Read line by line for line in in_file: #Declare variables score = 0 frame_scores = [] frames = 1 toss = 0 frame = 1 #Remove new line values and make a list of numbers line = line.strip() line = line.split(" ") toss_scores = line[:] #Convert char to int for element in range(len(line)): if line[element] == "-": line[element] = 0 elif line[element] == "X": line[element] = 10 elif line[element] == "/": continue else: line[element] = int(line[element]) #Iterate through each line for x in range(len(line)): ball = line[x] if (len(line) - 3 <= x) and (frame >= 10): toss += 1 if isspare(ball): score += (10 - line[x-1]) else: score += ball continue elif isstrike(ball): toss += 2 score += ball score += line[x+1] if isspare(line[x+2]): score += (10 - line[x+1]) else: score += line[x+2] elif isspare(ball): toss += 1 score += (10 - line[x-1]) score += line[x+1] else: toss += 1 score += ball #Toss represents balls "tossed" #Usually for each element, toss increases by 1 #With strikes it increases by 2 #This snippet will create a new frame everytime there is two tosses if toss % 2 == 0: frame += 1 frame_scores.append(score) #This snippet will append the final score to the frame_score list if toss <= 21: frame += 1 frame_scores.append(score) #Print scoreboard for each game print(" 1 2 3 4 5 6 7 8 9 10 ") print("+---+---+---+---+---+---+---+---+---+-----+") final_frame = 0 j = 0 while j <= (len(toss_scores) - 2): ball1 = toss_scores[j] if final_frame >= 9: ball2 = toss_scores[j + 1] last_ball = toss_scores[len(toss_scores) - 1] if last_ball is not None and (last_ball != ball2 or last_ball == "X"): print("|{:} {:} {:}|".format(ball1, ball2, last_ball), end = "") else: print("|{:} {:} |".format(ball1, ball2), end = "") j+=1 break elif ball1 == "X": print("|{:} ".format(ball1), end = "") final_frame += 1 j += 1 else: ball2 = toss_scores[j + 1] print("|{:} {:}".format(ball1, ball2), end = "") j+=2 final_frame += 1 print() for i in range(len(frame_scores)): if i == 9: print("|{:5d}|".format(frame_scores[i]), end = "") else: print("|{:3d}".format(frame_scores[i]), end = "") print() print("+---+---+---+---+---+---+---+---+---+-----+") print("\n") main()
85522c222a63b8236b0af9e93404e384e89acb3a
voodoopeople42/Vproject
/phonebook1.py
2,400
4.03125
4
contacts = ( {"Имя": "Игорь", "Номер": "094-456-72-89"}, {"Имя": "Виктор", "Номер": "092-664-52-88"}, {"Имя": "Сергей", "Номер": "089-435-23-23"}, ) FORMAT_STR = '{:<15} {:>12}' def list(contacts): print(FORMAT_STR.format("Имя", "Номер")) for contact in contacts: print(FORMAT_STR.format( contact ("Имя"), contact("Номер") )) def find(contacts): input (print("Введите имя контакта: ")) for contact in contacts: if contact ("Имя") == Имя: print(FORMAT_STR.format( contact ("Имя"), contact("Номер") )) break else: print("Контакт не найден") def delete(contacts): input (print("Введите контакт: ")) for contact in contacts: if contact ("Имя") == Имя: print("Вы действительно хотите удалить контакт? %s (Да/Нет)?: " %Имя) name_del = input("> ") if name_del == "Да": contacts.remove(contact) print("Контакт успешно удален!") def add(contacts): input (print("Введите имя контакта: ")) input (print("Веедите номер телефона: ")) new_contact = ( "Имя", "Номер" ) contact.append(new_contact) print("Контакт успешно сохранен!") print("___Телефонная книга___") print("""Что бы вы хотели?: * Список (Выводит список контактов) * Найти (Находит нужный контакт) * Добавить (Добавляет новый контакт) * Удалить (Удаляет выбранный контакт) * Изменить (Изменяет выбранный контакт) * Выход """) while True: print("\nВведите команду: ") command = input('> ') if command == 'Список': list(contacts) elif command == 'Найти': find(contacts) elif command == 'Добавить': add(contacts) elif command == 'Удалить': delete(contacts) elif command == 'Изменить': edit(contacts) elif command == 'Выход': break else: print("Неизвестная команда. \n(Возможно введена команда с маленькой буквы)")
cd854b7b0f06008e0b78456083efd9f828436254
eduardodcs/python-basico
/01comissao.py
363
3.75
4
print("Cálculo de salário com comissão (6%)") salarioFixo = float(input("Digite o salário do vendedor: ")) vendas = float(input("Digite o total vendido no mês: ")) vComissao = vendas * 0.06 salarioMes = salarioFixo + vComissao print("O vendedor receberá {:.2f} de salário mais {:.2f} de comissão. Total {:.2f}".format(salarioFixo, vComissao, salarioMes))
9957e509bf209b52e7e34de8b4ceed7cf997f858
ThoPhD/InterviewTests
/super.py
1,074
4
4
class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width def what_am_i(self): return 'Rectangle' class Square(Rectangle): def __init__(self, length): super().__init__(length, length) def what_am_i(self): return 'Square' class Cube(Square): def surface_area(self): face_area = self.area() return face_area * 6 def volume(self): face_area = super().area() return face_area * self.length def what_am_i(self): return 'Cube' def family_tree(self): return self.what_am_i() + ' child of ' + super(Cube, self).what_am_i() def family_tree_2(self): return self.what_am_i() + ' nephew of ' + super(Square, self).what_am_i() if __name__ == "__main__": c = Cube(3) print(c.surface_area()) print(c.volume()) print(c.what_am_i()) print(c.family_tree_2())
5ab8e34ed5ad974ecfb36c851ac0a1df38555260
Platforuma/Beginner-s_Python_Codes
/10_Functions/17_Function--Lambda-operators.py
478
4.21875
4
''' Create lambda functions for add, sub, mult and div ''' add = lambda num1, num2: num1 + num2 dif = lambda num1, num2: num1 - num2 mul = lambda num1, num2: num1 * num2 div = lambda num1, num2: num1 / num2 print("Sum :", add(9,3)) print("Difference :", dif(9,3)) print("Product :", mul(9,3)) print("Division :", div(9,3)) print("Sum :", add(232,12)) print("Difference :", dif(100,10)) print("Product :", mul(50,63)) print("Division :", div(789654,2542))
4920eee4c800f21553385e4fe64490ee4cae3cbf
munniomer/StackOverflow-API
/app/validators/validators.py
1,009
3.578125
4
"""Validators Module""" import re from app.api.v1.models.users_model import users class Validators(): """Validators Class""" def check_email(self, email): """Method for checking if user email exist""" user = [user for user in users if user['email'] == email] if user: return True return False def check_username(self, username): """Method for checking if username exist""" user = [user for user in users if user['username'] == username] if user: return True return False def valid_email(self, email): """ valid email """ regex = "^[\w]+[\d]?@[\w]+\.[\w]+$" return re.match(regex, email) def valid_name(self, name): """validate username""" regex = "^[a-zA-Z]{3,}$" return re.match(regex, name) def valid_password(self, password): """ valid password """ regex = "^[a-zA-Z0-9@_+-.]{3,}$" return re.match(regex, password)
6e1f9570281f331621c56e6720a65f61fae7c772
gdh756462786/Leetcode_by_python
/Array/Shuffle an Array.py
1,360
4.375
4
# coding: utf-8 ''' Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle(); ''' ''' 伪代码如下: for (i = 0 to nums.length) swap(nums[randint(0, i)], nums[i]) ''' import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type size: int """ self.nums = nums[:] self.base = nums[:] def reset(self): """ Resets the array to its original configuration and return it. :rtype: List[int] """ self.nums[:] = self.base return self.nums def shuffle(self): """ Returns a random shuffling of the array. :rtype: List[int] """ for x in range(len(self.nums)): y = random.randint(0, x) self.nums[x], self.nums[y] = self.nums[y], self.nums[x] return self.nums nums = [1,2,3] obj = Solution(nums) param_1 = obj.shuffle() print param_1 # param_2 = obj.reset()
5b3ce34d4f5aefc21f37e186e6121ab95e2b521a
dez-gm/practica-fundamentos-python
/segundapractica.py
633
4.125
4
# Imprimir tu nombre # cadena de caracteres # nombre = input("Introduce tu nombre: ") # print(f"Hola {nombre}") # entero edad = 25 # flotante - decimales altura = 1.75 # convertir a flotante edadString = str(edad) print(edad + edad) print(edadString + edadString) print(type(edad)) tuEdad = input("Intorduce tu edad: ") tuEdad = int(tuEdad) #Estructura de control IF if tuEdad >= 18 and tuEdad < 100: print("Eres mayor de edad") elif tuEdad >= 100: print("¿Eres inmortal?") elif tuEdad <= 0: print("No existes") else: print("Eres menor de edad") #Estructura de control FOR for i in range(0, 10): print(i)
66ba13c1a092d5389c8e576f096fb3fddb6f152e
Marcelo8173/phyton-fundamentos
/lacoDeRepeticao.py
441
4.25
4
for n1 in range(1,6): print(n1) # colocando um step for n2 in range(5,0,-1): print(n2) # for com soma print("\nSoma") soma = 0 for n3 in range(0,6): soma = soma + n3 print(soma) # string print("\nString") palavra = "marcelo" for letra in palavra: print(letra) # while print("\nWhile") numero = 1 while numero < 6: print(numero) numero += 1 soma = 0 n1 = 1 while n1 < 6: soma += n1 n1 += 1 print(soma)
f0bdbc292ed1150d28cebed0bc1cc39eb5485bc2
ZhuJiahui/Text-Categorizer
/textcat.py
8,846
3.734375
4
#Text Categorization Program for NLP #Ramon Sandoval import re, os, string, math, operator trainListName = raw_input("Please enter training data list name: ") testListName = raw_input("Please enter testing data list name: ") resultName = raw_input("Please enter output file: ") #Default files if nothing is entered if not trainListName: trainListName = 'corpus1_train.labels' if not testListName: testListName = 'corpus1_test.list' if not resultName: resultName = 'result.txt' trainList = open(trainListName, 'r') testList = open(testListName, 'r') result = open(resultName, 'w') #Only valid characters in a word are lowercase letters, all words processed into lowercase beforehand validChar = set(string.ascii_lowercase) #List of words so common they won't offer useful information in categorization stoplist = ["a", "about", "above", "above", "across", "after", "afterwards", "again", "against", "all", "almost", "alone", "along", "already", "also","although","always","am","among", "amongst", "amoungst", "amount", "an", "and", "another", "any","anyhow","anyone", "anything","anyway", "anywhere", "are", "around", "as", "at", "back", "be","became", "because","become","becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "bill", "both", "bottom","but", "by", "call", "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de", "describe", "detail", "do", "done", "down", "due", "during", "each", "eg", "eight", "either", "eleven","else", "elsewhere", "empty", "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few", "fifteen", "fify", "fill", "find", "fire", "first", "five", "for", "former", "formerly", "forty", "found", "four", "from", "front", "full", "further", "get", "give", "go", "had", "has", "hasnt", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "hundred", "ie", "if", "in", "inc", "indeed", "interest", "into", "is", "it", "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd", "made", "many", "may", "me", "meanwhile", "might", "mill", "mine", "more", "moreover", "most", "mostly", "move", "much", "must", "my", "myself", "name", "namely", "neither", "never", "nevertheless", "next", "nine", "no", "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves", "out", "over", "own","part", "per", "perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed", "seeming", "seems", "serious", "several", "she", "should", "show", "side", "since", "sincere", "six", "sixty", "so", "some", "somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "system", "take", "ten", "than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "thereupon", "these", "they", "thickv", "thin", "third", "this", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", "twelve", "twenty", "two", "un", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what", "whatever", "when", "whence", "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "whoever", "whole", "whom", "whose", "why", "will", "with", "within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves", "the"] allWords = {} #Dictionary of all words in training set and their frequency currTestDoc = {} #Dictionary of all words in current testing document and their frequency numOfAllWords = 0 #Number of all words, including their repitions, in training set numOfTerms = 0 #Number of all unique terms in training set cats = {} #List of all categories probWordCat = {} #Logarithmic probabilities of a word given a category docCatProb = {} #Logarithmic probabilites that document is in a specific category probCat = {} #Logarithmic probability of a category catFiles = {} #List of all category files, each file written with words and frequencies zeroProbs = {} #Logarithmic probabilities given to words that have zero probablities in a category WEIGHT = 5 #Weight of tokens in comparison to zero-probability tokens. One token is given WEIGHT+1 per frequency than other tokens allWordsFile = open('allWords.txt', 'w') ######################definitely fo real############################## #Find number of words in a dictionary array def numOfWords(someDict): x = someDict.values() return sum(x) #Remove capitalization/punctuation from tokens def cleanWord(word): word = word.lower() li = list(word) li = [x for x in li if x in validChar] word = "".join(li) return word #Add word to dictionaries def addWord(word, catName,mode): word = cleanWord(word) if not word: return 0 if word in stoplist: return 0 if mode is 'train': if word not in allWords: allWords[word] = WEIGHT else: allWords[word] += WEIGHT if word not in cats[catName]: cats[catName][word] = WEIGHT else: cats[catName][word] += WEIGHT else: if word not in allWords: return 0 if word not in currTestDoc: currTestDoc[word] = WEIGHT else: currTestDoc[word] += WEIGHT return 1 #Open a document and process it def whatsUpDoc(docName, catName, mode): doc = open(docName, 'r') while 1: text = doc.readline() if not text: break textTokens = text.split() if textTokens: for word in textTokens: addWord(word,catName,mode) #Train program def trainingMontage(): #Loop to open documents in training list and process them while 1: fileAndLabel = trainList.readline() if not fileAndLabel: break tokens = fileAndLabel.split() if tokens[1] not in cats: cats[tokens[1]] = {} catFiles[tokens[1]] = open(tokens[1] + ".txt", 'w') whatsUpDoc(tokens[0], tokens[1], 'train') #Find number of all words and all unique terms in training data numOfAllWords = numOfWords(allWords) numOfTerms = len(allWords) #Write to file on all words allWordsFile.write("Total words: " + str(numOfAllWords) + '\n') allWordsFile.write("Total unique terms: " + str(numOfTerms) + '\n') for word, num in allWords.items(): allWordsFile.write(word + ": " + str(num) + '\n') #Process word and frequency data for each category for catName, catWords in cats.items(): #Find number of words in a specific category numOfCatWords = numOfWords(catWords) #Calculate logarithmic zero probabilites, using Laplace smoothing zeroProbs[catName] = math.log(1) - math.log(numOfCatWords + numOfTerms) catFiles[catName].write("Total words: " + str(numOfCatWords) + '\n') #Find logarithmic probabilites of each category, taking into account Laplace smoothing probCat[catName] = math.log(numOfCatWords + numOfTerms)- math.log(numOfAllWords + numOfTerms) probWordCat[catName] = {} docCatProb[catName] = 0 #Find logarithmic conditional probabilties of a word in a given category, with Laplace smoothing for word, num in catWords.items(): wordprob = math.log(num + 1) - math.log(numOfCatWords + numOfTerms) probWordCat[catName][word] = wordprob catFiles[catName].write(word + ": " + str(num) + ", " + str(wordprob) + '\n') #Use naive Bayes approach def baseOfKnives(): #Start calculating log probabilites of a category given document words with log probability of category for catName, catProb in probCat.items(): docCatProb[catName] = catProb #Add log conditional probabilites of word in given category for all words in document for word, num in currTestDoc.items(): for catName in docCatProb.keys(): if word in probWordCat[catName]: docCatProb[catName] += probWordCat[catName][word] #+ math.log(num) else: docCatProb[catName] += zeroProbs[catName] #return category with highest probability return max(docCatProb, key = docCatProb.get) #Test program def testYourMight(): while 1: testFile = testList.readline() if not testFile: break tokens = testFile.split() currTestDoc.clear() whatsUpDoc(tokens[0], 'blah', 'test') result.write(tokens[0] + " " + baseOfKnives() + '\n') #Train then test program def wordsWordsWords(): trainingMontage() testYourMight() ##################main########################################## wordsWordsWords()
4b3f541e0fb7577e479e9dcab57ef1cca242636b
gupongelupe/ExerciciosFeitosPython
/ex057.py
276
4.03125
4
sexo = str(input('Digite seu sexo: [M/F] ')).upper() while sexo != 'M' and sexo!= 'F': sexo = str(input('Por favor digite novamente [M/F] ')).upper() if sexo == 'M': print('És macho my amigo!') elif sexo == 'F': print('És Moça my manita!')
225fc7da43f46e59685b9b88e9452a2407c58163
thinkreed/lc.py
/algo/first/p287_find_the_duplicate_number.py
502
3.53125
4
class Solution: def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ start = 1 end = len(nums) - 1 while start < end: middle = start + (end - start) // 2 count = 0 for num in nums: if num <= middle: count += 1 if count <= middle: start = middle + 1 else: end = middle return start
229628f40af614034e0eb9d04181f1f86d6ebe3f
w51w/python
/0914_자료구조/중첩리스트.py
216
3.984375
4
a=['a','b','c'] n=[1,2,3] x=[a,n] print(x) print(x[0]) print(x[0][1]) list2d= [[3,1,2],[1,5,2,6,3,8]] print(list2d) list2d[1].sort(); print(list2d) list2d[0].sort(); print(list2d) list2d[1].reverse(); print(list2d);
9ba9402b5e4cbeaaa0d125fc0b1d5a90bee4e868
ataias/Online-Judge-Submissions
/uri/1113.py
292
3.78125
4
#!/usr/bin/env python3 def main(): X, Y = 0, 1 while X != Y: X, Y = [int(x) for x in input().split()] if X == Y: break; if X > Y: print("Decrescente") else: print("Crescente") if __name__ == '__main__': main()
bc0f9b830d3d7f98ed2ebffa2923af8cf10f7e0b
NikolasMoatsos/Algo-Assignments
/count_fixed_polyominoes.py
2,501
3.625
4
import sys,pprint # The class with the "different polyomino" counter. class Counter: def __init__(self): self.count = 0 # Methods for add and return. def AddOne(self): self.count += 1 def ValueOf(self): return self.count # This checks if "i" is a neighbor of the parts of "p", except "u". def Neighbors(i,p): f = False for j in p[:-1]: if i in g[j]: f = True break return f # The method with the algorithm for the count of fixed polyominoes. def CountFixedPolyominoes(g,untried,n,p,c): while untried: u = untried.pop() p.append(u) if len(p) == n: c.AddOne() else: new_neighbors = [] for i in g[u]: if i not in untried and i not in p and not Neighbors(i,p) : new_neighbors.append(i) new_untried = [] new_untried.extend(untried) new_untried.extend(new_neighbors) CountFixedPolyominoes(g,new_untried,n,p,c) p.remove(u) return c.ValueOf() # This creates the graph. def CreateGraph(n): g = {} for x in range(-(n - 2),n): for y in range(0,n): if (abs(x) + abs(y)) < n: if (y > 0 or (y == 0 and x >= 0)): g[(x,y)] = [] # Check and append the neighbors of each node. if (abs(x+1) + abs(y)) < n and (y > 0 or (y == 0 and x+1 >= 0)): g[(x,y)].append((x+1,y)) if (abs(x) + abs(y+1)) < n and (y+1 > 0 or (y+1 == 0 and x >= 0)): g[(x,y)].append((x,y+1)) if (abs(x-1) + abs(y)) < n and (y > 0 or (y == 0 and x-1 >= 0)): g[(x,y)].append((x-1,y)) if (abs(x) + abs(y-1)) < n and (y-1 > 0 or (y-1 == 0 and x >= 0)): g[(x,y)].append((x,y-1)) else: break return g print_g = False # Check the command line arguments. if sys.argv[1] == "-p": print_g = True n = int(sys.argv[2]) else: n = int(sys.argv[1]) # Create the graph. g = CreateGraph(n) # Check and print the graph. if print_g: pprint.pprint(g) # Initialize the parameters of the algorithm. untried = [(0,0)] p = [] c = Counter() # Run the algorithm and print the result. print(CountFixedPolyominoes(g,untried,n,p,c))
fafa73aff5cfc4b1974d3ea83c367ba0edbad403
Ryuya1995/leetcode
/q58_Length_of_Last_Word.py
424
3.625
4
class Solution: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ s = s.split() return len(s[-1]) def lengthOfLastWord1(self, s): length = 0 tail = len(s) - 1 while tail >= 0 and s[tail] == ' ': tail -= 1 while tail >= 0 and s[tail] != ' ': length += 1 tail -= 1 return length
41e9e67fc7477020d0842243e3c7ae0c71e764fe
matheusbernat/GitRep
/Tentor/tenta2015_1.py
3,786
3.625
4
################################################ # TENTA 2015, 1 ################################################ # FACIT P UPPGIFTERNA JAG INTE LSTE: # Uppgift 4 (komma p vettiga namn, return lista med alla mjliga namn def combos_facit(word): n = len(word) res = [] for left in range(1, n-2+1): for right in range(1, n-left-1+1): res.append(word[:left]+word[-right:]) return res # Uppgift 5 (GRAFUPPGIFTEN! Return vilka noder man skulle komma fram till) def locations_facit(g, start, steps): if start not in g: return [] elif steps <= 0: return [start] else: res = [] for d in g[start]: new = locations(g, d, steps-1) for e in new: if e not in res: res.append(e) return res ################################################################ # Genomgngslsning i brjan, 5 min # UPPGIFT 1, 20 min def count_similar(str_1, str_2): """ Counts how many letters are simliar in two equal-sized strings """ similar = 0 for i in range(len(str_1)): if str_1[i] == str_2[i]: similar += 1 return similar def check_alike(str_1, str_2): """ Checks whether the first string is alike the second one """ def help_fn(str_1, str_2): if not str_1 or not str_2: return 0 elif str_1[0] == str_2[0]: return help_fn(str_1[1:], str_2[1:]) elif str_1[0] != str_2[0]: return 1 + help_fn(str_1, str_2[1:]) not_alike = help_fn(str_1, str_2) return not_alike < 2 def close_enough(str_1, str_2): if len(str_1) == len(str_2): return len(str_1) - count_similar(str_1, str_2) <= 1 elif len(str_1) < len(str_2): return check_alike(str_1, str_2) else: return check_alike(str_2, str_1) # UPPGIFT 2, 20 min def uniq_r(seq): if not seq: return [] elif len(seq) == 1 or seq[0] != seq[1]: return [seq[0]] + uniq_r(seq[1:]) elif seq[0] == seq[1]: return uniq_r(seq[1:]) def uniq_i(seq): final_seq = [seq[0]] for i in range(len(seq) - 1): if seq[i] != final_seq[-1]: final_seq.append(seq[i]) return final_seq # UPPGIFT 3, 30 min def gen_find(seq, func, underlist): """ Checks whether an element in a given list fulfills the functions req """ if not seq: return False if underlist == True: if isinstance(seq[0], list): return gen_find(seq[0], func, underlist) or \ gen_find(seq[1:], func, underlist) if func(seq[0]): return True else: return gen_find(seq[1:], func, underlist) def where(seq, elem): """ Locates position of an element in a given list """ if not gen_find(seq, (lambda x: x == elem), True): return "no" elif gen_find(seq, (lambda x: x == elem), False): return "top" else: return "deep" # UPPGIFT 4, 40 min """ def combos(string): #Generates all possible combinations of words by taking letters from mid """ # UPPGIFT 5, 50 min g = {'a':('d'), 'b':('a'), 'c':('b', 'd', 'f'), 'd':('h'), 'e':(), 'f':('e', 'g'), 'g':('h'), 'h':('f', 'i'), 'i':('j'), 'j':('h')} def locations(graph, start, steps): """ Returns a list of nodes that can be reached leading out from our given """ if start not in graph: return [] elif steps <= 0: return [start] else: res = [] for kids in graph[start]: new = locations(graph, kids, steps-1) for a in new: if a not in res: res.append(a) return res # UPPGIFT 6, 60 min # Lste uppgift A # TOTALT: 220 min, 80 min kvar fr genomgng
a8fd983b8ecc87f5faf968883647b3fb1336dbd0
tspolli/exercises
/temometro.py
424
4.21875
4
''' Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius. C = (5 * (F-32) / 9). ''' print("** CALCULO DE FARENHEIT PARA CELSIUS **") print("Informe a temperatura em graus Farenheit: ") graus_farenheit = int(input()) graus_celsius = 5*(graus_farenheit-32)/9 print("Graus Celsius: ", graus_celsius) print("Pressione enter para finalizar...") enter = str(input())
48edcc4cb67720366140929875c616baffee0ffb
Illugi317/gagnaskipan
/stack_queue/stack.py
930
3.703125
4
class Stack: def __init__(self): self.size = 0 self.capacity = 4 self.array = [0] * self.capacity def __str__(self): ret_str = "" for x in range(self.size): ret_str += f"{self.array[x]}, " return ret_str[:2] def push(self, value): if self.size == self.capacity: self.array = self.resize() self.array[self.size] = value self.size += 1 def pop(self): self.size -= 1 return self.array[self.size] def resize(self): self.capacity *= 2 new_array = [0] * self.capacity for x in range(self.size): new_array[x] = self.array[x] return new_array if __name__ == '__main__': a = Stack() a.push(1) a.push(2) a.push(3) a.push(4) a.push(5) print(a.pop()) print(a.pop()) print(a.pop()) print(a.pop()) print(a.pop())
6ce3ccfb1b09f3ab59c8d830f1cbc2ca06c9dd59
RGingrich8/StandManager
/MainMenu.py
958
3.921875
4
class MainMenu: def __init__(self, day_number): #Constructor self.day_number = day_number self.options = ["A - Advance to Day", "B - Buy Supplies", "S - Set Recipe and Prices", "V - View Career", "Q - Quit Game"] self.commands = ["B", "S", "V", "A", "Q"] def menu(self): #Run the menu and its options print("It is day " + str(self.day_number)) self.list_options() user_in = str(input("Which action would you like to take? ")).upper() while user_in not in self.commands: #While not a valid action, repeat the question user_in = str(input("Invalid action. Enter one of BSVA: ")).upper() return user_in #Return the user's choice def list_options(self): #Print out all of the options for the user for elem in self.options: print(elem) def inc_day(self): #Run the day and all of its actions self.day_number += 1
15f1085e70a20755be027a0bba5ffa914b6dcc2c
David-Xiang/Online-Judge-Solutions
/210731/LC13.py
704
3.546875
4
# LeetCode 13 # Roman to Integer # Number from typing import List class Solution: cToInt = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000) def romanToInt(self, s: str) -> int: ans = 0 for i in range(len(s) - 1): val = self.cToInt[s[i]] if s[i:i+2] in ("IV", "IX", "XL", "XC", "CD", "CM"): val = -val ans = ans + val ans = ans + self.cToInt[s[len(s)-1]] return ans if __name__ == "__main__": print(Solution().romanToInt("III")) print(Solution().romanToInt("IV")) print(Solution().romanToInt("IX")) print(Solution().romanToInt("LVIII")) print(Solution().romanToInt("MCMXCIV"))
767b41712c5d706b24c60c67b5ad69b45878ef4d
kamouzougan/firstProgram
/menu_total.py
893
4
4
import time def main() : moreitem=True total = 0 while(moreitem): time.sleep(3) print ('Welcome to the StemBrain') print ("Please enter y for yes amd n for no ") response = input() if response == 'y' or response =='Y': print("please enter for item name") else: print("Goodbye,Thank you for shopping with us") break total += get_item_price(get_item_name()) print ('Total Sum = ',total) print("") def get_item_name(): name = input() return name def get_item_price(value): #price = 0 price =int( input("Please enter the price of your item"+ value)) quantity = get_item_quantity() return price * quantity def get_item_quantity(): quantity =int( input("please enter your itwm quantity")) return quantity main()
058b7b6b2ee2e3502d3dc2159e600c9da4074a1e
Alexandra2802/sudoku
/solver.py
2,137
3.578125
4
board = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] def print_board(bo): for i in range(len(bo)): if i%3==0 and i!=0: print('-----------------') for j in range(len(bo[0])): if j%3==0 and j!=0: print('|',end='') if j==8: print(bo[i][j]) else: print(str(bo[i][j])+' ',end='') def find_empty(bo): ''' Gaseste un spatiu liber pe tabla :param bo: tabla :return: pozitia spatiului liber,tuplu incare primul element e linia si al doilea coloana sau None daca tabla e completa ''' for i in range(len(bo)): for j in range(len(bo[0])): if bo[i][j]==0: return (i,j) #linia,coloana return None #print(find_empty(board)) def check_valid(bo,nr,poz): ''' Verifica daca numarul pus pe tabla e valid :param bo: tabla :param nr: numarul introdus :param poz: pozitia numarului introdus :return: True daca e valida si False altfel ''' #verificare linie for i in range(9): if bo[poz[0]][i]==nr and poz[1]!=i: return False #verificare coloana for i in range(9): if bo[i][poz[1]]==nr and poz[0]!=i: return False #verificare careu mic box_x=poz[1]//3 box_y=poz[0]//3 for i in range(box_y*3,box_y*3+1): for j in range(box_x*3,box_x*3+1): if bo[i][j]==nr and (i,j)!=poz: return False return True #print(check_valid(board,3,(0,2))) def solve(bo): empty=find_empty(bo) if not empty: return True else: row,col=empty for i in range(1,10): if check_valid(bo,i,(row,col))==True: bo[row][col]=i if solve(bo): return True bo[row][col]=0 return False
c5ebc8d79d05eb14b86d878cc6254bb62f2e61c3
CircularWorld/Python_exercise
/month_02/teacher/day15/thread_lock.py
439
3.921875
4
""" 线程同步互斥 Lock方法 """ from threading import Thread,Lock lock = Lock() # 创建锁 # 共享资源 a = b = 0 def value(): while True: lock.acquire() # 上锁 if a != b: print("a = %d,b = %d"%(a,b)) lock.release() # 解锁 t = Thread(target=value) t.start() while True: with lock: # 上锁 a += 1 b += 1 # 语句块结束自动解锁 t.join()
1c8341a9229070e89fcafa63bef2e6d314db0675
Cubba2412/StudentGrades
/loadGrades.py
25,217
3.984375
4
import pandas as pd from userInput import * import os.path import numpy as np #Suppress pandas warnings from user pd.set_option('mode.chained_assignment', None) def loadGrades(): # loadGrades Loads in a CSV file containing N x M data values and # returns it as pandas dataframe ## # Usage: gradesData, dataLoaded, colNum, studentNum = loadGrades() ## # Output gradesData: N x M pandas dataframe with student data and grades in the # CSV file given # dataLoaded: Bool indicating that data has now been loaded ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 while True: try: #Load datafile if it is a valid filename, otherwise #reprompt for valid filename filename = inputChoiceStr("Please enter the name of the datafile to load: ",'') if(os.path.isfile(filename)): gradesData = pd.read_csv(filename) dataLoaded = True break else: print("\nFile not found. Please enter valid filename with file extension suffix") except: print("\nError while loading datafile") return gradesData, dataLoaded def checkData(gradesData): # checkData allows the user to check for various error in the loaded CSV file ## # Usage: Errors = checkData(gradesData) ## # Input: gradesData: N x M pandas dataframe with student data and grades # Output data: An updated N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 dataChecked = False everything = False while True: Errors = loadErrors(gradesData) #Prompt user for what errors they wish to see. #Varies depending on previous choices and errors present in data if not(Errors.empty): if(dataChecked & everything): choice = inputChoiceNum("Data checked for all Errors. Would you like to exit to the main menu? (Y:1,N:0) ", "Y/N") if(choice == 1): break else: everything = False else: options = determineOptions(Errors,everything) printOptions(options) if(dataChecked): userIn = inputChoiceNum("Which other Errors would you like to check for? ", "Data Check") choice = checkChoice(options,userIn) else: userIn = inputChoiceNum("What errors would you like to check the data for? ", "Data Check") choice = checkChoice(options,userIn) if (choice == 'Everything'): dataChecked = True everything = True if(errorExists(Errors,'WG')): for i in range(len(getNumErrors(Errors, 'WG',False))): #Inform user of which assignment for which student, #has a wrong grade with index data from Errors dataframe print("The grade ({}) for student {} with ID {} of \"{}\" is not on the 7 step scale".format(*getPrintData(gradesData, Errors, 'WG', i))) if(errorExists(Errors,'ID')): for i in range(len(getNumErrors(Errors, 'ID',False))): #Inform user of which students have the same student ID print("The studentID for student \"{}\" is the same as for student \"{}\"".format(*getPrintData(gradesData,Errors,'ID',i))) if(errorExists(Errors,'Name')): for i in range(len(getNumErrors(Errors, 'Name',False))): #Inform user of which students have the same name print("The name for the student with studentID \"{}\" is the same as for the student with studentID \"{}\"".format(*getPrintData(gradesData,Errors,'Name',i))) if not(Errors.empty): options = determineOptions(Errors,everything) printOptions(options) userIn = inputChoiceNum("What errors would you like to correct (if any)? ", "Data Check") choice = checkChoice(options,userIn) if(choice == 'Wrong Grade'): corWrongGrades(gradesData,Errors,everything) everything = False elif(choice == 'Duplicate Student ID\'s'): corWrongID(gradesData,Errors,everything) everything = False elif(choice == 'Duplicate Names'): corWrongNames(gradesData, Errors, everything) everything = False elif(choice == 'Everything'): corEverything(gradesData, Errors,everything) everything = False elif(choice == 'Go Back\n'): everything = False continue elif(choice == 'Exit to main menu\n'): print("Reverting back to main menu\n") break elif(choice == 'Wrong Grade'): dataChecked = True corWrongGrades(gradesData,Errors,everything) elif(choice == 'Duplicate Student ID\'s'): dataChecked = True corWrongID(gradesData,Errors,everything) elif(choice == 'Duplicate Names'): dataChecked = True corWrongNames(gradesData, Errors, everything) else: if(dataChecked): print("\nNo other errors found in the data. Reverting back to main menu...") else: print("\nNo errors found in the data. Reverting to main menu...") break return Errors def getErrIdxList(ErrorType): # getErrIdxList creates a list of the Error types to get print data for ## # Usage: ErrIdxList = getErrIdxList(ErrorType) ## # Input: type of Error in question # Output data: list of strings / chars used for which Errortype to locate # in the Errors dataframe ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 #Wrong Grades if(ErrorType == 'WG'): ErrIdxList = ['G','N','ID','A'] #Duplicate ID elif(ErrorType == 'ID'): ErrIdxList = ['N','N'] #Duplicate Name elif(ErrorType == 'Name'): ErrIdxList = ['ID','ID'] return ErrIdxList def getPrintData(gradesData,Errors,ErrorType,i): # getPrintData creates a list of the Error types to get print data for ## # Usage: stringValues = getErrIdxList(ErrorType) ## # Input: gradesData: N x M pandas dataframe with student data and grades # Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # ErrorType: Type of Error in question # i = iterator of for loop # Output data: list of strings to print with str.format ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 First = True stringValues = [] ErrIdxList = getErrIdxList(ErrorType) for j in range(len(ErrIdxList)): #Grade if (ErrIdxList[j] == 'G'): #Row index: row = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][0][i] #Column index column = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][1][i]+2 stringValues += [gradesData.iloc[(row,column)]] #Student Name elif (ErrIdxList[j] == 'N'): if((ErrorType == 'ID') and First): #Row index: row = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][0][i]-1 First = False else: row = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][0][i] #Column index column = 1 stringValues += [gradesData.iloc[(row,column)]] #Student ID elif (ErrIdxList[j] == 'ID'): if((ErrorType == 'Name') and First): row = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][0][i]-1 First = False else: #Row index: row = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][0][i] #Column index column = 0 stringValues += [gradesData.iloc[(row,column)]] #Assignment elif (ErrIdxList[j] == 'A'): #Get column name directly columnName = gradesData.columns[Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][1][i]+2] stringValues += [columnName] return stringValues def printOptions(options): # printOptions prints the users options ## # Usage: printOptions(options) ## # Input: options = list of string options to print ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 print("\nOptions: ") for i in options: print(i) return def getNumErrors(Errors,ErrorType,change): # getNumErrors finds the index in gradesData of the given error ## # Usage: num = getNumErrors(Errors,ErrorType,change) ## # Input: Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # ErrorType: Type of Error in question # change: is the index used for changing a value or simply accessing # an index # Output data: index or list of indexes (depending on the bool change) ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 if not(change): num = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1][0] else: num = Errors.loc[Errors['ErrorType'] == ErrorType].iloc[0][1] return num def corWrongGrades(gradesData,Errors,everything): # corWrongGrades corrects the wrong grades found in the gradesData given ## # Usage: corWrongGrades(gradesData,Errors,everything) ## # Input: gradesData: N x M pandas dataframe with student data and grades # Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # everything: bool value indicating if the option "check everything" # was chosen. Terminal output varies depending on this # The user is prompted throughout the function about how they want # the data corrected ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 dataChecked = True choice = 0 removed = False print("\nIncorrect Grades: ") for i in range(len(getNumErrors(Errors, 'WG',False))): #Inform user of which assignment for which student, has a wrong grade #with index data from Errors dataframe if not(everything): print("The grade ({}) for student {} with ID {} of \"{}\" is not on the 7 step scale".format(*getPrintData(gradesData, Errors, 'WG', i))) choice = inputChoiceNum("Would you like to remove this data? (Y:1, N:0) ", "Y/N") if(choice == 1): #Remove grade by setting to nan gradesData.iat[getNumErrors(Errors,'WG',True)[0][i],getNumErrors(Errors,'WG',True)[1][i]+2] = None removed = True else: choice = inputChoiceNum("This will effect all other data analysis. Are you sure? (Yes:1, No Remove it:0) ", "Y/N") if(choice ==1): continue else: removed = True gradesData.iat[getNumErrors(Errors,'WG',True)[0][i],getNumErrors(Errors,'WG',True)[1][i]+2] = None else: removed = True gradesData.iat[Errors.loc[0][1][0][i],Errors.loc[0][1][1][i]+2] = None if(removed): print("\nRemoving incorrect grades...") deleteError(Errors, "WG") print("Successfully removed grades in data which are not part of the 7 step scale") return def corWrongNames(gradesData,Errors,everything): # corWrongNames corrects the duplicate names found in the gradesData given ## # Usage: corWrongNames(gradesData,Errors,everything) ## # Input: gradesData: N x M pandas dataframe with student data and grades # Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # everything: bool value indicating if the option "check everything" # was chosen. Terminal output varies depending on this # The user is prompted throughout the function about how they want # the data corrected ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 dataChecked = True choice = 0 for i in range(len(getNumErrors(Errors, 'Name',False))): if not(everything): #Inform user of which students have the same name print("The name for the student with studentID \"{}\" is the same as for the student with studentID \"{}\"".format(*getPrintData(gradesData,Errors,'Name',i))) else: print("\nDuplicate Names") choice = inputChoiceNum("Would you like to correct the name? (Y:1, N:0) ", "Y/N") if(choice == 1): print("\n Rows of students with same name:\n",gradesData.loc[gradesData['Name'] == gradesData.iloc[getNumErrors(Errors, 'Name',False)[i]-1,1]].to_string(index = False, na_rep = '')) newName = inputChoiceStr("Please enter the name of the student: ", "Name") choice = inputChoiceNum("Do you want to change the name for the first or second occurence of the duplicated name? (First:0, Second: 1) ", "Y/N") if (choice == 1): #Change name to users input gradesData.iat[getNumErrors(Errors, 'Name',False)[0],1] = newName else: gradesData.iat[getNumErrors(Errors, 'Name',False)[0]-1,1] = newName print("\nEditing Name of student...") deleteError(Errors, "Name") print("Succesfully edited name of the student") else: print("\n Rows of students with same name:\n",gradesData.loc[gradesData['Name'] == gradesData.iloc[getNumErrors(Errors, 'Name',False)[i],1]].to_string(index = False, na_rep = '')) choice = inputChoiceNum("Would you like to remove the data for the student with duplicate name? (Y:1, N:0) ", "Y/N") if(choice == 1): choice = inputChoiceNum("First or second occurence of the Name? (First:0, Second: 1) ", "Y/N") if (choice == 1): #Find row to remove dropID = getNumErrors(Errors, 'Name',False)[0] else: dropID = getNumErrors(Errors, 'Name',False)[0]-1 print(dropID) #Remove row from data and reset index gradesData.drop(dropID,inplace = True) gradesData.reset_index(inplace = True, drop = True) print(gradesData) print("\nRemoving data with duplicate Name...") deleteError(Errors, "Name") print("Successfully removed data for duplicate Name") print("\nReverting back to main menu") return def corWrongID(gradesData,Errors,everything): # corWrongID corrects the duplicate student ID'sfound in the gradesData given ## # Usage: corWrongID(gradesData,Errors,everything) ## # Input: gradesData: N x M pandas dataframe with student data and grades # Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # everything: bool value indicating if the option "check everything" # was chosen. Terminal output varies depending on this # The user is prompted throughout the function about how they want # the data corrected ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 dataChecked = True choice = 0 for i in range(len(getNumErrors(Errors, 'ID',False))): if not(everything): #Inform user of which students have the same student ID print("The studentID for student \"{}\" is the same as for student \"{}\"".format(*getPrintData(gradesData,Errors,'ID',i))) #Prompt user for action to be taken for this data else: print("\nDuplicate ID's: ") choice = inputChoiceNum("Would you like to correct the students ID? (Y:1, N:0) ", "Y/N") if(choice == 1): print("\nRows of students wih same studentID\n",gradesData.loc[gradesData['StudentID'] == gradesData.iloc[getNumErrors(Errors, 'ID',False)[i]-1,0]].to_string(index = False, na_rep = '')) newID = inputChoiceStr("Please enter the students ID: ", "StudentID") choice = inputChoiceNum("Which ID should be replaced? First or second occurence of the ID? (First:0, Second: 1) ", "Y/N") if (choice == 1): #Change ID to what was given by the user gradesData.iat[getNumErrors(Errors, 'ID',False)[0],0] = newID else: gradesData.iat[getNumErrors(Errors, 'ID',False)[0]-1,0] = newID print("\nEditing studentID...") deleteError(Errors, "ID") print("Successfully edited StudentID") else: print("\nRows of students wih same studentID\n",gradesData.loc[gradesData['StudentID'] == gradesData.iloc[getNumErrors(Errors, 'ID',False)[i]-1,0]].to_string(index = False, na_rep = '')) choice = inputChoiceNum("Would you like to remove the data for this student ID? (Y:1, N:0) ", "Y/N") if(choice == 1): choice = inputChoiceNum("First or second occurence of the ID? (First:0, Second: 1) ", "Y/N") if (choice == 1): #Get row to remove dropID = getNumErrors(Errors, 'ID',False)[0] else: dropID = getNumErrors(Errors, 'ID',False)[0]-1 #Remove row from data and reset index gradesData.drop(dropID, inplace = True) gradesData.reset_index(inplace = True, drop=True) print("\nRemoving data with duplicate ID...") deleteError(Errors, "ID") print("Successfully removed data for duplicate ID") else: continue return def corEverything(gradesData,Errors,everything): # corEverything corrects all errors found in the gradesData given. ## # Usage: corWrongGrades(gradesData,Errors,everything) ## # Input: gradesData: N x M pandas dataframe with student data and grades # Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # everything: bool value indicating if the option "check everything" # was chosen. Terminal output varies depending on this # The user is prompted throughout the function about how they want # the data corrected ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 if(errorExists(Errors,'WG')): corWrongGrades(gradesData, Errors, everything) if(errorExists(Errors,'ID')): corWrongID(gradesData, Errors, everything) #Reload Errors to check if a removal of row with ID also fixed error #with same name Errors = loadErrors(gradesData) if(errorExists(Errors,'Name')): corWrongNames(gradesData, Errors, everything) else: print("No Errors present. Nothing corrected") return def errorExists(Errors,ErrorType): # errorExists checks if an of error of the given Errorytype in the data # Usage: errorExists(Errors,ErrorType) ## # Input: Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # ErrorType: Type of Error in question # Output: Bool value indiciating if the error exists ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 return (Errors['ErrorType'] == ErrorType).any() def determineOptions(Errors,everything): # determineOptions determines which options of datacheck the user has # depending of which errors are present # Usage: options = determineOptions(Errors,ErrorType) ## # Input: Errors:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located # ErrorType: Type of Error in question # Output: Bool value indiciating if the error exists ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 options = [] i = 1 #Wrong Grade if(errorExists(Errors,'WG')): options += ['{}. Wrong Grade'.format(i)] i += 1 #Duplicate ID if(errorExists(Errors,'ID')): options += ['{}. Duplicate Student ID\'s'.format(i)] i += 1 #Duplicate Name if(errorExists(Errors,'Name')): options += ['{}. Duplicate Names'.format(i)] i += 1 options += ['{}. Everything'.format(i)] i += 1 #Option to go back to options when "everything" option previously chosen if (everything): options += ['{}. Go Back\n'.format(i)] else: options += ['{}. Exit to main menu\n'.format(i)] return options def checkChoice(options,userIn): # checkChoice determines which option the user chose # Usage: userIn = determineOptions(options,userIn) ## # Input: Options: list of string options # userIn: the choice of the user (integer value) # Output: String corresponding to the users choice ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 for i in range(len(options)): if str(userIn) in options[i]: #Remove number in string and get raw string choice userIn = options[i][3:] print("You chose",userIn) break return userIn def deleteError(Errors,dropType): # deleteError deletes an Error from the Error dataframe of the given # Errorytype # Usage: detleteError(Errors,ErrorType) ## # Input: Errors:N x 2 pandas dataframe with with Error types as well as # the indexes in the given "gradesData" where they are located # ErrorType: Type of Error in question # Output:An updated N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 Errors = Errors.drop(Errors.loc[Errors['ErrorType'] == dropType].index[0]) return Errors def loadErrors(gradesData): # loadErrors locates the Errors found in the given gradesData dataframe # Usage: Errors = loadErrors(gradesData) ## # Input: gradesData: N x M pandas dataframe with student data and grades # Output:N x 2 pandas dataframe with Error types as well as # the indexes in the given "gradesData" where they are located ## # Author: Thomas B. Frederiksen s183729@student.dtu.dk, 2020 colNum = len(gradesData.columns) studentNum = gradesData.shape[0] grades = [None, -3, 0, 2, 4, 7, 10, 12] #Check if grade exists in valid grades of "grades" array #nan (None) included as we wish to determine grades not in the scale, not grades missing #convert to list to obtain index: wrongGrades = ~gradesData.iloc[0:studentNum,2:colNum].isin(grades).values idxGrade = np.where(wrongGrades == True) #Find indexes for students with same StudentID's duplicateID = gradesData.duplicated(['StudentID']).values idxID = np.where(duplicateID == True) #Find indexes for students with the same Names duplicateName = gradesData.duplicated(['Name']).values idxName = np.where(duplicateName == True) #Store all indexes above in a pandas dataframe: data = [] if (len(idxGrade[0]) > 0): #Wrong Grade data += [['WG',idxGrade]] if (len(idxID[0]) > 0): #Duplicate Student ID's data += [['ID',idxID]] if (len(idxName[0]) > 0): #Name data += [['Name',idxName]] Errors = pd.DataFrame(data,columns = ['ErrorType','Index']) return Errors
57fdd81e449737ce881b563705ff71abc670cd03
hashkanna/codeforces
/epi/linked_list/list.py
731
3.875
4
class ListNode: def __init__(self, data=0, next=None): self.data = data self.next = next def search_list(L, key): while L and L.data!=key: L = L.next return L def insert_after(node, new_node): new_node.next = node.next node.next = new_node def delete_after(node): node.next = node.next.next def merge_two_sorted_lists(L1, L2): dummy_head = tail = ListNode() while L1 and L2: if L1.data <= L2.data: tail.next = L1 L1 = L1.next else: tail.next = L2 L2 = L2.next tail = tail.next tail.next = L1 or L2 return
3d0360601225f8a1bed5b5213433900b4f9f2f42
dongxiexiyin/leetcode
/015-3sum/3sum.py
1,520
3.5625
4
# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. # # Note: # # The solution set must not contain duplicate triplets. # # Example: # # # Given array nums = [-1, 0, 1, 2, -1, -4], # # A solution set is: # [ # [-1, 0, 1], # [-1, -1, 2] # ] # # class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ #Brute Force #一种Solution,先排序,然后设置三个index i j k,i对nums做一次循环,每次循环中j和k一个在头一个在尾,往中间靠拢,有重复元素就跳过 resultList = [] nums.sort() if len(nums) < 3: return resultList for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue j = i + 1 k = len(nums) - 1 while j < k: tripleSum = nums[i] + nums[j] + nums[k] if tripleSum < 0: j += 1 elif tripleSum > 0: k -= 1 else: resultList.append([nums[i], nums[j], nums[k]]) j += 1 k -= 1 while j < k and nums[j] == nums[j - 1]: j += 1 while j < k and nums[k] == nums[k + 1]: k -= 1 return resultList
8567a5a5ea606c8e24363ff22fda8ce470c50bc0
wkdghdwns199/Python_basic_and_study
/chap_5/14_lam_bda.py
279
3.8125
4
# 함수를 선언합니다. power=lambda x:x*x under_3= lambda x: x<3 #변수를 선언합니다. list_input_a=[1,2,3,4,5] #map() 함수를 사용 합니다. output_a = map(power,list_input_a) print(list(output_a)) output_a=filter(under_3,list_input_a) print(list(output_a))
503b34b431b1c99a45c0e576ad27dc00a086d24f
diegofregolente/30-Days-Of-Python
/11_Day_Functions/3.py
238
4.09375
4
def add_all_nums(*nums): tot = 0 for n in nums: if isinstance(n, int): # or use type(n) to verify tot += n else: print(f'{n} is not a number') return tot print(add_all_nums(2, 'b', 3))
816ef08876a7b8726439112325a4c8f5053ba516
oswalgarima/leetcode-daily
/stack/baseball_game.py
1,734
3.5625
4
""" 682. Baseball Game https://leetcode.com/problems/baseball-game/ You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores. At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following: An integer x - Record a new score of x. "+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores. "D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score. "C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score. Return the sum of all the scores on the record. Example: Input: ops = ["5","2","C","D","+"] Output: 30 Explanation: "5" - Add 5 to the record, record is now [5]. "2" - Add 2 to the record, record is now [5, 2]. "C" - Invalidate and remove the previous score, record is now [5]. "D" - Add 2 * 5 = 10 to the record, record is now [5, 10]. "+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15]. The total sum is 5 + 10 + 15 = 30. """ # Runtime: 40ms (70.96%) class Solution: def calPoints(self, ops: List[str]) -> int: output = [] for i in range(len(ops)): if ops[i] == 'C': output.pop() elif ops[i] == 'D': output.append(output[-1] * 2) elif ops[i] == '+': output.append(output[-1] + output[-2]) else: output.append(int(ops[i])) return sum(output)