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
cea771953d2e1c6be63e6af061ff0c59dfeec3d0
tigerpatel13/Sorts
/main.py
423
4.09375
4
""" The file is used to run any type of sort using this single file and its options """ from pigeonhole_sort import pigeonhole def main(): item = [int(x) for x in input("Please enter a list you would like to sort using PigeonSort: ").split()] print("Sorted order is : ", end = ' ') pigeonhole(item) for i in range(0, len(item)): print(item[i], end = ' ') #Run the main inside of the main main()
79b1f026ffe90884d751a18e789bc9b87591261c
elhaidi/Design_Pattern
/Builder/ComputerBuilder/computer.py
669
3.625
4
class Computer: def __init__(self,case,mainboard,cpu,memory,hard_drive,video_card): self.case=case self.mainboard= mainboard self.cpu=cpu self.memory=memory self.hard_drive=hard_drive self.video_card=video_card def display(self): print("\t {:>10} : {}".format('Case',self.case)) print("\t {:>10} : {}".format('mainboard',self.mainboard)) print("\t {:>10} : {}".format('CPU',self.cpu)) print("\t {:>10} : {}".format('memory',self.memory)) print("\t {:>10} : {}".format('hard_drive',self.hard_drive)) print("\t {:>10} : {}".format('video_card',self.video_card))
1f3baebd7e89436d3ed0397b5d823c9178b32d6d
Bals-0010/Leet-Code-and-Edabit
/Leet Code/Remove Vowels from a String.py
288
4.03125
4
# instructions pending def testing(string): vowels_list = ['a','e','i','o','u','A','E','I','O','U'] str_list = [i for i in string if i not in vowels_list] final_list = "".join(str_list) return final_list print(testing("thisi is a string example"))
30aaffce13d69354705ccb9e3c9c46e565a3b6d2
Bals-0010/Leet-Code-and-Edabit
/Edabit/Identity matrix.py
1,664
4.28125
4
""" Identity Matrix An identity matrix is defined as a square matrix with 1s running from the top left of the square to the bottom right. The rest are 0s. The identity matrix has applications ranging from machine learning to the general theory of relativity. Create a function that takes an integer n and returns the identity matrix of n x n dimensions. For this challenge, if the integer is negative, return the mirror image of the identity matrix of n x n dimensions.. It does not matter if the mirror image is left-right or top-bottom. Examples id_mtrx(2) ➞ [ [1, 0], [0, 1] ] id_mtrx(-2) ➞ [ [0, 1], [1, 0] ] id_mtrx(0) ➞ [] Notes Incompatible types passed as n should return the string "Error". """ # Approach using numpy def generate_identity_matrix(n): import numpy as np temp_n = abs(n) identity_matrix = np.zeros((temp_n,temp_n)) for i in range(temp_n): identity_matrix[i][i] = 1 if n>0: return identity_matrix else: return np.flip(identity_matrix, axis=0) # print(generate_identity_matrix(-2)) # Approach without using numpy def generate_identity_matrix_no_np(n): temp_n = abs(n) id_matrix = [[]]*temp_n for i in range(temp_n): id_matrix[i] = [0 for i in range(temp_n)] for i in range(temp_n): for j in range(temp_n): if i==j: id_matrix[i][j] = 1 if abs(n)==n: return id_matrix else: id_matrix.reverse() return id_matrix # print(generate_identity_matrix_no_np(2)) print(generate_identity_matrix_no_np(-2))
10915b56f39c9f8315f0ed3e8176baccc33f418a
radhikar408/Assignments_Python
/assignment13/ques2.py
232
3.71875
4
# Q.2- Name and handle the exception occurred in the following program: # l=[1,2,3] # print(l[3]) #name of the error--list index out of range #handling the error try: li=[1,2,3] print(li[3]) except Exception as e: print(e)
80c382f2fb68f717d9bc66b4617de4aad1987527
radhikar408/Assignments_Python
/assignment4/ques5.py
182
4.125
4
#create a dictionary d={} name="" marks="" for i in range(3): name=input("enter your name ") marks=(int(input("enter your marks "))) d[name]=marks print("dictionary is ") print(d)
d07e252bff50c58d9cf0d612edbdfd78f9a7b7a7
radhikar408/Assignments_Python
/assignment17/ques1.py
349
4.3125
4
#Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface. import tkinter from tkinter import * import sys root=Tk() def show(): print("hello world") b=Button(root,text="Hello",width=25,command=show) b2=Button(root,text="exit",width=25, command=exit) b.pack() b2.pack() root.mainloop()
9f466238d87b0ed85803359c885a72a033bfac95
radhikar408/Assignments_Python
/assignment14/ques1.py
268
4.0625
4
#Q.1- Write a Python program to read last n lines of a file f=open('new.txt','r') #print(f.tell()) #a=f.tell() content=f.readlines() print(content) n=int(input("enter a number : ")) # for l in range(len(content)-n,len(content)): for i in range(): print(content[l])
93cb8ecf50c9f28524f1764ec62c5a9c2b6c4766
radhikar408/Assignments_Python
/assignment4/ques6.py
231
3.875
4
d={} name="" marks="" li=[] for i in range(10): name=input("enter your name ") marks=(int(input("enter your marks "))) d[name]=marks li.append(marks) d[name]=marks print("dictionary is ") print(d) print(li) li.sort() print(li)
eeaddb667703e9d83352cb5fad07709334d861bc
v1rals/python
/module2/guess_the_number.py
464
3.828125
4
#! /usr/bin/python3 import random rnd = random.randrange(1, 100) print("Я загадал число, может быть это", rnd ,",а может и нет") while True: guess = int(input('Попробуй угадать число: ')) if guess > rnd: print("Переборщил") continue if guess < rnd: print("Недоборщил") continue else: print("В самую точку!") break
c1e110c59311af1c81fc95f67368f46acd9d9fcd
cosmonautd/ED
/Trabalho Extra/Questão 3/project_selection_solution.py
5,630
3.703125
4
import numpy import string import matplotlib.pyplot as plt # V: A verba liberada pelo governo V = 300 # N: A quantidade de projetos submetidos # c: Os custos de cada projeto (em milhões) # q: A estimativa da quantidade de pessoas beneficiadas por cada projeto (em milhões) N = numpy.random.randint(20, 30) c = list(numpy.random.randint(10, 99, N)) q = list(numpy.random.randint(10, 99, N)) # Função de inicialização da população def init(pop_size): # A população é uma lista de indivíduos population = list() for _ in range(pop_size): # Cada indivíduo é uma lista binária de comprimento N # A presença do valor 1 no índice i indice que o projeto i faz # parte do conjunto de projetos selecionados. individual = list(numpy.random.randint(0, 2, N)) population.append(individual) return population # Função de aptidão def fit(population): # Lista de aptidões fitness = list() # A aptidão é calculada para todos os indíduos da população for individual in population: # TODO: Implementar o cálculo da aptidão do indivíduo if numpy.sum(numpy.array(individual)*numpy.array(c)) > V: f = numpy.min(q) else: f = numpy.sum(numpy.array(individual)*numpy.array(q)) # Fim do cálculo da aptidão do indivíduo fitness.append(f) return fitness # Função de seleção def selection(population, fitness, n): # Método da roleta def roulette(): # Obtenção dos índices de cada indivíduo da população idx = numpy.arange(0, len(population)) # Cálculo das probabilidades de seleção com base na aptidão dos indivíduos probabilities = fitness/numpy.sum(fitness) # Escolha dos índices dos pais parents_idx = numpy.random.choice(idx, size=n, p=probabilities) # Escolha dos pais com base nos índices selecionados parents = numpy.take(population, parents_idx, axis=0) # Organiza os pais em pares parents = [(list(parents[i]), list(parents[i+1])) for i in range(0, len(parents)-1, 2)] return parents # Método do torneio def tournament(K): # Lista dos pais parents = list() # Obtenção dos índices de cada indivíduo da população idx = numpy.arange(0, len(population)) # Seleção de um determinado número n de pais for _ in range(n): # Seleciona K indivíduos para torneio turn_idx = numpy.random.choice(idx, size=K) # Seleciona o indivíduo partipante do torneio com maior aptidão turn_fitness = numpy.take(fitness, turn_idx, axis=0) argmax = numpy.argmax(turn_fitness) # Adiciona o indivíduo selecionado à lista de pais parents.append(population[argmax]) # Organiza os pais em pares parents = [(list(parents[i]), list(parents[i+1])) for i in range(0, len(parents)-1, 2)] return parents # Escolha do método de seleção return roulette() # Função de cruzamento def crossover(parents, crossover_rate): # Lista de filhos children = list() # Iteração por todos os pares de pais for pair in parents: parent1 = pair[0] parent2 = pair[1] # TODO: Cruzamento ocorre com determinada probabilidade if numpy.random.random() < crossover_rate: # TODO: Implementar o método de cruzamento # Os pais (parent1 e parent2) são listas binárias de comprimento N # Definição do segmento de corte point = numpy.random.randint(0, len(parent1)) # Construção da representação dos filhos child1 = parent1[:point] + parent2[point:] child2 = parent2[:point] + parent1[point:] # Adição dos novos filhos à lista de filhos children.append(child1) children.append(child2) else: # Caso o cruzamento não ocorra, os pais permanecem na próxima geração children.append(parent1) children.append(parent2) return children # Função de mutação def mutation(children, mutation_rate): # Mutação pode ocorrer em qualquer dos filhos for i, child in enumerate(children): # TODO: Mutação ocorre com determinada probabilidade if numpy.random.random() < mutation_rate: # TODO: Implementar o método de mutação # Um filho (child) é uma lista binária de comprimento N # Seleciona uma coordenada aleatoriamente point = numpy.random.randint(0, len(child)) # Realiza um flip no bit children[i][point] = 1 if child[point] == 0 else 1 return children # Função de critério de parada def stop(): return False # Função de elitismo def elitism(population, fitness, n): # Seleciona n indivíduos mais aptos return [e[0] for e in sorted(zip(population, fitness), key=lambda x:x[1], reverse=True)[:n]] # https://codereview.stackexchange.com/questions/20569/dynamic-programming-knapsack-solution # A Dynamic Programming based Python Program for 0-1 Knapsack problem # Returns the maximum value that can be put in a knapsack of capacity V def maxknapsack(): K = [[0 for x in range(V+1)] for x in range(N+1)] for i in range(N+1): for w in range(V+1): if i==0 or w==0: K[i][w] = 0 elif c[i-1] <= w: K[i][w] = max(q[i-1] + K[i-1][w-c[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[N][V]
40607f14fdd0e1dc4c002e9f9d14d12371970c76
ucookie/share
/01_python高并发优化思路/multi_threads.py
1,233
3.890625
4
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import time import threading QUEUE = list() def fibonacci(n): '''斐波拉数列''' if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def init_queue(): '''初始化队列''' global QUEUE QUEUE = list(range(10))[::-1] def task(): while len(QUEUE) != 0: try: data = QUEUE.pop() print('work', data, 'start', end=' -> ') fibonacci(34) print('end') except Exception as ex: print(str(ex)) if __name__ == "__main__": print('单线程测试开始') init_queue() start_time = time.time() th = threading.Thread(target=task) th.start() th.join() single_time = time.time() - start_time print('\n多线程测试开始') init_queue() start_time = time.time() thread_list = list() for i in range(4): th = threading.Thread(target=task) th.start() thread_list.append(th) for t in thread_list: t.join() multi_time = time.time() - start_time print("单线程执行:", single_time) print("多进程执行:", multi_time)
4a2b683168580f13091d2d79038faff0098849cb
LucvandenBrand/OperatorGraph
/auto_tuner/ParseUtils.py
679
3.734375
4
def try_to_parse_int(value, defaultValue=0): try: return int(value) except ValueError: return defaultValue def try_to_parse_bool(value): value = value.lower() if value == "false" or value == "0": return False else: return True def try_to_parse_int_list(value, delimiter=","): elems = value.split(delimiter) list = [] for elem in elems: try: list.append(int(elem)) except ValueError: a = 0 return list def try_to_parse_str_list(value, delimiter=","): elems = value.split(delimiter) list = [] for elem in elems: list.append(elem) return list
42db780779436ef37aac6cc39b040bfff2d14833
brandon-hill/CS50
/bleep.py
1,222
3.796875
4
# Censors certain specified words in a given string from cs50 import get_string from sys import argv def main(): text = get_text("What message would you like to censor?\n") dictionary = open(argv[1]) banned = make_banned(dictionary) censor_text(text, banned) dictionary.close() # Prompt user for text to censor def get_text(prompt): while True: if len(argv) == 2: s = get_string(prompt) s_list = s.split() return s_list else: exit("Usage: python bleep.py dictionary") # Make a list from the dictionary def make_banned(dictionary): banned = [] for x in dictionary: banned.append(x.strip()) return banned # Censor the text and print def censor_text(text, banned): for x in text: bleeped = False # Loop through ban list and compare for j in banned: stripped = x.strip() if j.strip() == stripped.lower(): bleeped = True print(("*" * len(j.strip())) + " ", end="") if bleeped == False: print(x, end=" ") print() if __name__ == "__main__": main()
6c34aad1342424ae8a1def0a6cefa8c4797b6a00
purvitrivedi/get-next-cron-schedule
/application.py
1,347
3.625
4
#!/usr/bin/env python3 import sys import select from time_calc import validate_time_format from crontab_parser import parse_config, next_crontab_time def main(): try: if len(sys.argv) != 2: raise IndexError if not select.select([sys.stdin, ], [], [], 0.0)[0]: raise IndexError current_time = sys.argv[1] validated_current_time = validate_time_format(current_time) if validated_current_time: crontab_list = parse_config(sys.stdin) return next_crontab_time(validated_current_time, crontab_list) except IndexError: if len(sys.argv) != 2: print(''' ❗️ Error: Please input the current time as HH:MM❗️ Your command line input should follow the following format: ​./application.py HH:MM < config Example command line 👇 ​./application.py 17:30 < config ''') else: print(''' ❗️ Error: Please provide standard input ❗️ Your command line input should follow the following format to provide STDIN: ​./application.py HH:MM < config Example command line 👇 ​./application.py 17:30 < config ''') if __name__ == '__main__': main()
caa63eaa8c432be6f44075d6cb702d7ca7ede6fd
EZForever/pytrickz
/pytrickz/iterables.py
4,153
4.15625
4
''' Defines several handy `Iterable` classes. ``` from pytrickz.iterables import iterate print(iterate(lambda x: x * 3, 1).stream().take(5)) # (1, 3, 9, 27, 81) ``` ''' from typing import Callable, Generic, Iterable, Iterator from .stream import stream from .typevars import * class iterate(Generic[T]): ''' An `Iterable` that iterates `func` over `seed`, i.e. `seed`, `func(seed)`, `func(func(seed))`, endlessly. >>> iterate(lambda x: x * 3, 1).stream().take(5) (1, 3, 9, 27, 81) ''' class _iterator(Generic[T]): ''' The underlying `Iterator` for `iterate`. ''' def __init__(self, func: Callable[[T], T], initial: T): self.__func = func self.__val = initial self.__initial = True def __iter__(self) -> Iterator[T]: return self def __next__(self) -> T: if self.__initial: self.__initial = False else: self.__val = self.__func(self.__val) return self.__val def __init__(self, func: Callable[[T], T], initial: T): ''' Construct a `Iterable` that iterates `func` over `seed`, i.e. `seed`, `func(seed)`, `func(func(seed))`, endlessly. >>> iterate(lambda x: x * 3, 1).stream().take(5) (1, 3, 9, 27, 81) ''' self.__func = func self.__initial = initial def __iter__(self) -> Iterator[T]: ''' Wrapper of `self.iter()` for usage in language constructs. ''' return self.iter() def iter(self) -> Iterator[T]: ''' Obtain an `Iterator` for usage in language constructs. ''' return self._iterator(self.__func, self.__initial) def stream(self) -> stream[T]: ''' Construct an infinite reentrant `stream` backed by this `iterate`. Equivalent to `stream(self)`. >>> iterate(lambda x: x * 3, 1).stream().take(5) (1, 3, 9, 27, 81) ''' return stream(self) class lazyevaluate(Generic[T]): ''' An `Iterable` that delays invocation of `func` until iterated. Mainly used as a wrapper for eager evaluated functions, e.g. `sorted`. >>> lazyevaluate([3, 5, 4, 2, 1], sorted).stream().to(list) [1, 2, 3, 4, 5] ''' class _iterator(Generic[T]): ''' The underlying `Iterator` for `lazyevaluate`. ''' def __init__(self, iterable: Iterable[T], func: Callable[[Iterable[T]], Iterable[U]]): self.__iterable = iterable self.__func = func self.__initial = True def __iter__(self) -> Iterator[U]: return self def __next__(self) -> U: if self.__initial: self.__iterable = iter(self.__func(self.__iterable)) self.__initial = False return next(self.__iterable) def __init__(self, iterable: Iterable[T], func: Callable[[Iterable[T]], Iterable[U]]): ''' Construct an `Iterable` that delays invocation of `func` until iterated. >>> lazyevaluate([3, 5, 4, 2, 1], sorted).stream().to(list) [1, 2, 3, 4, 5] ''' self.__iterable = iterable self.__func = func def __iter__(self) -> Iterator[T]: ''' Wrapper of `self.iter()` for usage in language constructs. ''' return self.iter() def iter(self) -> Iterator[T]: ''' Obtain an `Iterator` for usage in language constructs. ''' return self._iterator(self.__iterable, self.__func) def stream(self) -> stream[T]: ''' Construct an non-reentrant `stream` backed by this `iterate`. Equivalent to `stream(self)`. >>> lazyevaluate([3, 5, 4, 2, 1], sorted).stream().to(list) [1, 2, 3, 4, 5] ''' return stream(self)
42fef2a758d2df6e05b7d5db3ecbd4e2d01b058b
scline96/my-exercism
/isogram/isogram.py
187
3.90625
4
def is_isogram(string): letters = [] for letter in string: if letter in letters: return False break letters.append(letter) return True
ef4a19480ad8d3012972ff69f314283332c89728
lightningC00kie/binary_addition
/script.py
1,049
3.859375
4
def binary_addition(n, a1, a2): carry = [] answer = [] for i in range(n-1, -1, -1): a = a1[i] b = a2[i] if len(carry) == 0: if a == 0 and b == 0: c = 0 if a == 1 and b == 1: c = 0 carry.append(1) if a == 1 and b == 0: c = 1 if a == 0 and b == 1: c = 1 answer.append(c) else: if a == 0 and b == 0: c = 1 if a == 1 and b == 1: c = 1 carry.append(1) if a == 1 and b == 0: c = 0 carry.append(1) if a == 0 and b == 1: c = 0 carry.append(1) carry.pop() answer.append(c) if len(carry) != 0: answer.append(1) else: answer.append(0) answer = answer[::-1] return answer a1 = [0,1,1,1,1,0,0,1] a2 = [1,1,0,1,0,1,0,1] print(binary_addition(8, a1, a2))
6a64bc653a10658506193c61804230571db73621
jacksonsr45/python_calculator
/app/src/app_calculator.py
2,978
3.625
4
__author__ = "jacksonsr45@gmail.com" import tkinter class Calculator: def __init__(self,root): self.root = root self.root.title("Calculator") x = (self.root.winfo_screenwidth() // 2) - (550 // 2) y = (self.root.winfo_screenheight() // 2) - (600 // 2) self.root.geometry("550x600+{}+{}".format( x, y)) self.value_display = tkinter.StringVar() self.frame = self.frame_calc(self.root, tkinter.TOP, 1, 4, "black") self.display(self.frame, ("Ubunto", 17)) self.clear(self.root) self.button_calculator(self.root) self.equals(self.root) def frame_calc(self, root, side, bw, bd, bg): frame = tkinter.Frame(root, borderwidth= bw, bd= bw, bg= bg) frame.pack(side= side, expand=tkinter.YES, fill= tkinter.BOTH) return frame def display(self, frame, font): display = tkinter.Entry(frame) display.configure(textvariable=self.value_display) display.configure(font=font) display.configure(justify='right') display.pack(side=tkinter.TOP, expand= tkinter.YES, fill= tkinter.BOTH) return display def button(self, frame, side, text, command=None): button = tkinter.Button(frame) button.configure(text= text) button.configure(font= ("Ubunto", 14)) button.configure(command=command) button.pack( side=side, expand=tkinter.YES, fill=tkinter.BOTH) return button def clear(self, root): for clear in (["CE"],["C"]): erase = self.frame_calc( root, tkinter.TOP, 1, 4, "white") for row in clear: self.button( erase, tkinter.LEFT, row, lambda storeObj=self.value_display, q= row: storeObj.set('')) def button_calculator(self, root): for num_btn in ("()%","/789", "*456", "-123", "+.0"): btn_calc = self.frame_calc( root, tkinter.TOP, 1, 4, "white") for row in num_btn: self.button( btn_calc, tkinter.LEFT, row, lambda display= self.value_display, q=row: display.set(display.get() + q)) def equals(self, root): equals_button = self.frame_calc( root, tkinter.TOP, 1, 4, "white") for value in "=": if value == '=': btn_equals = self.button( equals_button, tkinter.LEFT, value) btn_equals.bind('<ButtonRelease-1>', lambda e, s=self, display=self.value_display: s.calc(display), '+') else: btn_equals = self.button( equals_button, tkinter.LEFT, value, lambda display=self.value_display, s=' %s '%value: display.set(display.get()+s)) def calc(self, display): try: display.set(eval(display.get())) except: display.set("ERROR")
be71c571a73736a4d7fabf61a407ec2a492bdcbe
cooperbarth/texterize
/texterize/helpers/build_block.py
835
3.6875
4
import numpy as np, math #converts a string into a 2D numpy array of text the same shape as the image to be texterized def buildBlock(text, dimensions): ''' params: -text: a string to be split into a block -dimensions: the numpy shape of the input image return: A 2D numpy array of characters in the shape of dimensions ''' assert len(dimensions) == 3, "Image dimensions have an invalid shape, aborting." char_arr = np.array(list(text)) CHROMA_AREA = dimensions[0] * dimensions[1] if len(char_arr) > CHROMA_AREA: char_arr = char_arr[:CHROMA_AREA] else: append_index = 0 while len(char_arr) < CHROMA_AREA: char_arr = np.append(char_arr, char_arr[append_index]) append_index += 1 return np.reshape(char_arr, dimensions[:2])
d863a4f7a2235052c3f32222fb3cf70809d0ae94
NullPrimer/Exercise_App
/ExerciseApp.py
830
4.03125
4
# Array's import random Day_of_the_week =("Wednesday") print("This is your exercise for " + Day_of_the_week) if Day_of_the_week == "Monday": print(random.choice(("Bench", "Flys", "Dumbell_Raise"))) elif Day_of_the_week == "Tuesday": print(random.choice(("Shoulder Press", "Lat_Raises", "Face_Pull"))) elif Day_of_the_week == "Wednesday": print(random.choice(("Seated_Row", "Lat_Pulldown", "Bent_OverRow"))) elif Day_of_the_week == "Thursday": print(random.choice(("Row", "Seated_Row's", "Bent over Rows", "Lat Pulldown"))) elif Day_of_the_week == "Friday": print(random.choice(("Shoulder Press","Lat Raises", "Cable Pulls"))) elif Day_of_the_week == "Saturday": print("Rest_Day") # Exellent. Review the user imput Line 3 in case you have to code for a users input. Good Work. 30/06/2021
cae03ccf21b45ea7bc0dcc9b1fcf154192dee6f1
tmlrnc/axn_ml_2
/axn/ml/predict/predictor/algorithm/kmedian_VL.py
12,339
3.640625
4
""" trains the scikit-learn python machine learning algorithm library function https://scikit-learn.org then passes the trained algorithm the features set and returns the predicted y test values form, the function then compares the y_test values from scikit-learn predicted to y_test values passed in then returns the accuracy """ # pylint: disable=duplicate-code # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=invalid-name from sklearn.cluster import KMeans from axn.ml.predict.predictor import OneHotPredictor, Commandline from axn.ml.predict.config import get_ohe_config import numpy import logging import numpy import random from collections import defaultdict class K_Means: def __init__(self, k=2, tol=0.001, max_iter=300): self.k = k self.tol = tol self.max_iter = max_iter def fit(self, data): self.centroids = {} for i in range(self.k): self.centroids[i] = data[i] for i in range(self.max_iter): self.classifications = {} for i in range(self.k): self.classifications[i] = [] for featureset in data: distances = [ np.linalg.norm( featureset - self.centroids[centroid]) for centroid in self.centroids] classification = distances.index(min(distances)) self.classifications[classification].append(featureset) prev_centroids = dict(self.centroids) for classification in self.classifications: self.centroids[classification] = np.average( self.classifications[classification], axis=0) optimized = True for c in self.centroids: original_centroid = prev_centroids[c] current_centroid = self.centroids[c] if np.sum((current_centroid - original_centroid) / original_centroid * 100.0) > self.tol: print( np.sum( (current_centroid - original_centroid) / original_centroid * 100.0)) optimized = False if optimized: break def predict(self, data): distances = [np.linalg.norm(data - self.centroids[centroid]) for centroid in self.centroids] classification = distances.index(min(distances)) return classification class KMedian(object): """ Calculations associated with K-Means clustering on a set of n-dimensional data points to find clusters - closely located groups - of dataset points. """ def __init__( self, dataset_numpy_array, k_number_of_clusters, number_of_centroid_initializations, max_number_of_iterations=30): """ Attributes associated with all K-Means clustering of data points :param dataset_numpy_array: numpy array of n-dimensional points you'd like to cluster :param k_number_of_clusters: number of clusters to create :param max_number_of_iterations: maximum number of possible iterations to run K-Means """ self.dataset = dataset_numpy_array self.k_number_of_clusters = k_number_of_clusters self.number_of_instances, self.number_of_features = self.dataset.shape self.number_of_centroid_initializations = number_of_centroid_initializations self.inertia_values = [] self.max_number_of_iterations = max_number_of_iterations # all centroids and clustered dataset points self.clusters_all_iterations_record = [] @staticmethod def get_euclidean_distance( n_dimensional_numpy_array_0, n_dimensional_numpy_array_1): """ Static method to calculate the normalized Euclidean distance between any n-dimensional numpy arrays :param n_dimensional_numpy_array_0: one n-dimensional numpy array (aka a point in space) :param n_dimensional_numpy_array_1: another n-dimensional numpy array (aka a point in space) :return: magnitude of Euclidean distance between two n-dimensional numpy arrays; scalar value """ return numpy.linalg.norm( n_dimensional_numpy_array_0 - n_dimensional_numpy_array_1) def create_random_initial_centroids(self): """ Create random initial centroids based on dataset; creates # of centroids to match # of clusters :return: """ random_dataset_indices = random.sample( range(0, self.number_of_instances), self.k_number_of_clusters) random_initial_centroids = self.dataset[random_dataset_indices] return random_initial_centroids def assign_dataset_points_to_closest_centroid(self, centroids): """ Given any number of centroid values, assign each point to its closest centroid based on the Euclidean distance metric. Use data structure cluster_iteration_record to keep track of the centroid and associated points in a single iteration. :param centroids: numpy array of centroid values :return: record of centroid and associated dataset points in its cluster for a single K-Means iteration """ cluster_single_iteration_record = defaultdict(list) for dataset_point in self.dataset: euclidean_distances_between_dataset_point_and_centroids = [] for centroid in centroids: distance_between_centroid_and_dataset_point = self.get_euclidean_distance( centroid, dataset_point) euclidean_distances_between_dataset_point_and_centroids.append( distance_between_centroid_and_dataset_point) index_of_closest_centroid = numpy.argmin( euclidean_distances_between_dataset_point_and_centroids) closest_centroid = tuple(centroids[index_of_closest_centroid]) cluster_single_iteration_record[closest_centroid].append( dataset_point) return cluster_single_iteration_record def run_kmeans_initialized_centroid(self, initialization_number): """ Assign dataset points to clusters based on nearest centroid; update centroids based on mean of cluster points. Repeat steps above until centroids don't move or we've reached max_number_of_iterations. :return: None """ centroids = self.create_random_initial_centroids() # list of record of iteration centroids and clustered points self.clusters_all_iterations_record.append([]) for iteration in range(1, self.max_number_of_iterations + 1): cluster_single_iteration_record = self.assign_dataset_points_to_closest_centroid( centroids=centroids) self.clusters_all_iterations_record[initialization_number].append( cluster_single_iteration_record) updated_centroids = [] for centroid in cluster_single_iteration_record: cluster_dataset_points = cluster_single_iteration_record[centroid] updated_centroid = numpy.mean(cluster_dataset_points, axis=0) updated_centroids.append(updated_centroid) if self.get_euclidean_distance( numpy.array(updated_centroids), centroids) == 0: break centroids = updated_centroids return None def fit(self): """ Implements K-Means the max number_of_centroid_initializations times; each time, there's new initial centroids. :return: None """ for initialization_number in range( self.number_of_centroid_initializations): self.run_kmeans_initialized_centroid( initialization_number=initialization_number) # index of -1 is for the last cluster assignment of the iteration inertia_of_last_cluster_record = self.inertia( self.clusters_all_iterations_record[initialization_number][-1]) self.inertia_values.append(inertia_of_last_cluster_record) return None def inertia(self, clusters): """ Get the sum of squared distances of dataset points to their cluster centers for all clusters - defined as inertia :return: cluster_sum_of_squares_points_to_clusters """ cluster_sum_of_squares_points_to_clusters = 0 for centroid, cluster_points in clusters.items(): for cluster_point in cluster_points: euclidean_norm_distance = self.get_euclidean_distance( cluster_point, centroid) euclidean_norm_distance_squared = euclidean_norm_distance ** 2 cluster_sum_of_squares_points_to_clusters += euclidean_norm_distance_squared return cluster_sum_of_squares_points_to_clusters def index_lowest_inertia_cluster(self): """ In our list of inertia_values, finds the index of the minimum inertia :return: index_lowest_inertia """ minimum_inertia_value = min(self.inertia_values) index_lowest_inertia = self.inertia_values.index(minimum_inertia_value) return index_lowest_inertia def final_iteration_optimal_cluster(self): """ Get results of optimal cluster assignment based on the lowest inertia value :return: dictionary with keys as centroids and values as list of dataset points in the clusters """ # -1 gets us the final iteration from a centroid initialization of running K-Means return self.clusters_all_iterations_record[self.index_lowest_inertia_cluster( )][-1] def final_iteration_optimal_cluster_centroids(self): """ Get centroids of the optimal cluster assignment based on the lowest inertia value :return: list of tuples with tuples holding centroid locations """ return list(self.final_iteration_optimal_cluster().keys()) def predict(self, n_dimensional_numpy_array): """ Predict which cluster a new point belongs to; calculates euclidean distance from point to all centroids :param n_dimensional_numpy_array: new observation that has same n-dimensions as dataset points :return: closest_centroid """ # initially assign closest_centroid as large value; we'll reassign it # later closest_centroid = numpy.inf for centroid in self.final_iteration_optimal_cluster_centroids(): distance = self.get_euclidean_distance( centroid, n_dimensional_numpy_array) if distance < closest_centroid: closest_centroid = centroid return closest_centroid @Commandline("K_Means_VL") class K_Means_VL(OneHotPredictor): def __init__(self, target, X_test, X_train, y_test, y_train): """ initializes the training and testing features and labels :param target: string - label to be predicted or classified :param X_test: array(float) - testing features :param X_train: array(float) - training features :param y_test: array(float) - testing label :param y_train: array(float) - testing label """ super().__init__(target, X_test, X_train, y_test, y_train) self.model_name = 'K_Means_VL' def predict(self): """ trains the scikit-learn python machine learning algorithm library function https://scikit-learn.org then passes the trained algorithm the features set and returns the predicted y test values form, the function then compares the y_test values from scikit-learn predicted to y_test values passed in then returns the accuracy """ algorithm = KMedian(n_clusters=2, random_state=0) algorithm.fit(self.X_train.toarray(), self.y_train) y_pred = list(algorithm.predict(self.X_test.toarray())) self.acc = OneHotPredictor.get_accuracy(y_pred, self.y_test) return self.acc
6def63af02c7b610414cb91a43bdddf2411325ab
kiri182/Self-Taught-Programmer
/page116.py
815
3.640625
4
def listprint(): list_a = ['ウォーキング・デッド', 'アントラージュ', 'ザ・ソプラノズ', 'ヴァンパイア・ダイアリーズ'] for x in list_a: print(x) def count(): for i in list(range(25, 51, 1)): print(i) def loop(): n = 0 question = ['Who are you', 'Where are you from', "What's that"] while True: print("Hey...") user_input = input(question[n]) if user_input == 'q': break n = (n + 1) % 3 def looploop(): list1 = [8, 19, 148, 4] list2 = [9, 1, 33, 83] result = [] i = 0 j = 0 k = 0 for i in list1: for j in list2: if k < 4: x = i * j result.append(x) k = k + 1 k = 0 print(result)
443f7d7779ccff1e1dfc7e1f0a2cbefc98bc97d5
kiri182/Self-Taught-Programmer
/page69c1-3.py
311
3.734375
4
def square(x): return x ** 2 def strings(x): print(x) def func(x, y, z, i=10, j=2): print(x) print(y) print(z) if i > 1: print(i) else: print(j) i = input("what number do you like?: ") print(square(int(i))) strings('Btw, how are you?') func('a', 'b', 'c', 5)
dd579fcf0c2dde41709cc6a552777d799a5240f2
MattSokol79/Python_Introduction
/python_variables.py
1,289
4.5625
5
# How to create a variable # If you want to comment out more than one line, highlight it all and CTRL + / name = "Matt" # String # Creating a variable called name to store user name age = 22 # Int # Creating a variable called age to store age of user hourly_wage = 10 # Int # Creating a variable called hourly_wage to store the hourly wage of the user travel_allowance = 2.1 # Float # Creating a variable called travel_allowance to store the travel allowance of the user # Python has string, int, float and boolean values # How to find out the type of variable? # => type() gives us the actual type of value print(travel_allowance) print(age) print(hourly_wage) # How to take user data # Use input() to get data from users name1 = str(input("Please enter your name ")) # Getting user data by using input() method print(name1) # Exercise - Create 3 variables to get user data: name, DOB, age user_name = str(input("Please provide your name ")) user_dob = str(input("Please provide your date of birth in the format - dd/mm/yy ")) user_age = int(input("Please provide your age ")) print('Name: ', user_name) print('DOB: ', user_dob) print('Age: ', user_age) print('Type of variable: ') print('Name: ', type(user_name)) print('DOB: ', type(user_dob)) print('Age: ', type(user_age))
d7ee9dfcd9573db8b914dc96bff65c61753aceec
fadhilmulyono/CP1401
/CP1401Lab6/CP1401_Fadhil_Lab6_2.py
373
4.25
4
''' The formula to convert temperature in Fahrenheit to centigrade is as follows: c = (f-32)*5/9; Write a program that has input in Fahrenheit and displays the temperature in Centigrade. ''' def main(): f = float (input("Enter the temperature in Fahrenheit: ")) c = (f - 32) * 5 / 9 print("The temperature in Celsius is: " + str(c) + " °C") main()
db9eddc3ae20c784684b86d39aa675cd8764739f
fadhilmulyono/CP1401
/Prac05/CP1401_Fadhil_Prac5_3.py
292
4.40625
4
''' Get height Get weight Calculate BMI (BMI = weight/(height^2 )) Show BMI ''' def main(): height = float(input("Enter your height (m): ")) weight = float(input("Enter your weight (kg): ")) BMI = weight / (height ** 2) print("Your BMI is " + str(BMI)) main()
d3e53df801c4e65d76e275b9414312bdb2f618e5
fadhilmulyono/CP1401
/Prac08/CP1401_Fadhil_Prac8_3.py
607
4.3125
4
''' Write a program that will display all numbers from 1 to 50 on separate lines. For numbers that are divisible by 3 print "Fizz" instead of the number. For numbers divisible by 5 print the word "Buzz". For numbers that are divisible by both 3 and 5 print "FizzBuzz". ''' def main(): number = 0 while number < 50: number += 1 if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) main()
676f49df4e8c42e84026f7772ffa08d7d9fd35a0
oldpride/tpsup
/python3/examples/test_class_new_attr.py
823
3.703125
4
#!/usr/bin/env python3 # https://stackoverflow.com/questions/54358665/python-set-attributes-during-object-creation-in-new # test set attr in __new__ class TestClass(object): def __new__(cls, test_val): obj = object().__new__(cls) # cant pass custom attrs object.__setattr__(obj, 'customAttr', test_val) return obj # another way, NOT WORKING!!! # https://howto.lintel.in/python-__new__-magic-method-explained/ class CustomizeInstance: def __new__(cls, a, b): instance = super(CustomizeInstance, cls).__new__(cls) instance.a = a return instance def main(): print(TestClass(1)) print(TestClass(2).__dict__) print(TestClass(3).customAttr) print(CustomizeInstance(4, 5)) print(CustomizeInstance(6, 7).a) if __name__ == '__main__': main()
99340807f1f60f51cd4ddd83af753df01b947a89
oldpride/tpsup
/python3/examples/test_copilot_vscode.py
232
4.28125
4
#!/usr/bin/env python3 import datetime # get days between two dates def get_days_between_dates(date1, date2): return (date2 - date1).days + 1 print(get_days_between_dates(datetime.date(2018, 1, 1), datetime.date(2018, 1, 3)))
3d696720d0a36e1fe9628a2ead7826e2908f0fd1
oldpride/tpsup
/python3/examples/test_redefine_function.py
194
3.953125
4
#!/usr/bin/env python3 b=100 def temp(a): return a+1 plus1=temp print(f'plus1={plus1(b)}') def temp(a): return a+2 plus2=temp print(f'plus2={plus2(b)}') print(f'plus1={plus1(b)}')
1550ef200015ae11c213f5b0762e33a1ae24315c
oldpride/tpsup
/python3/examples/test_nested_dict.py
210
4.40625
4
#!/usr/bin/env python3 import pprint dict1 = {} dict2 = {'a': 1, 'b': 2} dict1['c'] = dict2 print('before, dict1 = ') pprint.pprint(dict1) dict2['a'] = 3 print('after, dict1 = ') pprint.pprint(dict1)
081dc3fac24a114892ee3fecc8212df7fb14aadd
oldpride/tpsup
/python3/examples/test_assign.py
688
3.984375
4
#!/usr/bin/env python for row in [ [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], ]: # note, # 1. use '+' to concatenate two lists # 2. use '*' to repeat a list # 3. use 'None' to fill up the list # 4. repeat 'None' twice to fill up the list arg1, arg2, *rest = row + [None]*2 print(f"row={row}, arg1={arg1}, arg2={arg2}, rest={rest}") print("") # result: # row=[1], arg1=1, arg2=None, rest=[None] # row=[1, 2], arg1=1, arg2=2, rest=[None, None] # row=[1, 2, 3], arg1=1, arg2=2, rest=[3, None, None] # row=[1, 2, 3, 4], arg1=1, arg2=2, rest=[3, 4, None, None] # row=[1, 2, 3, 4, 5], arg1=1, arg2=2, rest=[3, 4, 5, None, None]
997b83c89aa3c7039ab9ddc10b78f73334192d42
oldpride/tpsup
/python3/examples/test_attribute_vs_property_selector.py
1,661
3.515625
4
#!/usr/bin/env python # https://stackoverflow.com/questions/43627340 # An attribute is a static attribute of a given DOM node, # a property is a computed property of the DOM node object. # example # a property would be the checked state of a checkbox, or value or an input field. # an attribute would be href of an anchor tag or the type of an input DOM. # 2023/06/13 # $ siteenv # $ p3env # $ svenv # $ python test_attribute_vs_property_selector.py import os import urllib from selenium import webdriver from shutil import which def inline(doc): return "data:text/html;charset=utf-8,{}".format(urllib.parse.quote(doc)) browser_options = webdriver.chrome.options.Options() chrome_path = which("chrome") if not chrome_path: chrome_path = which("google-chrome") if not chrome_path: raise Exception("Chrome not found in path.") browser_options.binary_location = chrome_path log_base = os.environ.get("HOME") driverlog = os.path.join(log_base, "selenium_driver.log") chromedir = os.path.join(log_base, "selenium_browser") chromedir = chromedir.replace('\\', '/') browser_options.add_argument(f"--user-data-dir={chromedir}") driver = webdriver.Chrome(options=browser_options) inline_string = inline(''' <a href="https://google.com" id="hello">Hello World</a> <p> <input type="checkbox" id="foo" checked> <p> <input type="text" id="bar" value="cheesecake"> ''') print(f'inline_string = {inline_string}') driver.get(inline_string) selector = driver.find_element(webdriver.common.by.By.ID, "hello") # sele # print(f'get_attribute = {textbox.get_attribute("value")}') # print(f'get_property = {textbox.get_property("value")}')
34cd01dce906e6351e603ddd68b2b5cea5c124b9
Horacio23/python-class
/strings/string.py
243
3.546875
4
def stringJoin(): s = ';'.join(['pal','ineed','haro']) print(s) def concatinate(): s = ['pal','ind','rome'] res = ''.join(s) print(res) def main(): stringJoin() concatinate() if __name__=='__main__': main()
25bed37f4bdf2b62b3bcc74324ab69a68aa53fb6
rezaasdin/Tkinter-Traffic-Light
/traffic_light_console.py
2,224
3.515625
4
class TrafficLight(): def __init__(self): self.green_state = GreenState(self) self.yellow_state = YellowState(self) self.red_state = RedState(self) self.state = self.red_state def change_state(self): self.state.handle_request() def get_green_light_state(self): return self.green_state def get_yellow_light_state(self): return self.yellow_state def get_red_light_state(self): return self.red_state def set_state(self, state): self.state = state def __str__(self): return '{} {} {} {}'.format(self.green_state, self.yellow_state, self.red_state, self.state) class State(): def handle_request(self): pass def __str__(self): return 'red' class RedState(State): def __init__(self, traffic_light): self.traffic_light = traffic_light def handle_request(self): print('Wait for turning traffic light to green...') self.traffic_light.set_state(self.traffic_light.get_green_light_state()) def __str__(self): return 'Traffic light is on red.' class YellowState(State): def __init__(self, traffic_light): self.traffic_light = traffic_light def handle_request(self): print('Wait for turning traffic light to red...') self.traffic_light.set_state(self.traffic_light.get_red_light_state()) def __str__(self): return 'Traffic light is on yellow.' class GreenState(State): def __init__(self, traffic_light): self.traffic_light = traffic_light def handle_request(self): print('Wait for turning traffic light to yellow...') self.traffic_light.set_state(self.traffic_light.get_yellow_light_state()) def __str__(self): return 'Traffic light is on green.' tr = TrafficLight() rd_s = RedState(tr) yl_s = YellowState(tr) gr_s = GreenState(tr) import time first = True while True: if first: first = False print(tr.state) rd_s.handle_request() time.sleep(2) print(tr.state) gr_s.handle_request() time.sleep(2) print(tr.state) yl_s.handle_request() time.sleep(2) print(tr.state)
9cdd048dffa47e47ed7a9da8352c13832d6c3b96
wmoura12/materiais_apoio_cursos
/Palestras/202106 - Observatorio Social/arquivos_apoio/Aula02_Ex02_Print.py
425
3.96875
4
import time print('iniciando o código') segundos = 5 for i in range (segundos): print("Aguarde",segundos - i,"segundos") time.sleep(1) # Entrada de informações b = float(input('digite a largura: ')) h = float(input('digite a altura: ')) print("OK, vou calcular para você!\nAguarde 5 segundos") time.sleep(5) # Calculos x = b*h mensagem = 'a metragem quadrada é: ' + str(x) # Retorno usuário print(mensagem)
f540701887da1465a0479f586df7b36fd7c224b8
caryt/utensils
/date/tests.py
9,108
3.53125
4
"""Date tests. """ from unittest import TestCase from date import * class Test_Weekday(TestCase): """Weekdays enumerate Sun..Sat.""" def test_weekday(self): d = 15-Jan-2013 self.assertEqual(d.weekday, Tue) self.assertEqual(str(d.weekday), 'Tue') class Test_Date(TestCase): """Date objects handle date literals and arithemtic.""" def test_Date(self): d = Date(2013, 1, 15) self.assertEqual( str(d), '15-Jan-2013') def test_DateLiteral(self): d = 15-Jan-2013 self.assertEqual( str(d), '15-Jan-2013') def test_DateString(self): self.assertEqual( str(15-Jan-2013), '15-Jan-2013') self.assertEqual( str(Jan-2013), 'Jan-2013') self.assertEqual( str(15-Jan), '15-Jan') self.assertEqual( str( Jan), 'Jan') def test_invalidDate(self): self.assertRaises(OverflowError, lambda: 32-Jan-2013) self.assertRaises(OverflowError, lambda: 29-Feb-2013) def test_DateComponents(self): d = 15-Jan-2013 self.assertEqual(d.day, Date(2013, 1, 15)) self.assertEqual(d.month, Date(2013, 1, 0)) self.assertEqual(d.month, Month(2013, 1)) self.assertEqual(d.year, Date(2013, 0, 0)) self.assertEqual(d.year, Year(2013)) self.assertEqual(d.ymd, (2013, 1, 15)) def test_month_items(self): m = Feb-2013 self.assertEqual(m[ 1], 1-Feb-2013) self.assertEqual(m[-1], 28-Feb-2013) m = Mar-2013 self.assertEqual(m[ 1], 1-Mar-2013) self.assertEqual(m[-1], 31-Mar-2013) d = 15-Mar-2013 self.assertEqual(d.month[ 1], 1-Mar-2013) self.assertEqual(d.month[-1], 31-Mar-2013) def test_month(self): [self.assertEqual(date, Date(2013, 1, d + 1)) for (d, date) in enumerate(Jan-2013)] def test_julian(self): #self.assertEqual(int(1-Jan-2013), 2456295) self.assertEqual(Date(int(31-Jan-2013) + 1), 1-Feb-2013) self.assertEqual(Date(int(31-Jan-2013)), 31-Jan-2013) def test_year(self): j = int(1-Jan-2013) for date in Year(2013): self.assertEqual(date, Date(j)) self.assertEqual(int(date), j) j += 1 def test_week(self): w = (15-Jan-2013).week self.assertEqual(w[0], 13-Jan-2013) self.assertEqual(w[Sun], 13-Jan-2013) self.assertEqual(w[-1], 19-Jan-2013) self.assertEqual(w[Sat], 19-Jan-2013) self.assertEqual(str(w), '[13-Jan-2013..19-Jan-2013]') self.assertFalse(12-Jan-2013 in w) self.assertTrue( 13-Jan-2013 in w) self.assertTrue( 14-Jan-2013 in w) self.assertTrue( 19-Jan-2013 in w) self.assertFalse(20-Jan-2013 in w) def test_day_in_date(self): self.assertTrue( 1 in Jan-2013) self.assertTrue( 31 in Jan-2013) self.assertTrue( 1 in Feb-2013) self.assertFalse(31 in Feb-2013) self.assertTrue( 28 in Feb-2013) self.assertFalse(29 in Feb-2013) self.assertTrue( 29 in Feb-2012) def test_rawAddition(self): self.assertEqual(31-Jan-2013 + 1, 1-Feb-2013) def test_yesterday_today_tomorrow(self): self.assertEqual(int(Date.yesterday+1), int(Date.today)) self.assertEqual(int(Date.tomorrow -1), int(Date.today)) def test_format(self): """format(date, spec) allows strftime specs, e.g. format(date, '%d%m%y:6').""" self.assertEqual(format(1-Mar-2013, '%d%m%y:6'), '010313') self.assertEqual(format(1-Mar-2013, '%Y%m%d:8'), '20130301') class Test_Month(TestCase): """Month objects represent a Month and Year.""" def test_month_lengths(self): self.assertEqual(len(Feb-1900), 28) self.assertEqual(len(Feb-1901), 28) self.assertEqual(len(Feb-1902), 28) self.assertEqual(len(Feb-1903), 28) self.assertEqual(len(Feb-1904), 29) self.assertEqual(len(Feb-2000), 29) self.assertEqual(len(Feb-2001), 28) self.assertEqual(len(Feb-2002), 28) self.assertEqual(len(Feb-2003), 28) self.assertEqual(len(Feb-2004), 29) class Test_Year(TestCase): """Year objects represent a Year.""" def test_year_lengths(self): self.assertEqual(len((Feb-1900).year), 365) self.assertEqual(len((Feb-1901).year), 365) self.assertEqual(len((Feb-1902).year), 365) self.assertEqual(len((Feb-1903).year), 365) self.assertEqual(len((Feb-1904).year), 366) self.assertEqual(len((Feb-2000).year), 366) self.assertEqual(len((Feb-2001).year), 365) self.assertEqual(len((Feb-2002).year), 365) self.assertEqual(len((Feb-2003).year), 365) self.assertEqual(len((Feb-2004).year), 366) class Test_Duration(TestCase): """Durations are a number of days, months and/or years.""" def test_Duration(self): self.assertEqual(str(7*days), '7 days') self.assertEqual(str(2*months), '2 months') self.assertEqual(str(3*years), '3 years') self.assertEqual(31-Dec-2012 + 1*days, 1-Jan-2013) self.assertEqual(31-Dec-2012 + 1*months, 31-Jan-2013) self.assertEqual(31-Dec-2012 + 2*months, 28-Feb-2013) self.assertEqual(28-Feb-2013 - 2*months, 28-Dec-2012) # TODO: Is this right? self.assertEqual(31-Mar-2013 + 1*months, 30-Apr-2013) self.assertEqual(15-Jan-2013 + 7*days, 22-Jan-2013) self.assertEqual(15-Jan-2013 + 3*months, 15-Apr-2013) self.assertEqual(15-Jan-2013 + 2*years, 15-Jan-2015) d = 2*years + 3*months + 15*days self.assertEqual(d, Duration(2, 3, 15)) self.assertEqual(str(d), '2 years 3 months 15 days') self.assertEqual(1-Jan-2013 + 15*days, 16-Jan-2013) self.assertEqual(1-Apr-2013 + 15*days, 16-Apr-2013) self.assertEqual(1-Jan-2013 + d, 16-Apr-2015) self.assertEqual(16-Apr-2013- d, 1-Jan-2011) class Test_DateInterval(TestCase): """Date Intervals are [start..end].""" def test_DateInterval_1(self): i = (16-Apr-2015) - (1-Jan-2013) self.assertEqual(str(i), '[1-Jan-2013..16-Apr-2015]') self.assertEqual(i.d, 15) self.assertEqual(i.m, 3) self.assertEqual(i.y, 2) self.assertEqual(i.days, 835 * days) self.assertEqual(i.months, 27 * months + 15 * days) self.assertEqual(i.years, 2 * years + 3 * months + 15 * days) self.assertEqual(i.duration, Duration(2, 3, 15)) self.assertEqual(len(i), 835) self.assertTrue( 16-Apr-2015 in i) self.assertTrue( 1-Jan-2013 in i) self.assertFalse(17-Apr-2015 in i) self.assertFalse(31-Dec-2012 in i) def test_DateInterval_2(self): i = (1-Jan-2013) - (7-Dec-1963) self.assertEqual(len(i), 17923) self.assertEqual(i.years, 49 * years + 25 * days) def test_DateInterval_3(self): i = (1-Mar-2013) - (28-Feb-2013) self.assertEqual(len(i), 1) self.assertEqual(i.years, 1 * days) def test_DateInterval_4(self): i = (1-Mar-2012) - (28-Feb-2012) self.assertEqual(len(i), 2) self.assertEqual(i.years, 2 * days) def test_DateInterval_5(self): i = (31-Mar-2012) - (1-Mar-2012) self.assertEqual(len(i), 30) self.assertEqual(i.years, 30 * days) def test_DateInterval_fromNone(self): i = DateInterval(None, 1-Jan-2013) self.assertTrue( 1-Jan-2013 in i) self.assertFalse( 2-Jan-2013 in i) def test_DateInterval_toNone(self): i = DateInterval( 1-Jan-2013, None) self.assertFalse(31-Dec-2012 in i) self.assertTrue( 1-Jan-2013 in i) def test_DateInterval_allNone(self): i = DateInterval( None, None) self.assertFalse(31-Dec-2012 in i) self.assertFalse( 1-Jan-2013 in i) self.assertTrue(None in i) def test_DateInterval_intersection(self): i = DateInterval( 1-Mar-2012, 31-Mar-2012) self.assertEqual(i & DateInterval( 1-Jan-2012, 31-Dec-2012), i) self.assertEqual(i & DateInterval( 1-Jan-2012, 15-Mar-2012), DateInterval( 1-Mar-2012, 15-Mar-2012)) self.assertEqual(i & DateInterval(15-Mar-2012, 20-Mar-2012), DateInterval(15-Mar-2012, 20-Mar-2012)) self.assertEqual(i & DateInterval( 1-Apr-2012, 1-May-2012), None) class Test_Week(TestCase): """Week objects are DateIntervals that represent a calendar week [Sun..Sat].""" def test_week2(self): d = 15-Jan-2013 self.assertEqual(d.week[Fri], 18-Jan-2013) self.assertEqual(d.week[Mon], 14-Jan-2013) d = Jan-2013 self.assertEqual(d[Fri], [4-Jan-2013, 11-Jan-2013, 18-Jan-2013, 25-Jan-2013]) self.assertEqual(d[Fri][-1], 25-Jan-2013)
22dd50b91824ebec9b5bfb02589409947e0f07df
caryt/utensils
/lookup/lookup.py
1,445
3.609375
4
"""Lookup ========= """ from bisect import bisect_left, bisect_right from null import null class Over(object): """A High Value, useful for the final entry in Lookup tables.""" def __repr__(self): return 'Over' def __gt__(self, other): return True def __eq__(self, other): return other is Over def __lt__(self, other): return False Over = Over() class Lookup(object): """A Lookup table is an ordered list of (key, value) pairs. Looking up an item matches the first key **less than or equal to** the item. .. inheritance-diagram:: Lookup E.g. If aTable = ((100, 5), (200, 10), (500, 50)) then aTable[1] == 5, aTable[150] == 10, aTable[499] == 50. """ def __init__(self, *table): if table is not None: self.table = table def __getitem__(self, item): try: return self.table[self._lookup(item)][1] except IndexError: return Null def _lookup(self, item): return bisect_right(self.table, (item,)) def __repr__(self): return '\n'.join('<= {}\t {}'.format(k, v) for (k, v) in self.table) class LookupLessThan(Lookup): """A Lookup table is an ordered list of (key, value) pairs. Looking up an item matches the first key **less than** the item. E.g. If aTable = ((100, 5), (200, 10), (500, 50)) then aTable[1] == 5, aTable[150] == 10, aTable[499] == 50. .. inheritance-diagram:: LookupLessThan """ def _lookup(self, item): return bisect_left( self.table, (item, Over))
8b632f931537ba4098cb27359bb4d9e9af7dc135
ahalbert/python-euler
/euler41.py
324
3.5
4
__author__ = 'ahalbert' from euler7 import findPrimes def isPandigital(n): digits = "123456789" n = str(n) digits = digits[:len(n)] for i in digits: if i not in n: return False return True def euler41(): largest = 0 for i in findPrimes(9999999): if isPandigital(i): print i largest = i return largest
382700c11c43f4aa36ccdac6076a6b3685243c66
jasigrace/guess-the-number-game
/main.py
812
4.1875
4
import random from art import logo print(logo) print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100.") number = random.randint(1, 100) def guess_the_number(number_of_attempts): while number_of_attempts > 0: print(f"You have {number_of_attempts} remaining to guess the number. ") guess = int(input("Make a guess: ")) if guess < number: print("Too low.\nGuess again.") number_of_attempts -= 1 elif guess > number: print("Too high.\nGuess again.") number_of_attempts -= 1 elif guess == number: print(f"You got it. The answer was {number}.") number_of_attempts = 0 difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") if difficulty == "easy": guess_the_number(10) else: guess_the_number(5)
a8b2bce1a136602fbc22a90e772875bc773eab0b
JiaEn182445u/OSPhyton
/algorithm/FCFSOptimization.py
2,239
3.546875
4
from algorithm import FCFSParameter class FCFSOptimization: def __init__(self): self.dp = FCFSParameter.FCFSParameter("disk.ini") self.generateAnalysis() def printSequence(self, name, location): curr = 0 #current starting point prev = self.dp.getCurrent() #previous point total = 0#To show the final head movement of cylinders working1 = "" #To show the long working and find the difference in the brackets working2 = "" #To show the addition of the working after finding the difference in the brackets order = "" #To show the order of the queue in FCFS for i in location: curr = i #holds the same value as i in this for loop total += abs(prev - curr) #Calculation of the previous point subtracting the current point throughtout the whole working working1 += "|" + str(prev) + "-" + str(curr) + "|+" #Shows the working that finds the difference of the previous point subtracting the current point working2 += str(abs(prev - curr)) + "+" #Shows the addition working after finding the difference between the previous point and the current point prev = i #setting prev as i when for loop goes for the next value # removes arithmetical operations working1 = working1[0:-1] working2 = working2[0:-1] #adding curren tpoint into the order of sequence order = str(self.dp.getCurrent()) + ", " + str(location)[1:-1] #Say FCFS for indication print(name + "\n====") #Say the order of sequence print("Order of Access: " + order) #Show long calculation print("Total distance: " + "\n" + working1 + "\n") #Show shortened calculation after finding the difference print("= " + working2 + "\n") #Show total disk head movement print("= " + str(total) + "\n") def generateFCFS(self): # assign the sequence stated in disk.ini to seq seq = self.dp.getSequence() #Print FCFS sequence self.printSequence("FCFS", seq) def generateAnalysis(self): #generate FCFS self.generateFCFS()
38090603adca96a2605d8feb0ea655130bc346e5
michaelb-01/asset_IO
/examples/drawing_pen.py
1,706
3.71875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode PySide tutorial In this example, we select a colour value from the QtGui.QColorDialog and change the background colour of a QtGui.QFrame widget. author: Jan Bodnar website: zetcode.com last edited: August 2011 """ # drag text from input onto the button to change the button text import sys from PySide2 import QtGui, QtWidgets, QtCore class Example(QtWidgets.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 280, 270) self.setWindowTitle('Pen styles') self.show() def paintEvent(self, e): qp = QtGui.QPainter() qp.begin(self) self.drawLines(qp) qp.end() def drawLines(self, qp): pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine) qp.setPen(pen) qp.drawLine(20, 40, 250, 40) pen.setStyle(QtCore.Qt.DashLine) qp.setPen(pen) qp.drawLine(20, 80, 250, 80) pen.setStyle(QtCore.Qt.DashDotLine) qp.setPen(pen) qp.drawLine(20, 120, 250, 120) pen.setStyle(QtCore.Qt.DotLine) qp.setPen(pen) qp.drawLine(20, 160, 250, 160) pen.setStyle(QtCore.Qt.DashDotDotLine) qp.setPen(pen) qp.drawLine(20, 200, 250, 200) pen.setStyle(QtCore.Qt.CustomDashLine) pen.setDashPattern([1, 4, 5, 4]) qp.setPen(pen) qp.drawLine(20, 240, 250, 240) def main(): app = QtWidgets.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
54d9bd0b8590541debfc20a7dc977baf0e3a46c8
dhhyey-desai/Palindrome_checker
/main.py
805
3.59375
4
import pymongo from pymongo import MongoClient data = MongoClient() db = data.palindrome_checker users = db.users while True: word = input("Please enter a word\n") rev = word[::-1] if word == rev: print("This word is a palindrome") user1 = ({"Palindrome": word}) user_id = users.insert_one(user1).inserted_id else: print("This word is not a palindrome") user1 = ({"Not a Palindrome": word}) user_id = users.insert_one(user1).inserted_id option = input("Would you like to see more Palindromes?[Y/N]\n") if option == "Y": words = db.users.find({"Palindrome": word}) print(words) for doc in words: print(doc) else: pass pass
0491cafe80f3a348b0581ee93d03b8ba8f277e08
srsman/spider-college
/SpiderForCollege/bean/College.py
2,552
3.953125
4
""" 大学类 name:高校名 city:高校所在城市 department:高校归属哪个部门管理 levels:高校层次 url:高校官网 """ class College(object): def __init__(self, name='', icon='', city='', type='', department='', levels='', character='', url='', score=''): self._name = name self._icon = icon self._city = city self._type = type self._department = department self._levels = levels self._character = character self._url = url self._score = score @property def name(self): return self._name @name.setter def name(self, new_name): self._name = new_name @property def icon(self): return self._icon @icon.setter def icon(self, new_cion): self._icon = new_cion @property def city(self): return self._city @city.setter def city(self, new_city): self._city = new_city @property def type(self): return self._type @city.setter def type(self, new_type): self._type = new_type @property def department(self): return self._department @department.setter def department(self, new_department): self._department = new_department @property def levels(self): return self._levels @levels.setter def levels(self, new_levels): self._levels = new_levels @property def character(self): return self._character @character.setter def character(self, new_character): self._character = new_character @property def url(self): return self._url @url.setter def url(self, new_url): self._url = new_url @property def score(self): return self._score @score.setter def score(self, new_score): self._score = new_score def toString(self): # (college.name, college.city, college.type, college.department, college.levels, college.character, college.score) return '院校名称:'+college.name+'院校所在地:'+college.city+'院校隶属:'+college.department+'院校类型:'+college.type+'学历层次:'+college.levels+'院校特性:'+college.character+'满意度:'+college.score+'' if __name__ == '__main__': college = College() college.url = "aaa" college.city = 'aaa' college.url = 'bbb' college.character='aaa' college.score='aaa' college.levels='aaa' college.department='aaa' college.name='ds' print(college.toString())
cf0840aa10ba03a6bf786fdda6c05bcf72d8bf6d
issoni/twitter-bot
/mytwitterbot.py
2,481
3.609375
4
import sys import time import simple_twit from datetime import date, datetime def main(): # This call to simple_twit.create_api will create the api object that # Tweepy needs in order to make authenticated requests to Twitter's API. # Do not remove or change this function call. # Pass the variable "api" holding this Tweepy API object as the first # argument to simple_twit functions. api = simple_twit.create_api() simple_twit.version() # Project 04 Exercises ## # Exercise 1 - Get and print 10 tweets from your home timeline ## myTimeline = simple_twit.get_home_timeline(api, 10) ## for tweet in myTimeline: ## print(tweet.id) ## print(type(tweet.user)) ## print(tweet.author.name) ## print(tweet.user.name) ## print(tweet.full_text) ## print() ## ## # Exercise 2 - Get and print 10 tweets from another user's timeline ## careBotTimeline = simple_twit.get_user_timeline(api,"tinycarebot", 10) ## for tweet in careBotTimeline: ## print(tweet.id) ## print(type(tweet.user)) ## print(tweet.author.name) ## print(tweet.user.name) ## print(tweet.full_text) ## print() ## ## # Exercise 3 - Post 1 tweet to your timeline. ## myPost = simple_twit.send_tweet(api, "Exercise #3 on mytwitterbot.py (third run)") ## print(type(myPost)) ## ## # Exercise 4 - Post 1 media tweet to your timeline. ## myMediaPost = simple_twit.send_media_tweet(api, "Exercise #4 on mytwitterbot.py", "cat.jpg") ## print(type(myMediaPost)) # YOUR BOT CODE BEGINS HERE while True: year = datetime.now() currentYear = year.year today = date.today() d = today.strftime("%B %d, %Y") present = datetime.now() future = datetime(currentYear, 1, 1, 12, 0, 0) difference = present - future newDifference = 366 - difference.days tweet = "Today is " + str(d) + "." tweet2 = "Days left till " + str(currentYear + 1) + ": " + str(newDifference) if newDifference == 0: finalTweet = "HAPPY NEW YEAR!" else: finalTweet = tweet+ "\n"+ tweet2 print(finalTweet) myPost = simple_twit.send_tweet(api, finalTweet) print(type(myPost)) time.sleep(86400) # end def main() if __name__ == "__main__": main()
6dc95bab528b1bbd09521ddfdc3533caa83af8e5
TristanWedderburn/leetcode
/missingNumber.py
430
3.5625
4
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ # nums.sort() # for i in xrange(len(nums)): # if nums[i]!=i: # return i # return i+1 expectedSum = len(nums)*(len(nums)+1)/2 #formula to sum elements up to n actualSum = sum(nums) return expectedSum - actualSum
a67c9e5495b2c3b8079385bf20f6cb535e07cee1
TristanWedderburn/leetcode
/letterCombinationsOfAPhoneNumber.py
993
3.5625
4
class Solution(object): def __init__(self): self.combos = [] self.keypad = { '2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5':['j','k','l'], '6':['m','n','o'], '7':['p','q','r','s'], '8':['t','u','v'], '9':['w','x','y','z'], } def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return self.combos self.permutate(digits, '',0) self.combos.sort() return self.combos def permutate(self, digits, current, next): if next == len(digits): self.combos.append(current) return digit = digits[next] choices = self.keypad[digit] for choice in choices: self.permutate(digits,current+choice, next+1)
ef2407f29cd0990d9a09faa8e8ee636272ca862c
TristanWedderburn/leetcode
/maxDepthOfBinaryTree.py
912
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == None or root.val == None: return 0 depth = 1 q = deque() q.append((root,1)) #store tuple with node & current depth of node while(len(q)!=0): node = q.popleft() left = node[0].left right = node[0].right curr = node[1] if left!=None: q.append((left,curr+1)) if right!=None: q.append((right,curr+1)) depth = max(depth, curr) return depth
3654c6e6941304f8e95e428b490f68e7b6bb4227
randy-wittorp/ex
/ex39.py~
2,518
4.125
4
# create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } # create a basic set of states and some cities in them cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksongille' } # add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print out some cities print '-' * 10 print "NY State has: ", cities['NY'] print "OR State has: ", cities['OR'] # print some states print '-' * 10 print "Michigan's abbreviation is: ", states['Michigan'] print "Florida's abbreviation is: ", states['Florida'] # do it by using the state then cities dict print '-' * 10 print "Michigan has: ", cities[states['Michigan']] print "Florida has: ", cities[states['Florida']] # print every state abbreviation print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) # print every city in state print '-' * 10 for abbrev, city in cities.items(): print "%s is in %s" % (city, abbrev) # now do both at once print '-' * 10 for state, abbrev in states.items(): print "%s state is abbreviated %s and has city %s" % ( state, abbrev, cities[abbrev]) print '-' * 10 # safely get an abbreviation by state that might not be there state = states.get('Texas', None) if not state: print "Sorry, no Texas" # get a city with a default value city = cities.get('TX', 'does not exist') print "The city for the state 'TX' is: %s" % city print """ ----------------------------------------------------------- You may now enter additional states and their corresponding abbreviations. To exit, enter [Q]""" while True: # print "Enter new state name:" new_state = raw_input("Enter new state name:") if new_state.lower() == 'q': break print "Enter abbreviation:" new_abbrev = raw_input("> ") if new_abbrev.lower() == 'q': break print "-" * 60 print "You have entered %s, abbreviated as %s." % (new_state, new_abbrev) print "Correct? [Yn]" confirmation = raw_input("> ") if confirmation.lower() == 'n': continue else: states[new_state] = new_abbrev print "Would you like to see all the states so far[Yn]?" display_states = raw_input("> ") if display_states.lower() == 'n': continue else: print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) print "-" * 60
8db7d4ab1fc4d119e8c48f61821fae3dce188ea6
ernur1/thinking-recursively
/Chapter-3/exercise-3.5.py
748
4.0625
4
#============================================================================== # function to find the different arrangements possible using smaller number of letters #============================================================================== def permutations(letters, wordLength): if(wordLength < letters): if (wordLength == 1): return letters else: return letters * permutations(letters - 1, wordLength - 1) else: return "Wordlength can not be greater than no of available letters" if __name__ == '__main__': letters = int(raw_input("Enter the no of letters:")) wordLength = int(raw_input("Enter the length of word:")) print permutations(letters, wordLength)
48c2d231d58a0b04c6c91e529ee98bf985988857
ernur1/thinking-recursively
/Chapter-3/3.2-factorial.py
392
4.28125
4
#=============================================================================== # find the factorial of the given integer #=============================================================================== def factorial(num): if (num == 0): return 1 else: return num * factorial(num-1) if __name__ == '__main__': print "Factorial of given number is" , factorial(9)
752eb476bdcfb40289559b662245786b635c1766
ellen-yan/self-learning
/LearnPythonHardWay/ex33.py
362
4.15625
4
def print_num(highest, increment): i = 0 numbers = [] while i < highest: print "At the top i is %d" % i numbers.append(i) i = i + increment print "Numbers now: ", numbers print "At the bottom i is %d" % i return numbers print "The numbers: " numbers = print_num(6, 1) for num in numbers: print num
1ce6ad0a83e82ade475c75c40d9cf5c8fb4cac43
ellen-yan/self-learning
/LearnPythonHardWay/ex5.py
1,363
4.34375
4
my_name = 'Ellen X. Yan' my_age = 23 # not a lie my_height = 65 # inches my_weight = 135 # lbs my_eyes = 'Brown' my_teeth = 'White' my_hair = 'Black' print "Let's talk about %s." % my_name print "She's %d inches tall." % my_height print "She's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "She's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth # this line is tricky print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight) print "I just want to print %%" print "This prints no matter what: %r, %r" % (my_name, my_age) # '%s', '%d', and '%r' are "formatters". They tell Python to take the variable # on the right and put it in to replace the %s with its value # List of Python formatters: # %c: character # %s: string conversion via str() prior to formatting # %i: signed decimal integer # %d: signed decimal integer # %u: unsigned decimal integer # %o: octal integer # %x: hexadecimal integer (lowercase letters) # %X: hexadecimal integer (UPPERcase letters) # %e: exponential notation (with lowercase 'e') # %E: exponential notation (with UPPERcase 'E') # %f: floating point real number # %g: the shorter of %f and %e # %G: the shorter of %f and %E # %r: print the raw data (i.e. everything); useful for debugging
2a82f285d4c8f81e6a6511639631cba702e5874b
Satish-baradiya/Python-Scripts
/DSA/Sorting Algorithms/shell_sort.py
438
3.734375
4
def shellSort(input_list): gap = len(input_list)//2 while gap >0: for i in range(gap,len(input_list)): temp = input_list[i] j=i #Sort the sub list for this gap while j>=gap and input_list[j-gap]>temp: input_list[j] = input_list[j-gap] j = j-gap input_list[j] = temp #Reduce the gap for next element gap = gap//2 list = [19,2,31,45,30,11,121,27] shellSort(list) print(list)
9ac717872b1c1a54206dfc4546d41d91f54d661f
Satish-baradiya/Python-Scripts
/Web Scrapping/link_scrapper.py
337
3.65625
4
#This scripts gets all the links from a webpage and stores it into a list. #Getting title of wikipedia article using web scrapping. import requests import bs4 import lxml result = requests.get("https://en.wikipedia.org/wiki/Elon_Musk") result soup = bs4.BeautifulSoup(result.text,"lxml") res = list(soup.select('a')) res
abde85964ab7bf0622c04f25c675f00991cc377b
NachalnikKamchatki/PDFRenamer
/corr_file_name.py
976
4.03125
4
# Сhecks the character string (for example, file name) for correctness (absence of forbidden characters) def is_correct_filename(name: str, forbidden: list): ''' Are there any prohibited characters? ''' for c in name: if c in forbidden: return False return True def make_correct(filename: str, forbidden: list): ''' Replaces illegal characters with underscores. ''' if is_correct_filename(filename, forbidden): return filename else: for elem in forbidden: if elem in filename: filename = filename.replace(elem, '_') return filename def main(): forbidden = ['/', '\\', ':', '*', '?', '"', '>', '<', '|', '+', '%', '!', '@'] incorrect_filename = 'asd:gh/skkrd|' print(is_correct_filename(incorrect_filename, forbidden)) correct_fn = make_correct(incorrect_filename, forbidden) print(correct_fn) if __name__ == '__main__': main()
dfde62bcbc398265306822174373661091c08316
aldermartinezc/test_github
/graph_counts.py
3,628
3.578125
4
import matplotlib.pyplot as plt def graph_counts(state, dataframe, column, hasSubset, subset_Col, subset_Value, graphType, isPercentage, numShow, savePDF, savePNG): ''' Visualize particular columns in dataframe. Parameters: ---------- state: takes a string. The name of the state dataframe: takes a dataframe as input column: takes a column of the dataframe as input hasSubset: takes a boolean as input. Whether to take a subset of the dataframe subsetCol: takes both a string and 'None'. String for the column name; 'None' if hasSubset is False subsetValue: takes string, integer and 'None'. String and integer for the subset criteria; 'None' if hasSubset is False graphType: takes a string as input.Type of graph(bar, pie, hist, area...) isPercentage: takes a boolean as input. Show the graph in raw counts or percentage numShow: takes both integer and the string 'all' as input. The number of categories to show; 'all' for all categories savePDF: takes boolean as input. Whether to save image as a pdf savePNG: takes boolean as input. Whether to save image as a PNG Return: ------- None ''' #assigin color cusColor = 'b' if len(set(dataframe.loc[:,'BEERTYPE'])) == 1: for each in set(dataframe.loc[:,'BEERTYPE']): if each == 'NonLowPoint': cusColor = 'blue' elif each == 'LowPoint': cusColor = 'orange' else: pass graph_subset_name = '' #subset if hasSubset is False: col = dataframe.loc[:,str(column)] else: subsetCol = str(subset_Col) subsetValue = str(subset_Value) col = dataframe.loc[dataframe[subsetCol]==subsetValue, str(column)] if subsetValue == 'NonLowPoint': cusColor = 'blue' elif subsetValue == 'LowPoint': cusColor = 'orange' graph_subset_name = 'with subset '+str(subset_Col) +'where value is '+str(subset_Value) #show percentage or raw value if isPercentage: value_count = col.value_counts()/sum(col.value_counts()) plt_title = 'Percentage of Each by ' + str(column) else: value_count = col.value_counts() plt_title = 'Raw Count of Each by' + str(column) #number of categories if str(numShow) != 'all': value_count = value_count.head(numShow) #type of graph if str(graphType) == 'bar': ax = value_count.plot.bar(title = plt_title, color = cusColor) elif str(graphType) == 'pie': ax = value_count.plot.pie(autopct='%1.1f%%') elif str(graphType) == 'hist': ax = value_count.plot(kind = 'hist', color = cusColor) elif str(graphType) == 'area': ax = value_count.plot.area(color = cusColor) plt.title(plt_title) #save as PDF fig = ax.get_figure() fig_name = str(graphType) + ' plot of '+ str(plt_title) + graph_subset_name + ' -'+str(state) fig_name_pdf = fig_name+'.pdf' fig_name_png = fig_name+'.png' if savePDF and savePNG: fig.savefig(fig_name_pdf) fig.savefig(fig_name_png) else: if savePNG: fig.savefig(fig_name_png) elif savePDF: fig.savefig(fig_name_pdf)
265cfd59fe4dc187e6a1eddcac6f441d18cbe1e8
SokolnikSergey/VkPoster
/model/VkAuthorizationModel/ReadWriteToken.py
1,242
3.578125
4
import os,struct class ReadWriteToken: """This is class for search token to authorization on the site to achieve your aim in future without any questions about authorization (if your are entering not first time) write and read file with token """ @staticmethod # This method allows to search existing token def search_avaliable_token(file_name): if os.path.exists(file_name) and os.path.getsize(file_name): with open(file_name,"rb") as token_file: size_of_file = os.path.getsize(file_name) bytes_info = token_file.read() info = struct.unpack(str(size_of_file) + "s",bytes_info)[0].decode('utf-8') token_file.close() if not len(info) : return None return info else: return None @staticmethod #This method write token which you have recieved def write_token_to_file(path_to_file,token): bytes_token = bytes(token.encode()) format_for_pack = str(len(token)) + 's' token_file = open(path_to_file,"wb") token_file.write( struct.pack(format_for_pack,bytes_token)) token_file.close()
55c200066898a1ea3928796c088fc672b2520af4
mlukasik/spines
/classification/postprocess_matrix.py
947
3.71875
4
''' Created on Jan 16, 2013 @author: mlukasik ''' def choose_most_changing_least_changing(data_matrix, most_chg, least_chg): ''' Converts class value from real to boolean. We choose most_chg most changing values as positives and least_chg least changing values as negatives. ''' inddiff = [] for ind, row in enumerate(data_matrix): inddiff.append((ind, row[-1])) inddiff.sort(key=lambda x:abs(x[1])) #print "inddiff:", inddiff #print "len(inddiff):", len(inddiff) indices_true = set(map(lambda x: x[0], inddiff[:least_chg])) indices_false = set(map(lambda x: x[0], inddiff[-most_chg:])) new_data_matrix = [] for ind, row in enumerate(data_matrix): if ind in indices_true: row[-1] = 1 new_data_matrix.append(row) if ind in indices_false: row[-1] = 0 new_data_matrix.append(row) return new_data_matrix
63a5a714b9616501455bc4d7739d307009a84cde
Lopeze/Prim-s-Bio-Interactome
/io_utils.py
3,680
3.546875
4
''' I/O functions -cgraph(file)-> nodes, edges, weighted(optional) -adj_ls(nodes, edges, directed/undirected(optional) -adj_matrix(nodes, edges, directed/undirected(optional) I have created some optional boolean values that you can use to make the function work on undirected or directed graphs, and whether the graph has edge weights or not. ''' def cgraph(filee, weights = False): ''' With a file we will extract a graph of nodes and edges Input: 1. file containing nodes and edges 2. optional input that decides if graph has weights Return: 1. A list of nodes 2. A list of edges where edges are list pairs ''' nodes = [] edges = [] weighted = {} filee = open(filee) for line in filee: info = line.split() if info[0] not in nodes: nodes.append(info[0]) if info[1] not in nodes: nodes.append(info[1]) edges.append([info[0],info[1]]) if weights == True: weighted[info[0],info[1]] = int(info[2]) if weights == True: return nodes, edges, weighted else: return nodes, edges def adj_ls(nodes, edges, directed = False, weights = None): ''' From the nodes and edges make an adjacency list Input: 1. a list of nodes 2. a list of edges 3. optional boolean for directed edges 4. optional argument if weights are already created Return: A dictionary where each node has a list of nodes as its neighbors ''' adjlist = {} # if weights None: for node in nodes: adjlist[node] = [] for edge in edges: if directed == True: if node in edge[0]: if edge[1] not in adjlist[node]: adjlist[node].append(edge[1]) else: if node == edge[0]: if edge[1] not in adjlist[node]: adjlist[node].append(edge[1]) if node == edge[1]: if edge[0] not in adjlist[node]: adjlist[node].append(edge[0]) # else: # for weight in weights: # adjlist[weight] = adjlist[ return adjlist def adj_matrix(nodes, edges, directed = False): ''' This function creates an adjacency matrix from a list of nodes and edges and boolean value whether Input: 1. A list of nodes 2. A list of edges 3. True/False if directed or undirected graph Return: A list of lists representing an adjacency matrix ''' matrix = [] for node in nodes: helplist = [] for node2 in nodes: if directed == False: if [node, node2] in edges or [node2, node] in edges: helplist.append(1) else: helplist.append(0) else: if [node, node2] in edges: helplist.append(1) else: helplist.append(0) matrix.append(helplist) return matrix # def cgraphw(filee, delimeter): # ''' # With a file we will extract a graph of nodes,edges, and weights # corresponding to them # Input: # A file containing graph information # Return: # A list of # ''' # nodes = [] # edges = [] # weights = {} # for line in filee: # info = line.split() # nodes.append(info[0]) # nodes.append(info[1]) # weights[info[0],info[1]] = info[2] # edges.append(info) # return nodes, edges, weights
f175f9d3d2aaad0d6cc52f30c59099466f4cb785
ArretVice/algorithms-and-data-structures
/recursion.py
1,473
3.640625
4
import numpy as np array = list(np.random.randint(0, 100, 10)) print(f'Initial array: {array}\nSum = {sum(array)}\nLength = {len(array)}\nMax = {max(array)}') # recursive sum def rec_sum(array): if len(array) == 1: return array[0] else: return array.pop(0) + rec_sum(array) print(f'Recursive sum = {rec_sum(array.copy())}') # recursive length def rec_len(array): if array == list(): return 0 else: array.pop(0) return 1 + rec_len(array) print(f'Recursive length = {rec_len(array.copy())}') # recursive max def rec_max(array): if len(array) == 0: return None elif len(array) == 1: return array.pop(0) else: if array[0] > array[1]: array.pop(1) else: array.pop(0) return rec_max(array) print(f'Recursive max = {rec_max(array.copy())}') # recursive binary search def rec_binary_search(array, item): if array[0] <= item <= array[-1]: mid = len(array) // 2 if item == array[mid]: return item elif item < array[mid]: return rec_binary_search(array[:mid], item) else: return rec_binary_search(array[mid:], item) print( rec_binary_search(range(19), 18), rec_binary_search(range(100), 101), rec_binary_search(range(12, 5248, 2), 101), rec_binary_search(range(1024), 260), sep='\n' )
fe7c55558bc6bc0f6fe216ab207abd3ad2719ad2
meier3/wallbreakers
/week2/DistributeCandies.py
490
3.625
4
class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ # compile set of candy kinds kinds = set() for c in candies: kinds.add(c) # collect values numKinds = len(kinds) numCandies = len(candies) # solution is numKinds, but caps at half of the possible candies optimal = min((numCandies/2), numKinds) return optimal
178a37ed5f2501fc33aad24d2acaaf2978dca33f
anluxi/game
/game.py
1,714
3.875
4
print("hallo lovely") print("游戏\t恋爱\t猜数字") print("""欢迎来到千华月的小家 我是这里的主人千华月 请不要搞错,华月是姓千是名""") import random#导入伪随机库 import decimal#导入十进制库 import os#导入清屏库 three = decimal.Decimal("0.1")#将十进制状态赋值给three变量 two = random.randint(0,9)#将伪随机库内的整数随机模块赋值给two变量 love=0#好感度值初始化 one = 10#循环执行的次数初始化 game=5#好感度系统的循环次数的初始化 while one >0:#当one变量大于0时执行循环 temp = input("请输入一个数字:")#接收用户输入的数据 guess = int(temp)#将temp变量内的字符串转化成整数赋值给guess变量 if guess == two:#如果guess变量等于two变量那么执行本行 print("对了") while game>0: if guess == two: love += 100 aubd="好感度提升:" print(aubd,love) juzi="客人,你可以走了" agub=juzi.replace("客人","主人") print(agub) break break#本行条件为真时终止循环 else:#如果guess不等于two那么执行本行 def lovet(): zuji="客人,你可以走了" chcdd=zuji.replace("客人","白痴") print(chcdd) lovet() while game>0: love += 20 aujd="好感度提升:" print(aujd,love) break if guess > two: print("你的数字大了") else: print("你的数字小了") while game>0: game-=1 dhc="你还有第" chc="次机会" print(dhc,game,chc) break one -= 1#循环次数不断减1 print("游戏结束\nok\n我错了再见\n拜拜") print(r"游戏路径:/sdcard/AND")
78ff6b74d9fb98e9d27d458982c0844a79dadfd4
zhangxw1986/python_manage
/chap_11/index_words.py
659
4.09375
4
#! /usr/bin/env python # -*- coding:utf-8 -*- def index_words(text): result = [] if text: result.append(0) for index, value in enumerate(text, 1): if value == ' ': result.append(index) return result def g_index_words(text): 'print the location of every word' if text: yield 0 for index, value in enumerate(text, 1): if value == ' ': yield index if __name__ == "__main__": text = 'The Zen of Python, by Tim Peters' result = index_words(text) print(result) print(list(g_index_words(text))) print(g_index_words.__doc__) print(g_index_words.__name__)
590c9de183796d943f7f27281fc1f45455713be1
JimmySenny/demoInterview
/src/pufa/generate.py
634
3.640625
4
#!/usr/bin/env python3 class Solution: # def generate(self, numRows: int) -> List[List[int]]: def generate(self, numRows): ret = list(); i = 0 while i < numRows: row = list(); j = 0 while j < i+1: if j == 0 or j == i: row.append(1); else: row.append(ret[i-1][j] + ret[i-1][j-1]); j += 1 i += 1 ret.append(row); return ret; def main(): s = Solution() print(s.generate(5)); print(s.generate(10)); if __name__ == '__main__': main()
9d7ace0d89acca23afa3cc3ea8487347e6248b34
JimmySenny/demoInterview
/src/pufa/reverseString.py
642
3.859375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 切片 class Solution: # def reverseString(self, s: List[str]) -> None: def reverseString(self, s): #s = s[::-1]; s[0::] = s[::-1]; def reverseString1(self,s): left = 0 right = len(s) - 1 while left < right: tmp = s[left] s[left] = s[right] s[right] = tmp left += 1 right -= 1 def main(): l = [ "h","e","l","l","o" ]; s = Solution(); print( s.reverseString(l) ); print( l ); print( s.reverseString1(l) ); print( l ); if __name__ == '__main__': main();
b444ea4324f5f84364db4e5dc73e48b30e1b004b
JimmySenny/demoInterview
/src/pufa/repeatedSubstringPattern.py
500
3.703125
4
#!/usr/bin/env python3 class Solution: # def repeatedSubstringPattern(self, s: str) -> bool: def repeatedSubstringPattern(self, s): ss = s + s; if s in ss[1:-1]: return True; return False; def main(): s = Solution(); print(s.repeatedSubstringPattern("abab")); print(s.repeatedSubstringPattern("aba")); print(s.repeatedSubstringPattern("abcabcabcabc")); print(s.repeatedSubstringPattern("abba")); if __name__ =='__main__': main();
de75840ffebcd6abc795eb59451e7da91402ea53
deorerohan/InterviewPreparation
/Practice/HackerRank/ListComprehensions.py
586
3.734375
4
x = int(input()) + 1 y = int(input()) + 1 z = int(input()) + 1 n = int(input()) output = list() def UsingForLoop(x, y, z, n): for i in range(x): for j in range(y): for k in range(z): if i + j + k == n: continue output.append([i, j, k]) print(output) def UsingComprehension(x, y, z, n): output = [ [i, j, k] for k in range(z) for j in range(y) for i in range(x) if i + j + k != n ] # if i+j+k != n print(output) UsingComprehension(x, y, z, n)
b342abed1665454940f48e69e663f3ec50ee35cb
ahmadaljanabi/CS50-s-Web-Programming-with-Python-and-JavaScript
/lambda.py
247
3.90625
4
people = [ {"name": "Ahmed", "house": "South"}, {"name": "Hussain", "house": "North"}, {"name": "Mohammed", "house": "West"} ] # def f(person): # return person["name"] people.sort(key=lambda person: person["name"]) print(people)
4b2efd65c09a643a06b339ea868f63ae5ca6c76a
adibahsan/PythonProject
/lists.py
318
4.0625
4
#lists are mutable :D list1 = ["ami", "tumi", "shey", 1, 420.2] for x in list1: print(x) list2 = [list1, list1,list1] print(list2) for x in list2: for y in x: print(y,end=" ") print() for x in range (0,len(list2)): for y in range(0,len(list2[x])): print(list2[x][y],end=",") print()
a6f237792aef743e05e0e1d0f81e510b0926bdec
nsimsofmordor/PythonProjects
/Projects/PythonPractice.org/p2_odd_or_even.py
481
4.40625
4
# Ask the user for a number. # Depending on whether the number is even or odd, print out an appropriate message to the user. # If the number is a multiple of 4, print out a different message. # Ask for a positive number number = int(input("Enter a positive number: ")) while number < 0: number = int(input("Enter a positive number: ")) # print out if odd or even if number % 4 == 0: print("Multiple of 4") elif number % 2 == 0: print("Even") else: print("Odd")
ee6fcba43821b771900c0ced8ca27003e6085fd0
nsimsofmordor/PythonProjects
/Projects/PythonPractice.org/p6_sting_lists.py
287
4.53125
5
# Ask the user for a string and print out whether this string is a palindrome or not. my_str = str(input("Enter a string to check if it is a palindrome or not: ").lower()) rev_str = my_str[::-1].lower() if my_str == rev_str: print("Palindrome!") else: print("Not Palindrome!")
068905cbe2bea0582747af13f294ce98d8edf24f
nsimsofmordor/PythonProjects
/Projects/Python_Tutorials_Corey_Schafer/PPBT5 Dicts.py
1,064
4.375
4
# {Key:value} == {Identifier:Data} student = {'name': 'john', 'age': '27', 'courses': ['Math', 'Science']} print(f"student = {student}") print(f"student[name] = {student['name']}") print(f"student['courses'] = {student['courses']}\n") # print(student['Phone']) # throws a KeyError, sine that key doesn't exist print(student.get('phone', 'Not Found')) print() print("setting student[phone] = 555-5555") student['phone'] = '555-5555' print(student) print() print("results of student.update({'name': 'frank'})") student.update({'name': 'frank'}) print(student) print() print("deleting student['age']") del student['age'] print(student) print() print("printing the name...") name = student['name'] print(name) print("\nprinting the len of student") print(len(student)) print("\nprinting the student keys") print(student.keys()) print("\nprinting the student values") print(student.values()) print("\nprinting the student items") print(student.items()) print('\nprinting the key,value pairs') for key,value in student.items(): print (key, value)
329e327ea632d3ce5e77372b78e741820fe08d87
luismelendez94/holberton-system_engineering-devops
/0x16-api_advanced/100-count.py
280
3.546875
4
#!/usr/bin/python3 """ Recursive function that queries a Reddit API, parses the title of all hot articles, and prints a sorted count of given keywords """ import requests def count_words(subreddit, word_list): """ Get the total of titles recursively """ return None
961e2bbf24a3533c2dece5b0e4cfd0e09a7fcba2
Priyanka-Gore/INR-Exchange-Rate-
/Assignment.py
1,816
3.796875
4
import datetime import matplotlib.pyplot as plt import json import pandas as pd class my_dictionary(dict): def __init__(self): self = dict() def add(self, key, value): self[key] = value def common_dates(a, b): a_set = set(a) b_set = set(b) if len(a_set.intersection(b_set)) > 0: return (a_set.intersection(b_set)) def daterange(date1, date2): for n in range(int ((date2 - date1).days)+1): yield date1 + datetime.timedelta(n) #loading the data.json file and converting it into data frame the file is placed in same project directory with open('data.json') as json_data: d = json.load(json_data) df = pd.DataFrame(d["rates"]) index=df.index columns=df.columns print("Please enter a date in YYYY-MM-DD format .Date Should be Between Jan 2019 - Dec 2019") star_dt=input("Enter Start Date") yr,mo,day=map(int,star_dt.split('-')) start_dt = datetime.date(yr,mo,day) end_dt=input("End Date") yr,mo,day=map(int,end_dt.split('-')) end_dt = datetime.date(yr,mo,day) datelist=[] #To get the dates between Start date and End Date for dt in daterange(start_dt, end_dt): datelist.append(dt.strftime("%Y-%m-%d")) #print(datelist) #print(index) #print(columns) #finding common dates between dataframes columns and required dates finaldates=common_dates(columns,datelist) finaldates=list(finaldates) #creating dictionary to store INR exchange rates between given dates dict_obj = my_dictionary() for i in range(len(finaldates)): datepass=str(finaldates[i]) #print(datepass,df.loc['INR',datepass]) dict_obj.key = datepass dict_obj.value =df.loc['INR',datepass] dict_obj.add(dict_obj.key, dict_obj.value) keys = dict_obj.keys() values = dict_obj.values() #Plot graph plt.xticks(rotation=45) plt.bar(keys, values,align='edge') plt.show()
a660aaac8eebb1e01e1438edee918867de197dd0
dsalnasskhuzzzy/python
/multiDemensionalTicTacToe/nDttt.py
2,271
3.5
4
class board: def __init__(self,demensions,playerCount): #Both Player Count and Demensions must be natural numbers self.demensions = demensions self.marks = [[] for x in range(playerCount)] def addMarkForPlayer(self,mark,playerID): self.marks[playerID].append(mark) def checkIfValidMark(self,mark): if(len(mark)!=self.demensions): return False for part in mark: if(part != 0 and part != 1 and part != 2): return False for playerMarks in self.marks: for otherMark in playerMarks: if(otherMark == mark): return False #If it's not found to be a bad mark, it's Valid return True def lazyWinCheck(self,playerID): #Only checks the to see if the players last move has won them the game playerMarks = self.marks[playerID] moveCount = len(playerMarks) lastMark = playerMarks[moveCount-1] for index in range(moveCount-1): for secondIndex in range(index+1,moveCount-1): if(self.checkWinCoords(lastMark,playerMarks[index],playerMarks[secondIndex])): return True #If no valid win condition has been found the player has not won return False def checkWinCoords(self,c1,c2,c3): ascendingFound = False for index in range(self.demensions): a = c1[index] b = c2[index] c = c3[index] ascending = (a!=b and b!=c and c!=a) equality = a==b and b==c if (not ascendingFound) and (ascending): ascendingFound = True #Check for ascending then check for equality if not (ascending or equality): return False #If we make it to the end of this check and there is an ascending then it is a valid win condition if ascendingFound: return True plNum = int(raw_input("How many players?: ")) dem = int(raw_input("How many demensions?: ")) game = board(dem,plNum) gameDone = False playerID = -1 while(not gameDone): playerID = (playerID + 1) % plNum mark = [] for player in game.marks: print player while mark==[]: for x in range(dem): input = int(raw_input("PLAYER %d Enter (0,1, or 2) for demension %d |" % (playerID,x))) mark.append(input) if not game.checkIfValidMark(mark): print "Invalid Mark Thrown Away" mark = [] print "Mark Completed" game.addMarkForPlayer(mark,playerID) gameDone = game.lazyWinCheck(playerID) print "Player %d has won" % (playerID)
14325d0779ae0aa4b96b89daddcaef7448493106
msossoman/coderin90
/calculator.py
1,165
4.125
4
def add (a, b): c = a + b print "The answer is: {0} + {1} = {2}".format(a, b, c) def subtract (a, b): c = a - b print "The answer is {0} - {1} = {2}".format(a, b, c) def multiply (a, b): c = a * b print "The answer is {0} * {1} = {2}".format(a, b, c) def divide (a, b): c = a / b print "The answer is {0} / {1} = {2}".format(a, b, c) def choice(): operation = int(raw_input("""Select operation: \n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n Enter choice (1/2/3/4):""")) if operation == 1: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") add(float(a), float(b)) elif operation == 2: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") subtract(float(a), float(b)) elif operation == 3: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") multiply(float(a), float(b)) elif operation == 4: a = raw_input("Enter the first number: \n") b = raw_input("Enter the second number: \n") divide(float(a), float(b)) else: print "Please select a valid operation" choice() if __name__ == '__main__': choice()
0d7f49adb8e1057abdd0ef528636cdf2489ad2f8
Mcgrupp34/microbit
/code_assignment1_temp.py
691
3.75
4
from microbit import * #calibrate the compass when the program starts compass.calibrate #main loop while True: #Read temperature and place in variable temp = temperature() #Read compass heading and place in variable direction = compass.heading() #Display temp converted to Fahrenheit display.scroll(str(temp*(9/5)+32)+" Deg F") #Display compass heading display.scroll(str(direction)) #Build CSV entry variable entry = (str(temp)) + ", " + (str(direction)) #open csv on microbit with open('tempdir.csv') as csv: csv.write(entry) sleep(10000) #Print results to terminal print(entry)
483b5885c773d07ac670547100c67bd5f97e249f
EmilyLaforte/learning
/python/test.py
248
3.578125
4
import turtle t = turtle.Turtle() t.pencolor("pink") t.speed(0) for i in range(5): t.fd(50) t.lt(123) # Let's go counterclockwise this time t.pencolor("turquoise") for i in range(5): t.fd(100) t.lt(123) turtle.done()
cc556397a64793e5087523f19f4e6ce73b06ea82
jeffysam6/April-Leetcoding-Challenge
/search-in-rotated-sorted-array-week-3.py
906
3.53125
4
class Solution: def search(self, arr: List[int], target: int) -> int: if(len(arr) == 0): return -1 left = 0 right = len(arr) -1 while(left < right): mid = left + (right - left)//2 if(arr[mid] > arr[right]): left = mid + 1 else: right = mid initial = left left = 0 right = len(arr) - 1 if(target >= arr[initial] and target <= arr[right]): left = initial else: right = initial - 1 while(left <= right): mid = left + (right - left)//2 if(arr[mid] == target): return (mid) elif(target > arr[mid]): left = mid + 1 else: right = mid - 1 return -1
6cdff0ab5ee938a1ad0371041a12875817b9c65e
captflint/dndscripts
/deathsim.py
763
3.6875
4
import random trials = 0 survived = 0 died = 0 turnavg = 0 longest = 0 while trials != 1000000000: strikes = 0 turn = 0 while strikes < 3: roll = random.randint(1, 20) turn += 1 if roll == 20: strikes = 10 elif roll < 10: strikes += 1 else: pass if strikes == 10: survived += 1 else: died += 1 turnavg = (turnavg * (died - 1) + turn) / died if turn > longest: longest = turn trials += 1 if trials % 1000000 == 0: print(trials / 1000000000) print('Survival ratio:', survived / trials) print('Death ratio:', died / trials) print('Average time til death:', turnavg) print('Longest time until death:', longest)
e7b1564b9ca22fb1186ce66e261e9dd213a3c776
lffelmann/coincount
/coincount_lib.py
7,911
3.6875
4
"""Library with all the functions for CoinCount!""" import csv import pickle from math import pi, sqrt from typing import Any import cv2 import numpy as np def contour(image: Any, blur: int = 3, threshold: int = 110) -> list: """ Returns the contours of object in a image. Parameters: image: Image to get contours from. blur (int): Value for Gaussian Blur. Must be odd and positive. threshold (int): Threshold value for conversion from grey image to binary image. Returns: (list): List with founded contours, gray image, blurred image and binary image. -> [[contours], GrayImage, BlurImage, BinaryImage] """ try: img_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # to gray img_blur = cv2.GaussianBlur(img_gray, (blur, blur), 0) # blur img_bnry = cv2.threshold(img_blur, threshold, 255, cv2.THRESH_BINARY_INV)[1] # binary cnts, _ = cv2.findContours(img_bnry, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # get contours return [cnts, img_gray, img_blur, img_bnry] except: raise def circle(contour: list, image: Any, accuracy: float = 0.15, min_area: float = 0) -> list: """ Return if a contour is a circle or not. If TRUE it also returns area, perimeter and mean color. Parameters: contour (list): Contour to check. image: Image in which the contour appears. accuracy (float): Accuracy to determine if the contour is a circle or not. Must be between 0 and 1. min_area (float): Minimum area of circle. Returns: (list): List with result, area, perimeter, mean blue, mean green and mean red. -> [True/False, Area, Perimeter, MeanBlue, MeanGreen, MeanRed] """ try: area = cv2.contourArea(contour) # area perimeter = cv2.arcLength(contour, True) # perimeter radius_area = sqrt(area / pi) # radius from area radius_perimeter = perimeter / (2 * pi) # radius form perimeter if (radius_area * (1 - accuracy)) <= radius_perimeter <= ( radius_area * (1 + accuracy)) and area >= min_area: # compare radius area perimeter mask = np.zeros(image.shape[:2], dtype="uint8") #create mask cv2.drawContours(mask, [contour], -1, 255, -1) #draw contours masked = cv2.bitwise_and(image, image, mask=mask) #merge mask and image color = cv2.mean(masked, mask) #get mean colour return [True, area, perimeter, color[0], color[1], color[2]] return [False] except: raise def rectangle(contour: list, accuracy: float = 0.01, min_area: float = 0) -> list: """ Return if a contour is a rectangle or not. If TRUE it also returns the length of both sides. Parameters: contour (list): Contour to check. accuracy (float): Accuracy to determine if the contour is a rectangle or not. min_area (float): Minimum area of rectangle. Returns: (list): List with result, length of side a and length of side b. -> [Ture/False, SideA, SideB] """ try: length = [] area = cv2.contourArea(contour) # area approx = cv2.approxPolyDP(contour, accuracy * cv2.arcLength(contour, True), True) # simplify contour if (len(approx) == 4) and area >= min_area: # if four sides -> return length for i in range(0, len(approx) - 1): point = approx[i] - approx[i + 1] # x and y form 0,0 point = np.ndarray.tolist(point[0]) # point to array a_2 = abs(point[0]) ** 2 # calc a^2 b_2 = abs(point[1]) ** 2 # calc b^2 length.append(sqrt(a_2 + b_2)) # calc c and append to list # 4th line point = approx[3] - approx[0] # x and y form 0,0 point = np.ndarray.tolist(point[0]) # point to array a_2 = abs(point[0]) ** 2 # calc a^2 b_2 = abs(point[1]) ** 2 # calc b^2 length.append(sqrt(a_2 + b_2)) # calc c and append to list a = (length[0] + length[2]) / 2 # average length of side a b = (length[1] + length[3]) / 2 # average length of side b return [True, a, b] return [False] except: raise def len_pixel(reference_mm: list, reference_pxl: list) -> float: """ Returns the length of a pixel in mm, when there is a reference rectangle. Parameters: reference_mm (list): Length of reference rectangle in mm. reference_pxl (list): Length of reference rectangle in pixel. Returns: (float): Length of a pixel in mm. """ try: reference_mm.sort() # sort list reference_val reference_pxl.sort() # sort list reference_pxl pxl_len_0 = reference_mm[0] / reference_pxl[0] # calc len of pxl on short side pxl_len_1 = reference_mm[1] / reference_pxl[1] # calc len of pxl on long side return (pxl_len_0 + pxl_len_1) / 2 # calc and return average len except: raise def convert_len(length_of_pixel: float, length_in_pixel: float) -> float: """ Returns a length of pixel in mm. Parameters: length_of_pixel (float): Length of one pixel in mm. length_in_pixel (float): Length of the to converting element in pixel. Returns: (float): Length of the element in pixel. """ try: actual_length = length_of_pixel * length_in_pixel # calc actual len return actual_length except: raise def svm_readcsv(path: str, target_val: Any, list_data: list = None, list_target: list = None) -> list: """ Reads data from csv to list and adds target to list. Used for Support Vector Machine. Parameters: path (str): Path of csv file. target_val (Any): Target of the values in csv file. list_data (list): List to extend data. list_target (list): List to extend target. Returns: (list): List with list of csv values and list of targets -> [[Csv], [Target]] """ try: if list_data is None: # if no data list -> crate data list data = [] else: data = list_data if list_target is None: # if no target list -> crate target list target = [] else: target = list_target file = open(path, 'r', newline='') # open file reader = csv.reader(file) # create reader for row in reader: # add csv and target to list data.append(row) target.append(target_val) file.close() # close file return [data, target] except: raise def svm_writecsv(path: str, values: list) -> None: """ Write values into csv file. Used for Support Vector Machine. Parameters: path (str): Path of csv file. values (list): Values to write to csv files. """ try: file = open(path, 'a', newline='') # open file writer = csv.writer(file) # create writer writer.writerows(values) # write values file.close() # close file except: raise def svm_writemodel(path: str, model: Any) -> None: """ Saves model to file. Parameters: path (str): Path to save file. model (Any): Model to save. """ try: file = open(path, 'wb') # open file pickle.dump(model, file) # save file file.close() # close file except: raise def svm_readmodel(path: str) -> Any: """ Returns saved model from file. Parameters: path (str): Path of file of saved model. Returns: (Any): Saved model. """ try: file = open(path, 'rb') # open file model = pickle.load(file) # load model file.close() # close file return model except: raise
6ad85b2a11a283923a071fb9ee5a51847da13094
craigtmoore/secret_code
/main.py
3,562
3.671875
4
import argparse import os import string class EncodeDecode: def __init__(self): alphabet = string.printable + string.whitespace self.encodeDict = dict() self.decodeDict = dict() for i, character in enumerate(alphabet): self.encodeDict[character] = i self.decodeDict[str(i)] = character def run(self): running = True while running: task = (input("Would you like to [E]ncode or [D]ecode a message or a [F]ile or [X] to exit? ").upper())[0] if task == 'E': message = input("Enter the message to encode: \n") encoded_message = "" for character in message: value = self.encodeDict[character] encoded_message += f"{value} " print(encoded_message) elif task == 'D': message = input("Enter the message to decode: \n").split(" ") decoded_message = "" for character in message: if character != "": value = self.decodeDict[character] decoded_message += str(value) print(decoded_message) elif task == 'F': file_name = input("Enter the name of the file: ") task = input("Do you want to encode or decode?") if task == 'E': self.encode_file(file_name) if task == 'D': self.decode_file(file_name) elif task == 'X': running = False else: print("That is not a valid option") def decode_file(self, file_name): tmp_file_name = "temporary_file" with open(tmp_file_name, "w") as tmp_file: with open(file_name, "r") as file: for line in file.readlines(): characters = line.split(" ") for character in characters: if character.isnumeric(): value = self.decodeDict[character] tmp_file.write(f"{value}") os.remove(file_name) os.rename(tmp_file_name, file_name) print(f"Finished decoding file {file_name}") def encode_file(self, file_name): tmp_file_name = "temporary_file" with open(tmp_file_name, "w") as tmp_file: with open(file_name, "r") as file: for line in file.readlines(): for character in line: value = self.encodeDict[character] tmp_file.write(f"{value} ") tmp_file.write("\n") os.remove(file_name) os.rename(tmp_file_name, file_name) print(f"Finished encoding file {file_name}") if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("-f", "--file", required=False, help="file name") ap.add_argument("-d", "--decode", dest='decode', action='store_true') ap.add_argument("-e", "--encode", dest='decode', action='store_false') ap.set_defaults(decode=True) args = vars(ap.parse_args()) encodeDecode = EncodeDecode() file_name = args['file'] if file_name: if args['decode']: encodeDecode.decode_file(file_name) else: encodeDecode.encode_file(file_name) else: EncodeDecode().run()
0d83a00fa33a4cc38445fca9c4b72bdb840dea18
becodev/python-utn-frcu
/guia02python/ejercicio12.py
440
3.875
4
""" Dado un número de mes de 1 a 12 determinar cuántos días tiene dicho mes. """ # No se contempla año bisiesto mes = int(input("Ingrese numero de mes (1 a 12): ")) if(mes >= 1 and mes <= 12): if mes in [4, 6, 9, 11]: print("El mes ingresado tiene 30 dias.") elif(mes == 2): print("El mes ingresado tiene 28 dias.") else: print("El mes ingresado tiene 31 dias.") else: print("Mes incorrecto.")
a72228600b760a27521c4731693dce52c9fb1d8f
becodev/python-utn-frcu
/guia02python/ejercicio15.py
676
4.09375
4
""" Dado el valor numérico de la temperatura ambiente y su escala representada con una carácter (C Celsius y F Fahrenheit), convertirla a la otra escala aplicando las siguientes fórmulas según correspondan: a. de F a C: (temp_f - 32) * 5/9 b. de C a F: (temp_c * 5/9) + 32 """ temp = float(input("Ingrese temperatura: ")) escala = input("Ingrese escala de la temperatura(C o F): ") faren = round((temp * 9/5) + 32, 2) celsius = round((temp - 32) * 5/9, 2) if(escala.upper() == "C"): print("La temperatura en escala Fahrenheit es: ", faren) elif(escala.upper() == "F"): print("La temperatura en escala Celsius es", celsius) else: print("Escala incorrecta.")
c53d4eaa499f6920318a8fdd0b506511428c74b9
becodev/python-utn-frcu
/guia02python/ejercicio4.py
500
3.921875
4
""" Dada las tres notas obtenidas por un alumno en los distintos parciales, determinar si el mismo está aprobado o desaprobado. """ parcial1 = float(input("Ingrese nota primer parcial: ")) parcial2 = float(input("Ingrese nota segundo parcial: ")) parcial3 = float(input("Ingrese nota tercer parcial: ")) promedio = round((parcial1 + parcial2 + parcial3) / 3, 2) if(promedio >= 6): print("Alumno aprobado con promedio ", promedio) else: print("Alumno desaprobado con promedio ", promedio)
39cd0ae1ddb47e458d2137fab8f08575aaa81569
becodev/python-utn-frcu
/guia01python/ejercicio12.py
590
3.8125
4
""" Una empresa distribuidora de energía le cobrar a sus abonados el consumo de kW por hora, pero además debe sumarle el 0,21 % de impuesto, pero actualmente todos los cliente están dentro de un plan de promoción que les descuenta el 3,7 % del monto total a pagar. """ consumo = float(input("Ingrese consumo en KW: ")) precio = float(input("Ingrese costo del KW: ")) costo = consumo * precio impuesto = (0.21 / 100) * costo descuento = round((3.7 / 100) * (costo + impuesto), 2) total = round(((costo + impuesto) - descuento), 2) print("El importe a cobrar al cliente es: $", total)
508d6c36ad2d7ebdddf2cd856d58195c952bbf9e
becodev/python-utn-frcu
/guia02pythonCiclos/ejercicio6.py
261
3.609375
4
""" Dado 15 números indicar cuál es el mayor. """ numeros = [11, 33, 4, 5, 12, 56, 21, 34, 625, 76, 78, 12, 123, 54, 69] i = 0 mayor = 0 while i < 15: if(numeros[i] > mayor): mayor = numeros[i] i += 1 print("El numero mayor es %s" % mayor)
4293eb83b348924bd3db9c8ecb9f0dac2d5b5717
becodev/python-utn-frcu
/guia01python/ejercicio18.py
424
3.5625
4
""" Dada las tres mediciones que se realizó un pluviómetro en un día, cada vez que el mismo se vacía, determinar cuántos milímetros llovió ese día. """ medicion1 = float(input("Ingrese primera medicion: ")) medicion2 = float(input("Ingrese segunda medicion: ")) medicion3 = float(input("Ingrese tercera medicion: ")) milimetros = medicion1 + medicion2 + medicion3 print("Hoy llovió:", milimetros, "milimetros.")
76d0d1452b34e6f66f282a7b07302ebd3a835159
saiswethak/swetha
/66.py
170
3.609375
4
m=int(input()) count=0 for i in range(1,m): if(m % i) == 0: count+=1 if(count == 2): print("no") break else: print("yes")
334c8954b4b2e25721c95443caac224b89d74e9f
kenkitts/advent_of_code
/day10/day10p1.py
501
3.515625
4
def p1(): data = sorted([int(line.strip()) for line in open('input.txt','rt')]) previous_value, one_jolt_adapters, three_jolt_adapters = 0,0,0 for idx,val in enumerate(data): if val - previous_value == 1: one_jolt_adapters += 1 elif val - previous_value == 3: three_jolt_adapters += 1 previous_value = val three_jolt_adapters += 1 return one_jolt_adapters * three_jolt_adapters print('The solution to part 1 is: {}'.format(p1()))
160fa4ec6f60422e90267d51ffaaf7549e4cf229
realtalishaw/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/3-print_alphabt.py
118
3.796875
4
#!/usr/bin/python3 for i in range(26): if i != 4 and i != 16: print('{}'.format(chr(ord('a')+i)), end='')
1b26680c89752d77a1f78e231a9165c4a25a004c
Ashok-Mishra/python-samples
/python exercises/dek_program054.py
864
4.4375
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Define a class named Shape and its subclass Square. The Square class has # an init function which takes a length as argument. Both classes have a # area function which can print the area of the shape where Shape's area # is 0 by default. # Hints: # To override a method in super class, we can define a method with the # same name in the super class. class Shape(object): def area(self): return 0 class Square(Shape): def __init__(self, length): print 'calling init method' self.length = length def area(self): return self.length * self.length def main(): squareObj = Square(int(raw_input('Enter Length : '))) # squareObj = Square(int('5')) print 'Area of Square is : ', squareObj.area() if __name__ == '__main__': main()
40746a8b06658c8d7935e4238f69e17e1d7d9315
Ashok-Mishra/python-samples
/python exercises/dek_program068.py
970
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program068: # Please write a program using generator to print the even numbers between # 0 and n in comma separated form while n is input by console. # Example: # If the following n is given as input to the program: # 10 # Then, the output of the program should be: # 0,2,4,6,8,10 # Hints: # Use yield to produce the next value in generator. # In case of input data being supplied to the question, it should be # assumed to be a console input. def evenGenerator(endValue): eveniter = 0 while eveniter <= endValue: if eveniter % 2 == 0: yield eveniter eveniter += 1 def main(endValue): result = [] evenGen = evenGenerator(int(endValue)) for res in evenGen: result.append(str(res)) # print result print ",".join(result) if __name__ == '__main__': main(raw_input("Input endLimit: "))
e260d508fca7871b4955a4d44eded3503d532c18
Ashok-Mishra/python-samples
/python exercises/dek_program062.py
482
4.40625
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Write a program to read an ASCII string and to convert it to a unicode # string encoded by utf - 8. # Hints: # Use unicode() function to convert. def do(sentence): # print ord('as') unicodeString = unicode(sentence, "utf-8") print unicodeString def main(): sentence = 'this is a test' do(sentence) if __name__ == '__main__': main() # main(raw_input('Enter String :'))
047481cff2b6856af271cecf82fbeb71e1e68ad3
Ashok-Mishra/python-samples
/python exercises/dek_program071.py
571
4.40625
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program071: # Please write a program which accepts basic mathematic expression from # console and print the evaluation result. # Example: # If the following string is given as input to the program: # 35+3 # Then, the output of the program should be: # 38 # Hints: # Use eval() to evaluate an expression. def main(expression): print eval(expression) if __name__ == '__main__': expression = raw_input("Enter expression: ") main(expression) # main('34+5')
a3a5dc9698f22d9a7f8b66735894af658fffbc05
Ashok-Mishra/python-samples
/python exercises/dek_program011.py
1,214
4.03125
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program# : Name # => # Write a program which accepts a sequence of comma separated # 4 digit binary numbers as its input and then check whether # they are divisible by 5 or not. The numbers that are divisible # by 5 are to be printed in a comma separated sequence. # Example: # a='0100,0011,1010,1001' # Then the output should be: # 1010 # Notes: Assume the data is input by console. # Hints: # In case of input data being supplied to the question, # it should be assumed to be a console input. def start(binString): binString = binString.split(',') print binString newa = [] for x in binString: if int(x, 2) % 5 == 0: newa.append(x) return newa def main(): # start from here print "sample input\n", '0100,0011,1010,1011,1110,1001' # binString = '0100,0011,1010,1011,1110,1001' #*************** comment the below line to TEST binString = raw_input('Enter a Binary Number String: ') try: print start(binString) except: print 'Invalid Format',\ '0100,0011,1010,1011,1110,1001', '(Sample Format)' if __name__ == '__main__': main() # checked
d502383264e8d290050e3b1384916f7888c07677
Ashok-Mishra/python-samples
/python exercises/dek_program045.py
694
4.375
4
# !/user/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # Write a program which can filter even numbers in a list by using filter # function. The list is: # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. # Hints: # Use filter() to filter some elements in a list. # Use lambda to define anonymous functions. def do(start_number, end_number): list = [value for value in range(start_number, end_number + 1)] print 'list :', list result = filter(lambda number: number % 2 == 0, list) print 'Even Number From list :', result def main(): do(int(raw_input('Enter Starting Number :')), int(raw_input('Enter Ending Number :'))) if __name__ == '__main__': main()
9ffade93e2d1f84246df872596c06ba4fd3262cd
Ashok-Mishra/python-samples
/python exercises/dek_program005.py
905
4.0625
4
#!/user/bin/python # -*- coding: utf-8 -*- # Author : (DEK) Devendra Kavthekar # program005 : Name # => # Define a class which has at least two methods: # getString: to get a string from console input # printString: to print the string in upper case. # Also please include simple test function to test the class methods. # Hints: # Use __init__ method to construct some parameters class cString: def __init__(self): print 'inside __init__(self):' self.x = 'Default String' def getString(self): # input from console self.x = raw_input('Enter String : ') return self.x def printString(self): print 'in upper: ', self.x.upper() return self.x.upper() def test(): ac = cString() ac.getString() ac.printString() print 'TEST Class Methods' def main(): # start from here test() if __name__ == '__main__': main() # checked