blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
1d8a5cca19a4d956624e0c0a479fea9d1f5ce0dc
jacobiand/crud
/checkout/cliente.py
3,603
3.53125
4
from banco import Banco class Usuarios(object): def __init__(self, idusuario=0, nome="", telefone="", email="", usuario="", senha=""): self.info = {} self.idusuario = idusuario self.nome = nome self.telefone = telefone self.email = email self.usuario = usuario self.senha = senha self.log = 0 def insertUser(self): banco = Banco() try: c = banco.conexao.cursor() aux = self.selectUser(self.usuario) if aux == "Select usuario sucesso - usuario nao existe": c.execute("insert into usuarios (nome, telefone, email, usuario, senha) values ('" + self.nome + "', '" + self.telefone + "', '" + self.email + "', '" + self.usuario + "', '" + self.senha + "' )") banco.conexao.commit() c.close() if aux == "Select usuario sucesso - usuario nao existe": return "Insert usuario sucesso" else: return "Insert usuario falha - usuario ja existe" except: return "Inser usuario falha - error" def updateUser(self): banco = Banco() try: c = banco.conexao.cursor() c.execute("update usuarios set nome = '" + self.nome + "', telefone = '" + self.telefone + "', email = '" + self.email + "', usuario = '" + self.usuario + "', senha = '" + self.senha + "' where usuario = '" + self.usuario + "'") banco.conexao.commit() c.close() return "Update usuario sucesso" except: return "Update usuario falha - error" def deleteUser(self): banco = Banco() try: c = banco.conexao.cursor() c.execute("delete from usuarios where usuario = '" + self.usuario + "'") banco.conexao.commit() c.close() return "Delete usuario sucesso" except: return "Delete usuario falha - error" def selectUser(self, usuario): banco = Banco() try: c = banco.conexao.cursor() c.execute("select * from usuarios where usuario = '" + usuario + "'") for linha in c: self.idusuario = linha[0] self.nome = linha[1] self.telefone = linha[2] self.email = linha[3] self.usuario = linha[4] self.senha = linha[5] c.close() if self.idusuario == 0: return "Select usuario sucesso - usuario nao existe" else: return "Select usuario sucesso - usuario ja existe" except: return "Select usuario falha - error" def autenticaUser(self, usuario, senha): banco = Banco() self.usuario = usuario self.senha = senha try: c = banco.conexao.cursor() c.execute("select * from usuarios where usuario = '" + self.usuario + "' and senha = '" + self.senha + "'") for linha in c: self.idusuario = linha[0] self.nome = linha[1] self.telefone = linha[2] self.email = linha[3] self.usuario = linha[4] self.senha = linha[5] c.close() if self.idusuario > 0: self.log = self.idusuario return "Autentica usuario sucesso" return "Autentica usuario falha - usuario não encontrado" except: return "Autentica usuario falha - error"
5eb47e99757132c9439bb56f513b07885f43f6f7
Salehzz/Information-Retrieval-Project
/heap-zipf-law/heap's_law.py
687
3.515625
4
#Heaps' law import matplotlib.pyplot import math file = open("myfile.txt",'r') wordkinds = 0 words = 0 # har 50 kalame tedadkalamatmotefavet = {} kalamat = [] for line in file: for word in line.split(): words = words + 1 if(word not in kalamat): kalamat.append(word) wordkinds = wordkinds + 1 if(words%50 == 0): tedadkalamatmotefavet[math.log(words)] = math.log(wordkinds) # kamtarshodan nesbat anvaee kalamat be tedad an ha ba afzayesh tol matn kinds = list(tedadkalamatmotefavet.values()) faravani = list(tedadkalamatmotefavet.keys()) matplotlib.pyplot.plot(faravani,kinds) matplotlib.pyplot.show()
efaa4394956df2168d4911b51c35b05446557baf
ailihong/program
/python/tool_linux/batch_rename.py
1,344
3.5625
4
#!/usr/bin/python3 #coding:utf8 ''' 批量重命名,会删除原来的文件!!!,使用前注意备份,命名会自动补零 ''' import os import argparse def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='batch rename') parser.add_argument('--dir', dest='dir', help='file directory',default='None') parser.add_argument('--name', dest='name', help='name',default='bai') parser.add_argument('--date', dest='date', help='date',default='None') parser.add_argument('--end', dest='end', help='file type',default='None') args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() if args.dir=='None' or args.date=='None' or args.end=='None': print('input,output directory or data is not given,please add --help') else: list_name=os.listdir(args.dir)#不是绝对路径,只是文件名file.file total=len(list_name) len_total=len('%d'%total) n=0 for name in list_name: n+=1 new_name = args.name + args.date + '_%0*d.'%(len_total,n) + args.end dir_temp = args.dir if args.dir[-1]!='/': dir_temp=args.dir+'/' os.rename(dir_temp + name,dir_temp +new_name) print('doing,%d/%d\n'%(n,total))
abb90aee0832b21144bdfe2a1bb095e4e63f3f3a
yoshi-d-24/nlp100
/ch01/09.py
461
3.703125
4
# coding: utf-8 import random def sort_word(word): head = word[0] tail = word[len(word) - 1] l = list(word)[1:len(word)-1] random.shuffle(l) return head + "".join(l) + tail str1 = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ." ret = [] for w in str1.split(" "): if len(w) <= 4: ret.append(w) else: ret.append(sort_word(w)) print(" ".join(ret))
6ebffaee162c491cc4f2289845a1bf7bbcd33604
flub78/python-tutorial
/examples/conditions.py
374
4.1875
4
#!/usr/bin/python # -*- coding:utf8 -* print ("Basic conditional instructions\n") def even(a): if ((a % 2) == 0): print (a, "is even") if (a == 0): print (a, " == 0") return True else: print (a, "is odd") return False even(5) even(6) even(0) bln = even(6) if bln: print ("6 is even") print ("bye")
0b035de8980eedcb6535cb20cff82207df5b3bd3
flub78/python-tutorial
/examples/using_leap_year_module.py
241
3.984375
4
#!/usr/bin/python # -*- coding:utf8 -* import os from package.leap import * year = input("type a year: ") print "year=" + str(year) if leap_year(year): print ("leap year") else: print ("non leap year") print "bye" os.system("pause")
0e531d7c0b4da023818f02265ab9e009420eaec6
flub78/python-tutorial
/examples/test_random.py
1,395
4.1875
4
#!/usr/bin/python # -*- coding:utf8 -* """ How to use unittest execution: python test_random.py or python -m unittest discover """ import random import unittest class RandomTest(unittest.TestCase): """ Test case for random """ def test_choice(self): """ given: a list when: selecting a random elt then: it belongs ot the list """ lst = list(range(10)) # print lst elt = random.choice(lst) # print "random elt = ", elt self.assertIn(elt, lst) self.assertFalse(elt % 4 == 0, "True quite often") def test_shuffle(self): """ given: a list when: shuffled then: it still contains the same elements likely in different order """ lst = list(range(10)) shuffled = list(lst) # deep copy random.shuffle(shuffled) # print "lst =", lst # print "shuffled= ", shuffled sorted = list(shuffled) sorted.sort() # print "sorted = ", sorted same_order = True i = 0 while i < 10: same_order = same_order and (lst[i] == shuffled[i]) i += 1 self.assertEqual(sorted, lst) self.assertFalse(same_order, "list are not in the same order after shuffling") if __name__ == '__main__': unittest.main()
fafd460a0cf1f0f38a9cd9055915a26067019c45
flub78/python-tutorial
/examples/whiteboard.py
627
3.859375
4
#!/usr/bin/python # -*- coding:utf8 -* print ("Object management") class Whiteboard: """ A whiteboard simulator""" def __init__(self): self._surface = "" def write(self, str): if self._surface != "": self._surface += "\n" self._surface += str def display(self): return self._surface def erase(self): self._surface = "" classroom = Whiteboard() classroom.write("Hello") classroom.write("World") print (classroom.display()) classroom.erase() classroom.write("Hello World") print (classroom.display()) print ("bye")
972ee98f17d2e3ce810881019e74ab6e838ca505
mrmaxformax/sw_transpose
/main.py
6,340
4.21875
4
# !/usr/bin/env python3 """ This is a script designed to find the longest word in the text file, transpose the letters and show the result. """ import argparse import concurrent.futures import logging import logging.handlers import os import re import sys from glob import glob logger = logging.getLogger(os.path.splitext(os.path.basename(sys.argv[0]))[0]) def file_reading(file_path: str) -> list: """ The method just reads the text file line by line and saves the result to the list of strings. One line is in one list element :param file_path: Path to the file the script needs to read. :return: the list of strings, extracted from the file. """ logger.debug("Current file path: {}".format(file_path)) err_msgs = {'file_format_err': "Error: not supported file format!"} try: if not file_path.endswith('.txt'): print(err_msgs['file_format_err']) logger.debug(err_msgs['file_format_err']) sys.exit(1) with open(file_path, "r") as f: lines = list(filter(None, (line.rstrip() for line in f))) return lines except IOError as e: logger.exception("%s", e) sys.exit(1) def transpose(string_list: list) -> None: """ The method finds the longest word, transposes it and prints Original and Transpose words on the screen. Script exits with code '1' if gets empty list. If some string has more than one word it would be split into substrings and analyzed separately. If for some reason the script can not find any word, it prints the appropriate message. If the list has multiple words with the same length and that length is maximum, first word in the list will be returned as the longest. There can be multiple ways how to handle that situation (like print all, print some message, ask the user what should be done) but because there is no info in the description (the bug in the docs :-)) I choose the simplest way. Output example: Original: abcde Transposed: edcba :param string_list: the list of strings for analisys :return: None """ logger.debug("Got the list for analysis: {}".format(string_list)) max_len_word: str = '' err_msgs = {"empty_list": "Error: the list of strings is empty!\n", "empty_string": 'There is only empty strings. Try to use another file.\n'} if len(string_list) == 0: print(err_msgs['empty_list']) logger.debug(err_msgs['empty_list']) sys.exit(1) for i in range(len(string_list)): list_item = string_list[i] list_item = list_item.strip() if list_item: # if we don't use regex we have a problem # if we use it we have more problems list_item = re.sub(r'([-])\1+', ' ', list_item) list_item = list_item.replace(' - ', ' ').replace('- ', ' ').replace(' -', ' ') list_item = re.sub(r'[^A-Za-z\- _]+', '', list_item) sub_list_item = list_item.split(' ') for single_word in sub_list_item: if single_word: single_word = single_word.replace(' ', '') if len(single_word) > len(max_len_word): max_len_word = single_word max_len_word_transposed: str = max_len_word[::-1] if max_len_word_transposed: conclusion = f"Original: {max_len_word}\nTransposed: {max_len_word_transposed}\n" else: conclusion = err_msgs['empty_string'] logger.debug(conclusion) print(conclusion) def parse_args(arguments: list): """ Parse arguments. Just parse. :param arguments: the list of arguments, added by the user from CLI :return: the namespace with arguments and values """ parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("-f", type=str, help="Path to the file") parser.add_argument("-p", type=str, help="Path to the folder with multiple files") g = parser.add_mutually_exclusive_group() g.add_argument("--debug", "-d", action="store_true", default=False, help="enable debugging mode") g.add_argument("--silent", "-s", action="store_true", default=False, help="enable silent (only critical) mode") args_parsed = parser.parse_args(arguments) if not (args_parsed.f or args_parsed.p): parser.error('No files requested, add -f file_name or -p path_to_files or --help for more info.') return args_parsed def setup_logging(opt) -> None: """ Logging configuration. :param opt: arguments from cli to choose what type of logging, silent/debug/none is active """ root = logging.getLogger("") root.setLevel(logging.WARNING) logger.setLevel(opt.debug and logging.DEBUG or logging.INFO) if not opt.silent: ch = logging.StreamHandler() ch.setFormatter(logging.Formatter("%(levelname)s [%(name)s]: %(message)s")) root.addHandler(ch) def main(path: str) -> None: """ The main method runs 'file reading' and 'transpose' methods. The entry point. :param path: path to the file """ logger.debug("Working with the words from '{}' file".format(path)) list_of_strings = file_reading(file_path=path) transpose(string_list=list_of_strings) if __name__ == "__main__": args = parse_args(sys.argv[1:]) setup_logging(opt=args) err_msgs = {"path_file": "Error: The path to file was sent! Change to folder path not file path.", "dir_not_exist": "Error: The directory does not exist"} if args.f: main(path=args.f) else: if os.path.isfile(args.p): print(err_msgs['path_file']) logger.debug(err_msgs['path_file']) sys.exit(1) # Get a list of files to process if not os.path.exists(args.p): raise OSError(err_msgs['dir_not_exist']) files = glob(args.p + "/**/*.txt", recursive=True) # Create a pool of processes. One for each CPU. with concurrent.futures.ProcessPoolExecutor() as executor: # Process the list of files, split the work across the process pool to use all CPUs zip(files, executor.map(main, files))
09fb8df1f7ffab63510f4ad80879fa70b387bcc0
leskeylevy/Passlock
/user_test.py
1,989
3.796875
4
import unittest from user import User class TestUser(unittest.TestCase): def setUp(self): self.new_user = User('leskey', 'levy', '[email protected]', 'Nairobi') def test_init(self): ''' test to see if object isproperly initialised ''' self.assertEqual(self.new_user.first_name, 'leskey') self.assertEqual(self.new_user.last_name, 'levy') self.assertEqual(self.new_user.email, '[email protected]') self.assertEqual(self.new_user.Password, 'Nairobi') def tearDown(self): User.user_list = [] def test_save_user(self): ''' test to see if User object is saved into the user list ''' self.new_user.save_user() self.assertEqual(len(User.user_list), 1) def test_save_multiple_user(self): ''' test save multiple users to checkif we can save multiple users ''' self.new_user.save_user() test_user = User('leskey', 'levy', '[email protected]', 'Nairobi') test_user.save_user() self.assertEqual(len(User.user_list), 2) def test_delete_user(self): ''' test to see if the delete method works well ''' self.new_user.save_user() test_user = User('leskey', 'levy', '[email protected]', 'Nairobi') test_user.save_user() self.new_user.delete_user() self.assertEqual(len(User.user_list), 1) def test_find_user_by_last_name(self): self.new_user.save_user() test_user = User('leskey', 'levy', '[email protected]', 'Nairobi') test_user.save_user() found_user = User.find_by_last_name('levy') self.assertEqual(found_user.last_name, test_user.last_name) def test_user_exists(self): self.new_user.save_user() test_user = User('leskey', 'levy', '[email protected]', 'Nairobi') test_user.save_user() user_exists = User.user_exists('levy') self.assertTrue(user_exists) if __name__ == '__main__': unittest.main()
ffeaf6b8e04e6d5fdf793008cad6d8a76588665e
WyattBlair77/barnsley_fern
/barnsley_fern/barnsley_fern.py
2,346
3.75
4
''' This is a script to construct the Barnsley fern, a fractal discovered by mathematician Michael Barnsley. Due to its 'flexible' nature, in that by changing the hyper-parameters you can construct different ferns, the structure is classified as a super-fractal! The script works by iteratively applying one of four linear functions, weighted randomly, to an initial starting position: pos = [x_n,y_n]. Function X is applied with probability p = hp['p'][X], and if we let a = hp['a'][X], b = hp['b][X]... etc., it looks like [[a,b],[c,d]].[x_n,y_n] + [e,f] = [x_n+1, y_n+1] Function 0 (hp[x][0]): the stem Function 1 (hp[x][1]): successively smaller leaflets Function 2 (hp[x][2]): largest left hand leaflet Function 3 (hp[x][3]): largest right hand leaflet Disclaimer: My code was heavily influenced by the code on the Wikipedia page regarding this subject ''' # imports import numpy as np import turtle import random pen = turtle.Turtle() pen.speed(10000) pen.color('green') pen.penup() # initial pos x = 0 y = 0 pos = np.array([x, y]) # hyper-params barnsley = { 'a': [0, 0.85, 0.20, -0.15], 'b': [0, 0.04, -0.26, 0.28], 'c': [0, -0.04, 0.23, 0.26], 'd': [0.16, 0.85, 0.22, 0.24], 'e': [0, 0, 0, 0], 'f': [0, 1.60, 1.60, 0.44], 'p': [0.01, 0.85, 0.07, 0.07]} mutant1 = { 'a': [0, 0.95, 0.035, -0.04], 'b': [0, 0.005, -0.2, 0.2], 'c': [0, -0.005, 0.16, 0.16], 'd': [0.25, 0.93, 0.04, 0.04], 'e': [0, -0.002, -0.09, 0.083], 'f': [-0.4, 0.5, 0.02, 0.12], 'p': [0.02, 0.84, 0.07, 0.07]} fern_choices = [barnsley, mutant1] hp = fern_choices[1] iterations = 100000 seed_list = [] for i, count in zip(range(len(hp['p'])), ['0', '1', '2', '3']): seed_list += (int(hp['p'][i] * 100) * [count]) for i in range(iterations): # actually draw things pen.goto(85 * pos[0], 57 * pos[1] - 275) # 57 is to scale the fern and -275 is to start the drawing from the bottom. pen.pendown() pen.dot() pen.penup() # initialize transformation and offset_vector seed = random.choice(seed_list) transformation = np.array([[hp['a'][int(seed)], hp['b'][int(seed)]], [hp['c'][int(seed)], hp['d'][int(seed)]]]) offset_vector = np.array([hp['e'][int(seed)], hp['f'][int(seed)]]) # apply iteration pos = np.matmul(transformation, pos) pos += offset_vector
9caae8fc3ec860ba78469871567a7f1f02338a35
craymontnicholls/Booklet-7
/Python (booklet 7)/Automatic-feeder/main.py
374
3.84375
4
#tells the user what hopper and how many times it needs to be dispensed def feeder(meal, amount): if meal == "Breakfast": print ("Hopper1," * amount) elif meal == "Lunch": print ("Hopper2," * amount) elif meal == "Dinner": print ("Hopper1 ,Hopper2 ," * amount) #the '* amount' makes the string repeat a set number of times feeder("Lunch", 100000000 )
897c6e06ef61bbd7899e46cfeedbd5e20108efe4
L30n4rd0/Lista1_FPA
/Questao4/Matrix.py
1,983
3.921875
4
# -*- coding: utf-8 -*- ''' Created on 22/03/2017 @author: leonardo ''' from random import randint def initMatrix(): i = 0 global biggertElement global smallerElement while (i < len(matrix)): j = 0 while (j < len(matrix[i])): # new random element of 0 to 99 newElement = randint(0, 99) # if new random element exists into matrix, other new element is generated while (containesElement(newElement)): newElement = randint(0, 99) # new random element inserted into matrix matrix[i][j] = newElement if (newElement > biggertElement): biggertElement = newElement if (newElement < smallerElement): smallerElement = newElement j += 1 i += 1 def containesElement(element): # this method check if element already exists in the matrix for column in matrix: if (column.count(element)): return True return False def normalizeElement(element): return float(element) / (biggertElement - smallerElement) def normalizeMatrix(): i = 0 while (i < len(matrix)): j = 0 while (j < len(matrix[i])): matrix[i][j] = normalizeElement(matrix[i][j]) j += 1 i += 1 def printMatrix(matrixParam): for row in range(len(matrixParam)): str_row = '' for column in range(len(matrixParam)): str_row = str_row + ' %.02f |' % matrixParam[row][column] print str_row ##### START EXECUTION ##### matrix = [[0 for x in range(5)] for y in range(5)] #create matrix 5x5 biggertElement = 0 smallerElement = 100 initMatrix() print 'Matriz inicial:' printMatrix(matrix) normalizeMatrix() print 'Matriz normalizada:' printMatrix(matrix)
8598c34ff9028f4ec30d01522ca051c7272dd6d6
bipika/DataStructureAlgo
/dsa/Stack.py
512
3.90625
4
class Stack: def __init__(self): self.stack=list() def push(self,value): self.stack.append(value) def pop(self): if len(self.stack)<1: print ("Stack is empty") else: self.stack.pop() def printStack(self): print(self.stack) stack=Stack() stack.push(10) stack.push(20) stack.push(30) stack.printStack() stack.pop() stack.printStack() stack.pop() stack.printStack() stack.pop() stack.printStack() stack.pop() stack.printStack()
21b5a5dd2a92917e3585c0bba2fcb77ea6e66376
Sgt-Forge/Coursera-ML-Python
/machine-learning-ex2/main.py
7,672
4.09375
4
""" Programming exercise two for Coursera's machine learning course. Run main.py to see output for Week 3's programming exercise #2 """ import os import numpy as np from matplotlib import pyplot from mpl_toolkits.mplot3d import Axes3D from typing import List from scipy import optimize from sigmoid import sigmoid from logistic_cost import cost_function from regularized_cost_function import regularized_cost_function def print_section_header(section: str) -> None: """Prints a section header to STDOUT Args: section: Name of the section to print Returns: None """ spacing = 50 blank_space = ' ' * ((spacing - len(section)) // 2 - 1) print('='*spacing) print('{}{}'.format(blank_space, section)) print('='*spacing) def visualize(X: List[List[float]], y: List[int]) -> None: """Plot data. Generates scatter plot Args: X: A matrix of scores for exams 1 and 2 for each student y: Binary vector to track admittance for each student Returns: None """ pos = y == 1 neg = y == 0 _fig = pyplot.figure() pyplot.plot(X[pos, 0], X[pos, 1], 'k+', lw=2, ms=10) pyplot.plot(X[neg, 0], X[neg, 1], 'ko', mfc='y', ms=8, mec='k', mew=1) pyplot.xlabel('Exam Score 1') pyplot.ylabel('Exam Score 2') pyplot.legend(['Admitted', 'Rejected']) def optimize_theta(cost_function, initial_theta, X, y, options={'maxiter': 400}): """Optimize theta parameters using a cost function and initial theta Args: cost_function: Cost function used to calculate error initial_theta: Starting values for theta parameters X: Input features y: Labels for training set Returns: """ res = optimize.minimize(cost_function, initial_theta, (X, y), jac=True, method='TNC', options=options) return res def plot_decision_boundary(theta, X, y): """Plot data and draw decision boundary with given theta parameters. Generates scatter plot with decision boundary. Args: visualize: Plotting function to create a scatter plot theta: Theta parameters for the decision boundary X: A matrix of scores for exams 1 and 2 for each student y: Binary vector to track admittance for each student Returns: None """ visualize(X[:, 1:3], y) ''' If you want to figure out _how_ to plot the decision boundary, you have to understand the following links: https://statinfer.com/203-5-2-decision-boundary-logistic-regression/ https://en.wikipedia.org/wiki/Logistic_regression Basically we have to plot the line when our probability is 0.5. You can recover the theta paremeters from the equation by calculating the odds of classifying 0.5 (yes, the literal definition of odds: {p / 1-p} ) ''' X_points = np.array([np.min(X[:, 1]), np.max(X[:, 1])]) y_points = (-1 / theta[2]) * (theta[1] * X_points + theta[0]) pyplot.plot(X_points, y_points) def predict(theta, X): """Make predictions for test set with trained theta parameters Args: theta: Trained theta parameters X: Test set Returns: array-like of predictions """ predictions = sigmoid(X.dot(theta)) >= 0.5 return predictions def map_features(X1, X2): """Maps two features to a 6 degree polynomial feature set Args: X: initial feature set without bias feature Returns: Mapped feature set with added bias feature """ degree = 6 if X1.ndim > 0: mapped_features = [np.ones(X1.shape[0])] else: mapped_features = [(np.ones(1))] for i in range(1, degree + 1): for j in range(i + 1): mapped_features.append((X1 ** (i - j)) * (X2 ** j)) if X1.ndim > 0: return np.stack(mapped_features, axis=1) else: return np.array(mapped_features, dtype=object) def plot_non_linear_boundary(theta, X, y): visualize(X, y) u = np.linspace(-1, 1.5, 50) v = np.linspace(-1, 1.5, 50) z = np.zeros((u.size, v.size)) for i, ui in enumerate(u): for j, vj in enumerate(v): z[i, j] = np.dot(map_features(ui, vj), theta) z = z.T pyplot.contour(u, v, z, levels=[0], linewidths=2, colors='g') pyplot.contourf(u, v, z, levels=[np.min(z), 0, np.max(z)], cmap='Greens', alpha=0.4) def part_one(): """Driver function for part one of the exercise Visualize the data, compute cost and gradient and learn optimal theta paramaters Returns: None """ print_section_header('Section 1') data = np.loadtxt(os.path.join('data/ex2data1.txt'), delimiter=',') X, y = data[:, 0:2], data[:, 2] visualize(X, y) pyplot.show() m = y.size X = np.concatenate([np.ones((m, 1)), X], axis=1) theta = np.array([-24, 0.2, 0.2]) cost, gradient = cost_function(theta, X, y) print("Cost:\n\t{:.3f}".format(cost)) print("Gradient:\n\t{:.3f}, {:.3f}, {:.3f}".format(*gradient)) optimized = optimize_theta(cost_function, theta, X, y) optimized_cost = optimized.fun optimized_theta = optimized.x print('Optimized cost:\n\t{:.3f}'.format(optimized_cost)) print('Optimized theta:\n\t{:.3f}, {:.3f}, {:.3f}'. format(*optimized_theta)) plot_decision_boundary(optimized_theta, X, y) pyplot.show() test_scores = np.array([1, 45, 85]) probability = sigmoid(test_scores.dot(optimized_theta)) print('Probability for student with scores 45 and 85:\n\t{:.3f}'. format(probability)) print('Expected value: 0.775 +/- 0.002') predictions = predict(optimized_theta, X) print('Training accuracy:\n\t{:.3f}'. format(np.mean(predictions == y) * 100)) print('Expected accuracy: 89.00%') def part_two(): """Driver function for part two of the exercise Visualize the data, compute regularized cost and gradient, and learn optimal theta parameters Returns: None """ print_section_header('Section 2') data = np.loadtxt(os.path.join('data/ex2data2.txt'), delimiter=',') X, y = data[:, 0:2], data[:, 2] visualize(X, y) pyplot.show() X_mapped = map_features(X[:, 0], X[:, 1]) m = y.size theta = np.zeros(X_mapped.shape[1]) cost, gradient = regularized_cost_function(theta, X_mapped, y, 1) print("Cost:\n\t{:.3f}".format(cost)) print('Gradient:\n\t{:.4f}, {:.4f}, {:.4f}, {:.4f}, {:.4f}'. format(*gradient)) theta = np.ones(X_mapped.shape[1]) cost, gradient = regularized_cost_function(theta, X_mapped, y, 10) print('Set initial thetas to 1, and lambda to 10') print("Cost:\n\t{:.3f}".format(cost)) print('Gradient:\n\t{:.4f}, {:.4f}, {:.4f}, {:.4f}, {:.4f}'. format(*gradient)) optimized = optimize_theta(cost_function, theta, X_mapped, y, options={'maxiter': 100}) optimized_cost = optimized.fun optimized_theta = optimized.x plot_non_linear_boundary(optimized_theta, X, y) pyplot.show() def main(): """Main driver function. Runs the sections for programming exercise two Returns: None """ part_one() part_two() if __name__ == '__main__': main()
880604c0b72a37eb34c70d898692537357296f7b
shivamach/DIPLearn
/Learn/pandas/methods_loading.py
1,007
3.984375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd # In[2]: x = pd.DataFrame({'a':[1,2,3,4,5],'b':[20,20,30,40,50]}) # In[3]: x # In[7]: a = x.columns print(a) # In[5]: x.index #returns the info that is shown here right now # In[8]: x['b'].sum() #add bitches in a column or so # In[9]: def inc(x): x=x+100 return x #suppose wish to apply this whole function to a column , do next line # In[10]: x['b'].apply(inc) # In[11]: x.sort_values('b') #sort elements in a column #indexes changes in whole table and other columns to according to ascending order of #column selected # In[13]: x['b'].unique() #numpy array of unique values # In[15]: x['b'].nunique() #no of unique values # In[16]: x['b'].value_counts() #each unique value and how many times it occurs # In[17]: x.isnull() #is there a zero null anywhere in dataframe it will go true # In[18]: ######loading data using pandas############## # In[ ]:
f42e9b9dcb39bd8ab75956f1d0f1387d977cad14
mihirapatel/gwc-sip-projects
/logicoperators.py
345
3.921875
4
my_number = 52 def guessnumber(): user_number = input ("Guess my number: ") if int(user_number) == my_number: print("Good job! You guess the right number") print("Game over") elif int(user_number) > my_number: print("You number is too high") guessnumber() else: print("Your number is too low") guessnumber() guessnumber()
a10b9cbaa8dbe1cd916c0743b2c74672b2f79652
EBAX1/DATA533_Lab2
/graphsTrees/trees/tree.py
1,067
3.75
4
from graphsTrees.trees.node import Node class Tree: def create_node(self,key): return Node(key) def insert(self, node, key): if node is None: return self.create_node(key) else: node.left = self.insert(node.left, key) return node def search_node(self,node,key): if node is None: return "Node {} does not exist".format(key) if node.key == key: return "Node {} exists".format(key) else: return self.search_node(node.left,key) def inorder(self,node): if node is not None: self.inorder(node.left) print(node.key) self.inorder(node.right) def preorder(self, node): if node is not None: print(node.key) self.preorder(node.left) self.preorder(node.right) def postorder(self, node): if node is not None: self.postorder(node.left) self.postorder(node.right) print(node.key)
9ab0c6501b45b53d1c6f66a1944e685c471ef1b7
brkreddy06/GitDemo
/PythonTesting/pythonSelenium/demoBrowser.py
998
3.578125
4
from selenium import webdriver #browser exposes an executable file #Through Selenium test we need to invoke the executable file which will then invoke the actual browser # quit() method - it will close all the browsers both parent and child windows # close() method - it will close only the current window # back() method - it will take the screen back to the original page # refresh() - it will refresh the browser #driver = webdriver.Chrome(executable_path="C:\\Users\\brkre\\Ram\\Selenium\\chromedriver.exe") driver = webdriver.Firefox(executable_path="C:\\Users\\brkre\\Ram\\Selenium\\geckodriver.exe") driver.maximize_window() driver.get("https://rahulshettyacademy.com/#/index") #get method to hit the url on browser print(driver.title) print(driver.current_url) # current_url is used to check the accessing URL is correct or not to avoid the cyber attack driver.get("https://rahulshettyacademy.com/#/mentorship") driver.minimize_window() driver.back() driver.refresh() driver.close()
8307e6362f2cd80c59d3859a9f384b3d53926b4a
jtorbett23/python_tdd_fizz_buzz
/test_fizz_buzz.py
2,010
3.734375
4
import unittest import fizz_buzz class Test_fizz_buzz(unittest.TestCase): #returns a number def test_number(self): self.assertEqual(fizz_buzz.fizz_buzz(1),1) #returns Fizz on multiples of 3 def test_fizz(self): self.assertEqual(fizz_buzz.fizz_buzz(3),'Fizz') self.assertEqual(fizz_buzz.fizz_buzz(42),'Fizz') #returns Buzz on multiples of 5 def test_buzz(self): self.assertEqual(fizz_buzz.fizz_buzz(5),'Buzz') self.assertEqual(fizz_buzz.fizz_buzz(65),'Buzz') #returns FizzBuzz on multiples of 3 & 5 def test_buzz(self): self.assertEqual(fizz_buzz.fizz_buzz(15),'FizzBuzz') self.assertEqual(fizz_buzz.fizz_buzz(90),'FizzBuzz') #returns an error message for non-positive integers def test_edge_cases(self): # 0 and negative integers self.assertEqual(fizz_buzz.fizz_buzz(0),'Please enter a positive integer') self.assertEqual(fizz_buzz.fizz_buzz(-1),'Please enter a positive integer') self.assertEqual(fizz_buzz.fizz_buzz(-5),'Please enter a positive integer') #float values self.assertEqual(fizz_buzz.fizz_buzz(0.5),'Please enter a positive integer') self.assertEqual(fizz_buzz.fizz_buzz(-2.5),'Please enter a positive integer') #character values self.assertEqual(fizz_buzz.fizz_buzz('1'),'Please enter a positive integer') self.assertEqual(fizz_buzz.fizz_buzz('a'),'Please enter a positive integer') #string values self.assertEqual(fizz_buzz.fizz_buzz('abc'),'Please enter a positive integer') self.assertEqual(fizz_buzz.fizz_buzz('50'),'Please enter a positive integer') #special character values self.assertEqual(fizz_buzz.fizz_buzz('@'),'Please enter a positive integer') self.assertEqual(fizz_buzz.fizz_buzz('!'),'Please enter a positive integer') #to allow to run tests in terminal with 'python test_fizz_buzz.py' if __name__ == '__main__': unittest.main()
c31fb13e21683a899a332c89eb06c7157517038c
YW-Pan/gwr
/gwr_inversion.py
8,535
3.859375
4
""" ``GWR(fn , time, M, precin)`` gives the inverse of the Laplace transform function named ``fn`` for a given array of ``time``. The method involves the calculation of ``M`` terms of the Gaver-functional. The obtained series is accelerated using the Wynn-Rho convergence acceleration scheme. The precision of internal calculations is set to ``precin``. ``GWR(F, t, M)`` does the same, but the precision of the internal calculations is selected automatically: ``precin`` = 2.1 M). GWR(F, t) uses ``M`` = 32 terms and ``precin`` = 67 as defaults. It should give reasonable results for many problems. Important note: The Laplace transform should be defined as a function of one argument. It can involve anything from a simple Mathematica expression to a sophisticated Module. Since the Laplace transform will be evaluated with non-standard (multiple) precision, approximate numbers (with decimal point) or Mathematica functions starting with the letter ``N`` are not allowed in the function definition. Example usage: def fun(s): (1/s) * mp.exp(-mp.sqrt( (s ** 2 + (37 / 100) s + 1) / (s ** 2 + s + Pi))) t0 = 100 GWR(fun, t0) """ from inspect import signature from functools import lru_cache import numpy as np from mpmath import mp # type: ignore from typing import List, Dict, Tuple, Any, Callable, Union, Iterable, Optional from typing import cast MACHINE_PRECISION = 15 LOG2 = mp.log(2.0) def gwr(fn: Union[Callable[[float], Any], Callable[[float, int], Any]], time: Union[float, Iterable[float], np.ndarray], M: int = 32, precin: Optional[int] = None) -> Any: """ Gives the inverse of the Laplace transform function ``fn`` for a given array of ``time``. The method involves the calculation of ``M`` terms of the Gaver functional. The obtained series is accelerated using the Wynn-Rho convergence acceleration scheme. Returns a ``mp.mpf`` arbitrary-precision float number, a Sequence of ``mp.mpf``, or an ``np.ndarray`` of ``mp.mpf`` depending upon the type of the ``time`` argument. Parameters ---------- fn: Union[Callable[[float], Any], Callable[[float, int], Any]] The Laplace transformation to invert. Must take the Laplace parameter as the first argument, and optionally ``precin`` as the second argument. The precision is necessary for any functions that are memoized, otherwise the cached result will not necessarily match the input ``precin``. time: Union[float, Iterable[float], np.ndarray] The array of time at which to evalute ``fn``. M: int = 32 The number of terms of the Gaver functional. precin: Optional[int] = None The digits of precision to use. If None (default), automatically set to ``round(2.1 * M)``. Returns ------- result: Union[float, Iterable[float], np.ndarray] The inverted result. The type corresponds to the type of ``time``, but is typed as ``Any`` to avoid the requirement for type checking in calling code. """ dps = mp.dps # mp.dps = int(2.1 * M) if precin is None else precin mp.dps = round(21 * M / 10) if precin is None else precin # mp.dps = max(mp.dps, MACHINE_PRECISION) if not isinstance(time, Iterable): # should be a float, but make it a catch-all for any non-Iterable try: return _gwr(fn, time, M, mp.dps) except Exception as e: raise e finally: mp.dps = dps if not isinstance(time, np.ndarray): # evaluate any Iterable that is not an np.ndarray try: return [_gwr(fn, t, M, mp.dps) for t in time] except Exception as e: raise e finally: mp.dps = dps # must be an ndarray or else... !!! assert isinstance(time, np.ndarray), f'Unknown type for time: {type(time)}' if time.ndim < 1: # to iterate over an np.ndarray it must be a vector try: return np.array([_gwr(fn, time.item(), M, mp.dps)], dtype=object) except Exception as e: raise e finally: mp.dps = dps if time.ndim >= 2: # remove single-dimensional entries from any matrix np.squeeze(time) if time.ndim >= 2: # cannot iterate over a matrix mp.dps = dps raise ValueError(f'Expected ndim < 2, but got {time.ndim}') try: return np.array([_gwr(fn, t, M, mp.dps) for t in time], dtype=object) except Exception as e: raise e finally: mp.dps = dps @lru_cache(maxsize=None) def binomial(n: int, i: int, precin: int) -> float: return mp.binomial(n, i) @lru_cache(maxsize=None) def binomial_sum(n: int, i: int, precin: int) -> float: if i % 2 == 1: return -binomial(n, i, precin) else: return binomial(n, i, precin) @lru_cache(maxsize=None) def fac(n: int, precin: int) -> float: return mp.fac(n) @lru_cache(maxsize=None) def fac_prod(n: int, tau: float, precin: int) -> float: n_fac = fac(n - 1, precin) return tau * fac(2 * n, precin) / (n * n_fac * n_fac) @lru_cache(maxsize=None) def _gwr(fn: Union[Callable[[float], Any], Callable[[float, int], Any]], time: float, M: int, precin: int) -> float: """ GWR alorithm with memoization. """ tau = mp.log(2.0) / mp.mpf(time) # mypy can't type check the Callable at runtime, we must do it ourselves sig = signature(fn).parameters n_params = len(sig) fni: List[float] if n_params == 1: fni = [fn(i * tau) if i > 0 else 0 for i in range(2 * M + 1)] # type: ignore elif n_params == 2: fni = [fn(i * tau, precin) if i > 0 else 0 for i in range(2 * M + 1)] # type: ignore else: raise TypeError('Too many arguments for Laplace transform. Expected 1 or 2, got ' f'{n_params}. Function signature:\n{sig}') G0: List[float] = [0.0] * M Gp: List[float] = [0.0] * M M1 = M for n in range(1, M + 1): try: G0[n - 1] = fac_prod(n, tau, precin) \ * sum(binomial_sum(n, i, precin) * fni[n + i] for i in range(n + 1)) except Exception as e: if n == 1: # we didn't perform a single iteration... something must be broken raise e M1 = n - 1 break best = G0[M1 - 1] Gm: List[float] = [0.0] * M1 broken = False for k in range(M1 - 1): for n in range(M1 - 1 - k)[::-1]: try: expr = G0[n + 1] - G0[n] except: # expr = 0.0 broken = True break Gp[n] = Gm[n + 1] + (k + 1) / expr if k % 2 == 1 and n == M1 - 2 - k: best = Gp[n] if broken: break for n in range(M1 - k): Gm[n] = G0[n] G0[n] = Gp[n] return best def _gwr_no_memo(fn: Callable[[float], Any], time: float, M: int = 32, precin: int = 0) -> float: """ GWR alorithm without memoization. This is a near 1:1 translation from Mathematica. """ tau = mp.log(2.0) / mp.mpf(time) fni: List[float] = [0.0] * M for i, n in enumerate(fni): if i == 0: continue fni[i] = fn(n * tau) G0: List[float] = [0.0] * M Gp: List[float] = [0.0] * M M1 = M for n in range(1, M + 1): try: n_fac = mp.fac(n - 1) G0[n - 1] = tau * mp.fac(2 * n) / (n * n_fac * n_fac) s = 0.0 for i in range(n + 1): s += mp.binomial(n, i) * (-1) ** i * fni[n + i] G0[n - 1] *= s except: M1 = n - 1 break best = G0[M1 - 1] Gm: List[float] = [0.0] * M1 broken = False for k in range(M1 - 1): for n in range(M1 - 1 - k)[::-1]: try: expr = G0[n + 1] - G0[n] except: expr = 0.0 broken = True break expr = Gm[n + 1] + (k + 1) / expr Gp[n] = expr if k % 2 == 1 and n == M1 - 2 - k: best = expr if broken: break for n in range(M1 - k): Gm[n] = G0[n] G0[n] = Gp[n] return best def cache_clear() -> None: binomial.cache_clear() binomial_sum.cache_clear() fac.cache_clear() fac_prod.cache_clear() _gwr.cache_clear()
95c9ebf4dd644bd965dc6ac40c453e319289ead3
amyyang17/mywork
/上課內容/eggs/ham.py
488
3.6875
4
import numpy as np n=np.random.randint(1,101) guess,small,big=(0,1,100) while n!=guess: guess=int(input(f"從{small}到{big}猜個數字吧")) if guess > big or guess <small: print(f"超出範圍啦,從{small}到{big}猜個數字吧") else: if guess > n: print("太大囉!") big=guess elif guess < n : print("太小囉!") small=guess else: print("恭喜猜對啦!")
0f1d803c4737da4a1a1f6b312c0db88ab52e07ef
SarahYuHanCheng/Flask_microblog
/gameserver/1/1/1/1_1.py
403
3.90625
4
#!/usr/bin/python def run(): global paddle_vel,ball_pos,move_unit if (ball_pos[-1][0]-ball_pos[-2][0]) <0: print("ball moves left") if (ball_pos[-1][1]-ball_pos[-2][1]) >0: print("ball moves down") paddle_vel=move_unit elif (ball_pos[-1][1]-ball_pos[-2][1])<0: print("ball moves up") paddle_vel=-move_unit else: paddle_vel=0 print("ball moves right, no need to move paddle1")
ec22ae5b47366eccdb336c2b3f2de8c8ab376291
juanjosegdoj/Ejercicios-b-sicos-en-Python
/Básicos/dias,min, seg.py12.py
115
3.546875
4
for h in range(1,25): for m in range(1,60): for s in range(1,60): print(h,":",m,":",s)
b82b22249bd59acadf2e97c10b68924cbc3371a5
juanjosegdoj/Ejercicios-b-sicos-en-Python
/39Thai 21.py
713
3.796875
4
rocas_en_pila=int(input("ingrese numero de rocas en pila")) Nro_de_jugadores=int(input("ingrese numero de jugadores")) cont=1 while rocas_en_pila!=0: while True: if cont>Nro_de_jugadores: cont=1 print("Turno jugador",cont) rocas=int(input("Rocas a extraer ")) if rocas>0 and rocas<4: if rocas<=rocas_en_pila: rocas_en_pila = rocas_en_pila-rocas cont=cont+1 print("Rocas que quedan en pila ",rocas_en_pila) break print("No hay todo ese numero de rocas en la pila") print("sólo puedes cojer entre 1 y 3 rocas") print("El jugador ",cont-1," ha ganado")
ba51eba7ff0b4069d44110ecdac44bb48a58239f
juanjosegdoj/Ejercicios-b-sicos-en-Python
/57Reproductor_fib.py
682
3.90625
4
""" Por Juan José Giraldo Jimenez Objetivo: La explicación del ejercicio se encuentra en el punto 1 de: http://ingeniero.wahio.com/ejercicios-con-while/ """ x=input(":: ") if len(x)==1: x+="0" v=[int(x[-2]),int(x[-1])] while v[len(v)-1]<int(x): v.append(v[-2]+v[-1]) if v[-2]==int(x): ####### print("si está") ####### else: ####### print("No está") ####### # Las lineas que están marcadas (######) se podian reemplazar por lo siguiente: """ if int(x) in v: print ("si está") Pero esto es mas lento porque recorre la lista en orden y teniendo en cuenta que si el numero está, se encontraria en el penultima posición """
90bf8bba2f77ff42668772fa637aaba006e2c930
juanjosegdoj/Ejercicios-b-sicos-en-Python
/47.Astucia Naval.py
2,530
3.703125
4
def suma_de_matriz(matriz): suma=0 for i in matriz: suma+=sum(i) return(suma) def tablero(): matriz=[] for i in range(10): matriz.append([0]*10) return(matriz) def posbarcos(jugador1): for k in range(4): while True: fila=int(input("Ingrese fila: ")) columna=int(input("Ingrese columna: ")) if fila>-1 and fila<11 and columna>-1 and columna<11: break print("las coordenadas salen de el tablero, ingrese nuevamente: ") jugador1[fila][columna]=1 print("ORIENTACION: derecha, izquierda, arriba o abajo") orien=str(input("Orientacion del barco: ")) jugador1[fila][columna]=1 for i in range(k+1): if orien=="derecha": jugador1[fila][columna+i]=1 elif orien=="izquierda": jugador1[fila][columna-i]=1 elif orien=="abajo": jugador1[fila+i][columna]=1 elif orien=="arriba": jugador1[fila-i][columna]=1 else: print("Este barco no ingresó a la matriz") return jugador1 def jugando(jugador1,jugador2): while suma_de_matriz(jugador1)!=0 and suma_de_matriz(jugador2)!=0: print(" Turno de jugador1") print(" Ingrese coordenadas de tiro") fila=int(input(" ingrese fila: ")) columna=int(input(" ingrese columna: ")) if jugador2[fila][columna]==1: print(" Exploto!!!") jugador2[fila][columna]=0 if suma_de_matriz(jugador1)==0: return ("todos los barcos destruidos, el jugador2 ha ganado") print("Turno de jugador2") print("Ingrese coordenadas de tiro") fila=int(input("ingrese fila: ")) columna=int(input("ingrese columna: ")) if jugador1[fila][columna]==1: print("Exploto!!!") jugador1[fila][columna]=0 if suma_de_matriz(jugador2)==0: return ("todos los barcos destruidos, el jugador1 ha ganado") print("TABLERO DE JUGADOR 1") jugador1=tablero() x=posbarcos(jugador1) for bid in x: print(bid) print("TABLERO DE JUGADOR 2") jugador2=tablero() y=posbarcos(jugador1) for bid in y: print(bid) print("¡A JUGAR!") print(jugando(jugador1,jugador2))
4df78d64dfdeb4e003d85f2d3d7e8acbe57deb8e
juanjosegdoj/Ejercicios-b-sicos-en-Python
/Básicos/sucesion de fibonaci.py14.py
190
4.09375
4
def fibonacci(n): if n<2: return n else: return (fibonacci(n-1) + fibonacci(n-2)) n=int(input("puesto en la sucesion de fibonacci ")) print(fibonacci(n))
448fedde7f5555d3666a4491d1c13465c479a878
juanjosegdoj/Ejercicios-b-sicos-en-Python
/Básicos/positivo, negativo o Neutro.py2.py
336
3.859375
4
contP=0 contNeg=0 ContN=0 print("USTED VA INGRESAR 4 NUMEROS") for i in range(1,5): n=int(input("ingrese numero ")) if n>0: contP=contP+1 elif n<0: contNeg=contNeg+1 else: ContN=ContN+1 print("usted ingresó: ",contP," positivos,",contNeg," negativos,",ContN," neutros")
788bcba0f15b5a40ddc1d861a3633da784a5bc38
nodira/streamlit_docs
/tutorial/first_report_part2.py
8,405
4.0625
4
#FIRST_REPORT_LINK_PART2 import streamlit as st st.title("Tutorial: caching, mapping, and more!") st.write(""" *If you hit any issues going through this tutorial, check out our [Help](HELP_LINK) page.* At this point, you have probably [already set up Streamlit](INSTALLATION_LINK), and even created [your first Streamlit report](FIRST_REPORT_LINK). So now let's get down to a more concrete example of how you'd use Streamlit when trying to accomplish a real world task. ## The task A few years ago, the city of New York asked Uber to publish a dataset with information about their pickups and dropoffs. I don't know about you, but to me that sounds like an awesome trove of data --- let's use Streamlit to take a quick look at it! First, **create a new file called `uber_pickups.py`** and paste the following imports into it: ```python import streamlit as st import pandas as pd import numpy as np ``` Now let's make this thing official by giving it a title... ```python st.title('Uber pickups in NYC') ``` ...and then running the script. As usual, **when you run the script your Streamlit report will automatically pop up in your browser**. Of course, at this point it's just a blank canvas. _**REMINDER:** We recommend **arranging your browser window and text editor side by side,** so you can always see both at the same time._ ## Fetching some data Now let's write a function that loads the data for us: ```python DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data ``` As you can see, `load_data` is just a plain old function that downloads some data, puts it in a Pandas dataframe, and converts the date column from text to datetime. It accepts a parameter `nrows`, which specifies the number of rows to load into the dataframe. So let's try out this function and see what happens: ```python data_load_state = st.write('Loading data...') data = load_data(10000) data_load_state.write('Loading data... done!') ``` Well, that's... _underwelming_ ☹ Turns out, downloading the data takes a long time. Who knew?! And converting the date column to datetime costs us another huge chunk time. That's quite annoying. And just to show you exactly _how annoying_ this is, let's go ahead and **take a look at the data we just loaded**: ```python st.subheader('Raw data') st.write(data) ``` ...ugh. Another. Long. Wait. Wouldn't it be amazing if we could **avoid repeating this lenghty step** every time we re-ran the script? Streamlit to the rescue! Let's have a conversation about caching. ## Magical caching Try prepending `@st.cache` before the `load_data` declaration, so it looks like this: ```python @st.cache def load_data(nrows): ``` And then just save the script to have Streamlit automatically rerun it for you. Since this is the first time you're running the script with `@st.cache` in it, you'll see no change. But let's continue tweaking our file so you can see what happens next. Replace the line `st.write('Done!')` with this: ```python st.write('Done! (using st.cache)') ``` ...then save and notice how **the line you just added appears _immediately_**. If you take a step back for a second, this is actually quite amazing. Something magical is happening behind the scenes, and it's just a single line of code to activate it. ### But _how_? Let me go into a sidebar at this point and tell you how `@st.cache` actually works. When you mark a function with Streamlit's cache annotation, it tells Streamlit that whenever the function is called it should check three things: 1. The name of the function 1. The actual code that makes up the body of the function 1. The input parameters that you called the function with If this is the first time Streamlit has seen those three items, with those exact values, and in that exact combination, it runs the function and stores the result in a local cache. Then, next time the function is called, if those three values have not changed Streamlit knows it can skip executing the function altogether. Instead, it just reads the output from the local cache and passes it on to the caller. Bam! Like magic. "_But, wait a second,_" you're thinking, "_this sounds too good. What are the limitations of all this awesomesauce?_" The main limitation is related to item #2, above. That is, Streamlit's cache feature doesn't know about changes that take place outside the body of the annotated function. For example, the `load_data` function above depends on a couple of global variables. If we change those variables, Streamlit will have no knowledge of that and will keep returning the cached output as if they never changed to begin with. Similarly, if the annotated function depends on code that lives outside of it, and that outside code changes, the cache mechanism will be none-the-wiser. Same if the function reads a dataset from a URL, and the remote dataset is time-varying. These limitations are important to keep in mind, but tend not to be an issue a surprising amount of times. Those times, this cache is really transformational. So if nothing else, here's what you should take from this tutorial: _**PRO TIP:** Whenever you have a long-running computation in your code, consider refactoring it so you can use_ `@st.cache`_, if possible._ --- OK, sidebar over. Now that you know how the cache mechanism works, let's get back to the task at hand: understanding Uber's passenger pickup patterns in NYC. ## Drawing a histogram A basic question you might ask is "_what are Uber's busiest hours?_" To answer that, let's break down all the pickup times into at histogram, binned by hour: ```python st.subheader('Number of pickups by hour') hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0, 24))[0] st.bar_chart(hist_values) ``` Save the script and a histogram will appear immediately. What the chart tells us is that **Uber is busiest around 17:00 (i.e. 5pm)**. Cool! ## Dots on a map Now let's see what all those pickups look like when overlaid on top of a map of NYC: ```python st.subheader('Map of all pickups') st.map(data) ``` **Yes, really. Drawing a map is _that_ simple.** Just call `st.map` and pass in a datset where come column is named `lat` and another `lon`. And since this is not the 90s, the map is interactive: go ahead and try panning and zooming it a bit! But let's do one better. In the previous section, we learned that the peak Uber hour is 17:00, so you may be wondering "what are the peak Uber _locations_ at 5pm?" Well, that should be easy to find out: just filter the map to show only pickups between 5--6pm and find out. So replace the previous snippet with the following: ```python # Some number in the range 0-23 hour_to_filter = 17 filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader('Map of all pickups at %d:00' % d) st.map(filtered_data) ``` And we're done! Looks like **Uber's prime real estate at that time is Midtown, slightly off-center toward the East side**. Groovy! ## Appendix: the final script This is what `uber_pickups.py` should look like when you're done with this tutorial: ```python import streamlit as st import pandas as pd import numpy as np st.title('Uber pickups in NYC') DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') @st.cache def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data st.write('Loading data...') data = load_data(10000) st.write('Done! (using st.cache)') st.subheader('Raw data') st.write(data) st.subheader('Number of pickups by hour') hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] st.bar_chart(hist_values) # Some number in the range 0-23 hour_to_filter = 17 filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader('Map of all pickups at %d:00' % hour_to_filter) st.map(filtered_data) ``` """)
86eb3487607bf0b1cd76215e54ff8188b7471a25
Azakahul/InterviewProblems
/Python/Arrays/duplicatenumber.py
452
3.9375
4
# How do you find the duplicate number on a given integer array? def duplicatenumber(n, m, duplList): for num in range(n,m): currentnum = num count = 0 for x in duplList: if currentnum == x: count += 1 if count == 2: return currentnum dupList = list(range(100)) dupList[23] = 22 dupnumber = duplicatenumber(1,100, dupList) print("The duplicate number is " + str(dupnumber))
0838f1661aca1a4708782e5e1930e3c9b9a98eaa
zephyr-c/shopping-site
/customers.py
1,048
3.765625
4
"""Customers at Hackbright.""" class Customer(object): """Ubermelon customer.""" # TODO: need to implement this def __init__(self, first, last, email, password): self.first_name = first self.last_name = last self.email = email self.password = password def __repr__(self): return "<Customer: {}, {}, {}>".format(self.first_name, self.last_name, self.email) def read_customers_from_file(filepath): customer_info = {} with open(filepath) as file: for line in file: (first_name, last_name, email, password) = line.strip().split('|') customer_info[email] = Customer(first_name, last_name, email, password) return customer_info def get_by_email(email): return customer_dictionary[email] customer_dictionary = read_customers_from_file("customers.txt")
ab7145c79eb6bd339ac84c807f709bb1bc3f0423
Santexnik77/cursera_py4e
/w4ex.py
121
3.578125
4
hrs = input("Enter Hours:") rt = input("Enter rate:") hrsf = float(hrs) rtf = float(rt) pay = hrsf*rtf print("Pay:",pay)
1513bb7fdd3e2a396e715ea9a66ee51cd9fc6532
pl366/Tic--Tac--Toe
/TTT.py
3,319
3.859375
4
# -*- coding: utf-8 -*- """ Created on Tue May 16 12:48:37 2017 @author: PULKIT LUTHRA """ #Tic Tac Toe Game import random board=[] for i in range(9): board.append(-1) def drawBoard(): print(' | |') print(' ' + str(board[0]) + ' | ' + str(board[1]) + ' | ' + str(board[2])) print(' | |') print('---------------') print(' | |') print(' ' + str(board[3]) + ' | ' + str(board[4]) + ' | ' + str(board[5])) print(' | |') print('---------------') print(' | |') print(' ' + str(board[6]) + ' | ' + str(board[7]) + ' | ' + str(board[8])) print(' | |') def inputPlayerLetter(): letter = input("Do you want to be X or O?") letter=letter.upper() if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] def whoGoesFirst(): if random.randint(0, 1) == 0: return 'computer' else: return 'player' def checkWinner(bo, le): return ((bo[6] == le and bo[7] == le and bo[8] == le) or (bo[3] == le and bo[4] == le and bo[5] == le) or (bo[0] == le and bo[1] == le and bo[2] == le) or (bo[6] == le and bo[3] == le and bo[0] == le) or (bo[7] == le and bo[4] == le and bo[1] == le) or (bo[8] == le and bo[5] == le and bo[2] == le) or (bo[6] == le and bo[4] == le and bo[2] == le) or (bo[8] == le and bo[4] == le and bo[0] == le)) def getPlayerMove(playerLetter): while True: move = input("What is your next move? (0-8)") move=int(move) if board[move]!=-1: print ('Invalid move! Cell already taken. Please try again.\n') else: board[move]=playerLetter return def getComputerMove(computerLetter): while True: move = int(random.randint(0,8)) if board[move]!=-1: #print ('Invalid move! Cell already taken. Please try again.\n') continue else: board[move]=computerLetter return while True: for i in range(9): board[i]=-1 drawBoard() playerLetter, computerLetter = inputPlayerLetter() turn = whoGoesFirst() print('The ' + turn + ' will go first.') count=0 while True: if turn=='player': count+=1 getPlayerMove(playerLetter) drawBoard() if count>=5: if checkWinner(board,playerLetter): print ("Hurray!!!!You Win") break if count==9: print ("The match is drawn") break turn = 'computer' else: print ('Computers Turn') count+=1 getComputerMove(computerLetter) drawBoard() if count>=5: if checkWinner(board,computerLetter): print ("You Lose") break if count==9: print ("The match is drawn") break turn = 'player' playAgain=input('Do you want to play again? (yes or no)') if playAgain!='yes': break
b801a4581c35f8fef9b0c62c10aac0578fc9ae04
Mstoned/Python
/Pattern/py/num_pattern2.py
515
3.984375
4
''' Print the following pattern for the given N number of rows. Pattern for N = 4 1 11 202 3003 Input format :Integer N (Total no. of rows) Output format :Pattern in N lines Sample Input :5 Sample Output : 1 11 202 3003 40004 ''' num=int(input('Enter the num for pattern : ')) for i in range(1,num+1): for j in range(0,i): x=i-1 if x==0: print(1,end="") else: if x==j or j==0: print(x,end="") else:print(0,end="") print("")
ceca7f4c880b369b8849d82e1fe35e4d1f6e07d2
andremmfaria/exercises-coronapython
/chapter_07/chapter_7_7_6.py
752
3.90625
4
# 7-6. Three Exits: Write different versions of either Exercise 7-4 or Exercise 7-5 that do each of the following at least once: # # • Use a conditional test in the while statement to stop the loop. # # • Use an active variable to control how long the loop runs. # # • Use a break statement to exit the loop when the user enters a 'quit' value. loop = 0 while True: loop += 1 message = input("\nPlease enter your age: \n") if message == 'quit': print (str(loop)) break else: if (int(message) < 3): print("\nYour ticket is free! \n") elif(3<=int(message)<=12): print("\nYour ticket is $10 \n") else: print("\nYour ticket is $15 \n")
38081fd73316e20f6361d835d710dd379e8c78ea
andremmfaria/exercises-coronapython
/chapter_06/chapter_6_6_4.py
823
4.375
4
# 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) by replacing your series of print statements with ía loop that runs through the dictionary’s keys and values. When you’re sure that your loop works, add five more Python terms to your glossary. When you run your program again, these new words and meanings should automatically be included in the output. valdict = { "variable": "Elementar data type that stores values", "loop": "Self repeating structure", "dictionary": "Glossary structure", "array": "List of elements", "conditional": "Conditional test", "word0": "Value0", "word1": "Value1", "word2": "Value2", "word3": "Value3", "word4": "Value4" } for key in valdict: print(key + ", " + valdict[key])
9634250371f02daea5f2200e7ef401237a660e6f
andremmfaria/exercises-coronapython
/chapter_08/chapter_8_8_10.py
765
4.40625
4
# 8-10. Great Magicians: Start with a copy of your program from Exercise 8-9. Write a function called make_great() that modifies the list of magicians by adding the phrase the Great to each magician’s name. Call show_magicians() to see that the list has actually been modified. def show_magicians(great_magicians): for magician in great_magicians: print(magician) def make_great(magicians_names,great_magicians): while magicians_names: g_magician = magicians_names.pop() g_magician = 'Great ' + g_magician great_magicians.append(g_magician) magicians_names = ['houdini','david blane', 'chris angel'] great_magicians = [] show_magicians(magicians_names) make_great(magicians_names,great_magicians) show_magicians(great_magicians)
8c5498b935164c457447729c6de1553b390664e5
andremmfaria/exercises-coronapython
/chapter_06/chapter_6_6_8.py
522
4.34375
4
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet. pet_0 = { 'kind' : 'dog', 'owner' : 'Juliana' } pet_1 = { 'kind' : 'cat', 'owner' : 'Ana' } pet_2 = { 'kind' : 'fish', 'owner' : 'Joao' } pets = [pet_0, pet_1, pet_2] for p in pets: print(p)
7bc98b1c9a50acb1e7ff7fe3ce2781ace3a56eb8
andremmfaria/exercises-coronapython
/chapter_07/chapter_7_7_1.py
257
4.21875
4
# 7-1. Rental Car: Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.” message = input("Let me see whether I can find you a Subaru") print(message)
728475dad2bf31558ebc1280f527777e60362ee8
jerry8812/PR301Repo
/Assignment2/TIGrExTurtleDrawer.py
2,434
3.546875
4
""" Turtle Drawer By Sean Ryan """ from TIGr import AbstractDrawer import turtle class TurtleDrawer(AbstractDrawer): """Turtle Drawer Inherits: select_pen(pen_num), pen_down(), pen_up(), go_along(along), go_down(down), draw_line(direction, distance) Preset Pens: 1 - colour black, size 10 2 - colour red, size 10 3 - colour blue, size 10 Begin doctest - Written with Jonathan Holdaway and Sean Ryan 24/08/2019 >>> drawer.select_pen(2) Selected pen 2 >>> drawer.go_along(5) Gone to X=5 >>> drawer.go_down(5) Gone to Y=5 >>> drawer.pen_down() Pen down >>> drawer.draw_line(0, 5) drawing line of length 5 at 0 degrees >>> drawer.draw_line(90, 5) drawing line of length 5 at 90 degrees >>> drawer.draw_line(180, 5) drawing line of length 5 at 180 degrees >>> drawer.draw_line(270, 5) drawing line of length 5 at 270 degrees >>> drawer.pen_up() Pen lifted >>> drawer.clear() Cleared drawing End doctest """ def __init__(self): super().__init__() print('Now using Turtle Drawer') self.turtle = turtle.Turtle() turtle.Screen().title('TIGrEx') # look up table for pen colour self.pen_colour = {1: 'black', 2: 'red', 3: 'blue'} def shutdown(self): print('No longer using Turtle Drawer') self.clear() self.turtle = None def select_pen(self, pen_num): print(f'Selected pen {pen_num}') if pen_num in self.pen_colour: self.turtle.pen(fillcolor='white', pencolor=self.pen_colour[pen_num], pensize=10) else: print('Please choose a valid pen number.') def pen_down(self): print('Pen down') self.turtle.pendown() def pen_up(self): print('Pen lifted') self.turtle.penup() def go_along(self, along): print(f'Gone to X={along}') self.turtle.setx(along) def go_down(self, down): print(f'Gone to Y={down}') self.turtle.sety(down) def draw_line(self, direction, distance): print(f'drawing line of length {distance} at {direction} degrees') self.turtle.setheading(direction) self.turtle.forward(distance) def clear(self): print('Cleared drawing') self.turtle.clear() if __name__ == '__main__': import doctest drawer = TurtleDrawer() doctest.testmod(verbose=3)
15dd5f611510783c941a9473bd55d448fd05ce84
tahamazari/HackerRank
/sorting/counting_sort_2/counting_sort_2.py
877
3.671875
4
#!/bin/python3 import math import os import random import re import sys # Complete the countingSort function below. def countingSort(arr): sorted_array = [] count_array = [0]*(len(arr)) for i in range(0, len(arr)): count_array[arr[i]] += 1 for i in range(0, len(arr)): if(count_array[i] != 0): j = 0 while j < count_array[i]: sorted_array.append(i) j += 1 print(sorted_array) return sorted_array if __name__ == '__main__': os.environ['OUTPUT_PATH'] = "C://Users//taha_//Desktop//Hacker_rank//output.txt" OUTPUT_PATH = os.environ['OUTPUT_PATH'] fptr = open(OUTPUT_PATH, 'w') n = int(input()) arr = list(map(int, input().rstrip().split())) result = countingSort(arr) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
4fffdf8bfd105ee735595dc4cece8d19cabb3c78
tahamazari/HackerRank
/Hacker_rank/repeated_string.py
964
3.515625
4
#!/bin/python3 import math import os import random import re import sys # Complete the repeatedString function below. def repeatedString(s, n): x = 0 # for i in s: # s += str(i) # x += 1 # if( x < n): # for j in s: # s += str(j) # # total_a = 0 # # a = 0 # while a < n: # if(s[a] == 'a'): # total_a += 1 # a += 1 # for a in range(0, n): # if(a < n and s[a] == 'a'): # total_a += 1 total_a = 0 x = 0 for i in s: if(i == 'a'): total_a += 1 print(total_a) return total_a if __name__ == '__main__': os.environ['OUTPUT_PATH'] = "C://Users//taha_//Desktop//Hacker_rank//output.txt" OUTPUT_PATH = os.environ['OUTPUT_PATH'] fptr = open(OUTPUT_PATH, 'w') s = input() n = int(input()) result = repeatedString(s, n) fptr.write(str(result) + '\n') fptr.close()
7afe22606dcfcce5d705c3e412b3c33c4ccf8bf8
sahilchanglani/Turtle-crossing-game
/scoreboard.py
1,116
3.84375
4
from turtle import Turtle FONT = ("Courier", 24, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.level = 1 self.color("black") self.penup() with open("highscore.txt") as data: self.high_score = int(data.read()) self.hideturtle() self.display() def display(self): self.clear() self.goto(-280, 260) self.write(f"Level: {self.level}", align="left", font=FONT) self.goto(280, 260) self.write(f"Highscore: {self.high_score}", align="right", font=FONT) def level_up(self): self.level += 1 self.display() def game_over(self): if self.level > self.high_score: self.high_score = self.level with open("highscore.txt", mode="w") as data: data.write(f"{self.high_score}") self.display() self.goto(0, -50) self.write("New High-score!!", align="center", font=FONT) self.home() self.write("GAME OVER", align="center", font=("Courier", 40, "normal"))
d60aba690a4cf3dd04eb4f8d074a170fac1a3504
Nadeesha9090/SME---Python-Project
/Python Basic/Test - 04.py
236
3.90625
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 28 23:02:21 2018 @author: hp """ #For Loop numberList = [1,23,67,56,654,77,33,778,1,222,2345] for eachNumber in numberList: print(eachNumber) for x in range(1,12): print(x)
0113a118a572d8a111a06f4e87653a8f3f448014
pawelff/AdventOfCode2020
/day_02/4.py
316
3.59375
4
valid_passwords = 0 with open("3.txt", "r") as f: for line in f: words = line.split() positions = list(map(int, words[0].split('-'))) letter = words[1][0] password = words [2] if (password[positions[0]-1] == letter) != (password[positions[1]-1] == letter): valid_passwords += 1 print(valid_passwords)
9fd0b5a0a82a108e9f5b3c56135ae18bec2a3bd1
srikanthpragada/PYTHON_25_MAY_2020
/demo/oop/time.py
425
3.796875
4
class Time: def __init__(self, h, m, s): self.h = h self.m = m self.s = s @property def hours(self): return self.h @hours.setter def hours(self, value): if value >= 0 and value <= 23: self.h = value else: raise ValueError("Invalid hours") t = Time(10, 20, 30) t.hours = 15 print(t.hours) t2 = t t2.hours = 20 print(t.hours)
a1f9f339424711a8493e89eb801ca0e845d08daa
srikanthpragada/PYTHON_25_MAY_2020
/demo/table.py
340
4
4
import sys if len(sys.argv) < 2: print("Usage : python table.py <number> [length]") exit(1) if len(sys.argv) == 2: length = 10 # Default length else: length = int(sys.argv[2]) num = int(sys.argv[1]) # Number for which table is to be displayed for i in range(1, length + 1): print(f"{num:3} * {i:2} = {num * i:5}")
d1d34cd7626fb813412063e8f0e7748e0bc2f97b
Korasi/COSC-1336
/Lab4/lab4.py
3,239
3.859375
4
# This program computes statistics from a list of test scores # Nigel Myers # Fundamentals of Programming # ACC FALL 2018 # lab4.py # Prof Onabajo def output(string, outfile): #print output to console and data file print(string) outfile.write('%s\n' % string) def floatToString(input_): #convert float to string, removing trailing zeros and decimal return ('%f' % input_).rstrip('0').rstrip('.') def the_average_distance_of_each_data_point_from_the_mean_squared_then_square_rooted_to_remove_the_negative_sign_also_known_as_the_standard_deviation(scores, mean): #calculate standard deviation std = 0 for score in scores: #loop once for each test score dev = mean - score #calculate deviation from the mean std += dev ** 2 #square the deviation from the mean to remove negative, and add it to the sum of the squared means return (std / len(scores)) ** .5 #return the square root the squared means; the standard deviation def main(): #initialize variables sum_, mean, dev2, std, sd2 = 0, 0, 0, 0, 0 scores = [] with open('testscores.txt', 'r') as inputFile: #open input file (with open as _ removes the need for closing statements) while True: #infinite loop try: row = inputFile.readline().strip('\n').split(',') #strip newline, split by comma. [Student i, testScore] score = int(row[1].strip(' ')) #strip space from score, convert to int sum_ += score #increment sum by score scores.append(score) #add score to array of scores except (IndexError, ValueError): #reached end of file break #break out of loop mean = sum_ / len(scores) #calculate mean std = the_average_distance_of_each_data_point_from_the_mean_squared_then_square_rooted_to_remove_the_negative_sign_also_known_as_the_standard_deviation(scores, mean) #get standard deviation with open('Lab4_Output.txt', 'w') as outputFile: #open output file (with open as _ removes the need for closing statements) output('%8s %12s %12s %12s\n' % ('Score', 'DEV', 'DEV1', 'SD1'), outputFile) #headers for score in scores: #loop for each score in scores array dev = mean - score #calculate deviation from the mean dev1 = dev ** 2 #calculate the square of the deviation from the mean dev2 += dev1 #increment sum of squares of the deviation from the mean by dev1 sd1 = dev / std #calculate the standard score sd2 += sd1 #increment the sum standard scores by sd1 output('%8s %12s %12s %12s' % (score, floatToString(dev), floatToString(dev1), floatToString(sd1)), outputFile) #output and right align DEV, DEV1, SD1 output('\nSum:%s Mean: %s STD: %s' % (floatToString(sum_), floatToString(mean), floatToString(std)), outputFile) #output Sum, Mean, Standard Deviation output('Sum of DEV1: %s Sum of SD1: %s' % (floatToString(dev2), floatToString(sd2)), outputFile) #output Sum of deviations from the main, Sum of standard scores (should always be 0) print('\nOutput written to Lab4_Output.txt') main()
96a2564c2b098a9befed20ab03268ca58451d292
Korasi/COSC-1336
/Lab2/lab2.py
2,964
4.03125
4
# This program computes the cost of a house over five years given initial, fuel, and tax costs. # Nigel Myers # Fundamentals of Programming # ACC FALL 2018 # lab2.py # Prof Onabajo def validateData(displayText, *args): #prompt user for input, and validate if it's int or float # Usage: validateData(displayText[, minimumValue[, maximumValue]]) minimum = args[0] if len(args) >= 1 and isinstance(args[0], (float, int)) else float('-INF') #-inf default, args[0] if specified maximum = args[1] if len(args) >= 2 and isinstance(args[1], (float, int)) else float('INF') #inf default, args[1] if specified while True: #loop infinitely try: data = input(displayText) #get user input data = float(data) if '.' in data else int(data) #convert to float if decimal in string, else convert to int if data < minimum or data > maximum: #if outside of range print('This is an invalid number') continue #return to start of loop except ValueError: #if value error, alert user and loop back print('This is not a number.') else: #valid data; return data return data def validateInt(displayText, *args): #prompt user for input, and validate that datatype to be int # Usage: validateInt(displayText[, minimumValue[, maximumValue]]) while True: #infinite loop data = validateData(displayText, *args) #get input from validateData() if not isinstance(data, int): #if data is not int, then alert user and re-loop print('This is not an integer.') continue return data #is int; return data def output(string, outfile): print(string) outfile.write('\n%s' % string) def main(): #init variables initial, annual, tax = 0, 0, 0 houses = [] for i in range(validateInt('How many houses do you want to calculate the cost of? ', 0)): #set variables initial = validateData('\nPlease enter the initial cost of house %i. $' % (i + 1), 0) annual = validateData('Please inter the annual fuel cost of house %i. $' % (i + 1), 0) tax = validateData('Please enter the tax rate of the house %i. $' % (i + 1), 0) #calculate total price over five years and append to list 'houses' houses.append(initial + annual * 5 + initial * tax * 5) print('') #open output file with open('Lab2_Output.txt', 'w') as outfile: for i in range(len(houses)): #loop for each house output('The total cost of house %i over five years is $%.2f.' % (i + 1, houses[i]), outfile) #print house cost to output file and console output('\nHouse %i would cost the least money over the five years.' % (houses.index(min(houses)) + 1), outfile) #print house with best cost to file and console print('\nOutput written to Lab2_Output.txt') main()
963028e915a2b26601ee2dd3773175c5b50d0209
gelu100/power_exponent
/test_exponent.py
1,510
3.5625
4
import power_of_a_number import unittest class Powbase(unittest.TestCase): def test_is_natural_number_correctly_power(self): self.assertEqual(power_of_a_number.returning_power_base_of_a_number(2, 2), 4) def test_for_a_big_number(self): self.assertEqual(power_of_a_number.returning_power_base_of_a_number(4566, 12), 82116586110675706515281619246434838196064256) def test_if_power_is_a_string(self): with self.assertRaises(TypeError): power_of_a_number.returning_power_base_of_a_number('power', 2) def if_base_is_a_characater(self): with self.assertRaises(TypeError): power_of_a_number.returning_power_base_of_a_number(6,'Foo') def test_is_power_of_float(self): with self.assertRaises(TypeError): power_of_a_number.returning_power_base_of_a_number(8, 0.354) def test_zero_is_power_and_zero_is_base(self): self.assertEqual(power_of_a_number.returning_power_base_of_a_number(0, 0), 1) def test_is_the_power_equal_zero(self): self.assertEqual(power_of_a_number.returning_power_base_of_a_number(56, 0), 1) def test_0_to_negative_raises_exception(self): with self.assertRaises(ZeroDivisionError): power_of_a_number.returning_power_base_of_a_number(0, -2) def test_if_power_is_less_than_zero(self): self.assertEqual(power_of_a_number.returning_power_base_of_a_number(4,-2),0.0625) if __name__ == "__main__": unittest.main()
064f99bb33abef151e3dc319d6e02ce18a8d7237
Khusniyarovmr/Python
/Lesson_2/1.py
1,860
3.921875
4
""" 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), то программа должна сообщать ему об ошибке и снова запрашивать знак операции. Также сообщать пользователю о невозможности деления на ноль, если он ввел 0 в качестве делителя. """ x = '' while x != '0': a, b = int(input('Введите число 1: ')), int(input('Введите число 2: ')) i = 0 while i != 1: x = input('Введите знак операции: ') if x == '/' or x == '*' or x == '-' or x == '+': if x == '/' and b != 0: print(a / b) elif x == '/' and b == 0: print('Деление на 0 не возможно!') if x == '*': print(a * b) if x == '-': print(a - b) if x == '+': print(a + b) i = 1 elif x == '0': print('Выход из программы') break else: print('Введите другой знак операции!')
5e3d898b7992d9d2915045298ad4a676a18ba2f6
Khusniyarovmr/Python
/Lesson_1/5.py
638
4.03125
4
#5. Пользователь вводит две буквы. Определить, на каких местах # алфавита они стоят, и сколько между ними находится букв. print('Введите две буквы: ') a, b = input(), input() a1 = ord(a); b1 = ord(b) print('Первая буква находится на ', a1 - ord('a')+1, ' месте в алфавите') print('Вторая буква находится на ', b1 - ord('a')+1, ' месте в алфавите') print('Между первой и второй буквой находятся ', abs(a1-b1)-1, ' букв')
1647b333db7c0d04a16dc37f794146cb9843561b
Khusniyarovmr/Python
/Lesson_1/4.py
991
4.3125
4
""" 4. Написать программу, которая генерирует в указанных пользователем границах ● случайное целое число, ● случайное вещественное число, ● случайный символ. Для каждого из трех случаев пользователь задает свои границы диапазона. Например, если надо получить случайный символ от 'a' до 'f', то вводятся эти символы. Программа должна вывести на экран любой символ алфавита от 'a' до 'f' включительно. """ import random a = input('Начальный символ: ') b = input('Конечный символ: ') if str.isdigit(a): print(random.randint(int(a), int(b)+1)) print(random.uniform(int(a), int(b)+1)) else: print(chr(random.randint(ord(a), ord(b)+1)))
b6ed21a41ebf8993427eb5fe54474350e525d621
nathanleiby/algorithms-on-graphs
/week1_decomposition1/1_reachability/reachability.py
932
3.796875
4
# Uses python3 import sys def reach(adj, x, y): # do depth first search on an adjacency list visited = {} to_visit = [x] while len(to_visit) > 0: cur = to_visit.pop() visited[cur] = True if cur == y: # found return 1 neighbors = adj[cur] unvisited_neighbors = filter(lambda x: x not in visited, neighbors) to_visit.extend(unvisited_neighbors) return 0 def parse_input(input): data = list(map(int, input.split())) n, m = data[0:2] data = data[2:] edges = list(zip(data[0 : (2 * m) : 2], data[1 : (2 * m) : 2])) x, y = data[2 * m :] adj = [[] for _ in range(n)] x, y = x - 1, y - 1 for (a, b) in edges: adj[a - 1].append(b - 1) adj[b - 1].append(a - 1) return adj, x, y if __name__ == "__main__": # read from stdin adj, x, y = parse_input(sys.stdin.read()) print(reach(adj, x, y))
f763244810ef4e71e0a87af12f09107f1a8333cd
rams1996/Daily-coding-assignments
/lru-cache/lru-cache.py
1,275
3.640625
4
   def addToFront(self,node):        temp=self.head.nxt        temp.prev=node        self.head.nxt=node        node.nxt=temp        node.prev=self.head ​    def get(self, key: int) -> int:        if key in self.link:            node=self.removeNode(self.link[key])            self.addToFront(node)            self.link[key]=node            return node.val        else:            return -1         ​    def put(self, key: int, value: int) -> None:        newNode=LList(key,value)        if key in self.link:            node=self.removeNode(self.link[key])            self.addToFront(newNode)            self.link[key]=newNode        else:              if len(self.link)>=self.capacity:                NodeToBeDeleted=self.tail.prev                node=self.removeNode(NodeToBeDeleted)                del self.link[node.key]            self.addToFront(newNode)            self.link[key]=newNode            return None                     ​ ​ # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
ada45843b6e4b1208b304ac1d44874ae585c2123
Antonio985/SeminarioDeProgramacion
/Modulos/Modulo_Persona.py
240
3.625
4
#Creacion de la clase class Persona: def __init__(self, nombre, edad): self.__nombre = nombre self.__edad = edad def __str__(self): return "Nombre: "+self.__nombre+" y edad : "+str(self.__edad)
64dbc3fb5e9c6a20abee22a435f0a5f701a7bd35
mckilem/python1_hw
/lesson1/normal.py
1,917
3.71875
4
# Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа a = 1789876521 maxValue = -1 for x in str(a): b = int(x) if maxValue < b: maxValue = b print(maxValue) # Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Решите задачу используя только две переменные a = int(input('input integer a: ')) b = int(input('input integer b: ')) a = a + b b = (-1) * (b - a) a = a - b print('a = ' + str(a)) print('b = ' + str(b)) # Задача-3: Напишите программу, вычисляющую корни квадратного уравнения вида ax2 + bx + c = 0. # Для вычисления квадратного корня воспользуйтесь функицй sqrt() молудя math import math # math.sqrt(4) - вычисляет корень числа 4 # дано уравнение ax2 + bx + c = 0 # вводим a и b print('we have an equation ax2 + bx + c = 0. Please enter a,b and c') a = float(input('input a: ')) b = float(input('input b: ')) c = float(input('input c: ')) if (a==0) or (c==0): print('please^ enter correct values for a and c') else: # считаем дискриминант dis = b ** 2 - 4 * a * c if dis < 0: print('D<0: lets not get into irrational values') elif dis == 0: x = (-1) * b / (2 * a) print('D=0: equation has one solution: ' + str(x)) else: # D > 0 x1 = ((-1) * b + math.sqrt(dis)) / (2 * a) x2 = ((-1) * b - math.sqrt(dis)) / (2 * a) print('D>0: equation has two solutions: ' + str(x1) + ' and ' + str(x2))
b679d7831d5b98945e737a19deadcecfbf5f2463
rob-giuliano/Human.Number.Name
/lib/tkinter.py
2,143
3.9375
4
import tkinter as info import tkinter as tk class Application(info.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.hi_there = info.Button(self) self.hi_there["text"] = "Info: Numerology System \n( - Click Here -)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.quit = info.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") def say_hi(self): print(" ") print(" ") print(" ") print("=============================================================================") print(" === Numerology system === ") print("--------------------------------") print(" Every letter has a unique vibration and the numbers are assigned to " "letters on the vibrational value and the numbers only go from 1 to 9") print(" Numerology has numerous interpretations regarding each number," " but it is always easier to work with one-digit numbers, the meaning" " is clearer and the personality puzzle is easier to assemble.") print(" In Numerology it is often needed to reduce all two and three-digit numbers" " to one digit.") print("=============================================================================") print(" ") print(" ") print("Quit window, and check your master-numbers") root = info.Tk() app = Application(master=root) app.mainloop()
0578668b3eae5440e08535d5c1f0e52c0e2d2b24
Selasi3/tlc4_python
/tutorials/hello.py
81
3.671875
4
print("Hello,world") name = input("Enter your name: \n") print("Hello, ", name)
f1796363ad5afd125fd217c8eb8a78744b147542
zikoc15/ziko
/cazorla.py
2,790
3.921875
4
class Usuario: def __init__(self): self.nombre="a" self.apellido="s" self.correo="x" self.clave="c" usu=Usuario() listausu=list() correo="[email protected]" clave="daniel1999" salir="salir" for i in range (10): print("_______________________________") print(" INICIO ") print("_______________________________") print("") print("- Monitoreo") print("- Crear Usuario") print("- Escribe ('SALIR') para cerrar el programa") option=input() if option=="1": correo1=input('Correo: ') if correo==correo1: clave1=input('Clave: ') if clave==clave1: print("_______________________________") print(" MENU ") print("_______________________________") print("") print("- Registro de Usuario") print("- Borrar Usuario") print("- Cerrar el secion") option=input() if option=="1": for i in range(10): print("_______________________________") print(listausu) cha=input('Oprime enter') continue if option=="2": print("") if option=="3": continue else: print("Clave invalida") continue else: print("Correo no existente") continue if option=="2": print ("Usuario (Nombre): ") usu.nombre=input() print ("Usuario (apellido): ") usu.apellido=input() print ("Usuario (Correo): ") usu.correo=input() print ("Usuario (Clave): ") usu.clave=input() lista = ("Nombre: "+ usu.nombre +" Apellido: "+ usu.apellido + " Correo: "+ usu.correo +" Clave: "+ usu.clave+"\n"+"\n") listausu.append(usu.nombre + usu.apellido + usu.correo + usu.clave) archivo=open("Registro de Usuarios.txt","a") archivo.write(lista) archivo.close() for i in range (100): print("_______________________________") print(" MENU ") print("_______________________________") print("") print("- SUMA") print("- RESTA") print("- MULTIPLICAR") print("- DIVIDIR") print("- SALIR DE LA CALCULADORA") option=input() num3=int() if option=="1": print("Introduce dos numeros") num1=int(input()) num2=int(input()) num3=num2+num1 print(num1,"+",num2,"=",num3) if option=="2": print("Introduce dos numeros") num1=int(input()) num2=int(input()) num3=num2-num1 print(num1,"-",num2,"=",num3) if option=="3": print("Introduce dos numeros") num1=int(input()) num2=int(input()) num3=num2*num1 print(num1,"*",num2,"=",num3) if option=="4": print("Introduce dos numeros") num1=int(input()) num2=int(input()) num3=num2/num1 print(num1,"/",num2,"=",num3) if option=="5": break if option=="salir": break
a9791e4d76a4eb55c00a6ceb6a13f424c6828b56
rajeevbrahma/Smart-Traffic-Management-System-for-Emergency-Services
/server/traffic_calc/bearing.py
1,076
3.828125
4
#!/usr/bin/python ''' /*************************************************************************************** Name : bearng Description : calculates the bearing(angle) between given two lattitude and longitude points Parameters : l_lat1 and l_lng1 are point one lattitude and longitude respectively l_lat2 and l_lng2 are point two lattitude and longitude respectively Return : This function will return the bearing(angle) between given two lattitude and longitude points ****************************************************************************************/ ''' import math def bearng(l_lat1,l_lng1,l_lat2,l_lng2): l_lat1 = float(l_lat1) l_lng1 = float(l_lng1) l_lat2 = float(l_lat2) l_lng2= float(l_lng2) lndif = (l_lng2 - l_lng1) y = math.sin(lndif) * math.cos(l_lat1) x = math.cos(l_lat2) * math.sin(l_lat1) - math.sin(l_lat2) * math.cos(l_lat1)*math.cos(lndif) l_brng = math.atan2(y,x) l_brng = math.degrees(l_brng) l_brng = (l_brng +360)%360 l_brng = (360-l_brng) return l_brng
e616746e8b962a7bb3fdd4f52d363961caa0ed10
thonyeh/Numerical-analysis-1
/Sistema lineal/house.py
1,627
3.65625
4
from math import * from Tkinter import * m = int(raw_input("ingrese el numero de filas de la matriz ")) n = int(raw_input("ingrese el numero de columnas de la matriz ")) M = [] for i in range (m): M.append([0]*(n+1)) for i in range(m): print'ingrese los %d elementos de la fila %d:'%(n,i+1) for j in range(n): M[i][j]=input('') print'ingrese el vector b' for i in range(m): M[i][n]=input('') for i in range (m): print M[i][0:n+1] b=[] for i in range(m): b.append(0) for i in range(m): b[i]=M[i][n] sigma=0 beta=0 w=[] d=[] for i in range (m): w.append(0) def Householder(): for j in range (n): mayor = abs(M[j][j]) for k in range (j+1,m): if mayor < abs(M[k][j]): mayor = abs(M[k][j]) if mayor == 0: break sigma = 0 suma=0 for k in range(j,m): suma=suma+(M[k][j]**(2)) sigma=sqrt(suma) if M[j][j]<0: sigma=sigma*(-1) for k in range(j,m): w[k]=M[k][j] w[j]=w[j]+sigma suma=0 for k in range(j,m): suma=suma+w[k]**(2) beta=2*(suma)**(-1) M[j][j]=-sigma for l in range (j+1,n): s=0 for k in range(j,m): s=s+w[k]*M[k][l] for k in range (j,m): M[k][l]=M[k][l]-w[k]*s*beta #transformacion del vector b s=0 for k in range(j,m): s=s+w[k]*b[k] for k in range (j,m): b[k]=b[k]-w[k]*s*beta print M #resolucion del sistema Rx=b
e7e0e9a1443e557161e725c82f4ba2b98a779eb3
thonyeh/Numerical-analysis-1
/Sistema no lineal/Oferta-Demanda.py
3,127
3.71875
4
from math import * from numpy import * from numpy import log as ln import sympy as sy import matplotlib.pyplot as plt def datos(a,b,w): print 'Ingrese la cantidad de datos conocidos:' m=input ('') print '' print 'Ingrese los puntos conocidos y sus respectivos f(xk)' n=m-1 M=[0]*(n+1) N=[0]*(n+1) for i in range (n+1): M[i]=input('x%d='%i) N[i]=input('f(x%d)='%i) if w==1: puntos(b,M,N,m,w) R=lagrange(M,N,m) print 'El polinomio de Lagrange es:' print 'O(x)=',R print '' if w==2: puntos(b,M,N,m,w) R=lagrange(M,N,m) print 'El polinomio de Lagrange es:' print 'D(x)=',R print '' grafica(a,b,R) return R def main(): print 'Tengamos en cuenta' print 'Q: cantidad' print 'P:precio' print 'Ingrese un intervalor [a,b].' print 'Para mejor vision en la grafica, ingrese a=0 y b>max{xi}; donde xi son sus datos conocidos ' a=input('a=') b=input ('b=') print '' print 'RELACION Q-P (OFERTA)' print '' O=datos(a,b,1) print 'RELACION Q-P (DEMANDA)' print '' D=datos(a,b,2) doscurvas(a,b,O,D) print 'Para la determinacion aproximada del punto de equilibrio' print 'Tenemos que resolver O(x)=D(x)' F=O F+='-(' F+=D F+=')' print 'es decir F=0:; donde F es:' print F menu(O,D) def menu(O,D): print '1.Evalue un valor en O(x):' print '2.Evalue un valor en D(x):' print '3.REINICIAR' print '4.SALIR' r=input('') if r==1: x=input('x=') print fx(O,x) menu(O,D) elif r==2: x=input('x=') print fx(D,x) menu(O,D) elif r==3: main() else: pass def fx(f,y): x=y m=float(eval(f)) return m def grafica(a1,b1,f): x=arange(float(a1),float(b1),0.00001) f_x=eval(f) plt.plot(x,f_x) plt.xlabel('x') plt.ylabel('f(x)') plt.show() def puntos(b,M,N,m,w): plt.plot(M,N,'ro') if w==1: plt.axis([0,b,0,N[m-1]+0.5]) if w==2: plt.axis([0,b,0,N[0]+0.5]) plt.show() def doscurvas(a,b,P,Q): x=arange(float(a),float(b),0.00001) f_x=eval(P) plt.plot(x,f_x) f_x2=eval(Q) plt.plot(x,f_x2) plt.xlabel('x') plt.show() def lagrange(M,N,m): P='' s=0 for i in range(m): s1=N[i] for j in range(m): if j!=i: s1=s1*(M[i]-M[j])**(-1) print s1 print '' s+=s1 P+=str(s) P+='*x**2' s=0 for i in range(m): s2=(-1)*N[i] p=0 for j in range(m): if j!=i: p+=M[j] s2*=p for j in range(m): if j!=i: s2=s2*(M[i]-M[j])**(-1) s+=s2 if s!=0: if s>=0: P+='+' P+=str(s) P+='*x' s=0 for i in range(m): s3=N[i] for j in range(m): if j!=i: s3=s3*(M[j])*(M[i]-M[j])**(-1) s+=s3 if s!=0: if s>=0: P+='+' P+=str(s) return P main()
7fdd9eb08f57841e63f64018e6a54b0141740200
whjr2021/G11-C4-V1-TA1-Template
/C4_TA1_Template.py
242
4.03125
4
# TA 1a: Code to print the numbers 0 to 4 using a for loop with range() function in the format range(start, stop) # TA 1b: Code to print x-coordinates of the bricks using a for loop with range() function in the format range(stop)
bda4ab6244f4b4e8a4dec085483296fac1138e64
athuras/Projects
/Euler/e9.py
1,380
3.609375
4
#!/usr/bin/env python # For whatever reason, I actually had a really hard time with this one. # The triplet algorithm below returns a list of triplets, so to answer the # problem, simply find the product of the singleton e9.triplet(1000) from aux import fermat_sum_of_squares as fss def triplet(n): '''Find 0 < a < b < c | a + b + c == n, a^2 + b^2 == c^2''' # First, lets reduce the problem space, instead of finding a, and b # find q = (a + b) | q + c == n. This reduces the scope to O(n^2) # Given the above we can assert: # max(q) < 2c, min(q) > 2 (i.e. a, b >= 1) # min(c) > n / 3, max(c) <= n - 3 (0 < a < b >= 2) qc = ((q, c) for c in xrange(n - 3, n / 3 - 1, -1) for q in xrange(2 * n - 1, 2, -1) if q + c == n) # Using Fermats sum-of-squares assertion, we take only values of c # that can be expressed as a sum of squares valid = (i for i in qc if fss(i[1]**2)) # now find a, b given q, c. # after some algebra: # (n^2)/2 == n*q - a*b abc = ((a, b, q[1]) for q in valid for b in xrange(q[0], 1, -1) for a in xrange(min([b - 1, q[0] - b]), 0, -1) if (a + b + q[1] == n and (n**2) / 2 == n * q[0] - a * b and b < q[1])) return list(abc)
67c68f61b7656ab9661ddea2bb118a8359393723
baubrun/test-cases-and-debugging-PY
/problem7.py
1,348
4.09375
4
""" The function input is an array as input. The first element of the array is a string. The second is a number. Make this function return the string repeated as many times as specified by the second element of the array. If a negative number or zero is specified, return an empty string. If any invalid parameters are supplied return undefined. For example: f(["foo", 3]) // "foofoofoo" f(["fo", 3]) // "fofofo" f(["foo", -1]) // "" """ inputs = [ ["foo", 3], ["abs", -1], ["ab", 3], [3, "jilg"], ["12345 ", 5], ] outputs = [ "foofoofoo", "", "ababab", None, "12345 12345 12345 12345 12345 " ] def eq(lhs, rhs): """lhs outputs; rhs: inputs""" if isinstance(lhs, list): for i in range(len(lhs)): if lhs[i] != rhs[i]: return False return True return lhs == rhs def verify_equals(lhs, rhs): if not eq(lhs, rhs): raise Exception("Expected output does not match actual output") def f(x): if not isinstance(x[0], str) and not isinstance(x[1], int): return None if x[1] <= 0: return "" return x[0] * x[1] def run_test(i): expected = outputs[i] actual = f(inputs[i]) verify_equals(expected, actual) for t in range(len(inputs)): run_test(t) print("All tests passed for " + __file__)
bd35c095c678ee5b7003c2b1440f974105e9aaf3
conor-mcnally/sensehat
/animations/ect.py
3,089
3.609375
4
''' Sense HAT graphic animations: circle, triangle, line, and square functions. By Ethan Tamasar, 5/15/2017 ''' from sense_hat import SenseHat import time import numpy as np import time from random import randint def circle(image, position, radius, color, timer): sense = SenseHat() width, height = 8, 8 a, b = position[0], position[1] r = radius EPSILON = 1.2 image2 = image.reshape(8,8,3) # draw the circle for y in range(height): for x in range(width): if abs((x-a)**2 + (y-b)**2 - r**2) < EPSILON**2: image2[y][x] = color image3 = image2.reshape(64,3) sense.set_pixels(image3) time.sleep(timer) return image3 def cell(image, position, color, timer): sense = SenseHat() image2 = image.reshape(8,8,3) image2[position[0],position[1]] = color image3 = image2.reshape(64,3) sense.set_pixels(image3) time.sleep(timer) def line(image, point1, point2, color, timer): sense = SenseHat() image2 = image.reshape(8,8,3) x1 = point1[0] y1 = point1[1] x2 = point2[0] y2 = point2[1] dx = (x2 - x1) dy = (y2 - y1) if abs(dx) > abs(dy) : steps = abs(dx) else : steps = abs(dy) Xincrement = dx / steps Yincrement = dy / steps x = x1 y = y1 for v in range(steps + 1): image2[y,x] = color x = x + Xincrement; y = y + Yincrement; image3 = image2.reshape(64,3) sense.set_pixels(image3) time.sleep(timer) return image3 def triangle(image, point1, point2, point3, color, timer): sense = SenseHat() image2 = image.reshape(8,8,3) line(image2, point2, point1, color, timer) line(image2, point3, point2, color, timer) line(image2, point1, point3, color, timer) image3 = image2.reshape(64,3) sense.set_pixels(image3) time.sleep(timer) return image3 def square(image, point1, point2, point3, point4, color, timer): sense = SenseHat() image2 = image.reshape(8,8,3) line(image2, point1, point2, color, 0) line(image2, point2, point3, color, 0) line(image2, point3, point4, color, 0) line(image2, point4, point1, color, 0) image3 = image2.reshape(64,3) sense.set_pixels(image3) time.sleep(timer) return image3 def clear(image): sense = SenseHat() e = [0, 0, 0] image2 = np.array([ e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e ]) image = image2 sense.set_pixels(image) return image def blinking_circle(image,position): sense = SenseHat() for x in range(0, 10): r = randint(0,255) g = randint(0,255) b = randint(0,255) image1 = circle(image,(position[0],position[1]), 3, [r, g, b], 0.1) image2 = circle(image1,(position[0],position[1]), 2, [r, g, b], 0.1) image3 = circle(image2,(position[0],position[1]), 1, [r, g, b], 0.1)
7d3d8c430b0eadbc1f57797a657dd84dfa7e9b69
Madhiyarasan/Ancit_practice
/tsk3_sum of odd & even num.py
278
4.0625
4
X = int(input(" A= ")) Y = int(input(" B= ")) even = 0 odd = 0 for number in range(X,Y + 1): if(number % 2 == 0): even = even + number else: odd = odd + number print("The Sum of Even Numbers " ,even) print("The Sum of Odd Numbers ",odd)
5cb4a583ec8a49434d41500e142cb79879070d1a
mkccyro-7/Monday_test
/IF.py
226
4.15625
4
bis = int(input("enter number of biscuits ")) if bis == 3: print("Not eaten") elif 0 < bis < 3: print("partly eaten") elif bis == 0: print("fully eaten") else: print("Enter 3 or any other number less than 3")
0a2070678b36f8668454968e997251b273fb404e
Zaja91/python-exercises
/If_Statements/making_pizza.py
435
4
4
toppings = [] available_toppings = ('pomodoro', 'mozarella', 'funghi', 'salsiccia', 'alici', 'wurstel') print(f"Questa e la lista delle possibili scelte per creare la tua pizza: {available_toppings}") still_choosing = True while still_choosing: name = input("\n What ingredient do you want:") toppings.append(name) if name == 'quit': still_choosing = False toppings.pop() print(f"La tua pizza: {toppings}")
f029326ea49aaa4f1157fd6da18d6847144c5e26
Fran0616/beetles
/beatles.py
821
4.1875
4
#The beatles line up #empty list name beetles beatles = [] beatles.append("John Lennon") beatles.append("Paul McCartney") beatles.append("George Harrison") print("The beatles consist of ", beatles) print("Both name must be enter as written below\n") for i in beatles: i = input("Enter the name \"Stu Sutcliffe\": ") x = input("Enter the name \"Pete Best\": ") if i == "Stu Sutcliffe" and x == "Pete Best" : beatles.append(i) beatles.append(x) print("The beatles consist of ", beatles) break print("Will now remove Peter Best and Stu Sutcliffe from the group") #Deleting Stu Sutcliffe del beatles[3] #Deleting Pete Best del beatles[3] print("The beatles consist of ", beatles) print("Lets add Ringo Starr to the list ") beatles.insert(0, "Ringo Starr") print("The beatles now consist of: ", beatles)
5e55a27ef3a9fc45e5665c3b927c27c434525f6a
umaimagit/CodilitySolutions
/10. Prime n Composite Number/MinPerimeterRectangle.py
615
3.859375
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 14 17:58:25 2018 @author: Umaima """ # MinPerimeterRectangle # Find the minimal perimeter of any rectangle whose area equals N. def solution(N): # write your code in Python 3.6 if N <=0 : return 0 elif N == 1: return 4 perimeter = [] i = 1 while i * i <=N: if N % i == 0: side1 = N / i side2 = N / side1 perimeter.append(int(2 * (side1 + side2))) i += 1 return min(perimeter) A = 36 res = solution(A) print("A: " + str(A)) print("Result: " +str(res))
b37908cd9113aba08a87187cfc713c652be818a8
umaimagit/CodilitySolutions
/12. Euclidean algorithm/ChoclatesByNumbers.py
889
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 15 16:59:07 2018 @author: Umaima """ # ChocolatesByNumbers # There are N chocolates in a circle. Count the number of chocolates you will eat. # Below solution 50 % #def solution(N, M): # # if N == 0 : # return 0 # # if M == 0: # return N # # A = [] # # i = 0 # inc = 0 # # test = False # while test == False : # # inc = (i + M) % N # A.append(inc) # if A.count(inc) > 1: # test = True # i= i + M # # return len(A) -1 def gcd(a, b): mod = a % b if mod == 0: return b else: return gcd(b, mod) def solution(N, M): lcm = N * M /gcd(N, M) res = lcm / M return int(res) N = 10 M = 4 res = solution(N,M) print("N: ", N) print("M: ", M) print("Result: " +str(res))
4bff77a7850c72e6a9217ad9a28c446759c80184
umaimagit/CodilitySolutions
/extra/test3.py
571
3.53125
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 2 15:58:51 2018 @author: Umaima """ # test 3 correct code def solution(S): N = len(S) if N == 0: return 0 res = [0] start = "" end = "" ecount = N-1 for i in range(0, N): start = start + S[i] end = S[ecount] + end ecount = ecount - 1 if start == end: res.append(len(start)) res.pop() return max(res) S = "abbabba" #S = "codility" res = solution(S) print("S ",S) print("Res ",res)
a97e646cd9f7350f7f0e5294aa7e9abde183178d
umaimagit/CodilitySolutions
/15. Caterpiller Method/CountTriangles.py
914
3.796875
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 16 16:36:01 2018 @author: Umaima """ #CountTriangles #Count the number of triangles that can be built from a given set of edges. def solution(A): N = len(A) if(N < 3): return 0 A.sort() count = 0 # Below code 66 % result # for i in range(0, len(A)-2): # for j in range(i+1, len(A) - 1): # for k in range(j+1, len(A)): # # if ((A[i] + A[j]) > A[k]) and ((A[j] + A[k]) > A[i]) and ((A[k] + A[i]) > A[j]): # # count = count + 1 for i in range(0, N): z = i + 2 for j in range(i+1, N): while z < N and (A[i] + A[j]) > A[z]: z +=1 count += z - j - 1 return count A = [10,2,5,1,8,12] res = solution(A) print("A: " + str(A)) print("Result: " +str(res))
68e976659800b4f9c281e5186a741dc89fe4dbb2
AselK/Python
/for/Task1.py
270
3.90625
4
#Task1 Даны два целых числа A и B (при этом A ≤ B). Выведите все числа от A до B включительно a = int(input("Enter a: ")) b = int(input("Enter b: ")) if a <= b: for q in range(a, b + 1): print(q)
590a88d5eda6d642b44204a2d4435ea2b6c6b192
nguyenngochuy91/programming
/interview/ARRAYS/constructSquare.py
1,593
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 23 14:00:30 2019 @author: huyn """ #Given a string consisting of lowercase English letters, find the largest square number which #can be obtained by reordering the string's characters and replacing them with any digits you need #(leading zeros are not allowed) where same characters always map to the same digits and different characters always map to different digits. # #If there is no solution, return -1. def constructSquare(s): v = len(s) ds = {} dv = {} for l in s: if l not in ds: ds[l]=0 ds[l]+=1 for key in ds: val = ds[key] if val not in dv: dv[val]=[] dv[val].append(key) if len(ds)>10: return -1 if v ==1: return 9 start = int((10**(v-1))**.5) stop = int((10**v)**.5) for i in range(stop,start,-1): i = i**2 # check if there is a valid mapping num = str(i) ds = {} dn= {} check = True for l in num: if l not in ds: ds[l]=0 ds[l]+=1 for key in ds: v = ds[key] if v not in dn: dn[v]=[] dn[v].append(key) if len(dn)!=len(dv): continue for key in dn: if key not in dv: check = False break else: if len(dv[key])!=len(dn[key]): check = False break if check: return i return -1
0fd8177dcfaad841921329dc785e3fead49abff7
nguyenngochuy91/programming
/google code jam/2018/qualification/Go_Gopher.py
1,596
3.921875
4
""" Problem The Code Jam team has just purchased an orchard that is a two-dimensional matrix of cells of unprepared soil, with 1000 rows and 1000 columns. We plan to use this orchard to grow a variety of trees — AVL, binary, red-black, splay, and so on — so we need to prepare some of the cells by digging holes: In order to have enough trees to use for each year's tree problems, we need there to be at least A prepared cells. In order to care for our trees properly, the set of all prepared cells must form a single grid-aligned rectangle in which every cell within the rectangle is prepared. Note that the above also implies that none of the cells outside of that rectangle can be prepared. We want the orchard to look tidy! For example, when A=11, although the eleven prepared cells in the left figure below form a 3x4 rectangle (that is, with 3 rows and 4 columns), the cell in the center of the rectangle is not prepared. As a result, we have not yet completed preparing our orchard, since not every cell of the 3x4 rectangle is prepared. However, after just preparing the center cell, the rectangle of size at least 11 is fully filled, and the orchard is ready. Input T test Case A : minimum required prepared rectangular area process up to 1000 exchanges Sending I,J: row, column to deploy gopher 2<=i,j<=999 after 1000 I=0 ,J=0 : Correct I'=J'=-1: Incorrect """ import sys def solve(A): return result T = int(input()) for i in range(1, T + 1): A = int(input()) print("Case #{}: {}".format(T, result)) sys.stdout.flush()
c37472030cb3d72b60c0d5ccea081943992cc6d3
nguyenngochuy91/programming
/interview/ARRAYS/sort012Right.py
462
3.703125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 23 13:54:19 2019 @author: huyn """ def sort012Left(array): zero = 0 one = 0 two = len(array)-1 while one <=two: if array[one]==0: array[zero],array[one] = array[one],array[zero] zero+=1 one+=1 elif array[one]==1: one+=1 else: array[one],array[two]= array[two],array[one] two-=1 return array
dac7f02c8ac52601fac15dc17f051338f96f8d44
nguyenngochuy91/programming
/interview/BST/minEatingSpeed.py
1,141
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 23 14:08:25 2019 @author: huyn """ #875. Koko Eating Bananas #Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. #The guards have gone and will come back in H hours. # #Koko can decide her bananas-per-hour eating speed of K. Each hour, she chooses some pile of bananas, #and eats K bananas from that pile. If the pile has less than K bananas, she eats all of them instead, #and won't eat any more bananas during this hour. # #Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. # #Return the minimum integer K such that she can eat all the bananas within H hours. def minEatingSpeed(piles, H): def check(piles,K,H): hour = 0 for p in piles: hour+=p//K if p%K: hour+=1 return hour<=H start,stop = 0, max(piles) while start+1<stop: mid = (start+stop)//2 if check(piles,mid,H): stop = mid else: start = mid if check(piles,stop,H): return stop return start
b2d24ba64d36887d86851907621bcab0f4a00964
nguyenngochuy91/programming
/interview/BFS/BFS.py
2,979
3.984375
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 14 15:00:25 2019 @author: huyn """ import heapq,typing from collections import deque class TreeNode(object): def __init__(self, x,left=None,right=None): self.val = x self.left = left self.right = right # given a graph where vertices are cities, edge between vertices are bridges, with weight # given a graph, indicate by list of list, where each element of list [startNode,endNode,weight], # a source node, an end node, and k. Find the minimum weight path from source to end within k steps. def findCheapestPrice(n, flights, src, dst, k): k+=1 # Write your code here # initiate our priority queue priorityQueue = [] # initiate our distance as a dictionary distances = {i:float("inf") for i in range(n)} # generate a graph using our flights info graphs = {} # update this using our flights info for flight in flights: start,end,cost = flight if start not in graphs: graphs[start]={} graphs[start][end] = cost # push our src into the queue, each of item in queue store heapq.heappush(priorityQueue,(0,src,0)) # set distance to source as 0 distances[src]=0 while len(priorityQueue)!=0: print (priorityQueue) current_distance,current_vertex, current_step = heapq.heappop(priorityQueue) if current_vertex not in graphs: continue if current_vertex == dst: return current_distance for neighbor in graphs[current_vertex]: neighbor_distance = graphs[current_vertex][neighbor] # find the distance from src to this neighbor through our current_vertex distance = distances[current_vertex]+neighbor_distance # if this distance is currently less than the neighbor and the step +1 does not get over k, we insert it back if current_step+1<=k and distance<=distances[neighbor]: distances[neighbor] = distance heapq.heappush(priorityQueue,(distance,neighbor,current_step+1)) if distances[dst]==float("inf"): return -1 else: return distances[dst] #1161. Maximum Level Sum of a Binary Tree #Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. #Return the smallest level X such that the sum of all the values of nodes at level X is maximal. def maxLevelSum(self, root: TreeNode) -> int: currentL = 1 bestL,maxSum = 0,-float("inf") queue = deque([root]) while queue: currentSum,size = 0,len(queue) for _ in range(size): node = queue.popleft() currentSum+=node.val if node.left: queue.append(node.left) if node.right: queue.append(node.right) if currentSum>maxSum: bestL = currentL maxSum = currentSum currentL+=1 return bestL
b4c7a7fe4fe66fff18c0ffe10218c1719fa451d9
nguyenngochuy91/programming
/interview/DP/5216_CountVowelsPermutation.py
636
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 23:03:33 2019 @author: huyn """ #5216. Count Vowels Permutation def countVowelPermutation(n: int) -> int: d= {"a":"e","e":"ai","i":"aeou","o":"iu","u":"a"} if n==1: return 5 count = {"a":1,"e":1,"i":1,"o":1,"u":1} for i in range(n-1): newcount = {"a":0,"e":0,"i":0,"o":0,"u":0} for letter in "aeiou": for possible in d[letter]: newcount[possible]+=count[letter] count = {key:newcount[key]%(10**9+7) for key in newcount} res = 0 for key in count: res= (res+count[key])%(10**9+7) return res
1acd61984c36759fb5112c1ffb57842832627430
nguyenngochuy91/programming
/google code jam/2008/qualification/Fly_Swatter.py
2,131
3.828125
4
# -*- coding: utf-8 -*- """ What are your chances of hitting a fly with a tennis racquet? To start with, ignore the racquet's handle. Assume the racquet is a perfect ring, of outer radius R and thickness t (so the inner radius of the ring is R−t). The ring is covered with horizontal and vertical strings. Each string is a cylinder of radius r. Each string is a chord of the ring (a straight line connecting two points of the circle). There is a gap of length g between neighbouring strings. The strings are symmetric with respect to the center of the racquet i.e. there is a pair of strings whose centers meet at the center of the ring. The fly is a sphere of radius f. Assume that the racquet is moving in a straight line perpendicular to the plane of the ring. Assume also that the fly's center is inside the outer radius of the racquet and is equally likely to be anywhere within that radius. Any overlap between the fly and the racquet (the ring or a string) counts as a hit. Input One line containing an integer N, the number of test cases in the input file. The next N lines will each contain the numbers f, R, t, r and g separated by exactly one space. Also the numbers will have at most 6 digits after the decimal point. Output N lines, each of the form "Case #k: P", where k is the number of the test case and P is the probability of hitting the fly with a piece of the racquet. Answers with a relative or absolute error of at most 10-6 will be considered correct. """ from math import pi def findProbabilityHitting(f,R,t,r,g): result = 0.0 smallerRadius = R-t smallerCircleArea = pi*smallerRadius**2 # need to find free space inside smaller area # find number of string return round(result,7) def solve(infile,outfile): handle = open(infile,"r") N = int(handle.readline().strip()) outfile = open(outfile,"w") for testCase in range(1,N+1): f,R,t,r,g = [float(item) for item in handle.readline().strip().split()] P = findProbabilityHitting(f,R,t,r,g) outfile.write("Case #{}: {}\n".format(testCase,P)) outfile.close()
b50da8420a1585d387e5995f9e04eb3f72e336b8
nguyenngochuy91/programming
/google kick start/2019/round c/Wiggle_Walk.py
2,691
3.5625
4
# -*- coding: utf-8 -*- """ """ import sys T = int(input().strip()) def solve(instructions,R,C,SR,SC): d = {"R":{},"C":{}} d["R"][SC]=[[SR,SR]] d["C"][SR] = [[SC,SC]] visited = set() visited.add((SR,SC)) for instruction in instructions: if instruction=="N": SR-=1 if (SR,SC) in visited: # look at the array of interval of SR rowIntervals = insertInterval(d["R"][SC],SR,-1) d["R"][SC] = rowIntervals elif instruction == "S": SR+=1 if (SR,SC) in visited: # look at the array of interval of SR rowIntervals = insertInterval(d["R"][SC],SR,1) d["R"][SC] = rowIntervals elif instruction =="E": SC+=1 if (SR,SC) in visited: # look at the array of interval of SR colIntervals = insertInterval(d["C"][SR],SC,1) d["C"][SR] = rowIntervals else: SC-=1 if (SR,SC) in visited: # look at the array of interval of SR colIntervals = insertInterval(d["C"][SR],SC,-1) d["C"][SR] = rowIntervals # now we update our d and visited visited.add((SR,SC)) print (instruction,SR,SC) return SR,SC def insertInterval(intervals,SR,toAdd): output = [] i = 0 while i <len(intervals): interval = intervals[i] if SR>=interval[0] and SR<=interval[1]: if toAdd==1: highestR=interval+1 # check if we will have to merge if i+1<len(intervals): newInterval = intervals[i+1] if highestR>=newInterval[0] and highestR<=newInterval[1]: # merge interval[1] = newInterval[1] i= i+1 else: interval[1]+=1 else: lowestR = interval-1 if i-1 >=0: lastInterval = intervals[i-1] if lowestR>=lastInterval[0] and lowestR<=lastInterval[1]: interval[0]=lastInterval[0] # we have to pop last item in output output.pop() else: interval[0]-=1 i+=1 output.append(interval) output.append(newInterval) return output for i in range(T): N, R, C, SR , SC = [int(item) for item in input().split()] instructions = input() FR,FC = solve(instructions,R,C,SR,SC) print ("Case #{}: {} {}".format(i+1,FR,FC))
b35560cf7a36722b4b1e6f265ca31d1468cffb03
nguyenngochuy91/programming
/interview/GRAPH/graph.py
16,876
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 2 21:46:44 2019 @author: huyn """ import heapq from collections import deque # generate matrix given edges def generate(arr,n): d= {} for x,y in arr: if x not in d: d[x]=[] if y not in d: d[y]=[] d[x].append(y) d[y].append(x) matrix = [] for i in range(n): tmp= [] if i not in d: matrix.append([0]*n) continue for j in range(n): if j in d[i]: tmp.append(1) else: tmp.append(0) matrix.append(tmp) return matrix #The Ruler of HackerLand believes that every citizen of the country should have access to a library. #Unfortunately, HackerLand was hit by a tornado that destroyed all of its libraries and obstructed its roads! #As you are the greatest programmer of HackerLand, the ruler wants your help to repair the roads and build #some new libraries efficiently. # #HackerLand has cities numbered from to . The cities are connected by bidirectional roads. #A citizen has access to a library if: # #Their city contains a library. #They can travel by road from their city to a city containing a library. #The following figure is a sample map of HackerLand where the dotted lines denote obstructed roads: def roadsAndLibraries(n, c_lib, c_road, cities): if c_lib<=c_road: return c_lib*n d= {} for edge in cities: start,stop = edge if start not in d: d[start]=set() if stop not in d: d[stop]=set() d[start].add(stop) d[stop].add(start) # find connected component cc = [] visited = set() while cities: start,stop = cities.pop() newComponent = [] if start in visited or stop in visited: continue else: queue = [start] while queue: node = queue.pop() visited.add(node) heapq.heappush(newComponent,(-len(d[node]),node)) for neighbor in d[start]: if neighbor not in visited: queue.append(neighbor) cc.append(newComponent) minimum = 0 for component in cc: minimum+=c_lib+c_road*(len(component)-1) return minimum # for component in cc: #n, c_lib, c_road, cities=3,2,1,[[1, 2], [3, 1], [2, 3]] #roadsAndLibraries(n, c_lib, c_road, cities) #n, c_lib, c_road, cities=6 ,2, 5, [[1, 3], [3, 4], [2, 4], [1, 2], [2, 3], [5, 6]] #roadsAndLibraries(n, c_lib, c_road, cities) # find the nearest clone # https://www.hackerrank.com/challenges/find-the-nearest-clone/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=graphs def findShortest(graph_nodes, graph_from, graph_to, ids, val): edges = {} for i in range(len(graph_from)): start = graph_from[i] stop = graph_to[i] if start not in edges: edges[start]=[] if stop not in edges: edges[stop]=[] edges[start].append(stop) edges[stop].append(start) colors = set() for i in range(len(ids)): if ids[i]==val: colors.add(i+1) if len(colors)<=1: return -1 minimum = float("inf") visited = set() for id in colors: if id in visited: continue visited.add(id) queue = deque([]) count = 1 for neighbor in edges[id]: if neighbor not in visited: queue.append(neighbor) while queue: size = len(queue) for i in range(size): node = queue.popleft() visited.add(node) if ids[node-1]==val: minimum= min(minimum,count) break for neighbor in edges[node]: if neighbor not in visited: queue.append(neighbor) count+=1 return minimum #graph_nodes, graph_from, graph_to, ids, val= 4 ,[1, 1, 4] ,[2, 3, 2] ,[1, 2, 1, 1], 1 #findShortest(graph_nodes, graph_from, graph_to, ids, val) graph_nodes, graph_from, graph_to, ids, val=5 ,[1, 1, 2, 3] ,[2, 3, 4, 5] ,[1, 2, 3, 3, 2] ,2 #print(findShortest(graph_nodes, graph_from, graph_to, ids, val)) #DFS: Connected Cell in a Grid def maxRegion(grid): row = len(grid) col = len(grid[0]) def dfs(grid,x,y,row,col): size = 0 if grid[x][y]: grid[x][y]=0 size+=1 temp = [(1,1),(-1,-1),(1,-1),(-1,1), (0,1),(1,0),(0,-1),(-1,0)] for a,b in temp: newX,newY=x+a,b+y if newX>=0 and newX<row and newY>=0 and newY<col: size+= dfs(grid,newX,newY,row,col) return size myMax = 0 for i in range(row): for j in range(col): myMax= max(myMax,dfs(grid,i,j,row,col)) return myMax #grid = [[1,1,0,0], # [0,1,1,0], # [0,0,1,0], # [1,0,0,0] # ] #print (maxRegion(grid)) def minTime(roads, machines,n): d= {} minimal =0 # if any of the machine share an edge, delete the edge,add the weight # for start,end,time in roads: # return #roads,machines=[[2, 1, 8], [1, 0, 5], [2, 4, 5], [1, 3, 4]] ,[2, 4, 0] #print (minTime(roads, machines)) #roads,machines=[[0, 1, 4], [1, 2, 3], [1, 3, 7], [0, 4, 2]] ,[2, 3, 4] #print (minTime(roads, machines)) #684. Redundant Connection #In this problem, a tree is an undirected graph that is connected and has no cycles. # #The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), # with one additional edge added. #The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed. # #The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, #that represents an undirected edge connecting nodes u and v. # #Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple #answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the # same format, with u < v. def findRedundantConnection(edges): d = {} n= 0 v= {} for i in range(len(edges)): start,stop = edges[i] if start not in d: d[start] = [] if stop not in d: d[stop] = [] d[start].append(stop) d[stop].append(start) n= max(n,stop) v[tuple(edges[i])] = i visited = {i+1:False for i in range(n)} myPath = [] def dfs(currentNode,parent,path): check = False for neighbor in d[currentNode]: if parent!=neighbor: if visited[neighbor]: # we hit a circle path.append([currentNode,neighbor]) # print (path,currentNode,neighbor,"visited") # get the cycle # print (path) for i in range(len(path)): edge = path[i] # print (edge) if edge[0]!=neighbor: continue else: break for i in range(i,len(path)): edge = path[i] myPath.append(tuple(sorted(edge))) # print (myPath) return True elif neighbor in d: visited[neighbor]= True # print (currentNode,neighbor) path.append([currentNode,neighbor]) check = dfs(neighbor,currentNode,path) if check: break path.pop() return check for i in range(1,n+1): if not visited[i] and i in d: visited[i]= True check = dfs(i,None,[]) if check: break edge= None index = 0 # print (myPath) for path in myPath: if v[path]>index: index= v[path] edge =list(path) return edge #edges = [[1,2], [2,3], [3,4], [1,4], [1,5],[6,7],[8,9]] #print (findRedundantConnection(edges)) #834. Sum of Distances in Tree #An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given. # #The ith edge connects nodes edges[i][0] and edges[i][1] together. # #Return a list ans, where ans[i] is the sum of the distances between node i and all other nodes. def sumOfDistancesInTree(N,edges): res = [] return #given a graph, find the number of connected component def numberOfConnectedComponent(matrix): size =0 n = len(matrix) visited = [False]*n def dfs(visited,current,n): for node in range(n): if matrix[current][node] and not visited[node]: visited[node]= True dfs(visited,node,n) for node in range(n): if not visited[node]: size+=1 dfs(visited,node,n) return size #matrix = [[False,True,False,True], # [True,False,True,False], # [False,True,False,True], # [True,False,True,False]] #print (numberOfConnectedComponent(matrix)) #given a graph, and a vertex, find the size of connected component of that vertex def dfsComponentSize(matrix, vertex): n = len(matrix) visited = [False]*n visited[vertex]= True def dfs(visited,current,n): size = 1 for node in range(n): if matrix[current][node] and not visited[node]: visited[node]= True size+=dfs(visited,node,n) return size return dfs(visited,vertex,n) #given a graph, get all the connected component, recursive style def findAllConnectedComponentDFS(matrix): n = len(matrix) visited = [False]*n cc= [] def dfs(visited,current,n): path =[current] for node in range(n): if matrix[current][node] and not visited[node]: visited[node]= True path.extend(dfs(visited,node,n)) return path for node in range(n): if not visited[node]: visited[node]= True path = dfs(visited,node,n) cc.append(path) return cc #arr = [[1,2],[2,3],[4,5],[7,8],[9,10],[10,11]] #matrix = generate(arr,11) #print (matrix) #print (findAllConnectedComponentDFS(matrix)) #given a graph, get all the connected component, while style def findAllConnectedComponentBFS(matrix): n = len(matrix) visited = [False]*n cc= [] for node in range(n): if not visited[node]: queue = [node] visited[node] = True path = [] while queue: currentNode = queue.pop() path.append(currentNode) for neighbor in range(n): if not visited[neighbor] and matrix[currentNode][neighbor]: visited[neighbor] = True queue.append(neighbor) cc.append(path) return cc #arr = [[1,2],[2,3],[4,5],[7,8],[9,10],[10,11]] #matrix = generate(arr,11) #print (matrix) #print (findAllConnectedComponentBFS(matrix)) # given a graph, check if it is a tree (no cycle, and all connected) def isTree(matrix): n = len(matrix) numberOfConnected = 0 visited = [False]*n def dfs(visited,currentNode,parentNode,n): for node in range(n): if visited[node] and node !=parentNode and matrix[currentNode][node]: return True elif not visited[node] and matrix[currentNode][node]: visited[node]= True if dfs(visited,node,currentNode,n): return True return False for node in range(n): if not visited[node]: numberOfConnected+=1 visited[node]=True if dfs(visited,node,None,n): return False # print (numberOfConnected) return numberOfConnected==1 #arr = [[0,1],[1,2],[2,3],[3,4],[2,5],[4,6],[1,7],[5,0]] #matrix = generate(arr,7) #print (matrix) #print (isTree(matrix)) # given a graph, check it has a cycle, using normal dfs def hasCycle(matrix): n = len(matrix) visited = [False]*n def dfs(visited,currentNode,parentNode,n): for node in range(n): if matrix[currentNode][node]: # if the node is visited and not same as parent if parentNode!=node and visited[node]: return True elif not visited(node): visited[node] = True if dfs(visited,node,currentNode,n): return True return False for node in range(n): if not visited[node]: visited[node] = True if dfs(visited,node,None,n): return True return False # given a graph, check it has a cycle using coloring def hasCycleColor(matrix): return # given a graph, find all of its cycle def getAllCycle(matrix): n = len(matrix) #785. Is Graph Bipartite? def isBipartite(graph): d = {} for node,neighbors in enumerate(graph): if node not in d: # have not assign this node, that means any of the edge was not assigned neither stack = [node] d[node] = 0 while stack: node = stack.pop() for neighbor in graph[node]: if neighbor not in d: stack.append(neighbor) d[neighbor]= 1-d[node] elif d[neighbor]==d[node]: return False return True #graph = [[1,3], [0,2], [1,3], [0,2]] #print (isBipartite(graph)) #graph = [[1,2,3], [0,2], [0,1,3], [0,2]] #print (isBipartite(graph)) def smallestStringWithSwaps(s, pairs) -> str: edges = {} for index in range(len(s)): edges[index]= [] for x,y in pairs: edges[x].append(y) edges[y].append(x) visited= [False]*len(s) cc = [] def dfs(currentIndex,component): for neighbor in edges[currentIndex]: if not visited[neighbor]: visited[neighbor] = True component.append(neighbor) dfs(neighbor,component) for index in range(len(s)): if not visited[index]: visited[index]= True component = [index] dfs(index,component) cc.append(sorted(component)) s= list(s) for component in cc: stringComponent = [s[index] for index in component] stringComponent.sort() # print (stringComponent) for i in range(len(component)): indexToFillInS = component[i] letterToFill = stringComponent[i] s[indexToFillInS] = letterToFill return "".join(s) #s = "cba" #pairs = [[0,1],[1,2]] #print (smallestStringWithSwaps(s,pairs)) def nthUglyNumberNaive(n: int, a: int, b: int, c: int) -> int: a,b,c = sorted([a,b,c]) array = [a,b,c] smallest= min(array) n-=1 while n: if smallest == array[0]: array[0]+=a if array[1]==array[0]: array[1]+=b if array[2]==array[0]: array[2]+=c elif smallest ==array[1]: array[1]+=b if array[1]==array[0]: array[0]+=a if array[2]==array[1]: array[2]+=c else: array[2]+=c if array[1]==array[2]: array[1]+=b if array[2]==array[0]: array[0]+=a n-=1 smallest= min(array) print(array) return smallest #5200. Sort Items by Groups Respecting Dependencies #There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. # #Return a sorted list of the items such that: # #The items that belong to the same group are next to each other in the sorted list. #There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item). #Return any solution if there is more than one solution and return an empty list if there is no solution. # # def sortItems(n, m, group, beforeItems): d= {} for index in range(n): gr = group[index] n = 8 m = 2 group = [-1,-1,1,0,0,1,0,-1] beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
1836cc0e8889275fc16de885c28ad53e53fa4190
sabrina04/python-practice
/hackerrank/zip.py
433
3.921875
4
"""The first line contains and separated by a space. The next lines contains the space separated marks obtained by students in a particular subject. Print the averages of all students on separate lines.Print the averages of all students on separate lines.""" #!/usr/bin/python n,x = map(int, raw_input().split()) l = [] for i in range(x): l.append(map(float, raw_input().split())) for i in zip(*l): print sum(i)/len(i)
c4013a6320521c1f9ff26e95de8e0c91d70b38d0
Biarys/bt_plat
/Backtest/Templates.py
1,170
3.765625
4
import abc class DataReader: def __init__(self): self.data = {} def csvFile(self, path): #read one _file pass def readFiles(self, path): #read many files pass class Indicator(metaclass=abc.ABCMeta): """Abstract class for an indicator. Requires cols (of data) to be used for calculations""" @abc.abstractmethod def __init__(self, cols): pass @abc.abstractmethod def __call__(self): pass buyCond = sma5() > sma25() sellCond = sma5() < sma25() class TradeSignal: """ For now, long only. 1 where buy, 0 where sell Possibly add signal shift - added for now to match excel results """ def __init__(self, buyCond, sellCond): pass class TransPrice(TradeSignal): """ Raw transaction price meaning only initial buy and sellf prices are recorded without forward fill. """ def __init__(self, buyOn="Close", sellOn="Close"): pass class Returns(TransPrice): """ Calculate returns """ def __init__(self): pass class Stats(): """ Calculate stats on returns """ def __init__(self): pass
53a552b5666e4d95f73f8143d66daabb04f96b0e
jrparadis/eecummingsbot
/eecummings.py
1,409
4.0625
4
## ## formats everything into the style of an e.e. cummings poem. ## ## import random and text to speech from random import randrange import pyttsx ## text to turn into a poem text = ''' The Dodge Custom Royal is an automobile which was produced by Dodge in the United States for the 1955 through 1959 model years. In each of these years the Custom Royal was the top trim level of the Dodge line, above the mid level Dodge Royal and the base level Dodge Coronet. ''' ## characters to randomly insert fChar = ['\t', '\t(', ') ', '\n \t \t', '\n \t', ' ', ' ', ', ', ' ', ' ', ' ', '... ', '\n'] ## split the text t = text.split() ## make a function to return a number between 0 and the length of the def randPunct(): return randrange(0,len(fChar)) ## variables for changing variable types in the loops b = {} newT = {} i = 0 newerT = [] ## go through the split text, for each word pick a random formatting character from fChar for each in t: b[i] = fChar[randPunct()] newT[i] = each + b[i] i += 1 ## loop again and put it in the right variable type for each in newT: newerT += newT[each] ## put it all together together = ''.join(newerT) ## print it out print together ## use text to speech to say the text. helps to get an understand of the timing of the poem. engine = pyttsx.init() engine.say(together) engine.runAndWait()
d7e667067c4be8c691a512db9c6b4b32c96a07d2
ncerne00/Introduction_to_Python
/sets_and_dictionaries.py
1,961
4.03125
4
skills = {"Python", "Java", "Skateboarding", "Origami", "Woodworking"} print(skills) print("The number of skills in the set is", len(skills)) for skill in skills: print(skill) print() if "origami" in skills: print("Paper folding is my life.") skills.add("Problem-Solving") #adds one element skills.update(["SQL", "Graphic Design", "HTML", "Moonwalking"]) #adds several elements print(skills) skills.discard("Woodworking") # removes one element, doesn't pose an error if woodworking isnt in the list. The remove() command will. needed_skills = {"Python", "Jui-Jitsu", "Origami"} if skills <= needed_skills: print("This person has everything.") else: print("This person does not have all of the needed skills.") print("This person has these needed skills:", skills & needed_skills) # prints the elements that are in both sets print("This person lacks these needed skills:", needed_skills - skills) favorite_colors = {"Bob" : "Blue", "Sue" : "Purple", "Dylan" : "Orange", "Amy" : "Green", "Max" : "Chartreuse"} print(favorite_colors) print("There are", len(favorite_colors), "favorite color entries.") print("Dylan's favorite color is:", favorite_colors["Dylan"]) print("Amy's favorite color is:", favorite_colors.get("Amy")) favorite_colors["Fred"] = "Firehouse Red" # gets added in as a new entry favorite_colors["Max"] = "Brown" print(favorite_colors) favorite_colors.pop("Sue") print(favorite_colors) thing = {} thing2 = set() if "Sue" in favorite_colors: print("Sue's favorite color is", favorite_colors["Sue"]) else: print("I don't know what Sue's favorite color is.") for person in favorite_colors: print(person) for color in favorite_colors.values(): # .values prints the values, not the thing before the : print(color) for person, color in favorite_colors.items(): print(person + "'s favorite color is " + color)
0a29f5e6e2a53f839757c3f4ad0a438a8c90be30
ncerne00/Introduction_to_Python
/Virginia_Census_Example.py
1,022
3.875
4
file = open("Virginia_Census_2010.csv", "r", encoding="UTF-8-sig") vmap = {} for line in file: line = line.rstrip("\n") line = line.split(",") city = line[0].strip() population = int(line[1]) vmap[city] = population print("The dictionary contains", len(vmap), "entries.") print(vmap) print() for city in vmap: print(city, "Has a population of", vmap[city]) print() print("Blacksburg population:", vmap["Blacksburg"] ) vmap["Riner"] = 859 print() print("Riner population:", vmap["Riner"]) bigger = "" if vmap["Christiansburg"] > vmap["Blacksburg"]: bigger = "Christiansburg" else: bigger = "Blacksburg" difference = abs(vmap["Blacksburg"] - vmap["Christiansburg"]) print(bigger, "is larger by", difference, "people.") smallest = ("Blacksburg", vmap["Blacksburg"]) for city, population in vmap.items(): if population < smallest[1]: smallest = (city, population) print() print("The smallest city in Virginia is", smallest[0], "with a population of", smallest[1])
93642ed09a8bf109c903cd3dd2d3a5f5c910418c
ncerne00/Introduction_to_Python
/more_decisions.py
1,639
3.984375
4
size = 344 weight = 170 if size < 120: if weight < 100: print("It fits") else: print("Too heavy") else: print("Too big") if size < 120 and weight < 100: print("It fits") else: print("Too big or too heavy") project_duration = 10 if project_duration > 30: project_duration += 14 else: if project_duration > 14: project_duration += 7 else: if project_duration > 7: project_duration += 2 if project_duration > 30: project_duration += 14 elif project_duration > 14: project_duration += 7 elif project_duration > 7: project_duration += 2 print("project duration:", project_duration) cars_sold = 15 if cars_sold == 0: print("Unacceptable") elif cars_sold < 10: print("Less than desired") elif cars_sold < 20: print("Well done") else: print("excellent") if "alpaca" < "baboon": print("alpaca comes before baboon") else: print("baboon comes before alpaca") if "&@%*" < "#$!^": print("&@%* comes first") else: print("#$!^ comes first") # strings are sorted via unicode, in this case # comes first, and letters are in alphabetical order if ("alpaca" < "Baboon"): print("alpaca comes before Baboon") else: print("Baboon comes before alpaca") # capital letters come first before lowercase letters in the list of unicode event_description = "The ultimate party of the year!" if "party" in event_description: # in, not in, these are membership operators print("I'm there") if "studysession" not in event_description: print("I need to be intellectually challenged.") print("all done")
a81b7557ab5e822663c1e5a3f25b2e3ea75419df
Hack-Light/Python-Projects
/cube.py
127
3.734375
4
def cube(base, pow): result = 1 for index in range(pow): result *= base return result cub = cube(2,3) print(cub)
529f0b663b0610bca8278098d01cd5a26d43bb91
xmpf/aoc-2020
/DAY-3/part1.py
420
3.625
4
#!/usr/bin/env python3 if __name__ == "__main__": # parse input data = [ line.rstrip() for line in open("input", "r").readlines() ] # initial values x = 1 y = 3 total = 0 # corners width = len(data[0]) height = len(data) # processing while x < height: total += int(data[x][y] == '#') x += 1 y = (y + 3) % width print('Total trees:', total)
10727e7ae0ea9e908ca4e19b36dc75138b021eea
kesarwaniprakhar/Algorithms-codes
/insertionsort.py
735
3.875
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 15 20:29:29 2019 @author: prakhar prakash """ list1 = list() size = int(input('Enter the size of the list')) for r in range(size): list1.append(r) list1[r] = int(input('Enter the value at location ' + str(r) + ':')) print(list1) def insertionsort(list1): for r in range(len(list1)): key = list1[r] s = r-1 while(s >= 0 and key < list1[s]): #print(list1[s],list1[s+1]) list1[s+1] = list1[s] list1[s] = key # print(list1[s],list1[s+1]) s -= 1 insertionsort(list1) print(list1)
b4e0cfd09d1739e6dbe9d6b4397680eafbb110d7
kesarwaniprakhar/Algorithms-codes
/bubblesort.py
800
4
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 15 18:05:04 2019 @author: prakhar prakash """ list1 = list() size = int(input('Enter the size of the list')) for r in range(size): list1.append(r) list1[r] = int(input('Enter the value at location ' + str(r) + ':')) print(list1) def bubble(list1): istrue = False n = len(list1)-1 #this is optimised implementation while not istrue: istrue = True for r in range(n): if list1[r] > list1[r+1]: temp = list1[r] list1[r] = list1[r+1] list1[r+1] = temp istrue = False n -= 1 bubble(list1) print(list1)
ff3740adceb513f189834d4e2066a94c7a6c1f14
kesarwaniprakhar/Algorithms-codes
/mincostpathdynpro.py
916
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 11 08:10:49 2019 @author: prakhar prakash """ mat1 = [[1,2,3],[4,8,2],[1,5,3]] m = int(input('Enter the value of m')) n = int(input('Enter the value of n')) def mincostpath(mat1,m,n): dp = [[0 for x in range(len(mat1[0]))] for x in range(len(mat1)) ] dp[0][0] = mat1[0][0] for j in range(1,len(mat1[0])): #loop for first row and all columns dp[0][j] = mat1[0][j] + dp[0][j-1] for i in range(1,len(mat1)): # loop for first column and all rows dp[i][0] = mat1[i][0] + dp[i-1][0] for i in range(1,len(mat1)): for j in range(1,len(mat1[0])): #both loop for other than first row, all columns and first columns, all rows. dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) + mat1[i][j] return dp[m][n] print(mincostpath(mat1,m,n))
a828b7b203e02b29f033f82d0cca98d083d781be
Sneha-Santhosh/MachineLearning
/day10/test5.py
354
3.84375
4
''' . Write a program to obtain the negative of a grayscale image (hint:subtract 255 from all pixels values) ''' import cv2 as cv import numpy as np #Read image img1 = cv.imread('apple.jpg') img1 = 255-img1 print img1 cv.imshow("apple2", img1) # Hold image till anyt key pressed cv.waitKey(0) #orang RGB(255,165,0),BGR(0,165,255)
b43a14fea94c4d13ea22c637c674a94fb1209622
Sneha-Santhosh/MachineLearning
/day12/qa5.py
771
3.65625
4
''' Write a program to do face detection and eyes detection using haarclassifiers. ''' import numpy as np import cv2 as cv face_cascade=cv.CascadeClassifier('haarcascade_face.xml') eye_cascade=cv.CascadeClassifier('haarcascade_eye.xml') img=cv.imread('people.jpg') gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY) faces=face_cascade.detectMultiScale(gray,1.1) print faces for (x,y,w,h) in faces: cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray=gray[y:y+h,x:x+w] roi_color=img[y:y+h,x:x+w] eyes=eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: #cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) cv.circle(roi_color,(ex+20,ey+10), 25, (0,255,0), 2) cv.imshow('dst',img) cv.imshow('Gray',gray) cv.waitKey(0)
108183b937e830187b011e294794b6fd63235420
Sneha-Santhosh/MachineLearning
/day10/test2.py
424
3.921875
4
''' Write a program apply scaling on the image of the apple with scaling factor 2 on both x and y axes. ''' import cv2 as cv import numpy as np #Read image img = cv.imread('apple.jpg',0) rows,cols = img.shape dst = cv.resize( img,None, fx = 3, fy = 1, interpolation = cv.INTER_CUBIC ) cv.imshow("apple", dst) cv.imshow("apple2", img) # Hold image till anyt key pressed cv.waitKey(0)