blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
64029718781f0f862fed1741ef8c28bea8d80233
kcc3/hackerrank-solutions
/data_structures/python/linked_lists/insert_node_at_specific_position_in_linked_list.py
2,513
4.09375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty. """ import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def print_singly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) # Complete the insertNodeAtPosition function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def insertNodeAtPosition(head, data, position): """Function to insert a new node into a linked list at the specified index position Args: head (SinglyLinkedListNode): Head of the linked list data (int): Data to store in the linked list position (int): The position to store the new node Returns: head (SinglyLinkedListNode): Head of the new linked list with the added node """ if position == 0: return SinglyLinkedListNode(data) traverse = head for i in range(position - 1): traverse = traverse.next new_node = SinglyLinkedListNode(data) new_node.next = traverse.next traverse.next = new_node return head if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') llist_count = int(input()) llist = SinglyLinkedList() for _ in range(llist_count): llist_item = int(input()) llist.insert_node(llist_item) data = int(input()) position = int(input()) llist_head = insertNodeAtPosition(llist.head, data, position) print_singly_linked_list(llist_head, ' ', fptr) fptr.write('\n') fptr.close()
93d2c4f2eb3485d73051a93cfa531070aa46a563
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/bigger_is_greater.py
1,021
4.28125
4
def bigger_is_greater(w): """Hackerrank Problem: https://www.hackerrank.com/challenges/bigger-is-greater/problem Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria: - It must be greater than the original word - It must be the smallest word that meets the first condition Args: w (str): The word to swap Returns: str: Return the next highest lexicographical word or "no answer" """ # Find non-increasing suffix arr = [c for c in w] i = len(arr) - 1 while i > 0 and arr[i - 1] >= arr[i]: i -= 1 if i <= 0: return "no answer" # Find successor to pivot j = len(arr) - 1 while arr[j] <= arr[i - 1]: j -= 1 arr[i - 1], arr[j] = arr[j], arr[i - 1] # Reverse suffix arr[i:] = arr[len(arr) - 1: i - 1: -1] return "".join(arr) if __name__ == "__main__": print(bigger_is_greater("zzzayybbaa")) print(bigger_is_greater("zyyxwwtrrnmlggfeb"))
fcb4d9bc984884d587811ceb50aa624e520e709d
kcc3/hackerrank-solutions
/python/itertools/itertools_combinations_with_replacements.py
303
3.578125
4
""" Hackerrank Problem: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem """ from itertools import combinations_with_replacement string, k = input().split(" ") for combination in combinations_with_replacement(sorted(string), int(k)): print("".join(combination))
ef1ff7bf8a43249a3848049ae41e3506578d44ab
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/encryption.py
653
3.953125
4
import math def encryption(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/encryption/problem Encryption function based on the specifics as provided in the challenge. Args: s (str): The string to encrypt Returns: str: The string after passing through specified encryption """ string = s.replace(" ", "") columns = math.ceil(math.sqrt(len(string))) line = "" for i in range(columns): line += string[i::columns] + " " return line if __name__ == "__main__": print(encryption("have a nice day")) print(encryption("feedthedog")) print(encryption("chillout"))
8e6a005a4c9160c79ac341f317dedb5c6f04d9cb
cisquo/cours_python_hepia
/ex50.py
1,803
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #s = input ("Entrez une valeur: ") def longueur(l1): nb = 0 for x in l1: nb += 1 return nb def moyenne(l1): total = 0 for x in l1: total = total + x return total / longueur(l1) if l1 else 0 def plus_grand_ou_egal (l1, n): res = [] for x in l1: if x >= n : res.append(x) return res def plus_petit_ou_egal (l1, n): res = [] for x in l1: if x <= n : res.append(x) return res def minimum (l1): res = l1[0] for x in l1: if x < res : res = x return res def positive (l1): return plus_grand_ou_egal(l1,0) def dans(l1, n): return True if (set(l1) & set({n})) == {n} else False def binaire(l1): res = 0 for i, elem in enumerate(reversed(l1)): # print(i,':',elem) # print(elem*(2**i)) res += int(elem)*(2**i) return(res) def and_lst(lst): for elem in lst: if not elem: return False return True def zip(l1, l2): l3 = [] if len(l1) == len(l2): for i in range(len(l1)): l3.append((l1[i], l2[i])) return l3 return l3 # [(A,B]] -> ([A],[B]) def unzip(l1): l3 = [] l2 = [] for i, j in l1: l3.append(i) l2.append(j) return l2, l3 def f(x): return 2*x+2 def transform(lst,f): l2 = [] for elem in lst: l2.append( f(elem) ) return l2 def majeur(age): return age >= 18 def mineur(age): return age < 18 def filter(lst,f): l2 = [] for elem in lst: if f(elem): l2.append( (elem) ) return l2 def remove_duplicates(lst): l2 = [] for elem in lst: if f(elem) l2.append( (elem) ) return l2
72aa1573e269adc097e788feba4bec118353f114
cisquo/cours_python_hepia
/ex512.py
513
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #s = input ("Entrez une valeur: ") def add(dic,k,v): dic.append((k,v)) def index(dic,val): for k,v in dic: if v == val: return k def lenght(dic): return len(dic) def is_in(dic, cle): for k,v in dic: if k == cle: return True return False def val(dic): print (dic) def key(dic): for k,v in dic: print (k) def reverse(dic): for k,v in dic: print (v,k) try: res =
49f4e08c38d8f2429e77d4af1d29e4010c381208
archeranimesh/pythonFundamentals
/code/pyworkshop/02_list/list_sort.py
556
4.21875
4
# Two ways to sort a list. lottery_numbers = [1, 3, 345, 123, 789, 12341] # 1st method does not modify the original list, # returns a shallow copy of original list. print("sorted list: ", sorted(lottery_numbers)) # reverse the list. print("reverse list: ", sorted(lottery_numbers, reverse=True)) x = sorted(lottery_numbers) # returns a list. print("x = ", x, "\ntypeof(x): ", type(x)) # In place list sorting. lottery_numbers.sort() print("list sort: ", lottery_numbers) # reverse lottery_numbers.reverse() print("list reverse: ", lottery_numbers)
d7b87d4a7e4d87be392508d92cd10d2ff1e033e5
archeranimesh/pythonFundamentals
/code/pyworkshop/07_loops_if/05_break_continue_return.py
645
3.828125
4
# Break, stops the execution of loop and jumps to end of loop. # Continue, doesn't continue the following loop statement, but jump to start of loop. names = ["Jimmy", "Rose", "Max", "Nina", "Phillip"] for name in names: if len(name) != 4: continue # Start new iteration when len is not 4 print(f"Hello, {name}") if name == "Nina": break # Exit from loop when condition is met print("Done") # In nested loop, break exit from the loop it is part of i = 1 j = 1 while i < 10: while j < 10: print(f"{i} : {j}") j += 1 if j == 4: break # breaks from inner loop i += 1
63a6c50f451fd165eeff0b514a9c5e87b44b531d
michalecki/codewars
/sum_of_intervals.py
1,528
4.1875
4
''' Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4. List containing overlapping intervals: [ [1,4], [7, 10], [3, 5] ] The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4. ''' def sum_intervals(inp_arr): ''' :param array: array of intervals :return: sum of lengths of the intervals ''' # sort the intervals over the first digit inp_arr.sort() # loop and merge if overlap i = 0 while i < len(inp_arr) - 1: while inp_arr[i][1] >= inp_arr[i + 1][0]: inp_arr[i] = [inp_arr[i][0], max(inp_arr[i + 1][1], inp_arr[i][1])] del inp_arr[i + 1] if i == len(inp_arr) - 1: break i += 1 # calculate the sum total = sum([inp_arr[x][1] - inp_arr[x][0] for x in range(len(inp_arr))]) return total # testing sum_intervals([ [1, 2], [6, 10], [11, 15] ]) # \; // => 9 sum_intervals([ [1, 4], [7, 10], [3, 5] ]) # ; // => 7 sum_intervals([ [1, 5], [10, 20], [1, 6], [16, 19], [5, 11] ]) # ; // => 19
aa970b317af5316d42807008efbc5b41e8347486
michalecki/codewars
/sum_of_numbers.py
582
4.34375
4
def get_sum(a,b): ''' Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b. Note: a and b are not ordered! :param a: int :param b: int :return: int ''' if a == b: return a ab = [a, b] ab.sort() return sum(range(ab[0],ab[1]+1)) #testing print(get_sum(0,1)) # ok print(get_sum(4,4)) # ok print(get_sum(0,-1)) print(get_sum(-2,0)) print(get_sum(-3,-2)) print(get_sum(4,2)) print(get_sum(-3,5))#ok
67c080061bd2de6a136ca201be47f659b7770fa3
oostlab/python-pen-web
/bruteforce/postgress_brute.py
3,582
3.53125
4
#!/usr/bin/python3 ''' Postgress bruteforce script. A script for bruteforcing postgress Test with the following commandline python3 postgress_brute.py 192.168.2.5 users.txt passwords.txt ''' import psycopg2 import sys from time import sleep def execute_scan(host, userfile, passwordfile, port, connect_timeout, ssl): '''Execute the bruteforce scan :param str host: hosts (IP addresses, hostnames) comma separated :param str userfile: filename with usernames :param str passwordfile: filename with passwords :param int port : port number :param bool ssl: bool to set ssl :param bool use_subset: bool for subset of lists and slow connection ''' # connect_timeout = 2 # read_timeout = 2 try: # exceptions with files # open the Userfile in users list users = [] with open(userfile) as file: for line in file: users.append(line.strip()) passwords = [] with open(passwordfile) as file: for line in file: passwords.append(line.strip()) except Exception as FileError: print(FileError) login_postgress(host, users, passwords, port, connect_timeout, ssl) def check_postgress(host, port, connect_timeout): """Function for checking if there is postgress database running.""" try: # connect to the PostgreSQL server conn = psycopg2.connect(host="192.168.2.8", user="postgres", password="postgress", port=5432, connect_timeout=1) if conn is not None: conn.close() return True except (Exception, psycopg2.DatabaseError) as error: # print(error) if 'password authentication failed' in str(error): return True else: return False def login_postgress(host, users, passwords, port, connect_timeout, ssl): """Function for logging in to postgress.""" for user in users: for password in passwords: sleep(1) try: # connect to the PostgreSQL server # print('Connecting to the PostgreSQL database...') print(f'Trying with {user}:{password} on {host}') conn = psycopg2.connect(host=host, user=user, password=password, port=port, connect_timeout=connect_timeout) # conn = psycopg2.connect(host="192.168.2.8", port=5432, connect_timeout=1) if conn is not None: print(f'connected with {user}:{password} on {host}') conn.close() except (Exception, psycopg2.DatabaseError) as error: # print(error) if 'password authentication failed' in str(error): print('wrong userid and password') elif 'Connection refused' in str(error): print('Connection refused') break else: print(error) break else: continue break if len(sys.argv) != 4: print("Not enough arguments:\n" + 'Usage: postgress_brute.py target userfile passfile') else: host = sys.argv[1] users = sys.argv[2] passw = sys.argv[3] ssl = False if check_postgress(host, 5432, 3): print('postgress available continue with bruteforcing') execute_scan(host, users, passw, 5432, 1, ssl) else: print('No postgress server available')
791406611128204f4689899bf23292904e7e1c7d
trandaniel/project-euler-solutions
/python/problem004.py
393
4.03125
4
# A palindromic number reads the same both ways. The largest palindrome made from # the product of two 2-digit numbers is 9009 = 91 x 99. # # Find the largest palindrome made from the product of two 3-digit numbers. largest = 0 for i in xrange(100, 1000): for j in xrange(100, 1000): if (i * j > largest) and (str(i*j) == str(i*j)[::-1]): largest = i*j print largest
7e3dbd35ab956465da78d9d923a7ffe37f9005bc
makcg/HomeWork
/HW5/Lesson 5 Prictice task 3.py
635
4.0625
4
# Вспоминаем работу с файлом. Есть файл, в котором много англоязычных текстовых строк. # Считаем частоту встретившихся слов в файле, но через функции и map, без единого цикла! from collections import Counter file = open('text_for_ practice_task_3.py', 'r') def lower(a): return a.lower() def counter(f): list_split = list(map(str, f.split())) list_split = map(lower, list_split) counter = Counter(list_split) return counter print(list(map(counter, file))) file.close()
6f4909312fd87ec11a1e4c74c70a2e05fca8a840
makcg/HomeWork
/HW5/Lesson 5 Task 3.py
311
4.03125
4
from itertools import zip_longest s = [1, 2, 3, 4] u = ['q', 'w', 'e', 'r', 't'] y = [5, 6, 7, 8] def zip_func(a, b, c): """ input: three random lists combines three lists (including different lengths) return: one list """ return list(zip_longest(a, b, c)) print(zip_func(s, u, y))
23d50115da2e3217dfde2bd62ff14039ca1044f2
MayaYosef/Synthetic-Digits-Classification
/python/makegraphs.py
3,332
3.984375
4
""" this python file is responsible for making and saving graphs of the training process """ import matplotlib matplotlib.use( 'tkagg' ) import matplotlib.pyplot as plt import numpy as np import os import printmessage def graphs(H, plot_path, epoches): """ responsible for making, saving and presenting the graphs of the training process & printing a message with the location of the plots in the computer. param plot_path: the directory in which the graphs will be saved param epoches: the number of epochs- The number of times the images ran on the model for learning purposes """ os.mkdir(plot_path) plotpath1 = plot_path + r"\plot1.png" plotpath2 = plot_path + r"\plot2.png" plotpath3 = plot_path + r"\plot3.png" graph1(H, plotpath1, epoches) graph2(H, plotpath2) graph3(H, plotpath3) printmessage.printProcess("Graphs of the training process are in " + plot_path) def graph1(H, plot_path1, epoches): """ Creates a png image file in which it draws the learning graph of the model, saving it and showing it at the end of the training. (traning & validation accuracy & loss) param H: the history of the model training param plot_path1: the directory in which graphs 1 will be saved param epochs: the number of times the images ran on the model for learning purpose """ plt.style.use("ggplot") plt.figure() N = epoches plt.plot(np.arange(0, N), H.history["loss"], label="train_loss") plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, N), H.history["accuracy"], label="train_acc") plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_acc") plt.title("Training Loss and Accuracy") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend(loc="upper left") plt.savefig(plot_path1) #save plot to file plt.show() def graph2(H, plot_path2): """ Creates a png image file in which it draws the learning graph of the model, saving it and showing it after the user closed the first plot. (traning & validation cross entropy loss) param H: the history of the model training param plot_path2: the directory in which graphs 2 will be saved """ plt.style.use("ggplot") plt.figure() plt.title('Cross Entropy Loss') plt.plot(H.history['loss'], color='blue', label='train') plt.plot(H.history['val_loss'], color='orange', label='val') plt.legend(loc="upper left") plt.savefig(plot_path2) plt.show() def graph3(H, plot_path3): """ Creates a png image file in which it draws the learning graph of the model, saving it and showing it after the user closed the second plot. (traning & validation classification accuracy) param H: the history of the model training param plot_path3: the directory in which graphs 3 will be saved """ plt.style.use("ggplot") plt.figure() plt.title('Classification Accuracy') plt.plot(H.history['accuracy'], color='blue', label='train') plt.plot(H.history['val_accuracy'], color='orange', label='val') plt.legend(loc="upper left") plt.savefig(plot_path3) plt.show()
81e3bc5134fd6998b582378871194a42a9373528
melissawm/rse2017
/examples/example 1/IDEB.py
8,455
4.0625
4
# coding: utf-8 # # Example: IDEB Analysis # We are going to analyse data corresponding to the IDEB (Basic Education Development Index) for brazilian cities. The data comes from the file # In[1]: ideb_file = "IDEB por Município Rede Federal Séries Finais (5ª a 8ª).xml" # which was obtained from the main brazilian government open data site <a href="http://dados.gov.br">dados.gov.br</a> # Since we have an .xml file, we'll use the *xml.etree.ElementTree* module to parse its contents. For simplicity, we'll call this module *ET*. # In[2]: import xml.etree.ElementTree as ET # ### The ElementTree (ET) module # # An XML file is a hierarchical set of data, so the most intuitive way to represent this data is by a tree. To do this, the ET module implements two classes: the ElementTree class represents the whole XML file as a tree, and the Element class represents one node of this tree. All interactions that occurr with the whole file (like reading and writing to this file) are done through the ElementTree class; on the other hand, every interaction with an isolated element of the XML and its subelements are done through the Element class. # # By reading the docs, we learn that the *ET.parse* methods returns an *ElementTree* from a file. # In[3]: tree = ET.parse(ideb_file) # The *ElementTree* class has the following structure: # In[4]: dir(tree) # According to the documentation for this module, we access the ElementTree via its *root* node, which is an *Element* class instance. To see the root element, we use the *getroot* method: # In[5]: root = tree.getroot() # As an *Element*, the root object has the *tag* and *attrib* properties, and *attrib* is a dictionary of its attributes. Let's see what are these values: # In[6]: # root.tag # In[7]: # root.attrib # To access each child node of the root element, we iterate on these nodes (which are also *Elements*): # In[8]: # for child in root: # print(child.tag, child.attrib) # We can see that our XML comes with a lot of data. Next, we will try to get a subset of this data. # ### Selecting the data # Now that we have a better idea of the document's structure, let's build a pandas *DataFrame* with what we need. First, we can see that we only need the last node of the root element, "valores" (which stands for "values" in Portuguese); the other nodes are in fact just the header for the XML file. Let's explore this node. # In[9]: IDEBvalues = root.find('valores') # Note that there is one more layer of data here: # In[10]: # IDEBvalues # In[11]: # IDEBvalues[0] # Now, we can explore the grandchildren of the root node: # In[12]: # for child in IDEBvalues: # for grandchild in child: # print(grandchild.tag, grandchild.attrib) # Now, let's extract the data we are interested in: # In[13]: data = [] for child in IDEBvalues: data.append([float(child[0].text), child[1].text, child[2].text]) # In[14]: # data # Since <a href="http://pandas.pydata.org/">Pandas</a> seems to be fashionable right now ;) let's use it to store and treat this data. We'll give it a shorter name though, pd. # In[15]: import pandas as pd # Now, we create our DataFrame from the preexisting data. # In[16]: IDEBTable = pd.DataFrame(data, columns = ["Valor", "Municipio", "Ano"]) # In[17]: # IDEBTable # You can see there are two sets of data here, one for 2007 and another for 2009. We'll only use the most recent data for our "analysis". # In[18]: IDEBTable = IDEBTable.loc[0:19] # ### Identifying the city codes # # In our IDEBTable, cities are identified by their so called "IBGE Code", which is a code issued to each locality by the Brazilian Institute for Geography and Statistics (IBGE). In order to make this more user friendly, we'll read the most recent Excel file with the list of cities and their respective 7 digit codes (from 2014; these codes include a final verification digit). For this, we'll use the xlrd module, which must be manually installed; see <a href="https://pypi.python.org/pypi/xlrd">this</a>. # In[19]: localCodesIBGE = pd.read_excel("DTB_2014_Municipio.xls") # Now we can inspect the data by using the pandas *head* method for DataFrames: # In[20]: # localCodesIBGE.head() # The columns we are interested in are just "Nome_UF", "Cod Municipio Completo" and "Nome_Município", which stand for State (or Province), Complete City Code and City Name, respectively. # In[21]: localCodesIBGE = localCodesIBGE[["Nome_UF", "Cod Municipio Completo", "Nome_Município"]] # Now, we have two DataFrames: **IDEBTable**, containing the complete IDEB data corresponding to city names, and **localCodesIBGE**, containing the corresponding city codes. We must select from the complete **localCodesIBGE** table only the rows corresponding to cities for which we have the IDEB value. For this, we will extract from both DataFrames the columns corresponding to the city codes (remember that in the **localCodesIBGE** table, codes have an extra verification code which we will not use): # In[42]: IDEBCities = IDEBTable["Municipio"] cities = localCodesIBGE["Cod Municipio Completo"].map(lambda x: str(x)[0:6]) # Note that we have used *map* to transform numerical data into strings, removing the last digit. # # Now, both **IDEBCities** and **cities** are pandas Series objects. To get the indices of cities for which we have IDEB data, first we will identify which codes are **not** in **IDEBCities**: # In[43]: citiesToRemove = cities[~cities.isin(IDEBCities)] # We remove the corresponding rows from the localCodesIBGE table: # In[45]: newTable = localCodesIBGE.drop(citiesToRemove.index).reset_index(drop=True) # Finally, we will create a new DataFrame joining city name and IDEB value: # In[46]: finalData = pd.concat([newTable, IDEBTable], axis=1) # This gives # In[47]: finalData # ## Finishing up: a pretty figure # # In order to include graphics in notebooks, usually the first cell in the notebook contains the code # # % matplotlib inline # # or # # % matplotlib notebook # # Since we don't want to sacrifice the legibility of our *article* by starting it with some misterious command, we can use the **init_cell** nbextension so that a later cell is executed first on our notebook ([More details](#about_initcell)). # # First, let's import the pyplot sublibrary of the matplotlib library and call it plt: # In[48]: import matplotlib.pyplot as plt # We'll do a very simple plot, but for this it would be nice to use the city names instead of the numerical indices in the finalData table: # In[49]: finalData.set_index(["Nome_Município"], inplace=True) # Now, we will select the column with the values ("Valor") for the IDEB by city in the finalData table (note that the result of this operation is a Series): # In[50]: finalData["Valor"] # We are ready for our pretty (yet irrelevant) picture. # In[52]: finalData["Valor"].plot(kind='barh') plt.title("IDEB by city (Data from 2009)") # ## Comments about automatic documentation and script generation # # To convert this notebook to a regular Python .py script, use #jupyter-nbconvert --to python 'IDEB.ipynb' --template=removeextracode.tpl # The removeextracode.tpl has the following content: #{% extends 'python.tpl'%} #{% block input %} #{% if 'codecomment' in cell['metadata'].get('tags', []) %} # {{ cell.source | comment_lines }} #{% else %} # {{ cell.source | ipython2python }} #{% endif %} #{% endblock input %} # This means that we will include all notebook cells tagged with **codecomment** as comments on our script. This is to avoid generating a unusable script including our inspection of objects and attempts at solving a problem. # # For more details on templates and the nbconvert extension, check <a href="https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/">this page</a>, for example. # ## Initialization cell <a id='about_initcell'></a> # # Through the "init_cell" extension (also from nbextensions), it is possible to alter the order of execution of notebook cells. If we look at the metadata of the cell below, we can see that it is marked to be executed before all other cells, and so we obtain the desired result when we run all cells in the notebook. (This command allows us to see inline graphics inside our notebook). # In[53]: # %matplotlib inline
a013fb32d1e0ffc470c56a9f7ec6fefc8daf831c
NgoHarrison/CodingPractice
/7. Graphs/employee_inheritance.py
675
3.75
4
""" # Employee info class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.importance = importance # the id of direct subordinates self.subordinates = subordinates """ class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: mapping = {i.id: i for i in employees} def dfs(emp): cur = mapping[emp] return cur.importance + (sum(dfs(emp) for emp in cur.subordinates)) return dfs(id)
ee9eacd0237b3283f840b5b6b3ef338e2bc53cd4
NgoHarrison/CodingPractice
/3. Arrays/Longest_Mountain_In_Array.py
1,232
3.84375
4
def longestMountain(A): print(A) left = 0 right = len(A)-1 while left < right: #print(A[left:right+1]) middle = (right+left)//2 print(left,middle,right) temp = sorted(A[left:middle+1])+sorted(A[middle+1:right+1],reverse=True) if len(temp) < 3: return 0 if temp == A[left:middle]+A[middle:right+1] and len(temp)==(len(set(temp[0:middle]))+len(set(temp[middle:len(temp)]))): if temp[len(temp)//2] > temp[(len(temp)//2)-1] and temp[len(temp)//2] > temp[(len(temp)//2)+1]: return right-left+1 if A[left+1] <= A[left] and A[right] < A[right-1]: left+=1 elif A[left+1] > A[left] and A[right] >= A[right-1]: right-=1 else: left+=1 right-=1 return 0 arr=[0,1,2,3,4,5,4,3,2,1,0] arr2=[2,2,2] arr3=[2,1,4,7,3,2,5] arr4=[0,1,2,3,4,5,6,7,8,9,10,8,7,6,5,4,3,2,1,0] arr5=[0,1,2,3,4,5,6,7,8,9] arr6=[0,1,0,2,2] arr7=[4,2,9,8,0] print(longestMountain(arr7)) #print(arr[0:2]+arr[2:4]) #print('-------') #middle = 3 #print(sorted(arr[0:middle]+arr[middle:len(arr)])) #temp = sorted(arr,reverse=True) #print(arr) #print(temp) #print(arr==temp[0:len(temp)])
e000295cea431c02d05cc166379d0c564f0c7f1b
ShreyanGoswami/coding-contests
/Leetcode weekly contest 188/array_with_stack_ops.py
1,263
3.890625
4
''' Given an array target and an integer n. In each iteration, you will read a number from list = {1,2,3..., n}. Build the target array using the following operations: Push: Read a new element from the beginning list, and push it in the array. Pop: delete the last element of the array. If the target array is already built, stop reading more elements. You are guaranteed that the target array is strictly increasing, only containing numbers between 1 to n inclusive. Return the operations to build the target array. You are guaranteed that the answer is unique. ''' from typing import List def buildArray(self, target: List[int], n: int) -> List[str]: ''' Time complexity: O(n) Space complexity: O(n) ''' res = [] s = set(target) prefixSum = [0, 1] for i in range(2, n+1): if i in s: prefixSum.append(prefixSum[i-1] + i) else: prefixSum.append(prefixSum[i-1]) for i in range(1, n+1): if i in s: res.append('Push') else: if prefixSum[n] - prefixSum[i] == 0: break res.append('Push') res.append('Pop') return res
a72af4074104f47c32f8714796c4a1f6948bc8d1
ShreyanGoswami/coding-contests
/Leetcode weekly contest 189/rearrange_words_in_sentence.py
860
4.25
4
''' Given a sentence text (A sentence is a string of space-separated words) in the following format: First letter is in upper case. Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above. ''' class Solution: def arrangeWords(self, text: str) -> str: ''' Time complexity: O(nlogn) Space complexity: O(n*m) where n is the number of words and m is the maximum number of letters in a word ''' words = text.split() words[0] = words[0].lower() words.sort(key = lambda x: len(x)) words[0] = words[0].capitalize() return " ".join(x for x in words)
a16a99abd5d197bb93f5d17c11d014c27a8424d3
mit-mc-clas12/clas12osg
/client/options.py
1,066
3.625
4
# Import packageds/modules import argparse # This function will return all command line arguemnts as an object def get_args(): # Initalize an argparser object. Documentation on the argparser module is here: # https://docs.python.org/3/library/argparse.html argparser = argparse.ArgumentParser(prog='Submit', usage='%(prog)s [options]') # adding argument nargs='+' would make this option an array argparser.add_argument('scardFile', metavar='scard', type=str, help='Steering card text file') # Add ability for user to specify that they want to use SQLite, instead of MySQL database # Also, lets user specify the name and path of the SQLite DB file to use argparser.add_argument('--sqlite', help="use SQLITE file as DB", type=str, default=None) # Boolean arguement of using TEST MySQL DB or the main MySQL DB argparser.add_argument('--test', action='store_true', help='Use table CLAS12TEST instead of default CLAS12OCR', default=False) # Convert the arguement strings into attributes of the namespace args = argparser.parse_args() return args
9f94ef405e1ec63735e1e17bca483e706a86b3f9
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/continuedenemeleri.py
126
3.953125
4
liste = list(range(10)) for x in liste: if(x==3 or x== 6): continue print(x,"için değer sağlanmadı")
616234224c32a4d65e39ccc22ec1a7ae629adc20
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/atm_mak.py
815
3.5625
4
print("""************************* ATM Makinesine Hoşgeldiniz. işlemler; 1. Bakiye Sorgulama 2. Para Yatırma 3. Para Çekme Programdan çıkmak için "q" tuşlayın. *********************""") bakiye=1000 while True: işlem=input("İşlem Girin:") if(işlem=="q"): print("Yine Bekleriz...") break elif(işlem=="1"): print("Bakiye : {} tl dir".format(bakiye)) elif(işlem=="2"): miktar=int(input("miktar girin")) print("Yeni bakiye : {}".format(bakiye+miktar)) bakiye+=miktar elif(işlem=="3"): miktar=int(input("miktar girin")) if(bakiye-miktar<0): print("Bakiye yetersiz") continue bakiye-=miktar else: print("Geçersiz İşlem....")
4ed1796d9ce52c82fa6a4c7b79f706567ccd38db
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/basithesapmak.py
635
4.0625
4
print("""************************* Basit Hesap Makinesi Programı İşlemler; 1.Toplama İşlemi 2.Çıkarma İşlemi 3.Çarpma İşlemi 4.Bölme İşlemi ************************* """) a=int(input("Birinci Sayı:")) b=int(input("İkinci Sayı:")) işlem=input("İşlemi giriniz:") if (işlem=="1"): print("{} ile {} toplamı = {}".format(a,b,a+b)) pass elif(işlem=="2"): print("{} ile {} farkı = {}".format(a,b,a-b)) elif(işlem=="3"): print("{} ile {} çarpımı = {}".format(a,b,a*b)) elif(işlem=="4"): print("{} ile {} bölümü = {}".format(a,b,a/b)) else: print("Geçersiz İşlem")
388977d7fb69ba87b4074e8e31afe89d45b7a1fc
mebaysan/LearningKitforBeginners-Python
/ozelMethodlar.py
809
4.03125
4
class Fruits(): def __init__(self,name,calories): # bu sınıf initialize olduğunda yani türetildiğinde içine gelen parametreler bu sınıfın attribute'ları olacak self.name = name self.calories = calories def __str__(self): # bu sınıf türetildiğinde instance.name demeden bize bu sınıfın name'ini döndürür(burada öyle yazdığımız için bkz. 15. satır) return self.name def __len__(self): # bu sınıf türetildiğinde instance.calories demeden bize bu sınıfın calories'ini döndürür(burada öyle yazdığımız için bkz. 16. satır) return self.calories fruit = Fruits("banana",300) print(fruit) print(len(fruit)) # daha detaylı bilgi için google'da arama yapabilirsiniz. Diğer özel methodlara daha rahat ulaşırsınız
9a95bd01ae50049a5a8ecf46bf7d0f0ecd8d9e7d
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/fordöngüdenemeleri.py
805
3.78125
4
print("for döngü denemeleri") liste=[1,2,3,4,5,6] for denelem in liste: print(denelem) print("**********************") liste1=[2,123,132,432,123,543,753,123,76,986,10980,123,6,7,8,88,12,43,54] toplam = 0 print(liste1,"\nBu liste için:") for eleman in liste1: toplam = toplam + eleman print("Toplam: {} Eleman: {}".format(toplam,eleman)) print("****************************") liste2=[123,231,531,123,513,647,8975,123321,4452,124123,2,4,12,24,34,45,56,67,78] for cift in liste2: if(cift%2==0): print(cift) print("*************************************") x="Sanane Lan Mal" for harf in x: print(harf) print("*********************************") x="Sanane Lan Mal" for harf in x: print(harf*3) print("*****************************")
7ea8ef1011dbc1b781cf98c8f93dc4f079b0fcfc
mebaysan/LearningKitforBeginners-Python
/python_ders10_ileriseviye_veriyapıları_objeler/ileriseviye_kümeler.py
3,958
4.34375
4
print(""" İleri Seviye Kümeler (Sets) Kümeler, matematikte olduğu gibi bir elemandan sadece bir adet tutan bir veritipidir. Bu açıdan kullanıldıkları yerlerde çok önemli bir veritipi olmaktadırlar. x = set() # boş küme aynı zamanda x={\\1,2,3,1,2,3,1,2,3} dersekte küme oluşur yani {\\} süslü parantez liste = [1,2,3,3,1,1,2,2,2] # Aynı elemanı birçok defa barındıran bir liste x = set(liste) # Veri tipi dönüşümü print(x) ÇIKTISI: """) liste=[1,2,3,3,1,1,2,2,2] x=set(liste) print(x) print(""" y = set("Python Programlama Dili") # Aynı karakterler tek bir karaktere indirgendi. print(y) ÇIKTISI: """) y = set("Python Programlama Dili") print(y) print(""" For döngüsüyle Gezinmek Kümeler de tıpkı sözlükler gibi sırasız bir veri tipidir. Bunu for döngüsüyle görebiliriz. z= {"Python","Php","Java","C","Javascript"} for i in z: print(i) ÇIKTISI: """) z= {"Python","Php","Java","C","Javascript"} for i in z: print(i) print(""" Kümelerin Metodları Eleman Eklemek : add() metodu Kümeye eleman eklemimizi sağlar. Aynı eleman eklenmeye çalışırsa hata vermez ve herhangi bir ekleme işlemi yapmaz. x={1,2,3,4} x.add(4) -> şeklinde kullanılır ***************************************************** difference() metodu: Bu metod birinci kümenin ikinci kümeden farkını döner. küme1.difference(küme2) # Küme1'in Küme2'den farkı küme1={1,2,3,4,5,6,-1,-2,-16} küme2={2,3,4,5,6,7} küme1.difference(küme2) -> kullanım bu şekildedir. ************************************************************* difference_update() metodu Bu metod birinci kümenin ikinci kümeden farkını dönerek birinci kümeyi bu farka göre günceller. küme1.difference_update(küme2) # Küme1'in Küme2'den farkı küme1={1,2,3,4,5,6,-1,-2,-16} küme2={2,3,4,5,6,7} küme1.difference_update(küme2) -> şeklinde kullanılır/kısaca küme1 ve küme 2'nin farkının küme1'e atanması **************************************************************** discard() metodu İçine verilen değeri kümeden çıkartır. Eğer kümede öyle bir değer yoksa, bu metod hiçbir şey yapmaz(Hata vermez). küme1 = {1,2,3,4,5,6} küme1.discard(7) -> şeklinde kullanılır ********************************************************** intersection() metodu Bu metod iki kümenin kesişimleri bulmamızı sağlar. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.intersection(küme2) -> şeklinde kullanılır ************************************************************** intersection_update() metodu Bu metod birinci kümeyle ikinci kümenin kesişimlerini bulur ve birinci kümeyi bu kesişime göre günceller. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.intersection_update(küme2) -> şeklinde kullanılır ************************************************************** isdisjoint() metodu Bu metod, eğer iki kümenin kesişim kümesi boş ise True, değilse False döner. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.isdisjoint(küme2) -> şeklinde kullanılır ************************************************** Alt kümesi mi ? : issubset() metodu Bu metod , birinci küme ikinci kümenin alt kümesiyse True, değilse False döner. küme1 = {1,2,3} küme2 = {1,2,3,4} küme1.issubset(küme2) -> şeklinde kullanılır ****************************************************** union() metodu Bu metod, iki kümenin birleşim kümesini döner. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.union(küme2) -> şeklinde kullanılır *************************************************************** Birleşim Kümesi ve update : update() metodu Bu birinci kümeyle ikinci kümenin birleşim kümesini döner ve birinci kümeyi buna göre günceller. küme1 = {1,2,3,10,34,100,-2} küme2 = {1,2,23,34,-1} küme1.update(küme2) -> şeklinde kullanılır """)
d420487746d453766dba6c07946925311fba04ce
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/döngüler ödev dosyası/100ekadar3ebölünensayılar.py
382
3.828125
4
print(""" ************************* 1'den 100'e kadar olan sayılardan sadece 3'e bölünen sayıları ekrana bastırın. Bu işlemi continue ile yapmaya çalışın ************************* for i in range(1,101): if (i % 3 != 0): continue print(i) """) for i in range(1,101): if (i % 3 != 0): continue print(i)
81651c545870eb4c63fc32d1efa43f939755e07c
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/listcomprehension.py
863
3.890625
4
liste1=[1,2,3,4,5,6,7,8,9] liste2=list() for eleman in liste1: liste2.append(eleman) print(liste1,liste2) print("***************************") liste3=[1,2,3,4,5] liste4=[eleman for eleman in liste3] print(liste4) print("***********************") liste5=[3,4,5,6] liste6=[z*2 for z in liste5] print(liste6) print("***********************") a="BAYSAN" denlist=[k*2 for k in a] print(denlist) print("*******************************") denemelistesi=[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]] for v in denemelistesi: print("denemelistesi içindeki v değeri : ", v) print("*********************") denemelistesi=[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]] for v in denemelistesi: for m in v: print("v içindeki m değeri : ", m) print("LISTCOMPREHENSION KAYNAK KODLARDA DAHA DETAYLI")
13b2b73f35314cd4c54953ab352aecccc3536064
PC-reloaded/dsmp-pre-work
/Et-tu-Preetus/code.py
1,289
3.6875
4
# -------------- # Code starts here class_1=['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2=['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class= class_1+class_2 #new_class =class_1.extend(class_2) print(new_class) #n=class_1.append('preeti') #print(class_1) new_class.append("Peter Warden") print(new_class) new_class.remove("Carla Gentry") print(new_class) # Code ends here # -------------- # Code starts here courses= {'Math': 65, 'English':70, 'History':80, 'French':70, 'Science':60} #Math=courses['Math'] #English= courses['English'] #History=courses['History'] #French= courses['French'] #Science=courses['Science'] #total=Math + English + History + French+ Science total=sum(courses.values()) print(total) percentage=total*100/500 print(percentage) # Code ends here # -------------- # Code starts here mathematics= {'Geoffrey Hinton': 78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50, 'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75} topper= max(mathematics,key=mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here #first_name=topper[0:6] first_name=topper.split()[0] #print(first_name) last_name=topper.split()[1] #print(last_name) full_name=last_name+" "+first_name certificate_name=full_name.upper() print(certificate_name) # Code ends here
fa28369256363fc99fc9dbc34c8759d4b257226c
huai8551516/PythonPractice
/practice/3.py
559
3.765625
4
#!/usr/bin/python #-*- coding: utf-8 -*- #Author: hz #Environment: Linux & Ubuntu 17.10 #Filetype: Python Source Code #Tool: Vim #Date: #Decription: 一个整数,它加上100和加上268后都是一个完全平方数, # 请问该数是多少? from math import sqrt max = int(raw_input("你要求n以内的整数:")) num_seq = [] for i in range(max): num1 = int(sqrt(i + 100)) num2 = int(sqrt(i + 268)) if num1 ** 2 == i + 100 and \ num2 ** 2 == i + 268: num_seq.append(i) print num_seq
7992912bc6663e6485469094e125dc8d624a0ea0
epitaciosilva/estudosProgramacao
/lp2/atividadeHeranca/questao2/figura.py
594
3.609375
4
class Figura: def __init__(self, lado1, lado2): self.lado1 = lado1 self.lado2 = lado2 def __str__(self): return "Lado 1: {} \nLado 2: {} \nÁrea da figura: {}".format(self.lado1, self.lado2, self.calcularArea()) def calcularArea(self): return self.lado1*self.lado2 @property def lado1(self): return self.__lado1 @lado1.setter def lado1(self, lado1): self.__lado1 = lado1 @property def lado2(self): return self.__lado2 @lado2.setter def lado2(self, lado2): self.__lado2 = lado2
93e646aecd279d4479ad3e285a64307fec5f1560
epitaciosilva/estudosProgramacao
/lp2/atividadePolimorfismo/questao1/main.py
428
3.578125
4
class Viajante: def __init__(self, cls): self.__cls = cls def dizerOla(self): self.__cls.dizerOla(self) class Brasileiro(Viajante): def dizerOla(self): print("Olá") class Espanhol(Viajante): def dizerOla(self): print("Hola") class Americano(Viajante): def dizerOla(self): print("Hello") v1 = Viajante(Americano) v2 = Viajante(Espanhol) v3 = Viajante(Brasileiro) v1.dizerOla() v2.dizerOla() v3.dizerOla()
6a05ff59530c8b61f12c66d45a5a1d116a68f48b
Nick-Ohman/Intro-Python-II
/src/adv.py
5,620
3.5
4
from room import Room from player import Player from items import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), } # Link rooms together room['outside'].n_to = room['foyer'] room['foyer'].s_to = room['outside'] room['foyer'].n_to = room['overlook'] room['foyer'].e_to = room['narrow'] room['overlook'].s_to = room['foyer'] room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] ## create items items = { "food": Item("Sherbet Lemon", "You might need food if you get lost"), "water": Item("Water", "You might be thirsty with all this walking"), "Light": Item("Light of Eärendil's star", "May it be a light to you in dark places, when all other lights go out."), "Sword": Item("sword of gondor", "Protection for yourself"), "goldpiece": Item("Gold Piece", "Found your first piece"), "helmate": Item("Chest Armour", "Protection") } room["foyer"].items = [items["goldpiece"], items["Light"]] room["overlook"].items = [items["Sword"], items["food"]] room["narrow"].items = [items["water"]] room["treasure"].items = [items["water"]] # # Main # # Make a new player object that is currently in the 'outside' room. # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. # directions will ne N S E W # follow step 1 define room # after that take a name prompt needhelp = ''' \n How to play: \n\n, Type \'n\' to move north\n, Type \'s\' to move south\n, Type \'w\' to move west\n, Type \'e\' to move east\n, Type \'q\' at any time to quit\n Type \'h\' for help ''' def start_game(): player = Player(name = input('Enter name to start '), current_room = room['outside'], items = [items["helmate"]]) print(player) def grabdrop(): choice = input(f'This room has: {player.current_room.printitems()} \n ') print(choice) if choice == 'ok': pass elif choice == 'get': player.getItem(f'{choice[5:]}') elif choice == 'drop': player.dropItem(f'{choice[6:]}') else: pass # while not(player.in_treasure): while not(player.in_treasure): gamer_input = input( "\nWhich direction would you like to move? ") print('\n') if gamer_input == 'q': print('\n !! Thanks for playing !!\n') exit() elif gamer_input == 'h': print(needhelp) elif gamer_input == 'n': try: player.current_room = player.current_room.n_to if player.current_room.name == "Treasure Chamber": print(f' You are now in {player.current_room.name}, {player.current_room.description}') print('You have found the treasure') won_game = input('Would you like to play again? Type y for yes, n for no... ') if won_game == 'w': start_game() else: print('\n !! Thanks for playing !!\n') exit() else: print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print("There is no room to the north") gamer_input elif gamer_input == 's': try: player.current_room = player.current_room.s_to print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print('There is no room to the south.') gamer_input elif gamer_input == 'e': try: player.current_room = player.current_room.e_to print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print('There is no room to the east.') elif gamer_input == 'w': try: player.current_room = player.current_room.w_to print(f' You are now in {player.current_room.name}, {player.current_room.description}') grabdrop() gamer_input except: print('There is no room to the west.') gamer_input start_game()
d7cb0e91a9a37a49840f85845d499a92cafb85ca
cwang-armani/learn-python
/04 python核心/10 闭包.py
786
4.03125
4
''' 如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。 一个闭包就是你调用了一个函数A,这个函数A返回了一个函数B的引用给你。 这个返回的函数B就叫做闭包。你在调用函数A的时候传递的参数就是自由变量 ''' def test(number): print("---1---") def test_in(number2): print("---2---") print(number+number2) print("---3---") return test_in a = test(100) a(20) a(100) a(200) ''' #闭包可以简化调用过程,有些参数只需调用一次 def test(a,b): def test_in(x): print(a*x+b) return test_in line1 = test(1,1) line2 = test(10,4) line1(0) line2(0) '''
5327645fe2ad9a4bff50f3347cc8937c7c5b8645
cwang-armani/learn-python
/02 面向对象/8 继承.py
512
3.6875
4
class Animal(): def eat(self): print("吃") def drink(self): print("喝") def sleep(self): print("睡") def run(self): print("跑") '''继承父类的名字,直接打在里面,前面定义的就不用重写''' '''调用方法 先子类 后父类''' class Dog(Animal): def bark(self): print("汪汪叫") class Cat(Animal): def catch(self): print("抓老鼠") a=Animal() a.eat() wangcai = Dog() wangcai.eat() wangcai.bark() tom=Cat() tom.eat() tom.catch()
1eb433504868fbaa75faaa7bac81000f9431dee6
cwang-armani/learn-python
/09 数据结构与算法/5 栈.py
699
4.1875
4
class Queue(object): '''定义一个栈''' def __init__(self): self.__item = [] def is_empty(self): # 判断列表是否为空 return self.__item == [] def enqueue(self,item): # 入队 self.__item.append(item) return item def dequeue(self): # 出队 return self.__item .pop(0) def size(self): return len(self.__item) if __name__ == "__main__": q = Queue() print(q.enqueue(1)) print(q.enqueue(2)) print(q.enqueue(3)) print(q.enqueue(4)) print("-"*20) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue())
1cb3ec8f915657b3df448ea3f05b7705e69a1823
cwang-armani/learn-python
/04 python核心/15 带有参数的装饰器.py
443
3.703125
4
def func_args(arg): def func(function_name): def func_in(): print("日志 arg = %s"%arg) if arg == "hehe": function_name() function_name() else: function_name() return func_in return func #先执行@func_args("hehe"),返回了func的引用 #test=@func(test) @func_args("hehe") def test(): print("---test---") @func_args("haha") def test2(): print("---test2---") test() test2()
687c1ddb9719b34698ac3cb7f0bbfa158ac35760
cwang-armani/learn-python
/10 MySQL/1 表的创建.py
2,641
3.671875
4
数据库命令: 创建create database 数据库名 charset=utf8; 删除drop database 数据库名; 查看所有数据库:show databases; 使用数据库:use 数据库名; ---------------------------------------- 表命令: create table 表名(列...); 唯一标识的要求:id 类型:int unsigned 约束1:not null 约束2:primary key 约束3:auto_increment 列的格式:列的名称 类型 约束 create table students( -> id int not null primary key auto_increment, -> name varchar(10) not null, -> gender bit default 1, -> birthday datetime, -> isDelete bit default 0, -> ); 查看创建语法:show create table students; 查看表:show tables; 查看表结构:desc students; 修改表:alter table students add|modify|drop 列名 类型 约束; mysql> alter table students add isDelete bit default 0; 删除表:drop table 表名; ---------------------------------------- 添加数据:(必然会新增一行) mysql> insert into students values(0,'郭靖',1,'1990-1-1',0); mysql> insert into students(name,gender) values('黄蓉',0); mysql> insert into students(name,gender,birthday) values('杨过',0,'1989-03-20'); 修改数据: mysql> update students set birthday='1990-1-1' where id = 2; 删除数据: delete from students where id = 3 逻辑删除,并查看: mysql> update students set isDelete=1 where id=3; mysql> update students set isDelete=1 where id=3; 备份: mysql> mysqldump -uroot -p students > ~Desktop/bak.sql 恢复: mysql -uroot -p py31 < bak.sql ---------------------------------------- 外键设置: create table course( course_id varchar(20), deptnames varchar(20), credits int, foreign key(deptnames) references department(dept_name)); create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) ); 外键的级联操作 在删除students表的数据时,如果这个id值在scores中已经存在,则会抛异常 推荐使用逻辑删除,还可以解决这个问题 可以创建表时指定级联操作,也可以在创建表后再修改外键的级联操作 语法 alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade; 级联操作的类型包括: restrict(限制):默认值,抛异常 cascade(级联):如果主表的记录删掉,则从表中相关联的记录都将被删除 set null:将外键设置为空 no action:什么都不做
0ff2bdb2f351f3b15b54683fb4abed165d7f4dfa
cwang-armani/learn-python
/09 数据结构与算法/8 冒泡排序法.py
561
3.921875
4
# coding:utf-8 def bubble_sort(a_list): '''冒泡排序法''' n = len(a_list) for i in range(n-1): count = 0 # 中间的某次已经排序好了,直接跳出循环 for j in range(n-i-1): # 游标 if a_list[j] > a_list[j+1]: a_list[j],a_list[j+1] = a_list[j+1], a_list[j] count += 1 if count == 0: break print(a_list) if __name__ == "__main__": a = [13,45,675,123,7,32,89,312,45432] print(a) bubble_sort(a) '''最优时间复杂度O(n),一次成型''' '''最坏时间复杂度O(n^2)''' '''稳定性好'''
b66fd6478fd1c2a2fa3714dd3f6ce463cea6b48b
lisseta/Algorithm-Analysis_FESAr.
/problemaUno.py
676
3.84375
4
# Solución para el problema N° 1 de Diseño y Análisis de Algoritmos # Autor: SouYui # ! Requiere una lista de elementos tipo str # R Devuelve el indice del primer elemento que su predecesor es menor a él def primerElementoMenor(lista): if(type(lista) == list and len(lista) > 1): for i in range(1, len(lista)): if(len(lista[i]) > len(lista[i - 1])): return [i] else: print("No es una lista, verifique su entrada.") listaPrueba = ["Samuel", "Emilia", "Erick","Samuel", "Emmanuel"] result = primerElementoMenor(listaPrueba) print(f"El índice de la lista donde se encuentra el elemento es: {result}")
c5f0af436ab49400f930ec8436b3264e45f598b8
bobbykwariawan/m26415067
/PR/PR Minggu 4/Python Basic Exercises/list1.py/A.py
180
4.125
4
#!/usr/bin/python def match_ends(words): a=words if len(a)>2 and a[0]==a[len(a)-1]: a=len(a) else: a=0 return a print(match_ends(raw_input('Input words: ')))
ceb2b2a2b5d2a0bd0b2d1d52ce9b4973f5b9559b
UrviMalhotra/Inventory-Management-System
/shop.py
5,071
3.625
4
import json shop=open("shoprecored.json","r") sale=open("sales.json","r") shop_data=shop.read() sale_data=sale.read() record = json.loads(shop_data) record_sale=json.loads(sale_data) shop.close() sale.close() def check_inventory_item(): print("\n\n") Item_ID = input("Enter Item ID: ") if Item_ID in record.keys(): print(f"Yes!! {Item_ID} is present") print(f"Product ID: {Item_ID}") print(f"Product Name: " ,record[Item_ID]["Item Name"]) print(f"Price: " ,record[Item_ID]["Price"]) print(f"Quantity: " ,record[Item_ID]["Quantity"]) else: print(f"No!! {Item_ID} is not present") def update_item_inventory(): print("\n\n") Item_ID = input("Enter Item ID: ") if Item_ID in record.keys(): print(f"Product ID: {Item_ID}") print(f"Product Name: " ,record[Item_ID]["Item Name"]) print(f"Price: " ,record[Item_ID]["Price"]) print(f"Quantity: " ,record[Item_ID]["Quantity"]) change=int(input("\nPress:\n1. Update Price:\n2.Update Quantity: ")) if change==1: pr=int(input("Enter updated Price: ")) record[Item_ID] = {"Item Name": record[Item_ID]["Item Name"], "Quantity": record[Item_ID]["Quantity"], "Price": pr, "Weight": record[Item_ID]["Weight"], "Category": record[Item_ID]["Category"], "Brand": record[Item_ID]["Brand"] } update_inventory() elif change==2: qn=int(input("Enter updated Quantity: ")) record[Item_ID] = {"Item Name": record[Item_ID]["Item Name"], "Quantity": qn, "Price": record[Item_ID]["Price"], "Weight": record[Item_ID]["Weight"], "Category": record[Item_ID]["Category"], "Brand": record[Item_ID]["Brand"] } update_inventory() else: print("Invalid option selected") else: print(f"No!! {Item_ID} is not present") def check_sales_item(): print("\n\n") count=0 mob = input("Enter Mobile No: ") for m_key in record_sale: if(record_sale[m_key]['Mobile']==mob): count=1 if count==1: print(f"Customer ID: " ,m_key) print(f"Mobile: " ,record_sale[m_key]["Mobile"]) print(f"Product Name: " ,record_sale[m_key]["Customer_Name"]) print(f"Mobile: " ,record_sale[m_key]["Mobile"]) else: print(f"No customer with {mob} exists") def add_data(): print("\n\n") Item_ID = input("Enter Item ID: ") Item_Name = input("Enter Item Name: ") qn = int(input("Enter Quantity: ")) pr = int(input("Enter Price: ")) w = input("Enter Weight: ") cate = input("Enter Category: ") brand = input("Enter Brand: ") record[Item_ID] = {"Item Name": Item_Name, "Quantity": qn, "Price": pr, "Weight": w, "Category": cate, "Brand": brand } update_inventory() def check_inventory(): print(record) def check_sales(): print(record_sale) def purchase(): print("\n\n") name=input("Your name please: ") phone=input("Your number please: ") Item_ID = input("Enter Item ID: ") if Item_ID in record.keys(): qn = int(input("Enter Quantity: ")) if qn<=int(record[Item_ID]["Quantity"]): print(f"Product ID: {Item_ID}") print(f"Product Name: " ,record[Item_ID]["Item Name"]) print(f"Price: " ,record[Item_ID]["Price"]) print(f"Total Amount: " ,record[Item_ID]["Price"]*qn) record[Item_ID]["Quantity"]=record[Item_ID]["Quantity"] - qn #print(f"Updated Quantity " ,record[Item_ID]["Quantity"]) update_inventory() record_sale[len(record_sale)+1] = {"Customer_Name": name, "Mobile": phone, "Item ID": Item_ID, "Quantity": qn, "Total_amount": record[Item_ID]["Price"]*qn } update_sales() else: print("Not that amount of item in stock") else: print(f"No item with {Item_ID} exists") def update_inventory(): js = json.dumps(record) fd = open("shoprecored.json",'w') fd.write(js) fd.close() def update_sales(): js = json.dumps(record_sale) fd1 = open("sales.json",'w') fd1.write(js) fd1.close() print("\n\n Welcome to Inventary Management System\n\n") c=1 while(c==1): print("\n\n MAIN MENU\n\n") switch=int(input("Press:\n1. Check Inventary record\n2. Check Sales record\n3. Add item in inventory\n4. Make an Purchase\n5. Check Inventary Item\n6. Check Customer details\n7. Update Inventary Item\n8. Exit: ")) if(switch==1): check_inventory() elif switch==2: check_sales() elif switch==3: add_data() elif switch==4: purchase() elif switch==5: check_inventory_item() elif switch == 6: check_sales_item() elif switch ==7: update_item_inventory() elif switch == 8: c=0 else: ("Undefined Input")
5de9cfb12de98f8b6a7c76464769c66a3114981b
cesaralmeida93/python_settings
/src/start.py
303
3.828125
4
def soma(num_1: int, num_2: int) -> int: """Somando dois numeros :param - num_1: primeiro numero da soma - num_2: segundo numero da soma :return - Soma entre dois numeros """ soma_dois_numeros = num_1 + num_2 return soma_dois_numeros SOMA_DOIS_NUMEROS = soma(1, 2)
9b9c346df8541a4277617683cc140410632d6fe1
casteluc/space-invaders
/src/entities.py
3,271
3.546875
4
import pygame from pygame.locals import * FRIEND, ENEMY = 0, 1 UP, DOWN = 1, -1 START, STOP = 0, 1 RIGHT, LEFT = 0, 1 BIG, SMALL = 0, 1 # Loads game images shipImg = pygame.image.load("C:\casteluc\coding\spaceInvaders\img\ship.png") enemyImg = pygame.image.load("C:\casteluc\coding\spaceInvaders\img\enemy.png") brokenEnemy = pygame.image.load("C:\casteluc\coding\spaceInvaders\img\enemyBroken.png") class Ship(): def __init__(self, size, x, y, speed): self.size = size self.x = x self.y = y self.speed = speed self.hasAmmo = False self.isAlive = True self.hitBox = (self.x + 7, self.y + 5, 50, 54) # Moves the ship and updates its hitbox def move(self, direction): if direction == RIGHT: self.x += self.speed else: self.x -= self.speed self.hitBox = (self.x + 7, self.y + 5, 50, 54) # Draws the ship in the screen def draw(self, screen): screen.blit(shipImg, (self.x, self.y)) class Enemy(Ship): def __init__(self, size, x, y, speed, life): super().__init__(size, x, y, speed) self.direction = RIGHT self.life = life self.previousDirection = LEFT self.hitBox = (self.x + 3, self.y + 8, 57, 45) if life == 2: self.type = BIG else: self.type = SMALL # Move the enemy ship and updates its hitbox def move(self, direction): if direction == RIGHT: self.x += self.speed elif direction == LEFT: self.x -= self.speed elif direction == DOWN: self.y += 10 self.hitBox = (self.x + 3, self.y + 8, 57, 45) # Draw enemy on screen def draw(self, screen): if self.type == BIG: if self.life == 2: screen.blit(enemyImg, (self.x, self.y)) else: screen.blit(brokenEnemy, (self.x, self.y)) else: screen.blit(enemyImg, (self.x, self.y)) class Bullet(): def __init__(self, ship, direction, shooter): self.size = (2, 20) self.surface = pygame.Surface(self.size) self.surface.fill((255, 255, 255)) self.x = ship.x + (32) self.y = ship.y self.speed = 5 self.inScreen = True self.hasCollided = False self.direction = direction self.shooter = shooter if self.shooter == ENEMY: self.surface.fill((255, 0, 0)) # Moves the bullet and checks if its of the screen def move(self): if self.y + 10 > 0 or self.y + 10 > 600: self.y -= self.speed * self.direction else: self.inScreen = False # Draws the bullet in the screen def draw(self, screen): screen.blit(self.surface, (self.x, self.y)) # Checks if the bullet collided with an enemy. Returns True # if it collided and False if not def collidedWith(self, ship): onWidth = self.x < ship.hitBox[0] + ship.hitBox[2] - 1 and self.x > ship.hitBox[0] - 2 onHeight = self.y < ship.hitBox[1] + ship.hitBox[3] and self.y + 20 > ship.hitBox[1] if onWidth and onHeight: return True else: return False
2588dfde5582125de98eb50ab20e76762e01be8d
pragatij17/General-Coding
/Day 1/si_ci.py
447
4
4
# Create a program to calculate simple interest and compound interest, take input from the user. def simple_interest(p, r, t): si = (p * r * t)/100 return si def compound_interest(p, r, t): amount = p*(pow((1+r/100),t)) ci = amount-p return ci p=int(input('The principal is: ')) t=float(input('The time period is: ')) r=int(input('The rate of interest is: ')) print(simple_interest(p, r, t)) print(compound_interest(p, r, t))
985bb44337d98dcf1b07803b84ae7417f48c0015
pragatij17/General-Coding
/Day 6/python/sum_of_numbers.py
256
4.25
4
# Write a program that asks the user for a number n and prints the sum of the numbers 1 to n. def sum_of_number(n): sum = 0 for i in range(1,n+1): sum =sum + i return sum n = int(input('Last digit of sum:')) print(sum_of_number(n))
67e3db0c3723dccacf09bbdcf56f8e4aae14cbcd
CarelHernandez/chatter-bot
/Chatter bot.py
1,506
3.984375
4
print(" hi my name is Car-two-el, I am here to help you get comftorable with talking to people so dont get intrigued. So whats your name?) Name == input () print (" Hi there" + Name + " so I heard your shy? its okay let me help you get comfortable?" ) answer = input () if answer == "okay" or answer == "fine" answer == "I guess" answer == "ok" print ("okay then lets get started" ) elif anser == "no" or answer == "na" or answer == "its okay im fine" break print (" what sport do you like?" sport == input() print (" okay, imagine I was playing" + sport + " and you wanted to play with me, how would you approach me?") input () if input == "idk" or input == "nothing" print (" come on you got this, just think") print (" ok let try actually having a normal conversation, just relax and breathe." ) print (" lets start off again by, What is something cool about you that you think someone would be amazed about?") input () if input !== "idk" print " that's amazing, yeah share that with someone new you meet! with me I would say that I am a 17 year old robot made by a human to help a human" ) print (" would you need anymore help with being comfortable while interacting with humans?" ) Hmm = input () if Hmm == "no thanks" or Hmm == "no" or Hmm == "na" or Hmm == "nope" break print (" I am gonna go to rest, i am over heating, have a good day!")
79580d10f09043e7703f0f49c88116037f0c4e48
kartikhans/competitiveProgramming
/Min_Stack.py
643
3.578125
4
class MinStack: def __init__(self): """ initialize your data structure here. """ self.arr=[] self.prr=[] self.mini=100000000000 def push(self, x: int) -> None: self.arr.append(x) if(x<self.mini): self.mini=x self.prr.append(self.mini) def pop(self) -> None: self.arr=self.arr[:-1] self.prr=self.prr[:-1] if(len(self.prr)>0): self.mini=self.prr[-1] else: self.mini=100000000000 def top(self) -> int: return(self.arr[-1]) def getMin(self) -> int: return(self.prr[-1])
448d642fc8db9bd6bc2f4fd654cff693dcc77f25
kartikhans/competitiveProgramming
/missing_Number.py
192
3.65625
4
def missingNumber(nums): n=len(nums) arr=[0]*(n+1) for i in nums: arr[i]=1 for i in range(n+1): if(arr[i]==0): return(i)
c84859d03e6df77d8575dddd7192f2f36852ba31
RojieEmanuel/intro-python
/102.py
2,170
4.1875
4
weekdays = ['mon','tues','wed','thurs','fri'] print(weekdays) print(type(weekdays)) days = weekdays[0] # elemento 0 days = weekdays[0:3] # elementos 0, 1, 2 days = weekdays[:3] # elementos 0, 1, 2 days = weekdays[-1] # ultimo elemento test = weekdays[3:] # elementos 3, 4 weekdays days = weekdays[-2] # ultimo elemento (elemento 4 days = weekdays[::] # all elementos days = weekdays[::2] # cada segundo elemento (0, 2, 4) days = weekdays[::-1] # reverso (4, 3, 2, 1, 0) all_days = weekdays + ['sat','sun'] # concatenar print(all_days) # Usando append days_list = ['mon','tues','wed','thurs','fri'] days_list.append('sat') days_list.append('sun') print(days_list) print(days_list == all_days) list = ['a', 1, 3.14159265359] print(list) print(type(list)) print('\n\t') # list.reverse() # print(list) ######### print('#############################################################################################################################') print( 'Exercicios - Listas') # Faca sem usar loops ######### # Como selecionar 'wed' pelo indice? print('\n1') print(days_list[2]) # Como verificar o tipo de 'mon'? print('\n2') print(type(days_list[0])) # Como separar 'wed' até 'fri'? print('\n3') print(days_list[2:5]) # Quais as maneiras de selecionar 'fri' por indice? print('\n4') print(days_list[4]) print(days_list[4:5]) # Qual eh o tamanho dos dias e days_list? print('\n5') dias = len(days) listaD= len(days_list) print('tamanho de dias: ', dias) print('tamanho de days_list: ', listaD) # Como inverter a ordem dos dias? print('\n6') print(weekdays[::-1]) # Como atribuir o ultimo elemento de list na variavel ultimo_elemento e remove-lo de list? print('\n 10') ultimo_elemento = list[-1] print(ultimo_elemento) list.remove(list[-1]) print(list) # Como inserir a palavra 'zero' entre 'a' e 1 de list? print('\n7') list.insert(1,'zero') print(list) # Como limpar list? print('\n8') print(list.clear()) # Como deletar list? print('\n9') print() print('######################################### FIM ##############################################################################')
714406f52f4bd8bd2569626d6ac185aadea1e33e
Worcester-Preparatory-School-Comp-Sci/python-2-for-loop-with-input-KurtLeinemann
/PigLatin.py
265
3.921875
4
## Kurt Leinamann Pig Latin September 26 2019 word=input("Pick a word") vowelList=['a','e','i','o','u'] if word[0] in vowelList: print(word +"yay") #yikes... print(print... also didn't need to select a slice of word.. just whole word else: print(word[1:] + word[0] + "ay")
e3c4390df61f4a0bc49568058e76bcbec10b4c24
Ram-cs/Interview-prep-Cracking-the-coding-solutions-by-chapter
/Inheritance.py
1,328
4.03125
4
# class Vehicle: def __init__(self,brake=0, accelerate=0): self.brake = brake self.accelerate = accelerate def accelerate(self, accelerate): self.accelerate = accelerate def brake(self, brake): self.brake = brake class Car(Vehicle): def __init__(self, brake, accelerate): Vehicle.accelerate(accelerate) Vehicle.brake(brake) class Person: def __init__(self): self.firstName = "" self.lastName = "" self.__private = 0 #private member can not access from outside even with the instance of Person Object def assignName(self,first,last): self.firstName = first self.lastName = last def getName(self): return self.firstName + " " + self.lastName class Employee(Person): def __init__(self,first, last, number): self.employee = number Person.__init__(self) Person.assignName(self,first,last) def getName(self): print(Person.getName(self)) print(self.employee) class C: def __init__(self): Person.__init__(self) self.ok = 5 e = Employee("Ram","Yadav", 1001) e.getName() e.firstName = "Changed" e.lastName = "Changes" e.getName() print(e.firstName) print(e.lastName) print(e.employee) Person.getName() c = C() print(c.firstName)
fbe429daf028265ea14c3a945938f8b0b4a2d6f0
Akif-Mufti/Machine-Learning-with-Python
/plot1Barhist.py
522
3.59375
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 26 14:23:46 2017 @author: user """ from collections import Counter from matplotlib import pyplot as plt grades = [83,95,67,54,23] decile = lambda grade:grade // 10*10 histogram = Counter(decile(grade) for grade in grades) plt.bar([x-4 for x in histogram.keys()], histogram.values(),8) plt.axis([-5,105,0,5]) plt.xticks([10*i for i in range(11)]) plt.xlabel("Decline") plt.ylabel("# of students") plt.title("Distribution of Exam one grade") plt.show()
c1503433697543bdd5f5a3bd16ffd47a86574dbd
Akif-Mufti/Machine-Learning-with-Python
/FS3.py
522
3.515625
4
# Feature Extraction with PCA from pandas import read_csv from sklearn.decomposition import PCA # load data filename = 'pima-indians-diabetes.data.csv' names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = read_csv(filename, names=names) array = dataframe.values X = array[:,0:8] Y = array[:,8] # feature extraction pca = PCA(n_components=3) fit = pca.fit(X) # summarize components print("Explained Variance: %s"% fit.explained_variance_ratio_) print(fit.components_)
14acca9d50adbf5c80ae0b1884ec5236410c5138
captain204/Python-notes
/circle_rectangle.py
542
3.8125
4
from circle import Circle from rectangle import Rectangle class ShapeDemo(): @classmethod def main(cls, arg): width = 2 length = 3 radius =10 rectangle= Rectangle(width,length) print("Rectangle with:",width,"Length",length, "Rectangle area",rectangle.area(),rectangle.perimeter()) circle = Circle(radius) print("Circle radius", radius, "Circle area", circle.area,"Circle Perimeter",circle.perimeter()) if __name__ == "__main__": import sys ShapeDemo.main(sys.argv)
b32bde9d8552deda474e649b149e96dda4262915
Tu-Jiawei/For-study
/CNN for mnist.py
3,517
3.859375
4
''' from book 'Tensorflow+Keras 深度学习人工智能实践应用' TensorFlow MNIST数据集,卷积神经网络 ''' import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) def weight(shape): return tf.Variable(tf.truncated_normal(shape,stddev=0.1),name='W') def bias(shape): return tf.Variable(tf.constant(0.1,shape=shape),name='b') def conv2d(x,W): return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') with tf.name_scope('optimizer'): y_label=tf.placeholder("float",shape=[None,10],name="y_label") loss_function=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=y_predict,labels=y_label)) optimizer=tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss_function) with tf.name_scope("evaluate_model"): correct_prediction=tf.equal(tf.argmax(y_predict,1),tf.argmax(y_label,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float")) trainEpochs = 30 batchSize = 100 totalBatchs = int(mnist.train.num_examples/batchSize) epoch_list=[];accuracy_list=[];loss_list=[]; from time import time startTime=time() sess = tf.Session() sess.run(tf.global_variables_initializer()) for epoch in range(trainEpochs): for i in range(totalBatchs): batch_x, batch_y = mnist.train.next_batch(batchSize) sess.run(optimizer,feed_dict={x: batch_x, y_label: batch_y}) loss,acc=sess.run([loss_function,accuracy],feed_dict={x:mnist.validation.images, y_label:mnist.validation.labels}) epoch_list.append(epoch);loss_list.append(loss);accuracy_list.append(acc) print("Trian Epoch:",'%02d'%(epoch+1),"Loss=","{:.9f}".format(loss),"Accuracy:",acc) duration=time()-startTime print("Train Finished takes:",duration) #the loss about epoch %matplotlib inline import matplotlib.pyplot as plt fig=plt.gcf() fig.set_size_inches(10,5) plt.plot(epoch_list,loss_list,label='loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['loss'], loc='upper left') #the accuracy about epoch plt.plot(epoch_list, accuracy_list,label="accuracy" ) fig = plt.gcf() fig.set_size_inches(10,5) plt.ylim(0.8,1) plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend() plt.show() #test model in test datasets of mnist len(mnist.test.images) print("Accuracy:",sess.run(accuracy,feed_dict={x:mnist.test.images,y_label:mnist.test.labels})) prediction_result=sess.run(tf.argmax(y_predict,1),feed_dict={x:mnist.test.images[:50],y_label:mnist.test.labels}) print(prediction_result[:20]) #result show in photoes import numpy as np def show_images_labels_predict(images,labels,prediction_result): fig=plt.gcf() fig.set_size_inches(8,10) for i in range(0,20): ax=plt.subplot(5,5,1+i) ax.imshow(np.reshape(images[i],(28,28)),cmap='binary') ax.set_title("label=" +str(np.argmax(labels[i]))+ ",predict="+str(prediction_result[i]) ,fontsize=9) plt.show() show_images_labels_predict(mnist.test.images,mnist.test.labels,prediction_result) #save the model saver=tf.train.Saver() save_path=saver.save(sess,"saveModel/CNN_model1") print("Model saved in file: %s" % save_path) #export to tensorboard merged=tf.summary.merge_all() train_writer=tf.summary.FileWriter('log/CNN',sess.graph)
65307d9013fa55f166c2c669bd7290547c4e986b
DavidFitoussi/InheritanceSample
/Person.py
1,433
3.734375
4
from enum import Enum class TypePerson(Enum): student = 1 worker = 2 class Person: def __init__(self,name ="ingonito", age = None , height = None ): self.name = name # if name != None else "incognito" self.age = age self.height = height def WhoIam(self): print("person1.name={} is a{}".format(self.name,type(self))) class Student(Person): def __init__(self,department): Person.__init__(self, name="new student") self.department = department class Worker(Person): def __init__(self,salary): Person.__init__(self, name="new Worker") self.salary = salary class AbstactPerson(): def __init__(self, typePerson , globalname ): self.myPerson = Person() self.typePerson = typePerson if (typePerson == TypePerson.student ): self.myPerson = Student(globalname) else : self.myPerson = Worker(globalname) def getPerson(self): return self.myPerson instanceAbs = AbstactPerson(TypePerson.student,"dav") instanceAbs.getPerson().WhoIam() Person1 = Person(age=22,height=1.88) Person2 = Student("Computer Science") Person2.WhoIam() # function # create MobilePhone class # in init print("creating a phone") # create methods: ring, powerOn, # powerOff # create secret method: factoryRestart # create 2 phones
5a2c158aeb9c35af7c7cc3d5b2f8c08afc6200d5
GVK289/aws_folders
/backend-PY/car1.py
492
3.53125
4
class Car: def __init__(self, in_color,car_type, car_acc): #print('GVK') self.color = in_color self.accleration = car_acc self.type = car_type self.current_speed = 100 self.decelerate = 15 def accelerate(self): self.current_speed += self.accleration def brake(self): if self.current_speed>15: self.current_speed -= self.decelerate elif self.current_speed<15: self.current_speed = 0
1b1e1d95577219087180b5ef9f66c08fa339fc59
GVK289/aws_folders
/backend-PY/robo-main.py
1,146
3.59375
4
class Employee: bonous = 10000 no_of_employees = 0 raise_amount = 1.04 def __init__(self,first_name, last_name, salary): self.first_name = first_name self.last_name = last_name self.salary = salary self.email = first_name + '.' + last_name + '@gmail.com' Employee.no_of_employees +=1 def fullname(self): return '{} {}'.format(self.first_name,self.last_name) def apply_bonous(self): self.bonous = int(self.bonous + self.salary) def apply_raise(self): self.salary = int(self.salary * self.raise_amount) # @classmethod # def from_string(cls, emp_str): # first_name, last_name, salary = emp_str.split(' ') # return cls(first_name, last_name, salary) class Developer(Employee): raise_amount = 1.10 def __init__(self, first_name, last_name, salary, prog_lang): super().__init__(first_name, last_name, salary) self.prog_lang = prog_lang emp1 = Developer('vinay', 'kumar', 50000, 'Python') emp2 = Developer('vvv', 'kkkk', 60000, 'HTML') print(emp1.email) print(emp2.email)
1343e30afb43c35c44b16ddf3abf57dcae7ce2de
GVK289/aws_folders
/clean_code/clean_code_submissions/clean_code_assignment_002/test_car.py
10,605
3.546875
4
import pytest from car import Car ########### ******** Testing wether One object is creating ******** ########### def test_car_creating_one_car_object_with_given_instances_creates_car_object(): # Arrange color = 'Black' max_speed = 200 acceleration = 30 tyre_friction = 7 car_obj = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Act result = isinstance(car_obj, Car) # Assert assert result is True ########### ******** Testing wether Multiple objects are creating ******** ########### def test_car_creating_multiple_car_objects_with_given_instances_creates_car_objects(): # Arrange car_obj1 = Car(color='Red', max_speed=250, acceleration=50, tyre_friction=10) car_obj2 = Car(color='Black', max_speed=200, acceleration=40, tyre_friction=7) # Act creation_of_car_object1 = isinstance(car_obj1, Car) creation_of_car_object2 = isinstance(car_obj2, Car) result = car_obj1 == car_obj2 # Assert assert creation_of_car_object1 is True assert creation_of_car_object2 is True assert result is False ########### Testing the class Atrribute values Formats ########### def test_car_object_color_when_color_type_is_invalid_raises_exception(): """test that exception is raised for invalid color format""" # Arrange color = 1 max_speed = 30 acceleration = 10 tyre_friction = 3 # Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == "Invalid value for color" """ **** Testing Exceptions of class Atrribute values if not Positive type and Non-Zero **** """ @pytest.mark.parametrize("max_speed, acceleration, tyre_friction", [(-1, 10, 3), (0, 30, 10), ('1', 30, 20)]) def test_car_object_max_speed_when_max_speed_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction): # Arrange color = 'Red' # Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == 'Invalid value for max_speed' @pytest.mark.parametrize("max_speed, acceleration, tyre_friction", [(210, '10', 3), (100, 0, 10), (180, -30, 20)]) def test_car_object_acceleration_when_acceleration_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction): # Arrange color = 'Red' # Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == 'Invalid value for acceleration' @pytest.mark.parametrize("max_speed, acceleration, tyre_friction", [(210, 30, '10'), (100, 20, -1), (180, 40, 0)]) def test_car_object_tyre_friction_when_tyre_friction_value_is_invalid_raises_exception(max_speed, acceleration, tyre_friction): # Arrange color = 'Red' #Act with pytest.raises(Exception) as e: assert Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) # Assert assert str(e.value) == 'Invalid value for tyre_friction' ########### ******** Multiple Testings ******** ########### @pytest.fixture def car(): # Our Fixture function # Arrange color = 'Red' max_speed = 200 acceleration = 40 tyre_friction = 10 car_obj = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) return car_obj def test_car_object_when_engine_is_started_returns_true(car): # Arrange car.start_engine() # Act car_engine_start = car.is_engine_started # Assert assert car_engine_start is True def test_car_object_when_engine_is_started_twice_returns_true(car): # Arrange car.start_engine() car.start_engine() # Act car_engine_start = car.is_engine_started # Assert assert car_engine_start is True def test_car_object_when_engine_is_stop_returns_false(car): # Arrange car.stop_engine() # Act car_engine_stop = car.is_engine_started # Assert assert car_engine_stop is False def test_car_object_when_engine_is_stop_twice_returns_false(car): # Arrange car.stop_engine() car.stop_engine() # Act car_engine_stop = car.is_engine_started # Assert assert car_engine_stop is False def test_car_object_accelerate_when_engine_is_started_returns_current_speed(car): # Arrange car.start_engine() current_speed = 40 # Act car.accelerate() # Assert assert car.current_speed == current_speed def test_car_object_accelerate_when_car_object_current_speed_is_equal_to_car_object_max_speed_limit_returns_max_speed(car): # Arrange car.start_engine() max_speed = 200 car.accelerate() car.accelerate() car.accelerate() car.accelerate() # Act car.accelerate() # Assert assert car.current_speed == max_speed # ***** New capsys terminology ******* # def test_car_object_accelerate_when_car_engine_is_stop_returns_start_the_engine_to_accelerate(capsys, car): # Act car.accelerate() captured = capsys.readouterr() # Assert assert captured.out == 'Start the engine to accelerate\n' def test_car_object_sound_horn_when_engine_is_started_returns_Beep_Beep(capsys, car): # Arrange car.start_engine() # Act car.sound_horn() captured = capsys.readouterr() # Assert assert captured.out == 'Beep Beep\n' def test_car_object_sound_horn_when_engine_is_stop_returns_start_the_engine_to_sound_horn(capsys, car): # Act car.sound_horn() captured = capsys.readouterr() # Assert assert captured.out == 'Start the engine to sound_horn\n' ######## *********** Testing Encapusulation *********** ######## def test_encapsulation_of_car_object_color(car): # Act with pytest.raises(Exception) as e: car.color = 'Black' # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_acceleration(car): # Act with pytest.raises(Exception) as e: car.acceleration = 20 # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_max_speed(car): # Act with pytest.raises(Exception) as e: car.max_speed = 400 # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_tyre_friction(car): # Act with pytest.raises(Exception) as e: car.tyre_friction = 40 # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_is_engine_started(car): # Act with pytest.raises(Exception) as e: car.is_engine_started = True # Assert assert str(e.value) == "can't set attribute" def test_encapsulation_of_car_object_current_speed(car): # Act with pytest.raises(Exception) as e: car.current_speed = 300 # Assert assert str(e.value) == "can't set attribute" #---------------------------------------# @pytest.mark.parametrize( "color, max_speed, acceleration, tyre_friction, current_speed", [ ('Red', 1, 1, 1, 1), ('Blue', 150, 30, 10, 20), ('Black', 200, 40, 10, 30)]) def test_car_object_accelerate_when_car_object_current_speed_is_more_than_car_object_max_speed_limit_returns_max_speed(color, max_speed, acceleration, tyre_friction, current_speed): # Arrange car = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) car.start_engine() car.accelerate() car.accelerate() car.accelerate() car.accelerate() car.accelerate() car.accelerate() # Act car.accelerate() # Asset assert car.current_speed == max_speed def test_car_object_current_speed_when_car_object_is_in_idle_postion_intially_returns_zero(): # Arrange car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4) # Act car_idle_initial_speed = car.current_speed # Act assert car_idle_initial_speed == 0 def test_car_object_current_speed_when_car_object_engine_is_stopped_from_motion_returns_current_speed(): # Arrange car = Car(color='Red', max_speed=180, acceleration=45, tyre_friction=4) car.start_engine() current_speed = 135 car.accelerate() car.accelerate() car.accelerate() # Act car.stop_engine() # Assert assert car.current_speed == current_speed def test_apply_brakes_when_car_object_is_in_motion_returns_current_speed(car): # Arrange car.start_engine() car.accelerate() car.accelerate() current_speed = 70 # Act car.apply_brakes() # Assert assert car.current_speed == current_speed @pytest.mark.parametrize( "color,max_speed, acceleration, tyre_friction, current_speed", [ ('Red', 200, 50, 20, 30), ('Blue', 150, 25, 25, 0)]) def test_apply_breaks_when_car_object_current_speed_is_more_than_or_equal_to_car_object_tyre_friction_returns_current_speed(color, max_speed, acceleration, tyre_friction, current_speed): # Arrange car = Car(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction) car.start_engine() car.accelerate() # Act car.apply_brakes() # Assert assert car.current_speed == current_speed def test_apply_breaks_when_car_object_current_speed_is_less_than_car_object_tyre_friction_returns_zero(): # Arrange car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=15) car.start_engine() car.accelerate() current_speed_when_less_than_tyre_friction = 0 car.apply_brakes() car.apply_brakes() # Act car.apply_brakes() # Assert assert car.current_speed == current_speed_when_less_than_tyre_friction def test_apply_breaks_when_car_object_current_speed_is_equal_to_car_object_tyre_friction_returns_current_speed(): # Arrange car = Car(color='Red', max_speed=200, acceleration=40, tyre_friction=10) car.start_engine() car.accelerate() current_speed = 10 car.apply_brakes() car.apply_brakes() # Act car.apply_brakes() # Assert assert car.current_speed == current_speed
b293cdff81ef8d76c469aa41d74e33b26cbb64d3
zzynggg/python
/Sorting Algorithm.py
25,041
3.953125
4
# Author: Yong Zi Ying # Sorting Algorithm # Grade: 19.6/20 HD #%% Task 1:Radix Sort def best_interval(transactions, t): ''' This function is used to search for the total number of transactions within the best interval by using 2 pointers. :Input: An unsorted list of non-negative integers and a non-negative integer that represent a length of time in seconds (range). :Output: The best interval with minimum start time and the total number of transaction within the best interval. :Time Complexity: Best and worst case will be the same as the best and worst case for radix sort are the same. No matter there's only one element or more in the list, it will be pre-sorted by using radix sort. O (kN) + O (N) = O (kN), where O (kN) is from the radix sort function (explained in radix_sort function) and N is the length of the input list. :Auxiliary Space Complexity: O (N), which is from radix sort function (explained in radix_sort function). In this function, it required extra space for sorting which is O (N) auxiliary space and in comparing state does not required any extra space. :Space Complexity: O (kN), which is from radix sort function (explained in radix_sort function). The input space for comparing state is O (N) and the extra space for comparing state is O (1) so the space complexity will be O (kN) + O (N) + O (1) = O (kN) :Explanation: The input list will loop once only and 2 pointers are moving along the list to get the best time interval and the total number of transactions within the best interval. More details explanation is commented at the code. ''' # === sorting state === new_transactions = radix_sort(transactions) # pre-sort the transactions list # === Comparing state === begin_pointer = 0 exit_pointer = 0 counter = 0 max_counter = 0 best_t = 0 while begin_pointer < len(new_transactions): if len(new_transactions) == 0: # list is empty max_counter = 0 best_t = 0 break if (new_transactions[0]+t) >= new_transactions[-1]: # the first element + t is >= last element max_counter = len(new_transactions) best_t = new_transactions[-1] - t if best_t <= 0: # best_t cannot be -ve best_t = 0 break # exit loop early if (new_transactions[begin_pointer]+t) >= new_transactions[-1] or exit_pointer > len(new_transactions): break if new_transactions[exit_pointer] <= (new_transactions[begin_pointer]+t): # within the current interval exit_pointer += 1 elif new_transactions[exit_pointer] > (new_transactions[begin_pointer]+t): # exceed the current interval counter = exit_pointer - begin_pointer # get the total num of transaction within the interval if counter > max_counter: # get the largest total num of transaction within the list max_counter = counter best_t = new_transactions[exit_pointer-1] - t if best_t <= 0: # best_t cannot be -ve best_t = 0 counter = 0 if (new_transactions[begin_pointer]+t) < new_transactions[exit_pointer]: # duplicated element is found in the list begin_pointer += 1 # extra check to make sure the output is accurate counter = len(new_transactions) - begin_pointer # check the counter again if counter > max_counter: # update the max_counter if new bigger counter is found max_counter = counter best_t = new_transactions[-1] - t # update the best_t if new bigger counter is found if best_t <= 0: # best_t cannot be -ve best_t = 0 return (best_t, max_counter) def radix_sort(transactions): ''' To sort the input list into sorted list by calling multiple times of counting sort function. :Input: An unsorted list. :Output: A sorted list is returned. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(k) * O(N+M) -> O (kN + kM) = O (kN), where k is the biggest length of the element in the list, N is the length of the input list and M which is base constant so ignore M. We will need to call counting sort function for k times. :Auxiliary Space Complexity: each counting sort needs O(N + M + N) = O(N), where first N is the length of the output_array (new list that is same size with original list) that is created in the counting sort function based on the length of the input list and M (base) is the length of buckets. (count_array). A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and M is a constant number (base) so ignore it. :Space Complexity: O(kN+N+M+N) = O(kN), space complexity is input space + extra space. The input space is the length of the input list(N) and k columns (number of digits) which is O (kN) whereas the extra space from counting sort is O (N + M + N). M is base constant. (explained above) ''' # find max number of digits if len(transactions) > 0: max_num = max(transactions) else: max_num = 0 base = 10 columnn = 0 digit = base**columnn # loop the counting sort while max_num//digit > 0: counting_sort(transactions, digit, base) columnn += 1 digit = base**columnn return transactions def counting_sort(transactions, digit, base): ''' To sort the input list column by column into sorted list. :Input: An unsorted list, the column that is used to sort currently and the base value. :Output: The list is sorted until the current column. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(N+M), where N is the length of the input list and M is the biggest length of the element in the list. :Auxiliary Space Complexity: O(N + B + N) = O(N), where first N is the length of the output_array that is created in the functions based on the length of the input list and B (base) is the length of buckets. (count_array) A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and B is a constant number (base) so ignore it. :Space Complexity: O(N+N+B+N) = O(N), space complexity is input space + extra space. The input space is the length of the input list which is O (N) and the extra space is O (N + B + N). (explained above) ''' size = len(transactions) # initialize count array start from index 1 -> max_num count_array = [0] * base # initialize output array output_array = [0] * size # allocate number of elements to count array # base on the digit (column by column) for i in range(0, size): ind = transactions[i] // digit count_array[ind%base] += 1 # reused the count_array for position array for j in range(1, base): count_array[j] += count_array[j-1] # place the elements base on the position(count_array) # loop it in descending order for k in range(size-1, -1, -1): ind = transactions[k] // digit # get the right most digit output_array[count_array[ind%10] - 1] = transactions[k] count_array[ind%10] -= 1 # reuse and update the original list for l in range(0, size): transactions[l] = output_array[l] # %% Task 2: Counting Sort + Radix Sort def words_with_anagrams(list1, list2): ''' Using anagram to compare the words between 2 lists. Output the same anagram word from list1 that appears in list2. List1 will be priorities for output. :Input: Two unsorted string lists. :Output: A list of word from list1 that appear in list2 based on the same anagram of words. :Time Complexity: Best and worst case will be the same, O (L1M1 + L2M2), where L1 is the length of list1 and M1 is the biggest length of the characters of element in list1. L2 is the length of list2 and M2 is the biggest length of the characters of element in list2. if list1 have only 1 item to compare with multiple items in list2 the time complexity will be O (L1M1 + L2M2) vice versa when list2 have 1 item only. (of course the best is when either one of the lists is empty then the best complexity will be O(1)) The sorting state based on characters, the complexity for list1 is O (L1M1) and list2 is O (L2M2). The sorting state based on string elements, the complexity for list1 is O (L1) and list2 is O (L2). The comparing state complexity is based on the length of list1 which is O (L1) The comparing state 2 (refer to in-line comment) is constant. Thus, the overall time complexity is O (L1 + L1+ L2 + L1M1 + L2M2) = O (L1M1 + L2M2) :Auxiliary Space Complexity: O (L1 + L1 + L2) = O (L1 + L2), where L1 is the length of the duplication of list1 (deep copy list1 into new list) and a new list is created (output_list) with the same length as list1 (L1). The worst scenario is if all elements in list1 is appear in list2 so entire list1 is returned (L1 extra space needed). Another new list is created for list2 without duplicate elements, the length will be same as the original list2 if there’s no duplicate element in it (worse scenario). :Space Complexity: O (L1 + L2 + L1 + L2) = O (L1 + L2), space complexity is input space + extra space. The input space is L1 + L2, where L1 is the length of list1 and L2 is the length of list2. The extra space is O (L1 + L2) (explained above). :Explanation: Two lists are given, list1 will be priorities. All string elements from both lists are sorted in alphabetical order based on the characters in each string elements. [cats -> acst] After sorting each characters of string elements, sort both lists again now is sorted based on the entire string elements. [aelpp, acst -> acst, aelpp] Now, remove the duplicated elements in list2 and start comparing both lists. While comparing if the element from both lists has same initial character, it will be compared again based on each characters of the string elements. More details explanation is commented at the code. ''' # handle empty list if len(list1) == 0 or len(list2) == 0: # both list are empty return [] xori_list1 = list1.copy() # deep copy the list to prevent data loss (extra space required) xori_size = len(xori_list1) output_list = [] # extra space required # === Priority list (list1) === for i in range(xori_size): # sort each *characters* in word xori_list1[i] = counting_sort_alphabet(xori_list1[i]) for j in range(xori_size): # pair up each element with an unique key xori_list1[j] = (xori_list1[j], j) for _ in range(xori_size): # sort each *word* in list1 sorted_xori_list1 = radix_sort_string(xori_list1, 1) # === List 2 === list2_size = len(list2) for l in range(list2_size): # sort each *characters* in word list2[l] = counting_sort_alphabet(list2[l]) for _ in range(list2_size): # sort each *word* in list2 sorted_list2 = radix_sort_string(list2, 2) begin = 0 # start pointer exitt = 0 # end pointer while exitt < len(sorted_list2)-1: # remove duplicate anagram word in list2 if sorted_list2[begin] == sorted_list2[exitt+1]: exitt += 1 else: sorted_list2[begin+1] = sorted_list2[exitt+1] begin += 1 exitt += 1 sorted_xdupli_list2 = [] # extra space required for n in range(exitt): # list2 without duplicate elements sorted_xdupli_list2.append(sorted_list2[n]) if (len(sorted_list2) < 2): # restore list2 if only 1 element in list2 sorted_xdupli_list2 = sorted_list2 # === Comparing state === a = 0 # list one pointer b = 0 # list two pointer exit_check = 0 # avoid inf loop while a < xori_size: if sorted_xori_list1[a][0] == sorted_xdupli_list2[b]: # same anagram word found ori_pos = sorted_xori_list1[a][1] # original index of word output_list.append(list1[ori_pos]) a += 1 elif sorted_xori_list1[a][0] != sorted_xdupli_list2[b]: # different anagram word found # handle empty string if sorted_xori_list1[a][0] == '' and sorted_xdupli_list2[b] != '': a += 1 elif sorted_xori_list1[a][0] != '' and sorted_xdupli_list2[b] == '': b += 1 # compare the first character of the anagram word elif (sorted_xori_list1[a][0])[0] > sorted_xdupli_list2[b][0]: # compare first character b += 1 elif (sorted_xori_list1[a][0])[0] == sorted_xdupli_list2[b][0]: # compare first character # first character same pointer1 = 0 pointer2 = 0 meet_condition = True # comparing state 2 for _ in range(len(sorted_xori_list1[a][0])): # length of the word in list1 if (sorted_xori_list1[a][0])[pointer1] == (sorted_xdupli_list2[b])[pointer2]: # same initial is found pointer1 += 1 pointer2 += 1 meet_condition = False elif (sorted_xori_list1[a][0])[pointer1] > (sorted_xdupli_list2[b])[pointer2]: meet_condition = True b += 1 break elif (sorted_xori_list1[a][0])[pointer1] < (sorted_xdupli_list2[b])[pointer2]: meet_condition = True a += 1 break if pointer2 > len(sorted_xdupli_list2[b])-1: # exceed the length of word from list2 meet_condition = True b += 1 break # extra check if meet_condition == False: a += 1 # len(word1) < len(word2) else: # first character different a += 1 # extra check (improve accuracy) if b >= len(sorted_xdupli_list2)-1: # if list1 longer then list2 maintain the last element of list2 exit_check += 1 b = len(sorted_xdupli_list2)-1 # exit loop early if a > len(sorted_xori_list1)-1 and b == len(sorted_xdupli_list2)-1: break elif exit_check > a: break return output_list def radix_sort_string(listt, priority_list): ''' To sort the input list into sorted list by calling multiple times of counting sort function. :Input: An unsorted list and the priority number for the list (explained later). :Output: A sorted list. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(k) * O(N+M) -> O (kN + kM) = O (kN), where k is the biggest length of the element in the list, N is the length of the input list and M which is base constant so ignore M. We will need to call counting sort function for k times. :Auxiliary Space Complexity: each counting sort needs O(N + M + N) = O(N), where first N is the length of the output_array (new list that is same size with original list) that is created in the counting sort function based on the length of input list and M (base) is the length of buckets (count_array). A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and M is a constant number (base) so ignore it. :Space Complexity: O(kN+N+M+N) = O(kN), space complexity is input space + extra space. The input space is the length of the input list, N and k columns (number of digits) which is O (kN) whereas the extra space from counting sort is O (N + M + N). M is base constant. (explained above) :Explanation: The input parameter, priority_list is used to differentiate the list between list1 and list2. List1 will be priorities because we need to output the word from list1 that appear in list2 when comparing the word from both lists by using anagram. In order to get back the original words from list1 after comparing, each elements of list1 are paired up with a unique key so that the output is the original word (e.g cats) but not the sorted word (e.g acst). ''' max_word_size = len(listt[0]) # column if priority_list == 1: # list1 with keys # find the longest string in listt for i in range(len(listt)): word_size = len(listt[i][0]) if word_size > max_word_size: max_word_size = word_size else: # find the longest string in listt for word in listt: word_size = len(word) if word_size > max_word_size: max_word_size = word_size base = 27 # start at index 1 -> 27 column = max_word_size - 1 # word len = 4 (index[0-3]) # loop the string counting sort for column times while column >= 0: listt = counting_sort_word(listt, column, base, max_word_size, priority_list) column -= 1 return listt def counting_sort_word(listt, column, base, max_word_size, priority_list): ''' To sort the input list column by column into sorted list. :Input: An unsorted list, the column that is used to sort currently, the base value, the biggest length of the element in the list and the priority number of the list(explained in radix_sort_string). :Output: The list is sorted until the current column. :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(N+M), where N is the length of the input list and M is the biggest length of the element in the list. :Auxiliary Space Complexity: O(N + B + N) = O(N), where first N is the length of the output_array that is created in the functions based on the length of input list and B (base) is the length of buckets (count_array). A total of N number of items (second N) will be placed into buckets (same as the total items in output_array) and B is a constant number (base) so ignore it. :Space Complexity: O(N+N+B+N) = O(N), space complexity is input space + extra space. The input space is the length of the input list which is O (N) and the extra space is O (N + B + N). (explained above) ''' size = len(listt) # initialize count array start from index [0-26]-> 27 slots count_array = [0] * base # initialize output array output_array = [0] * size # allocate the char in the correct position ('a' at index 1) # ord('a') = 97 -1 = 96 accurate = ord('a') - 1 if priority_list == 1: # list1 with keys # allocate words to count_array # index 0 act as temporary storage for i in range(size): word = listt[i][0] if column < len(word): index = ord(word[column]) - accurate else: index = 0 count_array[index] += 1 else: # allocate words to count_array # index 0 act as temporary storage for word in listt: if column < len(word): index = ord(word[column]) - accurate else: index = 0 count_array[index] += 1 # reused the count_array for position array for j in range(1, base): count_array[j] += count_array[j-1] if priority_list == 1: # list1 with keys # place the elements base on the position(count_array) # loop it in descending order for k in range(size-1, -1, -1): word = listt[k][0] if column < len(word): # get the right most char index = ord(word[column]) - accurate else: index = 0 output_array[count_array[index] - 1] = listt[k] # store the tuple into output_array count_array[index] -= 1 else: # place the elements base on the position(count_array) # loop it in descending order for k in range(size-1, -1, -1): word = listt[k] if column < len(word): # get the right most char index = ord(word[column]) - accurate else: index = 0 output_array[count_array[index] - 1] = word # store the word into output_array count_array[index] -= 1 return output_array def counting_sort_alphabet(word): ''' To sort the word column by column into sorted word. :Input: A word with random alphabetical order (unsorted word). :Output: Each alphabet in the word is sorted (sorted word). :Time Complexity: Best and Worst complexity will be the same as the iterator doesn't terminate early. O(N+M) = O (N), where N is the length of the word and M is the base of the word which is constant. :Auxiliary Space Complexity: O(N + B + N) = O(N), where first N is the length of the output_array that is created in the functions based on the length of input word and B (base) is the length of buckets (count_array). A total of N number of characters (second N) will be placed into buckets (same as the total items in output_array) and B is a constant number (base) so ignore it. :Space Complexity: O(N+N+B+N) = O(N), space complexity is input space + extra space. The input space is the length of the input word which is O (N) and the extra space is O (N + B + N). (explained above) ''' size = len(word) base = 27 # initialize count array start from index [0-26]-> 27 slots count_array = [0] * base # initialize output array output_array = [0] * size # allocate the char in the correct position ('a' at index 1) # ord('a') = 97 -1 = 96 accurate = ord('a') - 1 sorted_word = "" # allocate characters into count_array # index 0 act as temporary storage for alphabet in range(size): index = ord(word[alphabet]) - accurate count_array[index] += 1 # place the elements base on the position(count_array) index = 0 for i in range(len(count_array)): alpha = chr(i + accurate) frequency = count_array[i] for _ in range(frequency): output_array[index] = alpha index += 1 # combine each characters into word for j in output_array: sorted_word += j return sorted_word
dcf7913f53b7ea31ba263c2a26ecd5a52334846e
SaidRem/algorithms
/find_biggest_(recursion).py
404
4.21875
4
# Finds the biggest element using recursion def the_biggest(arr): # Base case if length of array equals 2 . if len(arr) == 2: return arr[0] if arr[0] > arr[1] else arr[1] # Recursion case. sub_max = the_biggest(arr[1:]) return arr[0] if arr[0] > sub_max else sub_max if __name__ == '__main__': arr = list(map(int, input().strip().split())) print(the_biggest(arr))
97789c67c970f11cc90742a11d1bb43e7f94fb01
ekaterina533/lab2.2
/2задание.py
211
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == "__main__": a=input("Введите слово:") b=input("Введите ещё одно слово:") c = set(a).intersection(set(b)) print(c)
c31a7cc8af986a8823b96cc4cc72293040f3b710
richi1325/Markovian_decision_processes
/main.py
3,864
3.5
4
from time import sleep from menu import portada, eleccion from lectura import lecturaPMD, validadorEnteros from algoritmos import * from os import system from examples import base1 def main(): portada() input() tipo = None while True: system("cls") eleccion() seleccion = input("\n Seleccione una opción:") if seleccion == "1": tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() elif seleccion == "2": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() enumeracionExhaustivaPoliticas(estados,estados_decisiones, cij, k, tipo) input() elif seleccion == "3": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() solucionPorProgramacionLineal(estados,estados_decisiones, cij, k, tipo) input() elif seleccion == "4": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() mejoramientoPoliticas(estados,estados_decisiones, cij, k, tipo) input() elif seleccion == "5": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() alpha = validadorFlotantes(' Inserte el factor de descuento:') mejoramientoPoliticasDescuento(estados,estados_decisiones, cij, k, tipo, alpha) input() elif seleccion == "6": if tipo == None: print(" No se han ingresado los datos por primera vez, serás redireccionado a la opción 1....") sleep(6) tipo, estados, decisiones, estados_decisiones, decisiones_estados, cij, k = lecturaPMD() alpha = validadorFlotantes(' Inserte el factor de descuento:') iteraciones = validadorEnteros(' Inserte el número de iteraciones:') tolerancia = validadorFlotantesPositivos(' Inserte la tolerancia del método:') aproximacionesSucesivas(estados,estados_decisiones, cij, k, tipo,alpha,iteraciones,tolerancia) input() elif seleccion == "7": break else: print("\n¡Por favor ingrese una opción válida!") sleep(2) print(""" _ /.\\ Y \\ / "L // "/ |/ /\_================== / / / / ¡Hasta la próxima! \/ """) sleep(3) def validadorFlotantes(mensaje): while True: try: numero = input(mensaje) numero = float(numero) break except ValueError: print('¡Debes insertar un número!') return numero def validadorFlotantesPositivos(mensaje): while True: try: numero = input(mensaje) numero = float(numero) if numero<=0.0: print('El valor debe ser mayor a 0!') else: break except ValueError: print('¡Debes insertar un número!') return numero if __name__ == "__main__": main()
402632370f075fec73ef83f052aaee9150349108
zoulala/exercise
/leetcode/Sort_quick.py
1,338
3.90625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # # ***************************************************** # # file: Sort_quick.py # author: zoulingwei@zuoshouyisheng.com # date: 2021-12-29 # brief: # # cmd>e.g: # ***************************************************** """快速排序: 说白了就是给基准数据找其正确索引位置的过程,本质就是把基准数大的都放在基准数的右边,把比基准数小的放在基准数的左边,这样就找到了该数据在数组中的正确位置. 然后递归实现左边数组和右边数组的快排。 """ def quick_sort(nums, st, et): if st>=et: return i,j = st, et # 设置基准数 base = nums[i] # 如果列表后边的数比基准数大或相等,则前移一位直到有比基准数小的数 while (i < j) and (nums[j] >= base): j = j - 1 # 如找到,则把第j个元素赋值给第i个元素 nums[i] = nums[j] # 同样的方式比较前半区 while (i < j) and (nums[i] <= base): i = i + 1 nums[j] = nums[i] # 做完第一轮比较之后,列表被分成了两个半区,并且i=j,此时找到基准值 nums[i] = base # 递归前后半区 # print(base, myList) quick_sort(nums, st, i - 1) quick_sort(nums, j + 1, et) nums = [1,3,2,6,4,7,5] quick_sort(nums,0,6) print(nums)
8266e8603f0e2123137e0dadaf27ee36bafc4ac4
zoulala/exercise
/thoth-test/mongodb_test.py
7,399
3.53125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- from pymongo import MongoClient # 连接mongodb # ------------------------------ conn = MongoClient('localhost', 27017) db = conn.mydb #连接mydb数据库,没有则自动创建 my_set = db.test_set # 使用test_set集合,没有则自动创建 # 插入数据(insert插入一个列表多条数据不用遍历,效率高, save需要遍历列表,一个个插入) # ------------------------------ my_set.insert({"name":"zhangsan","age":18}) #或 my_set.save({"name":"zhangsan","age":18}) #添加多条数据到集合中 users=[{"name":"zhangsan","age":18},{"name":"lisi","age":20}] my_set.insert(users) #或 for w in users: my_set.save(w) # 查询数据库 # ------------------------------ # 查询全部 for i in my_set.find(): print(i) #查询name=zhangsan的 for i in my_set.find({"name":"zhangsan"}): print(i) print(my_set.find_one({"name":"zhangsan"})) # 更新数据 # ------------------------------ my_set.update({"name":"zhangsan"},{'$set':{"age":20}}, { 'upsert': True, #如果不存在update的记录,是否插入 'multi': False, #可选,mongodb 默认是false,只更新找到的第一条记录 'writeConcern': True #可选,抛出异常的级别。 } ) # 删除数据 # ------------------------------ #删除name=lisi的全部记录 my_set.remove({'name': 'zhangsan'}) #删除name=lisi的某个id的记录 id = my_set.find_one({"name":"zhangsan"})["_id"] my_set.remove(id) #删除集合里的所有记录 db.users.remove() # mongodb的条件操作符 # ------------------------------ # (>) 大于 - $gt # (<) 小于 - $lt # (>=) 大于等于 - $gte # (<= ) 小于等于 - $lte #例:查询集合中age大于25的所有记录 for i in my_set.find({"age":{"$gt":25}}): print(i) # 排序 \在MongoDB中使用sort()方法对数据进行排序,sort()方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序,-1为降序。 # ------------------------------ for i in my_set.find().sort([("age",1)]): print(i) # limit和skip # ------------------------------ #limit()方法用来读取指定数量的数据 #skip()方法用来跳过指定数量的数据 #下面表示跳过两条数据后读取6条 for i in my_set.find().skip(2).limit(6): print(i) # in # ------------------------------ #找出age是20、30、35的数据 for i in my_set.find({"age":{"$in":(20,30,35)}}): print(i) # or # ------------------------------ #找出age是20或35的记录 for i in my_set.find({"$or":[{"age":20},{"age":35}]}): print(i) #all # ------------------------------ # 查看是否包含全部条件 dic = {"name":"lisi","age":18,"li":[1,2,3]} dic2 = {"name":"zhangsan","age":18,"li":[1,2,3,4,5,6]} my_set.insert(dic) my_set.insert(dic2) for i in my_set.find({'li':{'$all':[1,2,3,4]}}): print(i) #输出:{'_id': ObjectId('58c503b94fc9d44624f7b108'), 'name': 'zhangsan', 'age': 18, 'li': [1, 2, 3, 4, 5, 6]} #push/pushAll # ------------------------------ my_set.update({'name':"lisi"}, {'$push':{'li':4}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'li': [1, 2, 3, 4], '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi'} my_set.update({'name':"lisi"}, {'$pushAll':{'li':[4,5]}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'li': [1, 2, 3, 4, 4, 5], 'name': 'lisi', 'age': 18, '_id': ObjectId('58c50d784fc9d44ad8f2e803')} # pop/pull/pullAll # ------------------------------ # pop # 移除最后一个元素(-1为移除第一个) my_set.update({'name':"lisi"}, {'$pop':{'li':1}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi', 'li': [1, 2, 3, 4, 4]} # pull (按值移除) # 移除3 my_set.update({'name':"lisi"}, {'$pull':{'li':3}}) #pullAll (移除全部符合条件的) my_set.update({'name':"lisi"}, {'$pullAll':{'li':[1,2,3]}}) for i in my_set.find({'name':"lisi"}): print(i) #输出:{'name': 'lisi', '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'li': [4, 4], 'age': 18} # 多级路径元素操作 # ------------------------------ dic = {"name":"zhangsan", "age":18, "contact" : { "email" : "1234567@qq.com", "iphone" : "11223344"} } my_set.insert(dic) #多级目录用. 连接 for i in my_set.find({"contact.iphone":"11223344"}): print(i) #输出:{'name': 'zhangsan', '_id': ObjectId('58c4f99c4fc9d42e0022c3b6'), 'age': 18, 'contact': {'email': '1234567@qq.com', 'iphone': '11223344'}} result = my_set.find_one({"contact.iphone":"11223344"}) print(result["contact"]["email"]) #输出:1234567@qq.com #多级路径下修改操作 result = my_set.update({"contact.iphone":"11223344"},{"$set":{"contact.email":"9999999@qq.com"}}) result1 = my_set.find_one({"contact.iphone":"11223344"}) print(result1["contact"]["email"]) #输出:9999999@qq.com # 还可以对数组用索引操作 dic = {"name":"lisi", "age":18, "contact" : [ { "email" : "111111@qq.com", "iphone" : "111"}, { "email" : "222222@qq.com", "iphone" : "222"} ]} my_set.insert(dic) #查询 result1 = my_set.find_one({"contact.1.iphone":"222"}) print(result1) #输出:{'age': 18, '_id': ObjectId('58c4ff574fc9d43844423db2'), 'name': 'lisi', 'contact': [{'iphone': '111', 'email': '111111@qq.com'}, {'iphone': '222', 'email': '222222@qq.com'}]} #修改 result = my_set.update({"contact.1.iphone":"222"},{"$set":{"contact.1.email":"222222@qq.com"}}) print(result1["contact"][1]["email"]) #输出:222222@qq.com # 索引 #--------------------------------- my_set.ensureIndex({'age':1}) # 在age字段上构建索引(B-tree),,, my_set.find({'age':23}) # 通过age字段查找速度将会大大提高 my_set.getIndexes() # 查看索引 my_set.dropIndex({'age':1}) # 删除索引 # demo #==================================================================================== #!/usr/bin/env python # -*- coding:utf-8 -*- from pymongo import MongoClient settings = { "ip":'192.168.0.113', #ip "port":27017, #端口 "db_name" : "mydb", #数据库名字 "set_name" : "test_set" #集合名字 } class MyMongoDB(object): def __init__(self): try: self.conn = MongoClient(settings["ip"], settings["port"]) except Exception as e: print(e) self.db = self.conn[settings["db_name"]] self.my_set = self.db[settings["set_name"]] def insert(self,dic): print("inser...") self.my_set.insert(dic) def update(self,dic,newdic): print("update...") self.my_set.update(dic,newdic) def delete(self,dic): print("delete...") self.my_set.remove(dic) def dbfind(self,dic): print("find...") data = self.my_set.find(dic) for result in data: print(result["name"],result["age"]) def main(): dic={"name":"zhangsan","age":18} mongo = MyMongoDB() mongo.insert(dic) mongo.dbfind({"name":"zhangsan"}) mongo.update({"name":"zhangsan"},{"$set":{"age":"25"}}) mongo.dbfind({"name":"zhangsan"}) mongo.delete({"name":"zhangsan"}) mongo.dbfind({"name":"zhangsan"}) if __name__ == "__main__": main()
ad820701830b1218dae30ec6f8168979064f2da9
zoulala/exercise
/others/a_stock_simulate.py
2,878
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # # ***************************************************** # # file: a_stock_simulate.py # author: zoulingwei@zuoshouyisheng.com # date: 2020-04-16 # brief: 看了一个操盘策略,用公式进行模拟。https://www.toutiao.com/i6815418938378158606 # # cmd>e.g: # ***************************************************** import random money = 100000. # 总价 p_num = 5. loss_k = 0.1 # 止损率 add_k = 0.2 # 止赢率 prob = 1./3 # 股票上涨概率(止赢概率) 该参数完全体现个人水平,影响最终结果走势 profit = 0. # 每一步利润 inps = 20000. # 初始入金 a_part = money/p_num # 每操作单元 def make_a_deal(inps,money,max_step=10): '''进行一笔交易 inps:入仓额 money:手上总额 max_step:最大交易次数 ''' print(max_step,inps, money) money -= inps # 入仓 outs = 0 # 交易终止条件 if money<0: return outs if max_step<1: return outs # 开始交易 max_step -= 1 # 交易次数减少一次 rd = random.random() # 0~1随机数 if rd < prob: profit = add_k*inps # 止赢 else: profit = -loss_k*inps # 止损 outs = inps+profit # 出仓 money += outs if outs > inps: inps += a_part # 止赢就加大一码入仓 if inps>money: # 入仓额度>总价,则不加码 inps -= a_part outs = make_a_deal(inps, money,max_step) # 继续交易 else: inps -= a_part # 止损就加减一码入仓 if inps<a_part: # 入仓额度最少为一码 inps = a_part outs = make_a_deal(inps, money,max_step) # 继续交易 return outs def make_a_deal2(inps,money,target=200000,step=0): '''进行一笔交易 inps:入仓额 money:手上总额 target:目标额 step:交易次数 ''' print('交易%s次,入仓%s,总额%s'%(step,inps, money)) # 交易终止条件 if money<0 or money>target: return 0 # 开始交易 money -= inps # 入仓 step += 1 # 交易次数减少一次 rd = random.random() # 0~1随机数 if rd < prob: profit = add_k*inps # 止赢 else: profit = -loss_k*inps # 止损 outs = inps+profit # 出仓 money += outs if outs > inps: inps += a_part # 止赢就加大一码入仓 if inps>money: # 入仓额度>总价,则不加码 inps -= a_part outs = make_a_deal2(inps, money,target,step=step) # 继续交易 else: inps -= a_part # 止损就加减一码入仓 if inps<a_part: # 入仓额度最少为一码 inps = a_part outs = make_a_deal2(inps, money,target,step=step) # 继续交易 return outs # make_a_deal(inps,money,max_step=100) make_a_deal2(inps,money,200000,0)
cf7b11055a31306a15a1485840d9c409020cb356
PromasterGuru/Hackerrank-Solutions
/Capitalize!/main.py
171
3.625
4
# Complete the solve function below. def solve(s): return ' '.join([word.capitalize() for word in s.split(' ')]) if __name__ == '__main__': print(solve(input()))
660e41b5a8d6da7ff132d7fd1c91ad29943cd1a0
PromasterGuru/Hackerrank-Solutions
/Alphabet Rangoli/main.py
321
3.53125
4
import string def print_rangoli(size): alphabets = list(string.ascii_lowercase)[:size] for i in range(size-1, -size, -1): res = '-'.join(alphabets[size-1:abs(i):-1] + alphabets[abs(i):size]) print(res.center(4*size-1, '-')) if __name__ == '__main__': n = int(input()) print_rangoli(n)
11649567de31fd5543c30fd786c222bb1438321a
PromasterGuru/Hackerrank-Solutions
/Electronics Shop/main.py
779
3.78125
4
from itertools import product def getMoneySpent(keyboards, drives, b): result = -1 for ar in list(product(*(keyboards, drives))): if sum(ar) <= b and sum(ar) > result: result = sum(ar) return result if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') bnm = input().split() b = int(bnm[0]) n = int(bnm[1]) m = int(bnm[2]) keyboards = list(map(int, input().rstrip().split())) drives = list(map(int, input().rstrip().split())) # # The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items # moneySpent = getMoneySpent(keyboards, drives, b) print(moneySpent) # fptr.write(str(moneySpent) + '\n') # fptr.close()
d16a3efed1b1437a0e4ed382af134e3510b5aac5
iuryferreira/python-data-structures
/data_structures/open_address_hashtable.py
2,174
3.71875
4
from data_structures.hashtable import HashTable from data_structures.utils.data_structures_visualization import DataStructuresVisualization class OpenAddressHashTable(HashTable): """ This class inherits from HashTable, using open address collision treatment. """ def __init__(self, size): super().__init__(size) def hash_func(self, value, sequence): return (super().hash_func(value) + (sequence - 2)) % (self.size) def __repr__(self): return "\nOpen Address HashTable:\n{0}".format(DataStructuresVisualization.open_address_hash_table(self.table)) def insert(self, value): sequence = 0 while sequence != self.size: position = self.hash_func(value, sequence) if self.table[position] is None: self.table[position] = value return position else: sequence += 1 return "All fields have already been filled." def search(self, value): sequence = 0 while sequence != self.size: position = self.hash_func(value, sequence) if self.table[position] == value: return position else: sequence += 1 return None def remove(self, value): position = self.search(value) if position is None: return "All fields are empty." else: self.table[position] = None class OpenAddressHashTableLinearProbing(OpenAddressHashTable): """ This class inherits from OpenAddressHashTable, and implements the linear hash function. """ def __init__(self, size): super().__init__(size) class OpenAddressHashTableQuadraticProbing(OpenAddressHashTable): """ This class inherits from OpenAddressHashTable, and implements the quradratic hash function. """ def __init__(self, size, c1, c2): self.c1 = c1 self.c2 = c2 super().__init__(size) def hash_func(self, value, sequence): return (super().hash_func(value) - 1 + self.c1 * (sequence-1) + (self.c2 * (sequence-1)) ^ 2) % (self.size)
5a1edee22fe63654a519259ee3b4ceaa2f4a345a
NaokiEto/CS171
/hw3/raster.py
4,108
4.3125
4
# Must be called before any drawing occurs. Initializes window variables for # proper integer pixel coordinates. def initDraw(xMin, xMax, yMin, yMax, xr, yr): global windowXMin, windowXMax, windowYMin, windowYMax, xRes, yRes windowXMin = xMin windowXMax = xMax windowYMin = yMin windowYMax = yMax xRes = xr yRes = yr # Helper function to convert a real x position into an integer pixel coord. def getPixelX(x): return int((x - windowXMin) / (windowXMax - windowXMin) * xRes) # Helper function to convert a real y position into an integer pixel coord. def getPixelY(y): return int((y - windowYMin) / (windowYMax - windowYMin) * yRes) # Helper function f as defined in the course text. Not sure exactly what # it means, on a conceptual level. def f(vert0, vert1, x, y): x0 = vert0[0] y0 = vert0[1] x1 = vert1[0] y1 = vert1[1] return float((y0 - y1) * x + (x1 - x0) * y + x0 * y1 - x1 * y0) # The meat of the package. Takes three vertices in arbitrary order, with each # vertex consisting of an x and y value in the first two data positions, and # any arbitrary amount of extra data, and calls the passed in function on # every resulting pixel, with all data values magically interpolated. # The function, drawPixel, should have the form # drawPixel(x, y, data) # where x and y are integer pixel coordinates, and data is the interpolated # data in the form of a tuple. # verts should be a (3-element) list of tuples, the first 2 elements in each # tuple being X and Y, and the remainder whatever other data you want # interpolated such as normal coordinates or rgb values def raster(verts, drawPixel, shadingType, material, lights, campos, matrix): xMin = xRes + 1 yMin = yRes + 1 xMax = yMax = -1 coords = [ (getPixelX(vert[0]), getPixelY(vert[1])) for vert in verts ] coordsX = verts[0] coordsY = verts[1] coordsZ = verts[2] lenX = len(coordsX) # find the bounding box for c in coords: if c[0] < xMin: xMin = c[0] if c[1] < yMin: yMin = c[1] if c[0] > xMax: xMax = c[0] if c[1] > yMax: yMax = c[1] print "the yMin is: ", yMin print "the yMax is: ", yMax print "the xMin is: ", xMin # normalizing values for the barycentric coordinates # not sure exactly what's going on here, so read the textbook fAlpha = f(coords[1], coords[2], coords[0][0], coords[0][1]) fBeta = f(coords[2], coords[0], coords[1][0], coords[1][1]) fGamma = f(coords[0], coords[1], coords[2][0], coords[2][1]) if abs(fAlpha) < .0001 or abs(fBeta) < .0001 or abs(fGamma) < .0001: return print "checkpoint" # go over every pixel in the bounding box for y in range(max(yMin, 0), min(yMax, yRes)): for x in range(max(xMin, 0), min(xMax, xRes)): # calculate the pixel's barycentric coordinates alpha = f(coords[1], coords[2], x, y) / fAlpha beta = f(coords[2], coords[0], x, y) / fBeta gamma = f(coords[0], coords[1], x, y) / fGamma #print "the alpha, beta and gamma are: ", alpha, ", ", beta, ", ", gamma # if the coordinates are positive, do the next check if alpha >= 0 and beta >= 0 and gamma >= 0: # interpolate the data for either gouraud or phong if (shadingType != 0): data = [0]*lenX for i in range(lenX): data[i] = alpha * coordsX[i] + beta * coordsY[i] + gamma * coordsZ[i] # interpolate the data for flat elif (shadingType == 0): data = [0]*6 for i in range(3): data[i] = alpha * coordsX[i] + beta * coordsY[i] + gamma * coordsZ[i] for i in range(3, 6): data[i] = coordsX[i] # and finally, draw the pixel if data[2] >= -1: drawPixel(x, y, data, shadingType, material, lights, campos, windowXMin, windowXMax, windowYMin, windowYMax, matrix)
91cd0209f59bcbdb4c4324ff8bcfaa0cc6b782a4
exload/CS50-2019
/pset6/bleep/bleep.py
889
3.765625
4
from cs50 import get_string from sys import argv, exit def main(): if len(argv) != 2: print("Usage: python bleep.py dictionary") exit(1) # Prompt the user to provide a message print("What message would you like to censor?") text = get_string() # Open file dict_file = open(argv[1], 'r') dictionary = set() for line in dict_file: dictionary.add(line.strip()) dict_file.close() # print("------------") # print(dictionary) # print("------------") # Entered text modification splited_text = text.split(' ') for word in splited_text: # print(word) # print("++++++") if word.lower() in dictionary: x = len(word) print("*" * x, end="") else: print(word, end="") print(" ", end="") print() if __name__ == "__main__": main()
bc49cd0006cb106bfa069970a3e37d84ec093b2f
ubco-mds-2018-labs/data533_lab2_vaghul_jiachen
/xuebadb/dfanalysis/cleanup.py
419
3.5
4
import numpy as np import pandas as pd import missingno import matplotlib.pyplot as plt def show_nulls(input_df): if(not isinstance(input_df, pd.DataFrame)): print("Can't cleanup an object that is not a dataframe") return None input_df.replace("None", np.nan, inplace = True) # Matrix that displays data sparsity to see missing/Null values missingno.matrix(input_df) plt.show()
11cc2c6083d06171c1e2db5e0c2c1b1502e3289a
lucasadelino/Learning-Python
/Automate the Boring Stuff Practice Projects/Chapter 7/regexstrip.py
218
4.0625
4
# A regex version of the strip() method import re def regexstrip(some_string, arg = '\s'): strip = re.compile('^' + arg + '*|' + arg + '*$') return strip.sub('', some_string) print(regexstrip('AAAbruceAAA'))
f3a85aff075359dfbbeedde83d6727735d3b7e29
BSkullll/DSA
/Stacks and Queues/balanced_parenthesis.py
393
3.796875
4
def balanced_parenthesis(data): if len(data) % 2 != 0: return False opening = {'{','(','['} datas = { ('(',')'), ('[',']'), ('{','}') } stack = [] for e in data: if e in opening: stack.append(e) else: if len(stack) == 0: return False ch = stack.pop() if (ch, e) not in datas: return False return len(stack) == 0 print(balanced_parenthesis('[]'))
51eef942ba2281b2f49dc1a8bc7ec8ee8990184f
BSkullll/DSA
/Array Question/anagram_by_sorted_approach.py
341
3.703125
4
def func(a, b): a = a.replace(' ', '').lower() b = b.replace(' ', '').lower() result = None if len(a) != len(b): return False else: a = sorted(a) b = sorted(b) for i in range(len(a)): if a[i] == b[i]: result = True continue else: result = False break return result print(func("abcc","abcd"))
4eb482a93d598a005ef04360363310916c619eeb
PdxCodeGuild/class_mudpuppy
/Assignments/Racheal/python/Lab2.py
713
4.0625
4
# lab2 """ instructions Search the interwebs for an example Mad Lib Create a new file and save it as madlib.py Ask the user for each word you'll put in your Mad Lib Use an fstring to put each word into the Mad Lib """ """ The wheels on the bus go round and round Round and round Round and round The wheels on the bus go round and round All through the town """ adjective = input("Enter an adjective: ") noun = input("Enter a noun: ") verb = input("Enter a verb: ") # There was a farmer who had {noun}, # And Bingo was his name-o. # B-I-N-G-O # And Bingo was his name-o. # There was a farmer who had a dog, # And Bingo was his name-o. print(f"There was a farmer who {verb}, {adjective},And {noun} was his name-o.")
6af4513c000f0bf8ae449e915e146515187fed08
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab07-rock_paper_scissors.py
1,327
4.25
4
#lab07-rockpaperscissors.py import random user_input = 'yes' while user_input == 'yes': print('Let\'s play rock-paper-scissors!') print('The computer will ask the user for their choice of rock, paper or scissors, and then the computer will randomly make a selection.') #computer tell user how the game will work user = input ('rock, paper or scissors:') choices = ('rock', 'paper', 'scissors') #the user will have to choose one of these options computer = random.choice(choices) #the computer will select a random choice if user == computer: print('It\'s a tie') elif user == 'rock': if computer == 'paper': print('Computer wins, the computer chose paper') if computer =='scissors': print('Computer loses, the computer chose scissors' ) elif user == 'paper': if computer =='scissors': print('Computer wins, the computer chose scissors' ) if computer == 'rock': print('Computer loses, the computer chose rock') elif user == 'rock': if computer =='scissors': print('Computer loses, the computer chose scissors' ) if computer == 'rock': print('Computer wins, the computer chose rock') user = input('Would you like to play again?')
f5bac030adc72702c31328a37f3c483b445bd25c
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/repl-example.py
227
3.8125
4
# Running state running = True # While it's running # LOOP while running: # READ value = input("Enter anything or done to exit: ") # EVALUATE if value == "done": running = False break # PRINT print(value)
10ad2eef9da72722ff2354360db06a58c6ff05af
PdxCodeGuild/class_mudpuppy
/3 JavaScript/js_py/rot13/rot13.py
334
3.5
4
import string unencoded = "helloiliketocode" unencoded = "uryybvyvxrgbpbqr" num_list = [] for letter in unencoded: num = string.ascii_lowercase.index(letter) num_list.append(num) encoded = '' for num in num_list: index = (num + 13) % len(string.ascii_lowercase) encoded += string.ascii_lowercase[index] print(encoded)
0ee076081c0c54572abae5c4ab18625918c643f8
PdxCodeGuild/class_mudpuppy
/Assignments/Manny/Python/lab23.py
2,197
3.859375
4
with open('contacts.csv', 'r') as file: lines = file.read().split('\n') list_of_lines = [] for line in lines: line = (line.split(",")) # makes our contact file nice and neat list_of_lines.append(line) # headers = list_of_lines[0] # other_lines = list_of_lines[1:] # 1: starts at the second item on the list not the 0 contacts = [] for line in other_lines: contact_dict = {} for index, item in enumerate(line): contact_dict[headers[index]] = item contacts.append(contact_dict) print(contacts) while True: user_choice = input("Choose (c)reate, (r)etrieve, (u)pdate, (d)elete, (q)uit: ") if 'r' == user_choice: name_choice = input("Enter the name you chose: ") found = False for contact in contacts: if contact["name"] == name_choice: # will show name choice if they are in contacts print(contact) found = True if found == False: print(f"{name_choice} is not in contacts.") elif 'q' == user_choice: break if 'u' == user_choice: name_choice = input("Enter the name you chose: ") for contact in contacts: if contact["name"] == name_choice: # print the contact name if the contact name is the same as the name choice key = input("name? food? hobby? ") value = input("What fo you want to change? ") contact[key] = value # the end updated if 'd' == user_choice: name_choice = input("Which name would you like to delete? ") for contact in contacts: if contact["name"] == name_choice: contacts.remove(contact) print(f"You deleted {name_choice}") if 'c' == user_choice: name_choice = input("Which name would you like to add? ") food_choice = input(f"What is {name_choice} favorite food?? ") hobby_choice = input(f"What is {name choice} favorite hobby? ") contact_dict = { 'name': name_choice, 'food': food_choice, 'hobby': hobby_choice, } contacts.append(contact_dict) print(contacts)
4885b4212545ee9f635fed82f045478503adc865
PdxCodeGuild/class_mudpuppy
/Reviewed/Brea/python/lab17/lab17_version2_checked.py
1,009
4.125
4
#Lab 17, Version 2 Anagram def split(word): return list(word) # good practice, but generally don't make a function # that calls a single function, especially one that's already well-known like list() def remove_spaces(str): new_str = '' for i in range(len(str)): if(str[i] != ' '): new_str += str[i] return new_str # I like that you did this the hard way (you learn more that way) # but you could just do str.replace('', ' ') # Also, don't use the parameter str, that overwrites a builtin function user_input1 = input("What is the first input you'd like to compare? : ") user_input1 = user_input1.lower() list_inp1 = split(remove_spaces(user_input1)) user_input2 = input("What is the second input to compare? : ") user_input2 = user_input2.lower() list_inp2 = split(remove_spaces(user_input2)) list_inp1.sort() list_inp2.sort() if list_inp1 == list_inp2: print("These two inputs are anagrams!") else: print("These two inputs are not anagrams!") # Nice!
37675d15d25aa51006258ff94564fbc04ff6e685
PdxCodeGuild/class_mudpuppy
/1 Python/class_demos/function-lecture/add-number-words-ultimate-solution.py
986
4.125
4
import operator def get_valid_input(): valid_input = False while not valid_input: num1 = input("Spell out a number with letters: ") if num1 in number_dict: return num1 else: print(f"{num1} is not supported. Try entering a different number: ") def reduce_list_to_value(fn, starting_value, values): accumulator = starting_value for val in values: accumulator = fn(accumulator, val) return accumulator def square_and_add(x,y): return x + y**2 number_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} numbers = [] for _ in range(4): inp = get_valid_input() numbers.append(number_dict[inp]) number_sum = reduce_list_to_value(operator.add, 0, numbers) product = reduce_list_to_value(operator.mul, 1, numbers) sum_squares = reduce_list_to_value(square_and_add, 0, numbers) print(f"The sum is {number_sum}, the product is {product}, the sum of squares is {sum_squares}")
096d0dc863ab7739debf8e8000545f4e7f7f3cda
PdxCodeGuild/class_mudpuppy
/Assignments/Devan/1 Python/labs/lab11-simple_calculator.py
1,098
4.21875
4
# Lab 11: Simple Calculator Version 3 def get_operator(op): return operators[op] def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y def eval(fn, n1, n2): return fn(n1, n2) operators = {'+': add, '-': subtract, '*': multiply, '/': divide} while True: try: operator = input('Enter your operator (+, -, *, /) or done: ') if operator == 'done': print('\nThanks for using the calculator.') break if operator not in operators: print('Not a vaild operator...') else: # todo: validate user entered number n1 = input('Enter the first number: ') if n1 is not int: print('Enter a vaild number. ') n2 = int(input('Enter the second number: ')) if n2 is not int: print('Enter a valid number. ') print(eval(get_operator(operator), int(n1), int(n2))) except KeyboardInterrupt: print('\nThank You') break
541761c20e5cdc6eb60fb7316866f139754f0841
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/wacky_functions.py
252
3.59375
4
wacky_functions.py def noisey_add(num1, num2): print(f"ADDING {num1} AND {num2}!!!!:D") return num1 + num2 def bad_add (num1, num2): print(num1 + num2) print(noisey_add(1, 3) + (-2 + 5)) # (1 + 3) + (-2 + 5) # 4 + (-2 + 5) # 4 + 3 # 7
50962379cef04f28b24854aeeaccc11e9f673a9b
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/labs06.py
1,170
4.21875
4
# Lab 6: Password Generator """ Let's generate a password of length `n` using a `while` loop and `random.choice`, this will be a string of random characters. """ import random import string # string._file_ = random.choice('string.ascii_letters + string.punctuation + string.digits') # #print((string._file_)) # pass_num = input ("How many characters? ") # pass_num = int(pass_num) # out_num = '' # for piece in range(pass_num): # out_num = out_num + random.choice(string.ascii_letters + string.punctuation + string.digits) # print(out_num) string._file_ = random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation) pass_low = input("How many lowercase? ") pass_low = int(pass_low) pass_high = input("How many uppercase? ") pass_high = int(pass_high) pass_dig = input("How many numbers? ") pass_dig = int(pass_dig) out_num = '' for piece in range(pass_low): out_num = out_num + random.choice(string.ascii_lowercase) for piece in range(pass_high): out_num = out_num + random.choice(string.ascii_uppercase) for piece in range(pass_dig): out_num = out_num + random.choice(string.digits) print(out_num)
b88a20e027f7711bff9a5b8a9d0658d3b8a638cb
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Python Labs/Lab25_version2.py
1,603
3.765625
4
#Lab 25, version 2, April 17th, 2020 class Atm: def __init__(account, balance = 0): account.negative = False account.balance = balance account.interest_rate = .01 account.transactions = [] def check_balance(account): #returns the account balance print(f"Your account currently has ${account.balance}") return account.balance def deposit(account, amount): #deposits the given amount in the account account.balance += amount account.transactions.append(f"User has deposited ${amount}, for a new balance of ${account.balance}") return account.balance def check_withdrawal(account, amount): if (account.balance - amount) >= 0: print("You're good.") return False elif (account.balance - amount) < 0: print("Careful, your withdrawal will put in in the red.") return True def withdraw(account, amount): account.balance -= amount account.transactions.append(f"User has withdrawn ${amount}, for a new balance of ${account.balance}") return account.balance def calc_interest(account): interest_calc = account.balance * account.interest_rate print(f"Your account has earned ${interest_calc} in interest.") return interest_calc def print_transactions(account): for item in account.transactions: print(item, sep='\n') return account.transactions Brea = Atm() Brea.deposit(100) Brea.withdraw(6) Brea.deposit(10000) Brea.print_transactions()
042467884095a0b0e7a52c67df4cae6033eb4f88
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab09-written_addition.py
1,444
3.90625
4
#lab09-written_addition.py units = { "m": 1, "ft": 0.3048, "mi": 1609.34, "km": 1000, "yd": 0.9144, "in": 0.0254 } user_unit = input("What unit are you using?") user_number = input("Enter the number of units.") user_number = int(user_number) if user_unit == "m": solution = units["m"] * user_number print(solution) elif user_unit == "ft": solution = units["ft"] * user_number print(solution) elif user_unit == "mi": solution = units["mi"] * user_number print(solution) elif user_unit == "km": solution = units["km"] * user_number print(solution) elif user_unit == "yd": solution = units["yd"] * user_number print(solution) else: solution = units["in"] * user_number print(solution) ### (user_unit)int = number_dict[user_unit] ### # written_addition.py num1 = input("Spell out a number with letters: ") num2 = input("Spell out a number with letters: ") number_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # num1_int = number_dict[num1] # num2_int = number_dict[num2] num1_int = 0 num2_int = 0 if num1 == 'one': num1_int = number_dict['one'] elif num1 == 'two': num1_int = number_dict['two'] elif ... number_sum = num1_int + num2_int print(f"The sum is {number_sum}") # user_ft = int(input("How many feet do you want to turn into meters? ")) # m = 0.3048 # solution = m * user_ft # print(f"the distance in meters is: {solution}")
9686df41204e02ef1e69ce6eda1c5cc539826484
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab03-grading.py
491
3.984375
4
#lab03-grading.py user_grade = int(input("What is your grade? ")) if user_grade > 100: print("Good job, you got an A+!") elif user_grade <= 100 and user_grade >= 90: print("Good job, you got an A.") elif user_grade <= 90 and user_grade >= 80: print("Not bad, you got an B.") elif user_grade <= 80 and user_grade >= 70: print("That's average, you got an C.") elif user_grade <= 70 and user_grade >= 60: print("Not very good, you got an D.") else: print("You failed!")
efb3cc272635bad1eac58a5a54352b76d8aaf03b
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test3.26.20.py
935
3.953125
4
# import random # eye = random.choice(';:') # nose = random.choice('->') # mouth = random.choice(')]') # output = eye + nose + mouth # print(output) # def make_face(eye, nose, mouth): # return eye + nose + mouth # # def make_eye(): # # return # # def make_nose(): # # return # # def make_mouth(): # # return # #print(make_face(make_eye(), make_nose(), make_mouth())) # #print(make_face(';', '>', ']')) #TRYING TO GET THE COMPUTER TO MAKE AN OPTIMAL GUESS THROUGH AVERAGES AND FEEDBACK def average(x, y): return round((x + y) / 2) def search(lower, upper, target, guess): print(f'You guessed {guess}') if guess == target: print('Correct!') elif guess < target: print('Too low!') search(guess, upper, target, average(guess, upper)) elif guess > target: print('Too high!') search(lower, guess, target, average(lower, guess)) search(1, 100, 1, 2)
29ea796e4e8cf9ed5da93f437c836b23eba80c34
PdxCodeGuild/class_mudpuppy
/1 Python/examples/book_recommender_v2.py
2,420
3.625
4
import requests import random from bs4 import BeautifulSoup # Create your own error called InvalidGenreError class InvalidGenreError(Exception): pass def get_books(genre='horror'): # Get html data from a website response = requests.get(f"https://www.goodreads.com/genres/new_releases/{genre}") # Turn it into something python can work with html = BeautifulSoup(response.text, 'html.parser') # Find all div elements on a page divs = html.find_all('div') # Found books books = [] # Loop over them for div in divs: classes = div.get('class') # If they have a class called 'coverWrapper'... if classes and 'coverWrapper' in classes: # Find the link and title of the book title = div.find('img')['alt'] link = div.find('a')['href'] # Add to our books list book = (title, link) books.append(book) # If we find no books, raise an error if len(books) == 0: raise InvalidGenreError("Invalid genre!") return books def get_suggested_books(books, count=3): # Setup our suggest books list suggested_books = [] # Start our books_found counter at 0 books_found = 0 # Make sure we don't loop forever count = min(len(books), count) # While we haven't found 3 books... while books_found < count: # Randomly pick a book suggested_book = random.choice(books) # If it hasn't already been picked... if suggested_book not in suggested_books: # Add it to our list suggested_books.append(suggested_book) # Increase the amount of books we've found books_found += 1 return suggested_books def print_suggestions(suggested_books): # Print our suggested books in a nice way print(f"We suggest these {len(suggested_books)} book(s):") print("-----------------------\n") for suggested_book in suggested_books: # Tuple unpack our title and link title, link = suggested_book print(title) print(f"https://www.goodreads.com{link}\n") # Default setup! # books = get_books() # suggested_books = get_suggested_books(books) # print_suggestions(suggested_books) # Take user input genre = input("What genre do you want?: ") count = int(input("How many do you want?: ")) # Try and get books, and catch an invalid genre try: books = get_books(genre) suggested_books = get_suggested_books(books, count) print_suggestions(suggested_books) except InvalidGenreError as e: print(e)
ba0752e6e9750a6b832ba939613811df382ee644
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/lab12-v1.py
318
4.0625
4
import random computer_guess = random.randint(1, 10) won = False print(computer_guess) for i in range(10): guess = float(input("Guess a number between 1-10: ")) if guess == computer_guess: won = True break print(f"Guess again, you meat bag! You have {9 - i} tries left...") if won: print("You won!")
361ac4d33c0fd3855b67ebb14103f6a2db052c0f
PdxCodeGuild/class_mudpuppy
/1 Python/hints/lab_23/list_to_dict.py
571
3.609375
4
# list_to_dict.py start_list = [['a', 'b', 'c'], ['d', 'e', 'f']] output = [] for one_list in start_list: # one_list = ['a', 'b', 'c'] print(one_list) one_dict = {} for index in [0, 1, 2]:#range(len(one_list)): #index = 0 #one_list[index] = 'a' one_dict[index] = one_list[index] # one_dict = {0: 'a', 1: 'b', 2: 'c'} output.append(one_dict) print(output) # [{0: 'a', 1: 'b', 2: 'c'}, {0: 'd', 1: 'e', 2: 'f'}] ''' endgoal = [ {0: 'a', 1: 'b', 2: 'c'}, {0: 'd', 1: 'e', 2: 'f'} ] print(endgoal) '''
d67ad475fcc9930444dfc9dba97ea0d380a8ce72
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/function.py
3,960
4.75
5
'''def my_function(fname): #fname is the argument, functions can have as many arguments as possible. just separate with commmas. #When the function is called, we pass along a first name. print(fname + " Refsnes")#used inside the function to print the full name: #shortened to args in Python documents #parameter is a variable listed inside the parentheses in the function definition. #argument is the value that are sent to the function when it is called my_function("Emil") = prints Emil Refsnes my_function("Tobias") = prints Tobias Refsnes my_function("Linus") = prints Linus Refsnes ----------------------------------------------------- if your function expects 2 arguments, you must call the function with 2 arguments, not more and not less. ----------------------------------------------------- ''' '''ARBITRARY ARGUMENTS, *args: if you don't know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly. ''' ''' enter = int(input("What's your favorite numnber? (0-2) : ")) def my_function(*kids): print("Your youngest child will be named" + kids[2]) #Depending on which name I want I can choose from the index my_function(" Emil", " Tobias", " Linus")#if we change 2 to enter, it still produces linus ''' #------------------------------------------------------------------ '''KEYWORD ARGUMENTs: We can also send arguments with the key = value syntax. This way the order of the arguments does not matter. ''' '''def my_function(child3, child2, child1): print("The youngest child is" + child3) my_function(child1 = " Emil", child2 = " Tobias", child3 = " Linus") ''' #---------------------------------------------------------------------- '''ARBITRARY KEYWORD ARGUMENTS (keyword arguments **kwargs): If you dont know how many keyword arguemtns will be passed into your function, add two asterisk: ** before the parameter name in the function definition. This way the function will receive a dictionary of argurments, and can access the items accordingly:''' '''def my_function(**kid): print("His last name is " + kid["lname"]) #If we don't put quotes, python will give us a NameError: 'lname' not defined my_function(fname = "Tobias", lname = "Refsnes")''' #----------------------------------------------------- '''DEFAULT PARAMETER VALUE: if we call the function without argument, it uses the default value: ''' ''' def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") ''' #-------------------------------------------------------------------------------- '''PASSING A LIST AS AN ARGUMENT - you can send any data types of argument to a function (string, number, list, dictionary, etc.) and it will be treated as the same data type inside the function. E.g if you send a LIST as an argument, it will still be alist when it reaches the function: ''' # def my_function(food): # for x in food: # print(x) # fruits = ["apple", "banana", "cherry"] # my_function(fruits) #apple #banana #cherry '''RETURN VALUES''' # def my_function(x): # return 5 * x # print(my_function(3)) = 15 # print(my_function(5)) = 25 # print(my_function(9)) = 45 #------------------------------------------------------------------ '''THE PASS STATEMENT''' # function definitions cannot be empty, # but if you for some reason have a function # definition with no content, put in the pass statement to avoid getting an error. def myfunction(): pass #---------------------------------------------------------------------------- Recursion means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result. BE CAREFUL WITH RECURSION - YOU CAN WRITE A FUNCTION THAT NEVER TERMINATES, OR ONE THAT USES EXCESS AMOUNTS OF MEMORY OR PROCESSOR POWER. tri_c
2874845c72626487f96500a7aac40ba91891870e
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/lab09-v2.5.py
617
4.34375
4
# Supported unit types supported_units = ["ft", "mi", "m", "km"] # Ask the user for the unit they want unit = input("What unit do you want: ") # If an invalid unit is specified, alert the user and exit if unit not in supported_units: print("Please enter a valid unit! Options are ft, mi, m, km...") exit() # Get the amount of units amount = float(input("How many units: ")) # Check to see if the unit matches one we know if unit == "ft": print(amount * 0.3048) elif unit == "mi": print(amount * 1609.34) elif unit == "m": print(amount * 1 * 1 * 1) # Extra spicy elif unit == "km": print(amount * 1000)
94aaa7a1f356fae443a91b748d7ad8f8fe395882
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/lab10.py
330
3.8125
4
list1 = [] i = 0 while True: num1 = (input("Input your first number: ")).lower() # print(num1.isdigit()) if num1.isdigit(): num2 = int(num1) list1.append(num2) elif num1 == "done": total = (sum(list1)//len(list1)) print(f"Your average is: {total}") break
7d22fbd58d09e95c2ab94e8adb567da9c3932b36
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab18.py
439
4.125
4
import string input_string = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] #change variable name #create an empty list for index in range(1,len(input_string)-1): left_side = input_string[index-1] middle = input_string[index] right_side = input_string[index + 1] if left_side < middle and right_side < middle: print(index) elif left_side > middle and right_side > middle: print(index)
adbf42f3752456bea0736e70ac0ac4133ede4db8
PdxCodeGuild/class_mudpuppy
/Assignments/Haoua/PYTHON/lab08.py
593
3.703125
4
amount = float(input("Enter a dollar amount (0-99) : ")) ver = amount.is_integer() print(ver) if ver is False: print(amount//.25, "quarters") amount = amount%.25 print(amount//.10, "dimes") amount = amount%.10 print(amount//.05, "nickles") amount = amount%.05 print(amount//.01, "pennies") amount = amount%.01 elif ver is True: print(amount//25, "quarters") amount = amount%25 print(amount//10, "dimes") amount = amount%10 print(amount//5, "nickles") amount = amount%5 print(amount//1, "pennies") amount = amount%1