blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
dc0cf84bbf13e3a61d52613f0aa7efc09761e553
st-lee/Supervised_ML_Lab
/L2_LinearRegression/S25_PolynomialRegression/polu_reg.py
1,067
3.921875
4
import pandas as pd import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures # Assign the data to predictor and outcome variables # TODO: Load the data data = pd.read_csv('data.csv') data.head(10) X = data['Var_X'].values.reshape(-1, 1) #不可以用data[['Var_X']]會出錯, 莫名其妙!For X, make sure it is in a 2-d array of 20 rows by 1 column. y = data['Var_Y'].values #can be 1-D or 2-D # Create polynomial features # TODO: Create a PolynomialFeatures object, then fit and transform the # predictor feature poly_feat = PolynomialFeatures(4) X_poly = poly_feat.fit_transform(X) # Make and fit the polynomial regression model # TODO: Create a LinearRegression object and fit it to the polynomial predictor # features poly_model = LinearRegression().fit(X_poly, y) # Once you've completed all of the steps, select Test Run to see your model # predictions against the data, or select Submit Answer to check if the degree # of the polynomial features is the same as ours!
ee43d4053f2f6dee246092f2c1619f274f5ec136
kakshay21/ML-tensorflow
/mnistv3.py
2,480
3.53125
4
import tensorflow as tf ''' Basic idea input > weight > hidden layer 1 (activation function)>weights >hidden layer 0 (activation function) > weights>hidden layer 2 (activation function) > weights > output layer ''' from tensorflow.examples.tutorials.mnist import input_data mnist=input_data.read_data_sets("A/", one_hot=True) n_nodes_hl1=500 n_nodes_hl2=500 n_nodes_hl0=500 n_nodes_hl3=500 n_classes=10 batch_size=100 x=tf.placeholder('float',[None,784]) y=tf.placeholder('float') def neuralNetworkModel(data): hidden_1_Layer={'weights':tf.Variable(tf.random_normal([784,n_nodes_hl1])),'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_2_Layer={'weights':tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_0_Layer={'weights':tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl0])),'biases':tf.Variable(tf.random_normal([n_nodes_hl0]))} hidden_3_Layer={'weights':tf.Variable(tf.random_normal([n_nodes_hl0,n_nodes_hl3])),'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))} output_Layer={'weights':tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),'biases':tf.Variable(tf.random_normal([n_classes]))} l1=tf.add(tf.matmul(data, hidden_1_Layer['weights']),hidden_1_Layer['biases']) l1=tf.nn.relu(l1) l2=tf.add(tf.matmul(l1, hidden_2_Layer['weights']),hidden_2_Layer['biases']) l2=tf.nn.relu(l2) l0=tf.add(tf.matmul(l2,hidden_0_Layer['weights']),hidden_0_Layer['biases']) l0=tf.nn.relu(l0) l3=tf.add(tf.matmul(l0, hidden_3_Layer['weights']),hidden_3_Layer['biases']) l3=tf.nn.relu(l3) output=tf.matmul(l3, output_Layer['weights'])+output_Layer['biases'] return output def trainNeuralNetwork(x): prediction=neuralNetworkModel(x) cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction,y)) optimizer=tf.train.AdamOptimizer().minimize(cost) hm_epochs=10 with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(hm_epochs): epoch_loss=0 for _ in range(int(mnist.train.num_examples/batch_size)): epoch_x,epoch_y=mnist.train.next_batch(batch_size) _, c=sess.run([optimizer,cost],feed_dict={x: epoch_x,y: epoch_y}) epoch_loss+=c print('Epoch',epoch,'completed out of ',hm_epochs,'loss: ',epoch_loss) correct=tf.equal(tf.argmax(prediction,1),tf.argmax(y,1)) accuracy=tf.reduce_mean(tf.cast(correct,'float')) print('Accuracy: ',accuracy.eval({x:mnist.test.images,y:mnist.test.labels})) trainNeuralNetwork(x)
139f09a7d3cc976b884cff51ab1e5785189416ff
MarcieL-Bezerra/Gerenciador-de-Portaria
/fotobd.py
463
3.71875
4
import sqlite3 class Banco(): def __init__(self): self.conexao = sqlite3.connect('SQLite_Python.db') self.createTable() def createTable(self): c = self.conexao.cursor() c.execute("""create table if not exists new_employee ( nomes TEXT NOT NULL, fotos BLOB NOT NULL, resumos TEXT NOT NULL, id INTEGER PRIMARY KEY autoincrement)""") self.conexao.commit() c.close()
186de9fba51a3542a8e5c5fafe4643de6c631536
jmullen2782/projects
/practice_classes.py
576
3.859375
4
''' Created on May 13, 2019 @author: jmullen19 ''' class Car: def __init__(self,c,m=0,s=0): self.color = c self.speed = s self.mileage = m def get_color(self): return self.color def get_speed(self): return self.speed def get_milage(self): return self.mileage def main(): car1 = Car("red", 50000, 0) car2 = Car("black") car3 = Car("blue", 10) print(car1.get_color(), car1.get_speed(), car1.get_mileage()) print(car2.get_color()) main()
1ba037ec34f8012dc79a275b0ad564f1a65b42ea
NoireFedora/PizzaParlourAPI
/PizzaParlour.py
14,562
3.65625
4
import flask import json from flask import Flask, request, jsonify app = Flask("Assignment 2") # Start Code @app.route('/pizza') def welcome_pizza(): return 'Welcome to Pizza Planet!' # Object Order class Order: def __init__(self, order_id: str, pizza_list: list = None, drink_list: list = None, address: str = None, delivery: str = None): # The Id of this Order self.order_id = order_id # The list contains all Pizza in this Order self.pizza_list = pizza_list # The list contains all Drinks in this Order self.drink_list = drink_list # Address self.address = address # Delivery Method self.delivery = delivery # Total Price of this Order self.total = 0 # Whether this Order is submitted or not. If not, it is a temporary Order. self.submitted = False # Object Pizza class Pizza: def __init__(self, size: str, type: str, toppings: list): # The Size of this Pizza self.size = size # The Type of this Pizza self.type = type # The list contains all Toppings in this Pizza self.toppings = toppings # Order Id Counter order_id_counter = 0 # The list contains all Orders orders = {} # Attributes of a Pizza pizza_attr = ["Id", "Size", "Type", "Toppings"] # Load menu from menu.json with open('menu.json') as json_file: menu = json.load(json_file) # Check whether a pizza request is valid or not def isvalidpizza(pizza, file_type): """ A json file (dictionary) sample: {"Id": 1, "Size": "Small", "Type": "Neapolitan", "Toppings": ["Chicken", "Beef", "Mushrooms"]} A csv file (string) sample: "Id,Size,Type,Toppings\n1,Small,Neapolitan,[Chicken,Beef,Mushrooms]" """ if file_type == "json": if len(pizza) != 4: return False if "Id" not in pizza or "Size" not in pizza or "Type" not in pizza or "Toppings" not in pizza: return False if pizza["Size"] not in menu or pizza["Type"] not in menu: return False for topping in pizza["Toppings"]: if topping not in menu: return False return True elif file_type == "csv": temp = pizza.split("\n") attrs = temp[0].split(",") vals = temp[1].split(",") if len(attrs) != 4 or len(vals) < 4: return False if "\r" in attrs[-1]: attrs[-1] = attrs[-1].strip("\r") if "[" in vals[3]: vals[3] = vals[3].strip("[") if "]" in vals[-1]: vals[-1] = vals[-1].strip("]") for attr in attrs: if attr not in pizza_attr: return False for val in vals[1:]: if val not in menu: return False return True # Check whether a drinks request is valid or not def isvaliddrinks(drinks, file_type): # A json file (dictionary) sample: # {"Id": 1, # "Drink": ["Coke", "Pepsi"]} if file_type == "json": if len(drinks) != 2: return False if "Id" not in drinks or "Drink" not in drinks: return False for drink in drinks["Drink"]: if drink not in menu: return False return True # A csv file (string) sample: # "Id,Drink\n1,[Coke,Pepsi]" elif file_type == "csv": temp = drinks.split("\n") attrs = temp[0].split(",") vals = temp[1].split(",") if len(attrs) != 2 or len(vals) < 2: return False if "\r" in attrs[-1]: attrs[-1] = attrs[-1].strip("\r") if "[" in vals[1]: vals[1] = vals[1].strip("[") if "]" in vals[-1]: vals[-1] = vals[-1].strip("]") if "Drink" not in attrs: return False for drink in vals[1:]: if drink not in menu: return False return True # Return an Order Id @app.route('/pizza/get_id', methods=['GET']) def get_id(): global order_id_counter order_id_counter += 1 return str(order_id_counter) # Submit a Pizza to a temporary Order (Create if not exist, Add if exist) @app.route('/pizza/submit_pizza/<delivery>', methods=['POST']) def submit_pizza(delivery): if delivery == "Foodora": pizza = request.data.decode('utf-8') if not isvalidpizza(pizza, "csv"): return "Pizza Request is not valid" temp = pizza.split("\n") values = temp[1].split(",") order_id = values[0] if "[" in values[3]: values[3] = values[3].strip("[") if "]" in values[-1]: values[-1] = values[-1].strip("]") if not (order_id in orders): orders[order_id] = Order(order_id) orders[order_id].pizza_list = [Pizza(values[1], values[2], values[3:])] if orders[order_id].delivery is None: orders[order_id].delivery = delivery else: if orders[order_id].pizza_list is None: orders[order_id].pizza_list = [Pizza(values[1], values[2], values[3:])] else: orders[order_id].pizza_list += [Pizza(values[1], values[2], values[3:])] orders[order_id].total += menu[values[1]] + menu[values[2]] for topping in values[3:]: orders[order_id].total += menu[topping] return "Pizza Request Received" if delivery == "Uber" or delivery == "PizzaP" or delivery == "Instore": content = json.loads(request.data) if not isvalidpizza(content, "json"): return "Pizza Request is not valid" order_id = str(content["Id"]) if not (order_id in orders): orders[order_id] = Order(order_id) orders[order_id].pizza_list = [Pizza(content["Size"], content["Type"], content["Toppings"])] if orders[order_id].delivery is None: orders[order_id].delivery = delivery else: if orders[order_id].pizza_list is None: orders[order_id].pizza_list = [Pizza(content["Size"], content["Type"], content["Toppings"])] else: orders[order_id].pizza_list += [Pizza(content["Size"], content["Type"], content["Toppings"])] orders[order_id].total += menu[content["Size"]] + menu[content["Type"]] for topping in content["Toppings"]: orders[order_id].total += menu[topping] return "Pizza Request Received" else: status_code = flask.Response(status=404) return status_code # Submit Drinks to a temporary Order (Create if not exist, Add if exist) @app.route('/pizza/submit_drinks/<delivery>', methods=['POST']) def submit_drinks(delivery): if delivery == "Foodora": drink = request.data.decode('utf-8') if not isvaliddrinks(drink, "csv"): return "Drink Request is not valid" temp = drink.split("\n") values = temp[1].split(",") order_id = values[0] if "[" in values[1]: values[1] = values[1].strip("[") if "]" in values[-1]: values[-1] = values[-1].strip("]") if not (order_id in orders): orders[order_id] = Order(order_id) orders[order_id].drink_list = values[1:] if orders[order_id].delivery is None: orders[order_id].delivery = delivery else: if orders[order_id].drink_list is None: orders[order_id].drink_list = values[1:] else: orders[order_id].drink_list += values[1:] for drink in orders[order_id].drink_list: orders[order_id].total += menu[drink] return "Drinks Request Received" if delivery == "Uber" or delivery == "PizzaP" or delivery == "Instore": content = json.loads(request.data) if not isvaliddrinks(content, "json"): return "Drink Request is not valid" order_id = str(content["Id"]) if not (order_id in orders): orders[order_id] = Order(order_id) orders[order_id].drink_list = content["Drink"] if orders[order_id].delivery is None: orders[order_id].delivery = delivery else: if orders[order_id].drink_list is None: orders[order_id].drink_list = content["Drink"] else: orders[order_id].drink_list += content["Drink"] for drink in orders[order_id].drink_list: orders[order_id].total += menu[drink] return "Drinks Request Received" else: status_code = flask.Response(status=404) return status_code # Submit an Address to a temporary Order (Create if not exist, Cover if exist) @app.route('/pizza/submit_address/<delivery>', methods=['POST']) def submit_address(delivery): if delivery == "Foodora": pizza = request.data.decode('utf-8') temp = pizza.split("\n") attrs = temp[0].split(",") values = temp[1].split(",") order_id = values[0] if len(attrs) != 2 or len(values) != 2: return "Address Request is not valid" if not (order_id in orders): orders[order_id] = Order(order_id) orders[order_id].address = values[1] if orders[order_id].delivery is None: orders[order_id].delivery = delivery else: orders[order_id].address = values[1] return "Address Request Received" if delivery == "Uber" or delivery == "PizzaP" or delivery == "Instore": content = json.loads(request.data) if "Id" not in content or "Address" not in content: return "Address Request is not valid" order_id = str(content["Id"]) if not (order_id in orders): orders[order_id] = Order(order_id) orders[order_id].address = content["Address"] if orders[order_id].delivery is None: orders[order_id].delivery = delivery else: orders[order_id].address = content["Address"] return "Address Request Received" else: status_code = flask.Response(status=404) return status_code # Pop a target Pizza @app.route('/pizza/pop_single_pizza/<order_id>/<index>', methods=['GET', 'Delete']) def pop_single_pizza(order_id, index): if order_id not in orders: return "Order Id does not exist" pizza_list = orders[order_id].pizza_list if int(index) > len(pizza_list) - 1: return "Index is not valid" pizza = pizza_list[int(index)] json_output = {"Size": pizza.size, "Type": pizza.type, "Toppings": pizza.toppings} orders[order_id].total -= menu[pizza.size] + menu[pizza.type] for topping in pizza.toppings: orders[order_id].total -= menu[topping] del pizza_list[int(index)] return jsonify(json_output) # Delete a drink @app.route('/pizza/delete_drink/<order_id>/<index>', methods=['DELETE']) def delete_drink(order_id, index): if order_id not in orders: return "Order Id does not exist" drink_list = orders[order_id].drink_list if int(index) > len(drink_list) - 1: return "Index is not valid" drink = drink_list[int(index)] orders[order_id].total -= menu[drink] del drink_list[int(index)] return "Drink Deleted" # Cancel an Order @app.route('/pizza/cancel_order/<order_id>', methods=['DELETE']) def cancel_order(order_id): if order_id not in orders: return "Order Id does not exist" del orders[order_id] return "Cancel Request Received" # Get Menu @app.route('/pizza/get_menu/<item>', methods=['GET']) def get_menu(item): if item == "FULL": return menu elif item not in menu: return "Item does not exist" else: return str(menu[item]) # Get a string contains all Pizza in target Order @app.route('/pizza/get_pizza_list/<order_id>', methods=['GET']) def get_pizza_list(order_id): if order_id not in orders: return "Order Id does not exist" order = orders[order_id] result = "" count = 0 for pizza in order.pizza_list: checkout = 0 count += 1 checkout += menu[pizza.size] + menu[pizza.type] result += "Pizza {}:".format( count) + "\n Size: " + pizza.size + "\n Type: " + pizza.type + "\n Toppings: " for topping in pizza.toppings: checkout += menu[topping] result += topping + " " result += "\n" result += "Price: {}".format(checkout) return result # Get a string contains all Drinks in target Order @app.route('/pizza/get_drink_list/<order_id>', methods=['GET']) def get_drink_list(order_id): if order_id not in orders: return "Order Id does not exist" order = orders[order_id] result = "Drink: " checkout = 0 for drink in order.drink_list: checkout += menu[drink] result += drink + " " result += "\n" + "Total Price: {}".format(checkout) return result # Check whether the Order is valid or not. If valid, then submit and return a string with all information of this Order. @app.route('/pizza/check_order/<order_id>', methods=['POST']) def check_order(order_id): if order_id not in orders: return "Order Id does not exist" order = orders[order_id] if order.delivery is None: return "No Delivery Method" if order.pizza_list is None and order.drink_list is None: return "Nothing Ordered" if order.delivery != "Instore": if order.address is None: return "No Address" order.submitted = True result = "Order {} Submitted\n".format(order_id) count = 0 for pizza in order.pizza_list: count += 1 result += " Pizza {}:".format( count) + "\n Size: " + pizza.size + "\n Type: " + pizza.type + "\n Topping: " for topping in pizza.toppings: result += topping + " " result += "\n" result += " Drink: " for drink in order.drink_list: result += drink + " " result += "\n" + "Total Price: {}".format(order.total) return result # Add a new Pizza Type with Price into Menu. Cover if exist. @app.route('/pizza/add_menu/<name>/<price>', methods=['POST']) def add_menu(name, price): menu[name] = int(price) with open('menu.json', "w") as json_file_w: json.dump(menu, json_file_w) return "Name:{}({}) is added to menu".format(name, price) if __name__ == "__main__": app.run()
9c159d70b5529806ad374a11f5895cd9d0ab4dbc
TovarischSukhov/learn-homework-1
/if2.py
1,138
4.3125
4
""" Домашнее задание №1 Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки * Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая строка 'learn', возвращает 3 * Вызвать функцию несколько раз, передавая ей разные праметры и выводя на экран результаты """ def main(): print ('Ваши последние слова?') s1 = input() s2 = input() if (isinstance(s1, str) == False or isinstance(s2, str) == False): print(0) elif len(s1) == len(s2): print(1) elif len(s1) > len(s2): print(2) elif (len(s1) != len(s2) and s2 == 'learn'): print(3) if __name__ == "__main__": main()
b463f58b7b58ae8d6ba0ba58caaea79fd57a23ae
ErNaman/python-practice
/sum2.py
156
4.0625
4
def sum(): x=int(input("enter value of x:- ")) y=int(input("enter value of y:- ")) z=x+y return(z) print("sum of x and y is:-",sum())
6a15d87db4c7774514cf4d143928e9f69699e8ad
Kemal001/TransferClassesOrganizer
/views/gui.py
3,454
3.734375
4
try: # default python should be 3 from tkinter import * except ImportError: # most likely triggered by using python 2.7 from Tkinter import * def remove_values_from_list(the_list, val): return [value for value in the_list if value != val] class MainWindow(): def __init__(self, parent): self.frame = Frame(parent) class ListFrame(): """ List Frame: Wrapper class for Tk frames that hold a title and a list. The constructor's parameters are a parent frame, a title, and an items list """ def __init__(self, parent, title, items_list): # It creates a frame inside the provided parent # It creates a frame for a scrollbar and a listbox # It packs the listbox # It calls the populate_list method frame = self.frame = Frame(parent, bd=2, relief='ridge', padx=5, pady=5) self.items_list = items_list self.list_and_scroll = Frame(self.frame) self.list_box = Listbox(self.list_and_scroll, width=20, height=5, relief='ridge') self.list_and_scroll.pack() self.sb = Scrollbar(self.list_and_scroll, orient=VERTICAL) self.sb.configure(command=self.list_box.yview) self.list_box.configure(yscrollcommand=self.sb.set) self.title = Label(self.frame, text=title).pack(padx=10, pady=5) self.populate_list(self.items_list).pack(padx=10, pady=5, side=LEFT) def add_scrollbar(self): # It packs the scrollbar self.sb.pack(side=RIGHT, fill=Y) def populate_list(self, items_list): # It add the items passed into the listbox self.list_box.delete(0, END) for item in items_list: self.list_box.insert(END, item) if len(items_list) > 5: self.add_scrollbar() return self.list_box def delete_selected_item(self): # It removes the currently selected item form the listbox if self.list_box.curselection(): current = int(self.list_box.curselection()[0]) self.items_list = remove_values_from_list(self.items_list, self.items_list[current]) self.list_box.delete(current) self.populate_list(self.items_list) def current_selection(self): # It returns the currently selected item return self.items_list[int(self.list_box.curselection()[0])] def pack(self): self.frame.pack(padx=10, pady=10) def add_to_list(self, form_entry): # It adds the item in the passed form_entry to the listbox item = form_entry.get().upper() self.items_list.append(item) form_entry.delete(0, END) self.populate_list(self.items_list) def delete_item(self, item): # It deletes a passed item from the listbox self.items_list = remove_values_from_list(self.items_list, item) self.populate_list(self.items_list) class FormFrame(): """ Form Frame: Wrapper class for Tk frames that let the user input information through a form with labels and text fields. The constructor's only parameter is a parent frame""" def __init__(self, parent): # It creates a frame inside the passed parent frame = self.frame = Frame(parent) self.entries = [] def pack(self): self.frame.pack(side=RIGHT) def add_field(self, title): # It adds a label and an entry to the parent frame Label(self.frame, text=title).pack(padx=5, pady=5) entry = Entry(self.frame) entry.pack(padx=5, pady=5) self.entries.append(entry) def add_button(self, title, action): # It adds a button to the frame, and binds the passed action to it Button(self.frame, text=title, command=action).pack(padx=5, pady=5)
720786e22b6aa24de7a02083e8f99f01a48296d6
antonioavilesUAG/cspp10
/unit3/aaviles_numguess.py
432
3.953125
4
import random num = (random.randint(1,100)) guess = int(input("Try to guess the right number: ")) attempt = 0 while num != guess: if num > guess: guess = (int(input("too low try again: "))) attempt = attempt + 1 elif num < guess: guess = (int(input("too high try again: "))) attempt = attempt + 1 elif num == guess: break print("you tried {}, number is {}".format(attempt, num))
ddc7cb26c35dfc5d26bb45e49fbee833867d86f6
barua-anik/python_tutorials
/truthiness.py
176
4.0625
4
animal = input("enter the animal you love ") if animal=="dog" or animal=="cat": print(animal + " is my favoutire too") else: print("I dont like this " + animal + " FU")
1a8b0042590fe138d545db120a406480ea26e9a1
jinwei15/java-PythonSyntax-Leetcode
/LeetCode/src/SqrtX.py
863
3.703125
4
import sys class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ if x == 0: return 0 if x == 1 or x == 2: return 1 left = 0 right = x while (True): mid = (left + right) // 2 if mid * mid > x: right = mid - 1 elif mid * mid == x or (mid + 1) * (mid + 1) > x: return mid else: left = mid + 1 # public int sqrt(int x) { # if (x == 0) # return 0; # int left = 1, right = Integer.MAX_VALUE; # while (true) { # int mid = left + (right - left)/2; # if (mid > x/mid) { # right = mid - 1; # } else { # if (mid + 1 > x/(mid + 1)) # return mid; # left = mid + 1; # } # } # }
3320804a329f20fd2793795e1cb49d16977f8c20
slemal/MATH0499-1
/clustering/Dendrogram.py
3,320
4.0625
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import abc from typing import * class Point(tuple): """ A class for representing points in the euclidean space. """ def __add__(self, other): return Point(self[i] + other[i] for i in range(len(self))) def __mul__(self, scalar): return Point(scalar * self[i] for i in range(len(self))) def __truediv__(self, scalar): return Point(self[i] / scalar for i in range(len(self))) class Vertex: """ A class used to manipulate trees. """ __metaclass__ = abc.ABCMeta def __init__(self, height: float = 0) -> None: self.height = height self.parent = None def find(self) -> None: return self.parent.find() if self.parent else self @abc.abstractmethod def __call__(self, height: float) -> Generator: pass class Leaf(Vertex): """ A class used to manipulate trees. A Leaf is a labelled vertex that has no child and stores a value. """ def __init__(self, label: str or int, value: Point) -> None: """ Initializes a leaf with a given value and sets its height to 0. """ Vertex.__init__(self) self.label = label self.value = value def __call__(self, height: float) -> Generator: """ Returns the singleton {label}. """ yield {self.label} class Node(Vertex): """ A class used to manipulate trees. A Node is a vertex that has at least one child (i.e. is not a Leaf). """ def __init__(self, height: float, children: Collection[Vertex]) -> None: """ Initializes a new node, parent to the vertexes in children, with a positive height and optionally a value. """ assert height > 0, "Height must be positive." Vertex.__init__(self, height) assert children, "Cannot create a Node with no child." for child in children: assert child.height <= height, "Invalid height." assert child.parent is None, "Invalid child." child.parent = self self.children = children def __call__(self, height: float) -> Generator: """ Returns the partition induced by the tree rooted at self and restricted to a given height. """ if height >= self.height: yield set.union(*(s for child in self.children for s in child(height))) else: for child in self.children: for s in child(height): yield s class Dendrogram: """ A class used to define and manipulate a dendrogram on a set. See https://fr.wikipedia.org/wiki/Dendrogramme for a formal definition. """ """ Initializes a new Dendrogram with singletons. """ def __init__(self, sample: Mapping[str or int, Point or Tuple[float]]) -> None: # O(n) self.leaves = {label: Leaf(label, Point(value)) for label, value in sample.items()} def find(self, label: str or int) -> Vertex: # O(n) in worst case, O(log(n)) expected """ Finds the root of the tree containing the Leaf label. """ return self.leaves[label].find() def join_leaves(self, l1: str or int, l2: str or int, height: float) -> None: # O(n) """ Joins the roots of the trees containing the leaves v1 and v2. """ r1, r2 = self.leaves[l1].find(), self.leaves[l2].find() Node(height, [r1, r2]) @property def root(self): first_leave = list(self.leaves.values())[0] return first_leave.find() def __call__(self, height: float) -> list: """ Returns the partition obtained by cutting the Dendrogram at a given height. """ return list(self.root(height))
6f0276de6fda4756849883ecdfd43ed299e19766
sbhattathiri/pesolutions
/project_euler_03.py
542
4.03125
4
import math def get_list_of_prime_numbers_below_x(x): set_of_prime_factors = set() while x%2 == 0: set_of_prime_factors.add(2) x = x/2 for divisor in range(3,int(math.sqrt(x))+1, 2): while x%divisor == 0: x = x/divisor set_of_prime_factors.add(divisor) if x > 2: set_of_prime_factors.add(x) return set_of_prime_factors if __name__ == '__main__': set_of_prime_factors = get_list_of_prime_numbers_below_x(600851475143) print(max(set_of_prime_factors))
9fc0ffaa5aee844e7b768a89da7deb3108f87b92
ASU-CompMethodsPhysics-PHY494/activity_10_numbers_sine_series
/series.py
418
3.875
4
# implementation def sin_recursive(x, eps=1e-16): """Calculate sin(x) to precision eps. Arguments --------- x : float argument of sin(x) eps : float, optional desired precision Returns ------- func_value, N where func_value = sin(x) and N is the number of terms included in the approximation. """ # .... # add your code here return sumN, n-1
51d2fd2cb1a1abce93daa7b1e6265d20a90a664a
maxsours/csc-311-final-project
/part_a/item_response.py
6,933
3.625
4
from utils import * import numpy as np import matplotlib.pyplot as plt def sigmoid(x): """ Apply sigmoid function. """ return np.exp(x) / (1 + np.exp(x)) def neg_log_likelihood(data, theta, beta): """ Compute the negative log-likelihood. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param theta: Vector :param beta: Vector :return: float """ ##################################################################### # TODO: # # Implement the function as described in the docstring. # ##################################################################### user_id = data["user_id"] question_id = data["question_id"] is_correct = data["is_correct"] neg_log_p_cij = lambda i: np.logaddexp(0, beta[question_id[i]] - theta[user_id[i]]) if is_correct[i] else np.logaddexp(0, theta[user_id[i]] - beta[question_id[i]]) log_lklihood = np.sum([neg_log_p_cij(i) for i in range(len(is_correct))]) ##################################################################### # END OF YOUR CODE # ##################################################################### return log_lklihood def update_theta_beta(data, lr, theta, beta): """ Update theta and beta using gradient descent. You are using alternating gradient descent. Your update should look: for i in iterations ... theta <- new_theta beta <- new_beta You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param lr: float :param theta: Vector :param beta: Vector :return: tuple of vectors """ ##################################################################### # TODO: # # Implement the function as described in the docstring. # ##################################################################### user_id = data["user_id"] question_id = data["question_id"] is_correct = data["is_correct"] grad_theta = 0 * theta for i in range(len(is_correct)): grad_theta[user_id[i]] += is_correct[i] - sigmoid(theta[user_id[i]] - beta[question_id[i]]) grad_theta /= len(theta) # Trying to maximize, not minimize theta += lr * grad_theta grad_beta = 0 * beta for i in range(len(is_correct)): grad_beta[question_id[i]] -= is_correct[i] - sigmoid(theta[user_id[i]] - beta[question_id[i]]) beta += lr * grad_beta ##################################################################### # END OF YOUR CODE # ##################################################################### return theta, beta def irt(data, val_data, lr, iterations): """ Train IRT model. You may optionally replace the function arguments to receive a matrix. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param val_data: A dictionary {user_id: list, question_id: list, is_correct: list} :param lr: float :param iterations: int :return: (theta, beta, val_acc_lst) """ # TODO: Initialize theta and beta. theta = np.random.rand(542) beta = np.random.rand(1774) val_acc_lst = [] train_acc_lst = [] for i in range(iterations): neg_lld = neg_log_likelihood(data, theta=theta, beta=beta) score = evaluate(data=val_data, theta=theta, beta=beta) tscore = evaluate(data=data, theta=theta, beta=beta) val_acc_lst.append(score) train_acc_lst.append(tscore) #print("NLLK: {} \t Score: {}".format(neg_lld, score)) theta, beta = update_theta_beta(data, lr, theta, beta) # Added list of training accuracies return theta, beta, val_acc_lst, train_acc_lst def evaluate(data, theta, beta): """ Evaluate the model given data and return the accuracy. :param data: A dictionary {user_id: list, question_id: list, is_correct: list} :param theta: Vector :param beta: Vector :return: float """ pred = [] for i, q in enumerate(data["question_id"]): u = data["user_id"][i] x = (theta[u] - beta[q]).sum() p_a = sigmoid(x) pred.append(p_a >= 0.5) return np.sum((data["is_correct"] == np.array(pred))) \ / len(data["is_correct"]) def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. sparse_matrix = load_train_sparse("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ##################################################################### # TODO: # # Tune learning rate and number of iterations. With the implemented # # code, report the validation and test accuracy. # ##################################################################### theta, beta, val_acc_list, train_acc_list = irt(train_data, val_data, 0.15, 300) plt.plot(val_acc_list, label = "Validation Accuracy") plt.plot(train_acc_list, label = "Training Accuracy") plt.title("Training Curve") plt.xlabel("Iteration") plt.ylabel("Accuracy") plt.legend() plt.show() ##################################################################### # END OF YOUR CODE # ##################################################################### ##################################################################### # TODO: # # Implement part (c) # ##################################################################### valid_acc = evaluate(val_data, theta, beta) test_acc = evaluate(test_data, theta, beta) print("Validation Accuracy:", valid_acc) print("Test Accuracy:", test_acc) # part (d) for i in range(5): beta_curr = beta[i] theta_curr = np.sort(theta) prob_correct = np.exp(-np.logaddexp(0, beta_curr - theta_curr)) plt.plot(theta_curr, prob_correct, label="j = " + str(i)) plt.title("Probability of Correct Respose vs. Theta") plt.ylabel("Probability") plt.xlabel("Theta") plt.legend() plt.show() ##################################################################### # END OF YOUR CODE # ##################################################################### if __name__ == "__main__": main()
6080c2a01d6a70a4a0f39cb254a22986975fe66b
davidadamojr/diary_of_programming_puzzles
/arrays_and_strings/regex_match_adv.py
3,219
3.859375
4
""" An efficient and elegant regular expression matcher. Note: This has not been tested at all. Source: http://morepypy.blogspot.com/2010/05/efficient-and-elegant-regular.html """ class Regex(object): def __init__(self, empty): # empty denotes whether the regular expression can match the empty string self.empty = empty # mark that is shifted through the regex self.marked = False def reset(self): """ reset all marks in the regular expression """ self.marked = False def shift(self, char, mark): """ shift the mark from left to right, matching character char """ # _shift is implemented in the concrete classes marked = self._shift(char, mark) self.marked = marked # this function checks whether a string matches a regex # @param {Object} re the regular expression to be matched # @param pattern the string to be matched def match(re, pattern): if not pattern: return re.empty # shift a mark in from the left result = re.shift(pattern[0], True) for char in pattern[1:]: # shift the internal marks around result = re.shift(char, False) re.reset() return result # This class matches one concrete character and is a subclass of Regex class Char(Regex): def __init__(self, char): Regex.__init__(self, char) self.char = char def _shift(self, char, mark): return mark and c == self.c # This class matches the empty regular expression "Epsilon" class Epsilon(Regex): def __init__(self): Regex.__init__(self, empty=True) def _shift(self, c, mark): return False # abstract class Binary for the case of composite regular expressions with # two children e.g. a | b class Binary(Regex): def __init__(self, left, right, empty): Regex.__init__(self, empty) self.left = left self.right = right def reset(self): self.left.reset() self.right.reset() Regex.reset(self) # matches if either of two regular expressions matches the string class Alternative(Binary): def __init__(selfself, left, right): empty = left.empty or right.empty Binary.__init__(self, left, right, empty) def _shift(self, c, mark): marked_left = self.left.shift(c, mark) marked_right = self.right.shift(c, mark) return marked_left or marked_right # Repetition is used to match a regular expression any number of times class Repetition(Regex): def __init__(self, re): Regex.__init__(self, True) self.re = re def _shift(self, c, mark): return self.re.shift(c, mark or self.marked) def reset(selfself): self.re.reset() Regex.reset(self) # Sequence class Sequence(Binary): def __init__(self, left, right): empty = left.empty and right.empty Binary.__init__(self, left, right, empty) def _shift(self, c, mark): old_marked_left = self.left.marked marked_left = self.left.shift(c, mark) marked_right = self.right.shift(c, old_marked_left or (mark and self.left.empty)) return (marked_left and self.right.empty) or marked_right
9ea5fed57237bb484f1b0023592e4df8448bf7ff
Parichaymandal/PythonProject
/analysis/anova.py
6,969
3.859375
4
import numpy as np from scipy.stats import f from matplotlib import pyplot as plt def seasonal_individual_averages(y, x, i): """Function that computes grouped averages of y by factors x (month) and i (individual identifier). x are considered to be months and are grouped according to meteorological seasons (Northern Hemisphere) Parameters ---------- y : numpy.ndarray 1-dimensional numpy array with outcome measurements x : numpy.ndarray 1-dimensional numpy array with month indentifiers i : numpy.ndarray 1-dimensional numpy array with individual indentifiers Returns ------- y_avg : numpy.ndarray outcome averages by season and identifier x_avg : numpy.ndarray season identifiers i_avg : numpy.ndarray individual identifiers """ y_avg = [] x_avg = [] i_avg = [] # Loop through all unique values for x and i for xi in ['winter', 'spring', 'summer', 'autumn']: for ii in np.unique(i): y_mean = [] # Loop through all elements of the array for k in range(len(y)): if xi == 'winter': if x[k] in [12,1,2] and i[k] == ii: y_mean.append(y[k]) elif xi == 'spring': if x[k] in [3,4,5] and i[k] == ii: y_mean.append(y[k]) elif xi == 'summer': if x[k] in [6,7,8] and i[k] == ii: y_mean.append(y[k]) elif xi == 'autumn': if x[k] in [9,10,11] and i[k] == ii: y_mean.append(y[k]) # Calculate mean y_mean = np.mean(y_mean) # And store results y_avg.append(y_mean) x_avg.append(xi) i_avg.append(ii) # Convert to array and return results y_avg = np.array(y_avg) x_avg = np.array(x_avg) i_avg = np.array(i_avg) return y_avg, x_avg, i_avg def repeated_measures_oneway_anova(y, x, i, path): """Function to compute repeated measures one-way ANOVA for a variable y with groups x, in which each individual i is measured several times. Parameters ---------- y : numpy.ndarray 1-dimensional numpy array with outcome measurements x : numpy.ndarray 1-dimensional numpy array with group indentifiers i : numpy.ndarray 1-dimensional numpy array with individual indentifiers Returns ------- F: numpy.float64 F test statistic pval: numpy.float64 P-value of the test """ # Running message print('Computing repeated measures anova analysis...') # Data checks: numpy array if type(y) != np.ndarray or type(x) != np.ndarray or type(i) != np.ndarray: raise Exception('Inputs must be of type numpy.ndarray') # Data checks: Same length if len(list(set([len(x), len(y), len(i)]))) != 1: raise Exception('Input arrays must have the same length') # Total sum of squares (SST) mean_all = np.mean(y) SST = np.sum((y-mean_all)**2) print('SST: '+ str(round(SST,2))) # Between sum of squares (SSB) mean_x = [] n_i = len(set(i)) for s in np.unique(x): tmp = y[np.where(x == s)] mean_x.append(np.mean(tmp)) SSB = np.sum(n_i * ((mean_x-mean_all)**2)) print('SSB: '+ str(round(SSB, 2))) # Within sum of squares (SSW) mean_w = {} for t in np.unique(x): tmp = y[np.where(x == t)] mean_w[t] = np.mean(tmp) ss_w = [] for u in range(y.shape[0]): ss_w.append((y[u] - mean_w[x[u]])**2) SSW = np.sum(ss_w) print('SSW: '+ str(round(SSW, 2))) # Subject sum of squares (SSS) mean_i = [] n_x = len(set(x)) for v in np.unique(i): tmp = y[np.where(i == v)] mean_i.append(np.mean(tmp)) SSS = np.sum(n_x * ((mean_i-mean_all)**2)) print('SSS: '+ str(round(SSS, 2))) # Error variability (SSE) SSE = SSW - SSS print('SSR: '+ str(round(SSE, 2))) # F statistic df1 = n_x-1 MSB = SSB/df1 df2 = (n_x-1)*(n_i-1) MSE = SSE/df2 F = MSB/MSE print('F: ' + str(round(F, 2))) # Compute p-value (F distribution) pval = 1-f.cdf(F, df1, df2) print('p-value: '+ str(round(pval, 4))) # Call plot function anova_plot(y, x, i, df1, df2, F, path) # Return results return F, pval def anova_plot(y, x, i, df1, df2, F, path): """Function to do a plot of the ANOVA results Parameters ---------- y : numpy.ndarray 1-dimensional numpy array with outcome measurements x : numpy.ndarray 1-dimensional numpy array with group indentifiers i : numpy.ndarray 1-dimensional numpy array with individual indentifiers df1: integer degrees of freedom of the numerator df2: integer degrees of freedom of the denominator F: float test statistic path: string path to write figure to disk """ # ANOVA plot fig, axes = plt.subplots(1, 3, figsize=(16, 5)) # 1st plot: Assumptions axes[0].hist(y, bins = 'auto') axes[0].set_title('ANOVA assumptions:\nNormality and outliers') axes[0].set_ylabel('Frequency') axes[0].set_xlabel('Seasonal mean temperature') # 2nd plot: Boxplots yplot = [] temp_mean = [] xplot = ['winter', 'spring', 'summer', 'autumn'] for xi in xplot: ysub = [] for k in range(len(y)): if x[k] == xi: ysub.append(y[k]) yplot.append(ysub) temp_mean.append(sum(ysub)/len(ysub)) axes[1].boxplot(yplot) axes[1].scatter([1,2,3,4], temp_mean) axes[1].set_xticklabels(xplot) axes[1].set_title('ANOVA exploration:\nSeasonal boxplots') axes[1].set_ylabel('Seasonal mean temperature') # 3th plot: Result # Derive pdf of the F distribution x_dist = np.linspace(f.ppf(0.0001, df1, df2), f.ppf(0.9999, df1, df2), 1000) rv = f(df1, df2) # Find critical value for distribution x_vals = rv.pdf(x_dist) crit = min(abs(x_vals-0.05)) crit = x_dist[np.min(np.where(abs(x_vals-0.05)==crit))] # Plot axes[2].plot(x_dist, x_vals, 'k-', lw=2, label='Test F distribution') axes[2].axvline(x = F, label='Observed statistic', c = 'blue') axes[2].axvline(x = crit, label='Critical value', c = 'red') axes[2].set_title('ANOVA test results: Statistic \n and critical value (5% confidence)') axes[2].set_ylabel('Probability') axes[2].set_xlabel('F value') plt.legend() fig.show() plt.savefig(path)
50f4a2a1d63024a25ab2fa9f56c7c5ebf571a3ff
asingleneuron/leetcode-solutions
/may_leetcode_challenge/Day_12/singlenonduplicate.py
2,367
3.71875
4
class Solution: def singleNonDuplicate_with_Xor(self, nums: List[int]) -> int: result = 0 for _ in nums: result ^= _ return result def singleNonDuplicateUtil(self, nums, low, high): if low >= high: # print(low, high) return nums[high] else: mid = (low + high) // 2 if mid % 2 == 0: mid -= 1 # print( nums[mid-1], nums[mid], nums[mid+1]) # print("lmh:",low, mid, high) if (nums[mid] > nums[mid - 1] and nums[mid] < nums[mid + 1]): # print("Found") return nums[mid] else: if nums[mid] == nums[mid + 1]: return self.singleNonDuplicateUtil(nums, low, mid - 1) else: return self.singleNonDuplicateUtil(nums, mid + 1, high) def singleNonDuplicate_rec(self, nums: List[int]) -> int: return self.singleNonDuplicateUtil(nums, 0, len(nums) - 1) def singleNonDuplicate_iterative(self, nums: List[int]) -> int: ''' [1, 2, 2, 6, 6, 7, 7] mid is 3 nums[mid-1], nums[mid], nums[mid+1] 2, 6, 6 if mid and mid+1 are same, single non duplicate will be on left side else right side [1, 2, 2, 6, 6] mid is 2 : even index nums[mid-1], nums[mid], nums[mid+1] 2, 2, 6 our logic got reversed here so we deduct -1 from mid new mid will be 1 1, 2, 2 will fit into our logic of identifying the single non duplicate number ''' low = 0 high = len(nums) - 1 ans = -1 while low < high: mid = (low + high) // 2 # print(low, high, mid) if mid % 2 == 0: # if mid index is even, shift mid -= 1 if nums[mid - 1] < nums[mid] and nums[mid] < nums[mid + 1]: ans = mid return nums[ans] else: if nums[mid] == nums[mid + 1]: high = mid - 1 else: low = mid + 1 return nums[high] def singleNonDuplicate(self, nums: List[int]) -> int: self.singleNonDuplicate_iterative(nums)
e4eacf2d2dd40e5c7c923ec6cbb8bc4ca85a98eb
EydenVillanueva/Exercises
/Python/chessMatrix.py
543
3.96875
4
def isChess(matrix): for i in range( len(matrix[0]) ): for j in range( len(matrix[0]) ): if ( i == 0 or i%2 == 0) and ( j == 0 or j%2 == 0): if matrix[i][j] != 1: return False elif i%2 != 0 and j%2 != 0: if matrix[i][j] != 1: return False return True if __name__ == "__main__": matrix = [ [1,0,1,0,1], [0,1,0,1,0], [1,0,1,0,1], [0,1,0,1,0], [1,0,1,0,1] ] print(isChess(matrix))
d354192b47c105b63d9389f69b21c75f3e62f466
ryeLearnMore/LeetCode
/069_sqrtx.py
812
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #@author: rye #@time: 2019/3/19 ''' 二分法。 当时没想到。 tips: 注意return的条件 ''' class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ # 作弊 # return int(x ** (1 / 2)) if x == 0: return 0 if x == 1: return 1 l, r = 0, x - 1 while l <= r: # mid1 = l + (r - l) >> 1 mid = l + ((r - l) >> 1) if mid ** 2 <= x and (mid + 1) ** 2 > x: return mid elif mid ** 2 > x: r = mid - 1 else: l = mid + 1 if __name__ == '__main__': x = 3 print(Solution().mySqrt(x))
40bd5380029210d44b09a9ff2cc08fc9347829cd
vyahello/rent-electro-scooter
/scooter/infrastructure/numbers.py
182
3.515625
4
def make_int(text: str, default: int = -1) -> int: """Converts text into integer.""" try: return int(text) except (TypeError, ValueError): return default
4c67876fa8e108563b99bbed7b845a192991c00a
ashcoder2020/Python-Practice-Code
/factorial using inbuilt function.py
115
4.09375
4
import math n=int(input("Enter a number to find factorial : ")) print(f"Factorial of {n} is ", math.factorial(n))
c3552f29f258b1c05ae8ea111f1d1bbb76d58616
chiseungii/baekjoon
/01110.py
200
3.671875
4
N = int(input()) before = N cycle = 0 while 1: cycle += 1 tmp = before % 10 + before // 10 after = before % 10 * 10 + tmp % 10 if after == N: break before = after print(cycle)
e50bda6eadc71faa6ac247c2aba8b22cf7bf9919
bartoszmaleta/3rd-Teamwork-week
/common_elements.py
409
4
4
first_list = [1, 2, 3, 5, 'test', 'piwo', 0, 11, 'o'] second_list = [1, 6, 3, 7, 0, 'test'] common_elements = [] for elem in first_list: if elem in second_list: common_elements.append(elem) print(common_elements) print() print('list of common elements: ', common_elements) print('list of common elements: {} '.format(common_elements)) print(f'list of common elements: {common_elements} ')
93d3f061b1f4d75aa6904e8e9d93184f6b03cefb
TatsuLee/pythonPractice
/leet/l24.py
839
3.90625
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head # create a fake head dummy = ListNode(None) dummy.next = head pHead = dummy while pHead.next and pHead.next.next: # swap node1 with node2 node2 = pHead.next.next pHead.next.next = node2.next # link node1 to node3 node2.next = pHead.next # link node2 to node1 pHead.next = node2 # link head to node2 # move pHead to node2 pHead = pHead.next.next return dummy.next
e3040d85188c338ac3c5c21527a22b73e0fe75f6
erjan/coding_exercises
/shortest_path_with_alternating_colors.py
3,987
3.796875
4
''' You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph. Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist. ''' #bfs import math from collections import deque class Solution(object): def shortestAlternatingPaths(self, n, red_edges, blue_edges): # build the graph in hash table graph = {i: [[], []] for i in range(n)} # node: [red edges list], [blue edges list] for [i, j] in red_edges: graph[i][0].append(j) for [i, j] in blue_edges: graph[i][1].append(j) res = [math.inf for _ in range(n)] # we will keep min length in this list res[0] = 0 # min length for the first node is 0 min_len = 0 # queue = deque() queue.append((0, "r")) queue.append((0, "b")) seen = set() while queue: level_size = len(queue) min_len += 1 for _ in range(level_size): node, color = queue.popleft() if (node, color) not in seen: seen.add((node, color)) # in addition to vertex, we need to have the color too # add all opposite color children in the queue if color == "r": for child in graph[node][1]: queue.append((child, "b")) res[child] = min(min_len, res[child]) # we reached to a child, so we have to update res[child] if color == "b": for child in graph[node][0]: queue.append((child, "r")) res[child] = min(min_len, res[child]) # we reached to a child, so we have to update res[child] for i in range(n): if res[i] == math.inf: res[i] = -1 return res ---------------------------------------------------------------------------------------------------------------------------------- class Solution: def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]: if n == 0: return [] # build graph adjList = {i:[] for i in range(n)} # {0: [(1, 'r'), 1:[], 2:[1, 'b']} for start, end in red_edges: adjList[start].append((end, 'r')) for start, end in blue_edges: adjList[start].append((end, 'b')) ans = [-1] * n ans[0] = 0 # do bfs by increasing level every time stack = [] for nextPtr, color in adjList[0]: stack.append((nextPtr, color)) # (position, color) visited = {(0, 'r'), (0, 'b')} # We start at vertex 0, so we don't want to go back to it. level = 0 while stack: level += 1 nextStack = [] for node, color in stack: if ans[node] == -1: ans[node] = level else: ans[node] = min(ans[node], level) for nextPtr, nextColor in adjList[node]: if color != nextColor and (nextPtr, nextColor) not in visited: nextStack.append((nextPtr, nextColor)) visited.add((nextPtr, nextColor)) stack = nextStack return ans
c4b56c25ddd0678b876aa087b26ca414c51b6c0d
Meghashrestha/assignment-python
/20.py
464
4.03125
4
#20. Write a Python program to count the number of strings where the string #length is 2 or more and the first and last character are same from a given list of #strings. def string(str): list=[] sum = 0 list = str.split(" ") n = len(list) for n in list: if n > 2: sum = sum + list.index(i) print(sum) else: return "wrong" return sum str = input("enter a string : ") print(string(str))
3d9d85478f3c933ca880f17e7a13a0edc0061154
AdamZhouSE/pythonHomework
/Code/CodeRecords/2469/60839/296065.py
446
3.671875
4
n=int(input()) x=input() y=input() if n==2 and x=="aabcbcdbca" and y=="aaab": print(4) print(2) elif n==2 and x=="aabcbcdaabca" and y=="aaadacab": print(4) print(5) elif n==2 and x=="aabcbcdaabca" and y=="aaacab": print(4) print(3) elif n==2 and x=="aabcbcdaabca" and y=="aaab": print(4) print(2) elif n==2 and x=="aabcbcdabca" and y=="aaab": print(4) print(2) else: print(n) print(x) print(y)
c28d83e05aa32ef301f553f24e11a2a1bccfbefd
hpellis/learnpythonthehardway
/harriet_ex11.py
306
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 28 17:03:34 2018 @author: 612383249 """ print("How old are you?", end='') age=input() print("How tall are you?", end='') height=input() print("How much do you weigh?", end='') weight=input() print(f"So, you're {age} old, {height} tall and {weight} heavy.")
02e18b4f8e3d36e39c330baaf133e11e955d25f2
ppjh8263/programmersCodingTest
/dartGameKakao2018/myCode.py
956
3.59375
4
import re def solution(dartResult): answer = 0 resultStr = dartResult score = re.findall("\d+", resultStr) squre = re.findall("\D", resultStr) scoreStr = re.findall("\D", resultStr) for i in range(0, 3): if '#' in squre: squre.remove('#') if '*' in squre: squre.remove('*') for i in range(0, 3): if squre[i] == 'S': score[i] = int(score[i]) elif squre[i] == 'D': score[i] = int(score[i]) ** 2 elif squre[i] == 'T': score[i] = int(score[i]) ** 3 for n in range(2, -1, -1): if scoreStr[-1] == '#': score[n] *= -1 scoreStr = scoreStr[:-2] elif scoreStr[-1] == '*': score[n] *= 2 if n != 0: score[n - 1] *= 2 scoreStr = scoreStr[:-2] else: scoreStr = scoreStr[:-1] answer = sum(score) return answer
52adf6d6bd45767c64729fcf7c422538aa01e39b
Sabrina-AP/python-curso_em_video
/Exercícios/ex079.py
409
4.1875
4
#79 aula 17 listas valores=[] continuar='S' while continuar!='N': valor=int(input('Digite um valor: ')) print('Valor adicionado com sucesso...') continuar=input('Quer continuar? [S/N] ').upper() if valor not in valores: valores.append(valor) valores.sort() print(f'Você digitou os valores: {valores}') #colocar o .sort aqui não funcionou
07efebab2d31d4e678d5153625526a951fb1c9eb
zzZ5/StudyNote
/Python/abstract factory.py
1,164
4.0625
4
#!usr/bin/python3 # -*- coding: utf-8 -*- # author zzZ5 import random class PetShop: '''一个宠物商店''' def __init__(self, animal_factory=None): # 宠物工厂只是一个抽象工厂, 我们可以在未来使其实例化 self.pet_factory = animal_factory def show_pet(self): # 使用抽象工厂创建和展示宠物 pet = self.pet_factory() print("We have a lovely {}, it says {}.".format(pet, pet.speak())) class Dog: # Dog工厂 def speak(self): return "woof" def __str__(self): return "Dog" class Cat: # Cat工厂 def speak(self): return "meow" def __str__(self): return "Cat" # 额外的工厂: def random_animal(): # 创建一个随机动物 return random.choice([Dog, Cat])() # 创建一个猫店 cat_shop = PetShop(Cat) cat_shop.show_pet() # 输出结果: We have a lovely Cat, it says meow. # 售卖随机动物的商店 shop = PetShop(random_animal) for i in range(3): shop.show_pet() '''输出结果: We have a lovely Dog, it says woof. We have a lovely Dog, it says woof. We have a lovely Cat, it says meow.
209fbf05a97dcfa2f38903915cea39a4992f0edd
pawangeek/Python-codes
/Maths/sum_tillone.py
166
3.796875
4
# Task : Repeatedly add all its digits until the result has only one digit. for i in range(int(input())): p = (int(input()))%9 print(9) if p==0 else print(p)
686c118683aa3f2a1a9579b87860057f9ce7820e
Per48edjes/Udacity-DAND-P3
/audit.py
8,793
3.90625
4
# Import dependencies import re # Function to clean phone numbers def update_phoneNum(phone_num): ''' Cleans phone numbers to match (xxx) xxx-xxxx phone number convention. Arguments: phone number (string) Returns: "cleaned" phone number (string) ''' # Dictionary containing one-off erroneous numbers after auditing one_offs = {'6667011': '(415) 666-7011', '6677005': '(415) 667-7005', '8852222': '(415) 885-2222', '153581220': '(415) 358-1220', '415221366': '(415) 221-3666', '415 242 960': '(415) 242-0960', '415-929-1183 or': '(415) 929-1183', '415-252-855': '(415) 252-8551' } if phone_num in one_offs: return one_offs[phone_num] ## Helper function to convert letters in phone numbers to numbers def letters_to_numbers(phone_num): ''' Cleans phone numbers that have alphabetic mnemonics Arguments: phone number (string) Returns: "cleaned" phone number (string) ''' # Initialize regex to look for alphabetic characters ph_letters_re = re.compile(r'[a-zA-Z]+') # Mapping letters to telephone keypad numbers keypad = { "ABC": '2', "DEF": '3', "GHI": '4', "JKL": '5', "MNO": '6', "PQRS": '7', "TUV": '8', "WXYZ": '9' } # Set up dictionary to map decoded words to words words_numbers_dict = {} results = ph_letters_re.findall(phone_num) if results: for word in results: replacement = '' for letter in word.upper(): for k, v in keypad.iteritems(): if letter in k: replacement += v words_numbers_dict[word] = replacement # Substitute word with number in string for word in words_numbers_dict: repl_re = re.compile(word) phone_num = repl_re.sub(words_numbers_dict[word], phone_num) return phone_num else: return phone_num # Strip number of all non-numeric characters after converting text to # digits stripped_num = re.sub(r'[^0-9]', '', letters_to_numbers(phone_num)) ## Helper function that formats a stripped phone number def phone_num_formatter(stripped_num): ''' Formats a string that's been stripped Arguments: stripped phone number (string) Returns: "cleaned" phone number (string) ''' # Determine how to format 10-digit phone number def ten_digit_formatter(ten_dig_num): ''' Formats string of 10 numbers into phone number convention ''' last_four = ten_dig_num[-4:] middle_three = ten_dig_num[-7:-4] area_code = ten_dig_num[0:3] return "(" + area_code + ") " + middle_three + "-" + last_four if len(stripped_num) == 10: return ten_digit_formatter(stripped_num) # Drop country prefix code elif len(stripped_num) == 11: return ten_digit_formatter(stripped_num[1:]) # Lastly, check to see if erroroneous number is a one-off case else: if stripped_num in one_offs: return one_offs[stripped_num] else: return '' return phone_num_formatter(stripped_num) # Function to standardize zip codes to 5 digit sequence def update_zipcode(zip_code): ''' Formats a string that's been stripped Arguments: zip code (string) Returns: "cleaned" zip code (string) ''' # Regex for valid San Francisco zipcodes zip_re = re.compile(r'^(94\d{3})(-\d{4})?$') m = zip_re.search(zip_code) # One-off corrections one_offs = {'14123': '94123', '41907': '94107', '90214': '94109', '95115': '94115', 'CA': '94133', '94113': '94133', '94087': '94107', '94013': '94103' } # Return normal zipcodes or truncated versions of extended zipcodes if m and (m.group(1) not in one_offs): return m.group(1) else: try: return one_offs[zip_code] except: return zip_code[0:5] # Function to clean unexpected street name according to mapping def update_street_name(name): ## Ignore these "streets," as they follow special conventions special_streets = ["San Francisco Bicycle Route 2", "Pier 39", "SF 80 PM 4.5", "Broadway"] if name in special_streets: return name # Regex to find streets with address numbers in 'addr:street' tag ## Check for prefix and suffix numbers testA_re = re.compile(r'^(#?\d+)\s(.*)') testB_re = re.compile(r'^(.*?)(\sSte|\sSuite)?\s(#?\d+)$') if (name not in special_streets): m = testA_re.search(name) n = testB_re.search(name) if m: name = m.group(2) if n: name = n.group(1) # Proper cases street names that do NOT start with a number try: int(name.split()[0][0]) except: name = name.title() # Street mapping street_mapping = { "St": "Street", "St.": "Street", "street": "Street", "st": "Street", "AVE": "Avenue", "Ave": "Avenue", "Ave.": "Avenue", "Blvd": "Boulevard", "Blvd.": "Boulevard", "Cresc": "Crescent", "Hwy": "Highway", "Dr": "Drive", "Ln.": "Lane", "Rd": "Road", "Rd.": "Road", "Pl": "Plaza", "Bldg": "Building" } # Appending specific street types to streets missing type designation incomplete_streetnames = { "15th": "15th Street", "Vallejo": "Vallejo Street", "Mason": "Mason Street", "Pollard": "Pollard Street", "South Park": "South Park Street", "Van Ness": "Van Ness Avenue", "Wedemeyer": "Wedemeyer Street", "Hyde": "Hyde Street", "Gough": "Gough Street", "Post": "Post Street", "Pier": "Pier 40 A", "New Montgomery": "New Montgomery Street", "Mission Rock": "Mission Rock Street", "Pacific Avenue Mall": "Pacific Avenue", "Broadway Street": "Broadway", "California": "California Street", "King": "King Street" } if name in incomplete_streetnames: return incomplete_streetnames[name] # One-off fixes oneoffs = { "Cesar Chavez St St": "Cesar Chavez Street", "19th & Linda San Francisco": "Linda Street", "Bay And Powell": "Bay Street", "Multi Use Building": "Phelan Avenue", "Murray Street And Justin Drive": "Justin Drive", "Willard North": "North Willard Street", "14th St, San Francisco ": "14th Street", "Broadway Street; Mason Street": "Mason Street", "One Letterman Drive": "Letterman Drive", } if name in oneoffs: return oneoffs[name] # Regex to find anomalous street types street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) result_re = re.search(street_type_re, name) if result_re: result = result_re.group() i = name.find(result) # Check street against street mapping; perform necessary adjustments if result in street_mapping: new_ending = street_mapping[result] return name[:i] + new_ending # Returns name as-is if it passes checks above else: return name else: return name
63c7448add1e11d406a06b801005e6f1ded5d92b
krishnanunni-pr/Pyrhon-Django
/Regular expression/Rules.py
685
4.0625
4
# re- regular pattern matching # 1 x='[abc]' either a b or c # 2 x='[^abc]' except abc # 3 x='[a-z]' a to z # 4 x='[A-Z]' A to Z # 5 x='[a-zA-Z]' both lower and upper case are checked # 6 x='[0-9]' check digits # 7 x='[^a-zA-Z0-9]' special symbols # 8 x='\s' check space # 9 x='\d' check the digits # 10 x='\D' except digits # 11 x='\w' all words except special characters # 12 x='\W' for special characters # quantifiers # 1 x='a+' a including group # 2 x='a*' count including zero number of a # 3 x='a?' count a as each including zero no of a # 4 x='a{2}' 2 no of a position # 5 x='a{2,3}' minimum 2 a and maximum 3 a # 6 x='^a' check starting with a # 7 x='a$' check ending with a
1422c7ddfe16c6e81586dde3db6509e61bea09da
eecs110/winter2019
/course-files/lectures/lecture_11/04_dictionary_lookup_from_file.py
687
3.875
4
import json import sys import os # read lookup table from a file: dir_path = os.path.dirname(sys.argv[0]) file_path = os.path.join(dir_path, 'state_capitals.json') f = open(file_path, 'r') capital_lookup = json.loads(f.read()) def get_state_capital(lookup, state): return lookup[state] # use lookup table to answer some questions: print('The capital of Florida is:', get_state_capital(capital_lookup, 'Florida')) print('The capital of Illinois is:', get_state_capital(capital_lookup, 'Illinois')) print('The capital of California is:', get_state_capital(capital_lookup, 'California')) print('The capital of Massachusetts is:', get_state_capital(capital_lookup, 'Massachusetts'))
60b079febe206d2196514a901fe9381d13065f6e
pratyusa98/Open_cv_Crashcourse
/opencvbasic/14. Bitwise Operations.py
875
3.5625
4
#Bitwise Operations includes AND, OR, NOT and XOR #It is most important and use for various purpose like masking #and find roi(region of intereset) which is in complex shape. import cv2 import numpy as np img1 = np.zeros((250, 500, 3), np.uint8) img1 = cv2.rectangle(img1,(150, 100), (200, 250), (255, 255, 255), -1) img2 = np.zeros((250, 500, 3), np.uint8) img2 = cv2.rectangle(img2,(10, 10), (170, 190), (255, 255, 255), -1) cv2.imshow("img1", img1) cv2.imshow("img2", img2) bitAnd = cv2.bitwise_and(img2, img1) bitOr = cv2.bitwise_or(img2, img1) bitNot1 = cv2.bitwise_not(img1) bitNot2 = cv2.bitwise_not(img2) bitXor = cv2.bitwise_xor(img1, img2) cv2.imshow('bitAnd', bitAnd) cv2.imshow('bitOr', bitOr) cv2.imshow('bitNot1', bitNot1) cv2.imshow('bitNot2', bitNot2) cv2.imshow('bitXor', bitXor) cv2.waitKey(0) cv2.destroyAllWindows()
a5bd7f15fdf6a73022e58f227cc10514449b6b3f
daniel-reich/ubiquitous-fiesta
/dWeA6vWdrPYtwhxoS_11.py
326
3.8125
4
import string def count_number(lst): digits = string.digits count = 0 lst = ((str(lst).replace('[','')).replace(']','')).split(' ') for eachvalue in lst: for eachletter in eachvalue: if eachletter in digits or eachletter == '.': count += 1 break else: continue return count
513bad1895d123a1329e90e26d4812c7e85127d5
karolkocemba/final
/flight_schedule.py
610
3.71875
4
import csv class FlightSchedule: def __init__(self): self.flights = [] self.plane_identifiers = [] self.miles = [] def read_data_from_file(self): with open("flight_data.csv", encoding='utf-8') as file: reader = csv.reader(file) for row in reader: self.flights.append(row[0]) self.miles.append(int(row[4])) if row[1] not in self.plane_identifiers: self.plane_identifiers.append(row[1]) def determine_longest_flight(self): longest_flight_length = max(self.miles) longest_flight_index = self.miles.index(longest_flight_length) return self.flights[longest_flight_index]
7efdbd00d940a12ecee31a67b789b7ccaa30f041
maggiebauer/homework-7.8-salesperson_report
/sales_report.py
2,146
4.09375
4
""" sales_report.py - Generates sales report showing the total number of melons each sales person sold. """ salespeople = [] # creates an empty list to add the salespeople melons_sold = [] # creates an empty list to track the number of melons sold f = open("sales-report.txt") # opens the file 'sales-report.txt' so it can be used within this file # and sets it the variable 'f' for line in f: #takes each line in the file which has been set to the 'sales-report.txt' file line = line.rstrip() # removes any whitespace at the end of each line entries = line.split("|") # creates a list for each line split on the '|' so that each salesperson, # total order, and number of melons has its own index salesperson = entries[0] # defines the salesperson as the first item in the entries list melons = int(entries[2]) # defines melons as the thrid item in the entries list and converts to an int if salesperson in salespeople: # if the salesperson has already been added to the salespeople list, # the following code will run position = salespeople.index(salesperson) # gets the index of the salesperson in the salespeople list melons_sold[position] += melons # adds the number of melons in this entry to the running total of melons # based on the list of melons having the same index as the salesperson list else: # if the salesperson is not already in the salespeople list, # the following code will run salespeople.append(salesperson) # the salesperson will be added to the end of the salespeople list melons_sold.append(melons) # the number of melons sold will be added to the end of the melons list for i in range(len(salespeople)): # for every number in the range from 0 to the length of the salesperson list # the following will run print("{} sold {} melons".format(salespeople[i], melons_sold[i])) # prints out the following phrase and inserts each salesperson at each index # and the corresponding melon count at that index in the melons list
ce981daae2eeda0038941778658b09ced578538b
kelv-yap/sp_dsai_python
/ca3_prac1_tasks/section_2/sec2_task4_submission.py
780
4.3125
4
number_of_months = 6 title = "Calculate the average of your last " + str(number_of_months) + "-months electricity bill" print("*" * len(title)) print(title) print("*" * len(title)) print() bills = [] bill_number = 1 while bill_number <= number_of_months: try: input_bill = float(input("Enter Bill #{}: ".format(bill_number))) bills.append(input_bill) bill_number += 1 except ValueError: print("Please enter a numeric value") print("Your electricity bills for the past " + str(number_of_months) + " months are:") bill_str_list = [] for bill in bills: bill_str_list.append("$" + str(bill)) print(*bill_str_list, sep=", ") average = sum(bills) / number_of_months print("The average of your electricity bill is {:.2f}".format(average))
d5cf8a29dfac969d2bcbeea28ff1b55e2478596a
KevinMichelle/Vision_FIME_2015
/package/utilities/structures.py
2,316
4.5625
5
import sys # Explanation about the 'dict_to_list' function # # We know that the basic element in a dictionary structure is a tuple: the key and their value corresponding to that key. # # The key must be hashable, so it may be a number, a tuple, things like that. If am not in a mistake, the value of can be anything. # # So, suppose I have the following dictionary # # Hello = {} # Hello[1] = 10 # Hello[2] = 7 # Hello[3] = 5 # # If print the dictionary it would be like this # # Hello = {1:10, 2:7, 5:7} # # I like use dictionary to check the frecuency of a certain colecction of items. It seems so natural do this task with dictionary. # But also I find difficult to do certain statistics things with a dictionary. # # So maybe you can try the following process: # "build" your structure as a dictionary because it is easier # convert the dictionary structure to a list. # # I find three situations about this process converting. # 1 - You dont care about the keys in the dictionary, only the values # Example: 10, 7, 5 # 2 - You care only the keys # Example: 1, 2, 3 # 3 - You care both the key and their value and want see how many times a element repeats # Example: 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 # # The 'bool_key' variable is a boolean that defines the flow of how you want convert the dictionary. # If it is true, definitely you want that the keys be in the list. If it is false, then you only will see their values, like in the case 1. # And the 'bool_dictio' variable is another boolean that only affecs the flow of the progam in if the 'bool_key' variable is true. # If it is true then you will see the list like in the case 3. If is is false, then it will be like in the case 2. def dict_to_list(structure, bool_key, bool_dictio): if type(structure) is dict: new_list = [] if bool_key: for element in structure: if bool_dictio: new_list.append(element) else: count = structure[element] for dummy in xrange(count): new_list.append(element) return new_list else: for element in structure: new_list.append(structure[element]) return new_list else: return None def tuple_to_list(structure): if type(structure) is tuple: new_list = [] for element in structure: new_list.append(element) return new_list else: return None
ebf12acbb0e446c1b793ef712c20103f070e0cbb
rohit523/LeetCode-June-Challenge
/Week2 June 8th–June 14th/Sort Colors.py
667
3.5
4
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ d = {} for num in nums: if num not in d: d[num] = 1 else: d[num] += 1 for i in range(len(nums)): if 0 in d and d[0] != 0: nums[i] = 0 d[0] -= 1 elif 1 in d and d[1] != 0: nums[i] = 1 d[1] -= 1 elif 2 in d and d[2] != 0: nums[i] = 2 d[2] -= 1
438adb533e5192dcce6070b12902f96676e852a4
nopomi/hy-data-analysis-python-2019
/hy-data-analysis-with-python-2020/part04-e09_snow_depth/src/snow_depth.py
271
3.578125
4
#!/usr/bin/env python3 import pandas as pd def snow_depth(): wh = pd.read_csv("src/kumpula-weather-2017.csv") max = wh["Snow depth (cm)"].max() return max def main(): print("Max snow depth: " + str(snow_depth())) if __name__ == "__main__": main()
4234c3e9b4ac0c1d3faf50985e00f1a55d860289
ZimingGuo/MyNotes01
/MyNotes_01/Step01/2-BASE02/day04_08/demo06.py
1,695
3.765625
4
# author: Ziming Guo # time: 2020/2/11 """ demo06: 函数参数 形式参数 练习:exercise09.py 练习:exercise10.py """ # 1. 缺省(默认)形参:如果实参不提供,可以使用默认值. # 如果实参没给全,就会用默认参数值代替 def fun01(a=None, b=0, c=0, d=0): print(a) print(b) print(c) print(d) # 关键字实参 + 缺省形参:调用者可以随意传递参数. # 如果只用缺形形参,那就会一直默认是前两个参数的值,只有用了关键字实参,才会定位 # fun01(b=2, c=3) # 2. 位置形参 def fun02(a, b, c, d): print(a) print(b) print(c) print(d) # 3.星号元组形参: * 将所有实参 合并 为一个元组 # 作用:把所有形参合起来 让实参个数无限 def fun03(*args): # args 的意思就是很多个 argument 的意思 print(args) # 有了这个方法,以前对于元组那些操作方法(切片,索引 etc)都可以用了 # fun03()# () # fun03(1)# (1,) # fun03(1,"2")# (1, '2') # 4.命名关键字形参:在星号元组形参以后的位置形参 # 目的:要求实参必须使用关键字实参. def fun04(a, *args, b): print(a) print(args) print(b) fun04(1, b=2) # 用这种命名关键字形参必须有 a 和 b # 而中间的 *argu 不是必须的 fun04(1, 2, 3, 4, b=2) def fun05(*, a, b): print(a) print(b) fun05(a=1, b=2) # 5. 双星号字典形参:**目的是将实参合并为字典. # 实参可以传递数量无限的关键字实参. # 最后打印出来的是个字典,把实参合并为字典 def fun06(**kwargs): print(kwargs) fun06(a=1, b=2)
797519240fa689fbfff1b39f022339ff78db84b8
daniel-reich/ubiquitous-fiesta
/aj7JPnAuW8dy4ggdp_19.py
172
3.71875
4
def parity(n): # remander = bool(n % 2) # if remainder == False: # return "even" # if remainder == True: # return "odd" return "even" if n % 2 == 0 else "odd"
192ca1743d1f2b5e4e56f76d93fd580434464bac
IvanIsCoding/OlympiadSolutions
/beecrowd/1094.py
740
3.5
4
# Ivan Carvalho # Solution to https://www.beecrowd.com.br/judge/problems/view/1094 # -*- coding: utf-8 -*- """ Escreva a sua solução aqui Code your solution here Escriba su solución aquí """ ordem = int(input()) dicio = {"C": 0, "R": 0, "S": 0} for i in range(ordem): a, b = input().split() dicio[b] += int(a) total = sum(dicio.values()) print("Total: %d cobaias" % total) print("Total de coelhos: %d" % dicio["C"]) print("Total de ratos: %d" % dicio["R"]) print("Total de sapos: %d" % dicio["S"]) print("Percentual de coelhos: %.2f %%" % (100.0 * (dicio["C"] / float(total)))) print("Percentual de ratos: %.2f %%" % (100.0 * (dicio["R"] / float(total)))) print("Percentual de sapos: %.2f %%" % (100.0 * (dicio["S"] / float(total))))
c3595aa8d5ca9e5ec7aeb75ca88c26fe095536ee
megarocks/data_science
/keras/02/naive_relu.py
760
3.5625
4
import numpy as np from numpy import array # keras.layers.Dense(512, activation='relu') # is equal to: # output = relu(dot(W, input) + b) # relu is equal to max(x, 0) - rectified linear unit def naive_relu(x): assert len(x.shape) == 2 x = x.copy() for i in range(x.shape[0]): for j in range(x.shape[1]): x[i, j] = max(x[i, j], 0) return x # tensor = array([ # [[1, 2, 3], [3, 2, 8], [5, 1, 7], [8, 4, 2], [13, 21, 18]], # [[1, 7, 4], [3, 5, 7, ], [11, 34, 18], [5, 1, 7], [3, 2, 8]] # ]) input_tensor = array([ [5, 9, -1, 7], [1, 8, 5, 4] ]) print(input_tensor) output_tensor = naive_relu(input_tensor) print(output_tensor) z = np.maximum(input_tensor, 0.) # rely on BLAS implememntation print(z)
12e9c7c6b041c1773b1894c3cd01fee49790b04f
DmytroBabenko/Data-Science-NLP-url-segmentation
/word_breaker.py
3,047
3.609375
4
from trie import Trie class WordBreaker: def __init__(self, trie: Trie): self.trie = trie def word_break(self, input_str: str): #key - position, value - word all_words = list() self._word_break_helper(input_str, 0, all_words) words = WordBreaker._find_the_best_combination_of_words(all_words, len(input_str)) return words def _word_break_helper(self, input_str: str, origin_pos : int, all_words: list): size = len(input_str) if size == 0: return for i in range(1, size + 1): sub_str = input_str[0:i] if WordBreaker._is_int_or_float(sub_str) or self.trie.search(sub_str): all_words.append((origin_pos, sub_str)) self._word_break_helper(input_str[i: size], origin_pos + i, all_words) #TODO: implement it more elegant and optimizer using dynamic programmin @staticmethod def _find_the_best_combination_of_words(all_words, length): next_pos = 0 all_combination = [] words = [] words_pos = WordBreaker._find_words_in_pos(all_words, next_pos) while len(words_pos) > 0: p, w = words_pos[-1] if len(words) == 0 or (p, w) != words[-1]: words.append((p, w)) next_pos = p + len(w) tmp_words = WordBreaker._find_words_in_pos(all_words, next_pos) if len(tmp_words) == 0: if next_pos == length: all_combination.append(words.copy()) words.pop() if words_pos[-1] in all_words: all_words.remove(words_pos[-1]) words_pos.pop() words_pos += tmp_words min = 1000 min_idx = -1 for i in range(0, len(all_combination)): if len(all_combination[-1]) < min: min = len(all_combination[-1]) min_idx = i result = [] for (p, w) in all_combination[min_idx]: result.append(w) return result @staticmethod def _find_words_in_pos(all_words, pos): all = list() for i in range(0, len(all_words)): p, w = all_words[i] if p == pos: all.append(all_words[i]) return all @staticmethod def _is_int_or_float(string): if string == '.': return True idx = ord(string[0]) if idx < ord('0') or idx > ord('9'): return False try: val = float(string) return True except: return False # if __name__== "__main__": # # # f = WordBreaker._is_int_or_float("week8") # # dictionary = ["mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream", "us", "to", "a", "day", "today"] # # trie = Trie.create_trie(dictionary) # word_breaker = WordBreaker(trie) # # broken, words = word_breaker.word_break("usatoday") # # a = 10
3125a85da2c7382e143f0e9e1dffd2f7aa7e61b4
J040-M4RC0S-Z/first-programs
/índice de massa corporal em python/IMC.py
652
3.640625
4
import math print("\033[1;35mIMC\033[m") alt = float(input("Digite a sua altura (metros): ")) peso = float(input("Digite o seu peso (kilos): ")) imc = peso/math.pow(alt,2) if imc < 18.5: print(f"""IMC: {imc:.2f} Situação: Abaixo do peso""") elif 18.5 <= imc <= 25: print(f"""IMC: {imc:.2f} Situação: Peso Ideal""") elif 25 <= imc <=30: print(f"""IMC: {imc:.2f} Situação: Sobrepeso""") elif 30 <= imc <= 40: print(f"""IMC: {imc:.2f} Situação: Obesidade""") elif imc > 40: print(f"""IMC: {imc:.2f} Situação: Obesidade Mórbida""") else: print("opção não encontrada")
78ae4f059d69cf4a7ca53a09dc9ac30529eec7e0
jberkow713/Super-Checkers
/logic.py
854
3.8125
4
def create_purpose(): favorite_events = [] print('Time to figure out your 5 favorite events') for i in range(5): favorite = input('Please type your favorite life events:') favorite_events.append(favorite) rankings = [] for x in favorite_events: print(f'Please rank {x} from 1 to 10 in the following prompt:') variable = False while variable == False: is_decimal = False while is_decimal == False: ranking = input(f'Please rank {x} from 1 to 10:') if ranking.isdecimal() == True: is_decimal = True ranking = int(ranking) variable = True rankings.append(ranking) event_dict = dict(zip(favorite_events, rankings)) return event_dict print(create_purpose())
7d60dd4dd82357ed74dd12dc05bc53ad3ab2b239
Grimness/pythonDemo
/iterationDemo.py
420
4.09375
4
from collections import Iterable d = {'a':1,'b':2,'c':3} for key in d: print(key) for value in d.values(): print(value) for ch in 'ABCDEFG': print(ch) print(isinstance('abc',Iterable)) print(isinstance([1,2,3,4],Iterable)) print(isinstance(12345,Iterable)) # enumerate() 方法可以让遍历对象生成角标 for i,value in enumerate(['A','B','C']): print(i,value) for x,y in [(1,1),(2,4),(3,9)]: print(x,y)
a787f03fd38a60d8f06e69ccdaaf3aec4a5680a3
Medona1999/Sem1-Python-Lab
/Python Programs/3swap.py
203
3.90625
4
x=int(input("enter the first number:")) y=int(input("enter the second number:")) print("Before Swapping") print("x=",x) print("y=",y) x=x+y y=x-y x=x-y print("After Swapping") print("x=",x) print("y=",y)
ded1825d4cd9226442393479dcd46eab4a24983d
C-CCM-TC1028-111-2113/homework-2-jennmvg
/assignments/02Licencia/src/licencia.py
435
3.78125
4
import math print ("Ingresa tu edad") edad= int(input()) if (edad>=18): id=print (input(("¿Tienes identificación oficial?(s/n)") ) if (id=="s"): print ("Trámite de licencia concedido") elif (id=="n"): print ("No cumples requisios") else print ("Respuesta incorrecta") elif (edad<18): print ("No cumples con los requisitos") else print ("Respuesta incorrecta")
9797fc4b5bd9aade67f003c6a8019d6c1e9cc0ec
kostacoffee/NCSSchallenge
/2014/Week 2/Aardvark!.py
203
3.890625
4
s = "aardvark" c = 0 for char in input(): if s[c] == char or s[c].upper() == char: c+=1 if (c >= len(s)): print("Aardvark!") break else: print("No aardvarks here :(")
72c6c2abcc890492a9a1c9e2cc74e4ccb894bc25
nagask/Interview-Questions-in-Python
/Arrays/MaximumDrop.py
546
3.96875
4
''' Given an array of integer, find the maximum drop between two array elements, given that second element comes after the first one. num = [13, 2, 23, 15, 6, 68, 19, 1, 12, 13, 100] Max drop is 99. But answer is 67 because second element must come after first element. Thus, (1,100) is not a valid case ''' num = [13, 2, 23, 15, 6, 68, 19, 1, 12, 13, 100] low = float('inf') max_drop = 0 for n in num[::-1]: if n < low: low = n else: if n - low > max_drop: max_drop = n - low print(max_drop)
c315abf452df8ce3803a1e7260941717f881b1b0
Weless/leetcode
/python/数组/1427. 字符串的左右移.py
460
3.765625
4
from typing import List class Solution: def stringShift(self, s: str, shift: List[List[int]]) -> str: for direction,amount in shift: if amount == 0: continue if direction == 0: s = s[amount:]+s[:amount] else: s = s[len(s)-amount:]+s[:-amount] return s S = Solution() s = "joiazl" shift = [[1,1],[1,6],[0,1],[1,3],[1,0],[0,3]] print(S.stringShift(s,shift))
7aaa71a1f89eaed610bfb2f57a6d211b9e1dd3b6
hisonic001/project
/coding_test/add_2_out_of_list(done).py
465
3.640625
4
numbers=[5,0,2,7] def solution(numbers): answer=[] for setnum in numbers: first = numbers.index(setnum) start = first + 1 restnum = numbers[start:] for rest in restnum: result = setnum + rest if result not in answer: answer.append(result) answer = sorted(answer) print(answer) solution(numbers) ## set 함수 사용하기 ## set()으로 중복된 list를 없앨 수 있다.
b297fd101ad12cf9ea1dd96cc10f1b6478d20c47
douglasdl/Python
/BasicCourse/practice04-06-01.py
535
3.71875
4
# coding:utf-8 def showMark(symbol, number): for n in range(number): print(symbol, end="") print() def showMark2(symbol, number): print(symbol * number) def showMark3(columns, rows, symbol): for c in range(columns): for r in range(rows-c): print(symbol, end="") print() def showMark4(columns, rows, symbol): for c in range(columns): for r in range(rows): print(symbol, end="") print() showMark("★", 5) print() showMark2("〇", 5) print() showMark3(5, 5, "△") print() showMark4(5, 5, "◇") print()
4fa8fd89c603866ba50d262f1d17a7d4a10b0b2a
razzaqim/NumPy-and-Pandas
/interrogation.py
1,482
3.5
4
import pandas as pd maths_results = pd.DataFrame ([[29, 40, "fail"], [18 , 85, "pass"], [21, 98, "pass"], [26, 76, "pass"], [20, 30, "fail"]], index = ["Hana", "Bella", "Jay", "Terry", "Niya"], columns = ["Age", "Percentage score", "Outcome",]) print(maths_results) print() print("Niya's results") print(maths_results.loc["Niya"]) print() print("Percentage score mean") results_mean = maths_results["Percentage score"].mean() print(results_mean) print() print("Students who scored less than or equal to 40%") myfilter = maths_results["Percentage score"] <= 40 print(myfilter) print() print("Top 3 students") filterr = maths_results["Percentage score"] > 40 highscores = maths_results[filterr] print(highscores.head(3)) print() print("Students over 20 that passed") double_filter = (maths_results["Outcome"] == "pass") & (maths_results["Age"] > 20) filtered = maths_results[double_filter] print(filtered) print() print("Highest Score") top_score = maths_results["Percentage score"] print(top_score.max()) print() print("Youngest Student") top_score = maths_results["Age"] print(top_score.min()) print() print("Ages of all students") print(maths_results["Age"]) print() print("Outcome of all students") print(maths_results.iloc[0: , 2]) print() print("Sorting students in age order") print(maths_results.sort_values("Age")) print() print("Rename score column") print(maths_results.rename(columns={"Percentage score":"Score(%)"}))
3696b7c25e976e1cb4b26a0ae859ddfbd3058976
wenjiaaa/Leetcode
/P0001_P0500/0103-binary-tree-zigzag-level-order-traversal.py
954
3.84375
4
# https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] queue = [root] res = [] layer = 1 while len(queue) != 0: tmp = [] for i in range(len(queue)): cur = queue.pop(0) if cur.left: queue.append(cur.left) if cur.right: queue.append(cur.right) if layer % 2 == 0: tmp.insert(0, cur.val) else: tmp.append(cur.val) res.append(tmp) layer += 1 return res
a93477059d37def22432536ca61fcbfd53f40430
taanh99ams/taanh-fundamental-c4e15
/SS02/0_to_n.py
177
4.28125
4
# for _ in range(2, 8, 3): # print("Hello") # # print("bye") # x = 5 # for i in range(x): # print(i) x = int(input("Enter a number")) for i in range(x): print(i)
ba35e826f7efd2cc2b33b58bb48e9182a19cd6db
imtiantian/Python_Awesome_Interview
/python数据结构与算法练习/sequential_search.py
340
4
4
#-*- coding=utf-8 -*- # 顺序查找 def sequential_search(list,item): pos=0 found=False while pos<len(list)and not found: if list[pos]==item: found=True else: pos=pos+1 return found,pos list=[1,2,32,8,17,19,13,0] # print (sequential_search(list,3)) print (sequential_search(list,13))
18496257a0890d8276ab146230c51eb2d48311d2
aryabartar/learning
/interview/stack-queue-deque/queueusingstack.py
488
3.84375
4
class Queue2Stack(object): def __init__(self): self.s1 = [] self.s2 = [] def enqueue(self, item): self.s1.append(item) def dequeue(self): s1 = self.s1 s2 = self.s2 while len(s1) != 0: s2.append(s1.pop()) value = s2.pop() while len(s2) != 0: s1.append(s2.pop()) return value q = Queue2Stack() for i in range(5): q.enqueue(i) for i in range(5): print(q.dequeue())
ea9a0a944dd98c3504c916cfdea324eb9c9b5063
kapilthakkar72/Sentiment-Mining-and-Domain-Adaptation
/General Sentiment Analyser/Data Training/rudraksh.py
4,161
3.5625
4
import csv import re #This Function removes names tagged in the tweets def removeAtTheRate(s): match = re.search(r'@([A-Za-z0-9_]+)', s) if match : start = match.start() end = match.end() s = s[0:start] + s[end:] return removeAtTheRate(s) else: return s # Generate Feature List # Words Defining Positiveness or Negativeness vocab = 'F:\\IIT Delhi\\Semester 4\\Natural Language Processing\\Assignment\\rudraksh\\Pos_neg.csv' feature_list = [] with open(vocab, 'r') as vocabfile: vocabs = csv.reader(vocabfile, delimiter=",") for word in vocabs: if(word[2]!="" or word[3]!=""): # Remove '#' if present x = word[0].find("#") if(x==-1): feature_list.append(word[0].lower()) else: feature_list.append((word[0][0:x]).lower()) # Remove first entry feature_list.pop(0) # Length of feature List print len(feature_list) feature_present = [False] * len(feature_list) ''' # Printing Some of the Features for i in range(0,10): print feature_list[i] ''' ''' # Processing With Tweet data # 1. Remove @ words, they do not represent anything # 2. Convert tweet to lower-case ''' # Read Tweets from Training data... tweets_path = 'F:\\IIT Delhi\\Semester 4\\Natural Language Processing\\Assignment\\training.csv' # Labels labels = [] tweets = [] # Feature List from Twitter features_from_twitter = [] features_from_twitter_freq = [] feature_list_freq = [0] * len(feature_list) with open(tweets_path, 'r') as csvfile: tweets = csv.reader(csvfile, delimiter=",") i = 1 for tweet in tweets: tt = removeAtTheRate(tweet[1]) tt = tt.lower() tweet.append(tt) ############################################ # Check if feature is present or not ########################################### while(True): match = re.search(r'([A-Za-z\']+)', tt) if match : start = match.start() end = match.end() word = tt[start:end] # print "Word:" + word tt = tt[0:start] + tt[end:] try: b=feature_list.index(word) except ValueError: # Not in feature list # Search in Twitter words try: c = features_from_twitter.index(word) #print "Searching for " + word + " in:" + str(features_from_twitter) except ValueError: # Not in Twitter feature list, add it features_from_twitter.append(word) features_from_twitter_freq.append(1) else: #print "and it found at location " + str(c) features_from_twitter_freq[c] = features_from_twitter_freq[c] + 1 else: feature_present[b] = True feature_list_freq[b] = feature_list_freq[b] + 1 else: break ########################################## labels.append(tweet[0]) i = i+1 if (i==(1600000*0.8)): #if (i==(5)): break new_feature_list = [] for i in range(0,len(feature_list)): if(feature_present[i]): new_feature_list.append(feature_list[i]) print "\n\nNew Feature List..." + str(len(new_feature_list)) features_with_freq = [] n = len(feature_list) for i in range(0,n): features_with_freq.append((feature_list[i],feature_list_freq[i])) features_with_freq.sort(key=lambda tup: tup[1]) for i in range(0,n): print features_with_freq[i][0] + "," + str(features_with_freq[i][1]) twitter_features_with_freq = [] print "\n\nTwitter List..." for i in range(0,len(features_from_twitter)): twitter_features_with_freq.append((features_from_twitter[i],features_from_twitter_freq[i])) twitter_features_with_freq.sort(key=lambda tup: tup[1]) for x in twitter_features_with_freq: print x[0] + "," + str(x[1]) print "Done"
0aad155bf9745bdaf0b4399ca01c979af8e448cc
meyerlazard/taffducamp
/site.py
555
3.640625
4
choix = ['yes','no'] print('Bonjour nous vous souhaitons la bienvenue chez LEONALMEYER, vous avez besoin de évaluer un projet dinvestissement,markusrobot va soccuper de vous') a = input('voulez vous que markus soccupe de vous ?') if a == choix[0]: n = input ('combien années : ') c = input('montant des cash flow : ') i = input ('quel taux ? :') r = int(i)/100 m = int(n) A = int(c) ceof = (1-(1+r)**(-m))/r Actualisation = A * ceof print('votre séquence de',m,'cash flow valent actuellement',Actualisation) else: print('Au revoir Monsieur')
319f458e23753e214544b8236b835b081b1d63d7
ChrisPMohr/RussianRailroads
/game_state.py
4,939
3.75
4
import game_board import player_board class GameState(object): """A game state consists of one game board and 2 - 4 player boards""" def __init__(self, player_num, names): self.player_num = player_num self.game_board = game_board.GameBoard(player_num, self) colors = ['red', 'blue', 'green', 'yellow'] self.player_boards = [ player_board.PlayerBoard(player_num, names[i], colors[i]) for i in range(player_num)] self.turn_order = [i for i in range(player_num)] self.current_turn_index = -1 self.worker_replacement_order = [] self.next_turn_order = self.turn_order self.round = 0 self.all_players_passed = False @property def current_player(self): """The player board of the current player""" return self.player_boards[self.turn_order[self.current_turn_index]] def next_round(self): """Finished the current round and resets the board for the next one. """ self.turn_order = self.next_turn_order self.round += 1 for player in self.player_boards: player.reset_board() self.game_board.start_round() self.current_turn_index = -1 self.all_players_passed = False def next_player(self, start=-1): """Returns the index of the next player to move""" if not self.all_players_passed: original_index = self.current_turn_index self.current_turn_index += 1 # Loop through players in player order, skipping # players who passed if self.current_turn_index >= len(self.turn_order): self.current_turn_index = 0 if start >= -1 and self.current_turn_index == start: # Everyone has passed self.all_players_passed = True # Set next turn order self.set_next_turn_order() # Generate order for moving pieces off of turn order spaces self.set_worker_replacement_order() return self.next_player() elif not self.current_player.passed: return self.turn_order[self.current_turn_index] else: return self.next_player( start if start >= 0 else original_index) else: if self.worker_replacement_order: return self.worker_replacement_order.pop(0) else: return -1 def player_passes(self): """Sets a player as having passed the round and returns the index of the next player to move """ self.current_player.passed = True return self.next_player() def set_next_turn_order(self): """Set the turn order for next round""" # Find the occupants of the turn order spaces first_space = game_board.TurnOrderActionSpace.all_spaces.get(0) second_space = game_board.TurnOrderActionSpace.all_spaces.get(1) # Modify the turn order next_turn_order = list(self.turn_order) # first space player if first_space.occupants: index = self.occupant_player_index(first_space.occupants) next_turn_order.remove(index) next_turn_order.insert(0, index) # second space player if second_space and second_space.occupants: index = self.occupant_player_index(second_space.occupants) if not first_space.occupants and self.turn_order[0] == index: # Special case if the first player is the only one to # change the player order, their position doesn't get worse pass else: next_turn_order.remove(index) next_turn_order.insert(1, index) self.next_turn_order = next_turn_order def set_worker_replacement_order(self): """Set the order of players to move their pieces off the turn selection spaces """ turn_order_spaces = [ (space, ordinal) for ordinal, space in game_board.TurnOrderActionSpace.all_spaces.items()] turn_order_spaces = sorted( turn_order_spaces, key=lambda x: x[1], reverse=True) self.worker_replacement_order = [ self.occupant_player_index(space.occupants) for space, ordinal in turn_order_spaces if self.occupant_player_index(space.occupants) is not None] def player_index_with_color(self, color): """Returns the index of the player with the given color""" for i, player in enumerate(self.player_boards): if player.color == color: return i return -1 def occupant_player_index(self, occupants): if occupants: color = occupants[0][1] return self.player_index_with_color(color)
2f6245f22c6713e2a614c9e028412e486f779b8e
EtienneBrJ/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/9-print_last_digit.py
143
3.8125
4
#!/usr/bin/python3 def print_last_digit(n): if n < 0: n = -n last_dig = n % 10 print(last_dig, end='') return last_dig
dae268110d36954ffc465c845627cc7c0589a515
s-nilesh/Leetcode-May2020-Challenge
/26-ContiguousArray.py
1,603
3.78125
4
#PROBLEM # Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. # Example 1: # Input: [0,1] # Output: 2 # Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. # Example 2: # Input: [0,1,0] # Output: 2 # Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. # Note: The length of the given binary array will not exceed 50,000. #SOLUTION-1 class Solution: def findMaxLength(self, nums: List[int]) -> int: result, count = 0, 0 lookup = {0: -1} for i, num in enumerate(nums): count += 1 if num == 1 else -1 if count in lookup: result = max(result, i - lookup[count]) else: lookup[count] = i return result #SOLUTION-2 from collections import Counter class Solution: def findMaxLength(self, nums: List[int]) -> int: if len(nums)<=1: return 0 max_len = 0 counter = Counter(nums) max_possible_len = (counter[min(counter)]*2) for i in range(len(nums)-1): # if max_len >= (counter[min(counter)]*2): # break j = i+1 while j<len(nums) and (max_len < max_possible_len): # for j in range(i+1,len(nums)): # print(nums[i:j+1]) count = Counter(nums[i:j+1]) if (count[0] == count[1]) and (len(nums[i:j+1])>max_len): max_len = len(nums[i:j+1]) j += 1 return max_len
a3a40441b92225c6879060a589f17dfd06ed8c2b
techrabbit58/LeetCode30DaysMay2020Challenge
/main/solutions/number_complement.py
2,431
4.03125
4
""" LeetCode 30-Day Challenge, May 2020, Week 1, Day 4 Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary. For a given number N in base-10, return the complement of it's binary representation as a base-10 integer. Example 3: Input: 7 Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. Example 4: Input: 10 Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. N o t e s 1. The given integer is guaranteed to fit within the range of a 32-bit signed integer. 2. You could assume no leading zero bit in the integer’s binary representation. """ def findComplement(num: int) -> int: return int(''.join([str((int(b) + 1) % 2) for b in bin(num)[2:]]), 2) def findComplement_v2(num: int) -> int: if not num: return 1 return ~num & sum([2 ** b for b in reversed(range((num).bit_length()))]) def findComplement_v3(num: int) -> int: return ~num & max(1, 2 ** (num).bit_length() - 1) def findComplement_v4(num: int) -> int: """The lLeetCode solutions runner judges this to be the fastest of all four.""" return num ^ max(1, 2 ** (num).bit_length() - 1) if __name__ == '__main__': print(findComplement_v4(5), 2) print(findComplement_v4(1), 0) print(findComplement_v4(7), 0) print(findComplement_v4(10), 5) print(findComplement_v4(0), 1) print(findComplement_v3(0), 1) print(findComplement_v2(0), 1) print(findComplement(0), 1) # last line of code
cabe6422b7dc84ea4af16db60a4504ce84e3028d
BENMASTERSOFT/python-2020
/numbers.py
486
3.671875
4
import os os.system('clear') name = "Ben Mastersoft" ############################################ # Data Types # Strings # Numbers # Lists # Tuple # Dictionaries # Boolean ########################################## num = 10 num1 = 10.25 print(num) print(float(num)) print(int(num1)) #Maths print("7+2 is " + str(7+2)) print("7-2 is " + str(7-2)) print("7*+2 is " + str(7*2)) print("7/2 is " + str(7/2)) print("7%2 is " + str(7%2)) print("5**2 is " + str(5**2)) print("5**3 is " + str(5**3))
f6bd7e1558cba48387c25c44431cc5049454c890
yijiantao/WorkSpace
/LeetCode Algorithms/code/83.删除排序链表中的重复元素.py
618
3.578125
4
# # @lc app=leetcode.cn id=83 lang=python3 # # [83] 删除排序链表中的重复元素 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: list_set = [] p = ListNode(None) p.next = head while p.next: if p.next.val not in list_set: list_set.append(p.next.val) p = p.next else: p.next = p.next.next return head # @lc code=end
12610d03d1a3dcda97b72efdc50565c862dcae78
rabiatuylek/Python
/for1.py
1,620
3.890625
4
#sehirler = ["adana","ankara","ardahan","amasya","edirne"] #for sehir in sehirler: # print(sehir) #i = 0 #while i<len(sehirler): # sehir = sehirler[i] # print(sehir) # i = i + 1 # dizi icerisinde yer alan elemanların ismi icerisinde "m" harfi bulunanların yazdırılması #sehirler = ["adana","ankara","ardahan","amasya","edirne"] #for sehir in sehirler: # if("m" in sehir): # print(sehir,"bu sehir m harfi içeriyor") # else: # print(sehir,"bu sehir içinde m harfi yok") # dısarıdan girilen metni harf harf alt alta yazdırınız #metin = input("lutfen kelime giriniz") #for a in metin: # print(a) # 10 ile 20 arasındaki asal sayıları yazdır #a = range(10,20) #for sayi in a: # if sayi>=10 and sayi<=20: # if sayi % 2 == 0: # print(sayi,"asal degil") # elif sayi % 3 == 0: # print(sayi,"asal degil") # elif sayi % 5 == 0: # print(sayi,"asal degil") # elif sayi % 7 == 0: # print(sayi,"asal degil") # else: # print(sayi,"asal sayıdır") #print(a) #sifrenin 3 defa yanlis girilmesi dahiline kullanıcıyı uyaran uygulama for i in range(3): parola = input("sifre gir") if i == 2: # sifre 3 defa yanlis girildi. print("sifrenizi 3 defa yanlıs giridiniz") elif not parola: # alan boş gecilirse print("alan bos gecemez") elif len(parola) in range (3,8): # parola 3 ile 8 karakter aralıgında olmalı print("parolanız:",parola,"olarak belirlenmistir") else: print("ya yuh hala dogru sifreni girmedin mi")
c8550cef63bc559f9f0e8fa7a9a058b4b270b3d3
DineshNadar95/Coding-stuff
/CodeSignal/move_diagonally.py
1,583
3.75
4
def move_diagonally(cols, rows, home_location, mall_location): x, y = home_location end_x, end_y = mall_location grid = [[set() for _ in range(cols)] for _ in range(rows)] dx, dy = 1, 1 direction_mapping = { (1, 1): 0, (-1, 1): 1, (1, -1): 2, (-1, -1): 3 } count = 0 while True: grid[x][y].add(direction_mapping[(dx, dy)]) print("Adding new dir ",grid[x][y]) if x == end_x and y == end_y: return count # print("old:", x, y) # print("delta:", dx, dy) new_x, new_y = x + dx, y + dy # print("updated:", new_x, new_y) count += 1 if (new_x > rows - 1 or new_x < 0) and (new_y > cols - 1 or new_y < 0): # print("-- corner") dx *= -1 dy *= -1 elif new_x > rows - 1 or new_x < 0: # print("--x breach") dx *= -1 elif new_y > cols - 1 or new_y < 0: # print("--y breach") dy *= -1 else: x, y = new_x, new_y if direction_mapping[(dx, dy)] in grid[x][y]: return -1 # test_inputs = [] # test_inputs.append((5, 5, 2, 1, 1, 2)) # test_inputs.append((5, 3, (2, 0), (3, 2))) print(move_diagonally(5, 5, (2, 1), (1, 2))) print(move_diagonally(5, 3, (2, 0), (3, 2))) print(move_diagonally(5, 2, (0, 0), (0, 1))) print(move_diagonally(5, 2, (0, 0), (0, 4))) print(move_diagonally(5, 2, (1, 0), (1, 4))) #print(move_diagonally(2, 5, (0, 0), (4, 1))) #print(move_diagonally(2, 5, (0, 0), (4, 0)))
2ff333ae0026130d43c1f2cf7c91f8a6e31bdc68
whatnowbrowncow/projects
/game5.py
3,294
4
4
def game_3(): print """ Welcome to the final round of your Epic quest...... A FIGHT TO THE DEATH!!!!!!! """ ready = raw_input("Are you ready to play? yes - I'm ready let's go / no - I'm scared!").lower() if ready == "yes": print """ THEN PREPARE TO DIE!!!! """ elif ready == "no": print """ There is no turning back now, PREPARE TO DIE!!!! """ else: print """ I see the fear has taken away your ability to answer my question, it matters not, PREPARE TO DIE!!!!!! """ death_match() def death_match(): inventory = [] Battleaxe = {'damage':35, 'protection':5,'healing':0, 'cooling':0, 'sacrificial_lamb':0,} Shield = {'damage':7, 'protection':25,'healing':0, 'cooling':5, 'sacrificial_lamb':0,} Armour = {'damage':0, 'protection':30,'healing':0, 'cooling':10, 'sacrificial_lamb':0,} Healingpotion = {'damage':0, 'protection':0,'healing':50, 'cooling':0, 'burning':0, 'sacrificial_lamb':0,} Fire = {'damage':25, 'protection':0,'healing':0, 'cooling':0, 'sacrificial_lamb':0,} Water = {'damage':0, 'protection':0,'healing':0, 'cooling':25, 'sacrificial_lamb':0,} DonaldTrump = {'damage':0, 'protection':0,'healing':0, 'cooling':0, 'sacrificial_lamb':100,} options = Battleaxe print """You may choose 3 items from the following list to help you in battle, choose wisely!: 1 - Battleaxe 2 - Shield 3 - Armour 4 - Healing potion 5 - fire 6 - water 7 - Donald Trump """ item_1 = raw_input("What is your first choice? 1-10:- ") if item_1 == "1": item_1 = Battleaxe elif item_1 == "2": item_1 = Shield elif item_1 == "3": item_1 = Armour elif item_1 == "4": item_1 = Healingpotion elif item_1 == "5": item_1 = Fire elif item_1 == "6": item_1 = Water elif item_1 == "7": item_1 = DonaldTrump print dict(item_1) print inventory.append [item_1] print print item_1 + " has been added to your inventory" print item_2 = raw_input("What is your first choice? 1-10:- ") print while len(inventory) < 2: if item_2 == item_1: print "You fool, you have already chosen this item! You need to pick again" item_2 = raw_input("I ask you again, What is your second choice? 1-10:- ") else: print "you have chosen: "+ options[item_2] inventory.append(options[item_2]) print print options[item_2] + " has been added to your inventory" print item_3 = raw_input("What is your third choice? 1-10:- ") while len(inventory) < 3: print if item_3 == item_1: print "You fool, you have already chosen this item! You need to pick again" item_3 = raw_input("I ask you again, What is your third choice? 1-10:- ") elif item_3 == item_2: print "You fool, you have already chosen this item! You need to pick again" item_3 = raw_input("I ask you again, What is your third choice? 1-10:- ") else: print "you have chosen: "+ options[item_3] inventory.append(options[item_3]) print print options[item_3] + " has been added to your inventory" print print "Your inventory contains" for item in inventory: print item print print """ It is time to proceed. Good Luck (You'll need it!)""" game_3()
0a0430b4871785f3e16c401b0ea4dcba11775fe5
neham0521/CS-1
/Check point 1/monkey_trouble.py
446
4.09375
4
while True: Monkey_a= input('Hey Monkey_a: Are you smiling(Y/N)').lower() if Monkey_a not in ('y','n'): print('Please enter only Y or N') continue else: break while True: Monkey_b = input('Hey Monkey_b: Are you smiling(Y/N)').lower() if Monkey_b not in ('y','n'): print('Please enter only Y or N') continue else: break if (Monkey_a == Monkey_b): print('You are in trouble!') else: print('You are safe!')
2d5d31cae9047383606f1dab0ab183e358856471
leemingeer/datastruct
/leetcode2.py
2,210
3.765625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None from functools import reduce class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ start0 = ListNode(0) node = start0 list1 = [] list2 = [] while True: list1.append(l1.val) if l1.next is not None: l1 = l1.next else: break while True: list2.append(l2.val) if l2.next is not None: l2 = l2.next else: break num1 = self.list2integer(list1[::-1]) num2 = self.list2integer(list2[::-1]) res = self.integer2list(num1 + num2, node) return start0.next def list2integer(self, list1): res = 0 for i in range(len(list1)): res = res * 10 + list1[i] return res def list2integer2(self, list1): return reduce(lambda x, y: x * 10 + y, list1) def integer2list(self, num, node): while True: next_node = ListNode(num % 10) node.next = next_node node = node.next num = num // 10 if num == 0: break # class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ start = ListNode(0) node = start carry = 0 while(l1 or l2): val1 = l1.val if l1 else 0 val2 = l2.val if l2 else 0 s = val1 + val2 + carry carry = s // 10 # keep the value in the next loop val = s % 10 if l1: l1 = l1.next if l2: l2 = l2.next node.next = ListNode(val) node = node.next if carry: node.next = ListNode(1) return start.next s = Solution() l1 = [2, 4 ,3] l2 = [5, 6, 4] #print s.addTwoNumbers(l1, l2) print s.list2integer2(l2)
94b2a5fd51070a6e6133dfdf614d2293f99a9db6
gtripti/PythonBasics
/Basics/Lists.py
839
4.15625
4
my_list= [1,2,3] print(my_list) my_list =['HELLO' , 100 , 2.3] print(my_list) # Check Length print(len(my_list)) my_list= ['one' , 'two' , 'three'] # Indexing print(my_list[0]) # Slicing print(my_list[1:]) another_list = ['four' , 'five'] print(my_list + another_list) new_list = my_list + another_list print(new_list) # Mutable new_list[0] = "ONE" print(new_list) # Methods # 1. Append to list new_list.append('six') print(new_list) # 2.Remove from end of list popped_item = new_list.pop() print(popped_item) print(new_list) # 3.Remove from specific index print(new_list.pop(0)) print(new_list) new_list = ['a','e','x','b','c'] num_list = [4,1,8,3] # 4.Sort the list -- doesn't return anything new_list.sort() print(new_list) num_list.sort() print(num_list) # Reverse a list num_list.reverse() print(num_list)
6feacd1794222455acfb5ae0cf31e4a470879e87
Barthelemy-Drabczuk/reversi
/Pawn.py
376
3.734375
4
""" Classe qui représente un pion de Reversi """ class Pawn: # True == White # False == Black def __init__(self, color, x, y): self.color = color self.x = x self.y = y def flip(self): self.color = not self.color def __str__(self): return str(self.color) def __repr__(self): return str(self.color)
1e6c1bdc4f587cac1e1f0485b5a78d71d5967e93
poojamadan96/code
/Inheritance/superExample.py
512
4.21875
4
class base: def __init__(self): super().__init__() print("base") class subchild: def __init__(self): print("Sub child") class superchild(base,subchild): # vase is parent class , subchild is child class def __init__(self): super().__init__() print("HEllo") ob=superchild() # First It will go to superchild will see a parent which is base classsuper so will reach to base class #there again is a super so will go to subchild and print that later base then will come to hello Sub child base HEllo
97fb36516feb5f1362ab79c82f7798b7a1a0db54
SHIVAPRASAD96/flask-python
/NewProject/python_youtube/continue and break.py
353
3.984375
4
print("continue and break"); magicnumber=26; #this program finds a magci number depending on what you assign to the magicnumber variable print("ramessh"+"anchan"+"jump" +"Of the roof"); for n in range(10,30): if n is magicnumber: print("Hey awesome the magic number is : ",n); break; else: print(n); continue;
195c8f32da9cc851b1b8b57500634a6b7e45a3fa
Poobalan1210/data-structures-python
/main.py
2,042
3.984375
4
class Node: def __init__(self,data=None,next=None): self.data=data self.next=next class Linkedlist: def __init__(self): self.head=None def insertatbeginning(self,data): node=Node(data,self.head) self.head=node return def insertatlast(self,data): if self.head is None: node =Node(data,None) return itr=self.head while itr.next: itr=itr.next itr.next=Node(data,None) return def length(self): count = 0 itr=self.head while itr: count += 1 itr=itr.next return count def remove(self,index): if index <0 and index > l.length(): raise Exception("List is empty") if index == 0: self.head =self.head.next return count=0 itr=self.head while itr: if count == index -1: itr.next = itr.next.next break itr=itr.next count += 1 def print(self): if self.head is None: print("list is empty") return itr=self.head lstr="" while itr: lstr+=str(itr.data)+"-->" itr=itr.next if len(lstr) >0: print(lstr) else: print("empty string") def removeval(self,data): if self.head is None: raise Exception("empty list") itr1 = self.head itr2 = self.head if itr1.data == data: self.head=itr1.next return while itr1: itr1=itr1.next if itr1.data == data: itr2.next = itr1.next break else: itr2=itr2.next if __name__ == '__main__': l=Linkedlist() l.insertatbeginning(5) l.insertatbeginning(6) l.insertatlast(10) l.insertatlast(11) l.print() l.remove(2) l.print() l.removeval(11) l.print()
d11c6afeff1571e3ae8830a0e676379cb7244559
balajich/python-crash-course
/beginners/05_functions/05_function_with_default_arguments.py
402
3.953125
4
''' Function with default arguments ''' def hello(message='Welcome to python tutorial'): """ Function with default arguments :param message: :return: """ print(message) if __name__ == '__main__': # Calling function with argument hello('Hello world') # Calling function with our argument # message formal argument is assigned with default value hello()
4cd4b0686439a3a1e14120d90ef7ab2b3f3474ea
sti320a/atcoder
/b0901.py
280
3.640625
4
import math x1, y1, x2, y2 = map(int, input().split()) #2点間の距離を求める def getDistance(x_1, y_1, x_2, y_2): result2 = pow(x_2 - x_1, 2) + pow(y_2 - y_1, 2) result = math.sqrt(result2) return int(result) #1辺の長さ L = getDistance(x1, y1, x2, y2)
20a6135c5f5873897127cc028a97e8d58fbd9ea7
muxiaofefei/LearningRecords
/python/drawSnake.py
486
4.03125
4
# 绘制Python import turtle def drawSnake(rad, angle, len, neckrad): for i in range(len): turtle.circle(rad,angle) turtle.circle(-rad,angle) turtle.circle(rad,angle/2) turtle.fd(rad) turtle.circle(neckrad+1,180) turtle.fd(rad*2/3) def main(): turtle.setup(1300,800,0,0) #设置启动窗口的宽高和在屏幕的位置 pythonsize = 30 turtle.pensize(pythonsize) #绘制大小 turtle.pencolor("blue") #颜色 turtle.seth(-40) drawSnake(40,80,5,pythonsize/2) main()
1275170992bf7e96f800574233fb3afd48cdf27a
Rohanarekatla/python-basics
/#IMPORT MATH.py
1,171
4.34375
4
import math #for using the math functions in python we need import them first ''' we can also use only the specefic math functions by : from math import sqrt,pow ''' ''' 1.pow() 2.abs() 3.floor() 4.ceil() 5.pi() 6.max() 7.min() ''' x = pow(2,3) print(x) #return the value of 2 power 3 print("___________________\n") print(math.floor(2.5)) #return the floor value(preceeding) of 2.5(simple mark : floor means down so it return preceeding value) print("___________________\n") print(math.ceil(2.5)) #return the ceil value (succeding) of 2.5 (simple mark : ceil means up (ceiling) so it return succeding value ) print("___________________\n") a = math.pi print(a) #return the exact value of pi print("___________________\n") print(min(3,4,5,8)) #return the minimum value (least value) print("___________________\n") print(max(2,4,7,9)) #return the maximum value (greater value) print("___________________\n") print(abs(-2.55)) # retun absolute (positive) value of the number
3446eb35ce2241a6ec4b50940a9db9bee80a0432
bryanh210/Algorithm_Data-Structure
/2019/search_in_rotated_and_sorted_array.py
1,725
4.40625
4
Find search and rotated and sorted array 3/4/19 Whiteboarding. Search in a rotated and sorted array LOGIC: We have to find which part of the array is sorted, and which is not, and whether the target is in the sorted portion or not Ex: [6,8,11,15,17,4,5], 4 min mid max If arr[min] < arr[mid] -> this part of array is sorted. Used binarySearch to find target if target is within range Then we know arr[mid] to arr[max] is not sorted. [15,17,3,5,8,11], 15 L M H [15,17,3,5,8,11] 15 L m H [6,8,11,15,17,3,5], 3 L M H L M H L M H low = 0 high = len - 1 calculate M if mid === target return mid if mid < high && high <= target Binary search if low < mid && low <= target Binary search else low = mid set low and high pointers low pointer starts at 0 high pointer starts at the last index of the array while low pointer is less than high pointer: find mid index = (low + high) / 2 if element at mid index is equal to target return mid index else if element at mid index > element at low index: If low = mid else element at mid index is larger than element at If high = mid 0 1 2 3 4 5 6 [6,8,11,15,17,3,5], 3 Low = 0 (6) High = 6 (5) Mid = 3 (15) def find_rotated(arr): Low = 0 High = len(arr) -1 rotated_helper(arr, low, high) Def rotated_helper(arr, low, high): Mid = low + ((high - low) // 2) If arr[low] < target and arr[mid] > target: binary_search(arr, low, mid) elif arr[mid] < target and arr[high] > target: binary_search(arr, mid, high) elif arr[low] < arr[mid]: rotated_helper(arr, mid, high) else: rotated_helper(arr, low, mid)
6554303516d08fee92aae2bfa67cad27c42e0481
Dexmo/pypy
/Class/battery.py
320
3.796875
4
class Battery: """ Simple class with battery model""" def __init__(self, battery_size=70): self.battery_size = battery_size def describe_battery(self): print("This car has battery with " + str(self.battery_size) + "kWh.") my_battery = Battery(battery_size=60) my_battery.describe_battery()
4246f91a9de85de9f4a4b82369f2d3a92711e6ee
DongIk-Jang/Python_Algorithm_Interview
/10_deque_priorityqueue/347_top_k_frequent_elements.py
322
3.703125
4
from collections import Counter def topKFrequent(nums, k): cnt = Counter() for num in nums: cnt[num] += 1 print(cnt) most_common = cnt.most_common(k) answer = list() for i, j in most_common: answer.append(i) return answer nums = [1,1,1,2,2,3] k = 2 print(topKFrequent(nums, k))
3b052cc6516c7d2978b75b041b401ddb06269324
Abinash04/Python
/basic/2017/2.py
500
3.78125
4
#By considering the terms in the Fibonacci sequence whose values do not exceed #four million, find the sum of the even-valued terms. def fibonacci(n): fib=[0,1] my_list=[] for i in range(2,n+1): fib.append(fib[-1]+fib[-2]) for i in range(len(fib)): if (fib[i] <= 4000000) and (fib[i]%2==0): my_list.append(fib[i]) print my_list total=sum(my_list) print total m = input("enter a value for fibonacci series\n") series=fibonacci(m)
3b82f1a3c4a4ce036f6eeb3634742c45280c267c
gengyu-mamba/Python3
/sample/basic/loop.py
638
3.8125
4
# 循环语句 # break语句 从循环内跳出(必须和if连用) # continue语句 跳跃到循环开头(必须和if连用) # pass语句 什么都不做 # else语句 用在循环语句后,如果正常结束循环就执行else语句 loop = ['pass', 'continue', 'break', 'python'] for letter in loop: if letter == 'pass': print(letter) pass elif letter == 'continue': print(letter) continue elif letter == 'break': print(letter) break else: print(letter) count = 0 while count < 10: print('i love C/C++') count += 1 else: print('i really love python')
921a6e23dad0c6f501cbec9896afca008b7feadb
cengiz1erg/HackerRank_Solutions
/Regex/DetectHTMLTags.py
448
3.5
4
import re input_number = int(input()) #take input number from user input_list = [] #list of strings of input tags captured_tags = [] for _ in range(input_number): input_list.append(input()) #take input tags for x in range(input_number): p = re.findall(r'<\s*(\w+)',input_list[x]) #return list of strings captured_tags = captured_tags + p #concat lists a = list(set(captured_tags)) #list of distinct strings a.sort() print(";".join(a))
d37934c4aca0f7a3714fdb7cbca2fee7afc5c7bb
kt0755/tensorflow_work
/cnn.py
3,687
3.578125
4
##### MNIST Classifier using CNN import tensorflow as tf # download MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # define CNN model def build_CNN_classifier(x): # MNIST data를 3 dimensional 형태로 reshape합니다. # MNIST data는 grayscale img 기 때문에 3번째차원(컬러채널)의 값은 1 x_image = tf.reshape(x, [-1, 28, 28, 1]) ###### 1st Conv Layer # 32 Filters (5x5 Kernel Size) # 28x28x1 -> 28x28x32 # relu( conv(W) + B ) W_conv1 = tf.Variable(tf.truncated_normal(shape=[5, 5, 1, 32], stddev=5e-2)) b_conv1 = tf.Variable(tf.constant(0.1, shape=[32])) h_conv1 = tf.nn.relu(tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1) # 1st Pooling Layer # Max Pooling을 이용해서 image 의 size 를 1/2로 downsample # 28x28x32 -> 14x14x32 h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') ###### 2nd Conv Layer # 64 Filters (5x5 Kernel Size) # 14x14x32 -> 14x14x64 W_conv2 = tf.Variable(tf.truncated_normal(shape=[5, 5, 32, 64], stddev=5e-2)) b_conv2 = tf.Variable(tf.constant(0.1, shape=[64])) h_conv2 = tf.nn.relu(tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], padding='SAME') + b_conv2) # 2nd Pooling Layer # Max Pooling을 이용해서 image의 size를 1/2로 downsample합니다. # 14x14x64 -> 7x7x64 h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') ##### FC Layer # 7x7 size 를 가진 64개의 activation map을 1024개의 특징들로 변환 # 7x7x64(3136) -> 1024 W_fc1 = tf.Variable(tf.truncated_normal(shape=[7 * 7 * 64, 1024], stddev=5e-2)) b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024])) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # Output Layer ... softmax # 1024개의 특징들(feature)을 10개의 class-one-hot encoding으로 표현된 숫자 0~9-로 변환 # 1024 -> 10 W_output = tf.Variable(tf.truncated_normal(shape=[1024, 10], stddev=5e-2)) b_output = tf.Variable(tf.constant(0.1, shape=[10])) logits = tf.matmul(h_fc1, W_output) + b_output y_pred = tf.nn.softmax(logits) return y_pred, logits # define placeholders to take input, output data x = tf.placeholder(tf.float32, shape=[None, 784]) y = tf.placeholder(tf.float32, shape=[None, 10]) # declare CNN y_pred, logits = build_CNN_classifier(x) # Cross Entropy를 loss function으로 정의하고 optimizer 를 define loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits)) train_step = tf.train.AdamOptimizer(1e-4).minimize(loss) # accuracy 계산하는 operation 추가 correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # session with tf.Session() as sess: # initialize all variables sess.run(tf.global_variables_initializer()) # 10000 Step만큼 optimize 를 수행 for i in range(10000): # 50개씩 MNIST data를 load batch = mnist.train.next_batch(50) # 100 Step마다 training dataset 에 대한 accuracy 를 print if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict={x: batch[0], y: batch[1]}) print("반복(Epoch): %d, 트레이닝 데이터 정확도: %f" % (i, train_accuracy)) # Optimizer 를 실행해 parameters 를 한스텝 update sess.run([train_step], feed_dict={x: batch[0], y: batch[1]}) # print test data accuracy print("test data accuracy : %f" % accuracy.eval(feed_dict={x: mnist.test.images, y: mnist.test.labels}))
7a6aff971c523696727afb286003439f399bee01
adriene-tien/ProblemSolving
/LeetCode/Easy/ContainsDuplicate.py
740
3.75
4
# LeetCode Easy # Contains Duplicate Question # O(n) time complexity, worst case is when all numbers are distinct (infinite numbers) # O(n) space complexity, worst case is when all numbers are distinct (infinite numbers, new dictionary entry each time) # Faster than 93% of other submissions, but use of dictionary increases space complexity. # If I were to use a nested for loop instead, it removes the need for as much space but increases time to O(n^2). class Solution: def containsDuplicate(self, nums: List[int]) -> bool: int_dict = {} for i in range(0, len(nums)): if nums[i] not in int_dict: int_dict[nums[i]] = 1 else: return True return False
0d8da24f6cd576f624635fa4ad8c71d8f7384568
CodevEnsenada/actividades
/alumnos/Perla/Actividades martes/actividad 1.2.py
461
3.796875
4
from random import randint minumero = randint(1,15) #genero mi numero print(minumero) #verifico mi numero intentos = 1 numero = int(input("adivina mi número, entre 1 y 15: ")) while numero != minumero: if numero > minumero: numero = int(input("mi número es menor, inténtalo de nuevo:")) else: numero = int(input("mi número es mayor, inténtalo de nuevo:")) intentos = intentos + 1 print("adivinaste! en el intento: " + str(intentos))
e45869eb64409366f129b110d2a0daba5fc8c781
miltonjdaz/learning_py
/Python_Practice.py/Section_8/S8_Rep1.py
276
4.15625
4
""" Section 8 Rep 1 """ # Nth fibonacci with loop def main(): n = int(input("The value of n: ")) curr, prev = 1, 1 for i in range(n-2): curr, prev = curr + prev, curr print("The nth Fibonacci number is", curr) if __name__ == '__main__': main()
269890b65715a16aa79763ccf33f213ea676f17b
132-cabdelmalek/Programming11
/CREATE IT YOURSELF.py
1,337
4.0625
4
from turtle import* def draw(do, val): do = do.upper() if do == 'F': forward(val) elif do == 'B': backward(val) elif do == 'L': left(val) elif do == 'R': right(val) elif do == 'U': penup() elif do == 'D': pendown() elif do == 'N': reset() else: print('Unknown Command') def str_art(program): cmd_list = program.split('-') for command in cmd_list: cmd_len = len(command) if cmd_len == 0: continue cmd_type = command[0] num = 0 if cmd_len > 1: num_string = command[1:] num = int(num_string) print(command, ':', cmd_type, num) draw(cmd_type, num) instructions = '''Enter a program for the turtle(Start with N-): eg. N-F100-R45-U-F100-L45-D-F100-R90-B50 N = New drawing U/D = Pen up/Pen down F(intergers) = Forward(intergers)steps B(intergers) = Backward(intergers)steps L(intergers) = Left turn(intergers)degrees R(intergers) = Right turn(intergers)degrees''' screen = getscreen() while True: t_program = screen.textinput('Drawing Machine', instructions) print(t_program) if t_program == None or t_program.upper() == 'END': break str_art(t_program)[/quote]
0955ac11fe79b08411f8864676a560aab917cc10
priteshmehta/leetcode
/group_anagrams.py
912
3.546875
4
def groupAnagrams(strs): def grp_annagram(sub_str): anagram_word1 = {} for s in sub_str: key = "".join(sorted(s)) try: anagram_word1[key].append(s) except KeyError: anagram_word1[key] = [s] return anagram_word1.values() n = len(strs) if n == 0: return [[]] elif n == 1: return [strs] else: word_dict = {} for s in strs: try: word_dict[len(s)].append(s) except KeyError: word_dict[len(s)] = [s] anagram_word = [] for key in word_dict.keys(): tmp_list = grp_annagram(word_dict[key]) anagram_word.extend(tmp_list) print(anagram_word) return anagram_word groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
1f03091cbfd57ee3d4a7c9797a5b9c15fe2f2ba8
Rahulnavayath/ICTA-Full-Stack-project
/python/sringz.py
141
3.640625
4
a=raw_input("enter a string=") for i in a: #if i=="l": print a[:-1] print a[2] print a[0:3] print a[-1:] print a[::-1] break
ddd9037614f03ea6a7038376f053596814477215
LikeLionSCH/9th_ASSIGNMENT
/19_허유빈/session03/01.py
299
3.71875
4
import math n = int(input("숫자를 입력하세요 >> ")) hap = 1 print(str(n)+"! =", end=" ") for i in range (n, 0, -1) : hap = hap * i if i == 1: print(i, end="") else : print(i, end="x") print(" =", hap) # result = (math.factorial(n)) # print(n, "! =", result)