blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
749178beb8f2ee98702d6b2256290f8d83f21bdd | OriEylon/automation_test | /try.py | 3,074 | 3.75 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
connection = None
try:
connection = sqlite3.connect(db_file)
except Error as e:
print(e)
return connection
def select_all_from(conn,from_where):
cur = conn.cursor()
cur.execute("SELECT * FROM {}".format(from_where))
rows = cur.fetchall()
for row in rows:
print(row)
def create_table(conn, create_table_sql):
try:
cursor = conn.cursor()
cursor.execute(create_table_sql)
except Error as e:
print(e)
def insert_to_projects(conn,project):
sql = ''' INSERT INTO projects(name,begin_date,end_date)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, project)
conn.commit()
return cur.lastrowid
def insert_to_employees(conn,employee):
sql = ''' INSERT INTO employees(name,works_on,adress)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, employee)
conn.commit()
return cur.lastrowid
def delete_employee(conn, id):
sql = 'DELETE FROM employees WHERE id=?'
cur = conn.cursor()
cur.execute(sql, (id,))
conn.commit()
def delete_all_employees(conn):
sql = 'DELETE FROM employees'
cur = conn.cursor()
cur.execute(sql)
conn.commit()
def main():
# database = r"C:\Users\Ori's pc\GitHub\automation_test\chinook.db"
db = r"C:\Users\Ori's pc\GitHub\automation_test\mydb.db"
# create a database connection
conn = create_connection(db)
# with conn:
# print("1. Query all employees:")
# select_all_employees(conn)
create_table_projects = '''CREATE TABLE IF NOT EXISTS projects (
id integer PRIMARY KEY,
name text NOT NULL,
begin_date text,
end_date text
); '''
create_table_employees = '''CREATE TABLE IF NOT EXISTS employees (
id integer PRIMARY KEY,
name text NOT NULL,
works_on integer NOT NULL,
adress text,
FOREIGN KEY (works_on) REFERENCES projects (id)
);'''
# create_table(conn,create_table_projects)
# create_table(conn, create_table_employees)
proj1 = ('test proj','12-12-19','14-12-19')
emp1 = ('ori eylon', '1','sheshet hayamim 50')
# insert_to_projects(conn, ('proj2','13-12-2019','31-12-2019'))
# insert_to_projects(conn, ('proj3', '01-01-2020', '31-12-2020'))
# insert_to_employees(conn, ('employee2','1','eli visel 3'))
# insert_to_employees(conn, ('employee3', '2', 'azrieli holon 2'))
# insert_to_employees(conn, ('employee5', '4', 'sheshet hayamim 55'))
# delete_employee(conn,5)
select_all_from(conn, 'projects')
select_all_from(conn, 'employees')
conn.close()
if __name__ == '__main__':
main()
|
62c3e6e9a96588d4f80fff39552b42a8eb5ba813 | onelharrison/python-practice | /words_rotation_point/words_rotation_point.py | 1,142 | 3.75 | 4 | def rotation_point(words):
start_point = 0
end_point = len(words) - 1
mid_point = end_point // 2
while start_point <= end_point:
if words[mid_point] < words[mid_point - 1]:
return mid_point
elif words[mid_point] < words[start_point]:
end_point = mid_point - 1
mid_point = (end_point + start_point) // 2
elif words[mid_point] > words[start_point]:
start_point = mid_point + 1
mid_point = (end_point + start_point) // 2
else:
return 0
return None
if __name__ == '__main__':
words_0 = [
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepist',
'asymptote',
'babka',
'banofee',
'engender',
'karpatka',
'othellolagkage'
]
assert rotation_point(words_0) == 5
words_1 = ['apples', 'berries', 'caramel', 'dip', 'enchiladas']
assert rotation_point(words_1) == 0
words_2 = ['berries', 'caramel', 'dip', 'xylophone', 'apples']
assert rotation_point(words_2) == 4
assert rotation_point([]) == None
|
1a80f6b7ee6adff4881db3a0fbb99636e0fe81b6 | AtalantaAlter/machinelearn | /learn_numpy/calc.py | 776 | 3.953125 | 4 | import numpy as np
p=np.array([[-1,4],
[-2,8]
]);
p1=np.array([[4,6],
[3,1]
]);
#矩阵乘法是将各个位置的值相乘
p3=p*p1;
print(p3);
print(np.multiply(p,p1)) #等价于上面
#点乘法 是将行和列相乘
'''
第一行的任意数字和第一列的任意数字累加
-1*4+-4*3=8 最后在第一行
第一行的任意数字和第二列的任意数字累加
-1*6+4*1=-2 在第一行
接下来第二行和第一列和第二列点乘 放在第二列
'''
print(np.dot(p,p1));#两个数组的点积,即元素对应相乘。 dot通用所有数组
print(np.matmul(p,p1))#两个数组的矩阵积
p=np.array([1,2]);
p1=np.array([2,3]);
print(np.vdot(p,p1))#两个向量的点积 1*2+2*3=8
print(np.inner(p,p1))
|
d42002714295c0119e6825291cdc1f8378bbc8f2 | Ghassen-Faidi/Learning-projects_py | /Python/Exersices/First Last/First last.py | 108 | 3.734375 | 4 | a = [2, 8, 5, 42, 12, 7]
items = []
def add(i):
items.append(a[i])
add(0)
add(-1)
print(items) |
53350afdb7bf3398636756205073726db35152be | Ghassen-Faidi/Learning-projects_py | /Python/HG converter/func.py | 752 | 3.84375 | 4 | # Functions
# Gregorian to Hijri
def GreToHij():
Greg = int(input("Enter a Gregorin(Miladi) year: \n>>>"))
# Calculation
Hij = (Greg-622)/0.97
# Get rid of the fraction
frac = Hij - int(Hij)
if frac > 0.5:
Hij = int(Hij)+1
else:
Hij= int(Hij)
# final result
print("The gregorin(Miladi) year", Greg, "is the year", "||",Hij,"||", "in hijri")
# Hijri to gregorian
def HijToGre():
Hij = int(input("Enter a hijri year: \n>>>"))
# Calculation
gre = 622 + Hij*0.97
# Get rid of the fraction
frac = gre - int(gre)
if frac > 0.5:
gre = int(gre)+1
else:
gre = int(gre)
# final result
print("The hejri year ", Hij, "is the year ","||",gre,"||", "Gregorian(Miladi)")
|
615e9a0302286d516d963277affe9aa7ded6a257 | MikeACG/surfOpt | /genetics.py | 2,777 | 3.546875 | 4 | import random as rd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
# implements a differential evolution GA
class diffEvolver:
def __init__(self, ps, F, cp, nfe, rng = 123):
self.ps = ps # population size
self.F = F # scaling factor
self.cp = cp # crossover probability
self.nfe = nfe # number of function evaluations
self.rng = rng # random seed for reproducibility
self.pop = [] # keeps the population after evolution
self.evals = [] # keeps the evaluations of the population after evolution
# sets the function to initialize individuals
def setPopulator(self, populator):
self.populator = populator
# sets the DE reproduction method
def setReproduction(self, reproduction):
self.reproduction = reproduction
# sets the survival method after reproduction and before next iteration of evolution
def setSurvival(self, survival):
self.survival = survival
# sets the distance fucntion for survival calculation
def setDistance(self, distance):
self.distance = distance
# allows for changing the rng seed
def setSeed(self, rng):
self.rng = rng
# prints progress of evolution process
def verbosity(self, ngen, nevals, population, evaluations):
meanFit = sum(evaluations) / len(evaluations)
print('GENERATION: ', str(ngen), ' / Fitness evaluations: ', nevals, '. Mean fitness is ', '{:.2f}'.format(meanFit), ", Showing top 10 individuals...", sep = '')
top = (-np.array(evaluations)).argsort()
for i in range(10):
ind = ['{:.2f}'.format(d) for d in population[top[i]]]
print("\t", "Fitness: ", '{:.2f}'.format(evaluations[top[i]]), " / Genotype: ", str(ind), sep = '')
# GA
def evolve(self, surf):
rd.seed(self.rng)
pop = [self.populator(surf.dlims, surf.ulims) for i in range(self.ps)]
nevals = 0
gen = 1
while nevals < self.nfe:
evals = [surf.f(i) for i in pop]
if nevals % (np.floor( (10 * self.nfe) / 100 )) == 0:
self.verbosity(gen, nevals, pop, evals)
new_pop = pop.copy()
for i in range(self.ps):
offspring = self.reproduction(i, pop, self.F, self.cp, surf.dlims, surf.ulims)
replace = self.survival(offspring, surf.f(offspring), pop, evals, self.distance)
if replace > -1:
new_pop[replace] = offspring
pop = new_pop
nevals += self.ps * 2
gen += 1
print("DONE, FINAL POPULATION:")
self.verbosity(gen, nevals, pop, evals)
self.pop = pop
self.evals = evals
|
9571e3ea20f160b28ae49cf6a0348dd49c614d58 | IvanildoCandido/learning-python | /units_numbers.py | 522 | 3.984375 | 4 | """
Faça um programa que leia um número de 0 a 9999 e
mostre na teça cada um dos digitos separados:
Ex: 1834
unidades: 4 dezenas: 3 centenas: 8 milhar: 1
"""
number = int(input("Informe um número: "))
unit = number // 1 % 10
ten = number // 10 % 10
hundred = number // 100 % 10
thousand = number // 1000 % 10
print("Analizando o número {}".format(number))
print("Unidades: {}".format(unit))
print("Dezenas: {}".format(ten))
print("Centenas: {}".format(hundred))
print("Milhares: {}".format(thousand))
|
5e23c58aae57333c223cdc4dd0c27bfd9c5e4544 | JRLV14/Pensamiento_Computacional | /funciones_y_abstracciones.py | 1,108 | 3.78125 | 4 | def busqueda_binaria():
epsilon = 0.01
bajo = 0.0
alto = max(1.0, objetivo)
respuesta = (alto + bajo) / 2
while abs(respuesta**2 - objetivo) >= epsilon:
print(f"bajo={bajo}, alto={alto}, respuesta={respuesta}")
if respuesta**2 < objetivo :
bajo = respuesta
else:
alto= respuesta
respuesta = (alto + bajo) / 2
print (f"la raiz cuadrada de {objetivo} es {respuesta}")
def enumeracion_exahustiva():
respuesta = 0
while respuesta**2 < objetivo:
print (f"{objetivo}, {respuesta}")
respuesta += .1
if respuesta**2 == objetivo:
print(f"la raiz cuadrada de {objetivo} es {respuesta}")
else:
decimal = round(respuesta, 10)
print (f"{decimal} es la raiz cuadrada de {objetivo}")
objetivo = int(input("Escoge un numero entero: "))
menu = """ "Metodo para encontrar la raiz:
1 - Metodo Binario
2 - Enumeracion matematica
"""
opcion = int (input(menu))
if opcion ==1:
busqueda_binaria()
elif opcion ==2:
enumeracion_exahustiva()
else:
print("Opcion no valida") |
51966fbad81a7355cb31857cbf663a13a7482706 | Shreejichandra/October-Leetcode | /1007_minimum_domino_rotations_for_equal_row.py | 1,869 | 4.03125 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
'''
class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
# All elements of A should be same as 1st element of A
start = A[0]
swaps1 = 0
for i in range(1, len(A)):
if A[i] == start:
continue
elif B[i] == start:
swaps1 += 1
else:
swaps1 = float('inf')
# All elements of B should be same as 1st element of B
start = B[0]
swaps2 = 0
for i in range(1, len(B)):
if B[i] == start:
continue
elif A[i] == start:
swaps2 += 1
else:
swaps2 = float('inf')
# All elements of A should be same as 1st element of B
start = B[0]
swaps3 = 1
for i in range(1, len(A)):
if A[i] == start:
continue
elif B[i] == start:
swaps3 += 1
else:
swaps3 = float('inf')
# All elements of B should be same as 1st element of A
start = A[0]
swaps4 = 1
for i in range(1, len(B)):
if B[i] == start:
continue
elif A[i] == start:
swaps4 += 1
else:
swaps4 = float('inf')
ans = min(swaps1, swaps2, swaps3, swaps4)
if ans == float('inf'):
return -1
else:
return ans
|
331d5354417420a43c8c6fbcdd8c9a640e61fa10 | mario-alop/ejemplos_python | /diccionario_notas.py | 845 | 3.96875 | 4 | estudiantes = {}
id = 1
aprobados = 5
suspensos = 4
suma = 0
media = 0
print()
cantidad = int(input('Introduce la cantidad de alumnos que vamos a guradar: '))
print()
while id <= cantidad:
nombre = input('Nombre del alumno: ')
nota = float(input('Dame una nota del alumno: '))
suma += nota
print()
estudiantes[id] = {'nombre': nombre, 'nota': nota}
id = id + 1
print()
for alumno, notas in estudiantes.items():
print(alumno,notas)
print()
print('Lista de Aprobados: ')
for key, value in estudiantes.items():
if value['nota'] >= aprobados:
print(key,value)
print()
print('Lista de Suspensos: ')
for key, value in estudiantes.items():
if value['nota'] <= aprobados:
print(key,value)
print()
for i in estudiantes:
media = i
print(f'La nota media de la clase es: ', suma/media)
print()
|
10378f358b3c66ef446ebd9449daa7c4df097750 | mario-alop/ejemplos_python | /fun_adivina.py | 629 | 3.9375 | 4 | from random import randint, uniform, random
print()
print('Introduzca un número del 1 al 10')
aleatorio = randint(0, 10)
#print(aleatorio)
def adivina():
try:
numero = int(input('Número: '))
if aleatorio == numero:
print('Has acertado el número!!!!')
elif aleatorio > numero:
print('El número es mayor.')
adivina()
return
elif aleatorio < numero:
print('El número es menor.')
adivina()
return
except:
print("Por favor ingrese un número válido del una al diez")
adivina()
adivina()
|
9943c849e468966d8c520e0626408c0cbef9eb0a | mario-alop/ejemplos_python | /diccionario.py | 348 | 3.65625 | 4 | lista = [12, 23, 5, 12, 92, 5,12, 5, 29, 92, 64, 23]
diccionario = {}
for i in lista:
if i not in diccionario:
diccionario[i] = 1
else:
diccionario[i] = diccionario[i] + 1
print()
print('Lista:')
print()
print(lista)
print()
print('Número de veces que aparece cada número en la lista:')
print()
print(diccionario)
print() |
ec6d3c49239b2b2092f22c2e99863283482285bd | qzylinux/Python | /if-else.py | 732 | 3.984375 | 4 | a='start'
while a!='end':
a=input('please input your weight:')
#判断输入的是数字还是其他
if a.isdigit():
#将input的输入str类型转换为int(需要的类型)
weight=int(a)
#输出转换后的数字
print('you input a float is %d.'%weight)
#判断体重类型
if weight<18.5:
print('you are underweight.')
#continue
elif weight<=25:
print('your weight is normal.')
#continue
elif weight<=28:
print('you are overweight.')
#continue
elif weight<=32:
print('you are fat.')
#continue
else:
print('you are seriously fat.')
#continue
#输入的不是数字时提示用户
else:
print('you input is not digit:%s'%a)
#提醒用户测试完毕
print('test is over!') |
833b170674ce129a25e3efbea133eae6c903cb1b | qzylinux/Python | /generator.py | 216 | 4.15625 | 4 | #generator 返回当前值,并计算下一个值
def mygenerator(max):
a,b,n=0,1,0
while n<max:
yield b
a,b=b,a+b
n=n+1
return 'done'
f=mygenerator(10)
print('mygenerator(10):',f)
for x in f:
print(x) |
40eefed408a874f7dc517a20c16238ddced6b516 | JiniousChoi/tree | /tree.py | 833 | 3.703125 | 4 | #!/usr/bin/python3
from enum import Enum
class Deco(Enum):
MID = '├── '
END = '└── '
CONT = '│ '
EMPTY = ' '
class Tree:
def __init__(self, traverser, print_node, deco=Deco):
self.deco = deco
self.traverser = traverser
self.print_node = print_node
def print(self):
for (dstack, node) in self.traverser:
self._print_decos(dstack)
self.print_node(node)
def _print_decos(self, dstack):
if not dstack:
return
for d in dstack[:-1]:
if d == self.deco.END:
print(self.deco.EMPTY.value, end='')
elif d == self.deco.MID:
print(self.deco.CONT.value, end='')
else:
print(d, end='')
print(dstack[-1].value, end='')
|
5034bd1032c880a1754a442d0fd519da6779e113 | adityakamble49/ml-algorithms | /supervised/regression/linearregression/linear_regression.py | 2,199 | 4.09375 | 4 | # # Linear Regression using Gradient Descent
# ## Import Packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# ## Import Data set
train_data = pd.read_csv('apartment_data_train.csv')
train_data.head()
train_data.info()
train_data.describe()
test_data = pd.read_csv('apartment_data_test.csv')
test_data.head()
# ## Feature Separation and Normalization
X_train = train_data.iloc[:, :-1].values
X_test = test_data.iloc[:, :].values
y_train = train_data.iloc[:, -1:].values
m = y_train.shape[0]
train_data_mean = train_data.mean(0)
train_data_std = train_data.std(0)
X_train_mean = train_data_mean[0:2].values
X_train_std = train_data_std[0:2].values
X_train_norm = (X_train - X_train_mean) / X_train_std
X_test_norm = (X_test - X_train_mean) / X_train_std
# ## Add Intercept Term to Features
train_ones = np.ones((X_train_norm.shape[0], 1))
test_ones = np.ones((X_test_norm.shape[0], 1))
X_train_norm = np.column_stack((train_ones, X_train_norm))
X_test_norm = np.column_stack((test_ones, X_test_norm))
# ## Perform Gradient Descent
# ### Compute Cost
def compute_cost(X, y, theta):
hx = np.matmul(X, theta)
error_values = hx - y
squared_error = np.square(error_values)
cost = np.sum(squared_error, 0)
return cost
# ### Gradient Descent
def gradient_descent(X, y, theta, alpha, iterations):
iteration_array = np.array([itr for itr in range(iterations)])
cost_history = []
for iteration in range(iterations):
hx = np.matmul(X, theta)
error_value = hx - y
error_value_multi = np.matmul(error_value.T, X)
delta = np.multiply(error_value_multi.T, (alpha / m))
theta = theta - delta
cost_history.append(compute_cost(X, y, theta))
return [theta, np.column_stack((iteration_array, np.asarray(cost_history)))]
# ### Use Gradient Descent
alpha = 0.01
num_iterations = 400
theta = np.zeros((X_train_norm.shape[1], 1))
theta, cost_history_result = gradient_descent(X_train_norm, y_train, theta, alpha, num_iterations)
result = np.matmul(X_test_norm, theta)
print(result)
# ### Cost Function
plt.plot(cost_history_result)
plt.xlabel("Iteration")
plt.ylabel("Cost")
plt.show()
|
9e2db45663075ac0ca4158318d93a039416a331d | gsg62/Basic-Python-Programs | /careerPathGamebook.py | 1,449 | 3.90625 | 4 | # Greg Geary
# Career Path Gamebook
print("Career Path Gamebook")
choice1 = input("Do you want to go to college after highschool? (yes/no)")
if choice1 == "yes":
choice2 = input("What major do you want? (computer science or buisness)")
if choice2 == "computer science":
choice3 = input("Do you want to be a programmer or computer engineer?")
if choice3 == "programmer":
print("you will be a programmer")
elif choice3 == "computer engineer":
print("You will be a computer engineer")
elif choice2 == "buisness":
choice4 = input("Do you want to be an accountant or entrepreneur?")
if choice4 == "accountant":
print("You will be an accountant")
elif choice4 == "entrepreneur":
print("You will be an entrepreneur")
elif choice1 == "no":
choice5 = input("Do you want to work restaurant or construction?")
if choice5 == "restaurant":
choice5 = int(input("How many hours do you want"
" to work a week?(20/30/40)"))
if choice5 == 20:
print("You will make about $16000 a year")
elif choice5 == 30:
print("You will make around $24000 a year")
elif choice5 == 40:
print("You will make around $31000 a year")
elif choice6 == "construction":
print("The average construction worker makes around $31000 a year")
|
8e3b79279217250bbf35acacc51e8df73ae7e93e | IsaacStong/Leet_Code_Solutions | /Add_Two_Numbers.py | 881 | 3.5625 | 4 | """Created by Isaac Stong on 6/17/20
Given two singly linked list sum the reverse of those linked lists
Store result in same manner.
Ex. (2 -> 4 -> 3) + (5 -> 6 -> 4) = 7 -> 0 -> 8
Explanation 342 + 465 = 807"""
class ListNode:
def __init__(self, val=0, next_node=None):
self.val = val
self.next = next_node
def add_two_numbers(l1, l2):
num1 = list_to_int(l1)
num2 = list_to_int(l2)
sum = num1 + num2
temp = None
for i in str(sum):
temp = ListNode(int(i), temp)
return temp
def list_to_int(l1):
if l1.next is None:
return l1.val
else:
return l1.val + (10*list_to_int(l1.next))
b1 = ListNode(6)
b2 = ListNode(2, b1)
b3 = ListNode(3, b2)
a1 = ListNode(3)
a2 = ListNode(2, a1)
a3 = ListNode(1, a2)
lel = add_two_numbers(b3, a3)
for i in range(3):
print(lel.val)
lel = lel.next
|
ac5fb09501c10e94d3f0c3149967aa2dc28d46ab | pranjal2203/Python_Programs | /recursive fibonacci.py | 518 | 4.5 | 4 | #program to print fibonacci series using recursion
#recursive function for generating fibonacci series
def FibRecursion(n):
if n <= 1:
return n
else:
return(FibRecursion(n-1) + FibRecursion(n-2))
#input from the users
no = int(input("Enter the terms: "))
#checking if the input is correct or not
if no <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(no):
print(FibRecursion(i),end=" ") |
7a0bc20e388ef8d5856a9513938852b890efcc71 | pranjal2203/Python_Programs | /goats_n_ducks.py | 454 | 4.03125 | 4 | #count and display no of goats n ducks by counting by their headds n feets
#inputing value of no of heads and legs
head=int(input("enter the number of heads : "))
legs=int(input("enter the number of legs : "))
#for loop for calculating no of goats and ducks
for duck in range(1,head):
goat=head-duck
tot=4*goat+2*duck
if(tot==legs):
print("total number of goats : ",goat)
print("total number of ducks : ",duck) |
61082c9e36d5c2f72e741985fcad901aaf77811c | Mushrif/Final_Project | /Final_Project_Python_BY_Musharraf_ALRUWAILL | 19,658 | 3.578125 | 4 | #!/usr/bin/env python3
import os
import sqlite3
import pprint
import random
filename = 'C:\sqlite\Mush_db.db'
conn = sqlite3.connect(filename)
class functions:
# to control all functions functionlaity
def _init_(self):
pass
def delete_Fun(self):
num_of_func = input("How many functions do you want to write ? ")
num_of_func = int(num_of_func)
# Getting the question requirment
for i in range (0,num_of_func):
print ("This is a secure access.")
Fname = input("Write the functions that you want to delete : ")
query = "DELETE FROM Functions WHERE NAME ='%s';" % (Fname)
conn.execute(query) # implements the query
conn.commit()
def add_function(self):
IDS = 0
first_time = False
# Getting the last ID for Questions table
for row in conn.execute('SELECT * FROM Functions'):
IDS = row[0]
if (IDS ==0 or IDS == None): # set 1 if it's the first time
IDS = 1
first_time = True
# Ask how many question to insert
num_of_fun = input("How many Function do you want to add ? ")
num_of_fun = int(num_of_fun)
# Getting the question requirment
for i in range (0,num_of_fun):
# knwoing if it's first time or not
if (first_time == True):
IDS = 1
first_time = False
else:
IDS = IDS + 1
inserting_list = []
Qs = input("Write the name of function : ")
inserting_list.append(Qs)
Qs = input("Write the description : ")
inserting_list.append(Qs)
Qs = input("Write the example : ")
inserting_list.append(Qs)
Qs = input("Write a note : ")
inserting_list.append(Qs)
Qs = input("Write its library : ")
inserting_list.append(Qs)
print (IDS , " " , Qs)
query = "INSERT INTO Functions (F_ID, NAME, Description, Example, Mynote, Use_library) VALUES (%i, '%s', '%s', '%s', '%s', '%s') " % (IDS, inserting_list[0],inserting_list[1],inserting_list[2],inserting_list[3],inserting_list[4])
conn.execute(query) # implements the query
conn.commit()
def Seraching(self):
list_Users = []
looking = input("What fucntions you like to look for ? ")
query = "SELECT * FROM Functions WHERE NAME = '%s';" % (looking)
for row in conn.execute(query):
list_Users.append(row)
len_of_list = len(list_Users)
if (list_Users == None):
print ("The function that you are looking for is not found ... ")
elif (len(list_Users) > 0):
print ("\tThe function ID is : \t", list_Users[0][0])
print ("\tThe function Name is : \t", list_Users[0][1])
print ("\tThe function Description is : \t", list_Users[0][2])
print ("\tThe function Example is : \t", list_Users[0][3])
print ("\tThe function Note is : \t", list_Users[0][4])
print ("\tThe function Use Library : \t", list_Users[0][5])
class User: # to have control over all users
filename = 'C:\sqlite\Mush_db.db'
conn = sqlite3.connect(filename)
def _init_(self):
pass
def Change_Password(self,UID):
Upassword = input(" Write you new password : ")
query = "UPDATE Users SET Password = '%s' WHERE U_ID = '%s';" % (Upassword,UID)
conn.execute(query) # implements the query
conn.commit()
def privilege(self):
print ("\n\t\tThis is Secure Access\n")
Uname = input("Write the user name that you want to alter his/her privilege : ")
Utype = input("Write the privilege (Admin/User) : ")
query = "UPDATE Users SET U_type = '%s' WHERE User_name = '%s';" % (Utype,Uname)
conn.execute(query) # implements the query
conn.commit()
def delete_user(self):
print ("\n\t\tThis is Secure Access\n")
Uname = input("Write the user name that you want to delete : ")
query = "DELETE FROM Users WHERE User_name ='%s';" % (Uname)
conn.execute(query) # implements the query
conn.commit()
def Add_User(self):
IDS = 0
first_time = False
# Getting the last ID for Questions table
for row in conn.execute('SELECT * FROM Users'):
IDS = row[0]
if (IDS ==0 or IDS == None): # set 1 if it's the first time
IDS = 1
first_time = True
# Ask how many question to insert
num_of_users = input("How many User do you want to add ? ")
num_of_users = int(num_of_users)
# Getting the question requirment
for i in range (0,num_of_users):
# knwoing if it's first time or not
if (first_time == True):
IDS = 1
first_time = False
else:
IDS = IDS + 1
print ("This is the User number %i." % (i+1))
inserting_list = []
Qs = input("Write the user name : ")
inserting_list.append(Qs)
Qs = input("Write the First name : ")
inserting_list.append(Qs)
Qs = input("Write the Last name : ")
inserting_list.append(Qs)
Qs = input("Write the Email : ")
inserting_list.append(Qs)
Qs = input("Write the paswword : ")
inserting_list.append(Qs)
Qs = input("Write the profile : ")
inserting_list.append(Qs)
Qs = input("Write the user type (Admin/User) : ")
inserting_list.append(Qs)
query = "INSERT INTO Users (U_ID, User_name, F_name, L_name, Email, Password, profile, U_type) VALUES (%i, '%s', '%s', '%s', '%s', '%s', '%s','%s')" % (IDS, inserting_list[0],inserting_list[1],inserting_list[2],inserting_list[3],inserting_list[4],inserting_list[5],inserting_list[6])
conn.execute(query) # implements the query
conn.commit()
def Access(self):
# Listing users info
list_Users = []
for row in conn.execute('SELECT * FROM Users'):
list_Users.append(row)
User_info = {}
User_info['User_name'] = ''
User_info['Password'] = ''
User_info['Name'] = ''
User_info['ID'] = ''
User_info['Type'] = ''
not_found = True
count = 0
# Getting User name and password input
while (not_found == True):
count = count + 1
User_name = input("Enter the user name: ")
Password = input("Enter the the password: ")
# Ensuring the user input and assign the info to User_info Dictionary
for Record in list_Users:
if(User_name == Record[1]) and (Password == Record[5]):
print ("\n\t\tYou have been successfully logged in.")
User_info['User_name'] = User_name
User_info['Password'] = Password
User_info['ID'] = Record[0]
User_info['Name'] = Record[2] + " " + Record[3]
if(Record[7] == 1): # Know if admin or not
User_info['Type'] = "Admin"
else:
User_info['Type'] = "User"
not_found = False
return (User_info)
if (not_found == True):
print ("\n\t\t It's wrong password or user name. \n")
print (" That was the ", count , " attempts.")
not_found = True
class question:
filename = 'C:\sqlite\Mush_db.db'
conn = sqlite3.connect(filename)
def _init_(self):
pass
def quiz(self):
IDS = 0
first_time = False
# Getting the last ID for Questions table
count = 0
for row in conn.execute('SELECT * FROM Questions'):
IDS = row[0]
count = count + 1
if (IDS ==0 or IDS == None):
print ("There is no question to do quiz .. sorry ")
xlist = []
while(1):
Q_count = input ("How many question do you like to quiz your self : ")
Q_count = int(Q_count)
xlist = []
if(Q_count > count ):
print ("Sorry , we just have %s number of questions " % (count))
else:
break
xlist = []
while(True):
x = random.randrange(1,(count+1))
if x not in xlist:
xlist.append(x)
if (len(xlist) == Q_count):
break
print ("lets play now ^_^ .... ")
right_answer = 0
for x in xlist:
x = int(x)
query = ("SELECT * FROM Questions WHERE Q_ID = %i " % (x))
for row in conn.execute(query):
print ("\t",row[1])
print ("\t\t1- ",row[2])
print ("\t\t2- ",row[3])
print ("\t\t3- ",row[4])
print ("\t\t4- ",row[5])
ans = input("Enter the number of the answer (1/2/3/4) : ")
RA = int(row[6])
if (RA == int(ans)):
print ("You got it right !!")
right_answer = right_answer + 1
else:
print ("Oh, it's wrong, sorry !!")
print ("the right answer is ", RA )
print ("The number of correct answer you got is : " , right_answer)
print ("it's a " , (((right_answer / Q_count) * 100)) , "% .")
def delete_Question(self):
num_of_QU = input("How many Question do you want to delete ? ")
num_of_QU = int(num_of_QU)
# Getting the question requirment
for i in range (0,num_of_QU):
print ("\n\t\tThis is Secure Access\n")
Ids = input("Write the ID of Question that you want to delete : ")
query = "DELETE FROM Questions WHERE Q_ID ='%s';" % (Ids)
conn.execute(query) # implements the query
conn.commit()
def Add_Question(self):
print ("\n\t\tThis is Secure Access\n")
# initiat the ID variable
IDS = 0
first_time = False
# Getting the last ID for Questions table
for row in conn.execute('SELECT * FROM Questions'):
IDS = row[0]
if (IDS ==0 or IDS == None): # set 1 if it's the first time
IDS = 1
first_time = True
# Ask how many question to insert
num_of_question = input("How many question do you want to write ? ")
num_of_question = int(num_of_question)
# Getting the question requirment
for i in range (0,num_of_question):
# knwoing if it's first time or not
if (first_time == True):
IDS = 1
first_time = False
else:
IDS = IDS + 1
print (IDS)
print ("This is the Question number %i." % (i+1))
inserting_list = []
Qs = input("Write the Questions : ")
inserting_list.append(Qs)
Qs = input("Write the first Answer : ")
inserting_list.append(Qs)
Qs = input("Write the Second Answer : ")
inserting_list.append(Qs)
Qs = input("Write the Third Answer : ")
inserting_list.append(Qs)
Qs = input("Write the fourth Answer : ")
inserting_list.append(Qs)
Qs = input("Write the number of the right answer : ")
inserting_list.append(Qs)
query = "INSERT INTO Questions (Q_ID, Questions, Ans_1, Ans_2, Ans_3, Ans_4, Right_Ans) VALUES (%i, '%s', '%s', '%s', '%s', '%s', '%s')" % (IDS, inserting_list[0],inserting_list[1],inserting_list[2],inserting_list[3],inserting_list[4],inserting_list[5])
conn.execute(query) # implements the query
conn.commit()
# Wecloming the user
print ("\t\t\tWeclome to Python Helper Version 1")
print ("\t\t\t WRITTEN BY MUSHARRAF ALRUWAILL")
print ("\t\t\t INSTRUCTOR : GULA NURMATOVA")
print ("\t\t\t UNH ")
# -----------------------------------------
End_App = False
User_info = {}
UC = User()
User_info['User_name'] = ''
User_info['Password'] = ''
User_info['Name'] = ''
User_info['Type'] = ''
global User_choice
while(End_App == False):
if(User_info['Type'] == '' ):
User_info = UC.Access()
if ( User_info['Type'] == "Admin" ):
print ("\n\nWhat Would like to do ", User_info['Name'], " ?")
print ("\n\t Admin privilege :")
print ("\t\t 1- Add new Question")
print ("\t\t 2- Delete Question")
print ("\t\t 3- Add new Function")
print ("\t\t 4- Delete Function")
print ("\t\t 5- Add new User")
print ("\t\t 6- Delete User")
print ("\t\t 7- alter privilege")
print ("\n\t As a normal user access : ")
print ("\t\t 8- Search for function")
print ("\t\t 9- Quiz game")
print ("\t\t 10- Change Password")
print ("\t\t 11- Log out")
print ("\t\t 12- Quit")
User_choice = input("\n\n\t\twhat would you like to do : ")
User_choice = int(User_choice)
elif ( User_info['Type'] == "User" ):
print ("\n\t",User_info['Name'], " have right to do : ")
print ("\t\t 1- Search for function")
print ("\t\t 2- Quiz game")
print ("\t\t 3- Change Password")
print ("\t\t 4- Log out")
print ("\t\t 5- Quit")
User_choice = input("\n\n\t\twhat would you like to do : ")
User_choice = int(User_choice)
question_imp = question()
user_imp = User()
function_imp = functions()
if ( User_info['Type'] == "Admin" and User_choice == 1):
question_imp.Add_Question()
elif (User_info['Type'] == "Admin" and User_choice == 2):
question_imp.delete_Question()
elif (User_info['Type'] == "Admin" and User_choice == 3):
function_imp.add_function()
elif (User_info['Type'] == "Admin" and User_choice == 4):
function_imp.delete_Fun()
elif (User_info['Type'] == "Admin" and User_choice == 5):
user_imp.Add_User()
elif (User_info['Type'] == "Admin" and User_choice == 6):
user_imp.delete_user()
elif (User_info['Type'] == "Admin" and User_choice == 7):
user_imp.privilege()
elif (User_info['Type'] == "Admin" and User_choice == 8):
function_imp.Seraching()
elif (User_info['Type'] == "Admin" and User_choice == 9):
question_imp.quiz()
elif (User_info['Type'] == "Admin" and User_choice == 10):
MyID = User_info['ID']
print (MyID)
user_imp.Change_Password(MyID)
elif (User_info['Type'] == "Admin" and User_choice == 11):
User_info['User_name'] = ''
User_info['Password'] = ''
User_info['Name'] = ''
User_info['Type'] = ''
elif (User_info['Type'] == "Admin" and User_choice == 12):
End_App = True
elif (User_info['Type'] == "User" and User_choice == 1):
function_imp.Seraching()
elif (User_info['Type'] == "User" and User_choice == 2):
question_imp.quiz()
elif (User_info['Type'] == "User" and User_choice == 3):
MyID = User_info['ID']
user_imp.Change_Password(MyID)
elif (User_info['Type'] == "User" and User_choice == 4):
User_info['User_name'] = ''
User_info['Password'] = ''
User_info['Name'] = ''
User_info['Type'] = ''
elif (User_info['Type'] == "User" and User_choice == 5):
End_App = True
else:
print("\t\tYou should choose one of the shown options.")
# Implementing the choice
conn.close()
|
25cb724c79dabac67e6a7cb66b459708a46b6c6a | cgDeepLearn/DSA_python | /6-trees/PriorityQueue_list.py | 1,516 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
优先队列的list实现(), O(n)插入,O(1)访问
若采用链表实现,头插入和弹出,O(1)插入,O(n)检查和弹出
date:2017/10/11
"""
class PrioQueueError(ValueError):
pass
class PrioQueue():
"""
优先队列
"""
def __init__(self, elist=None):
"""
Args:
elist:初始化数据,默认为None
"""
if elist is None:
elist = []
# 用list转换,对实参表做一个拷贝,避免共享,或者用elist=None并在文档字符串中描述它
self._elems = list(elist)
# 较小的优先,也可用元组表示数据元(1, data),一个表示优先级,一个表示数据
self._elems.sort(reverse=True)
def is_empty(self):
return not self._elems
def enqueue(self, item):
"""入队"""
index = len(self._elems) - 1
while index >= 0:
if self._elems[index] <= item:
index -= 1
else:
break
self._elems.insert(index + 1, item)
def dequeue(self):
"""出列"""
if self.is_empty():
raise PrioQueueError("in pop")
return self._elems.pop()
if __name__ == '__main__':
a = [3, 2, 4, 6, 5]
b = (5, 6, 4, 2, 3)
PQ = PrioQueue(b)
print(PQ.dequeue()) # 2
PQ.enqueue(1)
print(PQ.dequeue()) # 1
PQ2 = PrioQueue()
PQ2.enqueue(3)
PQ2.enqueue(4)
PQ2.enqueue(2)
print(PQ2.dequeue()) # 2
|
ce05dd1910832fe0b4c8e964e659d0576fa609d8 | cgDeepLearn/DSA_python | /8-dict_and_set/dict_list.py | 2,865 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
基于list的字典实现
"""
class Assoc():
"""
字典的基本关联类
"""
def __init__(self, key, value):
self.key = key
self.value = value
def __lt__(self, other):
return self.key < other.key
def __le__(self, other):
return self.key < other.key or self.key == other.key
def __str__(self):
return "Assoc({0}, {1})".format(self.key, self.value)
class DictList():
"""
基于List的字典类
"""
def __init__(self):
self._elems = []
def is_empty(self):
return not self._elems
def num(self):
return len(self._elems)
def search(self, key):
for elem in self._elems:
if elem.key == key:
return elem.value
return None
def insert(self, key, value):
self._elems.append(Assoc(key, value))
def delete(self, key):
for i, elem in enumerate(self._elems):
if elem.key == key:
self._elems.pop(i)
return
def entries(self):
for elem in self._elems:
yield elem.key, elem.value
def values(self):
for elem in self._elems:
yield elem.value
# end of class
class DictOrdList(DictList):
"""
有序key时,二分查找插入
"""
def insert(self, key, value):
"""有了修改,没有插入"""
if self.is_empty(): # 为空直接插入
super().insert(key, value)
return
find, pos = self.search(key) # search 返回位置和是否找到
if find: # 已存在key直接修改值
self._elems[pos].value = value
else: # 不存在插入相应位置
self._elems.insert(pos, Assoc(key, value))
def search(self, key):
"""
返回二元组,找到与否find和位置pos
没找到仍然返回在有序key中的位置pos
"""
elems = self._elems
if self.is_empty(): # 为空时返回None和0
return None, 0
low, high = 0, len(elems) - 1
pos = 0
while low <= high:
mid = (low + high) // 2
if key == elems[mid].key:
return elems[mid].value, mid
if key < elems[mid].key:
high = mid - 1
if high < 0:
pos = 0
else:
low = mid + 1
pos = low
return None, pos
def main():
from random import randint, seed
seed(1)
dic1 = DictOrdList()
print("before insert:")
for i in range(10):
key, value = randint(1, 50), randint(1, 100)
print(key, value)
dic1.insert(key, value)
print("after insert: ")
for k, v in dic1.entries():
print(k, v)
if __name__ == '__main__':
main()
|
6490128a5a204c3d6a117c326d5e5c398f3195f5 | blockheads/ConquerorGame | /Console.py | 4,314 | 3.609375 | 4 | # this is our font size we use for our console
import pygame
from pygame import font
from parsing.parse import Parser
from Canvas import WHITE, BLACK
CONSOLE_FONT_SIZE = 16
# how long the console should be
CONSOLE_LENGTH = 5
CONSOLE_LINE_WIDTH = 3
class Console:
def __init__(self,size):
# length of the console
self._size = 20
# stores our Message objects in a list
self._log = []
# initialize our log to the empty string for each entry
for i in range(0,self._size):
self._log.append(Message(["?"*40]))
# parsing for commands
self.parser = Parser(self)
"""
Returns overall size of the console
"""
@property
def size(self):
return self._size
@property
def log(self):
return self._log
"""
pushes a message onto the console
"""
def push(self, message):
# if we are pushing a trivial string we wrap it around our Message class for ease
if isinstance(message, str):
# we have to try and parse this message
self.parser.command(message)
print("converted...")
message = Message([message])
# iterate from the top, pushing each message up 1
for i in range(self._size-1, 0, -1):
self._log[i] = self._log[i-1]
# finally set the bottom equal to the message
self._log[0] = message
"""
displays the console to the screen given a valid display
"""
def display(self, userInput, display, height, width):
# console text
font = pygame.font.Font('freesansbold.ttf', CONSOLE_FONT_SIZE)
for i in range(0, self.size):
currMessage = self._log[i]
# we continue outputting, until the bitter end
string, image = currMessage.pop(0)
j = 0
# why python have no do while whatever
# shift from previous text/images
shift = 0
while string:
currect = pygame.Rect(shift, height - (i+2)*CONSOLE_FONT_SIZE, width,CONSOLE_FONT_SIZE)
curtext = font.render(string, True, WHITE, BLACK)
shift += len(string)*CONSOLE_FONT_SIZE/1.9
# if we got a image
if image:
# need to scale it down to our font size
display.blit(pygame.transform.scale(image, (CONSOLE_FONT_SIZE + 1, CONSOLE_FONT_SIZE + 1)), (shift, height - (i+2) * CONSOLE_FONT_SIZE), special_flags = pygame.BLEND_RGBA_MULT)
shift += CONSOLE_FONT_SIZE
display.blit(curtext, currect)
j += 1
string, image = currMessage.pop(j)
# create a text surface object,
# on which text is drawn on it.
text = font.render(userInput, True, WHITE, BLACK)
# text surface object
textRect = text.get_rect()
textRect.midleft = (0, height - CONSOLE_FONT_SIZE / 2)
display.blit(text, textRect)
# 'text console' output for text based aspect
consolestart = height - ((self.size + 1) * CONSOLE_FONT_SIZE)
pygame.draw.line(display, BLACK, (0, consolestart), (width, consolestart), CONSOLE_LINE_WIDTH)
class Message:
"""
Initializes a message with pairs of strings/images
ie. string1 -> image1 -> string2 -> image2 ... StringN -> ImageN
can choose ordering, ie. image before message?
"""
def __init__(self, strings, images=None):
self._strings = strings
if images:
self._images = images
else:
self._images = [None]
"""
Pop's a String and Image pair off of the 'image and string lists
not really popping, changed to use a index because I was having issues
with copying the objects, and thought this is faster anyways, more code
but more eficent
"""
def pop(self, i):
if i >= len(self._images):
# if out of strings and images return (None,None) Tuple
if i >= len(self._strings):
return None, None
# otherwise return (String,None) Tuple
return self._strings[i], None
# otherwise we pop off a pair of a string and a image
return self._strings[i], self._images[i]
|
d9f819d9f4be1751951d24cf14164923ee246924 | stroke-one/ProjectEuler_Python | /Euler_007.py | 437 | 3.59375 | 4 | import time
t = time.time()
class prime():
def __init__(self):
self.primes = [2]
def test(self, number):
for n in self.primes:
if number % n == 0:
return
self.primes.append(number)
num = 2
p = prime()
while 1:
num += 1
p.test(num)
if len(p.primes) == 10001:
print(p.primes[-1])
break
print(time.time() - t)
#time 8.036999940872192
|
58c6c0e2929a494e250ae4c7936c8aebe00fb9e4 | stroke-one/ProjectEuler_Python | /Euler_012.py | 539 | 3.578125 | 4 | import time
t = time.time()
def facts(triangle):
factorials = []
for n in range(1, int(triangle**.5)):
if triangle % n == 0:
factorials.append(n)
factorials.append(triangle//n)
return(len(factorials))
current_triangle = 1
current_step = 1
number_of_factorials = 0
while number_of_factorials < 500:
current_step += 1
current_triangle += current_step
number_of_factorials = facts(current_triangle)
print(current_triangle)
print(number_of_factorials)
print(time.time() - t)
|
ac8b06c7597bede605741007b994f3e3c8e56975 | nilidan/Training | /MachineLearning/Starting Template for Trainging and Splitting/data_preprocessing_template.py | 650 | 3.515625 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
print(X)
print(y)
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(X[:, 1:3])
X[:, 1:3]=imputer.transform(X[:, 1:3])
print(X)
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) |
2049e82aa7a5a24f4f9bdf39393b2aba2b1faa6a | kipland-m/PythonPathway | /FactorialRecursion.py | 764 | 4.21875 | 4 | # This program is a part of my program series that I will be using to nail Python as a whole.
# Assuming given parameter is greater than or equal to 1 | Or just 0.
def Factorial(n):
if (n >= 1):
return n * Factorial(n-1)
else:
return 1
# Function Fibonacci will take "n" as parameter, in which said parameter returns value in corresponding
# position within Fibonacci sequence, so if n=4 it would return 4th number in Fibonacci sequence.
def Fibonacci(n):
#If this condition is met it can be referred to as the recursive case
if (n >= 3):
return Fibonacci(n-1) + Fibonacci(n-2)
#If this condition is met it can be referred to as the base case
else:
return 1
print(Factorial(3))
print(Fibonacci(4)) |
5495c20c68683ee40fcfccd91ecdde5f2c5e1a6e | Beard12/PythonWork | /Pylot/loginapp/models/Welcome.py | 3,777 | 3.765625 | 4 | """
Sample Model File
A Model should be in charge of communicating with the Database.
Define specific model method that query the database for information.
Then call upon these model method in your controller.
Create a model using this template.
"""
from system.core.model import Model
import re
class Welcome(Model):
def __init__(self):
super(Welcome, self).__init__()
def create_user(self,info):
EMAIL_REGEX = re.compile(r'^[a-za-z0-9\.\+_-]+@[a-za-z0-9\._-]+\.[a-za-z]*$')
errors = []
# Some basic validation
if not info['first_name'] or not info['last_name']:
errors.append('Your first and last name cannot be blank')
elif len(info['first_name']) < 2 or len(info['last_name']) < 2:
errors.append('Your first and last name must be at least 2 characters long')
elif not info['first_name'].isalpha() or info['last_name'].isalpha():
errors.append('Every character in your first and last name need to be letters')
if not info['email']:
errors.append('Email cannot be blank')
elif not EMAIL_REGEX.match(info['email']):
errors.append('Email format must be valid!')
if not info['password']:
errors.append('Your password cannot be blank')
elif len(info['password']) < 8:
errors.append('Your password must be at least 8 characters long')
elif info['password'] != info['cf_password']:
errors.append('Your password and confirmation must match!')
if errors:
return {"status": False, "errors": errors}
else:
hashed_pw = self.bcrypt.generate_password_hash(info['password'])
data = {
'first_name' : info['first_name'],
'last_name' : info['last_name'],
'email' : info['email'],
'password' : hashed_pw,
'description' : ' ',
'active' : True,
'user_level' : admin
}
query = "INSERT INTO users (first_name, last_name, email, password) VALUES(:first_name, :last_name, :email, :password)"
self.db.query_db(query,data)
return { "status": True}
def login(self,info):
errors=[]
query = "SELECT * FROM users WHERE email = :email LIMIT 1"
data = { 'email': info['email'] }
user = self.db.query_db(query, data)
if len(user) < 1:
errors.append("We do not have your email on file please register")
return {'status': False, "errors" : errors}
elif self.bcrypt.check_password_hash(user[0]['password'], info['password']):
return {'status' : True, 'name': user[0]['first_name']}
else:
errors.append("We're are sorry but your password did not match our records please try again.")
return{'status' : False , "errors" : errors }
"""
Below is an example of a model method that queries the database for all users in a fictitious application
Every model has access to the "self.db.query_db" method which allows you to interact with the database
def get_user(self):
query = "SELECT * from users where id = :id"
data = {'id': 1}
return self.db.get_one(query, data)
def add_message(self):
sql = "INSERT into messages (message, created_at, users_id) values(:message, NOW(), :users_id)"
data = {'message': 'awesome bro', 'users_id': 1}
self.db.query_db(sql, data)
return True
def grab_messages(self):
query = "SELECT * from messages where users_id = :user_id"
data = {'user_id':1}
return self.db.query_db(query, data)
""" |
ff2eb76db8619b619e9e18a4c1a36cc2d2fd1afd | Beard12/PythonWork | /pythonbasic/drawstars.py | 295 | 3.515625 | 4 | def draw_stars(arr):
for x in range(0, len(arr)):
count = arr[x]
if type(count) is str:
print count[0].lower() * len(count),
print ("\n")
else:
for i in range(0, count):
print "*",
print("\n")
x=[4,6,1,3,5,7,25]
b=[4, "Tom", 1, "Micheal", 5, 7, "Jimmy Smith"]
draw_stars(b) |
a4d239d34499301270a10040016fca94af868b91 | asen-krasimirov/Python-Advanced-Course | /Exam-Exercises/Python Advanced Exam Preparation- 17 February 2020/Problem 3- Advent Calendar.py | 366 | 3.84375 | 4 |
def fix_calendar(array):
swaps = -1
while True:
if swaps == 0:
break
swaps = 0
for i in range(len(array)-1):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
swaps += 1
return array
numbers = [3, 2, 1]
fixed = fix_calendar(numbers)
print(fixed)
|
1d85c44a1e6eaa0d02100d03914fecae90d886ff | asen-krasimirov/Python-Advanced-Course | /Exam- Python Advanced - September 2020/Problem 2- Chechmate.py | 1,137 | 4 | 4 |
def valid_index(number):
if -1 < number < 8:
return True
return False
def is_queen_attaching(matrix, directions, *cur_position):
for direction in directions:
local_row, local_column = cur_position
row_delta, column_delta = direction
for _ in range(8):
local_row += row_delta
local_column += column_delta
if not valid_index(local_row) or not valid_index(local_column):
break
if matrix[local_row][local_column] == "Q":
break
if matrix[local_row][local_column] == "K":
return True
return False
field = [input().split() for _ in range(8)]
possible_directions = [
(-1, 0), (1, 0),
(0, -1), (0, 1),
(-1, -1), (-1, 1), (1, -1), (1, 1)
]
attacking_queens = []
for r in range(8):
for c in range(8):
if field[r][c] == "Q":
if is_queen_attaching(field, possible_directions, r, c):
attacking_queens.append([r, c])
if attacking_queens:
for queen in attacking_queens:
print(queen)
else:
print("The king is safe!")
|
7bfd25ac37b7057b5c5df020ca86ce7c92425a23 | asen-krasimirov/Python-Advanced-Course | /2. Tuples and Sets/2.2 Exercises/Problem 1- Unique Usernames.py | 171 | 3.640625 | 4 | number_of_usernames = int(input())
usernames = set()
for _ in range(number_of_usernames):
name = input()
usernames.add(name)
print('\n'.join(usernames))
|
85ffedeeaebc6040cfa3985cbf3622494e634669 | asen-krasimirov/Python-Advanced-Course | /6. File Handling/6.2 Exercises/Problem 3- File Manipulation.py | 1,638 | 3.921875 | 4 | import os
while True:
data = input().split("-")
command = data[0] # Saves the command
if command == "End": # If the command is "End" the program stops
break
file_name = data[1] # Saves the name, all commands use it
if command == "Create":
"""
Creates a new file.
If there is such file, overwrites it.
"""
with open(file_name, "w"):
pass
elif command == "Add":
"""
Adds to the end of a file.
If there isn't such file, creates it and writes inside it.
"""
content = data[2]
with open(file_name, "a") as file:
file.write(content + "\n") # Adds additional new line symbol
elif command == "Replace":
"""
Opens a file, gets it's content and overwrites the file with replaced strings.
"""
old_string = data[2]
new_string = data[3]
if not os.path.exists(file_name): # If the file does not exists trows an skips the command
print("An error occurred")
continue
with open(file_name) as file: # Gets the content
file_content = file.readlines()
with open(file_name, "w") as file: # Replaces all old strings with new ones
for line_ in file_content:
line = line_.replace(old_string, new_string)
file.write(line)
elif command == "Delete":
"""
Deletes the file if it exists.
"""
if not os.path.exists(file_name):
print("An error occurred")
continue
os.remove(file_name)
|
25a1c557ef87b2d713b294d0ea94271f80fd1f2a | asen-krasimirov/Python-Advanced-Course | /3. Multidimensional Lists/3.1 Lab/Problem 4- Symbol in Matrix.py | 611 | 3.984375 | 4 | # def get_input_as_list_in_int(separator=" "):
# return list(map(int, input().split(separator)))
def find_symbol_in_matrix(matrix_, size_, symbol_):
for row in range(size_):
for column in range(size_):
element = matrix_[row][column]
if element == symbol_:
return f"({row}, {column})"
return f"{symbol_} does not occur in the matrix"
size = int(input())
matrix = []
for _ in range(size):
line = list(input())
matrix.append(line)
symbol = input()
result = find_symbol_in_matrix(matrix, size, symbol)
print(result)
|
0445b2d1dc7c3fcdfb2a5eedb9826adf1a34b412 | asen-krasimirov/Python-Advanced-Course | /2. Tuples and Sets/2.1 Lab/Problem 5- SoftUni Party.py | 431 | 3.671875 | 4 | number_of_guests = int(input())
invited_guests = set()
for _ in range(number_of_guests):
name = input()
invited_guests.add(name)
guests_that_came = set()
while True:
name = input()
if name == "END":
break
guests_that_came.add(name)
guests_that_did_not_came = invited_guests - guests_that_came
print(len(guests_that_did_not_came))
print('\n'.join(sorted(guests_that_did_not_came)))
|
02fc6e716ebaccf5a932ff18884a79451e7eb1c8 | asen-krasimirov/Python-Advanced-Course | /1. Lists as Stacks and Queues/1.1. Exercises/Problem 6- Balanced Parentheses 2.py | 602 | 3.671875 | 4 | from collections import deque
sequence = deque(list(input()))
fail_flag = False
if len(sequence) % 2 != 0:
fail_flag = True
while sequence and not fail_flag:
current_bracket = sequence.popleft()
next_bracket = sequence.pop()
if current_bracket == '(' and next_bracket == ')':
continue
elif current_bracket == '[' and next_bracket == ']':
continue
elif current_bracket == '{' and next_bracket == '}':
continue
else:
fail_flag = True
break
if fail_flag:
print("NO")
else:
print("YES")
|
2d771ad4c572f4b08b9ef60d5d7c901df24e82d5 | asen-krasimirov/Python-Advanced-Course | /1. Lists as Stacks and Queues/1.1. Exercises/Problem- Taxi Express.py | 710 | 3.859375 | 4 | from collections import deque
customers = deque(list(map(int, input().split(", "))))
drive = input().split(", ")
drivers = deque(list(map(int, drive[::-1])))
total_time = 0
while customers and drivers:
customer = customers.popleft()
driver = drivers.popleft()
if driver >= customer:
total_time += customer
else:
customers.appendleft(customer)
if not customers:
print("All customers were driven to their destinations")
print(f"Total time: {total_time} minutes")
elif not drivers:
customers = list(map(str, customers))
print("Not all customers were driven to their destinations")
print(f"Customers left: {', '.join(customers)}")
|
89b99e4eb04aa879244d934f43af01c8caa2db46 | asen-krasimirov/Python-Advanced-Course | /Exam-Exercises/Python Advanced Exam - 27 June 2020/Problem 2- Snake.py | 2,385 | 3.546875 | 4 |
class GameLogic:
__possible_moves = {
"up": (-1, 0),
"down": (1, 0),
"left": (0, -1),
"right": (0, 1),
}
def __init__(self, territory):
self.territory = territory
self.territory_size = len(territory)
self.snake_position = self.find_element("S")
self.game_over = False
self.food_quantity = 0
def find_element(self, element):
for r in range(self.territory_size):
for y in range(self.territory_size):
if self.territory[r][y] == element:
return r, y
def snake_position_delta(self, direction):
cur_row, cur_column = self.snake_position
self.territory[cur_row][cur_column] = "."
new_row, new_column = cur_row+self.__possible_moves[direction][0],\
cur_column+self.__possible_moves[direction][1]
self.snake_position = new_row, new_column
return new_row, new_column
def snake_move(self):
cur_row, cur_column = self.snake_position
new_elem = self.territory[cur_row][cur_column]
if new_elem == "*":
self.food_quantity += 1
if self.food_quantity >= 10:
self.game_over = True
if new_elem == "B":
self.territory[cur_row][cur_column] = "."
cur_row, cur_column = self.find_element("B")
self.snake_position = cur_row, cur_column
def place_snake(self):
cur_row, cur_column = self.snake_position
self.territory[cur_row][cur_column] = "S"
def print_territory(self):
for row in self.territory:
print("".join(row))
def validate_index(matrix_length, number):
if -1 < number < matrix_length:
return True
return False
field_size = int(input())
field = [list(input()) for _ in range(field_size)]
game = GameLogic(field)
while not game.game_over:
command = input()
new_position = game.snake_position_delta(command)
if not validate_index(field_size, new_position[0]) or not validate_index(field_size, new_position[1]):
game.game_over = True
continue
game.snake_move()
game.place_snake()
if game.game_over and game.food_quantity < 10:
print("Game over!")
else:
print("You won! You fed the snake.")
print(f"Food eaten: {game.food_quantity}")
game.print_territory()
|
c629410961abac7f096b2022d9e6725356a91fc2 | jantonisito/Daniel-Arbuckles-Mastering-Python | /Chapter01/example_1_2_2_with_main.py | 263 | 3.71875 | 4 | import math
def main():
print(example_function('Alice',7))
print(example_function('Bob', 5))
def example_function(name, radius):
area = math.pi * radius ** 2
return "The area of {} is {}".format(name, area)
if __name__ == '__main__':
main() |
7dc680094d33f5f071e6325038e5185d67792a5f | emimuniz/URIONLINEJUGDLE | /1018 - Cédulas.py | 1,172 | 3.78125 | 4 | #Leia um valor inteiro. A seguir, calcule o menor número de notas possíveis (cédulas) no qual o valor pode ser decomposto.
#As notas consideradas são de 100, 50, 20, 10, 5, 2 e 1. A seguir mostre o valor lido e a relação de notas necessárias.
valor = int(input(''))
val = valor
cem = cinquenta = vinte = dez = cinco = dois = um = 0
if int(valor/100) >= 1:
cem = int(valor/100)
valor -= cem*100
if int(valor/50) >= 1:
cinquenta = int(valor/50)
valor -= cinquenta*50
if int(valor/20) >= 1:
vinte = int(valor/20)
valor -= vinte*20
if int(valor/10) >= 1:
dez = int(valor/10)
valor -= dez*10
if int(valor/5) >= 1:
cinco = int(valor/5)
valor -= cinco*5
if int(valor/2) >= 1:
dois = int(valor/2)
valor -= dois*2
if int(valor/1) >= 1:
um = int(valor/1)
valor -= um*1
print('{}'.format(valor))
print('{} nota(s) de R$ 100,00'.format(cem))
print('{} nota(s) de R$ 50,00'.format(cinquenta))
print('{} nota(s) de R$ 20,00'.format(vinte))
print('{} nota(s) de R$ 10,00'.format(dez))
print('{} nota(s) de R$ 5,00'.format(cinco))
print('{} nota(s) de R$ 2,00'.format(dois))
print('{} nota(s) de R$ 1,00'.format(um))
|
b12a456322a8fa9063ac2d2bda209c2b579ceb0b | emimuniz/URIONLINEJUGDLE | /1051 - Imposto de Renda.py | 526 | 3.765625 | 4 | salario = float(input(''))
if salario <= 2000.00:
print('Isento')
elif 2000.01 < salario <= 3000:
t = (salario - 2000)
tx = (t * 8) / 100
print("R$ %.2f" % tx)
elif 3000.01 < salario <= 4500:
t = (salario - 2000)
t1 = t - 1000
tx1 = (1000 * 8) / 100
tx2 = (t1 * 18) / 100
print("R$ %.2f" % (tx1 + tx2))
else:
t = (salario - 2000)
t1 = t - 1000
tx1 = (1000 * 8) / 100
t2 = t1 - 1500
tx2 = (1500 * 18) / 100
tx = (t2 * 28) / 100
print("R$ %.2f" % (tx + tx1 + tx2)) |
6e0da55d79941b5c5346e974de8dbf1a964951d9 | cihangiroksuz/python | /Koşullu Durumlar/mükemmelsayıbulma_2.py | 386 | 3.71875 | 4 | x=int(input("Lütfen sayı giriniz:"))
b=1
c=int()
toplam=int()
while 1:
b=b+1
if b<=x:
if x%b==0:
c=x/b
print(c)
toplam=toplam+c
else:
break
print("Toplam:{}" .format(toplam))
if toplam==x:
print("Girilen sayı MÜKEMMEL SAYI'dır.")
else:
print("Girilen sayı MÜKEMMEL SAYI değildir.")
|
e39b60eb97dcccc582853714ff3370ad4cac1fdc | cihangiroksuz/python | /fonksiyonlar/ekok,.py | 900 | 3.828125 | 4 | def ekok(x, y):
ekok1 = 1
ekok2 = 1
ekok3 = 1
i = 2
while 1:
if x % i == 0 and y % i != 0:
x = x / i
ekok1 = ekok1 * i
elif y % i == 0 and x % i != 0:
y = y / i
ekok2 = ekok2 * i
elif x % i == 0 and y % i == 0:
x = x / i
y = y / i
ekok3 = ekok3 * i
else:
i = i + 1
if (x == 1 and y == 1):
break
sonuc = ekok1 * ekok2 * ekok3
return sonuc
while 1:
print("Programdan çıkmak için q 'ya basınız.")
y = (input("Lütfen sayı giriniz:"))
z = (input("Lütfen sayı giriniz:"))
if y == 'q' or z == 'q':
print("Programdan çıkılıyor....")
break
else:
b: int = int(y)
c: int = int(z)
a = ekok(b, c)
print(a)
|
1569b35a0e54cd3a8c65961822601ad613536628 | cihangiroksuz/python | /Koşullu Durumlar/kullanıcı_girisi.py | 338 | 3.671875 | 4 | print("Lütfen kullanıcı adı ve şifrenizi giriniz\n")
kullaniciadi=str(input("Kullanıcı Adı:"))
parola=str(input("Parola:"))
if kullaniciadi == 'boztepeghetto' and parola == 'ghettokemal61':
print("Giriş onaylandı.")
else:
print("Kullanıcı adı ya da parolayı yanlış giridniz. Lütfen tekrar deneyiniz.")
|
5f72be073a858b4421bbc997bc021b0d97aeeb72 | sreeramvasu/Coursera_Python | /Pong.py | 4,948 | 3.984375 | 4 | # Implementation of classic arcade game Pong
# Author: SV
# Mailto: sreeram.vasudevan@gmail.com
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
LEFT = False
RIGHT = True
# initialize ball_pos and ball_vel for new bal in middle of table
ball_pos = [WIDTH / 2, HEIGHT / 2]
ball_vel = [2, 1]
# initialize paddle parameters
paddle1_pos = PAD_HEIGHT / 2
paddle2_pos = PAD_HEIGHT / 2
paddle1_vel = 0
paddle2_vel = 0
PADDLE_VEL = 5 # the speed with which either of the paddle moves
# initialize score variables score1 and score2
score1 = 0
score2 = 0
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
# ball position
ball_pos = [WIDTH / 2, HEIGHT / 2]
# horizontal velocity
ball_vel[0] = -random.randrange(120, 240) / 100
if direction == RIGHT:
ball_vel[0] *= -1
# vertical velocity
ball_vel[1] = -random.randrange(60, 180) / 100
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2 # these are ints
# set/reset the scores
score1 = 0
score2 = 0
# set/reset the paddle positions
paddle1_pos = HEIGHT / 2
paddle2_pos = HEIGHT / 2
# set/reset the ball
direction = ball_vel[0] > 0
spawn_ball(direction)
def draw(c):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
# draw mid line and gutters
c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
if ball_pos[0] >= WIDTH - BALL_RADIUS - PAD_WIDTH or ball_pos[0] <= BALL_RADIUS + PAD_WIDTH:
# ball goes to side
if paddle1_pos < ball_pos[1] < paddle1_pos + PAD_HEIGHT and ball_vel[0] < 0: # ball bounces from paddle1
ball_vel[0] *= -1.1 # 10% increase in the velocity
ball_vel[1] *= 1.1
elif paddle2_pos < ball_pos[1] < paddle2_pos + PAD_HEIGHT and ball_vel[0] > 0: # ball bounces from paddle2
ball_vel[0] *= -1.1 # 10% increase in the velocity
ball_vel[1] *= 1.1
else:
if ball_vel[0] > 0: # ball falls in right gutter
score1 += 1
else: # ball falls in left gutter
score2 += 1
direction = ball_vel[0] < 0
spawn_ball(direction) # start the ball from the center when falls in gutter
if ball_pos[1] >= HEIGHT - BALL_RADIUS or ball_pos[1] <= BALL_RADIUS: # ball goes to bottom/top
ball_vel[1] = -ball_vel[1]
# draw ball
c.draw_circle(ball_pos, BALL_RADIUS, 2, 'White', 'White')
# update paddle's vertical position, keep paddle on the screen
if (paddle1_pos <= HEIGHT - PAD_HEIGHT and paddle1_vel > 0) or (paddle1_pos >= 0 and paddle1_vel < 0):
paddle1_pos += paddle1_vel
elif (paddle2_pos <= HEIGHT - PAD_HEIGHT and paddle2_vel > 0) or (paddle2_pos >= 0 and paddle2_vel < 0):
paddle2_pos += paddle2_vel
# draw paddles
c.draw_polygon([[0, paddle1_pos], [PAD_WIDTH, paddle1_pos], [PAD_WIDTH, paddle1_pos + PAD_HEIGHT ], [0, paddle1_pos + PAD_HEIGHT]], 1, 'White', 'White')
c.draw_polygon([[WIDTH, paddle2_pos], [WIDTH - PAD_WIDTH, paddle2_pos], [WIDTH - PAD_WIDTH, paddle2_pos + PAD_HEIGHT], [WIDTH, paddle2_pos + PAD_HEIGHT]], 1, 'White', 'White')
# draw scores
c.draw_text(str(score1), [40, 50], 30, 'White')
c.draw_text(str(score2), [WIDTH - 80, 50], 30, 'White')
def keydown(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP['down']:
paddle2_vel = PADDLE_VEL
if key == simplegui.KEY_MAP['up']:
paddle2_vel = -PADDLE_VEL
if key == simplegui.KEY_MAP['w']:
paddle1_vel = -PADDLE_VEL
if key == simplegui.KEY_MAP['s']:
paddle1_vel = PADDLE_VEL
def keyup(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP['down']:
paddle2_vel = 0
if key == simplegui.KEY_MAP['up']:
paddle2_vel = 0
if key == simplegui.KEY_MAP['w']:
paddle1_vel = 0
if key == simplegui.KEY_MAP['s']:
paddle1_vel = 0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
# adding restart button to start a new game
frame.add_button("Restart", new_game, 100)
# start frame
new_game()
frame.start()
|
e32e692b073d079bb59aa2ed83460f8f3ff8802d | mukeshmithrakumar/PythonUtils | /PythonMasterclass/Exercise2.py | 1,362 | 4.5625 | 5 | """
Create a program that takes an IP address entered at the keyboard
and prints out the number of segments it contains, and the length of each segment.
An IP address consists of 4 numbers, separated from each other with a full stop. But
your program should just count however many are entered
Examples of the input you may get are:
127.0.0.1
.192.168.0.1
10.0.123456.255
172.16
255
So your program should work even with invalid IP Addresses. We're just interested in the
number of segments and how long each one is.
Once you have a working program, here are some more suggestions for invalid input to test:
.123.45.678.91
123.4567.8.9.
123.156.289.10123456
10.10t.10.10
12.9.34.6.12.90
'' - that is, press enter without typing anything
This challenge is intended to practise for loops and if/else statements, so although
you could use other techniques (such as splitting the string up), that's not the
approach we're looking for here.
"""
IP_address =(input("Please enter an IP Address: \n"))
segment_length = 0
segment = 1
for char in IP_address:
if (char !='.'):
segment_length += 1
else:
print("The {} segment length is {}".format(segment,segment_length))
segment_length = 0
segment += 1
if char != '.':
print("The {} segment length is {}".format(segment, segment_length))
|
7016534bdc605ab2cea27bfb6916c440c52ad441 | leahabiol/conditionals | /conditionals.py | 1,653 | 4.09375 | 4 | # if "Sammie" > "Leah":
# print "My name is greater!"
# elif "Leah" > "Sammie":
# print "Their name is greater."
# else:
# print "Our names are equal!"
# date = 19
# if date > 15:
# print "Oh, we're halfway there!"
# else:
# print "The month is still young."
# today = "Thursday"
# if today == "Monday":
# print "Yaaas Monday! Here we go!"
# elif today == "Tuesday":
# print "Sigh, it's only Tuesday."
# elif today == "Wednesday":
# print "Humpday!"
# elif today == "Thursday":
# print "#tbt"
# elif today == "Friday":
# print "TGIF!"
# else:
# print "Yeah, it's the weekend!"
# age = 33
# # if age >= 18:
# # print "Yay! I can vote!"
# # else:
# # print "Aww, I cannot vote."
# # if age >= 18 and age >= 21:
# # print "I can vote and go to a bar!"
# if age >= 21:
# print "I can go to a bar."
# elif age >= 18:
# print "I can vote, but I cannot go to a bar."
# else:
# print "I cannot vote or go to a bar."
# if 8 % 2 == 0:
# print "The number 8 is even."
# else:
# print "The number 8 is odd."
# if 8 % 2 != 0:
# print "The number 8 is odd."
# else:
# print "The number 8 is even."
# if 8 % 2 == 0 and 9 % 2 == 0:
# print "Both numbers are even."
# elif 8 % 2 == 0 and 9 % 2 != 0:
# print "8 is even and 9 is odd."
# elif 8 % 2 != 0 and 9 % 2 == 0:
# print "8 is odd and 9 is even."
# else:
# print "Both numbers are odd."
favorite_color = "black"
if favorite_color == "blue" or favorite_color == "yellow" or favorite_color == "red":
print "My favorite color is primary color."
else:
print "My favorite color is a secondary color."
|
4dae827b1f8b2e14be39ceff7a8dc3926051de17 | jpz/puzzles | /listener-4425/foursquares.py | 2,062 | 3.96875 | 4 | #!/usr/bin/env python3
##################################
# PUBLIC INTERFACE
##################################
# This file implements a dictionary of the sum of square solutions for n, where
# n = a^2 + b^2 + c^2 + d^2, and a to d are rangebound from [0..25], and a >= b >= c >= d
# A solution is determined according to precedence rules which favours a minimum number
# of squares when there are two solutions, i.e. d, c, or b = 0, and thereafter, larger leading numbers,
# e.g. 18 = 3^2 + 3^2 = 4^2 + 1^2 + 1^2, however [3 3 0 0] is the solution for 18 due to fewer digits required.
# 55 = 5^2 + 5^2 + 2^2 1^2 = 7^2 + 2^2 + 1^2 + 1^2, however [7 2 1 1] is preferred due to larger leading numbers (7 > 5)
def get_foursquare(num):
return FOURSQUARES.get(num)
def get_foursquare_inv(nums):
return get_foursquare(sum_of_squares(nums))
def is_foursquare(nums):
nums = _regularise_numbers(nums)
return get_foursquare_inv(nums) == nums
##################################
# IMPLEMENTATION
##################################
FOURSQUARES = {}
def _regularise_numbers(numbers: list):
"""sorts the numbers descending, and removes all zeros"""
nums = numbers.copy()
ok = True
while ok:
try:
nums.remove(0)
except:
ok = False
nums.sort(reverse=True)
return nums
def sum_of_squares(lst: list):
return sum(n * n for n in lst)
def _init():
for i in range(26):
for j in range(26):
for k in range(26):
for l in range(26):
nums = _regularise_numbers([i, j, k, l])
total = sum_of_squares(nums)
if total in FOURSQUARES:
old = FOURSQUARES[total]
if len(nums) < len(old):
FOURSQUARES[total] = nums
elif len(nums) == len(old) and nums > old:
FOURSQUARES[total] = nums
else:
FOURSQUARES[total] = nums
_init()
|
913657a4a9e4cd57ed5d46802060bb3661732448 | tsigemit/Python_Script | /week2/practice.py | 523 | 3.8125 | 4 | whole_deck = "abcdefg"
my_card = "h"
print('Looking for card', my_card,'among', whole_deck)
top = len(whole_deck)
bottom = 0
while bottom < top:
print('bottom =', bottom, 'top =', top,
'- remaining cards', whole_deck[bottom:top])
middle = (top+bottom)//2
if whole_deck[middle] == my_card:
break
elif my_card < whole_deck[middle]:
top = middle-1;
else:
# my_card > whole_deck[middle]
bottom = middle+1
print('Card', my_card, 'is at position', middle)
|
b01c601a91f9d5f9489e2633cd2faa2d1a5bc2ab | risg99/Data-Science | /Corona/visualisation.py | 6,215 | 3.8125 | 4 | #!/usr/bin/env python
# coding: utf-8
# We are just going to visualize the dataset given in this python notebook using Choropleth Maps.
#
#
# A choropleth map is a type of thematic map where areas or regions are shaded in proportion to a given data variable.
# Static choropleth maps are most useful when you want to compare a desired variable by region. For example, if you wanted to compare the crime rate of each state in the US at a given moment, you could visualize it with a static choropleth.
#
#
# An animated or dynamic choropleth map is similar to a static choropleth map, except that you can compare a variable by region, over time. This adds a third dimension of information and is what makes these visualizations so interesting and powerful.
# In[2]:
# Import libraries
import numpy as np
import pandas as pd
import plotly as py
import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
# In[4]:
# Read Data
df = pd.read_csv("covid_19_data.csv")
print(df.head())
# In[5]:
df = df.rename(columns={'Country/Region':'Country'})
df = df.rename(columns={'ObservationDate':'Date'})
# In[6]:
df.head()
# In[7]:
# Manipulate Dataframe
df_countries = df.groupby(['Country', 'Date']).sum().reset_index().sort_values('Date', ascending=False)
df_countries = df_countries.drop_duplicates(subset = ['Country'])
df_countries = df_countries[df_countries['Confirmed']>0]
# In[8]:
df.head()
# In[9]:
df_countries.head()
# In[10]:
# Create the Choropleth for confirmed cases
fig = go.Figure(data=go.Choropleth(
locations = df_countries['Country'],
locationmode = 'country names',
z = df_countries['Confirmed'],
colorscale = 'Reds',
marker_line_color = 'black',
marker_line_width = 0.5,
))
fig.update_layout(
title_text = 'Confirmed Cases as of March 28, 2020',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
projection_type = 'equirectangular'
)
)
# In[11]:
# Manipulate Dataframe
df_countries1 = df.groupby(['Country', 'Date']).sum().reset_index().sort_values('Date', ascending=False)
df_countries1 = df_countries1.drop_duplicates(subset = ['Country'])
df_countries1 = df_countries1[df_countries1['Deaths']>0]
# In[12]:
df_countries1
# In[13]:
# Create the Choropleth for death cases
fig = go.Figure(data=go.Choropleth(
locations = df_countries1['Country'],
locationmode = 'country names',
z = df_countries1['Deaths'],
colorscale = 'Reds',
marker_line_color = 'black',
marker_line_width = 0.5,
))
fig.update_layout(
title_text = 'Death Cases as of March 28, 2020',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
projection_type = 'equirectangular'
)
)
# In[14]:
# Manipulate Dataframe
df_countries2 = df.groupby(['Country', 'Date']).sum().reset_index().sort_values('Date', ascending=False)
df_countries2 = df_countries2.drop_duplicates(subset = ['Country'])
df_countries2 = df_countries2[df_countries2['Recovered']>0]
# In[15]:
df_countries2
# In[16]:
# Create the Choropleth for recovered cases
fig = go.Figure(data=go.Choropleth(
locations = df_countries2['Country'],
locationmode = 'country names',
z = df_countries2['Recovered'],
colorscale = 'Reds',
marker_line_color = 'black',
marker_line_width = 0.5,
))
fig.update_layout(
title_text = 'Recovered Cases as of March 28, 2020',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
projection_type = 'equirectangular'
)
)
# In the above we are just inputting the location, location mode and z as the parameters, rest all of the code is the standard plotly code for choropleth graph. Reference: https://plotly.com/python/choropleth-maps/
# Let's look at how much more effective and engaging an animated choropleth map is compared to a static one.
# In[17]:
# Manipulating the original dataframe
df_countrydate = df[df['Confirmed']>0]
df_countrydate = df_countrydate.groupby(['Date','Country']).sum().reset_index()
df_countrydate
# In[18]:
# Creating the visualization
fig = px.choropleth(df_countrydate,
locations="Country",
locationmode = "country names",
color="Confirmed",
hover_name="Country",
animation_frame="Date"
)
fig.update_layout(
title_text = 'Global Spread of Coronavirus (wrt confirmed cases)',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
))
fig.show()
# In[19]:
# Manipulating the original dataframe
df_countrydate1 = df[df['Deaths']>0]
df_countrydate1 = df_countrydate1.groupby(['Date','Country']).sum().reset_index()
df_countrydate1
# In[21]:
# Creating the visualization
fig = px.choropleth(df_countrydate1,
locations="Country",
locationmode = "country names",
color="Deaths",
hover_name="Country",
animation_frame="Date"
)
fig.update_layout(
title_text = 'Globally deceased due to Coronavirus (wrt deaths cases)',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
))
fig.show()
# In[22]:
# Manipulating the original dataframe
df_countrydate2 = df[df['Deaths']>0]
df_countrydate2 = df_countrydate2.groupby(['Date','Country']).sum().reset_index()
df_countrydate2
# In[23]:
# Creating the visualization
fig = px.choropleth(df_countrydate2,
locations="Country",
locationmode = "country names",
color="Recovered",
hover_name="Country",
animation_frame="Date"
)
fig.update_layout(
title_text = 'Global recovery due to Coronavirus (wrt recovered cases)',
title_x = 0.5,
geo=dict(
showframe = False,
showcoastlines = False,
))
fig.show()
|
a05db85fa702bd7b4c723c111aad94243a0c1b1e | Ares-debugger/Frontend-01-Template | /week02/三种递归二叉树遍历.py | 1,081 | 3.515625 | 4 |
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def helper(root):
if root:
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
return res
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def helper(root):
if root:
helper(root.left)
helper(root.right)
res.append(root.val)
helper(root)
return res
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def helper(root):
if root:
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res
solu = Solution()
# print(solu.preorderTraversal([2,7,11,13],9))
|
0512db35031316c393b4571c8dca11b0a411b22a | kramin343/test_2 | /first.py | 428 | 4.28125 | 4 | largest = None
smallest = None
while True:
num1 = input("Enter a number: ")
try:
num = float(num1)
except:
print('Invalid input')
continue
if num == "done" :
break
if largest == none:
largest = num
smallest = num
if largest < num:
largest = num
if smallest > num:
smallest = num
print("Maximum is",largest)
print("Minimum is",smallest) |
ebdd809c06fe5aa9bef2639eba594c976357c5b8 | JeffACate/LearnPythonProject | /Code/AverageConfidence.py | 400 | 3.53125 | 4 | tot = 0
count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
else:
line = line.strip()
start = line.find('0')
end = len(line)
section = line[start:end]
num = float(section)
tot = num + tot
count = count + 1
print("Average spam confidence: ", tot/count)
|
5bee6ade1e7340c4fc502c4cc2cad724c40342be | maharshmellow/patelib | /patelib/adt/boundedQueue.py | 1,637 | 3.796875 | 4 | class BoundedQueue:
"""Queue with a capacity"""
def __init__(self, capacity):
self.__items = []
self.__capacity = capacity
try:
if (int(capacity) >= 0):
pass
else:
raise
except:
raise
def enqueue(self, item):
try:
if len(self.__items) < self.__capacity:
self.__items.append(item)
else:
raise
except:
raise
def dequeue(self):
try:
if len(self.__items) > 0:
firstElement = self.__items[0]
self.__items.remove(firstElement)
return(firstElement)
else:
raise
except:
raise
def peek(self):
try:
if len(self.__items) > 0:
firstElement = self.__items[0]
return(firstElement)
else:
raise
except:
raise
def isEmpty(self):
if len(self.__items) == 0:
return(True)
else:
return(False)
def isFull(self):
if len(self.__items) == self.__capacity:
return(True)
else:
return(False)
def size(self):
return(len(self.__items))
def capacity(self):
return(self.__capacity)
def clear(self):
self.__items = []
def getItems(self):
# backend way to get the items even though they are meant to be private
return(self.__items)
def __str__(self):
return(str(self.__items))
|
56ba1be71e3cc80e4844ed48172d8b54ad112808 | maharshmellow/patelib | /patelib/adt/queue.py | 786 | 3.5 | 4 | class Queue:
"""ADT - First in First Out"""
def __init__(self):
self.__items = []
def queue(self, item):
self.__items.append(item)
def dequeue(self):
if len(self.__items) > 0:
removedItem = self.__items[0]
self.__items.remove(removedItem)
return(removedItem)
def peek(self):
if len(self.__items) > 0:
return(self.__items[0])
def isEmpty(self):
return(len(self.__items) == 0)
def size(self):
return(len(self.__items))
def clear(self):
self.__items = []
def getItems(self):
# backend way to get the items even though they are meant to be private
return(self.__items)
def __str__(self):
return(str(self.__items))
|
0ca502687d92d2e25228cf70a6cc1fe8499ae045 | victormaiam/python_studies | /conditions.py | 1,111 | 4.15625 | 4 | is_hot = False
is_cold = False
if is_hot:
print("It`s a hot day.")
print ("Drink plenty of water.")
elif is_cold:
print("It`s a cold day.")
print("Wear warm clothes.")
else:
print("It`s a lovely day.")
print("Enjoy your day.")
tem_credito = False
preco = 1000000
preco1 = preco * 0.10
preco2 = preco * 0.20
if tem_credito:
print(preco1)
else:
print(preco2)
print("Sua entrada é nesse valor.")
if tem_credito:
entrada = 0.1 * preco
else:
entrada = 0.2 * preco
print(f"Entrada: R${entrada}" )
tem_salario_alto = True
tem_bom_credito = False
if tem_salario_alto and tem_bom_credito:
print("Você pode pegar um empréstimo")
else:
print("Você não pode pegar empréstimo.")
if tem_bom_credito or tem_salario_alto:
print("Você pode pegar um empréstimo")
temperatura = 30
if temperatura != 30:
print("É um dia quente!")
else:
print("Não é um dia quente.")
nome = "Victor"
if len(nome) < 3:
print("Nome precisa ter 3 caracteres")
elif len(nome) > 50:
print("Nome só pode ter até 50 caracteres.")
else:
print("Parece bom!") |
3e7950446a092a65ef871c98e64e9820a6e637a5 | victormaiam/python_studies | /exercise1_4.py | 399 | 4.3125 | 4 | ''''
Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.
'''
def calcula_soma(limite):
soma = 0
for i in range(0, limite + 1):
if i%3 == 0 or i%5 == 0:
soma = soma + i
return(soma)
limite = 20
soma = calcula_soma(limite)
print(soma) |
b6e5336a9730937696b15554609ee1334bdc6203 | junglefire/introduction_to_ml_with_python | /chap04/dummy_variables.py | 1,573 | 3.671875 | 4 | import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
# 导入mglearn模块
import sys
sys.path.append("../")
import mglearn
# The file has no headers naming the columns, so we pass header=None
# and provide the column names explicitly in "names"
data = pd.read_csv("./data/adult.data", header=None, index_col=False, names=['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income'])
# For illustration purposes, we only select some of the columns
data = data[['age', 'workclass', 'education', 'gender', 'hours-per-week', 'occupation', 'income']]
# IPython.display allows nice output formatting within the Jupyter notebook
# display(data.head())
print(data.head())
print("\n\n")
print(data.gender.value_counts())
print("\n\n")
print("Original features:\n", list(data.columns), "\n")
data_dummies = pd.get_dummies(data)
print("Features after get_dummies:\n", list(data_dummies.columns))
print("\n\n")
# print(data_dummies.head())
features = data_dummies.ix[:, 'age':'occupation_ Transport-moving']
# Extract NumPy arrays
X = features.values
y = data_dummies['income_ >50K'].values
print("X.shape: {} y.shape: {}".format(X.shape, y.shape))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
print("Test score: {:.2f}".format(logreg.score(X_test, y_test)))
|
2b7f8be7b350e53a298987a6f562b76fd04e9216 | hoo00nn/Algorithm | /Programmers_Lv2/Hash-위장(Level2).py | 377 | 3.5625 | 4 | def solution(clothes):
answer = 1
test = {}
for i in dict(clothes).values():
if i in test.keys():
test[i] += 1
else:
test[i] = 1
for i in test.keys():
test[i] += 1
answer *= test[i]
return answer-1
solution([["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]])
|
6e815f5e411a15b3ad1ea382adbedae06072ffd5 | hoo00nn/Algorithm | /Programmers_Lv2/Sort-K번째 수(Level1).py | 353 | 3.515625 | 4 | def solution(array, commands):
answer = []
for i in range(0, len(commands)):
start = commands[i][0] - 1
end = commands[i][1]
num = commands[i][2] - 1
isSorted = sorted(array[start:end])
answer.append(isSorted[num])
return answer
solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]]) |
10b58c2923c3a3a2508bd44ae011a64301c61e92 | hoo00nn/Algorithm | /Programmers_Lv2/Level2-폰켓몬.py | 792 | 3.59375 | 4 | # 첫 번째 시도 정확성 30.0 나머지 시간초과..
from itertools import combinations
def solution(nums):
answer = list(map(lambda x: len(set(x)), combinations(nums, len(nums) // 2)))
return max(answer)
# 두 번째 시도 정확성 80.0 나머지 시간초과..
from itertools import combinations
def solution(nums):
if len(nums) // 2 >= len(set(nums)):
return len(set(nums))
answer = list(map(lambda x: len(set(x)), combinations(nums, len(nums) // 2)))
return max(answer)
# 세 번째 시도 통과
# 조금만 생각해보면 되게 간단한 문제였는데,,
# 문제 잘 읽고 입출력 예시에서 힌트를 찾자!
def solution(nums):
if len(nums) // 2 >= len(set(nums)):
return len(set(nums))
return len(nums) // 2 |
57d3c5593f11f34bebb752bad652fa60ac9b5aee | hoo00nn/Algorithm | /Programmers_Lv1/Level1-시저 암호.py | 519 | 3.703125 | 4 | # 문자를 ASCII 코드로 변환하는 함수 ord() 함수
# ASCII 코드를 문자로 변환하는 함수 chr() 함수
def solution(s, n):
answer = ''
ALPHA = 26
ALPHA_LOWER = 97
ALPHA_UPPER = 65
for i in s:
if i == ' ':
answer += ' '
else:
if i.isupper():
answer += chr(ALPHA_UPPER + (ord(i) + n - ALPHA_UPPER) % ALPHA)
else:
answer += chr(ALPHA_LOWER + (ord(i) + n - ALPHA_LOWER) % ALPHA)
return answer |
ae2d1018c63e42d3cf8ebc036f6777fbbc588f1e | hoo00nn/Algorithm | /알고리즘 구현/DFS와 BFS/깊이 우선 탐색.py | 414 | 3.53125 | 4 | def dfs(graph, root):
visited = []
stack = [root]
while stack:
n = stack.pop()
if n not in visited:
visited.append(n)
stack += set(graph[n]) - set(visited)
print(n)
return visited
graph_list = {1: [2, 3, 4],
2: [1, 4],
3: [1, 4],
4: [1, 2, 3]
}
root_node = 1
dfs(graph_list, root_node)
|
68bd2c0f2ef93783095770f31b5b47ac42dacd8a | ASh1ne/myownrepo | /exercise6.py | 436 | 3.984375 | 4 | dayCount = 0
print("Введите начальную дистанцию")
defaultDistance = int(input())
print("Введите необходимый результат")
upgradeDistance = int(input())
while defaultDistance <= upgradeDistance:
defaultDistance = defaultDistance + (defaultDistance*0.1)
dayCount += 1
print(f"Спортсмен достиг результата {defaultDistance:.2f} на {dayCount} день") |
83ca590d681b8cc8b76146d7a4fdd539c880b4e1 | pythonRepo4/SEC-Scrape | /SQL/SQLMethods.py | 1,882 | 3.5 | 4 | from SQL import sqlite as sql
"""-----------------------------------------------------------------------------------
Returns earnings data from EarningsData.db
-----------------------------------------------------------------------------------"""
def getDebtData(tickerName, year):
try:
tableName = tickerName + "_debt_" + str(year)
tempData = sql.executeReturn('SELECT * FROM ' + tableName)
return tempData[0]
except:
return None
def returnTable(tableName):
try:
tempData = sql.executeReturn('SELECT * FROM ' + tableName)
return tempData[0]
except:
return None
"""-----------------------------------------------------------------------------------
Insert Operating Lease commitments as tickername, year, [y1, y2, y3, y4, y5, all others]
-----------------------------------------------------------------------------------"""
def insertDebt(tickerName, year, data):
tableName = tickerName + "_debt_" + str(year)
sql.execute("DROP TABLE IF EXISTS " + tableName , None)
sql.execute('CREATE TABLE ' + tableName + "(y1 REAL, y2 REAL, y3 REAL, y4 REAL, y5 REAL, y6 REAL)", None)
sql.execute("INSERT INTO " + tableName + " VALUES (?,?,?,?,?,?)" , data)
"""-----------------------------------------------------------------------------------
getAll will return all tables currently in HistoricalPrices.db.
removeTicker will remove that table from the database.
-----------------------------------------------------------------------------------"""
def getAll():
allTables = sql.executeReturn("SELECT name FROM sqlite_master WHERE type = 'table';")
return allTables
def deleteTicker(tickerName):
sql.execute('DROP TABLE IF EXISTS ' + tickerName, None)
#
# list = ["MSFT"]
# for i in list:
# for j in range(2012,2018):
# print(getDebtData(i, str(j))) |
f8585415e04f4b7d84726d0888d82bdcf009de67 | LimbOfTree/LegisQuest | /BookHomework/Vehicles.py | 406 | 3.78125 | 4 | class vehicle:
def __init__(self):
raise NotImplementedError('Don\'t just make a vehicle, make a specific type of vehicle.')
def __str__(self):
return "{}".format(self.name)
class motorcycle(vehicle):
def __init__(self):
self.name = 'Motorcycle'
self.wheels = 4
class car(vehicle):
def __init__(self):
self.name = 'Car'
self.wheels = 4 |
0e2fa11b94b12602692645663ecdcd57317e79a4 | leomatheuss/aulapy | /LISTA3/tuplas.py | 316 | 3.78125 | 4 | """
Tuplas são bastante parecidas com listas
Existem duas diferenças básicas:
Sua representação é por parenteses ()
Tuplas são IMUTÁVEIS. Toda operação em uma tupla, gera uma nova tupla
"""
# É possível gerar uma tupla dinamicamente com range(inicio, fim, passo)
tupla = tuple(range(1,6,2)) |
f7d81f1ed243a05e02f725f081cfa3dd37605d70 | leomatheuss/aulapy | /LISTA2/lista2sec5e3.py | 264 | 3.765625 | 4 | #notas válidas
nota1 = float(input())
nota2 = float(input())
if ((0.0 < nota1 < 10.0) and (0.0 < nota2 < 10.0)) == True:
media = (nota1 + nota2 )/ 2
print(f'A média das duas notas é {media}')
else:
print("Uma, ou as duas notas estão inválidas")
|
d7d60620c5192189c1dbfb89a006a7f607945617 | leomatheuss/aulapy | /LISTA 1/atividade3.py | 152 | 3.78125 | 4 | idade = int(input())
ano_atual = int(input('Entre com o ano atual'))
ano_nasc = ano_atual - idade
print(f"O ano de nascimento da pessoa é: {ano_nasc}") |
6bb25ae3b0ce05f16ecd3f34cfdcd997ab1c1805 | leomatheuss/aulapy | /URI_atividades/1168.py | 176 | 3.828125 | 4 | leds = (6,2,5,5,4,5,6,4,7,6)
n = int(input())
for i in range(n):
num = input()
soma = 0
for j in num:
soma = soma + leds[int(j)]
print(soma, "leds") |
2c7b33bf5b87afc2ebe5379d3705b7b30576831b | leomatheuss/aulapy | /URI_atividades/1120.py | 269 | 3.609375 | 4 | while True:
x, y = map(int,input().split())
if x == 0 and y == 0:
break
else:
x = str(x)
y = str(y)
b = y.replace(x, '')
if b == '':
print(0)
else:
y = int(b)
print(y) |
963c397a588e8db33c06323cd90e225051eb77b8 | leomatheuss/aulapy | /URI_atividades/mdcteste.py | 171 | 3.609375 | 4 | def mdc(x,y):
mdc1 = x
while x % mdc1 != 0 or y % mdc1 != 0:
mdc1 = mdc1 - 1
return print(mdc1)
f1 = int(input())
f2 = int(input())
mdc(f1, f2) |
3c057937f265a653fde61863d1d4ed3088a3e73d | leomatheuss/aulapy | /URI_atividades/1065.py | 183 | 3.640625 | 4 | nums = []
for i in range(1,6):
nums.append(int(input()))
cont = 0
for j in nums:
if j % 2 == 0:
cont = cont + 1
else:
pass
print(cont,"valores pares") |
9508618304d962e676556eb7b1a78a818bdd3dae | leomatheuss/aulapy | /URI_atividades/1132_func.py | 315 | 4.0625 | 4 | def verifica(x, y):
'''
Função que vai verificar se o número é divisível por 13
'''
teste = 0
for i in range(x, y+1):
if i % 13 != 0:
teste = teste + i
print(teste)
a = int(input())
b = int(input())
if a < b:
verifica(a, b)
elif a > b:
verifica(b, a)
|
9a95ff5dd167c9ecae9fc8392620899db10719f5 | MysticAhuacatl/PHY494 | /assignments-2019-MysticAhuacatl/assignment_04/Submission/problem1.py | 708 | 3.5625 | 4 | # Problem 4.
s = """'But I don't want to go among mad people,' Alice remarked.
'Oh, you can't help that,' said the Cat, 'we're all mad here. I'm
mad. You're mad.' 'How do you know I'm mad?' said Alice. 'You
must be,' said the Cat, 'or you wouldn't have come here.'"""
counts = [0,0,0,0,0,0]
def count_vowels(words):
words = words.lower()
for letter in words:
if letter=='a':
counts[0] += 1
if letter=='e':
counts[1] += 1
if letter=='i':
counts[2] += 1
if letter=='o':
counts[3] += 1
if letter=='u':
counts[4] += 1
if letter=='y':
counts[5] += 1
count_vowels(s)
print(counts)
|
9f8362f2099487f776356be66e3d34aecfedc32b | MysticAhuacatl/PHY494 | /assignments-2019-MysticAhuacatl/assignment_02/Solution/addtemperatures.py | 223 | 3.78125 | 4 | # HW02 2.2
T_K = float(input("Temperature in Kelvin --> "))
theta_F = float(input("Temperature difference in Fahrenheit --> "))
delta_T_K = 5/9 * theta_F
T_total = T_K + delta_T_K
print("Total T " + str(T_total) + " K")
|
1e81046ef18617b2f1d1a7f5f105fe619dafb6c7 | oneelay/Intro_Biocomp_ND_318_Tutorial5 | /Exercise5_new.py | 1,374 | 3.765625 | 4 | #Exercise 5 Om and Joshua
import os
import numpy
import pandas
#Set working directory and read in wages file
os.chdir('C:\\Users\\joshu\\OneDrive\\github\\BioComp\\Intro_Biocomp_ND_318_Tutorial5\\')
wages=pandas.read_csv("wages.csv")
#START OF CHALLENGE 1
#isolate 2 columns: Gender and YearsExperience
first2columns=wages.iloc[:,0:2]
#isolate females and males separately
females=first2columns[first2columns.gender=="female"]
males=first2columns[first2columns.gender=="male"]
#remove duplicates and make into panda dataframe form
F=females.drop_duplicates()
M=males.drop_duplicates()
f=pandas.DataFrame(F)
m=pandas.DataFrame(M)
#concatenate dataframes and write to a file
A=pandas.concat([f,m])
first2columnsA=A.iloc[:,0:2]
first2columnsA
A.to_csv("challenge1.txt",sep=' ')
#START OF CHALLENGE 2
#isolate the gender, yearsexp, and wages for the dataframe (df)
Slice3=wages.loc[:, ['gender','yearsExperience','wage' ]]
#Slice 3 is now the working df. We will now print the highest earner
highEarn=Slice3.nlargest(1,'wage')
print "The highest earner is:" , highEarn
#We will not print the lowest earner
lowEarn=Slice3.nsmallest(1,'wage')
print "The lowest earner is:" , lowEarn
#We will not print the top 10 highest earning females
females=Slice3[Slice3.gender=='female']
top10f=females.nlargest(10, 'wage')
print "The top ten highest earning females are:" , top10f
|
56cf27d686c64d1fba048058e0e211acf7a4a638 | IlyaShushlebin/lab7 | /testSwitchNewTab.py | 1,422 | 3.5625 | 4 | import time
import math
# webdriver это и есть набор команд для управления браузером
from selenium import webdriver
# инициализируем драйвер браузера. После этой команды вы должны увидеть новое открытое окно браузера
driver = webdriver.Chrome("C:/chromedriver/chromedriver.exe")
# Метод get сообщает браузеру, что нужно открыть сайт по указанной ссылке
driver.get("http://suninjuly.github.io/redirect_accept.html")
time.sleep(5)
# поис кнопки "I want to go on a magical journey!
btn = driver.find_elements_by_css_selector(".btn")
btn[0].click()
# переход на вторую вкладку
driver.switch_to.window(driver.window_handles[1])
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
# Считываем значение х
x = driver.find_element_by_id("input_value").text
y = calc(x)
# Ищем поле для ввода ответа
textInputAnswer = driver.find_element_by_id("answer")
textInputAnswer.send_keys(y)
# Найдем кнопку submit
btnSubmit = driver.find_element_by_css_selector(".btn")
btnSubmit.click()
time.sleep(5)
# После выполнения всех действий мы не должны забыть закрыть окно браузера
driver.quit() |
36ee5944630dd54e5fa5c80b26a02085c03d6706 | Faraz-Nasir/Jumble-Words-tkinter | /sqlite.py | 16,011 | 3.625 | 4 | import sqlite3
import pandas as pd
#connect to database
conn=sqlite3.connect('Jumbled_Words.db')
c=conn.cursor()
'''
c.execute("""
CREATE TABLE words(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
Word TEXT
)
""")'''
def add(word_list,number_of_words_in_the_list):
conn=sqlite3.connect("Jumbled_Words.db")
c=conn.cursor()
for i in range(number_of_words_in_the_list):
c.execute("INSERT INTO words VALUES (:ID,:word)",
{
'ID':i,
'word':word_list[i]
}
)
conn.commit()
conn.close()
word_list=["philanthropist",
"antidote",
"strive",
"ambidextrous",
"retrospective",
"precursors",
"introvert",
"gerontocracy",
"ambiguous",
"braggart",
"aggravate",
"entice",
"alleviate",
"adorn",
"equilibrium",
"abhor",
"connote",
"endeavor",
"agile",
"renovate",
"curriculum",
"malevolent",
"amalgamate",
"drowsiness",
"stray",
"disrobe",
"acumen",
"suffocate",
"sporadic",
"scent",
"sequence",
"audacious",
"affinity",
"animosity",
"heterogeneous",
"fragile",
"legacy",
"massacre",
"appease",
"submerge",
"adulteration",
"combustion",
"premature",
"shunned",
"anguish",
"apt",
"conceal",
"grumble",
"indigenous",
"offhand",
"loll",
"correlate",
"somersault",
"abscond",
"edible",
"extinguish",
"inquest",
"surcharge",
"accolade",
"conjoin",
"timid",
"opaqueness",
"disallow",
"abide",
"impermeable",
"console",
"warrant",
"acclaimed",
"extinct",
"reminiscent",
"catalyst",
"embezzle",
"shallow",
"clientele",
"brittle",
"negligent",
"affable",
"salvage",
"moribund",
"relapse",
"dangle",
"ascend",
"asterisk",
"yarn",
"arrogance",
"divergence",
"allegiance",
"vigorous",
"dwarf",
"livid",
"rejuvenation",
"fragrant",
"judicious",
"hospitable",
"odor",
"scribble",
"ameliorate",
"poseur",
"sawdust",
"narcissism",
"dullard",
"succumb",
"sluggard",
"flop",
"ingest",
"reiterate",
"derivative",
"defer",
"eloquence",
"clot",
"commuter",
"weigh",
"steeply",
"torque",
"benefactor",
"moderation",
"plea",
"invincible",
"enduring",
"flimsy",
"tadpole",
"turmoil",
"sanity",
"cryptic",
"gallant",
"endorse",
"sponge",
"volatile",
"alloy",
"reconcile",
"fission",
"commemorate",
"gait",
"dormant",
"shard",
"chisel",
"encapsulate",
"complaisant",
"grievous",
"hypocrisy",
"enzyme",
"eradicate",
"infuriate",
"Lambaste",
"sanction",
"engulf",
"euphoria",
"renowned",
"colloquial",
"evoke",
"mischievous",
"implicit",
"abysmal",
"dote",
"riddle",
"misogynist",
"disproof",
"sadastic",
"impromptu",
"inclined",
"erratic",
"meticulous",
"ambivalent",
"pertain",
"auxiliary",
"constrict",
"luminary",
"ossified",
"tonic",
"perish",
"presentiment",
"indistinct",
"dupe",
"abstruse",
"turbulence",
"connoisseur",
"aberration",
"extralegal",
"pest",
"parenthesis",
"sophisticated",
"ail",
"limp",
"arcane",
"mite",
"edify",
"recuperate",
"satiate",
"yeoman",
"fidelity",
"pluck",
"perjury",
"paradigm",
"gullible",
"sobriety",
"tractable",
"writ",
"mesmerize",
"predominate",
"articulate",
"fleet",
"solvent",
"dislodge",
"partisan",
"spear",
"vivacious",
"beguile",
"coagulation",
"foolproof",
"liberality",
"elaborate",
"brass",
"permeate",
"malleable",
"suffice",
"lampoon",
"immutable",
"forgery",
"patron",
"cordial",
"retrograde",
"cumbersome",
"sheath",
"repel",
"unscathed",
"superimpose",
"boisterous",
"implosion",
"centurion",
"knit",
"pivotal",
"enigma",
"buoyant",
"jabber",
"treacherous",
"bewilder",
"stride",
"garrulous",
"redeem",
"calipers",
"impede",
"resuscitation",
"apartheid",
"concur",
"indulgent",
"recitals",
"woo",
"misanthrope",
"evasive",
"eulogy",
"foster",
"pilferer",
"refine",
"dexterity",
"bogus",
"incongruous",
"multifarious",
"skit",
"repulsive",
"hapless",
"convoluted",
"indefatigability",
"fawn",
"wince",
"feud",
"cognizant",
"substantiation",
"euthanasia",
"irate",
"underbid",
"alcove",
"frantic",
"peccadillo",
"pervade",
"decree",
"concoct",
"turquoise",
"miser",
"valiant",
"derogatory",
"tarnished",
"reverent",
"imminent",
"voluptuous",
"suppress",
"irrevocable",
"soggy",
"vindictive",
"wanton",
"pinch",
"earthenware",
"unearth",
"savor",
"hoax",
"vitriolic",
"loquacious",
"defiance",
"candid",
"warmonger",
"gust",
"coalescing",
"precursory",
"counterfeit",
"gush",
"quandary",
"chortle",
"compunction",
"plunge",
"revere",
"swerve",
"abraded",
"punitive",
"dawdler",
"noxious",
"torment",
"squander",
"exculpate",
"stifled",
"antithetical",
"deplete",
"apropos",
"recompense",
"coerce",
"aseptic",
"implacable",
"holster",
"proliferate",
"propagation",
"personable",
"reciprocity",
"vigilance",
"distraught",
"ineptitude",
"lustrous",
"condense",
"extol",
"forestall",
"stipulate",
"lament",
"provoke",
"plummet",
"subpoena",
"accrue",
"idolatry",
"apprehensive",
"nihilism",
"soot",
"valorous",
"complaisance",
"illicit",
"viscous",
"aversion",
"haughty",
"concord",
"latent",
"topple",
"supersede",
"entangle",
"variegate",
"inept",
"deviance",
"enunciate",
"polemic",
"pristine",
"impediment",
"floe",
"malevolence",
"prevalent",
"undermine",
"arduous",
"slack",
"calisthenics",
"placate",
"palate",
"regicide",
"iconoclast",
"pungency",
"aloof",
"indomitable",
"finesse",
"whimsical",
"tamper",
"recluse",
"hush",
"felon",
"frugal",
"shun",
"mendacious",
"apprise",
"muffler",
"bigot",
"imperative",
"enthral",
"smolder",
"dismal",
"perilous",
"lavish",
"trickle",
"diabolical",
"vehemence",
"disencumber",
"impending",
"stickler",
"stigma",
"avow",
"castigation",
"benevolence",
"incessant",
"squat",
"indulge",
"deter",
"incredulous",
"tenacity",
"exuberance",
"apostate",
"gist",
"transient",
"connotation",
"engrave",
"berate",
"conciliatory",
"subdue",
"soar",
"empirical",
"procrastination",
"tassel",
"immaculate",
"astute",
"flaunting",
"impair",
"prone",
"coy",
"pillage",
"incorrigibility",
"extrovert",
"approbation",
"efface",
"taciturn",
"mollify",
"exorbitant",
"sober",
"truce",
"conviction",
"bolster",
"precepts",
"castigate",
"curtail",
"fallacious",
"espouse",
"nonchalant",
"flamboyant",
"gorge",
"vex",
"grandiloquent",
"poncho",
"impassive",
"pitfall",
"coddle",
"inscrutable",
"shrill",
"arboreal",
"boorish",
"lull",
"timorous",
"imperturbable",
"perch",
"prudence",
"cohort",
"sagacious",
"ignoble",
"intersperse",
"oblivious",
"rescind",
"nebulous",
"disseminate",
"heed",
"laudatory",
"bask",
"fluke",
"ebullient",
"pliant",
"endearing",
"precarious",
"inferno",
"palpitate",
"embellish",
"ominous",
"fluster",
"matriculation",
"susceptibility",
"graze",
"quell",
"divulge",
"dubious",
"malapropism",
"maverick",
"irascible",
"incise",
"ostracism",
"ambrosial",
"sidestep",
"extort",
"cling",
"epitome",
"arabesque",
"ferocity",
"cantankerous",
"chaste",
"corroboration",
"expurgate",
"insensible",
"garner",
"fidget",
"impervious",
"rift",
"efficacy",
"Conduce",
"attune",
"convoke",
"enmity",
"credulous",
"palpability",
"plead",
"feral",
"gourmand",
"morbid",
"superfluous",
"equipoise",
"veer",
"benign",
"lackluster",
"chastisement",
"breach",
"rarefy",
"dissent",
"neophyte",
"reticence",
"pious",
"trudge",
"thrift",
"daunt",
"veneration",
"grave",
"frenetic",
"disheveled",
"temperate",
"impiety",
"blas�",
"scalding",
"irresolute",
"rave",
"heresy",
"guile",
"fret",
"chicanery",
"telltale",
"feckless",
"ardor",
"debacle",
"tawdry",
"striated",
"jocular",
"exoneration",
"contentious",
"cajole",
"resilience",
"disdain",
"taunt",
"alacrity",
"abeyance",
"apotheosis",
"hoodwink",
"glimmer",
"terse",
"ulterior",
"jagged",
"myriad",
"inimitable",
"conundrum",
"incite",
"falter",
"drawl",
"clamor",
"nexus",
"render",
"clinch",
"abet",
"decorum",
"quiescence",
"discreet",
"ale",
"sash",
"ruffian",
"tepid",
"itinerate",
"doleful",
"innocuous",
"exhaustive",
"abrogate",
"recant",
"crush",
"talon",
"quack",
"emaciate",
"sever",
"sodden",
"mephitic",
"sketchy",
"intrepid",
"preternatural",
"pariah",
"unfeigned",
"servile",
"ossify",
"prim",
"churlish",
"fixate",
"commodious",
"flinch",
"insurrection",
"recast",
"thwart",
"transgress",
"engrossing",
"vilify",
"intransigence",
"covert",
"heinous",
"infuse",
"ubiquitous",
"quixotic",
"fracas",
"putrefaction",
"torpid",
"assuage",
"insinuate",
"sycophant",
"urbane",
"ebullience",
"austere",
"inadvertent",
"assail",
"stingy",
"equivocal",
"proclivity",
"cower",
"colander",
"maul",
"provisional",
"burnish",
"penury",
"dirge",
"ire",
"vain",
"ruddy",
"forfeit",
"engender",
"occluded",
"rotund",
"puerile",
"savant",
"profuse",
"enervate",
"adamant",
"dynamo",
"equivocate",
"gnaw",
"wean",
"pry",
"beatify",
"discrete",
"hegemony",
"glut",
"crease",
"ascertain",
"foray",
"guileless",
"sting",
"splice",
"penitent",
"elegy",
"reticent",
"pusillanimous",
"obtuse",
"paucity",
"retinue",
"diatribe",
"cogitate",
"consummate",
"stolid",
"effrontery",
"dissolution",
"derision",
"indolence",
"pyre",
"erudite",
"mercurial",
"corporeal",
"pedestrian",
"equable",
"admonitory",
"luculent",
"coeval",
"insularity",
"auspicious",
"secular",
"streak",
"nascent",
"decry",
"penchant",
"pulchritude",
"onus",
"vanquish",
"extirpate",
"assiduous",
"privation",
"accretion",
"covetous",
"defalcate",
"baneful",
"indelible",
"palliate",
"cogent",
"dearth",
"pellucid",
"condone",
"lumber",
"discredit",
"recidivism",
"lurk",
"coda",
"cornucopia",
"veneer",
"petrify",
"censure",
"elicit",
"serration",
"dainty",
"caustic",
"highbrow",
"odious",
"abjure",
"chauvinist",
"tyro",
"inane",
"dilate",
"deprave",
"denigrate",
"duplicity",
"protracted",
"taut",
"turbid",
"fledgling",
"punctilious",
"bellicose",
"ignominious",
"interim",
"avid",
"florid",
"malign",
"inundate",
"attenuate",
"consume",
"phlegmatic",
"sanctimony",
"inimical",
"prevaricate",
"ingenuous",
"veracity",
"barren",
"plaque",
"lien",
"exigency",
"chagrin",
"aver",
"credulity",
"snub",
"libel",
"forbearance",
"volubility",
"conceit",
"idiosyncrasy",
"obdurate",
"dud",
"None",
"facile",
"contiguous",
"jejune",
"waft",
"resigned",
"abut",
"finagle",
"repudiate",
"tocsin",
"verisimilitude",
"fringe",
"chastened",
"somatic",
"pernicious",
"husk",
"insipid",
"coax",
"dolt",
"penurious",
"parley",
"effluvia",
"incursion",
"obfuscate",
"preclude",
"disingenuous",
"encumbrance",
"obtain",
"morose",
"gloat",
"quirk",
"extempore",
"disparate",
"regale",
"scorch",
"perpetrate",
"foil",
"salubrious",
"malinger",
"grouse",
"Palpable",
"discern",
"waffle",
"transitory",
"perfunctory",
"pundit",
"extant",
"mundane",
"deluge",
"visceral",
"lachrymose",
"ascribe",
"sullied",
"exscind",
"temerity",
"extenuate",
"grovel",
"collusion",
"squalid",
"undulate",
"fagged",
"shrewd",
"hollow",
"harbinger",
"august",
"conspicuous",
"epiphany",
"rife",
"evince",
"Pastiche",
"gaucherie",
"snare",
"rancorous",
"finical",
"mellifluous",
"macabre",
"uncouth",
"amortize",
"obviate",
"levity",
"ascetic",
"delineate",
"paean",
"nadir",
"emote",
"fervor",
"congeal",
"verve",
"gauche",
"lope",
"expostulate",
"discourse",
"lionize",
"dilettante",
"noisome",
"bandy",
"dogmatic",
"epicurean",
"sumptuous",
"craven",
"lassitude",
"ostentation",
"sanguine",
"irksome",
"prodigal",
"brash",
"requite",
"imperious",
"didactic",
"presage",
"sophomoric",
"trifling",
"drone",
"verdant",
"ensconce",
"intransigent",
"prodigious",
"palatial",
"agog",
"desiccant",
"philistine",
"broach",
"wile",
"heretic",
"supine",
"reactionary",
"raconteur",
"ferment",
"qualm",
"hauteur",
"perfidious",
"festoon",
"rumple",
"propitious",
"remonstrate",
"roll",
"curmudgeon",
"bequest",
"inchoate",
"facetious",
"fatuous",
"reproach",
"wan",
"rapacious",
"stymie",
"baleful",
"obtrusive",
"preen",
"jibe",
"extricable",
"figurehead",
"benison",
"provident",
"rivet",
"barrage",
"fetid",
"burgeon",
"overweening",
"discountenance",
"vacillation",
"eschew",
"pedantic",
"impetuous",
"rueful",
"equanimity",
"hubris",
"kibosh",
"mendicant",
"soporific",
"atonement",
"ford",
"forswear",
"excoriation",
"macerate",
"supplicate",
"saturnine",
"skiff",
"boggle",
"profundity",
"blithe",
"slur",
"contemn",
"blandness",
"cloture",
"hallow",
"tortuous",
"egress",
"scabbard",
"rant",
"vacuity",
"dereliction",
"seminal",
"petrous",
"prudish",
"mendacity",
"machination",
"restive",
"perspicacity",
"labyrinthine",
"esoteric",
"perfidy",
"entreat",
"prune",
"incumbents",
"contrite",
"maladroit",
"probity",
"manacle",
"indigence",
"fervid",
"imbroglio",
"stigmatize",
"molt",
"overhaul",
"germane",
"specious",
"goad",
"vestige",
"cravat",
"eddy",
"cordon",
"forage",
"poignant",
"depredation",
"flax",
"parsimonious",
"exploit",
"subsume",
"aleck",
"petulant",
"rubicund",
"severance",
"ineluctable",
"platitude",
"lugubrious",
"insouciant",
"halcyon",
"officious",
"gouge",
"interdict",
"onerous",
"predilection",
"flout",
"demagogue",
"belligerent",
"chary",
"feint",
"profligate",
"impute",
"upbraid",
"cabal",
"deprecate",
"obsequious",
"inveterate",
"retard",
"spurious",
"propitiatory",
"maudlin",
"shunt",
"aplomb",
"dulcet",
"tautology",
"inured",
"None",
"nemesis",
"gregarious",
"denouement",
"hone",
"cursory",
"forge",
"impecunious",
"sordid",
"argot",
"plethora",
"sinuous",
"vigilant",
"libertine",
"desultory",
"propinquity",
"salacious",
"augury",
"harangue",
"odium",
"turgid",
"recalcitrant",
"harrow",
"mulct",
"homiletics",
"eclat",
"foible",
"epistle",
"deposition",
"inculcate",
"tangential",
"gainsay",
"middling",
"countervail",
"moot",
"repertoire",
"nary",
"pinchbeck",
"stentorian",
"finicky",
"resort",
"profane",
"divestiture",
"gossamer",
"churl",
"temperance",
"truculence",
"inveigh",
"diffidence",
"atavistic",
"levee",
"astringent",
"pucker",
"trepidation",
"opprobrious",
"diaphanous",
"nugatory",
"rebuff",
"distrait",
"tenuous",
"detumescence",
"glean",
"disinter",
"vitiate",
"foppish",
"panegyric",
"flak",
"ramify",
"plod",
"refractory",
"fecund",
"encomium",
"expedient",
"pugnacious",
"vituperate",
"trenchant",
"disconcert",
"quail",
"obloquy",
"discomfit",
"impudent",
"quaff",
"untoward",
"sermon",
"voluble",
"sublime",
"rabble",
"calumny",
"peremptory",
"strut",
"blandishment",
"cant",
"bereft",
"fetter",
"prosaic",
"turpitude",
"glib",
"raffish",
"ensign",
"contumacious",
"asperity",
"meretricious",
"simper",
"idyll",
"teetotal",
"incense",
"veritable",
"invective",
"mien",
"implicate",
"endemic",
"hirsute",
"unencumbered",
"sophistry",
"impugned",
"surfeit",
"quotidian",
"umbrage",
"miseenscene",
"felicitous",
"hack",
"toady",
"peregrination",
"mettle",
"ineffable",
"ecumenical",
"incipient",
"canvass",
"plaintive",
"pine",
"ostensible",
"tout",
"piquant",
"tamp",
"forbear",
"slate",
"minatory",
"stanch",
"fledged",
"plumb",
"deferential",
"sundry",
"stipple",
"blatant",
"aspersion",
"demur",
"consternation",
"spurn",
"cadge",
"bedizen",
"purvey",
"desuetude",
"suppliant",
"presumption",
"brummagem",
"countenance",
"belabor",
"obstreperous",
"redoubtable",
"balk",
"supercilious",
"trite",
"virago",
"stygian",
"rebus",
"orison",
"preponderance",
"reprobate",
"hermetic",
"expiation",
"vagary",
"sententious",
"trencherman",
"hew",
"proscribe",
"dissemble",
"portent",
"imperviousness",
"picaresque",
"pileous",
"venal",
"doggerel",
"splenetic",
"peripatetic",
"imprecation",
"froward",
"profligacy",
"lithe",
"mettlesome",
"petrified",
"succor",
"fulsome",
"ferret",
"travesty",
"duress",
"puissance",
"acarpous",
"pied",
"effete",
"edacious",
"constrain",
"sobriquet",
"wend",
"fulmination",
"nibble",
"ponderous",
"brook",
"palaver",
"pique",
"slake",
"salutary",
"detraction",
"welter",
"repast",
"abraid",
"nostrum",
"stint",
"pith",
"suborn",
"nonplused",
"refulgent",
"expatiate",
"fustian",
"garble",
"recondite",
"scurvy",
"mince",
"epithet",
"sedulous",
"prolix",
"importune",
"involute",
"bilge",
"cavalcade",
"sere",
"droll",
"descry",
"brazen",
"repine",
"limn",
"wag",
"lucubrate",
"coruscate",
"crass",
"consequential",
"foment",
"testiness",
"recreancy",
"arrant",
"quibble",
"lam",
"Archaic",
"imbibe"
]
def show_database():
conn=sqlite3.connect('Jumbled_Words.db')
c=conn.cursor()
c.execute("SELECT * FROM words")
records=c.fetchall()
for record in records:
print(record)
number=len(word_list)
show_database()
conn.commit()
conn.close() |
e2d162869509023697e5231bdf2d5b214ced5f26 | rmesseguer/number_game | /number_game.py | 1,430 | 4.09375 | 4 | import random
robot_score = 0
player_score = 0
while True:
num = random.randint(1,10)
good_guess = False
while not good_guess:
try:
guess = int(input('Guess a number between 1 and 10: '))
if guess < 1 or guess > 10:
raise ValueError()
good_guess = True
except ValueError:
print("Sorry I didnt understand that. Please try again.")
times = 1
while times < 3 and guess != num:
if (guess > num):
try:
guess = int(input('Lower. Please guess again: '))
except ValueError:
print("Sorry I didnt understand that. Please guess again:")
else:
try:
guess = int(input('Higher. Guess again: '))
except ValueError:
print("Sorry I didnt understand that. Please guess again:")
times = times + 1
if (times == 3):
print('Too many tries!')
if (guess == num):
player_score = player_score + 1
print('You win!', player_score, 'vs', robot_score, '\,,/(^_^)\,,/')
else:
robot_score = robot_score + 1
print('You lose! The number was ' + str(num) + '. ',player_score, ' vs ', robot_score, '¯\_(oO)_/¯',sep='') |
28d5915b71c0f0ce0266c6169d724582b0d3963c | ranju117/cegtask | /7.py | 286 | 4.21875 | 4 | #tuple
tuple1 = ('python', 'ruby','c','java')
list1 = ['python','ruby','c','java']
print tuple1
print list1
# Let's include windows in the list and it works!
list1[1] = "windows"
list1[2]="Python"
print list1
# Windows does not work here!
tuple1[1] = "windows"
print tuple1 |
897aeeae7843d653f2c422df5c0bcd5367076eb2 | admk/nabp | /pynabp/conf/validator/constraints.py | 4,691 | 3.53125 | 4 | from base import Validator, ValidateError
# use a dummy lambda to get the function type
func = type(lambda _: 0)
# constraint functions
natural = lambda val: val >= 0
positive = lambda val: val > 0
negative = lambda val: val < 0
odd = lambda val: val % 2 == 1
even = lambda val: val % 2 == 0
def boundaries(
min_val=None, min_inclusive=False,
max_val=None, max_inclusive=False):
"""Return a constraint function that bounds the value within the range
specified by min_val and max_val.
"""
return lambda val: \
(val >= min_val if min_val is not None else True) and \
(val <= max_val if max_val is not None else True) and \
(val != min_val if not min_inclusive else True) and \
(val != max_val if not max_inclusive else True)
def time_unit(val):
"""Time unit constraint finds values of the form: 10ns
"""
import re
return re.search(r'^\d+(s|ms|us|ns|ps|fs)$', val) is not None
def function_arg_count(count):
import inspect
return lambda function: len(inspect.getargspec(function).args) == count
class TypeValidateError(ValidateError):
"""Type mismatch found"""
class NullableValidateError(ValidateError):
"""Cannot be None valued"""
class ConstraintFunctionValidateError(ValidateError):
"""Failed to validate with function"""
class ConstraintsValidator(Validator):
"""A validator that accepts a dictionary of constraints for configuration
validation.
"""
def __init__(self, config):
super(ConstraintsValidator, self).__init__(config)
self._constraints = {}
def add_constraints(self, dictionary=None, **kwargs):
"""Add constraints to check
Data structure must be:
key=(type, nullable, constraint functions)
type - a Python or a custom type
nullable - True/False, indicate if the value can be None valued
constraint functions - a list of functions or a function for other
constraint checking, the function returns True on satisfied
constraint, returns False otherwise
"""
if dictionary:
self._constraints.update(dictionary)
self._constraints.update(**kwargs)
def validate_constraints(self, conf):
"""A validator method that perform preliminary checks to parameters.
It uses the constraints added to perform checks
"""
for key, val in conf.iteritems():
self._null_check(key, val)
self._type_check(key, val)
self._function_check(key, val)
def _type_check(self, key, val):
"""Perform type check for key/value pair
It raises an exception when the value has a type mismatch.
"""
if not val:
return
val_types = self._type_constraint(key)
if not isinstance(val, val_types):
raise TypeValidateError(
'Type mismatch, expected %s, found %s' %
(val_types, str(type(val))))
def _null_check(self, key, val):
"""Perform null check for key/value pair
It raises an exception when the value cannot be nullable but with a
None value.
"""
val_none = self._nullable_constraint(key)
if val is None and not val_none:
raise NullableValidateError(
'Not nullable key has a null value: (%s, %s)' %
(key, str(val)))
def _function_check(self, key, val):
"""Perform check on the value with constraint functions
"""
if not val:
return
val_constr_func = self._function_constraint(key)
if not val_constr_func:
return
for val_func in val_constr_func:
if not val_func(val):
raise ConstraintFunctionValidateError(
'Constraint %s unsatisfied for (%s, %s)' %
(str(val_func), key, str(val)))
def _type_constraint(self, key):
"""Return the type cosntraint on the value for a corresponding key"""
val_types = self._constraints[key][0]
if not isinstance(val_types, (tuple, list)):
val_types = (val_types)
return val_types
def _nullable_constraint(self, key):
"""Return the nullable cosntraint on the value for a corresponding key
"""
return self._constraints[key][1]
def _function_constraint(self, key):
"""Return the cosntraint functions on the value for a corresponding key
"""
constr = self._constraints[key][2]
if type(constr) is func:
constr = [constr]
return constr
|
2293c26f5ae1fdf5417ce4033829cc36c80cff00 | furkanaygur/Codewars-Examples | /RemoveTheParantheses.py | 754 | 4.4375 | 4 | '''
Remove the parentheses
In this kata you are given a string for example:
"example(unwanted thing)example"
Your task is to remove everything inside the parentheses as well as the parentheses themselves.
The example above would return:
"exampleexample"
Notes
Other than parentheses only letters and spaces can occur in the string. Don't worry about other brackets like "[]" and "{}" as these will never appear.
There can be multiple parentheses.
The parentheses can be nested.
'''
def remove_parentheses(s):
result = ''
a = 0
for i in s:
if i == '(': a += 1
elif i == ')': a -=1
elif a == 0: result += i
return result
print(remove_parentheses('sBtJXYI()DpVxQWId MWVozwWva kri obRgP AXjTKQUjXj xoEA xmkTQ LvrfGyNzCTqHHTWFPuLvrRWba fnWbFNVQBANn ZqwHzLTxkSuAPQiccORuQHNLxlaiYJSTESsOMoMooVbvDxZiEbilrgJeUfACIeEw AzPXkOrDk vjAAaqiPyMIOl UvLWq UMigMOi YRwiiOFcNRVyZbAPajY e YHldtivKMbFGwr pfKGlBRBjq wiHlobnqR GNMxf eW veFKMNzopYXf sG)VAyjLrHjxwNR ZPlkAp NRyKEKCM'))
|
d7eb20ba3f3a7b3b858265fb5dc87aea3939d909 | furkanaygur/Codewars-Examples | /MatrixAddition.py | 1,056 | 4.15625 | 4 | '''
Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers.
How to sum two matrices:
Take each cell [n][m] from the first matrix, and add it with the same [n][m] cell from the second matrix. This will be cell [n][m] of the solution matrix.
Visualization:
|1 2 3| |2 2 1| |1+2 2+2 3+1| |3 4 4|
|3 2 1| + |3 2 3| = |3+3 2+2 1+3| = |6 4 4|
|1 1 1| |1 1 3| |1+1 1+1 1+3| |2 2 4|
Example
matrixAddition(
[ [1, 2, 3],
[3, 2, 1],
[1, 1, 1] ],
// +
[ [2, 2, 1],
[3, 2, 3],
[1, 1, 3] ] )
// returns:
[ [3, 4, 4],
[6, 4, 4],
[2, 2, 4] ]
'''
def matrix_addition(a,b):
result = []
for i in range(len(a)):
temp = []
for j in range(len(a)): temp.append(a[i][j] + b[i][j])
result.append(temp)
return result
print(matrix_addition([[1, 2], [1, 2]], [[2, 3], [2, 3]])) |
68ef323d3c407c857ff33a26bc91847a4af5356f | furkanaygur/Codewars-Examples | /ParseStringReloaded.py | 1,991 | 3.953125 | 4 | '''
Description:
Input
Range is 0-999
There may be duplicates
The array may be empty
Example
Input: 1, 2, 3, 4
Equivalent names: "one", "two", "three", "four"
Sorted by name: "four", "one", "three", "two"
Output: 4, 1, 3, 2
Notes
Don't pack words together:
e.g. 99 may be "ninety nine" or "ninety-nine"; but not "ninetynine"
e.g 101 may be "one hundred one" or "one hundred and one"; but not "onehundredone"
Don't fret about formatting rules, because if rules are consistently applied it has no effect anyway:
e.g. "one hundred one", "one hundred two"; is same order as "one hundred and one", "one hundred and two"
e.g. "ninety eight", "ninety nine"; is same order as "ninety-eight", "ninety-nine"
'''
def sort_by_name(arr):
n = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten',
11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen',
20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety',100:'hundred',
1000:'thousand'}
temp = []
result = []
t = ''
for i in arr:
if i not in n:
if len(str(i)) == 2:
t = str(n[i//10 * 10]) + ' '
t += str(n[i%10])
temp.append(t)
if len(str(i)) == 3:
t = str(n[i//100]) + ' hundred '
if int(i%100) != 0 and i%100 in n:
t += str(n[i%100])
else:
i = i%100
if i != 0:
t += str(n[i//10 * 10]) + ' '
t += str(n[i%10])
temp.append(t)
else:
temp.append(n[i])
for i in sorted(temp):
c = temp.index(i)
result.append(arr[c])
return result
print(sort_by_name([300, 238, 231])) |
a8477323029366675ff8de5169e40fbc701ffe0a | furkanaygur/Codewars-Examples | /SplitStrings.py | 844 | 4.28125 | 4 | '''
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:
solution('abc') # should return ['ab', 'c_']
solution('abcdef') # should return ['ab', 'cd', 'ef']
'''
def solution(s):
result = ''
result_array = []
flag = False
for i in range(len(s)):
if result == '':
result += f'{s[i]}'
flag = True
elif flag == True:
result += f'{s[i]}'
result_array.append(result)
result = ''
flag = False
if i == len(s)-1 and flag == True:
result_array.append(f'{s[i]}_')
return result_array
print(solution('')) |
8093fd80925a5c7fd809bdb195ab6f8ac552fbd6 | furkanaygur/Codewars-Examples | /DecipherThis.py | 945 | 4.03125 | 4 | '''
You are given a secret message you need to decipher. Here are the things you need to know to decipher it:
For each word:
the second and the last letter is switched (e.g. Hello becomes Holle)
the first letter is replaced by its character code (e.g. H becomes 72)
Note: there are no special characters used, only letters and spaces
Examples
decipherThis('72olle 103doo 100ya'); // 'Hello good day'
decipherThis('82yade 115te 103o'); // 'Ready set go'
'''
def decipher_this(string):
result = ''
for i in string.split(' '):
number, chars = '', []
for j in i:
if j.isnumeric(): number += str(j)
else: chars += j,
result += chr(int(number))
if len(chars) >= 2: chars[0], chars[-1] = chars[-1], chars[0]
result += ''.join(chars) + ' '
return result.rstrip()
print(decipher_this('65 119esi 111dl 111lw 108dvei 105n 97n 111ka')) |
ad213ac20a71fb84dfa39d4ad5375110c6f6281b | furkanaygur/Codewars-Examples | /Snail.py | 2,004 | 4.3125 | 4 | '''
Snail Sort
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:
array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
This image will illustrate things more clearly:
Note 1: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
Note 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]].
'''
def snail(snail_map):
result = []
def leftToRight(array):
a = snail_map[0]
snail_map.remove(snail_map[0])
return a
def upToBottom(array):
a = []
for i in range(len(array)):
a += array[i][len(array)],
snail_map[i]= snail_map[i][:-1]
return a
def rightToLeft(array):
a = []
for i in reversed(array[len(array)-1]):
a += i,
snail_map.remove(snail_map[len(array)-1])
return a
def bottomToUp(array):
a = []
x = len(array)-1
for i in range(len(array)):
a += array[x][0],
snail_map[x]= snail_map[x][1:]
x -= 1
return a
lenght = [len(i) for i in snail_map]
while True:
if len(result) != sum(lenght): result += leftToRight(snail_map)
else: break
if len(result) != sum(lenght): result += upToBottom(snail_map)
else: break
if len(result) != sum(lenght): result += rightToLeft(snail_map)
else: break
if len(result) != sum(lenght): result += bottomToUp(snail_map)
else: break
return result
print(snail([[1,2,3,1], [4,5,6,4], [7,8,9,7],[7,8,9,7]])) |
6879db3b8aabbae7dcc46f3c4d3be47bafa9c3e0 | shivangi-ml/projects | /Recurrent_Neural_Networks/google_stock_price.py | 2,787 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 23 20:29:56 2019
@author: spriyadarshini
"""
# import libs
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#import dataset
dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:,[1]].values
# scaling is a must . we will do normalisation
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler()
training_set = sc.fit_transform(training_set)
X_train = []
y_train = []
# now we will create dataset of timestamp 60 and 1 output ie one row will contain 60 days of stock price and 61st will be the predicted stock price
for i in range(60,training_set.shape[0]):
seq = training_set[i-60:i]
X_train.append(seq)
y_train.append(training_set[i])
#since RNN only take array... we have to convert the lists into array
X_train = np.array(X_train)
y_train = np.array(y_train)
#building the model with 4 LSTM layers
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import Dropout # used for randomly dropping out the neurons to prevent overfitting
regressor = Sequential()
regressor.add(LSTM(units = 50,return_sequences = True, input_shape = (X_train.shape[1],1)))
regressor.add(Dropout(rate = 0.2))
regressor.add(LSTM(units = 50,return_sequences = True))
regressor.add(Dropout(rate = 0.2))
regressor.add(LSTM(units = 50,return_sequences = True))
regressor.add(Dropout(rate = 0.2))
regressor.add(LSTM(units = 50))
regressor.add(Dropout(rate = 0.2))
# output layer
regressor.add(Dense(output_dim = 1))
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
regressor.fit(X_train,y_train,batch_size = 32, epochs = 100)
#predicting and visualising the model
dataset_test = pd.read_csv('Google_Stock_Price_Test.csv')
real_stock_price = dataset_test.iloc[:,[1]].values
# now in order to predict the stock of 3rd jan 2017, we need to see the stocks of 60 days before that
#so we need to concatenate test and training dataset
dataset_total = pd.concat((dataset_train['Open'],dataset_train['Open']),axis = 0)
inputs = dataset_total[len(dataset_total)-len(dataset_test) -60:].values
inputs = inputs.reshape(-1,1)
# since model was trained in scaled data..
inputs = sc.fit_transform(inputs)
X_test = []
for i in range(60,80):
seq = inputs[i-60:i]
X_test.append(seq)
X_test = np.array(X_test)
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)
# visualing the trend now
plt.plot(real_stock_price,color = 'red',label = 'Google real stock price')
plt.plot(predicted_stock_price,color = 'blue',label = 'Google predicted_stock_price')
plt.xlabel('time')
plt.ylabel('Google stock price')
plt.legend()
plt.show()
|
1c528e653a6fb181308c0eda02a65b1f518fa03d | 901david/algorithms | /python/merge-sorted-arrays.py | 681 | 3.90625 | 4 | arr1 = [1, 2, 5, 8, 9]
arr2 = [5, 8, 9, 23]
def iterative_array_merger(arr1, arr2):
merged = []
while len(arr1) and len(arr2):
if arr1[0] < arr2[0]:
merged.append(arr1.pop(0))
else:
merged.append(arr2.pop(0))
return [*merged, *arr1, *arr2]
#print(iterative_array_merger(arr1, arr2))
def recursive_array_merge(arr1, arr2, merged=[]):
if len(arr1) and len(arr2):
if arr1[0] < arr2[0]:
merged.append(arr1.pop(0))
else:
merged.append(arr2.pop(0))
return recursive_array_merge(arr1, arr2, merged)
return [*merged, *arr1, *arr2]
print(recursive_array_merge(arr1, arr2))
|
e33e9e635201dc2ba729ef957ec92c0f7480e5d7 | ndhansen/programming-challenges | /02_BMI_calculator/calculator.py | 159 | 4 | 4 | weight = float(input("What is your weight (kg)? "))
height = float(input("What is your height (m)? "))
print("Your BMI is", round(weight / (height ** 2), 1))
|
285f86a89e23cecb1a4b0d062d87735624040b4b | scipianne/OLS | /calculations.py | 5,107 | 3.578125 | 4 | # coding: utf-8
import math
class Matrix(list):
"""
Список, который считает себя квадратной матрицей
с шириной int(sqrt(len - 1)) + 1
"""
def __len__(self): # переопределяем функцию len как ширину матрицы
length = super(Matrix, self).__len__()
if length:
width = int(math.sqrt(length - 1)) + 1
else:
width = 0
return width
def __getitem__(self, key):
width = len(self)
x, y = key
return super(Matrix, self).__getitem__(x * width + y)
def __setitem__(self, key, item):
width = len(self)
x, y = key
return super(Matrix, self).__setitem__(x * width + y, item)
def solve(matr, rez):
"""
по квадратной матрице n*n matr и n-мерному вектору rez возвращает
вектор sol, из которого получается исходный домножением на матрицу
matr * sol = rez
(решает систему линейных уравнений методом гаусса)
"""
n = len(matr)
for i in xrange(n - 1):
j = i
while j < n and matr[j, i] == 0: # находим строку с ненулевым i-тым элементом
j += 1
if j != n:
matr_i = []
for k in xrange(n):
matr[j, k], matr[i, k] = matr[i, k], matr[j, k] # ставим найденную строку на i-тое место
matr_i.append(matr[i, k])
rez[j], rez[i] = rez[i], rez[j]
for k in xrange(i + 1, n): # вычитаем найденную строку из всех, домножив на коэффициент, чтобы обнулить
c = matr[k, i] / matr_i[i] # i-тый столбец всюду, кроме нее
for l in xrange(n):
matr[k, l] -= c * matr_i[l]
rez[k] -= c * rez[i]
sol = []
for i in xrange(n - 1, -1, -1): # решаем верхнетреугольную систему уравнений
if matr[i, i]: # проверка на обратимость матрицы, если на диагонали есть ноль, то решение неоднозначно
sol_i = rez[i] / matr[i, i]
sol.append(sol_i)
for j in xrange(i):
rez[j] -= matr[j, i] * sol_i
else:
return False
sol.reverse()
return sol
def find_vct(x, y, n):
"""
по набору точек x_i и значениям в них y_i строит
n-мерный вектор - правую часть системы уравнений
"""
m = len(x)
vct = []
for i in xrange(n - 1, -1, -1):
vct.append(y[0] * x[0] ** i)
for i in xrange(1, m):
for j in xrange(n - 1, -1, -1):
vct[n - j - 1] += y[i] * x[i] ** j
return vct
def matrix_create(x, n):
"""
создает матрицу - коэффициенты системы линейных уравнений,
которую необходимо решить
"""
m = len(x)
matr = Matrix()
for i in xrange(n):
for j in xrange(n):
matr.append(1. * x[0] ** (2 * (n - 1) - i - j))
for k in xrange(1, m):
for i in xrange(n):
for j in xrange(n):
matr[i, j] += 1. * x[k] ** (2 * (n - 1) - i - j)
return matr
def quad_dif(x, y, a):
"""
для найденных коэффициентов f(x) считает сумму квадратов
(y - f(x))^2 согласно мнк
"""
m = len(x)
rez = 0
n = len(a)
for i in xrange(m):
square = y[i]
for j in xrange(n):
square -= a[j] * (x[i] ** (n - j - 1))
rez += square ** 2
return rez
def coef(x, y, deg):
"""
по набору точек x_i, значений в них y_i и
желаемой степени deg находит коэффициенты многочлена
f(x)
"""
difs = {}
if deg != 1: # если задана степень многочлена, пытаемся решить задачу для нее
matrix = matrix_create(x, deg)
coef_ = solve(matrix, find_vct(x, y, deg))
if coef_:
return coef_
deg = len(x) # если степень не задана, берем количество точек как максимум
for n in xrange(2, deg + 1): # решаем задачу для всех степеней до выбранного максимума, из решений выбираем
matrix = matrix_create(x, n) # оптимальное
coef_ = solve(matrix, find_vct(x, y, deg))
if coef_:
dif = quad_dif(x, y, coef_)
difs[dif] = coef_
if difs:
min_dif = min(difs.keys())
return difs[min_dif]
return False
|
fbed9de940cb5f58be578eae698ad6d85bdeff42 | jmockbee/strings | /example1.py | 229 | 3.890625 | 4 | def double_word(word):
word = word * 2
return word + str(len(word))
print(double_word("hello")) # Should return hellohello10
print(double_word("abc")) # Should return abcabc6
print(double_word("")) # Should return 0
|
b24d011cf6257002c11e2f76a0a54961151641e7 | AlamgirHassan5002/Word-Split-Python | /index.py | 1,615 | 3.609375 | 4 | def WordSplit(strArr):
size=len(strArr)
word=strArr[0]
pattern=strArr[1]
words1=[]
words2=[]
patternlist=pattern.split(",")
length=0
for i in range(0,len(word)-1):
for j in range(0,len(patternlist)):
pattern1=patternlist[j]
length=0
if(word[i]==pattern1[0]):
for k in range(0,len(pattern1)):
z=i+k
if(z<=len(word)):
if(word[z]==pattern1[k]):
length+=1
else:
break
else:
break
if(length==len(pattern1)):
words1.append(pattern1)
check=False
for i in range(0,len(words1)-1):
for j in range(i+1,len(words1)):
x=words1[i]
x+=words1[j]
if(len(x)==len(word)):
words2.append(words1[i])
words2.append(words1[j])
check=True
break
if(check==True):
for i in range(0,len(words2)):
for j in range(0,len(words2)):
if((words2[i]+words2[j])==word):
return [words2[i],words2[j]]
else:
return []
print(WordSplit(["baseball","a,all,b,ball,bas,base,cat,code,d,e,quit,z"]))
print(WordSplit(["abcgefd","a,ab,abc,abcg,b,c,dog,e,efd,zzzz"]))
print(WordSplit(["hamza","h,z,laiba,haz,ham,za,dog,e,efd,zzzz"]))
print(WordSplit(["molvihamza","a,ab,abc,mercedes,mol,molvi,ha,hamza,efd,zzzz"]))
|
63cf1c0ac7e3880b7217de8c4fe78bc6e2a9f6dd | ustczhhao/Simulation-of-Gibson-et-al-Paper | /2.1. Gibson First Reaction Method_OOP.py | 8,588 | 3.90625 | 4 | import numpy as np
from numpy import random
import matplotlib.pyplot as plt
%matplotlib inline
class ChemicalSpecies(object):
'''define the class of chemical species'''
def __init__(self, name, count):
self.name=name
self.count=count
class Reaction(object):
'''define the class of chemical reactions'''
def __init__(self,reactant_list, product_list, coefficient_dic, reconstant):
self.reactant_list=reactant_list
self.product_list=product_list
self.coefficient_dic=coefficient_dic
self.reaction_constant=reconstant
def get_propensity(self):
'''calculate the propensity of the chemical reaction'''
k=1
for i in self.reactant_list:
k=k*i.count**self.coefficient_dic[i.name]
propensity=self.reaction_constant*k
return propensity
def execute(self):
'''calculate the molecular count of reactants and products after the reaction has been executed'''
for i in self.reactant_list:
i.count-=self.coefficient_dic[i.name]
for j in self.product_list:
j.count+=self.coefficient_dic[j.name]
return self.reactant_list,self.product_list
class System(object):
'''define the class of chemical system'''
def __init__(self, reaction_list, chemical_list):
self.reaction_list=reaction_list
self.chemical_list=chemical_list
def run_firstreaction(self,chemicals=None):
'''Use the First Reaction Method to simulate one reaction step of the system with 5 reactions in Gibson et al'''
rx1,rx2,rx3,rx4,rx5=self.reaction_list # use rx1~rx5 to store the 5 chemical reactions
if chemicals==None:
h,s,j,k,l,m,n=self.chemical_list #give the initial value of h~n
else:
h,s,j,k,l,m,n=chemicals # when run_firstreaction has been run, update the value of h~n
in_equilibrium = False # a marker to determine whether the system has reached equilibrium
prop1=rx1.get_propensity()
prop2=rx2.get_propensity()
prop3=rx3.get_propensity()
prop4=rx4.get_propensity()
prop5=rx5.get_propensity()
prop_list=[prop1,prop2,prop3,prop4,prop5]
tau_list=[]
for i in prop_list:
if i==0:
tau_list.append(np.inf)
else:
tau_list.append(((1/i)*np.log(1/(1-np.random.random()))))
if prop_list!=[0,0,0,0,0]: # if prop_list!=[0,0,0,0,0], the system did not reach equilibrium
tau=min(tau_list)
u=np.argmin(tau_list)
if u==0:
[h,s],[j]=rx1.execute()
elif u==1:
[s,j],[k]=rx2.execute()
elif u==2:
[k,l],[l,m]=rx3.execute()
elif u==3:
[m],[k,n]=rx4.execute()
else:
[l,n],[h]=rx5.execute()
elif prop_list==[0,0,0,0,0]: # if tau_list=[0,0,0,0,0], the system has reached equilibrium
in_equilibrium = True
tau=np.inf
else:
print("Error: negative propensities.")
species_list=[h,s,j,k,l,m,n]
return species_list, tau, in_equilibrium
def stimulate(self,start_time, end_time):
'''Stimulate the reactions during a given time period from start_time to end_time'''
t0=start_time # will be used to store the reaction time, and the initial vaule of it is the stimulation start time
t_list=[start_time] # will be used to store t0, and the first element is the stimulation start time
chem_list=[self.chemical_list] # will be used to store the chemical species after each round of run_firstreaction, and
# the first element is the initial value of the chemical species
chemcount_list=[] #will be used to store the molecular count of chemical species after each each round of run_firstreaction
totalcount_list=[] # will be used to store the chemcount_list after each round of run_firstreaction
for i in self.chemical_list:
chemcount_list.append(i.count) # the elements in first chemcount_list is the initial value of chemical species
totalcount_list.append(chemcount_list) # store the first chemcount_list in totalcount_list
equilibrium=False
species_list, t, equilibrium=self.run_firstreaction() # since for the first round of run_firstreaction, the value of
# chemical species was from the self.chemical_list,(following
# round use the previous calculation result of run_firstreaction
t0+=t # update t0
t_list.append(t0) # after first round of run_firstreaction, store the updated t0 to t_list
chem_list.append(species_list) # after first round of run_firstreaction, store the updated species_list to chem_list
# the species_list here will be used for second round of run_firstreaction, and so forth.
chemcount_list=[]
for i in species_list: # after first round of run_firstreaction, store the updated molecular count of chemical
chemcount_list.append(i.count) # species into chemcount_list
totalcount_list.append(chemcount_list) # store the chemcount_list into totalcount_list
while t0<end_time: # when t0<end_time (stimulation ending time), run the while loop
species_list, t, equilibrium=self.run_firstreaction(species_list) # use previous species_list as input to run the
# run_directmethod.
if t!=np.inf: # t!=np.inf means prob_list!=[0,0,0,0,0], the system has not reached equilibrium
t0+=t # after each round of run_firstreaction update t0
t_list.append(t0) # after each round of run_firstreaction, store the updated t0 to t_list
chem_list.append(species_list) #store the updated species_list to chem_list,the species_list here will be used for
# the next round of run_firstreaction.
chemcount_list=[] # after each round of run_firstreaction, store the updated molecular count of chemical
for i in species_list: # species into chemcount_list
chemcount_list.append(i.count)
totalcount_list.append(chemcount_list) # store the chemcount_list into totalcount_list
else: # t=0 means sum(prob_list)==0, the system has reached equilibrium
equilibrium=True
break
return np.array(t_list), np.array(totalcount_list), equilibrium
def display(self, start_time, end_time, time):
'''get the system state (molecular count of each chemical) at a given time point'''
td,c,s=self.stimulate(start_time,end_time) # run the stimulate method and store the results in td, c and s
if time<td[-1]:#if the given time is smaller then td[-1](the equilibrium time), it means the system has not reached
n=len(td) # equilirium
for i in range(n): # from the first element in td to search the elements which time is between them.
if time>=td[i] and time<td[i+1]: # then get the corresponding element in c, this system state at given time
system_state=c[i] # has the same molecular counts with this element
break
else: # if the given time is larger than td[-1](the equilibrium time), it means the system has reached equilirium
system_state=c[-1] # just give the last element in c (the equilibrium state) to system_state
print(list(zip(td,c)))
print("The system state at time: {0} is: {1}".format(time,system_state))
plt.plot(td,c)
|
41965f24584a736144f5fa0bdd7814a21a44cc61 | Melwyna/LaboratorioColecciones | /custom_functions/temperature_methods.py | 4,137 | 3.6875 | 4 | #Promedio de cada depatamento
def suma(a):
sum=0
for item in a:
sum=sum+item
prome=sum/len(a)
return prome
#Promedio nacional y temperatura promedio de los meses más calientes de los 3 departamentos
def suma2(a):
sum=0
for item in a:
sum=sum+item
return sum
def promedion2(a,b,c):
ter2=(a+b+c)/36
return ter2
def promedion(a,b,c):
ter=(a+b+c)/3
return ter
#Valor del mes mas caliente del departamento
def masc(a):
mes = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
mascaliente=a[0]
for item in a:
if item>mascaliente:
mascaliente=item
return mascaliente
#El mes mas caliente del departamento
def maso(a):
mes = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
mascaliente=a[0]
for item in a:
if item>mascaliente:
mascaliente=item
if mascaliente==a[0]:
return "enero"
else:
if mascaliente==a[1]:
return "febrero"
else:
if mascaliente==a[2]:
return "marzo"
else:
if mascaliente==a[3]:
return "abril"
else:
if mascaliente==a[4]:
return "mayo"
else:
if mascaliente==a[5]:
return "junio"
else:
if mascaliente==a[6]:
return "julio"
else:
if mascaliente==a[7]:
return "agosto"
else:
if mascaliente==a[8]:
return "septiembre"
else:
if mascaliente==a[9]:
return "octubre"
else:
if mascaliente==a[10]:
return "noviembre"
else:
if mascaliente==a[11]:
return "diciembre"
#El promedio mas caliente de los tres departamentos y la temperatura más caliente del año, en qué departamento se presentó y en cual mes se presento
def prommcali(a,b,c):
if a>b and a>c:
return "Santander"
if b>c and b>a:
return "Guajira"
if c>b and c>a:
return "Nariño"
#Valor del mes mas caliente de cada departamento y la temperatura más caliente del año, en qué departamento se presentó y en cual mes se presento
def prommcali2(a,b,c):
if a>b and a>c:
return a
if b>c and b>a:
return b
if c>b and c>a:
return c
#La temperatura más caliente del año, en qué departamento se presentó y en cual mes se presento
def prommcali3(a,b,c):
mesc11 = maso(a)
mesc22 = maso(b)
mesc33 = maso(c)
if a>b and a>c:
return mesc11
if b>c and b>a:
return mesc22
if c>b and c>a:
return mesc33
#Desviación estándar de la temperatura en cada departamento
import math
def varianza(a):
suma = 0
for item in a:
suma = suma + item
promedio = suma / len(a)
v1 = promedio - a[0]
if v1 < promedio:
v1 = (v1) * (-1)
else:
v1 = v1
v2 = promedio - a[1]
if v2 < promedio:
x2 = (v2) * (-1)
else:
x2 = v2
v3 = promedio - a[2]
if v3 < promedio:
x3 = (v3) * (-1)
else:
x3 = v3
v4 = promedio - a[3]
if v4 < promedio:
x4 = (v4) * (-1)
else:
x4 = v4
v5 = promedio - a[4]
if v5 < promedio:
x5 = (v5) * (-1)
else:
x5 = v5
v6 = promedio - a[5]
if v6 < promedio:
x6 = (v6) * (-1)
else:
x6 = v6
v7 = promedio - a[6]
if v7 < promedio:
x7 = (v7) * (-1)
else:
x7 = v7
v8 = promedio - a[7]
if v8 < promedio:
x8 = (v8) * (-1)
else:
x8 = v8
v9 = promedio - a[8]
if v9 < promedio:
x9 = (v9) * (-1)
else:
x9 = v9
v10 = promedio - a[9]
if v10 < promedio:
x10 = (v10) * (-1)
else:
x10 = v10
v11 = promedio - a[10]
if v11 < promedio:
x11 = (v11) * (-1)
else:
x11 = v11
v12 = promedio - a[11]
if v12 < promedio:
x12 = (v12) * (-1)
else:
x12 = v12
varia = (
v1 ** 2 + v2 ** 2 + v3 ** 2 + v4 ** 2 + v5 ** 2 + v6 ** 2 + v7 ** 2 + v8 ** 2 + v9 ** 2 + v10 ** 2 + v11 ** 2 + v12 ** 2) / len(
a)
varianza = math.sqrt(varia)
return (varianza) |
4e5453723e9224120e84b3f6713af9aa84c647a6 | FA0AE/Mision-03 | /Boletos.py | 1,510 | 4.15625 | 4 | # Autor: Francisco Ariel Arenas Enciso
# Actividad : Cálculo del total a pagar de boletos dependiendo de su clase
'''
Función que recibe los datos de entrada de la función main (número de boletos) como parametros, los alamcena en
variables y realiza las operaciones artimeticas necesarias para devolver datos de salida (total a pagar).
'''
def calcularPago (asientoA, asientoB, asientoC):
pago_asientoA = asientoA * 925
pago_asientoB = asientoB * 775
pago_asientoC = asientoC * 360
total_pago = pago_asientoA + pago_asientoB + pago_asientoC
return total_pago
'''
Función main (Es la responsable del funcionamiento de todo el programa).
Primero le pide al usuario el número de boletos de cada clase de boletos. Posteriormente envía esos datos a la
función defcalcularPago.
Finalmente imprime la cantidad de boletos de cada clase y el total a pagar.
'''
def main():
numero_boletosA = int(input('¿Cuántos boletos del tipo A se compraron? '))
numero_boletosB = int(input('¿Cuántos boletos del tipo B se compraron? '))
numero_boletosC = int(input('¿Cuántos boletos del tipo C se compraron? '))
total_aPagar= calcularPago(numero_boletosA, numero_boletosB, numero_boletosC)
print ("Número de boletos de clase A: ", str(numero_boletosA))
print ("Número de boletos de clase B: ", str(numero_boletosB))
print ("Número de boletos de clase C: ", str(numero_boletosC))
print ("El costo total es: $ %5.2f" % (total_aPagar))
main()
|
0d644ab18e56d13805766663cc0fb4bf7fd20840 | reeha-parkar/python | /dunder_magic_methods.py | 1,006 | 4.15625 | 4 | import inspect
'''x = [1, 2, 3]
y = [4, 5]
print(type(x)) # Output: <class 'list'>
# Whatever we make it print, it follows a certain pattern
# Which means that there is some class related method that works uunder the hood to give a certain output
'''
# Let's make our own data type:
class Person:
def __init__(self, name):
self.name = name
def __repr__(self): # a dunder/magic method that allows us to define object's string representation
return f'Person({self.name})'
def __mul__(self, x):
if type(x) is not int:
raise Exception('Invalid argument, must be type int')
self.name = self.name * x
def __call__(self, y):
print('called this function', y)
def __len__(self):
return(len(self.name))
p = Person('tim')
p * 4
p(4) # When you call this function, __call__ will work
print(p) # this initially, prints the memory address location
# The dunder methods are a part of 'data model' of python
print(len(p)) |
bdee03756772c0848b3a27bf3c309e3523205975 | reeha-parkar/python | /classmethod_and_staticmethod.py | 1,109 | 4.1875 | 4 | # class methods and static method:
# class method is a method in the class whcih takes te class name as a parameter, requires class instances
# static method is a method which can be directly called without creating an instance of the class
class Dog:
dogs = []
def __init__(self, name):
self.name = name
self.dogs.append(self)
@classmethod
def num_dogs(cls): # cls means the name of the class
return len(cls.dogs)
@staticmethod
def bark(n):
for _ in range(n):
print('Bark!')
'''
# Calling a classmethod:
tim = Dog('tim')
jim = Dog('jim')
print(Dog.dogs) # will get the Dog objects
print(tim.dogs) # will get the same 2 dog objects
print(Dog.num_dogs()) # will get 2
'''
# Calling a static method
Dog.bark(5)
# Only using the class name to get the method, without creating an instance
# Static method is used when you don't need self or an object of the class
# does not require a minimum parameter
# Class method takes the actual class and can access whatever is in the class
# requires a minimum one oarameter and that is 'cls'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.