blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ef35e70ab533ad35f5f299aa602eed0bf4d7a403
Adison25/CS362-inClass4
/countPytest.py
467
3.625
4
def count(count): check = 1 #check input for i in range(len(count)): if (i+1 < len(count)) and count[i] != " " and count[i+1] == " ": check = check + 1 return check def test_palindromeTrue(): assert count("maam") == 1 assert count("hi everyone") == 2 assert count("what up bud") == 3 def test_palindromeFalse(): assert not count("man what up") == 2 assert not count("sa ck") == 3 assert not count("12 3 1") == 4
14082d5fe19213c33b4aee7ad4b6663883007a42
Pritish0173/Phonebook
/Contact.py
5,800
3.78125
4
import pickle import pathlib # Class for contact inputs class Contact: def __init__(self, name, phno, email): self.name = name if phno.isdigit(): self.phno = phno else: self.phno = None if email.isspace() or email == "": self.email = None else: self.email = email def __str__(self): s = "{Name: "+self.name if self.phno is not None: s += ", Phone: " + self.phno if self.email is not None: s += ", Email: " + self.email s += "}" return s # function for menu def menu(): print("Please select one of the following options:") print("1. Add Contact") print("2. Display Contacts") print("3. Search Contacts") print("4. Delete Contacts") print("5. Exit") print() option = int(input("Enter the option no.: ")) return option # function for adding contact details def addcontact(pb): print() print("Contacts will be stored in the format [Name, Contact number, Email id]") print() name = input("Enter the name: ") if name.isspace() or name == "": print("Please enter name of the contact") return phno = input("Enter the phone number: ") email = input("Enter the email address: ") contact = Contact(name, phno, email) temp = [contact.name, contact.phno, contact.email] pb.append(temp) with open('listfile.data', 'wb') as filehandle: # store the data as binary data stream pickle.dump(pb, filehandle) # function for displaying contact details def display(pb): print() print("Contacts will be displayed in the format [Name, Contact number, Email id]") for i in pb: print(i) # function for sorting contact list def sortcontacts(pb, i): copy_pb = [] for contact in pb: if contact[i-1] is not None: copy_pb.append(contact) return sorted(copy_pb, key = lambda x: x[i-1]) # function for doing exact binary search on contact list def binarysearch(pb, key, i, lo, hi): if lo >= hi: return -1 mid = (hi - lo)//2 + lo if pb[mid][i] == key: return mid if pb[mid][i] > key: return binarysearch(pb, key, i, lo, mid-1) if pb[mid][i] < key: return binarysearch(pb, key, i, mid+1, hi) # function for doing nearby search on contact list def nearbysearch(pb, key,i): l = [] for s in pb: if key in s[i] and s[i] is not None: l.append(s) return l # function for selecting on either exact search or nearby search def search(pb): print("Please select one of search criteria:") print("1. By name") print("2. By contact no") print("3. By email") i = int(input("Enter the option Number: ")) if i not in (1,2,3): print("Invalid Option") else: sorted_pb = sortcontacts(pb, i) print() print("Please select one of search criteria:") print("1. Exact Search") print("2. Nearby search") j = int(input("Enter the option number: ")) if j not in (1,2): print("Invalid option") else: if j == 1: key = input("Enter your Search key: ") res = binarysearch(sorted_pb, key, i-1, 0, len(sorted_pb)) if res == -1: print("Contact not Found") else: print() print("Contact found") print(sorted_pb[res]) else: key = input("Enter your search key: ") res = nearbysearch(sorted_pb, key, i-1) if res == []: print("Contact not found") else: print() print("Nearby results") for k in res: print(k) # function for deleting a contact def delete(pb): print("Please select one of Delete criteria:") print("1. By name") print("2. By contact no") print("3. By email") i = int(input("Enter the option number: ")) if i not in (1,2,3): print("Invalid Option") else: sorted_pb = sortcontacts(pb, i) key = input("Enter your search key: ") res = binarysearch(sorted_pb, key, i-1, 0, len(sorted_pb)) if res == -1: print("Contact not found") else: print() print("Contact found") print(sorted_pb[res]) pb.remove(sorted_pb[res]) with open('listfile.data', 'wb') as filehandle: # store the data as binary data stream pickle.dump(pb, filehandle) print("Contact Deleted") # main function for phonebook application def phonebook(): print("--------------------------------") print("Phonebook Application") print("--------------------------------") pb = [] file = pathlib.Path("listfile.data") if file.exists (): with open('listfile.data', 'rb') as filehandle: # read the data as binary data stream pb = pickle.load(filehandle) else: with open('listfile.data', 'wb') as filehandle: # store the data as binary data stream pickle.dump(pb, filehandle) while True: option = menu() if option == 1: addcontact(pb) print() elif option == 2: display(pb) print() elif option == 3: search(pb) print() elif option == 4: delete(pb) print() elif option == 5: print("Thanks") break else: print("Invalid option") print() phonebook()
5a160497703f7ee6efd9cbf8d3216993d7315d6f
tusharmahajan/machine-learning-june-2018
/Kernel_filteringMatrix.py
614
3.8125
4
import numpy as np def multiply (big_matrix , small_matrix): temp1 = np.subtract((big_matrix.shape),(small_matrix.shape)) temp = np.add((temp1),([1,1])) x , y = small_matrix.shape[0],small_matrix.shape[1] final_matrix = np.zeros(temp) for i in range(temp[0]): for j in range(temp[1]): c = big_matrix[i:i+x , j:j+y] element_product = np.multiply(c, small_matrix) final_matrix[i][j] = np.sum(element_product) return final_matrix a = input() b= input() print multiply(b,a) # [[2,3,1],[4,2,1],[1,3,2]] # [[1,2],[3,4]]
fc01cec9b9acfbad9ed6e8cb1a7ad0ac65fbd0af
RocketDonkey/project_euler
/python/problems/euler_035.py
594
3.5
4
"""Project Euler - Problem 35 The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ from primes import primes def Euler035(): s = set() ps = set(primes.Eratosthenes(1000000)) for i in ps: n = str(i) if all([1 if int(n[-j:] + n[:-j]) in ps else 0 for j in xrange(len(n))]): s.add(i) return len(s) if __name__ == '__main__': print Euler035()
4d872b88871da0fd909f4cb71954a3f0f8d0f43f
RocketDonkey/project_euler
/python/problems/euler_001.py
470
4.125
4
"""Project Euler - Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def Euler001(): num = 1000 r = range(3, num) for index, i in enumerate(xrange(3, num)): if sum(bool(j) for j in (i%3, i%5)) > 1: r[index] = 0 return sum(r) def main(): print Euler001() if __name__ == '__main__': main()
b6673f4de385c539083d0be484d0caa8a789697b
i-abr/DecentralizedErgodicControl
/d_erg_lib/barrier.py
1,120
3.78125
4
import numpy as np class Barrier(object): ''' This class prevents the agent from going outside the exploration space ''' def __init__(self, explr_space, pow=2, weight=100): self.explr_space = explr_space self.dl = explr_space[1,:] - explr_space[0,:] self.pow = pow self.weight = weight self.eps = 0.01 def cost(self, x): ''' Returns the actual cost of the barrier ''' cost = 0. cost += np.sum((x > self.explr_space[1,:]-self.eps) * (x - (self.explr_space[1,:]-self.eps))**self.pow) cost += np.sum((x < self.explr_space[0,:]+self.eps) * (x - (self.explr_space[0,:]+self.eps))**self.pow) return self.weight * cost def dx(self, x): ''' Returns the derivative of the barrier wrt to the exploration state ''' dx = np.zeros(x.shape) dx += 2*(x > (self.explr_space[1,:]-self.eps)) * (x - (self.explr_space[1,:]-self.eps)) dx += 2*(x < (self.explr_space[0,:]+self.eps)) * (x - (self.explr_space[0,:]+self.eps)) return self.weight * dx
aa431f95be0baf167285a62987df29142a75557c
nicodaisuki/Stochastic-Process-2018
/Queue.py
1,310
3.671875
4
#Written by Kalvin Goode 9454554, 4/27/2018 import numpy as np import matplotlib.pyplot as plt import math T=100 record=[0] customer=[0] server=[0] time=0 state=-1 maxi=0 while(time<T): if(state==-1): #when no customer in line customer=np.random.exponential(0.5,1) time+=customer state+=1 #one more customer in line server=np.random.exponential(0.25,1) #serving time customer=np.random.exponential(0.5,1) #next customer arrival time else: if(server[0]<customer[0]): #when serving is shorter than arrival for x in range(state+1): record[x]+=server[0] time+=server[0] customer[0]-=server[0] state-=1 #one less customer in line server=np.random.exponential(0.25,1) #serving time else: #when serving is longer than arrival time+=customer[0] for x in range(state+1): record[x]+=customer[0] server[0]-=customer[0] state+=1 #one more customer in line while(maxi<=state): record.append(0) maxi+=1 customer=np.random.exponential(0.5,1) #next customer arrival time print("By theory, the stationary distribution is [50, 25, 12.5 , 6.25, 3.125, 1.563, ...].") print("By simulation, the distribution is [ ", end="") for x in range(maxi-1): print(np.round(record[x],3),", ", end="") print(np.round(record[maxi-1],3),"].")
ba8fa01022b4e438af5998b9a991f4809f8a889d
WhiteHair-H/StudyRasberry21
/Test/test/test01.py
716
3.859375
4
# 변수 기본 n = 1 name = 'Sung' n = n + 2 value = 1.2 * n # print('{0} = 1.2 * {1}'.format(value, n)) # print(name) # 문자(배열) 인덱스 방법 greeting = 'Hello World' # print(greeting[0]) # H # print(greeting[2:5]) # llo # print(greeting[:2]) # l # print(greeting[-2:]) # ld # print(greeting * 2) # List numbers = [0, 1, 2, 3] # print(numbers) # print(numbers[0]) # print(numbers[2:4]) names = ['Kim', 'Lee', 'Park', 'Choi'] array = numbers + names # print(array) # print(array[-1]) # print(array * 2) array[3] = 7 # print(array) # Tuple person = ('Kim', 24, 'male') print(person) print(person[1]) #person[1] = 45 name, age, gender = person print(gender) print('github 추가 내용입니다.')
dd722b74a09bab091674c315ac8442486fd41eed
mnylen/pygraph
/pygraph/core.py
4,657
3.78125
4
class Node(object): """ Represents a node in a graph. """ pass class NamedNode(Node): """ Represents a named node in a graph. """ name = str def __init__(self, name): self.name = name def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == other.name def __str__(self): return self.name class ComponentNode(Node): """ Represents a component in a graph. """ nodes = set def __init__(self, nodes = None): if nodes is None: nodes = set() self.nodes = nodes def __str__(self): return "__".join([str(x) for x in self.nodes]) class ByteNodeMatrix(object): matrix = dict def __init__(self): self.matrix = dict() def set(self, i, j, b): """ @i: Node @j: Node @b: anything Sets given byte to edge i -> j """ if i not in self.matrix: self.matrix[i] = dict() self.matrix[i][j] = b def get(self, i, j): """ @i: Node @j: Node Gets value for edge i -> j, or -1 if the matrix does not contain such edge. """ if i in self.matrix and j in self.matrix[i]: return self.matrix[i][j] else: return -1 class Digraph(object): nodes = dict nodemap = None incoming = dict def __init__(self): self.nodes = dict() self.incoming = dict() def add_edge(self, from_node, to_node): self.add_node(from_node) self.add_node(to_node) self.nodes[from_node].add(to_node) self.incoming[to_node].add(from_node) def add_node(self, node): if node not in self.nodes: self.nodes[node] = set() self.incoming[node] = set() def has_edge(self, from_node, to_node): return from_node in self.nodes and to_node in self.nodes[from_node] def remove_edge(self, from_node, to_node): self.nodes[from_node].remove(to_node) self.incoming[to_node].remove(from_node) def edges(self): edges = set() for node in self.nodes: for adjacent_node in self.nodes[node]: edges.add( (node, adjacent_node) ) return edges def nodes_set(self): return set(self.nodes.keys()) def to_dot(self): dot = "digraph {\n" for v in self.nodes_set(): if len(self.nodes[v]) == 0: dot += "\t%s;\n" % str(v) else: for w in self.nodes[v]: dot += "\t%s -> %s;\n" % (str(v), str(w)) dot += "}\n" return dot def subgraph(self, v): """ Creates a subgraph by performing DFS in the current digraph for node v and taking any nodes and edges traversed to the subgraph. returns Digraph """ from pygraph.algorithms.traversal import NodeVisitor, dfs class Visitor(NodeVisitor): def __init__(self, result): self.result = result def visit_node(self, dg, v): self.result.add_node(v) def visit_edge(self, dg, v, w): self.result.add_edge(v, w) dg = Digraph() visitor = Visitor(dg) dfs(self, v, visitor) return dg def copy(self): dg = Digraph() dg.nodes = self.nodes.copy() dg.nodemap = self.nodemap.copy() dg.incoming = self.incoming.copy() return dg def revert(self): tmp = self.nodes self.nodes = self.incoming self.incoming = tmp @staticmethod def from_file(filename): f = None dg = Digraph() try: f = open(filename, "r") for line in f.readlines(): parts = line.split(":") node_name = "" edge_target_list_str = "" if len(parts) > 1: node_name, edge_target_list_str = parts else: node_name = parts[0] if len(node_name) > 0: dg.add_node(NamedNode(node_name)) for edge_target_name in edge_target_list_str.strip().split(" "): edge_target_name = edge_target_name.strip() if len(edge_target_name) > 0: dg.add_edge(NamedNode(node_name), NamedNode(edge_target_name)) finally: if f: f.close() return dg
0de97c7d711b39eb109dbe8649918792fd8eedf0
maria-zdr/softuni
/Python Fundamentals/Exams/Exam 2018-08-11/02. Gladiator Inventory.py
712
3.59375
4
inventory = input().split() while True: data = input().split() if data[0] == 'Fight!': break command = data[0] equipment = data[1].split('-')[0] if command == 'Buy' and equipment not in inventory: inventory.append(equipment) elif command == 'Trash' and equipment in inventory: inventory.remove(equipment) elif command == 'Repair' and equipment in inventory: inventory.remove(equipment) inventory.append(equipment) elif command == 'Upgrade' and equipment in inventory: upgrade = data[1].split('-')[1] ix = inventory.index(equipment) inventory.insert(ix + 1, equipment + ':' + upgrade ) print(' '.join(inventory))
cb674d1adb077f2d6b3e97cfe9b8bb69f1925851
maria-zdr/softuni
/Python Fundamentals/Lists/8. Append Lists.py
144
3.734375
4
data = input().split('|') data.reverse() list_result = [] for item in data: list_result.extend(item.split()) print(' '.join(list_result))
e1bdf5cb2bfa3603b68919c32c56d864b0f5475f
maria-zdr/softuni
/Python Fundamentals/Lists Exercise/02. Split by Word Casing.py
676
3.96875
4
list_specials = [',', ';', ':', '.', '!', '(', ')', '\"', '\'', '\\', '/', '[', ']'] list_lower = [] list_mixed = [] list_upper = [] data = input() for item in list_specials: data = data.replace(item, ' ') list_data = data.split(' ') for item in list_data: if item != '': if item == item.upper() and item.isalpha(): list_upper.append(item) elif item == item.lower() and item.isalpha(): list_lower.append(item) else: list_mixed.append(item) print('Lower-case: {}'.format(', '.join(list_lower))) print('Mixed-case: {}'.format(', '.join(list_mixed))) print('Upper-case: {}'.format(', '.join(list_upper)))
f62cf967c6b3031706c8b5c535b18c9de6a6b5e5
maria-zdr/softuni
/Python Fundamentals/Regular Expressions/08. Word Encounter.py
413
3.78125
4
import re search = input() result = [] sentence_pattern = r'^[A-Z].*[.!?]$' while True: data = input() if data == 'end': break if re.match(sentence_pattern, data): words = re.findall(r'\w+', data) for item in words: symbols = re.findall(search[0], item) if len(symbols) >= int(search[1]): result.append(item) print(', '.join(result))
443bad08b80bb0fee43ee1b71c4917399e058dd2
saniya-ashrafi/assignment1
/question5.py
162
3.6875
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 24 12:53:56 2020 @author: DELL """ n = 2 for i in range(1, 11, 1): product = n*i print(product)
6571413a33535ab3723664c44f542114b4f2f863
cliuthulu/day4
/Exercise04/testing.py
590
3.703125
4
def custom_len(input_list): """custom_len(input_list) imitates len(input_list)""" for i in input_list: count =0 count += i return count def custom_insert(input_list, index, value): """custom_insert(input_list, index, value) imitates input_list.insert(index, value) """ list_length = custom_len(input_list) input_list[index:index] = [value] return input_list # def custom_extend(input_list, values): # """custom_extend(input_list, values) imitates input_list.extend(values)""" # return input_list + [value] list = [0,1,2,3,4,5,6,7,8,9] print custom_insert(list, 3, 455)
f679fa0e53bcd748e7a52ef58081ab66ec26b0e0
RichardJ16/Cracking-The-Coding-Interview
/Chapter-1/Q1_6.py
1,261
3.96875
4
# implement an algorithm that performs a string compression def repeatedCharacter(string): i = 0 c = 1 retString = "" while i != len(string): if i != len(string) - 1 and string[i] == string[i + 1]: c = c + 1 elif i != len(string) - 1 and string[i] != string[i + 1]: retString = retString + string[i] + str(c) c = 1 else: if string[i] == string[i - 1]: retString = retString + string[i] + str(c) return checkRetString(retString, string) else: c = 1 retString + string[i] + str(c) return checkRetString(retString, string) i = i + 1 def checkRetString(retString, string): if len(retString) < len(string): return retString else: return string def problemSet(): test = "aabbccdd" runProblemSet(test) test = "aaabbbcccddd" runProblemSet(test) test = "abcd" runProblemSet(test) test = "aaaaaaabcd" runProblemSet(test) # False, False, True, True, True def runProblemSet(string): print("String Compression?", repeatedCharacter(string)) problemSet()
336411cb85a117b0da2de56b67b33a8186ca541b
deiuch/PPSE
/Assignment10/lab10.py
6,541
3.6875
4
### Python Programming for Software Engineers ### Assignment 10 ### '(Anniversary) Inverse of Assignment 10' ### Eugene Zuev, Tim Fayz # Here is your story: # It is 2005. Recently, you've got your dream job offer from one of the # best "Big Five" tech company. More than that, you've been immediately # accepted as a Lead Developer! Isn't it cool..huh? BUT! Here is the # trick.. Your manager (as it turns out after a month of normal # operation) is a real pro butt! The story doesn't tell us if he was a # Lead Developer too. What we know, however, is that he is most certainly # the one who had been doing "mission critical tasks" at the very # beggining of the company. He [as our course suggests] loves Python more # than his wife and always keep in touch with the latest news stories. # [btw...the reason he gave up his original job is a decision to stop # h***ing his own brain and let others do that instead. Maybe he tired in # general or that's a priority change. Nobody knows now...] So now, on # the same cool Reddit channel he once heard there is an upcoming PEP 343 # that introduces a "with" statement. "What's THAT, man!?" -- he # wondered. The old pro immediately realizes whatever it is he wants it # to be integrated as a "new great technology" [but yet keeping his own # hands clean]. So the choice WHO will teach others to use this statement # (and adopt it into an existing code base) fell on YOU. [That may sound # strange] but now he wants you to prepare a set of tasks to be sure that # the aforementioned PEP 343 was read, consumed and understood by all # department developers. As an example -- how these all should look like # -- the old pro referenced back to well-known assignments 7 till 9. # Moreover, he decided to entitle most of the tasks to mix his own # intentions. As it turns out (again) he is a sly one. Our pro butt wants # a "special edition" of your working where all the answers are given in # advance! [most probably to "save" his time of doing it by hands; which # is a bad idea anyway...] As you may guess, he set up a deadline ['cause # you know...he is a manager] that you are supposed to meet! It's Nov 21, # 10:35AM [just in case you have forgotten.] He absolutely can't keep his # patience of waiting for your tasks! And the ultimate moment where he # will proudly spread them over the department uttering "This is how we # stay on cutting-edge!" # End of the story. # You can begin now... # Introduction (an abstract) # ---------------------------------------------- def file_example(): with open('cool_file_name.format') as my_file: my_file.write('Hello, world!') pass # No need to close the file, it will not be accessible since this line def iostream_example(): # from contextlib import redirect_stdout # from io import StringIO my_stdout = StringIO() with redirect_stdout(my_stdout): print('Hello, world!') pass # Here `my_stdout` will contain the string 'Hello, world!', and nothing will go to the stdio def combined_example(): # from contextlib import redirect_stdout with open('my.log') as log_file, redirect_stdout(log_file): print('16:34:50 - printed this log') pass # All the `print`ed text will go to the file `my.log` # Task 1 (demonstrates the benefits of using with) # ---------------------------------------------- # Write the analog of the `with` statement in terms of `try` statement. # Describe the benefits that you're getting out of using `with`. # ANSWER: -------------------------------------- # Instead of this context manager some existing may be used class MyCoolContextManager: def __enter__(self): pass def __exit__(self): pass __mng = MyCoolResource() __resource = __mng.__enter__() # `with` allows us to not write this terrible `try/finally` guards try: pass # some actions with this resource finally: __mng.__exit__(__resource) # this will happen in any case # Task 2 (demonstrates how to use several nested with's) # ---------------------------------------------- # Give an example of nested `with` statements. Try to optimize this using # only one `with` statement. See the syntax description of the `with` # statement. # ANSWER: -------------------------------------- from io import StringIO with StringIO() as my_stdout: with redirect_stdout(my_stdout): print('Hellom world!') with StringIO() as my_stdout, redirect_stdout(my_stdout): print('Hellom world!') # Task 3 (demonstrates how to create your own context manager) # ---------------------------------------------- # Statement `with` is using some special methods to manage the resource. # Implement a class that will reflect this methods and will be suitable # for use in the `with` statement. Search `Context Manager` for details. # ANSWER: -------------------------------------- class MyCoolResource: def close(self): pass class MyCoolContextManager2: def __enter__(self): return MyCoolResource() def __exit__(self, resource): resource.close() # Task 4 (demonstrates exception handling) # ---------------------------------------------- # Provide a couple of examples showing what happens if an exception will # occur before the end of using of some resource. The first example # should NOT use the `with` statement, but the second should. Totally, # this examples should show the difference between the cases where you # do not take care of deallocation for ALL cases (just start using and # then end using), and where you use some smart language mechanics. # ANSWER: -------------------------------------- def exception_example1(): f = open('abcde.txt') f.write('Heeey!') raise RuntimeError() # oops! File will stay open... f.close() def exception_example2(): with open('fghij.txt') as f: f.write('Heeey!') raise RuntimeError() # File will be definitely closed # Task 5 (your own) # ---------------------------------------------- # Reconstruct your own Context Manager like `redirect_stdout`, but which # should take a path to the file, open it and write all the text given # to the `print` function to this file, and at the end closes this file. # P.S.: be honest and do not look at the original implementation from # the library :D # ANSWER: -------------------------------------- class MyCoolLogger: def __enter__(self, path): # return self.file := open(path) self.file = open(path) return self.file def __exit__(self): self.file.close()
611005f58d797bbd7d3ad69ed33a65d7bf3a94a3
millarba/python_exercises
/ex18.py
360
3.59375
4
def print_two(*args): arg1, arg2 = args print("arg1: %r, arg2: %r" % (arg1, arg2)) def print_two_again(arg1, arg2): print("arg1: %r, arg2: %r" % (arg1, arg2)) def print_one(arg1): print("arg1: %r" % arg1) def print_none(): print("I got nothin'.") print_two("Ben", "Millar") print_two_again("Ben", "Millar") print_one("Ben") print_none()
655bbb317e61c21922655f2af31b54f87d55e7d6
kristiyanto/python_scratchbook-
/.metadata/.plugins/org.eclipse.core.resources/.history/6f/60a63aecb60600161c55dd4c932dba0b
458
3.8125
4
#!/usr/bin/python3.5 def main(): str = "abcde" result = isUniqueChars(str) print("Unique") if result else print("Not Unique") def isUniqueChars(str): if len(str) > 128: print(len(str)) return False else: charByte = bytearray() for char in str: return False if ord(char) in charByte else charByte.append(ord(char)) return True print(charByte) if __name__ == "__main__": main()
cca943ffc0b1a91fcdb9e8603a8a2b5fb1483c61
larteyjoshua/Numerical-Assignments
/Assignment 3/Example64.py
858
3.703125
4
## module trapezoid ''' Inew = trapezoid(f,a,b,Iold,k). Recursive trapezoidal rule: old = Integral of f(x) from x = a to b computed by trapezoidal rule with 2ˆ(k-1) panels. Inew = Same integral computed with 2ˆk panels. ''' import math def trapezoid(f,a,b,Iold,k): if k == 1:Inew = (f(a) + f(b))*(b - a)/2.0 else: n = 2**(k -2 ) # Number of new points h = (b - a)/n # Spacing of new points x = a + h/2.0 sum = 0.0 for i in range(n): sum = sum + f(x) x = x + h Inew = (Iold + h*sum)/2.0 return Inew def f(x): return math.sqrt(x)*math.cos(x) Iold = 0.0 for k in range(1,21): Inew = trapezoid(f,0.0,math.pi,Iold,k) if (k > 1) and (abs(Inew - Iold)) < 1.0e-6: break Iold = Inew print("Integral =",Inew) print("nPanels =",2**(k-1)) input("\nPress return to exit")
6c2aa82e6ff3db888043ceb17d9ff238c7ba7adb
elizamendibekova/Hello-world
/lesson8_1.py
326
4
4
import csv def csv_dict_reader(file_obj, delimiter=','): reader = csv.DictReader(file_obj, delimiter=delimiter) for line in reader: print(line) print("__________") print(line["first_name"]) print(line["last_name"]) print("__________") with open("data.csv", "r") as file_obj: csv_dict_reader(f_obj)
cdf60a273c103d29671403509ad0f86e2498f697
arikj/Smart-email-client
/gui.py
530
3.625
4
from Tkinter import * def bind(widget, event): def decorator(func): widget.bind(event, func) return func return decorator master = Tk() listbox = Listbox(master) listbox.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: listbox.insert(END, item) listbox.pack() @bind(listbox, '<<ListboxSelect>>') def onselect(evt): w = evt.widget index = int(w.curselection()[0]) value = w.get(index) print 'You selected item %d: "%s"' % (index, value) mainloop()
d84763b79621f589befd50627021828c3dcbe5d1
RenatoCPortella/estruturasRepeticao
/ex7.py
137
4.0625
4
maior = 0 for i in range(5): numero = int(input('Informe um número: ')) if numero > maior: maior = numero print(maior)
6c2bd58af252864346c4bf4b2abef281dcc00859
Chaenini/Programing-Python-
/IX. 프로젝트/tictactoe.py
1,425
3.734375
4
class TicTacToe : def __init__(self) : self.board = [".", ".", ".",\ ".", ".", ".",\ ".", ".", "."] self.current_turn = "X" def set(self, row, col): # if self.current_turn == "O" : # self.current_turn = "X" # else : # self.current_turn = "O" if self.get(row, col) == ".": self.current_turn = "X" if self.current_turn == "O" else "O" self.board[(row * 3)+col] = self.current_turn def get(self,row,col): return self.board[(row * 3)+col] def check_winner(self): check = self.current_turn for i in range(3) : #세로 if self.get(i,0) == self.get(i,1) == self.get(i,2) == check : return check #가로 elif self.get(0,i) == self.get(1,i) == self.get(2,i) == check : return check # \ 대각선 if self.get(0,0) == self.get(1,1) == self.get(2,2) == check : return check # / 대각선 elif self.get(0,2) == self.get(1,1) == self.get(2,0) == check : return check #무승부 if not "." in self.board : return "무승부" def __str__(self) : s = "" for i,v in enumerate(self.board): s += v if i % 3 == 2 : s += "\n" return s
080089fcb0b7c72054d9ae4c6058f08f409ad197
Chaenini/Programing-Python-
/2314_이채린/choice.py
2,121
3.5
4
from urllib.parse import urlunparse, urlparse from tutorial import Tutorial from schoolFileReader import SchoolFileReader class Choice: def choice(self) : name = input("이름을 입력해주세요 : ") age = input("나이를 입력해주세요 : ") f = open("data.txt", 'w') f.write(name + " ") f.write(age + " ") print("\n") print("안녕하세요 ! " + name + "님의 고등학교 진학을 도와드릴 '학교가고' 프로그램 입니다 :) ! ") print("\n") t = Tutorial() t.tutorial() arr = ["1. 컴퓨터 코딩","2. 회계 및 전산","3. 디자인","4. 조리 및 식품","5. 기계","6. 과학","7. 항공정비 및 항공서비스","8. 동물","9. 농사","10. 뷰티"] school = ["미림여자정보과학고등학교","서울여자상업고등학교","서울디자인고등학교","서울조리고등학교","수도전기공업고등학교","서울과학고등학교","강호항공고등학교","광주자연과학고등학교","충주농업고등학교","한국뷰티고등학교"] url = ['https://www.e-mirim.hs.kr/main.do', "http://sys.sen.hs.kr/index.do", "http://seodi.sen.hs.kr/51522/subMenu.do","http://kcas.hs.kr/", "http://sudo.sen.hs.kr/index.do", "http://sshs.hs.kr/index.do","http://school.jbedu.kr/kangho", "http://kns.hs.kr/main/main.php", "http://school.cbe.go.kr/cjagh-h","http://kbeauty.jje.hs.kr/"] for i in arr: print(i) print("원하는 분야의 번호를 입력하세요 : ") keyword = input() print("▼▽▼▽▼▽▼▽▼▽▼▽▼▽▼▽▼▽▼▽▼▽▼▽") print(arr[(int(keyword)-1)]) print("학교 : "+school[int(keyword)-1]) print("사이트 : "+url[int(keyword)-1]) print("▲△▲△▲△▲△▲△▲△▲△▲△▲△▲△▲△▲△") f.write(school[int(keyword)-1] + " ") f.write(url[int(keyword)-1] + " ") f.close()
077812fb91097182d15a3aa0dba8c1bdb6946a03
Chaenini/Programing-Python-
/Function2.py
3,423
3.828125
4
#107p import random def rolling_dice(): n = random.randint(1,6) #1<=n<=6인 랜덤수 random(1,6) = 1~5 randint(1,6) = 1~6 print("6면 주사위를 굴린 결과 : ",n) #파이썬은 오버로딩이 불가하다 def rolling_dice(pip): n = random.randint(1,pip) #1<=n<=6인 랜덤수 random(1,6) = 1~5 randint(1,6) = 1~6 print(pip,"면 주사위를 굴린 결과 : ",n) def rolling_dice(pip, repeat): for r in range(1,repeat+1): n = random.randint(1,pip) #1<=n<=6인 랜덤수 random(1,6) = 1~5 randint(1,6) = 1~6 print(pip,"면 주사위를 굴린 결과 : ",r," : ",n) rolling_dice(6,1) rolling_dice(6,0) rolling_dice(6,5) rolling_dice(6,2) rolling_dice(6,3) print() #109P def star() : print("*"*5) star() star() star() #113p print("♡") print("♡","♪") print("♡","♪","♣") print("♡","♪","♣","♠") print("♡","♪","♣","♠","★") #114p def p (*args) : string = "" for a in args : string += a print(string) print("♡") print("♡","♪") print("♡","♪","♣") print("♡","♪","♣","♠") #114p def p(space, space_num, *args) : string = args[0] for i in range(1,len(args)): string += (space * space_num)+args[1] print(string) p(",",3,"♡","♪") p("★",3,"♡","♪","♣") p("★",3,"♡","♪","♣","♠") #115p def star2(ch, *nums): #for i in range(1,len(nums)): #print (nums[0]* nums[i]) for n in nums : print(ch * n) star2("♪",3) star2("♡",1,2,3) #116p def fn(a,b,c,d,e) : print(a,b,c,d,e) fn(1,2,3,4,5) fn(10,20,30,40,50) fn(a=1, b=2, c=3, d=4, e=5) fn(51, 2, c=3, d=4, e=5) #fn(d=1, e=2, 3,4,5) = 에러 #118p def star(mark, repeat, space, space_repeat, line): for i in range(line): String = "" String += (mark*repeat) + (space*space_repeat) + (mark*repeat) print(String) star("※", 3, "_", 2, 3) #119p def Hello(msg = "안녕하세요"): print(msg + "!") Hello("하이") Hello("hi") Hello() #120p def hello2(name, msg="안녕하세요") : print(name+"님, "+msg+" ! ") hello2("김가영","오랜만 이에요") hello2("김선옥") hello2("이채린") def fn2(a,b=[]): b.append(a) print(b) fn2(3) #[].append(3) = [3] fn2(5) #[].append(5) = [5] : x [3,5] : o fn2(10) #[3,5,10] fn2(7,[1]) #[3,5,10,7] : x [7,1] : o #fn2(a=7, b=[1]) : #print([1].append(7)) def gugudan(dan=2): for i in range(1,9+1): #print(dan,"x",i,"=",dan*i) print(str(dan)+"x"+str(i)+"="+str(dan*i)) print() gugudan(3) gugudan(2) gugudan() def sum(*numbers): sum_value=0 for number in numbers: sum_value +=number return sum_value print("1 + 3 = ",sum(1,3)) print("1 + 3 + 5 + 7 = ",sum(1,3,5,7)) def min(*numbers): min_value=0 for number in numbers : min_value -= number return min_value print("min(3,6,-2) = ", min(3,6,-2)) def max(*numbers): max_value=numbers[0] for number in numbers : if max_value < number : max_value=number return max_value print("max(4,5,-2,10) = ",max(4,5,-2,10)) def multi_num(multi, start, end) : result = [] for n in range(start,end): if n % multi ==0 : result.append(n) return result print("multi_num(17,1.200) = ",multi_num(17,1,200)) print("multi_num(3,1,100) = ",multi_num(3,1,100))
a25fd3f691c1205fd09a1f1ad3530e7e12f26d2d
hofvanta/basic_programs
/server_names2.py
888
3.640625
4
def add_some(servers): """ - voeg Helsinki toe aan het einde van de lijst - voeg ~Madrid~ toe tussen ~Tokyo~ en ~Paris~ """ def get_five_letter_servers(servers): five_letter_names = ['Paris'] # fixture '''Doorloop de list servers. indien de lengte van de servernaam lengte 5 heeft, voeg dan toe aan five_letter_names''' return five_letter_names def print_reverse(a_list): '''Maak een kopie van a_list mbv slicing. Gebruik list.pop() om van de gekopieerde lijst telkens het laatste item eruit te halen. print telkens het item. ''' def main(): servers = ['Amsterdam', 'Tokyo', 'Paris', 'Brussel'] add_some(servers) '''print het aantal servers''' filtered = get_five_letter_servers(servers) '''print het aantal vijf-letter-servers''' print_reverse(filtered) if __name__ == "__main__": main()
9e253fc47680f2d2d74f3a98815eb9517eae936b
MushtaqRossier/Task-Manager
/task_manager_new.py
18,322
4.03125
4
from datetime import date #------------------------------------------------------------------------------ """ Creating a function that registers new users whose details are not yet in the text file. """ def reg_user(): user_list = [] with open("user.txt") as f: incorrect_info = True while incorrect_info: #Requests user to input new username new_user = input("Create your new user name here: ") #Opens user text file to read f = open("user.txt", "r") for line in f: info = line.split(", ") #Converts data in f to lists user_list.append(info[0]) if new_user not in user_list: #Requests user to enter and confirm new password new_password = input("Create your new password here: ") confirm = input("Confirm your new password here: ") if new_password == confirm: #Opens user text file to append new details file = open("user.txt", "a") file.write("\n" + new_user + ", ") file.write(new_password) #Closing user text file with updated details file.close() incorrect_info = False break else: print("Your passwords do not match") else: print("User already exist, please try again") #Closes user text file f.close() return "Registration of new user was successful" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Creating a function that assigns a new task to the user and writes the details to a text file. """ def add_task(): with open("tasks.txt") as f: #Opens tasks text file to append f = open("tasks.txt", "a") #Requests user to input the following details username = input("Enter username of the person that the task is assigned to: ") title = input("Enter the title of the task: ") description = input("Enter the description of the task here: ") assign = input("Enter the date the task was assigned to you (format: year-month-day): ") due = input("Enter the due date of the task (format: year-month-day): ") complete = "" #Writes details to tasks text file f.write(username + ", " + title + ", " + description + ", " + assign + ", " + due + ", " + complete + '\n') #Closes tasks text file with new appended details f.close() return "Assigning task to new user was successful" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Function that reads and convert data from tasks text file to a nested list. """ def to_list(): with open("tasks.txt") as f: #Initialising a variable that will be used in the loop new_list = [] f = open("tasks.txt", "r") #Loops through tasks text file, reads the data, edit the the data and store in new variables for line in f: x = line.replace("\n", "") y = x.split(", ") new_list.append(y) f.close() return new_list #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Creating a function that reads all the task assignments in the text file and displays it in a user-friendly manner. """ def view_all(): count = 0 new_list = to_list() #Outputs the task assignments in a user-friendly manner for inner_list in new_list : count += 1 print("Task number = " + str(count)) print("Task assigned to : " + inner_list[0]) print("Job title : " + inner_list[1]) print("Job description : " + inner_list[2]) print("Date assigned : " + inner_list[3]) print("Due date : " + inner_list[4]) print("Completed? : " + inner_list[5]) print() return "All task assignments are presented above" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Function that allows the user that is logged in to view their task assignments. """ def view_mine(): count = 0 new_list = to_list() #Outputs the user's task assignments in a user-friendly manner for inner_list in new_list : count += 1 if user == inner_list[0] : print("Task number = " + str(count)) print("Task assigned to : " + inner_list[0]) print("Job title : " + inner_list[1]) print("Job description : " + inner_list[2]) print("Date assigned : " + inner_list[3]) print("Due date : " + inner_list[4]) print("Completed? : " + inner_list[5]) print() return "Choose task number to view details" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Function that enables the user to mark their task assignments as complete. """ def mark_as_complete(x): new_list = to_list() for inner_list in new_list: if user == inner_list[0]: new_list[x - 1][5] = "Yes" return new_list[x - 1], "Your task completion was successful" def edit_the_task(x): #Initialising a variable that will be used in the loop new_list = to_list() for inner_list in new_list: if user == inner_list[0]: username = input("Who is taking over the responsibility of this task: ") due = input("What is the new due date (format year-month-day): ") new_list[x - 1][0] = username new_list[x - 1][4] = due return new_list[x - 1], "The editing of your details was successful" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Function that writes the task statistics to the task overview text file. """ def task_overview_write(): with open("task_overview.txt") as f: count = 0 count_complete = 0 count_incomplete = 0 complete_overdue = 0 incomplete_perc = 0 overdue_perc = 0 today = str(date.today()) new_list = to_list() current = today.replace("-", "") for inner_list in new_list: count += 1 due = inner_list[3].replace("-", "") #Condtions that check whether tasks are complete or incomplete and overdue if inner_list[-1] == "No": count_incomplete += 1 elif inner_list[-1] == "Yes": count_complete += 1 elif inner_list[-1] == "No" and int(current) > int(due): complete_overdue += 1 #Calculating percenatges incomplete_perc = (count_incomplete/count)*100 overdue_perc = (complete_overdue/count)*100 f = open("task_overview.txt", "w") f.write(str(count) + ", " + str(count_complete) + ", " + str(count_incomplete) + ", " + str(incomplete_perc) + ", " + str(overdue_perc)) f.close() return "All statistics have been successfully written to task_overview.txt" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Function that displays the data in the task overview text file in a friendly manner. """ def task_overview_display(): with open("task_overview.txt") as f: f = open("task_overview.txt", "r") new_list = [] for line in f: y = line.split(", ") new_list.append(y) f.close() for inner_list in new_list: print("Total number of tasks = " + inner_list[0]) print("Total number of completed tasks = " + inner_list[1]) print("Total number of uncompleted tasks = " + inner_list[2]) print("The percentage of incomplete tasks = " + inner_list[3] + "%") print("The percentage of overdue tasks = " + inner_list[4] + "%") print() return "" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Function that writes the user statistics to the user overview text file. """ def user_overview_write(): with open("user.txt") as f: f = open("user.txt", "r") user_list = [] new_list = to_list() today = str(date.today()) current = today.replace("-", "") count_user = 0 count_task = 0 count_user1 = 0 count_user2 = 0 count_user3 = 0 user1_complete = 0 user2_complete = 0 user3_complete = 0 user1_incomplete = 0 user2_incomplete = 0 user3_incomplete = 0 incomplete_overdue1 = 0 incomplete_overdue2= 0 incomplete_overdue3 = 0 for line in f: info = line.split(", ") #Converts data in f to lists user_list.append(info[0]) for i in user_list: count_user += 1 for inner_list in new_list: count_task += 1 due = inner_list[3].replace("-", "") #Checking conditions for each registered user if user_list[1] in inner_list: count_user1 += 1 if inner_list[-1] == "No": user1_incomplete += 1 elif inner_list[-1] == "Yes": user1_complete += 1 elif inner_list[-1] == "No" and int(current) > int(due): incomplete_overdue1 += 1 if user_list[2] in inner_list: count_user2 += 1 if inner_list[-1] == "No": user2_incomplete += 1 elif inner_list[-1] == "Yes": user2_complete += 1 elif inner_list[-1] == "No" and int(current) > int(due): incomplete_overdue2 += 1 if user_list[3] in inner_list: count_user3 += 1 if inner_list[-1] == "No": user3_incomplete += 1 elif inner_list[-1] == "Yes": user3_complete += 1 elif inner_list[-1] == "No" and int(current) > int(due): incomplete_overdue3 += 1 #Calculating percentages count_user1 = (count_user1/count_task)*100 count_user2 = (count_user2/count_task)*100 count_user3 = (count_user3/count_task)*100 user1_complete = (user1_complete/count_task)*100 user2_complete = (user2_complete/count_task)*100 user3_complete = (user3_complete/count_task)*100 user1_incomplete = (user1_incomplete/count_task)*100 user2_incomplete = (user2_incomplete/count_task)*100 user3_incomplete = (user3_incomplete/count_task)*100 incomplete_overdue1 = (incomplete_overdue1/count_task)*100 incomplete_overdue2 = (incomplete_overdue2/count_task)*100 incomplete_overdue3 = (incomplete_overdue3/count_task)*100 f.close() f = open("user_overview.txt", "w") f.write("Total number of registered users = " + str(count_user) + "\nTotal number of tasks = " + str(count_task) + "\n") f.write("\n") f.write(user_list[1] + ": Percentage of tasks assigned = " + str(count_user1) + "%, Percentage of completed tasks = " + str(user1_complete) + "%, Percentage of incompleted tasks = " + str(user1_incomplete) + "%, Percentage of tasks that are incomplete and overdue = " + str(incomplete_overdue1) + "\n") f.write("\n") f.write(user_list[2] + ": Percentage of tasks assigned = " + str(count_user2) + "%, Percentage of completed tasks = " + str(user2_complete) + "%, Percentage of incompleted tasks = " + str(user2_incomplete) + "%, Percentage of tasks that are incomplete and overdue = " + str(incomplete_overdue2) + "\n") f.write("\n") f.write(user_list[3] + ": Percentage of tasks assigned = " + str(count_user3) + "%, Percentage of completed tasks = " + str(user3_complete) + "%, Percentage of incompleted tasks = " + str(user3_incomplete) + "%, Percentage of tasks that are incomplete and overdue = " + str(incomplete_overdue3) + "\n") f.write("\n") f.close() return "All statistics have been successfully written to user_overview.txt" #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ """ Function that displays the data in the user overview text file in a friendly manner. """ def user_overview_display(): with open("user_overview.txt", "r") as f: f = open("user_overview.txt", "r") read_file = f.read() f.close() return read_file #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ #BEGINNING OF THE PROGRAM!! #Open user text file for reading #Checking if the person trying to login is a registered user with open("user.txt", "r") as file: #Loop to check for the correct username and password incorrect_info = True while incorrect_info: user = input("Username: ") file = open("user.txt", "r") #Loop through all lines of user text file to see if the username is registered for line in file: info = line.split(", ") if user == info[0]: break if user == info[0]: while True: #If the username is valid, check for the correct password password = input("Password: ") if password == info[1].strip(): incorrect_info = False break else: print("Incorrect password, please try again") else: print("Username does not exist") #Closes the user text file file.close() #Outputs the menu options for admin and other registered users after succesful login print("Please select one of the following options:") if user == "admin": print("r - register user \n" + "a - add task \n" + "va - view all tasks \n" + "vm - view my tasks \n" + "gr - generate reports \n" + "ds - display statistics \n" + "e - exit") else: print("r - register user \n" + "a - add task \n" + "va - view all tasks \n" + "vm - view my tasks \n" + "e - exit") #Initialising variable that will be used in task option loop task = "" new_list = to_list() while task != "e": #Requests user to input which option on the menu they'd like to choose task = input("Enter your task option here: ") print() if task == "r": #Registers new user in order for them to be able to login to the task manager if user != "admin": print("Only admin is allowed to register new users") else: print(reg_user()) if task == "a": #Assigns task details to user print(add_task()) if task == "va": #Displays all the task assignments print(view_all()) if task == "vm": #Displays task assignments assigned to the user that logged in print(view_mine()) user_choice1 = int(input("Enter which task you'd like to mark as complete or edit: ")) user_choice2 = input("Would you like to mark as complete or edit: ") if user_choice2 == "mark as complete": print(mark_as_complete(user_choice1)) elif user_choice2 == "edit": print(edit_the_task(user_choice1)) if task == "gr": #Generates user and task reports print(task_overview_write()) print(user_overview_write()) if task == "ds": #Displays task and user statistics if user == "admin": print("Task statistics: \n") print(task_overview_display()) print() print("User statistics: \n") print(user_overview_display()) else: ("Only admin can generate reports") #------------------------------------------------------------------------------
54406e46376433c727027b350e1b7b6a6f818181
kamil-fijalski/python-reborn
/@Main.py
2,365
4.15625
4
# Let's begin this madness print("Hello Python!") int1 = 10 + 10j int2 = 20 + 5j int3 = int1 * int2 print(int3) print(5 / 3) # floating print(5 // 3) # integer str1 = "Apple" print(str1[0]) print(str(len(str1))) print(str1.replace("p", "x") + " " + str1.upper() + " " + str1.lower() + " " + str1.swapcase()) # method "find" works like "instr" in SQL # tuples are immutable and they can be nesting tuple1 = ("A", "B", 1, 2, 3.14, 2.73) print(type(tuple1)) print(tuple1[2]) tupleStr = tuple1[0:2] print(tupleStr) tupleNest = (("Jazz", "Rock"), "Dance", ("Metal", "Folk")) print(tupleNest[0][1]) # list are mutable -> square brackets / list can nested other lists and tuples list1 = [5, 1, 3, 10, 8] print(sorted(list1)) list1.extend([7, 12]) # extend adds two elements -> APPEND adds one element (list with elements 7, 12) print(list1) list1[0] = 100 # are mutable print(list1) del(list1[2]) print(list1) str2 = "Quick brown fox jumps over the lazy dog" listSplit = str2.split() print(listSplit) listSplit2 = listSplit[:] # clone existing list # sets / collection -> unique element => curly brackets set1 = set(list1) print(set1) set1.add(256) set1.add(512) print(set1) set1.remove(100) print(set1) check = 512 in set1 # checking if element exists in given set print(check) set88 = {2, 4, 5, 7, 9} set99 = {1, 3, 5, 8, 9} print(set88 & set99) # intersect of the two sets / or "intersection" method print(set88.union(set99)) print(set88.difference(set99)) # dictionaries -> key: value # keys are immutable and unique, values can be mutable and duplicates dict1 = {1: "one", 2: "two", 3: "three"} print(dict1) print(dict1[3]) dict1[1000] = "thousand" # adding new element print(dict1) del(dict1[2]) # delete element print(dict1) print(2 in dict1) # checking if element exists in dict print(dict1.keys()) print(dict1.values()) age = 25 if age < 25: print("less") elif age > 25: print("more") else: print("equal") squares = {"red", "blue", "yellow", "black", "purple"} for i in squares: print(i) str88 = "" for r in range(10, 15): str88 = str88 + str(r) + " " print(str88) str99 = "" while age < 30: str99 = str99 + "bu" + " " age += 1 print(str99 + "BUM!") def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) nn = input("Give me a word... ") print(factorial(len(nn)))
07a0371a7d0a0cc437508f6b6b94c27ef212973e
kamil-fijalski/python-reborn
/@Pandas.py
563
3.53125
4
# Loading data import pandas as pd xlsx_path = 'test.xlsx' df = pd.read_excel(xlsx_path) # df -> dataframe # print(df) y = df.keys() print(y) # creating single dataframe (here: with phone numbers) z = df[['phone']] print(z) a1 = df['postal'].unique() # find unique elements in df print(a1) print("Length of A1: " + str(len(a1))) a2 = df['ccnumber'] >= 4903431815520553 print(a2) # list of boolean values # new dataframe with condition a3 = df[df['ccnumber'] >= 4903431815520553] print("Length of A3: " + str(len(a3))) print(a3) a3.to_csv('test_csv.csv')
f1fd7d472442e9889ff367595b2acf09eba013b0
stephen-engler/numpy
/index_selection.py
642
3.5625
4
import numpy as np arr = np.arange(0,11) #indexing similar to lists print(arr[4]) #same with slicing print(arr[1:5]) print(arr[5:]) #broadcast arr[0:5]=100 print(arr) arr = np.arange(0,11) #data isn't copied but reference #if want copy arr_copy = arr.copy() arr_copy[:] = 100 print(arr) print(arr_copy) arr_2d = np.array([[5,10,15], [20,25,30], [35,40,45]]) print(arr_2d) #array[row][column] or array[array,column] print(arr_2d[0][0]) print(arr_2d[2,2]) #grab sub matrix print(arr_2d[:2, 1:]) #conditional selection arr = np.arange(1,11) bool_arr = arr >5 print(bool_arr) print(arr[bool_arr]) #or print(arr[arr>5]) print(arr[arr<3])
b31b9ae8e5a092fabd066dfe7bf602530ab342ad
sravyasr/find-s
/EnjoySport/enjoySport.py
1,276
3.78125
4
import csv weather_dataset = [] # Import the data from the CSV file with open('enjoysport.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: weather_dataset.append(row) # The attributes that describe the weather dataset_attributes = ['Sky', 'AirTemp', 'Humidity', 'Wind', 'Water', 'Forecast'] # Initial hypothesis, which is the most specific hypothesis target_concept = ['0', '0', '0', '0', '0', '0'] # Function that compares an attr. from a single positive training data and an attr. from the current hypothesis # Returns the instance attr. if 0, the same attr. if they are the same and a ? if they are different def finds(instance_attribute, hypotheses): if hypotheses == '0': return instance_attribute elif hypotheses == '?': return '?' else: if hypotheses == instance_attribute: return hypotheses else: return '?' # Runs all the training data through the map function for instance in weather_dataset: if instance[6] == '1': target_concept = list(map(finds, instance, target_concept)) # Displays the final hypothesis print('The target concept for the Enjoy Sport data set is : '+str(dataset_attributes)+' => '+str(target_concept))
1db82a8ede171d97c4fb116285464f684e1b8305
limuxiao/PythonNote_Liy
/week01/TestClass/Base.py
873
3.671875
4
# -*- coding:utf-8 -*- class Base(object): def __init__(self): print('----Base init----') def get_base(self): return 'Base' def test(self): print('----Base test----') @classmethod def test_class_method(cls): print('----Base class method----') @staticmethod def test_static_method(): print('----Base static method----') class A(Base): def __init__(self): print('----A init----') def test(self): print('----A test----') class B(Base): def __init__(self): print('----B init----') def test(self): print('----B test----') class C(A, B): def test(self): B.test(self) print('----C test----') def main(): c = C() # print(C.__mro__) # C.test_class_method() c.test() pass if __name__ == '__main__': main()
30f92614c829fbed5b1a8182b991b2a6c58a906b
limuxiao/PythonNote_Liy
/week04/测试tcp/TcpServer.py
1,428
3.5625
4
# -*- coding:utf-8 -*- import socket from threading import Thread class ServerThread(Thread): """ 服务端线程类 """ def __init__(self, sock, c_addr): super().__init__() self.__sock = sock self.__c_addr = c_addr def run(self): while True: ret = self.__sock.recv(1024) print(ret) self.__sock.send(b'gg') class TcpServer(object): """ TcpServer """ def __init__(self, ip, port): self.__ip = ip self.__port = port self.__server = None def create_server(self): """ 创建一个tcp服务端 :return: 返回对象自身 """ if self.__server is None: self.__server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__server.bind((self.__ip, self.__port)) self.__server.listen(5) return self def start(self): """ 开始处理客户端的连接 :return: """ while True: s_server, c_addr = self.__server.accept() # print(c_addr) server_thread = ServerThread(s_server, c_addr) server_thread.start() pass def f1(): tcp_server = TcpServer('172.21.150.1', 7788) tcp_server.create_server().start() pass def main(): f1() pass if __name__ == '__main__': main()
742147147bab1046e6a51dda4d2523ee8dde61da
limuxiao/PythonNote_Liy
/week02/测试内建属性及方法、元类/测试集合的交并补差.py
403
3.6875
4
# -*- coding:utf-8 -*- def f1(): a = [i for i in range(10)] print(a) b = a[::2] print(b) a = set(a) b = set(b) print(type(a)) print(type(b)) b.add(3) b.add(5) b.add(10) print(a & b) print(a | b) print(a ^ b) print(a - b) print(b ^ a) print(b - a) print() def main(): f1() pass if __name__ == '__main__': main()
23a77292c1a854f580f9ab3d90d2f108aa5b67c0
limuxiao/PythonNote_Liy
/week02/TestDongtai/test.py
883
3.65625
4
# -*- coding:utf-8 -*- import types class Person(object): def __init__(self, name, age): self.name = name self.age = age pass def test01(): # print(globals()) num = 10 print(locals()) def test02(): p1 = Person('p1', 20) print(p1.name) print(p1.age) p1.address = '背景' print(p1.address) # help(types.MethodType) p1.get_address = types.MethodType(get_address, p1) print(p1.get_address()) Person.get_person = get_person print(Person.get_person()) print(p1.get_person()) Person.load_person = load_person Person.load_person() @classmethod def get_person(cls): return 'hha ' @staticmethod def load_person(): print('----load person----') def get_address(self): return self.address def main(): # test01() test02() pass if __name__ == '__main__': main()
d19d5cde9dc4b5d71bc1d308a2385fc40b51f9be
limuxiao/PythonNote_Liy
/week03/测试线程/简单的生产者与消费者模式.py
1,506
3.890625
4
# -*- coding:utf-8 -*- import threading from threading import Thread from queue import Queue import time class Factory(Thread): """ 工厂类 """ def __init__(self, queue): super().__init__() self.queue = queue pass class Producer(Factory): """ 生产者类 """ def run(self): while True: if self.queue.qsize() < 1000: print('----需要生产----生产线程id:%s----生产产品id:%d----' % (threading.current_thread().name, self.queue.qsize()+1)) self.queue.put(self.queue.qsize() + 1) time.sleep(0.1) else: print('----不需要生产----生产线程id:%s----' % threading.current_thread().name) time.sleep(0.5) class Consumer(Factory): """ 消费者类 """ def run(self): while True: if self.queue.qsize() > 100: print('----可以消费----消费线程id:%s----消费产品id:%d----' % (threading.current_thread().name, self.queue.get())) time.sleep(0.2) else: print('----不可以消费----消费线程id:%s----' % threading.current_thread().name) time.sleep(0.5) def f1(): queue = Queue() for i in range(5): p = Producer(queue) p.start() for i in range(3): c = Consumer(queue) c.start() def main(): f1() pass if __name__ == '__main__': main()
09afa3fca2b02f25714da3d474f3c764c969362a
limuxiao/PythonNote_Liy
/week02/TestBibao.py
991
3.859375
4
# -*- coding:utf-8 -*- def test01(num1): print("----test01----") def test(num2): return num1 + num2 return test def test02(): fun1 = test01(100) fun2 = test01(1) print(fun1(100)) print(id(fun1)) print(id(fun2)) a = test01 b = test01 print(a == b) print(a is b) print(id(a)) print(id(b)) def test03(func): def inner(num=0): print('----test03----') func(num) print('----inner----') return inner @test03 def test04(): print('----test04----') @test03 def test05(num): print('----test05----%d' % num) def test06(func): def inner(): print('----test06----') func() return inner def test07(): print('----test07----') def main(): # test02() # test03() # test04() test05(50) # test07() # test07() # a = test06(test07) # a() pass if __name__ == '__main__': main() # test07 = test06(test07) # test07()
bf3ffe57af7faa05f72e2fd499ff3abd6fe4b514
limuxiao/PythonNote_Liy
/week02/测试装饰器/通用方法装饰器.py
897
3.859375
4
# -*- coding:utf-8 -*- def decorator(fn): """ 这是一个通用方法装饰器,可以用来装饰无参无返回值、无参有返回值、有参无返回值、有参有返回值的方法 :param fn: :return: """ def inner(*args, **kwargs): print('----inner----') return fn(*args, **kwargs) return inner @decorator def f1(): print('----f1----') @decorator def f2(*args, **kwargs): print('----f2----') print('args:%s\nkwargs:%s' % (args, kwargs)) @decorator def f3(): print('----f3----') return 20 @decorator def f4(*args, **kwargs): print('----f4----') print('args:%s\nkwargs:%s' % (args, kwargs)) return args[0] def main(): # f1() a = [1, 2, 3, 4] b = {'name': 'laowang', 'age': 18} # f2(*a, **b) # print(f3()) print(f4(*a, **b)) pass if __name__ == '__main__': main()
52158b57f39a21327a5db258b4f8f6159d83a761
limuxiao/PythonNote_Liy
/week01/Animal.py
525
3.78125
4
# -*- coding:utf-8 -*- class Animal: def __init__(self): pass def eat(self): print('.....eating.....') class C(Animal): def __init__(self, name='Haha', age=15): # Animal.__init__(self) super().__init__() pass def eat(self): print('=====eating=====') # Animal.eat(self) super().eat() def drake(self): print('.....drake.....') def main(): c = C() c.eat() c.drake() pass if __name__ == '__main__': main()
f04e1a64bf4afb4829576a5a5b0f163b2e7571b0
limuxiao/PythonNote_Liy
/测试杀死进程/kill.py
206
3.703125
4
# -*- coding:utf-8 -*- import os def f1(): while True: pass def main(): t = (1, 2, 3) if t and len(t) % 2 == 0: print('s') pass if __name__ == '__main__': main()
cdd94f94c27e93456937456ab31b03088d0d4d5e
limuxiao/PythonNote_Liy
/week01/TestExtend.py
585
3.703125
4
# -*- coding:utf-8 -*- class A: def __init__(self): self.num = 100 self.__num = 200 def test01(self): print('----test01----') def __test02(self): print('----test02----') def test03(self): self.__test02() class B(A): def __init__(self): super().__init__() pass def main(): b = B() print(b.num) # print(b.__num) 不能访问父类的私有属性 b.test01() # b.__test02() 不能访问父类的私有方法 b.test03() pass if __name__ == '__main__': main()
8bcd20c785d72d4e21a828bb383f894c0c54c40b
limuxiao/PythonNote_Liy
/week02/测试内建属性及方法、元类/用type元类创建类.py
282
3.5
4
# -*- coding:utf-8 -*- def f1(): """ 这是最简单的用type方法来创建类 :return: """ Bird = type('Bird', (), {'name': 'haha'}) bird1 = Bird() print(Bird.name) pass def main(): f1() pass if __name__ == '__main__': main()
e12b80ac73eea3290d8fa2f58f40a3a4df196730
cmajorsolo/python-resharper
/three_sum.py
1,272
3.515625
4
class Solution: def threeSum(self, nums): result = [] print(float('inf')) for i in range(0, len(nums)): for j in range(i+1, len(nums)): for k in range(j+1, len(nums)): if nums[i] + nums[j] + nums[k] == 0: childResult = [nums[i], nums[j], nums[k]] childResult = sorted(childResult) if (childResult not in result): result.append(childResult) return result def threeSum2(self, nums): nums = sorted(nums) ans = [] target = float('inf') for i in range(len(nums)): if -nums[i] == target: continue target = -nums[i] l, r = i + 1, len(nums) - 1 fl, fr = float('inf'), float('inf') while l < r: if nums[l] + nums[r] == target: if fl != nums[l] or fr != nums[r]: ans.append([-target, nums[l], nums[r]]) fl, fr = nums[l], nums[r] r -= 1 elif nums[l] + nums[r] < target: l += 1 else: r -= 1 return ans
01efe6fc3d174b7cf2e200183b3ca5ebea966c57
cmajorsolo/python-resharper
/reverseNodesInKGroupTest.py
3,807
3.65625
4
import unittest from ListNode import ListNode from reverseNodesInKGruop import Solution class reverseNodeInKGroupTest(unittest.TestCase): def example_k_is_3_test(self): node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 k = 3 expectedNode1 = ListNode(3) expectedNode2 = ListNode(2) expectedNode3 = ListNode(1) expectedNode4 = ListNode(4) expectedNode5 = ListNode(5) expectedNode1.next = expectedNode2 expectedNode2.next = expectedNode3 expectedNode3.next = expectedNode4 expectedNode4.next = expectedNode5 solution = Solution() actualResult = solution.swapInKGruop(node1, k) self.assertTrue(expectedNode1.equalTo(actualResult)) def example_k_is_2_test(self): node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 k = 2 expectedNode1 = ListNode(2) expectedNode2 = ListNode(1) expectedNode3 = ListNode(4) expectedNode4 = ListNode(3) expectedNode5 = ListNode(5) expectedNode1.next = expectedNode2 expectedNode2.next = expectedNode3 expectedNode3.next = expectedNode4 expectedNode4.next = expectedNode5 solution = Solution() actualResult = solution.swapInKGruop(node1, k) self.assertTrue(expectedNode1.equalTo(actualResult)) def more_than_2_groups_test(self): node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node6 = ListNode(6) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 k = 3 expectedNode1 = ListNode(3) expectedNode2 = ListNode(2) expectedNode3 = ListNode(1) expectedNode4 = ListNode(6) expectedNode5 = ListNode(5) expectedNode6 = ListNode(4) expectedNode1.next = expectedNode2 expectedNode2.next = expectedNode3 expectedNode3.next = expectedNode4 expectedNode4.next = expectedNode5 expectedNode5.next = expectedNode6 solution = Solution() actualResult = solution.swapInKGruop(node1, k) self.assertTrue(expectedNode1.equalTo(actualResult)) def more_than_2_gruops_one_node_left_test(self): node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node6 = ListNode(6) node7 = ListNode(7) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node7 k = 3 expectedNode1 = ListNode(3) expectedNode2 = ListNode(2) expectedNode3 = ListNode(1) expectedNode4 = ListNode(6) expectedNode5 = ListNode(5) expectedNode6 = ListNode(4) expectedNode7 = ListNode(7) expectedNode1.next = expectedNode2 expectedNode2.next = expectedNode3 expectedNode3.next = expectedNode4 expectedNode4.next = expectedNode5 expectedNode5.next = expectedNode6 expectedNode6.next = expectedNode7 solution = Solution() actualResult = solution.swapInKGruop(node1, k) self.assertTrue(expectedNode1.equalTo(actualResult)) if __name__ == '__main__': unittest.main()
5b5df1e0ddd93a652798dc007f4f4649549eee0c
cmajorsolo/python-resharper
/longest_substring.py
349
3.578125
4
from collections import deque class findLongestSubString: def longest_string_online(self, s): curr = deque() longest = 0 for c in s: if c in curr: while curr.popleft() != c: pass curr.append(c) longest = max(longest, len(curr)) return max(len(curr), longest)
5dd93fd8351ea6bbc9baa49d8b8731e052712dc0
omer-goder/python-skillshare-beginner
/list/slicing_a_list.py
203
4.0625
4
### 15/04/2020 ### Author: Omer Goder ### Slicing a list names = ['tony','deirdre','senan','carol'] print(names[0:2]) print(names[1:3]) print(names[:3]) print(names[2:]) print(names[-3:])
7b2d9aa4ece7d8a777def586cb3af02685eac071
omer-goder/python-skillshare-beginner
/conditions/not_in_keyword.py
347
4.1875
4
### 17/04/2020 ### Author: Omer Goder ### Checking if a value is not in a list # Admin users admin_users = ['tony','frank'] # Ask for username username = input("Please enter you username?") # Check if user is an admin user if username not in admin_users: print("You do not have access.") else: print("Access granted.")
622772dadf07330ab6e90b5dcb485c2b87d42178
omer-goder/python-skillshare-beginner
/json/storing_and_reading_user_data.py
351
3.875
4
### 18/05/2020 ### Author: Omer Goder ### Storing and reading user data import json filename = 'username.json' try: with open(filename) as f1: username = json.load(f1) except FileNotFoundError: username = input("What's your saint nick's name") with open(filename, 'w') as f2: json.dump(username, f2) else: print("Welcome back %s!" % username)
3cbb12303b7788144cde7c943ed8c69be387b426
omer-goder/python-skillshare-beginner
/super basics/split_test.py
200
3.6875
4
### 15/05/2020 ### Author: Omer Goder ### Testing the split() function str = 'hello world and welcome to the show' print(str.split(' ', 4)) for word in range(len(str.split())): print(str.split()[word])
f457e6763c190e10b297912019aa76ad7dc899a4
omer-goder/python-skillshare-beginner
/dictionary/adding_user_input_to_a_dictionary.py
997
4.375
4
### 04/05/2020 ### Author: Omer Goder ### Adding user input to a dictionary # Creat an empty dictionary rental_properties = {} # Set a flag to indicate we are taking apllications rental_open = True while rental_open: # while True # prompt users for name and address. username = input("\nWhat is your name?") rental_property = input("What is the address of the property you would like to rent?") # Store the responses in a dictionary rental_properties[username] = rental_property # Ask if the user knows anyone else who would like to rent their property repeat = input("\nDo you know anyone how might like to rent out their propery?\t(Y/N)").lower() if repeat == 'y': continue # just to check code upgrading option else: rental_open = False # Adding propery is complete print('\n---Property to rent---') for username, rental_property in rental_properties.items(): print(username.title() + " have a property at " + rental_property.title() + " to rent.")
fd1ccd8e94a9a2f7d68ce5caade21b4727a5356e
omer-goder/python-skillshare-beginner
/conditions/or_keyword.py
418
4.21875
4
### 17/04/2020 ### Author: Omer Goder ### Using the OR keyword to check values in a list # Names registered registered_names = ['tony','frank','mary','peter'] username = input("Please enter username you would like to use.\n\n").lower() #Check to see if username is already taken if username in registered_names: print("Sorry, username is already taken.") else: print("This username is available")
c4a68db98e27273aebfcf3499d716bf6b0abe142
omer-goder/python-skillshare-beginner
/methods/get_method(2).py
380
4.03125
4
### 21/04/2020 ### Author: Omer Goder ### Editing & deleting values in a dictionary # terms = {'integer' : 'Is a number that contains a decimal place.'} # terms['integer'] = 'A whole number' # print(terms.get('integer')) terms = {'integer' : 'Is a number that contains a decimal place.' , 'string' : 'a sequence of characters.'} del terms['integer'] print(terms)
a673aa5f87153106ae8f45ff660453ff185e5da2
omer-goder/python-skillshare-beginner
/functions/passing_info_to_function.py
628
3.546875
4
### 05/05/2020 ### Author: Omer Goder ### Passing information to function def welcome(username): """Showing a username""" print("Hi " + username.title() + ".\n") # Notice that the name of the argument sent to the function (call) # doesn't have to be the same as the argument the function accepts name = 'omer' welcome(name) # We can also call the function with the value of the argument # instead of a parameter holding that value welcome('jessie') # While using keyword arguments like the following # the argument sent to the function (call) # must be sent after the same name the function accepts welcome(username = 'david')
34c12dde56d3cb3176565750b4292d6a062105df
omer-goder/python-skillshare-beginner
/list/a_list_of_numbers.py
552
4.25
4
### 15/04/2020 ### Author: Omer Goder ### Creating a list of numbers # Convert numbers into a list numbers = list(range(1,6)) print(numbers) print('\n') # print("List of even number in the range of 0 to 100:") even_numbers = list(range(0,102, 2)) print(even_numbers) print('\n') print("List of square values of 1 to 10:") squares = [] for value in range(1,11): square = value ** 2 squares.append(square) print(squares) print('\n') digits = [1,2,3,4,5] print(min(digits)) print(max(digits)) print(sum(digits)) print('\n')
97360bd4a55477713e3868b9c9af811143151aca
omer-goder/python-skillshare-beginner
/class/class_as_attribute(2).py
1,127
4.34375
4
### 11/05/2020 ### Author: Omer Goder ### Using a class as an attribute to another class class Tablet(): """This will be the class that uses the attribute.""" def __init__(self, thickness, color, battery): """Initialize a parameter as a class""" self.thickness = thickness self.color = color self.battery = battery self.screen = Screen() class Screen(): """This will be the attribute for the other class.""" def __init__(self, glass_grade = 'gorilla glass', color = 'BW', screen_size = '8"'): """Initalize the attributes of the Attrib class.""" self.glass = glass_grade self.color = color self.screen_size = screen_size def screen_type(self): """Print the attributes""" print("Glass: " + self.glass + "\nSize: " + self.screen_size + ".") def screen_color(self): """Print the arguments.""" print("This is a " + self.color + " screen.\n") my_tablet = Tablet('5 mm', 'green', '4800 mAh') my_tablet.screen.screen_type() my_tablet.screen.screen_color() my_screen = Screen('Gorilla 8', 'color', '10"') my_tablet.screen = my_screen my_tablet.screen.screen_type() my_tablet.screen.screen_color()
c137de8352cecb7bff57b404c8bb64a48732c1a1
omer-goder/python-skillshare-beginner
/functions/positional+arbitrary(var_args).py
372
3.796875
4
### 06/05/2020 ### Author: Omer Goder ### Using positional and arbitrary arguments together def assign_seat(seat, *requests): """Assign a seat and requests to a passenger""" print("\nThe passenger in seat %d has made the follwing requests:" % (seat)) for request in requests: print("- " + request) assign_seat(5, 'window seat', 'pre-order breakfast', 'extra leg space')
c2f5de301a04d61edf9c2cb2aa4887b910b13436
maclyne/volcano_database
/my_utils.py
7,453
4.21875
4
"""Collects data from a column within a dataset * open_file - opens a comma separated CSV file * get_column - searches through a data file and finds specific values relating to an inputted search parameter(s). * identify_column - Identifies the query columns of interest if entered as an integer or a string and gives the index values of those columns. * check_plume_height - Opens a comma separated CSV file, calculates if the value in the first query column is greater than the value in the second query column and then adds a 'y' or 'n' to the outputted list """ import sys import csv import re def open_file(file_name): """ Opens a comma separated CSV file Parameters ---------- file_name: string The path to the CSV file. Returns: -------- Output: the opened file """ # Checks for file not found and perrmission errors try: f = open(file_name, 'r') except FileNotFoundError: print("Couldn't find file " + file_name) sys.exit(3) except PermissionError: print("Couldn't access file " + file_name) sys.exit(4) # opens the file f = open(file_name, 'r', encoding="ISO-8859-1") return(f) def get_column(file_name, query_column, query_value, result_column=1): """ Opens a comma separated CSV file and returns a list of integers from the result_column where the query_value matches the value in the query_column. Parameters ---------- file_name: string The path to the CSV file. query_column: integer or string The column to search for the query_value in. query_value: string The value to be searched for result_column: integer or string or list The column(s) to be returned when the row contains the query_value. If string, must match the data set header for that column. If an integer, the count must start at 0. Returns: -------- Output: list of intergers or list of lists of strings with multiple result column inputs values in the result_column matching the query_value entry. """ f = open_file(file_name) # separates header line and removes /n header_unsplit = f.readline().rstrip() # splits header. The gibberish is to not split based on commas in () header = re.split(r',(?!(?:[^(]*\([^)]*\))*[^()]*\))', header_unsplit) # calls the column_index function to identify the query and result columns # based on either their integer or string value i = identify_column(query_column, header) ii = [] if type(result_column) is list: for r_column in result_column: column_index = identify_column(r_column, header) ii.append(column_index) else: ii = identify_column(result_column, header) # create Results list to add results to with multiple result columns output = [] for line in f: A = line.rstrip().split(',') # checks if value in the query_column matches the inputted query_value if A[i] == query_value: # appends value in the result columns to the outputted Result list if type(result_column) is list: case = [] for index in ii: case.append(A[index]) output.append(case) # appends value in the result column to the outputted Result array else: try: output.append(int(A[ii])) except ValueError: output.append(A[ii]) # exception for query_value not found if len(output) == 0: print(query_value + ' was not located in the column ' + str(query_column)) f.close() return(output) def identify_column(query_column, header): """ Identifies the query column of interest if entered as an integer or a string and gives the index values of that column. Parameters ---------- query_column: integer or string The column to search for the query_value in. header: list of strings The header of the file of interest which contains the column titles to be searched for a match with inputted strings for query columns. Returns: -------- index: integer Index value of the query column. """ index = 0 # checks if integer for column was inputted # assumes counting starting at 0 for column_header in header: try: type(int(query_column)) == int column = int(query_column) # checks for array length exception if column > (len(header) - 1): print("Searching for result column " + str(query_column) + " but there are only " + str(len(header)-1) + " fields") sys.exit(1) else: index = column except ValueError: if query_column == column_header: break else: index += 1 # checks for str(query_column) match exception if index > (len(header)-1): print("Searching for result column " + query_column + " but this file does not contain it") sys.exit(1) return(index) def check_plume_height(file_name, query_columns): """ Opens a comma separated CSV file, calculates if the value in the first query column is greater than the value in the second query column and then adds a 'y' or 'n' to the outputted list. Parameters ---------- file_name: string The path to the CSV file. query_columns: integer or string The columns to be compared. NOTE: the value in the first input column is determined to be greater or equal to the value in the second input column. Expecting only two query columns. Returns: -------- greater_than_zero: list list of 'y' or 'n' corresponding to if the values in the query columns were greater than or equal to each other or not. """ f = open_file(file_name) # separates header line and removes /n header_unsplit = f.readline().rstrip() # splits header. The gibberish is to not split based on commas in () header = re.split(r',(?!(?:[^(]*\([^)]*\))*[^()]*\))', header_unsplit) # calls the column_index function to identify the query columns # based on either their integer or string value i = [] for q_column in query_columns: column_index = identify_column(q_column, header) i.append(column_index) # create Results list to add results to with multiple result columns greater_than_zero = [] for line in f: A = line.rstrip().split(',') # appends value in the result columns to the outputted Result list difference = float(A[i[0]]) - float(A[i[1]]) if difference >= 0: greater_than_zero.append('y') else: greater_than_zero.append('n') f.close() return(greater_than_zero)
2aa556b46db3f7aca4065431d91ccdb460cd1127
CodeDeemons/Python-Tkinter-Gui-Project
/Email_Sender/main.py
4,074
3.84375
4
from tkinter import * import smtplib from tkinter import messagebox # making tkinter window root = Tk() root.geometry('500x500') root.title('Email Sender @_python.py_') root.resizable(False, False) root.config(bg="#fff") # variable for Entry box Email = StringVar() Password = StringVar() To = StringVar() Subject = StringVar() # In this we make layout for sing in mail id def emaillogin(): f = Frame(root, height=480, width=500, bg='#FFF') Label(f, text="Sign in", font=("Helvetica", 30, "bold"), bg='#FFF', fg="#2F9DFF").place(x=180, y=120) Label(f, text='to continue to Email', font=("Helvetica", 12, "bold"), fg='#666A6C', bg='#FFF').place(x=170, y=170) Label(f, text='Email', font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=140, y=210) email = Entry(f, textvariable=Email, font=('calibre',10,'normal'), width=30, bg="#E2E2E2") email.place(x=140, y=230) Label(f, text='Password', font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=140, y=280) password = Entry(f, textvariable=Password, font=('calibre',10,'normal'), width=30, bg="#E2E2E2", show="*") password.place(x=140, y=300) Button(f, text='NEXT',font=("Helvetica", 10, "bold"), bg='#2F9DFF', fg="#FFF", command=mail_verification).place(x=300,y=330) Label(f, text='Note:',font=("Helvetica", 10, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=400) Label(f, text='1. If Mail Id is not working use different one.',font=("Helvetica", 8, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=420) Label(f, text='2. Please remove also email authentication for testing this application.',font=("Helvetica", 8, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=440) Label(f, text=' otherwise use fake/temporary Mail Id.',font=("Helvetica", 8, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=460) f.place(x=0, y=0) # here we make send mail layout like from, to, subject and text box def mail_compose(): global body f = Frame(root, height=480, width=500, bg='#FFF') Label(f, text='New Message', font=("Helvetica", 12, "bold"), fg='#fff', bg='#666A6C').place(x=20, y=20) Label(f, text='From', font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=60) Label(f, text=f"<{Email.get()}>", font=("Helvetica", 12, "bold"), fg='#4C4A49', bg='#FFF').place(x=20, y=80) Label(f, text='To', font=("Helvetica", 12), fg='#4C4A49', bg='#FFF').place(x=20, y=130) to = Entry(f, textvariable=To, font=('calibre',10,'normal'), width=50, bg="#E2E2E2") to.place(x=20, y=150) Label(f, text='Subject', font=("Helvetica", 12), fg='#4C4A49', bg='#FFF').place(x=20, y=170) subject = Entry(f, textvariable=Subject, font=('calibre',10,'normal'), width=50, bg="#E2E2E2") subject.place(x=20, y=190) Label(f, text='Body', font=("Helvetica", 12), fg='#4C4A49', bg='#FFF').place(x=20, y=210) body = Text(f, font=('calibre',10,'normal'), width=50, bg="#E2E2E2", height=12) body.place(x=20, y=230) Button(f, text='Send',font=("Helvetica", 10, "bold"), bg='#2F9DFF', fg="#FFF", command=mail_sending).place(x=20,y=440) f.place(x=0, y=0) # here 1st we verify mail after that we call to # mail_compose fun otherwise it's show error def mail_verification(): global server server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() try: server.login(Email.get(), Password.get()) mail_compose() except Exception: messagebox.showerror('Sign in Error!', 'Please check your email id and password\notherwise use different mail id') # after verfication we send mail from this function def mail_sending(): subject = Subject.get() body_text = body.get("1.0", "end-1c") msg = f"Subject : {subject} \n\n {body_text}" server.sendmail( Email.get(), To.get(), msg ) messagebox.showinfo("Success!", 'mail has been send') if __name__ == '__main__': emaillogin() root.mainloop()
d347210fb0e7008e8cf45df56bf5f5725e0fe324
saikrishna-427/Python_learning
/Duplicate_bithday.py
403
3.78125
4
#finding duplicate birthdays in lists of python def has_duplicates(dates): word_checked = {} same_date = [] for i in dates: if i not in word_checked: word_checked[i] = 1 else: if word_checked[i] == 1: same_date.append(i) word_checked[i] = word_checked[i] + 1 return word_checked dates = [(2020, 5, 17),(2019, 5, 17),(2020, 5, 17)] has_duplicates(dates)
2b844498e1179dc75c64f18154c693b780f4965b
TRManderson/math4202
/ride_sharing/models.py
2,264
3.734375
4
from typing import List, Optional import math import attr import pickle Time = float # type alias @attr.s(frozen=True) class Location(object): """ The distance between any pair of locations must be known, this is the only requirement. A simple way to fulfill this requirement is by generating 2D coordinates for locations and using euclidean distance as the distance metric. """ x = attr.ib() y = attr.ib() def distance_to(self, other): return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2) @attr.s(frozen=True) class Announcement(object): """ Announcements include an origin and departure location, an earliest departure time, a latest arrival time, and an announcement time. The time-flexibility of an announcement is the difference between latest arrival and earliest departure, minus travel time. v(s) = trip origin w(s) = trip destination e(s) = earliest departure l(s) = latest arrival f(s) = time_flexibility """ # __slots__ = ('origin', 'dest', 'depart', 'arrive') origin = attr.ib() # type: Location dest = attr.ib() # type: Location depart = attr.ib() # type: Time arrive = attr.ib() # type: Time rider = None # type: Optional[bool] driver = None # type: Optional[bool] rider_driver_str = attr.ib(init=False) def __attrs_post_init__(self): set = lambda v: object.__setattr__(self, 'rider_driver_str', v) if self.rider: set("Rider") elif self.driver: set("Rider") else: set("") class RiderAnnouncement(Announcement): rider = True driver = False class DriverAnnouncement(Announcement): rider = False driver = True @attr.s(frozen=True) class DataSet(object): locations = attr.ib() rider_announcements = attr.ib() driver_announcements = attr.ib() matches = attr.ib() rider_preferences = attr.ib() driver_preferences = attr.ib() @classmethod def load_data(cls, f): return cls(**pickle.load(f)) def save_data(self, f): pickle.dump(attr.asdict(self, recurse=False), f) __all__ = [ 'Location', 'RiderAnnouncement', 'DriverAnnouncement', 'DataSet' ]
f385856290585e7e625d82c6f1d0b6f5aa171f71
akram2015/Python
/HW4/SECURITY SCANNER.py
631
4.4375
4
# this program Prompt user for a file name, and read the file, then find and report if file contains a string with a string ("password=") in it. # file name = read_it.txt found = True userinput = input ("Enter the file name: ") string = input ("Enter the string: ") myfile = open (userinput) # open the file that might contain a string for line in myfile: if string in line: print ("The line which contain the string", string, "is: ", line) # print the line that contain the string found = False myfile.close() if found: print ("The string", string, "does not exist in", userinput, "file!")
c6ee4574166c0e00e6e7bddad59ca354677ea66a
akram2015/Python
/HW3/BunnyEars.py
431
4.3125
4
# Recursive function that return the number of ears for bunnies def bunny_ears(n): # n number of bunnies if n <= 0: # 0 bunny condition return 0 elif n % 2 == 0: # for even numbers of bunnies return bunny_ears(n-1) + 2 else: # for odd numbers of bunnies return bunny_ears(n-1) + 3 x = int(input("Enter a number of bunnies: ")) print("The number of ears are:", bunny_ears(x))
429776165afb038e33026788881f504f137d629e
kellischeuble/cs-module-project-hash-tables
/applications/markov/markov.py
474
3.5
4
import random with open("input.txt") as f: words = f.read() words = words.split() word_after = dict() for i, word in enumerate(words[:-1]): if word in word_after: word_after[word].append(words[i+1]) else: word_after[word] = [words[i+1]] sentence = "he" value = sentence while not sentence.endswith('.'): new_word = random.choice(word_after[value]) sentence = sentence + ' ' + new_word value = new_word print(sentence)
446deb2d033de690fb358330d3665c53d35a3d55
DeanTae/sample
/second.py
512
3.8125
4
def determinePrime(number): if number < 2: return False if number == 2: return True for i in range(2,number): if number % i == 0: return False return True def checkPrimeDuplicate(d): count = 0 for i in range(0,len(d)): for specific in d[i]: if determinePrime(specific)==True: count = count + 1 return count print(checkPrimeDuplicate([[0,1,3],[3,2,4,5,2],[6]])) def testCheckPrimeDuplicate(): print("testing checkPrimeDuplicate") assert(checkPrimeDuplicate([[2,3,4,5],[6,4,5]])==4)
46df9c3814c9e167351f58cae2a60e7b225921b1
CodecoolGlobal/lightweight-erp-python-p-a
/sales/sales.py
17,680
3.640625
4
""" Sales module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * title (string): Title of the game sold * price (number): The actual sale price in USD * month (number): Month of the sale * day (number): Day of the sale * year (number): Year of the sale * customer_id (string): id from the crm """ # everything you'll need is imported: # User interface module import ui # data manager module import data_manager # common module import common import datetime def getMax(list): maxElement = list[0] for elements in list: if elements > maxElement: maxElement = elements return maxElement def start_module(): """ Starts this module and displays its menu. * User can access default special features from here. * User can go back to main menu from here. Returns: None """ table = data_manager.get_table_from_file("sales/sales.csv") table_title = ["id", "title", "price", "month", "day", "year"] list_options = ["Show table", "Add product", "Remove product", "Update table", "Get the item's ID with the lowest price", "Get th number of items sold in a given range of years"] ui.print_menu("Sales module menu:", list_options, "Exit program") while True: option = ui.get_inputs(["Please enter a number"], "") if option[0] == "1": show_table(table) elif option[0] == "2": table = add(table) elif option[0] == "3": id_ = ui.get_inputs(["ID: "], "Please type ID to remove: ")[0] table = remove(table, id_) elif option[0] == "4": id_ = ui.get_inputs(["ID: "], "Please type ID to update: ")[0] table = update(table, id_) elif option[0] == "5": result = get_lowest_price_item_id(table) ui.print_result(result, "Printing the number of games by manufacturers") elif option[0] == "6": result = get_items_sold_between(table, 3, 14, 2016, 8, 10, 2016) ui.print_result(result, "Items sold between the given dates") elif option[0] == "0": exit() else: ui.print_error_message("No such an option!") def show_table(table): """ Display a table Args: table (list): list of lists to be displayed. Returns: None """ title_list = ["id", "title", "price", "month", "day", "year"] table = data_manager.get_table_from_file("sales/sales.csv") ui.print_table(table, title_list) def add(table): """ Asks user for input and adds it into the table. Args: table (list): table to add new record to Returns: list: Table with a new record """ list_labels = ["title: ", "price: ", "month: ", "day: ", "year: "] wanna_stay = True while wanna_stay: new_product = ui.get_inputs(list_labels, "Please provide product information") new_product.insert(0, common.generate_random(table)) table.append(new_product) next_step = ui.get_inputs([""], "Press 0 to save & exit or 1 to add another product.")[0] if next_step == "0": data_manager.write_table_to_file("sales/sales.csv", table) wanna_stay = False return table def remove(table, id_): """ Remove a record with a given id from the table. Args: table (list): table to remove a record from id_ (str): id of a record to be removed Returns: list: Table without specified record. """ wanna_stay = True current_iterates = 0 max_iterates = len(table) while wanna_stay: for i, v in enumerate(table): if v[0] == id_: table.remove(table[i]) elif v[0] != id_ and current_iterates < max_iterates: current_iterates += 1 else: ui.print_error_message("There is nothing with the given ID!") next_step = ui.get_inputs([""], "Press 0 to exit or 1 to remove another product.")[0] if next_step == '0': data_manager.write_table_to_file("sales/sales.csv", table) wanna_stay = False else: id_ = ui.get_inputs(["Please type ID to remove: "], "\n")[0] continue return table def update(table, id_): """ Updates specified record in the table. Ask users for new data. Args: table (list): list in which record should be updated id_ (str): id of a record to update Returns: list: table with updated record """ wanna_stay = True current_iterates = 0 max_iterates = len(table) while wanna_stay: for i, v in enumerate(table): if v[0] == id_: first_step = ui.get_inputs([""], "Please specify, what would you like to change at the given index? (title, price, month, day, year)")[0] if first_step == "title": new_title = ui.get_inputs([""], "Please give a new title!") v[1] = new_title[0] elif first_step == "price": new_price = ui.get_inputs([""], "Please give a new price!") v[2] = new_price[0] elif first_step == "month": new_month = ui.get_inputs([""], "Please give a new month!") v[3] = new_month[0] elif first_step == "day": new_day = ui.get_inputs([""], "Please give a new day!") v[4] = new_day[0] elif first_step == "year": new_day = ui.get_inputs([""], "Please give a new year!") v[5] = new_year[0] else: ui.print_error_message("There's no such an option!") elif v[0] != id_ and current_iterates < max_iterates: current_iterates += 1 else: ui.print_error_message("You can't add an item because of some reasons!") last_step = ui.get_inputs([""], "Press 0 to exit or 1 to update another item.")[0] if last_step == '0': data_manager.write_table_to_file("sales/sales.csv", table) wanna_stay = False else: id_ = ui.get_inputs(["Please type an ID to update the item at the given ID: "], "\n")[0] continue return table # special functions: # ------------------ def get_lowest_price_item_id(table): """ Question: What is the id of the item that was sold for the lowest price? if there are more than one item at the lowest price, return the last item by alphabetical order of the title Args: table (list): data table to work on Returns: string: id """ pList = [] for inList in table: pList.append(int(inList[2])) maxPrice = 110 for num in pList: if num < maxPrice: maxPrice = num strPrice = str(maxPrice) for inList in table: if strPrice in inList[2]: result = inList[0] return result def get_items_sold_between(table, month_from, day_from, year_from, month_to, day_to, year_to): """ Question: Which items are sold between two given dates? (from_date < sale_date < to_date) Args: table (list): data table to work on month_from (int) day_from (int) year_from (int) month_to (int) day_to (int) year_to (int) Returns: list: list of lists (the filtered table) """ year_from = str(year_from) month_from = str(month_from) day_from = str(day_from) if len(month_from) == 1: month_from = str(0) + month_from if len(day_from) == 1: day_from = str(0) + day_from from_date = str(year_from) + str(month_from) + str(day_from) year_to = str(year_to) month_to = str(month_to) day_to = str(day_to) if len(month_to) == 1: month_to = str(0) + month_to if len(day_to) == 1: day_to = str(0) + day_to to_date = str(year_to) + str(month_to) + str(day_to) sale_date = "" updated_table = [] for items in table: if len(items[3]) == 1: items[3] = str(0) + items[3] if len(items[4]) == 1: items[4] = str(0) + items[4] sale_date = items[5] + items[3] + items[4] if from_date < sale_date < to_date: items[2] = int(items[2]) items[3] = int(items[3]) items[4] = int(items[4]) items[5] = int(items[5]) updated_table.append(items[:-1]) return updated_table # functions supports data analyser # -------------------------------- def get_title_by_id(id): """ Reads the table with the help of the data_manager module. Returns the title (str) of the item with the given id (str) on None om case of non-existing id. Args: id (str): the id of the item Returns:a str: the title of the item """ table = data_manager.get_table_from_file("sales/sales.csv") for row in table: if id in row[0]: return row[1] return None def get_title_by_id_from_table(table, id): """ Returns the title (str) of the item with the given id (str) on None om case of non-existing id. Args: table (list of lists): the sales table id (str): the id of the item Returns: str: the title of the item """ for row in table: if id in row[0]: return row[1] return None def get_item_id_sold_last(): """ Reads the table with the help of the data_manager module. Returns the _id_ of the item that was sold most recently. Returns: str: the _id_ of the item that was sold most recently. """ table = data_manager.get_table_from_file("sales/sales.csv") dateList = [] for inList in table: dateList.append(datetime.datetime(int(inList[5]), int(inList[3]), int(inList[4]))) maxDate = getMax(dateList) strMaxDate = str(maxDate) maxDateList = strMaxDate.split('-') day = maxDateList[2].rstrip('0: ') maxDateList.pop(2) maxDateList.append(day) for inList in table: if inList[5] == maxDateList[0] and inList[3] == maxDateList[1] and inList[4] == maxDateList[2]: return inList[0] def get_item_id_sold_last_from_table(table): """ Returns the _id_ of the item that was sold most recently. Args: table (list of lists): the sales table Returns: str: the _id_ of the item that was sold most recently. """ dateList = [] for inList in table: dateList.append(datetime.datetime(int(inList[5]), int(inList[3]), int(inList[4]))) maxDate = getMax(dateList) strMaxDate = str(maxDate) maxDateList = strMaxDate.split('-') day = maxDateList[2].rstrip('0: ') maxDateList.pop(2) maxDateList.append(day) for inList in table: if inList[5] == maxDateList[0] and inList[3] == maxDateList[1] and inList[4] == maxDateList[2]: return inList[0] def get_item_title_sold_last_from_table(table): """ Returns the title of the item that was sold most recently. Args: table (list of lists): the sales table Returns: str: the title of the item that was sold most recently. """ dateList = [] for inList in table: dateList.append(datetime.datetime(int(inList[5]), int(inList[3]), int(inList[4]))) maxDate = getMax(dateList) strMaxDate = str(maxDate) maxDateList = strMaxDate.split('-') day = maxDateList[2].rstrip('0: ') maxDateList.pop(2) maxDateList.append(day) for inList in table: if inList[5] == maxDateList[0] and inList[3] == maxDateList[1] and inList[4] == maxDateList[2]: return inList[1] def get_the_sum_of_prices(item_ids): """ Reads the table of sales with the help of the data_manager module. Returns the sum of the prices of the items in the item_ids. Args: item_ids (list of str): the ids Returns: number: the sum of the items' prices """ table = data_manager.get_table_from_file("sales/sales.csv") sum = 0 for items in table: if items[0] in item_ids: sum += int(items[2]) else: pass return sum def get_the_sum_of_prices_from_table(table, item_ids): """ Returns the sum of the prices of the items in the item_ids. Args: table (list of lists): the sales table item_ids (list of str): the ids Returns: number: the sum of the items' prices """ sum = 0 for items in table: if items[0] in item_ids: sum += int(items[2]) else: pass return sum def get_customer_id_by_sale_id(sale_id): """ Reads the sales table with the help of the data_manager module. Returns the customer_id that belongs to the given sale_id or None if no such sale_id is in the table. Args: sale_id (str): sale id to search for Returns: str: customer_id that belongs to the given sale id """ table = data_manager.get_table_from_file("sales/sales.csv") customer_id = "" for items in table: if sale_id == items[0]: customer_id = items[6] else: pass return customer_id def get_customer_id_by_sale_id_from_table(table, sale_id): """ Returns the customer_id that belongs to the given sale_id or None if no such sale_id is in the table. Args: table: table to remove a record from sale_id (str): sale id to search for Returns: str: customer_id that belongs to the given sale id """ customer_id = "" for items in table: if sale_id == items[0]: customer_id = items[6] else: pass return customer_id def get_all_customer_ids(): """ Reads the sales table with the help of the data_manager module. Returns: set of str: set of customer_ids that are present in the table """ table = data_manager.get_table_from_file("sales/sales.csv") customer_ids = set() for items in table: customer_ids.add(items[6]) return customer_ids def get_all_customer_ids_from_table(table): """ Returns a set of customer_ids that are present in the table. Args: table (list of list): the sales table Returns: set of str: set of customer_ids that are present in the table """ customer_ids = set() for items in table: customer_ids.add(items[6]) return customer_ids def get_all_sales_ids_for_customer_ids(): """ Reads the customer-sales association table with the help of the data_manager module. Returns a dictionary of (customer_id, sale_ids) where: customer_id: sale_ids (list): all the sales belong to the given customer (one customer id belongs to only one tuple) Returns: (dict of (key, value): (customer_id, (list) sale_ids)) where the sale_ids list contains all the sales id belong to the given customer_id """ table = data_manager.get_table_from_file("sales/sales.csv") my_dict = {} for t in table: my_dict.setdefault(t[6], []).append(t[0]) return my_dict def get_all_sales_ids_for_customer_ids_from_table(table): """ Returns a dictionary of (customer_id, sale_ids) where: customer_id: sale_ids (list): all the sales belong to the given customer (one customer id belongs to only one tuple) Args: table (list of list): the sales table Returns: (dict of (key, value): (customer_id, (list) sale_ids)) where the sale_ids list contains all the sales id belong to the given customer_id """ my_dict = {} for t in table: my_dict.setdefault(t[6], []).append(t[0]) return my_dict def get_add(list): sum = 0 for items in list: sum += items return sum def get_num_of_sales_per_customer_ids(): """ Reads the customer-sales association table with the help of the data_manager module. Returns a dictionary of (customer_id, num_of_sales) where: customer_id: num_of_sales (number): number of sales the customer made Returns: dict of (key, value): (customer_id (str), num_of_sales (number)) """ table = data_manager.get_table_from_file("sales/sales.csv") my_dict = {} for t in table: sum = 0 if t[6] not in my_dict: my_dict.setdefault(t[6], []).append((sum+1)) else: my_dict.setdefault(t[6], []).append((sum+1)) result = {key: get_add(values) for key, values in my_dict.items()} return result def get_num_of_sales_per_customer_ids_from_table(table): """ Returns a dictionary of (customer_id, num_of_sales) where: customer_id: num_of_sales (number): number of sales the customer made Args: table (list of list): the sales table Returns: dict of (key, value): (customer_id (str), num_of_sales (number)) """ my_dict = {} for t in table: sum = 0 if t[6] not in my_dict: my_dict.setdefault(t[6], []).append((sum+1)) else: my_dict.setdefault(t[6], []).append((sum+1)) result = {key: get_add(values) for key, values in my_dict.items()} return result
8e2989008f52b56dee43360378533c5b4a757d90
josego85/livescore-cli
/lib/tt.py
2,078
4.40625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import re ''' module to convert the given time in UTC to local device time _convert() method takes a single time in string and returns the local time convert() takes a list of time in string format and returns in local time NOTE: any string not in the format "digits:digits" will be returned as is USAGE: >>>convert(['19:45','18:15','5:45','512','FT']) ['01:00','00:00','11:30','512','FT'] isgreat(time1,time2) takes two time strings such as "4:30" and "12"15" and returns if the first time is greater than the second. if time1>time2: return 1 if time2>time1: return -1 if time1==time2: return 0 NOTE: the function stalls if not in the above format USAGE: >>>isgreat("3:00","4:15") -1 ''' if time.daylight: offsetHour = time.altzone / 3600.0 else: offsetHour = time.timezone / 3600.0 hour = int(-offsetHour) minute = int(-offsetHour * 60 % 60) def _convert(time): if bool(re.match(r'[0-9]{1,2}:[0-9]{1,2}', time)): time = list(map(int, time.split(':'))) time[1] += minute time[0] += hour if time[1] > 59: time[1] -= 60 time[0] += 1 elif time[1] < 0: time[1] += 60 time[0] -= 1 if time[0] < 0: time[0] += 24 elif time[0] > 23: time[0] -= 24 time = _fix(str(time[0])) + ":" + _fix(str(time[1])) return time def _fix(y): if len(y) == 1: y = '0' + y return y def convert(times): times = list(map(_convert, times)) return times def is_great(time1, time2): t1 = list(map(int, time1.split(':'))) t2 = list(map(int, time2.split(':'))) if t1[0] > t2[0]: return 1 elif t2[0] > t1[0]: return -1 else: if t1[1] > t2[1]: return 1 elif t2[1] > t1[1]: return -1 else: return 0 def datetime_now(): return time.strftime("%c")
8a24e0a0f9795f924856420f34c1f57a0034b0e4
Daniel451/praktikumNN
/PyObjMLP/NeuralNetworkClass.py
15,969
3.703125
4
__author__ = 'daniel' import numpy import LayerClass import sys class NeuralNetwork: def __init__(self, in_input, hiddenLayerList, outputLayerLength, out_expected, label="no-name"): """ :param in_input: InputLayer -> List of lists which hold input value/data for each input neuron Must have same length as out_expected Example for XOR-Problem: [ [0,0], [0,1], [1,0], [1,1] ] :param hiddenLayerList: List of Hidden Layers Example: [2,3,2] would create 3 Hidden Layers with 2, 3 and 2 Neurons :param outputLayerLength: Integer -> Number of output Neurons :param out_expected: List containing lists which hold expected output values/data Must have same length as in_input Example for XOR-Problem: [ [0], [1], [1], [0] ] """ self.__checkForErrors(in_input, hiddenLayerList, outputLayerLength, out_expected) # set the label of the net self.label = str(label) # set the input layer data and length self.inputLayer = in_input self.inputLayerLength = len(self.inputLayer[0]) # set the exptected output values for each entry in inputLayer self.outExpected = out_expected # initialize hiddenLayer self.hiddenLayer = [] # insert the length of input layer to the beginning of the hiddenLayerList # this is needed to calculate the weights for layer 1 of the hidden layers hiddenLayerList.insert(0, self.inputLayerLength) # create all hidden layers in one loop for i in range(1, len(hiddenLayerList)): # append one complete layer to hiddenLayer # Layer( neuronCount, parentLayerLength, label ) self.hiddenLayer.append(LayerClass.Layer(hiddenLayerList[i], hiddenLayerList[i-1], i)) # create the output layer # Layer( neuronCount, parentLayerLength, label ) self.outputLayer = LayerClass.Layer(outputLayerLength, self.hiddenLayer[len(self.hiddenLayer)-1].getLength(), "Output") # make all layers easy accessable self.hiddenAndOutputLayer = [] self.hiddenAndOutputLayer += self.hiddenLayer self.hiddenAndOutputLayer.append(self.outputLayer) def teach(self, iterations = 1000, epsilon=0.2): """ train the net :param iterations: number of learning steps to make :param epsilon: learning rate """ for i in range(0, iterations): # set input and expectedOutput randomSelect = numpy.random.randint(0, len(self.inputLayer)) input = numpy.array(self.inputLayer[randomSelect]) self.currentOutExpected = numpy.array(self.outExpected[randomSelect]) # feedforward self.output = self.__feedforward(input) # calculate errors self.__updateErrors() # update weights self.__updateWeights(input, epsilon) # update bias self.__updateBias(epsilon) def __updateErrors(self): debug = False # calculate the erros # for index in range ( endOfTheList, beginningOfTheList, decrement index by 1 ) # so this loop starts at the end of all layers (outputLayer) # and iterates its way to the top for i in range( len(self.hiddenAndOutputLayer) - 1, -1, -1 ): # error for output layer --- first iteration if i == (len(self.hiddenAndOutputLayer)-1): self.outputLayer.setError( self.currentOutExpected - self.output ) if debug: self.__print("output error:", self.outputLayer.getError()) # error for hidden layers else: # get current layer to update its error currentLayer = self.hiddenAndOutputLayer[i] # get the underlyingLayer (lambda+1) for backpropagation/calculation underlyingLayer = self.hiddenAndOutputLayer[i+1] # calculate new error currentLayer.setError( self.transferFunctionDeriv( currentLayer.getLastInnerActivation() ) * numpy.dot( underlyingLayer.getError(), underlyingLayer.getAllWeightsOfNeurons() ) ) if debug: print("") self.__print("layer", i) self.__print("activation", currentLayer.getLastInnerActivation()) self.__print("_deriv(activation)", self.transferFunctionDeriv(currentLayer.getLastInnerActivation())) self.__print("underlyingLayer.error", underlyingLayer.getError()) self.__print("underlyingLayer.weights", underlyingLayer.getAllWeightsOfNeurons()) self.__print("error x weights", numpy.dot(underlyingLayer.getError(),underlyingLayer.getAllWeightsOfNeurons()) ) self.__print("new error (acti * (error x weights))", currentLayer.getError()) def __print(self, label, item): print(str(label) + " :\n" + str(item)) def __updateBias(self, epsilon): """ update the bias of the net """ for layer in self.hiddenAndOutputLayer: layer.setBias( layer.getAllBiasOfNeurons() + ( epsilon * layer.getError() ) ) def __updateWeights(self, u_input, epsilon): """ update the weights of the net """ debug = False # for each layer update the weights at once for key, layer in enumerate(self.hiddenAndOutputLayer): # for the first hidden layer it is epsilon * error * input if key == 0: layer.setWeights( layer.getAllWeightsOfNeurons() + ( epsilon * ( layer.getError()[numpy.newaxis].T * u_input ) ) ) if debug: print("") self.__print("weights", layer.getAllWeightsOfNeurons()) self.__print("epsilon", epsilon) self.__print("layer error", layer.getError()[numpy.newaxis].T) self.__print("input", u_input) self.__print("error x input", layer.getError()[numpy.newaxis].T * u_input) self.__print("epsilon * (error x input)", epsilon * ( layer.getError()[numpy.newaxis].T * u_input )) self.__print("new weights: ", layer.getAllWeightsOfNeurons() + ( epsilon * ( layer.getError()[numpy.newaxis].T * u_input ) )) # for all other hidden layers and output layer the calculation # is epsilon * error * output_of_parent_layer else: layer.setWeights( layer.getAllWeightsOfNeurons() + ( epsilon * ( layer.getError()[numpy.newaxis].T * self.hiddenAndOutputLayer[key-1].getLastOutput() ) ) ) if debug: print("") self.__print("weights", layer.getAllWeightsOfNeurons()) self.__print("epsilon", epsilon) self.__print("layer error", layer.getError()[numpy.newaxis].T) self.__print("input (parent output)", self.hiddenAndOutputLayer[key-1].getLastOutput()) self.__print("error x input", layer.getError()[numpy.newaxis].T * self.hiddenAndOutputLayer[key-1].getLastOutput()) self.__print("epsilon * (error x input)", epsilon * ( layer.getError()[numpy.newaxis].T * self.hiddenAndOutputLayer[key-1].getLastOutput() )) self.__print("new weights: ", layer.getAllWeightsOfNeurons() + ( epsilon * ( layer.getError()[numpy.newaxis].T * self.hiddenAndOutputLayer[key-1].getLastOutput() ) )) def __feedforward(self, f_input): """ does an feedforward activation of the whole net :param f_input: has to be a numpy array matching the dimension of InputLayer """ ###################### ### initialization ### ###################### # set last_out to current input last_out = f_input ####################################### ### start calculating - feedforward ### ####################################### # feedforward - loop through all layers for key, layer in enumerate(self.hiddenAndOutputLayer): layer = self.hiddenAndOutputLayer[key] parentLayer = self.hiddenAndOutputLayer[key-1] # calculate inner activation without bias # numpy.dot of all neuron weights of the current layer and the output of the parent layer innerActivation = numpy.dot(layer.getAllWeightsOfNeurons(), last_out) # add the bias of each neuron to the innerActivation innerActivation += layer.getAllBiasOfNeurons() # standardize innerActivation innerActivation /= parentLayer.getLength() # save new innerActivation values in layer layer.setLastInnerActivation(innerActivation) # calculate new output of the current layer # this is used as input for the next layer in the next iteration # or as output for the output layer when the loop is finished last_out = self.transferFuction(innerActivation) # save new output values in layer layer.setLastOutput(last_out) return layer.getLastOutput() def calculate(self, c_input, expOut = None): """ calculate the output for some given input (feedforward activation) :param c_input: a list, containing the input data for input layer """ ###################### ### error checking ### ###################### # check if c_input is set correctly if not ( (type(c_input) is list) and (len(c_input) == self.inputLayerLength) ): sys.exit("Error: c_input has to be a list containing the input data of length " + str(self.inputLayerLength)) # set the output of the net self.output = self.__feedforward(numpy.array(c_input)) print("") print("#################################################################") print("## calculating... ##") print("#################################################################") print("## Input was: ##") print(c_input) if expOut: print("## ##") print("## Expected Output is: ##") print(expOut) print("## ##") print("## Output is: ##") print(self.output) print("## ##") print("## Output is (3 decimal places): ##") print( numpy.round(self.output,3) ) print("## ##") print("## Output is (0 decimal places): ##") print( numpy.round(self.output,0) ) print("## ##") print("#################################################################") print("") def transferFuction(self, x): return numpy.tanh(x) def transferFunctionDeriv(self, x): return 1 - numpy.power(numpy.tanh(x), 2) def printNetWeights(self): print("######################################################") print(" neural net: " + self.label) print("######################################################") print("") print("###############") print("### weights ###") print("###############") print("") print("-> " + str(len(self.hiddenAndOutputLayer)) + " layers total (hidden + output layer, input is not counted)") print("-> layer " + str(len(self.hiddenAndOutputLayer)-1) + " is the output layer") print("") for key, layer in enumerate(self.hiddenAndOutputLayer): print("--- Layer: " + str(key) + " --- (" + str(layer.getLength()) + " neurons total | each row represents the weights of one neuron)") for neuronweight in layer.getAllWeightsOfNeurons(): print(neuronweight) print("") def __checkForErrors(self, in_input, hiddenLayerList, outputLayerLength, out_expected): """ checks for errors before starting current init things """ errStr = "!!!!!!!!!!!!!\n" errStr += "!!! ERROR !!!\n" errStr += "!!!!!!!!!!!!!\n" errStr += "\n" # check if input data and expected output and hiddenLayerList are lists if not ( (type(in_input) is list) and (type(out_expected) is list) and (type(hiddenLayerList) is list) ): errStr += "Error: in_input, hiddenLayerList and out_expected must be lists" sys.exit(errStr) if not ( (type(outputLayerLength) is int) and (outputLayerLength > 0) ): errStr += "Error: outputLayerLength has to be an integer > 0" sys.exit(errStr) # check input data length and expected output data length if len(in_input) != len(out_expected): errStr += "Error: the length of the input data list does not match the length " errStr += "of the expected output data list" sys.exit(errStr)
18518e9f199ab496543d8ab73e6ba210326effff
zxy987872674/LearnCode
/python/commonPackage/Re/learnGroup.py
1,251
3.59375
4
#coding=utf-8 ''' match和search一旦匹配成功,就是一个match object对象,而match object对象有以下方法: group() 返回被 RE 匹配的字符串 start() 返回匹配开始的位置 end() 返回匹配结束的位置 span() 返回一个元组包含匹配 (开始,结束) 的位置 group() 返回re整体匹配的字符串,可以一次输入多个组号,对应组号匹配的字符串。 a. group()返回re整体匹配的字符串, b. group (n,m) 返回组号为n,m所匹配的字符串,如果组号不存在,则返回indexError异常 c.groups()groups() 方法返回一个包含正则表达式中所有小组字符串的元组,从 1 到所含的小组号,通常groups()不需要参数,返回一个元组,元组中的元就是正则表达式中定义的组。 ''' import re a = "123abc456" print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0)) #123abc456,返回整体 print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1)) #123 print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2)) #abc print(re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3)) #456 ###group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3) 列出第三个括号匹配部分。###
3c865ce1b84c94cb1d888623993f382bf1da0119
claudiaps/Atividades_Grafos
/frete/frete.py
551
3.640625
4
import graph def main(): base_input = input().split(' ') # le o input do usuario numero_cidades = int(base_input[0]) gp = graph.Graph() for i in range(1, numero_cidades+1): gp.add_vertex(str(i)) numero_pares = int(base_input[1]) for i in range(numero_pares): base_input = input().split(' ') gp.add_edge(gp.get_vertex(base_input[0]), gp.get_vertex(base_input[1]), value=int(base_input[2])) distance = gp.dijkistra(gp.get_vertex('1')) print(distance[gp.get_vertex(str(numero_cidades))]) main()
e35d0410866646f3f604dc8d2a628a67ea19ee6e
sclarke/adventofcode2017
/d23.py
2,131
3.609375
4
from collections import defaultdict import math with open('d23_input.txt') as f: puzzle_input = [line.strip().split() for line in f.readlines()] def run_program(instructions, part2_mode=False): registers = defaultdict(int) if part2_mode: registers['a'] = 1 pointer = 0 mul_count = 0 def get_value(n): return int(n) if not n.isalpha() else registers[n] def cpy(x, y): registers[x] = get_value(y) def sub(x, y): registers[x] -= get_value(y) def mul(x, y): registers[x] *= get_value(y) def jnz(x, y): nonlocal pointer if (get_value(x)) != 0: pointer += get_value(y) else: pointer += 1 commands = dict(set=cpy, sub=sub, mul=mul, jnz=jnz) while 0 <= pointer < len(instructions): try: cmd, *par = instructions[pointer] except IndexError: break # this is interesting if we hack the input values to smaller/manageable numbers if part2_mode and pointer == 24: print(registers) commands[cmd](*par) if cmd != 'jnz': pointer += 1 if not part2_mode and cmd == 'mul': mul_count += 1 return mul_count def is_prime(n): if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) print('Part 1:', run_program(puzzle_input)) # only useful if the program is hacked to be faster (i.e., smaller register values in the input file) # print(run_program(puzzle_input, part2_mode=True)) # with smaller numbers in the input registers, the inconsistent increment of register h becomes apparent. # Looks like h doesn't increment for each value of b (stepping by 17) when b is prime. # for n in range(81, 1781, 17): # print(n, is_prime(n)) register_b = 81 * 100 + 100_000 # puzzle_input[0], puzzle_input[4], puzzle_input[5] register_c = register_b + 17_000 # puzzle_input[6], puzzle_input[7] step_size = 17 # puzzle_input[30] print('Part 2:', sum(not is_prime(n) for n in range(register_b, register_c + 1, step_size)))
c5730814dc5fe6c882bdd9da2bed29cf57b7c174
sclarke/adventofcode2017
/d12.py
1,460
3.625
4
test_input = """ 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5""".strip().splitlines() with open('d12_input.txt') as f: puzzle_input = f.readlines() def build_groups(inp): return dict(parse_line(line) for line in inp) def parse_line(line): """return the index and direct links described by a string representing a pipe""" k, v = line.strip().split(' <-> ') return k, v.split(', ') def get_all_links(pipes, root_node="0"): """given a dict of links, walk the tree to find all possible endpoints from a given startpoint""" new_nodes = links = {root_node} while True: new_links = set() for node in new_nodes: new_links |= set(pipes[node]) if new_links.issubset(links): break else: links |= new_links new_nodes = new_links return links def get_all_groups(pipes): """given a dict of links, remove a family of nodes until all the families are gone""" groups = list() while pipes: random_node = next(iter(pipes)) links = get_all_links(pipes, root_node=random_node) groups.append(links) for link in links: del pipes[link] return groups print(len(get_all_links(build_groups(test_input)))) print(len(get_all_links(build_groups(puzzle_input)))) print(len(get_all_groups(build_groups(test_input)))) print(len(get_all_groups(build_groups(puzzle_input))))
e5f6cbd259cc613d9b22f3f92f355a2cf3111bad
JHyuna/BOJ_Algorithm
/1 prob each day/B2-12605.py
144
3.5
4
n = int(input()) for i in range(1,n+1): string = reversed(input().rstrip().split()) print('Case #' + str(i) + ': ' + ' '.join(string))
1cf6a640c2aa811acb14cb9552e2ce0ec035834e
JHyuna/BOJ_Algorithm
/1 prob each day/B3-4153.py
257
3.65625
4
while True: in_value = input() if in_value != '0 0 0': L = sorted(tuple(map(int, in_value.split()))) if L[-1]**2 == (L[0]**2 + L[1]**2): print('right') else: print('wrong') else: break
17488c10bb60d5145c5f1427f07947ba8d399602
JHyuna/BOJ_Algorithm
/1 prob each day/B3-1547.py
235
3.609375
4
a = [0,1,2,3] # 인덱스활용을 쉽게 하기 위해 1번 컵의 인덱스를 1로 조정 n = int(input()) for _ in range(n): i,j = map(int, input().split()) a[i],a[j] = a[j],a[i] print(a.index(1)) # 1번 컵의 위치를 뽑기
9af2b9f10033e86f5d76efc59890853944c074e8
tdworowy/PythonPlayground
/Playground/Python_Staff/Functions_/recursion.py
805
3.734375
4
def my_sum(l): print(l) try: if not l: return 0 else: return l[0] + my_sum(l[1:]) except RecursionError as re: print(re) return 0 def my_sum2(l): try: first, *rest = l print(l) return first if not rest else first + my_sum2(rest) except RecursionError as re: print(re) return 0 except MemoryError as re: print(re) return 0 def sum_tree(l): tot = 0 for x in l: if not isinstance(x, list): tot += x else: tot += sum_tree(x) print(tot) return tot if __name__ == "__main__": l = list(range(1, 999999, 1)) l2 = list(range(1, 99, 1)) L = [1, [2, [3, [4, 5, 5], 6, 8], 2], 5] print(sum_tree(L))
2fc23ce67186f112699e3f53aa9c30db64eb6969
tdworowy/PythonPlayground
/Playground/Exercises/exer41_longest_common_prefix.py
927
3.828125
4
from typing import List def longest_common_prefix(strs: List[str]) -> str: if not strs: return "" shortest = min(strs, key=len) for i, ch in enumerate(shortest): for other in strs: if other[i] != ch: return shortest[:i] return shortest if __name__ == "__main__": print(longest_common_prefix(["flower", "flow", "flight"])) print(longest_common_prefix([""])) print(longest_common_prefix(["a"])) print(longest_common_prefix(["ab", "a"])) print(longest_common_prefix(["aa", "ab"])) print(longest_common_prefix(["aca", "cba"])) print(longest_common_prefix(["", ""])) print(longest_common_prefix(["", "b"])) print(longest_common_prefix(["a", "ac"])) print(longest_common_prefix(["baab", "bacb", "b", "cbc"])) print(longest_common_prefix(["reflower", "flow", "flight"])) print(longest_common_prefix(["aaa", "aa", "aaa"]))
74bc4222b6e007c9667db92c7e3e83ec23add7fb
tdworowy/PythonPlayground
/Playground/Exercises/exer27_luck_balance.py
534
3.578125
4
contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]] k = 3 def luck_balance(k, contests): max_luck = 0 loose_important = 0 contests.sort(reverse=True) for contest in contests: if contest[1] == 0: max_luck += contest[0] else: if loose_important < k: max_luck += contest[0] loose_important += 1 else: max_luck -= contest[0] return max_luck if __name__ == "__main__": print(luck_balance(k, contests))
afd20e690a99e1cc6d1e81d3d9b309c34faaae5c
tdworowy/PythonPlayground
/Playground/Algorithms/search/binary_search.py
634
3.796875
4
from random import randint from Playground.my_utils.staff.timer3 import timer3 @timer3 def binary_search(list_: list, item): """list_ must be sorted""" first = 0 last = len(list_) - 1 while first <= last: mind_point = (first + last) // 2 if list_[mind_point] == item: return True else: if item < list_[mind_point]: last = mind_point - 1 else: first = mind_point + 1 return False if __name__ == '__main__': list_ = [randint(0, 10000) for x in range(100000)] list_.sort() print(binary_search(list_, 500))
aecb84b02845448af1d14231c361784d1648a4e2
tdworowy/PythonPlayground
/Playground/Algorithms/graph_theory/searching/depth_first_search.py
836
3.734375
4
import networkx as nx import matplotlib.pyplot as plt def depth_first_search(graph: dict, start: str, visited: set = None) -> set: if visited is None: visited = set() visited.add(start) print(start) for next_ in graph[start] - visited: depth_first_search(graph, next_, visited) return visited if __name__ == "__main__": graph = { 'Amin': {'Wasim', 'Nick', 'Mike'}, 'Wasim': {'Imran', 'Amin'}, 'Imran': {'Wasim', 'Faras'}, 'Faras': {'Imran'}, 'Mike': {'Amin'}, 'Nick': {'Amin'} } res1 = depth_first_search(graph, 'Amin') print("_" * 10) res2 = depth_first_search(graph, 'Mike') graph1 = nx.DiGraph(graph) print(res1) print(res2) nx.draw(graph1, with_labels=True, node_color='y', node_size=800) plt.show()
7cf3e7e2beb6eaf848222ea04aa50f6b98bc613e
tdworowy/PythonPlayground
/Playground/Algorithms/math/chinese_remainder_theorem.py
496
3.65625
4
def extended_gcd(a: int, b: int) -> tuple: assert a >= 0 and b >= 0 and a + b > 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) return d, x, y def chinese_remainder_theorem(n1, r1, n2, r2): (_, x, y) = extended_gcd(n1, n2) n = x * n1 * r2 + y * n2 * r1 return n % (n1 * n2) if __name__ == "__main__": print(chinese_remainder_theorem(686579304, 295310485, 26855093, 8217207))
3e99c0a7604aab2ba84d72aec599904d2d8c20a5
tdworowy/PythonPlayground
/Playground/Exercises/exer35_number_format.py
201
3.625
4
def print_formatted(number): w = len(f'{number:b}') for n in range(1, number + 1): print(f'{n:={w}} {n:={w}o} {n:={w}X} {n:={w}b}') if __name__ == '__main__': print_formatted(99)
2da5f1a682922369aab5671f38cee51472c2cebc
tdworowy/PythonPlayground
/Playground/Python_Staff/OOP/ovrloading/iters1.py
744
3.78125
4
class Squares: def __init__(self, start, stop): if self.check(start): self.value = start - 1 self.stop = stop else: self.value = 0 self.stop = 0 def __iter__(self): return self def __next__(self): if self.value == self.stop: raise StopIteration self.value += 1 return self.value ** 2 def check(self, value): flag = value > 0 if not flag: print("\nstart value must be >0") return flag if __name__ == "__main__": for i in Squares(1, 20): print(i, end=" ") for i in Squares(0, 20): print(i, end=" ") for i in Squares(-1, 20): print(i, end=" ")
6776d2097a5446cfb1a14a91c9e684114d59053f
tdworowy/PythonPlayground
/Playground/Algorithms/graph_theory/gale_shapley_algoritmh.py
1,173
3.65625
4
def stable_matching(n: int, men_preferences: list, women_preferences) -> list: unmarried_men = list(range(n)) man_spouse = [None] * n woman_spouse = [None] * n next_man_choice = [0] * n while unmarried_men: he = unmarried_men[0] his_preferences = men_preferences[he] she = his_preferences[next_man_choice[he]] her_preferences = women_preferences[she] current_husband = woman_spouse[she] if current_husband is None: next_man_choice[he] = next_man_choice[he] + 1 man_spouse[he], woman_spouse[she] = she, he unmarried_men.remove(he) else: next_man_choice[he] = next_man_choice[he] + 1 if her_preferences.index(current_husband) > her_preferences.index(he): man_spouse[he], woman_spouse[she] = she, he man_spouse[current_husband] = None unmarried_men.remove(he) unmarried_men.append(current_husband) return man_spouse if __name__ == "__main__": assert (stable_matching(1, [[0]], [[0]]) == [0]) assert (stable_matching(2, [[0, 1], [1, 0]], [[0, 1], [1, 0]]))
fa886013b6d810ce7f844b42dc2967c14568c619
tdworowy/PythonPlayground
/Playground/my_utils/staff/random_string.py
322
3.640625
4
import string from random import choices def generate_random_string(size): return "".join(choices(string.ascii_lowercase, k=size)) def generate_random_string_all(size): return ''.join(choices(string.ascii_letters + string.digits, k=size)) if __name__ == '__main__': print(generate_random_string_all(12))
365dea86fb894b0afd126443b31efe81c301542d
tdworowy/PythonPlayground
/Playground/Python_Staff/Tests/unit_tests2.py
423
3.765625
4
print("I'm : ", __name__) def min_max(test, *args): res = args[0] for arg in args: if test(arg, res): res = arg return res def less_than(x, y): return x < y def greater_than(x, y): return x > y if __name__ == '__main__': # tests , won't run if module is imported print(min_max(less_than, 4, 2, 1, 4, 67, 8, 9, 3, 1)) print(min_max(greater_than, 4, 2, 1, 4, 67, 8, 9, 3, 1))
c9c6c0860f6ae331a292e90f1f2aebfb340227f6
tdworowy/PythonPlayground
/Playground/Python_Staff/metaclasses/meta5_Overloading_call.py
960
3.609375
4
class SuperMeta: def __call__(self, classname, supers, classdic): print("in SuperMeta.call: ", classname, supers, classdic, sep='\n') Class = self.__new__(classname, supers, classdic) self.__init__(Class,classname, supers, classdic) return Class class SubMeta(SuperMeta): def __new__(self,classname,supers,classdic): print("in SubMeta.new: ",classname,supers,classdic,sep='\n') return type(classname,supers,classdic) def __init__(self,Class,classname,supers,classdic): print("in SubMeta.init: ", classname, supers, classdic, sep='\n') print("...... Object initialized. Class:",list(Class.__dict__.keys())) class Eggs: pass if __name__ == '__main__': print("Create class") class Spam(Eggs,metaclass=SubMeta()):# that example did not work data = 1 def meth(self,arg): pass print("Add instance") X =Spam() print("Data: ",X.data)
65994e9c687f0d2fa7f77765f0e39ff216798fc7
tdworowy/PythonPlayground
/Playground/Exercises/exer33_count_triplets.py
980
3.734375
4
from itertools import permutations # performance could by much better def count_triplets(arr: list, r: int) -> int: try: if len(arr) <= 2: return 0 triplets = [tuple(sorted(per)) for per in permutations(arr, 3)] count = 0 for triplet in triplets: if triplet[1] == triplet[0] * r and triplet[2] == triplet[1] * r: count += 1 return count // 6 except Exception: return 0 if __name__ == '__main__': arr = [1, 5, 5, 25, 125] r = 5 triplets_count = count_triplets(arr, r) print(triplets_count) # 4 arr = [1, 3, 9, 9, 27, 81] r = 3 triplets_count = count_triplets(arr, r) print(triplets_count) # 6 arr = [1] * 100 r = 1 triplets_count = count_triplets(arr, r) print(triplets_count) # 161700 arr = [1237] * 100000 r = 1 triplets_count = count_triplets(arr, r) print(triplets_count) # 166661666700000 # memory error
00b71c3107af4a6423504b0bd808e327b4e9eec8
Nhlamulomax/Lottery_Project
/lottery.py
4,725
3.78125
4
import random from datetime import datetime, date import calendar import csv class NationLottery: # # Function to populate entry ticket def populate_draw_ticket(self): x = 0 y = 6 entry_ticket = [] # List to store 6 draw numbers from the user while x < 6: user_number = input("Please enter " + str(y) + " numbers into your National Lottery Entry Ticket: ") if str(user_number) == '': print( 'The Entry Ticket should have 6 number, please you are not allowed to skip to enter a number. Thanks!') user_number = input("Please enter " + str(y) + " numbers into your National Lottery Entry Ticket: ") else: pass entry_ticket.append(user_number) x += 1 y -= 1 return entry_ticket # Function to generate 7 winning numbers including bonus number which is the last number def generate_winning_numbers(self): nums = [] # List containing the 7 winning numbers including bonus y = 0 while y < 7: for x in range(7): lottery_number = random.randint(1, 49) nums.append(lottery_number) y += 1 return nums # Function to get a winning number by comparing the entered tickets to the winning numbers. def getting_winning_numbers(self): count = 0 my_date = date.today() tdays_day = calendar.day_name[my_date.weekday()] european_countries = ['Belgium', 'Bulgaria', 'Croatia', 'Austria', 'Cyprus', 'Czech Republic', 'Denmark', 'Finland', 'Netherlands', 'Poland', 'Switzerland', 'Russia', 'Germany', 'Turkey', 'France', 'Italy', 'United Kingdom', 'Greece', 'Portugal', 'Macedonia', 'Latvia', 'Monaco', 'San Marino', 'Liechtenstein', 'Andorra', 'Isle of Man', 'Jersey', 'Malta', 'Iceland', 'Estonia'] week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] all_national_lottery = 0 # National lotteries run once a week, so I choose to run it every wednsday if tdays_day == week[2]: winning_numbers = self.generate_winning_numbers # A list of 6 winning numbers and 1 bonus, calling generate_winning_numbers() # There are currently 30 independent national lotterie while all_national_lottery < 30: country = (european_countries[all_national_lottery]).lower() draw_date = date.today() draw_number = 2589 entry_ticket_file = country + '_' + str(draw_date) + '_' + str(draw_number) draw_numbers = self.populate_draw_ticket() # Comparing the entered tickets to the winning numbers. for d_nums in draw_numbers: for w_nums in winning_numbers: if int(d_nums) == int(w_nums): print(str(d_nums)) count += 1 # Count matched numbers (Main ball set) n (Any additional ball sets) else: pass # If a Ticket has matched all numbers, indicate that the jackpot was won if count == 6: print(country + " has won the Jackpot, yeeeeee!") if count >= 1: # Indicate number of winning numbers the player won print(country + " won " + str(count) + " number(s)") else: print(country + " did not win any number, we are sorry you should try again") print(" ") # Uploading entry tickets into CSV file with open(entry_ticket_file + '.csv', 'w') as csvFile: writer = csv.writer(csvFile) writer.writerows(str(draw_numbers)) csvFile.close() # Upload winning numbers into CSV file with open(entry_ticket_file + '.csv', 'w') as csvFile: writer = csv.writer(csvFile) writer.writerows(str(winning_numbers)) csvFile.close() # Increment my While Loop all_national_lottery += 1 def run(self): self.getting_winning_numbers() #a = NationLottery() #a.getting_winning_numbers() if __name__ == '__main__': NationLottery().run()
66223d5145ced27275b93e64d71f623d6fb99411
dwaynethebard/djisktra-vs-Astar
/TwoThreeNode.py
15,573
4
4
class TwoThreeNode: def __init__(self, parent=None, count=0, smallest=None, largest=None, left=None, middle=None, right=None): self.parent = parent self.count = count self.smallest = smallest self.largest = largest self.left = left self.middle = middle self.right = right ######################## # comparison operators # ######################## def __lt__(self, other): if self.largest == other.largest: return self.smallest < other.smallest else: return self.largest < other.largest def __le__(self, other): if self.largest == other.largest: return self.smallest <= other.smallest else: return self.largest <= other.largest def __gt__(self, other): if self.largest == other.largest: return self.smallest > other.smallest else: return self.largest > other.largest def __ge__(self, other): if self.largest == other.largest: return self.smallest >= other.smallest else: return self.largest >= other.largest def __eq__(self, other): return (self.largest == other.largest and self.smallest == other.smallest) def __ne__(self, other): return (self.largest != other.largest or self.smallest != other.smallest) ############# # to string # ############# # delegates to recursive depth-first search "treeToStr" def __str__(self): return self.str(self, "") def str(self, node, indent=""): if isInterior(node): cargo = indent + "(v " + str(node.smallest) + \ " : ^ " + str(node.largest) + \ " : # " + str(node.count) + ')\n' else: return indent + str(node) + '\n' left = node.str(node.left, indent + " |") middle = node.str(node.middle, indent + " |") right = "" if hasThreeChildren(node): right = node.str(node.right, indent + " |") return cargo + left + middle + right def list(self): if isInterior(self.left): if hasThreeChildren(self): output = (self.left.list() + self.middle.list() + self.right.list()) else: output = (self.left.list() + self.middle.list()) return output else: if hasThreeChildren(self): output = [self.left, self.middle, self.right] else: output = [self.left, self.middle] return output ######################### # search implementation # ######################### def search(self, value, index): if isInterior(self.left): # do recursions based on values if value <= self.left.largest: return self.left.search(value, index) index += self.left.count if value <= self.middle.largest: return self.middle.search(value, index) index += self.middle.count if (hasThreeChildren(self) and value <= self.right.largest): return self.right.search(value, index) return None else: # do inserts based on values if value == self.left: return index index += 1 if value == self.middle: return index index += 1 if value == self.right: return index return None ######################### # select implementation # ######################### def select(self, index): if isInterior(self.left): if index < self.left.count: return self.left.select(index) index -= self.left.count if index < self.middle.count: return self.middle.select(index) index -= self.middle.count if (hasThreeChildren(self) and index < self.right.count): return self.right.select(index) else: return None else: if index == 0: return self.left elif index == 1: return self.middle else: return self.right ######################### # insert implementation # ######################### # deals with everything to do with leaf level insertion # - traversal to leaf level # - insertion at leaf level # - splitting if two many leaves # - call recursive splitting algorithm to repair tree def insert(self, value): # check if we are one level above leaves if isInterior(self.left): # do recursions based on values if value <= self.left.largest: self.left.insert(value) elif (value <= self.middle.largest or not hasThreeChildren(self)): self.middle.insert(value) else: self.right.insert(value) else: # do inserts based on values if not hasThreeChildren(self): self.pinNode(value) else: newNode = self.splitNode(value) self.rippleSplit(newNode) # recursive splitting algorithm that traverses the tree backwards # deals with: # traversal # insertion # identifying when a new root needs to be constructed def rippleSplit(self, overflow): if isRoot(self): self.makeNewRoot(overflow) return else: current = self.parent if not hasThreeChildren(current): current.pinNode(overflow) return else: newNode = current.splitNode(overflow) current.rippleSplit(newNode) # places a node as a child of a node with two children # determines by itself which child it should be given ordering def pinNode(self, overflow): if overflow <= self.left: self.right = self.middle self.middle = self.left self.left = overflow elif overflow <= self.middle: self.right = self.middle self.middle = overflow else: self.right = overflow # ensure the node is not one above the leaves if isInterior(self.left): self.count = self.left.count + self.middle.count + self.right.count self.smallest = self.left.smallest self.largest = self.right.largest overflow.parent = self else: self.count = 3 self.smallest = self.left self.largest = self.right self.correctHeuristics() # takes one node with three children, and one extra child # makes a new node and adjusts the old node # returns the new node def splitNode(self, overflow): temp = sorted([self.left, self.middle, self.right, overflow]) self.left = temp[0] self.middle = temp[1] if isInterior(self.left): self.count = self.left.count + self.middle.count self.smallest = self.left.smallest self.largest = self.middle.largest newNode = TwoThreeNode(self.parent, temp[2].count + temp[3].count, temp[2].smallest, temp[3].largest, temp[2], temp[3], None) newNode.left.parent = newNode newNode.middle.parent = newNode else: self.count = 2 self.smallest = self.left self.largest = self.middle newNode = TwoThreeNode(self.parent, 2, temp[2], temp[3], temp[2], temp[3], None) self.right = None return newNode # creates a new root using two nodes as children # takes the old root and an addition node as the children def makeNewRoot(self, overflow): if isInterior(overflow): newRoot = TwoThreeNode(None, self.count + overflow.count, self.smallest, overflow.largest, self, overflow, None) else: newRoot = TwoThreeNode(None, self.count + overflow.count, self, overflow, self, overflow, None) self.parent = newRoot overflow.parent = newRoot ######################### # delete implementation # ######################### def delete(self, value): if isInterior(self.left): # descend tree if value <= self.left.largest: return self.left.delete(value) elif value <= self.middle.largest: return self.middle.delete(value) elif (hasThreeChildren(self) and value <= self.right.largest): return self.right.delete(value) else: # the value does not exist in the tree return False else: # self.unPinNode(value) # self.rippleMerge() # self.correctHeuristics() # return True # one above leaf level if hasThreeChildren(self): deleted = self.unPinNode(value) if deleted: self.correctHeuristics() return deleted else: deleted = self.unPinNode(value) if deleted: self.rippleMerge() return deleted def unPinNode(self, target): if target == self.left: self.left = self.middle self.middle = self.right elif target == self.middle: self.middle = self.right elif target == self.right: pass else: return False self.right = None self.smallest = self.left self.largest = self.middle self.count = 2 return True # only work when sibling has 3 children def takeFromLeft(self, sibling): self.middle = self.left self.left = sibling.right if not isLeaf(self.left): self.left.parent = self sibling.right = None if not isLeaf(self.left): self.count = self.left.count + self.middle.count self.smallest = self.left.smallest self.largest = self.middle.largest sibling.count = sibling.left.count + sibling.middle.count sibling.smallest = sibling.left.smallest sibling.largest = sibling.middle.largest else: self.count = 2 self.smallest = self.left self.largest = self.middle sibling.count = 2 sibling.smallest = sibling.left sibling.largest = sibling.middle def takeFromRight(self, sibling): self.middle = sibling.left if not isLeaf(self.middle): self.middle.parent = self sibling.left = sibling.middle sibling.middle = sibling.right sibling.right = None if not isLeaf(self.left): self.count = self.left.count + self.middle.count self.smallest = self.left.smallest self.largest = self.middle.largest sibling.count = sibling.left.count + sibling.middle.count sibling.smallest = sibling.left.smallest sibling.largest = sibling.middle.largest else: self.count = 2 self.smallest = self.left self.largest = self.middle sibling.count = 2 sibling.smallest = sibling.left sibling.largest = sibling.middle def rippleMerge(self): if isRoot(self): if hasOneChild(self): self.collapseRoot() return else: current = self.parent if isLeftChild(self): if hasThreeChildren(current.middle): self.takeFromRight(current.middle) else: current.middle.pinNode(self.left) current.left = current.middle current.middle = current.right current.right = None elif isMiddleChild(self): if hasThreeChildren(current.left): self.takeFromLeft(current.left) else: current.left.pinNode(self.left) current.middle = current.right current.right = None else: if hasThreeChildren(current.middle): self.takeFromLeft(current.middle) else: current.middle.pinNode(self.left) current.right = None if hasOneChild(current): current.rippleMerge() else: self.correctHeuristics() def collapseRoot(self): self.left.parent = None # travels up the path used to reach this location, # fixes the heuristics inside the nodes along the path # only fixes the heuristics of ancestors, not the current node def correctHeuristics(self): current = self.parent while isInterior(current): current.count = (current.left.count + current.middle.count) current.smallest = current.left.smallest if(hasThreeChildren(current)): current.count += current.right.count current.largest = current.right.largest else: current.largest = current.middle.largest current = current.parent #################### # Friend functions # #################### def isLeaf(node): return type(node) is not TwoThreeNode def isInterior(node): return type(node) is TwoThreeNode def hasThreeChildren(node): return node.right is not None def hasTwoChildren(node): return (node.right is None and node.middle is not None) def hasOneChild(node): return (node.right is None and node.middle is None and node.left is not None) def isLeftChild(node): return node.parent.left is node def isMiddleChild(node): return node.parent.middle is node def isRightChild(node): return node.parent.right is node def isRoot(node): return node.parent is None
0c900e9b4ad2f2b3e904ee61661cda39ed458646
shivraj-thecoder/python_programming
/Swapping/using_tuple.py
271
4.34375
4
def swap_tuple(value_one,value_two): value_one,value_two=value_two,value_one return value_one,value_two X=input("enter value of X :") Y=input("enter value of Y :") X, Y=swap_tuple(X,Y) print('value of X after swapping:', X) print('value of Y after swapping:', Y)
3ef0e6ed115ebe2fddc00f41289a9745bcec1299
KhMassri/for-test-repo
/nicecode.py~
811
3.875
4
import matplotlib.pyplot as plt plt.figure #create data x_series = [0,1,2,3,4,5] y_series_1 = [x**2 for x in x_series] y_series_2 = [x**3 for x in x_series] #plot data plt.plot(x_series, y_series_1, label="x^2") plt.plot(x_series, y_series_2, label="x^3") #add in labels and title plt.xlabel("Small X Interval") plt.ylabel("Calculated Data") plt.title("Our Fantastic Graph") #add limits to the x and y axis plt.xlim(0, 6) plt.ylim(-5, 80) #create legend plt.legend(loc="upper left") #save figure to png plt.savefig("example.png") import matplotlib.pyplot as plot xs = range(11) ys = [i * 2 for i in xs] zs = [i ** 2 for i in xs] plot.title(r'x * 2 and x ** 2') plot.plot(xs, ys, label=r'$twice$', color='red') plot.plot(xs, zs, ':', label=r'$square$') plot.legend(loc='upper right') plot.show()
7af3a6e053f3fec84eaad6efd69f0c69d8d1e797
inaciofabricio/python
/001 - Python basico/Variaveis.py
204
3.6875
4
# -*- coding: utf-8 -*- a = 5 b = 10 print(a+b) print(type(a+b)) print('') a = 5.0 b = 10.0 print(a+b) print(type(a+b)) print('') texto = "Lorem ipsum dolor sit amet." print(texto) print(type(texto))
b56efda70d65a9dd33277bae1eac032a6d99b083
Serzol64/mypythonlearntasks1
/task17.py
233
4
4
def sum_digits(num): digits = [int(d) for d in str(num)] return sum(digits) f = input("Введите целое число:") print("Результат сложения цифр целого числа:", sum_digits(int(f)))
522705d07896e40a3b0bffc5f293d826b084b65b
Serzol64/mypythonlearntasks1
/task5.py
158
3.8125
4
my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20} print('Maximal keys:') print([k for k,v in my_dict.items() if v == max(my_dict.values())])
723718ae13d59a4555082a280513070b0766cf1d
danstelian/python_misc
/filter_compress_vs_comprehensions.py
1,536
3.734375
4
from itertools import compress from random import randint # filter vs list comprehensions (eg 1) nums = [randint(-9, 10) for i in range(15)] positive = [num for num in nums if num > 0] negative = list(filter(lambda num: num < 0, nums)) print(f'positive: {positive}\nnegative: {negative}', end='\n\n') # filter vs list comprehensions (eg 2) def is_int(val): try: num = int(val) return True except ValueError: return False values = ['1', '0', '2', '-3', '-', '4', 'N/A', '5'] numbers = list(filter(lambda val: is_int(val), values)) # or numbers = list(filter(is_int, values)) # finally numbers = list(map(int, filter(is_int, values))) print(numbers) # with list comprehension - a more refined result # a list comprehension (or generator expression) has the power to transform the data at the same time numbers = [int(num) if int(num) > 0 else abs(int(num)) for num in values if is_int(num) and int(num) != 0] print(numbers, end='\n\n') # compress vs list comprehensions addresses = [ '5412 N CLARK', '5148 N CLARK', '5800 E 58TH', '2122 N CLARK', '5645 N RAVENSWOOD', '1060 W ADDISON', '4801 N BROADWAY', '1039 W GRANVILLE' ] zips = [5, 5, 5, 2, 5, 1, 4, 1] zip5 = [n == 5 for n in zips] new_addresses = list(compress(addresses, zip5)) # print(*new_addresses, sep=', ') # list comprehension new_addresses = [addr for index, addr in enumerate(addresses) if zip5[index]] print(*new_addresses, sep=', ')
c7787f3109f9b87d2bc040dd524b4f1829341546
danstelian/python_misc
/counter_most_common.py
2,160
3.921875
4
""" Experimenting with Python's Counter data type! Counter is a container that keeps track of how many times equivalent values are added. Just like a dictionary (it's a dict subclass), except values can be positive/negative integers. It's an unordered collection where elements are stored as keys. """ from collections import Counter # initialization - from list names = ['Anna', 'Dan', 'John', 'Dave', 'Dan', 'Jimmy', 'Ash', 'Anna', 'Dan', 'Nicolas'] count_names = Counter(names) # count_names.most_common(3) it's a list of tuples for item, count in count_names.most_common(3): print(f'{item}: {count}') # initialization - from dict food = dict(spam=3, toast=2, ham=0, eggs=5) count_food = Counter(food) for item, count in count_food.most_common(5): print(f'{item}: {count}') # most regular dict methods are available print(count_names.keys()) print(count_food.values()) print(count_food.items()) # and back to list food_list = list(count_food.elements()) # not in the same order print(food_list) # indexing eggs = count_food['eggs'] # returns 0 if element not found # case in which a dict raises an error bread = count_food['bread'] print(bread) # add counts count_food['spam'] += 1 # new entry count_food['bread'] = 99 # update will increment the value count_food.update({'bread': 1}) # a dict count_food.update(['bread']) # a list, one of each print(count_food['bread']) # bread = 101 # subtract count_food['bread'] -= 100 print(count_food['bread']) # bread = 1 # remove altogether del(count_food['spam']) print(count_food) # no spam in the Counter print(count_food['spam']) # no error!!! returns 0 :) # subtracting counts money = dict(Bitcoin=3, Ethereum=15, Ripple=347, Stellar=2348) shield = {'Ethereum': 3, 'Stellar': 257} sword = {'Bitcoin': 1, 'Ripple': 89} gloves = ['Ethereum'] # one wallet = Counter(money) # buy a shield wallet.subtract(shield) # buy a sword wallet.subtract(sword) # buy gloves wallet.subtract(gloves) # minus one Ethereum # buy freedom freedom = dict(Bitcoin=99, Ethereum=199, Ripple=1999, Stellar=9999) wallet.subtract(freedom) print(wallet) # damn! # game over wallet.clear()
d79e21953263250a7c94461da0d80f57fd290fa7
danstelian/python_misc
/groupby_vs_defaultdict.py
1,117
3.53125
4
from itertools import groupby from collections import defaultdict from operator import itemgetter rows = [ {'address': '5412 N CLARK', 'date': '07/01/2012'}, {'address': '5148 N CLARK', 'date': '07/04/2012'}, {'address': '5800 E 58TH', 'date': '07/02/2012'}, {'address': '2122 N CLARK', 'date': '07/03/2012'}, {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}, {'address': '1060 W ADDISON', 'date': '07/02/2012'}, {'address': '4801 N BROADWAY', 'date': '07/01/2012'}, {'address': '1039 W GRANVILLE', 'date': '07/04/2012'} ] # to use groupby, the list must be firs sorted by the desired field rows.sort(key=itemgetter('date')) for date, items in groupby(rows, key=itemgetter('date')): print(date) for i in items: print(f'\t{i}') print('-'*100) # same thing with defaultdict by_date = defaultdict(list) # rows don't have to be sorted f = itemgetter('date') for row in rows: by_date[f(row)].append(row) for key in sorted(by_date.keys()): print(f'{key}') for item in by_date[key]: print(f'\t{item}')
ad00ddf3a4f192d2017d9bb8fbb5dd4d90d9a065
Mengeroshi/python-tricks
/3.Classes-and-OOP/4.3.copying_arbitrary_objects.py
779
4.1875
4
import copy """Shallow copy of an object """ class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f'Point({self.x!r}, {self.y!r})' a = Point(23, 42) b = copy.copy(a) print(a) print(b) print(a is b) class Rectangle: def __init__(self, topleft, bottomright): self.topleft = topleft self.bottomright = bottomright def __repr__(self): return(f'Rectangle({self.topleft!r}, {self.bottomright!r})') rect = Rectangle(Point(0,1), Point(5, 6)) srect = copy.copy(rect) print(rect) print(srect) print(rect is srect) rect.topleft.x = 999 print(rect) print(srect) """ Deep copy of an object """ deep_rect = copy.deepcopy(rect) deep_rect.topleft.x = 222 print(rect) print(deep_rect)
95bdcf9a12edae1be18cfd5b5c1705967fda44a4
Mengeroshi/python-tricks
/2.Efective-Functions/3.1decorators.py
284
3.671875
4
""" Decorators: allow you to extend the behaviour of a callable(fun, class, method) """ def null_decorator(func): return func def greet(): return 'hello' greet = null_decorator(greet) print(greet()) @null_decorator def greeting(): return 'hello!' print(greeting())