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 |
|---|---|---|---|---|---|---|
58e95dd1b6f235ea6b2e4817724b1b8590666005 | brunalimap/house_rocket | /notebooks/aula_python01.py | 3,308 | 4 | 4 | import pandas as pd
df = pd.read_csv('data/kc_house_data.csv')
# Para verificar o dataset
#print(df.head())
# Para verificar os tipos das variáveis das colunas
#print(df.dtypes)
# Primeiras Perguntas dos CEO
# 1- Quantas casas estão disponíveis para comprar?
# Estratégia
# 1. Selecionar a coluna 'id'
# 2. Contar o número de valores únicos
print("\nQuantidade de casas disponíveis para compra: {}".format(len(df['id'].unique())))
print("\n")
# 2- Quantos atributos as casas possuem?
# Considerando id e date
print("\nQuantidade de atributos as casas possuem: {}".format(len(df.columns)))
print("\n")
# Se considerar id e date
atributos = len(df.drop(['id','date'],axis=1).columns)
print("\nQuantidade de atributos que as casas possuem não considerando id e data: {}".format(atributos))
print("\n")
# 3- Quais são os atributos das casas?
print("\nOs atributos são: {}".format(df.columns))
print("\n")
# 4- Qual a casa mais cara ( casa com o maior valor de venda)?
#preciso que mostre o ID da casa
sales = df[['id','price']].sort_values('price', ascending=False).reset_index(drop= True).loc[0,'id']
print("\n A casa com o maior valor de venda é {}".format(sales))
print("\n")
# 5- Qual a casa com o maior número de quartos?
bedrooms = df[['id','bedrooms']].sort_values('bedrooms',ascending=False).reset_index(drop=True).loc[0,'id']
print("\n A casa com o maior quantidade de quartos: {}".format(bedrooms))
print("\n")
# 6- Qual a soma total de quartos do conjunto de dados?
print('Total de quartos que tem no dataset: {}'.format(df['bedrooms'].sum()))
print("\n")
# 7- Quantas casas possuem 2 banheiros?
a = df.query('bathrooms == 2')['bathrooms'].count()
print('O número de casas com 2 banheiros é de: {}'.format(a))
print("\n")
# 8- Qual o preço médio de todas as casas no conjunto de dados?
b = df['price'].mean()
print('Preço médio de todas as casas: {}'.format(round(b,2)))
print("\n")
# 9- Qual o preço médio de casas com 2 banheiros?
c = df.loc[df['bathrooms'] == 2, 'price'].mean()
print('Preço médio das casas com 2 banheiro: {}'.format(round(c,2)))
print("\n")
# 10- Qual o preço mínimo entre as casas com 3 quartos?
d = df.query('bedrooms == 3')['price'].min()
print('Preço minimo em casas com dois andares: {}'.format(round(d,2)))
print("\n")
# 11- Quantas casas possuem mais de 300 metros quadrados na sala de estar?
df['m2_living'] = df['sqft_living']*0.093
m2 = len(df.loc[df['m2_living'] > 300,'id'])
print('Quantidade de casa que possuem mais de 300 metros quadrados é {}'.format(m2))
print("\n")
# 12- Quantas casas tem mais de 2 andares?
e = df.loc[df['floors'] > 2,'id'].size
print('Quantidade de casas com mais de 2 andares no dataset: {}'.format(e))
print("\n")
# 13- Quantas casas tem vista para o mar?
print('Casas com vista para o mar: {}'.format(df[df['waterfront']==1].shape[0]))
print("\n")
# 14- Das casas com vista para o mar, quantas tem 3 quartos?
f = len(df.loc[(df['waterfront'] == 1) & (df['bedrooms'] == 3),'id'])
print('Casas com vista para o mar e com 3 quartos: {}'.format(f))
print("\n")
# 15- Das casas com mais de 300 metros quadrados de sala de estar, quantas tem mais de 2 banheiros banheiros?
print('Total de com mais de 2 banheiros: {}'.format(df[(df['m2_living'] > 300) & (df['bathrooms']> 2)].shape[0]))
|
4c3c113d6b9546ec9eba9f289524f25313aa0a25 | jbbang3/thinklikeCS | /Ch10List.py | 1,498 | 3.6875 | 4 | def middle(t):
return t[1:-1]
def cumsum(x):
newt=[]
for i in range(len(x)):
print(i)
newt+=[sum(x[:i+1])]
return newt
def nested_sum(t):
summed=0
for i in range(len(t)):
summed+=sum(t[i])
return summed
letters=['a', 'b', 'c', 'd']
print(middle(letters))
number=[1, 2, 3, 4, 5, 6]
print(cumsum(number))
t = [[1, 2], [3], [4, 5, 6]]
print(nested_sum(t))
import time
def make_word_list1():
"""Reads lines from a file and builds a list using append."""
t = []
fin = open('words.txt')
for line in fin:
word = line.strip()
t.append(word)
return t
def make_word_list2():
"""Reads lines from a file and builds a list using list +."""
t = []
fin = open('words.txt')
for line in fin:
word = line.strip()
t = t + [word]
return t
start_time = time.time()
t = make_word_list1()
elapsed_time = time.time() - start_time
print(len(t))
print(t[:10])
print(elapsed_time, 'seconds')
start_time = time.time()
t = make_word_list2()
elapsed_time = time.time() - start_time
print(len(t))
print(t[:10])
print(elapsed_time, 'seconds')
#Q4===================================================
def has_duplicates(t):
for i in range(len(t)):
if t[i] in t[i+1:]:
return True
if i>0:
if t[i] in t[:i]:
return True
return False
t1=[1, 1, 3, 4, 9, 5]
t2=[1, 2, 3, 4, 6, 5]
print(has_duplicates(t1))
print(has_duplicates(t2)) |
3bb12286fa514a14083d77e90a9bf443dff65d4d | AngeloBradley/Data-Structures-w-Python | /SLinkedList.py | 13,616 | 4.0625 | 4 | from LinkedList import LinkedList
from Node import Node
import sys
class SLinkedList(LinkedList):
def __init__(self):
LinkedList.__init__(self)
#==================================#Private Helper Functions#==================================
def insertion_handler(self, newdata, pointer1, pointer2):
#pointer1 is 1 step in front of where the new node belongs
#pointer2 is 1 step behind where the new node belongs
new_node = Node(newdata)
new_node.nextval = pointer1
pointer2.nextval = new_node
self.increaselength()
def remove_head(self):
if self.empty:
return -1
if self.length == 1:
current_head = self.headval
current_head.nextval = None #current_head broken away from list
self.empty = True
self.headval = None
self.tailval = None
else:
current_head = self.headval
new_head = self.headval.nextval
current_head.nextval = None #current_head broken away from list
self.headval = new_head #new_head formally established
self.decreaselength()
return current_head
def remove_tail(self):
if self.empty:
return -1
if self.length == 1:
#in this scenario the head and the tail are the same node
current_tail = self.remove_head()
self.empty = True
self.headval = None
self.tailval = None
else:
pointer1, pointer2 = self.init_pointers()
#using pointer1.nextval so that when the loop exits
#pointer1 is on the last node and pointer2 (new_tail)
#is on the second to last node
while pointer1.nextval is not None:
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
current_tail = self.tailval
new_tail = pointer2
new_tail.nextval = None #current_tail officially broken away from list
self.tailval = new_tail #new tail formally established
self.decreaselength()
return current_tail
#==================================#Public Functions#==================================
def alternating_split(self):
list1 = SLinkedList()
list2 = SLinkedList()
for i in range(self.length):
if i % 2 == 0:
list1.append(self.remove_head())
else:
list2.append(self.remove_head())
return list1, list2
def append(self, newdata):
if self.empty:
return self.set_headval_for_empty_list(newdata)
else:
if newdata.__class__.__name__ == 'Node':
new_node = newdata
else:
new_node = Node(newdata)
self.tailval.nextval = new_node
self.tailval = new_node
self.increaselength()
return new_node
def append_list(self, list2):
self.length += list2.length
if self.empty:
self.headval = list2.headval
self.tailval = list2.tailval
else:
self.tailval.nextval = list2.headval
self.tailval = list2.tailval
list2.headval = None
list2.tailval = None
list2 = None
def deep_copy(self):
copy = SLinkedList()
pointer1, pointer2 = self.init_pointers()
while pointer1 is not None:
copy.append(pointer1.dataval)
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
return copy
def deletelist(self):
while self.headval is not None:
self.remove_head()
return self.headval, self.tailval, self.length, self.empty
def frontbacksplit(self):
backsplit = SLinkedList()
if self.length < 2:
return backsplit
pointer1, pointer2 = self.init_pointers()
mid = 0
if self.length % 2 == 0:
mid = int(self.length / 2)
else:
mid = int((self.length // 2) + 1)
for i in range(mid):
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
#pointer1 is at the head of the backsplit
#pointer2 is at the tail of the frontsplit
backsplit.headval = pointer1
backsplit.tailval = self.tailval
backsplit.empty = False
self.tailval = pointer2
self.tailval.nextval = None
return backsplit
def insert_nth(self, index, newdata):
if index > self.length:
return -1
elif index == 0:
return self.prepend(newdata)
elif index == self.length:
return self.append(newdata)
else:
pointer1, pointer2 = self.init_pointers()
for _ in range(index):
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
#pointer1 is pointing to index after the desired location
#pointer2 is pointing to the index before
if newdata.__class__.__name__ == 'Node':
new_node = newdata
else:
new_node = Node(newdata)
pointer2.nextval = new_node
new_node.nextval = pointer1
self.increaselength()
return new_node
def insert_sort(self):
new_list = SLinkedList()
for _ in range(self.length):
reinsertion_data = self.remove_head().dataval
new_list.ordered_insert(reinsertion_data)
self.headval = new_list.headval
def merge_sort(self):
pass
def move_node(self, list2):
move_this_node = list2.remove_head()
self.prepend(move_this_node)
def ordered_insert(self, newdata, code = 0):
if self.empty:
new_node = self.set_headval_for_empty_list(newdata)
return new_node
#code == 0 for ascending and 1 for descending
if code not in (0,1):
sys.exit('invalid code value')
if code == 0:
pointer1, pointer2 = self.init_pointers()
while pointer1 is not None:
if pointer1.dataval > newdata:
if pointer1 == self.headval:
self.prepend(newdata)
return
self.insertion_handler(newdata, pointer1, pointer2)
return
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
if code == 1:
pointer1, pointer2 = self.init_pointers()
while pointer1 is not None:
if pointer1.dataval < newdata:
if pointer1 == self.headval:
self.prepend(newdata)
return
self.insertion_handler(newdata, pointer1, pointer2)
return
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
#this line simply adds the new node to the end if there are no values in the list
#by which to add the node in ascending (all values are smaller) or descending (all values are larger)
self.append(newdata)
return
def pop(self):
return self.remove_head().dataval
def prepend(self, newdata):
if self.empty:
return self.set_headval_for_empty_list(newdata)
else:
if newdata.__class__.__name__ == 'Node':
new_node = newdata
else:
new_node = Node(newdata)
new_node.nextval = self.headval
self.headval = new_node
self.increaselength()
return new_node
def push(self, newdata):
self.append(newdata)
def remove(self, data, code = 0):
#code = 0 removes first instance from the left
#code = 1 removes all instances
#code = 2 removes first instance from the right
if self.empty:
return -1
if code not in (0,1,2):
sys.exit('incorrect code value passed to remove function')
if code == 0:
pointer1, pointer2 = self.init_pointers()
while pointer1 is not None:
if pointer1.dataval == data:
if pointer1 == self.headval:
removed_node = self.remove_head()
elif pointer1 == self.tailval:
removed_node = self.remove_tail()
else:
removed_node = pointer1
pointer2.nextval = removed_node.nextval
removed_node.nextval = None
self.decreaselength()
if self.length == 0: self.empty = True
return removed_node
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
return None
if code == 1:
pointer1, pointer2 = self.init_pointers()
while pointer1 is not None:
if pointer1.dataval == data:
if pointer1 == self.headval:
#because p1 and p2 are both pointing to the node
#that is due to be removed, you need to first move
#both of them to what will become the new head
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
removed_node = self.remove_head()
continue
if pointer1 == self.tailval:
removed_node = self.remove_tail()
pointer1 = pointer2
continue
removed_node = pointer1
pointer2.nextval = removed_node.nextval
p1 = removed_node.nextval #ensures that pointer1 does not break away with the removed node
removed_node.nextval = None
pointer1 = p1 #places pointer1 on the next node in the list
self.decreaselength()
continue
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
if self.length == 0: self.empty = True
return removed_node
if code == 2:
pointer1, pointer2 = self.init_pointers()
index = 0
indices = []
while pointer1 is not None:
if pointer1.dataval == data:
#add the "index" of all values matching the removal data parameter
indices.append(index)
index += 1
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
pointer1, pointer2 = self.init_pointers()
#iterate through the list again to the location of the last matching node
for _ in range(indices[len(indices) - 1]):
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
#remove node here, note that the right-most instance could be the first node in the list
if pointer1 == self.headval:
removed_node = self.remove_head()
elif pointer1 == self.tailval:
removed_node = self.remove_tail()
else:
removed_node = pointer1
pointer2.nextval = removed_node.nextval
removed_node.nextval = None
self.decreaselength()
if self.length == 0: self.empty = True
return removed_node
def remove_duplicates(self):
pointer1 = self.headval.nextval
pointer2 = self.headval
while pointer1 is not None:
if pointer1.dataval == pointer2.dataval:
data = pointer1.dataval
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
self.remove(data)
continue
pointer1, pointer2 = self.update_pointers(pointer1, pointer2)
def reverselist_inplace(self):
pass
def sorted_intersect(self, list2):
l1 = self.deep_copy()
l2 = list2.deep_copy()
l1.append_list(l2)
l1.printlist()
print()
l1.insert_sort()
l1.printlist()
print()
l1.remove_duplicates()
l1.printlist()
print()
return l1
def sorted_merge(self, list2):
self.append_list(list2)
self.insert_sort()
def shuffle_merge(self, list2):
i = 0
while list2.headval is not None:
if i % 2 == 1:
self.insert_nth(i, list2.remove_head())
i += 1
if __name__ == '__main__':
list1 = SLinkedList()
list2 = SLinkedList()
for i in range(5):
list1.append(i)
for i in range(3,8):
list2.append(i)
list3 = list1.sorted_intersect(list2)
list3.printlist() |
0fd48c88aaa2783327154f9189d9b07e16b5f7e8 | Teakmin/algorithm | /solving/fibonacci.py | 179 | 3.71875 | 4 | def fib(n):
if n == 0 or n==1 : return n # fib(0) = 1, fib(1) =1
return fib(n - 1 ) + fib(n - 2) # fib(n) = fib(n-1) + fib(n-2)
print(fib(5))
print(fib(4))
print(fib(3)) |
388bd00a1e22c4b91ddddfb08eed5c05c61f4607 | justinyates887/tkinter-practice | /hello.py | 450 | 3.9375 | 4 | #tkinter is built into python
from tkinter import *
#To use a widget, or window, you have to declare it from tkinter
root = Tk()
#you can then add a label to the widget
myLabel = Label(root, text='Hello World')
#The pack function is a primitive way to get the widget to appear on screen
myLabel.pack() #Now the window will appear once ran
#Event loops are needed for gui's in order to determine the actions taken by the user on screen
root.mainloop()
|
7ca6661867b207e89b504eabf422334c6c5c9d58 | thouzeauhernan/Phyton | /index.py | 5,583 | 3.625 | 4 | from sqlite3.dbapi2 import Row
from tkinter import ttk
from tkinter import *
import sqlite3
print("hola mundo")
class producto:
db_nombre = 'baseDatos.db'
#
def __init__(self,window):
self.wind=window
self.wind.title('nueva aplicacion')
#crear un frame
frame = LabelFrame(self.wind, text = 'Registrar un nuevo producto')
frame.grid(row=0,column=0, columnspan=3,pady=20)
#label de entrada
Label(frame, text = 'nombre:').grid(row=1, column=0)
self.name = Entry(frame)
self.name.focus()
self.name.grid(row=1, column=1)
#label de entrada
Label(frame, text = 'Precio:').grid(row=2, column=0)
self.precio = Entry(frame)
self.precio.grid(row=2, column=1)
#boton de producto
ttk.Button(frame, text='Guardar Producto', command = self.add_productos).grid(row=3, columnspan=2, sticky=W + E)
#mensaje de Salida
self.mensaje = Label(text='', fg='red')
self.mensaje.grid(row=3, column=0, columnspan=2, sticky=W+E)
#tabla
self.tree = ttk.Treeview(height=10,columns=2)
self.tree.grid(row=4, column=0, columnspan=2)
self.tree.heading('#0', text = 'Nombre', anchor = CENTER)
self.tree.heading('#1', text = 'Precio', anchor = CENTER)
#botones para eliminar y editar
ttk.Button(text='Eliminar Producto', command = self.eliminar_producto).grid(row=5,column=0, sticky=W + E)
ttk.Button(text='Editar Producto', command = self.editar_producto).grid(row=5, column=1, sticky=W + E)
#traer los datos de la db
self.get_productos()
#
def run_query(self, query, parametros = ()):
with sqlite3.connect(self.db_nombre) as conn:
cursor = conn.cursor()
resultado = cursor.execute(query, parametros)
conn.commit()
return resultado
def get_productos(self):
#limpiando la tabla
record = self.tree.get_children()
for element in record:
self.tree.delete(element)
#consulta de datos
query = 'SELECT * FROM productos ORDER BY Nombre DESC'
db_filas = self.run_query(query)
for row in db_filas:
self.tree.insert('',0,text = row[1], values = row[2])
#
def validacion(self):
return (len(self.name.get()) !=0 and len(self.precio.get()) !=0)
#
def add_productos(self):
if self.validacion():
query = 'INSERT INTO productos VALUES(NULL, ?, ?)'
parametros =(self.name.get(),self.precio.get())
self.run_query(query,parametros)
self.mensaje['text'] = 'Producto Guardado Correctamente'
self.name.delete(0,END)
self.precio.delete(0,END)
else:
self.mensaje['text'] = 'El nombre y el Precio son requeridos'
self.get_productos()
def eliminar_producto(self):
self.mensaje['text'] = ''
try:
self.tree.item(self.tree.selection())['text'][0]
except IndexError as e:
self.mensaje['text'] = 'Seleccione un Producto'
return
self.mensaje['text'] = ''
Nombre = self.tree.item(self.tree.selection())['text']
query = 'DELETE FROM productos WHERE Nombre = ?'
self.run_query(query,(Nombre,))
self.mensaje['text'] = 'El producto fue eliminado correctamente'
self.get_productos()
def editar_registro(self, nuevo_nombre, Nombre, nuevo_precio, Precio_viejo):
query = 'UPDATE productos set Nombre = ?, Precio = ? WHERE Nombre = ? AND Precio = ?'
parametros = (nuevo_nombre, nuevo_precio,Nombre,Precio_viejo)
self.run_query(query,parametros)
self.ventana_editar.destroy()
self.mensaje['text'] = 'El producto fue actualizado correctamente'
self.get_productos()
def editar_producto(self):
self.mensaje['text'] = ''
try:
self.tree.item(self.tree.selection())['text'][0]
except IndexError as e:
self.mensaje['text'] = 'Seleccione un Producto'
return
Nombre = self.tree.item(self.tree.selection())['text']
Precio_viejo = self.tree.item(self.tree.selection())['values'][0]
self.ventana_editar = Toplevel()
self.ventana_editar.title = 'Editar Producto'
#nombre viejo
Label(self.ventana_editar, text= 'Nombre Actual').grid(row=0,column=1)
Entry(self.ventana_editar, textvariable = StringVar(self.ventana_editar, value = Nombre), state= 'readonly').grid(row=0,column=2)
#nombre nuevo
Label(self.ventana_editar, text= 'Nombre Nuevo').grid(row=1,column=1)
nuevo_nombre = Entry(self.ventana_editar)
nuevo_nombre.grid(row=1,column=2)
#Precio viejo
Label(self.ventana_editar, text= 'Precio Actual').grid(row=2,column=1)
Entry(self.ventana_editar, textvariable = StringVar(self.ventana_editar, value = Precio_viejo), state= 'readonly').grid(row=2,column=2)
#Precio nuevo
Label(self.ventana_editar, text= 'Precio Nuevo').grid(row=3,column=1)
nuevo_precio = Entry(self.ventana_editar)
nuevo_precio.grid(row=3,column=2)
Button(self.ventana_editar, text = 'Actualizar Datos', command = lambda: self.editar_registro(nuevo_nombre.get(),Nombre,nuevo_precio.get(),Precio_viejo)).grid(row=4,column=2, sticky=W)
if __name__=='__main__':
window = Tk()
aplicacion = producto(window)
window.mainloop() |
c3f3e836042df5e06d1f19b26fda1197726d2030 | mikofski/poly2D | /polyDer2D.py | 2,204 | 4.25 | 4 | import numpy as np
def polyDer2D(p, x, y, n, m):
"""
polyDer2D(p, x, y, n, m)
Evaluate derivatives of a 2-D polynomial using Horner's method.
Evaluates the derivatives of 2-D polynomial `p` at the points
specified by `x` and `y`, which must be the same dimensions. The
outputs `(fx, fy)` will have the same dimensions as `x` and `y`.
The order of `x` and `y` are specified by `n` and `m`, respectively.
Parameters
----------
p : array_like
Polynomial coefficients in order specified by polyVal2D.html.
x : array_like
Values of 1st independent variable.
y : array_like
Values of 2nd independent variable.
n : int
Order of the 1st independent variable, `x`.
m : int
Order of the 2nd independent variable, `y`.
Returns
-------
fx : ndarray
Derivative with respect to x.
fy : ndarray
Derivative with respect to y.
See Also
--------
numpy.polynomial.polynomial.polyval2d : Evaluate a 2-D polynomial at points (x, y).
Example
--------
>>> print polyVal2D([1,2,3,4,5,6],2,3,2,1)
>>> (39, 11)
>>> 1*2*2*3 + 2*3 + 4*2*2 + 5
39
>>> 1*(2**2) + 2*2 + 3
11
>>> print polyVal2D([1,2,3,4,5,6,7,8,9],2,3,2,2)
>>> (153, 98)
>>> 1*2*2*(3**2) + 2*(3**2) + 4*2*2*3 + 5*3 + 7*2*2 + 8
153
>>> 1*2*(2**2)*3 + 2*2*2*3 + 3*2*3 + 4*(2**2) + 5*2 + 6
98
"""
# TODO: check input args
p = np.array(p)
x = np.array(x)
y = np.array(y)
n = np.array(n)
m = np.array(m)
# fx = df/dx
fx = n * p[0]
for ni in np.arange(n - 1):
fx = fx * x + (n - ni - 1) * p[1 + ni]
for mi in np.arange(m):
mj = (n + 1) * (mi + 1)
gx = n * p[mj]
for ni in np.arange(n - 1):
gx = gx * x + (n - ni - 1) * p[mj + 1 + ni]
fx = fx * y + gx
# fy = df/dy
fy = p[0]
for ni in np.arange(n):
fy = fy * x + p[1 + ni]
fy = m * fy
for mi in np.arange(m - 1):
mj = (n + 1) * (mi + 1)
gy = p[mj]
for ni in np.arange(n):
gy = gy * x + p[mj + 1 + ni]
fy = fy * y + (m - mi - 1) * gy
return fx, fy
|
d3be3d7e395eafc7174e41ec2a9e995616374be0 | PacktPublishing/Raspberry-Pi-Making-Amazing-Projects-Right-from-Scratch- | /Module 1/Chapter 1/prog4.py | 106 | 3.65625 | 4 | def fib(n):
a,b = 0,1
for i in range(n):
a,b = b,a+b
return a
for i in range(0,10):
print (fib(i))
|
8e3cc0cdc15f9e761c8056591532dd2409b6fd5b | PacktPublishing/Raspberry-Pi-Making-Amazing-Projects-Right-from-Scratch- | /Module 1/Additional code files/Additional_Programs_Part_1/prog2.py | 398 | 3.609375 | 4 | # Fractal Koch
import turtle
def koch(t, order, size):
if order == 0:
t.forward(size)
else:
for angle in [60, -120, 60, 0]:
koch(t, order-1, size/3)
t.left(angle)
def main():
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
myTurtle.penup()
myTurtle.backward(250)
myTurtle.pendown()
koch ( myTurtle, 4, 500 )
myWin.exitonclick()
main()
|
8e44b4f33e8737c96f56d1b20c70c8ba3488d83f | andutzu7/Lucrare-Licenta-MusicRecognizer | /Music Recognizer/Metrics/BinaryCrossentropy.py | 1,870 | 4 | 4 | import numpy as np
from .Loss import Loss
class BinaryCrossentropy(Loss):
"""
The class computes the binary crossentropy by applying the formula.
Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.407-412]
"""
def forward(self, y_pred, y_true):
"""
Performs the forward pass.
Args : y_pred(np.array): Model predictions
y_true(np.array): Actual values
Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.112-116]
"""
# Clip data to prevent division by 0 and to avoid draging the mean towards any value
y_pred_clipped = np.clip(y_pred, 1e-7, 1 - 1e-7)
# Calculate the loss by sample
sample_losses = -(y_true * np.log(y_pred_clipped) +
(1 - y_true) * np.log(1 - y_pred_clipped))
# Compute the mean
sample_losses = np.mean(sample_losses, axis=-1)
return sample_losses
def backward(self, derivated_values, y_true):
"""
Perform the backward pass.
Args : derivated_values(np.array): Input values.
y_true(np.array): Actual values
Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.430-436]
"""
# Number of samples and outputs
samples = len(derivated_values)
outputs = len(derivated_values[0])
# Clip data to prevent division by 0 and to avoid draging the mean towards any value
clipped_derivated_values = np.clip(derivated_values, 1e-7, 1 - 1e-7)
# Calculate gradient
self.derivated_inputs = -(y_true / clipped_derivated_values -
(1 - y_true) / (1 - clipped_derivated_values)) / outputs
# Normalize the gradient and applying it to the values
self.derivated_inputs = self.derivated_inputs / samples
|
19dafbf700ec73673dd5fddd2b12472785a14467 | andutzu7/Lucrare-Licenta-MusicRecognizer | /Music Recognizer/Metrics/MeanAbsoluteError.py | 1,462 | 4.03125 | 4 | import numpy as np
from .Loss import Loss
class MeanAbsoluteError(Loss):
"""
The MAE class computes the loss by calculating the average of the absolute value of the errors
(the average squared difference between the estimated and actual values)
Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.430-436]
"""
def forward(self, y_pred, y_true):
"""
Performs the forward pass.
Args : y_pred(np.array): Model predictions
y_true(np.array): Actual values
Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.430-436]
"""
# Perform the MAE error.
sample_losses = np.mean(np.abs(y_true - y_pred), axis=-1)
return sample_losses
def backward(self, derivated_values, y_true):
"""
Perform the backward pass.
Args : derivated_values(np.array): Input values.
y_true(np.array): Actual values
Sources: * Neural Networks from Scratch - Harrison Kinsley & Daniel Kukieła [pg.430-436]
"""
# Taking the number of outputs in every sample we'll use
samples = len(derivated_values)
outputs = len(derivated_values[0])
# Calculate the gradient
self.derivated_inputs = np.sign(y_true - derivated_values) / outputs
# Normalize the gradient and applying it to the values
self.derivated_inputs = self.derivated_inputs / samples
|
e49bdaefea94b60748c118015eb75b1980bc3cc3 | charlesepps79/ch_3 | /shrinking_guest_list.py | 3,716 | 4.25 | 4 | # 3-7. Shrinking Guest List: You just found out that your new dinner
# table won't arrive in time for the dinner, and you have space for
# only two guests.
# Start with your program from Exercise 3-6. Add a new line that prints
# a message saying that you can invite only two people for dinner.
guests = ['Ted Bundy', 'Pedro Lopez', 'H.H. Holmes']
message = "To " + guests[0].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[1].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[-1].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "I regret to inform you that " + guests[0].title() + " will not be able to attend as he is having a friend for dinner."
print(message)
popped_guest = guests.pop(0)
guests.insert(0, 'John Wayne Gacy')
message = "To " + guests[0].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[1].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[-1].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "Honored guests, I am pleased to announce that I have found a bigger table!"
print(message)
guests.insert(0, 'Harold Shipman')
guests.insert(2, 'Jeffrey Dahmer')
guests.insert(-1, 'Jack the Ripper')
message = "To " + guests[0].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[1].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[2].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[3].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[4].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[-1].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "I regret to inform you that I can only invite two guests"
print(message)
# Use pop() to remove guests from your list one at a time until only
# two names remain in your list. Each time you pop a name from your
# list, print a message to that person letting them know you're sorry
# you can't invite them to dinner.
popped_guest = guests.pop(0)
message = "To " + popped_guest.title() + ". I regret to inform you that your presence will no longer be needed"
print(message)
popped_guest = guests.pop(0)
message = "To " + popped_guest.title() + ". I regret to inform you that your presence will no longer be needed"
print(message)
popped_guest = guests.pop(1)
message = "To " + popped_guest.title() + ". I regret to inform you that your presence will no longer be needed"
print(message)
popped_guest = guests.pop(1)
message = "To " + popped_guest.title() + ". I regret to inform you that your presence will no longer be needed"
print(message)
# Print a message to each of the two people still on your list, letting
# them know they're still invited.
message = "To " + guests[0].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
message = "To " + guests[1].title() + ". The honor of your presence is requested for dinner and cocktails"
print(message)
# Use del to remove the last two names from your list, so you have an
# empty list. Print your list to make sure you actually have an empty
# list at the end of your program.
del guests[0:2]
print(guests)
|
fb9b534920888e4d9ce1cb440a260bb6927cf11e | GeeksHubsAcademy/2020-hackathon-zero-python-retos-pool-4 | /src/kata2/rpg.py | 1,274 | 3.96875 | 4 | #!/usr/bin/python
import random
import string
def RandomPasswordGenerator(passLen=10):
resultado = ""
letras = string.ascii_letters
digitos = string.digits
signosDePuntuacion = string.punctuation
# Generamos una contrseña simplemente de letras
n = 0
while n < passLen:
resultado += random.choice(letras)
n += 1
# Le añadimos un digito y un singo de puntuación siempre y cuando la longitud de la contraseña es mayor/igual a 3
if passLen >= 3:
# Vamos a calcular en que posiciones ponemos el dígito y el signo de puntuación
indices = [0, 0]
# Calculamos la primera posición
indices[0] = random.randint(1, passLen - 1)
# Calculamos la segunda posición
# No queremos la primera y no queremos que pisemos la del dígito
while indices[1] == 0 or indices[1] == indices[0]:
indices[1] = random.randint(1, passLen - 1)
# Reemplazamos dichas posiciones
tmpResultado = list(resultado)
tmpResultado[indices[0]] = random.choice(digitos)
tmpResultado[indices[1]] = random.choice(signosDePuntuacion)
# Volvemos a asignar el resultado
resultado = "".join(tmpResultado)
return resultado |
a61402a1392632c8b661e1feb93249f0f8e782ec | Nionchik/Nionchik.github.io | /PhitonLessons/Condition.py | 261 | 3.78125 | 4 | money = 2000
if money >= 100 and money <= 500:
print('КУПИ ЖВАЧКУ')
else:
print('НЕ ПОКУПАЙ ЖВАЧКУ')
if money >= 1000 and money <= 2000:
print('Купи игрушку')
else:
print('Не покапай игрушку')
|
cc739faec2db174882aa754012daa6d07c1dcbcc | Nionchik/Nionchik.github.io | /PhitonLessons/Domashka2_Else & If.py | 249 | 3.796875 | 4 | money = 490
if money >= 100:
print('Ты нормально обепеченный человек')
else :
print('Ты очень беден или богат')
if money >= 500:
print('Ты слишком богатый человек')
|
7e7cb661a3ff5ab152b247b74217e0e5edb7a74c | serhatarslan1/Denemeler | /Bilet ücreti.py | 550 | 3.703125 | 4 | #25.02.2018
__author__ = "Serhat Arslan"
while True:
print("Öğrenci (1)")
print("Tam (2)")
print("65 Yaş Üzeri(3)")
print("-------------------")
print
seçim= input("Bilet Türü Seçiniz:")
if seçim=="1":
print("Öğrenci bilet ücretiniz 1.75 TL.")
elif seçim=="2":
print("Tam bilet ücretiniz 2.5 TL.")
elif seçim=="3":
print("65 yaş üzeri biletiniz ücretsizdir.")
else:
print("Lütfen geçerli bir bilet seçiniz. Program Sonlandı.")
break
|
43bd9e4306c3e31a78795005e12a57bb63e06751 | JakeBednard/CodeInterviewPractice | /7-1_MergeTwoSortedLinkedList.py | 1,311 | 4.09375 | 4 | """Merge 2 prior sorted linked list into linked list"""
class node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_linked_list(head):
temp = []
while True:
temp.append(head.value)
head = head.next
if head is None:
break
print(temp)
def merge_two_lists(l1, l2):
head = node(-1, None)
point = head
while l1 or l2:
if l1 and l2:
if l1.value <= l2.value:
point.next = node(l1.value)
point = point.next
l1 = l1.next
elif l1.value > l2.value:
point.next = node(l2.value)
point = point.next
l2 = l2.next
elif l1 and not l2:
point.next = node(l1.value)
point = point.next
l1 = l1.next
else:
point.next = node(l2.value)
point = point.next
l2 = l2.next
return head.next
# Linked List 1
list1 = node(0)
point = list1
for i in [3,5,7,9,11,13,15,17]:
point.next = node(i)
point = point.next
# Linked List 2
list2 = node(1)
point = list2
for i in [2,2,3,4,5]:
point.next = node(i)
point = point.next
list3 = merge_two_lists(list1, list2)
print_linked_list(list3)
|
4f6c341cb5903f526d9780af9d1aa2f8b2b87e35 | JakeBednard/CodeInterviewPractice | /6-1B_ManualIntToString.py | 444 | 4.125 | 4 | def int_to_string(value):
"""
Manually Convert String to Int
Assume only numeric chars in string
"""
is_negative = False
if value < 0:
is_negative = True
value *= -1
output = []
while value:
value, i = divmod(value, 10)
output.append((chr(i + ord('0'))))
return ('-' if is_negative else '') + "".join(reversed(output))
print(int_to_string(133))
print(int_to_string(-133)) |
3eb362415223db72994bcd38fd329f08624ca2ad | zhuyidiwow/Learning-Python | /course3/assign_week5.py | 364 | 3.71875 | 4 | import urllib
import xml.etree.ElementTree as ET
url = raw_input("Enter url: ")
data = urllib.urlopen(url).read() # read the xml to a string
tree = ET.fromstring(data) # make a tree with that string
count_lst = tree.findall(".//count") # find all count tags and return a list
total = 0
for count in count_lst:
total = total + int(count.text)
print total
|
0e4e3032733e0e07094344c896c907161ef70ddd | sptechguru/Python-Core-Basics-Programs | /ifelse.py | 171 | 3.96875 | 4 | var1 = 355
var2 = 35
var3 = int(input())
if var3 > var1:
print("Greater Number is")
elif var3 == var1:
print("Equal Numbers")
else:
print("Less Number is ")
|
1c6b1d582a9b2ec6ff7ac5bfa5d4fa9a00e57de8 | sptechguru/Python-Core-Basics-Programs | /oops/opps.py | 259 | 3.71875 | 4 | class Person:
def __init__(self,first_name, last_name, age):
print("Init Method")
self.name= first_name
self.last = last_name
self.age = age
p1 = Person('santosh','pal',24)
print(p1.name)
print(p1.last)
print(p1.age)
|
02f83da16ff3445b8d2776f3db483110aff7b4a0 | sptechguru/Python-Core-Basics-Programs | /string.py | 222 | 3.9375 | 4 | mystr = "Santosh is good Boy"
# print(len(mystr))
# # print(mystr[10])
print(mystr.upper())
print(mystr.lower())
print(mystr.count("0"))
print(mystr.find("is"))
print(mystr.capitalize())
print(mystr.replace("is" ,"are")) |
5573f3eeb4a16263a4204b4ef1058858646b9873 | sptechguru/Python-Core-Basics-Programs | /oops/multipleinhertance.py | 1,101 | 4.1875 | 4 | import time
class phone:
def __init__(self,brand,model_name,price):
self.brand = brand
self.model_name = model_name
self.price = price
def full_name(self):
return f"{self.brand}{self.model_name} {self.price}"
# multiple inheritance in class phone is Dervive Class & Main Class
# smartphone is child Class
class Smartphone(phone):
def __init__(self,brand,model_name,price,ram,internal_memory,rear_camera):
super().__init__(brand,model_name,price)
self.ram =ram
self.internal_memory = internal_memory
self.rear_camera = rear_camera
def last_name(self):
return f"{self.brand}{self.model_name} {self.price} {self.ram}{self.internal_memory} {self.rear_camera}"
phone = phone(' Nokia ','110',1000)
smartphone = Smartphone(' oneplus :','5+ :','30000 :' ,'6Gb :','64GB :','20Mp')
print(phone.full_name())
print()
time.sleep(2)
print(smartphone.last_name())
# print(smartphone.full_name()+ f" And Price is {smartphone.price}{smartphone.ram} "
# f"{smartphone.internal_memory}{smartphone.rear_camera}")
|
7cb34e5485d3bb69e8479f85ce08880cf9acd73e | Nathan-Patnam/Bioinformatics-AssignmentsandProjects | /Peptide Encoding/PeptideEncoding.py | 10,797 | 4.21875 | 4 | # function that takes in a single amino acid either in its 3 letter or one letter form and returns all of the possible codons that map to that amino acid
import itertools
def peptideEncoding():
aminoAcid = str(input("Please enter either a 3 letter or 1 letter amino acid sequence"))
aminoAcid = aminoAcid.upper()
length = len(aminoAcid)
#dictionaries that act like the codon tables
codonThreeDictionary = {"PHE": ["TTT, TTC"],
"LEU": ["CTT, CTC, CTA, CTG, TTA, TTG"],
"SER": ["TCT, TCC, TCA, TCG, AGT, AGC"],
"TYR": ["TAT, TAC"],
"STOP": ["TAA, TAG, TGA"],
"CYS": ["TGT, TGC"],
"TRP": ["TGG"],
"PRO": ["CCT, CCC, CCA, CCG"],
"HIS": ["CAT, CAC"],
"GLY": ["GGT, GGC, GGA, GGG"],
"ARG": ["CGT, CGC, CGA, CGG, AGA, AGG"],
"ILE": ["ATT, ATC, ATA"],
"MET": ["ATG"],
"THR": ["ACT, ACC, ACA, ACG"],
"ASN": ["AAT, AAC"],
"LYS": ["AAA, AAG"],
"VAL": ["GTT, GTC, GTA, GTG"],
"ALA": ["GCT, GCC, GCA, GCG"],
"ASP": ["GAT, GAC"],
"GLU": ["GAA, GAG"], }
codonOneDictionary = {"F": ["TTT, TTC"],
"L": ["CTT, CTC, CTA, CTG, TTA, TTG"],
"S": ["TCT, TCC, TCA, TCG, AGT, AGC"],
"Y": ["TAT, TAC"],
"STOP": ["TAA, TAG, TGA"],
"C": ["TGT, TGC"],
"W": ["TGG"],
"P": ["CCT, CCC, CCA, CCG"],
"H": ["CAT, CAC"],
"G": ["GGT, GGC, GGA, GGG"],
"R": ["CGT, CGC, CGA, CGG, AGA, AGG"],
"I": ["ATT, ATC, ATA"],
"M": ["ATG"],
"T": ["ACT, ACC, ACA, ACG"],
"N": ["AAT, AAC"],
"K": ["AAA, AAG"],
"V": ["GTT, GTC, GTA, GTG"],
"A": ["GCT, GCC, GCA, GCG"],
"D": ["GAT, GAC"],
"E": ["GAA, GAG"], }
#find the list of values(codons) mapped to a desired key (amino acid)
if length == 3:
if aminoAcid in codonThreeDictionary:
print(codonThreeDictionary[aminoAcid])
elif length == 1:
if aminoAcid in codonOneDictionary:
print(codonOneDictionary[aminoAcid])
else:
print(
"The amino acid you inputted was not in the correct format, please enter a single amino acid using either its 1 letter or 3 letter abbreviation")
def listPeptideEncoding():
aminoAcid = str(input("Please enter an amino acid sequence: "))
threeOrOneLetter = int(input("Did you enter the above amino acid sequence using the 1 or 3 letter abbreviation"
" (type in either 1 or 3): "))
aminoAcidList = []
length = len(aminoAcid)
#dictionaries that are codon tables
codonThreeDictionary = {"PHE": ["TTT, TTC"],
"LEU": ["CTT, CTC, CTA, CTG, TTA, TTG"],
"SER": ["TCT, TCC, TCA, TCG, AGT, AGC"],
"TYR": ["TAT, TAC"],
"STOP": ["TAA, TAG, TGA"],
"CYS": ["TGT, TGC"],
"TRP": ["TGG"],
"PRO": ["CCT, CCC, CCA, CCG"],
"HIS": ["CAT, CAC"],
"GLY": ["GGT, GGC, GGA, GGG"],
"ARG": ["CGT, CGC, CGA, CGG, AGA, AGG"],
"ILE": ["ATT, ATC, ATA"],
"MET": ["ATG"],
"THR": ["ACT, ACC, ACA, ACG"],
"ASN": ["AAT, AAC"],
"LYS": ["AAA, AAG"],
"VAL": ["GTT, GTC, GTA, GTG"],
"ALA": ["GCT, GCC, GCA, GCG"],
"ASP": ["GAT, GAC"],
"GLU": ["GAA, GAG"], }
codonOneDictionary = {"F": ["TTT, TTC"],
"L": ["CTT, CTC, CTA, CTG, TTA, TTG"],
"S": ["TCT, TCC, TCA, TCG, AGT, AGC"],
"Y": ["TAT, TAC"],
"STOP": ["TAA, TAG, TGA"],
"C": ["TGT, TGC"],
"W": ["TGG"],
"P": ["CCT, CCC, CCA, CCG"],
"H": ["CAT, CAC"],
"G": ["GGT, GGC, GGA, GGG"],
"R": ["CGT, CGC, CGA, CGG, AGA, AGG"],
"I": ["ATT, ATC, ATA"],
"M": ["ATG"],
"T": ["ACT, ACC, ACA, ACG"],
"N": ["AAT, AAC"],
"K": ["AAA, AAG"],
"V": ["GTT, GTC, GTA, GTG"],
"A": ["GCT, GCC, GCA, GCG"],
"D": ["GAT, GAC"],
"E": ["GAA, GAG"], }
#creates the list of lists by looking up the amino acids as keys in the table and appending its mapped list of
#codons to the list aminoAcidList
if threeOrOneLetter == 1:
aminoAcid = aminoAcid.upper()
for oneLetterChar in aminoAcid:
aminoAcidList.append(codonOneDictionary[oneLetterChar])
print(aminoAcidList)
elif threeOrOneLetter == 3:
counter = 0
aminoAcid = aminoAcid.upper()
while counter < length:
threeLetterAminoAcid = aminoAcid[counter:counter + 3]
aminoAcidList.append((codonThreeDictionary[threeLetterAminoAcid]))
counter += 3
print(aminoAcidList)
else:
print(
"Please enter in either 1 or 3 if the amino acid sequence you entered used the 3 or 1 letter abbreviation")
def checkIfSubStringInmRNA(mRNASequence, aminoAcidList):
#itertool function creates every possible permutation from a list of lists i.e [1,2,3],[1,2] would return
#[1,1],[1,2],[2,1],[2,2],[3,1],[3,2],
possibleAminoAcidStrings = list(itertools.product(*aminoAcidList))
numSubStrings = len(possibleAminoAcidStrings)
for i in range(numSubStrings):
substring = "".join(possibleAminoAcidStrings[i])
substring.replace(" ", "")
if substring in mRNASequence:
return True, substring
else:
return False, "none"
def findAminoAcidinmRNA():
mRNASequence = str(input("Please enter a mRNA Sequence")).upper()
aminoAcid = str(input("Please enter an amino acid sequence: "))
threeOrOneLetter = int(input("Did you enter the above amino acid sequence using the 1 or 3 letter abbreviation"
" (type in either 1 or 3): "))
aminoAcidList = []
isAminoAcidInmRNA = False
length = len(aminoAcid)
codonThreeDictionary = {"PHE": ["UUU", "UUC"],
"LEU": ["CUU", "CUC", "CUA", "CUG", "UUA", "UUG"],
"SER": ["UCU", "UCC", "UCA", "UCG", "AGU", "AGC"],
"TYR": ["UAU", "UAC"],
"STOP": ["UAA", "UAG", "UGA"],
"CYS": ["UGU", "UGC"],
"TRP": ["UGG"],
"PRO": ["CCU", "CCC", "CCA", "CCG"],
"HIS": ["CAU", "CAC"],
"GLY": ["GGU", "GGC", "GGA", "GGG"],
"ARG": ["CGU", "CGC", "CGA", "CGG", "AGA", "AGG"],
"ILE": ["AUU", "AUC", "AUA"],
"MET": ["AUG"],
"THR": ["ACU", "ACC", "ACA", "ACG"],
"ASN": ["AAU", "AAC"],
"LYS": ["AAA", "AAG"],
"VAL": ["GUU", "GUC", "GUA", "GUG"],
"ALA": ["GCU", "GCC", "GCA", "GCG"],
"ASP": ["GAU", "GAC"],
"GLU": ["GAA", "GAG"]}
codonOneDictionary = {"F": ["UUU", "UUC"],
"L": ["CUU", "CUC", "CUA", "CUG", "UUA", "UUG"],
"S": ["UCU", "UCC", "UCA", "UCG", "AGU", "AGC"],
"Y": ["UAU", "UAC"],
"STOP": ["UAA", "UAG", "UGA"],
"C": ["UGU", "UGC"],
"W": ["UGG"],
"P": ["CCU", "CCC", "CCA", "CCG"],
"H": ["CAU", "CAC"],
"G": ["GGU", "GGC", "GGA", "GGG"],
"R": ["CGU", "CGC", "CGA", "CGG", "AGA", "AGG"],
"I": ["AUU", "AUC", "AUA"],
"M": ["AUG"],
"T": ["ACU", "ACC", "ACA", "ACG"],
"N": ["AAU", "AAC"],
"K": ["AAA", "AAG"],
"V": ["GUU", "GUC", "GUA", "GUG"],
"A": ["GCU", "GCC", "GCA", "GCG"],
"D": ["GAU", "GAC"],
"E": ["GAA", "GAG"]}
if threeOrOneLetter == 1:
aminoAcid = aminoAcid.upper()
for oneLetterChar in aminoAcid:
aminoAcidList.append(codonOneDictionary[oneLetterChar])
trueOrFalse, substring = checkIfSubStringInmRNA(mRNASequence, aminoAcidList)
if trueOrFalse == True:
print("The amino acid sequence", substring, "was found in the mRNA")
if trueOrFalse == False:
print("no amino acid sequence was found in the mRNA")
elif threeOrOneLetter == 3:
counter = 0
aminoAcid = aminoAcid.upper()
while counter < length:
threeLetterAminoAcid = aminoAcid[counter:counter + 3]
aminoAcidList.append((codonThreeDictionary[threeLetterAminoAcid]))
counter += 3
trueOrFalse, substring = checkIfSubStringInmRNA(mRNASequence, aminoAcidList)
if trueOrFalse == True:
print("The amino acid sequence", substring, "was found in the mRNA")
if trueOrFalse == False:
print("no amino acid sequence was found in the mRNA")
else:
print(
"Please enter in either 1 or 3 if the amino acid sequence you entered used the 3 or 1 letter abbreviation")
|
6305d8b2f7033d5b7895f02cb0f9ed8b5edafe9e | andrewbom/Automation-Car-Sharing-System | /agentpi/database_utils.py | 2,955 | 3.90625 | 4 | import sqlite3
from sqlite3 import Error
class Database_utils:
def __init__(self, connection=None):
self.database_name = 'agentpi_db'
self.con = self.sql_connection()
self.sql_initialize()
def sql_initialize(self):
self.sql_table()
self.sql_insert_data()
def sql_connection(self):
try:
con = sqlite3.connect(self.database_name)
return con
except Error:
print(Error)
def sql_table(self):
cursorObj = self.con.cursor()
cursorObj.execute("""
DROP TABLE IF EXISTS car_details
""")
# Create a car details' TABLE in the local database
cursorObj.execute("""
CREATE TABLE IF NOT EXISTS car_details(
id integer PRIMARY KEY,
car_id real,
make_name text,
model_name text,
seating_capacity real,
colour text,
car_type text,
registration_no real,
lat real ,lng real)
""")
# Create a user details' TABLE in the local database
cursorObj.execute("""
CREATE TABLE IF NOT EXISTS user_details(
id integer PRIMARY KEY,
username text,
password text,
customer_id integer,
face_id integer)
""")
self.con.commit()
def sql_insert_data(self):
cursorObj = self.con.cursor()
# Set 1 Car information that connected to 1 agent pi in the local database
cursorObj.execute("INSERT INTO car_details(car_id , make_name ,model_name ,seating_capacity, colour, car_type ,registration_no ,lat ,lng ) VALUES (1 ,'Sedan' ,'Toyota' ,4 ,'red' ,'suv' ,32 ,-9 ,-9 )")
self.con.commit()
def insert_account(self, email, password, customer_id, face_id):
cursorObj = self.con.cursor()
cursorObj.execute("INSERT INTO user_details(username, password, customer_id, face_id) VALUES (?, ?, ?, ?)", (email, password, customer_id, face_id))
self.con.commit()
def update_car_location(self, lat, lng):
cursorObj = self.con.cursor()
cursorObj.execute('UPDATE car_details SET lat = {} and lng = {} where id = 1'.format(lat, lng))
self.con.commit()
def get_car_data(self):
cursorObj = self.con.cursor()
cursorObj.execute('SELECT * FROM car_details')
return cursorObj.fetchone()
def get_face_data(self, face_id):
cursorObj = self.con.cursor()
cursorObj.execute('SELECT * FROM user_details WHERE face_id = {}'.format(face_id))
return cursorObj.fetchone()
def get_user_data(self):
cursorObj = self.con.cursor()
cursorObj.execute('SELECT * FROM user_details')
return cursorObj.fetchone()
|
462ab3ed06b932739727251a1660d1658d71e63d | thomasrmulhern/event_generator | /op_data_gen.py | 11,270 | 3.640625 | 4 | import pandas as pd
import numpy as np
from random import choice
import datetime
import string
def create_file(num_rows):
#TODO: Write code to dump straight to a csv rather than creating a pandas dataframe
'''
Description: Create a pandas df that will hold all the data and ultimately
output to json. Should have a column for every field we want in our final
json file.
Inputs: None
Return: Dataframe object
Example:
>>>create_file()
Empty DataFrame
Columns: [mongoID, timestamp, type, targetUserId, targetUserName,
creatorUserId, creatorUserName,objectId]
Index: []
'''
columns = ['mongoID','timestamp','type','targetUserId','targetUserName',
'targetType', 'creatorUserId','creatorUserName','creatorType','objectId']
df = pd.DataFrame(columns=columns, index=np.arange(0, num_rows))
return df
def choose_event(event_df):
# TODO: Add logic so that certain related events happen in order e.g. message sent before message opened,
# messages sent to one clinician opened by same clinician, etc.
'''
Description: Choose randomly from a list of possible events
Inputs: Dataframe object
return: string
Examples:
>>> choose_event()
"Goal_created"
>>> choose_event()
"Goal_rejected"
>>> choose_event()
"Survey_answered"
'''
chosen_event = choice(event_df['event'])
return chosen_event
def choose_creator(event):
#TODO: Add logic:
# certain events happen need to in a certain order and have the right creator e.g. dont let someone open a message
# before they've been sent one, don't let someone answer a survey before its been assigned to them, etc.
'''
Description: Choose a creator for the previously chosen event based on the
type of event and other logic
Inputs: string
Return: string
Examples:
>>> choose_creator("Goal_created")
"Clinician"
>>> choose_creator("Goal_rejected")
"Clinician"
>>> choose_creator("Survey_answered")
"Patient"
'''
# Enumerate the values of the events column. If value equals predetermined event, use the index to look at the
# clinician and patient columns. If either is a match, append it to the list to draw from later.
possible_user_types = []
for index, value in enumerate(event_df['event']):
if value == event:
if event_df.iloc[index]['clinician'] == 1:
possible_user_types.append("clinician")
if event_df.iloc[index]['patient'] == 1:
possible_user_types.append("patient")
# Choose a value from the possible user types
user_type = choice(possible_user_types)
# Enumerate the values of the userType column. Compare the chosen user type
# to the values, and if they are equal,
# use the index to append potential creators to a list
possible_users = []
for index, value in enumerate(user_df['userType']):
if value.lower() == user_type.lower():
possible_users.append(user_df.iloc[index]['user'])
# Choose a creator
creator = choice(possible_users)
return creator
def choose_target(event, creator):
#TODO: Add logic:
#patients only interact with their clinicians and vice versa
#clinicians can only create patients
'''
Description: Choose an event target based on a specific type of event and a
specific creator
Inputs: string
return: string
Examples:
>>> choose_target('User_created', 'Clinician_4')
'Clinician_4'
>>> choose_target('Message_sent', 'Clinician_1')
'Patient_17'
>>> choose_target('Goal_rejected', 'Clinician_3')
'Clinician_1'
'''
# If the userType of the row at the index where the
if (user_df.iloc[user_df[user_df['user'] == creator].index]['userType'] == \
"Clinician").item():
creator_row = cc_df[cc_df['events'] == event]
if creator_row['creator_clinician'].item() == 1:
pat = creator_row['target_patient'].item()
clin = creator_row['target_clinician'].item()
if pat == 1 and clin == 1:
choice_type = choice(['Patient', "Clinician"])
a = choice(user_df.iloc[user_df[user_df['userType'] == \
choice_type].index]['user'].values)
return a
elif pat == 1 and clin == 0:
b = choice(user_df.iloc[user_df[user_df['userType'] == \
'Patient'].index]['user'].values)
return b
else:
return creator
else:
print("HOUSTON WE HAVE A CLINICIAN PROBLEM")
elif (user_df.iloc[user_df[user_df['user'] == creator].index]['userType'] ==\
"Patient").item():
creator_row = cp_df[cp_df['events'] == event]
if creator_row['creator_patient'].item() == 1:
pat = creator_row['target_patient'].item()
clin = creator_row['target_clinician'].item()
if pat == 1 and clin == 1:
choice_type = choice(['Patient', "Clinician"])
d = choice(user_df.iloc[user_df[user_df['userType'] == \
choice_type].index]['user'].values)
return d
elif clin == 1 and pat == 0:
f = choice(user_df.iloc[user_df[user_df['userType'] == \
'Clinician'].index]['user'].values)
return f
else:
return creator
# else:
# print("HOUSTON WE HAVE A PATIENT PROBLEM")
def get_userIDs(creator, target):
'''
Description: Get the creator and target user names for the chosen creator
and target.
Inputs: string
Return: string, string
Examples:
>>> get_userIDs(clinician_2, clinician_2)
9v9lrwx5lclc44okov5d, 9v9lrwx5lclc44okov5d
>>> get_userIDs(clinician_2, Patient_5)
9v9lrwx5lclc44okov5d, dt0kzk9ffhjjmtcl9lvh
>>> get_userIDs(Patient_5, clinician_2)
dt0kzk9ffhjjmtcl9lvh, 9v9lrwx5lclc44okov5d
'''
creatorID = user_df[user_df['user'] == creator]['userId'].item()
targetID = user_df[user_df['user'] == target]['userId'].item()
return creatorID, targetID
def get_types(creator, target):
'''
Description: Get the creator and target types.
Inputs: string, string
Return: string, string
Examples:
>>> get_types(clinician_2, clinician_2)
Clinician, Clinician
>>> get_types(clinician_2, Patient_5)
Clinician, Patient
>>> get_types(Patient_5, clinician_2)
Patient, Clinician
'''
creator_type = user_df.iloc[user_df[user_df['user'] == creator].index]\
['userType'].item()
target_type = user_df.iloc[user_df[user_df['user'] == target].index]\
['userType'].item()
return creator_type, target_type
def get_objectId(event):
'''
Description: Get the object ID for the event
Inputs: string
Return: string
Examples:
>>> get_objectId('Goal_rejected')
q6aqbyr5e176wdz657o4
>>> get_objectId('Message_opened')
boevapphzp8vblskmwbd
>>> get_objectId('User_profile_change')
d07pkjihm273doctvr5b
'''
#
return event_df.iloc[event_df[event_df['event']== event].index]\
['objectId'].item()
def create_timestamp(startDate):
# TODO: add logic:
# events happen within realistic times
'''
Description: Generates a timestamp by converting epoch to timestamp after
adding a random number between 10 and 90 equating to between 10 and 90
minutes
Inputs: epoch start timer
Return: timestamp object
Examples:
>>> create_timestamp(start,l)
"2018-11-13T14:21:02.22000"
>>> create_timestamp(start,l)
"2018-11-13T14:43:02.22000"
>>> create_timestamp(start,l)
"2018-11-13T15:51:02.22000"
'''
delta = choice(np.arange(300, 15000))
epoch = startDate + delta
dt = datetime.datetime.fromtimestamp(epoch)
new_dt = "".join('{0}-{1}-{2} {3}:{4}:{5}.{6}'.format(str(dt.year),
str(dt.month), str(dt.day), str(dt.hour), str(dt.minute),str(dt.second),
str(dt.microsecond)))
#print (f"new dt: {new_dt}, delta: {delta/3600}")
return new_dt, epoch
def create_mongoid():
'''
Description: Generate random string to represent mongoid
Inputs: None
Return: string
Examples:
>>> create_mongoid()
5beaddce8f76c34362863d1b
>>> create_mongoid()
P9vE1ZqsoDZJAGeHP95ESVL9
'''
mongoid = ''.join([choice(string.ascii_letters + string.digits) for n in \
range(24)])
return mongoid
def output(df):
'''
Description: Turns the pandas data frame we've been working on into a json
file so we can import it other databases, and data viz analytics tools for
testing
Inputs: Pandas data frame with the data we've iterated to collect
Return: Json file
Examples:
>>> output(df)
>>>What file type? (csv or json): <<csv>>
>>>Output path: <</Users/thomasmulhern/Desktop/data.csv>>
Process finished with exit code 0
'''
ext = input('What file type? (csv or json): ')
#path = input('Path for json file: ')
path = input('Output path: ')
if ext == 'csv':
return df.to_csv(path)
if ext == 'json':
return df.to_json(path)
if __name__ == "__main__":
# import data into data frames
user_df = pd.read_csv('/Users/thomasmulhern/new_desk/post/itether/data_generator/event_generator/data/user_data.csv')
event_df = pd.read_csv('/Users/thomasmulhern/new_desk/post/itether/data_generator/event_generator/data/event_data.csv')
cp_df = pd.read_csv('/Users/thomasmulhern/new_desk/post/itether/data_generator/event_generator/data/cp.csv')
cc_df = pd.read_csv('/Users/thomasmulhern/new_desk/post/itether/data_generator/event_generator/data/cc.csv')
# get user input for number of rows to create
num_rows = int(input('How many rows of data do you want?: '))
df = create_file(num_rows)
start_date = 1452233440.404116 # 2016, 1, 7, 23, 10, 40, 404116 # There is
# no special significance to this date
# Create the data for a single line, add it to the dataframe, and repeat for
# the length of the dataframe
for index in range(num_rows):
event = choose_event(event_df)
creator = choose_creator(event)
target = choose_target(event, creator)
creatorID, targetID = get_userIDs(creator, target)
creatorType, targetType = get_types(creator, target)
objectid = get_objectId(event)
timestamp, seconds = create_timestamp(start_date)
start_date = seconds
mongoid = create_mongoid()
# Add rows of data to the data frame
df.iloc[index] = {'type':event, 'creatorUserName':creator,
'targetUserName':target, 'creatorUserId':creatorID,
'targetUserId':targetID, 'objectId':objectid, 'timestamp':timestamp,
'mongoID':mongoid,'creatorType':creatorType, 'targetType':targetType}
#print(df.iloc[0])
output(df)
|
b9da92ef59f3a2568f255889f9ad078fc7adc44e | coderliuhao/DataScienceBeginner | /python_advanced/some_builtin_module/thread_priority_queue.py | 2,068 | 3.796875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/9/3 下午5:11
# @Author : liu hao
# @File : thread_priority_queue.py
"""python的queue模块提供同步的线程安全队列类,包括FIFO(先入先出)队列Queue
LIFO(后入先出)队列LifoQueue,优先级队列priorityQueue"""
"""useful methods in queue method
1 queue.qsize() return length of queue
2 queue.empty() whether a queue is empty
3 queue.full() whether a queue is full
4 queue.full return maxsize of queue
5 queue.get([block[,timeout]]]) acquire queue and timeout value
6 queue.get_nowait() equal to queue.get(False)
7 queue.put(item) write item into queue
8 queue.put_nowait(item) equal to queue.put(item,False)
9 queue.task_done() when a tasked finished,send tasked-finished queuea singnal
10 queue.join() execute another task once current queue is empty """
import queue
import threading
import time
exit_flag=0
class mythread(threading.Thread):
def __init__(self,thread_id,name,q):
threading.Thread.__init__(self)
self.thread_id=thread_id
self.name=name
self.q=q
def run(self):
print("start thread :"+self.name)
process_data(self.name,self.q)
print("exit thread"+self.name)
def process_data(thread_name,q):
while not exit_flag:
queue_lock.acquire()
if not active_queue.empty():
data=q.get()
queue_lock.release()
print("%s processing %s" %(thread_name,data))
else:
queue_lock.release()
time.sleep(1)
thread_list=["thread1","thread2","thread3"]
name_list=["one","two","three","four","five"]
queue_lock=threading.Lock()
active_queue=queue.Queue(10)
threads=[]
thread_id=1
for thread_name in thread_list:
thread=mythread(thread_id,thread_name,active_queue)
thread.start()
threads.append(thread)
thread_id+=1
queue_lock.acquire()
for name in name_list:
active_queue.put(name)
queue_lock.release()
while not active_queue.empty():
pass
exit_flag=1
for t in threads:
t.join()
print("all thhread exited")
|
678a1fdeea549523ac4f965bdd47bf67352fa867 | dspruell/scripts | /utils/jjdecode/jjdecode-file.py | 1,389 | 3.75 | 4 | #!/usr/bin/env python3
#
# Decode jjencoded file using jjdecode module.
#
# <https://github.com/crackinglandia/python-jjdecoder>
#
# Copyright (c) 2019 Darren Spruell <phatbuckett@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from argparse import ArgumentParser, FileType
from jjdecode import JJDecoder
def main():
descr = "Decode jjencoded file using jjdecode module."
parser = ArgumentParser(descr)
parser.add_argument(
"infile", type=FileType("rb"), help="input file to decode"
)
args = parser.parse_args()
jj = JJDecoder(args.infile.read())
args.infile.close()
print(jj.decode())
if "__name__" == "__main__":
try:
main()
except KeyboardInterrupt:
pass
|
f9522ba0b82fc6032c66db240cab133cb8192a02 | Kim-house/Lesson-1 | /encapsulation.py | 767 | 4.0625 | 4 | # class Computer:
# def __init__(self):
# self.__maxprice = 900
# def sell(self):
# print("Selling Price: {}".format(self.__maxprice))
# def setMaxPrice(self, price):
# self.__maxprice = price
# c = Computer()
# c.sell()
# # change the price
# c.__maxprice = 1000
# c.sell()
# # using setter function
# c.setMaxPrice(1000)
# c.sell()
class Person:
def __init__(self):
self.__name = "john"
self.__age = 20
def write(self):
print("my name is {}, my age is {}".format(self.__name, self.__age))
def new_name(self, name, age):
self.__name = name
self.__age = age
p = Person()
p.write()
# print(p.__name)
p.__name="ken"
p.__age=18
p.write()
p.new_name("jamo", 31)
p.write() |
0af3c908c726ef19b620caf23c2acd770d44b5a5 | Kim-house/Lesson-1 | /lesson2.py | 187 | 3.609375 | 4 | x=4
print ((x<6) and (x>2))
print ((x<6) & (x>2))
print (x>6) or (x<2)
print ((x>6) | (x<2))
a = [1, 2, 3]
b = [1,2,3]
print (a)
print (b)
print (a == b)
print (1 in a)
print (4 not in b) |
5024d194462c7b6a0fc33aebaf49bca19c9642e4 | upekshaa/puzzle_solver | /puzzle_tools.py | 5,640 | 3.765625 | 4 | """
Some functions for working with puzzles
"""
from puzzle import Puzzle
from collections import deque
# set higher recursion limit
# which is needed in PuzzleNode.__str__
# you may uncomment the next lines on a unix system such as CDF
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1))
import sys
sys.setrecursionlimit(10**6)
def depth_first_solve(puzzle):
"""
Return a path from PuzzleNode(puzzle) to a PuzzleNode containing
a solution, with each child containing an extension of the puzzle
in its parent. Return None if this is not possible.
@param Puzzle puzzle: Puzzle
@rtype: PuzzleNode| None
>>> from word_ladder_puzzle import WordLadderPuzzle
>>> pn2 = WordLadderPuzzle("on", "no", {"on", "oo", "no"})
>>> sol = depth_first_solve(pn2)
>>> print(sol)
on -> no
<BLANKLINE>
oo -> no
<BLANKLINE>
no -> no
<BLANKLINE>
<BLANKLINE>
"""
seen = set()
# helper function
def recs(puz, set_):
"""
Return a valid solution in the form of PuzzleNode from given puz and
make sure to ignore any extensions that are already in set_
@param Puzzle puz : Puzzle to search
@param Set set_: set to track
@rtype: PuzzleNode
"""
if not puz.extensions():
if puz.is_solved():
return PuzzleNode(puz, [])
else:
return None
else:
for move in puz.extensions():
if str(move) not in seen:
set_.add(str(move))
r = recs(move, set_)
if not r:
continue
else:
curr = PuzzleNode(puz, [r], None)
r.parent = curr
return curr
return recs(puzzle, seen)
def breadth_first_solve(puzzle):
"""
Return a path from PuzzleNode(puzzle) to a PuzzleNode containing
a solution, with each child PuzzleNode containing an extension
of the puzzle in its parent. Return None if this is not possible.
@type puzzle: Puzzle
@rtype: PuzzleNode
>>> from word_ladder_puzzle import WordLadderPuzzle
>>> pn2 = WordLadderPuzzle("on", "no", {"on", "oo", "no"})
>>> sol = breadth_first_solve(pn2)
>>> print(sol)
on -> no
<BLANKLINE>
oo -> no
<BLANKLINE>
no -> no
<BLANKLINE>
<BLANKLINE>
"""
q = deque()
q.append(PuzzleNode(puzzle))
seen = set()
# if q is not empty
while q:
# pop first node entered
lnk = q.popleft()
# check if node is solution
if lnk.puzzle.is_solved():
# return lnk
if not lnk.parent:
return lnk
else:
return invert(lnk)
# popped value isn't solution
else:
# if node not in seen and has extensions
if lnk.puzzle.extensions() != [] and not puzzle.fail_fast():
for move in lnk.puzzle.extensions():
if str(move) not in seen:
seen.add(str(move))
q.append(PuzzleNode(move, [], lnk))
# if node is in seen or doesnt have extensions
else:
continue
return None
# helper method to breadth first search
def invert(lk):
"""
Return a valid path, made up of a list of PuzzleNode children, after linking
the parent references from lk
@param PuzzleNode lk: PuzzleNode that has a parent reference
@return: PuzzleNode
"""
q = deque()
q.append(lk)
while q:
val = q.pop()
if val.parent:
pn = val.parent
pn.children.append(val)
q.append(pn)
else:
return val
# Class PuzzleNode helps build trees of PuzzleNodes that have
# an arbitrary number of children, and a parent.
class PuzzleNode:
"""
A Puzzle configuration that refers to other configurations that it
can be extended to.
"""
def __init__(self, puzzle=None, children=None, parent=None):
"""
Create a new puzzle node self with configuration puzzle.
@type self: PuzzleNode
@type puzzle: Puzzle | None
@type children: list[PuzzleNode]
@type parent: PuzzleNode | None
@rtype: None
"""
self.puzzle, self.parent = puzzle, parent
if children is None:
self.children = []
else:
self.children = children[:]
def __eq__(self, other):
"""
Return whether Puzzle self is equivalent to other
@type self: PuzzleNode
@type other: PuzzleNode | Any
@rtype: bool
>>> from word_ladder_puzzle import WordLadderPuzzle
>>> pn1 = PuzzleNode(WordLadderPuzzle("on", "no", {"on", "no", "oo"}))
>>> pn2 = PuzzleNode(WordLadderPuzzle("on", "no", {"on", "oo", "no"}))
>>> pn3 = PuzzleNode(WordLadderPuzzle("no", "on", {"on", "no", "oo"}))
>>> pn1.__eq__(pn2)
True
>>> pn1.__eq__(pn3)
False
"""
return (type(self) == type(other) and
self.puzzle == other.puzzle and
all([x in self.children for x in other.children]) and
all([x in other.children for x in self.children]))
def __str__(self):
"""
Return a human-readable string representing PuzzleNode self.
# doctest not feasible.
"""
return "{}\n\n{}".format(self.puzzle,
"\n".join([str(x) for x in self.children])) |
b070ec7bba67bf6ade44913ec99b59b914a59cdb | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithms on strings/week1/suffix_tree/suffix_tree.py | 1,222 | 3.71875 | 4 | # python3
import sys
from collections import deque
from collections import defaultdict
def build_trie(text):
trie = defaultdict(dict)
i = 0
patterns = [text[i:] for i, _ in enumerate(text)]
for pattern in patterns:
v = 0
for symbol in pattern:
if symbol in trie[v]:
v = trie[v][symbol]
else:
i += 1
trie[v][symbol] = i
v = i
return trie
def Suffix_tree(trie):
result = []
def dfs(index, text_string):
if index not in trie and text_string:
result.append(text_string) # If end of the tree, then append
return
current_branch = trie[index]
if len(current_branch) > 1 and text_string:
result.append(text_string) # If branching out, append till last branch and reset text string
text_string = ""
for symbol, ind in current_branch.items():
dfs(ind, text_string + symbol)
dfs(0, "")
return result
def build_suffix_tree(text):
trie = build_trie(text)
return Suffix_tree(trie)
if __name__ == '__main__':
text = input()
result = build_suffix_tree(text)
print("\n".join(result)) |
7d26e6913a4b0024fa1082e5f3ea7c9ff0cbc50b | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithms on strings/week2/suffix_array/suffix_array.py | 572 | 4.21875 | 4 | # python3
import sys
from collections import defaultdict
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
suffix = []
for i in range(len(text)):
suffix.append((text[i:], i))
suffix.sort()
for arr, indx in suffix:
print(indx, end=' ')
if __name__ == '__main__':
text = sys.stdin.readline().strip()
build_suffix_array(text)
|
847ce21722b4237ffc0ca03f5bb6fb7f5b319f47 | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithm toolbox/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py | 651 | 4 | 4 | # Uses python3
import sys
import unittest
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
def get_fibonacci_last_digit_fast(n):
if (n <= 1):
return n
f = [0,1]
for i in range(2,n+1):
f.append((f[i-2] + f[i-1]) % 10)
return f[-1]
def fibonacci_sum_fast(n):
n = (n + 2) % 60
c = get_fibonacci_last_digit_fast(n)
if c == 0 :
c = 9
return c
return c - 1
n = int(input())
print(fibonacci_sum_fast(n))
|
17daf1b70f5135d5117c97e024322d3689eefc6e | Azab007/Data-Structures-and-Algorithms-Specialization | /algorithm toolbox/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py | 630 | 3.828125 | 4 | # Uses python3
def get_fibonacci_last_digit_fast(n):
if (n <= 1):
return n
f = [0,1]
for i in range(2,n+1):
f.append((f[i-2] + f[i-1]) % 10)
return f[-1]
def fibonacci_sum_fast(n):
n = (n + 2) % 60
c = get_fibonacci_last_digit_fast(n)
if c == 0 :
c = 9
return c
return c - 1
def fibonacci_partial_sum_fast(from_, to):
fir = fibonacci_sum_fast(to)
sec = fibonacci_sum_fast(from_ - 1)
if fir >= sec:
return fir - sec
else:
return (10 + fir) - sec
from_, to = map(int, input().split())
print(fibonacci_partial_sum_fast(from_, to)) |
6ffc5c38b51f1665cb27f987bebc51005df8a9af | saraben6/tictascii | /tictascii/ticlib/players.py | 1,540 | 3.84375 | 4 |
import random
from .exceptions import MarkerOutOfRange, MarkerExists
class Player(object):
def __init__(self, marker):
self.marker = marker
self.games_won = 0
def increment_wins(self):
self.games_won += 1
def get_wins(self):
return self.games_won
def make_a_move(self, board):
raise NotImplementedError()
class HumanPlayer(Player):
def make_a_move(self, board):
while True:
try:
x = int(raw_input("X: "))
y = int(raw_input("Y: "))
valid_coordinates = True
except ValueError:
print "Invalid input for coordinates. Try again."
valid_coordinates = False
if valid_coordinates:
try:
board.set_marker(self.marker, x, y)
except MarkerOutOfRange:
print "The provided marker isn't within the board range."
except MarkerExists:
print "A marker has already been placed at this location."
else:
return
class ComputerPlayer(Player):
def make_a_move(self, board):
while True:
x = random.randint(0, board.DIMENSIONS - 1)
y = random.randint(0, board.DIMENSIONS - 1)
try:
board.set_marker(self.marker, x, y)
except MarkerExists:
pass # just retry if there's already a marker here
else:
return
|
8b94f093e253caaccfbb16840192d95657bf69e4 | ikailash19/guvi | /beginpgm52.py | 359 | 3.859375 | 4 | numer1=int(input())
if numer1==1:
print("One")
elif numer1==2:
print("Two")
elif numer1==3:
print("Three")
elif numer1==4:
print("Four")
elif numer1==5:
print("Five")
elif numer1==6:
print("Six")
elif numer1==7:
print("Seven")
elif numer1==8:
print("Eight")
elif numer1==9:
print("Nine")
elif numer1==0:
print("Zero")
elif numer1==10:
print("Ten")
|
96d7879af212c0651d753f442bccc52c8886c2d4 | ikailash19/guvi | /beginpgm54.py | 64 | 3.859375 | 4 | numer1=int(input())
print (numer1 if numer1%2==0 else numer1-1)
|
81f431a16062a3eae5be9788e8f1b52d08085b53 | ikailash19/guvi | /playerpgm43.py | 68 | 3.703125 | 4 | arr,ar=map(str,input().split())
print("yes" if ar in arr else "no")
|
63c0824145f1f4b350ae060f28a90e7e4da1893a | ikailash19/guvi | /beginpgm71.py | 98 | 3.828125 | 4 | arr=list(input())
ar=list(map(str,arr))
ar.reverse()
if arr==ar:
print("yes")
else:
print("no")
|
cbc8b8b708a11ddcc9711b2d33a4d8f838a436a8 | spandangithub2016/Python | /trip.py | 617 | 3.8125 | 4 | def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city=="Charlotte":
return 183
elif city=="Tampa":
return 220
elif city=="Pittsburgh":
return 222
elif city=="Los Angeles":
return 500
def rental_car_cost(days):
cost=40*days;
if(days<=2):
return cost;
elif(days>=7):
return cost-50;
elif(days>=3):
return cost-20;
def trip_cost(city,days,spending_money):
return rental_car_cost(days)+hotel_cost(days)+plane_ride_cost(city)+spending_money;
print (trip_cost("Los Angeles",5,600))
|
27b24ddcce76385c3616b51897e55d01acdadca1 | spandangithub2016/Python | /inheritance.py | 479 | 3.5625 | 4 | class parent:
def func(self,a,b):
self.a=a
self.b=b
def view(self):
print "this is super class"
print "a=",self.a," and b=",self.b
class child (parent):
def view(self):
print "this is child class"
print "a=",self.a," and b=",self.b
def only(self):
print "this is for only child class"
s=parent()
s.func(10,20)
s.view()
c=child()
c.func(100,200)
c.view()
c.only()
print"Thank you"
|
2acae9e81e1b4e4d9eb804b9972febbfee484cf3 | nirajbawa/python-programing-code | /13_pytthon.py | 965 | 3.8125 | 4 | # practice set
# 2.
# while(True):
# name = raw_input("inter your name")
# mark = input("enter your marks")
# phone = input("enter your number")
# try:
# mark = int(mark)
# phone = int(phone)
# template = "the name of th student is {}, his marks are {} and phone number is {} "
# output = template.format(name, mark, phone)
# print(output)
# except Exception as f:
# print(f)
# 2.
# l = [str(i*7 )for i in range(1, 11)]
# print(l)
# vertical = "\n".join(l)
# print(vertical)
# 3.
# l = [11,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,56,67,976]
# a = filter(lambda a: a%5==0, l)
# print(list(a))
# 4.
# from functools import reduce
# l = [3,8,4,2,5]
# a = reduce(max, l)
# print(a)
# print(max(7, 34))
# 5.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
app.run(debug=True) |
c4b070167650e5804d5203337a1e26d656ea6978 | nirajbawa/python-programing-code | /4_python.py | 1,270 | 3.953125 | 4 | #pratice set
# 1. make list of 7 fruit using user input
#user input
# f1 = raw_input("Enter fruit Number 1 ")
# f2 = raw_input("Enter fruit Number 2 ")
# f3 = raw_input("Enter fruit Number 3 ")
# f4 = raw_input("Enter fruit Number 4 ")
# f5 = raw_input("Enter fruit Number 5 ")
# f6 = raw_input("Enter fruit Number 6 ")
# f7 = raw_input("Enter fruit Number 7 ")
# #store user input in list
# fruit_list = [f1,f2,f3,f4,f5,f6,f7]
# #print fruit list
# print(fruit_list)
# 2. make list of student marks
# m1 = int(input("Enter Marks for student Number 1 "))
# m2 = int(input("Enter Marks for student Number 2 "))
# m3 = int(input("Enter Marks for student Number 3 "))
# m4 = int(input("Enter Marks for student Number 4 "))
# m5 = int(input("Enter Marks for student Number 5 "))
# m6 = int(input("Enter Marks for student Number 6 "))
# mark_list = [m1,m2,m3,m4,m5,m6]
# mark_list.sort()
# print(mark_list)
#3. tupls
# a = (2,6,6,7,8)
#a[2]= 5 #'tuple' object does not support item assignment
#4. write a program to sum a list with 4 number
# a = [2,4,56,7]
# # print(a[0]+a[1]+a[2]+a[3]) # sum of number
# print(sum(a))
# 4. write a program to count the number to count in the following tuple
a=(7,0,8,0,0,9)
b = a.count(0)
print(b) |
ac886fd8959715ebc061ba29118debb608ddf14c | SSeanin/data-structures-and-algorithms | /structures/tree.py | 4,118 | 3.8125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, data):
self.children.append(Node(data))
class StrictNode:
def __init__(self, data):
self.left_child = None
self.middle_child = None
self.right_child = None
self.data = data
class BSTNode:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
def insert_data(self, data):
if data < self.data and self.left_child:
self.left_child.insert_data(data)
elif data < self.data:
self.left_child = BSTNode(data)
elif data > self.data and self.right_child:
self.right_child.insert_data(data)
else:
self.right_child = BSTNode(data)
def find(self, value):
if self.data == value:
return self
elif not self.left_child and not self.right_child:
return None
elif value < self.data:
return self.left_child.find(value)
else:
return self.right_child.find(value)
def minimum(self):
if not self.left_child:
return self
else:
return self.left_child.minimum()
def bst_traverse_inorder(root: BSTNode, callback):
if root is not None:
bst_traverse_inorder(root.left_child, callback)
callback(root)
bst_traverse_inorder(root.right_child, callback)
def traverse_preorder(root: StrictNode, callback):
if root is not None:
callback(root)
traverse_preorder(root.left_child, callback)
traverse_preorder(root.middle_child, callback)
traverse_preorder(root.right_child, callback)
def traverse_inorder(root: StrictNode, callback):
if root is not None:
traverse_inorder(root.left_child, callback)
callback(root)
traverse_inorder(root.middle_child, callback)
traverse_inorder(root.right_child, callback)
def traverse_postorder(root: StrictNode, callback):
if root is not None:
traverse_postorder(root.left_child, callback)
traverse_postorder(root.middle_child, callback)
traverse_postorder(root.right_child, callback)
callback(root)
def count_leaves(root: StrictNode):
if root is None:
return 0
if root.left_child is None and root.middle_child is None and root.right_child is None:
return 1
else:
return count_leaves(root.left_child) + count_leaves(root.middle_child) + count_leaves(root.right_child)
def node_depth(root: StrictNode, node: StrictNode, level: int = 0):
if root == node:
return level
if root is None:
return -1
left_sub_level = node_depth(root.left_child, node, level + 1)
if left_sub_level != -1:
return left_sub_level
middle_sub_level = node_depth(root.middle_child, node, level + 1)
if middle_sub_level != -1:
return middle_sub_level
right_sub_level = node_depth(root.right_child, node, level + 1)
if right_sub_level != -1:
return right_sub_level
return -1
class Tree:
def __init__(self, root: Node = None):
self.root = root
def traverse_breadth_first(self, callback):
nodes = [self.root]
while nodes:
if nodes[0].children:
nodes.extend(nodes[0].children)
callback(nodes.pop(0))
def traverse_depth_first(self, callback):
nodes = [self.root]
while nodes:
callback(nodes[0])
if nodes[0].children:
nodes[0:0] = nodes[0].children
nodes.pop(0)
class BST:
def __init__(self, *args):
self.root: BSTNode = BSTNode(args[0])
for data in args[1:]:
self.insert_data(data)
def insert_data(self, data):
self.root.insert_data(data)
def traverse(self, callback):
bst_traverse_inorder(self.root, callback)
def find(self, value):
return self.root.find(value)
def minimum(self):
return self.root.minimum()
|
1b6ea806ee13af70efeaa04e2b15456ca396fb9a | guyincognito-io/cryptopals | /set1/challenge8.py | 264 | 3.546875 | 4 | import helper
with open("8.txt", "rb") as f:
for line in f:
ciphertext = line.strip()
if helper.checkForECBEncryption(ciphertext.decode('hex'), 16):
print "Found possible ECB Encrypted ciphertext: "
print ciphertext
|
6b0808ea4b78e02e0d6e792206bee00af8ad8d24 | zingkg/arkham-horror-assistant | /minify_xml.py | 275 | 3.5 | 4 | #!/usr/bin/python
import sys
def main(argv):
file = open(argv[0])
line = file.readline()
while line != '':
if not '<!--' in line:
print(line.strip(), end='')
line = file.readline()
if __name__ == '__main__':
main(sys.argv[1:])
|
8a69b86370d2b9f0961d97e27595e0d56c1a2654 | KhaledAbuNada-AI/Python-Course | /Numbers.py | 523 | 3.828125 | 4 | from math import *
number1 = 5
number2 = -3
my_list = [1, 10, 15, 100]
# Operations
print((number1 + number2) * 2)
print(number1 * number2)
print(number1 - number2)
print(number1 / number2)
print(number1 % number2)
# Numbers math
print(abs(number2))
print(pow(number1, 2))
# Numbers Max, Min
print(max(my_list))
print(min(my_list))
# Numbers
print(round(6.9))
# Math Module
print(floor(6.9))
print(ceil(3.1))
print(sqrt(10))
# Converting and merging texts with numbers
aeg = 20
text = 'My Aeg ' + str(aeg)
print(text)
|
918a92d75f0bbf33e42246adc0d9624e6428a886 | KhaledAbuNada-AI/Python-Course | /Strings.py | 517 | 3.71875 | 4 | text = "\"Data Structuring\" is Very Important\n" \
" for any Programmer who wants to become\n" \
"a \"Professional\" in the field"
#Lower , Upper Strings
lower_text = text.lower()
upper_text = text.upper()
print(upper_text)
print(lower_text.islower())
print(text.isupper())
# Index Strings
index_text = text[16]
print(index_text)
print(text.index("Programmer"))
# Replace Strings
replace_text = text.replace("Data Structuring", "Problem Solving")
print(replace_text)
# len Strings
print(len(text))
|
bb95c7251ca5c6699244ea651deed2d7aaf749e3 | hoobui/mypython | /def.py | 288 | 3.609375 | 4 | # def gen_fib():
#
# s = int(input('please input a num: '))
# fib = [0,1]
# for i in range(s):
# fib.append(fib[-1] + fib[-2])
# print(fib)
#
# gen_fib()
# print('-' * 50)
# gen_fib()
# import sys
# print(sys.argv)
def pstar(n=30):
print('*' * n)
pstar(12)
|
b8b604b9aa550500df7a0057333de126e9c0115f | nuggy875/tensorflow-of-all | /5. linear regression.py | 1,682 | 3.640625 | 4 | # 5. linear regression
# 선형 회귀에 대하여 알아본다.
# X and Y data
import tensorflow as tf
# 학습을 할 data
#x_train = [1, 2, 3]
#y_train = [1, 2, 3]
# 그래프 빌드 #
# placeholder 사용
X = tf.placeholder(tf.float32, shape=[None])
Y = tf.placeholder(tf.float32, shape=[None])
# 계속 업데이트 되는 값은 Variable : trainable variable
# random_normal : 랜덤한 값을 준다. : parameter : shape
W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# Our hypothesis function is XW + b
hypothesis = X * W + b
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# cost minimize - 일단은 지금 넘어감
optimizer = tf.train.GradientDescentOptimizer(learning_rate= 0.01)
train = optimizer.minimize(cost)
# train 노드
# 그래프 빌드 끝 #
# 그래프 실행 #
# launch the graph in a session
sess = tf.Session()
# initializes global variables in the graph - variable 을 사용할때면 무조건 초기화 필수
sess.run(tf.global_variables_initializer())
# Fit the line with new training data
for step in range(2001):
cost_val, W_val, b_val, _ = \ # 값들을 집어 넣을 때
sess.run([cost, W, b, train], # 한번에 돌리고 싶을대
feed_dict={X: [1, 2, 3, 4, 5],
Y: [2.1, 3.1, 4.1, 5.1, 6.1]})
if step % 20 == 0:
print(step, cost_val, W_val, b_val)
# Testing our model - 테스트 하는 부분
print(sess.run(hypothesis, feed_dict={X: [5]}))
print(sess.run(hypothesis, feed_dict={X: [2.5]}))
print(sess.run(hypothesis, feed_dict={X: [1.5, 3.5]})) # 동시에 대답해봐
|
eba2ffaeaf9b38da5f9ae60b785f406070267873 | nuggy875/tensorflow-of-all | /7. gradient descent algorithm.py | 1,147 | 4.125 | 4 | # 7. gradient descent algorithm
# 경사 하강법 이해를 목적으로 한다.
import tensorflow as tf
# 그래프 빌드 #
# 데이터
x_data = [1, 2, 3]
y_data = [1, 2, 3]
# 변하는 값
W = tf.Variable(tf.random_normal([1]), name='weight')
# 데이터를 담는 값 'feed_dict'
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# Our hypothesis for linear model X * W --> simplify the numerical expression
hypothesis = X * W
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Launch the graph in a session
# Minimize : Gradient Descent using derivative: W -= Learning_rate * derivative
# gradient = d ( cost ) / dw
# W = W - rate * d/dw( cost )
learning_rate = 0.1
gradient = tf.reduce_mean((W * X - Y) * X)
descent = W - learning_rate * gradient
update = W.assign(descent)
# assign : 연산 후 새 값을 재 설정하는 operator
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
for step in range(21):
sess.run(update, feed_dict={X: x_data, Y: y_data})
print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W))
|
467bf2b94016e26a7c4e92a5a7fdc2623818a9aa | concpetosfundamentalesprogramacionaa19/practica220419-iancarlosortega | /problema2.py | 521 | 3.828125 | 4 | """
Problema 1 del laboratorio 1
autor @iancarlosortega
"""
#Declaracion de las variables por teclado
x = input("Ingrese la variable x: \n")
y = input("Ingrese la variable y: \n")
z = input("Ingrese la variable z: \n")
#Operacion para encontrar el valor de m
m = (float(x)+(float(y)/float(z)))/(float(x)-(float(y)/float(z)))
#Mostrar en pantalla las variables y el resultado de m
print ("El valor de m, en base a las variables es: \nx = %s \n\ty = %s \n\t\tz= %s \nda como resultado: \n\t\t\tm = %.2f" % (x,y,z,m)) |
a483b1b0862163e0fbd84a837361b52608ca4c5e | adamhowe/Selection | /Revision exercise 2.py | 200 | 4.125 | 4 | #Adam Howe
#Revision exercise 2
#30/09/2014
age = int(input("Please enter your age: "))
if age >= 17:
print("You are old enough to drive")
else:
print("You are too young to drive")
|
21ae49cdd1d8966dab16659f9ccd70ff0f28e459 | shashikdm/Deep-Neural-Network | /DNN.py | 6,851 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 07:19:27 2018
@author: shashi
"""
import numpy as np
import matplotlib.pyplot as plt
#Class for trainer
class DNN:
def __init__(self, layers, neurons, X_train, y_train, learning_rate = 0.01, iterations = 5000, activation_hidden = "relu", activation_output = "sigmoid", show_cost = True, plot_cost = True):
self.layers = layers #No. of layers = output layer + hidden layers
self.X_train = np.array(X_train,ndmin = 2) #Input layer
self.y_train = np.array(y_train,ndmin = 2) #output layer
self.neurons = np.array(neurons) #List containing number of neurons in each layer
self.neurons = np.append(self.X_train.shape[0], self.neurons)#0th layer is input
self.weights = [] #Weights for each layer Remember indices start from 0
self.biases = [] #Biases for each layer
for i in range(0, layers): #Random initialisation with correct dimensions
self.weights.append(np.random.randn(self.neurons[i+1],self.neurons[i])*0.01)
self.biases.append(np.zeros((self.neurons[i+1],1)))
self.activation_hidden = activation_hidden #Activation function for hidden layer
self.activation_output = activation_output #Activation function of output layer
self.learning_rate = learning_rate #The learning rate
self.iterations = iterations#No. of iterations
self.activations = []#stores activations used for backprop
self.linears = []#stores Z values used for backprop
self.costs = []#Stores costs to plot
self.show_cost = show_cost;
self.plot_cost = plot_cost
def train(self):#call this to train the model
for i in range(0, self.iterations):#outer loop for forward and backward props
self.forward_prop(self.X_train)
if i%100 == 0 and (self.show_cost or self.plot_cost):#pring every 100th value
self.costs.append(self.compute_cost(self.activations[self.layers], self.y_train))
if self.show_cost:
print("cost @", i,":", self.costs[-1])
self.backward_prop()
if self.plot_cost:#Plot
plt.plot(np.squeeze(self.costs))
plt.ylabel('cost')
plt.xlabel('iterations (x100)')
plt.title("Learning rate =" + str(self.learning_rate))
plt.show()
def forward_prop(self, X):
A = X
self.activations = []
self.linears = []
self.activations.append(A)
for i in range(0, self.layers):
Z = np.dot(self.weights[i], A) + self.biases[i]
if i < self.layers-1 and self.activation_hidden == "relu":
A = self.relu(Z)
elif i < self.layers-1 and self.activation_hidden == "sigmoid":
A = self.sigmoid(Z)
elif i < self.layers-1 and self.activation_hidden == "softmax":
A = self.softmax(Z)
elif i == self.layers-1 and self.activation_output == "relu":
A = self.relu(Z)
elif i == self.layers-1 and self.activation_output == "sigmoid":
A = self.sigmoid(Z)
elif i == self.layers-1 and self.activation_output == "softmax":
A = self.softmax(Z)
self.linears.append(Z)
self.activations.append(A)
def backward_prop(self):
AL = self.activations[self.layers]
A = self.activations[self.layers-1]
Z = self.linears[self.layers-1]
#starting with derivative of cross entropy cost function for binary classification
if self.activation_output == "sigmoid":
dLdA = -(np.divide(self.y_train,AL)-np.divide(1-self.y_train,1-AL))/self.y_train.shape[1]
dAdZ = self.dsigmoid(Z)
dLdZ = dLdA*dAdZ
dLdW = np.dot((dLdZ),A.T)/self.y_train.shape[1] #A = dZdW
dLdb = np.sum(dLdZ, axis = 1, keepdims = True)/self.y_train.shape[1]
self.weights[self.layers-1] = self.weights[self.layers-1] - self.learning_rate*dLdW
self.biases[self.layers-1] = self.biases[self.layers-1] - self.learning_rate*dLdb
dLdA = np.dot(self.weights[self.layers-1].T,dLdA*dAdZ)
elif self.activation_output == "softmax":
dLdZ = (AL - self.y_train)
dLdW = np.dot(dLdZ,A.T)/self.y_train.shape[1] #A = dZdW
dLdb = np.sum(dLdZ, axis = 1, keepdims = True)/self.y_train.shape[1]
self.weights[self.layers-1] = self.weights[self.layers-1] - self.learning_rate*dLdW
self.biases[self.layers-1] = self.biases[self.layers-1] - self.learning_rate*dLdb
dLdA = np.dot(self.weights[self.layers-1].T,dLdZ)
for i in reversed(range(0, self.layers-1)):
Z = self.linears[i]
A = self.activations[i]
if i < self.layers-1 and self.activation_hidden == "relu":
dAdZ = self.drelu(Z)
elif i < self.layers-1 and self.activation_hidden == "sigmoid":
dAdZ = self.dsigmoid(Z)
elif i < self.layers-1 and self.activation_hidden == "softmax":
dAdZ = self.dsoftmax(Z)
dLdW = np.dot((dLdA*dAdZ),A.T) #A = dZdW
dLdb = np.sum(dLdA*dAdZ, axis = 1, keepdims = True)
self.weights[i] = self.weights[i] - self.learning_rate*dLdW
self.biases[i] = self.biases[i] - self.learning_rate*dLdb
dLdA = np.dot(self.weights[i].T,dLdA*dAdZ)
def relu(self, z):#Helper function relu #tested ok
return np.maximum(0,z)
def drelu(self, z):#Helper function derivative of relu #tested ok
z[z<=0] = 0
z[z>0] = 1
return z
def sigmoid(self, z):#Helper function sigmoid #tested ok
return 1/(1+np.exp(-z))
def dsigmoid(self, z):#Helper function derivative of sigmoid #tested ok
return self.sigmoid(z)*(1-self.sigmoid(z))
def softmax(self, z):#helper function softmax #doubtful
z = z - np.max(z)
return np.exp(z)/np.sum(np.exp(z), axis = 0, keepdims = True)
def dsoftmax(self, z):#helper function forderivative of softmax #doubtful
return self.softmax(z)*(1-self.softmax(z))
def compute_cost(self, AL, y):#Helper function cross entropy cost
#cross entropy loss function for binary classification
return -np.sum(np.dot(y.T,np.log(AL)))/y.shape[1]
def predict(self, X_test):#returns probs and predictions
self.forward_prop(X_test)
probabilities = np.array(self.activations[self.layers],ndmin = 2)
predictions = np.zeros((self.neurons[-1],X_test.shape[1]))
for i in range(0,X_test.shape[1]):
predictions[np.argmax(probabilities[...,i]),i] = 1
return probabilities, predictions
|
25293e5fc75005831882e6dcc66cfb43d04f74bc | jvpersuhn/Pythonzinho | /Aula19/Exercicio1.py | 1,416 | 3.734375 | 4 | # Aula 19 - 04-12-2019
# Lista com for e metodos
# 1 - Com a seguinte lista imprima na tela (unsado a indexação e f-string)
cadastroHBSIS = [ 'nome', ['Alex' ,'Paulo' ,'Pedro' ,'Mateus' ,'Carlos' ,'João' ,'Joaquim'],
'telefone',['4799991','4799992','4799993','4799994','4799995','4799996','4799997'],
'email', ['a@a.com','b@b.com','c@c.com','d@d.com','e@e.com','f@f.com','g@g.com'],
'idade', ['18' ,'25' ,'40' ,'16' ,'15' ,'19' ,'17' ]
]
# for i in range(0,7):
# print(f'Nome: {cadastroHBSIS[1][i]} Telefone: {cadastroHBSIS[3][i]} Email: {cadastroHBSIS[5][i]} Idade: {cadastroHBSIS[7][i]}\n')
# print(f'Nome: {cadastroHBSIS[1][i]} Telefone: {cadastroHBSIS[3][i]} Email: {cadastroHBSIS[5][i]} Idade: {cadastroHBSIS[7][i]}\n')
# nome Alex telefone: 4799991
# idade Carlos é 15 anos
# email de Mateus é d@d.com
# 2 - usando o for, imprima todos nomes um abaixo do outro
# for i in cadastroHBSIS[1]:
# print(i)
# 3 - Usando a indexação faça uma lista com 3 bibliotecas contendo os dados do Mateus, Paulo e João
# contendo como chaves: nome, email, idade, telefone (nesta sequencia)
bibl = []
lista = [1,5,7,3]
for i in range(1,6,2):
dic = {}
for j in lista:
dic[cadastroHBSIS[j - 1]] = cadastroHBSIS[j][i]
bibl.append(dic)
for i in bibl:
print(i)
|
0d280f685edb91eb846721c56525aff826e53bcd | jvpersuhn/Pythonzinho | /Aula4/Arquivo.py | 998 | 3.578125 | 4 | import os
def escrever():
if not os.path.isdir('Dados'):
os.mkdir('Dados')
nome = input('Digite o nome: ')
idade = input('Digite a idade: ')
arquivo = nome + ',' + idade + '\n'
f = open('Dados/Aluno.txt','a')
f.write(arquivo)
f.close()
def ler_tudo():
f = open('Dados/Aluno.txt', 'r')
listaArquivo = []
for x in f:
listaArquivo.append(x)
listaSeparada = []
for x in listaArquivo:
listaSeparada.append(x.split(','))
for x in listaSeparada:
print(f'Nome: {x[0]}')
print(f'Idade: {x[1]}')
f.close()
def mostra_menu():
print('=' * 20)
print('Digite 1 para cadastrar')
print('Digite 2 para ler tudo')
print('Digite 3 para sair')
print('=' * 20)
mostra_menu()
escolha = input('Digite sua escolha: ')
while escolha != '3':
if escolha == '1':
escrever()
else:
ler_tudo()
mostra_menu()
escolha = input('Digite sua escolha: ')
|
e6dbeb843c51beb815314ee4afa57553328a295d | kaushal087/hangman | /isWordGuessed.py | 574 | 3.75 | 4 | ##############################################################
from imports import *
def isWordGuessed(secretWord,lettersGuessed):
for w in secretWord:
if w not in lettersGuessed:
return False
return True
##############################################################
######################### test case ##########################
# secretWord='ppe'
# lettersGuessed=['e','i','k','p','r','s']
# print isWordGuessed(secretWord,lettersGuessed)
##############################################################
|
c85c8d5d4fd42761939cf23b76eedd680b9e8df6 | Naveen1331/DSA_Algorithms | /array.py | 148 | 4.0625 | 4 | arr = [11, 22, 33, 44, 55]
print("Array is :", arr)
res = arr[::-1] # reversing using list slicing
print("Resultant new reversed array:", res) |
cfc5bdca05d896c71b3323bd0dd1e69632d7c418 | taras18taras/Python | /Prometheus/Python/5.3 (prometeus).py | 743 | 3.84375 | 4 | def super_fibonacci(n, m):
# за умовою перші m елементів - одиниці
if n<=m:
return 1
# інакше доведеться рахувати
else:
# ініціалізуємо змінну для суми
sum = 0
# і додаємо m попередніх членів послідовності, для розрахунку кожного з них рекурсивно викликаємо нашу функцію
for i in range(1, m+1):
previous = super_fibonacci(n-i, m)
sum = sum + previous
# повертаємо суму, яка є значенням n-го елементу
return sum
print(super_fibonacci(21,2)) |
8249802cd86228639448f3564468a76d98b7e32c | taras18taras/Python | /Простые числа.py | 583 | 4.03125 | 4 | #Написать функцию is_prime, принимающую 1 аргумент — число от 0 до 1000, и возвращающую True,
# если оно простое, и False - иначе
def is_prime(number):
"""Эту функцию можно сильно оптимизировать. Подумайте, как"""
if number == 1:
return False # 1 - не простое число
for possible_divisor in range(2, number):
if number % possible_divisor == 0:
return False
return True
print(is_prime(10000000001)) |
c11e4094d06bf9532751d48952f1893bee903d12 | vazgenzohranyan/battleship | /utils.py | 3,464 | 3.609375 | 4 | import numpy as np
def find_neighbour(pos, board):
i,j = pos
for n in range(i - 1, i + 2):
for m in range(j - 1, j + 2):
if m in range(10) and n in range(10) and [i, j] != [n, m]:
if board[n][m] == 1:
return False
return True
def find_available_positions(length, vertical, board):
positions = []
if vertical:
for i,raw in enumerate(board):
for j,p in enumerate(raw):
if p == 0:
pos = []
for k in range(length):
if (i+k) in range(10):
if board[i+k][j]==0 and find_neighbour([i+k,j], board):
pos.append([i+k,j])
elif board[i+k][j] == 1 or find_neighbour([i+k,j], board) is False:
pos = None
break
else:
pos = None
break
if pos is not None:
positions.append(pos)
else:
for i,raw in enumerate(board):
for j,p in enumerate(raw):
if p == 0:
pos = []
for k in range(length):
if (j+k) in range(10):
if board[i][j+k]==0 and find_neighbour([i,j+k],board):
pos.append([i,j+k])
elif board[i][j+k] == 1 or find_neighbour([i,j+k],board) is False:
pos = None
break
else:
pos = None
break
if pos is not None:
positions.append(pos)
return positions
def set(length, board):
vertical = np.random.randint(0, 2)
positions = find_available_positions(length, vertical, board)
if len(positions) == 0:
generate_board()
coord = positions[np.random.randint(0, len(positions))]
print(length, coord)
place_ship(coord,board)
def place_ship(coord,board):
for p in coord:
board[p[0]][p[1]] = 1
def generate_board():
board = np.zeros((10, 10))
ships = {
'4': 1,
'3': 2,
'2': 3,
'1': 4
}
for ship in ships:
length = int(ship)
for _ in range(ships[ship]):
set(length, board)
return board
|
0f43f2db6e2f5157c833faf3c49247ce40e28f35 | juannlenci/ejercicios_python | /Clase03/tabla_informe.py | 2,119 | 3.609375 | 4 | #Informe.py
import csv
camion = []
precio = {}
costo_total=0.00
ganancia=0.00
balance=0.00
def leer_camion(nombre_archivo):
'''
Se le pasa el nombre del archivo a leer y devuelve
una lista con nombre, cajones y precio
'''
camion =[]
lote = {}
with open (nombre_archivo, "rt") as f:
rows = csv.reader(f)
header = next(rows)
for row in rows:
try:
lote = {"nombre" : row[0],"cajones": int(row[1]),"precio": float(row[2])}
camion.append(lote)
except ValueError:
print(f"warning 1")
return camion
def leer_precios(nombre_archivo):
'''
Se le pasa el nombre del archivo a leer y devuelve
un diccionario con nombre y precio
'''
precio = {}
with open (nombre_archivo, "rt") as f:
rows = csv.reader(f)
for row in rows:
try:
precio[row[0]] = float(row[1])
except IndexError:
print(f"warning 2")
return precio
def hacer_informe(lista_camion,dict_precios):
'''
Se le pasan lista de camion con nombre, cajones y precio, y
diccionario de precios y devuelve una lista con el informe
'''
informe = []
for n_fila, fila in enumerate(lista_camion):
precios = (dict_precios[(camion[n_fila]["nombre"])])-lista_camion[n_fila]["precio"]
fila_informe = (lista_camion[n_fila]["nombre"], lista_camion[n_fila]["cajones"], lista_camion[n_fila]["precio"], precios)
informe.append(fila_informe)
return informe
camion = leer_camion("../Data/camion.csv")
precio = leer_precios("../Data/precios.csv")
informe = hacer_informe(camion, precio)
headers = ('Nombre', 'Cajones', 'Precio', 'Cambio')
nombre_campo = (f'{headers[0]:>10s} {headers[1]:>10s} {headers[2]:>10s} {headers[3]:>10s}')
print (nombre_campo)
separacion = "---------- ---------- ---------- ----------"
print (separacion)
for nombre, cajones, precio, cambio in informe:
signo_precio = "$ " + str(precio)
print(f'{nombre:>10s} {cajones:>10d} {signo_precio:>10s} {cambio:>10.2f}')
|
fb6dbaed129890aa171757a61785cf8084a32168 | juannlenci/ejercicios_python | /Clase07/informe.py | 2,425 | 3.609375 | 4 | #!/usr/bin/env python3
#%%Informe.py
from fileparse import parse_csv
def leer_camion(nombre_archivo):
'''
Se le pasa el nombre del archivo a leer y devuelve
una lista con nombre, cajones y precio
'''
with open(nombre_archivo, encoding="utf8") as file:
camion = parse_csv(file, select=["nombre","cajones","precio"], types=[str, int, float])
return camion
def leer_precios(nombre_archivo):
'''
Se le pasa el nombre del archivo a leer y devuelve
un diccionario con nombre y precio
'''
with open(nombre_archivo, encoding="utf8") as file:
precio = dict(parse_csv(file, types=[str, float], has_headers=False))
return precio
def hacer_informe(lista_camion,dict_precios):
'''
Se le pasan lista de camion con nombre, cajones y precio, y
diccionario de precios y devuelve una lista con el informe
'''
informe = []
for n_fila, fila in enumerate(lista_camion):
precios = (dict_precios[(lista_camion[n_fila]["nombre"])])-lista_camion[n_fila]["precio"]
fila_informe = (lista_camion[n_fila]["nombre"], lista_camion[n_fila]["cajones"], lista_camion[n_fila]["precio"], precios)
informe.append(fila_informe)
return informe
def imprimir_informe(informe):
'''
Se le pasan informe generado e imprime la tabla
'''
headers = ('Nombre', 'Cajones', 'Precio', 'Cambio')
nombre_campo = (f'{headers[0]:>10s} {headers[1]:>10s} {headers[2]:>10s} {headers[3]:>10s}')
print (nombre_campo)
separacion = "---------- ---------- ---------- ----------"
print (separacion)
for nombre, cajones, precio, cambio in informe:
signo_precio = "$ " + str(precio)
print(f'{nombre:>10s} {cajones:>10d} {signo_precio:>10s} {cambio:>10.2f}')
return
def main(parametros):
'''
Se le pasan los parametros nombre de programa, nombre de archivos de camion
y de precios, crea el informe y lo imprime
'''
nombre_archivo_camion = parametros[1]
nombre_archivo_precios = parametros[2]
camion = leer_camion(nombre_archivo_camion)
precio = leer_precios(nombre_archivo_precios)
informe = hacer_informe(camion, precio)
imprimir_informe(informe)
return
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
raise SystemExit(f'Uso adecuado: {sys.argv[0]} ' 'archivo_camion archivo_precios')
main(sys.argv)
|
6dcd8553477affaecb3e2f97f06af531129f9c04 | iuliarevnic/Gomoku | /helpers.py | 19,656 | 4.25 | 4 | '''
Created on 23 dec. 2018
@author: Revnic
'''
def checkRows(matrix):
'''
Function that checks whether there are 5 consecutive elements of 1 or 2 on any row of a given matrix
input: matrix
preconditions:-
output: 0 or 1 or 2
postconditions: If there are such 5 elements of 1, the function returns 1,if there are such 5 elements of 2 else it returns 0
'''
for line in range(0,15):
column=0
while column<=10:
if(matrix[line][column]==1 and matrix[line][column+1]==1 and matrix[line][column+2]==1 and matrix[line][column+3]==1 and matrix[line][column+4]==1):
return 1
elif matrix[line][column]==2 and matrix[line][column+1]==2 and matrix[line][column+2]==2 and matrix[line][column+3]==2 and matrix[line][column+4]==2:
return 2
column+=1
return 0
def checkColumns(matrix):
'''
Function that checks whether there are 5 consecutive elements of 1 or 2 on any column of a given matrix
input: matrix
preconditions:-
output: 0 or 1 or 2
postconditions: If there are such 5 elements of 1, the function returns 1,if there are such 5 elements of 2 else it returns 0
'''
for column in range(0,15):
line=0
while line<=10:
if(matrix[line][column]==1 and matrix[line+1][column]==1 and matrix[line+2][column]==1 and matrix[line+3][column]==1 and matrix[line+4][column]==1):
return 1
elif matrix[line][column]==2 and matrix[line+1][column]==2 and matrix[line+2][column]==2 and matrix[line+3][column]==2 and matrix[line+4][column]==2:
return 2
line+=1
return 0
def checkDiagonals(matrix):
'''
Function that checks whether there are 5 consecutive elements of 1 or 2 diagonally in a given matrix
input: matrix
preconditions:-
output: 0 or 1 or 2
postconditions: If there are such 5 elements, the function will return the value of the elements, else it will return 0
'''
for line in range(0,11):
for column in range(0,11):
if matrix[line][column]==1 and matrix[line+1][column+1]==1 and matrix[line+2][column+2]==1 and matrix[line+3][column+3]==1 and matrix[line+4][column+4]==1:
return 1
elif matrix[line][column]==2 and matrix[line+1][column+1]==2 and matrix[line+2][column+2]==2 and matrix[line+3][column+3]==2 and matrix[line+4][column+4]==2:
return 2
for line in range(0,11):
for column in range(14,3,-1):
if matrix[line][column]==1 and matrix[line+1][column-1]==1 and matrix[line+2][column-2]==1 and matrix[line+3][column-3]==1 and matrix[line+4][column-4]==1:
return 1
elif matrix[line][column]==2 and matrix[line+1][column-1]==2 and matrix[line+2][column-2]==2 and matrix[line+3][column-3]==2 and matrix[line+4][column-4]==2:
return 2
return 0
def MaximumRows(matrix,position):
'''
Function that finds the maximum number of consecutive elements of 2 in a row, having at least an element of 0 at one end of the sequence
input: matrix, position
preconditions:-
output: maximum
postconditions:-
'''
maximum=0
for line in range(0,15):
column=0
while column<=14:
ok=0
length=0
while matrix[line][column]==2 and column<14:
length+=1
column+=1
if column==14 and matrix[line][13]==2 and matrix[line][14]==2:
length+=1
if length!=0:
if (column-1-length>=0 and matrix[line][column-1-length]==0):
ok=1
columnIndex=column-1-length
elif (column<=14 and matrix[line][column]==0):
ok=1
columnIndex=column
if length>maximum and ok==1:
maximum=length
position[0]=line
position[1]=columnIndex
column+=1
return maximum
def MaximumColumns(matrix,position):
'''
Function that finds the maximum number of consecutive elements of 2 in a column, having at least an element of 0 at one end of the sequence
input: matrix, position
preconditions:-
output: maximum
postconditions:-
'''
maximum=0
for column in range(0,15):
line=0
while line<=14:
ok=0
length=0
while matrix[line][column]==2 and line<14:
length+=1
line+=1
if line==14 and matrix[line][13]==2 and matrix[line][14]==2:
length+=1
if length!=0:
if (line-1-length>=0 and matrix[line-1-length][column]==0):
ok=1
lineIndex=line-1-length
elif (line<=14 and matrix[line][column]==0):
ok=1
lineIndex=line
if length>maximum and ok==1:
maximum=length
position[0]=lineIndex
position[1]=column
line+=1
return maximum
def MaximumDiagonals(matrix,position):
'''
Function that finds the maximum number of consecutive elements of 2 diagonally, having at least an element of 0 at one end of the sequence
input: matrix, position
preconditions:-
output: maximum
postconditions:-
'''
maximum=0
for line in range(0,11):
column=0
while column<=10:
length=0
ok=0
auxiliaryLine=line
while matrix[auxiliaryLine][column]==2 and auxiliaryLine<14 and column<14:
length+=1
auxiliaryLine+=1
column+=1
if auxiliaryLine==14 and matrix[auxiliaryLine][column]==2 and matrix[auxiliaryLine-1][column-1]==2:
length+=1
elif column==14 and matrix[auxiliaryLine][column]==2 and matrix[auxiliaryLine-1][column-1]==2:
length+=1
if length!=0:
if (auxiliaryLine-1-length>=0 and column-1-length>=0 and matrix[auxiliaryLine-1-length][column-1-length]==0):
ok=1
lineIndex=auxiliaryLine-1-length
columnIndex=column-1-length
elif (auxiliaryLine<=14 and column<=14 and matrix[auxiliaryLine][column]==0):
ok=1
lineIndex=auxiliaryLine
columnIndex=column
if length>maximum and ok==1:
maximum=length
position[0]=lineIndex
position[1]=columnIndex
column+=1
for line in range(0,11):
column=14
while column>=4:
length=0
ok=0
auxiliaryLine=line
while matrix[auxiliaryLine][column]==2 and auxiliaryLine<14 and column>0:
length+=1
auxiliaryLine=auxiliaryLine+1
column=column-1
if auxiliaryLine==14 and matrix[auxiliaryLine][column]==2 and matrix[auxiliaryLine+1][column+1]==2:
length+=1
elif column==0 and matrix[auxiliaryLine][column]==2 and matrix[auxiliaryLine-1][column+1]==2:
length+=1
if length!=0:
if (auxiliaryLine-1-length>=0 and column+1+length<=14 and matrix[auxiliaryLine-1-length][column+1+length]==0):
ok=1
lineIndex=auxiliaryLine-1-length
columnIndex=column+1+length
elif (auxiliaryLine<=14 and column>=0 and matrix[auxiliaryLine][column]==0):
ok=1
lineIndex=auxiliaryLine
columnIndex=column
if length>maximum and ok==1:
maximum=length
position[0]=lineIndex
position[1]=columnIndex
column=column-1
return maximum
def computerWin(matrix,winPosition):
'''
Function that checks if the computer has a chance to win with the next move, and if so, it also gives the position of the computer element
input: matrix,winPosition
preconditions:-
output:0 or 1
postconditions:-
'''
for line in range(0,15):
column=0
while column<=11:
if matrix[line][column]==2 and matrix[line][column+1]==2 and matrix[line][column+2]==2 and matrix[line][column+3]==2:
if column-1>=0 and matrix[line][column-1]==0:
winPosition[0]=line
winPosition[1]=column-1
return 1
else:
if column+4<=14 and matrix[line][column+4]==0:
winPosition[0]=line
winPosition[1]=column+4
return 1
column+=1
for column in range(0,15):
line=0
while line<=11:
if matrix[line][column]==2 and matrix[line+1][column]==2 and matrix[line+2][column]==2 and matrix[line+3][column]==2 :
if line-1>=0 and matrix[line-1][column]==0:
winPosition[0]=line-1
winPosition[1]=column
return 1
else:
if line+4<=14 and matrix[line+4][column]==0:
winPosition[0]=line+4
winPosition[1]=column
return 1
line+=1
for line in range(0,12):
for column in range(0,12):
if matrix[line][column]==2 and matrix[line+1][column+1]==2 and matrix[line+2][column+2]==2 and matrix[line+3][column+3]==2:
if line-1>=0 and column-1>=0 and matrix[line-1][column-1]==0:
winPosition[0]=line-1
winPosition[1]=column-1
return 1
else:
if line+4<=14 and column+4<=14 and matrix[line+4][column+4]==0:
winPosition[0]=line+4
winPosition[1]=column+4
return 1
for line in range(0,12):
for column in range(14,2,-1):
if matrix[line][column]==2 and matrix[line+1][column-1]==2 and matrix[line+2][column-2]==2 and matrix[line+3][column-3]==2:
if line-1>=0 and column+1<=14 and matrix[line-1][column+1]==0:
winPosition[0]=line-1
winPosition[1]=column+1
return 1
else:
if line+4<=14 and column-4>=0 and matrix[line+4][column-4]==0:
winPosition[0]=line+4
winPosition[1]=column-4
return 1
return 0
def oneMoveVictory(matrix,blockPosition):
'''
Function that checks whether the human player is at one-move victory or not, and if it is, it finds the position for the computer player to put his piece on, blocking the human player
input: matrix, blockPosition
preconditions:-
output:0 or 1
postconditions:-
'''
#cautarea pe randuri
for line in range(0,15):
column=0
while column<=11:
if matrix[line][column]==1 and matrix[line][column+1]==1 and matrix[line][column+2]==1 and matrix[line][column+3]==1:
if column-1>=0 and matrix[line][column-1]==0:
blockPosition[0]=line
blockPosition[1]=column-1
return 1
else:
if column+4<=14 and matrix[line][column+4]==0:
blockPosition[0]=line
blockPosition[1]=column+4
return 1
column+=1
for line in range(0,15):
column=0
while column<=12:
if matrix[line][column]==1 and matrix[line][column+1]==1 and matrix[line][column+2]==1 and column-1>=0 and matrix[line][column-1]==0 and column+3<=14 and matrix[line][column+3]==0:
blockPosition[0]=line
blockPosition[1]=column-1
return 1
column+=1
for line in range(0,15):
column=0
while column<=12:
if matrix[line][column]==1 and matrix[line][column+1]==1 and matrix[line][column+2]==1:
if column-1>=0 and matrix[line][column-1]==0:
blockPosition[0]=line
blockPosition[1]=column-1
return 1
else:
if column+3<=14 and matrix[line][column+3]==0:
blockPosition[0]=line
blockPosition[1]=column+3
return 1
column+=1
#cautarea pe coloane
for column in range(0,15):
line=0
while line<=11:
if matrix[line][column]==1 and matrix[line+1][column]==1 and matrix[line+2][column]==1 and matrix[line+3][column]==1 :
if line-1>=0 and matrix[line-1][column]==0:
blockPosition[0]=line-1
blockPosition[1]=column
return 1
else:
if line+4<=14 and matrix[line+4][column]==0:
blockPosition[0]=line+4
blockPosition[1]=column
return 1
line+=1
for column in range(0,15):
line=0
while line<=12:
if matrix[line][column]==1 and matrix[line+1][column]==1 and matrix[line+2][column]==1 and line-1>=0 and matrix[line-1][column]==0 and line+3<=14 and matrix[line+3][column]==0:
blockPosition[0]=line-1
blockPosition[1]=column
return 1
line+=1
for column in range(0,15):
line=0
while line<=12:
if matrix[line][column]==1 and matrix[line+1][column]==1 and matrix[line+2][column]==1:
if line-1>=0 and matrix[line-1][column]==0:
blockPosition[0]=line-1
blockPosition[1]=column
return 1
else:
if line+3<=14 and matrix[line+3][column]==0:
blockPosition[0]=line+3
blockPosition[1]=column
return 1
line+=1
#cautarea pe diagonale
for line in range(0,12):
for column in range(0,12):
if matrix[line][column]==1 and matrix[line+1][column+1]==1 and matrix[line+2][column+2]==1 and matrix[line+3][column+3]==1:
if line-1>=0 and column-1>=0 and matrix[line-1][column-1]==0:
blockPosition[0]=line-1
blockPosition[1]=column-1
return 1
else:
if line+4<=14 and column+4<=14 and matrix[line+4][column+4]==0:
blockPosition[0]=line+4
blockPosition[1]=column+4
return 1
for line in range(0,13):
for column in range(0,13):
if matrix[line][column]==1 and matrix[line+1][column+1]==1 and matrix[line+2][column+2]==1 and line-1>=0 and column-1>=0 and matrix[line-1][column-1]==0 and line+3<=14 and column+3<=14 and matrix[line+3][column+3]==0:
blockPosition[0]=line-1
blockPosition[1]=column-1
return 1
for line in range(0,13):
for column in range(0,13):
if matrix[line][column]==1 and matrix[line+1][column+1]==1 and matrix[line+2][column+2]==1:
if line-1>=0 and column-1>=0 and matrix[line-1][column-1]==0:
blockPosition[0]=line-1
blockPosition[1]=column-1
return 1
else:
if line+3<=14 and column+3<=14 and matrix[line+3][column+3]==0:
blockPosition[0]=line+3
blockPosition[1]=column+3
return 1
for line in range(0,12):
for column in range(14,2,-1):
if matrix[line][column]==1 and matrix[line+1][column-1]==1 and matrix[line+2][column-2]==1 and matrix[line+3][column-3]==1:
if line-1>=0 and column+1<=14 and matrix[line-1][column+1]==0:
blockPosition[0]=line-1
blockPosition[1]=column+1
return 1
else:
if line+4<=14 and column-4>=0 and matrix[line+4][column-4]==0:
blockPosition[0]=line+4
blockPosition[1]=column-4
return 1
for line in range(0,13):
for column in range(14,1,-1):
if matrix[line][column]==1 and matrix[line+1][column-1]==1 and matrix[line+2][column-2]==1 and line-1>=0 and column+1<=14 and matrix[line-1][column+1]==0 and line+3<=14 and column-3>=0 and matrix[line+3][column-3]==0:
blockPosition[0]=line-1
blockPosition[1]=column+1
return 1
for line in range(0,13):
for column in range(14,1,-1):
if matrix[line][column]==1 and matrix[line+1][column-1]==1 and matrix[line+2][column-2]==1:
if line-1>=0 and column+1<=14 and matrix[line-1][column+1]==0:
blockPosition[0]=line-1
blockPosition[1]=column+1
return 1
else:
if line+3<=14 and column-3>=0 and matrix[line+3][column-3]==0:
blockPosition[0]=line+3
blockPosition[1]=column-3
return 1
return 0
def firstComputerElement(matrix,playerElementPosition):
'''
Function that checks whether its the computer's first turn or not
input: matrix,playerElementPosition
preconditions:-
output: 0 or 1
postconditions:-
'''
for line in range(0,15):
for column in range(0,15):
if(matrix[line][column]==2):
return 0
for line in range(0,15):
for column in range(0,15):
if (matrix[line][column]==1):
playerElementPosition[0]=line
playerElementPosition[1]=column
return 1
def isFull(matrix):
'''
Function that checks whether the matrix is full or not
input: matrix
preconditions:-
output: 0 or 1
postconditions:-
'''
for line in range(0,15):
for column in range(0,15):
if matrix[line][column]==0:
return 0
return 1 |
5cf606c2bc4fe03967952f96b4a42b2a41b846f4 | derickdev6/pybasic | /number_guesser.py | 597 | 3.71875 | 4 | import random
def run():
lifes = 5
rand_number = random.randint(0, 100)
while True:
if lifes == 0:
print('You lost :(')
break
print('Try to guess')
chosen = int(input(': '))
if rand_number > chosen:
lifes -= 1
print('> - Lifes left: ' + str(lifes))
elif rand_number < chosen:
lifes -= 1
print('< - Lifes left: ' + str(lifes))
else:
print('Congratulations!')
break
if __name__ == '__main__':
run()
print('\nEnd of program... \n')
|
9f556c096bdca4d5a5657485875b17b2bbadfec5 | uoshvis/scrapy-examples | /src/xpath_examples/first_node.py | 1,396 | 3.59375 | 4 | from scrapy import Selector
def example_node():
# https://www.zyte.com/blog/xpath-tips-from-the-web-scraping-trenches/
# the difference between //node[1] and (//node)[1]
# //node[1] selects all the nodes occurring first under their respective parents.
sel = Selector(text="""
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul class="list">
<li>4</li>
<li>5</li>
<li>6</li>
</ul>""")
xp = lambda x: sel.xpath(x).getall()
# get all first LI elements under whatever it is its parent
all_first_li = xp("//li[1]")
assert all_first_li == ['<li>1</li>', '<li>4</li>']
# get the first LI element in the whole document
first_li_whole = xp("(//li)[1]")
assert first_li_whole == ['<li>1</li>']
# get all first LI elements under an UL parent
all_first_li_ul = xp("//ul/li[1]")
assert all_first_li_ul == ['<li>1</li>', '<li>4</li>']
# get the first LI element under an UL parent in the whole document
first_li_ul_whole = xp("(//ul/li)[1]")
assert first_li_ul_whole == ['<li>1</li>']
# to get a collection of the local anchors that occur first under their respective parents:
# //a[starts-with(@href, '#')][1]
# to get the first local anchor in the document:
# (//a[starts-with(@href, '#')])[1]
if __name__ == '__main__':
example_node()
|
241396d6059ddf3b6bdb521cd0c26f311d2ad4d6 | StefaRueRome/LaboratorioFuncionesRemoto | /potencia.py | 175 | 3.8125 | 4 |
def a_power_b(a,b):
prod=1
for i in range(0,b):
prod=prod*a
return prod
a=int(input("Ingrese la base: "))
b=int(input("Ingrese la potencia: "))
print(a_power_b(a,b)) |
4d74e0f3212ef18edd0fcc5b556d852baa403c4b | samp830/CS61A | /hw/hw01/quiz/quiz01.py | 983 | 4.0625 | 4 | def multiple(a, b):
"""Return the smallest number n that is a multiple of both a and b.
>>> multiple(3, 4)
12
>>> multiple(14, 21)
42
"""
lcm = max(a,b)
while lcm % min(a,b) != 0:
lcm = lcm + max(b,a)
return lcm
def unique_digits(n):
"""Return the number of unique digits in positive integer n
>>> unique_digits(8675309) # All are unique
7
>>> unique_digits(1313131) # 1 and 3
2
>>> unique_digits(13173131) # 1, 3, and 7
3
>>> unique_digits(10000) # 0 and 1
2
>>> unique_digits(101) # 0 and 1
2
>>> unique_digits(10) # 0 and 1
2
"""
def has_digit(n,k):
check= False
while n > 0:
digit = n%10
if digit == k:
check = True
n=n//10
return check
b = 0
unique = 0
while b < 10:
if has_digit(n,b):
unique +=1
b+=1
else:
b+=1
return unique |
0aa845bb1209f9edb325fd573291d06afa48ee5c | alephramos/Hackwords | /hackwords.py | 375 | 3.640625 | 4 | # -*- coding: utf_8 -*-
import pandas as pd
import sqlite3,random
mypath = "Files/"
df = pd.DataFrame()
connection = sqlite3.connect('words.db')
cursor = connection.cursor()
query="select word,frecuency,length(word) as len from hackword order by frecuency desc"
df = pd.read_sql_query(query,connection)
print(df.sort(["frecuency"],ascending=False))
for index,row in df.in |
74a6e558d7e5f7958973ebf3114e85bbfddb243d | alexescalonafernandez/service-locator | /service_locator/ioc.py | 5,218 | 3.96875 | 4 | from enum import Enum
class Singleton:
"""
Decorator for add singleton pattern support
@author: Alexander Escalona Fernández
"""
def __init__(self, decorated):
"""
:param decorated: class to convert to singleton
"""
self._decorated = decorated
def instance(self):
"""
:return: the singleton instance of decorated
"""
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
@Singleton
class ServiceLocator:
"""
Implementation of service locator pattern. It represents the Registry of service locator and as such is a Singleton.
@author: Alexander Escalona Fernández
"""
def __init__(self):
"""
Initialize the registry data structure.
"""
self.services = {}
def register(self, service, serviceImpl, serviceImplQualifier):
"""
Register a service implementation with a given qualifier
:param service: the marker interface to group implementations
:param serviceImpl: the implementation of the given marker interface
:param serviceImplQualifier: the qualifier string that identifies the implementation
:return:
"""
if service not in self.services:
self.services[service] = {}
if serviceImplQualifier in self.services[service]:
raise RuntimeError(
'There is a ' + serviceImplQualifier + ' qualifier for ' + service + ' instance in service locator')
self.services[service][serviceImplQualifier] = serviceImpl
def lookup(self, service, qualifier=''):
"""
:param service: the marker interface to group implementations
:param qualifier: the qualifier string that identifies the implementation
:return: the implementation of the given marker interface with the given qualifier
"""
if service not in self.services:
return None
if qualifier not in self.services[service]:
return None
return self.services[service][qualifier]()
class Scope(Enum):
PROTOTYPE = 1
SINGLETON = 2
class ServiceProvider:
"""
Decorator to populate the ServiceLocator
@author: Alexander Escalona Fernández
"""
def __init__(self, service, qualifier='', scope=Scope.PROTOTYPE):
"""
:param service: the marker interface to group implementations
:param qualifier: the qualifier string that identifies the implementation
:param scope: the scope of instance, if prototype create one each time is requested, if singleton
the instance acts as a singleton
"""
self._service = service
self._qualifier = qualifier
if isinstance(scope, Scope):
self._scope = scope
else:
raise ValueError("The scope argument value is incorrect. Uses Scope enum class for set this parameter.")
def __call__(self, provider):
"""
:param provider: the implementation of the given marker interface, which will be registered
in the Service Locator
:return:
"""
def prototype(constructor):
def factory():
return constructor()
return factory
def singleton(instance):
def _instance():
return instance
return _instance
if self._scope == Scope.SINGLETON:
ServiceLocator.instance().register(self._service, singleton(provider()), self._qualifier)
else:
ServiceLocator.instance().register(self._service, prototype(provider), self._qualifier)
class ServiceProxy(object):
"""
Create a proxy for service implementation. The goal of this class is only lookup in the Service Locator
registry when is needed.
@author: Alexander Escalona Fernández
"""
def __init__(self, service, qualifier=''):
self._service = service
self._qualifier = qualifier
self._implementation = None
def __getattr__(self, item):
if object.__getattribute__(self, "_implementation") is None:
setattr(self, "_implementation", ServiceLookup.lookup(self._service, self._qualifier))
return getattr(object.__getattribute__(self, "_implementation"), item)
class ServiceLookup:
"""
Facade to lookup implementation from service locator registry
@author: Alexander Escalona Fernández
"""
@staticmethod
def lookup(service, qualifier=''):
"""
Returns if exists, an implementation from Service Locator registry
:param service: the marker interface to group implementations
:param qualifier: the qualifier string that identifies the implementation
:return: the implementation of the given marker interface with the given qualifier
"""
return ServiceLocator.instance().lookup(service, qualifier)
@staticmethod
def proxy(service, qualifier=''):
return ServiceProxy(service, qualifier)
|
61fd094bc05f18dadbfb7a90ea641ae943504d44 | moldabek/WebDevelopment | /week8/lab7/5.functions/c.py | 88 | 3.53125 | 4 | def xor(a,b):
return a^b
a = [int(i) for i in input().split()]
print(xor(a[0],a[1]))
|
c181197fae9dcf631399298063c953dc071b271a | moldabek/WebDevelopment | /week8/lab7/1.input-output/a.py | 82 | 3.71875 | 4 | from math import sqrt
n = int(input())
m = int(input())
print(sqrt(n**2 + m**2))
|
0aca92e95b1a6d7260776caf897432ceabe3a2f8 | moldabek/WebDevelopment | /week8/lab7/2.if-else/c.py | 118 | 3.859375 | 4 | n = int(input())
m = int(input())
if n == 1 and m == 1 or n != 1 and m != 1:
print("YES")
else:
print("NO")
|
01aaf5aec0ca74fdfec8f95d7137979737c313a4 | JMH201810/Labs | /Python/p01320g.py | 1,342 | 4.5 | 4 | # g. Album:
# Write a function called make_album() that builds a dictionary describing
# a music album. The function should take in an artist name and an album
# title, and it should return a dictionary containing these two pieces of
# information. Use the function to make three dictionaries representing
# different albums. Print each return value to show that the dictionaries
# are storing the album information correctly.
# Add an optional parameter to make_album() that allows you to store the
# number of tracks on an album. If the calling line includes a value for
# the number of tracks, add that value to the album's dictionary.
# Make at least one new function call that includes the number of tracks on
# an album.
def make_album(artist_name, album_title, nTracks=''):
if nTracks:
d = {'artist_name':artist_name,
'album_title':album_title,
'nTracks':nTracks}
else:
d = {'artist_name':artist_name,
'album_title':album_title}
return d
d1 = make_album('Bob','Album1')
d2 = make_album('Donald','Album2')
d3 = make_album('Gertrude','Album3')
print ('\n', d1, '\n', d2, '\n', d3)
d1 = make_album('Bob','Album1')
d2 = make_album('Donald','Album2')
d3 = make_album('Gertrude','Album3', 7)
print ('\n', d1, '\n', d2, '\n', d3)
|
64a30bf626d62b29ae78c9ac9435dc1ca5c929f3 | JMH201810/Labs | /Python/p01320L.py | 568 | 4.15625 | 4 | # l. Sandwiches:
# Write a function that accepts a list of items a person wants on a sandwich.
# The function should have one parameter that collects as many items as the
# function call provides, and it should print a summary of the sandwich that
# is being ordered.
# Call the function three times, using a different number
# of arguments each time.
def toppings(*thing):
print ()
for t in thing:
print('-', t)
toppings('butter', 'air', 'salt')
toppings('worms', 'sand', 'rocks', 'tahini')
toppings('wallets', 'staplers')
|
a8da0ec50d16d15d4dca89edc8b794c440994bf5 | JMH201810/Labs | /Python/p01310i.py | 813 | 3.875 | 4 | # Pets:
# Make several dictionaries, where the name of each dictionary is
# the name of a pet. In each dictionary, include the kind of animal
# and the owner's name. Store these dictionaries in a list called pets.
# Next, loop through your list and as you do print everything you know
# about each pet.
Suzy = {'type':'cat', 'name':'Suzy', 'owner':'Patricia'}
Jinx = {'type':'cat', 'name':'Jinx', 'owner':'Sarah'}
Fruit = {'type':'cat', 'name':'Fruit', 'owner':'Collin'}
Simon = {'type':'cat', 'name':'Simon', 'owner':'MaryAnn'}
Prudence = {'type':'cat', 'name':'Prudence', 'owner':'MaryAnn'}
pets = [Suzy, Jinx, Fruit, Simon, Prudence]
for p in pets:
print("\nData about ", p['name'],":",sep='')
for k,v in p.items():
if k != 'name':
print(k,": ",v,sep='')
|
ae64e924773c4243da27404de13e74ce2e973b56 | JMH201810/Labs | /Python/p01310j.py | 631 | 4.59375 | 5 | # Favorite Places:
# Make a dictionary called favorite_places.
# Think of three names to use as keys in the dictionary, and store one to
# three favorite places for each person.
# Loop through the dictionary, and print each person's name and their
# favorite places.
favorite_places = {'Alice':['Benton Harbor', 'Alice Springs', 'Utah'],
'Brenda':['Ann Arbor', 'Detroit', 'Eau Claire'],
'Charles':['under the couch', 'VBISD', 'Michigan']}
for person,placeList in favorite_places.items():
print("\n",person,"'s favorite places are:", sep='')
for place in placeList:
print(place)
|
d6c1fa3d43547d59fa10a9e6d1e51e169dac8a18 | JMH201810/Labs | /Python/p01210i.py | 924 | 4.875 | 5 | # Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza
# names in a list, and then use a for loop to print the name of each pizza.
pizzaTypes = ['Round', 'Edible', 'Vegetarian']
print("Pizza types:")
for type in pizzaTypes:
print(type)
# i. Modify your for loop to print a sentence using the name of the pizza
# instead of printing just the name of the pizza. For each pizza you should
# have one line of output containing a simple statement like I like pepperoni
# pizza.
print("Using a sentence:")
for type in pizzaTypes:
print("I like",type,"pizza.")
# ii. Add a line at the end of your program, outside the for loop, that states how
# much you like pizza. The output should consist of three or more lines
# about the kinds of pizza you like and then an additional sentence, such as I
# really love pizza!
print ("I really love pizza!")
|
e86600435612f88fbf67e3e805f0e21e6f0f51f8 | 23-Dharshini/priyadharshini | /count words.py | 253 | 4.3125 | 4 | string = input("enter the string:")
count = 0
words = 1
for i in string:
count = count+1
if (i==" "):
words = words+1
print("Number of character in the string:",count)
print("Number of words in the string:",words) |
046c8f695ebefbe7fb30651c7b6444610702d93e | Whatsupyuan/python_ws | /10. 第十章_02-异常except/10_1004_test01.py | 349 | 3.921875 | 4 | def plus():
try:
num1 = int(input("Please input first number.."))
num2 = int(input("Please input second number.."))
# python 3.6 捕获多个异常,不能使用 , 号分隔
except TypeError:
print("error.")
except ValueError:
print("valueError")
else:
return num1 + num2
print(plus()) |
1622d36817330cc707a1a4e4c4e52810065aa222 | Whatsupyuan/python_ws | /4.第四章-列表操作/iterator_044_test.py | 1,306 | 4.15625 | 4 | # 4-10
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("The first three items in the list are" )
print(players[:3])
print()
# python3 四舍五入 问题
# 官方文档写了,round(number[, ndigits]) values are rounded to the closest multiple of 10 to the power minus ndigits;
# if two multiples are equally close, rounding is done toward the even choice
# (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
# 就是说round(1/2)取离它最近的整数,如果2个数(0和1)离它一样近,则取偶数(the even choice)。
# 因此round(1.5)=2, round(2.5)=2, round(3.5)=4, round(4.5)=4。
# http://www.cnblogs.com/lxmwb/p/7988913.html
# 4-10-2 打印列表中间的3个元素
print("Three items from the middle of the list are:")
import decimal
half_length = len(players)
a = decimal.Decimal(half_length)/2
decimal.getcontext().rounding = decimal.ROUND_UP
half_num = round(a,0)
print(players[int(half_num-2):int(half_num+1)])
print()
# 4-10-3 打印列表尾部的3个元素
print("The last three items in the list are:")
print(players[half_length-3:])
# 4-11-1
pizzas = ["one_pizza" , "two_pizza" , "thress_pizza"]
friend_pizzas = pizzas[:]
pizzas.append("none-pizza");
print(pizzas)
print(friend_pizzas)
for p in pizzas:
print(p) |
6eec6a9e295edab7320b350776335b60ce1080ae | Whatsupyuan/python_ws | /9.第九章-类class/09_class_0910_testRandom.py | 305 | 3.78125 | 4 | from random import randint
# 生成 1 到 6 之间的随机数
x = randint(1, 6)
print(x)
class Die():
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
print(randint(1, 6))
die = Die()
print("开始投掷骰子")
for num in range(1, 11):
die.roll_die()
|
975d3f6ea1518c2e1f8d3939da09bbaf66b4acb3 | Whatsupyuan/python_ws | /5.第五章-if/if_0230_test.py | 471 | 4 | 4 | # 5.2.1
str1 = "print info"
str2 = "print name"
print(str1 == str2)
# 5.2.2
print(str1.lower() == str2)
# 5.2.3
int1 = 100
int2 = 110
print(int1 == int2)
print(int1 != int2)
print(int1 > int2)
print(int1 < int2)
print(int1 >= int2)
print(int1 <= int2)
# 5.2.4
if int1 == int2 or int1 <= int2:
print(1)
if int1 != int2 and int1 < int2:
print(22)
# 5.2.5
print()
cars = ["benz", "bmw", "toyota"]
if "uia" in cars:
print(1)
if "uia" not in cars:
print(2) |
98d23e0af9f04e9ba50bdf07a6f04bec5b1e2d57 | Whatsupyuan/python_ws | /4.第四章-列表操作/iterator_044_split.py | 461 | 3.71875 | 4 |
players = ['charles', 'martina', 'michael', 'florence', 'eli']
split_arr = players[0:1]
print(split_arr)
split_arr = players[1:]
print(split_arr)
# 内容指向一直的 list , 则两个list不能相互独立
new_players = players
new_players.insert(0,"yuan")
print(new_players)
print(players) ;
print()
# 复制列表 [:] , 复制之后的列表是独立的内存指向
new_players = players[:]
new_players.append("Kobe")
print(players)
print(new_players) |
134d4811b1e629067e1f711f145fff9b889617aa | Whatsupyuan/python_ws | /6.第六章-字典(Dictionary)/06_dic_0603_iteratorDictionary.py | 734 | 4.28125 | 4 | favorite_num_dic = {"Kobe": 24, "Jame": 23, "Irving": 11}
# 自创方法,类似于Map遍历的方法
for num in favorite_num_dic:
print(num + " " + str(favorite_num_dic[num]))
print()
# 高级遍历方法 items() 方法
print(favorite_num_dic.items())
for name,number in favorite_num_dic.items():
print(name + " " + str(number))
print()
# key获取 字典 中的所有key --- keys()
# 如果将上述代码中的for name in favorite_languages.keys(): 替换为for name in favorite_languages: ,输出将不变。
for key in favorite_num_dic.keys():
print(key)
print()
# 字典获取所有的 value --- values()
# 类似于 Map.keys() 与 Map.values()
vals = favorite_num_dic.values()
for val in vals:
print(val)
|
9c54989a85bd5020fe1407b3ea1a90046034c8b4 | Whatsupyuan/python_ws | /7.第七章-用户输入input和while循环/07_input_0201_while_0705test.py | 237 | 4 | 4 | # 电影院
while True:
info = int(input("岁数?"))
if info == 888:
break
if info < 3:
print("免费")
elif info > 3 and info < 12:
print("10美元")
elif info > 15:
print("15美元")
|
81ba73b968e2676a4d6d4485dce939b5c1e3443e | Whatsupyuan/python_ws | /4.第四章-列表操作/test.py | 736 | 3.953125 | 4 | # 4-3
# for num in range(1,20):
# print(num)
def iteratorMethod(list):
for val in list:
print(val)
numArr = list(range(1, 1000 * 1000 + 1))
# iteratorMethod(numArr)
# print(min(numArr))
# print(max(numArr))
# print(sum(numArr))
# numArr = list(range(1,20,2))
# iteratorMethod(numArr)
# numArr = list(range(3, 31, 3))
# iteratorMethod(numArr)
# arr = []
# for num in range(1,11):
# arr.append(num**3)
# iteratorMethod(arr)
# arrNum = [num**3 for num in range(1,11)]
# iteratorMethod(arrNum)
# orderedDict 保存插入字典中的顺序
from collections import OrderedDict
dict = OrderedDict()
dict["h3"] = "hello3"
dict["h1"] = "hello1"
dict["h2"] = "hello2"
for k, v in dict.items():
print(k + " " + v) |
689e63b9210d28d7d709c06806b607e4b1d22831 | Whatsupyuan/python_ws | /9.第九章-类class/09_class_0905_extend.py | 636 | 3.765625 | 4 | '''
父类 , 子类
继承
'''
class Car():
def __init__(self , name , series):
self.name = name
self.series = series
def carInfo(self):
print(self.name + " " + self.series)
class ElectriCar(Car):
def __init__(self , name , series ):
# super() 必须写成方法体形态 , 与JAVA不同
super().__init__(name , series)
def printElectriCarInfo(self):
print(self.name + " " + self.series + "Electri")
car = Car("toyota" , "霸道")
car.carInfo()
carElec = ElectriCar("特斯拉" , "P80")
carElec.printElectriCarInfo()
# 输出
# toyota 霸道
# 特斯拉 P80Electri |
3d36ddfcdb53ea51d3e0b1b44ac347ec35c58c18 | Whatsupyuan/python_ws | /3.第三章-列表/list_03_sorted.py | 262 | 3.828125 | 4 | # list排序
cars = ['bmw', 'audi', 'toyota', 'subaru'] ;
sorted_cars = sorted(cars);
print("排序之后列表 : " + str(sorted_cars));
print("原始列表 : " + str(cars));
# sorted 反响排序
print("sorted倒序排列:" + str(sorted(cars,reverse=True))) ; |
8a042aa4d931d9ed16594b4f3988ad35d6222325 | Whatsupyuan/python_ws | /10. 第十章_02-异常except/10_1003_pass.py | 923 | 3.703125 | 4 | def countWord(fileName):
if fileName:
try:
with open(fileName) as file:
content = file.readlines()
# except 之后要捕获的异常可以不写
# 程序一样会执行
except FileNotFoundError:
# pass 当程序出现异常时 , 什么操作都不执行
pass
else:
wordsCount = 0
for line in content:
wordsCount += len(line.split())
return wordsCount
# 第二种方法: 一次性读取所有文件内容
def countFileIncludWord(fileName):
if fileName:
try:
with open(fileName) as file:
content = file.read()
except:
pass
else:
return len(content.split())
num = countWord("10_1001_exception.py")
num2 = countFileIncludWord("10_1001_exception.py")
if num:
print(num)
if num2:
print(num2) |
4804a7005c71ed635bbd1dbff0be64ff46cd78ad | Whatsupyuan/python_ws | /10. 第十章_01-文件操作File/10_file_1007_test.py | 210 | 3.703125 | 4 | flag = True
while flag:
name = input("Pleas input your name ... ")
if name and name == 'q':
flag = False
continue
with open("guest.txt", "a") as file:
file.write(name + "\n") |
3d999ca8f12348a3cb229be5af0f9cdba4ccc0b2 | ArvindAROO/algorithms | /sleepsort.py | 1,052 | 4.125 | 4 | """
Sleepsort is probably the wierdest of all sorting functions
with time-complexity of O(max(input)+n) which is
quite different from almost all other sorting techniques.
If the number of inputs is small then the complexity
can be approximated to be O(max(input)) which is a constant
If the number of inputs is large then the complexity is
approximately O(n)
This function uses multithreading a kind of higher order programming
and calls n functions, each with a sleep time equal to its number.
Hence each of the functions wake in Sorted form
But this function is not stable for very large values
"""
from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v:
mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
sorted_x=sleepsort(x)
print(sorted_x)
|
5ff98430566fb288495995803076102ae131d7f8 | artheadsweden/python_adv_april19 | /Day1/Print.py | 528 | 3.609375 | 4 | from functools import wraps
def print_with_start(original_print):
@wraps(original_print)
def wrapper(*args, **kwargs):
pre = ""
if "start" in kwargs:
pre = kwargs['start']
kwargs.pop('start')
original_print(pre, *args, **kwargs)
return wrapper
print = print_with_start(print)
def main():
x = 10
print("x is", x)
print("x", end="")
print(x, start=" =")
print(f"x is {x}", start="<", end=">\n", sep="")
if __name__ == '__main__':
main()
|
f5703afe5db60099c947aafae9847b96e3b3b9a7 | noeldelgadom/devF | /easy:P/easy2.py/product.py | 454 | 4.03125 | 4 | # -*- encoding: utf8 -*-
lista1=[1,2,4,5,9,4]
lista2=[6,1,2,3,1,4]
print "sumar de las listas"
for i in range(len(lista1)):
print lista1[i]+lista2[i]
print ""
print "Resta de las listas"
for i in range(len(lista1)):
print lista1[i]-lista2[i]
print ""
print "Divicion de las listas"
for i in range(len(lista1)):
print lista1[i] / lista2[i]
print ""
print "Multiplicacion de las listas"
for i in range(len(lista1)):
print lista1[i]*lista2[i]
|
0ebdd0da9d050cd2f5f70738697a84e26a385b35 | Dedlipid/PyBits | /basechanger.py | 408 | 3.734375 | 4 | def f():
n=int(raw_input("Enter number "))
b=int(raw_input("Enter base "))
l=[]
if n == 0 :
print "0 in any base is 0"
else:
while n > 0:
l.extend([n % b])
n /= b
l = l[::-1]
if b <=10:
l = ''.join(str(e) for e in l)
else :
l = ' '.join(str(e) for e in l)
print l
c = raw_input("Press enter to run again")
if c == "":
f()
f()
|
77d4482ba88837a3bca6280a08320a2b0eb70aac | KD4N13-L/Data-Structures-Algorithms | /Sorts/merge_sort.py | 1,591 | 4.21875 | 4 | def mergesort(array):
if len(array) == 1:
return array
else:
if len(array) % 2 == 0:
array1 = []
half = (int(len(array) / 2))
for index in range(0, half):
array1.append(array[index])
array2 = []
for index in range(half, len(array)):
array2.append(array[index])
array1 = mergesort(array1)
array2 = mergesort(array2)
return merge(array1, array2)
else:
array1 = []
half = (int((len(array) + 1) / 2))
for index in range(0, half):
array1.append(array[index])
array2 = []
for index in range(half, len(array)):
array2.append(array[index])
array1 = mergesort(array1)
array2 = mergesort(array2)
return merge(array1, array2)
def merge(array1, array2):
temp_array = []
while array1 and array2:
if array1[0] > array2[0]:
temp_array.append(array2[0])
array2.pop(0)
else:
temp_array.append(array1[0])
array1.pop(0)
while array1:
temp_array.append(array1[0])
array1.pop(0)
while array2:
temp_array.append(array2[0])
array2.pop(0)
return temp_array
def main():
array = input("Enter the number of array members, seperated by a coma")
array = array.split(',')
length = len(array)
for item in range(length):
array[item] = int(array[item])
print(mergesort(array))
main()
|
e9225939223ee4486cd867bfe1018e5788716e4a | AngiesEmail/ARTS | /ProgrammerCode/mergeTwoSortedLists.py | 757 | 3.515625 | 4 | class ListNode(Onject):
def __init__(self,x):
self.val = x
self.next = None
def mergeLists(l1,l2):
dummy = result = ListNode(l1.val)
node1 = l1.next
node2 = l2
while node1 != None and node2 != None:
if node1.val <= node2.val:
result.next = node1
node1 = node1.next
result = result.next
else:
if result.val <= node2.val:
result.next = node2
node2 = node2.next
result = result.next
else:
curNode = result
result.val = node2.val
result.next = curNode
node2 = node2.next
result = result.next
return dummy
mergeLists |
7c3abbae1e51ca3e6b12f151000b2e06d01b6ded | iagoguimaraes/introducaopython | /aula2/decisao.py | 1,067 | 4.09375 | 4 | def ex_16():
primeiro_numero = float(input('Digite um número: '))
segundo_numero = float(input('Digite outro número: '))
if(primeiro_numero > segundo_numero):
print('O número {} é maior.'.format(primeiro_numero))
elif(segundo_numero > primeiro_numero):
print('O número {} é maior.'.format(segundo_numero))
else:
print('Os números {0} e {1} são iguais.'.format(primeiro_numero, segundo_numero))
def ex_17(numero):
if (float(numero) < 0):
print('O número {} é negativo.'.format(numero))
elif(float(numero) > 0):
print('O número {} é positivo.'.format(numero))
else:
print('Você digitou {}.'.format(numero))
def ex_19(letra):
if(letra.isalpha()):
vogais = ['A', 'E', 'I', 'O', 'U']
print('{} é uma vogal.'.format(letra)) if letra.upper() in vogais else print('{} é uma consoante.'.format(letra))
else:
print('Letra inválida.')
def run():
ex_16()
ex_17(input('Digite um número: '))
ex_19(input('Digite uma letra: '))
|
6e0f318c5fcbccfc8e04a6c0866b04e8b84a76f4 | cristigavrila/Python-Basics | /string_null_bool.py | 114 | 3.859375 | 4 | #a string with 0 is still true in boolean condiion
s = '0'
if s:
print('true')
else:
print('False')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.