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 |
|---|---|---|---|---|---|---|
a5aa9d1003ff2a25340a7e491e08b7edf1d211cb | bawate/recipe-app-api | /app/app/calc.py | 168 | 4.09375 | 4 |
def add(x, y):
"""Add the two numbers together"""
return x + y
def subtract(x, y):
"""Subtract the two numbers and return the output"""
return x - y
|
784b7b523480ccf7e5f6f0199b77f936031817a1 | CristiReyes/Assignment-9 | /classBattleship.py | 1,563 | 4.09375 | 4 | from random import randrange
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print(' '.join(row))
shipX = randrange(5)
shipY = randrange(5)
counter = 0
print("Let's play battleship!\nTry and sink my battleship in 4 tries!\n")
while (counter < 4):
print_board(board)
try:
row_guess = int(input("\nPlease guess a row: "))
column_guess = int(input("Please guess a column: "))
if ((row_guess < 0 or row_guess > 4) or (column_guess < 0 or column_guess > 4)):
print("\nInvalid input--out of board range\n")
elif (board[row_guess][column_guess] == "X"):
print("\nInvalid input--you have already guessed this coordinate\n")
elif (row_guess != shipX or column_guess != shipY):
print("\nIncorrect guess")
board[row_guess][column_guess] = "X"
counter += 1
print("You have", 4 - counter, "tries left!\n")
elif (row_guess == shipX and column_guess == shipY):
counter += 1
print("\nYou have sunk my battleship in", counter, "tries!")
break;
except Exception as e:
print("\nInvalid input--please enter a number\n")
if (row_guess != shipX or column_guess != shipY):
print("Here was my ship!\n")
board[shipX][shipY] = "*"
print_board(board)
print("\nYou failed to sink my battleship! Please try again!") |
c58baaecc2fe4213097c80ec74bfdca41d2b99ad | xdronmanx/a3200-2015-algs | /lab4/Gogolev/Zadacha4.py | 932 | 3.71875 | 4 | from sys import stdin
first_line = stdin.readline()
list = [int(p) for p in first_line.split(' ')]
k = 10
def INSERTION_SORT(list):
for j in range(1, len(list)):
key = list[j]
i = j - 1
while (i >= 0) and (list[i] > key):
list[i+1] = list[i]
i = i - 1
list[i+1] = key
return list
def MERGE(leftpart, rightpart):
list = []
while leftpart and rightpart:
if leftpart[0] < rightpart[0]:
list.append(leftpart.pop(0))
else:
list.append(rightpart.pop(0))
if leftpart:
list.extend(leftpart)
if rightpart:
list.extend(rightpart)
return list
def MERGE_SORT(list):
length = len(list)
if length >= 10:
mid = int(length / 2)
list = MERGE(MERGE_SORT(list[:mid]), MERGE_SORT(list[mid:]))
else:
list = INSERTION_SORT(list)
return list
print(MERGE_SORT(list))
|
fa611914011816c11f5d5dd6151440c3d283b2b0 | JayBhakhar/maths-project | /python files/task2.py | 242 | 3.5 | 4 | ## TASK 6.9.14 ##
import itertools
lst = []
num = int(input("input number for permutations :- "))
for n in range(num):
n = n + 1
lst.append(n)
for p in itertools.permutations(lst):
print(''.join(str(x) for x in p))
|
7c9e4ac3c13a544af61ae090df839bc6cc64073a | LorchZachery/satlabeling | /dev/hotkeys/hotkeys.py | 1,199 | 3.859375 | 4 | from pynput import keyboard
# the key combination to look for
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(vk=65)}
]
def execute():
"""function to execute when a combination is pressed"""
print("do something")
# The currently pressed key (initially empty)
pressed_vks = set()
def get_vk(key):
"""
Get the virtual key code form a key.
these are used so case/shift modifications are ignored
"""
return key.vk if hasattr(key, 'vk') else key.value.vk
def is_combination_pressed(combination):
"""check if the combination is satisifed using the keys pressed in pressed_vks
"""
return all([get_vk(key) in pressed_vks for key in combination])
def on_press(key):
"""when a key is pressed"""
vk = get_vk(key) # get keys vk
pressed_vks.add(vk) # adding it to the set of currently pressed keys
for combination in COMBINATIONS:
if is_combination_pressed(combination):
execute()
break
def on_release(key):
"""when key is released"""
vk = get_vk(key)
pressed_vks.remove(vk)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join() |
dea7be93bb9263fb2a4d9b34211ec58944b1a130 | dwg920302/python_customs | /darkspace/kakao2.py | 1,152 | 3.578125 | 4 | # 0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요.
#
# 예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다.
#
# 0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요.
#
# 제한 사항
# numbers의 길이는 1 이상 100,000 이하입니다.
# numbers의 원소는 0 이상 1,000 이하입니다.
# 정답이 너무 클 수 있으니 문자열로 바꾸어 return 합니다.
'''
numbers = [3, 30, 34, 5, 9]
res = ''
numbers = list(map(lambda a: str(a), numbers))
print(numbers)
numbers.sort(reverse=True)
for i in numbers:
res += i
print(res)
'''
# 1번 식은 되는데 2번 식에서 틀림 (3이 앞에 와야 하는데 30이 옴). 문자열로는 풀 수 없고, 식으로 해야 함
numbers = [3, 30, 34, 5, 9]
numbers = list(map(lambda a: str(a), numbers))
numbers.sort(key=lambda a: a * 3, ) |
3bf49a56937907bf9e6dac455d92ededc5dc91b0 | dwg920302/python_customs | /darkspace/practice_questions/pr4to2.py | 410 | 3.5 | 4 | class AllAvg(object):
def __init__(self):
pass
@staticmethod
def main():
res = 0
ls = []
while 1:
num = input('더할 수를 입력 (0 입력 시 종료) ->')
if num == '0':
break
else:
ls.append(num)
for i in ls:
res += int(i)
print(f'{res/len(ls)}')
AllAvg.main()
|
c45411686f718da72193c21419c52e94ab639716 | cloudwiki/learnPython | /class_generator_8_queens.py | 1,347 | 3.625 | 4 | __metaclass__ = type
def conflict(state, nextX):
nextY = len(state)
for i in range(nextY):
#Every element in state and its index represent the position in the table.
#e.g. state(0)=1, means the queue's position is at cell(1,0). index is for Y axis, value is for X axis
#the expression represents
#if the nextX are equals to any existing queue's X(state(i)), then conflict occur
#if the distance on Y axis(state(i) - nextX) equals to the distance on X axis(nextY - i), then conflict occurs
if abs(state[i] - nextX) in (0, nextY-i):
return True
return False
def queen(num, state=()):
for i in range(num):
if not conflict(state, i): #valid position found
if len(state) == num - 1:
yield (i,)
else:
for result in queen(num, state + (i,)):
yield (i,) + result
def prettyPrint(state):
length = len(state)
for i in range(length):
print '.' * (state[i]) +repr(state[i])+ '.'* (length - state[i]-1)
queen4 = queen(4)
state = queen4.next()
print state
prettyPrint(state)
prettyPrint(state)
#print list(queen(10))
queen10 = queen(10)
state1 = queen10.next()
print state1+
prettyPrint(state1)
|
d352e9025b496ce99ba87a9e8b66916464230442 | dodomorandi/hatspil | /hatspil/reports/report_table.py | 7,207 | 3.53125 | 4 | """An abstraction layer to handle tables in a report.
Reports need some HTML, therefore an abstraction layer is extremely
useful to create and customize a table before the HTML code is
generated.
This module contains some classes that ease the process.
"""
from collections import OrderedDict
from enum import Enum
from typing import (Any, Callable, Iterable, List, MutableMapping, Optional,
Sequence, Union)
class ReportTableSortingType(Enum):
"""The sorting of a table column."""
ASCENDING = "asc"
DESCENDING = "des"
class ReportTableColumnOrdering:
"""Helper class to store the sorting for a specific table column."""
def __init__(self, column_index: int, sorting_type: ReportTableSortingType) -> None:
"""Create an instance of the class."""
self.column_index = column_index
self.sorting_type = sorting_type
def html(self) -> str:
"""Create the configuration string to put inside the HTML."""
return '[{}, "{}"]'.format(self.column_index, self.sorting_type.value)
class ReportTable:
"""A helper class to handle a table inside a report."""
Entry = Union[str, int, float, bool]
# This is an OrderedDict, but the annotation is not accepted in Python 3.6
columns: MutableMapping[str, List[Entry]]
def __init__(self, html_id: str, *column_names: str) -> None:
"""Create an instance of the class.
Args:
html_id: the 'id' of the html table that will be created.
column_names: the name for each column that will be created
in the table.
"""
self.html_id = html_id
self._order: Optional[List[ReportTableColumnOrdering]] = None
self._row_modifier: Optional[
Callable[[MutableMapping[str, ReportTable.Entry]], str]
] = None
self._table_class: Optional[str] = None
self.style: Optional[str] = None
self.set_columns(column_names)
def set_columns(self, column_names: Iterable[str]) -> None:
"""Set the name of the columns.
This function overrides any previous names, therefore it is a
good idea to call this function once per instance.
"""
self.columns: MutableMapping[str, ReportTable.Entry] = OrderedDict()
for column_name in column_names:
self.columns[column_name] = []
def add_row(self, row: Sequence[Entry]) -> None:
"""Add a row to the table.
The number of elements in the row must be the same as the length
of the columns. It is necessary to call
`ReportTable.set_columns` beforehand to perform a useful
operation.
Args:
row: a sequence of entries. Each entry can be a str, an int,
a float or a bool.
"""
assert all(map(lambda column: column is not None, self.columns.values()))
assert len(row) == len(self.columns)
for column, entry in zip(self.columns.values(), row):
column.append(entry)
@property
def order(self) -> Optional[List[ReportTableColumnOrdering]]:
"""Get the order of the columns.
The value is set using `ReportTable.set_order`.
"""
return self._order
def set_order(
self,
order: Union[Iterable[ReportTableColumnOrdering], ReportTableColumnOrdering],
) -> None:
"""Set the order of the columns.
The arguments will be always converted into a list of ordering
elements.
Args:
order: a single column ordering or an iterable of column
ordering objects. In both cases a list is saved
internally.
"""
if isinstance(order, ReportTableColumnOrdering):
self._order = [order]
else:
self._order = list(order)
if not self._order:
self._order = None
@property
def row_modifier(self) -> Optional[Callable[[MutableMapping[str, Entry]], str]]:
"""Get the row modifier function, if any.
See the documentation of the setter for more information.
"""
return self._row_modifier
@row_modifier.setter
def row_modifier(
self, modifier: Optional[Callable[[MutableMapping[str, Entry]], str]]
) -> None:
"""Set the row modifier function.
The `modifier` function is used to add some HTML properties to
each 'tr' element depending on the content of the row. This is
mostly useful to change the style of the row when one or more
properties have interesting values.
"""
self._row_modifier = modifier
@property
def table_class(self) -> Optional[str]:
"""Get the table HTML class."""
return self._table_class
@table_class.setter
def table_class(self, table_class: Optional[str]) -> None:
"""Set the table HTML class."""
self._table_class = table_class
def html(self) -> str:
"""Create the HTML representation of the table.
In case no columns have been set, an empty str is returned.
"""
if not self.columns:
return ""
def default_row_modifier(_: Any) -> str:
return ""
if self._row_modifier:
row_modifier = self._row_modifier
else:
row_modifier = default_row_modifier
html_rows: List[str] = []
if self.columns:
first_column_len = len(next(iter(self.columns.values())))
assert all(
map(
lambda column: len(column) == first_column_len,
self.columns.values(),
)
)
for row_index in range(len(next(iter(self.columns.values())))):
row = self._get_row(row_index)
html_rows.append(
"<tr{}>{}</tr>".format(
row_modifier(row),
"".join(f"<td>{value}</td>" for value in row.values()),
)
)
return (
'<table id="{}"{}>'
"<thead><tr>{}</tr></thead>"
"{}</table>"
"<script>$(document).ready( function () {{"
"$('#{}').DataTable({});"
"}} );"
"</script>"
).format(
self.html_id,
f' class="{self.table_class}"' if self.table_class else "",
"".join([f"<th>{col_name}</th>" for col_name in self.columns.keys()]),
"".join(html_rows),
self.html_id,
"{{'order': [{}]}}".format(
",".join([order.html() for order in self._order])
)
if self._order
else "",
)
def _get_row(self, row_index: int) -> MutableMapping[str, Entry]:
assert self.columns
assert row_index >= 0
assert row_index < len(next(iter(self.columns.values())))
row_content: MutableMapping[str, ReportTable.Entry] = OrderedDict()
for col_name, entries in self.columns.items():
row_content[col_name] = entries[row_index]
return row_content
assert row_index < len(self.columns)
|
93228a077666cb8189480f29a59d84c2c4876b18 | gmayank32/SklearnTutorialWorkspace | /skeletons/exercise_02_sentiment.py | 3,551 | 3.53125 | 4 | """Build a sentiment analysis / polarity model
Sentiment analysis can be casted as a binary text classification problem,
that is fitting a linear classifier on features extracted from the text
of the user messages so as to guess wether the opinion of the author is
positive or negative.
In this examples we will use a movie review dataset.
"""
# Author: Olivier Grisel <olivier.grisel@ensta.org>
# License: Simplified BSD
import sys
import numpy as np
from os.path import isdir,join
from os import listdir
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_files
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.linear_model import SGDClassifier
import pandas as pd
from os import *
if __name__ == "__main__":
# NOTE: we put the following in a 'if __name__ == "__main__"' protected
# block to be able to use a multi-core grid search that also works under
# Windows, see: http://docs.python.org/library/multiprocessing.html#windows
# The multiprocessing module is used as the backend of joblib.Parallel
# that is used when n_jobs != 1 in GridSearchCV
# the training data folder must be passed as first argument
movie_reviews_data_folder = 'moviesreview'
dataset = load_files(movie_reviews_data_folder, shuffle=True, \
load_content=True, encoding = "UTF-8")
print("n_samples: %d" % len(dataset.data))
# split the dataset in training and test set:
docs_train, docs_test, y_train, y_test = train_test_split(
dataset.data, dataset.target, test_size=0.25, random_state=None)
# TASK: Build a vectorizer / classifier pipeline that filters out tokens
# that are too rare or too frequent
linear_model = ('lsvc', LinearSVC(penalty='l2', loss='hinge',random_state=41, max_iter=50))
SGDClassifier_model = ('sgdc', SGDClassifier(penalty='l2', loss='hinge',random_state=41, n_iter=100))
clf = Pipeline([
('tfidf', TfidfVectorizer()),
SGDClassifier_model
])
text_clf = clf.fit(docs_train, y_train)
# TASK: Build a grid search to find out whether unigrams or bigrams are
# more useful.
# Fit the pipeline on the training set using grid search for the parameters
parameters = { 'tfidf__ngram_range':[(1, 1), (1,2)],
'tfidf__use_idf':[True, False],
'sgdc__alpha': [1e-03, 1e-02, 1e-01, 1, 10, 1e02]
#'lsvc__C': (1e-03, 1e-01, 1, 10, 1e02)
}
gs_clf = GridSearchCV(clf, parameters, n_jobs = -1, verbose = 100000)
gs_clf = gs_clf.fit(docs_train, y_train)
# TASK: print the cross-validated scores for the each parameters set
# explored by the grid search
print gs_clf.best_score_
for param_name in sorted(parameters.keys()):
print(param_name, gs_clf.best_params_[param_name])
# TASK: Predict the outcome on the testing set and store it in a variable
# named y_predicted
y_predicted = gs_clf.predict(docs_test)
# Print the classification report
print(metrics.classification_report(y_test, y_predicted,
target_names=dataset.target_names))
# Print and plot the confusion matrix
cm = metrics.confusion_matrix(y_test, y_predicted)
print(cm)
import matplotlib.pyplot as plt
plt.matshow(cm)
plt.show()
|
3e5e11a8ca59974cce5523a2ba0ad5b714e1c4dc | EduardoCastro15/Compiladores | /Practicas/PracticaOpcional/Final.py | 8,996 | 3.890625 | 4 | from Automata import *
import Thompson
#función para crea tuplas que guardan las transiciones del archivo
def tres(transiciones):
Aux = [] #Lista auxiliar
anterior = 0 #Badera auxiliar
for i in range(0,int(len(transiciones)/3)): #Ciclo del numero de transacciones entre 3
siguiente = (i+1)*3 #Calculamos el valor del siguiente
Aux.append(transiciones[anterior:siguiente]) #Agregamos al final de la lista los items dentro del rango anterior y siguiente de las transacciones
anterior = siguiente #Igualamos ambas variables auxiliares
return Aux #Retornamos la lista auxiliar
#Función que convierte todas las cadenas de una lista en enteros
def convertir(cadena):
Aux = [] #Lista auxiliar
for i in range(0,len(cadena)): #Ciclo del numero de la cadena
Aux.append(int(cadena[i])) #Agregamos al final de la lista la cadena convertida a entero
return Aux #Retronamos la lista auxiliar
#Función que crea una lista separando una cadena
def get_elementos(cadena):
i = 0 #Reinicio del contador
j = 0 #Reinicio del contador
elementos = [] #Lista auxiliar
while i <= len(cadena): #Ciclo dependiente del tamaño de la cadena
if i == len(cadena) or cadena[i] == ',' or cadena[i] == '\n': #Si llega al final de la cadena, o si encuentra una coma o un salto de linea
elementos.append(cadena[j:i]) #Guarda todo lo anterior en un item de la lista auxiliar
i += 1 #Incrementamos el contador
j = i #Igualamos el contador
i+=1 #Incrementamos el contador
return elementos #Retornamos la lista auxiliar
#Función que crea una nueva lista, usando como delimitador un salto de linea
def get_lista(inicial,cadena):
i = inicial #Igualamos el contador
while cadena[i] != '\n': #Ciclo dependiente de encontrar un salto de linea
i += 1 #Incrementamos el contador
return cadena[inicial:i] #Retornamos la lista con el rango indicado
#Función main
if __name__ == "__main__":
f = open('Thompson2.txt','r') #Abrimos el archivo del AF
contenido = f.read() #Procedemos a leer el AF
i = 0 #Contador del renglón
estados = get_lista(i,contenido) #Creamos una lista con los estados del AF
i += (len(estados) + 1) #Incrementamos el contador de renglónes
simbolos = get_lista(i,contenido) #Creamos una lista con los simbolos del AF
i += (len(simbolos) + 1) #Incrementamos el contador de renglónes
inicial = get_lista(i,contenido) #Creamos una lista con el estado inicial del AF
i += (len(inicial) + 1) #Incrementamos el contador de renglónes
final = get_lista(i,contenido) #Creamos una lista con el estado final del AF
i += (len(final) + 1) #Incrementamos el contador de renglónes
transiciones = contenido[i:len(contenido)] #Creamos una lista con las transiciones del AF
estados = convertir(get_elementos(estados)) #Separamos los items de la lista y los convertimos las cadenas en enteros
simbolos = get_elementos(simbolos) #Separamos los items de la lista
inicial = convertir(get_elementos(inicial)) #Separamos los items de la lista y los convertimos las cadenas en enteros
final = convertir(get_elementos(final)) #Separamos los items de la lista y los convertimos las cadenas en enteros
transiciones = tres(get_elementos(transiciones)) #Separamos los items de la lista y los convertimos las cadenas en tuplas
estados.append(-1) #Agregamos un estado al final de la lista -1
if len(inicial) > 1: #Comprobamos que solo exista un único estado inicial
print("\nSolo puede haber un estado inicial...") #Mensaje de error
exit() #Fin del programa
nodos = [] #Lista de nodos
i = 0 #Reinicio del contador
for i in range(0,len(estados)): #Ciclo del número de estados
primero = False #Bandera indicadora del estado inicial
ultimo = False #Bandera indicadora del estado final
if estados[i] in inicial: #Comprobamos si el estado actual es el inicial
primero = True #Bandera verdadera
if estados[i] in final: #Comprobamos si el estado actual es el final
ultimo = True #Bandera verdadera
nodos.append(Estado(estados[i],primero,ultimo)) #Creamos objeto nuevo dentro de lista nodos
i = 0 #Reinicio del contador
for i in range(0,len(transiciones)): #Ciclo del número de transiciones
Aux = posicion(nodos,transiciones[i][0]) #Obtenemos la posicion de la transición en la lista de nodos
if Aux != -1: #Si se logró encontrar la transición buscada
Aux2 = posicion(nodos,transiciones[i][2]) #Obtenemos la posicion de la transición en la lista de nodos
if Aux2 != -1: #Si se logró encontrar la transición buscada
nodos[Aux].agregar_transicion(transiciones[i][1],Aux2) #Mediante el método del objeto, agregamos las transiciones validadas
i = 0 #Reinicio del contador
for i in range(0,len(nodos)): #Ciclo del número de nodos
Aux = completar(simbolos,simbolos_transitivos(nodos[i],simbolos)) #Extraemos los simbolos de transición y los completamos
j = 0 #Reinicio del contador
for j in range(0,len(Aux)): #Ciclo del número de transiciones no validas
nodos[i].agregar_transicion(Aux[j],estados.index(-1)) #Mediante el método del objeto, agregamos las transiciones no validas
print("\n __________Tabla de formalizada de relaciones__________") #Titulo de la tabla
imprimir_tabla(nodos,simbolos) #Imprimimos tabla formalizada de relaciones
Nuevos_estados = [] #Lista de nuevos estados
estados_alcanzables = [str(estados[inicial[0]])] #Lista de estados alcanzables con el estado inicial
estados_alcanzables += Thompson.Cerradura_E(transiciones,str(estados[inicial[0]])) #Agregamos los estados alcanzables aplicando la cerradura épsilon
Nuevos_estados.append(Thompson.Estado_AFD('A',estados_alcanzables,0)) #Ya tenemos los nuevos estados alcanzables iniciales, y pertenecen al grupo A
bandera = 1 #Bandera axiliar
while bandera != 0: #Ciclo dependiente de la bandera
bandera = 0 #Cambio de la bandera
i = 0 #Reinicio del contador
for i in range(0,len(Nuevos_estados)): #Ciclo del número de nuevos estados
j = 0 #Reinicio del contador
for j in range(0,len(simbolos)): #Ciclo del número de simbolos
estados_alcanzables = Thompson.Ir_a(transiciones,simbolos[j],Nuevos_estados[i]) #Modificamos la lista aplicando la función Ir_a
if Thompson.analisis(Nuevos_estados,estados_alcanzables): #Analizamos comparando los nuevos estados y los estados alcanzables, si son iguales
letra = chr(ord(Nuevos_estados[len(Nuevos_estados) - 1].simbolo) + 1) #Obtenemos la letra del siguiente grupo de estados
if Thompson.final(final,estados_alcanzables,estados):
Nuevos_estados.append(Thompson.Estado_AFD(letra,estados_alcanzables,2)) #Ya tenemos los nuevos estados alcanzables finales
else:
Nuevos_estados.append(Thompson.Estado_AFD(letra,estados_alcanzables,1)) #Ya tenemos los nuevos estados alcanzables normales
bandera += 1 #Activamos la bandera para repetir el ciclo
N_trancisiones = Thompson.crear_trancisiones(Nuevos_estados,transiciones,simbolos) #Calculamos el número de transiciones
N_final = [] #Lista de nodos finales
N_estados = [] #Lista de número de estados
i = 0 #Reinicio del contador
for i in range(0,len(Nuevos_estados)): #Ciclo del número de nuevos estados
if Nuevos_estados[i].inicial: #Si el estado actual es inicial
N_inicial = [i] #Se crea una lista del tamaño del contador
if Nuevos_estados[i].final: #Si el estado actual es final
N_final += [i] #Se incrementa la lista del tamaño del contador
N_estados += [Nuevos_estados[i].simbolo] #Se incrementa la lista del tamaño del simbolo
Nuevos_estados.append(Thompson.Estado_AFD("-1",[],1)) #Creamos un nuevo objeto al final de la lista de nuevos estados
N_estados.append("-1") #Agregamos un -1 al final de la lista
i = 0 #Reinicio del contador
for i in range(0,len(N_trancisiones)): #Ciclo del número de transiciones
Aux = Thompson.posicion(Nuevos_estados,N_trancisiones[i][0]) #Obtenemos la posicion de la transición en la lista de nodos
if Aux != -1: #Si se logró encontrar la transición buscada
Aux2 = Thompson.posicion(Nuevos_estados,N_trancisiones[i][2]) #Obtenemos la posicion de la transición en la lista de nodos
if Aux2 != -1: #Si se logró encontrar la transición buscada
Nuevos_estados[Aux].agregar_transicion(N_trancisiones[i][1],Aux2) #Mediante el método del objeto, agregamos las transiciones validadas
i = 0 #Reinicio del contador
for i in range(0,len(Nuevos_estados)): #Ciclo del número de nuevos estados
Aux = Thompson.completar(simbolos,Thompson.simbolos_transitivos(Nuevos_estados[i],simbolos)) #Extraemos los simbolos de transición y los completamos
j = 0 #Reinicio del contador
for j in range(0,len(Aux)): #Ciclo del número de transiciones no validas
Nuevos_estados[i].agregar_transicion(Aux[j],N_estados.index("-1")) #Mediante el método del objeto, agregamos las transiciones no validas
print("\n\n __________Tabla de simplificada de transicciones__________\n") #Titulo de la tabla
Thompson.imprimir_tabla_nueva(Nuevos_estados,simbolos) #Imprimimos la tabla simplificada de transacciones
|
68fcee641d98c5364551e28cb08b4adbcc3eb772 | waallf/bishi_ | /1/5.py | 821 | 3.5625 | 4 | line = input()
# line = "1-8/3+1"
fuhao = ("+","-","*","/")
def yunsuan(a,b,c):
if c == "+":
return a+b
if c == "-":
return b-a
if c == "*":
return a*b
if c == "/":
return b/a
fuzhan = ["#"]
shuzhan = []
all = int(line[0])
for i in line:
if i in fuhao:
if ((i == "*" or i == "/") and fuzhan[-1] !="#") or ((i == "+" or i == "-") and (fuzhan[-1]== "+" or fuzhan[-1]== "-")):
yusuan = fuzhan.pop()
all= yunsuan(float(shuzhan.pop()),float(shuzhan.pop()),yusuan)
fuzhan.append(i)
shuzhan.append(all)
else:
fuzhan.append(i)
else:
shuzhan.append(i)
while fuzhan[-1] != "#":
all= yunsuan(float(shuzhan.pop()),float(shuzhan.pop()),fuzhan.pop())
shuzhan.append(all)
print(int(all)) |
43eb8cab392f0af1963cb32b5736d64a5c45ef8f | jjgecon/Personal_coding_projects | /MATLAB Intro/Sollow.py | 2,319 | 3.671875 | 4 | # Code by Javier Gonzalez on December 2019
# For any questions please contact javierj.g18@gmail.com
# Simple Sollow Model with graphs
import numpy as np
import matplotlib.pyplot as plt
# Set time period and grid space
T,n = 1, 100
# Capital Grid
k = np.linspace(0,T,n)
# Set the functions
def production(k, alpha = 0.5,A=1):
""" This function will define the production process"""
return A*k**alpha
def savings(Prod, beta = 0.4):
return beta*Prod
def depreciation(k,delta = 0.1):
return (1-delta)*k
#Set lists
product_savings = []
product = []
product_savings_prime = []
product_prime = []
depreciationlist = []
# For loop to fill the lists
for i in k:
product.append(production(i))
product_savings.append(savings(production(i)))
product_prime.append(production(i,A=1.5)) # Here we change the Technology
product_savings_prime.append(savings(production(i,A=1.5)))
depreciationlist.append(depreciation(i))
# Last Checks
kss = []
tol = 0.0025 # Tolerance level to 1 SS
for i in k:
if i == 0:
a1 = 0
a2 = 0
if abs(savings(production(i)) - depreciation(i)) <= tol and savings(production(i)) != 0:
print(f'Steady State at {i:.2f} capital with A = 1')
print(f'Production Level at {production(i):.2f} with A = 1')
a1 += 1
kss.append(i) #used for graphing purposes
if abs(savings(production(i,A=1.5)) - depreciation(i)) <= tol and savings(production(i)) != 0:
print(f'Steady State at {i:.2f} capital with A = 1.5')
print(f'Production Level at {production(i):.2f} with A = 1.5')
a2 += 1
kss.append(i) #used for graphing purposes
if a1 == 0:
print('No Steady State for A = 1')
if a2 == 0:
print('No Steady State for A = 1.5')
# Graph
colors = ['g','y']
fig, ax = plt.subplots(figsize=(10, 6))
zoom = 1 #0.5 for a better zoom
plt.axis([0, zoom, 0, zoom]) #Change this for a better zoom on the SS
ax.plot(k,product,'--k')
ax.plot(k,product_savings,'k',label='Savings with A = 1')
ax.plot(k,product_prime,'--b')
ax.plot(k,product_savings_prime,'b',label='Savings with A = 1.5')
ax.plot(k,depreciationlist,'r',label='Depreciation')
for i,color in zip(kss,colors):
line = []
b = np.linspace(0,8,n)
for e in k:
line.append(i)
ax.plot(line,b,color, alpha=0.2)
plt.legend()
plt.show() |
79fda46293cd0e4507776b9a56fdbee2181acfc7 | goodwjsphone/WilliamG-Yr12 | /pygmae/balls.py | 2,030 | 3.984375 | 4 | #Import libaries
import pygame
import math
import random
# Difine colours
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
WHITE = (0,0,0)
#initialise pygame
pygame.init()
# set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width,screen_height])
#used to manage how fast the screen updates
clock = pygame.time.Clock()
# dfine the class ball
class Ball():
#contsutcot function to define inital state of a ball object
def __init__(self,x,y,col,x_speed,y_speed):
#---class attributes---
#ball position
self.x = x
self.y = y
# ball vecotr
self.change_x = x_speed
self.change_y = y_speed
#Ball colour
self.color = col
#Ball size
self.size = 5
# --- Class Methods ---
# Dfines the balls movement
def move(self):
self.x += self.change_x
self.y += self.change_y
if self.x <0 + self.size or self.x > 700 - self.size:
self.change_x *= -1
if self.y <0 + self.size or self.y > 400 - self.size:
self.change_y *= -1
# Draws the ball on the screen
def draw(self,screen):
pygame.draw.circle(screen,self.color,[self.x,self.y],self.size)
# set game loop ot false so it runs
done = False
#create an object using the ball class
theBall = Ball(100,100,RED,2,1)
theBall2 = Ball(50,100,RED,2,1)
my_balls = []
for i in range (1000):
theBallx = Ball(random.randint(0,399),random.randint(0,699),RED,2,1)
my_balls.append(theBallx)
#game loop
while not done:
#clear the screen
screen.fill(WHITE)
#Draw the ball on the screen and then move it on
theBall.draw(screen)
theBall.move()
theBall2.draw(screen)
theBall2.move()
for b in my_balls:
b.draw(screen)
b.move()
# frame speed
clock.tick(999)
# update the screen with drawing
pygame.display.flip()
pygame.quit
|
fd73641925aa29814156330883df9d132dbcb802 | goodwjsphone/WilliamG-Yr12 | /ACS Prog Tasks/04-Comparision of two.py | 296 | 4.21875 | 4 | #write a program which takes two numbers and output them with the greatest first.
num1 = int(input("Input first number "))
num2 = int(input("Input second number "))
if num1 > num2:
print (num1)
else:
print(num2)
## ACS - You need a comment to show where the end of the if statement is.
|
82d97c5675e99633b6b63b7d525822bbd3882bb0 | zarkaltair/Learn-python | /Tasks by MFTI/tasks to module #3.py | 279 | 3.5 | 4 | def min(x, y):
if x <= y:
return x
else:
return y
def sum(x):
res = 0
for i in range(x):
res += i
return res
def print_nums(x):
for i in range(x):
print(i)
return
print_nums(10)
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(4))
|
40e1eaceaa0f5cb8111b5ace4ac79664026c1a32 | zarkaltair/Learn-python | /Lessons by HoudyHo/lesson (31).py | 1,571 | 4.03125 | 4 | # Модуль itertools стандартная библиотека, один тип функций в этой библиотеке это бесконечные итераторы
from itertools import count # count выводит все элементы в соответствии с заданными параметрами
for i in count(3):
print(i)
if i >= 11:
break
from itertools import accumulate, takewhile
nums = list(accumulate(range(8))) # accumulate выводит последовательную сумму всех элемнтов
print(nums)
print(list(takewhile(lambda x: x <= 6, nums))) # takewhile выводит (циклически) значения
from itertools import takewhile
nums = [2, 4, 6, 7, 9, 8]
a = takewhile(lambda x: x % 2 == 0, nums) # print[2, 4, 6] цифра 8 не входит в заданный диапазон, потому что цикл прерывается на цифре 7 (цикл выдает False и прерывается)
print(list(a))
from itertools import product, permutations
letters = ('A', 'B')
print(list(product(letters, range(2)))) # product комбинирует све заданные значния в соответствии с заданными условиями
print(list(permutations(letters))) # permutations комбинирует все заданные значения между собой
from itertools import product
a = {1, 2}
print(len(list(product(range(3), a))))
|
72d30c71a2db05c7d7bc10a83c3c5dc644d2a83b | zarkaltair/Learn-python | /Lessons by HoudyHo/lesson (18).py | 1,230 | 3.765625 | 4 | test = None
if(test == None):
print(test)
foo = print()
if foo == None:
print(1)
else:
print(2)
# Dictionary - Словарь
test = {
'ключ1':'значение1',
'ключ2':'значение2',
}
try:
print(test['тестовый_ключ'])
except KeyError:
print('Такого ключа не существует!')
test = {
'ключ1':'значение1',
125:'сто двадцать пять',
}
if 125 in test:
print('exist')
else:
print('not exist')
primes = {1:2,2:3,4:7,7:17}
print(primes[primes[4]])
contacts = {
'Андрей Змеевский':'+153654665132',
'Никита Хогвартс' :'+265465416351',
'Роман Таненбаум' :'+151635415513'
}
testing = input('Кого ишем?: ')
if testing in contacts:
print('Контакт найден, номер телефона: '+contacts[testing])
else:
print('Контакт не найден!')
contacts = {
'Андрей Змеевский':'+153654665132',
'Никита Хогвартс' :'+265465416351',
'Роман Таненбаум' :'+151635415513'
}
print(contacts.get('Никита Хогвартс','Номер не найден!'))
contacts = {
'Андрей Змеевский':'+153654665132',
'Никита Хогвартс' :'+265465416351',
'Роман Таненбаум' :'+151635415513'
}
print(contacts.get('Даша Шармбатон','Номер не найден!'))
fib = {1:1,
2:1,
3:2,
4:3
}
print(fib.get(4,0)+fib.get(7,5))
|
640ca5a2d92ab891850b77b0ca823a67875827af | zarkaltair/Learn-python | /Lessons by HoudyHo/lesson (16).py | 771 | 4 | 4 | def exc(text):
assert text!=''
print(str(text)+'!')
exc('Hi')
def test(number):
assert number>0, 'Number should be bigger than 0.'
print(str(number))
test(10)
file=open('test.txt','r')
print(file.read())
file.close()
filename = input('Укажите файл?: ')
file = open(filename,'r')
print('В данном файле '+str(len(file.read()))+' символов')
file.close()
file = open('test.txt','w')
file.write('Hello world!')
file.close()
filename = input('Введите имя файла: ')
text = input('Введите текст: ')
file = open(filename,'w')
file.write(text)
file.close()
file = open('test.txt','a')
file.write(' It is.')
file.close()
file = open('somefile.txt','r')
for i in range(21):
print(file.read(8))
file.close()
|
4074745536d1e72f684c66b59a50d73e06c192c1 | zarkaltair/Learn-python | /Lessons by HoudyHo/lesson (9).py | 126 | 3.828125 | 4 | number = 0
while number <= 10:
number +=1
if (number % 2) != 0:
continue;
print('Четное число ' + str(number)) |
cd1a1d0e5e8a812f8807e38617b0209b439526ba | zarkaltair/Learn-python | /Lessons by HoudyHo/lesson (4).py | 828 | 3.953125 | 4 | a = input('Введите первое число : ')
b = input('Введите второе число : ')
print(int(a) + int(b))
print(str(1) + '2' + str(3) + '4')
name = input('Enter your name: ')
count = input('How many?: ')
print(name*int(count))
pogoda = 'Зима'
time = 'День'
print( 'Программа запущена.' )
if pogoda == 'Зима':
print( 'Сейчас холодная погода, лучше никуда не идти!' )
if time == 'Ночь':
print( 'Сейчас еще и ночь, ты псих вообще?' )
if time == 'День':
print( 'Сейчас конечно день, но холодно как...' )
if pogoda == 'Дождь':
print( 'Ууу ... Сейчас дождик, ты блин промокнешь!' )
print( 'Программа завершена.' ) |
ae0d80dd8205cf6e4e2a4e8fe376fcb73a85ec10 | olcplif/python-hw | /#15_Argument_parser/Task_1.py | 1,444 | 3.75 | 4 | # 1. Написати програму яка буде зберігати username і email в файл json.
# При наявності користувачів перед тим як додати юзера програма повинна перевірити чи не існує на данний момент
# користувача з таким username і email, якщо існує вивести помилку.
import argparse
import json
class ParsErrorUsername(Exception):
pass
class ParsErrorEmail(Exception):
pass
parser = argparse.ArgumentParser()
parser.add_argument("--username", help="Enter username")
parser.add_argument("--email", help="Enter email")
args = parser.parse_args()
user_dict = {}
if args.username:
user_dict['username'] = args.username
if args.email:
user_dict['email'] = args.email
user_file = open('users.json', 'r')
users_data = json.loads(user_file.readline())
user_file.close()
# TODO: Maybe to use the function
try:
for user in users_data:
if user['username'] == user_dict['username']:
raise ParsErrorUsername
elif user['email'] == user_dict['email']:
raise ParsErrorEmail
users_data.append(user_dict)
except ParsErrorUsername:
print("Such a username is present")
except ParsErrorEmail:
print("Such a email is present")
user_file = open('users.json', 'w')
user_file.write(json.dumps(users_data))
user_file.close()
|
a504de158456b0ed73810de157595638f3bb6236 | olcplif/python-hw | /hw#11_Testing/calc_unitests/calc.py | 3,692 | 3.859375 | 4 |
class Calc:
@staticmethod
def sum(a: int, b: int) -> int:
""" Шукає суму двох чисел
>>> Calc.sum(4, 5)
9
Використовуючи формулу a + b
:param a: перший доданок, може бути int або float
:param b: другий доданок, може бути int або float
:return: сума доданків, може бути int або float залежно від параметрів
"""
return a + b
@staticmethod
def minus(a: int, b: int) -> int:
""" Шукає різницю двох чисел
>>> Calc.minus(5, 4)
1
Використовуючи формулу a - b
:param a: перший від'ємник, може бути int або float
:param b: другий від'ємник, може бути int або float
:return: різниця від'ємників, може бути int або float залежно від параметрів
"""
return a - b
@staticmethod
def mul(a: int, b: int) -> int:
""" Шукає добуток двох чисел
>>> Calc.mul(3, -4)
-12
Використовуючи формулу a * b
:param a: множене, може бути int або float
:param b: множник, може бути int або float
:return: добуток, може бути int або float залежно від параметрів
"""
return a * b
@staticmethod
def div(a: int, b: int) -> float:
""" Шукає частку двох чисел
>>> Calc.div(-4, -2)
2.0
Використовуючи формулу a / b
:param a: ділене, може бути int або float
:param b: дільник, може бути int або float
:return: частка, може бути тільки float
"""
return a / b
@staticmethod
def percent(a: int, b: int) -> float:
""" Шукає процент від числа
>>> Calc.percent(20, 50)
10.0
Використовуючи формулу a / 100 * b
:param a: число, з якого визначається відсоток, може бути int або float
:param b: шуканий відсоток, може бути int або float
:return: відсоток від числа, може бути тільки float
"""
return a / 100 * b
@staticmethod
def pow(a: int, b: int) -> int:
""" Шукає степінь числа
>>> Calc.pow(3, 2)
9
Використовуючи формулу a ** b
:param a: число, яке підноситься до степеню, може бути int або float
:param b: степінь, може бути int або float
:return: число піднесене до степеня, може бути int або float
"""
return a ** b
@staticmethod
def root(a: int, b=2) -> float:
""" Шукає корінь числа
>>> Calc.root(9, 2)
3.0
Використовуючи формулу a ** (1 / b)
:param a: число, з якого шукається корінь, може бути int або float
:param b: степінь кореня (по замовчуванню - квадратний корінь), може бути int
:return: корінь числа, може бути тільки float
"""
return a ** (1 / b)
|
547d80458ccdd2ae094da776e14344e26b9e8a59 | Cooler5339/homework_alevel | /lesson 3 (ATM V2).py | 296 | 3.75 | 4 | money = int(input('Withdrawal amount:'))
banknotes = [50,100,200,500,1000]
for i in banknotes:
if money >= 0:
change = money // i
money -= change * i
if change != 0:
print ('Get your money!:'+str(change)+'*'+str(i)+'$')
else:
print ('GoodBye! See later!') |
662d78c93d5033e86f181c7d1bd1d4ad59fc2814 | Cooler5339/homework_alevel | /Lesson 6(Students_Grades).py | 470 | 3.78125 | 4 |
std = {'Alex': 51, 'Bob': 66, 'Jango': 87, 'James': 87}
n = std.keys()
n = len(n)
point = sum(std.values())
avrg_grades = point / n
print("Средний балл студентов: " + str(int(avrg_grades)))
print('Студенты с баллом выше среднего: ')
for i in std:
if std[i] > avrg_grades:
print(i)
print("Студенты с баллом ниже среднего:")
for i in std:
if std[i] < avrg_grades:
print(i)
|
22f107c9e4ce076b6c85487a69afddf89078e389 | rahmatmaftuh/numpytutorial | /5manipulasimatrix.py | 620 | 4.0625 | 4 | import numpy as np
a = np.array(([1,2,3],
[4,5,6],
[7,8,9]))
print("matriks a dengan ukuran", a.shape) #cara 1
print("matriks a dengan ukuran", np.shape(a)) #cara 2
#transpose matrix = perubahan baris jadi kolom dan sebaliknya
print("transpose matrix a") #cara 1
print(np.transpose(a)) #cara 2
print(a.T) #cara 3
#flatten array = dijadiin matrix baris
print("flatten matrix a: ")
print(a.ravel())
print(np.ravel(a))
#reshape matrix, ini beda sama transpose
print("reshape matrix a: ")
print(a.reshape(9,1))
#resize matrix
print("resize matrix a: ")
a.resize(3,3)
print(a)
|
f5f9f5d2efbb9b2e1d94f0dc69462e599cb354cc | michaelmiranda1/python | /Michael Miranda Midterm.py | 6,511 | 3.703125 | 4 |
# coding: utf-8
# '''
# PART TWO:
#
# Students choice!
#
# Create a new Jupyter notebook.
# In that notebook, I would like for you to choose a plotting library (matplotlib, bokeh, holoviews, or seaborn)
# and either a data set from the example data sets included with that library or another data set you may find
# of particular interest.
#
# In one or more cells, write a short report about the data set, using Markdown and LaTeX markup as necessary to describe the data, and what a reader might glean from it.
#
# In additional cells, write a short Python program to read in the data set and produce one or more plots from the data.
#
# '''
# In[ ]:
import numpy as np
import holoviews as hv
hv.extension('bokeh')
import bokeh.sampledata
bokeh.sampledata.download()
# This data set has information of four stocks of Apple(AAPL) Google(GOOG), IBM(IBM) and Microsoft(MSFT). This is targeted of getting the information from the date and the adjusted close price. The first graph gives us an indication of the trend over time on how the adjusted close price moved in relation to time since 2000. These are compared to each other. This data would give the reader an indication and an outlook to compare and contrast each other in relation to related to tech stocks. This would try to give a relatable forecast to try to make the best investment for future assets based on historical data.
#
# The tech industry could also provide some data if there is some mutually exclusive data that correlates with each other. Some data will have trends that all stocks will go in an upward motion as an industry as a whole. The data can give an indication as to see if some stocks have a correlation with each other.
#
# The one month average graph's can give an indication as an analytical tool used to identify current price trends and the potential for a change in an established trend.
#
# The moving average (MA) is a simple technical analysis tool that smooths out price data by creating a constantly updated average price. The average is taken over a specific period of time, like 10 days, 20 minutes, 30 weeks or any time period the trader chooses. There are advantages to using a moving average in your trading, as well as options on what type of moving average to use. Moving average strategies are also popular and can be tailored to any time frame, suiting both long-term investors and short-term traders.
#
# A moving average simplifies price data by smoothing it out and creating one flowing line. This makes seeing the trend easier. Exponential moving averages react quicker to price changes than simple moving averages. In some cases, this may be good, and in others, it may cause false signals. Moving averages with a shorter look back period (20 days, for example) will also respond quicker to price changes than an average with a longer look back period (200 days).
#
# Moving average crossovers are a popular strategy for both entries and exits. MAs can also highlight areas of potential support or resistance. While this may appear predictive, moving averages are always based on historical data and simply show the average price over a certain time period.
#
# In[5]:
import numpy as np
from bokeh.layouts import gridplot
from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.stocks import AAPL, GOOG, IBM, MSFT
def datetime(x):
return np.array(x, dtype=np.datetime64)
p1 = figure(x_axis_type="datetime", title="Stock Closing Prices")
p1.grid.grid_line_alpha=0.3
p1.xaxis.axis_label = 'Date'
p1.yaxis.axis_label = 'Price'
p1.line(datetime(AAPL['date']), AAPL['adj_close'], color='#A6CEE3', legend='AAPL')
p1.line(datetime(GOOG['date']), GOOG['adj_close'], color='#B2DF8A', legend='GOOG')
p1.line(datetime(IBM['date']), IBM['adj_close'], color='#33A02C', legend='IBM')
p1.line(datetime(MSFT['date']), MSFT['adj_close'], color='#FB9A99', legend='MSFT')
p1.legend.location = "top_left"
aapl = np.array(AAPL['adj_close'])
aapl_dates = np.array(AAPL['date'], dtype=np.datetime64)
window_size = 30
window = np.ones(window_size)/float(window_size)
aapl_avg = np.convolve(aapl, window, 'same')
p2 = figure(x_axis_type="datetime", title="AAPL One-Month Average")
p2.grid.grid_line_alpha = 0
p2.xaxis.axis_label = 'Date'
p2.yaxis.axis_label = 'Price'
p2.ygrid.band_fill_color = "olive"
p2.ygrid.band_fill_alpha = 0.1
p2.circle(aapl_dates, aapl, size=4, legend='close',
color='darkgrey', alpha=0.2)
p2.line(aapl_dates, aapl_avg, legend='avg', color='navy')
p2.legend.location = "top_left"
goog = np.array(GOOG['adj_close'])
goog_dates = np.array(GOOG['date'], dtype=np.datetime64)
window_size = 30
window = np.ones(window_size)/float(window_size)
goog_avg = np.convolve(goog, window, 'same')
p3 = figure(x_axis_type="datetime", title="GOOG One-Month Average")
p3.grid.grid_line_alpha = 0
p3.xaxis.axis_label = 'Date'
p3.yaxis.axis_label = 'Price'
p3.ygrid.band_fill_color = "olive"
p3.ygrid.band_fill_alpha = 0.1
p3.circle(goog_dates, goog, size=4, legend='close',
color='pink', alpha=0.2)
p3.line(goog_dates, goog_avg, legend='avg', color='orange')
p3.legend.location = "top_left"
ibm = np.array(IBM['adj_close'])
ibm_dates = np.array(IBM['date'], dtype=np.datetime64)
window_size = 30
window = np.ones(window_size)/float(window_size)
ibm_avg = np.convolve(ibm, window, 'same')
p4 = figure(x_axis_type="datetime", title="IBM One-Month Average")
p4.grid.grid_line_alpha = 0
p4.xaxis.axis_label = 'Date'
p4.yaxis.axis_label = 'Price'
p4.ygrid.band_fill_color = "cyan"
p4.ygrid.band_fill_alpha = 0.1
p4.circle(ibm_dates, ibm, size=4, legend='close',
color='green', alpha=0.2)
p4.line(ibm_dates, ibm_avg, legend='avg', color='red')
p4.legend.location = "top_left"
msft = np.array(MSFT['adj_close'])
msft_dates = np.array(MSFT['date'], dtype=np.datetime64)
window_size = 30
window = np.ones(window_size)/float(window_size)
msft_avg = np.convolve(msft, window, 'same')
p5 = figure(x_axis_type="datetime", title="MSFT One-Month Average")
p5.grid.grid_line_alpha = 0
p5.xaxis.axis_label = 'Date'
p5.yaxis.axis_label = 'Price'
p5.ygrid.band_fill_color = "yellow"
p5.ygrid.band_fill_alpha = 0.1
p5.circle(msft_dates, msft, size=4, legend='close',
color='black', alpha=0.2)
p5.line(msft_dates, msft_avg, legend='avg', color='indigo')
p5.legend.location = "top_left"
output_file("stocks.html", title="stocks.py example")
show(gridplot([[p1,p2,p3,p4,p5]], plot_width=400, plot_height=400)) # open a browser
|
0081d5aee1547ad94975bbc294a419c9dff3287e | pavel-stoykov/python_advanced | /Lab_04/03.even_matrix.py | 258 | 3.640625 | 4 | row_counter = int(input())
matrix = [[int(num) for num in input().split(', ')] for row in range(row_counter)]
even_matrix = [[matrix[row][col] for col in range(len(matrix[row])) if matrix[row][col] % 2== 0]for row in range(len(matrix))]
print(even_matrix) |
330f50a9f2ce32dbdd10580fb4f3588c8a649bf8 | pavel-stoykov/python_advanced | /Exercise_05/03.min_max_sum.py | 251 | 4 | 4 | numbers = [int(x) for x in input().split()]
min_num = min(numbers)
max_num = max(numbers)
sum_of_numbers = sum(numbers)
print(f'The minimum number is {min_num}')
print(f'The maximum number is {max_num}')
print(f'The sum number is: {sum_of_numbers}') |
34f204200e558447243cff4744db849206990a37 | pavel-stoykov/python_advanced | /Lab_02/02.average_student_grade.py | 474 | 4.0625 | 4 | number_of_students = int(input())
student_record = {}
for _ in range(number_of_students):
token = input().split()
name = token[0]
grade = float(token[1])
if name not in student_record:
student_record[name] = [grade]
else:
student_record[name].append(grade)
for name, marks in student_record.items():
grades = [''.join(f'{mark:.2f}') for mark in marks]
print(f'{name} -> {" ".join(grades)} (avg: {sum(marks)/ len(marks):.2f})') |
2b9acbe4f5531d940d6ace3940d6f62a37716237 | pavel-stoykov/python_advanced | /EXAM(OLD PROBLEMS)/01.santa_present_factory.py | 1,740 | 3.5625 | 4 | from collections import deque
DOLL = 150
WOODEN_TRAIN = 250
TEDDY_BEAR = 300
BICYCLE = 400
materials = deque(int(x) for x in input().split())
magic_level = deque(int(x) for x in input().split())
gifts = {
'Doll': 0,
'Wooden train': 0,
'Teddy bear': 0,
'Bicycle': 0
}
while materials and magic_level:
total_magic_level = 0
current_materials = materials.pop()
current_magic_level = magic_level.popleft()
total_magic_level = current_materials * current_magic_level
if total_magic_level == DOLL:
gifts['Doll'] += 1
elif total_magic_level == WOODEN_TRAIN:
gifts['Wooden train'] += 1
elif total_magic_level == TEDDY_BEAR:
gifts['Teddy bear'] += 1
elif total_magic_level == BICYCLE:
gifts['Bicycle'] += 1
elif current_magic_level == 0 and current_materials == 0:
continue
elif current_magic_level == 0:
materials.append(current_materials)
continue
elif current_materials == 0:
magic_level.appendleft(current_magic_level)
continue
elif total_magic_level < 0:
materials.append(current_magic_level + current_materials)
elif total_magic_level > 0:
materials.append(current_materials + 15)
if gifts['Doll'] >= 1 and gifts['Wooden train'] >= 1\
or gifts['Teddy bear'] >= 1 and gifts['Bicycle'] >= 1:
print('The presents are crafted! Merry Christmas!')
else:
print('No presents this Christmas!')
if materials:
print(f'Materials left: {", ".join(map(str, materials))}')
if magic_level:
print(f'Magic left: {", ".join(map(str, magic_level))}')
for name, value in sorted(gifts.items()):
if value == 0:
continue
else:
print(f'{name}: {value}')
|
b90d53eecb97b29b7ed1216789795c4e93cf97ff | NiyazHellYeah/Test | /2.1.py | 572 | 4.09375 | 4 | #Создать список и заполнить его элементами различных типов данных.
#Реализовать скрипт проверки типа данных каждого элемента.
#Использовать функцию type() для проверки типа.
#Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
list = [2, 'text', 456, 45.3, None, True]
for i in list:
print(f'Элемент {i} это {type(i)}')
|
f97d622ce56e91169df1810f16702072542cbf8b | paulscottrobson/mz-virtual-machine | /documents/comparison_check.py | 185 | 3.578125 | 4 | def check(b,a):
if b <= a:
print("FFFF")
else:
print("0000")
check(3,2)
check(2,2)
check(2,3)
print("")
check(-3,-2)
check(-2,-2)
check(-2,-3)
print("")
check(2,-2)
check(-2,2) |
a7b9758e30b5b2ef0ae6a43a68671ce37f709c9a | joao-pedro-serenini/recursion_backtracking | /fibonacci_problem.py | 678 | 4.1875 | 4 | def fibonacci_recursion(n):
if n == 0:
return 1
if n == 1:
return 1
return fibonacci_recursion(n-1) + fibonacci_recursion(n-2)
# top-down approach
def fibonacci_memoization(n, table):
if n not in table:
table[n] = fibonacci_memoization(n-1, table) + fibonacci_memoization(n-2, table)
# return table
return table[n]
# bottom-up approach
def fibonacci_tabulation(n, table):
for i in range(2, n+1):
table[i] = table[i-1] + table[i-2]
# return table
return table[n]
# print(fibonacci_recursion(5))
t = {0: 1, 1: 1}
# print(fibonacci_memoization(5, t))
print(fibonacci_tabulation(5, t))
|
523b8d740409e168ec71a85de5ca4b0461f1afa7 | Jinwon777777/Baekjoon-Algorithm | /1920 수 정렬.py | 435 | 3.75 | 4 | def binary_search(a, x):
start = 0
end = len(a)-1
while start <= end:
mid = (start+end)//2
if x == a[mid]:
return 1
elif x > a[mid]:
start = mid + 1
else:
end = mid - 1
return 0
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
a = sorted(a)
for i in range(m):
print(binary_search(a,b[i])) |
a606701ff19aeb87aa7747cd39d40feb826ccb29 | PhyzXeno/python_pro | /transfer_to_x.py | 991 | 4.25 | 4 | # this piece of code will convert strings like "8D4C2404" into "\x8D\x4C\x24\x04"
# which will then be disassembled by capstone and print the machine code
import sys
from capstone import *
# print("the hex string is " + sys.argv[1])
the_str = sys.argv[1]
def x_encode(str):
the_str_len = len(str)
count = 0
the_x_str = r"\x" # \x is not some kind of encodeing. It is an escape character, the fllowing two characters will be interpreted as hex digit
# in order not to escape here, we need raw string to stop character escaping
while 1:
the_x_str = the_x_str + sys.argv[1][count:count+2] + r"\x"
count += 2
if count == the_str_len:
return(the_x_str[:-2].decode("string_escape")) # this will convert raw string into normal string
def x_disassem(str):
CODE = str
# CODE = "\x89\xe5"
# print(type(CODE))
md = Cs(CS_ARCH_X86, CS_MODE_64)
for i in md.disasm(CODE, 0x1000):
print "0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str)
x_disassem(x_encode(the_str))
|
03eb76f8d1e0ed2cc8a90a690bcf2362dd6e2ff8 | makkolli31/DeepLearning | /rnn_raw.py | 8,770 | 4.03125 | 4 | #An attempt at a batched RNNs
#
#I don't think this is an LSTM. What is the difference, exactly? I want to
#know the more complicated functional forms, how to backprop them, and what
#the advantage is.
import numpy as np
import matplotlib.pyplot as plt
class RNNlayer(object):
def __init__(self, x_size, h_size, y_size, learning_rate):
self.h_size = h_size
self.learning_rate = learning_rate#ugh, nightmares
#inputs and internal states for each layer, used during backpropagation
self.x = {}
self.h = {}
self.h_last = np.zeros((h_size, 1))
#x is the input. h is the internal hidden stuff. y is the output.
self.W_xh = np.random.randn(h_size, x_size)*0.01#x -> h
self.W_hh = np.random.randn(h_size, h_size)*0.01#h -> h
self.W_hy = np.random.randn(y_size, h_size)*0.01#h -> y
self.b_h = np.zeros((h_size, 1))#biases
self.b_y = np.zeros((y_size, 1))
#the Adagrad gradient update relies upon having a memory of the sum of squares of dparams
self.adaW_xh = np.zeros((h_size, x_size))#start sums at 0
self.adaW_hh = np.zeros((h_size, h_size))
self.adaW_hy = np.zeros((y_size, h_size))
self.adab_h = np.zeros((h_size, 1))
self.adab_y = np.zeros((y_size, 1))
#given an input, step the internal state and return the output of the network
#Because the whole network is together in one object, I can make it easy and just
#take a list of input ints, transform them to 1-of-k once, and prop everywhere.
#
# Here is a diagram of what's happening. Useful to understand backprop too.
#
# [b_h] [b_y]
# v v
# x -> [W_xh] -> [sum] -> h_raw -> [nonlinearity] -> h -> [W_hy] -> [sum] -> y ... -> [e] -> p
# ^ |
# '----h_next------[W_hh]-----------'
#
def step(self, x):
#load the last state from the last batch in to the beginning of h
#it is necessary to save it outside of h because h is used in backprop
self.h[-1] = self.h_last
self.x = x
y = {}
p = {}#p[t] = the probabilities of next chars given chars passed in at times <=t
for t in range(len(self.x)):#for each moment in time
#self.h[t] = np.maximum(0, np.dot(self.W_xh, self.xhat[t]) + \
# np.dot(self.W_hh, self.h[t-1]) + self.b_h)#ReLU
#find new hidden state in this layer at this time
self.h[t] = np.tanh(np.dot(self.W_xh, self.x[t]) + \
np.dot(self.W_hh, self.h[t-1]) + self.b_h)#tanh
#find unnormalized log probabilities for next chars
y[t] = np.dot(self.W_hy, self.h[t]) + self.b_y#output from this layer is input to the next
p[t] = np.exp(y[t]) / np.sum(np.exp(y[t]))#find probabilities for next chars
#save the last state from this batch for next batch
self.h_last = self.h[len(x)-1]
return y, p
#given the RNN a sequence of correct outputs (seq_length long), use
#them and the internal state to adjust weights
def backprop(self, dy):
#we will need some place to store gradients
dW_xh = np.zeros_like(self.W_xh)
dW_hh = np.zeros_like(self.W_hh)
dW_hy = np.zeros_like(self.W_hy)
db_h = np.zeros_like(self.b_h)
db_y = np.zeros_like(self.b_y)
dh_next = np.zeros((self.h_size, 1))#I think this is the right dimension
dx = {}
for t in reversed(range(len(dy))):
#find updates for y stuff
dW_hy += np.dot(dy[t], self.h[t].T)
db_y += dy[t]
#backprop into h and through nonlinearity
dh = np.dot(self.W_hy.T, dy[t]) + dh_next
dh_raw = (1 - self.h[t]**2)*dh#tanh
#dh_raw = self.h[t][self.h[t] <= 0] = 0#ReLU
#find updates for h stuff
dW_xh += np.dot(dh_raw, self.x[t].T)
dW_hh += np.dot(dh_raw, self.h[t-1].T)
db_h += dh_raw
#save dh_next for subsequent iteration
dh_next = np.dot(self.W_hh.T, dh_raw)
#save the error to propagate to the next layer. Am I doing this correctly?
dx[t] = np.dot(self.W_xh.T, dh_raw)
#clip to mitigate exploding gradients
for dparam in [dW_xh, dW_hh, dW_hy, db_h, db_y]:
dparam = np.clip(dparam, -5, 5)
for t in range(len(dx)):
dx[t] = np.clip(dx[t], -5, 5)
#update RNN parameters according to Adagrad
#yes, it calls by reference, so the actual things do get updated
for param, dparam, adaparam in zip([self.W_hh, self.W_xh, self.W_hy, self.b_h, self.b_y], \
[dW_hh, dW_xh, dW_hy, db_h, db_y], \
[self.adaW_hh, self.adaW_xh, self.adaW_hy, self.adab_h, self.adab_y]):
adaparam += dparam*dparam
param += -self.learning_rate*dparam/np.sqrt(adaparam+1e-8)
return dx
def rnn_raw():
#open a text file
data = open('shakespeare.txt', 'r').read() # should be simple plain text file
chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print('data has %d characters, %d unique.' % (data_size, vocab_size))
#make some dictionaries for encoding and decoding from 1-of-k
char_to_ix = { ch:i for i,ch in enumerate(chars) }
ix_to_char = { i:ch for i,ch in enumerate(chars) }
#num_hid_layers = 3, insize and outsize are len(chars). hidsize is 512 for all layers. learning_rate is 0.1.
rnn1 = RNNlayer(len(chars), 50, 50, 0.001)
rnn2 = RNNlayer(50, 50, 50, 0.001)
rnn3 = RNNlayer(50, 50, len(chars), 0.001)
#iterate over batches of input and target output
seq_length = 25
losses = []
smooth_loss = -np.log(1.0/len(chars))*seq_length#loss at iteration 0
losses.append(smooth_loss)
smooth_error = seq_length
for j in range(10):
print("============== j = ",j," ==================")
for i in range(int(len(data)/(seq_length*50))):
inputs = [char_to_ix[c] for c in data[i*seq_length:(i+1)*seq_length]]#inputs to the RNN
targets = [char_to_ix[c] for c in data[i*seq_length+1:(i+1)*seq_length+1]]#the targets it should be outputting
if i%1000==0:
sample_ix = sample([rnn1, rnn2, rnn3], inputs[0], 200, len(chars))
txt = ''.join([ix_to_char[n] for n in sample_ix])
print(txt)
losses.append(smooth_loss)
#forward pass
x = oneofk(inputs, len(chars))
y1, p1 = rnn1.step(x)
y2, p2 = rnn2.step(y1)
y3, p3 = rnn3.step(y2)
#calculate loss and error rate
loss = 0
error = 0
for t in range(len(targets)):
loss += -np.log(p3[t][targets[t],0])
if np.argmax(p3[t]) != targets[t]:
error += 1
smooth_loss = smooth_loss*0.999 + loss*0.001
smooth_error = smooth_error*0.999 + error*0.001
if i%10==0:
print(i,"\tsmooth loss =",smooth_loss,"\tsmooth error rate =",float(smooth_error)/len(targets))
#backward pass
dy = logprobs(p3, targets)
dx3 = rnn3.backprop(dy)
dx2 = rnn2.backprop(dx3)
dx1 = rnn1.backprop(dx2)
plt.plot(range(len(losses)), losses, 'b', label='smooth loss')
plt.xlabel('time in thousands of iterations')
plt.ylabel('loss')
plt.legend()
plt.show()
#let the RNN generate text
def sample(rnns, seed, n, k):
ndxs = []
ndx = seed
for t in range(n):
x = oneofk([ndx], k)
for i in range(len(rnns)):
x, p = rnns[i].step(x)
ndx = np.random.choice(range(len(p[0])), p=p[0].ravel())
ndxs.append(ndx)
return ndxs
#I have these out here because it's not really the RNN's concern how you transform
#things to a form it can understand
#get the initial dy to pass back through the first layer
def logprobs(p, targets):
dy = {}
for t in range(len(targets)):
#see http://cs231n.github.io/neural-networks-case-study/#grad if confused here
dy[t] = np.copy(p[t])
dy[t][targets[t]] -= 1
return dy
#encode inputs in 1-of-k so they match inputs between layers
def oneofk(inputs, k):
x = {}
for t in range(len(inputs)):
x[t] = np.zeros((k, 1))#initialize x input to 1st hidden layer
x[t][inputs[t]] = 1#it's encoded in 1-of-k representation
return x
if __name__ == "__main__":
rnn_raw() |
65b2fa8b9512bf5becb5cb06ede5c8419f179426 | balcanuc/playground | /serve.py | 275 | 3.65625 | 4 | #!/usr/bin/env python
print('Content-type: text/html\n')
print('<title>Hello World</title>')
for num in range(2, 5000):
prime = True
for i in range(2,num):
if (num%i == 0):
prime = False
if prime:
print(num)
# comment added by ccsyi06
|
55afd5b5bd7c9e281bbf5a37dfe588e8f0456661 | panzerox123/Intro-to-CV-and-DL | /linear_regression_formula.py | 805 | 3.828125 | 4 | import numpy
import matplotlib.pyplot as plt
import pandas as pd
#from sklearn.linear_model import LinearRegression
dataset = pd.read_csv("data.csv")
X = dataset['sqft_living']
Y = dataset['price']
#print(X)
#print(Y)
len_x = len(X)
len_y = len(Y)
x_sum = 0
y_sum = 0
for i in range(0,len_x):
x_sum = x_sum + X[i]
y_sum = y_sum + Y[i]
X_mean = x_sum/len_x
Y_mean = y_sum/len_y
#print(Y_mean, X_mean)
slope_num = 0
slope_den = 0
for i in range(0,len_x):
slope_num = slope_num + (X[i]-X_mean)*(Y[i]-Y_mean)
slope_den = slope_den + (X[i]-X_mean)**2
slope=slope_num/slope_den
C_term = Y_mean - X_mean*slope
#print(slope, C_term)
Y_new = list()
for i in range(0,len_x):
Y_new.append(X[i]*slope + C_term)
plt.scatter(X,Y,color="red")
plt.plot(X,Y_new,color="black")
plt.show()
|
3a4b122d8d066cee75d23e342ae79fe6e098e305 | PotatoTaco/Programming-Crappy-Solutions | /Machine Learning/Algorithms from Scratch/Genetic Algorithm.py | 2,198 | 3.515625 | 4 | import random
# Finds the number 10 from a range of 0 to 100
class GeneticAlgorithm:
def __init__(self, debug=False):
self.population = []
self.debug = debug
### These 4 functions can be altered depending on what is being searched
def randomInit(self):
self.population = [random.randint(0,100) for i in range(10)]
def fitness(self, val):
return abs(val-10)
def mutate(self,val):
return val + random.randint(-10,10)
def mate(self, val1, val2):
return self.mutate(val1+val2)
### The Actual Search Code
def search(self, elitism=0.1, mateRate=0.9, mateSelection=0.5, maxGeneration=-1):
minFitness = None
value = None
self.randomInit()
generation = 1
while (maxGeneration == -1 or generation < maxGeneration) and \
(minFitness == None or minFitness > 0):
#Debugging
if self.debug: print(f"Generation {generation}, Fitness={minFitness}: {self.population}")
# Elitism
popSize = len(self.population)
self.population = sorted(self.population,key=self.fitness)
self.population = self.population[:int(popSize*elitism)]
# Mutation
for i in range(int(popSize*mateRate)):
#Choose 2 random parents among the fittest to mate
ranges = int(popSize*mateSelection)
parent1 = random.choice(self.population[:ranges])
parent2 = random.choice(self.population[:ranges])
self.population.append(self.mate(parent1,parent2))
# Find new minimum fitness
newFitness = self.fitness(self.population[0])
if minFitness == None or newFitness < minFitness:
minFitness = newFitness
value = self.population[0]
generation += 1
if self.debug: print(f"Generation {generation}, Fitness={minFitness}: {self.population}")
return generation,value
def test():
algo = GeneticAlgorithm(debug=True)
print(algo.search())
if __name__=="__main__":
test()
|
faa8d2c01c7ee9411c16d86ac35291dddaa3ea07 | PotatoTaco/Programming-Crappy-Solutions | /Frameworks Testing/Discord Bot/Python/basic.py | 2,579 | 3.71875 | 4 | #https://realpython.com/how-to-make-a-discord-bot-python/
import discord
from discord.ext import commands
TOKEN = input("Enter discord token: ")
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
@bot.event
async def on_message(message):
# Prevent the bot from responding to itself
if message.author == bot.user:
return
print(message.content)
@bot.command(name='direct-message', help='Direct Message test')
async def dm(ctx):
member = ctx.author
await member.create_dm()
message = await member.dm_channel.send(
f'Hi {member.name}, I heard you dm me!'
)
#await message.edit(content="hi")
@bot.command(name='channel-message', help='Send a message to the group')
async def channel_message(ctx):
### Message and content
content = "This is a sample group message, where you can put normal text **with special markdown formatting**, :laughing: and stuff"
embed = discord.Embed(title="Sample Embed", description="This is an embed, where you can put your content inside", color=0x00ff00)
embed.add_field(name="Field", value="You can put your contents inside fields like this", inline=False)
message = await ctx.send(content=content, embed=embed)
await message.add_reaction(emoji="\N{WHITE HEAVY CHECK MARK}")
### Respond to reactions ###################################################
def check(reaction, user):
return reaction.emoji == "\N{WHITE HEAVY CHECK MARK}" \
and user != bot.user and user == ctx.author
while True:
## Add emoji reaction
res = await bot.wait_for('reaction_add', check=check)#, timeout=60.0)
if res:
new_embed = discord.Embed(title="Updated Embed", description="You can also modify the embed", color=0x00ff00)
await message.edit(content="The bot can check for reactions, and do whatever you want (eg. send a new message, dm)\nIn this case: update the message", embed=new_embed)
## Remove emoji reaction
res = await bot.wait_for('reaction_remove',check=check)
if res:
await message.edit(content=content, embed=embed)
############################################################################
@bot.command(name='yes-number', help='Put in a number like `!yes-number 1`. Used to test passing parameters into commands')
async def yesnumber(ctx, number: int):
message = await ctx.send(f"You given a number {number}. Whether it is right is debatable.")
bot.run(TOKEN)
|
f48a8232fb0645e5a3e96f406a019552080d6020 | shmuli9/rolling_averages_data_challenge | /rolling_averages.py | 2,710 | 3.625 | 4 | import csv
import time
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
''' example.csv contains the values for the system. The thing to note about the file
is that the sampling periods are not every 1 second. So there might be a value at
t = 0s of 200, and then the next value at t = 3s of 210 watts. We can assume that
the power value for times 1s, and 2s are also 200 watts. (So the power profile is a step
function)
Example call
===========
dataframe = load_csv()
dataframe_with_rolling = calculate_rolling_average(dataframe, averaging_period=600)
'''
def load_csv():
""" load the CSV containing the values.
Returns:
pd.DataFrame: [index, time, value]
"""
return pd.read_csv('example.csv')
def calculate_rolling_average(data: pd.DataFrame, averaging_period=600):
"""Summary
Calculate a rolling average
Args:
data (pd.DataFrame): contains two columns for time and power
averaging_period (int): (optional) default 10 minutes (600s)
Returns:
DataFrame: [time, value, moving_average]
"""
data["moving_average"] = data.rolling(averaging_period, on="time").mean()
return data
def preprocess(data: pd.DataFrame):
"""
Process the data
- Add in missing time steps
- Fill missing values with previous valid value (I assume the data follows a step function)
"""
processed = data.drop(axis=1, labels=["index"]) # drop unneeded column
# add in missing times
new_index = pd.Index(np.arange(0, data["time"].max(), 1), name="time")
processed = processed.set_index("time").reindex(new_index).reset_index()
# fill missing values
processed["value"].replace(0, np.nan, inplace=True) # convert all 0's to NaN
processed["value"].fillna(method="ffill", inplace=True) # forward fill all NaN (eg, use previous value)
processed["value"].replace(np.nan, 0, inplace=True) # change any values that dont have a previous value to 0
return processed
def plot_chart(data):
plt.figure(figsize=(10, 8), dpi=300)
plt.plot(data["time"], data["value"], 'g-', label="original data", linewidth="0.5")
plt.plot(data["time"], data["moving_average"], "b-", label="moving average", linewidth=3)
plt.title("Rolling Average Power (w)")
plt.xlabel("Time")
plt.ylabel("Power (w)")
plt.legend()
plt.savefig(f"rolling_average_{str(datetime.now()).split(' ')[1].split('.')[0].replace(':', '_')}.png",
bbox_inches='tight')
# plt.show()
if __name__ == "__main__":
values = preprocess(load_csv())
d = calculate_rolling_average(values)
plot_chart(d)
|
7664385455f917000232e15bd520625c5e6966d6 | marshallwicker/AITournament | /maroon.py | 14,887 | 3.640625 | 4 | from isolation import *
import random
X = True
def congruent_mod(x, y, n):
return (x - y) % n == 0
class PlayerAgent(Player):
mid_tiles = {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}
def __init__(self, name, token):
"""
Initialize a new instance
:param name: this player's name
:param token: This player's token
"""
super().__init__(name, token)
self.turn_count = 0
if self.token() == Board.BLUE_TOKEN:
self.opp = Board.RED_TOKEN
else:
self.opp = Board.BLUE_TOKEN
def take_turn(self, board):
"""
Make a move on the isolation board
:param board: an Board object
:return: Return a Move object
"""
#start=sw()
# if X:
# print("\n{} taking turn: ".format(self._name), end='')
# print(self.turn_count)
if self.turn_count < 6:
to_space_id, push_out_space_id = early_move(self, board)
move = Move(to_space_id, push_out_space_id)
self.turn_count += 1
elif self.turn_count < 15:
to_space_id, push_out_space_id = late_strategy_with_punch(self, board, 5)
move = Move(to_space_id, push_out_space_id)
self.turn_count += 1
else:
to_space_id, push_out_space_id = late_strategy_with_punch(self, board, 10)
move = Move(to_space_id, push_out_space_id)
self.turn_count += 1
#if X: print(' ', move)
#print(sw()-start)
return move
def random_move(player, board):
space_id = board.token_location(player.token())
neighbors = board.neighbor_tiles(space_id)
print('possible moves:', neighbors)
return random.choice(list(neighbors))
def random_punch(player, board, move_to,adj=False):
cur_loc = board.token_location(player.token())
opp_loc = board.token_location(player.opp)
tiled_spaces = board.push_outable_square_ids()
tiled_spaces.discard(move_to)
tiled_spaces.add(cur_loc)
if adj:
possible_punch=board.neighbor_tiles(opp_loc)
tmp2=board.tile_square_ids()
punch = possible_punch.intersection(tmp2)
else:
tmp = board.neighbor_tiles(opp_loc)
punch = list(tmp)
for tile in tmp:
for outer in board.neighbor_tiles(tile):
if not(outer in punch):
punch.append(outer)
if move_to in punch:
punch.remove(move_to)
if cur_loc in board.neighbors(opp_loc) or cur_loc in board.squares_at_radius(opp_loc, 2):
punch.append(cur_loc)
if move_to in punch:
punch.remove(move_to)
if punch:
return random.choice(list(punch))
else:
return random.choice(list(tiled_spaces))
def early_move(player, board):
if player.token() == Board.BLUE_TOKEN:
move = early_move_blue(player, board)
punch = early_punch_blue(player, board, move)
else:
move = early_move_red(player, board)
punch = early_punch_red(player, board, move)
return move, punch
def early_move_blue(player, board):
cur_loc = board.token_location(player.token())
if cur_loc in player.mid_tiles:
if cur_loc + 1 in board.push_outable_square_ids() and not (congruent_mod(cur_loc, board.N - 1, board.N)):
to_space_id = cur_loc + 1
elif cur_loc >= (board.N * board.M / 2):
if cur_loc - board.N + 1 in board.push_outable_square_ids() and not (
congruent_mod(cur_loc, board.N - 1, board.N)):
to_space_id = cur_loc - board.N + 1
elif cur_loc - board.N in board.push_outable_square_ids():
to_space_id = cur_loc - board.N
else:
to_space_id = random_move(player, board)
elif cur_loc < (board.N * board.M / 2):
if cur_loc + board.N + 1 in board.push_outable_square_ids() and not (
congruent_mod(cur_loc, board.N - 1, board.N)):
to_space_id = cur_loc + board.N + 1
elif cur_loc + board.N in board.push_outable_square_ids():
to_space_id = cur_loc + board.N
else:
to_space_id = random_move(player, board)
else:
to_space_id = random_move(player, board)
else:
possible_loc = board.neighbor_tiles(cur_loc).intersection(player.mid_tiles)
if bool(possible_loc):
distances = []
for element in possible_loc:
tmp = (element, board.distance_between(element, board.token_location(Board.RED_TOKEN)))
distances.append(tmp)
cur_min = distances[0]
for i in range(1, len(distances)):
if distances[i][1] < cur_min[1]:
cur_min = distances[i]
to_space_id = cur_min[0]
else:
to_space_id = random_move(player, board)
return to_space_id
def early_move_red(player, board):
cur_loc = board.token_location(player.token())
if cur_loc in player.mid_tiles:
if cur_loc - 1 in board.push_outable_square_ids() and not (congruent_mod(cur_loc, 0, board.N)):
to_space_id = cur_loc - 1
elif cur_loc >= (board.N * board.M / 2):
if cur_loc - board.N - 1 in board.push_outable_square_ids() and not (congruent_mod(cur_loc, 0, board.N)):
to_space_id = cur_loc - board.N - 1
elif cur_loc - board.N in board.push_outable_square_ids():
to_space_id = cur_loc - board.N
else:
to_space_id = random_move(player, board)
elif cur_loc < (board.N * board.M / 2):
if cur_loc + board.N - 1 in board.push_outable_square_ids() and not (congruent_mod(cur_loc, 0, board.N)):
to_space_id = cur_loc + board.N - 1
elif cur_loc + board.N in board.push_outable_square_ids():
to_space_id = cur_loc + board.N
else:
to_space_id = random_move(player, board)
else:
to_space_id = random_move(player, board)
else:
possible_loc = board.neighbor_tiles(cur_loc).intersection(player.mid_tiles)
if bool(possible_loc):
distances = []
for element in possible_loc:
tmp = (element, board.distance_between(element, board.token_location(player.opp)))
distances.append(tmp)
cur_min = distances[0]
for i in range(1, len(distances)):
if distances[i][1] < cur_min[1]:
cur_min = distances[i]
to_space_id = cur_min[0]
else:
to_space_id = random_move(player, board)
return to_space_id
def early_punch_blue(player, board, move):
push_out_space_id = move
opp_loc = board.token_location(player.opp)
if opp_loc - 1 in board.push_outable_square_ids() and not (congruent_mod(opp_loc, 0, board.N)):
push_out_space_id = opp_loc - 1
if move != push_out_space_id: return push_out_space_id
alt_push = {opp_loc + 1, opp_loc - 1, opp_loc + Board.N, opp_loc - Board.N}.intersection(
board.neighbor_tiles(opp_loc))
possible_push = board.neighbor_tiles(opp_loc) - alt_push
if bool(possible_push):
distances = []
for element in possible_push:
tmp = (element, board.distance_between(element, move))
distances.append(tmp)
cur_max = distances[0]
for i in range(1, len(distances)):
if distances[i][1] > cur_max[1]:
cur_max = distances[i]
push_out_space_id = cur_max[0]
elif opp_loc + 1 in board.push_outable_square_ids() and not (congruent_mod(opp_loc, board.N - 1, board.N)):
push_out_space_id = opp_loc + 1
if move != push_out_space_id:
return push_out_space_id
else:
return random_punch(player, board, move)
def early_punch_red(player, board, move):
push_out_space_id = move
opp_loc = board.token_location(player.opp)
if opp_loc + 1 in board.push_outable_square_ids() and not (congruent_mod(opp_loc, board.N - 1, board.N)):
push_out_space_id = opp_loc + 1
if move != push_out_space_id: return push_out_space_id
alt_push = {opp_loc + 1, opp_loc - 1, opp_loc + Board.N, opp_loc - Board.N}.intersection(
board.neighbor_tiles(opp_loc))
possible_push = board.neighbor_tiles(opp_loc) - alt_push
if bool(possible_push):
distances = []
for element in possible_push:
tmp = (element, board.distance_between(element, move))
distances.append(tmp)
cur_max = distances[0]
for i in range(1, len(distances)):
if distances[i][1] > cur_max[1]:
cur_max = distances[i]
push_out_space_id = cur_max[0]
elif opp_loc - 1 in board.push_outable_square_ids() and not (congruent_mod(opp_loc, 0, board.N)):
push_out_space_id = opp_loc - 1
if move != push_out_space_id:
return push_out_space_id
else:
return random_punch(player, board, move)
def late_strategy(player, board, look_ahead):
cur_loc = board.token_location(player.token())
opp_loc = board.token_location(player.opp)
knowledge = []
new_board = Board()
for tile in board.neighbor_tiles(cur_loc):
if player.token() == Board.BLUE_TOKEN:
new_board.set_state(tile, opp_loc, board.pushed_out_square_ids())
else:
new_board.set_state(opp_loc, tile, board.pushed_out_square_ids())
tmp = (tile, h(tile, opp_loc, board))
knowledge.append(tmp)
for i in range(1, look_ahead):
for tile in knowledge:
for next_tile in new_board.neighbor_tiles(tile[0]):
if player.token() == Board.BLUE_TOKEN:
new_board.set_state(next_tile, opp_loc, board.pushed_out_square_ids())
else:
new_board.set_state(opp_loc, next_tile, board.pushed_out_square_ids())
tmp = (tile[0], next_tile, h(tile, player, new_board))
knowledge.append(tmp)
knowledge.remove(tile)
move_to = max(knowledge, key=lambda x: x[len(x) - 1])[0]
return move_to, random_punch(player, board, move_to,True)
def look_ahead(token,knowledge,other_knowledge,current_board):
board = Board()
knowledge_copy=knowledge[:]
for anti_fact in other_knowledge:
fut_opp_loc=anti_fact.get_cur_loc()
for fact in knowledge_copy:
for next_tile in current_board.neighbor_tiles(fact.get_cur_loc()):
possible_opp_moves=current_board.neighbors(fut_opp_loc)
missing_tiles = anti_fact.get_punches().union(fact.get_punches(), current_board.pushed_out_square_ids())
if next_tile in possible_opp_moves:
possible_opp_moves-={next_tile}
possible_opp_moves-=missing_tiles
for push in possible_opp_moves:
missing_tiles.add(push)
if token == Board.BLUE_TOKEN:
board.set_state(next_tile, fut_opp_loc, missing_tiles)
else:
board.set_state(fut_opp_loc, next_tile, missing_tiles)
tmp1 = (next_tile,push)
new_moves=fact.get_moves()
new_moves.append(tmp1)
new_punches=fact.get_punches()
new_punches.add(push)
tmp2 = Fact(h(next_tile,fut_opp_loc,board),new_moves,new_punches)
knowledge.append(tmp2)
missing_tiles.discard(push)
if fact in knowledge: knowledge.remove(fact)
return knowledge
def late_strategy_with_punch(player, board, steps):
cur_loc = board.token_location(player.token())
opp_loc = board.token_location(player.opp)
self_knowledge = [Fact(h(cur_loc,opp_loc,board),[(cur_loc,None)])]
opp_knowledge=[Fact(h(opp_loc,cur_loc,board),[(opp_loc,None)])]
self_knowledge = look_ahead(player.token(), self_knowledge, opp_knowledge, board)
self_knowledge.sort(key=lambda x: x.get_h(),reverse=True)
if len(self_knowledge)>15:
self_knowledge=self_knowledge[:15]
for i in range(1,steps):
opp_knowledge=look_ahead(player.opp,opp_knowledge,self_knowledge,board)
opp_knowledge.sort(key=lambda x: x.get_h(),reverse=True)
if len(opp_knowledge) > 15:
opp_knowledge = opp_knowledge[:15]
self_knowledge=look_ahead(player.token(),self_knowledge,opp_knowledge,board)
self_knowledge.sort(key=lambda x:x.get_h(),reverse=True)
if len(self_knowledge) > 15:
self_knowledge = self_knowledge[:15]
if self_knowledge:
for i in range(0,15):
ret = self_knowledge[i].next_move()
if ret[0]!=ret[1]:
break
if ret[0] == ret[1]:
move_to = random_move(player, board)
ret = (move_to, random_punch(player, board,move_to, True))
else:
move_to=random_move(player,board)
ret = (move_to,random_punch(player,board,move_to,True))
return ret[0],ret[1]
def h(tile, opp_loc, board):
return len(board.neighbor_tiles(tile)) - len(board.neighbor_tiles(opp_loc))
class Fact:
def __init__(self,value,sequence=[],pushes=set()):
self._moves=sequence
self._punch=pushes
self._h=value
def get_moves(self):
return self._moves[:]
def get_punches(self):
return self._punch.copy()
def get_h(self):
return self._h
def get_cur_loc(self):
return self._moves[len(self._moves)-1][0]
def next_move(self):
return self._moves[1]
def __eq__(self, other):
return self._h==other._h and self._moves==other._moves and self._punch==other._punch
def __ne__(self, other):
return self._h != other._h and self._moves != other._moves and self._punch != other._punch
def __lt__(self, other):
return self._h < other.h
def __gt__(self, other):
return self._h > other.h
def __le__(self, other):
return self._h <= other.h
def __ge__(self, other):
return self._h >= other.h
# Board.set_dimensions(6, 8)
# # match = Match(AgentPlayer('Blue', Board.BLUE_TOKEN),
# # AgentPlayer('Red', Board.RED_TOKEN))
# # print(match.start_play())
# d={'Blue':0,'Red':0}
# for i in range(100):
# match = Match(AgentPlayer('Blue', Board.BLUE_TOKEN),
# AgentPlayer('Red', Board.RED_TOKEN))
# tmp =match.start_play()
# d[tmp]+=1
# print('Blue:',d['Blue'])
# print('Red:',d['Red'])
#
# # match = Match(hp.HumanPlayer('Blue', Board.BLUE_TOKEN),
# # AgentPlayer('Red', Board.RED_TOKEN))
# # print(match.start_play())
|
e44ce2e63d37ea010cb07d82b35dec3a5f129612 | lky1020/OpenCV | /OpencvPython/Chapter4.py | 517 | 3.71875 | 4 | #Chapter 4 - Shapes & Texts
import cv2
import numpy as np
img = np.zeros((512, 512, 3), np.uint8)
#print(img.shape)
#img[:]= 255, 0, 0 #blue, green, red
#shapes
cv2.line(img, (0, 0), (img.shape[1], img.shape[0]), (0, 255, 0), 3) #shape[1] = width, shape[0] = height
cv2.rectangle(img, (0, 0), (250, 250), (0, 0, 255), 2)
cv2.circle(img, (400, 50), 30, (255, 255, 0), 3)
#text
cv2.putText(img, "OpenCV", (300, 200), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 150, 0), 1)
cv2.imshow("Image", img)
cv2.waitKey(0) |
44435a2014b6a639d8da89bd5a59ed297360f46e | sky332060679/python_exercises | /列表.py | 258 | 3.75 | 4 | number = [1,2,1,3,1,4,1,5]
number.remove(number[1])
number[1]="sky"
number[3]="star"
print(number)
num = [1,2,3]
num.extend([4,"k",8])
num[1] = 5
print(num)
loc1 = num.index(1)
print(loc1)
number.pop()
print(number)
number.pop(1)
print(number)
dir(list) |
9579ff167d38ede721ad4a9526fc140406285322 | ramonvoges/wordcloud | /goethecloud.py | 1,005 | 3.8125 | 4 | """A short script to create wordclouds from a given text and with a """
from PIL import Image
from wordcloud import WordCloud
# import wordcloud
# from nltk.corpus import stopwords
from stop_words import get_stop_words
import random
import numpy as np
import matplotlib.pyplot as plt
with open("Goethe_Sammler.txt", "r") as f:
text = f.read()
goethe_mask = np.array(Image.open('Goethe_Schattenriss.jpg'))
blacklist = get_stop_words('german')
blacklist = set(blacklist)
blacklist = blacklist.union({'wäre', 'konnte', 'lassen', 'sagte', 'muß', 'Oheim', 'Julie', 'sei'})
def grey_color(word, font_size, position, orientation, random_state=None, **kwargs):
return("hsl(0, 0%%, %d%%)" % np.random.randint(10, 20))
wc = WordCloud(background_color='white', mask=goethe_mask, stopwords=blacklist, width=800, height=800)
wc.generate(text)
wc.recolor(color_func = grey_color)
fig = plt.figure(dpi=600)
plt.imshow(wc, interpolation="bilinear")
plt.axis('off')
fig.savefig('WC_Goethe.jpg')
|
47626d69623bdd02a17afa26135ba68fd9d59ad3 | deilsonamaral1/checkerboard-turtle | /checkerboard.py | 2,748 | 3.890625 | 4 | # Checkerboard by Deilson Amaral and Amanda Tavares
import turtle as t
t.penup()
# Set position to better draw the Checkerboard
t.setpos(-258,-258)
t.pendown()
t.speed(0)
square_len = 66
pattern1_distance = -7
pattern2_distance = -9
square_num = 8
# The black squares with space to draw other
def square():
t.color('black')
t.begin_fill()
for i in range(4):
t.forward(square_len)
t.left(90)
t.end_fill()
t.penup()
t.forward(square_len)
t.pendown()
# A row has 4 black squares, the space between them is the white square
def row():
for j in range(4):
t.penup()
t.forward(square_len)
t.pendown()
square()
# The first pattern draw a row that starts with a white square
def pattern1():
row()
t.penup()
t.forward(pattern1_distance * square_len)
t.left(90)
t.forward(square_len)
t.right(90)
t.pendown()
# The second pattern draw a row that starts with a black square
def pattern2():
row()
t.penup()
t.forward(pattern2_distance * square_len)
t.left(90)
t.forward(square_len)
t.right(90)
t.pendown()
def board():
# A board have 8 rows, so we put this in a range
for k in range(8):
# The even row has pattern2
if k % 2 == 0:
pattern2()
# The odd row has pattern1
else:
pattern1()
# Here we draw the Checkerboard outline. It's the sum of square len
def outline():
t.penup()
t.forward(square_len)
t.pendown()
for h in range(4):
t.forward(square_num * square_len)
t.right(90)
board()
outline()
# Lists of Turtles, that here is the Checkerboard piece
list1 = []
list2 = []
# A Checkerboard has 12 pieces, so we add 12 circle Turtles to each list, one for red and other for yellow pieces
for i in range(12):
list1.append(t.Turtle('circle'))
list1[i].turtlesize(2, 2, 2)
list1[i].penup()
list1[i].color('red')
list1[i].goto(0,-220)
list2.append(t.Turtle('circle'))
list2[i].turtlesize(2, 2, 2)
list2[i].penup()
list2[i].color('yellow')
# We place every piece into the square
list1[0].goto(223,-220)
list1[1].goto(93,-220)
list1[2].goto(-37,-220)
list1[3].goto(-167,-220)
list1[4].goto(-93,-160)
list1[5].goto(-223,-160)
list1[6].goto(37,-160)
list1[7].goto(167,-160)
list1[8].goto(93,-100)
list1[9].goto(223,-100)
list1[10].goto(-37,-100)
list1[11].goto(-167,-100)
list2[0].goto(-93,220)
list2[1].goto(-223,220)
list2[2].goto(37,220)
list2[3].goto(167,220)
list2[4].goto(93,160)
list2[5].goto(223,160)
list2[6].goto(-37,160)
list2[7].goto(-167,160)
list2[8].goto(-93,100)
list2[9].goto(-223,100)
list2[10].goto(37,100)
list2[11].goto(167,100)
# This code is to Window doesn't close!
t.done()
|
d5c87c28e1f6505f198d33629b1049f254df8857 | dilawarm/crypto-tools | /vigenere-cipher.py | 791 | 4 | 4 | import string
import operator
ALPHABET = string.ascii_uppercase + "ÆØÅ"
def vigenere(plaintext, key, algo):
op = operator.add if algo.lower() == "encrypt" else operator.sub
return "".join(
ALPHABET[
(
op(
ALPHABET.index(plaintext[i].upper()),
ALPHABET.index(key[i % len(key)].upper()),
)
)
% len(ALPHABET)
]
for i in range(len(plaintext))
if plaintext[i] != " "
)
if __name__ == "__main__":
choice = input("Encrypt or Decrypt [e/d]: ")
text = input("Text: ").upper()
key = input("Key: ").upper()
if choice == "e":
print(vigenere(text, key, "encrypt"))
else:
print(vigenere(text, key, "decrypt")) |
bf6f04f7153f61fa4b46fc99f71116374d9230d4 | AgustinParmisano/tecnicatura_analisis_sistemas | /trabajos_entregas/parcial/mariano/and_or_OP.py | 993 | 3.859375 | 4 | #1)
#a)Realice una funcion que dado los numeros pasados por parametro retorne si A=1 y B=1 Res=1, Res=0 en cualquier otro caso.
A = input("Ingrese un numero: ")
B = input("Ingrese otro numero: ")
def andfun(A,B):
if A == 1 and B == 1:
return 1
else:
return 0
print(andfun(A,B))
#b)Realice una funcion que simule una compuerta OR dados 2 numeros pasados por parametro y retorne el Res
C = input("ingrese un numero binario: ")
D = input ("ingrese otro numero binario: ")
def orfun(C,D):
if C == 1 or D == 1:
return 1
else:
return 0
print(orfun(C,D))
#2)Realice una funcion que dado dos numeros binarios de 8 bits (ej: "01010101") retorne el resultado de Operacion AND
n_1 = raw_input("Ingrese un numero binario de 8 bits: ")
n_2 = raw_input("Ingrese otro numero binario de 8 bits: ")
def andop(n_1,n_2):
lista = []
conteo = 0
for i in n_1:
result = andfun(int(i),int(n_2[conteo]))
conteo = conteo + 1
lista.append(result)
return lista
print(andop(n_1,n_2))
|
7bc36647921f253c1ed133c6593de0c35104d261 | AgustinParmisano/tecnicatura_analisis_sistemas | /ingreso/maxmin.py | 592 | 4.3125 | 4 | #!/usr/bin/python
# coding=utf-8
'''
Realizar un programa que lea dos números enteros desde teclado e informe
en pantalla cuál de los dos números es el mayor. Si son iguales
debe informar en pantalla lo siguiente: “Los números leídos son iguales”.
'''
num1 = int(raw_input('Ingrese un número: '))
num2 = int(raw_input('Ingrese otro número: '))
if num1 > num2:
print(" El número %s es mayor que %s" % (num1, num2))
elif num1 < num2:
print("El número %s es mayor que %s" % (num2, num1))
else:
print("Los números %s y %s son iguales" % (num1, num2))
|
0d354df29e4cb1c53cb6e2c5f5dbe2237bd3b179 | AgustinParmisano/tecnicatura_analisis_sistemas | /programacion1/practica4/practicaruben.py | 565 | 3.640625 | 4 | #!/usr/bin/python
cuenta = {}
p1 = raw_input ("ingrese su nombre: ")
p2 = raw_input ("ingrese su apellido: ")
p3 = input ("ingrese su dni: ")
p4 = (p1 + p2)
len (p4)
clave = (len(p4)*p3)
cuenta = {"nombre":p1,"apellido":p2,"dni":p3,"clave":(clave)}
print (cuenta)
key = raw_input ("ingrese campo que quiere modificar: " )
print "el %s que quiere modificar tiene de valor: %s" % (key,cuenta[key])
opcion = input ("quiere modificar el campo elegido? 1=si o 0=no: ")
if opcion == 1:
valor = raw_input ("ingrese nuevo valor: ")
cuenta[key] = valor
print (cuenta)
|
57e9dfdc906e74b737efbe5372dbf0dc2b2d5dcf | AgustinParmisano/tecnicatura_analisis_sistemas | /programacion1/practica3/examples/while_example_dict.py | 459 | 3.90625 | 4 | #while con diccionarios
salir = False
lista_personas = []
while not salir:
persona = {}
persona["nombre"] = raw_input("Ingrese nombre: ")
persona["apellido"] = raw_input("Ingrese apellido: ")
persona["edad"] = input("Ingrese nombre: ")
lista_personas.append(persona)
print("Persona Agregada")
salir = input("Terminar:1, Continuar:0 ")
print("Lista de Personas Agregadas:")
print(lista_personas)
print lista_personas[2]["nombre"] |
79a66e49efd1a09bbab6be1c2762e67536c3316e | AgustinParmisano/tecnicatura_analisis_sistemas | /programacion1/practica2/pract2_punt2_B.py | 121 | 3.9375 | 4 | #!/usr/bin/python
char = raw_input("Ingrese un caracter: ")
if char == "A":
print("65")
if char == "a":
print("91")
|
c3d0f6d7b3313771078a67651c4bf0502b8bbe77 | cpe202spring2019/lab1-eddiekaung | /lab1_test_cases.py | 8,505 | 3.578125 | 4 | import unittest
from lab1 import *
# A few test cases. Add more!!!
class TestLab1(unittest.TestCase):
def test_max_list_iter_none(self):
"""test case for when int_list in None"""
tlist = None
with self.assertRaises(ValueError): # used to check for exception
max_list_iter(tlist)
def test_max_list_iter_empty_list(self):
"""test case for when int_list is empty"""
self.assertEqual(max_list_iter([]), None)
def test_max_list_iter_first_max(self):
"""test case for when first index is max"""
self.assertEqual(max_list_iter([5, 4, 3]), 5)
self.assertEqual(max_list_iter([-1, -24, -34]), -1)
self.assertAlmostEqual(max_list_iter([8.9, 2.3, -0.5]), 8.9)
def test_max_list_iter_second_max(self):
"""test case for when second index is max"""
self.assertEqual(max_list_iter([2, 4, 1]), 4)
self.assertEqual(max_list_iter([-89, -24, -100]), -24)
self.assertAlmostEqual(max_list_iter([-8, 2.3, -0.5]), 2.3)
def test_max_list_iter_third_max(self):
"""test case for when third index is max"""
self.assertEqual(max_list_iter([1, 2, 3]), 3)
self.assertEqual(max_list_iter([-100, -94, -34]), -34)
self.assertAlmostEqual(max_list_iter([-8.9, -8, -0.5]), -0.5)
def test_max_list_iter_all_max(self):
"""test case for when all numbers are max"""
self.assertEqual(max_list_iter([5, 5, 5]), 5)
self.assertEqual(max_list_iter([-1, -1, -1]), -1)
self.assertAlmostEqual(max_list_iter([8.9, 8.9, 8.9]), 8.9)
def test_max_list_iter_first_two_max(self):
"""test case for when first two nums are max"""
self.assertEqual(max_list_iter([5, 5, 3]), 5)
self.assertEqual(max_list_iter([-1, -24, -34]), -1)
self.assertAlmostEqual(max_list_iter([8.9, 2.3, -0.5]), 8.9)
def test_max_list_iter_last_two_max(self):
"""test case for when last two nums are max"""
self.assertEqual(max_list_iter([1, 3, 3]), 3)
self.assertEqual(max_list_iter([-100, -34, -34]), -34)
self.assertAlmostEqual(max_list_iter([-8.9, -0.5, -0.5]), -0.5)
def test_max_list_iter_first_and_third_max(self):
"""test case for when first and third nums are max"""
self.assertEqual(max_list_iter([3, 2, 3]), 3)
self.assertEqual(max_list_iter([-34, -94, -34]), -34)
self.assertAlmostEqual(max_list_iter([-0.5, -8, -0.5]), -0.5)
def test_reverse_rec_none(self):
"""test case for when int_list is None"""
tlist = None
with self.assertRaises(ValueError): # used to check for exception
reverse_rec(tlist)
def test_reverse_rec_empty_list(self):
"""test case for when int_list is empty"""
self.assertEqual(reverse_rec([]), []) # in case of empty lists
def test_reverse_rec(self):
"""test case for reverse_rec"""
self.assertEqual(reverse_rec([3, 2, 1]), [1, 2, 3])
self.assertEqual(reverse_rec([4.5, 2.3, 4]), [4, 2.3, 4.5])
self.assertEqual(reverse_rec([3, -5, 4.5, 2, 3]), [3, 2, 4.5, -5, 3])
def test_reverse_rec_all_nums_same(self):
"""test case for when all values are the same"""
self.assertEqual(reverse_rec([3, 3, 3]), [3, 3, 3])
self.assertEqual(reverse_rec([4.5, 4.5, 4.5]), [4.5, 4.5, 4.5])
self.assertEqual(reverse_rec([-5, -5, -5, -5]), [-5, -5, -5, -5])
def test_reverse_rec_first_two_nums_same(self):
"""test case for when first two values are the same"""
self.assertEqual(reverse_rec([3, 3, 1]), [1, 3, 3])
self.assertEqual(reverse_rec([4.5, 4.5, 6.5]), [6.5, 4.5, 4.5])
self.assertEqual(reverse_rec([-5, -5, -3]), [-3, -5, -5])
def test_reverse_rec_last_two_nums_same(self):
"""test case for when last two values are the same"""
self.assertEqual(reverse_rec([3, 3, 3]), [3, 3, 3])
self.assertEqual(reverse_rec([4.5, 4.5, 4.5]), [4.5, 4.5, 4.5])
self.assertEqual(reverse_rec([-5, -5, -5, -5]), [-5, -5, -5, -5])
def test_reverse_rec_first_and_last_num_same(self):
"""test case for when all values are the same"""
self.assertEqual(reverse_rec([3, 2, 3]), [3, 2, 3])
self.assertEqual(reverse_rec([4.5, 6.5, 4.5]), [4.5, 6.5, 4.5])
self.assertEqual(reverse_rec([-5, -3, -5]), [-5, -3, -5])
def test_bin_search_none(self):
"""test case for when int_list is None"""
tlist = None
with self.assertRaises(ValueError): # used to check for exception
bin_search(tlist, 0, 0, None)
def test_bin_search_low_greater_than_high(self):
"""test case for when low is greater than high"""
tlist = [0,1,2,3,4,5,6,7,8,9,10]
low = 5
high = 0
self.assertEqual(bin_search(2, low, high, tlist), None)
def test_bin_search_low_equals_high(self):
"""test case for when low is greater than high"""
tlist = [0,1,2,3,4,5,6,7,8,9,10]
low = 5
high = 5
self.assertEqual(bin_search(2, low, high, tlist), None)
def test_bin_search_low_equals_high_equals_target_index(self):
"""test case for when low is greater than high"""
tlist = [0,1,2,3,4,5,6,7,8,9,10]
low = 5
high = 5
self.assertEqual(bin_search(5, low, high, tlist), 5)
def test_bin_search_empty_list(self):
"""test case for when int_list in empty"""
tlist = []
self.assertEqual(bin_search(11, 0, len(tlist)-1, tlist), None)
def test_bin_search_not_found(self):
"""test case for when target is not found"""
list_val =[0,1,2,3,4,7,8,9,10]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(11, 0, len(list_val)-1, list_val), None)
def test_bin_search_lower_half(self):
"""test case for when target is in lower half of the list"""
list_val =[0,1,2,3,4,7,8,9,10]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(4, 0, len(list_val)-1, list_val), 4)
def test_bin_search_upper_half(self):
"""test case for when target is in upper half of the list"""
list_val =[0,1,2,3,4,7,8,9,10]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(7, 0, len(list_val)-1, list_val), 5)
def test_bin_search_random_lower_half(self):
"""test case for when target is in the lower half of the list"""
list_val =[2,15,23,26,56,57,66,66,89,99,100]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(26, 0, len(list_val)-1, list_val), 3)
def test_bin_search_random_upper_half(self):
"""test case for when target is in the lower half of the list"""
list_val =[2,15,23,26,56,57,60,66,89,99,100]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(66, 0, len(list_val)-1, list_val), 7)
def test_bin_search_middle(self):
"""test case for when target is at the midpoint"""
list_val =[2,15,23,26,56,57,60,66,89,99,100]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(57, 0, len(list_val)-1, list_val), 5)
def test_bin_search_even_list(self):
"""test case for when the list has even number of length"""
list_val =[2,15,23,26,56,57,60,66,89,99]
low = 0
high = len(list_val)-1
self.assertEqual(bin_search(57, 0, len(list_val)-1, list_val), 5)
def test_bin_search_random_high_low_without_target(self):
"""test cases for when the high and low doesn't contain target"""
list_val =[2,15,23,26,56,57,60,66,89,99]
self.assertEqual(bin_search(57, 0, 3, list_val), None)
def test_bin_search_random_high_low_with_target(self): # buggy
"""test cases for when the high and low contain target"""
list_val =[2,15,23,26,56,57,60,66,89,99, 123]
self.assertEqual(bin_search(57, 0, 20, list_val), 5)
def test_bin_search_list_len_one(self):
"""test cases for when the list length is one and contains target"""
list_val =[2]
self.assertEqual(bin_search(2, 0, 0, list_val), 0)
def test_bin_search_list_len_one_not_found(self):
"""test cases for when list length is one and doesn't contain target"""
list_val =[2]
self.assertEqual(bin_search(4, 0, 0, list_val), None)
if __name__ == "__main__":
unittest.main()
|
cb98d945347ea48f38f8aca0eba2629615b09cb8 | ShenYuCN/WorkspacePython | /common/time/time_clock.py | 436 | 3.65625 | 4 | import time
import random
originalTime = time.time()
# temp = originalTime + 30 * 60 + random.randint(1,10*60)
# temp = originalTime + 10 * index + random.randint(5,10)
temp = originalTime + random.randint(5,10)
print('temp:',int(temp),'originalTime:',int(originalTime))
while True:
if time.time() > temp:
print('temp:',int(temp),'now:',int(time.time()))
print('zheli break')
break
else:
print('sleeping')
time.sleep(3) |
ba9f1fd6c7c56f7673b760b605b0fc17d14e0556 | mylgcs/python | /训练营day02/01_函数.py | 851 | 4.15625 | 4 | # 将一个常用的功能封装为一个单独的代码片段,用一个单词来表示,通过这个单词,只需极简结的代码,即可实现这个功能,
# 这样的代码片段,称为"函数"!
# 比如print 和 input就是函数
# 函数
def print_poetry():
print("春眠不觉晓,处处蚊子咬,夜来嗡嗡声,叮的包不少。")
# 函数调用
print_poetry()
# 函数的参数与返回值
# 通过参数将数据传递给函数,通过返回值将运算的结果回传
def add(a, b):
return a + b
# 运算结果可以赋值给另一个变量,也可以直接使用
c = add(1, 2)
print(c)
# 调用函数的式子,也是有值的,返回值就是函数调用表达式的值
print(add(3, 5) + 4)
# 传参可以带标签
def p_pow(num, power):
return num ** power
print(p_pow(num=10, power=2))
|
5159bf2cc3aa09a0c788414dd11d11a86323e415 | pansilup/demo-on-homomorphic-encryption | /3DGHV_FHE_add_mul_comp.py | 7,936 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
----------------------------------------------------------
Program : Demonstrates DGHV fully homomorphic encryption
scheme and examples for Addition, Subtraction,
Multiplication & Comparison
Author : Pansilu Pitigalaarachchi
Created : on Mon Sep 14 11:54:36 2020
Based on: Concepts & Examples of https://asecuritysite.com
and thanks to the world of Free online resources
----------------------------------------------------------
"""
import sys
from random import randint
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def tobits(val):
l = [0]*(8)
l[0]=val & 0x1
l[1]=(val & 0x2)>>1
l[2]=(val & 0x4)>>2
l[3]=(val & 0x8)>>3
return l
def XOR(a,b):
return ( (NOT(a)*b) + (a*NOT(b)))
def NOT(val):
return(val ^ 1)
def AND(a,b):
return(a*b)
def OR(a,b):
return(a+b)
def HA(bit1,bit2):
sum=XOR(bit1,bit2)
carryout=AND(bit1,bit2)
return sum,carryout
def FA(bit1,bit2,cin):
sum1,c1=HA(bit1,bit2)
sum,c2=HA(sum1,cin)
carryout=OR(c1,c2)
return sum,carryout
def FOURBITADDER(*value):
i = 0
for n in value:
i = i + 1
if(i==1):cval_a0 = n
if(i==2):cval_a1 = n
if(i==3):cval_a2 = n
if(i==4):cval_a3 = n
if(i==5):cval_b0 = n
if(i==6):cval_b1 = n
if(i==7):cval_b2 = n
if(i==8):cval_b3 = n
if(i==9):c_carryin = n
c_sum1,c_carryout=FA(cval_a0,cval_b0,c_carryin )
c_sum2,c_carryout=FA(cval_a1,cval_b1,c_carryout )
c_sum3,c_carryout=FA(cval_a2,cval_b2,c_carryout )
c_sum4,c_carryout=FA(cval_a3,cval_b3,c_carryout )
return c_sum1,c_sum2,c_sum3,c_sum4,c_carryout
def TWOBITMUL(*value):
i = 0
for n in value:
i = i + 1
if(i==1):cval_a0 = n
if(i==2):cval_a1 = n
if(i==3):cval_b0 = n
if(i==4):cval_b1 = n
c_mul1 = AND(cval_a0,cval_b0)
c_mul2,c_carryout = HA(AND(cval_a1,cval_b0),AND(cval_a0,cval_b1))
c_mul3,c_mul4 = HA(c_carryout,AND(cval_a1,cval_b1))
return c_mul1,c_mul2,c_mul3,c_mul4
def THREEBITMUL(*value):
i = 0
for n in value:
i = i + 1
if(i==1):cval_a0 = n
if(i==2):cval_a1 = n
if(i==3):cval_a2 = n
if(i==4):cval_b0 = n
if(i==5):cval_b1 = n
if(i==6):cval_b2 = n
cml0 = AND(cval_a0,cval_b0)
cml1,ha1_c = HA(AND(cval_a1,cval_b0),AND(cval_a0,cval_b1))
ha2_out,ha2_c = HA(AND(cval_a2,cval_b0),AND(cval_a1,cval_b1))
cml2,fa1_c = FA(AND(cval_a0,cval_b2),ha2_out,ha1_c)
fa2_out,fa2_c = FA(AND(cval_a1,cval_b2),AND(cval_a2,cval_b1),ha2_c)
cml3,ha3_c = HA(fa2_out,fa1_c)
cml4,cml5 = FA(AND(cval_a2,cval_b2),fa2_c,ha3_c)
return cml0,cml1,cml2,cml3,cml4,cml5
def cipher(bit,p):
q=randint(20000, 30000)
r=randint(1,10)
return( q * p + 2*r +int(bit)),q,r
def inv(val):
return(val ^ 1)
max_no = int(15)
print(bcolors.OKGREEN)
print(bcolors.UNDERLINE+'DEMO : DGHV Fully Homomorphic Encryption : Addition,Subtraction,Multiplication and Millionaires\' problem')
val1 = 3
val2 = 2
#val1 = int(input("Enter Number 1 : "))
#val2 = int(input("Enter Number 2 : "))
#err = 0
#if(val1 > max_no):
# print("Number 1 is invalid");err = 1;
#if(val2 > max_no):
# print("Number 2 is invalid");err = 1;
#if(err == 1):
# sys.exit()
cin=0
v1=[]
v2=[]
v1=tobits(val1)
v2=tobits(val2)
print(bcolors.ENDC)
raw_input("Key Generation : Continue ...")
print(bcolors.OKGREEN+'# Key Generation >>')
print("-----------------------------------------------------------------------------------------------------")
p =randint(3e23, 6e23)*2+1
public_key = [0 for i in range(32)]
print('Public key:'+bcolors.ENDC)
for i in range(0,len(public_key)):
public_key[i],q,r = cipher(0,p)
print public_key[i],
print(bcolors.OKGREEN+'\nSecret Key : '+bcolors.ENDC)
print p
print(bcolors.OKGREEN+'\nPlain Text Numbers : '+bcolors.ENDC)
print val1,', ',val2
raw_input("\nEncryption : Continue ...")
print(bcolors.OKGREEN+'\n\n# Encryption >>')
print("-----------------------------------------------------------------------------------------------------")
c_carryin,q,r=cipher(cin,p)
cval_a0,q,r=cipher(v1[0],p)
cval_b0,q,r=cipher(v2[0],p)
cval_a1,q,r=cipher(v1[1],p)
cval_b1,q,r=cipher(v2[1],p)
cval_a2,q,r=cipher(v1[2],p)
cval_b2,q,r=cipher(v2[2],p)
cval_a3,q,r=cipher(v1[3],p)
cval_b3,q,r=cipher(v2[3],p)
print(bcolors.OKGREEN+'Cipher Text : Number 1'+bcolors.ENDC)
print cval_a0,cval_a1,cval_a2,cval_a3
print(bcolors.OKGREEN+'Cipher Text : Number 2'+bcolors.ENDC)
print cval_b0,cval_b1,cval_b2,cval_b3
raw_input("\nComputations : Continue ...")
print(bcolors.OKGREEN+'\n\n# Computing On Encrypted Data >>')
print("-----------------------------------------------------------------------------------------------------")
print (bcolors.OKGREEN+'Addition \t: Answer in Encrypted form'+bcolors.ENDC)
#c_sum1,c_carryout=FA(cval_a0,cval_b0,c_carryin )
#c_sum2,c_carryout=FA(cval_a1,cval_b1,c_carryout )
#c_sum3,c_carryout=FA(cval_a2,cval_b2,c_carryout )
#c_sum4,c_carryout=FA(cval_a3,cval_b3,c_carryout )
c_sum1,c_sum2,c_sum3,c_sum4,c_carryout = FOURBITADDER(cval_a0,cval_a1,cval_a2,cval_a3,cval_b0,cval_b1,cval_b2,cval_b3,c_carryin)
print c_sum1,c_sum2,c_sum3,c_sum4
#decrypt
sum1 = (c_sum1 % p) % 2
sum2 = (c_sum2 % p) % 2
sum3 = (c_sum3 % p) % 2
sum4 = (c_sum4 % p) % 2
carryout = (c_carryout % p) % 2
print (bcolors.OKGREEN+'Subtraction \t: Answer in Encrypted form'+bcolors.ENDC)
c_carryin,q,r=cipher(1,p)
c_sum1_,c_carryout=FA(cval_a0,XOR(cval_b0,c_carryin),c_carryin )
c_sum2_,c_carryout=FA(cval_a1,XOR(cval_b1,c_carryin),c_carryout )
c_sum3_,c_carryout=FA(cval_a2,XOR(cval_b2,c_carryin),c_carryout )
c_sum4_,c_carryout=FA(cval_a3,XOR(cval_b3,c_carryin),c_carryout )
#c_sum1_,c_sum2_,c_sum3_,c_sum4_,c_carryout = FOURBITADDER(cval_a0,cval_a1,cval_a2,cval_a3,cval_b0,cval_b1,cval_b2,cval_b3,c_carryin)
print c_sum1_,c_sum2_,c_sum3_,c_sum4_
sum1_ = (c_sum1_ % p) % 2
sum2_ = (c_sum2_ % p) % 2
sum3_ = (c_sum3_ % p) % 2
sum4_ = (c_sum4_ % p) % 2
carryout = (c_carryout % p) % 2
print(bcolors.OKGREEN+'Multiplication \t: Answer in Encrypted form'+bcolors.ENDC)
#c_mul1 = AND(cval_a0,cval_b0)
#c_mul2,c_carryout = HA(AND(cval_a1,cval_b0),AND(cval_a0,cval_b1))
#c_mul3,c_mul4 = HA(c_carryout,AND(cval_a1,cval_b1))
c_mul1,c_mul2,c_mul3,c_mul4 = TWOBITMUL(cval_a0,cval_a1,cval_b0,cval_b1)
print c_mul1,c_mul2,c_mul3,c_mul4
mul1 = (c_mul4 % p) % 2
mul2 = (c_mul3 % p) % 2
mul3 = (c_mul2 % p) % 2
mul4 = (c_mul1 % p) % 2
#c_mul1,c_mul2,c_mul3,c_mul4,c_mul5,c_mul6 = THREEBITMUL(cval_a0,cval_a1,cval_a2,cval_b0,cval_b1,cval_b2)
#mul1 = (c_mul6 % p) % 2
#mul2 = (c_mul5 % p) % 2
#mul3 = (c_mul4 % p) % 2
#mul4 = (c_mul3 % p) % 2
#mul5 = (c_mul2 % p) % 2
#mul6 = (c_mul1 % p) % 2
#print(c_mul1,c_mul2,c_mul3,c_mul4,c_mul5,c_mul6)
print(bcolors.OKGREEN+'Comparison \t: Answer in Encrypted form'+bcolors.ENDC)
cipher_older = inv(cval_a1)*cval_b1 + inv(cval_a1)*inv(cval_a0)*cval_b0 + inv(cval_a0)*cval_b1*cval_b0
print cipher_older
compresult = (cipher_older % p) % 2
raw_input("\nDecryption : Continue ...")
print(bcolors.OKGREEN+'\n\n# Decyption of computation results >>')
print("-----------------------------------------------------------------------------------------------------")
print'Number 1:',val1
print'Number 2:',val2
print'\nResult of Addition\t: ',sum4,sum3,sum2,sum1,' -> ',sum4*8+sum3*4+sum2*2+sum1*1
#print'Carry-out:\t',carryout
print'Result of Substraction\t: ',sum4_,sum3_,sum2_,sum1_,' -> ',sum4_*8+sum3_*4+sum2_*2+sum1_*1
print'Result of Multiplication: ',mul1,mul2,mul3,mul4,' -> ',mul1*8+mul2*4+mul3*2+mul4*1
if (compresult==1):
print'Result of Comparison\t: ',compresult,'\t -> Number 2 is greter than Number 1'
else:
print'Result of Comparison\t: ',compresult,'\t -> Number 2 is NOT greter than Number 1'
print(bcolors.ENDC)
|
1ccb06e849cbfddb4d6b6944c5ced71f63c927f9 | ravikailash/CtCI-6th-Edition-Python | /Chapter16/6_Smallest_Difference.py | 1,524 | 4.03125 | 4 | '''
Exercise: 16.6 Smallest Difference
Find the pair with the least difference (one from each array)
Example:
Input : [1, 3, 15, 11, 2], [23, 127, 235, 19, 8]
Output: 3, (11, 8)
'''
import sys
# Function to sort the arrays in O(nlog(n))
def merge_sort(arr):
# function to create the partitions
def make_partition(arr):
if len(arr) <= 1:
return arr
middle = len(arr) // 2
left = make_partition(arr[:middle])
right = make_partition(arr[middle:])
return merge_partition(left, right)
# function to merge the array partitions
def merge_partition(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
return make_partition(arr)
# Function to find the smallest difference
def find_smallest_difference(array1, array2):
array1 = merge_sort(array1)
array2 = merge_sort(array2)
a, b, difference = 0, 0, sys.maxsize
pair = []
while a < len(array1) and b < len(array2):
if abs(array1[a] - array2[b]) < difference:
difference = abs(array1[a] - array2[b])
pair = [array1[a], array2[b]]
if array1[a] < array2[b]:
a += 1
else:
b += 1
return difference, pair
# driver main
if __name__ == '__main__':
test_case = [[[1, 3, 15, 11, 2], [23, 127, 235, 19, 8]],
[[2, 11, 15, 1], [12, 4, 235, 19, 127, 23]]]
for case in test_case:
print(find_smallest_difference(case[0], case[1]))
|
312a2e85b4ccda00f60582c622cef45399f840ff | aayushidwivedi01/puzzles-uninformed-search | /test_hw2.py | 4,160 | 3.59375 | 4 | import homework2 as hw # this imports our code in example.py, assuming it is in the same directory
import unittest
class TestProblem1(unittest.TestCase):
def test_num_placements_all(self):
print "PROD:{}".format(hw.num_placements_all(3))
def test_num_placements_one_per_row(self):
self.assertEqual(hw.num_placements_one_per_row(2), 8)
self.assertEqual(hw.num_placements_one_per_row(3), 162)
self.assertEqual(hw.num_placements_one_per_row(5), 375000)
def test_n_queens_valid(self):
l = [0,0]
self.assertFalse(hw.n_queens_valid(l))
self.assertTrue(hw.n_queens_valid([0,2]))
self.assertFalse(hw.n_queens_valid([0, 1]))
self.assertTrue(hw.n_queens_valid([0, 3, 1]))
self.assertTrue(hw.n_queens_valid([6,4,2,0,5,7,1,3]))
def test_n_queens_solutions(self):
solutions = list(hw.n_queens_solutions(6));
for solution in solutions:
print solution
print "Total:{}".format(len(list(solutions)))
class TestProblem2(unittest.TestCase):
def test_init(self):
board = [[False, False],[True, True]]
lights = hw.LightsOutPuzzle(board);
self.assertEqual(lights.get_board(), board)
def test_create_puzzle(self):
p = hw.create_puzzle(2,3)
self.assertEquals(p.get_board(),\
[[False, False, False], [False, False, False]])
def test_perform_move(self):
p = hw.create_puzzle(3, 3)
p.perform_move(1, 1)
self.assertEquals( p.get_board(), [[False, True, False],\
[True, True, True ],\
[False, True, False]])
p2 = hw.create_puzzle(3, 3)
p2.perform_move(0, 0)
self.assertEquals( p2.get_board(),[[True, True, False],\
[True, False, False],\
[False, False, False]])
def test_scramble(self):
p = hw.create_puzzle(3,3)
p.scramble();
print p.get_board()
def test_is_solved(self):
p = hw.create_puzzle(3,3)
self.assertTrue(p.is_solved())
b = [[True,True], [False, True]]
p = hw.LightsOutPuzzle(b)
self.assertFalse(p.is_solved())
def test_successors(self):
p = hw.create_puzzle(2, 2)
for move, new_p in p.successors():
print move, new_p.get_board()
for i in range(2, 6):
p = hw.create_puzzle(i, i + 1);
print len(list(p.successors()))
def test_find_solution(self):
p = hw.create_puzzle(2, 3)
for row in range(2):
for col in range(3):
p.perform_move(row, col)
self.assertEqual(p.find_solution(), [(0, 0), (0, 2)])
class TestProblem3(unittest.TestCase):
def test_is_solved(self):
t = [True, True, False, False];
self.assertFalse(hw.is_solved(t, 4, 2));
t2 = [False, True, True]
self.assertTrue(hw.is_solved(t2, 3,2));
def test_solve_identical_disks(self):
p = hw.solve_identical_disks(4, 2);
self.assertEqual(p, [(0, 2), (1, 3)]);
p = hw.solve_identical_disks(5, 2);
self.assertEqual(p, [(0, 2), (1, 3), (2, 4)]);
p = hw.solve_identical_disks(4, 3);
self.assertEqual(p , [(1, 3), (0, 1)]);
p = hw.solve_identical_disks(5, 3);
self.assertEqual(p , [(1, 3), (0, 1), (2, 4), (1, 2)]);
def test_create_distince_disks(self):
p = hw.create_distinct_disks(5,3);
self.assertEqual(p, [ 1, 2, 3, 0, 0]);
def test_create_goal(self):
p = hw.create_goal(5, 3)
self.assertEqual(p, [0, 0, 3, 2, 1]);
def test_solve_distinct_disks(self):
p = hw.solve_distinct_disks(4, 2);
self.assertEqual(p, [(0, 2), (2, 3), (1, 2)]);
p = hw.solve_distinct_disks(4, 3);
self.assertEqual(p, [(1, 3), (0, 1), (2, 0), (3, 2), (1, 3),(0, 1)]);
p = hw.solve_distinct_disks(10, 5);
#self.assertEqual(p, [(1, 3), (2, 1), (0, 2), (2, 4), (1, 2)]);
print len(p)
if __name__ == '__main__':
unittest.main()
|
df7821e9150c8313a38474711a7219b5e62817b0 | chibby0ne/data_science_book | /statistics.py | 6,056 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Counter
from matplotlib import pyplot as plt
from linear_algebra import sum_of_squares, dot
import math
num_friends = [100, 49, 41, 40, 25 ]
daily_minutes = [20, 10, 5, 4, 15 ]
friend_counts = Counter(num_friends)
xs = range(101)
ys = [friend_counts[x] for x in xs]
plt.bar(xs, ys)
plt.axis([0, 101, 0, 25])
plt.title("Histogram of Friend Counts")
plt.xlabel("# of friends")
plt.ylabel("# of people")
# plt.show()
num_points = len(num_friends)
print(num_points)
largest_value = max(num_friends)
print(largest_value)
smallest_value = min(num_friends)
print(smallest_value)
sorted_values = sorted(num_friends)
smallest_value = sorted_values[0]
second_smallest_value = sorted_values[1]
second_largest_value = sorted_values[-2]
#################
#
# Central Tendencies
#
#################
#
#
def mean(x):
"""TODO: Docstring for mean.
:x: TODO
:returns: TODO
"""
return sum(x) / len(x)
print(mean(num_friends))
# The mean is too supceptible to outliers, and if we are sure that outliers are
# just bad data then the mean is a better measure of the central tendency
def median(v):
"""TODO: Docstring for function.
:arg1: TODO
:returns: TODO
"""
n = len(v)
sorted_v = sorted(v)
midpoint = n // 2
if n % 2 == 1:
return sorted_v[midpoint]
else:
lo = midpoint - 1
hi = midpoint
return (sorted_v[lo] + sorted_v[hi]) / 2
print(median(num_friends))
# Is a generalization of median
# Represents the value less than which a certain percentile of the data lies
def quantile(x, p):
"""returns the pth-percentile value in x
:x: list
:p: percentile value
:returns: TODO
"""
p_index = int(p * len(x))
return sorted(x)[p_index]
quantile(num_friends, 0.10)
quantile(num_friends, 0.25)
quantile(num_friends, 0.75)
quantile(num_friends, 0.90)
# Most common value
def mode(x):
"""returns a list, wmight be more than a node
:x: list of input
:returns: TODO
"""
counts = Counter(x)
max_count = max(counts.values())
return [x_i for x_i, count in counts.items()
if count == max_count]
mode(num_friends)
#########################################
#
# Dispersion - how spread out is the data
#
########################################
# "range" already means something in Python, so we'll use a different name
# range is just the difference between the largest and the smallest value
# A very simple measure of dispersion is just the difference between the largest and smallest elements
def data_range(x):
"""TODO: Docstring for data_range.
:x: TODO
:returns: TODO
"""
return max(x) - min(x)
data_range(num_friends)
# A more complex measure of dispersion is the variance
def de_mean(x):
"""translate x by substracting its mean (so the result has mean 0)
:x: list
:returns:
"""
x_bar = mean(x)
return [x_i - x_bar for x_i in x]
def variance(x):
"""assumes x has at least two elements
:x: list
:returns: variance integer
"""
n = len(x)
deviations = de_mean(x)
return sum_of_squares(deviations) / (n - 1)
variance(num_friends)
# Note that whatever units our data is in, all of our measures of central tendency are in the same unit.
# The reange will similarly be in the same unit.
# The variance on the other hand has units that are the squares of the original units
def standard_deviation(x):
"""TODO: Docstring for standard_deviation.
:x: list
:returns: integer
"""
return math.sqrt(variance(x))
standard_deviation(num_friends)
# Both the range and the mean have the same outlier problem that we saw earlier with the mean.
# A more robust alternative computes the difference between the 75th percentile value and the 25th percentile value:
# Which is quite plainly unaffected by a small number of outliers
def interquartile_range(x):
"""TODO: Docstring for interquartile_range.
:x: TODO
:returns: TODO
"""
return quantile(x, 0.75) - quantile(x, 0.25)
#################################
#
# Correlation - relation of one thing with another
#
#################################
# The paired analoge of variance.
# Whereas variance measure how a single variable deviates from its mean,
# Covariance measures how to variables vary in tandem from their means
def covariance(x, y):
""" x and y should have the same length
:x: first variable (list)
:y: second variable (list)
:returns: integer
"""
n = len(x)
return dot(de_mean(x), de_mean(y)) / (n - 1)
# dot sums up the products of corresponding pairs of elements
# when corresponding elements of x and y are either both above their means or both below their means, a positive number enters the sum
# Whe one is above its mean and the other below, a negative number enters the sum.
# Correspondingly, a large positive covariance means that x tends to be large when y is larger and small when y is small.
# Correspondingly, a large negative covariance means that x tends to be large when y is small and small when y is large.
# A covariance close to zero means that no such relationship exists
print(covariance(num_friends, daily_minutes))
# It can b ehard to interpret the covariance for a copuple of reasons
# 1. Its units are the products of the inputs unitns which can be hard to make sense of.
# 2. If each user had twice as many friends (but the same number of minutes), the covariance would be twice as large.
# But in a sense the variables would be just as interrelated. Said differently, it's hard to say what counts as a "large" covariance
def correlation(x, y):
"""Calculates the correlation between two variables
:x: list
:y: list
:returns:
"""
stdev_x = standard_deviation(x)
stdev_y = standard_deviation(y)
if stdev_x > 0 and stdev_y > 0:
return covariance(x, y) / stdev_x / stdev_y
else:
return 0
print(correlation(num_friends, daily_minutes))
|
eeb00931ba248bbd9bf559f1d9b00182afbb0667 | FraugDib/algorithms | /money_change.py | 4,602 | 4.1875 | 4 | import time
def find_change(results, current_decomposition, n, denominations):
"""Find changes
Arguments
results -- accumulate result in an array. Each item is also an array
current_decomposition -- decomposition of n in denominations
n -- number to decompose. Does not change
denominations -- array of denominations to be used for decomposition
"""
# Guard conditions to stop the recursion
if sum(current_decomposition) == n:
results.append(list(current_decomposition))
return
elif sum(current_decomposition) > n:
return
# We first iterate through the denominations
# then recursively call the function to continue
# to find the remaining decomposition in denomination of n
for denomination in denominations:
my_current_decomposition = list(current_decomposition)
my_current_decomposition.append(denomination)
find_change(results, my_current_decomposition, n, denominations)
return
def main():
# Test 1 #############################################
expected_results =[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
test(n=10,denominations=[1], expected_results=expected_results)
# Test 2 #############################################
expected_results = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 8],
[1, 8, 1],
[8, 1, 1]]
test(n=10,denominations=[1, 8], expected_results=expected_results)
# Test 3 #############################################
expected_results =[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 7],
[1, 1, 7, 1],
[1, 1, 8],
[1, 7, 1, 1],
[1, 8, 1],
[7, 1, 1, 1],
[8, 1, 1]]
test(n=10,denominations=[1, 7, 8], expected_results=expected_results)
# Test 3 #############################################
expected_results =[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 3],
[1, 1, 1, 1, 1, 1, 3, 1],
[1, 1, 1, 1, 1, 3, 1, 1],
[1, 1, 1, 1, 1, 5],
[1, 1, 1, 1, 3, 1, 1, 1],
[1, 1, 1, 1, 3, 3],
[1, 1, 1, 1, 5, 1],
[1, 1, 1, 3, 1, 1, 1, 1],
[1, 1, 1, 3, 1, 3],
[1, 1, 1, 3, 3, 1],
[1, 1, 1, 5, 1, 1],
[1, 1, 3, 1, 1, 1, 1, 1],
[1, 1, 3, 1, 1, 3],
[1, 1, 3, 1, 3, 1],
[1, 1, 3, 3, 1, 1],
[1, 1, 3, 5],
[1, 1, 5, 1, 1, 1],
[1, 1, 5, 3],
[1, 3, 1, 1, 1, 1, 1, 1],
[1, 3, 1, 1, 1, 3],
[1, 3, 1, 1, 3, 1],
[1, 3, 1, 3, 1, 1],
[1, 3, 1, 5],
[1, 3, 3, 1, 1, 1],
[1, 3, 3, 3],
[1, 3, 5, 1],
[1, 5, 1, 1, 1, 1],
[1, 5, 1, 3],
[1, 5, 3, 1],
[3, 1, 1, 1, 1, 1, 1, 1],
[3, 1, 1, 1, 1, 3],
[3, 1, 1, 1, 3, 1],
[3, 1, 1, 3, 1, 1],
[3, 1, 1, 5],
[3, 1, 3, 1, 1, 1],
[3, 1, 3, 3],
[3, 1, 5, 1],
[3, 3, 1, 1, 1, 1],
[3, 3, 1, 3],
[3, 3, 3, 1],
[3, 5, 1, 1],
[5, 1, 1, 1, 1, 1],
[5, 1, 1, 3],
[5, 1, 3, 1],
[5, 3, 1, 1],
[5, 5]]
test(n=10,denominations=[1, 3, 5], expected_results=expected_results)
def test(n, denominations, expected_results):
print("Testing `find_change()` for n: {}, denominations: {}".format(n, denominations))
results = []
current_decomposition = []
start = time.time()
find_change(results, current_decomposition, n, denominations)
end = time.time()
print("Time elapsed: {}".format(end - start))
print("Results: \n{}\n".format(results))
assert (results == expected_results)
main()
|
71e3cde9c72a32fbe851556cd631bf4197683cec | hellosheng1989/Tree-Regression-etc | /decision boundary plot learning.py | 1,399 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 20:41:46 2015
@author: SSL
"""
#
# Example code that shows how to plot the function value and a decision
# boundary for a simple logistic regression model using python
#
# Author: Nathan Jacobs (with some initial code by Hampton Young)
#
import numpy as np
from scipy.special import expit
import matplotlib.pyplot as plt
# define our hypothesis (vectorized!)
def f(x):
return expit(np.matrix([0, 1, -.5,.5])*x);
# create the domain for the plot
x_min = -5; x_max = 5
y_min = -5; y_max = 5
x1 = np.linspace(x_min, x_max, 200)
y1 = np.linspace(y_min, y_max , 200)
x,y = np.meshgrid(x1, y1)
#
# evalute it in a vectorized way (and reshape into a matrix)
#
# make a 3 x N matrix of the sample points
data = np.vstack((
np.ones(x.size), # add the bias term
x.ravel(), # make the matrix into a vector
y.ravel(),
y.ravel()**2)) # add a quadratic term for fun
z = f(data)
z = z.reshape(x.shape)
#
# Make the plots
#
# show the function value in the background
cs = plt.imshow(z,
extent=(x_min,x_max,y_max,y_min), # define limits of grid, note reversed y axis
cmap=plt.cm.jet)
plt.clim(0,1) # defines the value to assign the min/max color
# draw the line on top
levels = np.array([.5])
cs_line = plt.contour(x,y,z,levels)
# add a color bar
CB = plt.colorbar(cs)
plt.show()
|
b4a12f6745de0c32fcbcccaef64c8417b1c8db50 | Limmen/Distributed_ML | /lab2/fashon_mnist_tf/task2/task2.py | 8,610 | 3.734375 | 4 | # Task 2 - Feed-Forward NN with 4 layers
# 1. See results in stats.txt, A bit more overfitting in this task since the model is more powerful.
# We got better accuracy with ReLU, they had about the same overfitting but ReLU was just higher accuracy overall.
# 2. ReLU gives faster convergence than sigmoid.
# Reasons: sigmoid is more likely to suffer vanishing gradient (saturates when activation is close to 1 or -1)
# sigmoid smaller derivative over all. ReLU higher derivative (can be a problem if it is too high though)
# Problem with ReLU is that ReLU units can die, however does not seem to be a problem in this small network.
# Initialize weights and bias to non-zero help avoid dying ReLU.
# 3. Reason for softmax is that we do multinomial classification,
# softmax layer outputs vector of probabilities rather than scalar. Sigmoid not as easy to
# do multinomial classification. Softmax is also suited for the loss function cross-entropy (log undo exp)
# 4. Yes, in terms of accuracy we can see it sometimes dropping in both training and test data,
# this might indicate that it overshoot a local minima, either due to learning rate being too high, or
# because the approximate gradient (SGD) was not correct. Sometimes the accuracy drop in both.
# Sometimes accuracy drop in only test-data, that indicates overfitting and can be improved with regularization.
# Sometimes accuracy drop in training data only, that might indicate that it was
# a training-batch very different from the previous batches and also different than the test-data.
# The same phenomena can be observed on the loss-plot (loss increase rather than accuracy decrease)
from __future__ import print_function
# all tensorflow api is accessible through this
import tensorflow as tf
# to visualize the resutls
import matplotlib.pyplot as plt
# 70k mnist dataset that comes with the tensorflow container
from tensorflow.examples.tutorials.mnist import input_data
# Enable deterministic comparisons between executions
tf.set_random_seed(0)
# constants
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE
NUM_CLASSES = 10
GD_LEARNING_RATE = 0.5
ADAM_LEARNING_RATE = 0.005
NUM_HIDDEN_1 = 200
NUM_HIDDEN_2 = 100
NUM_HIDDEN_3 = 60
NUM_HIDDEN_4 = 30
# load data
mnist = input_data.read_data_sets('../data/fashion', one_hot=True, validation_size=0)
print('Number of train examples in dataset ' + str(len(mnist.train.labels)))
print('Number of test examples in dataset ' + str(len(mnist.test.labels)))
# Define placeholders for input data and for input truth labels
x = tf.placeholder(tf.float32,
[None, IMAGE_SIZE, IMAGE_SIZE, 1]) # training examples (just one color channel, i.e grayscale)
y_ = tf.placeholder(tf.float32, [None, NUM_CLASSES]) # correct answers(labels)
# Define variables for the parameters of the model: Weights and biases, random-initialization with gaussian dist.
w_1 = tf.Variable((tf.truncated_normal([784, NUM_HIDDEN_1], stddev=0.1)))
b_1 = tf.Variable(tf.zeros([NUM_HIDDEN_1]))
w_2 = tf.Variable((tf.truncated_normal([NUM_HIDDEN_1, NUM_HIDDEN_2], stddev=0.1)))
b_2 = tf.Variable(tf.zeros([NUM_HIDDEN_2]))
w_3 = tf.Variable((tf.truncated_normal([NUM_HIDDEN_2, NUM_HIDDEN_3], stddev=0.1)))
b_3 = tf.Variable(tf.zeros([NUM_HIDDEN_3]))
w_4 = tf.Variable((tf.truncated_normal([NUM_HIDDEN_3, NUM_HIDDEN_4], stddev=0.1)))
b_4 = tf.Variable(tf.zeros([NUM_HIDDEN_4]))
w_5 = tf.Variable((tf.truncated_normal([NUM_HIDDEN_4, NUM_CLASSES], stddev=0.1)))
b_5 = tf.Variable(tf.zeros([NUM_CLASSES]))
# 2. Define the model - compute predicitions
xx = tf.reshape(x, [-1, IMAGE_PIXELS]) # flatten the images into a single vector of pixels (1D input, not 2D)
# Hidden unit acitvations : ReLU or Sigmoid
hidden1 = tf.nn.relu(tf.matmul(xx, w_1) + b_1)
hidden2 = tf.nn.relu(tf.matmul(hidden1, w_2) + b_2)
hidden3 = tf.nn.relu(tf.matmul(hidden2, w_3) + b_3)
hidden4 = tf.nn.relu(tf.matmul(hidden3, w_4) + b_4)
# hidden1 = tf.nn.sigmoid(tf.matmul(xx, w_1) + b_1)
# hidden2 = tf.nn.sigmoid(tf.matmul(hidden1, w_2) + b_2)
# hidden3 = tf.nn.sigmoid(tf.matmul(hidden2, w_3) + b_3)
# hidden4 = tf.nn.sigmoid(tf.matmul(hidden3, w_4) + b_4)
# Compute the logits, aka the inverse of the sigmoid/softmax outputs
logits = tf.matmul(hidden4, w_5) + b_5
# Define the loss, which is the loss between softmax of logits and the labels
# Tensorflow performs softmax (the output activation) as part of the loss for efficiency
cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=logits, name='xentropy'))
# 4. Define the accuracy
# Correct prediction is black/white, either the classification is correct or not
# Accuracy is the ratio of correct predictions over wrong predictions
correct_predictions = tf.equal(tf.argmax(logits, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
# 5. Train with an Optimizer
#train_step = tf.train.GradientDescentOptimizer(GD_LEARNING_RATE).minimize(cross_entropy_loss)
train_step = tf.train.AdamOptimizer(ADAM_LEARNING_RATE).minimize(cross_entropy_loss)
# initialize and run start operation
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# Function representing a single iteration during training.
# Returns a tuple of accuracy and loss statistics.
def training_step(i, update_test_data, update_train_data):
# actual learning
# reading batches of 100 images with 100 labels
batch_X, batch_Y = mnist.train.next_batch(100)
# the backpropagation training step
sess.run(train_step, feed_dict={xx: batch_X, y_: batch_Y})
# evaluating model performance for printing purposes
# evaluation used to later visualize how well you did at a particular time in the training
train_a = [] # Array of training-accuracy for a single iteration
train_c = [] # Array of training-cost for a single iteration
test_a = [] # Array of test-accuracy for a single iteration
test_c = [] # Array of test-cost for a single iteration
# If stats for train-data should be updates, compute loss and accuracy for the batch and store it
if update_train_data:
train_acc, train_cos = sess.run([accuracy, cross_entropy_loss], feed_dict={xx: batch_X, y_: batch_Y})
train_a.append(train_acc)
train_c.append(train_cos)
# If stats for test-data should be updates, compute loss and accuracy for the batch and store it
if update_test_data:
test_acc, test_cos = sess.run([accuracy, cross_entropy_loss],
feed_dict={xx: mnist.test.images, y_: mnist.test.labels})
test_a.append(test_acc)
test_c.append(test_cos)
return train_a, train_c, test_a, test_c
# 6. Train and test the model, store the accuracy and loss per iteration
train_accuracy = [] # Array of training-accuracy for each epoch
train_cost = [] # Array of training-cost for each epoch
test_accuracy = [] # Array of test-accuracy for each epoch
test_cost = [] # Array of test-cost for each epoch
NUM_TRAINING_ITER = 10000
NUM_EPOCH_SIZE = 100
for i in range(NUM_TRAINING_ITER):
test = False
if i % NUM_EPOCH_SIZE == 0:
test = True
print("iter: " + str(i))
a, c, ta, tc = training_step(i, test, test) # Get the statistics for this training step
# Update the stats with stats for this training step
train_accuracy += a
train_cost += c
test_accuracy += ta
test_cost += tc
# 7. Plot and visualise the accuracy and loss
print('Final test accuracy ' + str(test_accuracy[-1]))
print('Final test loss ' + str(test_cost[-1]))
# accuracy training vs testing dataset
plt.plot(train_accuracy, label='Train data')
plt.xlabel('Epoch')
plt.plot(test_accuracy, label='Test data')
plt.ylabel('Accuracy')
plt.grid(True)
plt.legend()
plt.title('Accuracy per epoch train vs test')
plt.show()
# loss training vs testing dataset
plt.plot(train_cost, label='Train data')
plt.plot(test_cost, label='Test data')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Loss per epoch, train vs test')
plt.grid(True)
plt.show()
# Zoom in on the tail of the plots
zoom_point = 50
x_range = range(zoom_point, int(NUM_TRAINING_ITER / NUM_EPOCH_SIZE))
plt.plot(x_range, train_accuracy[zoom_point:])
plt.plot(x_range, test_accuracy[zoom_point:])
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.title('Accuracy per epoch train vs test')
plt.legend()
plt.grid(True)
plt.show()
plt.plot(train_cost[zoom_point:])
plt.plot(test_cost[zoom_point:])
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Loss per epoch train vs test')
plt.legend()
plt.grid(True)
plt.show()
|
eddbfcdcac00ce56bd2b01f0b860544ce2ebfe8b | jhonCenaDito/ML | /distance.py | 485 | 3.734375 | 4 | import numpy as np
size1 = int(input("Size of first array:"))
a = np.empty(size1)
for i in range(len(a)):
x = float(input("Element:"))
a[i]=x
print(np.floor(a))
size2 = int(input("Size of second array:"))
b = np.empty(size2)
for i in range(len(b)):
x = float(input("Element:"))
b[i]=x
print(np.floor(b))
q = int(input("Value of q:"))
result = 0
for i in range(len(a)):
result += ((abs(a[i] - b[i])) ** q)
print(result)
result = (result) ** 1/q
print(result) |
dc78fb5c530654bfe6b5bf2c81618e681ba98135 | richjeet/restaurant | /ScatterPlot.py | 778 | 3.71875 | 4 | # SCATTER PLOT
# Import the necessary modules
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn')
# Initialize the lists for X and Y
sp = pd.read_csv('ScatterPlot.csv')
print(sp.head())
Food= sp['MonthlyExpenseFood']
Grocery= sp['MonthlyExpenseGrocery']
ratio = sp['Ratio']
# Plot the data using scatter() method
plt.scatter(Food, Grocery, c= ratio, cmap= 'rainbow', edgecolor= 'black', linewidth= 1, alpha= 0.75)
plt.xscale('log')
plt.yscale('log')
cbar = plt.colorbar()
cbar.set_label('Food/Grocery Ratio')
plt.title('Food & Grocery Expenses Pattern', fontdict={'fontname':'Comic Sans MS' , 'fontsize': 15})
plt.xlabel('Monthly Expenses on Food (in $)')
plt.ylabel('Monthly Expenses on Grocery (in $)')
plt.tight_layout()
# Show the plot
plt.show() |
de62d877172215f9cbb0b30b24e8009b3485bf47 | cpkoywk/IST664_Natural_Language_Processing | /Lab 1/assignment1.py | 1,148 | 4.21875 | 4 | '''
Steps:
get the text with nltk.corpus.gutenberg.raw()
get the tokens with nltk.word_tokenize()
get the words by using w.lower() to lowercase the tokens
make the frequency distribution with FreqDist
get the 30 top frequency words with most_common(30) and print the word, frequency pairs
'''
#Import required modules
import nltk
from nltk import FreqDist
from nltk.corpus import brown
#check what file they've got in gutenberg
nltk.corpus.gutenberg.fileids()
#I will pick 'shakespeare-hamlet.txt'
file0 = nltk.corpus.gutenberg.fileids()[-3]
#file0 = 'shakespeare-hamlet.txt'
#1. get the text with nltk.corpus.gutenberg.raw()
hamlettext=nltk.corpus.gutenberg.raw(file0)
#2. Get the tokens with nltk.word_tokenize()
hamlettokens = nltk.word_tokenize(hamlettext)
#3. Get the words by using w.lower() to lowercase the tokens
hamletwords = [w.lower() for w in emmatokens]
#4. make the frequency distribution with FreqDist
fdist = FreqDist(hamletwords)
fdistkeys=list(fdist.keys())
#5. get the 30 top frequency words with most_common(30) and print the word, frequency pairs
top30keys=fdist.most_common(30)
for pair in top30keys:
print (pair)
|
3dc68ef09e9d9603205971449f3c33aa0ccadb8b | HarshadMahajan/Python | /ImpPrograms/JumpCheck.py | 570 | 3.84375 | 4 | def checkJump(list2):
list3=[]
jump=0
for i in range(0,len(list2)):
if list2[i]==0:
list3.append(i)
print(list3)
for j in range(0,len(list3)-1):
if list3[j+1]-list3[j]==1:
print("here")
pass
else:
print("there")
jump+=1
return jump
list1=[]
ip=int(input("How many numbers"))
'''for i in range(ip):
val=int(input("Enter the value"))
list1.append(val)'''
list1=[0,1,0,0,0,1,0]
output=checkJump(list1)
print(output)
|
d15ec60b357e0fa12ca61ab6de77dd4e47b39af5 | HarshadMahajan/Python | /challange-Coderbyte/map-and-lambda-expression/map-and-lambda-expression.py | 237 | 3.625 | 4 | #!/usr/bin/env python
N = int(raw_input())
if N == 0:
fibs = []
elif N == 1:
fibs = [0]
else:
fibs = [0, 1]
while N > len(fibs):
fibs.append(fibs[-1] + fibs[-2])
assert len(fibs) == N
print map(lambda x: x**3, fibs)
|
f6b1e488b4e9ffe777ebf095f8b0f6f971a46869 | HarshadMahajan/Python | /Data Types/1-python-lists.py | 644 | 4.09375 | 4 | #!/usr/bin/python
t = int(raw_input())
nums = []
for i in range(0, t):
orgs = raw_input().split(' ')
if orgs[0] == "insert":
nums.insert(int(orgs[1]), int(orgs[2]))
elif orgs[0] == "append":
nums.append(int(orgs[1]))
elif orgs[0] == "remove":
nums.remove(int(orgs[1]))
elif orgs[0] == "pop":
nums.pop()
elif orgs[0] == "index":
print nums.index(int(orgs[1]))
elif orgs[0] == "count":
print nums.count(int(orgs[1]))
elif orgs[0] == "sort":
nums.sort()
elif orgs[0] == "reverse":
nums.reverse()
elif orgs[0] == "print":
print nums
|
e6d41b36bad86757c9ddf5f06950d5d85d284580 | HarshadMahajan/Python | /challange-Coderbyte/find-angle/find-angle.py | 211 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import division
import math
ab = int(raw_input())
bc = int(raw_input())
c = math.degrees(math.atan(ab / bc))
c = int(round(c))
print str(c) + '°'
|
75878426bcd9e85977798a77469e77306fe37543 | HarshadMahajan/Python | /Classes/2-class-2-find-the-torsional-angle.py | 1,016 | 3.609375 | 4 | import math
class Points():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, O):
x = self.x - O.x
y = self.y - O.y
z = self.z - O.z
return Points(x, y, z)
def dot(self, O):
x = self.x * O.x
y = self.y * O.y
z = self.z * O.z
return x + y + z
def cross(self, O):
x = self.y * O.z - self.z * O.y
y = self.z * O.x - self.x * O.z
z = self.x * O.y - self.y * O.x
return Points(x, y, z)
def absolute_scale(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), .5)
def solve(A, B, C, D):
A, B, C, D = Points(*A), Points(*B), Points(*C), Points(*D)
X = (B - A).cross(C - B)
Y = (C - B).cross(D - C)
angle = math.acos(X.dot(Y) / (X.absolute_scale() * Y.absolute_scale()))
print "%.2f" % math.degrees(angle)
points = list()
for _ in range(4):
points.append(map(float, raw_input().split()))
solve(*points)
|
2b41cfa7994ec770f4f9fcb3a0bcf1cf989eda61 | HarshadMahajan/Python | /challange-Coderbyte/validate-list-of-email-address-with-filter/validate-list-of-email-address-with-filter.py | 344 | 3.78125 | 4 | #!/usr/bin/env python
import re
def isValidAddress(address):
result = re.match(r'[a-zA-z0-9\-_]+@[a-zA-Z0-9]+\..{1,3}$', address)
return True if result else False
N = int(raw_input())
addresses = []
for i in range(N):
addresses.append(raw_input())
addresses = filter(isValidAddress, addresses)
addresses.sort()
print addresses
|
c1560c6661b5e85e379782cc32e4a02df3886530 | HarshadMahajan/Python | /Regex and Parsing/9-validating-named-email-addresses.py | 240 | 3.84375 | 4 | import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z]{1}[\w\-\.]+@[a-zA-Z]+\.[a-zA-Z]{1,3}$')
for _ in range(int(raw_input())):
name, email = raw_input().strip().split()
if (re.match(EMAIL_REGEX, email[1:-1])):
print name, email
|
9690a88dd1eef02c7e87d615b303e9910a2c3e66 | Mukul-Singh-github/Python-Programs-Games- | /BlackJack.py | 4,787 | 3.953125 | 4 |
#This is Black Jack Game
#HOW TO PLAY THE GAME
#There is a dealer and a player they will both have two random cards from the deck of 52
#the player's always plays first.
#the goal is to have total value of our cards close to 21 aur 21.
#if player's total of two card is suppose 15 player can say hit and he/she will be given a random card form the deck by the dealer
#player can get as many cards as he wants from dealer to make his total colse to 21 or 21
#but if players value reaches above 21 the th player is bust and loses the bet amount
#when player is close to 21 and can get bust player can choose to stay that means no more cards will be served to him
#then plays the dealer.
#a rule for dealer is that he has to hit till his cards value greater than or equals to 17.
#once card value exceeds the limit he has to stay.
#then the value is compared.
#value close to 21 aur 21 wins and is value is 21 the person is called the blackjack and wins the 3 times the bet amount
#NOTE: Ace can have two values 1 or 11 player will have to choose according to his situation which value can take closer to 21 or 21.
values={"ace":[1,11],"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"ten":10,"joker":10,"king":10,"queen":10}
name=["ace","two","three","four","five","six","seven","eight","nine","ten","joker","king","queen"]
types=["clubs","hearts","diamond","spade"]
global player_state
player_state=1
class Card:
def __init__(self,card_name,card_type):
self.card_name=card_name
self.card_type=card_type
self.card_value=values[card_name]
def __str__(self):
return f"{self.card_name} of {self.card_type}"
class Deck:
def __init__(self):
self.allcards=[]
for n in name:
for t in types:
card_obj=Card(n,t) #here of card object will be created
self.allcards.append(card_obj)
#shuffle(self.allcards)
class Bank_account:
def __init__(self,name,balance):
self.name=name
self.balance=balance
def check_balance(self):
return f"Your current balance is {self.balance}"
def deposit(self,deposit_amt):
self.balance += deposit_amt
return self.balance
def withdraw(self,withdrawing_amt):
if withdrawing_amt > self.balance:
print(f"Not enough balance! withdrawing amount is {withdrawing_amt} while balance is {self.balance}")
else:
self.balance -= withdrawing_amt
return self.balance
#shuffles the deck
def shuffle_deck(deck):
from random import shuffle
shuffle(deck.allcards)
# hit method
def hit(Who,player_deck,dealer_deck,player_state):
if Who == "p" and player_state != 0:
player_deck = player_deck.append(deck.allcards.pop(0))
elif Who == "d":
dealer_deck = dealer_deck.append(deck.allcards.pop(0))
else:
print("player_state is 0 cannot hit")
# stay method
def stay():
global player_state
player_state=0
def game_reset(player_deck,dealer_deck):
for i in range(0,len(player_deck)): #returning cards to deck from players deck
deck.allcards.append(player_deck.pop(0))
for i in range(0,len(dealer_deck)): #returning cards to deck from dealers deck
deck.allcards.append(dealer_deck.pop(0))
shuffle_deck(deck)
global player_state
player_state = 1
for i in range(0,2): #two cards for player
player_deck.append(deck.allcards.pop(0))
for i in range(0,2): #two cards for dealer
dealer_deck.append(deck.allcards.pop(0))
print(f"Your bank balance is {player_acc.balance}")
bet=int(input("how much you wanna bet! "))
while bet not in range(100, (player_acc.balance+1)):
bet=int(input("bet range error!"))
player_move()
# Main game logic
def player_situation(player_sum):
if player_sum > 21:
print("Player Bust!!, the bet amt is lost ")
player_acc.balance -= bet
return True
elif player_sum == 21:
print("Player is a BlackJack")
player_acc.balance+=int(bet+bet*1.5)
return True
else:
return False
def dealer_situation(dealer_sum):
if dealer_sum > 21:
player_acc.balance+=(bet+bet)
print("Deaer Bust!!, Player gets doubled bet amt")
return True
if dealer_sum == 21:
print("Dealer is a BlackJack")
player_acc.balance -= bet
return True
else:
return False
def win_check(player_sum,dealer_sum,):
if player_sum > dealer_sum:
print("Players total is greater than dealers total, Player Wins!! ","\n",)
player_acc.balance += (bet+bet)
return True
elif dealer_sum > player_sum:
print("Dealers total is greater than Players total, Dealer Wins!! ","\n")
player_acc.balance -= bet
return True
elif dealer_sum == player_sum:
print("dealers and Players sum is equal, It's a tie!!","\n")
return True
else:
return False
|
15a79024657a7564d79b63195c64e1b75e56f5b7 | niall-oc/things | /codility/fish.py | 4,904 | 3.78125 | 4 |
# -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/
You are given two non-empty arrays A and B consisting of N integers.
Arrays A and B represent N voracious fish in a river, ordered downstream
along the flow of the river.
The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q,
then fish P is initially upstream of fish Q. Initially, each fish has a
unique position.
Fish number P is represented by A[P] and B[P]. Array A contains the sizes
of the fish. All its elements are unique. Array B contains the directions
of the fish. It contains only 0s and/or 1s, where:
0 represents a fish flowing upstream,
1 represents a fish flowing downstream.
If two fish move in opposite directions and there are no other (living)
fish between them, they will eventually meet each other. Then only one
fish can stay alive − the larger fish eats the smaller one. More precisely,
we say that two fish P and Q meet each other when P < Q, B[P] = 1 and
B[Q] = 0, and there are no living fish between them. After they meet:
If A[P] > A[Q] then P eats Q, and P continues flowing downstream,
If A[Q] > A[P] then Q eats P, and Q continues flowing upstream.
We assume that all the fish are flowing at the same speed. That is, fish
moving in the same direction never meet. The goal is to calculate the
number of fish that will stay alive.
For example, consider arrays A and B such that:
A[0] = 4 B[0] = 0
A[1] = 3 B[1] = 1
A[2] = 2 B[2] = 0
A[3] = 1 B[3] = 0
A[4] = 5 B[4] = 0
Initially all the fish are alive and all except fish number 1 are moving
upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish
number 3 and eats it too. Finally, it meets fish number 4 and is eaten by
it. The remaining two fish, number 0 and 4, never meet and therefore stay
alive.
Write a function:
def solution(A, B)
that, given two non-empty arrays A and B consisting of N integers,
returns the number of fish that will stay alive.
For example, given the arrays shown above, the function should return 2,
as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of A[] is an integer within the range [0..1,000,000,000];
each element of B[] is an integer that can have one of the following values: 0, 1;
the elements of A are all distinct.
# 100% solution https://app.codility.com/demo/results/trainingXUEZDW-AC7/
"""
import time
def solution(A, B):
"""
Similar to the passing cars problem, the passing fish eat each other.
Each downstream fish is pushed onto the downstream stack.
Upstream fish are considered survivors if not eaten.
When an upstream fish is encountered the downstream fish in its path are popped
Each fish size is compared and teh smaller discarded.
"""
downstream = []
survivor = []
for i in range(0, len(A)):
print(f'pass {i}')
if B[i]: # If a fish is swimming downstream place him in that stack
downstream.append(A[i])
# print(f'survivor: <--{survivor}, downstream: {downstream}--> {A[i]} is A[{i}] -- Downstream encountered')
continue
elif downstream: # If the fish is swiming upstream and there are fish in the downstream
while downstream:
if downstream[-1] < A[i]: # This fish is compared to the downstream fish.
# print(f'survivor: <--{survivor}, downstream: {downstream}--> {A[i]} is A[{i}]')
downstream.pop()
else:
break # When this current fish is eaten by a downstream fish
else: # All the downstream fish are eaten by the current upstream fish
survivor.append(A[i])
# print(f'survivor: <--{survivor}, downstream: {downstream}-->')
else: # All the downstream fish are eaten
survivor.append(A[i])
# print(f'survivor: <--{survivor}, downstream: {downstream}-->')
# print(f'survivor: <--{survivor}, downstream: {downstream}-->')
return len(survivor+downstream)
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(2, ([4, 3, 2, 1, 5], [0, 1, 0, 0, 0])),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!') |
1a50b33e46332742fb6a5beb00dee504f4560a8f | niall-oc/things | /puzzles/grid8/grid8.py | 3,303 | 4.09375 | 4 | """
### FILL IN THE GRID PUZZLE
Objective: Arange the numbers 1 through 8 in the grid below.
+---+---+
| | |
+---+---+---+---+
| | | | |
+---+---+---+---+
| | |
+---+---+
RULES:
No consecutive numbers may appear next to each other either vertically, horizontally or diagonally.
Each number may only be used once.
"""
from copy import deepcopy
# Operating on the premise that a gird is in reality a collection of x,y coordinates.
# A grid state could be
# { (1,2,): 1, (1,3,): None,
# (2,1,): None, (2,2,): None, (2,3,): None, (2,4,): None,
# (3,2,): None, (3,3,): None }
# +---+---+
# | 1 | |
# +---+---+---+---+
# | | | | |
# +---+---+---+---+
# | | |
# +---+---+
# At the begining of the game no number is assigned to any position on the grid.
GRID = {
(1, 2,): None,
(1, 3,): None,
(2, 1,): None,
(2, 2,): None,
(2, 3,): None,
(2, 4,): None,
(3, 2,): None,
(3, 3,): None
}
def find_neighbours(cell):
"""
Given a cell with coords (x,y) the neighbours are:
(x-1, y-1), ( x , y-1), (x+1, y-1),
(x-1, y ), (x+1, y ),
(x-1, y+1), ( x , y+1), (x+1, y+1),
The center space is (x,y) which is the cell itself and not a neighbour.
"""
neighbours = set()
x, y = cell
for x_comp in (x-1, x, x+1):
for y_comp in (y-1, y, y+1):
neighbours.add((x_comp, y_comp))
neighbours.remove(cell)
return neighbours
def assignment_valid(grid_square, value, state):
"""
Find all neighbouring grids on the board that have values.
Ensure that the value is not within 1 of of the assignment value.
value | neighbours | valid |
------+---------------+-------|
1 | 3, 4, 2 | False | because 2 is next to 1
1 | 3, 6, 8 | True |
"""
# neighbours should be there for one another!
# neighbours are the set of grid squares surrounding the x, y coords given
# that also intersect with the squares in state.keys()
neighbours = set(state.keys()).intersection(find_neighbours(grid_square))
# for any neighbour who is not None
# if the abs(neighbour-value) is > 1 the move is valid
# TIP: use a list comprehension to cycle through all neighbours who are not None
# recording the boolean equivilent of abs(neighbour-value) > 1.
# use the all() function to check all items in the lits are True
is_valid = all(
[
bool(abs(state[neighbour]-value) > 1)
for neighbour in neighbours
if state[neighbour] is not None
]
)
return is_valid
def assign_to_grid(grid_square, value, state):
"""
Assigns value to grid_square within a copy of state.
:param tuple grid_square: An (x, y,) tuple representing a square on the board.
:param int value: The value we want to assign.
:param dict state: The state of the universe.
:return dict: The updated state of the universe.
"""
new_state = deepcopy(state)
if new_state[grid_square] is None:
new_state[grid_square] = value
else:
raise ValueError('{0} contains value {1}'.format(grid_square, value))
return new_state
|
eb9d5ad1a3bb38c87c64f435c2eabd429405ddc3 | niall-oc/things | /codility/odd_occurrences_in_array.py | 2,360 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/
A non-empty array A consisting of N integers is given. The array contains an odd
number of elements, and each element of the array can be paired with another
element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
Write a function:
def solution(A)
that, given an array A consisting of N integers fulfilling the above conditions,
returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the function should return 7, as explained in the example above.
Write an efficient algorithm for the following assumptions:
N is an odd integer within the range [1..1,000,000];
each element of array A is an integer within the range [1..1,000,000,000];
all but one of the values in A occur an even number of times.
# 100% solution https://app.codility.com/demo/results/trainingCB48ED-3XU/
"""
import time
def solution(A):
"""
Bitwise or between 2 numbers where N==N produces a 0.
Therefore even pairing of numbers will produce zero.
The remainder of the bitwise or operation will be equal to the one odd occurance
in the array.
"""
result=0
for item in A:
result ^= item
return result
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(7, ([1,1,2,2,7],)),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!')
|
57994eee0033581a355200e38514b5504652fca3 | niall-oc/things | /codility/max_double_slice_sum.py | 2,808 | 4.03125 | 4 |
# -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_double_slice_sum/
A non-empty array A consisting of N integers is given.
A triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N, is called a double slice.
The sum of double slice (X, Y, Z) is the total of A[X + 1] + A[X + 2] + ...
+ A[Y − 1] + A[Y + 1] + A[Y + 2] + ... + A[Z − 1].
For example, array A such that:
A[0] = 3
A[1] = 2
A[2] = 6
A[3] = -1
A[4] = 4
A[5] = 5
A[6] = -1
A[7] = 2
contains the following example double slices:
double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17,
double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 − 1 = 16,
double slice (3, 4, 5), sum is 0.
The goal is to find the maximal sum of any double slice.
Write a function:
def solution(A)
that, given a non-empty array A consisting of N integers, returns the maximal sum of
any double slice.
For example, given:
A[0] = 3
A[1] = 2
A[2] = 6
A[3] = -1
A[4] = 4
A[5] = 5
A[6] = -1
A[7] = 2
the function should return 17, because no double slice of array A has a sum of greater
than 17.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [3..100,000];
each element of array A is an integer within the range [−10,000..10,000].
# 100% solution https://app.codility.com/demo/results/trainingK57V65-35K/ O(n)
"""
import time
def solution(A):
"""
Use a prefix scan technique.
Walk array A and record all lower slices
Walk array A and record all upper slices.
Finally walk the prefix slice totals and find the max Double slice.
"""
n = len(A)
max_uppers = [0]*n
max_lowers = [0]*n
max_sum = 0
for i in range(n-2, 0, -1):
max_sum = max(0, max_sum+A[i])
max_lowers[i] = max_sum
max_sum = 0
for i in range(1, n-1):
max_sum = max(0, max_sum+A[i])
max_uppers[i] = max_sum
max_sum = 0
for i in range(0, n-2):
max_sum = max(max_sum, max_uppers[i] + max_lowers[i+2])
return max_sum
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(17, ([3, 2, 6, -1, 4, 5, -1, 2],)),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!') |
203ae511e881868303be870501531fb41c688fea | niall-oc/things | /codility/dis_analysis.py | 840 | 4.125 | 4 | def factorial(n):
# recursive
if not n:
return 1
else:
return n * factorial(n-1)
def factorial_for(n):
if not n:
return 1
else:
r = 1
for i in range(1, n+1):
r = i*r
return r
def factorial_while(n):
if not n:
return 1
else:
i = r = 1
while i < n+1:
r = i*r
i += 1
return r
def fibonacci(n):
# recursive
if not n:
return 0
elif n<3:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def fibonacci_itr(n, seq=False):
# iterator
if not n:
r = [0]
elif n<3:
r = [0,1,1] if n == 2 else [0,1]
else:
r = [0,1,1]
for _ in range(3, n+1):
r += [r[-2] + r[-1]]
return r if seq else r[-1]
|
a523273dc9d1ad99757b69d934be11c74f4dd009 | niall-oc/things | /codility/stone_wall.py | 2,995 | 3.828125 | 4 |
# -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/
You are going to build a stone wall. The wall should be straight and N meters
long, and its thickness should be constant; however, it should have different
heights in different places. The height of the wall is specified by an array
H of N positive integers. H[I] is the height of the wall from I to I+1 meters
to the right of its left end. In particular, H[0] is the height of the wall's
left end and H[N−1] is the height of the wall's right end.
The wall should be built of cuboid stone blocks (that is, all sides of such
blocks are rectangular). Your task is to compute the minimum number of blocks
needed to build the wall.
Write a function:
def solution(H)
that, given an array H of N positive integers specifying the height of the wall,
returns the minimum number of blocks needed to build it.
For example, given array H containing N = 9 integers:
H[0] = 8 H[1] = 8 H[2] = 5
H[3] = 7 H[4] = 9 H[5] = 8
H[6] = 7 H[7] = 4 H[8] = 8
the function should return 7. The figure shows one possible arrangement of seven
blocks.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array H is an integer within the range [1..1,000,000,000].
# 100% solution https://app.codility.com/demo/results/trainingQB8TDX-9DP/
"""
import time
def solution(H):
"""
if a block is higher than the last it goes on the stack.
If a block is lower the stack is popped and counted
until the top block on the stack is lower than the current block.
"""
stack = [-1]
block_count = 0
for height in H:
if stack[-1] > height: # Pop blocks and count
while stack[-1] > height:
stack.pop()
block_count += 1
# print(f'blocks: {block_count} - stack: {stack} - height: {height}')
if height > stack[-1]: # after all blocks are popped consider adding this block.
stack.append(height)
# print(f'blocks: {block_count} - stack: {stack} - height: {height}')
return block_count + len(stack) -1
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(7, ([8, 8, 5, 7, 9, 8, 7, 4, 8],)),
(2, ([4, 4, 5, 5, 4, 4],)),
(3, ([1, 2, 3],)),
(1, ([2, 2, 2, 2],)),
(1, ([1],)),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!') |
db239ae5d7cc670f71e8af8d99bc441f4af2503a | niall-oc/things | /puzzles/movies/movies.py | 2,571 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Given the following list in a string seperated by \n characters.
Jaws (1975)
Starwars 1977
2001 A Space Odyssey ( 1968 )
Back to the future 1985.
Raiders of the lost ark 1981 .
jurassic park 1993
The Matrix 1999
A fist full of Dollars
10,000 BC (2008)
1941 (1979)
24 Hour Party People (2002)
300 (2007)
2010
Produce the following output.
2000s : 3
1970s : 3
1980s : 2
1990s : 2
1960s : 1
"""
import re
year_pattern = re.compile("[0-9]{4}") # or [0-9]{4}
def find_year(title):
"""
Returns a 4 digit block nearest the right of the string title.
OR
Returns None.
EG.
Starwars (1977) # year is 1997
2001 A space odyssey 1968 # year is 1968
2010 # NO year
1985. # NO year
75 # NO year
usage:
>>> find_year("starwars (1977)")
1977
:param str title: A string containing a movie title and year of relaease.
:return str: Year of release
"""
# find all patterns that match the year pattern
matches = year_pattern.findall(title)
# if any matches
if matches:
# record for convienence
year = matches[-1]
too_short = len(title) < 8
# If the year is the title then return None
if year == title:
return None
# If we have enough room for 1 block of 4 digits and its at the start
elif too_short and title.startswith(year):
return None
else:
return year
def rank_decades(movies):
"""
Returns a dictionary of decades -> number of movies released.
usage:
>>> rank_decades(['starwars 1977'])
{'1970s': 1}
:param list movies: A collection of title strings
:return dict: decades and number of releases.
"""
results = {}
for movie in movies:
year = find_year(movie)
# If we found a release year then count it
if year:
# A way to map year to decade
decade = "{0}0s".format(year[:3])
else:
decade = "None"
results[decade] = results.setdefault(decade, 0) + 1
return results
if __name__ == "__main__":
f = open('movie_releases.txt')
movie_data = f.read()
all_movies = movie_data.split('\n')
rank = rank_decades(all_movies)
for decade, count in sorted(rank.items(), key=lambda s: s[1], reverse=True):
print "%s : %s" % (decade, count,)
|
e6ea4c49d3012708cededb29a1f79f575561c82f | niall-oc/things | /codility/frog_jmp.py | 2,058 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/
A small frog wants to get to the other side of the road. The frog is currently
located at position X and wants to get to a position greater than or equal to Y.
The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its
target.
Write a function:
def solution(X, Y, D):
that, given three integers X, Y and D, returns the minimal number of jumps from
position X to a position equal to or greater than Y.
For example, given:
X = 10
Y = 85
D = 30
the function should return 3, because the frog will be positioned as follows:
after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Write an efficient algorithm for the following assumptions:
X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
# 100% solution https://app.codility.com/demo/results/trainingWK4W5Q-7EF/
"""
import time
def solution(X, Y, D):
"""
Simply divide the jumps into the distance.
Distance being y-X and ensuring a finaly jump over the line!
"""
distance = (Y-X)
hops = distance // D
if distance%D: # landing even is not over the line!
hops += 1
return hops
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(3, (10, 85, 30,)),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!')
|
c19bf205d5b5c6727b416e0eb658a7e6c6336f74 | niall-oc/things | /codility/frog_river_one.py | 3,224 | 4.09375 | 4 |
# -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/
A small frog wants to get to the other side of a river. The frog is initially
located on one bank of the river (position 0) and wants to get to the opposite
bank (position X+1). Leaves fall from a tree onto the surface of the river.
You are given an array A consisting of N integers representing the falling leaves.
A[K] represents the position where one leaf falls at time K, measured in seconds.
The goal is to find the earliest time when the frog can jump to the other side of
the river. The frog can cross only when leaves appear at every position across
the river from 1 to X (that is, we want to find the earliest moment when all the
positions from 1 to X are covered by leaves). You may assume that the speed of
the current in the river is negligibly small, i.e. the leaves do not change their
positions once they fall in the river.
For example, you are given integer X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
In second 6, a leaf falls into position 5. This is the earliest time when leaves
appear in every position across the river.
Write a function:
def solution(X, A)
that, given a non-empty array A consisting of N integers and integer X, returns
the earliest time when the frog can jump to the other side of the river.
If the frog is never able to jump to the other side of the river, the function
should return −1.
For example, given X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
the function should return 6, as explained above.
Write an efficient algorithm for the following assumptions:
N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].
# 100% solution https://app.codility.com/demo/results/trainingCAGTQH-NBU/
"""
import time
def solution(X, A):
"""
Many implementations are possible.
Knowing there are X positions needing a leaf record the position of each leaf
falls until all positions have a leaf
"""
# use a set to record leaf positions as they fall
leaf_set = set()
for i in range(0, len(A)):
if A[i] > X: # Discard leaves that are falling outside the frogs path.
continue
leaf_set.add(A[i]) # New elements added bring us closer to the solution.
if (len(leaf_set) == X):
return i
return -1
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(6, (5, [1, 3, 1, 4, 2, 3, 5, 4],)),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!') |
74c545021bb4322872287accaf68765b46d44c8f | zsediqyar/CIS61 | /COVID19-weeks/lab_9.py | 1,955 | 3.9375 | 4 | # IMPORTED FUNCTIONS AND CLASSES
# for question two
class Link:
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
# for question three
class Tree:
def __init__(self, entry, child=[]):
for c in child:
assert isinstance(c, Tree)
self.entry = entry
self.child = child
def __repr__(self):
if self.child:
child_str = ', ' + repr(self.child)
else:
child_str = ''
return 'Tree({0}{1})'.format(self.entry, child_str)
def is_leaf(self):
return not self.child
# QUESTION ONE
def scale(s, k):
yield from map(lambda x: x * k, s)
s = scale([1, 5, 2], 5)
type(s)
print(list(s))
# QUESTION TWO
def link_to_list(link):
lst = []
while link != Link.empty:
lst.append(link.first)
link = link.rest
return lst
def link_to_list(link):
if link == Link.empty:
return []
else:
return [link.first] + link_to_list(link.rest)
# link = Link(1, Link(2, Link(3, Link(4))))
# print(link_to_list(link))
# print(link_to_list(Link.empty))
# QUESTION THREE
def cumulative_sum(t):
if t.is_leaf():
pass
else:
for child in t.child:
cumulative_sum(child)
t.entry += sum([child.entry])
# t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])
# print(t)
# cumulative_sum(t)
# print(t)
# QUESTION FOUR
def is_bst(t):
if t.is_leaf():
return True
if len(t.child) == 1:
return True
elif t.entry < t.child[0].entry and t.entry > t.child[1].entry:
return False
for c in t.child:
return is_bst(c)
# t1 = Tree(6, [Tree(2, [Tree(1), Tree(4)]), Tree(7, [Tree(7), Tree(8)])])
# print(is_bst(t1))
# t2 = Tree(8, [Tree(2, [Tree(9), Tree(1)]), Tree(3, [Tree(6)]), Tree(5)])
# print(is_bst(t2))
|
575320ec01e71aeb6179a71f2fe231e83e1cb3fa | zsediqyar/CIS61 | /week_2/lab_2.py | 1,656 | 4.0625 | 4 | from operator import add, sub
# QUESTION 1
def both_positive(x, y):
return x > 0 and y > 0
print(both_positive(1, 6))
# QUESTION 2
def a_plus_abs_b(a, b):
if b < 0:
f = sub
else:
f = add
return f(a, b)
print(a_plus_abs_b(1, -5))
# QUESTION 3
def two_of_three(a, b, c):
return max(a*a+b*b, a*a+c*c, b*b+c*c)
print(two_of_three(5, 3, 1))
# QUESTION 4
def largest_factor(n):
factor = n - 1
while factor > 0:
if n % factor == 0:
return factor
factor -= 1
print(largest_factor(15))
print(largest_factor(80))
# QUESTION 5
def sum_digits(n):
number = n
result = 0
while number > 0:
remainder = number % 10
result += remainder
number = number // 10
return result
print(sum_digits(123))
# QUESTION 6
def hailstone(n):
drop_point = 1
while n != 1:
print(n)
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
drop_point = drop_point + 1
print(n)
hailstone(10)
# QUESTION 7
def fibonacciN(n):
old_val = 0
curr_val = 1
if n < 0:
print(f"{n} is an incorrect number")
elif n == 1:
return curr_val
else:
for i in range(1, n):
fib_value = old_val + curr_val
old_val = curr_val
curr_val = fib_value
return curr_val
print(fibonacciN(5))
print(fibonacciN(7))
# QUESTION 8
def is_prime(n):
if n == 1:
return True
num = 2
while num < n:
if n % num == 0:
return False
num += 1
return True
print(is_prime(13))
print(is_prime(15))
|
e95be775f63568c96ab74027cc5128e40a2ecb4a | junaidnz97/Competitive-Programming | /SPOJ/GCD2 - GCD2.py | 237 | 3.703125 | 4 | def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
test=int(input())
for i in range(0,test):
inp=input()
inp=inp.split()
a=int(inp[0])
b=int(inp[1])
c=gcd(a,b)
print(c)
|
7d8dbd2a9a0f07a80037438ff3bfd84d4bac0fb9 | jason870518/JerryHW | /0326/sources/calculator.py | 217 | 3.890625 | 4 | def calculator(x ,y , operator):
if(operator=='+'):
return (x + y)
if(operator=='-'):
return (x - y)
if(operator=='*'):
return (x * y)
if(operator=='/'):
return (x / y)
|
c956a8bade22ace7bbd5dbdcb1d99ceeb81df9c2 | turab45/Travel-Python-to-Ml-Bootcamp | /Day 1/prime-in-range.py | 332 | 3.71875 | 4 |
# Author: Muhammad Turab
factor = 0
for i in range(0, 100):
if (i == 1):
continue
factor = 1
for j in range(2, i // 2 + 1):
if (i % j == 0):
factor = 0
break
# factor = 1 means i is prime
# and factor = 0 means i is not prime
if (factor == 1):
print(i, end=" ")
|
782ec079574fb356dc83ca93db09cd62cd33356c | turab45/Travel-Python-to-Ml-Bootcamp | /Day 2/Q1.py | 293 | 3.953125 | 4 |
# Author : Muhammad Turab
def add_into_list(number, list):
list_len = len(list)
for i in range(list_len):
list[i] = list[i] + number
return list
list1 = [1, 2, 3, 12, 19, 2]
print("Before adding 3: ", list1)
list1 = add_into_list(3, list1)
print("After adding 3: ", list1)
|
e7cc7acf58fb03f5052a257eb4211f44f9ebe8e0 | hoangtunglamm/hoangtunglam-session3-c4e13 | /list/testtiep.py | 352 | 3.75 | 4 | menu = ['com ga', "com rang", "banh trang","nem"]
for index, item in enumerate(menu): #emumerate la liet ke
print(index + 1,". ", item,sep="")
a = int(input("vi tri chu muon thay doi: "))
b = input("sua thanh? ")
index = a - 1
menu[index] = b
for index, item in enumerate(menu): #emumerate la liet ke
print(index + 1,". ", item,sep="")
|
5e636ab79bdcbef2f6ffdc5e51868ba3ea9e5286 | hoangtunglamm/hoangtunglam-session3-c4e13 | /homework/shop.py | 836 | 4.03125 | 4 | menu = ['T-Shirt', 'Sweater']
while True:
YourAnswer = input("Welcome to our shop,what do you want (C,R,U,D)? ")
if YourAnswer.upper() == 'C':
MyAdd = input("Enter New Item: ")
menu.append(MyAdd)
print("Our Item",end = ":",sep = "")
print(*menu,sep=",")
elif YourAnswer.upper() == 'R' :
print(*menu,sep=',')
elif YourAnswer.upper() == 'U':
Position = int(input("Your Position: "))
Position -= 1
myUpdate = input("Your update: ")
myList[Position] = myUpdate
print(*menu,sep=',')
elif YourAnswer.upper() == 'D':
Del_Position = int(input("Position you wanna del: "))
Del_Position -= 1
menu.pop(Del_Position)
print(*menu,sep = ',')
else:
print("index out of range or wrong words")
break
|
6d9f114137d797356159757b9fbe33d3205f9860 | ababaug/AUGUSTINE-ABAH-CIPHER | /cipher.py | 1,705 | 3.765625 | 4 | import unicodedata
# coding: utf-8
def cipher(lineNumber):
alpha_dict = {}
with open("files/input.txt", "r") as instr:
line = instr.readlines()[lineNumber]
r_line = line.rstrip() # removes space beneath
instr_list = r_line.split(":")
count = int(instr_list[0])
enc_dec = int(instr_list[1])
lang = int(instr_list[2])
text = instr_list[3]
with open("files/languages.txt", 'r') as language:
lang_line = language.readlines()[lang]
r_lang_line = lang_line.rstrip() # removes space beneath
alphabets = r_lang_line[r_lang_line.find("[") + 1 : r_lang_line.find("]")].split()
for alpha in alphabets:
_alpha = {alpha : alphabets[(alphabets.index(alpha) + count) % 26]}
alpha_dict.update(_alpha)
if(enc_dec == 0 ): #encrypt
encrypt(alpha_dict, text)
elif(enc_dec == 1): #decrypt
decrypt(alpha_dict, text)
else:
return "Invalid choice of encryption or decryption"
def encrypt(alpha_dict, text):
cypherText = ""
for letter in text:
if letter == " ":
cypherText += " "
else:
cypherText += "%s" %alpha_dict.get(letter)
print("Screen Output -> "+ cypherText)
def decrypt(alpha_dict, text):
decyphered = ""
key_list = list(alpha_dict.keys())
value_list = list(alpha_dict.values())
for letter in text:
if letter == " ":
decyphered += " "
else:
decyphered += key_list[value_list.index(letter)]
print("Screen Output -> "+ decyphered) |
a1aeb5483a52e6fd8d49394a428ab11fea0cf483 | LiZimo/gensearch_wknockoff | /gen_search2/gen_search.py | 10,648 | 3.65625 | 4 | #!/usr/bin/env python
'''
Search for patterns using the learn/predict functions provided by scikit-learn library.
There are 3 files involved in every run:
1) A csv input file, which has samples as rows, and variables as columns.
2) A csv labels files, has the same samples as in the input file and,
the class (0/1) as a row.
3) Params file, which determines the run parameters.
'''
from __future__ import division
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
import argparse
import ConfigParser
import sys
import csv
import pandas as pd
from pandas import DataFrame, Series
import numpy as np
import itertools as it
import math
## from matplotlib import pyplot as plt
import sklearn
from sklearn import cross_validation, metrics
import classifier
import knockoff
import operator
import pickle
#Read in feature and label files
def read_csv(csv_file):
data = pd.read_csv(csv_file, sep=',', header=0, index_col=0)
print("Read file : %s" % csv_file)
return data
#Read in parameter file
def read_params(params_file):
cfg = ConfigParser.ConfigParser()
cfg.read(params_file)
try:
n = cfg.getint("params", "n")
nsteps = cfg.getint("params", "nsteps")
k = cfg.getint("params", "k")
method = cfg.getint("params", "method")
if method < 1 or method > 2:
print("ERROR : Method must be between 1 and 2\n\tmethod 1: test and train on same data\n\tmethod 2: k-fold cross validation")
sys.exit(1)
print("Read parameters : n = %d, nsteps = %d, k = %d, method = %d" % (n, nsteps, k, method))
except:
print("ERROR : Could not read parameter file")
sys.exit(1)
return n, nsteps, k, method
#Check that classes on features and labels match
def check_consistency(inputs, labels):
if (inputs.index.all() == labels.index.all()):
print("Consistency check : Indices match")
else:
print("ERROR : Indices do not match")
sys.exit(1)
#calculate measures from k-fold cross validation
def kfold(X, y, clf, k):
nclasses = len(np.unique(y))
acc = 0
kf = cross_validation.KFold(len(y), n_folds=k, indices=True, shuffle=True, random_state=np.random.randint(100))
while (any([len(np.unique(y[test]))<nclasses or len(np.unique(y[train]))<nclasses for test, train in kf])):
kf = cross_validation.KFold(len(y), n_folds=k, indices=True, shuffle=True, random_state=np.random.randint(100))
for train, test in kf:
y_pred = clf.fit(X[train], y[train]).predict(X[test])
acc += metrics.accuracy_score(y[test], y_pred)
return acc/k
#Run k-fold cross validation multiple times, return mean accuracy
def kfold_multi_run(X, y, clf, k, nsteps):
acc = 0
for i in range(nsteps):
acc += kfold(X, y, clf, k)
return acc/nsteps
#Test and train on the same data
def run(X, y, clf):
y_pred = clf.fit(X, y).predict(X)
acc = metrics.accuracy_score(y, y_pred)
return acc
# get the coefficient matrix back from the classifier
def return_coeff(X, y,clf):
coefficients = clf.fit(X, y).coef_
##print coefficients
##raw_input()
return coefficients
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', required=True,
help='Filename of samples file in csv. This argument is required')
parser.add_argument('-l', '--labels', required=True,
help='Filename of the labels file in csv. This argument is required')
parser.add_argument('-p', '--params', required=False,
help='Filename of the sets of combinations')
parser.add_argument('-o', '--output', required=True,
help='Filename of output file to generate. Required')
parser.add_argument('-v', '--verbose', action="store_true", help='Turn on verbose output')
parser.add_argument('-n', '--n', required=False,
help='The index number of slice ?')
parser.add_argument('-s', '--nsteps', required=False,
help='The number of steps ?')
parser.add_argument('-k', '--kval', required=False,
help='The number of steps ?')
parser.add_argument('-m', '--method', required=False,
help='Choose method 1/2 ?')
print '\n{s:{c}^{n}}\n'.format(s='Sanity Checks',n=106,c='-')
args = parser.parse_args()
inputs = read_csv (args.input)
labels = read_csv (args.labels)
param = args.params
n = int(args.n)
nsteps = int(args.nsteps)
k = int(args.kval)
method = int(args.method)
outfile= args.output
print("Arg parameters : n = %d, nsteps = %d, k = %d, method = %d" % (n, nsteps, k, method))
#Exit immediately if consistency checks do not pass
check_consistency (inputs, labels)
#List of possible k-combinations
#sets = list(it.combinations(range(inputs.shape[1]), int(n)))
sets = pickle.load(open(param,"rb"))
numSets = len(sets)
print '\n{s:{c}^{n}}\n'.format(s='Running for %d Feature Combinations' % numSets,n=106,c='-')
#Run for all possible n-combinations of feature sets
y = np.array(labels[labels.columns[0]])
sys.stdout.write('0%')
sys.stdout.flush()
percentDone = 0
results = []
mydict = {}
for i in range(numSets):
X = inputs[list(sets[i])].values
if method == 1:
acc = run(X, y, classifier.clf)
coeffs = return_coeff(X,y,classifier.clf)
elif method == 2:
acc = kfold_multi_run(X, y, classifier.clf, k, nsteps)
coeffs = return_coeff(X,y,classifier.clf).tolist()
if method == 3:
X_reg = inputs[list(sets[i])].values
got_knockoff = False
s = 1
while got_knockoff == False:
try:
X_tilde = knockoff.perform_knockoff(list(X_reg),s)
got_knockoff = True
break
except:
s = s*(0.75)
continue
X = np.concatenate(((knockoff.normalize_columns(X_reg)),knockoff.normalize_columns(X_tilde)), axis = 1)
our_clf = classifier.clf
feat1_done = False
feat2_done = False
regul = 11.0
step = 2.0
last_change = 0
while feat1_done == False:
coeffs = our_clf.fit(X,y).coef_.tolist()[0]
# coeffs_round = list(round(x, ) for x in coeffs)
# coeffs = coeffs_round
if coeffs[0]==0.0 and coeffs[2]==0.00:
if last_change == -1:
step = step/2
regul = regul + step
last_change = 1
print "increased regularization 0"
# raw_input()
elif coeffs[0]!=0.0 and coeffs[2]==0.00:
try: mydict[inputs[list(sets[i])].columns[0]] += 1
except: mydict[inputs[list(sets[i])].columns[0]] = 1
feat1_done = True
print "done 0"
# print "feat1 came before knockoff"
# raw_input()
elif coeffs[0]==0.0 and coeffs[2]!=0.00:
feat1_done = True
print "done 0"
# print "feat 1 came after knockoff"
# raw_input()
elif coeffs[0]!=0.0 and coeffs[2]!=0.00:
if last_change == 1:
step = step/2
regul = regul - step
last_change = -1
print "decreased regularization 0"
# raw_input()
our_clf.set_params(C = regul)
regul = 11.0
step = 2.0
last_change = 0
while feat2_done == False:
coeffs = our_clf.fit(X,y).coef_.tolist()[0]
# print "got new coeffs"
# print coeffs
# raw_input()
if coeffs[1]==0.0 and coeffs[3]==0.00:
if last_change == -1:
step = step/2
regul = regul + step
last_change = 1
print "increased regularization 1"
# raw_input()
elif coeffs[1]!=0.0 and coeffs[3]==0.00:
try: mydict[inputs[list(sets[i])].columns[1]] = mydict[inputs[list(sets[i])].columns[1]] + 1
except: mydict[inputs[list(sets[i])].columns[1]] = 1
feat2_done = True
print "done 1"
# print "feat2 came before knockoff"
# raw_input()
elif coeffs[1]==0.0 and coeffs[3]!=0.00:
feat2_done = True
print "done 1"
# print "feat 2 came after knockoff"
# raw_input()
elif coeffs[1]!=0.0 and coeffs[3]!=0.00:
if last_change == 1:
step = step/2
regul = regul - step
last_change = -1
print "decreased regularization 1"
# raw_input()
our_clf.set_params(C = regul)
if method!=3:
results.append([round(acc,2)] + [x for x in inputs[list(sets[i])].columns]+ coeffs)
if i/numSets >= percentDone:
sys.stdout.write('...'+ str(percentDone*100))
sys.stdout.flush()
percentDone += 0.01
sys.stdout.write('100%\n')
sys.stdout.flush()
#Rank results by highest accuracy:
if method!=3:
results.sort(key=lambda x: x[0], reverse=True)
if method == 3:
results = sorted(mydict.items(), key=operator.itemgetter(1), reverse=True)
# percentages = []
# for entry in results:
# new_entry = list(entry)
# new_entry[1]=float(new_entry[1]/((inputs.shape[1])-1))
# percentages.append(new_entry)
# results = percentages
fp = open(outfile, 'wb')
w = csv.writer(fp)
print '\n{s:{c}^{n}}\n'.format(s='Writing Results',n=106,c='-')
# No need for fancy notices
#w.writerow(["accuracy"] + ["feature_"+str(i) for i in range(n)] + ["feature_"+str(i)+"_index" for i in range(n)])
for x in results[:1000]:
w.writerow(x)
fp.close()
print("Done!")
|
daa741e39e9e1b51c0c08a4cb97ad51e97b29aab | SarthakGirotra/Chess_python | /chess/game.py | 2,087 | 3.59375 | 4 | import pygame
from .board import Board
from .constants import WHITE, BLACK, BLUE, SQUARE_SIZE
class Game:
def __init__(self, win):
self.win = win
self._init()
def _init(self):
self.board = Board(self.win)
self.turn = WHITE
self.valid_moves = []
self.selected = None
def update(self):
self.board.draw_board()
self.draw_valid_moves(self.valid_moves)
pygame.display.update()
def select(self, row, col):
if self.selected:
result = self._move(row, col)
if not result:
self.selected = None
piece = self.board.get_piece(row, col)
if piece != 0 and piece.color == self.turn:
self.selected = piece
king, P = self.board.check_Check()
if king:
if(self.board.checkmate(king, P)):
print('check')
else:
self.reset()
self.valid_moves = self.board.valid_moves_check(P, king, piece)
else:
self.valid_moves = self.board.check_protection(piece)
return True
return False
def _move(self, row, col):
piece = self.board.get_piece(row, col)
if self.selected and (row, col) in self.valid_moves:
if piece != 0:
self.board.remove(row, col)
self.board.move(self.selected, row, col)
self.change_turn()
else:
return False
return True
def change_turn(self):
self.valid_moves = []
if self.turn == WHITE:
self.turn = BLACK
else:
self.turn = WHITE
def draw_valid_moves(self, moves):
for move in moves:
row, col = move
pygame.draw.circle(self.win, BLUE, (col * SQUARE_SIZE +
SQUARE_SIZE//2, row * SQUARE_SIZE + SQUARE_SIZE//2), 12)
def undo(self):
print('undo')
def reset(self):
self._init()
print('Game Reset')
|
fdec6fee3a57a11783c40eafcb9125b11e174f51 | Anshu-Singh1998/python-tutorial | /fourty.py | 289 | 4.28125 | 4 | # let us c
# Write a function to calculate the factorial value of any integer enyered
# through the keyboard.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
n = int(input("Input a number to compute the factorial : "))
print(factorial(n))
|
85e5854450a443a1ee79a1364a98a27c24516681 | Anshu-Singh1998/python-tutorial | /seven.py | 488 | 3.8125 | 4 | # let us c
# Input cost price and sales price of an item through keyboard.
# wap to determine whether the seller made profit or loss
# and also determine profit or loss he made.
cp = int(input("Enter cost price:"))
sp = int(input("Enter selling price:"))
loss = 0
profit = 0
if cp > sp:
loss = cp - sp
print("business ran in loss", loss)
elif cp < sp:
profit = sp - cp
print("congratulations you are in profit", profit)
else:
print("continue with what you are doing")
|
5ca65e5362eca7bf9cfeda1021564e6c20ccb4a5 | Anshu-Singh1998/python-tutorial | /eight.py | 228 | 4.25 | 4 | # let us c
# input a integer through keyboard and find out whether it is even or odd.
a = int(input("Enter a number to find out even or odd:"))
if a % 2 == 0:
print("the number is even")
else:
print("the number is odd")
|
4516d98fd3db1d9c9049bb6cb3d1fe18e9e7914b | Anshu-Singh1998/python-tutorial | /nineteen.py | 268 | 4.15625 | 4 | # From internet
# Write a program to remove an element from an existing array.
from array import *
num = list("i", [4, 7, 2, 0, 8, 6])
print("This is the list before it was removed:"+str(num))
print("Lets remove it")
num.remove(2)
print("Removing performed:"+str(num)) |
edf8f4a595688a90b7b816a09cfaf75a73cb621e | Anshu-Singh1998/python-tutorial | /second.py | 388 | 3.9375 | 4 | # let us c
# Input a distance through keyboard where distance between two cities are (in km) .
# convert and print this distance
# in meters , feet, inches and centimeters.
kilometers = int(input("Enter a distance:"))
meter = kilometers*1000
feet = kilometers*3280.84
centimeter = kilometers*100000
inch = kilometers*39370.1
print(kilometers)
print(feet)
print(centimeter)
print(inch)
|
72dcbbca43b43701f50195a9767c6de6a20bda8b | wcphkust/sling | /python/avl_insert.py | 3,025 | 3.515625 | 4 | import random
import pprint
class node:
def __init__(self, key = 0, height = 0, left = None, right = None):
self.key = key
self.height = height
self.left = left
self.right = right
##################
# accessory func #
##################
def get_height(x):
if x is None:
return -1
else:
return x.height
def create_avl(size):
root = None
for i in range(0, size-1):
root = insert_node(x, random.randit(0, 20))
return root
def insert_node(x, k):
if x is None:
leaf = node(k, 0, None, None)
return leaf
else:
xl = x.left
xr = x.right
if k < x.key:
new_left = insert(xl, k)
x.left = new_left
res = balance(x)
return res
else:
new_right = insert(xr, k)
x.right = new_right
res = balance(x)
return res
def balance(x):
lht = get_height(x.left)
rht = get_height(x.right)
right = x.right
left = x.left
if rht == lht + 2:
rlht = get_height(right.left)
rrht = get_height(right.right)
right_left = right.left
right_right = right.right
if rlht <= rrht:
inc_rlht = rlht + 1
x.height = inc_rlht
x.right = right_left
inc_inc_rlht = rlht + 2
right.height = inc_inc_rlht
right.left = x
return right
else:
right_left_left = right_left.left
right_left_right = right_left.right
inc_lht = lht + 1
x.height = inc_lht
x.right = right_left_left
inc_rrht = rrht + 1
right.height = inc_rrht
right.left = right_left_right
inc_inc_lht = lht + 2
right_left.height = inc_inc_lht
right_left.left = x
right_left.right = right
return right_left
elif lht == rht + 2:
llht = get_height(left.left)
lrht = get_height(left.right)
left_left = left.left
left_right = left.right
if lrht <= llht:
inc_lrht = lrht + 1
x.height = inc_lrht
x.left = left_right
inc_inc_lrht = lrht + 2
left.height = inc_inc_lrht
left.right = x
return left
else:
left_right_left = left_right.left
left_right_right = left_right.right
inc_rht = rht + 1
x.height = inc_rht
x.left = left_right_right
inc_llht = llht + 1
left.height = inc_llht
left.right = left_right_left
inc_inc_rht = rht + 2
left_right.height = inc_inc_rht
left_right.left = left
left_right.right = x
return left_right
elif rht == lht + 1:
inc_rht = rht + 1
x.height = inc_rht
return x
else:
int inc_lht = lht + 1
x.height = inc_lht
return x
def
##################
# end acc func #
##################
def insert(x, k):
if x is None:
leaf = node(k, 0, None, None)
return leaf
else:
xl = x.left
xr = x.right
if k < x.key:
new_left = insert(xl, k)
x.left = new_left
res = balance(x)
return res
else:
new_right = insert(xr, k)
x.right = new_right
res = balance(x)
return res
def main():
root = create_avl(10)
insert(root, random.randit(0, 20))
insert(root, 100)
insert(root, -100)
insert(None, random.randit(0, 20))
if __name__=="__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.