blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
02234574399517d3716ee9db17225765ae862379 | wmcknig/pynigma | /src/components/Rotor.py | 1,481 | 3.8125 | 4 | class Rotor:
ROTOR_LENGTH = 26
def __init__(self, t, offset = 0):
"""
Requires: a valid sequence of ROTOR_LENGTH, containing
every integer from 0 to ROTOR_LENGTH - 1 inclusive.
Ensures: this is at the given rotor state (0 by default)
"""
self.t = t
self.offset = offset % self.ROTOR_LENGTH
def advance_rotor(self):
"""
Mutates: self.offset
Ensures: self.offset = (self.offset + 1) % ROTOR_LENGTH
"""
self.offset = (self.offset + 1) % self.ROTOR_LENGTH
def signal_in(self, signal):
"""
Requires: an integer from 0 to ROTOR_LENGTH representing the
absolute position of the signal
Ensures: the output position of the signal, in absolute terms
"""
#get relative signal position from input and obtain relative output
output = self.t[(signal + self.offset) % self.ROTOR_LENGTH]
#return absolute output signal position
return (output - self.offset) % self.ROTOR_LENGTH
def signal_out(self, signal):
"""
Requires: an integer from 0 to ROTOR_LENGTH representing the
absolute position of the signal
Ensures: the output position of the signal, in absolute terms
"""
#get output for relative input position, get absolute output
output = self.t.index((signal + self.offset) % self.ROTOR_LENGTH)
return (output - self.offset) % self.ROTOR_LENGTH
|
c4c44139b1ded9455fdf467d9f4ad43091569c27 | nanrak/210CT | /Task3_4.py | 2,853 | 3.96875 | 4 | '''
Task 3 - 4
------------------
Adapt your graph structure from the previous week to support weights for the edges and implement Dijkstra's algorithm.
The output of the program should be the total cost and the actual path found.
'''
import sys
class Node:
def __init__(self, label):
self.label = label
class Edge:
def __init__(self, to_node, weight):
self.to_node = to_node
self.weight = weight
class Graph:
def __init__(self):
self.nodes = set()
self.edges = dict()
def add_node(self, node):
self.nodes.add(node)
def add_edge(self, from_node, to_node, weight):
edge = Edge(to_node, weight)
if from_node.label in self.edges:
from_node_edges = self.edges[from_node.label]
else:
self.edges[from_node.label] = dict()
from_node_edges = self.edges[from_node.label]
from_node_edges[to_node.label] = edge
def min_cost(q, cost):
min_node = None
for node in q:
if min_node == None:
min_node = node
elif cost[node] < cost[min_node]:
min_node = node
return min_node
def dijkstra(graph, start):
q = set()
cost = {}
prev = {}
for v in graph.nodes:
cost[v] = sys.maxint
prev[v] = sys.maxint
q.add(v)
cost[start] = 0
while q:
v = min_cost(q, cost)
q.remove(v)
if v.label in graph.edges:
for _, w in graph.edges[v.label].items():
temp = cost[v] + w.weight
if temp < cost[w.to_node]:
cost[w.to_node] = temp
prev[w.to_node] = v
return cost, prev
def path(prev, from_node):
previous_node = prev[from_node]
route = [str(from_node.label)]
while previous_node != sys.maxint:
route.append(str(previous_node.label))
temp = previous_node
previous_node = prev[temp]
route.reverse()
return route
###################################################################################
graph = Graph()
a = Node(1)
graph.add_node(a)
b = Node(2)
graph.add_node(b)
c = Node(3)
graph.add_node(c)
d = Node(4)
graph.add_node(d)
e = Node(5)
graph.add_node(e)
f = Node(6)
graph.add_node(f)
g = Node(7)
graph.add_node(g)
graph.add_edge(a, b, 4)
graph.add_edge(a, c, 3)
graph.add_edge(a, e, 7)
graph.add_edge(b, c, 6)
graph.add_edge(b, d, 5)
graph.add_edge(c, d, 11)
graph.add_edge(c, e, 8)
graph.add_edge(d, e, 2)
graph.add_edge(d, f, 2)
graph.add_edge(d, g, 10)
graph.add_edge(e, f, 5)
graph.add_edge(f, g, 3)
cost, prev = dijkstra(graph, a)
print 'path : ' + str(path(prev, g))
print 'cost : ' + str(cost[g])
|
3eeb1699971abe0a7994f63a5fe95fe06a713847 | pprobst/ELC117-2018a | /extras/OOP1_python/test_circle.py | 250 | 3.6875 | 4 | from circle import Circle
c1 = Circle()
c2 = Circle()
print("Area C1: {}".format(c1.area()))
print("Area C2: {}".format(c2.area()))
c1.r = 5.0
print(c1.r)
circulos = []
for i in range(10):
circulos.append(Circle())
print(circulos[0].area())
|
fecfa629838dd438eede4ce891d085d53470f61c | AronDJacobsen/Algo_Data_Project | /3_closest.py | 3,271 | 3.8125 | 4 |
import numpy as np
from collections import deque
#we want to create the vertex to hold vales like neighbours, depth etc.
class vertex:
def __init__(self, i, j, char):
self.position = (i, j) #up/down, left/right respectively
self.depth = None # to be updated
self.neighbours = []
self.char = char
class build:
def __init__(self, maze, stop): # indicated it needs maze as input
self.vertices = self.create_graph(maze)
self.find_neighbours(stop) # finding possible neighbours and updating vertices
def create_graph(self, maze):
#we want to create a dict which holds the class of a vertex based on position
vertices = {}
for i in range(N):
for j in range(N):
vertices[ (i,j) ] = vertex(i, j, maze[i][j]) #object created
return vertices
def find_neighbours(self, stop):
for (i, j) in self.vertices.keys():
# i is up/down, j is left/right# to get the x and y
possible_neighbours = [ (self.vertices.get( (i, j-1) ), 'W '),
(self.vertices.get( (i, j+1) ), 'E '),
(self.vertices.get( (i-1, j) ), 'N '),
(self.vertices.get( (i+1, j) ), 'S ')
]
for (neighbour, dir) in possible_neighbours:
if neighbour is not None and neighbour.char != stop:
self.vertices[(i, j)].neighbours.append((neighbour, dir))
# in this class so that we keep the self
def BFS(self, pacman_pos):
# s holds all the values of the vertex
s = self.vertices[ pacman_pos ] # start from top left
s.depth = '' # has to be 1 for codejudge
queue = deque() # just to initialize
# we make opposite of enqueue and dequeue as append and pop left
queue.append(s)
ghost_found = False
while len(queue) > 0:
v = queue.popleft() # think of v as s, just in the loop
#this makes the list updated
for (neighbour, dir) in v.neighbours:
if neighbour.depth == None: # none if not visited
if neighbour.char == 'G': # first/closest ghost found
ghost_found = True
path = v.depth + dir # the optimal path
return path
neighbour.depth = v.depth + dir # this also makes it marked
queue.append(neighbour) # makes us loop thought the front every time
if not ghost_found:
path = str()
return path
if __name__ == "__main__":
#size
N = int(input())
maze = [0]*N # initialize
for i in range(N):
maze[i] = list(input())
# If maze is 1x1
if N == 1:
path = str()
else:
found = False
for i in range(N):
for j in range(N):
if maze[i][j] == 'P':
pacman_pos = (i, j)
found = True
break
stop = '#'
G = build(maze, stop)
if found:
path = G.BFS(pacman_pos)
else:
path = str()
print(path)
|
303ba987eeb196baf6e950ff63372a693bb52e91 | LugBastos/Projetos-Faculdade | /votacaoPremio.py | 2,737 | 3.65625 | 4 | #Entrade de valores
coloborador1 = int(input("Primeiro colaborador, escolha o console de última geração: (1)PLAYSTATION / (2)XBOX / (3)NINTENDO "))
coloborador2 = int(input("Segundo colaborador, escolha o console de última geração: (1)PLAYSTATION / (2)XBOX / (3)NINTENDO "))
coloborador3 = int(input("Terceiro colaborador, escolha o console de última geração: (1)PLAYSTATION / (2)XBOX / (3)NINTENDO "))
coloborador4 = int(input("Quarto colaborador, escolha o console de última geração: (1)PLAYSTATION / (2)XBOX / (3)NINTENDO "))
coloborador5 = int(input("Quinto colaborador, escolha o console de última geração: (1)PLAYSTATION / (2)XBOX / (3)NINTENDO "))
#Contador de votos
voto_playstation = 0
voto_xbox = 0
voto_nintendo = 0
#Analise votos primeiro colaborador
if coloborador1 == 1:
voto_playstation = voto_playstation + 1
elif coloborador1 == 2:
voto_xbox = voto_xbox + 1
elif coloborador1 == 3:
voto_nintendo = voto_nintendo + 1
#Analise votos segundo colaborador
if coloborador2 == 1:
voto_playstation = voto_playstation + 1
elif coloborador2 == 2:
voto_xbox = voto_xbox + 1
elif coloborador2 == 3:
voto_nintendo = voto_nintendo + 1
#Analise votos terceiro colaborador
if coloborador3 == 1:
voto_playstation = voto_playstation + 1
elif coloborador3 == 2:
voto_xbox = voto_xbox + 1
elif coloborador3 == 3:
voto_nintendo = voto_nintendo + 1
#Analise votos quarto colaborador
if coloborador4 == 1:
voto_playstation = voto_playstation + 1
elif coloborador4 == 2:
voto_xbox = voto_xbox + 1
elif coloborador4 == 3:
voto_nintendo = voto_nintendo + 1
#Analise votos quinto colaborador
if coloborador5 == 1:
voto_playstation = voto_playstation + 1
elif coloborador5 == 2:
voto_xbox = voto_xbox + 1
elif coloborador5 == 3:
voto_nintendo = voto_nintendo + 1
#Desvio condicional vitoria
if voto_playstation > voto_xbox and voto_playstation > voto_nintendo:
print("***********************************")
print("PLAYSTATION WIN! Total de votos: {}".format(voto_playstation))
print("***********************************")
elif voto_xbox > voto_playstation and voto_xbox > voto_nintendo:
print("***********************************")
print("XBOX WIN! Total de votos: {}".format(voto_xbox))
print("***********************************")
elif voto_nintendo > voto_playstation and voto_nintendo > voto_xbox:
print("***********************************")
print("NINTENDO WIN! Total de votos: {}".format(voto_nintendo))
print("***********************************")
else:
print("Dois consoles tiveram a mesma quantidade de votos.")
print("Verifique os critérios de desempate.")
|
dc048905570ea63e95032108822934f60bb4c77b | Caizhiwen/Image-based-Reminder | /openCv/hello_world.py | 724 | 3.921875 | 4 | #Load up a color image in grey scale and save it as black&white
import numpy as np
import cv2
# cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
# cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
# cv2.IMREAD_UNCHANGED : Loads image as such including alpha channel
# Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.
img = cv2.imread('images/HelloWorld.png',0)
cv2.imshow('image',img)
k = cv2.waitKey(0) & 0xFF
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('images/HelloWorld.jpg',img)
cv2.destroyAllWindows()
|
09188ac7a45e50d7be77836d0ae423b5ad79c64b | abalarajendrakumar/Resumeparser | /db.py | 2,282 | 3.75 | 4 | # -*- coding: utf-8 -*-s
"""
Created on Fri Feb 14 13:05:41 2020
@author: User
#cursor.execute("DROP TABLE Candidate")
#cursor.execute("DROP TABLE Recruiter")
#cursor.execute("DROP TABLE CandidateDetails")
#cursor.execute("DROP TABLE JobPostings")
#conn.execute("CREATE TABLE Candidate (USER_NAME TEXT NOT NULL,EMAIL TEXT NOT NULL PRIMARY KEY,PASSWORD CHAR(20) NOT NULL);")
#c.execute("CREATE TABLE Recruiter (COMPANY_NAME TEXT NOT NULL,EMAIL TEXT NOT NULL PRIMARY KEY, PASSWORD CHAR(20) NOT NULL)")
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 21:11:59 2020
@author: ELCOT
"""
'''
un="dhakshin@gmail.com"
sql_update_query = """DELETE from CandidateDetails where username = ?"""
c.execute(sql_update_query, (un, ))
conn.commit()
un=""
sql_update_query = """DELETE from CandidateDetails where username = ?"""
c.execute(sql_update_query, (un, ))
conn.commit()
#c.execute("CREATE TABLE CandidateDetails (username varchar(30) PRIMARY KEY, data json NOT NULL)")
#c.execute("CREATE TABLE JobPostings (COMPANY TEXT NOT NULL,LOCATION TEXT NOT NULL,SKILL json NOT NULL,DESIGNATION TEXT NOT NULL,EXPERIENCE TEXT NOT NULL,EDUCATION TEXT NOT NULL)")
'''
import sqlite3;
conn = sqlite3.connect('project.db')
cursor = conn.cursor()
print("\n\nCandidate db content")
conn.commit()
for row in conn.execute('select * from candidate'):
print(row)
print()
conn.close()
print("---------------------------------------------------------------------------")
import sqlite3
conn = sqlite3.connect('project.db')
c=conn.cursor()
print("\n\n\nRecruiter db content")
for row in conn.execute('select * from Recruiter'):
print(row)
print()
conn.close()
print("---------------------------------------------------------------------------")
import sqlite3
conn = sqlite3.connect('project.db')
c=conn.cursor()
conn.commit()
print("\n\n\nCandidate Details db content")
for row in conn.execute('select * from CandidateDetails'):
print(row)
print()
conn.close()
print("---------------------------------------------------------------------------")
import sqlite3
conn = sqlite3.connect('project.db')
c=conn.cursor()
conn.commit()
print("\n\n\nJob posting db content")
for row in conn.execute('select * from JobPostings'):
print(row)
print()
conn.close()
|
932755c39862cf98d39a5edaf5f2dc03dcf758b2 | howard199113/Python-Assignments | /Making Dctionaries.py | 157 | 3.59375 | 4 | howard = {"name":"Howard","Age":"26","country of birth":"Taiwan","favoirte language":"Python"}
for obj in howard:
print "My "+ obj + " is " + howard[obj] |
074e4dcc4968b670b3c161d2ccca0b3239179f9a | moniqueds/FundamentosPython-Mundo1-Guanabara | /ex012.py | 272 | 3.53125 | 4 | preco = float(input('Informe o valor do produto: R$ '))
novo = preco - (preco * 5 / 100)
print('O valor do produto sem desconto era de R$ {:.2f}, mas com desconto de 5% irá custar R$ {}'.format(preco, novo))
#para calcular percentual precisa ser:
# 5/100 = 0.05
|
02cdf23d234d56f3de0f9af1fed602ecaeb3046e | moniqueds/FundamentosPython-Mundo1-Guanabara | /ex033.py | 733 | 4.3125 | 4 | #Faça um programa que leia três números e mostre qual é maior e qual é o menor.
from time import sleep
print('Você irá informar 3 números a seguir...')
sleep(2)
a = int(input('Digite o primeiro número: '))
b = int(input('Digite o segundo número: '))
c = int(input('Digite o terceiro número: '))
print('Analisando o menor...')
sleep(3)
#Verificar quem é o menor número
menor = a
if b<a and b<c:
menor = b
if c<a and c<b:
menor = c
print('o menor valor digitado foi {}.'.format(menor))
print('Analisando o maior...')
sleep(4)
#Verificar quem é o maior número
maior = a
if b>a and b>c:
maior = b
if c>a and c>b:
maior = c
print('O maior valor digitado foi {}.'.format(maior))
|
c3e7f465cceb9c3ca3e692b21539554ba1729747 | Keng-Hwee/flask-restful | /basics/basic_flask_app.py | 2,178 | 3.5 | 4 | from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
stores = [
{
'name': 'My Wonderful Store',
'items': [
{
'name': 'My Item',
'price': 15.99
}
]
}
]
@app.route('/')
def home():
return render_template('index.html')
#######################
# We are a server now #
#######################
# POST - used to receive data
# GET - used to send data back
# Endpoints to set up:
# POST /store data: {name:} ---> (create a new store with a given name)
@app.route('/store', methods=['POST'])
def create_store():
# Note that the request will contain the name of the store
request_data = request.get_json()
new_store = {
'name': request_data['name'],
'items': []
}
stores.append(new_store)
return jsonify(new_store)
# GET /store/<string:name> ---> (get a store for a given name, and return some data about it)
@app.route('/store/<string:name>')
def get_store(name):
for store in stores:
if store['name'] == name:
return jsonify(store)
return jsonify({'message': 'store not found'})
# GET /store ---> (to return a list of stores)
@app.route('/store')
def get_stores():
return jsonify({'stores': stores})
# POST /store/<string:name>/item {name: , price:} ---> (create an item inside a specific store)
@app.route('/store/<string:name>/item', methods=['POST'])
def create_item_in_store(name):
request_data = request.get_json()
for store in stores:
if store['name'] == name:
new_item = {
'name': request_data['name'],
'price': request_data['price']
}
store['items'].append(new_item)
return jsonify(new_item)
return jsonify({'message': 'store not found'})
# GET /store/<string:name>/item ---> (Get all the item in a specific store)
@app.route('/store/<string:name>/item')
def get_items_in_store(name):
for store in stores:
if store['name'] == name:
return jsonify({'items': store['items']})
return jsonify({'message': 'store not found'})
app.run(port=5000)
|
22602a8aef57ff7508cb189a6516a2fe05e5910c | srikoder/CryptoStuff | /CryptoPals/2018csb1098_15.py | 456 | 3.6875 | 4 | def pad(m, blength):
numPad = (blength - len(m))
paded = (chr(numPad)*numPad).encode()
ans = m.encode()+paded
return ans
def main():
c = input()
count = 0
for ch in c:
if ch=='\\':
break
else:
count = count+1
unpad = c[1:count]
print(len(c))
if pad(unpad, len(c)-12) == "b'" + c + "'":
print("Yes")
else:
print("No")
if __name__ == '__main__':
main() |
671b743b1a208bb2f23e00ca96acad7710bd932f | slutske22/Practice_files | /python_quickstart_lynda/conditionals.py | 1,192 | 4.21875 | 4 | # %%
raining = input("Is it raining outside? (yes/no)")
if raining == 'yes':
print("You need an umbrella")
# %%
userInput = input("Choose and integer between -10 and 10")
n = int(userInput)
if n >= -10 & n <= 10:
print("Good Job")
# %%
def minimum(x, y):
if x < y:
return x
else:
return y
# %%
minimum(2, 5)
# %%
minimum(4, 2)
# %%
minimum(4, 4)
# %%
minimum(3, 3.1)
# %%
# if-elif statements
raining = input("Is it raining? (yes/no)")
umbrella = input("Do you have an umbrella? (yes/no)")
if raining == 'yes' and umbrella == 'yes':
print("Don't forget your umbrella")
elif raining == 'yes' and umbrella == 'no':
print("Wear a waterproof jacket with a hood")
else:
print("Netflix and chill")
# %%
x = input("Enter a number here: ")
x = float(x)
if x < 2:
print("The number is less than 2")
elif x > 100:
print("The number is greater than 100")
elif x > 6:
print("The number is greater than 6")
else:
print("The number is between 2 and 6 inclusive")
# %%
def abs_val(num):
if num < 0:
return -num
elif num == 0:
return 0
else:
return num
# %%
result = abs_val(-4)
print(result)
# %%
|
c8d2b0438078200fdede0fac7ad74dac1394ca42 | slutske22/Practice_files | /python_misc/cells.understanding.py | 415 | 3.609375 | 4 | from heapq import heappop
# %% Understanding zip: create tuples from zipped lists
dxs = [-1, -1, 0, 1, 1, 1, 0, -1]
dys = [ 0, -1, -1, -1, 0, 1, 1, 1]
zipped = zip(dxs, dys)
print(list(zipped))
# %% Typings?
g: int
g = 'j' #like wtf does this mean
# %%
from heapq import heappop
stuff = list(['a', 'b', 'c', 'd'])
print(heappop(stuff), stuff)
print(heappop(stuff), stuff)
print(heappop(stuff), stuff)
# %%
|
337573761ea3f446741271a7a4629229562bcf7f | davidgamero/terminal-gatech-2019 | /line_fuctions.py | 588 | 3.71875 | 4 | def get_line_points(start, end):
line_points = []
# Flip so we always go the right
if start[0] > end[0]:
temp = start
start = end
end = temp
x1 = start[0]
y1 = start[1]
x2 = end[0]
y2 = end[1]
slope = (y2-y1)/(x2-x1)
x = x1
y = y1
print('X = ' + str(x))
while(x <= x2):
new_point = [x, round(y)]
print(new_point)
if new_point not in line_points:
line_points.append(new_point)
x += 1
y += slope
return line_points
print(get_line_points([1, 2], [5, 5]))
|
4a669abe46dc9db2dc55070d6034574901859fa2 | ccamargo8/Mi-primer-repositorio | /Ejemplo matriz.py | 539 | 3.65625 | 4 | import random
estrella="\u2605"
filas=int(input("Ingrese el numero de filas: "))
columnas=int(input("Ingrese el numero de columnas: "))
#Matriz construida por comprensión
cielo=[[" " for i in range(columnas)] for j in range (filas)]
for i in range(filas): #Se recorren filas
for j in range(columnas): #Se recorre la parte interna de cada fila
num=random.randint(0,5)
if num ==2:
cielo[i][j]=estrella
for fil in cielo:
for elementos in fil:
print(elementos, end=" ")
print() |
cbb2f5554253520124a6a7541e9852d00839251a | ccamargo8/Mi-primer-repositorio | /POO.py | 1,216 | 3.5 | 4 | import random as rd
#Clase estrella. Si se crea una clase sin atributos, se usa pass
class estrella():
lugar="Espacio"
#Self quiere decir que el constructor le pertenece a la clase definida
def __init__(self,
color="Blanca",
edad=0,
constelacion="nula"
):
self.color=color ##Se crea un atributo para el objeto
self.edad=edad
self.constelacion=constelacion
def __str__(self):
return f"""Clase Estrella:
Las estrellas que se crean con esta clase, tienen tres atributos:
color={self.color}
edad={self.edad}
Constelacion={self.constelacion}
"""
def edad_aleatoria(self):
self.edad = rd.randint(1,10000)
print(f"edad = {self.edad}")
#Crear objeto de la clase estrella: Instanciar
miestrella=estrella("Azul",10000)
miestrella2=estrella("Verde")
miestrella3=estrella("Amarillo")
miestrella4=estrella("Roja")
miestrella4.lugar="Otra dimension"
miestrella5=estrella()
miestrella6=estrella(color="azul",edad=1000,constelacion="Sagitario")
|
0a218975ac821d79a7df598d3ecec85fcf212d21 | ccamargo8/Mi-primer-repositorio | /Ejemplo matriz 2.py | 1,031 | 4 | 4 | f = int(input("Cuantas empresas? "))
c = int(input("Cuantos empleados por empresa? "))
matriz=[[0]*c for i in range (f)]
print(matriz)
for i in range(f):
suma=0
for j in range(c):
valor = int(input(f"Ingrese el valor para la empresa {i}, empleado{j}: "))
matriz[i][j]=valor
suma=suma+matriz[i][j]
promedio=suma/c
print(f"El promedio de la empresa {i} es {promedio}")
print(matriz)
#%%
def calcularPromedio(empresas):
suma = 0
for i in empresas:
suma=suma+i
return suma/len(empresas)
f = int(input("Cuantas empresas? "))
c = int(input("Cuantos empleados por empresa? "))
matriz=[[0]*c for i in range (f)]
print(matriz)
for i in range(f):
suma=0
for j in range(c):
valor = int(input(f"Ingrese el valor para la empresa {i}, empleado{j}: "))
matriz[i][j]=valor
suma=suma+matriz[i][j]
for i in range(f):
print("Empresa",i)
x = calcularPromedio(matriz[i])
print("Edad promedio",x)
print(matriz) |
529a258ef79a5194d1f3a49c570076464334b744 | ccamargo8/Mi-primer-repositorio | /funOpVectores.py | 714 | 3.84375 | 4 | def buscarDato(V,d):
"""Programa para buscar un dato en un vector"""
i=1
while i<=V[0] and V[i]!=d:
i=i+1
if i <= V[0]:
return i
return -1
def borrar(V,i):
"""Programa para borrar un dato de un vector"""
for j in range(i,V[0]):
V[j]=V[j+1]
V[0]=V[0]-1
def ordenaAscen(V):
for i in range(1, V[0]):
k = i
for j in range(i+1, V[0] + 1):
if V[j] < V[k]:
k = j
intercambiar(V, i, k)
def ordenaAscen(V):
for i in range(1, V[0]):
for j in range(1, V[0] – I + 1):
if V[j] > V[j + 1]:
intercambiar(V, j, j + 1) |
f4a153a819c9bd6aeeed4347cc6ff2cef4be6db2 | chen-alain/Algorithm-Fight-Club | /Round-5/LUKE GUERDAN quicksort.py | 1,446 | 4.0625 | 4 | def quicksortRecur(array, low, high):
print "Entering quicksort: " + str(array) + " low: %d - high: %d" % (low, high)
if (low > high):
return
pivot = array[(low + high) / 2]
print "pivot: %d\n" % pivot
i = low
j = high
while(i <= j):
while(array[i] < pivot):
i += 1
while(array[j] > pivot):
j = j - 1
if(i <= j):
temp = array[i]
array[i] = array[j]
array[j] = temp
i += 1
j = j - 1
if (low < j):
quicksortRecur(array, 0, pivot - 1)
if (high > i):
quicksortRecur(array, pivot, high)
def quicksortIter1(array, low, high):
print "Entering quicksort: " + str(array) + " low: %d - high: %d" % (low, high)
if (low > high):
return
pivot = array[(low + high) / 2]
print "pivot: %d\n" % pivot
i = low
j = high
while(i <= j):
while(array[i] < pivot):
i += 1
while(array[j] > pivot):
j = j - 1
print "about to comare: array[i] = %d array[j] = %d" % (array[i], array[j])
if(i <= j):
temp = array[i]
array[i] = array[j]
array[j] = temp
i += 1
j = j - 1
return
if (low < j):
quicksortIter1(array, 0, pivot - 1)
if (high > i):
quicksortIter1(array, pivot, high)
array = [8, 5, 9, 3,2,1, 1, 7]
quicksortRecur(array, 0, len(array) - 1)
quicksortIter1(array, 0, len(array) - 1)
print array
|
9b2defe6842ac55e6b0c1157f04da230f3d33bb4 | LuisDiego10/Circuit-Designer | /src/graph/__init__.py | 7,766 | 3.5625 | 4 | import json
from typing import List, Any
from graph.Node import Node
class Graph:
paths: List[List[int]]
nodes: List[Node]
def __init__(self):
"""
create a empty graph class
"""
self.nodes = []
self.paths = []
self.sorted_up = []
self.sorted_down = []
pass
def insert_node(self, node: Node):
"""
Insert a node and its arcs in the graph
:type node: Node
"""
self.nodes.append(node)
path = []
for i in self.nodes:
if i in node.arcs:
path.append(1)
else:
path.append(0)
for i in self.paths:
i.append(0)
self.paths.append(path)
def del_node(self, node):
"""
delete a Node and it arcs from the graph
:param node: Node or Node name
"""
node = self.find_node(node)
index = self.nodes.index(node)
self.paths.pop(index)
for i in self.paths:
i.pop(index)
self.nodes.remove(node)
def find_node(self, name):
"""
Search in graph nodes the node by their name
:param name: Node or Node name
:return: Node
"""
if name.__class__ != str:
return name
for i in self.nodes:
if i.name == name:
return i
else:
return -1
def new_arc(self, start_node, end_node):
"""
Create a new arc
:param start_node: start Node or it name
:param end_node: end Node or it name
"""
start_node = self.find_node(start_node)
end_node = self.find_node(end_node)
if -1 == start_node or -1 == end_node:
return
start_node.new_arc(end_node)
self.paths[self.nodes.index(start_node)][self.nodes.index(end_node)] = 1
def del_arc(self, start_node, end_node):
"""
Delete a arc
:param start_node:
:param end_node:
"""
start_node = self.find_node(start_node)
end_node = self.find_node(end_node)
if -1 == start_node or -1 == end_node:
return
start_node.arcs.remove(end_node)
self.paths[self.nodes.index(start_node)][self.nodes.index(end_node)] = 0
def update_graph_arcs(self):
"""
Update the adjacency matrix with Nodes arc list
"""
paths = []
for i in self.nodes:
path = []
for a in self.nodes:
if a in i.arcs:
path.append(1)
else:
path.append(0)
paths.append(path)
self.paths = paths
def update_node_arcs(self):
"""
Update the Nodes arcs with the adjacency matrix
"""
for i in self.nodes:
i.arcs = []
a = 0
while a < len(self.paths):
b = 0
while b < len(self.paths):
if self.paths[a][b] == 1:
self.nodes[a].new_arc(self.nodes[b])
b += 1
a += 1
def graph_dump(self, save: str):
"""
Generate a .graph file where the graph is saved
:param save: name for the save file
:return: the save file text
"""
self.update_graph_arcs()
text = "\n"
for i in self.nodes:
node = Node()
node.name = i.name
node.value = i.value
node.position = i.position
node.rotation = i.rotation
node.type = i.type
for a in i.arcs:
node.arcs.append(a.name)
text = text + "\n" + "@" + json.dumps(node.__dict__)
text = text + "\n"
for i in self.paths:
text = text + "\n" + json.dumps(i)
file = open(("saves/" + save + ".graph"), "w") # Creation of personal file for graph
file.write(text)
file.close()
return text
def graph_load(self, save: str):
"""
Load a .graph file in this object ¡Do not create a new one by itself!
:param save: the addrres or text of the save file
:return:
"""
if save[-7:-1] != ".graph":
save = open(save).read().splitlines()
elif save.find("@{"):
save = save.splitlines()
else:
return
self.nodes = []
self.paths = []
for line in save:
if len(line) == 0:
continue
if line[0] == "@":
json_node = line[1:]
json_node = json.loads(json_node)
node = Node()
node.build(json_node)
self.nodes.append(node)
elif line[0] == "[":
self.paths.append(json.loads(line))
else:
pass
self.update_node_arcs()
self.update_graph_arcs()
def sort(self):
"""
place holder for sort algorithms
"""
list_A = self.nodes.copy()
list_B = self.nodes.copy()
self.sorted_up = self.quicksort(list_A)
self.sorted_down = self.mergesort(list_B)
self.sorted_down
for a in self.sorted_up:
print(a.name)
print("\n")
for a in self.sorted_down:
print(a.name)
pass
def quicksort(self, list):
print("Lista: ", list)
if len(list) == 1 or len(list) == 0:
return list
else:
pivot = list[0].name
i = 0 # El i es utilizado como contador para cuando aparezca un elemento menor al pivot
# Recorre la lista
for j in range(len(list) - 1):
if list[j + 1].name < pivot:
list[j + 1], list[i + 1] = list[i + 1], list[j + 1]
i += 1
list[0], list[i] = list[i], list[0] # Intercambiar el pivot por el último elemento menor encontrado
# Dividir la lista
firts = self.quicksort(list[:i])
print("Firts", firts)
second = self.quicksort(list[i + 1:])
print("Second", second)
firts.append(list[i])
return firts + second
# Function performs the comparisons and joins the elements to show the result
def merge(self, left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i].name > right[j].name:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
# Function that divides the list and points to the middle
def mergesort(self, list):
if len(list) <= 1:
return list
mid = int(len(list) / 2)
left = self.mergesort(list[:mid])
right = self.mergesort(list[mid:])
return self.merge(left, right)
def dijkstra(self, group: [], matrix=None):
if matrix is None:
matrix = self.paths
start = group[0]
end = group[1]
# the position of the end and the start has importance because it is a Directed Graph:
start_index = self.nodes.index(start)
end_index = self.nodes.index(end)
length = len(self.nodes)
dist = [10000] * length
paths_min = [[]] * length
dist[start_index] = 0
queue = []
# get a id for all the nodes with their position in list
for i in range(length):
queue.append(i)
while queue:
# select the minimum weight and add path
min = self.dijkstra_min(dist, queue)
queue.remove(min)
for i in range(length):
if matrix[min][i] > 0 and i in queue:
if dist[min] + matrix[min][i] < dist[i]:
dist[i] = dist[min] + matrix[min][i]
paths_min[i] = paths_min[min] + [self.nodes[min]]
print(paths_min)
return paths_min[end_index]
def dijkstra_min(self, dist, queue):
minimum = 100000
min_index = -1
# chose the minimum element
for i in range(len(dist)):
if (dist[i] < minimum) and (i in queue):
minimum = dist[i]
min_index = i
return min_index
pass
#
# """TEST GRAPH"""
#
# graph = Graph()
#
# node1 = Node()
# node1.set_name("one")
# graph.insert_node(node1)
#
# node2 = Node()
# node2.set_name("two")
# graph.insert_node(node2)
#
# node3 = Node()
# node3.set_name("Three")
# graph.insert_node(node3)
#
# node4 = Node()
# node4.set_name("fourth")
# graph.insert_node(node4)
#
# node5 = Node()
# node5.set_name("five")
# graph.insert_node(node5)
#
# graph.new_arc(node1, "two")
# graph.new_arc("two", "one")
# graph.del_arc("two", "one")
# # graph.new_arc("two", "one")
# # graph.new_arc(node3, "one")
# graph.new_arc(node3, node2)
# graph.new_arc(node2, node4)
# graph.new_arc(node4, node1)
# graph.new_arc(node5, "one")
# graph.new_arc(node5, "five")
#
# # print(graph.__dict__)
# # print(graph.graph_dump("graph one"))
# # graph.graph_load("saves/graph one.graph")
# # print(graph.graph_dump("graph one"))
# a = graph.dijkstra([node3, node1])
# print("a")
# print(a)
# for i in a:
# print(i.name)
# print("A D")
#
# ##
# # one connect to two
# # two connect to one
# # three connect to one and two
# # fourth is not connect to any
# # five is connect to one and five
# ##
|
2ac0f93a0ade5c1f9b151df58fce8ca7deee3c11 | gsharansingh/easygplot | /easygplot/read.py | 5,137 | 3.9375 | 4 | import numpy as np
import csv
from sklearn.impute import SimpleImputer
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
class CSV:
"""
This module will read the csv file and create an object containing data and labels.
Parameters
----------
filename: str
Input the name of the csv file to read.
For example, Plot.CSV('...filename.csv...')
labels: bool (default = True)
Set 'True', if you want to set any column in the file as x-axis.
Set 'False', if you want indexing of x-axis from 0 to length(rows).
delimiter: one char str (default = `,`)
If the csv file is separated with some other symbols (such as ':', ';', '/t',....), Input that symbol.
set_index: int (default = 0)
If you want some other column index to be x-axis, pass that column index.
If you do not want any column index to be x-axis, pass 'None'.
missing_data_handling_strategy: str, Optional (default = 'mean')
In the case, some values are missing in the file, then either replace the values or drop the row/column.
If 'mean', it will replace missing value using mean along column.
If 'median', it will replace missing value using median along column.
If 'most_frequent', it will replace missing value using the most frequent value along column.
If 'constant', it will replace missing value with fill_value.
If 'drop_row', it will drop the whole row containing missing value.
If 'drop_column', it will drop the whole column containing missing value.
skip_lines: int (default = None)
If some empty line(s) or description present in the beginning of the file,
input the number of lines to discard the lines.
TODO:
Complete
"""
def __init__ (self, filename, labels = True, delimiter=",", set_index = 0, missing_data_handling_strategy = 'mean', skip_lines = None):
self.data = None
self.columns = []
try:
with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile, delimiter=delimiter)
if skip_lines:
for _ in range(skip_lines):
next(csvreader)
# extracting field names through first row
if labels:
self.columns = next(csvreader)
self.data = np.genfromtxt(csvfile, delimiter=delimiter)
except:
raise "Give a valid filename!!"
if np.isnan(self.data).any():
import matplotlib.pyplot as plt
print("Data contains missing values. Here is the representation of missing values:")
plt.imshow(~np.isnan(self.data), aspect = 'auto', cmap = plt.cm.gray, interpolation='nearest')
self.data = np.delete(self.data, np.argwhere(np.isnan(self.data).all(axis = 0)), axis = 1)
self.data = np.delete(self.data, np.argwhere(np.isnan(self.data).all(axis = 1)), axis = 0)
print("""NOTE: if the data has whole row or column as missing values, that row or column is already dropped!\
\nFor more information, check 'missing_data_handling_strategy' parameter in Docu String by: 'print(easygplot.read.CSV.__doc__)'""")
if missing_data_handling_strategy == 'drop_column':
self.data = np.delete(self.data, np.argwhere(np.isnan(self.data).any(axis = 0)), axis = 1)
elif missing_data_handling_strategy == 'drop_row':
self.data = np.delete(self.data, np.argwhere(np.isnan(self.data).any(axis = 1)), axis = 0)
else:
imputer = SimpleImputer(missing_values=np.nan, strategy=missing_data_handling_strategy)
self.data[:, :] = imputer.fit_transform(self.data[:, :])
if set_index == None:
self.x_label = list(range(self.data.shape[0]))
self.row_data = self.data[:, :]
if labels:
self.labels = (self.x_label, self.columns)
else:
self.labels = (self.x_label, list(range(self.data.shape[1])))
else:
self.x_label = self.data[:, set_index]
if set_index == 0:
self.row_data = self.data[:, 1:]
if labels:
self.labels = (self.x_label, self.columns[1:])
else:
self.labels = (self.x_label, list(range(self.data.shape[1]-1)))
else:
self.row_data = np.hstack((self.data[:, :set_index], self.data[:, set_index+1:]))
if labels:
self.labels = (self.x_label, self.columns[:set_index] + (self.columns[set_index+1:]))
else:
self.labels = (self.x_label, list(range(self.data.shape[1]-1)))
def __getitem__ (self, index):
return self.row_data[:, index], (self.labels[0], self.labels[1][index])
def __str__ (self):
return f"Columns: {self.columns}"
def __len__ (self):
return self.data.shape[0] |
19830b17fe1289929e9d9d7f6312715ea6cafeb7 | SDSS-Computing-Studies/006b-more-functions-ye11owbucket | /problem2.py | 774 | 4.125 | 4 | #!python3
"""
##### Problem 2
Create a function that determines if a triangle is scalene, right or obtuse.
3 input parameters:
float: one side
float: another side
float: 3rd side
return:
0 : triangle does not exist
1 : if the triangle is scalene
2 : if the triangle is right
3 : if the triangle is obtuse
Sample assertions:
assert triangle(12,5,13) == 2
assert triangle(5,3,3) == 1
assert triangle(5,15,12) == 3
assert triangle(1,1,4) == 0
(2 points)
"""
def triangle(a,b,c):
side=[a,b,c]
side.sort()
if side[0]+side[1] < side[2]:
return 0
if side[0]**2+side[1]**2 > side[2]**2:
return 1
if side[0]**2+side[1]**2 == side[2]**2:
return 2
if side[0]**2+side[1]**2 < side[2]**2:
return 3
pass |
d0c11c50751edd87834d175c3da469dd5798f009 | kathmandu777/CompetitiveProgramming | /AtCoder/ABC/47/A47.py | 109 | 3.71875 | 4 | a, b, c = map(int, input().split())
if a + b == c or a+c==b or b+c==a:
print("Yes")
else:
print("No") |
d65975d3639c3217e144c20f710bda998a3a022c | kathmandu777/CompetitiveProgramming | /AtCoder/typical90/38.py | 189 | 3.78125 | 4 | from math import gcd
def lcm(a, b):
return a // gcd(a, b) * b
a, b = map(int, input().split())
ans = lcm(a, b)
if ans > 1000000000000000000:
print("Large")
else:
print(ans)
|
5acf15ce3fb66c989ad18a538fa76d10c40c0d23 | Soojin-C/Soft_Dev_Work | /18_listcomp/pyth.py | 222 | 3.953125 | 4 | # Soojin Choi
# SoftDev1 pd08
# K18 -- Getting Clever with List Comprehensions
# 2019-04-15
def triple(num):
return [(c, b, a) for a in range(num) for b in range(a) for c in range(b) if a*a == b*b + c*c]
print(triple(19)) |
110ee696b9aaca673716a87b62859a9189ec2f82 | Soojin-C/Soft_Dev_Work | /23_memoize/fib.py | 947 | 3.578125 | 4 | #
import random
def make_HTML_heading(f):
txt = f()
def inner():
return '<h1>' + txt + '</h1>'
return inner
# equiv to greet = make_HTML_heading(greet)
@make_HTML_heading # v1
def greet():
greetings = ["Hello","Welcome","AYO!", "Hola", "Bonjour", "Word up"]
return random.choice(greetings)
print(greet()) # v1
# v0 greet_heading = make_HTML_heading(greet)
# v0 print(greet_heading())
# memoization -> process of storing previously calculated results to avoid recalculation
# fib
def memoization(fxn):
val = {}
def inner(n):
if n not in val:
print(n)
val[n] = fxn(n)
return val[n]
return inner
@memoization
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
#elif n in val:
# return val[n]
else:
calc = fib(n-1) + fib(n-2)
# val[n] = calc
return calc
#fib = memoization(fib)
print(fib(7))
|
35bbf1589f356460621c1b30e7e0767ad44dca92 | MacLure/python-basics | /strings.py | 890 | 4 | 4 | print('Malcolm MacLure')
print("o----")
print(' ||||')
print('*' * 10)
price = 10
rating = 4.9
name = "Malcolm"
is_published = True
print(price)
name = input("What is your name? ")
print("Hi " + name)
fav_color = input("What color do you like? ")
print(name + " likes " + fav_color)
print("first letter is " + name[0])
print("next 3 letters: " + name[1:4])
print("first 5 letters: " + name[:5])
print("last letters after the 5th: " + name[5:])
birth_year = input('Birth year: ')
age = 2019 - int(birth_year)
print(type(age))
print(age)
multiline_string = '''Hello,
This is a miltiline
string.'''
print (multiline_string)
msg = f'{name} likes {color}.'
print(msg)
string_length = len(name)
print(string_length)
print(name.upper())
print(multiline_string.find('llo'))
print(multiline_string.find('x'))
print(multiline_string.replace('Hello', 'hey hey'))
print('multiline' in multiline_string) |
f48d66b2f5160b271af8e24c4d458656d0cbd571 | Cliedy-s/AIclass | /1911/1119/1119/_1119_02_DBConnect_SelectToDic.py | 435 | 3.8125 | 4 | import sqlite3
import sys
from datetime import datetime
def main():
conn = sqlite3.connect('database.db')
conn.row_factory = sqlite3.Row # 딕셔너리 구조로 컬럼을 접근하는 옵션
cursor = conn.cursor()
cursor.execute("SELECT * FROM books;")
rows = cursor.fetchall()
for row in rows:
print(row, row['title'], row['pages'])
if __name__ == "__main__":
sys.exit(int(main() or 0))
|
d0cdb4adfa23380fe67475b546ec6b4d6bcb743d | Cliedy-s/AIclass | /1911/1114/1114_01_함수/_1114_02_FileReadWrite.py | 1,242 | 3.640625 | 4 |
# dir
import os
# mkdir
if(not os.path.isdir('data')):
os.mkdir('data')
# file
import sys
print(sys.stdin.encoding)
print(sys.stdout.encoding)
# create file
f = open('data/test.txt', 'w', encoding='utf-8')
f.close()
# with
with open('data/test.txt','w', encoding='utf-8') as f:
f.write('write with with')
# write file
#delete original
f = open('data/test.txt','w', encoding='utf-8')
for x in range(1,11):
data = f'{x}번째 줄입니다. \n'
f.write(data)
f.close()
#append
f = open('data/test.txt','a', encoding='utf-8')
f.write('-' * 50)
for x in range(11,21):
f.write(f'\n{x} : Hello Python ')
f.close()
# read file
# readlines => list
print()
f = open('data/test.txt','r',encoding= 'utf-8')
print(''.join(f.readlines()))
f.close()
# readline => string
f = open('data/test.txt','r',encoding= 'utf-8')
while True:
line = f.readline()
if(not line) :
break
print(line, end='')
f.close()
# readline => string (2)
with open('data/test.txt','r',encoding= 'utf-8') as f :
for word in f:
print(word.strip())
# read => big string
print()
f = open('data/test.txt','r',encoding= 'utf-8')
print(f.read())
f.close()
|
303d8a6188befcd79bfc7540d919c60b5635ab7f | Cliedy-s/AIclass | /1911/1118/1118/_1118_01_basicclass_property.py | 1,857 | 3.578125 | 4 | class TestClass:
memberCnt = 0
#def __init__(self, name='홍기롷' , phone='010-1111-1111'):
# self.name = name
# self.phone = phone
# print('생성')
#def __init__(self, **kwargs): # 많이 쓰는 방법
# self.name = kwargs.get('name', '홍길동')
# self.phone = kwargs.get('phone','010-1111-1111')
# print('생성')
#def __init__(self, *kwargs):
# self.name = kwargs['name'] == None and '홍길동' or kwargs['name']
# self.phone = kwargs['phone'] == None and '010-1111-1111' or kwargs['phone']
# print('생성')
def __init__(self, *args, **kwargs):
if len(args) == 2:
self.__name = args[0]
else:
self.__name = kwargs.get('name', '홍길동')
self.phone = kwargs.get('phone','010-1111-1111')
print('생성')
TestClass.memberCnt +=1
# property
# get
@ property
def name(self):
return self.__name
# set
@ name.setter
def name(self, name):
self.__name = name
#
def showInfo(self):
return self.__str__()
# == ToString()
def __str__(self):
return f"name : {self.name} phone : {self.phone}"
def __del__(self):
TestClass.memberCnt -= 1
print('소멸')
def main():
tc = TestClass(name = '홍길동', phone = '111-1111-1111')
tc2 = TestClass()
tc3 = TestClass('박박박','333-3333-3333')
print(tc)
print(tc2) # __str__
print(tc2.showInfo())
print(id(tc), id(tc2))
print(tc.__dict__)
print(tc2.__dict__) # 속성 값만 보여줌
print(dir(tc)) # 선언된 메서드까지 보여줌
print(TestClass.memberCnt, tc.memberCnt, tc2.memberCnt)
del tc2
print(TestClass.memberCnt, tc.memberCnt)
print(tc)
if (__name__ == '__main__') : main() |
f4739ff93399de8d4e4700bc743959737bac6a18 | Cliedy-s/AIclass | /1911/1113/1113_01_몸풀기/_1113_02_elif.py | 403 | 3.953125 | 4 | a = int(input('a : '))
if a%2 : # 1 => 홀수 : 참, 0 => 짝수 : 거짓
print('홀수')
else :
print('짝수')
if a > 0 :
print('양수')
elif a < 0 :
print('음수')
else :
print('0')
if a :
print('양수')
elif a <0 :
print('음수')
else :
print('0')
if 0:
pass
elif 3:
pass
else :
print('4')
3 in [1,2,3]
if 4 not in [1,2,3]:
print('안녕')
|
b983feb44b8289edfb1a208ab90faa693c8007ff | gangys0411/python | /day02/for_04.py | 110 | 3.75 | 4 | for j in range(2, 10):
for i in range(1, 10):
print('{}X{}={}'.format(j, i, j*i))
print("\n")
|
11afcc9e6d5d4568a481cf9bccea8f2cb523f62e | gangys0411/python | /day02/while_01.py | 77 | 3.671875 | 4 | count = 0
while count < 3:
print("횟수 : ", count)
count +=1
|
96c16c6f7147474b895edc5234691a4caeba8471 | MarvickF/Coding-from-School-2020 | /CH5 LAB.py | 790 | 4.09375 | 4 | """
Program: sentence generator.py
Marvick Felix
This program generates sentences using grammar and simple vocab and prints them.
"""
import random
prepositions = ("WITH", "BY")
articles = ("A", "THE")
nouns = ("DOG", "MOUSE", "CAR","KEYBOARD")
verbs = ("RAN","SAW","LEFT")
def sentence():
return nounPhrase()+ " " + verbPhrase()
def nounPhrase():
return random.choice(articles)+" " + random.choice(nouns)
def verbPhrase():
return random.choice(verbs) + " " + nounPhrase() + " " + prepositionalPhrase()
def prepositionalPhrase():
return random.choice(prepositions) + " " + nounPhrase()
def main():
number = int(input("Enter the number of sentences: "))
for count in range(number): print(sentence())
if __name__ == "__main__":
main()
|
f9b4912d65ffb4d7d088bb1a5508ccf50d96dcdf | nickstoian/LanguageModeling | /CompareCorpora.py | 2,841 | 3.53125 | 4 | # Nicolas Stoian
# CS780 Natural Language Processing
# Homework - Language Modeling
textFile = open('brown-train-padded.txt', 'r')
unigramDict = dict()
for line in textFile:
for word in line.split():
if word not in unigramDict:
unigramDict[word] = 1
else:
unigramDict[word] += 1
textFile.close()
def unigramCompare(textFile, unigramDict):
numTokens = 0
numTokensNotInTraining = 0
for line in textFile:
for word in line.split():
numTokens += 1
if word not in unigramDict:
numTokensNotInTraining += 1
print("Test file name =", textFile.name)
print("Total number of words in file =", numTokens)
print("Number of words not appearing in training data =", numTokensNotInTraining)
print("Percentage of words not appearing in training data =", (numTokensNotInTraining / numTokens) * 100, "%")
print()
print()
print("Question 3")
textFile1 = open('brown-test-padded.txt', 'r')
textFile2 = open('learner-test-padded.txt', 'r')
unigramCompare(textFile1, unigramDict)
unigramCompare(textFile2, unigramDict)
textFile1.close()
textFile2.close()
textFile = open('brown-train-processed.txt', 'r')
bigramDict = dict()
prevWord = ""
for line in textFile:
for word in line.split():
if word == '<s>':
prevWord = word
elif prevWord + " " + word not in bigramDict:
bigramDict[prevWord + " " + word] = 1
prevWord = word
else:
bigramDict[prevWord + " " + word] += 1
prevWord = word
textFile.close()
def bigramCompare(textFile, unigramDict, bigramDict):
numBigrams = 0
numBigramsNotInTraining = 0
for line in textFile:
prevWord = ""
for word in line.split():
if word not in unigramDict:
word = "<unk>"
if word == '<s>':
prevWord = word
elif prevWord + " " + word not in bigramDict:
numBigramsNotInTraining += 1
numBigrams += 1
prevWord = word
else:
numBigrams += 1
prevWord = word
print("Test file name =", textFile.name)
print("Total number of bigrams in file =", numBigrams)
print("Number of bigrams not appearing in training data =", numBigramsNotInTraining)
print("Percentage of bigrams not appearing in training data =", (numBigramsNotInTraining / numBigrams) * 100, "%")
print()
print()
print("Question 4")
textFile1 = open('brown-test-padded.txt', 'r')
textFile2 = open('learner-test-padded.txt', 'r')
bigramCompare(textFile1, unigramDict, bigramDict)
bigramCompare(textFile2, unigramDict, bigramDict)
textFile1.close()
textFile2.close()
|
9a266880216cdf3a9c10495912467403e69cc5a0 | tony-blake/MultiUserBlog3 | /helpers/form_data.py | 704 | 3.953125 | 4 | """ Handles hashing and verification of user passwords
Examples:
username("some_username")
password("some_unencrypted_password")
email("some_email")
* Returns a Match object if valid, otherwise returns None
"""
import re
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
PASS_RE = re.compile(r"^.{3,20}$")
EMAIL_RE = re.compile(r'^[\S]+@[\S]+\.[\S]+$')
def username(username):
""" Returns a Match object if valid """
return username and USER_RE.match(username)
def password(password):
""" Returns a Match object if valid """
return password and PASS_RE.match(password)
def email(email):
""" Returns a Match object if valid """
return not email or EMAIL_RE.match(email)
|
e935b348e9f40316060ccab9f045ce3b7151a1fe | scriptedinstalls/Scripts | /python/strings/mystrings.py | 574 | 4.25 | 4 | #!/usr/bin/python
import string
message = "new string"
message2 = "new string"
print message
print "contains ", len(message), "characters"
print "The first character in message is ", message[0]
print "Example of slicing message", message, "is", message[0:4]
for letter in message:
print letter
if message == message2:
print "They match!"
message = string.upper(message)
print message
message = string.lower(message)
print message
print string.capitalize(message)
print string.capwords(message)
print string.split(message)
print string.join(message)
|
ceb846a43c34cfa75d688986d1f3b2a24a8875aa | evvanErb/DailyDigest | /sendMail.py | 1,278 | 3.5 | 4 | """Send Mail"""
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
with open ("passwords.txt", "r") as myfile:
keysAndPasses = myfile.read()
keysAndPasses = eval(keysAndPasses)
EMAIL_PASSWORD = keysAndPasses["EMAIL_PASSWORD"]
SENDER_ADDR = keysAndPasses["SENDER_ADDR"]
def sendEMail(messageContent, receiveAddr, session):
#Setup the MIME
message = MIMEMultipart()
message["From"] = "Daily Digest"
message["To"] = receiveAddr
message["Subject"] = "Daily Digest Report"
#The body and the attachments for the mail
message.attach(MIMEText(messageContent, "html"))
#Text of email
text = message.as_string()
#Send EMail
session.sendmail(SENDER_ADDR, receiveAddr, text)
def sendMassIndividualEmails(messageContent, addresses):
#Create SMTP session for sending the mail
session = smtplib.SMTP("smtp.gmail.com", 587) #use gmail with port
session.starttls() #enable security
session.login(SENDER_ADDR, EMAIL_PASSWORD) #login with mail_id and password
#Iterate over all user emails and send to each
for email in addresses:
sendEMail(messageContent, email, session)
#End Session after all emails sent
session.quit()
print("[*] Mail Sent")
|
e05c5f29757947574b0ed92d3bab95678b489cdf | lisiur/leetcode | /tests/test_implement_strstr.py | 1,435 | 3.5625 | 4 | import unittest
from solutions.implement_strstr.solution import Solution
class TestStrStr(unittest.TestCase):
def test_1(self):
u_input = {
'haystack': 'hello',
'needle': 'll'
}
u_output = 2
solution = Solution()
u_result = solution.strStr(**u_input)
self.assertEqual(u_output, u_result)
def test_2(self):
u_input = {
'haystack': 'aaaaa',
'needle': 'bba'
}
u_output = -1
solution = Solution()
u_result = solution.strStr(**u_input)
self.assertEqual(u_output, u_result)
def test_3(self):
u_input = {
'haystack': 'aaaaa',
'needle': ''
}
u_output = 0
solution = Solution()
u_result = solution.strStr(**u_input)
self.assertEqual(u_output, u_result)
def test_4(self):
u_input = {
'haystack': 'aaaaa',
'needle': 'a'
}
u_output = 0
solution = Solution()
u_result = solution.strStr(**u_input)
self.assertEqual(u_output, u_result)
def test_5(self):
u_input = {
'haystack': 'a',
'needle': 'a'
}
u_output = 0
solution = Solution()
u_result = solution.strStr(**u_input)
self.assertEqual(u_output, u_result)
if __name__ == '__main__':
unittest.main()
|
753ac65d90f255043c2c7db008fb11f9783c746d | lisiur/leetcode | /solutions/reverse_integer/solution.py | 564 | 3.546875 | 4 | class Solution:
def larger(self, a: str, b: str):
if len(a) > len(b):
return True
elif len(a) < len(b):
return False
else:
return a > b
def reverse(self, x: int) -> int:
maxN = '2147483647'
if x == -2147483648: # 把边界条件剔除,则后面 x = -x 是安全的操作
return 0
sign = 1 if x >= 0 else -1
x = sign * x
s = str(x)[::-1]
if self.larger(s, maxN):
return 0
else:
return sign * int(s)
|
db8303b93df50c980a95e58b8ed00df139718cff | dongshuicen/py_practice1 | /practice/TimeTest.py | 357 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import time
print(time.localtime(time.time()))
print("格式化后当前日期:" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
import calendar
months = {1,2,3,4,5,6,7,8,9,10,11,12}
years = [2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020]
for y in years:
for i in months:
print(calendar.month(y, i))
|
09f88fe9c8285725678f93ebacf9a9544184d6ce | Dairo01001/python_URI | /URI_1021.py | 504 | 3.640625 | 4 | def main():
billetes = [100, 50, 20, 10, 5, 2]
monedas = [100, 50, 25, 10, 5, 1]
n = float(input())
print('NOTAS:')
for billete in billetes:
ans = n // billete
n = n - (ans * billete)
print(f'{int(ans)} nota(s) de R$ {billete:.2f}')
print('MOEDAS:')
n = n * 100
for moneda in monedas:
ans = n // moneda
n = n - (ans * moneda)
print(f'{int(ans)} moeda(s) de R$ {moneda / 100:.2f}')
if __name__ == '__main__':
main()
|
355f4f4f88df99e546aa8dd06ac4ffb957430a81 | Dairo01001/python_URI | /URI_1118.py | 497 | 3.65625 | 4 | def solve():
suma: float = 0.0
cont: int = 0
while cont < 2:
score = float(input())
if 0 <= score <= 10:
suma += score
cont += 1
else:
print('nota invalida')
print(f'media = {(suma / cont):.2f}')
def main():
solve()
while True:
ans = int(input('novo calculo (1-sim 2-nao)\n'))
if ans == 1:
solve()
elif ans == 2:
break
if __name__ == '__main__':
main()
|
63dc2d245a9951bac2d9b12df9ac94cea24ff252 | Dairo01001/python_URI | /URI_1133.py | 284 | 4 | 4 | def swap(a: int, b: int):
if a > b:
return b + 1, a
return a, b
def main():
x = int(input())
y = int(input())
x, y = swap(x, y)
for i in range(x, y):
if i % 5 == 2 or i % 5 == 3:
print(i)
if __name__ == '__main__':
main()
|
82b342be159fdbf98ded99bab601f79a90bbc300 | sanyaverma/shipdesigns.github.io | /hmw-generator.py | 2,386 | 3.734375 | 4 | import random
#Fun How Might We statements
actions = ["design ", "build ", "create ", "invent ", "make "]
objects = ["a bed", "an ice cream cone", "shoes", "music player", "an ecosystem", "a new planet", "a coffee shop", "a new tea flavor", "a bottle of wine", "the Shift house"]
subjects = ["dragons", "a tent", "humans", "Ria Bazaz", "our society", "babies", "my grandmother"]
impact = ["we solve world hunger", "we can turn dirt into clean water",
"earth gets destroyed", "tornado occurs", "happiness is brought", "a dog cries", "you fuck it ship it"]
randomactions = random.choice(actions)
randomobjects = random.choice(objects)
randomsubjects = random.choice(subjects)
randomimpact = random.choice(impact)
fun_hmw_prompt = "How might we " + randomactions + randomobjects + " for " + randomsubjects + " so that " + randomimpact + "?"
print(fun_hmw_prompt)
#Serious How Might We statements
seriousprompt= ["redesign the contraceptive buying experience for teenage girls to make it less stigmatizing?", "empower individuals to remain hopeful and build better online communities that promote well-being, provide people with daily structure, and give them hope for a better future?",
"improve the bill splitting process for college students to ensure no one is paying too much or too little?",
"strengthen a college campus community by connecting mentors and mentees to help new students adjust to campus life?",
"increase accessibility to technology products and services and areas with poor internet access?",
"promote recycle reduce, and reuse habits to preschoolers to help build a sustainable future?",
"help working adults prioritize healthy living habits including fitness and diet to reduce their risk of disease?",
"help Snapchat cater to a more diverse audience while also maintaining the current user base?",
"design an interface that gives car owners the ability to get information about their car from a remote location?",
"design an interface that gives homeowners the ability to get information about their house, via IoT devices, from a remote location?",
"design a platform for users to select a topic and pair them in a voice chat with someone else wanting to discuss the same topic?"
"write a How Might we Statement?"]
randomseriousprompt = random.choice(seriousprompt)
serious_hmw_prompt = "How might we " + randomseriousprompt
print(serious_hmw_prompt) |
49a1ffd693a73f5e6d0f271b28e877fd051eab1e | Serikaku/Treinamento-Python | /CursoemVideo/ex057.py | 223 | 3.953125 | 4 | sexo = str(input('Digite seu sexo [M/F]: ')).strip().upper()
while sexo not in 'MmFf':
sexo = str(input('Dados invalidos. Digite seu sexo [M/F]: ')).strip().upper()
print('Sexo {} registrado com sucesso'.format(sexo))
|
a86d25ff9597219c946ce2a6ae6701ea6a874b56 | Serikaku/Treinamento-Python | /CursoemVideo/ex084.py | 779 | 3.625 | 4 | lista = []
pessoa = []
pesado = leve = 0
while True:
pessoa.append(str(input('Nome: ')))
pessoa.append(float(input('Peso: ')))
if len(lista) == 0:
pesado = leve = pessoa[1]
else:
if pessoa[1] > pesado:
pesado = pessoa[1]
if pessoa[1] < leve:
leve = pessoa[1]
lista.append(pessoa[:])
pessoa.clear()
cont = str(input('Deseja continuar? [S/N] ')).strip()
if cont in 'Nn':
break
print(f'{len(lista)} pessoas foram cadastradas.')
print(f'O maior peso foi de {pesado}Kg. Peso de ', end='')
for p in lista:
if p[1] == pesado:
print(f'[{p[0]}]', end=' ')
print(f'\nO menor peso foi de {leve}Kg. Peso de ', end='')
for p in lista:
if p[1] == leve:
print(f'[{p[0]}]', end=' ')
|
cece13bc067a242963346a7b85203eab0a9c16a1 | Serikaku/Treinamento-Python | /CursoemVideo/ex038.py | 255 | 4.03125 | 4 | x = int(input('Digite um numero inteiro: '))
y = int(input('Digite outro numero inteiro: '))
if x > y:
print('O primeiro valor eh maior')
elif x < y:
print('O segundo valor eh maior')
else:
print('Nao existe valor maior, os dois sao iguais')
|
126a2ce7838ca8ffa13f21e9ad5edaad0871653e | Serikaku/Treinamento-Python | /CursoemVideo/ex049.py | 137 | 4.03125 | 4 | x = int(input('Digite um numero inteiro para saber sua tabuada: '))
for i in range(0, 11):
print('{} x {:2} = {}'.format(x, i, x*i))
|
a166ad36b59f7a81590b48df9349a7352952cbaa | Serikaku/Treinamento-Python | /CursoemVideo/ex098.py | 609 | 3.765625 | 4 | from time import sleep
def contador(x, y, z):
if z < 0:
z = z * -1
elif z == 0:
z = 1
print(f'Contagem de {x} ate {y} de {z} em {z}')
if x < y:
for j in range(x, y + 1, z):
print(f'{j} ', end='')
sleep(0.25)
else:
for j in range(x, y - 1, -z):
print(f'{j} ', end='')
sleep(0.25)
print('FIM')
print('-' * 40)
contador(1, 10, 1)
contador(10, 0, 2)
print('Agora e sua vez de personalizar a contagem')
i = int(input('Inicio: '))
f = int(input('Fim: '))
p = int(input('Passo: '))
contador(i, f, p)
|
5e4509c1c093e67f3a225e156b7496b9de66ac2c | Serikaku/Treinamento-Python | /CursoemVideo/ex044.py | 533 | 3.765625 | 4 | x = float(input('Digite o valor da compra: '))
y = int(input('''Forma de pagamento
1 a vista dinheiro/cheque
2 vista no cartao
3 2x no cartao
4 3x ou mais no cartao
'''))
if y == 1:
print('O valor a ser pago eh: R${:.2f}'.format(x*0.9))
elif y == 2:
print('O valor a ser pago eh: R${:.2f}'.format(x*0.95))
elif y == 3:
print('O valor a ser pago eh: R${:.2f}'.format(x))
elif y == 4:
print('O valor a ser pago eh: R${:.2f}'.format(x*1.2))
else:
print('Voce digitou um opcao invalida')
|
9765d97890708ad90aa79dc6246f1892d91ada0f | Serikaku/Treinamento-Python | /CursoemVideo/ex010.py | 134 | 3.921875 | 4 | x = float(input('Digite quantos reais você possui na carteira: R$'))
print('Você pode comprar US${:.2f} Dólares'.format(x / 3.27))
|
f7978987760c18c4645ef89b6981d10125dc91ab | Serikaku/Treinamento-Python | /PythonTeste/aula09a.py | 256 | 3.71875 | 4 | frase = 'Curso em Video Python'
print(frase[::2])
print(frase.count('o'))
print(len(frase.strip()))
print(frase.replace('Python', 'Android'))
print(frase)
print('Curso' in frase)
print(frase.find('aaaa'))
dividido = frase.split()
print(dividido[2][3]) |
d3f7f5eaa8d5d72840df9d59033a421a01dc871e | maricielo935/trabajopurihuaman | /ejercicio6.py | 311 | 3.625 | 4 | #Teorema de Poncelet
cateto1,cateto2,hipotenusa,radio=0.0,0.0,0.0,0.0
#Asignacion de valores
cateto1=30
cateto2=40
hipotenusa=50
#Calculo
radio=(cateto1+cateto2-hipotenusa)/2
#Mostrar valores
print("cateto1 = ", cateto1)
print("cateto2 = ", cateto2)
print("hipotenusa =", hipotenusa)
print("radio =", radio)
|
1f8b658b51a25b6fb9d7009766dcdff44f5a6da9 | namaslay33/digitalCrafts | /python-exercises/W1/Thur/TurtleExercises/Square.py | 489 | 4 | 4 | from turtle import *
import matplotlib
import matplotlib.pyplot as plot
def square() :
forward(50)
right(50)
forward(50)
right(50)
square()
# plot.show()
# from turtle import *
# import matplotlib
# import matplotlib.pyplot as plot
# def turtocta():
# for i in range(8):
# forward(100)
# right(45)
# plot.show()
# if __name__ == "__main__":
# turtocta()
# from turtle import *
# shape("turtle")
# width(5)
# circle(75)
# mainloop()
|
b71f6bd7944952554f9369bdb51a6e372110ff16 | jzagozda/Incu2020 | /PyWebinar1/FunctionsFix.py | 444 | 3.875 | 4 | def test_function(a,b):
""" Why result1 is None? :(
"""
result = a*b
print('Result: {0}'.format(result))
return result
result1 = test_function(2,4)
print(result1)
#######################################
def test_function2(a,b):
""" Why do we have only 15 instead of Result: 15 as well? :(
"""
result = a*b
print('Result: {0}'.format(result))
return result
result2 = test_function2(3,5)
print(result2) |
6835453a527ac9ada2daf07f8d4694d9352ebb86 | hboonewilson/IntroCS | /DAs/WilsonBooneDA9.py | 2,088 | 3.765625 | 4 | #Boone Wilson
#DA 9
#Section A04
#11/7
def getHawkID():
return ['hbwilson']
#write function that takes as an argument either a 12-digit positive integer or
#string consisting of 12 digits and calculates the 13th digit
def calculatgeCheckDigit(n):
#create a list to hold all of the digits as strings
myList = []
#convert n to a string myString
myString = str(n)
#add each digit to the list of digits in the correct order... turn to integers!
for num in myString:
myList.append(int(num))
#create a variable to track sum
add = 0
#digits at even indexes are added to sum and odd are multiplied by three and
#added to the sum
for i in range(0, 12):
if i % 2 == 0:
#set even indicies' value to prod
prod = myList[i]
#odd!
else:
#set odd indicies' (value * 3) to product
prod = myList[i] * 3
#add whatever prod is to add
add += prod
for i in range(0, 10):
if (add + i) % 10 == 0:
return i
def flipBits(myString):
for let in myString:
if let == '0' or let == '1':
pass
else:
return 'not a binary string'
if len(myString) == 8:
pass
else:
return 'wrong length'
#create return str
retstr = ''
for let in myString:
if let == '0':
retstr += '1'
else:
retstr += '0'
return retstr
def xor(string1, string2):
zero = '0'
one = '1'
for number in string1:
if number == zero or number == one:
pass
else:
return 'not binary strings'
for number in string2:
if number == zero or number == one:
pass
else:
return 'not binary strings'
if len(string1) == 4 and len(string2) == 4:
pass
else:
return 'wrong length'
retstr = ''
for i in range(0, 4):
if string1[i] == string2[i]:
retstr += '0'
else:
retstr += '1'
return retstr
|
e6b681234935ea15b7784a76d9921a900e137e7f | hboonewilson/IntroCS | /Collatz Conjecture.py | 885 | 4.46875 | 4 | #Collatz Conjecture - Start with a number n > 1. Find the number of steps it...
#takes to reach one using the following process: If n* is even, divide it by 2.
#If *n is odd, multiply it by 3 and add 1.
collatz = True
while collatz:
input_num = int(input("Give me a number higher than 1: "))
if input_num > 1:
number = input_num
collatz = False
elif input_num == 1:
print("A number larger than 1 please.")
else:
print("That number is less than 1!")
steps = 0
while number != 0:
print(number)
steps += 1
if number%2 == 0:
number = number/2
if number == 1:
print(f"It took {steps} steps to make it to one.")
break
if number%2 == 1:
number = number*3 + 1
|
4107ba5e1bad42808d61e400d5da73ba46befcdf | hboonewilson/IntroCS | /base10base2converter.py | 1,149 | 3.96875 | 4 | #create a function that takes a number and a letter as an argument and converts
#the number into the opposite base (2==>10) (10===>2)
def binaryTenConverter(num, base):
#decide which way to convert
if base.lower() == "b":
#count length of binary string
s_num = str(num)
long = len(s_num)
#iterate and creat a list of t/f for each place value
t_f = []
for i in range(0, long):
#if zero, add false
if s_num[i] == '0':
t_f.append(False)
#if one add True
elif s_num[i] == '1':
t_f.append(True)
#return t_f
#set long = to lenght of t_f list
long = len(t_f)
print(long)
#create three objects ans and counter
ans = 0
counter = 0
for i in range(0, long):
#set long to new length
long = long - counter
value = 2 ** long
print(value)
if t_f[i]:
ans += value
counter += 1
else:
counter += 1
pass
return ans |
106bad049c8f2140ee27ef5e798d8c4b7c0a90f3 | hboonewilson/IntroCS | /DAs/WilsonHenryDA2.py | 1,090 | 4 | 4 | #Henry Wilson
#Discussion Assignment 1
#Section 0A04
# Aug/29/19
#getHawkID
def getHawkID():
return ['hbwilson']
#write a function with 3 arguements, all of which are numbers.
#return the three arguments' average rounded to the nearest THENTH
def calculateAverage(n1, n2, n3):
#find mean
mean = (n1 + n2 + n3) / 3
#return rounded mean
return round(mean, 1)
#write a function with 3 arguements, all of which are numbers.
#return the three arguments' average rounded to the nearest THENTH in the form..
#of a string.
def getAverageString(n1, n2, n3):
#find mean
mean = (n1 + n2 + n3) / 3
#round mean
rounded = round(mean , 1)
#integrate mean into string
return f"The average value is {rounded}."
#write a function that takes 3 arguments, 2 values, and a string ("S"/"P")
#if 'S': return the sum
#if 'P': return the product
def doMath(n1, n2, operation):
#find out which operation to do from operation arg.. then return the answer
if operation.upper() == 'S':
return n1 + n2
elif operation.upper() == 'P':
return n1 * n2 |
abedcc99b6929f548c4b50b5f1f622a7ae7a6349 | bibanon/macrochan-scraper | /utils.py | 781 | 3.578125 | 4 | # handy file interfacing utilities
import os
import requests
def mkdirs(path):
"""Make directory, if it doesn't exist."""
if not os.path.exists(path):
os.makedirs(path)
def download_file(local_filename, url, clobber=False):
"""Download the given file. Clobber overwrites file if exists."""
dir_name = os.path.dirname(local_filename)
mkdirs(dir_name)
if clobber or not os.path.exists(local_filename):
i = requests.get(url)
# if not exists
if i.status_code == 404:
print('Failed to download file:', local_filename, url)
return False
# write out in 1MB chunks
chunk_size_in_bytes = 1024*1024 # 1MB
with open(local_filename, 'wb') as local_file:
for chunk in i.iter_content(chunk_size=chunk_size_in_bytes):
local_file.write(chunk)
return True
|
bbeb369e80c881f49f839022a68466650810bdda | ScottSko/Python---Pearson---Third-Edition---Chapter-9 | /Chapter 9 - Algorithm Workbench #6 - 10.py | 140 | 3.515625 | 4 | def main():
set1 = set([1, 2, 3])
set2 = set([3, 4, 5])
set3 = set1.symmetric_difference(set2)
print(set3)
main() |
8e6a9f4ffb5d58bf653ecaaba0b73a3e53642a8c | ScottSko/Python---Pearson---Third-Edition---Chapter-9 | /Chapter 9 - Programming Exercises #9 - Blackjack Simulator.py | 3,751 | 3.5625 | 4 | import random
def create_deck():
deck = {"Ace of Spades": 1, "2 of Spades" : 2, "3 of Spades": 3, "4 of Spades": 4, "5 of Spades" : 5,
"6 of Spades" : 6, "7 of Spades" : 7, "8 of Spades": 8, "9 of Spades": 9, "10 of Spades": 10,
"Jack of Spades": 10, "Queen of Spades": 10, "King of Spades": 10,
"Ace of Hearts": 1, "2 of Hearts": 2, "3 of Hearts": 3, "4 of Hearts": 4, "5 of Hearts": 5,
"6 of Hearts": 6, "7 of Hearts": 7, "8 of Hearts": 8, "9 of Hearts": 9, "10 of Hearts": 10,
"Jack of Hearts": 10, "Queen of Hearts": 10, "King of Hearts": 10,
"Ace of Clubs": 1, "2 of Clubs": 2, "3 of Clubs": 3, "4 of Clubs": 4, "5 of Clubs": 5,
"6 of Clubs": 6, "7 of Clubs": 7, "8 of Clubs": 8, "9 of Clubs": 9, "10 of Clubs": 10,
"Jack of Clubs": 10, "Queen of Clubs": 10, "King of Clubs": 10,
"Ace of Diamonds": 1, "2 of Diamonds": 2, "3 of Diamonds": 3, "4 of Diamonds": 4, "5 of Diamonds": 5,
"6 of Diamonds": 6, "7 of Diamonds": 7, "8 of Diamonds": 8, "9 of Diamonds": 9, "10 of Diamonds": 10,
"Jack of Diamonds": 10, "Queen of Diamonds": 10, "King of Diamonds": 10}
return deck
def deal_cards(deck):
p1_hand_value = 0
p2_hand_value = 0
card_number = 0
win = False
for count in range(len(deck)):
while win == False:
#https://stackoverflow.com/questions/4859292/how-to-get-a-random-value-in-python-dictionary
#That will work in Python 2.x where d.keys() is a list, but it won't work in Python 3.x where d.keys() is an iterator. You should do random.choice(list(d.keys())) instead.
key = random.choice(list(deck.keys()))
print("Card #", card_number + 1, "for Player 1:")
print(key)
if key == "Ace of Spades" or key == "Ace of Hearts" or key == "Ace of Clubs" or key == "Ace of Diamonds" and p1_hand_value < 11:
p1_hand_value += 11
else:
p1_hand_value += deck[key]
del deck[key]
key2 = random.choice(list(deck.keys()))
print("Card #", card_number + 1, "for Player 2:")
print(key2)
card_number += 1
if key2 == "Ace of Spades" or key2 == "Ace of Hearts" or key2 == "Ace of Clubs" or key2 == "Ace of Diamonds" and p2_hand_value < 11:
p2_hand_value += 11
else:
p2_hand_value += deck[key2]
del deck[key2]
if p1_hand_value == 21 and p2_hand_value == 21:
print("Player 1's hand value is", p1_hand_value)
print("Player 2's hand value is", p2_hand_value)
print("The game is a tie")
win = True
elif p1_hand_value > 21 and p2_hand_value > 21:
print("Player 1's hand value is", p1_hand_value)
print("Player 2's hand value is", p2_hand_value)
print("The game is a tie")
win = True
elif p1_hand_value > 21 or p2_hand_value == 21:
print("Player 1's hand value is", p1_hand_value)
print("Player 2's hand value is", p2_hand_value)
print("Player 2 wins!")
win = True
elif p2_hand_value > 21 or p1_hand_value == 21:
print("Player 1's hand value is", p1_hand_value)
print("Player 2's hand value is", p2_hand_value)
print("Player 1 wins!")
win = True
def main():
deck = create_deck()
input("Press enter to play.")
deal_cards(deck)
main() |
db066f582ca23bce7f1f7285ed984130ec617517 | Sabin-Gurung/RecordVisualizer | /Record.py | 566 | 3.59375 | 4 | #!/usr/bin/python3
class Record():
def __init__ (self, name, surname, dateOfBirth, address, occupation):
self.__name = name.upper()
self.__surname = surname.upper()
self.__DOB = dateOfBirth.upper()
self.__address = address.upper()
self.__occupation = occupation.upper()
def getData (self):
'''returns a list containing data in the right order'''
return [self.__name, self.__surname, self.__DOB, self.__address, self.__occupation]
@staticmethod
def getHeaders():
return ["Name", "Surname", "DOB", "Address", "Occupation"]
|
8e0ad0188d8c57078f4df07b3633cd79d296b03f | ramo16/algorithms | /plus minus.py | 1,391 | 3.9375 | 4 | """
Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and which fraction of its elements are zeroes, respectively. Print the decimal value of each fraction on a new line.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable.
Input Format
The first line contains an integer, , denoting the size of the array.
The second line contains space-separated integers describing an array of numbers .
Output Format
You must print the following lines:
A decimal representing of the fraction of positive numbers in the array.
A decimal representing of the fraction of negative numbers in the array.
A decimal representing of the fraction of zeroes in the array.
Sample Input
6
-4 3 -9 0 4 1
Sample Output
0.500000
0.333333
0.166667
Explanation
There are positive numbers, negative numbers, and zero in the array.
The respective fractions of positive numbers, negative numbers and zeroes are , and , respectively.
"""
#!/bin/python
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
p=0
ne=0
z=0
for i in range(len(arr)):
if arr[i]>0: p=p+1
elif arr[i]<0: ne=ne+1
else: z=z+1
print float(p)/len(arr)
print float(ne)/len(arr)
print float(z)/len(arr)
|
f25620d50790ea9ea3d83d519ed5c014dd7defb9 | ShinSnap/Coursera_Coursework | /PythonForEveryone/py4e_assign_4_6.py | 294 | 4 | 4 | def computepay(hours,rate) :
if hours <= 40 :
return hours * rate
elif hours > 40 :
return (40 * rate) + ((hours - 40) * (rate * 1.5))
rawhrs = input("Enter Hours: ")
rawrate = input("Enter Rate: ")
hrs = float(rawhrs)
rate = float(rawrate)
print(computepay(hrs,rate)) |
2820f6b37bebf0ff0389259ce640b22ac19f0117 | watchbutdonotlearn/PySharedclipboard | /client.py | 2,413 | 3.78125 | 4 | import socket # Import socket module
from pynput import keyboard
import tkinter as tk
host = ""
def saveip():
while True:
saveyn = input('Do you want to save your ip for next time? yes/no ')
if saveyn == "yes":
h = open('ipname', 'w')
h.write(host)
h.close()
break
elif saveyn == "no":
break
try:
with open('ipname', 'r') as f:
ipfilec = ""
ipfilec = f.read()
if ipfilec == "":
print('ipname file is empty')
print('Where to connect to (IP can be found through "ip addr" on linux, "ipconfig" on windows): ')
print('If you do not want to type this on next startup, create a file called "ipname" containing the target IP')
host = input('IP: ')
saveip()
else:
host = ipfilec
except:
print('ipname file not found')
print('Where to connect to (IP can be found through "ip addr" on linux, "ipconfig -a" on windows): ')
print('If you do not want to type this on next startup, create a file called "ipname" containing the target IP')
host = input('IP: ')
saveip()
port = 60000
print('Connect to: ' + host)
def getClipboardText():
root = tk.Tk()
# keep the window from showing
root.withdraw()
try:
return root.clipboard_get().encode("UTF-8", "ignore")
except:
return "ERR: clipboard is not text".encode()
def send():
s = socket.socket() # Create a socket object
s.connect((host, port))
#s.send("SEND".encode())
print('clipboard contains: ' + getClipboardText().decode('UTF-8', 'ignore'))
g = open('mytext.txt', 'wb')
g.write(getClipboardText())
g.close()
filename='mytext.txt'
f = open(filename,'rb')
l = f.read(1024)
while l != b'':
s.send(l)
print('Sent '+ repr(l))
l = f.read(1024)
f.close()
print('Done sending')
def on_activate():
print('Global hotkey activated!')
send()
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<alt>+c'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
|
e4412ee5916c086afa98285337bbad4ef7c37d0f | UF-Elektron/HelloWorld | /ETH_Aufgaben/poker.py | 1,810 | 3.578125 | 4 | print("*********")
print("P O K E R")
print("*********")
print("EINGABE IHRER KARTEN")
print("Geben Sie alle Karte in absteigender Wertigkeit ein: ")
print()
#Einlesen der Karten
card = [[0 for x in range(2)] for y in range(5)]
for cardId in range (0, 5):
for cardEl in range (0, 2):
print("Karte Nr ", cardId, "Farbe ", cardEl)
card[cardId][cardEl] = int(input("Wert "))
for cardId in range (0, 5):
print("Karte Nr ", cardId ," Wert = ", card[cardId][0] ," Farbe ", card[cardId][1])
#Bewertung der Hand
result = "Nothing :-("
colourCounter = 0
sameValue = [0 for x in range(15)]
row = 0
valueOld = card[0][0] + 1
colourOld = card[0][1]
for cardId in range (0, 5):
value = card[cardId][0]
colour = card[cardId][1]
if(valueOld == card[cardId][0] + 1):
row += 1
for x in range (0, 14):
if(x == card[cardId][0]):
sameValue[x] += 1
if(colour == colourOld):
colourCounter += 1
colourOld = colour
valueOld = card[cardId][0]
if(colourCounter == 5):
result = "Flush"
if(row == 5):
result = "Straight Flush"
if(card[0][0] == 14):
result = "Royal Flush"
elif row == 5:
result = "Straight"
highestNumber = 1
highestNumberOld = 1
for x in range (0, 14):
print(sameValue[x])
if highestNumber < sameValue[x]:
highestNumber = sameValue[x]
elif highestNumberOld < sameValue[x]:
highestNumberOld = sameValue[x]
if highestNumber == 4:
result = "Four of a kind"
elif highestNumber == 3:
result = "Three of a kind"
if highestNumberOld == 2:
result = "Full House"
elif highestNumber == 2:
result = "One Pair"
if highestNumberOld == 2:
result = "Two Pairs"
print("Your score: ", result)
|
8619c9355a1bfde0b4fdacf73c09b95edaa30128 | salma-nyagaka/golclinics-dsa | /classwork/01-arrays-and-strings/alternating_characters.py | 178 | 3.734375 | 4 | def alternatingCharacters(s):
result = 0
for i in range(len(s) - 1):
if (s[i] == s[i + 1]):
result += 1
return result |
568cdf4684e99910da53da82228d8d93320bc82c | salma-nyagaka/golclinics-dsa | /classwork/01-arrays-and-strings/minimum_swaps.py | 355 | 3.515625 | 4 | def minimumSwaps(arr):
swaps = 0
tmp = {}
for i, val in enumerate(arr):
import pdb
pdb.set_trace()
tmp[val] = i
for i in range(len(arr)):
if arr[i] != i+1:
swaps += 1
t = arr[i]
arr[i] = i+1
arr[tmp[i+1]] = t
tmp[t] = tmp[i+1]
return swaps |
4063cecbd1eee1918db71b5c7ad10460cb8f83a6 | L-dongkyung/study_Numpy | /tuple.py | 466 | 3.890625 | 4 | a = (1, 2, 3)
b = (1, 2, 4)
c = (1, 2, 3)
# print(type(a))
# print(type(a[0]))
# print(type(a[1]))
# print(type(a[2]))
# a[0] = -1
# print(a)
# print(a[0:2])
# print(a == b)
# print(a is b)
# print(a == c)
# print(a is c)
d = list(a)
d[0] = -1
e = tuple(d)
# print(e)
f = (1, 'abc', [1, 2, 3])
before_id = id(f[2])
# print(type(f[2]))
f[2].append(4)
# print(f[2])
# print(id(f[2]) == before_id)
# print(f)
# f[2] = 5
g = 1,2
print(g)
x, y = g
print(x, y)
|
6fb5fb5dc3264574117b16d3deffdad25885c0fa | ajamanjain/AI-Python_Program | /Cannibals_and_Missionaries.py | 2,521 | 3.765625 | 4 | m1 = 3 # int(input("Enter the number of the missionary: "))
c1 = 3 # int(input("Enter the number of the Cannibal: "))
m2 = 0
c2 = 0
print("Intially m&c at bank 1: ")
print(m1, c1)
print("Intially m&c at bank 2: ")
print(m2, c2)
# place1=[m1,c1]
# place2=[m2,c2]
# print(place1)
# print(place2)
while(1):
r = int(input("Enter rule no.: "))
if(r == 1):
m1 -= 1
c1 -= 1
m2 += 1
c2 += 1
print("when 1m and 1c goes from bank1 to bank 2")
print("bank1:")
print(m1, c1)
print("bank2:")
print(m2, c2)
elif(r == 2):
m1 -= 1
m2 += 1
print("when 1m goes from bank1 to bank 2")
print("bank1:")
print(m1, c1)
print("bank2:")
print(m2, c2)
elif(r == 3):
c1 -= 1
c2 += 1
print("when 1c goes from bank1 to bank 2")
print("bank1:")
print(m1, c1)
print("bank2:")
print(m2, c2)
elif(r == 4):
m1 -= 2
m2 += 2
print("when 2m goes from bank1 to bank 2")
print("bank1:")
print(m1, c1)
print("bank2:")
print(m2, c2)
elif(r == 5):
c1 -= 2
c2 += 2
print("when 2c goes from bank1 to bank 2")
print("bank1:")
print(m1, c1)
print("bank2:")
print(m2, c2)
elif(r==6): #
m1+=1
c1+=1
m2-=1
c2-=1
print("when 1m and 1c goes from bank2 to bank1")
print("bank1:")
print(m1,c1)
print("bank2:")
print(m2,c2)
elif(r==7):#
m1+=1
m2-=1
print("when 1m goes from bank2 to bank1")
print("bank1:")
print(m1,c1)
print("bank2:")
print(m2,c2)
elif(r==8):#
c1+=1
c2-=1
print("when 1c goes from bank2 to bank1")
print("bank1:")
print(m1,c1)
print("bank2:")
print(m2,c2)
elif(r==9):#
m1+=2
m2-=2
print("when 2m goes from bank bank2 to bank1")
print("bank1:")
print(m1,c1)
print("bank2:")
print(m2,c2)
elif(r==10):#when 2c goes from bank1 to bank 2
c1+=2
c2-=2
print("when 2c goes from bank2 to bank1")
print("bank1:")
print(m1,c1)
print("bank2:")
print(m2,c2)
if(m2==3 and c2==3):
break
print("FINALLY M&C at BANK1 : ")
print(m1,c1)
print("FINALLY M&C at BANK2 : ")
print(m2,c2)
# Answer: 1,7,5,8,4,6,4,8,5,8,5
|
31fe48fb9839914dcfdb510de5b6a56923fd26a6 | objarni/kyh-practice | /vecka_3_uppg_20till28/uppgift26.py | 1,884 | 3.5 | 4 | '''
Nu ska vi leka med att skicka parametrar till en databas!
OMDB är en IMDB-liknande hemsida på nätet, som också tillhandahåller
ett API där man kan göra sökningar.
26.1 Jag har fixat en API-nyckel åt oss! Därför kan vi använda detta
webb-API (som är ett REST-API) och leka. Testa att skriva följande
i en browser:
http://www.omdbapi.com/?t=Alien&apikey=9f6d550c
Ändra på "Alien" till en annan film!
26.2 Använd requests.get() med ovanstående URL, fast ta bort ? och framåt.
Använd istället params={"t": "Alien", "apikey": "9f6d550c"} så kommer
requests att lägga på ? och & och sånt strunt själv. :)
Pretty printa (pprint) JSON-resultatet med ett Pythonprogram!
26.3 Bygg ett Pythonprogram där användaren frågar efter en film, och skriv
sedan ut en snygg infobox om filmen, typ så här:
*** Resultat från OMDB! ***
Alien (1979) regisserades av Ridley Scott.
Skådisar: Tom Skerritt, Sigourney Weaver, Veronica Cartwright, Harry Dean Stanton
IMDB betyg: 8.4
Awards: Won 1 Oscar. Another 16 wins & 22 nominations.
Längd: 117 min
'''
import json
import requests
from pprint import pprint
def main():
movie = input("Ange film: ")
r = requests.get("http://www.omdbapi.com/", params={"t": movie, "apikey": "9f6d550c"})
text = r.text
result = json.loads(text)
if "Error" in result:
print("Hittar inte filmen!")
main()
year = result['Year']
title = result['Title']
director = result['Director']
actors = result['Actors']
imdb = result['imdbRating']
awards = result['Awards']
runtime = result['Runtime']
print("*** Resultat från OMDB! ***")
print(f"{title} ({year}) regisserades av {director}.")
print(f"Skådisar: {actors}")
print(f"IMDB betyg: {imdb}")
print(f"Awards: {awards}")
print(f"Längd: {runtime} min")
main()
|
e28cd7478454ac6a826a8aa0b3164c6cbd830a99 | objarni/kyh-practice | /vecka_8/upg51_8.py | 1,463 | 3.9375 | 4 | '''
51.1 Skriv om funktionen add_as_def som lambda, och lagra i en variabel
def add_as_def(a, b):
return a + b
# add_as_lambda = ???
51.2 Skriv om obj som en funktion "upper"
obj = lambda s: s.upper()
51.3 Översätt denna lambda till en vanlig def funktion
join_as_lambda = lambda strings, inbetween: inbetween.join(strings)
51.4 Vad kommer följande program att skriva ut? Läs och diskutera först.
Testkör därefter, och förklara varför ni får det resultat ni får...
anna = ("Anna", "Persson", 42)
lova = ("Lova", "Andersson", 35)
alex = ("Alex", "Börjesson", 10)
people = [anna, lova, alex]
on_surname = sorted(people, key=lambda p: p[1])
for (first, last, age) in on_surname:
print(f"{first} {last} ({age} år)")
51.5 Skriv ett program som utgår ifrån ovanstående, men skriver ut personerna i åldersordning.
51.6 Utgående ifrån förra programmet, ändra så att en "def age_sorter" funktion används istället för lambdan,
med hjälp syntaxen key=age_sorter. Vilket sätt tycker ni är tydligast?
51.7 Skriv om föregående program så att det använder sig av en class Person med attributen first, last och age
istället för tuppler. Vilken form tycker ni är lättast att läsa?
51.8 Varför kan inte hello skrivas som lambdauttryck? Försök gärna skriva om det till lambdaform!
def hello(name):
import random
rnd_age = random.randint(1, 150)
print(f"Hello {name}! I guess your age is {rnd_age}")
'''
|
a761e59f300f440a39f7f3d01fef601ee11c8815 | objarni/kyh-practice | /mix/for_loops.py | 539 | 4.03125 | 4 | print('\nMed range(0, 5):')
for i in range(0, 5):
print(i)
print('\nMed listor:')
min_lista = ["abc", "def"]
for elem in min_lista:
print(elem)
print('\nMed enumerate och lista:')
min_lista = ["abc", "def"]
for num, elem in enumerate(min_lista):
print(num, elem)
print('\nMed dict:')
min_dict = {
"Olof": True,
"Lisa": True
}
for key in enumerate(min_dict):
print(key)
print('\nMed dict och enumerate:')
min_dict = {
"Olof": True,
"Lisa": True
}
for num, key in enumerate(min_dict):
print(num, key)
|
48e2d703aa29d67354173182b16e097b84a82ad3 | objarni/kyh-practice | /vecka_2_uppg_12till19/uppgift15_1.py | 358 | 3.71875 | 4 | # 15.1 Implementera "wordcount" som jag och Christoffer byggde
def wordcount(text):
# 1. Dela texten i mellanrum (med split)
# 2. Beräkna längden på resultatlistan
# 3. Profit
return len(text.split())
if __name__ == '__main__':
text = input("Skriv in en text:")
print(f"I den texten hittade jag {wordcount(text)} ord. Byeeee!")
|
3cdefa5fc0556e48dd29d897ab81119e71969efb | zooo1/algorithm | /boj/14890.py | 1,589 | 3.71875 | 4 | import sys
input = sys.stdin.readline
def makeSlope(n):
global N, L
slope = [0]*N
i, j = 0,0
while(i<N-1):
# 다음 index와 같은 값
if (board[n][i] == board[n][i+1]):
i += 1
# 다음 index에서 높이가 1 클 때
elif (board[n][i] +1 == board[n][i+1]):
j = i
cnt = 0
while (j>=0 and cnt<L):
if (not slope[j] and board[n][j]+1==board[n][i+1]):
j -= 1
cnt += 1
else:
return 0
if cnt == L:
for k in range(j+1, i+1):
slope[k] = 1
i += 1
else:
return 0
# 다음 index에서 높이가 1 작을 때
elif(board[n][i]-1 == board[n][i+1]):
j = i+1
cnt = 0
while (j<N and cnt<L):
if (not slope[j] and board[n][j] == board[n][i]-1):
j += 1
cnt += 1
else:
return 0
if cnt == L:
for k in range(i+1, j):
slope[k] = 1
i = j-1
else:
return 0
# 나머지 경우는 모두 불가능함
else:
return 0
return 1
N, L = map(int, input().split())
board = [[int(x) for x in input().split()] for _ in range(N)]
ans = 0
for n in range(N):
ans += makeSlope(n)
board = list(zip(*board))
for n in range(N):
ans += makeSlope(n)
print(ans)
|
c69b825497b92d2132ef34700f6581edd1d72049 | laurentlam/labyrinth_solving | /Main_Code/environment.py | 18,030 | 4.25 | 4 | # '''''' Environment and state classes ''''''
# Numpy is needed for matrix operations
import numpy
# Random is needed for random initialisations
import random
# Restrictions for states in the maze:
# - A "start" or an "arrival" state is on the border of the maze.
# - an "arrival" state is unique in a maze.
# Reminder : List_of_states=["o","x","s","e"], respectively hole, wall, start and arrival
class state:
def __init__(self,name_index):
""" A state is defined by its name_index, meaning the index corresponds to a state (see List_of_states). """
self.name_index=name_index
def reward(self):
"""
Calculates the reward of the Agent going to this state.
We assume here that to a state is given a unique reward.
That can be done with the List_of_Rewards below.
"""
List_of_Rewards=[-1,-1000,-10,50000]
return (List_of_Rewards[int(self.name_index)])
def arrival_state(self):
"""
This method makes the state an arrival state.
The arrival state has its name_index to 3 (see List_of_states).
"""
self.name_index=3
#definition of random functions, according to restrictions of a maze.
def random_intern_state(self):
"""
This method randomly creates a state of the inside of the maze in accordance with restrictions.
The intern possible states are holes and walls, corresponding to a name_index of 0 or 1 (see List_of_states).
"""
dice=random.randint(0,1)
self.name_index=dice
def random_extern_state(self):
"""
This method randomly creates a state of the border of the maze in accordance with restrictions.
We intentionally forget the (unique) arrival state (name_index of 3, see List_of_states) to add it in the end.
"""
dice=random.randint(1,2)
self.name_index=dice
class ENV:
def __init__(self,width,length,states,current_position):
"""
An environment is defined by its shape (width and length) ,
its states wich is a numpy matrix (array) of indexes of states (name_index of each state),
and the current position of the agent.
"""
#Dimensions of the environment
self.width=width
self.length=length
#List of states of the environment where there is a hole, a wall, a start or an end.
self.states=states
#current position of the agent
self.current_position=current_position
def show(self):
"""
This method prints on the screen the matrix of states of the environment.
For this, the matrix of states has to be created from the matrix of name_index of states (self.states).
The transition can be done with the List_of_states.
Plus, the current position of the agent is visualised.
"""
#5 states exists : hole (can go), wall (can't go), start and end as :
List_of_states=[".","x","s","e"]
#conversion to python classical matrix
List_to_print=self.states.tolist()
#conversion of each state to its associated character
(i,j) = self.current_position
str = (self.length+1)*' -'
print(str)
for x in range(self.width):
for y in range(self.length):
if (x == i) and (y == j):
List_to_print[x][y] = "A"
else:
List_to_print[x][y] = List_of_states[int(List_to_print[x][y])]
#the state we print has become its character value instead of the index
print('|',' '.join(List_to_print[x]) ,'|')
print(str)
def isInitialState(self, state):
""" Check whether state is a starting position, return a boolean """
if (state.name_index!=2):
return(False)
else:
return(True)
def initialStates(self):
""" Returns the list of all possible starting positions """
initStates = []
for i in range(self.length):
for j in range(self.width):
state_temp=state(self.states[i][j])
if self.isInitialState(state_temp):
initStates.append([i,j])
return(initStates)
def isTerminalState(self, state):
""" Checks whether state is a finish position, return a boolean """
if (state!=3):
return(False)
else:
return(True)
def terminalStates(self):
""" Return list of all possible ending positions """
termStates = []
for i in range(self.length):
for j in range(self.width):
state_temp=state(self.states[i][j])
if self.isTerminalState(state_temp):
termStates.append([i,j])
return(termStates)
def State(self,position):
""" Returns the name_index of the state of the given position, meaning the state of the given position """
[i,j]=position
name_index=int(self.states[i,j])
return name_index
def currentState(self):
"""Returns the name_index of the current state, meaning the state of the current position"""
current_name_index=self.State(self.current_position)
return current_name_index
def possibleActions(self,position):
""" Finds all possible motions (actions) from a given position in the maze"""
# List_of_states=["o","x","s","e"]=[hole,wall,start,end]=[0,1,2,3]
possible_actions=[]
states = self.states
[x,y] = position
width = self.width
length = self.length
# Checking if there is no misplacement of the agent
#if (current_state==1) or (current_state==3):
# return (NULL)
# NULL value is chosen because empty list is for another error case (see above at next return)
# If Agent on the border of the maze
if ((x==0) or (x==width-1) or (y==0) or (y==length-1)):
# North and South
# North
if (x==0):
# North West
if (y==0):
if (states[x+1,y]!=1) and (states[x+1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([1,0])
if (states[x,y+1]!=1) and (states[x,y+1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,1])
# North East
elif (y==length-1):
if (states[x+1,y]!=1) and (states[x+1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([1,0])
if (states[x,y-1]!=1) and (states[x,y-1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,-1])
# North else
else:
if (states[x+1,y]!=1) and (states[x+1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([1,0])
for j in [-1,1]:
if (states[x,y+j]!=1) and (states[x,y+j]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,j])
# South
if (x==width-1):
# South West
if (y==0):
if (states[x-1,y]!=1) and (states[x-1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([-1,0])
if (states[x,y+1]!=1) and (states[x,y+1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,1])
# South East
elif (y==length-1):
if (states[x-1,y]!=1) and (states[x-1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([-1,0])
if (states[x,y-1]!=1) and (states[x,y-1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,-1])
# South else
else:
if (states[x-1,y]!=1) and (states[x-1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([-1,0])
for j in [-1,1]:
if (states[x,y+j]!=1) and (states[x,y+j]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,j])
# West and East
# West
if (y==0):
# North West
if (x==0):
if (states[x+1,y]!=1) and (states[x+1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([1,0])
if (states[x,y+1]!=1) and (states[x,y+1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,1])
# South West
elif (x==width-1):
if (states[x-1,y]!=1) and (states[x-1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([-1,0])
if (states[x,y+1]!=1) and (states[x,y+1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,1])
# West else
else:
if (states[x,y+1]!=1) and (states[x,y+1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,1])
for i in [-1,1]:
if (states[x+i,y]!=1) and (states[x+i,y]!=2): #Not a wall or starting position in the North then in the South
possible_actions.append([i,0])
# East
if (y==length-1):
if (x==0):
if (states[x+1,y]!=1) and (states[x+1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([1,0])
if (states[x,y-1]!=1) and (states[x,y-1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,-1])
# South East
elif (x==width-1):
if (states[x-1,y]!=1) and (states[x-1,y]!=2): # Not a wall or starting position in the South
possible_actions.append([-1,0])
if (states[x,y-1]!=1) and (states[x,y-1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,-1])
# East else
else:
if (states[x,y-1]!=1) and (states[x,y-1]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,-1])
for i in [-1,1]:
if (states[x+i,y]!=1) and (states[x+i,y]!=2): #Not a wall or starting position in the North then in the South
possible_actions.append([i,0])
# If the agent is within the maze
else:
# North and South
for i in [-1,1]:
if (states[x+i,y]!=1) and (states[x+i,y]!=2): #Not a wall or starting position in the North then in the South
possible_actions.append([i,0])
# West and East
for j in [-1,1]:
if (states[x,y+j]!=1) and (states[x,y+j]!=2): #Not a wall or starting position in the West then in the East
possible_actions.append([0,j])
# ['N', 'S', 'O', 'E'] corresponds to [[-1,0],[1,0],[0,-1],[0,1]]
# Which are relative motions from the current position
return(possible_actions)
# Note : if possible_actions is empty, the agent is blocked and the maze can't be solved --> error case.
def next_position(self,position,action):
""" returns the next position from position if action is applied
Args:
action : The action to do at the current state
Returns:
next_position : the position of the agent if the action was applied
"""
[i,j]=position
i+=action[0]
j+=action[1]
return [i,j]
def runStep(self, action):
"""Perform the action in the state to change the position and get the reward
Args:
action : The action to do at the current state
Returns:
The current position is updated
Return the total associated reward
"""
# Checking if the action is in the possible_actions
if action not in self.possibleActions(self.current_position):
print("action is not a possible action (runStep)")
return None
# 1) Next position of the agent
self.current_position=self.next_position(self.current_position,action)
# 2) reward : reward from the new state of the agent
reward=state(self.State(self.current_position)).reward()
# Returning : the reward
return reward
def create_random_environment(self):
""" This method initializes an environment randomly, according to the assumed restrictions
Args:
No arguments.
Returns:
self (the maze) is actualized : width, length, states and current position
"""
# List of states
width=self.width
length=self.length
states=numpy.zeros((width,length))
# Creation of states within the maze
for i in range (1,width-1):
for j in range (1,length-1):
state_temp = state(0)
# Having 1/4 probability to get a wall
state_temp.random_intern_state()
if (state_temp.name_index == 1):
state_temp.random_intern_state()
states[i,j] = state_temp.name_index
# Creation of states around the maze
for j in range(length):
state_temp.random_extern_state()
states[-1,j] = state_temp.name_index
state_temp.random_extern_state()
states[0,j] = state_temp.name_index
for i in range(1,width-1): # Specific borns to exclude already assigned states
state_temp.random_extern_state()
states[i,-1] = state_temp.name_index
state_temp.random_extern_state
states[i,0] = state_temp.name_index
self.states=states
# Creation of a list of the initial states
initialStates_list = self.initialStates()
if (len(initialStates_list)<2):
return None
# Choosing a random initial state to start with
random_index=random.randint(0,len(initialStates_list)-1)
# Initial state not in a corner
while (initialStates_list[random_index]==[0,0]) or (initialStates_list[random_index]==[width-1,length-1]) or (initialStates_list[random_index]==[0,length-1]) or (initialStates_list[random_index]==[width-1,0]):
random_index=random.randint(0,len(initialStates_list)-1)
self.current_position = initialStates_list[random_index]
start_position = self.current_position
#Making the initial state accessible
if (start_position[0]==0):
states[start_position[0]+1,start_position[1]]=0
if (start_position[0]==width-1):
states[start_position[0]-1,start_position[1]]=0
if (start_position[1]==0):
states[start_position[0],start_position[1]+1]=0
if (start_position[1]==length-1):
states[start_position[0],start_position[1]-1]=0
# creation of the arrival (substitution to a starting state)
initialStates_list.pop(random_index) # list of starts without the agent starting position
random_index=random.randint(0,len(initialStates_list)-1)
# Terminal state not in a corner
corners=[[0,0],[width-1,length-1],[width-1,0],[0,length-1]]
while initialStates_list[random_index] in corners:
random_index=random.randint(0,len(initialStates_list)-1)
arrival_position = initialStates_list[random_index]
states[arrival_position[0],arrival_position[1]] = 3
# Making the terminal state accessible
if (arrival_position[0]==0):
states[arrival_position[0]+1,arrival_position[1]]=0
if (arrival_position[0]==width-1):
states[arrival_position[0]-1,arrival_position[1]]=0
if (arrival_position[1]==0):
states[arrival_position[0],arrival_position[1]+1]=0
if (arrival_position[1]==length-1):
states[arrival_position[0],arrival_position[1]-1]=0
# Other unused initial states become a wall
initialStates_list.pop(random_index) #list of starts without the agent finish position
for position in initialStates_list:
states[position[0],position[1]] = 1
initialStates_list = [start_position[0],start_position[1]]
# States of the environment are now fully randomly created in accordance with every restriction
self.states=states
def create_existing_environment(self,fichier_labyrinthe):
"""Lecture du fichier de labyrinthe"""
grille = []
fichier = open(fichier_labyrinthe, "r")
ligne = fichier.readline()
while ligne != ".\n":
ligne_grille = []
for case in ligne.split(" "):
ligne_grille.append(int(case))
grille.append(ligne_grille)
ligne = fichier.readline()
self.states=numpy.array(grille)
|
bb14f56c650407842332f6effded0f1825b8f245 | valeria-chemtai/Checkpoint1-Amity | /Amity.py | 16,702 | 3.53125 | 4 | """Class Amity is the controller of the app using
the Models Views Controller concept i.e. MVC"""
import random
from sqlalchemy.orm import sessionmaker
from Models.person import Person, Fellow, Staff
from Models.room import Office, LivingSpace
from Models.database import People, Rooms, Base, engine
# Initiate link to database for storage and retrival of data
DBSession = sessionmaker(bind=engine)
session = DBSession()
class Amity(object):
def __init__(self):
self.rooms = []
self.offices = []
self.living_spaces = []
self.allocated = []
self.unallocated = []
def create_room(self, room_name, purpose):
""" method for creating rooms in Amity """
if (isinstance(room_name, str) and isinstance(purpose, str)):
if [room for room in self.rooms
if room_name.upper() == room.room_name.upper()]:
print("{} Exists in Amity.".format(room_name.upper()))
return "{} Exists in Amity.".format(room_name.upper())
if purpose == "OFFICE" or purpose == "office":
room = Office(room_name.upper())
self.offices.append(room)
self.rooms.append(room)
print("{} {} created".format(room.room_name, room.purpose))
return "Room Created"
elif purpose == "LIVINGSPACE" or purpose == "livingspace":
room = LivingSpace(room_name.upper())
self.living_spaces.append(room)
self.rooms.append(room)
print("{} {} created".format(room.room_name, room.purpose))
return "Room Created"
print("{} is not a valid room type.".format(purpose))
print("Invalid Room Name")
return "Invalid Room Name"
def add_person(self, first_name, second_name, role, wants_accomodation):
""" method for adding a fellow/staff to amity database """
if (isinstance(first_name, str) and isinstance(second_name, str)):
person_name = first_name.upper() + " " + second_name.upper()
allocated = [allocated for allocated in self.allocated
if person_name.upper() == allocated.
person_name.upper()]
unallocated = [unallocated for unallocated in self.unallocated
if person_name.upper() == unallocated.
person_name.upper()]
person = allocated or unallocated
if person:
print("{} Exists in Amity.".format(person_name))
return "{} Exists in Amity.".format(person_name)
if role.upper() == "FELLOW" and wants_accomodation == "N":
person = Fellow(person_name)
self.allocate_office(person)
return "Fellow Added"
elif role.upper() == "FELLOW" and wants_accomodation == "Y":
person = Fellow(person_name)
self.allocate_office(person)
self.allocate_living_space(person)
return "Fellow Added and LIvingSpace Allocated"
elif role.upper() == "STAFF" and wants_accomodation == "N":
person = Staff(person_name)
self.allocate_office(person)
return "Staff Added"
elif role.upper() == "STAFF" and wants_accomodation == "Y":
person = Staff(person_name)
self.allocate_office(person)
print("Staff Added and Allocated Office Only")
return "Staff Added and Allocated Office Only"
print("Invalid Person Name")
return "Invalid Person Name"
def allocate_office(self, person):
"""allocate_office is a method used for allocation of
office to both staff and fellows"""
try:
if self.offices:
room = [room for room in self.offices if len(
room.occupants) < 6]
office = random.SystemRandom().choice(room)
office.occupants.append(person)
self.allocated.append(person)
print("{} allocated office {}".format(person.person_name,
office.room_name))
return "Office Allocated"
else:
self.unallocated.append(person)
print("No Office available now, {} placed in waiting list ".
format(person.person_name))
return "No Office Available"
except IndexError:
self.unallocated.append(person)
print("No Office available now, {} placed in waiting list ".
format(person.person_name))
def allocate_living_space(self, person):
try:
if self.living_spaces:
room = [room for room in self.living_spaces if len(
room.occupants) < 4]
living = random.SystemRandom().choice(room)
living.occupants.append(person)
print("and allocated livingspace {}".format(living.room_name))
else:
self.unallocated.append(person)
print("No living space now, {} placed in waiting list"
.format(person.person_name))
except IndexError:
self.unallocated.append(person)
print("No living space available now, {} placed in waiting list "
.format(person.person_name))
def allocate_unallocated_office(self, person):
try:
if self.offices:
room = [room for room in self.offices if len(
room.occupants) < 6]
office = random.SystemRandom().choice(room)
office.occupants.append(person[0])
self.allocated.append(person[0])
self.unallocated.remove(person[0])
print("{} moved from waiting list to {}".
format(person[0].person_name, office.room_name))
else:
print("No Offices Available Yet")
return "No Offices Available Yet"
except IndexError:
print("No Offices Available Yet")
def allocate_unallocated_livingspace(self, person):
try:
if self.living_spaces:
room = [room for room in self.living_spaces if len(
room.occupants) < 6]
living = random.SystemRandom().choice(room)
living.occupants.append(person[0])
self.allocated.append(person[0])
self.unallocated.remove(person[0])
print("{} moved from waiting list to {}".format(
person[0].person_name, living.room_name))
else:
print("No Livingspaces Available Yet")
return "No Livingspaces Available Yet"
except IndexError:
print("No Livingspaces Available Yet")
def allocate_unallocated(self, first_name, second_name):
"""Method to allocate unallocate members rooms"""
try:
person_name = first_name.upper() + " " + second_name.upper()
person = [person for person in self.unallocated if
person_name.upper() == person.person_name.upper()]
room = [room for room in self.rooms if person[0] in room.occupants]
if not person:
print("{} Not in Unallocated".format(person_name))
return "{} Not in Unallocated".format(person_name)
elif person and room:
if room[0].purpose == "office":
self.allocate_unallocated_livingspace(person)
return "Fellow Now Allocated LivingSpace"
else:
self.allocate_unallocated_office(person)
return "Member Now Allocated Office"
except IndexError:
print("Person given not in Unallocated")
def reallocate_person(self, first_name, second_name, room_name):
""" method to reallocate a person to another room """
try:
person_name = first_name.upper() + " " + second_name.upper()
allocated = [allocated for allocated in self.allocated if
person_name.upper() == allocated.person_name.upper()]
room = [room for room in self.rooms if room_name.upper() ==
room.room_name.upper()]
person = allocated
if not person:
print("Add {} to Amity first".format(person_name))
return "Add {} to Amity first".format(person_name)
elif not room:
print("{} is not a room in Amity".format(room_name))
return "{} is not a room in Amity".format(room_name)
elif [occupant for occupant in room[0].occupants
if person_name == occupant.person_name]:
print("{} is already in {}".format(
person_name, room[0].room_name))
return "{} is already in {}".format(person_name,
room[0].room_name)
elif (room[0].purpose == "office" and len(room[0].occupants) == 6):
print("{} is full.".format(room[0].room_name))
return "Room is Full"
elif (room[0].purpose == "living_space" and
len(room[0].occupants) == 4):
print("{} is full.".format(room[0].room_name))
return"Room is Full"
else:
old_room = [room for room in self.rooms if person[
0] in room.occupants]
if old_room[0].purpose == room[0].purpose:
room[0].occupants.append(person[0])
old_room[0].occupants.remove(person[0])
person[0].old_room = room[0].room_name
print("{} was moved from {} to {}".format(
person[0].person_name, old_room[0].room_name,
room[0].room_name))
return "Reallocated Successfully"
else:
print("Can Only Reallocate to Room with Purpose as Current Room")
return "Choose Appropriate Room Type"
except Exception as e:
print("Error Occured, Try Later")
def load_people(self, filename):
""" method to add people to rooms from a text file """
try:
if filename:
try:
with open(filename, 'r') as f:
people = f.readlines()
for person in people:
params = person.split() + ["N"]
self.add_person(params[0], params[
1], params[2], params[3])
print("People Successfully Loaded")
return "People Successfully Loaded"
except IndexError:
print("Data not consistent")
return "Data not consistent"
except FileNotFoundError:
print("File Not Found")
return "File Not Found"
def print_allocations(self, filename):
""" method to print a list of allocations on screen
with option to store in a txt file """
if not self.rooms:
print("No Rooms to Show")
return "No Rooms"
output = " "
for room in self.rooms:
if len(room.occupants):
output += room.room_name.upper() + '\n'
output += "--" * 60 + '\n'
for occupant in room.occupants:
output += occupant.person_name + ", "
output += ("\n\n")
print(output)
return "Allocations Printed"
if filename:
with open(filename, 'w') as f:
f.write(output)
print("Allocations Printed to {}".format(filename))
return "Allocations Printed to {}".format(filename)
def print_unallocated(self, filename):
""" method to print a list of unallocated people in screen
with option to store in a text file """
if not self.unallocated:
print("No Member in Unallocated")
return "No Member in Unallocated"
else:
print("\n UNALLOCATED MEMBERS")
print("----" * 10)
for person in self.unallocated:
person_name = person.person_name
print(person_name)
print("----" * 10)
return "Unallocated Displayed"
if filename:
with open(filename, 'w') as f:
f.write(person_name)
print("Data Saved to Text File")
return "Data Saved to Text File"
def print_room(self, room_name):
""" method to print room and all people allocated to that room."""
room = [room for room in self.rooms if room_name.upper() ==
room.room_name.upper()]
if room:
room = room[0]
print("\n{}'s OCCUPANTS".format(room.room_name.upper()))
print("----" * 10)
for person in room.occupants:
print(person.person_name)
print("----" * 10)
return "Print room successful"
else:
print("{} does not exist in Amity".format(room_name.upper()))
return "Room does not exist"
def save_state(self, database_name="Amity_database.db"):
""" method to save all data in the app into SQLite database """
try:
for table in Base.metadata.sorted_tables:
session.execute(table.delete())
session.commit()
for person in self.allocated + self.unallocated:
rooms_allocated = " "
for room in self.rooms:
if person in room.occupants:
rooms_allocated += room.room_name + " "
person = People(Name=person.person_name, Role=person.role,
RoomAllocated=rooms_allocated)
session.add(person)
for room in self.rooms:
people = " "
for occupant in room.occupants:
people += occupant.person_name + " "
room = Rooms(Name=room.room_name,
Purpose=room.purpose, Occupants=people)
session.add(room)
session.commit()
print("Data Saved Successfully")
return "Data Saved"
except:
session.rollback()
print("Error Saving to DB")
def load_state(self, database_name):
""" method to load data from database into the app """
# Load room data
try:
for room_name, purpose, occupants in session.query(Rooms.Name, Rooms.Purpose, Rooms.Occupants):
individuals = occupants.split(" ")
individuals.remove("")
if purpose == "office":
room = Office(room_name)
for individual in individuals:
person = Person(individual)
room.occupants.append(person)
self.offices.append(room)
self.rooms.append(room)
elif purpose == "living_space":
room = LivingSpace(room_name)
for individual in individuals:
person = Person(individual)
room.occupants.append(person)
self.living_spaces.append(room)
self.rooms.append(room)
# Load People data
for person_name, role, rooms_allocated in session.query(People.Name, People.Role, People.RoomAllocated):
if role == "FELLOW":
person = Fellow(person_name)
if len(rooms_allocated) > 1:
self.allocated.append(person)
else:
self.unallocated.append(person)
else:
person = Staff(person_name)
if len(rooms_allocated) > 1:
self.allocated.append(person)
else:
self.unallocated.append(person)
print("Data Successfully Loaded to App")
return "Data Successfully Loaded to App"
except:
print("Invalid database name")
return "Invalid Database Name"
|
9b3ddd5ee73a2ffc0e2e9f790f4b5b6a6aaa36ac | adamcristi/TheHatefulMemesChallenge-ASET | /Implementation/classifiers/classifier.py | 454 | 3.53125 | 4 | import abc
class Classifier:
def __init__(self):
pass
@abc.abstractmethod
def load_data(self, args): # load the images and texts
pass
@abc.abstractmethod
def preprocess(self, *args): # preprocess the images and texts
pass
@abc.abstractmethod
def train(self, args): # create model and train data
pass
@abc.abstractmethod
def show_best_result(self, args) -> float:
pass
|
de3a8f6ebe60273e6bf7cb9224bf7ad3ee4a6a98 | TomButts/Lichen-Project | /feature-extraction/tools/parsers/csv/parse.py | 423 | 3.625 | 4 | import csv
def parse(targets_path):
"""Parse a csv containing an ordered list of targets on the first row.
Args:
targets_path: The path to the csv file
Returns:
row: A list of targets from the first row of the csv.
"""
with open(targets_path, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ',', quotechar = '\"')
for row in reader:
return row
|
2aac3019d09b202cd50e62bea9eb294be8cbd0aa | davethedave41/ALprogramming | /crypto/encryption.py | 2,457 | 3.703125 | 4 | from cryptography.fernet import Fernet
import io
#Function which generates our key (AES)
def keyGen():
key = Fernet.generate_key()
# with open('key.key','wb') as f:
# f.write(key)
file = open('key.key', 'wb')
file.write(key)
file.close()
#Function which reads the key
def keyRead():
try:
# with open('key.key','rb') as f:
# f.read()
file = open('key.key', 'rb') # must be in binary format
key = file.read()
file.close()
return key
except FileNotFoundError:
#If key does not exists a new one is created.
print("No Key exists, a new one has just been created.")
keyGen()
keyRead()
# Function to encrypt usernames using the key
def encrypt_users(u_data, Key):
u_name = u_data['username']
u_data = str(u_data)
fernet = Fernet(Key)
encrypted = fernet.encrypt(u_data.encode())
with open('Users/'+u_name+'.txt','wb') as f:
f.write(encrypted)
# ecnrypts a single tweet --
def encrypt_tweets(tweet, u_name, Key):
fernet = Fernet(Key)
encrypted = fernet.encrypt(tweet.encode())
with open('tweets.txt','ab') as f:
f.write(encrypted)
with open('tweets.txt','a') as f:
f.write('\n')
# decrypts tweets ONLY if user is in the trust network
# returns a list of strings, decrypted posts must be converted to dictionaries
def decrypt_tweets(trust_net, Key):
trusted = False
tweets = []
fernet = Fernet(Key)
with open('tweets.txt','rb') as f:
for line in f:
trusted = False
decrypted = fernet.decrypt(line)
decrypted = decrypted.decode()
for name in trust_net:
if name in decrypted:
tweets.append(decrypted)
trusted = True
break
if trusted == True:
print('victory royale')
pass
else:
tweets.append(line.decode())
return tweets
# decrypt usernames using the key
def decrypt_users(u_name, Key):
fernet = Fernet(Key)
try:
with open('Users/'+u_name+'.txt','rb') as f:
user_stats = f.read()
decrypted = fernet.decrypt(user_stats)
decrypted = decrypted.decode()
decrypted = eval(decrypted)
return decrypted
except FileNotFoundError as e:
print('nothing..')
return None
return None
|
85299f7db32018c1b3be12b6ebdae3c521fe3842 | HenriqueSamii/TP1-Fundamentos-de-Programa-o-com-Python | /tp1IntroPiton11.py | 285 | 4.40625 | 4 | #11. Faça uma função no Python que, utilizando a ferramenta turtle, desenhe um triângulo de lado N.
import turtle
def triangulo(n):
for target_list in range(3):
turtle.forward(int(n))
turtle.left(120)
x = input("Tamanho do triângulo - ")
triangulo(x) |
84e2b62c922b04f427741fd805c3705f657783ea | HenriqueSamii/TP1-Fundamentos-de-Programa-o-com-Python | /tp1IntroPiton5.py | 2,316 | 4.375 | 4 | #5. Trabalhar com tuplas é muito importante! Crie 4 funções nas quais:
#
# 1.Dada uma tupla e um elemento, verifique se o elemento existe na tupla
# e retorne o indice do mesmo
# 2.Dada uma tupla, retorne 2 tuplas onde cada uma representa uma metade da tupla original.
# 3.Dada uma tupla e um elemento, elimine esse elemento da tupla.
# 4.Dada uma tupla, retorne uma nova tupla com todos os elementos invertidos.
tupleO = ("1","3","Mega", "Odeth", "10","Deth")
def proucura_item(item):
global tupleO
if item in tupleO:
print(item + " esta na posição " + str(tupleO.index(item))+ " da tupla")
else:
print(item + " não existe na tupla")
def tuple_half():
half1 = []
half2 = []
for items in range(len(tupleO)//2):
half1.append(tupleO[items])
for items in range(len(tupleO)-len(tupleO)//2,len(tupleO)):
half2.append(tupleO[items])
half1 = tuple(half1)
half2 = tuple(half2)
print(str(half1)+" "+str(half2))
def delet_item(item):
global tupleO
if item in tupleO:
arrayHolder = []
#arrayHolder.append(tupleO)
for items in range(len(tupleO)):
arrayHolder.append(tupleO[items])
arrayHolder.remove(item)
tupleO = tuple(arrayHolder)
print("Tupla modificada para: " + str(arrayHolder))
else:
print(item + " não existe na tupla")
def invert_items():
global tupleO
arrayHolder = []
for items in range(len(tupleO)-1,-1,-1):
arrayHolder.append(tupleO[items])
arrayHolder = tuple(arrayHolder)
print(arrayHolder)
N = 6
while N != "5":
N = input("\nTulpa original: "+str(tupleO)+"\n1.Verificar se o elemento existe na tupla e retornar o indice.\n2.Retornar 2 tuplas com cada metade da tupla original.\n3.De um elemento para ser eliminado da esse tupla.\n4.Retornar uma tupla com todos os elementos invertidos.\n5.Terminar Programa\n")
if N=="1":
itemProucura = input("Elemento proucurado - ")
proucura_item(itemProucura)
elif N=="2":
tuple_half()
elif N=="3":
itemDelet = input("Elemento a deletar - ")
delet_item(itemDelet)
elif N=="4":
invert_items()
elif N=="5":
print("Adeus")
else:
print("Essa opção não existe")
|
8583ef2b7d2bb5ea062a32df0220426a4e9a51b1 | Valay/Learning-Java | /goldmine/goldmine.py | 8,103 | 3.515625 | 4 | #!/usr/bin/python
import sys
import argparse
import time
import random
parser = argparse.ArgumentParser(description='Get the test file')
parser.add_argument('--testfile', type=str, help="path to save the alignemnts to direcotry")
dr = ['l','d','u','r']
# Direction of movement
d = {
'l' : [0,-1],
'r' : [0, 1],
'd' : [1, 0],
'u' : [-1,0]
}
# This function evaluates my current proposal
def evaluate_objective_function_on_proposal(moves):
# Takes a proposal(list of moves) and evaluate it based on mine_map
cur = list(start)
pickaxe = 1
score = 0
try:
for x in moves:
if mine_map[d[x][0]+cur[0]][d[x][1]+cur[1]] == 10: # Hurray I found a new axe, double my gold from now onwards!
pickaxe *= 2
elif mine_map[d[x][0]+cur[0]][d[x][1]+cur[1]] == -1: # If it hits the wall this proposal is not valid
return -100
else:
# increase the score based on what I found by moving in certain direction!
score = score + mine_map[d[x][0]+cur[0]][d[x][1]+cur[1]] * pickaxe
#print score
cur[0] += d[x][0]
cur[1] += d[x][1]
except IndexError:
# If it goes out of index, this proposal is not valid simply return the
#print d[x][0]+cur[0], d[x][1]+cur[1]
return -100
return score
def validate(moves):
valid = set()
valid.add( tuple(start) )
cur = tuple(start)
for i in range(len(moves)):
if valid.add( (d[moves[i]][0]+cur[0], d[moves[i]][1]+cur[1]) ) == None:
return False
cur[0] += d[moves[i]][0]
cur[1] += d[moves[i]][1]
print True
return true
#def shuffleProposal(moves):
# random.shuffle(moves)
# return moves
def randomProposal(moves):
rows = len(mine_map)
cols = len(mine_map[1])
valid = set()
#print start
valid.add(tuple(start))
cur = tuple(start)
temp = cur
for i in range(len(moves)):
count = 0
while temp in valid:
count +=1
if count > 4:
return moves
k = random.randrange(4)
if d[dr[k]][0]+cur[0] < rows and d[dr[k]][0]+cur[0] >= 0 and d[dr[k]][1]+cur[1] < cols and d[dr[k]][1]+cur[1] >= 0:
temp = (d[dr[k]][0]+cur[0], d[dr[k]][1]+cur[1])
#print cur, temp
valid.add(temp)
moves[i] = dr[k]
cur = temp
#print valid
return moves
# def randomPairProposal(moves):
# length = len(moves)
# e1 = random.randrange(length)
# e2 = random.randrange(length)
# # swap these elements
# temp = moves[e1]
# moves[e1] = moves[e2]
# moves[e2] = temp
# return moves
# def randomLast2SwapProposal(moves):
# return moves
#
def randomLast2Proposal(moves):
valid = set()
valid.add(tuple(start))
for i in range(len(moves)-2):
valid.add( (d[moves[i]][0], d[moves[i]][1]) )
cur = [d[moves[i]][0], d[moves[i]][1]]
temp = tuple(cur)
for i in range(2):
while temp in valid:
k = random.randrange(4)
temp = (d[dr[k]][0]+cur[0], d[dr[k]][1]+cur[1])
valid.add(temp)
cur = temp
moves[-1*(i+1)] = dr[k]
return moves
#
def randomLast4Proposal(moves):
valid = set()
valid.add(tuple(start))
for i in range(len(moves)-4):
valid.add( (d[moves[i]][0], d[moves[i]][1]) )
cur = [d[moves[i]][0], d[moves[i]][1]]
temp = tuple(cur)
for i in range(4):
while temp in valid:
k = random.randrange(4)
temp = (d[dr[k]][0]+cur[0], d[dr[k]][1]+cur[1])
valid.add(temp)
cur = temp
moves[-1*(i+1)] = dr[k]
return moves
#
def randomLast8Proposal(moves):
if len(moves) <= 8:
return moves
valid = set()
valid.add(tuple(start))
for i in range(len(moves)-8):
valid.add( (d[moves[i]][0], d[moves[i]][1]) )
cur = [d[moves[i]][0], d[moves[i]][1]]
temp = tuple(cur)
for i in range(8):
while temp in valid:
k = random.randrange(4)
temp = (d[dr[k]][0]+cur[0], d[dr[k]][1]+cur[1])
valid.add(temp)
cur = temp
moves[-1*(i+1)] = dr[k]
return moves
#
def randomLastKProposal(moves):
k = random.randrange(len(moves))
valid = set()
valid.add(tuple(start))
for i in range(len(moves)-k):
valid.add( (d[moves[i]][0], d[moves[i]][1]) )
cur = [d[moves[i]][0], d[moves[i]][1]]
temp = tuple(cur)
for i in range(k):
while temp in valid:
k = random.randrange(4)
temp = (d[dr[k]][0]+cur[0], d[dr[k]][1]+cur[1])
valid.add(temp)
cur = temp
moves[-1*(i+1)] = dr[k]
return moves
def randomMixProposals(moves):
# import pdb
# pdb.set_trace()
k = random.randrange(len(proposals))
return proposals[k](moves)
def local_search(num_moves,init_moves, epsilon, time_delta):
# takes number of moves, initial moves, epsilon, and time in seconds
best_score_so_far = 0
best_moves_so_far = init_moves
#moves = list(best_moves_so_far)
start_time = time.time()
while (time.time() - start_time) < time_delta :
moves = list(best_moves_so_far)
# Get a random proposal from randomMixProposal function
moves = randomMixProposals(moves)
if not validate(moves):
continue
#print moves
# Evaluate the given proposal and calculate the score
score = evaluate_objective_function_on_proposal(moves)
#print score
if( score - best_score_so_far >= epsilon):
best_score_so_far = score
best_moves_so_far = list(moves)
print score
print best_moves_so_far
return (best_score_so_far, best_moves_so_far)
# The list of proposal functions used!
proposals = [
# shuffleProposal,
randomProposal,
# randomPairProposal,
# randomLast2SwapProposal,
# randomLast2Proposal,
# randomLast4Proposal,
# randomLastKProposal,
# randomLast8Proposal
]
# Start from here!
if __name__ == '__main__':
# Parse the arguments to get the test file
args = parser.parse_args()
# Open the test file
f = open(args.testfile,'r')
# get the size of matrix and the number of moves
line = f.readline()
line.strip()
# parse the line
words = line.lstrip('=').split(',')
# Create the mine map
global mine_map
mine_map = [[0]*int(words[0]) for i in range(int(words[1]))]
num_moves = int(words[2])
global start
start = []
#global moves = [0]*num_moves
# Fill up the mine map
for i in range(int(words[0])):
line = f.readline().strip()
j=0
for char in line:
if char == 'd':
mine_map[i][j] = 10
elif char == '.':
mine_map[i][j] = 0
elif char == 'w':
mine_map[i][j] = -1
elif char =='s':
mine_map[i][j] = 0
start.append(i)
start.append(j)
else:
mine_map[i][j] = int(char)
j += 1
# okay map is now generated
# Test the mine_map and evaluation function
for l in mine_map:
print l
#moves = ['r','d','d','d','d','l','u','l']
#print num_moves
#print moves
#print evaluate_objective_function_on_proposal(moves)
f.close()
# Gold Mine runner
initial_moves = []
for i in range(num_moves):
initial_moves.append( dr[random.randrange(4)] )
#initial_moves = ['l','r']
epsilon = -1
time_frame = 20
answer = local_search(num_moves, initial_moves, epsilon, time_frame)
print answer[0]
print answer[1]
|
fa7d390f1021e66a2ec287ea0fb15568f2ab4361 | durbonca/python-basic-exercises | /ejercicios python basicos/2.py | 116 | 3.5625 | 4 | base = float(input('base: '))
altura = float(input('altura: '))
print('area de cuadrado: {}' .format (base*altura)) |
2a251fb6764b5d54e052d754a0931951e0c590a7 | AWOLASAP/compSciPrinciples | /python files/pcc EX.py | 343 | 4.28125 | 4 | '''
This program was written by Griffin Walraven
It prints some text to the user.
'''
#Print text to the user
print("Hello!! My name is Griffin Walraven.")
#input statement to read name from the user
name = input("What is yours? ")
print("Hello ", name, "!! I am a student at Hilhi.")
print("I am in 10th grade and I love Oregon!")
print("Hello World!!!")
|
6f13837ea35bbec037f9bc7144f7ff634268ba44 | AWOLASAP/compSciPrinciples | /python files/assingment7.py | 215 | 3.96875 | 4 | def convert_to_dec(b):
value, total = 1, 0
for i in reversed(str(b)):
if i == '1':
total += value
value *= 2
return total
binary = input("Give me an 8-bit binary number: ")
print(convert_to_dec(binary))
|
3bc172ed239a7420049479378bc660dab7ce772e | ambikeshkumarsingh/LPTHW_ambikesh | /ex3.py | 477 | 4.25 | 4 | print("I will count my chickens:" )
print("Hens", 25 +30/6)
print("Roosters",100-25*3 %4)
print("Now I will count the eggs")
print(3 + 2 + 1- 5 + 4 % 2-1 /4 + 6)
print("Is is true that 3+2<5-7")
print(3+2<5-7)
print("What is 3+2 ? ", 3+2)
print("What is 5-7 ?", 5-7)
print("Oh! that's why It is false")
print("How about some more")
print ("Is it greater?", 5> -2)
print("Is it greater or equal ?" , 5>= -2)
print("Is it less or equal?", 5<= -2)
|
78bf22ce561d77a45d54a4e144da53c37f84e6e7 | AbeJLazaro/MetodosNumericos | /RK2y4.py | 7,939 | 3.75 | 4 | import matplotlib.pyplot as plt
class RK2:
Zderivada='24*x**2'
Yderivada='z'
#valores que se inician al crear un objeto nuevo
x=[]
y=[]
z=[]
F=[]
h=0.3
#valores dinamicos, estos son auxiliares para encontrar a y
x=0
k1=[]
k2=[]
#k3=[]
#k4=[]
#valores para graficar
valoresy=[]
valoresx=[]
def __init__(self):
#se agrega en el vector(lista) y los valores iniciales tomando en cuenta que
#la primer posición es la variable x y la segunda es la variable y
self.x=[0]
self.y=[0]
self.z=[-3]
#se define el vector F que es la función de cada una de las derivadas
#de las variables arriba descritas, se ponen en vorma de cadena para
#operarlas mediante el comando eval, haciendo dinamico este problema
#podiendo agregar cualquier tipo de ecuacion
self.F=['z','24*(x**2)']
#se agregan los valores iniciales en la lista de tiempos y de valores
#en equis para su posteriror ploteo
#self.graf.append(self.x)
#self.grafx.append(self.y[0])
#self.grafxanalitica.append(self.y[0])**********************************************
def Fcalcula(self,x,y,z):
resultado=[]
for f in self.F:
resultado.append(eval(f))
#se regresa una lista de resultados de evaluar F(t,Y)
return resultado
def kUno(self):
k1=[]
x=self.x[len(self.x)-1]
y=self.y[len(self.y)-1]
z=self.z[len(self.z)-1]
Fevaluada=self.Fcalcula(x,y,z)
for f in Fevaluada:
k1.append(f*self.h)
self.k1=k1
def kDos(self):
k2=[]
x=self.x[len(self.x)-1]+self.h
y=self.y[len(self.y)-1]+self.k1[0]
z=self.z[len(self.z)-1]+self.k1[1]
Fevaluada=self.Fcalcula(x,y,z)
for f in Fevaluada:
k2.append(f*self.h)
self.k2=k2
def NuevaY(self):
self.y.append(self.y[len(self.y)-1]+((1/2)*(self.k1[0]+self.k2[0])))
self.z.append(self.z[len(self.z)-1]+((1/2)*(self.k1[1]+self.k2[1])))
#self.xA=math.cos(self.t)+math.sin(self.t)
#se define la funcion itera para poder ocupar hacer uso de las funciones anteriores.
#Las funciones anteriores no necesitan parametros mas que Fcalcula, esto es a lo que
#pretendia llegar al usar el paradigma oriendato a objetos para no estar batallando
#con saber que valores pasar a las funciones en una funcion global main como
#la que se ve a continucacion.
#Se define una nueva t, se generan las K's y posterior se genera la nueva y
#al final estos valores se agregan a las listas para su ploteo
def itera(self):
self.kUno()
self.kDos()
self.NuevaY()
self.x.append(round(self.x[len(self.x)-1]+self.h,1))
class RK4:
Zderivada='24*x**2'
Yderivada='z'
#valores que se inician al crear un objeto nuevo
x=[]
y=[]
z=[]
F=[]
h=0.3
#valores dinamicos, estos son auxiliares para encontrar a y
x=0
k1=[]
k2=[]
#k3=[]
#k4=[]
#valores para graficar
valoresy=[]
valoresx=[]
def __init__(self):
#se agrega en el vector(lista) y los valores iniciales tomando en cuenta que
#la primer posición es la variable x y la segunda es la variable y
self.x=[0]
self.y=[0]
self.z=[-3]
#se define el vector F que es la función de cada una de las derivadas
#de las variables arriba descritas, se ponen en vorma de cadena para
#operarlas mediante el comando eval, haciendo dinamico este problema
#podiendo agregar cualquier tipo de ecuacion
self.F=['z','24*(x**2)']
#se agregan los valores iniciales en la lista de tiempos y de valores
#en equis para su posteriror ploteo
#self.graf.append(self.x)
#self.grafx.append(self.y[0])
#self.grafxanalitica.append(self.y[0])**********************************************
def Fcalcula(self,x,y,z):
resultado=[]
for f in self.F:
resultado.append(eval(f))
#se regresa una lista de resultados de evaluar F(t,Y)
return resultado
def kUno(self):
k1=[]
x=self.x[len(self.x)-1]
y=self.y[len(self.y)-1]
z=self.z[len(self.z)-1]
Fevaluada=self.Fcalcula(x,y,z)
for f in Fevaluada:
k1.append(f*self.h)
self.k1=k1
def kDos(self):
k2=[]
x=self.x[len(self.x)-1]+self.h/2
y=self.y[len(self.y)-1]+self.k1[0]/2
z=self.z[len(self.z)-1]+self.k1[1]/2
Fevaluada=self.Fcalcula(x,y,z)
for f in Fevaluada:
k2.append(f*self.h)
self.k2=k2
def kTres(self):
k3=[]
x=self.x[len(self.x)-1]+self.h/2
y=self.y[len(self.y)-1]+self.k2[0]/2
z=self.z[len(self.z)-1]+self.k2[1]/2
Fevaluada=self.Fcalcula(x,y,z)
for f in Fevaluada:
k3.append(f*self.h)
self.k3=k3
def kCuatro(self):
k4=[]
x=self.x[len(self.x)-1]+self.h
y=self.y[len(self.y)-1]+self.k3[0]
z=self.z[len(self.z)-1]+self.k3[1]
Fevaluada=self.Fcalcula(x,y,z)
for f in Fevaluada:
k4.append(f*self.h)
self.k4=k4
def NuevaY(self):
self.y.append(self.y[len(self.y)-1]+(1/6)*(self.k1[0]+2*self.k2[0]+2*self.k3[0]+self.k4[0]))
self.z.append(self.z[len(self.z)-1]+(1/6)*(self.k1[1]+2*self.k2[1]+2*self.k3[1]+self.k4[1]))
#self.xA=math.cos(self.t)+math.sin(self.t)
#se define la funcion itera para poder ocupar hacer uso de las funciones anteriores.
#Las funciones anteriores no necesitan parametros mas que Fcalcula, esto es a lo que
#pretendia llegar al usar el paradigma oriendato a objetos para no estar batallando
#con saber que valores pasar a las funciones en una funcion global main como
#la que se ve a continucacion.
#Se define una nueva t, se generan las K's y posterior se genera la nueva y
#al final estos valores se agregan a las listas para su ploteo
def itera(self):
self.kUno()
self.kDos()
self.kTres()
self.kCuatro()
self.NuevaY()
self.x.append(round(self.x[len(self.x)-1]+self.h,1))
def ecuacionReal(valores):
lista=[]
for x in (valores):
lista.append(eval('2*x**4-3*x'))
return lista
rk2=RK2()
rk4=RK4()
for i in range(10):
rk2.itera()
rk4.itera()
lista=ecuacionReal(rk2.x)
#texto='+-------------------------------------------------------------------------+\n'
#texto+='{0}{1:>7}{0}{2:>21}{0}{3:>21}{0}{4:>21} \n'.format('|','Tiempo','Solucion RK2','Solucion RK4','solucion real')
#texto+='+-------------------------------------------------------------------------+\n'
#for i in range(10):
# texto+='{0}{1:>7}{0}{2:>21}{0}{3:>21}{0}{4:>21} \n'.format('|',rk2.x[i],rk2.y[i],rk4.y[i],lista[i])
#print(texto)
texto='+-------------------------------------------------------------------------+\n'
texto+='|Tiempo | Solucion RK2 |Solución RK4 |Solcuion Real'
texto+='+-------------------------------------------------------------------------+\n'
for i in range(10):
texto+='|'+str(rk2.x[i])+'|'+str(rk2.y[i])+'|'+str(rk4.y[i])+'|'+str(lista[i])+'\n'
print(texto)
fig = plt.figure(figsize=(10,6))
plt.title("Grafica comparativa")
plt.xlabel("Tiempo T")
plt.ylabel("Posicion en X")
plt.grid()
plt.plot(rk2.x,rk2.y,'r*-',label="solucion con RK2")
plt.plot(rk4.x,rk4.y,'bo-',label="solucion con RK4")
plt.plot(rk4.x,lista,'go-',label="solucion real")
plt.legend(loc="upper left")
plt.show()
#plt.savefig("picturename.png")
|
4648766292cce07ebc5dffcb9b3ff5758e2d7faa | AbeJLazaro/MetodosNumericos | /newtonCriterioParo.py | 4,339 | 3.765625 | 4 | # Autores: Mercedes Miranda
# El nombre de tu amigo
# Fecha; 9 de septiembre de 2019
# Metodo Newton Raphson
import sympy as sym
#se define el simbolo variable principal, no mover
x = sym.Symbol('x')
#se define la funcipon para desarrollar el metodo
#funcion es la función en terminos de sympy, trataré de agregar un apendice
#de funciones posibles que se pueden agregar
#x0 es el valor semilla, tomar las consideraciones necesarias para ello
#errorRelativo es el criterio de paro dado por el usuario
#es importante tener en cuenta que las iteraciones seran pocas debido a la
#eficacia del metodo
def newton(funcion,x0,errorRelativo,digitos):
#se calcula la derivada y la division de f(x)/f'(x)
derivada = funcion.diff(x,1)
diferencia=funcion/derivada
#se muestra la division
print("h(x) = f(x)/f'(x)")
print("h(x) = ",diferencia)
#variable auxiliar para las iteraciones
iteracion=0
banderaConvergencia=0
#listas para guardar la información
valoresAproximados=[x0]
valoresErrorRelativo=['-']
criterioDeConvergencia=[round(CriterioConvergencia(funcion,x0),digitos)]
while(True):
#se calcula la aproximacion
xAnterior=x0
a=diferencia.subs(x,x0)
a=x0-a.evalf()
x0=round(a,digitos)
valoresAproximados.append(x0)
#si estamos en una iteracion diferente a la primera, se calcula el
#error relativo
if(iteracion!=0):
errorR=round((abs((x0-xAnterior)/x0))*100,digitos)
valoresErrorRelativo.append(errorR)
#si se cumple el criterio de paro, sale de las iteraciones
if(errorR<errorRelativo):
break
#se calcula el valor de convergencia
valorG=round(CriterioConvergencia(funcion,x0),digitos)
criterioDeConvergencia.append(valorG)
#se checa si el valor cumple o no lo especificado
if abs(valorG)>1:
banderaConvergencia=1
break
#se incrementa en 1 el contador de iteraciones
iteracion+=1
#se retornan todas las listas y el valor de la bandera
return valoresAproximados,valoresErrorRelativo,criterioDeConvergencia,banderaConvergencia
#esta función evalua para el criterio de convergencia en cada aproximación generada y regresa
#el valor de la evaluación de |G'(x)|
def CriterioConvergencia(funcion,x0):
#se calculan las dos derivadas
derivada = funcion.diff(x,1)
derivadaDos = funcion.diff(x,2)
#se genera a la función G'(x)
G=(funcion*derivadaDos)/(derivada**2)
#se evalua para la raiz encontrada
a=G.subs(x,x0)
a=a.evalf()
return a
#solo genera la grafica de la funcion
def Grafica(funcion):
grafica=sym.plotting.plot(funcion,show=True)
#función maestra
def main():
#la función se muestra aquí
funcion=sym.cos(x)-(x**2)
#si quieres que el usuario ingrese la función, descomenta las lineas entre
#signos de suma y comenta la linea de arriba de "funcion"
#recuerda usar la documentación para saber como ingresar ciertas funciones
#++++++++++++++++++++++++++
#funcion=input("ingresa la función en terminos de x")
#++++++++++++++++++++++++++
#grafica
Grafica(funcion)
#criterio de paro
errorRelativo=float(input("introduce el porcentaje de error para el criterio de paro "))
#valor semilla
semilla=float(input("ingresa el valor semilla "))
#cantidad de digitos al redondear
digitos=int(input("cantidad de digitos de redondeo, hasta 8 permitidos "))
#se generan todos los valores necesarios para desplegar la tabla
valores,errores,criterios,bandera=newton(funcion,semilla,errorRelativo,digitos)
#se imprimen los valores
print("{:2}|{:^12}|{:^12}|{:^12}|{:^12}".format("I","xi","xi+1","ErrorR","CritConv"))
for i in range(len(valores)-1):
print("{:2}|{:12}|{:12}|{:12}|{:12}".format(i+1,valores[i],valores[i+1],errores[i],criterios[i]))
#hasta acá es donde se checa el criterio de convergencia
if bandera==1 :
print("hubo un problema con el criterio de paro en la ultima iteración, quizá por esto terminó el proceso")
print("revisa tu valor semilla e intenta con otro ")
main()
|
cffc2440c9d7945fe89f9cc7d180ee484f0a7689 | bartoszkobylinski/tests | /tests/tests.py | 1,544 | 4.3125 | 4 | import typing
import unittest
from app import StringCalculator
'''
class StringCalculator:
def add(self, user_input: str) -> int:
if user_input is None or user_input.strip() == '':
return 0
else:
numbers = user_input.split(',')
result = 0
for number in numbers:
if number.isdigit:
result += int(number)
else:
raise ValueError
print(f"ValueError:Your input is not a digit. You have to give a digits to add them.")
return result
'''
class TestStringCalculator(unittest.TestCase):
calculator = StringCalculator()
def test_adding_one_number(self):
self.assertEqual(self.calculator.add("2"), 2)
def test_when_whitespace__is_given(self):
self.assertEqual(self.calculator.add(' '), 0)
def test_when_none_is_given(self):
self.assertEqual(self.calculator.add(None), 0)
def test_when_two_number_are_given(self):
self.assertEqual(self.calculator.add("2,5"), 7)
def test_when_input_is_not_digit(self):
with self.assertRaises(ValueError):
self.assertRaises(self.calculator.add("Somestring, not a digit"), 3)
def test_when_digit_is_less_then_zero(self):
self.assertEqual(self.calculator.add("-5,8"), 3)
def test_when_two_digit_are_less_then_zero(self):
self.assertEqual(self.calculator.add("-5,-8"), -13)
if __name__ == "__main__":
unittest.main() |
27e3f72da48f727adedef391c7011bd0ffd82f67 | minrat/AI | /stage1/tkinter/Cal_GUI_demo.py | 1,451 | 3.65625 | 4 | from tkinter import *
class GUICal:
def __init__(self):
self.root = Tk()
self.root.title("计算器")
fm1 = Frame(self.root)
Entry(fm1).grid(row=0, column=0, columnspan = 4)
Entry(fm1).grid(row=1, column=0, columnspan=4)
fm1.pack(side = TOP, expand = YES)
fm2 = Frame(self.root)
Button(fm2, text = "C",width=5).grid(row=1, column = 0, columnspan = 2)
Button(fm2, text = "%").grid(row = 1, column = 2)
Button(fm2, text = "/").grid(row = 1, column = 3)
Button(fm2, text = "7").grid(row = 2, column = 0)
Button(fm2, text="8").grid(row=2, column=1)
Button(fm2, text="9").grid(row=2, column=2)
Button(fm2, text="X").grid(row=2, column=3)
Button(fm2, text="4").grid(row=3, column=0)
Button(fm2, text="5").grid(row=3, column=1)
Button(fm2, text="6").grid(row=3, column=2)
Button(fm2, text="-").grid(row=3, column=3)
Button(fm2, text="1").grid(row=4, column=0)
Button(fm2, text="2").grid(row=4, column=1)
Button(fm2, text="3").grid(row=4, column=2)
Button(fm2, text="+").grid(row=4, column=3)
Button(fm2, text="0", width=5).grid(row=5, column=0, columnspan = 2)
Button(fm2, text=".").grid(row=5, column=2)
Button(fm2, text="=").grid(row=5, column=3)
fm2.pack(side=BOTTOM)
self.root.mainloop()
if __name__ == '__main__':
c = GUICal()
|
66a7e79ba8462ebcfb8cb2c2a4159b475736e56d | slamatik/codewars | /5 kyu/Double Cola 5 kyu.py | 644 | 3.75 | 4 | data = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"]
def who_is_next(names, r):
if r <= 5:
return names[r - 1]
start = 1
letter_count = 1
while start < r:
start += len(names) * letter_count
letter_count *= 2
letter_count //= 2
cnt = len(names)
if start == r:
return names[0]
while True:
start -= letter_count
cnt -= 1
if start == r:
return names[cnt]
elif start > r:
continue
else:
return names[cnt]
print(who_is_next(data, 1))
print(who_is_next(data, 52))
print(who_is_next(data, 7230702951))
|
e3359660fa9fd421ca4d1340872afd89fd4f8bf2 | slamatik/codewars | /5 kyu/Vecotr Class 2 5 kyu.py | 1,330 | 3.546875 | 4 | class Vector:
def __init__(self, *args):
if len(args) == 1:
self.x = args[0][0]
self.y = args[0][1]
self.z = args[0][2]
self.magnitude = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
else:
self.x = args[0]
self.y = args[1]
self.z = args[2]
self.magnitude = (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
def cross(self, other):
cx = self.y * other.z - self.z * other.y
cy = self.z * other.x - self.x * other.z
cz = self.x * other.y - self.y * other.x
return Vector(cx, cy, cz)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def to_tuple(self):
return self.x, self.y, self.z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __eq__(self, other):
return all((self.x == other.x, self.y == other.y, self.z == other.z))
def __str__(self):
return f"<{self.x}, {self.y}, {self.z}>"
examples = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
v = Vector(examples[0])
# v2 = Vector(*examples[0])
v2 = Vector(examples[0])
print(v == v2)
|
350983b69426ad8ec696f51dd9ca04f0387afdd0 | slamatik/codewars | /4 kyu/Sudoku Solution Validator 4 kyu.py | 874 | 3.5 | 4 | def valid_solution(board):
for i in board:
if len(set(i)) != len(i):
return False
for x in range(9):
temp = []
for y in range(9):
temp.append(board[y][x])
if len(set(temp)) != len(temp):
return False
for i in range(9):
row = 3 * (i // 3)
col = 3 * (i % 3)
cube = []
for j in range(9):
y = row + j // 3
x = col + j % 3
cube.append(board[y][x])
if len(set(cube)) != len(cube):
return False
return True
print(valid_solution(
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9, 1], [3, 4, 5, 6, 7, 8, 9, 1, 2], [4, 5, 6, 7, 8, 9, 1, 2, 3],
[5, 6, 7, 8, 9, 1, 2, 3, 4], [6, 7, 8, 9, 1, 2, 3, 4, 5], [7, 8, 9, 1, 2, 3, 4, 5, 6], [8, 9, 1, 2, 3, 4, 5, 6, 7],
[9, 1, 2, 3, 4, 5, 6, 7, 8]]))
|
d86b9bf29c50110b1d882a681ac4e130880fa70a | slamatik/codewars | /6 kyu/Pyramid Array.py | 107 | 3.53125 | 4 | def pyramid(n):
sol = [[1 for n in range(m + 1)] for m in range(n)]
return sol
print(pyramid(3))
|
4d736b85b8483afdc011e62aafca69dbbcc683f3 | slamatik/codewars | /5 kyu/Maximum subarray sum 5 kyu.py | 314 | 3.78125 | 4 | def max_sequence(arr):
if not arr:
return 0
if all(i < 0 for i in arr):
return 0
table = [arr[0]]
for i in range(1, len(arr)):
table.append(max(table[-1] + arr[i], arr[i]))
return max(table)
print(max_sequence([]))
print(max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
|
95822ffd1d75b64b794edc2ea215a5c964b8d85e | slamatik/codewars | /5 kyu/Pete, the baker 5 kyu.py | 293 | 3.671875 | 4 | recipe = {"flour": 500, "sugar": 200, "eggs": 1}
available = {"flour": 1200, "sugar": 1200, "eggs": 5, "milk": 200}
def cakes(recipe, available):
try:
return min([available[i] // recipe[i] for i in recipe])
except KeyError:
return 0
print(cakes(recipe, available))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.