blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d83d3c82b0c0820ad995c56b1c333ba68333cabb
ARWA-ALraddadi/python-tutorial-for-beginners
/01-Workshop/Workshop-Solutions/pythagorean_theorem.py
3,456
4.78125
5
# Pythagorean Theorem # # THE PROBLEM # # Recall from high-school geometry lessons Pythagoras' famous # theorem about right-angled triangles: # # "The square of the hypotenuse equals the sum of the squares # of the other two sides" # # Write a script to calculate and print the length of a right-angled # triangle's hypotenuse given the lengths of the other two sides. # For instance, given the two lengths below the answer should # equal 5. # # COMMENT: This is not especially hard, but we're not going to # give you any hints. In particular, you will need to find out # for yourself how to express the required mathematical formula # in Python. It's important that you know where to find such # information by yourself because your Workshop Facilitators will # not always be on hand to assist you. side_a = 3 side_b = 4 # A (LONG-WINDED) SOLUTION # # 1. In natural language the expression we need to evaluate is # "the square root of 'side_a' squared plus 'side_b' squared". # # 2. Dissecting this statement we can see that we need three # mathematical operators to solve the problem, addition, # squaring and taking a square root. The challenge then becomes # how to express these in Python. # # a. We have already used Python's addition operator "+" many # times, so we probably don't need to investigate this # any further. However, we can find out more about it by # consulting Section 5.6, "Binary Arithmetic Operations" in # the "Python Language Reference Manual" which defines core # features of the Python scripting language. # # b. One way to find the square of a number is to multiply it # by itself, e.g., "side_a * side_a", but a way that better # describes the intention of the expression is to raise the # value to the power 2. A search through the "Python Language # Reference Manual" produces a description of Python's # in-built power operator "**" in Section 5.4, "The Power # Operator". # # c. Finally we need to find a square root. There is no built-in # operator to do this in Python, so we turn to the "Python # Library Reference" which describes a vast range of extra # Python functions. A search in this document reveals a # square root function "sqrt(x)" in Section 9.2.2, "Power # and Logarithmic Functions". This function takes a numeric # argument "x" and returns its square root, so obviously meets # our needs. # # d. Putting all this together means that the Python expression # we want is "sqrt((side_a ** 2) + (side_b ** 2))". # # 3. However, if we attempt to evaluate this expression in IDLE we # get an error message, "NameError: name 'sqrt' is not defined". # This is because the square root function is not in-built, so # we need to import it before we use it. According to Section 9.2 # of the "Python Library Reference" this function is part of the # "math" module. There are a few different ways to refer to # library functions from external modules in Python, but the # most elegant is to declare "from MODULE import FUNCTION". As # explained in Section 6.12 of the "Python Language Reference", # this makes the named function directly available to the # current program. # # 4. After all that effort our final solution is the following two # lines of code! from math import sqrt print(sqrt((side_a ** 2) + (side_b ** 2)))
59f5244a8ce3b1330fb10b90a8c6ab153620e728
qwerty282/class
/OddEvenSeparator.py
312
3.515625
4
class OddEvenSeparator(): def __init__(self): self.lst = [] def add_number(self, number): self.lst.append(number) def even(self): return list(filter(lambda x: x % 2 == 0, self.lst)) def odd(self): return list(filter(lambda x: x % 2 != 0, self.lst))
b1ed6cbd5e71d87171fb2da4d00e222d87a02ec2
gregunz/MachineLearning2017
/project01/src/gradients.py
502
3.640625
4
# -*- coding: utf-8 -*- """ Gradients """ from functions import sigmoid def compute_gradient(y, tx, w, fn="mse"): """Compute the (stochastic) gradient given a cost function.""" if fn.lower() == "mse": N = len(y) e = y - (tx @ w) grad = - (tx.T @ e) / N return grad, e if fn.lower() == "sig": pred = sigmoid(tx @ w) grad = tx.T @ (pred - y) return grad raise NameError("Not such fn exists \"" + fn + "\"")
9d9a5ffeec51084045fce1b2fba4b69e69137262
reema-eilouti/python-problems
/CA04/problem8.py
315
4.3125
4
# CA04 Problem8 # Write a program which prints the absolute value of any given number n without using the abs() function . number = int(input("Please enter a number: ")) if number > 0 : print(f"The absolute value of {number} is {number}") else : print(f"The absolute value of {number} is {-1 * number}")
839279706fcda6b1800162c03b12e07a7462b7a0
breno-abreu/TrabalhosRedes
/Trabalho 1/servidor_web.py
7,349
3.671875
4
# UTFPR - 2021/1 # Bacharelado em Sistemas de Informação # Redes de Computadores # Trabalho 1 - Servidor Web Multithread # Autor: Breno Moura de Abreu # RA: 1561286 # Python 3 import threading import socket import os def main(): """ Função principal que inicia a execução do servidor """ print('[INICIALIZANDO SERVIDOR]') try: # Tenta executar o servidor print('[RODANDO SERVIDOR]') executar_servidor() except KeyboardInterrupt: # Finaliza a execução do programa caso ^C seja pressionado no Terminal print('\n[DESLIGANDO SERVIDOR]') except Exception as exc: print('[ERRO] ' + str(exc)) def executar_servidor(): """ Função que cria o socket do servidor e executa o loop principal """ # Cria o socket do servidor, sendo AF_INET relativo ao IPv4 # E SOCK_STREAM relativo a TCP server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Permite que a mesma porta possa ser usada novamente após a execução # do programa. Caso essa linha não exista, deve-se trocar a porta a cada # vez que o programa é executado server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Descobre o IPv4 da máquina hostname = socket.gethostname() ip_servidor = socket.gethostbyname(hostname + ".local") # Associa o socket com um IP e uma porta server_socket.bind((ip_servidor, 5000)) print('IPv4 do Servidor: ' + ip_servidor) # Servidor passa a ouvir requisições de clientes server_socket.listen() while True: # Servidor espera a requisição de um cliente # Socket do cliente que fez uma requisição é criado # A variável 'addr' guarda o IP e porta do cliente client_socket, addr = server_socket.accept() # Objeto da classe HttpRequest é criado recebendo o socket do cliente # A requisição do cliente então é tratada com os métodos da classe http_request = HttpRequest(client_socket, addr) # Thread é criada para tratar a requisição de cada cliente paralelamente thread = threading.Thread(target=http_request.run) # Desliga uma thread caso a thread principal seja desligada thread.daemon = True # Inicia o tratamente da requisição do cliente thread.start() # Fecha o socket do servidor server_socket.close() class HttpRequest: """ Classe contendo os métodos para tratar uma requisição de um cliente e enviar os dados necessários """ def __init__(self, client_socket, addr): """ Armazena o socket de um cliente e seu endereço """ self.client_socket = client_socket self.addr = addr # Variáveis auxiliares para indicar o fim de uma linha self.CRLF = '\r\n' self.CRLF2 = '\r\n\r\n' def run(self): """ Tenta tratar a requisição de um cliente """ try: self.process_request() except Exception as exc: print('[ERRO] ' + str(exc)) def process_request(self): """ Trata a requisição de um cliente e retorna os dados necessários """ # Recebe a mensagem de requisição de um cliente request_msg = self.client_socket.recv(4096).decode() # Divide a mensagem em partes request_vec = request_msg.split("\n") nome_arquivo = '' print('IP cliente: ' + self.addr[0]) print('Porta cliente: ' + str(self.addr[1])) if len(request_vec) > 0: # Descobre o nome do arquivo requerido pelo cliente print('Requisição: ' + request_vec[0] + '\n') nome_arquivo = request_vec[0].split(' ') nome_arquivo = '.' + nome_arquivo[1] if self.arquivo_existe(nome_arquivo): # Caso o arquivo exista, envia o arquivo para o cliente # Adiciona a linha de status texto = self.status_line(200) + self.CRLF # Adiciona a linha contendo o tipo de conteúdo a ser enviado texto += 'Content-Type: ' + self.content_type_line(nome_arquivo) + self.CRLF # Adiciona o tamanho do arquivo a ser enviado texto += 'Content-Length: ' + str(os.path.getsize(nome_arquivo)) + self.CRLF2 # Envia o cabeçalho para o cliente self.client_socket.sendall(texto.encode()) # Recebe o arquivo requerido como byte stream arquivo = self.ler_arquivo(nome_arquivo) # Envia o arquivo para o cliente self.client_socket.sendall(arquivo) else: # Caso o arquivo não exista, devolve uma página com o erro 404 Not Found texto = self.status_line(404) + self.CRLF texto += "Content-Type: text/html; charset=utf-8" + self.CRLF2 texto += "<html><head><title>404 Not Found</title></head><body>" texto += "<h1>404 Not Found</h1><h2>Arquivo Não Encontrado</h2></body></html>" self.client_socket.sendall(texto.encode()) # Desliga a conexão do socket do cliente self.client_socket.shutdown(socket.SHUT_WR) # Fecha o socket do cliente self.client_socket.close() def status_line(self, status): """ Retorna a linha de texto adequada para diferentes status de uma página """ if status == 200: return "HTTP/1.0 200 OK" elif status == 404: return "HTTP/1.0 404 Not Found" def content_type_line(self, nome_arquivo): """ Identifica o tipo de conteúdo de um arquivo e retorna seu tipo MIME """ if nome_arquivo.endswith('.htm') or nome_arquivo.endswith('.html'): return 'text/html; charset=utf-8' elif nome_arquivo.endswith('.txt'): return 'text/plain' elif nome_arquivo.endswith('.jpg'): return 'image/jpeg' elif nome_arquivo.endswith('.png'): return 'image/png' elif nome_arquivo.endswith('.gif'): return 'image/gif' elif nome_arquivo.endswith('.ogg'): return 'audio/ogg' elif nome_arquivo.endswith('.webm'): return 'audio/webm' elif nome_arquivo.endswith('.wav'): return 'video/wav' elif nome_arquivo.endswith('.mpeg'): return 'audio/mpeg' elif nome_arquivo.endswith('.pdf'): return 'application/pdf' return 'application/octet-stream' def arquivo_existe(self, nome_arquivo): """ Verifica se um arquivo existe ou não """ try: if nome_arquivo != './': arquivo = open(nome_arquivo) arquivo.close() return True except IOError as exc: print('[ERRO] ' + str(exc)) return False def ler_arquivo(self, nome_arquivo): """ Abre um arquivo e retorna seu conteúdo como byte stream """ if(nome_arquivo != './favicon.ico'): if nome_arquivo == './': arquivo = open('./index.html', 'rb') else: arquivo = open(nome_arquivo, 'rb') conteudo = arquivo.read() arquivo.close() return conteudo return '' if __name__=="__main__": main()
111c1c28723b552c7c881d2c692ecc13de614bbc
hexnut/bibleresearch
/bin/primegen.py
633
3.84375
4
#!/usr/bin/python3 import sys primeList=[]; def is_prime(p): if (p <= 0 or p == 1 or p == 4): return False; prime = True; for j in range(2, int(p/2)): if p % j == 0: prime=False; continue; return prime; # Main loop to find primes for line in sys.stdin: i = int(line) if is_prime(i) == True: primeList.append(i) # Print a formatted list for i in range(0, len(primeList)): p = primeList[i] print(str(i+1) + ": " + str(p), end='') if (p+6 in primeList): #print "s(" + str(p) + "," + str(p+6) + ")" print("(s)") else: print()
a7893d7c18c9238eab7823cf9e8d2e0f0488c74a
bjb421361141/learnPython
/exception/exception.py
1,592
3.859375
4
""" 异常捕获: 当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行, 而是直接跳转至错误处理代码,即except语句块,执行完except后,如果有finally语句块,则执行finally语句块 调试: 1、使用assert 单元测试:具体参考TestMyORM.py文件 文档型测试:在类中编写测试代码 """ try: print('try...') r = 10 / int('a') print('result:', r) except ValueError as e: print('ValueError:', e) except ZeroDivisionError as e: print('ZeroDivisionError:', e) finally: print('finally...') print('END') def foo(s): n = int(s) # assert必须为ture 不然断言失败输出错误信息 assert n != 0, 'n is zero!' return 10 / n """ 文档类测试 放于类内部,只执行第一个注释框中的内容 测试代码 >>> 代码行 输出预期 使用 ...省略输出 """ class Dict(dict): """ >>> d2 = Dict(a=1, b=2, c='3') >>> d2['empty'] Traceback (most recent call last): ... KeyError: 'empty' """ def __init__(self, **kw): super(Dict, self).__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"'Dict' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value if __name__ == '__main__': import doctest doctest.testmod()
e47f22de5745a09433eb9423ebc14e003f38022b
WouterVdd/Learning_Python
/Numbers-Binary_to_Decimal_and_Back_Converter/main.py
859
4.4375
4
# Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or # a binary number to its decimal equivalent. choice = input("Do you want to convert a binary or decimal number? (b/d) ") number = 0 converted = 0 if choice == "b": try: number = int(float(input("Give in a binary number: "))) converted = int(str(number), 2) except ValueError as e: print("Oops! That was no valid number. Try again...") exit(-1) elif choice == "d": try: number = int(float(input("Give in a decimal number: "))) converted = bin(number) except ValueError as e: print("Oops! That was no valid number. Try again...") exit(-1) else: print("Error: %s is not a valid choice!" % choice) exit(-1) print("%s converted is: %s" % (str(number), str(converted)))
d7e11528ac4da80b93ec4a00e386eb4f7c1e1765
ZJmitch/Booleans
/Problem 5 task2.py
237
3.546875
4
#Justin Mitchell #3/7/2021 #Problem 5 task2 def task2(): a1 = (input( "Do you need a pan? ")) a2 = (input( "Do you need groceries ")) a3 = (input( "Do you have a small debuff? ")) print(a1, a2, a3,) task2()
c336cb812d7b9af88dfeb646d4d32f87e9118e21
poetchess/pythonrunner
/data_structures/dictionary_set/StrKeyDict0.py
2,010
3.765625
4
# A better way to create a user-defined mapping type is to subclass # collections.UserDict instead of dict. Here, the point is to show that # '__missing__' is supported by the built-in dict.__getitem__ method. # '__missing__' method is not defined in the base 'dict' class, but 'dict' is # aware of it. If we subclass 'dict' and provide a '__missing__' method, the # standard dict.__getitem__ will call it whenever a key is not found, instead # of raising KeyError. class StrKeyDict0(dict): def __missing__(self, key): if isinstance(key, str): # Check is needed to avoid potencial infinite recursion. raise KeyError('key {} is missing'.format(key)) return self[str(key)] # The 'get' method delegates to __getitem__ by using the self[key] # notation; that gives the opportunity for our __missing_ to act. def get(self, key, default=None): try: return self[key] except KeyError: # If a KeyError was raised, __missing_ already failed, so we return # the 'default'. return default # This method is needed for consistent behavior. def __contains__(self, key): # Search for unmodified key, then for a str built from the key. # A subtle detail in the implementation: we do not check for the key # in the usual Pythonic way, k in mydict, because that would # recursively call __contains__. We avoid this by explicitly looking # up the key in self.keys(). return key in self.keys() or str(key) in self.keys() if __name__ == '__main__': d = StrKeyDict0([('2', 'two'), ('4', 'four')]) print('Tests using `d[key]` notation:') print(d['2']) print(d[4]) try: print(d[1]) except KeyError as e: print(e) print('Tests using `d.get(key)` notation:') print(d.get('2')) print(d.get(4)) print(d.get(1, 'N/A')) print('Tests the `in` operation:') print(2 in d) print(1 in d)
808e4c695d003441d7eeee830a2f42b584e41da1
kien6034/CSFoundation
/1_Array/9_string_rotation/main.py
521
4.375
4
#assume that you have a method isSubstring which checks one word is a substring of another #given 2 strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call isSubstring str1 = input("enter string 1: ") str2 = input("enter string 2: ") def isRotation(str1, str2): if len(str1) != len(str2): return False str3 = str2 + str2 if str1 in str3: return True else: return False if isRotation(str1, str2): print("YEs") else: print("No")
3306a98074c070db85e8e65680bc56303e6c52f0
gurjot1996/FULL-STACK-NAODEGREE-2
/databases office/databases.py
937
4.15625
4
from collections import namedtuple import sqlite3 Link=namedtuple('List',['id','name','age','school_name','marks']) list=[ Link(1,'gurjot',23,'ster',98), Link(2,'jot',3,'sero',78), Link(3,'gu',2,'ste',90) ] #creating databse connection db=sqlite3.connect(':memory:') #creating table in named gurjot db.execute('create table gurjot '+'(id integer,name text,age integer,school_name text,marks integer)') #inserting values from a list into a database table for j in list: db.execute('insert into gurjot values(?,?,?,?,?)',j) #executing select query on table named gurjot c=db.execute('select * from gurjot') #c is a cursor that points to the rows entry of gurjot table for k in c: #we are creating a object of type Link and then using dot operator we are accessing various attributes link=Link(*k) print link.name+' has obtained '+str(link.marks)+' and his school is '+link.school_name+'\n'
c1f949e09645a6b6e2e944a4209348a249463e65
skb30/UCSC-Python2
/import_tests/moduleA.py
635
3.578125
4
import glob class A (): def __init__(self, arg1, arg2="kenneth", arg3="barth"): self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 print("inside A constructor") def print_args(self): print("Name: {} {} {}".format(self.arg1, self.arg2, self.arg3)) return glob.glob("*.*") # # class B(A): # def __init__(self, arg1): # self.arg1 = arg1 # print("inside B arg1 = {}".format(self.arg1)) # self.print_args() # # a = A('scott','James', 'Barth') # b = B('scott') # for item in a.print_args(): # print(item) # # b = ["1" + i for i in a.print_args()]
0cfc4037dd3bef8d19e63b7b7e39225b8006eeb1
saranya-1621/alph.py
/alphabet.py
210
4.3125
4
ch=input("please enter your own character:") if((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')): print("the given character",ch,"is a Alphabet") else: print("the given character",ch,"is Not alphabet")
c3cc8256eea981f51d943e650b2cf13feb6d82bb
Behroz-Arshad/Assignment
/Question no 20.py
805
4.03125
4
#Question no 20 ''' Represent a small bilingual lexicon as a Python dictionary in the following fashion { "merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år" } and use it to translate your Christmas cards from English into Swedish. That is, write a function `translate()` that takes a list of English words and returns a list of Swedish words. ''' #Code def translate(s): dic={ "merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år" } a=(s.split(" ")) is_valid=True l=[] for i in a: if i in dic: l.append(dic[i]) else: is_valid=False print(i,"is not valid word") break if is_valid==True: for lan in l: print(lan,end=" ")
793beeee296927573942c6a91ccb7430d50f6223
DEVARUN98/pythonprog
/oops/inheritance/inhert7.py
569
3.734375
4
class Person: def set(self,name,age): self.name=name self.age=age print(self.name,self.age) class Child(Person): def setv(self,clas,age): self.clas=clas self.age=age print(self.clas,self.age) class Parent(Person): def setp(self,name,adrs): self.name=name self.adrs=adrs print(self.name,self.adrs) class Student(Child): def sets(self,name,std): self.name=name self.std=std print(self.name,self.std) st=Student() st.sets("bn",7) st.set("lossd",8) st.setv(4,9)
e4fe27af8fc48750022a93f6287869408de27dd0
quirk0o/nlp-2-clustering
/lcs.py
829
3.609375
4
import numpy as np def longest_common_substring(word_a, word_b): len_a = len(word_a) len_b = len(word_b) if min(len_a, len_b) == 0: return 0 lcs = np.zeros([len_a + 1, len_b + 1]) max_len = 0 for i, a in enumerate(word_a, start=1): for j, b in enumerate(word_b, start=1): if a == b: lcs[i][j] = lcs[i - 1][j - 1] + 1 max_len = max(max_len, lcs[i][j]) else: lcs[i][j] = 0 return int(max_len) def lcs_distance(word_a, word_b): return 1 - float(longest_common_substring(word_a, word_b)) / max(len(word_a), len(word_b)) if __name__ == '__main__': print longest_common_substring('kot', 'kot') print longest_common_substring('kot', 'kod') print longest_common_substring('telefon', 'telegraf')
8ad205c228e2ac3c0ec393c10efe03c29928203c
pyaephyokyaw15/PythonFreeCourse
/chapter5/list_func2.py
229
3.65625
4
lst =[10,-2,40,100,12] lst.reverse() print ("Reverse ", lst) lst.sort() print ("lst ", lst) lst.sort(reverse=True) print ("lst ", lst) lst_two = lst[:] print(" Id ",id(lst)) print(" Id ",id(lst_two)) print("list two ",lst_two)
2a4994ba962dedd6300f9197913ede9985da7f67
MichealGarcia/code
/py3hardway/ex15.py
640
4.25
4
# Import argv from the sys module from sys import argv # unpack te argument variable for running the script, # Create parameters to run script script, filename = argv # Create a variable that will open the txt file. txt = open(filename) # print the name of the file we call, then print the text inside the opened # txt file using the read method print(f"Here's your file {filename}:") print(txt.read()) # Use the input method to get the name of the file and open then read it print("Type the filename again:") file_again = input("> ") txt_again = open(file_again) print(txt_again.read()) txt = txt.close() txt_again = txt_again.close()
d90bad3b1844a46cc3bef2668a5d3e5bda569eb9
dmgolembiowski/CookbookDMG
/ThatActuallyWorked/dictArgs.py
377
3.734375
4
#!/usr/bin/env python3 def values(x): for keys in x: print('x['+str(keys)+'] =', x[keys]) aDictionary = { 'first':'is the worst', 'second':'is the best', 'third':'is the one with the treasure chest'} values(aDictionary) """ $ ./dictArgs.py x[first] = is the worst x[second] = is the best x[third] = is the one with the treasure chest """
e7f23659641159c2e39edc3343e69c6e34501712
amogchandrashekar/Leetcode
/Medium/Jump Game/Jump Game_greedy.py
348
3.734375
4
from typing import List class Solution: def canJump(self, nums: List[int]) -> bool: last_pos = len(nums) - 1 for index in range(len(nums) - 1, -1, -1): last_pos = max(last_pos, index + nums[index]) return last_pos == 0 if __name__ == "__main__": nums = [3,2,1,0,4] print(Solution().canJump(nums))
876189545604cfa50768ab4dff73e4a462df27a9
HunterDuan/git
/basis/crawl/Login.py
702
3.515625
4
#用户登陆,user.txt存在已有账户信息 myfile = open('user.txt', 'r') logintimes = 0 islogin = 1 while True: if islogin == 1: if logintimes == 3: print('登陆超过次数,再见') break else: print('这是你第%d次登陆,你还剩余%d次机会'%(logintimes + 1 , 3 - logintimes)) account = input('请输入你的账户:') password = input('请输入你的密码:') myfile.seek(0,0) for buf in myfile: account_buf = buf.split(':')[0] password_buf = buf.split(':')[1][:-1] if account_buf == account and password == password_buf: print('登录成功:', account_buf) islogin = 0 break logintimes += 1 continue else: break
04fd763f99a16e2af7e37dd2c71b267846f2b742
sfeng77/myleetcode
/maximumSubarray.py
860
4.0625
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. """ class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return [] currSum = 0 minSum = 0 maxSum = 0 maxId = 0 minId = 0 for i in range(0,len(nums)): currSum += nums[i] if maxSum <= currSum: maxSum = currSum maxId = i if minSum > currSum: minSum = currSum minId = i print "max:", maxSum, maxId print "min:", minSum, minId return nums[minId:maxId+1]
404286a4dcba349669d7ff73481ab88774f6f84b
Raxev/research_recurrences
/api/utils.py
5,108
3.9375
4
from typing import Tuple, Iterable, TYPE_CHECKING from pendulum import date, period if TYPE_CHECKING: from pendulum import Date BREAK_NEEDED_PER_X_MINUTES = 90 MINUTES_PER_BREAK = 10 REQUIRED_MINUTES_PER_CREDIT_HOUR = 800 def class_period_weekdays(start_date: 'Date', end_date: 'Date', off_days: Iterable['Date']) -> Tuple[int, ...]: """ Calculates the number of days each week day occurs in a given period aside from holidays :param start_date: The inclusive start date of the class period. :param end_date: The inclusive end date of the class period. :param off_days: The dates of all holidays in the class period. May contain holidays outside of the class period. :return: A tuple where the index represents the weekday and the value represents the number of class days for this weekday in the given class period. Monday is at index 0 and Sunday is at 6. >>> mlk = date(2020, 1, 20) >>> spring_break = period(date(2020, 3, 9), date(2020, 3, 15)) >>> spring_holidays = period(date(2020, 4, 10), date(2020, 4, 12)) >>> OFF_DAYS = {mlk, *spring_break, *spring_holidays} >>> class_period_weekdays( ... start_date=date(2020, 1, 13), ... end_date=date(2020, 5, 12), ... off_days=OFF_DAYS) (16, 17, 16, 16, 15, 15, 15) """ off_days = set(off_days) class_weekdays = [0] * 7 for day in period(start_date, end_date): if day not in off_days: class_weekdays[day.weekday()] += 1 return tuple(class_weekdays) def class_date_range(start_date: 'Date', end_date: 'Date', off_days: Iterable['Date'], class_weekdays: Tuple[bool, bool, bool, bool, bool, bool, bool]) -> Tuple['Date', 'Date']: """ Calculates the start and end dates for a class. :param start_date: The inclusive start date of the class period. :param end_date: The inclusive end date of the class period. :param off_days: The dates of all holidays in the class period. May contain holidays outside of the class period. :param class_weekdays: What days will the class meet? Monday is at index 0 and Sunday is at 6. :return: The start and end date for a class that meets the given weekdays in the period. >>> mlk = date(2020, 1, 20) >>> spring_break = period(date(2020, 3, 9), date(2020, 3, 15)) >>> spring_holidays = period(date(2020, 4, 10), date(2020, 4, 12)) >>> off_days = {mlk, *spring_break, *spring_holidays} >>> start_and_end = class_date_range( ... start_date=date(2020, 1, 13), ... end_date=date(2020, 5, 12), ... off_days=off_days, ... class_weekdays=(True, False, True, False, False, False, False)) >>> print(start_and_end) (Date(2020, 1, 13), Date(2020, 5, 11)) """ class_start_date = None class_end_date = None off_days = set(off_days) for day in period(start_date, end_date): if day in off_days: continue if class_weekdays[day.weekday()]: class_start_date = day break for day in reversed([*period(start_date, end_date)]): if day in off_days: continue if class_weekdays[day.weekday()]: class_end_date = day break return class_start_date, class_end_date def calculate_cod( class_weekdays: Tuple[bool, bool, bool, bool, bool, bool, bool], class_credit_hours: int, class_period_weekdays: Tuple[int, int, int, int, int, int, int]) -> Tuple[float, float]: """ :param class_weekdays: What days will the class meet? Monday is at index 0 and Sunday is at 6. :param class_credit_hours: How many credit hours does the class have? :param class_period_weekdays: A tuple where the index represents the weekday and the value represents the number of class days for this weekday in the given class period. Monday is at index 0 and Sunday is at 6. :return: The minimum number of minutes each class needs to last. It's recommended to round up to a multiple of 5. >>> calculate_cod( ... class_weekdays=(True, False, True, False, False, False, False), ... class_credit_hours=3, ... class_period_weekdays=(16, 17, 16, 16, 15, 15, 15)) 75.0 """ if not any(class_weekdays): raise ValueError("At least one week day must be checked.") # Remember that booleans (x) are worth 0 or 1. So we're adding up all the days where # the class will meet. class_weekday_count = sum(x * y for x, y in zip(class_weekdays, class_period_weekdays)) class_needed_minutes = class_credit_hours * REQUIRED_MINUTES_PER_CREDIT_HOUR minutes_per_class_minus_breaks = class_needed_minutes / class_weekday_count needed_breaks = minutes_per_class_minus_breaks // BREAK_NEEDED_PER_X_MINUTES minutes_per_class = minutes_per_class_minus_breaks + needed_breaks * MINUTES_PER_BREAK return minutes_per_class, needed_breaks
cc1367ecb72e85606b369a99d12defea576bc5d9
mjh09/python-code-practice
/alternatingSums.py
287
3.59375
4
def alternatingSums(a): switch = True team_1 = [] team_2 = [] for weight in a: if switch: team_1.append(weight) switch = False else: team_2.append(weight) switch = True return [sum(team_1), sum(team_2)]
a3eea486a2dc4c1cc6b004eb5da68c57f102a962
dragove/storode
/example/src/myutil/get_student_number.py
407
3.53125
4
# @req 43b6 def get_student_number(fname): f = open(fname, encoding='utf8') lines = f.readlines() f.close() numbers = [] for line in lines: line = line.strip() line = line.replace('\t', ' ') lst = line.split(' ') for x in lst: if len(x) == 12 and x[0] == '2': # @req 43b6:BACK3 numbers.append(x) return list(set(numbers))
c8c7521c9c534b7cc63c869ea48c7c4fa7869bdc
aaronweise1/ccsf_advanced_python_231
/homework/homework4/peer_review_hw4/vn.py
4,084
4.03125
4
############################################################# # CS231 Lab 4 # # Use textwrap, yield and generator --- # # -Write a program to lazily rewrap text from the filename # # passed so it fits an 80 column per line without breaking # # any words. Use generator yields the next lines of text # # # # Student Name: James Lin JamesLin288@gmail.com # # Instructor Name: Aaron Brick ABrick@ccsf.edu # ############################################################# import os import textwrap import sys import select def file_reader(): if (len(sys.argv) > 1): fileName = open(sys.argv[1], 'r').readlines() fileName = (' '.join(fileName)) # fileSize = int(os.path.getsize(sys.argv[0]))/80 //calculates the size and know how many lines else: dirList = os.listdir("./") inputName = input("Please enter the name of the text file to be used: ") fileName = open(inputName, 'r').readlines() fileName = (' '.join(fileName)) # fileSize = int(os.path.getsize(fileName))/80 // not able to get file size back to the main wrapper = textwrap.TextWrapper(width=80) word_list = wrapper.wrap(text=fileName) # fileWrap = textwrap.fill(fileName, width=80) // fill- will create one single long line for line in word_list: yield line lineGenerator = file_reader() print (next(lineGenerator)) print (next(lineGenerator)) #print(sys.argv[0]) #print(int(os.path.getsize(sys.argv[0]))/80) #print(sys.argv[1]) #print(int(os.path.getsize(sys.argv[1])/80)) #print(fileSize) print ("Following is the wrapped file printed line by line: ") for i in range (5): print (next(lineGenerator)) ############# Following is the sample output ############## #[jlin199@hills ~]$ python3 CS231Lab4WrapYield.py wraptest.txt #This function wraps the input paragraph such that each line in the paragraph #is at most width characters long. The wrap method returns a list of output #Following is the wrapped file printed line by line: #lines. The returned list is empty if the wrapped output has no content. This #function wraps the input paragraph such that each line in the paragraph is at #most width characters long. The wrap method returns a list of output lines. The #returned list is empty if the wrapped output has no content. This function #wraps the input paragraph such that each line in the paragraph is at most width #[jlin199@hills ~]$ more wraptest.txt <<=== original test file #This function wraps the input paragraph such that each line #in the paragraph is at most width characters long. The wrap method #returns a list of output lines. The returned list #is empty if the wrapped output has no content. #This function wraps the input paragraph such that each line #in the paragraph is at most width characters long. The wrap method #returns a list of output lines. The returned list #is empty if the wrapped output has no content. #This function wraps the input paragraph such that each line #in the paragraph is at most width characters long. The wrap method #returns a list of output lines. The returned list #is empty if the wrapped output has no content. #[jlin199@hills ~]$ python3 CS231Lab4WrapYield.py #Please enter the name of the text file to be used: wraptest.txt #This function wraps the input paragraph such that each line in the paragraph #is at most width characters long. The wrap method returns a list of output #Following is the wrapped file printed line by line: #lines. The returned list is empty if the wrapped output has no content. This #function wraps the input paragraph such that each line in the paragraph is at #most width characters long. The wrap method returns a list of output lines. The #returned list is empty if the wrapped output has no content. This function #wraps the input paragraph such that each line in the paragraph is at most width #[jlin199@hills ~]$ ########## End of sample output ###################
ce227bacc58454476eec738a22e906a480e6d360
arunima14/MLH-LHD-Learn-2022
/Day 1/text based adventure game/main.py
3,433
4
4
class Player: def __init__(self): self.name = "" self.inventory = [] def set_name(self, name): self.name = name def add_inventory(self, item): self.inventory += items class Room: def __init__(self): self.name = "" self.description = "" self.items = [] def set_name(self, name): self.name = name def add_items(self, items): self.items += items def remove_item(self, item): self.items.remove(item) def set_description(self, description): self.description = description # Print title screen print ("+---------------------------------------+") print ("| Text Adventure Game |") print ("+---------------------------------------+") print () # Build player player = Player() input = input("Please enter your name: ") player.set_name(input) print ("Hello, " + player.name + ".\n") # Build rooms, room items, and map map_width, map_height = 2, 2 rooms = [[Room() for x in range(map_width)] for y in range(map_height)] rooms[0][0].set_name("Bedroom") rooms[0][0].set_description("You are in your bedroom.") rooms[0][0].add_items(["wallet", "keys"]) rooms[0][1].set_name("Bathroom") rooms[0][1].set_description("You are in the bathroom.") rooms[0][1].add_items(["toilet paper", "magazine"]) rooms[1][0].set_name("Kitchen") rooms[1][0].set_description("You are in the kitchen.") rooms[1][0].add_items(["towel", "chainsaw"]) rooms[1][1].set_name("Garage") rooms[1][1].set_description("You are in the garage.") rooms[1][1].add_items(["car", "gasoline"]) def move(input, rooms, x, y): if input == "n": if y > 0: y -= 1 else: print ("You can't go that way.") elif input == "s": if y < map_height - 1: y += 1 else: print ("You can't go that way.") elif input == "e": if x > 0: x -= 1 else: print ("You can't go that way.") elif input == "w": if x < map_width - 1: x += 1 else: print ("You can't go that way.") return x, y def get(inventory, item, room): if item in room.items: inventory.append(item) room.remove_item(item) print ("You pick up the " + item + ".") else: print ("You don't see that here.") x, y = 0, 0 print (rooms[x][y].name + ": " + rooms[x][y].description) print ("You see: " + str(rooms[x][y].items)) playing = True while (playing): input_move = input("> ") if (input == "n" or input == "s" or input == "e" or input == "w"): x, y = move(input_move, rooms, x, y) print (rooms[x][y].name + ": " + rooms[x][y].description) print ("You see: " + str(rooms[x][y].items)) elif input_move == "look": print (rooms[x][y].name + ": " + rooms[x][y].description) print ("You see: " + str(rooms[x][y].items)) elif input_move[:4] == "get ": item = input[4:] get(player.inventory, item, rooms[x][y]) elif input_move == "i": print ("Inventory: " + str(player.inventory)) elif input_move == "help": print ("Type n/e/s/w to move your player") print ("Type i to view your inventory") print ("Type quit to quit the game") print ("Other commands: get, look, open, close, and more.") elif input_move == "quit": playing = False else: print ("I don't understand.")
80e312213020d00289d3e3157549e0ee87ada9f3
UCD-pbio-rclub/Pithon_MinYao.J
/hw4-3_interactive_palindrome_ignore_capital.py
535
4.25
4
def is_palindrome(): while True: print('Welcome to is_palindrome.') user_input = input('Please enter a potential palindome: ') user_input = user_input.lower() if(user_input==user_input[::-1]): print(user_input.capitalize(), "is a palindrome") else: print(user_input.capitalize(), "isn't a palindrome") user_input = input('Do another search? [y/n]: ').lower() user_input = user_input or 'y' if user_input == 'n': break
f8e266800de232823928d6b0e2fa24a52d8158d0
JarrenTay/LeetCodeSolutions
/LeetCode21.py
1,496
4.03125
4
# ---------------------------------------------------------------------------- # Leetcode problem title: Merging Two Sorted Lists # Leetcode problem number: 21 # Leetcode problem difficulty: Easy # Solution by: Jarren Tay # Date: 9/24/2019 # Time to solve: 00:11:15 # ---------------------------------------------------------------------------- # Comments: Easy problem. Failed the first time because of an oversight on a # possible test case. Also almost missed a submission from forgetting a mental # note # ---------------------------------------------------------------------------- # Takeaway: Take notes, read them, and think of edge cases # ---------------------------------------------------------------------------- # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: node1 = l1 node2 = l2 head = ListNode curr = head while True: if node1 == None: curr.next = node2 break if node2 == None: curr.next = node1 break if node1.val < node2.val: curr.next = node1 node1 = node1.next else: curr.next = node2 node2 = node2.next curr = curr.next return head.next
ad8dcb09a67cf586ddfbef4074328d4634c39f44
angrajlatake/100-days-to-code
/day27/mile_to_km_calculator.py
1,212
4.34375
4
import tkinter from itertools import cycle window = tkinter.Tk() window.title("GUI Program") window.minsize(width=500, height=300) window.config(padx=100,pady=100) converted_number = 0 #Conversion fucntion def convert_miles_to_km(): miles = input.get() global converted_number converted_number = round((int(miles)*1.60934),2) lable2.config(text= converted_number) def convert_km_to_miles(): km = input.get() global converted_number converted_number = round((int(km) / 1.60934), 2) lable2.config(text=converted_number) #INPUT input = tkinter.Entry(text="Miles",width=10) input.grid(column=2,row=1) #LABLES lable1= tkinter.Label(text="is equal to",font=("Arial", 20)) lable1.grid(column=1,row=2) lable2= tkinter.Label(text=converted_number,font=("Arial", 20)) lable2.grid(column=2,row=2) lable3= tkinter.Label(text="Km",font=("Arial", 20)) lable3.grid(column=3,row=2) lable3= tkinter.Label(text="Miles",font=("Arial", 20)) lable3.grid(column=3,row=1) #Button button = tkinter.Button(text= "Calculate", command= convert_miles_to_km) button.grid(column=2,row=3) #This is the given task. Lets go one step further and make a button to switch the units window.mainloop()
86aab355914c3fa812c8ba2e8c6ab18327d39eb0
SBriguglio/HashCrackerAssignment
/createHashCSV.py
512
3.53125
4
import csv import hashlib def main(): with open('userhashes512.csv', 'w', newline='') as csvfile: fieldnames = ['users', 'hashed_passwords'] line = csv.DictWriter(csvfile, fieldnames=fieldnames) for i in range(20): username = input("username: ") password = input("password: ") hashed = hashlib.sha512(password.encode()).hexdigest() line.writerow({'users': username, 'hashed_passwords': hashed}) if __name__ == '__main__': main()
588c4f0425bfb8d5d2749a76ff6511a56e930d64
catchonme/algorithm
/Python/151.reverse-words-in-a-string.py
295
3.90625
4
#!/usr/bin/python3 class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ tmp = s.split() res = " ".join(tmp[::-1]) return res sol = Solution() result = sol.reverseWords('jack is my name') print(result)
e85c9b74f21398d44c29e353572319cb77125568
jtraver/dev
/python3/math/pow1.py
200
4.28125
4
#!/usr/bin/env python3 # pow Return x**y (x to the power of y). import math val1 = 5.6 exp1 = 1.72 pow1 = math.pow(val1, exp1) print("pow(%s, %s) = %s" % (str(val1), str(exp1), str(pow1)))
85ee903f543c4e2d608c4190fb340143af7e356d
balajich/python-crash-course
/beginners/05_functions/08_function_with_positional_and_keyword_arguments.py
490
3.78125
4
''' Function with positional and key word arguments ''' def add(a, b, c=0, d=0): """ Division function with position argumenst a,b and keyword arguments c,d with default values :param a: :param b: :return: """ return a + b + c + d if __name__ == '__main__': # Calling function that has both keyword and named arguments print(add(1, 2, c=3, d=4)) print(add(1, 2, c=3)) # This is OK print(add(2, c=3, d=4)) # This is not OK, leads to error
c7676a47b2fddf27a758828f8058697a7f7014fc
lucasjribeiro/projects
/Python/_last_tmp.py
101
3.875
4
c = float(input('Digite a temperatura em °C: ')) print('A temperatura em °F = {}'.format(9*c/5+32))
64d628f8842e08f5e45a8e12f024aa765ab5e046
hudefeng719/uband-python-s1
/homeworks/B21052/checkin02/day02-homework-02.py
291
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: caramel def main(): total_money = 100 apple_price = 5 pie_price = 20 total_number = total_money / (apple_price + pie_price) print 'total_number %s ' % (total_money / (apple_price + pie_price)) if __name__ == '__main__': main()
ad234feaeae3b331b0d63f98d190a9648729ea9c
vektorelpython/Python8
/ifElseElif/ifelseelif.py
792
3.9375
4
Not = 34 """ 0-25 EE 26-44 FE 45-50 FF 51-59 FD 60-65 DD 66-69 DC 70-75 CC 76-80 CB 81-89 BB 90-95 BA 96-100 AA """ if Not>0 and Not<=25: print("EE") elif Not>25 and Not<=44: print("EF") else: print("Hesaplanmadı") a = 2 b= 3 c = 1 if (a>0 and not b < 1 ) and (a == 4 or c > 0): print("İf Çalışır") else: print("Else Çalışır") liste = [1,2,3,6,8,9,4,3] sayi = int(input("aramak istediğim sayıyı gir")) if sayi in liste: print("Sayı Listede var Sayının indisi:",liste.index(sayi)) else: print("Sayı Yok") print(liste) sifre = input("Şifre Giriniz") if not sifre: print("Şifre Girmediniz") metin = input("İfade giriniz") harf = "u" if harf in metin: print("u var") a = int("1") b = 1 if a is b: print(a) else: print("--")
ce46d82cf9a502dd952ef6a9e284d58423b9cbc3
halima254/manage-password
/contact.py
3,082
4.03125
4
import pyperclip import random class Contact: ''' class contacts generates new instances of a class ''' contact_list = [] def __init__(self, user_name, password): ''' __init__ method helps in defining properties for our objects. Args: user_name : New contact user name. password: New contact password. ''' self.user_name = user_name self.password= password def save_contact(self): ''' save contact object into contact list ''' Contact.contact_list.append(self) def delete_contact(self): ''' delete_contact method deletes a saved contact from the contact list ''' Contact.contact_list.remove(self) class Credentials(): """ Create credentials class to help create new objects of credentials """ credentials_list = [] @classmethod def verify_contact(cls,user_name, password): """ method to verify whether the user is in the contact_list or not """ a_cont = "" for user in Contact.contact_list: if(contact.user_name == user_name and contact.password == password): a_cont == contact.user_name return a_cont def __init__(self,account,userName, password): """ method that defines user credentials to be stored """ self.account = account self.user_name = userName self.password = password def save_details(self): """ method to store a new credential to the credentials list """ Credentials.credentials_list.append(self) def delete_credentials(self): """ delete_credentials method that deletes an account credentials from the credentials_list """ Credentials.credentials_list.remove(self) @classmethod def find_credential(cls, account): """ Method that takes in a account_name and returns a credential that matches that account_name. """ for credential in cls.credentials_list: if credential.account == account: return credential @classmethod def if_credential_exist(cls, account): """ Method that checks if a credential exists from the credential list and returns true or false depending if the credential exists. """ for credential in cls.credentials_list: if credential.account == account: return True return False @classmethod def display_credentials(cls): """ Method that returns all items in the credentials list """ return cls.credentials_list @classmethod def generate_Password(cls): """ Method that generates password """ chars = 'zxcvbnmlkjhgfdsaqwertyuiop1234567890' password = ''.join(random.choice(chars)for _ in range(8)) return password
2b47648b747adf57add27e86fa19850521e1760b
L200180005/Algostruk
/MODUL 1/2.py
161
3.671875
4
def persegiEmpat(a,b): for i in range (a): if i == 0 or i == a-1: print("@"*a) else: print ("@"+" "*(b-2)+"@")
846f9b92b796155b694099840a7327cf4e43d6b1
DiyanKalaydzhiev23/Advanced---Python
/Tuples and Sets - Lab/Parking Lot.py
284
3.6875
4
parking = set() for _ in range(int(input())): command, number = input().split(", ") if command == "IN": parking.add(number) else: parking.remove(number) if parking: [print(car) for car in parking] else: print("Parking Lot is Empty")
bef2030e9d5bf64f7b3291e4c5770228c9af2adc
esoergel/dimagi
/set_combination.py
836
4
4
def get_combinations(word_lists): """ generates a list of lists of possible combinations by recursing on the remaining lists (yo dawg...). """ if len(word_lists) == 1: return [ [word] for word in word_lists[0] ] combos = [] sub_combos = get_combinations(word_lists[1:]) for word in word_lists[0]: for sub_combo in sub_combos: combos.append( [word] + sub_combo ) return combos def print_combinations(word_lists): """ Returns all possible combinations of one word from each list word_lists should be a list of word lists """ for combination in get_combinations(word_lists): print " ".join(combination) word_lists = [ ["apple", "banana", "pear"], ["car", "truck"], ["zambia", "malawi", "kenya"], ] print_combinations(word_lists)
ce609e77c690ca65c204dd8178d93d4d8239b975
ForrestCo/first_python
/Day2/列表.py
3,561
3.8125
4
# -*- coding: utf-8 -*- # !/usr/bin/env python # @File : 列表.py # @Author: 杨崇 # @Date : 2019/1/8 # @Desc : null # 定义一个空列表 # li = [] # # li1 = [1, '张三', 'jack', 'Rose'] # print(li1) # print(li) # # count = len(li1) # count1 = len(li) # print(count) # print(count1) import keyword # li = [] # 定义一个空的列表 # li1 = [1, 3, 'jack', 'Rose'] # # # 添加元素 # # 在末尾追加数据 列表.append(数据) # li1.append('张三') # # # 在指定位置插入数据(位置前有空元素会补位) 列表.insert(索引, 数据) # li1.insert(1, '李四') # li.insert(2, 'jack') # print(li1) # print(li1[1]) # print(len(li)) # print(li[0]) # # # 将可迭代对象中 的元素 追加到列表 列表.extend(Iterable) # li2 = [1, 2, 3, '李四'] # li.extend(li2) # print('remove删除:', li) # # # 删除元素 # # 删除指定索引的数据 ,直接从内存中删除 del 列表[索引] # del li[0] # print(li) # # 删除第一个出现的指定数据 ------ 列表.remove(数据) # li = [1, 2, 'jack', 4, 'jack'] # li.remove('jack') # print(li) # # # 删除末尾数据,返回被删除的元素 列表.pop() # print(li.pop()) # print(li) # # # 删除指定索引数据------ 列表.pop(索引) # li = [1, 2, 'jack', 4, 'jack'] # i = li.pop() # print(i) # print(li) # # 清空列表----- 列表.clear # li.clear() # print(li) # # # # 修改元素------ 列表[索引] = 数据 # li = [1, 2, 3, 4, 'jack', 'Rose'] # li[1] = 'yc' # print(li) # # # # 查看 列表[索引] # # # 根据值查询索引,返回首次出现时的索引,没有查到会报错 # # 数据在列表中出现的次数 # # 列表.count(数据) # print(li.index('yc')) # # # # 数据在列表中出现的次数 # print(li.count(1)) # # # 列表长度 # print(len(li)) # # # 检查列表中是否包含某元素 # # if 数据 in 列表: # if 'y' in li: # print("true") # else: # print("false") # # # 排序 # # 升序排序 列表.sort() # li.clear() # li = [6, 5, 7, 9, 3, 1, 3] # print(li) # 排序前 # # li.sort() # print(li) # 排序后 # # # 降序排序 # # 列表.sort(reverse=True) # li.sort(reverse=True) # 降序排序 reverse = True # li.sort(reverse=False) # 升序排序 reverse = False # print(li) # print("*" * 50) # # 逆序、反转 列表.reverse() # li = [6, 5, 7, 9, 3, 1, 3] # print(li) # li.reverse() # print(li) # # # # print("*" * 50) # # print(keyword.kwlist) # # # # 循环遍历 # i = 0 # li = [6, 5, 7, 9, 3, 1, 3] # l = len(li) # for i in range(0, l): # number = li[i] # print(number, ' ', end='') # # print('') # # 列表嵌套 # li = [ # ['河南', '郑州'], # ['浙江', '杭州'], # ['四川', '成都'] # ] # # count1 = len(li) # for i in range(0, count1): # li1 = li[i] # count2 = len(li1) # for j in range(0, count2): # print(li1[j], ' ', end='') # print('') # i = 0 # j = 0 # while i < 5: # print('hello') # while j < 5: # print('hello') # continue # j += 1 # i += 1 # break import random school = [[], [], []] # 定义学校和办公室 teacher = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] # 定义教师信息 count_teacher = len(teacher) # 获取teacher列表中的元素个数 count_school = len(school) # 获取school列表中的元素个数 # 遍历teacher列表中的元素,追加到school[]中 for i in range(0, count_teacher): # 获取随机数 result1 = random.randint(0, count_school) school[result1].append(teacher[i]) print(school)
c8ca59419d99d1086c49adeeda9da9436f9dcb2b
stepanLys/algoritms_sa31
/5/Array.py
585
3.59375
4
# -*- coding: utf-8 -*- import random class Array(): def __init__(self): self.list = [round(random.uniform(0, 100), 2) for i in range(random.randint(2,100))] # self.list = [input('enter array: ')] self.list1 = list() self.list2 = list() self.n = input('n: ') def draw(self): return self.list def inputN(self): return self.n def separate(self): self.list1 = self.list[:int(self.inputN())] self.list2 = self.list[int(self.inputN()):] return self.list1, self.list2
656e6c7a0872c2ae2c89f8dc1f9cdf1d6f5071d1
hiraditya/tkinter
/buttons.py
410
3.578125
4
# Controlling the layout using frames import tkinter as tk w = tk.Tk() f1 = tk.Frame(w) f2 = tk.Frame(w) f1.pack(side=tk.TOP) f2.pack(side=tk.BOTTOM) b1 = tk.Button(f1, text="b1", fg="blue") b2 = tk.Button(f1, text="b2", bg="red") b3 = tk.Button(f1, text="b3") b4 = tk.Button(f2, text="b4") b2.pack(side=tk.LEFT) b1.pack(side=tk.LEFT) b3.pack(side=tk.LEFT) b4.pack() w.mainloop()
abf9072ce2116f57d9ff4dfed851c02f0e753e1c
GarrettGutierrez1/FFG_Geo
/ffg_geo/triangle2.py
963
3.90625
4
# -*- coding: utf-8 -*- """triangle.py A module implementing Triangle2, which is the representation of a 2-dimensional triangle produced by triangulation. License: http://www.apache.org/licenses/LICENSE-2.0""" from typing import Iterable, List class Triangle2(object): """A 2-dimensional triangle. Attributes: v: The vertices in counter-clockwise order. n: The neighbors in counter-clockwise order.""" def __init__(self, v: Iterable = (None, None, None), n: Iterable = (None, None, None)) -> None: """Initializes the Triangle2. Args: v: The vertex indices. n: The neighbor triangle indices.""" self.v = list(v[:3]) # type: List[int] self.n = list(n[:3]) # type: List[int] def __str__(self) -> str: """str's the triangle. Returns: The triangle as a str.""" return 'Triangle: v: {} n: {}'.format(tuple(self.v), tuple(self.n))
2de4ac8002a009d4ca0944653f89dcf834d9026d
anhowe1/PG_AH
/personality_servey_ AHowe.py
1,738
4.1875
4
print ("what's your name") name=input().title() print ("cool nice to meet you" + name) print ("What's your favorite sport?") sport=input().title() if sport == "Skiing": print ("I love skiing too") elif sport == "Snowboarding": print ("I have never tryed snowboarding") elif sport == "Dance": print ("A lot of my friends dance") else: print (sport + " sounds like a lot of fun.") print ("What's your favorite animal?") animal=input().title() if animal == "Dog": print ("I have a dog, her name is Bailey and she is an australian shepherd.") elif animal == "Cat": print ("I have three cats, their names are Mr. Cheeky Chops, Leo and Max") elif animal == "Elephant": print ("They are beautiful, did you know they cover themselves in mud to protect their skin from the sun?") elif animal == "Bear": print ("Did you know black bears love honey! What type of Bear do you like most: Black Bear, polar Bear or grizzly bear") bear = input().title() if bear == "Black Bear" or bear == "Grizzly Bear": print ("My favorite bear type is a polar Bear") elif bear == "Polar Bear": print ("I love polar bears as well") print ("What's your favorite pass time activity, other than sports") activity = input() if activity == "reading": print ("my favorite book is The Golden Compass") elif activity == "hanging out with my friends": print ("I like to hang out with my friends as well") elif activity == "drawing": print ("I love drawing. Do you ever paint?(please just say Yes or No)") paint = input().title() if paint == "Yes": print("awesome") elif paint == "No": print("cool, you should try it some times")
6d906600afd9f093e3116efaed3cab2fdf71d474
geniayuan/MachineLearningCoursera
/ex1/ex1_multi.py
4,137
4.4375
4
# Machine Learning Online Class # Exercise 1: Linear regression with multiple variables # # Instructions # ------------ # # This file contains code that helps you get started on the # linear regression exercise. # # You will need to complete the following functions in this # exericse: # # warmUpExercise.m # plotData.m # gradientDescent.m # computeCost.m # gradientDescentMulti.m # computeCostMulti.m # featureNormalize.m # normalEqn.m # # For this part of the exercise, you will need to change some # parts of the code below for various experiments (e.g., changing # learning rates). # import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import axes3d, Axes3D from computeCost import computeCost from gradientDescent import gradientDescent from featureNormalize import featureNormalize from normalEqn import normalEqn ## ================ Part 1: Feature Normalization ================ print('Loading data ...') #filename = input("please enter the file name: ") filename = "ex1data2.txt" data = np.loadtxt(filename, delimiter = ',') m = data.shape[0] x = data[:,0:2] y = data[:,2] print('Normalizing Features ...') x_norm, x_mu, x_std = featureNormalize(x) # Add intercept term to X X = np.c_[np.ones(m), x_norm] y = y.reshape(m,1) ## ================ Part 2: Gradient Descent ================ # ====================== YOUR CODE HERE ====================== # Instructions: We have provided you with the following starter # code that runs gradient descent with a particular # learning rate (alpha). # # Your task is to first make sure that your functions - # computeCost and gradientDescent already work with # this starter code and support multiple variables. # # After that, try running gradient descent with # different values of alpha and see which one gives # you the best result. # # Finally, you should complete the code at the end # to predict the price of a 1650 sq-ft, 3 br house. # # Hint: By using the 'hold on' command, you can plot multiple # graphs on the same figure. # # Hint: At prediction, make sure you do the same feature normalization. # print('Running gradient descent ...') # Choose some alpha value alpha = 0.8; num_iters = 50; # Init Theta and Run Gradient Descent theta = np.zeros( (X.shape[1], 1) ); theta, J_history = gradientDescent(X, y, theta, alpha, num_iters); # Plot the convergence graph plt.figure(1, figsize=(8,6)); plt.plot(J_history, '-b', linewidth=2); plt.xlabel('Number of iterations') plt.ylabel('Cost J') plt.show() # Display gradient descent's result print('Theta computed from gradient descent:', theta); # Estimate the price of a 1650 sq-ft, 3 br house # Recall that the first column of X is all-ones. Thus, it does # not need to be normalized. example = (np.array([1650,3]) - x_mu) / x_std x_test = np.insert(example, 0, 1) price = float(np.dot(x_test,theta)) print('Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):', price) ## ================ Part 3: Normal Equations ================ print('Solving with normal equations...') # ====================== YOUR CODE HERE ====================== # Instructions: The following code computes the closed form # solution for linear regression using the normal # equations. You should complete the code in # normalEqn.m # # After doing so, you should complete this code # to predict the price of a 1650 sq-ft, 3 br house. # # Add intercept term to X X = np.insert(x, 0, 1, axis = 1) # Calculate the parameters from the normal equation theta = normalEqn(X, y) # Display normal equation's result print('Theta computed from the normal equations:') print(theta) # Estimate the price of a 1650 sq-ft, 3 br house example = np.array([1650,3]) x_test = np.insert(example, 0, 1) price = float( np.dot(x_test,theta) ) print('Predicted price of a 1650 sq-ft, 3 br house (using gradient descent):', price);
0cf30dadeaf9c921b1bd6708fbe917dfe407ac8f
kalvare/machine_learning
/core/optimizers/SGD.py
1,424
3.578125
4
""" This file contains code for the implementation of Stochastic (mini-batch) Gradient Descent """ class SGD(object): """ Class implementing Stochastic (mini-batch) Gradient Descent """ def __init__(self, params, gradients, lr=0.001, weight_decay=0.0): """ Constructor. Args: params: tuple of tensor, parameters to optimize. This should be a tuple of all parameter sets in the model to update. Each parameter set should be a tensor. gradients: tuple of tensor, corresponding gradients for params. Again, this should be a tuple with a one-to-one correspondence to params. lr: float, learning rate for numerical optimization. weight_decay: float, weight decay for regularization. """ self.params = params self.gradients = gradients self.lr = lr self.weight_decay = weight_decay def step(self): """ Takes a single optimization step. Returns: None """ for params, gradients in zip(self.params, self.gradients): grad = gradients if self.weight_decay > 0: # Add weight decay directly to the gradients grad += self.weight_decay * params params.sub_(self.lr * grad)
e8099664f4aeea4f2e177bec26ea18c0360138d9
lyyyuna/zhi_xu_zhe
/30/minstack.py
905
3.828125
4
class MinStack(): def __init__(self): self.real_stack = [] self.min_stack = [] def push(self, num): self.real_stack.append(num) if not self.min_stack: self.min_stack.append(num) else: min_now = self.min_stack[-1] if num < min_now: self.min_stack.append(num) else: self.min_stack.append(min_now) def pop(self): if not self.min_stack or not self.real_stack: return None self.min_stack.pop() return self.real_stack.pop() def min(self): if not self.min_stack: return None return self.min_stack[-1] s = MinStack() s.push(2.98) s.push(3) print(s.real_stack) print(s.min()) s.pop() print(s.real_stack) print(s.min()) s.push(1) print(s.real_stack) print(s.min()) s.pop() print(s.real_stack) print(s.min())
12d39a42f1ac2addb17e56d0fea15701a7fcd58b
vdemchenko3/Projects
/BRAF/Random_Forest_module.py
24,808
3.59375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd import random class BiasedRandomForest(): # This class is a modified RandomForest class that uses trees from both the base and critical datasets for predictions def __init__(self, x, y, x_braf, y_braf, num_trees, num_trees_braf, num_features, sample_size=None, sample_size_braf=None, depth=10, min_leaf=5): np.random.seed(42) # keep same randoms for testing and reproducibility if sample_size is None: self.sample_size = len(y) if sample_size_braf is None: self.sample_size_braf = len(y_braf) self.x = x self.y = y self.num_trees = num_trees self.x_braf = x_braf self.y_braf = y_braf self.num_trees_braf = num_trees_braf self.num_features = num_features # number of decision splits self.depth = depth # minimum number of rows required in a node to cause further split. self.min_leaf = min_leaf # deciding how many features to include if self.num_features == 'sqrt': self.num_features = int(np.sqrt(x.shape[1])) elif self.num_features == 'log2': self.num_features = int(np.log2(x.shape[1])) else: self.num_features = num_features # creating tree instances trees = [self.create_tree() for i in range(num_trees)] trees_braf = [self.create_tree_braf() for i in range(num_trees_braf)] self.trees = trees+trees_braf def create_tree(self): # This is effectively bootstrapping sample_size number of samples in place rand_idxs = np.random.choice(len(self.y), replace = True, size = self.sample_size) # This gets us the features we've decided to use feature_idxs = np.random.choice(self.x.shape[1], size = self.num_features) # returns a DecisionTree using the randomized indexes selected and min_leaf return DecisionTree(self.x.iloc[rand_idxs], self.y[rand_idxs], self.num_features, idxs=np.array(range(self.sample_size)), feature_idxs = feature_idxs, depth = self.depth, min_leaf = self.min_leaf) def create_tree_braf(self): # This is effectively bootstrapping sample_size number of samples in place rand_idxs = np.random.choice(len(self.y_braf), replace = True, size = self.sample_size_braf) # This gets us the features we've decided to use feature_idxs = np.random.choice(self.x_braf.shape[1], size = self.num_features) # returns a DecisionTree using the randomized indexes selected and min_leaf return DecisionTree(self.x_braf.iloc[rand_idxs], self.y_braf[rand_idxs], self.num_features, idxs=np.array(range(self.sample_size_braf)), feature_idxs = feature_idxs, depth = self.depth, min_leaf = self.min_leaf) def predict(self, x): # gets the mean of all predictions across the RF pred = np.mean([t.predict(x) for t in self.trees], axis = 0) # returns a 1 or 0 given the predictions return [1 if p>0.5 else 0 for p in pred] def predict_proba(self, x): # gets the mean of all predictions across the RF pred = np.mean([t.predict(x) for t in self.trees], axis = 0) # returns 'probability' that a 1 or 0 will be selected return [[1.-p,p] for p in pred] class RandomForest(): def __init__(self, x ,y, num_trees, num_features, sample_size=None, depth=10, min_leaf=5): np.random.seed(42) # keep same randoms for testing and reproducibility if sample_size is None: self.sample_size = len(y) self.x = x self.y = y self.num_trees = num_trees self.num_features = num_features # number of decision splits self.depth = depth # minimum number of rows required in a node to cause further split. self.min_leaf = min_leaf # deciding how many features to include if self.num_features == 'sqrt': self.num_features = int(np.sqrt(x.shape[1])) elif self.num_features == 'log2': self.num_features = int(np.log2(x.shape[1])) else: self.num_features = num_features # creating tree instances self.trees = [self.create_tree() for i in range(num_trees)] def create_tree(self): # This is effectively bootstrapping sample_size number of samples in place rand_idxs = np.random.choice(len(self.y), replace = True, size = self.sample_size) # This gets us the features we've decided to use feature_idxs = np.random.choice(self.x.shape[1], size = self.num_features) # returns a DecisionTree using the randomized indexes selected and min_leaf return DecisionTree(self.x.iloc[rand_idxs], self.y[rand_idxs], self.num_features, idxs=np.array(range(self.sample_size)), feature_idxs = feature_idxs, depth = self.depth, min_leaf = self.min_leaf) def predict(self, x): # gets the mean of all predictions across the RF pred = np.mean([t.predict(x) for t in self.trees], axis = 0) # returns a 1 or 0 given the predictions return [1 if p>0.5 else 0 for p in pred] def predict_proba(self, x): # gets the mean of all predictions across the RF pred = np.mean([t.predict(x) for t in self.trees], axis = 0) # returns 'probability' that a 1 or 0 will be selected return [[1.-p,p] for p in pred] class DecisionTree(): def __init__(self, x, y, num_features, idxs, feature_idxs, depth, min_leaf): self.x = x self.y = y self.num_features = num_features self.depth = depth self.idxs = idxs self.feature_idxs = feature_idxs self.min_leaf = min_leaf self.n_rows = len(idxs) self.n_cols = x.shape[1] self.val = np.mean(y[idxs]) # checks how effective a split of a tree node is self.score = float('inf') # finds which variable to split on self.find_varsplit() def find_varsplit(self): # find best split in current tree for i in self.feature_idxs: self.find_best_split(i) # check for leaf node so no split to be made if self.is_leaf: return # if it is note a leaf node, we need to create an lhs and rhs x = self.split_col # np.nonzero gets a boolean array, but turns it into indexes of the Truths lhs = np.nonzero(x <= self.split)[0] rhs = np.nonzero(x > self.split)[0] # get random features lhs_feat = np.random.choice(self.x.shape[1], size = self.num_features) rhs_feat = np.random.choice(self.x.shape[1], size = self.num_features) self.lhs_tree = DecisionTree(self.x, self.y, self.num_features, self.idxs[lhs], lhs_feat, depth = self.depth-1, min_leaf = self.min_leaf) self.rhs_tree = DecisionTree(self.x, self.y, self.num_features, self.idxs[rhs], rhs_feat, depth = self.depth-1, min_leaf = self.min_leaf) def find_best_split(self, var_idx): # takes variable index (var_idx) and finds if it's a better split than we have so far # since the initial score is set to infinity, it will always be more beneficial to create a split # we'll be doing this in a greedy way with O(n) runtime # get all the rows that we're considering for this tree, but only the particular variable we're looking at x = self.x.values[self.idxs, var_idx] y = self.y[self.idxs] # get the indices of the sorted data sort_idx = np.argsort(x) sort_x = x[sort_idx] sort_y = y[sort_idx] # loop over all data entries possible for this tree for i in range(0, self.n_rows - self.min_leaf-1): # making sure we're not on a leaf node and skipping over same, bootstrapped values in the data if i < self.min_leaf or sort_x[i] == sort_x[i+1]: continue lhs = np.nonzero(sort_x <= sort_x[i])[0] rhs = np.nonzero(sort_x > sort_x[i])[0] # if we're looking at a split with no rhs, skip it because it's not a split if rhs.sum()==0: continue gini = calc_gini(lhs, rhs, sort_y) # check if this split's gini is better than another splith if gini < self.score: self.var_idx = var_idx self.score = gini self.split = sort_x[i] # function that's calculate 'on the fly' and can be used without parentheses # @ is a 'decorator' @property def split_name(self): return self.x.columns[self.var_idx] @property def split_col(self): return self.x.values[self.idxs, self.var_idx] @property def is_leaf(self): return self.score == float('inf') def __repr__(self): # This function helps us to get a better representation of the objects when we print them out s = f'n: {self.n_rows}; val: {self.val}' if not self.is_leaf: # if this node isn't a leaf, print out the score, split, and name on which it split s += f'; score: {self.score}; split: {self.split}; var: {self.split_name}' return s def predict(self, x): # get predictions of the tree are the predictions for each row in an array # loops through rows because x is matrix and the leading axis is 0 meaning row return np.array([self.predict_row(xi) for xi in x]) def predict_row(self, xi): # predictions for each row # check if leaf node if self.is_leaf: return self.val # if variable in row xi is <= split value, go down left tree, otherwise right tree best = self.lhs_tree if xi[self.var_idx] <= self.split else self.rhs_tree return best.predict_row(xi) class Metrics(): # This class holds all the metrics that we use def __init__(self, y_true, pred, prob): self.y_true = y_true self.pred = pred self.prob = prob def compute_confusion_matrix(self): # Computes a confusion matrix using numpy for two np.arrays true and pred # Number of classes c = len(np.unique(self.y_true)) # makes sure confusion matrix is at least a 2x2 if c <=1 : c = 2 cm = np.zeros((c, c)) for a, p in zip(self.y_true, self.pred): cm[int(a)][int(p)] += 1 return cm def calc_precision_recall(self, conf_mat): # calculate the precision, recall, and specificity given a confusion matrix # This formulation can be applied to multiple classes TP = conf_mat.diagonal() FP = np.sum(conf_mat, axis=0) - TP FN = np.sum(conf_mat, axis=1) - TP TN = conf_mat.sum() - (FP + FN + TP) precision = TP / (TP+FP) recall = TP / (TP+FN) # we don't use this for our purpose, but good to have it just in case specificity = TN / (TN + FP) # returns metrics for 1 class since we have a binary classification problem return precision[1], recall[1], specificity[1] def calc_roc_prc(self): # calculates the values for the ROC and PRC curves # false positive rate fpr = [] # true positive rate tpr = [] # precision rate prec = [] # Iterate thresholds from 0.0, 0.01, ... 1.0 thresholds = np.arange(0.0, 1.01, .01) # get number of positive and negative examples in the dataset P = sum(self.y_true) N = len(self.y_true) - P # iterate through all thresholds and determine fraction of true positives # and false positives found at this threshold for thresh in thresholds: FP=0 TP=0 for i in range(len(self.prob)): if (self.prob[i] > thresh): if self.y_true[i] == 1: TP = TP + 1 if self.y_true[i] == 0: FP = FP + 1 # checks to make sure there are no undefined values and sets them to 1 if N == 0: fpr.append(1) else: fpr.append(FP/float(N)) if P == 0: tpr.append(1) else: tpr.append(TP/float(P)) if (TP+FP) == 0: prec.append(1) else: prec.append(TP/(TP+FP)) # return values in ascending order return np.array(tpr)[::-1], np.array(fpr)[::-1], np.array(prec)[::-1] def AUC(self,x,y): # return Area Under Curve using the trapezoidal rule return np.trapz(y,x) def calc_gini(left, right, y): # this function calculates the gini score and will be the decision maker for splitting trees # this is the default in sklearn, but we can use other scoring functions if we wish classes = np.unique(y) n = len(left) + len(right) s1 = 0 s2 = 0 for cls in classes: # find probability of each class and add the square to s1/s2 p1 = len(np.nonzero(y[left] == cls)[0]) / len(left) s1 += p1*p1 p2 = len(np.nonzero(y[right] == cls)[0]) / len(right) s2 += p2*p2 # weighted average of (1-sum_left) and (1-sum_right) gini = (1-s1)*(len(left)/n) + (1-s2)*(len(right)/n) return gini def euclidean_distance(row1,row2,length): # calculates Euclidean distance between two data entries with i columns distance = 0.0 for i in range(length): distance += (row1[i] - row2[i])**2. return np.sqrt(distance) def get_KNN(dataset, test_row, K): # function to get K nearest neighbors from pandas df distances = [] length = dataset.shape[1] # loop over all rows in dataset for i in range(dataset.shape[0]): # calculate distance to each row dist = euclidean_distance(test_row, dataset.iloc[i], length) distances.append((dataset.iloc[i], dist)) # sort the distances distances.sort(key=lambda x: x[1]) # get the K closest distances # since for our purposes we're using a separate dataset, # we're not worried about the same row being it's own neighbor neighbors = distances[:K] # returns the row and the distance return neighbors def get_folds(X, K): # This function is a modification from sklearn to get the indices of K folds n_samples = len(X) indices = np.arange(n_samples) n_folds = K fold_sizes = np.full(n_folds, n_samples // n_folds, dtype=np.int) fold_sizes[:n_samples % n_folds] += 1 folds = [] current = 0 for fold_size in fold_sizes: start, stop = current, current + fold_size folds.append(indices[start:stop]) current = stop return folds def get_folds_braf(X, X_crit, K): # This function is a modification from sklearn to get the indices of K folds n_samples = len(X) indices = np.arange(n_samples) n_samples_crit = len(X_crit) indices_crit = np.arange(n_samples_crit) n_folds = K fold_sizes = np.full(n_folds, n_samples // n_folds, dtype=np.int) fold_sizes[:n_samples % n_folds] += 1 fold_sizes_crit = np.full(n_folds, n_samples_crit // n_folds, dtype=np.int) fold_sizes_crit[:n_samples_crit % n_folds] += 1 folds = [] folds_crit = [] current = 0 for i in range(len(fold_sizes)): start, stop = current, current + fold_sizes[i] folds.append(indices[start:stop]) current = stop crit_idx = [] j = 0 # collect indices from the critical dataset until you find enough for each critical fold # that satisfy the below conditions while len(crit_idx) < fold_sizes_crit[i]: # check if the current row from the critical data set is not in the current fold # for the regular dataset and not in a previous critical fold if j < X_crit.shape[0] and (X.iloc[indices[start:stop]] == X_crit.loc[j]).any().all() == False \ and all(j not in lst for lst in folds_crit): # if not, append its index to the list that contains the indices for this critical fold crit_idx.append(j) # if we've used up all the entries, choose some at random # this is not ideal and there might be some overlap between the # regular and critical folds. This will likely only happen on the # last fold and shouldn't occur for many values elif j >= X_crit.shape[0]: j_rand = random.randrange(0, X_crit.shape[0], 1) if (X.iloc[indices[start:stop]] == X_crit.loc[j_rand]).any().all() == False \ and j_rand not in crit_idx: crit_idx.append(j_rand) j+=1 folds_crit.append(np.array(crit_idx)) return folds, folds_crit def get_BRAF_df(dataset, col, mincls, majcls, knn): # function for getting the critical dataset for BRAF # define initial critical dataset as the minority class dataset df_crit = dataset.loc[dataset[col] == mincls] # define majority dataset df_maj = dataset.loc[dataset[col] == majcls] # define minority dataset df_min = dataset.loc[dataset[col] == mincls] # loop over the minority dataset to get KNN and add them to the critical dataset for i in range(df_min.shape[0]): # Get k nearest neighbors Tnn = get_KNN(df_maj, df_min.iloc[i], knn) for j in range(len(Tnn)-1): # Check if this particular neighbor is in the critical dataset if (df_crit == Tnn[j][0]).all(1).any() == False: df_crit = df_crit.append(Tnn[j][0],ignore_index=True) df_crit = df_crit.sample(frac=1).reset_index(drop=True) return df_crit def get_cv_preds_braf(X, Y, X_braf, Y_braf, k_folds, n_trees, n_trees_braf, n_feat, dep, m_leaf): # This is a function for evaluating k-folds CV and returning the true y, predictions, and probabilities # it works for a BiasedRandomForest class folds, folds_braf = get_folds_braf(X, X_braf, k_folds) # scores are ordered in precision, recall, AUROC, AUPRC, TPR, FPR, prec_rate y_pred_prob = [] for i in range(len(folds)): # indices for the validation subset val = X.index.isin(folds[i]) val_braf = X_braf.index.isin(folds_braf[i]) # separate the dataset into train and test for each CV X_train = X.iloc[~val] X_test = X.iloc[val] Y_train = Y.iloc[~val] Y_test = Y.iloc[val] # braf X_train_braf = X_braf.iloc[~val_braf] Y_train_braf = Y_braf.iloc[~val_braf] # call BiasedRandomForest Class ens = BiasedRandomForest(X_train, np.array(Y_train), X_train_braf, np.array(Y_train_braf), num_trees=n_trees, num_trees_braf=n_trees_braf, num_features=n_feat, depth=dep, min_leaf=m_leaf) # the predictions and their probabilities # we only use the X_test values for the CV (rather than X_test+X_test_braf) # since they most closely resemble the test dataset that we'll use when evaluating the model pred_RF = ens.predict(X_test.values) prob_RF = ens.predict_proba(X_test.values) y_pred_prob.append([np.squeeze(np.array(Y_test)),np.array(pred_RF),np.array(prob_RF)[:,1]]) return y_pred_prob def get_cv_preds(X, Y, k_folds, n_trees, n_feat, dep, m_leaf): # This is a function for evaluating k-folds CV and returning the true y, predictions, and probabilities # it works for the RandomForest class folds = get_folds(X, k_folds) # scores are ordered in precision, recall, AUROC, AUPRC, TPR, FPR, prec_rate y_pred_prob = [] for i in range(len(folds)): # indices for the validation subset val = X.index.isin(folds[i]) # separate the dataset into train and test for each CV X_train = X.iloc[~val] X_test = X.iloc[val] Y_train = Y.iloc[~val] Y_test = Y.iloc[val] # call RandomForest Class ens = RandomForest(X_train, np.array(Y_train), num_trees=n_trees, num_features=n_feat, depth=dep, min_leaf=m_leaf) # the predictions and their probabilities pred_RF = ens.predict(X_test.values) prob_RF = ens.predict_proba(X_test.values) y_pred_prob.append([np.squeeze(np.array(Y_test)),np.array(pred_RF),np.array(prob_RF)[:,1]]) return y_pred_prob def get_cv_scores(y_pred_prob): # calculate the scores given the true y values, predictions, and probabilites # scores are ordered in precision, recall, AUROC, AUPRC, TPR, FPR, prec_rate scores = [] for i in range(len(y_pred_prob)): met = Metrics(y_pred_prob[i][0], y_pred_prob[i][1], y_pred_prob[i][2]) # confusion matrix cm = met.compute_confusion_matrix() # precision recall precision, recall, _ = met.calc_precision_recall(cm) # TPR, FPR, 'precision rate' tpr, fpr, prec = met.calc_roc_prc() # AUROC and AUPRC auprc = met.AUC(tpr,prec) auroc = met.AUC(fpr,tpr) scores.append([precision,recall,auroc,auprc,tpr,fpr,prec]) return scores def plot_PRC(rec,prec,label,AUC): # plots and saves PRC plot # label is to differentiate CV and test sets fig, ax = plt.subplots(figsize= [12,10]) ax.set_xlabel('Recall', fontsize=23) ax.set_ylabel('Precision', fontsize=23) ax.set_title(f'{label} PRC Curve with AUPRC: {AUC:.4f}', fontsize=27) ax.plot(rec,prec,linewidth=3,color='b') ax.spines['top'].set_linewidth(2.3) ax.spines['left'].set_linewidth(2.3) ax.spines['right'].set_linewidth(2.3) ax.spines['bottom'].set_linewidth(2.3) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(18) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(18) # plt.savefig(f'{label}_PRC_Curve',fmt='png') def plot_ROC(fpr,tpr,label,AUC): # plots and saves ROC plot # label is to differentiate CV and test sets fig, ax = plt.subplots(figsize= [12,10]) ax.set_xlabel('False Positive Rate', fontsize=23) ax.set_ylabel('True Positive Rate', fontsize=23) ax.set_title(f'{label} ROC Cure with AUROC: {AUC:.4f}', fontsize=27) ax.plot(fpr,tpr,linewidth=3,color='r') ax.spines['top'].set_linewidth(2.3) ax.spines['left'].set_linewidth(2.3) ax.spines['right'].set_linewidth(2.3) ax.spines['bottom'].set_linewidth(2.3) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(18) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(18) # plt.savefig(f'{label}_ROC_Curve',fmt='png')
8f94512eb96bb70dfd4d62d7bf2b39c1dd235192
DevShasa/code-challenges
/codewars/binary_sum.py
227
4.21875
4
''' Implement a function that adds two numbers together and returns their sum in binary The conversion can happen before or after the addition ''' def add_binary(a, b): return str(bin(a+b))[2:] print(add_binary(51,12))
1d3cdf18ccfc7d0e193004d6677b3119d02c6576
Belchy06/CP1404-Practicals
/prac_01/shop_calculator.py
519
3.75
4
""" Shop The total is usually a few cents off due to floating point error. Could be fixed by using a decimal type """ numItems = int(input("Number of items: ")) while numItems <= 0: print("Invalid number of items entered!") numItems = int(input("Number of items: ")) prices = [] for i in range(numItems): price = float(input("Price of item: $")) prices.append(price) total = sum(prices) if total > 100: total *= 0.9 print("The total for {} items is ${:.2f}".format(numItems, round(total, 2)))
a9859d7aa64d16c64b7e9c2a51063aae23c6a145
ModiEsawi/IDS-UCS-A-star-IDA-star-Best-first-search
/Searcher.py
3,937
3.890625
4
from queue import PriorityQueue # check if a certain node is inside a queue def checkIfInQueue(node, pq, nodesDic): if pq.empty(): return False tempQ = PriorityQueue() nodeState = node.getState() for i in pq.queue: tempQ.put(i) while not tempQ.empty(): index = int(tempQ.get()[1]) if index in nodesDic: got = nodesDic.get(index).getState() if nodeState == got: return True return False # get the priority of a node in the queue (which is it's f value) def getPriority(node, pq, nodesDic): tempQ = PriorityQueue() for i in pq.queue: tempQ.put(i) nodeState = node.getState() while not tempQ.empty(): nodeNumber = tempQ.get() currentNode = nodesDic.get(int(nodeNumber[1])) got = currentNode.getState() if nodeState == got: return nodeNumber[0] # after we change a nodes F value we pop it from the queue and then return it so it will have its right place def resetPriority(node, pq, needed, smallestValue): newQueue = PriorityQueue() nodesDic = needed[1] numberDic = needed[0] nodeNumber = numberDic[node] while not pq.empty(): temp = pq.get() if temp[1] != nodeNumber: newQueue.put(temp) newQueue.put((needed[2], needed[3])) fatherNode = needed[4] node.setFather(fatherNode) finalGoal = needed[5] goalX = int(finalGoal.getState()[0]) goalY = int(finalGoal.getState()[1]) pathCost = fatherNode.getPathCost() + node.getCost() node.setfValue(pathCost + (smallestValue * max(abs(node.getState()[0] - goalX), abs(node.getState()[1] - goalY)))) node.setPathCost(pathCost) nodesDic[needed[3]] = node numberDic[node] = needed[3] return newQueue # find the node in the dictionary def findNodeInDic(nodeToLookFor, nodesDic): for key, value in nodesDic.items(): state = value.getState() if state == nodeToLookFor.getState(): return value return None # look for a certain node in the queue and return it def returnNodeFromQueue(node, pq, nodesDic): tempQ = PriorityQueue() nodeState = node.getState() for i in pq.queue: tempQ.put(i) while not tempQ.empty(): index = int(tempQ.get()[1]) got = nodesDic.get(index) state = got.getState() if nodeState == state: return got return False # after we change a nodes F value we pop it from the queue and then return it so it will have its right place def UCSresetPriority(node, pq, numberDic, nodesDic, newPriority, newNodeNumber, fatherNode): newQueue = PriorityQueue() nodeNumber = numberDic[node] while not pq.empty(): temp = pq.get() if temp[1] != nodeNumber: newQueue.put(temp) newQueue.put((newPriority, newNodeNumber)) node.setFather(fatherNode) node.setPathCost(fatherNode.getPathCost() + node.getCost()) nodesDic[newNodeNumber] = node numberDic[node] = newNodeNumber return newQueue """ * The Searcher abstract class. * defines methods that are common among all the searchers. """ class Searcher: def __init__(self, totalPathCost=0, evaluatedNodes=0): self.totalPathCost = totalPathCost self.evaluatedNodes = evaluatedNodes self.priorityQueue = [] # return the number of nodes evaluated in the algorithm (expanded) def getNumberOfNodesEvaluated(self): return self.evaluatedNodes # trace back from the goal node to its ancestors and return the path/ def traceBack(self, goalState): fathers = [goalState] while goalState.getWhereWeCameFrom() is not None: fathers.append(goalState.getWhereWeCameFrom()) goalState = goalState.getWhereWeCameFrom() return fathers
2090cd61a5a3ecd03e15c4256028188c7f49b78c
ShubhangiDabral13/Pythonic_Lava_Coding_Question
/GeeksForGeeks/gfg-Basic Question/Pangram Checking/Pangram_checking.py
651
3.71875
4
def pangram_checker(s): c = [0]*26 for i in s.lower(): if i != " ": c[ord(i) - ord("a")] += 1 for i in range(26): if c[i] == 0 : return False return True sentence = "The quick brown fox jumps over the little lazy dog" if (pangram_checker(sentence)): print (sentence) print("is a pangram") else: print(sentence) print("is not a pangram") sentence = "The quick brown fox jumps over the little lazy" if (pangram_checker(sentence)): print (sentence) print("is a pangram") else: print(sentence) print("is not a pangram")
d1aeb57f2039fa34a1ef8eb0b63f3662a902c216
Llontop-Atencio08/t07_Llontop.Rufasto
/Llontop_Atencio/Bucles.Para.py
561
3.5
4
#Ejercicio01 i=0 s=0 max=50 while(i<=max): i+=1 if((i%2)==0): s=s+2 #fin_si #fin_while print("suma pares:",s) #Ejercicio02 #Numeros pares del 0 al 100 n=0 while(n<=100): print(n) n+=2 #fin_while #Ejercicio03 #suma de la serie i=0 s=0 max=30 while(i<=max): i+=3 if((i%2)==0): s=s+10 #fin_si #fin_while print("suma:",s) #Ejercicio04 #numeros del 10 al 40 n=10 while(n<=40): print(n) n+=1 #fin_while #Ejercicio05 #numeros del 150 al 50 i=150 while(i>=50): print(i) i-=1 #fin_while
707fe89d3a32aa24565f70e24b7ef4af81bde491
jaredsutt34/NextGen
/reg_files/whileloop.py
273
3.9375
4
import random secretNumber = random.randint (1,10) guessNumber = int(input("Guess a number...")) # runs until its false while guessNumber != secretNumber: guessNumber = int(input("WRONG. Guess another number...")) print('You won.. the number was..', secretNumber)
53536c3733e5a2637d25454026c95c227488d08a
jherskow/intro2cs
/intro2cs/ex10/article.py
1,998
4.0625
4
"""######################################################################## # FILE : article.py # WRITER : Joshua Herskowitz , jherskow , 321658379 # EXERCISE : intro2cs ex10 2016-2017 # DESCRIPTION: Implements article object and functionality. ########################################################################""" # ========== IMPORTS ====================================================== import copy # ========== CLASS ARTICLE ================================================ class Article: """ A class representing an article, with a title and a list of neighboring articles that are linked to by the article. """ # ===== Article - class methods ======= def __init__(self, article_title): """ Initialize a new Article. """ self._title = article_title self._neighbors = dict() def get_title(self): """ Returns the Article's own title. :return: String of title. """ return copy.copy(self._title) def add_neighbor(self, neighbor): """ Adds an Article to neighbors dict. :param neighbor: Obj of type Article """ if neighbor not in self: self._neighbors[neighbor.get_title()] = neighbor def get_neighbors(self): """ :return: List of neighboring articles. """ return [art_obj for art_obj in self._neighbors.values()] def __repr__(self): """ :return: String of tuple (title, neighbor_list) """ title = self._title neighbor_list = [art_title for art_title in self._neighbors] repr_tup = (title, neighbor_list) return str(repr_tup) def __len__(self): """ :return: Integer size of neighbors dict. """ return len(self._neighbors) def __contains__(self, item): """ :return: True if article is in neighbors dict. (by object) """ return item in self._neighbors.values()
6f27a269d8e70e42e8ae490b529af365981c281c
mitch-io/TAFE
/reverse_txt_file.py
410
4.28125
4
#ask user to enter a string fileName = input('Name of file to reverse: ') #read file into list varible with open(fileName, "r") as f: text = f.readline() print('\nOrignal text...') print(text) i = len(text) - 1 reverseText = str() #iterate over text backwards while i >0: reverseText = reverseText + (text[i]) i -= 1 print('\nText reversed...') print(reverseText) f.close()
3b88e7fe1128ff685a286e69e87f6512cba2185d
Aasthaengg/IBMdataset
/Python_codes/p03447/s859870676.py
100
3.6875
4
X=int(input()) A=int(input()) B=int(input()) money=X money -= A money -= B*(money//B) print(money)
b6da24bde656db7be449fb3ae06d7fa2a3f0864f
saimy019/PythonPrimers
/Inventory Mangement.py
6,765
4.125
4
###################### # Date: 01-05-2020 # Author: Mohammad Nawaid Saify # Stage5 # IT Concept Assignment # Environment: IDLE 3.8, Python 3.8 ########################## #Aarry taken for storing records hardwarestore = [] #Method prompting user to enter another record def doContinue(): isContinue = input("Do you wish to enter another record? (Y/N) ") if isContinue.lower() == "y": return True elif isContinue.lower() == "n": return False else: doContinue() def start(choice): #Imported date and time pre-defined package import datetime from datetime import datetime hid = 0 if choice.upper() == "A": keepAsking = True # Defining list for storing data print ("Hardware Manager") # Starting while loop for user to enter data while keepAsking: nameOfHardwareProduct = input('Hardware: ') if nameOfHardwareProduct == "": print('No record has been recorded.') keepAsking = doContinue() if keepAsking: continue else: menu() yearOfProductPurchased = int(input('Purchase Year: ')) if yearOfProductPurchased == "": print('No record has been recorded.') keepAsking = doContinue() if keepAsking: continue else: menu() productUser = input('User: ') if productUser == "": print('No record has been recorded.') keepAsking = doContinue() if keepAsking: continue else: menu() locationOfUser = input('Location: ') if locationOfUser == "": print ('No record has been recorded. ') elif locationOfUser.lower() not in ('home', 'office'): print ("No record has been recorded. ") keepAsking = doContinue() if keepAsking: continue else: menu() print (nameOfHardwareProduct + " " + "(" + str( yearOfProductPurchased) + ")" + " has been recorded as assigned to " + productUser + " and retained at " + locationOfUser + ".") ctime = datetime.now().strftime("%A,%d.%B %Y %I:%M %p") mtime = datetime.now().strftime("%A,%d.%B %Y %I:%M %p") hardwarestore.append( [nameOfHardwareProduct, yearOfProductPurchased, productUser, locationOfUser, ctime, mtime]) #print (hardwarestore) with open("data.txt", 'w') as output: for i in range(len(hardwarestore)): hstore = hardwarestore[i] #print(str(i + 1) + " . " + hstore[0] + " (" + str(hstore[1]) + ") - " + hstore[2] + ", " + hstore[ #3] + "\n" + "Created: " + str(hstore[4]) + "\n" + "Modified: " + str(hstore[5])) output.write(str(i+1) + " . " + hstore[0] + " (" + str(hstore[1]) + ") - " + hstore[2] + ", " + hstore[3] + "\n"+"Created: " + str(hstore[4]) + "\n"+"Modified: " + str(hstore[5])+ "\n") menu() elif choice.upper() == "L": #print (hardwarestore) if not hardwarestore: print("No Records to display") else: f = open("data.txt") for line in f: print(line) f.close() menu() menu() elif choice.upper() == "C": if not hardwarestore: print("No Records to display") else: ChangeItem = input("Enter Record ID ") cID=int(ChangeItem) filename = "data.txt" contents = [] with open(filename, "r+") as f: frec = f.readlines() if cID > len(frec): print("There are no records with the ID "+str(ChangeItem)) else: for word in frec: field = word.split(" ") if field[0] == ChangeItem: oldUser = field[5] oldLocation = field[6] newUser = str(input("Enter a new user:")) newLocation = str(input("Enter a new location")) field[5] = field[5].replace(oldUser, newUser) field[6] = field[6].replace(oldLocation, newLocation + '\n') contents.append(" ".join(field)) #print(contents) else: contents.append(" ".join(field)) frec = f.readlines() with open(filename, "w+") as f: for line in contents: f.write(line) f.close() menu() elif choice.upper() == "D": DeleteItem = input("Enter Record ID ") DID= int(DeleteItem) filename = "data.txt" with open(filename, "r+") as f: lines=f.readlines() if DID > len(lines): print("No records found") else: for w in lines: words = w.split(" ") if words[0] == DeleteItem: print("You are about to delete " + str(words[2]) + " " + str(words[3])) print ("Do you wish to delete this record " + DeleteItem + "(Y/N)") DeleteItem = int(DeleteItem)-1 verifyDelete = str.lower(input(">")) if verifyDelete == "y": filename = "data.txt" with open(filename, "r") as f: lines = ' '.join([a for i, a in enumerate(f) if i != DeleteItem]) with open(filename, "w") as f: f.write(lines) menu() elif choice.upper() == "E": import csv import pandas as pd df = pd.read_csv("data.txt", delimiter=',') df.to_csv('data.csv') menu() elif choice.upper() == "Q": print ("Thank you") exit(0) else: print("Wrong choice !!. START AGAIN") def menu(): print("Hardware Manager") print ("(A)dd a new record") print ("(L)ist existing records") print ("(C)hange records") print ("(D)elete records") print ("(E)xport to CVS") print("(Q)uit") c = input("Your choice: ") start(c) menu()
a04f2c814dd363c433b07e3246c68aa53e530fc3
Nik-Kobzev/foundation_python-language
/Домашнее задание урок 1/Task number 5.py
622
3.921875
4
proceeds = int(input('Введите значение выручки: ')) costs = int(input('Введите значение издержки: ')) if proceeds > costs: print('Фирма работает на прибыль') print(f'Рентабельность составила: {proceeds/costs}') count_fellow_worker = int(input('Введите кол-во сотрудников в фирме: ')) print(f'Прибыль фирмы в расчете на одного сотрудника: {(proceeds - costs) / count_fellow_worker}') else: print('Фирма работает на убыток')
087576bf863eb4a4bf974ebc798a0b343f6fb7cd
hxxtsxxh/codewithmosh-tutorials
/Tutorial6 String Methods.py
894
4.59375
5
course = 'Python for beginners' # to calculate the number of characters in this string, we use a method called "len." print(len(course)) # now if we want to make our text in course all lowercase or uppercase, we use the dot operator. print(course.lower()) # you can also do all uppercase print(course.upper()) # Reminder: these changes wont change our original string. print(course) # lets say we want to know at what position is a certain letter. To do this, do the following command. print(course.find('P')) # this gives us an output of 0 as it is the "0th" position in the sentence. # if we want to replace a certain part of a string, then we pass the course.replace command as shown print(course.replace('beginners', 'Absolute Beginners')) # even this will not change our original string print(course) print('Python' in course) # this will output whether the word, Python is in our text.
4e491b996a84173ba8dde1d1e4eb75c0917d93fb
susanshen/inf1340_2015_asst2
/exercise1.py
564
4
4
#!/usr/bin/env python """ Assignment 2, Exercise 1, INF1340, Fall, 2015. Pig Latin This module converts English words to Pig Latin words """ __author__ = 'Paniz Pakravan' __email__ = "p.pakravan@mail.utoronto.ca" __copyright__ = "2015 Paniz Pakravan" __date__ = "06 November 2015" VOWELS = ["a", "e", "i", "o", "u"] def pig_latinify(word): """ Describe your function :param : :return: output_word :raises: """ first_letter = word[0] if first_letter in VOWELS: # case a) output_word = word + "yay" return output_word print(pig_latinify("apple"))
1307ab32de39faf0ff4ee85740860aa8457b6ff9
sunny809/leetcode-solutions
/leetcode/LongestSubstring/solution_test.py
1,317
3.765625
4
import unittest; from leetcode.LongestSubstring.solution import Solution # from https://leetcode-cn.com/problems/add-two-numbers/description/ class SolutionTest(unittest.TestCase): def test_basic(self): input = "abcabcbb" so = Solution() length = so.lengthOfLongestSubstring(input) self.assertEqual(3, length) def test_1(self): input = "bbbbbb" so = Solution() length = so.lengthOfLongestSubstring(input) self.assertEqual(length, 1) def test_2(self): input = "pwwkew" so = Solution() length = so.lengthOfLongestSubstring(input) self.assertEqual(length, 3) def test_3(self): input = "aab" so = Solution() length = so.lengthOfLongestSubstring(input) self.assertEqual(length,2) def test_4(self): input = "dvdf" so = Solution() length = so.lengthOfLongestSubstring(input) self.assertEqual(3, length) def test_5(self): input = "jbpnbwwd" so = Solution() length = so.lengthOfLongestSubstring(input) self.assertEqual(4, length) def test_6(self): input = "bpfbhmipx" so = Solution() length = so.lengthOfLongestSubstring(input) self.assertEquals(7, length)
86a9e9a2c98083e0e9a2dfd2bea41eea88186d9a
SharanyaAntony/Python-exercise
/dupBy7.py
397
3.703125
4
#4.day 5 from array import * ar =array('i',[12, 90, 34, 78, 11, 90]) for yet in ar:print(yet) num=int(input("enter the num")) def findDup(start=0,end=len(ar)): if start<=end: if ar[start] == ar[start+1]: print(ar[start]," is duplicate") if ar[start]%num: print(ar[start]) start += 1; findDup(start, end) findDup() print()
c8e647a35146a47e328d728d48b497c624b6a79a
docmarionum1/HackerRank
/algorithms/search/circle.py
309
3.53125
4
from math import sqrt, ceil for _ in range(int(raw_input())): r,k = map(int, raw_input().split()) c = 1 if sqrt(r).is_integer() else 0 for x in range(1,int(ceil(sqrt(r)))): if sqrt(r - x**2).is_integer(): c += 1 print "possible" if 4*c <= k else "impossible"
2312a4f7458fb149e26380606d7b28f60703780b
Venhoff-cpu/Python_exercises
/Other/find_missing.py
811
3.796875
4
def find_missing(li, n): if not isinstance(n, int): return 'Wartośc n musi być liczbą całkowitą dlodatnią' if n <= 1: return 'Wartośc n musi być liczbą całkowitą dlodatnią większą od 1.' if not isinstance(li, list) and isinstance(li, str): return 'Do przeszukania należy podać listę' if not all(isinstance(item, int) for item in li): return 'Lista musi składać się z liczb całkowitych dodatnich.' if max(li) > n or min(li) < 1: return 'Lista poza przedziałem 1 - n' n_range = [i for i in range(1, n+1)] return [missing for missing in n_range if missing not in li] if __name__ == '__main__': n = 10 for_finding_missing = [1, 3, 4, 6] print(find_missing(for_finding_missing, n))
8e8367b2327be4ff7224892b8cc7e757c78bb2e6
denemorhun/Python-Problems
/Hackerrank/Strings/split_string_into_even_odd.py
289
4
4
# split a string into even and odd indices def split_string_into_even_odd(s): # have to use stride s[0:-1:2], start at 0, jump 2 print(s[0::2], s[1::2]) def main(): split_string_into_even_odd("Hacker") split_string_into_even_odd("Rank") if __name__ == '__main__': main()
5f267ec90e978c528ea6f57d85529c6e2c460f5f
Matuiss2/URI-ONLINE
/1600- 1999/1957.py
178
4.125
4
numero = int(input()) # Tranforma um n° dec em hex usando {:x}, o upper é para retornar como maiúsculas os valores hex que são letras print("{:x}".format(numero).upper())
1b68f7e884e1760600adfcdfd8dc49ac1dd3441c
Taycode/cracking-the-coding-interview-solutions
/chapter1_arrays_and_strings/is_permutation_1_2.py
564
3.90625
4
""" Given two strings, write a method to decide if one is a permutation of the other """ def is_permutation(first_string, second_string): """ :param first_string: string :param second_string: string :return: boolean """ the_dict = {} for _ in first_string: if _ not in the_dict.keys(): the_dict[_] = 1 else: the_dict[_] += 1 for _ in second_string: if _ not in the_dict.keys(): return False else: the_dict[_] -= 1 if max(list(the_dict.values())) > 0: return False else: return True print(is_permutation('dogs', 'gosd'))
406b4b1f38f3eae373cd437d5882aa4fc499c18e
kritikyadav/Practise_work_python
/simple-basic/11.py
116
3.59375
4
a=int(input("devisor= ")) b=int(input("divident= ")) c=a//b ##where c is qutient d=a-b*c print("Reminder= ",d)
fbc694ba152a573ab732fda23277123016fa28af
anshulkamath/gopher-world-source
/classes/GeneticAlgorithm.py
6,334
3.515625
4
import numpy as np import time from typing import Callable from classes.Encoding import Encoding import geneticAlgorithm.fitnessFunctions as functions import geneticAlgorithm.library as geneticLib class GeneticAlgorithm(): ''' Class can be used as a template for creating a genetic algorithm. The user must provide self-consistent initialization, selection, recombination, and mutation functions, as well as a valid encoder instance. Then, the run() method (with the respective arguments) will generate a trap using the genetic algorithm instance created and return relevant data. ''' def __init__(self, init_pop_func: Callable = None, select_func : Callable = None, mutat_func : Callable = None, cross_func : Callable = None, encoder : Encoding = None): self.init_pop_func = init_pop_func if init_pop_func else geneticLib.initializePopulation self.select_func = select_func if select_func else geneticLib.selectionFunc self.mutat_func = mutat_func if mutat_func else geneticLib.mutationFunc self.cross_func = cross_func if cross_func else geneticLib.crossoverFunc self.encoder = encoder if encoder else Encoding() def run(self, functionName, maxGenerations = 10000, showLogs = True, trial = None, barData={}, writer=None, startPopulation=None): """ Finds a near-optimal solution in the search space using the given fitness function Returns a 3-tuple of (finalPopulation, bestTrap (encoded), bestFitness) """ fitnessFunc = functions.getFunctionFromName(functionName) fitnesses = np.array(20 * [0]) population = np.array([]) if fitnessFunc == functions.getBinaryDistance: functions.targetTrap = geneticLib.generateTrap(self.encoder) # Destructure population into CSV format getWriteData = lambda population, fitnesses : [ [ trial, generation, trap, functionName, round(fitnesses[i], 4), round(functions.getLethality(trap, self.encoder), 4), round(functions.getCoherence(trap, self.encoder), 4), round(functions.getCombined(trap, self.encoder), 4), ] for i, trap in enumerate(population) ] # the format of startPopulation (take a list of traps and encode them) # trap format found in legacy.designedTraps # startPopulation = [encode(trap) for trap in [trap1, trap2, ...]] if startPopulation: print('A starting population has been found.') # Sampling the (encoded) population until we get one non-zero member # (unless we provide a starting population) while (not startPopulation and np.count_nonzero(fitnesses) == 0): population = geneticLib.initializePopulation(self.encoder) fitnesses = fitnessFunc(population, self.encoder) # Recalculate frequencies fitnesses = fitnessFunc(population, self.encoder) if startPopulation: print('A starting population has been found.') print(f'There are {len(startPopulation)} individuals in the starting population') print( f'The average coherence of these traps is \ {np.average([functions.getCoherence(x) for x in startPopulation])}' ) print( f'The average lethality of these traps is \ {np.average([functions.getLethality(x) for x in startPopulation])}' ) generation = 0 startTime = lastTime = time.time() writeData = getWriteData(population, fitnesses) currMax = np.argmax(fitnesses) maxFitness, bestTrap = fitnesses[currMax], population[currMax] while generation < maxGenerations: if showLogs and (generation % 50 == 0): print(f"Generation {generation}:") print("Current Max fitness\t: {}".format(round(max(fitnesses), 3))) print("Global Max fitness\t: {}".format(round(maxFitness, 3))) print("Lap Time\t\t: {}".format(round(time.time() - lastTime, 4))) print("Total Time\t\t: {}".format(round(time.time() - startTime, 4))) print("------------------------") print() # Set last time lastTime = time.time() # Creating new population using genetic algorithm newPopulation = [] for _ in range(len(population)): parent1, parent2 = self.select_func(population, fitnesses) child = self.cross_func(parent1, parent2) childMutated = self.mutat_func(self.encoder, child) newPopulation.append(childMutated) # Calculating new fitnesses and updating the optimal solutions fitnesses = fitnessFunc(newPopulation, self.encoder) population = newPopulation currMax = np.argmax(fitnesses) if fitnesses[currMax] > maxFitness: maxFitness = fitnesses[currMax] bestTrap = newPopulation[currMax] generation += 1 # Add new data to the writeData list if writer: writeData.extend(getWriteData(population, fitnesses)) if barData: barData['counter'] += 1 numBars, maxSteps = barData['numBars'], barData['maxSteps'] modulo = maxSteps // numBars if numBars <= maxSteps else 1 if barData['counter'] % modulo == 0: barData['bar'].next(n=max(1, numBars / maxSteps)) if writer and writeData: writer.writerows(writeData) if showLogs: print(f"Generation {generation}:") print("Current Max fitness\t: {}".format(round(max(fitnesses), 3))) print("Global Max fitness\t: {}".format(round(maxFitness, 3))) print("Lap Time\t\t: {}".format(round(time.time() - lastTime, 4))) print("Total Time\t\t: {}".format(round(time.time() - startTime, 4))) print("------------------------") print() return np.array(population), bestTrap, maxFitness
f88b7d9ec416042d17f7b4f3c40581abb1fed346
jh-lau/leetcode_in_python
/01-数据结构/数组/1128.等价多米诺骨牌对的数量.py
1,392
3.765625
4
""" @Author : liujianhan @Date : 2021/1/26 10:05 @Project : leetcode_in_python @FileName : 1128.等价多米诺骨牌对的数量.py @Description : 给你一个由一些多米诺骨牌组成的列表 dominoes。 如果其中某一张多米诺骨牌可以通过旋转 0 度或 180 度得到另一张多米诺骨牌,我们就认为这两张牌是等价的。 形式上,dominoes[i] = [a, b] 和 dominoes[j] = [c, d] 等价的前提是 a==c 且 b==d,或是 a==d 且 b==c。 在 0 <= i < j < dominoes.length 的前提下,找出满足 dominoes[i] 和 dominoes[j] 等价的骨牌对 (i, j) 的数量。   示例: 输入:dominoes = [[1,2],[2,1],[3,4],[5,6]] 输出:1 提示: 1 <= dominoes.length <= 40000 1 <= dominoes[i][j] <= 9 """ from typing import List class Solution: # 284ms, 24.3MB @staticmethod def num_equiv_domino_pairs(dominoes: List[List[int]]) -> int: num = [0] * 100 res = 0 for x, y in dominoes: val = 10 * x + y if x > y else 10 * y + x res += num[val] num[val] += 1 return res if __name__ == '__main__': test_cases = [ [[1, 2], [2, 1], [3, 4], [5, 6]], [[1, 2], [2, 1], [3, 4], [4, 3]], ] for tc in test_cases: print(Solution.num_equiv_domino_pairs(tc))
584a8c92dbfbb94427a9e70ea9ffbfb3ac41ab38
VikasRana/age-in-seconds
/ais.py
1,653
4.3125
4
import time print("Hello and welcome to my 'age in seconds' calculator! Please press enter to continue.") time.sleep(2) user_years = input("Press Enter Now") # user_info_asked user_years = input("Total Years : ") user_days = input("Total Extra Days : ") user_hours = input("Total Extra Hours : ") user_minutes = input("Total Extra Minutes : ") # some_so-called_humorus_statements print("Please wait for few secs while I calculate your age!") time.sleep(2) print("This will take time.") time.sleep(2) print("Damn! Some more time.") time.sleep(2) print("Unfortunately I'm not fast :(") time.sleep(2) print("Almost there?") time.sleep(4) print("Nah. Don't think so.") time.sleep(2) print("Hurray, I'm done here.") time.sleep(2) print("Pretty impressive, hun? What do you eat?") time.sleep(3) # integer_conversion_of_data int(user_years) int(user_days) int(user_hours) int(user_minutes) # conversion_in_seconds years_in_seconds = int(user_years) * 365.25 * 24 * 60 * 60 days_in_seconds = int(user_days) * 24 * 60 * 60 hours_in_seconds = int(user_hours) * 60 * 60 minutes_in_seconds = int(user_minutes) * 60 # total_age total_seconds = years_in_seconds + days_in_seconds + hours_in_seconds + minutes_in_seconds print('\n') print('\n') print("You") time.sleep(1) print("have") time.sleep(1) print("successfully") time.sleep(1) print("lived") time.sleep(1) print("{} plus few more seconds you wasted calculating. Hehe.".format(total_seconds)) time.sleep(5) print('\n') print('\n') print("An idiotic bot at its best! Hun???") time.sleep(3) print('\n') print('\n') print("Credits: VikasRana")
d28b61e5764c561b594e0723c43f5c56a8591f1e
shambhand/pythontraining
/material/code/functional_programming/yield_demo.py
260
3.734375
4
#! /usr/bin/python3 def gen_squares (N): for i in range (N): yield i ** 2 def main (): for i in gen_squares (10): print ("i:", i, sep='') x = gen_squares (10) for j in range (10): print (next (x)) main ()
5eb786ff211d96f1cf082c78b69cf7ef1c549f53
erkang123/fullstack_s2
/week4/day3/闭包.py
378
3.5
4
#__author:"HYK" #DATE:2018/4/21 def outer(): x = 10 def inner(): #条件一 inner就是内部函数 print(x) #条件二 外部环境的一个变量 return inner #结论 内部函数inner就是一个闭包 # outer()() f = outer() f() #inner() #局部变量,全局无法调用 # 关于闭包:闭包 = 内部函数 + 定义函数时的环境
226c40a29fbe853edc9afcf0e41cd3ecf99a8b83
WildesPiva/napp_academy
/semana15/candidatura/projeto/separate/generate_data.py
840
3.75
4
from abc import ABC, abstractmethod from pathlib import Path class AbstractGenerateData(ABC): """ Class to generate final file data ---------- Parameters path_file : str, path object or file-like object Any valid string path is acceptable. """ def __init__(self, path_file): if not Path(path_file).is_dir(): raise Exception("Invalid file path") self.path_file = path_file @abstractmethod def generate_data(self): pass class GenerateDataCsv(AbstractGenerateData): def generate_data(self, file_name, data, header=None): """ Generate csv with final data """ with open(f'{self.path_file}/{file_name}.csv', 'w') as csvfile: if header: csvfile.write(header) csvfile.writelines(data) return True
e2a68a784b6946592860eed8c916d08532aaa8c8
evizcarra-unix/module-1
/Simple Program.py
1,186
4.09375
4
""" Author: Ezra Vizcarra Topic: Simple Program Purpose: Nothing too serious with this program. This is to showcase and verify the synchronized process with VS Code and GitHub. """ hello = 'Hello World!' #Defined functions for each set {regular, uppercase, lowercase}. def display_regular(message): print(message) def display_uppercase(message): new_message = message.upper() print(new_message) def display_lowercase(message): new_message = message.lower() print(new_message) #Visual welcome screen to User with a brief intro. print('----Hello World!----i\nThis is a simple testing sentence formatter:\n' ' 1. Prints regular\n 2. Prints uppercase\n 3.Prints lowercase') #Skips a line to give it a space between both prints, this requires User to type something. user_message = input('\nWhat would you like to test? ') #Calls the functions and prints them as listed on intro in line 21. display_regular(user_message) display_uppercase(user_message) display_lowercase(user_message) #Spaces between displayed output. print() #Calls the function to alternate the hard-coded print. display_regular(hello) display_uppercase(hello) display_lowercase(hello)
b4bbd1a42ef4e37508294bc2027000d2e1f7cca5
marcusau/pyworkforce
/pyworkforce/shifts/utils.py
368
3.75
4
def check_positive_integer(name, value): if value <= 0 or not isinstance(value, int): raise ValueError(f"{name} must be a positive integer") else: return True def check_positive_float(name, value): if value <= 0 or not isinstance(value, float): raise ValueError(f"{name} must be a positive float") else: return True
3a7d0ff164312d5565538303a44969ca84a592bf
hussain-bim/pythonpdf
/rotatepdf.py
742
3.515625
4
import PyPDF2 from PyPDF2 import PdfFileReader, PdfFileWriter import os import glob def pdf_rotate(path): fname = os.path.splitext(os.path.basename(path))[0] pdf = PdfFileReader(path) pdf_writer = PdfFileWriter() for page in range(pdf.getNumPages()): new_page = pdf.getPage(page) new_page.rotateClockwise(270) pdf_writer.addPage(new_page) with open('C:\\Users\\Admin\\Downloads\\pdfmergeorsplit\\' + fname + '.pdf', 'wb') as out: pdf_writer.write(out) print('Rotated: {}'.format(fname)) if __name__ == '__main__': paths = glob.glob('C:\\Users\\Admin\\Downloads\\pdfmergeorsplit\\*.pdf') paths.sort() for path in paths: pdf_rotate(path)
47de68cb420deed327f1ad774db5984282e54a6a
allanCordeiro/pacman-pygame
/pacman.py
715
3.578125
4
import pygame pygame.init() # constantes AMARELO = (255, 255, 0) PRETO = (0, 0, 0) RAIO = 20 VELOCIDADE = 1 tela = pygame.display.set_mode((640, 480), 0) x = 10 y = 10 vel_x = VELOCIDADE vel_y = VELOCIDADE while True: #regras x += vel_x y += vel_y if x + RAIO > 640: vel_x = -VELOCIDADE if x - RAIO < 0: vel_x = VELOCIDADE if y + RAIO > 480: vel_y = -VELOCIDADE if y - RAIO < 0: vel_y = VELOCIDADE #desenho tela.fill(PRETO) pygame.display.update() pygame.draw.circle(tela, AMARELO, (int(x), int(y)), RAIO, 0) pygame.display.update() #eventos for e in pygame.event.get(): if e.type == pygame.QUIT: exit()
48106e3efde4395dde8d0d75706dec91a017754a
austin-bowen/sharnn
/sharnn/activation.py
3,596
3.671875
4
"""Contains several common activation functions.""" import numpy as np class Activation: """Base class for representing an activation and its first derivative.""" def __call__(self, x): return self.function(x) def __str__(self) -> str: return self.__class__.__name__ def function(self, x): """The activation function.""" raise NotImplementedError('"function" method needs to be overridden.') def prime(self, x): """The first derivative of function() w.r.t. "x".""" raise NotImplementedError('"prime" method needs to be overridden.') def check_prime(self, checks=1000, epsilon=1e-7, min_value=-100, max_value=100): """Checks if prime() appears to be the derivative of function(). Derivative estimates are made "checks" times using this formula, with x randomly generated in the range of [min_value, max_value): y_prime_est = (self(x+epsilon) - self(x-epsilon)) / (2*epsilon) The maximum difference between y_prime_est and self.prime(x) is returned. If the value is "too high", you may have a problem with your prime(). """ # Choose x in range [min_value, max_value) x = np.random.random((1, checks)) * (max_value - min_value) + min_value y_prime_est = (self(x + epsilon) - self(x - epsilon)) / (2 * epsilon) return np.max(np.abs(self.prime(x) - y_prime_est)) class Identity(Activation): """Identity""" def function(self, x): return x def prime(self, x): try: return np.ones(x.shape) except AttributeError: return 1.0 identity = Identity() class LeakyReLU(Activation): """Leaky Rectified Linear Unit""" def __init__(self, slope): """slope must be in range [0, 1).""" Activation.__init__(self) if (slope < 0) or (slope >= 1): raise ValueError('slope must be in range [0, 1).') self.slope = slope def __str__(self) -> str: return f'{self.__class__.__name__}(slope={self.slope})' def function(self, x): return np.maximum(self.slope * x, x) def prime(self, x): # Assume x is an instance of np.ndarray try: prime = (x > 0).astype('float') if self.slope: prime[prime == 0.0] = self.slope # Otherwise, treat as single except AttributeError: prime = 1.0 if (x > 0) else self.slope return prime class ReLU(LeakyReLU): """Rectified Linear Unit""" def __init__(self): """""" LeakyReLU.__init__(self, 0.0) def __str__(self) -> str: return Activation.__str__(self) relu = ReLU() class Sigmoid(Activation): """Sigmoid""" def function(self, x): return 1 / (1 + np.exp(-x)) def prime(self, x): x = self(x) return x * (1 - x) sigmoid = Sigmoid() class Tanh(Activation): """Hyperbolic Tangent""" def function(self, x): return np.tanh(x) def prime(self, x): return 1 - np.power(np.tanh(x), 2) tanh = Tanh() class Sin(Activation): def function(self, x): return np.sin(x) def prime(self, x): return np.cos(x) class Sin2(Activation): def function(self, x): return 0.5 * np.power(np.sin(x), 2) def prime(self, x): return np.sin(x) * np.cos(x) class Test0(Activation): def function(self, x): return x / (1 + np.sign(x) * x) def prime(self, x): return np.power(1 + np.sign(x) * x, -2)
16a231a8ed56e0121d17e85130bdf22a5791ae93
jaimitoconfig/udemy_flaskapi
/models/store.py
1,868
3.953125
4
""" Store Model. NOTE: A resource will typically need to extract information for a model. Make the models first. 06/27/2019 Jaime Quintero """ from db import db class StoreModel(db.Model): __tablename__ = 'stores' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) # This is considered a back reference, which checks to see what items are assigned to what store. # items is a list of ItemModel objects. A many to one relationship. # lazy='dynamic' tells SQLAlchemy to not create objects, yet. .all() will take care of that. # That makes items a query builder. items = db.relationship('ItemModel', lazy='dynamic') # In ItemModel the foreignKey() checks for what is related. def __init__(self, name): self.name = name def store(self): """Simply returns a dictionary representation of the store, with it's items. """ # .all() will fetch all the items since items is a query builder. # It's possible that this is slower since it's looking into the data base. # Instead of saving all objects and then iterating. # That's how SQLAlchemy works—we use self to refer to the content related to this particular object return {'name': self.name, 'items': [item.item() for item in self.items.all()]} # Has to be self.items. def save_to_db(self): """Saving an store into the DB. """ db.session.add(self) db.session.commit() def delete_from_db(self): """Deleting a store in the DB. """ # Remember that the store can not have items linked if deleting. db.session.delete(self) db.session.commit() @classmethod def find_by_name(cls, name): """This will find the store specified by the name param in DB using SQLAlchemy. """ return cls.query.filter_by(name=name).first()
d35d48933ec29ae8bed7cdcfdfd101a4f077116f
SandeshUpadhyaya/Machine-Learning
/LinearRegression.py
1,689
3.71875
4
import pandas as pd import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split #Initializin the values of X and Y X = np.random.rand(100,1) Y = np.random.rand(100,1) plt.scatter(X,Y) plt.show() #Adding one to X X = np.concatenate((np.ones((100,1)),X),axis=1) #splitting data into train and test set X_train,X_test,y_train,y_test = train_test_split(X,Y,test_size=0.2,random_state=1) #defining the hypothesis def hypothesis(x,w): return np.dot(x,w) #defining the error def error(x,y,w): return (hypothesis(x,w) - y) #defining the cost function def computeCost(x,y,w): m = len(y) J = (1/(2*m) * np.sum(error(x,y,w)**2)) return J #Initializing the weights w = np.random.rand(X_train.shape[1]).reshape(2,1) #hypothesis for data before training plt.scatter(X_train[0:,1:], y_train,color = "m", marker = "o", s = 30) # predicted response vector y_pred = hypothesis(X_train,w) # plotting the regression line plt.plot(X_train[0:,1:], y_pred, color = "g") # putting labels plt.xlabel('x') plt.ylabel('y') # function to show plot plt.show() #gradient descent implementation def gradientDescent(x,y,w,lr,iter): train_loss = [] m = len(y) for i in range(iter): w = w - ((lr/m) * np.sum(error(x,y,w)*x)) J = computeCost(x,y,w) train_loss.append(J) plt.plot(range(iter),train_loss) plt.show() print("Starting training loss: ",train_loss[0],"Last training loss ",train_loss[-1]) print("Train loss is ",train_loss[0]-train_loss[-1]) return w #gradient descent output w1 = gradientDescent(X_train,y_train,w,0.01,700)
65dcb4af29d4c471313359a0ed52006721293671
lucaseduardo101/MetodosII
/NewtonCotes/NewtonCotes.py
3,308
3.8125
4
# -*- coding: utf-8 -*- import sys import leitura from math import sqrt, exp, sin, cos #arq = sys.argv[1] #l = leitura.ler(arq) #falta receber esses valores do arquivo txt #n=l[0]#recebe o valor de n #i=l[1]#recebe o numero da funcao escolhida #a=l[2][0] #recebe o limite inferior #b=l[2][1] #recebe o limite superior n=2 #recebe o valor de n i=6 #recebe o numero da funcao escolhida a= -1.0 #recebe o limite inferior b= 1.0 #recebe o limite superior # Escolha da funcao # ----------------------------------------- # | indices | # | # ----------------------------------------- # | 1 | 1/sqrt(x) | # | 2 | 1/sqrt(1-x^2) | # | 3 | 2x^3 + 3x^2 + 6x + 1 | # | 4 | 1 - x -4x^3 + 2x^5 | # | 5 | 4/(1 + x^2) | # ----------------------------------------- print "funcao numero:",i #selecionaFunc(funcao) def f(indice,x): if (indice == 0): return (2*x**3 + 3*x**2 + 6*x+1) if (indice == 1): return (1/sqrt(x)) elif (indice == 2): return (1/sqrt(1-x**2)) elif (indice == 3): return (2 * x**3 + 3 * x**2 + 6 * x + 1) elif (indice == 4): return (1 - x -4 * x**3 + 2 * x **5) elif (indice == 5): return (4/(1 + x**2)) elif (indice == 6): return (1 / sqrt( 1 - x**2 )) else: print ('Funcao nao definida na tabela.') exit() #Newton Cotes fechada de grau = 1 def newtonCotesFechadaGrau1(): return (b-a)*(f(i,a) + f(i,b))/2 #print "valor calculado obtido pela frmula Newton Cotes fechada de grau 1: ",newtonCotesFechadaGrau1() #Newton Cotes fechada de grau = 2 def newtonCotesFechadaGrau2(): return (b-a)*(f(i,a) + (4*f(i,(a+b)/2)) + f(i,b))/6 #print "valor calculado obtido pela frmula Newton Cotes fechada de grau 2: ",newtonCotesFechadaGrau2() #Newton Cotes fechada de grau = 3 def newtonCotesFechadaGrau3(): return (b-a)*(f(i,a) + (3*f(i,(2*a+b)/3)) + (3*f(i,(a+2*b)/3)) + f(i,b))/8 #print "valor calculado obtido pela frmula Newton Cotes fechada de grau 3: ",newtonCotesFechadaGrau3() #Newton Cotes fechada de grau = 4 def newtonCotesFechadaGrau4(): return (b-a)*(f(i,a) + (32*f(i,(3*a+b)/4)) + (12*f(i,(a+b)/2)) + (32*f(i,(a+3*b)/4)) + f(i,b))/90 #print "valor calculado obtido pela frmula Newton Cotes fechada de grau 4: ",newtonCotesFechadaGrau4() #Newton Cotes aberta de grau = 1 def newtonCotesAbertaGrau1(): aux= (b-a)/3; return (b-a)*(f(i,a+aux) + f(i,a+(2*aux)))/2; print "valor calculado obtido pela frmula Newton Cotes aberta de grau 1: ",newtonCotesAbertaGrau1() #Newton Cotes aberta de grau = 2 def newtonCotesAbertaGrau2(): h=(b-a)/4; return (b-a)*(2*f(i,a+h) - f(i,a+2*h) + 2*f(i,a+3*h))/3; print "valor calculado obtido pela frmula Newton Cotes aberta de grau 2: ",newtonCotesAbertaGrau2() #Newton Cotes aberta de grau = 3 def newtonCotesAbertaGrau3(): h=(b-a)/5; return (b-a)*(11*f(i,a+h) + f(i,a+2*h) + f(i,a+3*h)+ 11*f(i,a+4*h))/24; print "valor calculado obtido pela frmula Newton Cotes aberta de grau 3: ",newtonCotesAbertaGrau3() #Newton Cotes aberta de grau = 4 def newtonCotesAbertaGrau4(): h=(b-a)/6; return (b-a)*(11*f(i,a+h) - 14*f(i,a+2*h) + 26*f(i,a+3*h) - 14*f(i,a+4*h) + 11*f(i,a+5*h))/20 print "valor calculado obtido pela frmula Newton Cotes aberta de grau 4: ",newtonCotesAbertaGrau4()
1747425bbcfcfed44bb206cc53517f2dd1ff0647
maguas01/hackerRank
/pStuff/Reverse_a_linked_list.py
750
4.25
4
''' You’re given the pointer to the head node of a linked list. Change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. ''' """ Reverse a linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def Reverse(head) : curr = head nextNode = None prev = None while( curr != None ) : nextNode = curr.next curr.next = prev prev = curr curr = nextNode head = prev return head
65390b7e003d11c59684d98679e34e3a54171b6d
desmayer/python
/condition.py
592
3.96875
4
a=1 value = input('Enter a Number:') while value != int: print('\nNot A Number') value = input('Enter a number:') b=int(input) ''' \n NEW LINE ''' ''' 'One' [TRUE] if (var == 1) else [FALSE] 'Not One' ''' print('\nVariable a is :','One' if ( a== 1) else 'Not One') print('Variable a is :','Even' if ( a % 2 == 0) else 'Odd') print('\nVariable b is :','One' if ( b== 1) else 'Not One') print('Variable b is :','Even' if ( b % 2 == 0) else 'Odd') max = a if (a>b) else b print('\nGreater Value Is:',max) print('\nFirst Number:',a) print('Second Number:',b) print('\n',a,'x',b,'=',a*b)
d2395a0a3454c8cf3cefbc5be281c8182819681d
RakeshKumar045/DataStructures_Algorithms_Python
/Sorting/Merge sort.py
833
3.765625
4
arr = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0] def mergesort(arr): if len(arr) == 1: return arr length = len(arr) mid = length // 2 left = arr[:mid] right = arr[mid:] print('Left {}'.format(left)) print('Right {}'.format(right)) return merge(mergesort(left), mergesort(right)) def merge(left, right): result = [] leftindex = 0 rightindex = 0 while leftindex < len(left) and rightindex < len(right): if left[leftindex] < right[rightindex]: result.append(left[leftindex]) leftindex += 1 else: result.append(right[rightindex]) rightindex += 1 print(left, right) print(result + left[leftindex:] + right[rightindex:]) return result + left[leftindex:] + right[rightindex:] x = mergesort(arr) print(x)
83dd97230eca7e3d86c4c10765109a34b4aa236b
Priyanshu-server/Python-Beginner-to-Advance
/PrimeNumberFinder/PrimeNumberFinder.py
199
4.125
4
num = int(input("Enter your number :: ")) for i in range(2,num): output = num%i if output == 0: print("Number is not prime") break; else: print("Number is Prime")
b3dd3ef32c336b87d2d9e882c57f0b5dc5611b34
tzielaski/python_szkolenie
/oop_addressbook_operators.py
857
3.875
4
from dataclasses import dataclass @dataclass() class Contact: name: str addresses: list = None def __str__(self): return f'{self.__dict__}' def __iadd__(self, other): if isinstance(other, Address): self.addresses.append(other) return self def __contains__(self, item): if isinstance(item, Address): return item in self.addresses @dataclass class Address: location: str def __repr__(self): return f'{self.__dict__}' contact = Contact(name='José', addresses=[Address(location='JPL')]) contact += Address(location='Houston') contact += Address(location='KSC') print(contact) # {'name': 'José', 'addresses': [{'city': 'JPL'}, {'city': 'Houston'}, {'city': 'KSC'}]} if Address(location='Bajkonur') in contact: print(True) else: print(False) # False
a8d0484cfec464cd3c2591317489d6a452ad9a96
copsahl/PyCiphers
/ciphers.py
3,628
4.125
4
import string def rot13(message, rot): '''Implementation of the ROT13 Cipher using ASCII Decimal Values''' encryptedMsg = '' for char in message: count = rot if " " in char: encryptedMsg += ' ' # Capital Letters elif ord(char) >= 65 and ord(char) <= 90: if ord(char) + count > 90: diff = 90 - ord(char) count = count - diff encryptedMsg += chr(65 + (count - 1)) else: encryptedMsg += (chr(ord(char) + rot)) # Lowercase Letters elif ord(char) >= 97 and ord(char) <= 122: if ord(char) + count > 122: diff = 122 - ord(char) count = count - diff encryptedMsg += chr(97 + (count - 1)) else: encryptedMsg += (chr(ord(char) + rot)) # Special Characeters else: encryptedMsg += char return encryptedMsg def rot47(message, rot): '''Implementation of the ROT47 Cipher using ASCII Decimal Values 33-126''' encryptedMsg = '' for char in message: count = rot if " " in char: encryptedMsg += ' ' elif ord(char) in range(33, 127): if ord(char) + count > 126: diff = 126 - ord(char) count = count - diff encryptedMsg += chr(33 + (count - 1)) else: encryptedMsg += (chr(ord(char) + rot)) else: encryptedMsg += char return encryptedMsg def caesarCipher(message, shift): '''Implementation of the Caeser Cipher''' if shift % 26 == 0: # Raise error if shift won't work raise ValueError("Shift value will not encode text") message = message.lower().replace(" ", '') # Remove spaces in message alphabet = string.ascii_lowercase # Create list of alphabet shiftAlphabet = alphabet[shift:] + alphabet[:shift] # Create shifted list hiddenMsg = '' for x in range(0, len(message)): for y in range(0, len(alphabet)): if message[x] == alphabet[y]: # If index in alphabet = letter in msg hiddenMsg += shiftAlphabet[y] # Use that index in shifted alphabet return hiddenMsg '''Affine Cipher''' affineDic = string.ascii_uppercase def affineEncode(message, aKey, bKey): '''Implementation of the affine cipher''' global affineDic message = message.upper() charValues = [] encodedMsg = '' for char in message: for val in range(0,len(affineDic)): if char == affineDic[val]: charValues.append(val) for value in charValues: num = ((aKey * value) + bKey) % 26 for val in range(0, len(affineDic)): if num == val: encodedMsg += affineDic[val] return encodedMsg def morseCode(message, decode): '''Implementation of Morse Code''' morseDic = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', '.':'.-.-.-', ',':'--..--', '?':'..--..', '/':'-..-.', '@':'.--.-.', ' ':'/' } message = message.upper() encodedMsg = '' if decode == False: for char in message: for k,v in morseDic.items(): if char == k: encodedMsg += (str(v) + " ") elif decode == True: letters = message.split(" ") for x in range(0, len(letters)): for k,v in morseDic.items(): if letters[x] == v: encodedMsg += k return encodedMsg
7f3dc29caf530eb6e8d92a687c7c1281c3ccded5
SilviaAmAm/tf_hackathon
/linear_regression.py
2,071
3.984375
4
""" This script shows how to do linear regression with tensorflow. """ import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns # Generating some sample data train_X = np.array([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1]) train_Y = np.array([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3]) num_samples = train_X.shape[0] # Parameters learning_rate = 0.01 iterations = 2000 ### ------ ** Creating the graph ** ------- # Placeholders - where the data can come into the graph X = tf.placeholder(tf.float32, [None]) Y = tf.placeholder(tf.float32, [None]) # Creating the parameters for y = mx + c c = tf.Variable(np.random.randn(), name='c') m = tf.Variable(np.random.randn(), name='m') # Creating the model: y = mx + c model = tf.add(c, tf.multiply(m, X)) # Creating the cost function cost_function = 0.5 * (1.0/num_samples) * tf.reduce_sum(tf.pow(model - Y, 2)) # Defining the method to do the minimisation of the cost function optimiser = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function) ### -------- ** Initialising all the variables ** -------- init = tf.global_variables_initializer() ### -------- ** Starting the session ** ---------- with tf.Session() as sess: sess.run(init) for i in range(iterations): sess.run(optimiser, feed_dict={X: train_X, Y: train_Y}) if (i+1)%50 == 0: cost = sess.run(cost_function, feed_dict={X: train_X, Y: train_Y}) print("Step:", '%04d' % (i+1), "cost=", "{:.9f}".format(cost), "m=", sess.run(m), "c=", sess.run(c)) slope = sess.run(m) intercept = sess.run(c) ### -------- ** Plotting the results ** ------------ sns.set() fig, ax = plt.subplots() ax.scatter(train_X, train_Y) plot_x = [np.amin(train_X)-2, np.amax(train_X)+2] plot_y = [slope*plot_x[0] + intercept , slope*plot_x[1] + intercept ] ax.plot(plot_x, plot_y, color=sns.xkcd_rgb["medium green"]) ax.set_xlabel('x') ax.set_ylabel('y') plt.show()
5e440811fde134ba1aba2b1b4ce0a00772a9ee89
SurajMishra-07/Code-with-harry-Python-Course
/genrator..py
1,056
4.46875
4
""" iterable=objects which have methods defined on them,__iter__() or __getitem__() iterator=objects which have __next() using this we iterate the iterable iteration=process of iterating """ # generator - it is basically a func which yield a value(generate one value at that time) but only return when we want . also it returns values one by one whereas a normal func returns all the value in a single go # formaing a self generator def gen(n): for i in range(n): yield i #it is agenerator it generate a value on a fly # use because we dont want that a huge no is first save on our memry thst print # here it generate that print than further generate n=gen(5) #genetating generator object print(n) #give object name print(n.__next__()) #i told u above print(next(n)) #another way to apply next func on generator obeject print(n.__next__()) print(n.__next__()) print(n.__next__()) # # after this it will give me error # print(n.__next__()) # since abvome my iteration stops # for range() has a inbuilt stopper
f2aeeb51d755406bcaed57488f42be27052ad005
tinghaoMa/python
/demo/OOP/oop_advanced_03.py
808
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 多重继承 MixIn的目的就是给一个类增加多个功能, 这样,在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能, 而不是设计多层次的复杂的继承关系。 只要选择组合不同的类的功能,就可以快速构造出所需的子类 ''' class Animal(object): pass # 大类: class Mammal(Animal): pass class Bird(Animal): pass class Runnable(object): def run(self): print('Running...') class Flyable(object): def fly(self): print('Flying...') # 各种动物: class Dog(Mammal, Runnable): pass class Bat(Mammal, Runnable): pass class Parrot(Bird, Flyable): pass class Ostrich(Bird, Flyable): pass
03c9fb86e020121f678fb6ee5f57966b01194da0
mouday/SomeCodeForPython
/python_psy_pc/work/回文数.py
186
3.59375
4
num = 123321 num_p = 0 num_t = num while num !=0: num_p = num_p * 10 + num % 10 num = num / 10 print num,num_p,num_t if num_t == num_p: print "ok" else: print "no"
de5d6222cb4d1afb503c50d7f356db6a0fd83415
Deivid09/Fundamentos-de-programacion
/Ejercicio 6 For tabla.py
795
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 25 18:47:56 2021 @author: trausch """ #programa lee una tabla y la imprime desde el 1 hasta el 20 y suma resultado #declarar variables tabla = 0 multiplicador = 1 resultado = 0 sumaResultado = 0 conRepCiclo = 1 #leer el numero de la tabla para la cual vamos a realizar las operaciones tabla = int(input("Tabla : ")) #Leer el multiplicador multiplicador = int(input("Ingrese Multiplicador : ")) #inicio el ciclo repetitivo que se llama FOR for conRepCiclo in range (multiplicador +1): resultado = tabla * conRepCiclo sumaResultado = resultado + sumaResultado print (tabla, " * ", conRepCiclo, " = ", resultado) #se imprime la suma por fuera de ciclo print ("La suma del los resultados es : ", sumaResultado)
ac64ae8cd91c3160d4e7cb61eec0fd7508e4aeb5
L1M80/my-atcoder-answers
/abc049/c.py
320
3.5625
4
#!/usr/bin/env python3 # https://atcoder.jp/contests/abc049/tasks/arc065_a s = input()[::-1] collector = '' t = '' words = ['remaerd', 'maerd', 'resare', 'esare'] for c in s: collector += c if collector in words: t += collector collector = '' if s == t: print('YES') else: print('NO')
13ae7881c19bd73b9183ef071184b2cb20c9ac01
faizerhussain/TestingEclipseGitUpload
/Hello1/Funntions.py
478
3.546875
4
def sayHello(name): print('hello', name) sayHello('Faizer') def sayHello1(name= 'hussain'): print('hello', name) sayHello1() sayHello1('Faiz') def getSum(n1,n2): total=n1+n2 return total addSum=getSum(2, 3) print('addition is ',addSum) print('***************') def multipleArgumentAddScores(name='tom',*score): print(name) for s in score: print (s) multipleArgumentAddScores('test',1,2)
cd94a2fb19602f487520b8d8f9f60a8c3755f520
ferrerinicolas/python_samples
/5.While Loops/5.1.5 Program Tracing Part2.py
142
3.75
4
# Can you guess what this program prints? x = 5 y = 5 while x > 5 or y < 10: print(x) print(y) x = 15 - x y = y + 2