blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
607863663fa8320ee701abf3a1f3c1370575d1b4 | Sakura-lyq/test | /python函数.py | 1,507 | 3.828125 | 4 | help(abs)
abs(-33)
max(12,77,34,56,33)
print(int(13.33))
print(float(13.33))
print(str(13.33))
print(bool(13.33))
print(bool(0))
print(hex(33))
from absert import my_abs
print(my_abs(-4))
def my_abs(x):
if not isinstance(x,(float,int)):
raise TypeError('bad operand type')
if x>=0 :
return x
else:
return -x
print(my_abs(88))
import math
def move(x,y,step,angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx,ny
x,y = move(100, 100, 60, math.pi/6)
print(x,y)
import math
def quadratic(a,b,c):
Z=b**2-4*a*c
if Z==0:
x=-c/b
return x
elif Z>=0:
x1=(-b+math.sqrt(b**2-4*a*c))/2/a
x2=(-b-math.sqrt(b**2-4*a*c))/2/a
return x1,x2
else:
print("此方程无解")
print(quadratic(2,3,1))
##函数的参数
def students(age,name,height,weight):
print('age:',age)
print('name:',name)
print('height:',height)
print('weight:',weight)
students(11,'lisa',160,50)
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
calc(1,2,3)
def person(name, age, *args, city, job):
print(name, age, args, city, job)
person('lin',16,33,25,16,city='Nanjing',job='Teacher')
##递归函数
def fact(n):
return fact_iter(n,1)
def fact_iter(num,product):
if num==1:
return product
return fact_iter(num-1,num*product)
fact(4)
fact(100) |
f4dc8b28b04602efeeec0a20b509eb6635ea93a5 | MakingL/huaweiCodeCraft2019 | /CodeCraft-2019/src/Dijkstra/Dijkstra.py | 2,699 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/3/26 9:47
# @Author : MLee
# @File : Dijkstra.py
import heapq
# import logging
from collections import deque
class PriorityQueue:
def __init__(self):
self.elements = []
def empty(self):
return len(self.elements) == 0
def put(self, item, priority):
heapq.heappush(self.elements, (priority, item))
def get(self):
return heapq.heappop(self.elements)[1]
def clear(self):
return self.elements.clear()
def size(self):
return len(self.elements)
class Dijkstra(object):
"""docstring for Dijkstra"""
def __init__(self, graph):
super(Dijkstra, self).__init__()
self.graph = graph
def get_neighbors(self, current):
return self.graph.get_neighbors(current)
def dijkstra_search(self, start, goal):
# logging.info("start dijkstra search: from {} to {}".format(start, goal))
frontier = PriorityQueue()
frontier.clear()
frontier.put(start, 0)
# logging.info("priority queue element type: {} length: {}".format(type(start), frontier.size()))
came_from = {}
cost_so_far = dict()
came_from[start] = None
cost_so_far[start] = 0
while not frontier.empty():
current = frontier.get()
# logging.info("current node : {}".format(current))
if current == goal:
break
for edge_id, edge in self.get_neighbors(current).items():
next_node_id = edge.end_id
# logging.info("next node id: {} edge id: {}".format(next_node_id, edge.road_id))
new_cost = cost_so_far[current] + self.cost(edge)
if next_node_id not in cost_so_far or new_cost < cost_so_far[next_node_id]:
cost_so_far[next_node_id] = new_cost
priority = new_cost
frontier.put(next_node_id, priority)
came_from[next_node_id] = current
return self.reconstruct_path(came_from, goal), cost_so_far[goal]
def cost(self, edge):
return edge.weight
def reconstruct_path(self, came_from, goal):
"""
重新建立路径完整信息
:param came_from: 节点的父节点集合
:param goal: 目标节点
:return: 包含源节点 ID 到目标节点 ID 的路径
"""
path = deque()
path.clear()
node = goal
path.appendleft(node)
while node in came_from:
node = came_from[node]
if node is None:
continue
path.appendleft(node)
return path
|
79fa76fa59f81ea9f7b12f0aea7f3dd7d14ab1db | mough/Python-Challenge | /Check io/Checkio.py | 2,894 | 3.5625 | 4 |
def checkio(n):
possibles = []
factors = [[i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0]
print("factors", factors)
for item in factors:
possibles.append(''.join([str(i) for i in item]))
smallest = int(possibles[0])
for item in possibles:
if int(item) < smallest:
smallest = int(item)
print(possibles)
if str(n) in str(smallest):
print(0)
else:
print(smallest)
checkio(125)
# if __name__ == '__main__':
# #These "asserts" using only for self-checking and not necessary for auto-testing
# assert checkio(20) == 45, "1st example"
# assert checkio(21) == 37, "2nd example"
# assert checkio(17) == 0, "3rd example"
# assert checkio(33) == 0, "4th example"
# assert checkio(3125) == 55555, "5th example"
# assert checkio(9973) == 0, "6th example"
# def find_path(graph, start, end, path=[]):
# possibles = dict()
# for i in graph.split(','):
# possibles.setdefault(i[0], []).append(i[1])
# possibles.setdefault(i[1], []).append(i[0])
# print(possibles)
#
# path = path + [start]
# if start == end:
# return path
# if start not in possibles:
# return None
# for vertex in possibles[start]:
# if vertex not in path:
# extended_path = find_path(vertex, end, path)
# if extended_path:
# return extended_path
# return None
#
#
# print(find_path("12,23,34,45,56,67,78,81", 1, 7))
#This part is using only for self-testing
# if __name__ == "__main__":
# def check_solution(func, teleports_str):
# route = func(teleports_str)
# teleports_map = [tuple(sorted([int(x), int(y)])) for x, y in teleports_str.split(",")]
# if route[0] != '1' or route[-1] != '1':
# print("The path must start and end at 1")
# return False
# ch_route = route[0]
# for i in range(len(route) - 1):
# teleport = tuple(sorted([int(route[i]), int(route[i + 1])]))
# if not teleport in teleports_map:
# print("No way from {0} to {1}".format(route[i], route[i + 1]))
# return False
# teleports_map.remove(teleport)
# ch_route += route[i + 1]
# for s in range(1, 9):
# if not str(s) in ch_route:
# print("You forgot about {0}".format(s))
# return False
# return True
#
# assert check_solution(checkio, "12,23,34,45,56,67,78,81"), "First"
# assert check_solution(checkio, "12,28,87,71,13,14,34,35,45,46,63,65"), "Second"
# assert check_solution(checkio, "12,15,16,23,24,28,83,85,86,87,71,74,56"), "Third"
# assert check_solution(checkio, "13,14,23,25,34,35,47,56,58,76,68"), "Fourth"
|
d9e8bfbbf6a53ba9a224c5d7889bc3eff43b4d64 | markliu2013/machine-learning | /toturial_projects/mock/knn_base.py | 1,040 | 3.5625 | 4 | import numpy as np
from utils import distance
'''
https://github.com/SmallVagetable/machine_learning_python/blob/master/knn/knn_base.py
https://github.com/Dod-o/Statistical-Learning-Method_Code/blob/master/KNN/KNN.py
'''
class KNN(object):
def __init__(self, k=20, p=2):
self.k = k
self.p = p
def fit(self, X, y):
self.X = X
self.y = y
def predict(self, X):
return np.fromiter(map(self._predict_x, X), dtype=np.int)
def _predict_x(self, x):
train_length = len(self.X)
## i个样本的距离
distList = [0] * train_length
# 遍历训练集中所有的样本点,计算与x的距离
for i in range(train_length):
distList[i] = distance(self.X[i], x, self.p)
# 对距离列表进行排序
topKList = np.argsort(np.array(distList))[:self.k]
labelList = [0] * len(np.unique(self.y))
for index in topKList:
labelList[int(self.y[index])] += 1
return labelList.index(max(labelList)) |
ccc0a511f5ae0ec0ec660d5ea293b97b28ada6e1 | das-jishu/data-structures-basics-leetcode | /Trees/implement-with-OOP.py | 867 | 3.65625 | 4 |
class BinaryTree(object):
def __init__(self, value):
self.key = value
self.leftChild = None
self.rightChild = None
def insertLeft(self, newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self, newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootVal(self, val):
self.key = val
def getRootVal(self):
return self.key
|
45691c5bebb73d1e6cb5eb917fa00bfe090b383c | gondimribeiro/leetcode | /python/KLengthApart.py | 674 | 3.734375 | 4 | '''
Given an array nums of 0s and 1s and an integer k, return True if all
1's are at least k places away from each other, otherwise return False.
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/
'''
from typing import List
class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
if 1 not in nums or k == 0:
return True
n = len(nums)
dist = k
for i in range(n):
if nums[i]:
if dist < k:
return False
dist = 0
else:
dist += 1
return True
|
daa4268d63fcae04d91bf6a318947465a09cbba0 | tshuaking/Bioinformatic-stuff | /Finding positions of of strand and complement strand.py | 1,069 | 3.8125 | 4 | filename=input("filename?")
Genome=open(filename).readline().rstrip()
Pattern=input("Pattern?")
def patternfinder(Pattern,Genome):
revpat=Pattern[::-1] #reversing the pattern for easier analysis
revcomp="" #variable with empty space to store values later
jump=len(Pattern) #the length of the pattern
lstn=list()
for num in range(len(Pattern)): #revpat and Pattern are the same length
if revpat[num]=="A":revcomp+"T" #checking the reverse pattern to replace it with complement base
elif revpat[num] == "T": revcomp + "A"
elif revpat[num] == "C": revcomp + "G"
elif revpat[num] == "G": revcomp + "C"
for number in range(len(Genome)):
if Genome[number:number+jump]== Pattern:lstn.append(number)
#number is the starting position and "number+jump" is the boundary of the pattern to check
if Genome[number:number+jump]== revcomp:lstnappend(number)
print(" ".join(str(x) for x in lstn)) #convert integers to str to be able to use .join()
patternfinder(Pattern,Genome) |
646918df28e634bd836a8c0439d3b2491f7eadf1 | Programacion-Algoritmos-18-2/ejercicios-clases-6-1-CeliaMaca | /busquedaLineal/modelado/modelo.py | 1,635 | 4.0625 | 4 | # Se crea la clase Equipo
class Equipo(object):
def __init__(self, nombre, ciudad, campeonatos, numJugadores):
self.nombre = nombre
self.ciudad = ciudad
self.campeonatos = int(campeonatos)
self.numJugadores = numJugadores
#Metodos set y get
def agregarNombre(self, nombre):
self.nombre = nombre
def obtenerNombre(self):
return self.nombre
def agregarCiudad(self, ciudad):
self.ciudad = ciudad
def obtenerCiudad(self):
return self.ciudad
def agregarCampeonatos(self, campeonatos):
self.campeonatos = int(campeonatos)
def obtenerCampeonatos(self):
return self.campeonatos
def agregarNumJugadores(self, numJugadores):
self.numJugadores = numJugadores
def obtenerNumJugadores(self):
return self.numJugadores
# Método para imprimir
def __str__(self):
return "%s - %s - %d - %f" % (self.nombre, self.ciudad, self.campeonatos, self.numJugadores)
class OperacionesEquipo(object):
def __init__(self, listado):
self.listadoEquipos = listado
# Ordenar los objetos por nombres
def ordenarPorNombre(self):
nombre = ""
for n in self.listadoEquipos:
nombre = nombre + n.obtenerNombre() + ", "
return nombre
# Ordenar los objetos por campeonatos
def ordenarCampeonatos(self):
numero = 0
nombre = []
for n in self.listadoEquipos:
numero = n.obtenerCampeonatos()
nombre.append(numero)
nombre.sort()
return nombre
def __str__(self):
cadena = ""
for n in self.listadoEquipos:
cadena = "%d" %(self.ordenarPorNombre())
cadena = "%d" %(self.ordenarCampeonatos())
return cadena |
91222e6ffb8f5926a142838bc9ee738ce9dbe85d | tatarinova0903/PythonLabs1 | /Экзамен/sortirovka.py | 1,779 | 3.515625 | 4 |
count = 0
# Перепишем все в файл-помощник
with open('file.txt') as file1:
with open('help.txt', 'w') as file2:
for line in file1:
count += 1
file2.write(line)
for i in range(count):
# Запоминаем текущее значение (первый элемент в неотсортированной части)
file = open('help.txt')
for j in range(i):
file.readline()
current = file.readline()
file.close()
# Пусть пока что минимум - это первое значение в неотсортированной части
min = current
minind = i
# Поиск минимума
file = open('help.txt')
for j in range(i+1):
file.readline()
for j in range(i+1, count):
line = file.readline()
if int(line) < int(min):
min = line
if line[len(line) - 1] != '\n':
min += '\n'
file.close()
# Меняем местами минимум и первый элемент неотсортированной части
with open('file.txt', 'w') as file1:
with open('help.txt', 'r') as file2:
for j in range(count):
line = file2.readline()
if line[len(line) - 1] != '\n':
line += '\n'
if line == current:
file1.write(min)
elif line == min:
file1.write(current)
else:
file1.write(line)
# Обновляем файл-помощник
with open('file.txt') as file1:
with open('help.txt', 'w') as file2:
for line in file1:
file2.write(line) |
ea61f6b4d64b8a3c025f07fd39564d044cbe6ea2 | AntonioGallego/mastermind-python | /mazmorra.py | 3,654 | 4.09375 | 4 | # Programado por Antonio Gallego. Producciones Tetric Games con motor Surreal
import random
nombre = input("¿Cómo te llamas, piratilla? > ")
print("""
, \ / ,
/ \ )\__/( / \
/ \ (_\ /_) / \
____/_____\__\@ @/___/_____\____
| |\../| |
| \VV/ |""")
# Esta chorrada es lo que más me ha costado
titulo = nombre + "'s Game"
p=int((34-len(titulo))/2) # padding
if len(titulo)%2==1:
q = p
else:
q = p-1
print("|"+" "*p+titulo+" "*q+"|")
print("""|_________________________________|
| /\ / \\\\ \ /\ |
| / V )) V \ |
|/ ` // ' \|
` V '
""")
input("Y ahora, {}, dale al ENTER si estás listo".format(nombre)) #pausa
print("\nPero antes de continuar, {}, un consejo\n"
"Este vídeo está patrocinado por GVGMall\n"
"Blah Blah Blah Blah Blah Blah\n"
"OK, al lío\n".format(nombre))
opcion1 = input("Vas por el campo cuando un OVNI gigante te abduce\n"
"Te despiertas en la nave nodriza de los marcianos\n"
"Hay unos extraterrestres con una jeringa chunga a tu lado\n"
"En una repisita ves un objeto negro brillante\n"
"(A) Tratas de despistarles para coger el objeto (B) Te pones a discutir con ellos > ")
if opcion1 == "A":
print("\n- ¡Hostiás! ¿Qué es eso? - dices apuntando por la ventanilla de la nave\n"
"Mientras miran los marcianos aprovechas para meterte el objeto de la repisa en el bolsillo...\n")
tienes_el_satisfier_de_los_marcianos = (opcion1 == "A")
opcion2 = input("Los marcianos se mosquean y se van a por tí\n"
"(A) Huyes hacia el teletransportador (B) Intentas ponerte al volante de la nave > ")
if opcion2=="A":
print("En el teletransportador se cuela una mosca justo a la que entras\n"
"si has visto la película sabes que la cosa acaba mal :-(\n")
elif opcion2 == "B":
opcion3 = input(("Saltas raudo a los mandos de la nave\n"
"Hay un botón gordo rojo que pone SCRAM en marciano\n"
"(A) Le das al botón (B) Le das muy fuerte al botón > "))
if opcion3 == "A":
print("¡Bravo {}, has saltado de la nave!\n".format(nombre))
print("Vuelves a la Tierra. Estás a salvo...")
if tienes_el_satisfier_de_los_marcianos:
print("¡Además robaste el satisfier de los Marcianos!\n"
"¡¡Tienes tecnología extraterrestre!!\n"
"¡¡¡Todo el mundo te cree, eres un héroe mundial!!! :-)\n")
else:
print("...pero nadie te cree. Todo el mundo piensa que estás como una chota.\n"
" Al menos te salvaste :-P")
elif opcion3 =="B":
print("¡Joder, {}, has roto el botón! Ahora los marcianos van a acabar contigo fijo :-(".format(nombre))
premio = random.randint(1,6)
dado = int(input("Rápido, tira un dado > "))
if dado != premio:
print("Saltaste al hiperespacio, apareces junto a Low Spec Gamer\n"
"Te dedicas el resto de tu vida a rular la demo del Assasins en laptops cutres :-/")
else:
print("Los marcianos están hasta los huevos de tí y te mandan a un zoo en Ceres :-(")
else:
print("Te has hecho la picha un lío y te han terminado tirando por el retrete de la nave :-(")
else:
print("Los marcianos te venden a Jabba the Hutt, y acabas en una plancha de carbono :-(")
|
d4b2834428df39da0910c118bfb65424004afe83 | Barzabel/py | /data structure/stack1.py | 2,093 | 3.671875 | 4 | class Node:
def __init__(self,val):
self.value = val
self.prev = None
class Stack:
def __init__(self):
self.stack = None
self.count = 0
def size(self):
return self.count
def pop(self):
if self.size()== 0:
return None # если стек пустой
res = self.stack.value
self.stack = self.stack.prev
self.count = self.count - 1
return res
def push(self, value):
NewNode = Node(value)
NewNode.prev = self.stack
self.stack = NewNode
self.count = self.count + 1
def peek(self):
if self.size()== 0:
return None # если стек пустой
res = self.stack.value
return res
def postpr(st):
res = None
ar = st.split(" ")
ar = [x for x in ar if x != '']
stack1 = Stack()
stack2 = Stack()
for x in ar:
stack2.push(x)
while stack2.count > 0:
stack1.push(stack2.pop())
while stack1.count > 0:
if stack1.peek() != "*" and stack1.peek() != "+" and stack1.peek() != "/" and stack1.peek() != "-" and stack1.peek() != "=":
stack2.push(stack1.pop())
else:
if stack1.peek() == "*":
stack2.push(float(stack2.pop()) * float(stack2.pop()))
stack1.pop()
elif stack1.peek() == "+":
stack2.push(float(stack2.pop()) + float(stack2.pop()))
stack1.pop()
elif stack1.peek() == "-":
a = stack2.pop()
stack2.push(float(stack2.pop()) - float(a))
stack1.pop()
elif stack1.peek() == "/":
a = stack2.pop()
stack2.push(float(stack2.pop()) / float(a))
stack1.pop()
elif stack1.peek() == "=":
res = stack2.peek()
stack1.pop()
res = stack2.peek()
return res
print(postpr("8 2 + 10 + 12 * 44 - ="))
|
757b7382e02d7d42012bc261e43c3ca671d3d74c | dwayneellis/homework2 | /lab6.22.py | 895 | 3.953125 | 4 | # Dwayne Ellis
# CIS 2348
# October 6, 2020
# Lab 6.22 Brute force equation solver
# Numerous engineering and scientific applications require finding solutions to a set of equations. Ex: 8x + 7y = 38 and
# 3x - 5y = -1 have a solution x = 3, y = 2. Given integer coefficients of two linear equations with variables x and y,
# use brute force to find an integer solution for x and y in the range -10 to 10.
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
def func_1(x, y):
return a*x + b*y - c
def func_2(x, y):
return d*x + e*y - f
final_x = 100
final_y = 100
for x in range(-10, 11):
for y in range(-10, 11):
if func_1(x, y) == func_2(x, y) and func_1(x, y) == 0:
final_x = x
final_y = y
if final_x != 100:
print(final_x, final_y)
else:
print('No solution')
|
7a7d37707ad91840ca9c7679c00bf2931fed8641 | ankurgokhale05/LeetCode | /Amazon/Trees/98-Validate_Binary_Search_Tree.py | 1,034 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
The idea above could be implemented as a recursion. One compares the node value with its upper and lower limits if they are available. Then one repeats the same step recursively for left and right subtrees.
Time complexity : O(N) since we visit each node exactly once.
Space complexity : O(N) since we keep up to the entire tree.
'''
class Solution:
def isValidBST(self, root):
def helper(node, lower = float('-inf'), upper = float('inf')):
if not node:
return True
val = node.val
if val <= lower or val >= upper:
return False
if not helper(node.right, val, upper):
return False
if not helper(node.left, lower, val):
return False
return True
return helper(root)
|
067fd8efdb34444c94b1a7ae4f7a9bfdb1cb11c4 | emiairi/Curso-em-video | /PythonExercicios/ex029.py | 459 | 3.75 | 4 | # Desafio 029 - Radar eletrônico.
"""Escreva um programa que leia a velocidade de um carro.
Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado.
A multa vai custar R$ 7,00 por cada kh acima do limite."""
lim = 80
vel = float(input('Qual a velocidade do carro em km/h? '))
if vel > lim:
multa = 7 * (vel - lim)
print('Você foi multado em: R$ {:.2f}'.format(multa))
print('Tenha um bom dia! Dirija com segurança!') |
b1af9d8f15385203f866d4245ab95a7ea7b90efa | MPKeet/PE-Class | /Database_Creator.py | 1,945 | 3.5 | 4 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
#Create random first year of revenue
df=pd.DataFrame(np.random.randint(100000,2500000,size=(10000,1)))
#Second Random Year of Revenue
Yr2Rev=pd.DataFrame(np.random.randint(150000,3000000,size=(10000,1)))
#Creates a third year of revenue with a 12% over the past year
df['Yr3Rev'] = df['Yr2Rev'].apply(lambda x: x*1.12)
#Creates equity ownership of owners
Equity=pd.DataFrame(np.random.uniform(0.1,1,size=(10000,1)))
df=df.rename(columns={'Equity':'Owner_Equity'})
df=df.rename(columns={df.columns[0]:'Yr1Rev'})
#Creates randomized assets
Assets=pd.DataFrame(np.random.randint(1000000,10000000,size=(10000,1)))
df['Assets']=Assets
df=df.rename(columns={'Total Assets':'Total_Assets'})
#Creates randomized liabilities
Liabilities=pd.DataFrame(np.random.randint())
#Creates Current assets from total assets with a 0.25 assumption
df['Current_Assets'] = df['Total_Assets'].apply(lambda x: x*0.25)
#Total Liabilities randomisation
Total_Liabilities=pd.DataFrame(np.random.randint(1000000,8000000,size=(10000,1)))
df['Total_Liabilities']=Total_Liabilities
#Calulate current liabilities from total liabilities, assumption of 0.25 ratio
df['Current_Liabilities'] = df['Total_Liabilities'].apply(lambda x: x*0.25)
#Calculate Liquidity_R given information
df['Liquidity_R'] = df.apply(lambda x: x['Current_Assets'] if x['Current_Assets'] < 1 else x['Current_Assets']/x['Current_Liabilities'], axis=1)
#Creates Randomized COGS Ratio
Avg_COGS_R=pd.DataFrame(np.random.uniform(0.1,0.8,size=(10000,1)))
df['Avg_COGS_R']=Avg_COGS_R
#Gross Profit Margin
df['Profit'] = df.apply(lambda x: x['Yr3Rev'] if x['Yr3Rev'] < 1 else ((x['Yr3Rev']-(x['Yr3Rev']*x['Avg_COGS_R']))/x['Yr3Rev']), axis=1)
#Useful for a few trial runs
df=df.drop(columns='DtoC')
#Writes df to csv
df.to_csv(r'/Users/maxwellkeeter/Desktop/CompSci Resources/Python/PE.csv')
print(df)
|
5aed360ef73f2edff24f45a7837271e4c1871b8f | lightfish-zhang/python-study | /function/def.py | 1,339 | 3.984375 | 4 | # -*- coding: utf-8 -*-
print abs(-100)
def my_abs(x):
if x >= 0:
return x
else:
return -x
print my_abs(-100)
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print power(5,2)
def power2(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print power2(3)
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc([1,2,3])
# 不定参数
def calc2(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc2(1,2,3)
nums = [1,2,3]
print calc2(*nums)
# 关键字参数
def person(name, age, **kw):
print 'name:', name, 'age:', age, 'other:', kw
person('Michael', 30)
person('Adam', 45, gender='M', job='Engineer')
# 在Python中定义函数,可以用必选参数、默认参数、可变参数和关键字参数,这4种参数都可以一起使用,或者只用其中某些,但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数和关键字参数。
def func(a, b, c=0, *args, **kw):
print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw
func(1,2,3,'a','b',x=99)
# *args是可变参数,args接收的是一个tuple;
# **kw是关键字参数,kw接收的是一个dict。
|
a3b04edc5a5999c42a3181ca7d07becfd163b37e | luishmcmoreno/project-euler | /0050.py | 1,154 | 3.578125 | 4 | from bisect import bisect_left
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
hi = hi if hi is not None else len(a) # hi defaults to len(a)
pos = bisect_left(a, x, lo, hi) # find insertion position
return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end
def mark_multiples(arr, n):
i = n*2
while i < len(arr):
arr[i] = False
i += n
n = 1000000
sieve = [True] * n
sieve[0] = False
sieve[1] = False
i = 2
while (i <= int(n**(0.5))):
mark_multiples(sieve, i)
i += 1
while (not sieve[i]): i += 1
primes = []
prime_sum = []
i = 0
for numb in sieve:
if (numb):
primes.append(i)
i += 1
j = 1
prime_sum.append(0)
for prime in primes:
prime_sum.append(prime_sum[j-1] + primes[j -1])
j += 1
i = 0
number_of_primes = 0
for sum in prime_sum:
for j in range(i - number_of_primes + 1, -1, -1):
if (prime_sum[i] - prime_sum[j] > n): break
if (binary_search(primes, prime_sum[i] - prime_sum[j]) >= 0):
number_of_primes = i - j
result = prime_sum[i] - prime_sum[j]
i += 1
print result |
7cf8b6645ed560a808d39057dc162fc3574bd8b3 | ZoranPandovski/design-patterns | /Behavioral/Strategy/python/strategy_demo.py | 236 | 3.5 | 4 | #!/usr/bin/env python2.7
from sorting_strategies import *
sorter = ListSorter(AscendingSort())
values = [1, 2, 5, 8, 6, 3, 7, 4]
print(sorter.sort_list(values))
sorter.change_strategy(DescendingSort())
print(sorter.sort_list(values))
|
c297d635e2f4394dfee9d62a036064b0eb075627 | danielaczs13/Matem-ticas-Computacionales-1745851MC | /ordenamiento por insercion.py | 331 | 3.578125 | 4 | def ordenamiento_por_insercion(arreglo):
for indice in range(1,len(arreglo)):
valor = arreglo[lista]
i = lista - 1
while i>=0:
if valor < arreglo[i]:
arreglo[i+1] = arreglo[i]
arreglo[i] = valor
i = i - 1
else:
break
A=[4,1,3,5,22,8,500]
ordenamiento_por_insercion(A)
print (A)
|
e9c2377d983ff546e1cdc452c473d0daa8864e6e | dthilieu/the-shell | /handle_backslash.py | 825 | 4.0625 | 4 | def encode_backslash(user_input):
"""
Turn double backslash into
a single backslash inside squares
"""
return user_input.replace("\\\\", "[\\]")
def decode_backslash(user_input):
"""
Turn a single backslash inside squares
into a single backslash
"""
user_input.replace("[\\]", "\\")
return user_input.replace("[\\]", "\\")
def remove_backslash(user_input):
"""
Remove all backslash that is used to escaped another character
"""
list_string = list(user_input)
index = 0
# check if it is an decoded backslash or not
# if false, remove it
while index < len(list_string):
if list_string[index] == "\\" and list_string[index - 1] != "[":
list_string.pop(index)
else:
index += 1
return "".join(list_string)
|
1a0155105047bf78d9a8c8e733b0206d8aa10225 | vkurup/project-euler | /12.py | 815 | 4.09375 | 4 | #!/usr/bin/env python2
# triangle numbers: 1, 3, 6, 10, 15, 21, 28, 36, 45
# What is the value of the first triangle number to have over 500
# divisors?
import math
def divisors(n):
"Return all factors of n"
divisors = []
for i in range(1, int(math.sqrt(n))+1):
if n%i == 0:
divisors.append(i)
divisors.append(n / i)
return sorted(set(divisors))
def odd(n):
return n%2 != 0
def first_triangle_with_n_divisors(n):
"Return first triangle number with greater than n divisors"
length = 0
i = 1
next_triangle = 1
while length <= n:
i += 1
next_triangle += i
if odd(next_triangle): continue
length = len(divisors(next_triangle))
return next_triangle
print "answer = ", first_triangle_with_n_divisors(500)
|
d8890b9a67756117df0bf81bf7748e58037860f6 | alexandraback/datacollection | /solutions_5670465267826688_0/Python/katharas/solve.py | 2,482 | 3.796875 | 4 |
from operator import mul
class quaternion:
def __init__(self, type, mul):
self.type = type
self.mul = mul
def __mul__(self, other):
if self.type == 'r':
return quaternion(other.type, self.mul*other.mul)
elif self.type == 'i':
if other.type == 'r':
return quaternion('i', self.mul*other.mul)
elif other.type == 'i':
return quaternion('r', -self.mul*other.mul)
elif other.type == 'j':
return quaternion('k', self.mul*other.mul)
else:
return quaternion('j', -self.mul*other.mul)
elif self.type == 'j':
if other.type == 'r':
return quaternion('j', self.mul*other.mul)
elif other.type == 'i':
return quaternion('k', -self.mul*other.mul)
elif other.type == 'j':
return quaternion('r', -self.mul*other.mul)
else:
return quaternion('i', self.mul*other.mul)
else:
if other.type == 'r':
return quaternion('k', self.mul*other.mul)
elif other.type == 'i':
return quaternion('j', self.mul*other.mul)
elif other.type == 'j':
return quaternion('i', -self.mul*other.mul)
else:
return quaternion('r', -self.mul*other.mul)
def __repr__(self):
return "quaternion('%s', %d)" % (self.type, self.mul)
def __eq__(self, other):
return self.type == other.type and self.mul == other.mul
def __ne__(self, other):
return not self == other
def to_quaternion(s):
return quaternion(s, 1)
def indexes(qs, q):
idxs = []
for idx, qq in enumerate(qs):
if qq == q:
idxs.append(idx)
return idxs
def solve(X, qs):
q = []
for i in range(X):
q.extend(qs)
N = len(q)
forward = [q[0]]
for i in xrange(1, N):
forward.append(forward[-1]*q[i])
if forward[-1] != quaternion('r', -1):
return "NO"
i = 0
for i in xrange(N):
if forward[i] == quaternion('i', 1):
break
for i in xrange(i+1, N):
if forward[i] == quaternion('k', 1):
return "YES"
return "NO"
T = int(raw_input())
for t in range(1, T+1):
X = map(int, raw_input().split())[1]
qs = map(to_quaternion, raw_input().strip())
print "Case #%d: %s" % (t, solve(X, qs))
|
99dbfa066610cd5390aefad0ba4045ad72b68cc9 | abandonsea/msba_reid | /utils/distance.py | 8,209 | 3.8125 | 4 | """Numpy version of euclidean distance, shortest distance, etc.
Notice the input/output shape of methods, so that you can better understand
the meaning of these methods."""
import numpy as np
import torch
import time
import sys
def normalize(nparray, order=2, axis=0):
"""Normalize a N-D numpy array along the specified axis."""
norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True)
return nparray / (norm + np.finfo(np.float32).eps)
def compute_dist(array1, array2, type='euclidean'):
"""Compute the euclidean or cosine distance of all pairs.
Args:
array1: numpy array with shape [m1, n]
array2: numpy array with shape [m2, n]
type: one of ['cosine', 'euclidean']
Returns:
numpy array with shape [m1, m2]
"""
assert type in ['cosine', 'euclidean']
if type == 'cosine':
array1 = normalize(array1, axis=1)
array2 = normalize(array2, axis=1)
dist = np.matmul(array1, array2.T)
return dist
else:
# shape [m1, 1]
square1 = np.sum(np.square(array1), axis=1)[..., np.newaxis]
# shape [1, m2]
square2 = np.sum(np.square(array2), axis=1)[np.newaxis, ...]
squared_dist = - 2 * np.matmul(array1, array2.T) + square1 + square2
squared_dist[squared_dist < 0] = 0
dist = np.sqrt(squared_dist)
return dist
def shortest_dist(dist_mat):
"""Parallel version.
Args:
dist_mat: pytorch Variable, available shape:
1) [m, n]
2) [m, n, N], N is batch size
3) [m, n, *], * can be arbitrary additional dimensions
Returns:
dist: three cases corresponding to `dist_mat`:
1) scalar
2) pytorch Variable, with shape [N]
3) pytorch Variable, with shape [*]
"""
m, n = dist_mat.size()[:2]
# Just offering some reference for accessing intermediate distance.
dist = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
if (i == 0) and (j == 0):
dist[i][j] = dist_mat[i, j]
elif (i == 0) and (j > 0):
dist[i][j] = dist[i][j - 1] + dist_mat[i, j]
elif (i > 0) and (j == 0):
dist[i][j] = dist[i - 1][j] + dist_mat[i, j]
else:
dist[i][j] = torch.min(dist[i - 1][j], dist[i][j - 1]) + dist_mat[i, j]
dist = dist[-1][-1]
return dist
def local_dist(x, y, aligned):
"""Parallel version.
Args:
x: numpy array, with shape [M, m, d]
y: numpy array, with shape [N, n, d]
Returns:
dist: numpy array, with shape [M, N]
"""
M, m, d = x.size()
N, n, d = y.size()
#x = torch.tensor(x).cuda()
#y = torch.tensor(y).cuda()
x = x.view(M*m, d)
y = y.view(N*n, d)
#x = x.reshape([M * m, d])
#y = y.reshape([N * n, d])
# shape [M * m, N * n]
#dist_mat = compute_dist(x, y, type='euclidean')
dist_mat = torch.cdist(x, y)
#dist_mat = (np.exp(dist_mat) - 1.) / (np.exp(dist_mat) + 1.)
dist_mat = (torch.exp(dist_mat) - 1.) / (torch.exp(dist_mat) + 1.)
# shape [M * m, N * n] -> [M, m, N, n] -> [m, n, M, N]
dist_mat = dist_mat.reshape([M, m, N, n]).permute([1, 3, 0, 2])
# shape [M, N]
if aligned:
dist_mat = shortest_dist(dist_mat)
else:
raise Exception("Only aligned dist is implemented!")
return dist_mat
def low_memory_matrix_op(
func,
x, y,
x_split_axis, y_split_axis,
x_num_splits, y_num_splits,
verbose=False, aligned=True):
"""
For matrix operation like multiplication, in order not to flood the memory
with huge data, split matrices into smaller parts (Divide and Conquer).
Note:
If still out of memory, increase `*_num_splits`.
Args:
func: a matrix function func(x, y) -> z with shape [M, N]
x: numpy array, the dimension to split has length M
y: numpy array, the dimension to split has length N
x_split_axis: The axis to split x into parts
y_split_axis: The axis to split y into parts
x_num_splits: number of splits. 1 <= x_num_splits <= M
y_num_splits: number of splits. 1 <= y_num_splits <= N
verbose: whether to print the progress
Returns:
mat: numpy array, shape [M, N]
"""
if verbose:
printed = False
st = time.time()
last_time = time.time()
mat = [[] for _ in range(x_num_splits)]
for i, part_x in enumerate(
np.array_split(x, x_num_splits, axis=x_split_axis)):
for j, part_y in enumerate(
np.array_split(y, y_num_splits, axis=y_split_axis)):
part_mat = func(part_x, part_y, aligned)
mat[i].append(part_mat)
if verbose:
if not printed:
printed = True
else:
# Clean the current line
sys.stdout.write("\033[F\033[K")
print('Matrix part ({}, {}) / ({}, {}), +{:.2f}s, total {:.2f}s'
.format(i + 1, j + 1, x_num_splits, y_num_splits,
time.time() - last_time, time.time() - st))
last_time = time.time()
mat[i] = np.concatenate(mat[i], axis=1)
mat = np.concatenate(mat, axis=0)
return mat
def low_memory_local_dist(x, y, aligned=True):
print('Computing local distance...')
slice_size = 200 # old 200
x_num_splits = int(len(x) / slice_size) + 1
y_num_splits = int(len(y) / slice_size) + 1
z = low_memory_matrix_op(local_dist, x, y, 0, 0, x_num_splits, y_num_splits, verbose=True, aligned=aligned)
return z
def compute_local_distmat_using_gpu(probFea, galFea, memory_save=True, mini_batch=2000):
print('Computing distance using GPU ...')
feat = torch.cat([probFea, galFea]).cuda()
all_num = probFea.size(0) + galFea.size(0)
if memory_save:
distmat = torch.zeros((all_num, all_num), dtype=torch.float16) # 14 GB memory on Round2
i = 0
while True:
it = i + mini_batch
# print('i, it', i, it)
if it < feat.size()[0]:
distmat[i:it, :] = torch.pow(torch.cdist(feat[i:it, :], feat), 2)
else:
distmat[i:, :] = torch.pow(torch.cdist(feat[i:, :], feat), 2)
break
i = it
else:
### new API
distmat = torch.pow(torch.cdist(feat, feat), 2)
# print('Copy distmat to original_dist ...')
original_dist = distmat.numpy() # 14 GB memory
del distmat
del feat
return original_dist
def fast_local_dist(x, y, aligned=True, verbose=True):
print('Computing local distance...')
slice_size = 200 # old 200
if verbose:
#import sys
printed = False
st = time.time()
last_time = time.time()
x = torch.tensor(x, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.float32)
feat = torch.cat([x, y]).cuda()
all_num = feat.size(0)
mat = np.zeros((all_num, all_num), dtype=np.float16)
x_num_splits = int(all_num / slice_size) + 1
y_num_splits = int(all_num / slice_size) + 1
pi = 0
for i, part_x in enumerate(torch.split(feat, slice_size, dim=0)):
# move to cuda
dx = part_x.size(0)
pj = 0
for j, part_y in enumerate(torch.split(feat, slice_size, dim=0)):
# move to cuda
dy = part_y.size(0)
#print('dx, dy', dx, dy)
# compute using gpu
#print('part_x', part_x.size(), 'part_y', part_y.size())
part_mat = local_dist(part_x, part_y, aligned)
#print('part_mat', part_mat.size())
# fetch result
part_mat = part_mat.cpu().numpy()
mat[pi:pi+dx, pj:pj+dy] = part_mat
pj += dy
if verbose:
if not printed:
printed = True
else:
# Clean the current line
sys.stdout.write("\033[F\033[K")
print('Matrix part ({}, {}) / ({}, {}), +{:.2f}s, total {:.2f}s'
.format(i + 1, j + 1, x_num_splits, y_num_splits,
time.time() - last_time, time.time() - st))
last_time = time.time()
pi += dx
return mat
|
8ccbaadb1d6186c6d86dfec599b2d3f7e0fc8a88 | Frann2807/Mi-primer-programa | /conceptos_practica/parte_uno/encontrando_numero_mas_grande/pregunta_infinito_numero_mayor.py | 580 | 3.96875 | 4 | """
Pregunta al usuario una serie de 10 numeros, determina cual es el mas grande de los 10.
"""
numeros_usuario = []
numero_usuario = ""
while len(numeros_usuario) < 10:
while not numero_usuario.isdigit():
numero_usuario = input("Dime un numero:")
numeros_usuario.append(int(numero_usuario))
numero_usuario = ""
print("¡Numero añadido!")
print(numeros_usuario)
numero_grande = numeros_usuario [0]
for numero in numeros_usuario:
if numero_grande < numero:
numero_grande = numero
print("El numero mas grande es {}".format(numero_grande)) |
5dac9240929bd4182be9a3c44f444558950d75cb | lai2234/Machine_Learning01 | /Untitled-3.py | 2,019 | 3.796875 | 4 | #!/usr/bin/env python3
# # -*- coding: utf-8 -*-
# """@author: TsunPang Lai"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import explained_variance_score
# Importing the dataset
dataset = pd.read_csv('/Users/Pang/Downloads/RedditData.csv')
# Creating a dataset of predictors and target
X= dataset.iloc [:, 0:8].values #predictor dataset IV
y= dataset.iloc [:, 8:9].values #target dataset DV
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3,
random_state = 0)
from sklearn.metrics import explained_variance_score, mean_absolute_error
# Decision Tree Regressor
from sklearn.tree import DecisionTreeRegressor
# Creating an instance of Decision Tree Regression
regressor_dt= DecisionTreeRegressor(random_state= 0, max_depth=3 )
regressor_dt.fit(X_train, y_train)
y_pred_dt= regressor_dt.predict(X_test)
# Printing the metrics of the model
print('Variance score: %.2f', explained_variance_score(y_test, y_pred_dt))
print('MAE score: %.2f', mean_absolute_error(y_test, y_pred_dt))
# Fitting Multiple Linear Regression to the Training set and reporting the accuracy
from sklearn.linear_model import LinearRegression
# Creating an instance of Linear regression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred=regressor.predict(X_test)
# Printing the metrics of the model
print('Variance score: %.2f', explained_variance_score(y_test, y_pred))
print('MAE score: %.2f', mean_absolute_error(y_test, y_pred))
# Random Forest Regressor
from sklearn.ensemble import RandomForestRegressor
# Creating an instance of random forest regressor
rf_regressor = RandomForestRegressor(n_estimators=5, random_state=0)
rf_regressor.fit(X,y)
y_pred_rf = rf_regressor.predict(X_test)
print('Variance score: %.2f', explained_variance_score(y_test, y_pred_rf))
print('MAE score: %.2f',mean_absolute_error(y_test, y_pred_rf))
|
95ae2d4e01e9257e074f939bd4345866b55a5990 | shangar21/Obelus | /sr_test.py | 1,237 | 3.625 | 4 | import speech_recognition as sr
import convert
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say Something : ")
audio = r.listen(source)
#lst = ["21", "x", "^", "2", "-", "x", "-", "30", "+","x", "^", "4", "+", "9", "x", "^", "3"]
#print(*convert.poly(lst))
try:
text = r.recognize_google(audio)
text = convert.get_math_syntax(text)
arr = text.split(" ")
print(*arr, sep = ",")
if "solve" in arr[0]:
arr = arr[1:]
for i in range(len(arr)):
if "x" in arr[i]:
if arr[i][0].isdigit():
string = convert.seperate_cf(arr[i])
if string != None:
arr[i] = "x"
arr.insert(i, string)
print(*convert.poly(arr))
elif arr[0] in ["sine", "cos", "tan", "arcsine", "arccos", "arctan"]:
arr = convert.trigno(arr)
print(*arr)
elif "log" in arr[0]:
arr = convert.logarithm(arr)
print(*arr)
except:
print("Sorry, unable to understand.")
#print(int_multiply(text))
#print(int_addition(text))
#print(int_subtraction(text))
|
1da3c1521a8a1ba2943d3268762bb8f98f9801fc | jocelynr24/PythonExamples | /Classe/voiture/voiture.py | 657 | 3.578125 | 4 | # Ma classe Voiture
class Voiture:
# Constucteur de la classe voiture
def __init__(self, marque, roues, couleur, vole):
self.marque = marque
self.roues = roues
self.couleur = couleur
self.vole = vole
# Méthode afficherVoiture() pour afficher une description de la voiture
def afficherVoiture(self):
if(self.vole):
texteVoler = "peut voler"
else:
texteVoler = "ne peut pas voler"
descriptionFinale = "Ma voiture de marque", self.marque, "de couleur", self.couleur, "possède", str(self.roues), "roues et", texteVoler
return " ".join(descriptionFinale) |
93a27b8cbdc6953823a3014721b7a7a0daf22bf8 | tonningp/cis208 | /bit_operations/xchg/debug/loop_print.py | 519 | 3.6875 | 4 | # The following is a python class that will print the loop a specified number of times
import gdb
class LoopPrint(gdb.Function):
"""Print a loop the specfied number of times"""
def __init__(self):
super(LoopPrint,self).__init__("loop_print")
def invoke (self,count,*cmd):
i = 0
while i < count:
for c in cmd:
gdb.execute(c.string())
gdb.execute('c')
i = i + 1
return count
# register the loop_print function
LoopPrint()
|
a68b48c5241ab1c18f8cca5333f7433b5eede768 | csiro-coasts/emsarray | /src/emsarray/operations/triangulate.py | 7,523 | 4.09375 | 4 | """
Operations for making a triangular mesh out of the polygons of a dataset.
"""
from typing import List, Tuple, cast
import xarray
from shapely.geometry import LineString, MultiPoint, Polygon
Vertex = Tuple[float, float]
Triangle = Tuple[int, int, int]
def triangulate_dataset(
dataset: xarray.Dataset,
) -> Tuple[List[Vertex], List[Triangle], List[int]]:
"""
Triangulate the polygon cells of a dataset
A mesh can be constructed from this triangulation,
for example using `Holoviews TriMesh <holoviews_>`_
or `trimesh.Trimesh <trimesh_>`_.
Parameters
----------
dataset
The dataset to triangulate
Returns
-------
tuple of vertices, triangles, and cell indices.
A tuple of three lists is returned,
containing vertices, triangles, and cell indices respectively.
Each vertex is a tuple of (x, y) or (lon, lat) coordinates.
Each triangle is a tuple of three integers,
indicating which vertices make up the triangle.
The cell indices tie the triangles to the original cell polygon,
allowing you to plot data on the triangle mesh.
Examples
--------
Using holoviews_. Try this in an IPython notebook for nice visualisations:
.. code-block:: python
import emsarray
import holoviews as hv
from emsarray.operations import triangulate_dataset
from holoviews import opts
hv.extension('bokeh')
# Triangulate the dataset
dataset = emsarray.tuorial.open_dataset("austen")
vertices, triangles, cell_indices = triangulate_dataset(dataset)
# This takes a while to render
mesh = hv.TriMesh((triangles, vertices))
mesh
Using trimesh_. This should pop up a new window to display the output:
.. code-block:: python
import emsarray
import numpy
import trimesh
from emsarray.operations import triangulate_dataset
dataset = emsarray.tutorial.open_dataset("gbr4")
vertices, triangles, cell_indices = triangulate_dataset(dataset)
# Trimesh expects 3D vertices.
vertices = numpy.c_[vertices, numpy.zeros(len(vertices))]
mesh = trimesh.Trimesh(vertices=vertices, faces=triangles)
mesh.invert() # Trimesh grids expect the opposite winding order
depth = 1 - (dataset.data_vars["Mesh2_depth"].values / -200)
depth_colour = numpy.c_[depth, depth, depth, numpy.ones_like(depth)] * 255
mesh.visual.face_colors = depth_colour[cell_indices]
mesh.show()
.. _holoviews: https://holoviews.org/reference/elements/bokeh/TriMesh.html
.. _trimesh: https://trimsh.org
"""
polygons = dataset.ems.polygons
# Getting all the vertices is easy - extract them from the polygons.
# By going through a set, this will deduplicate the vertices.
# Back to a list and we have a stable order
vertices: List[Vertex] = list({
vertex
for polygon in polygons
if polygon is not None
for vertex in polygon.exterior.coords
})
# This maps between a vertex tuple and its index.
# Vertex positions are (probably) floats. For grid datasets, where cells
# are implicitly defined by their centres, be careful to compute cell
# vertices in consistent ways. Float equality is tricky!
vertex_indices = {vertex: index for index, vertex in enumerate(vertices)}
# Each cell polygon needs to be triangulated,
# while also recording the convention native index of the cell,
# so that we can later correlate cell data with the triangles.
polygons_with_index = [
(polygon, index)
for index, polygon in enumerate(polygons)
if polygon is not None]
triangles_with_index = list(
(tuple(vertex_indices[vertex] for vertex in triangle_coords), dataset_index)
for polygon, dataset_index in polygons_with_index
for triangle_coords in _triangulate_polygon(polygon)
)
triangles: List[Triangle] = [tri for tri, index in triangles_with_index] # type: ignore
indices = [index for tri, index in triangles_with_index]
return (vertices, triangles, indices)
def _triangulate_polygon(polygon: Polygon) -> List[Tuple[Vertex, Vertex, Vertex]]:
"""
Triangulate a polygon.
.. note::
This currently only supports simple polygons - polygons that do not
intersect themselves and do not have holes.
Examples
--------
.. code-block:: python
>>> polygon = Polygon([(0, 0), (2, 0), (2, 2), (1, 3), (0, 2), (0, 0)])
>>> for triangle in triangulate_polygon(polygon):
... print(triangle.wkt)
POLYGON ((0 0, 2 0, 2 2, 0 0))
POLYGON ((0 0, 2 2, 1 3, 0 0))
POLYGON ((0 0, 1 3, 0 2, 0 0))
See Also
--------
:func:`triangulate_dataset`,
`Polygon triangulation <https://en.wikipedia.org/wiki/Polygon_triangulation>`_
"""
if not polygon.is_simple:
raise ValueError("_triangulate_polygon only supports simple polygons")
# This is the 'ear clipping' method of polygon triangulation.
# In any simple polygon, there is guaranteed to be at least two 'ears'
# - three neighbouring vertices whos diagonal is inside the polygon.
# An ear can be clipped off the polygon, giving one triangle and a new,
# smaller polygon. Repeat till the polygon is a triangle.
#
# This algorithm is not the best if given particularly bad polygons,
# but for small convex polygons it is approximately linear in time.
# Most polygons will be either squares, convex quadrilaterals, or convex
# polygons.
# Maintain a consistent winding order
polygon = polygon.normalize()
triangles: List[Tuple[Vertex, Vertex, Vertex]] = []
# Note that shapely polygons with n vertices will be closed, and thus have
# n+1 coordinates. We trim that superfluous coordinate off in the next line
while len(polygon.exterior.coords) > 4:
exterior = polygon.exterior
coords = exterior.coords[:-1]
# We try and make an ear from vertices (i, i+1, i+2)
for i in range(len(coords) - 2):
# If the diagonal between i and i+2 is within the larger polygon,
# then this entire triangle is within the larger polygon
vertices = [coords[i], coords[i + 2]]
multipoint = MultiPoint(vertices)
diagonal = LineString(vertices)
if (
diagonal.covered_by(polygon)
# The intersection of the diagonal with the boundary should be two
# points - the vertices in question. If three or more points are in
# a line, the intersection will be something different. Removing
# that ear will result in two disconnected polygons.
and exterior.intersection(diagonal).equals(multipoint)
):
triangles.append((coords[i], coords[i + 1], coords[i + 2]))
polygon = Polygon(coords[:i + 1] + coords[i + 2:])
break
else:
# According to the twos ear theorem, we should never reach this
raise ValueError(
f"Could not find interior diagonal for polygon! {polygon.wkt}")
# The trimmed polygon is now a triangle. Add it to the list and we are done!
triangles.append(cast(
Tuple[Vertex, Vertex, Vertex],
tuple(map(tuple, polygon.exterior.coords[:-1]))))
return triangles
|
f63f68bcd264787d36c2a9b39389c32b32e1ba87 | jonwihl/15-110-Principles-of-Computing-Coursework | /num_perfect_square.py | 374 | 3.65625 | 4 | import math
def num_perfect_square(numbers):
prime_numbers = []
for x in range(0, len(numbers)):
if numbers[x] >= 0:
if math.sqrt(numbers[x]).is_integer() == True:
prime_numbers.append(numbers[x])
elif x == len(numbers) and math.sqrt(numbers[x]).is_integer() == False:
not_in_list = -1
return not_in_list
else:
x += 1
return (len(prime_numbers)) |
04066dea022f10bc3b28949c26bcc27756fcbd79 | Yacovmm/tp3-fundamentosPython-infnet | /exercise3.py | 335 | 3.796875 | 4 | lista = ["yacov","luciano","thiago","nome4","nome5","nome6","nome7","nome8","nome9"]
lista2 = [1, 2, 3, 4, 5]
for i, word in lista:
a = word[::-1]
lista[i] = a
print(lista)
lista = ["yacov","luciano","thiago","nome4","nome5","nome6","nome7","nome8","nome9"]
lista = list(map(lambda x: x[::-1], lista))
print(lista)
|
b78b7a203f2c637321b41bd651bf53efbc9aad00 | durgaswaroop/unoino | /tests/test_player.py | 1,385 | 3.921875 | 4 | import unittest
from uno.Card import Card
from uno.Player import Player
class TestPlayer(unittest.TestCase):
# Player should decide to Draw from the deck when there are no valid cards
def test_player_decides_to_draw_when_there_Are_no_valid_cards(self):
player = Player("S", [Card("RED", 1)] * 7)
top_card = Card("BLUE", 4)
self.assertEqual(player.decide_action(top_card), "TAKE")
# Player should decide to PLAY when there are valid cards
def test_player_should_play_when_there_are_valid_cards(self):
player = Player("S", [Card("RED", 1)] * 7)
top_card = Card("RED", 1)
self.assertEqual(player.decide_action(top_card), "PLAY")
# Player's total value should be the sum of values of all of his cards
def test_players_total_value_is_sum_of_values_of_his_cards(self):
cards = [Card("RED", 2), Card("BLUE", 8), Card("RED", action="SKIP"),
Card("YELLOW", action="REVERSE"), Card(wild="WILD"),
Card(wild="WILD_DRAW_FOUR")]
player = Player(name="DSP", cards=cards)
self.assertEqual(player.get_total_value(), 150)
# Players total value should be zero when he has no cards
def test_player_with_no_cards_should_have_zero_value(self):
cards = []
player = Player(name="", cards=cards)
self.assertEqual(player.get_total_value(), 0)
|
2bb24658aaee83b6845f7b9b7c99eda4d801f858 | somemonks/snah_python | /guess.py | 752 | 3.96875 | 4 | # this is a number guessing game
import random
guessesTaken = 0
print ('Hello bub! What is your name?')
playerName = input()
number = random.randint(1,200)
print('Well, ' + playerName + ', I am thinking of a number between 1 and 200.')
while guessesTaken < 6:
print ('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken +1
if guess < number:
print('Too low!')
if guess > number:
print('Too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good Job, ' + playerName + ', You got it in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. You suck, it was ' + number + '.')
|
513039302ca0ecce29bc6c664667b69184ca015d | AlexandrMelnic/Penal-Code-Generator | /codice_penale_scraper.py | 2,173 | 3.6875 | 4 | import requests
from bs4 import BeautifulSoup
'''
The structure of the wiki page to crawl is:
libro1:
titolo1
text
titolo2
text
...
...
...
libro2:
...
...
...
'''
class WebScraper:
'''
After instantiating the class use the method return_scraped_pages
to get the full text. The text is saved in the path specified as
input parameter.
The class uses Beautifoul soup to perform the scraping.
'''
def __init__(self, PATH):
self.wiki_link = 'https://it.wikisource.org'
self.PATH = PATH
def get_soup(self, link):
'''
Given a specific link returns the soup object.
'''
link = self.wiki_link + link
req = requests.get(link)
soup = BeautifulSoup(req.text, "lxml")
return soup
def get_links(self, link):
'''
Method that allows to enter in the different sections titolo1, titolo2,...
given the link of the current node.
'''
soup = self.get_soup(link)
links = []
for elem in soup.find('div', {'class':'testi diritto'}).find_all('li'):
links.append(elem.find('a', href=True)['href'])
return links
def get_texts(self, link):
'''
Given the link of one section this method gets the texts defined
by the tag <p>, <h3> and <dd>.
'''
soup = self.get_soup(link)
texts = []
for elem in soup.find('div', {'class':'testi diritto'}).find_all(['h3','p', 'dd']):
texts.append(elem.text)
return texts
def save_scraped_pages(self):
file = open(self.PATH, 'w')
'''
Get all the texts for all sections and save in file.
'''
text = []
for link in self.get_links('/wiki/Codice_penale')[:-1]:
for link2 in self.get_links(link):
file.write(' '.join(self.get_texts(link2)))
file.close() |
f9d31e568ab4b31b2d53a0016c70914fcd71c769 | dylwwj123/my-beautiful-python | /Python基础笔记.py/小项目/自动化办公/读写csv文件/读csv文件.py | 506 | 3.59375 | 4 | import csv
def readCsv(path):
infolist = []
with open(path, "r")as f:
allFileInfo = csv.reader(f)
for rowstr in allFileInfo:
allcount = rowstr.count('')
print(allcount)
for newrows in range(allcount):
rowstr.remove('')
infolist.append(rowstr)
return infolist
path1 = r"/Users/wukaihao/Desktop/python/hello.py/小项目/自动化办公/读写csv文件/csv002.csv"
infolist = readCsv(path1)
print(infolist) |
b473a753933a3b06411f199bc97796bb0f4b0173 | pprasad14/Python_fundamentals | /exception_handling.py | 1,589 | 4.21875 | 4 | #Example 1
import sys
try:
print(1/0)
except ZeroDivisionError:
print("Divide by zero error")
##############
try:
print(1+a)
except NameError:
print("undefined variable detected")
##############
try:
'1' + 1
except TypeError:
print("incorrect type detected")
##############
try:
number = int(input("Enter a number between 1 - 10: "))
if number >10 or number <1:
raise ValueError
except ValueError:
print("Wrong Input")
sys.exit()
print("number: ",number)
##############
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
fh.close()
##############
try:
fh = open("testfile", "r") #Read permission
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
fh.close()
##############
try:
print("opening file")
fh = open("testfile", "r")
try:
fh.write("This is my test file for exception handling!!")
finally:
print ("Going to close the file")
fh.close()
except IOError:
print ("Error: can\'t find file or read data")
##############
# Define a function here.
def temp_convert(var):
try:
return int(var)
except (ValueError):
print ("The argument does not contain numbers\n", var)
# Call above function here.
temp_convert("xyz")
temp_convert("123")
|
319b47cb56b10d5d19b7a614e0740ac134ec6df2 | r3dmaohong/PythonPractice | /insertion sort.py | 340 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 17:02:25 2016
@author: wjhong
"""
def insert(x):
n = len(x)
i = 1
while i<n-1:
key = x[i]
j = i-1
while j>=0 and key<x[j]:
x[j+1]= x[j]
j -= 1
x[j+1] = key
i += 1
return x
print insert([1,10,2,5,41,25,3,48])
|
df679f4017418bbf56e9e04c32c8391374928a65 | kavener/Spider | /5/Hike_MongoDB.py | 481 | 3.625 | 4 | import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.students
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170102',
'name': 'Mary',
'age': 21,
'gender': 'female'
}
# result = collection.insert_one(student2)
# print(result)
reslut = collection.find_one({'name': 'Jordan'})
print(reslut)
count = collection.find().count()
print(count) |
978c0fe8d4337b26a29d7b21c16cc2abe3105d7c | jaychao1973/PythonOneDay-gui-image- | /image_p.py | 493 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 16:09:08 2018
@author: justinwu
"""
from PIL import Image,ImageColor
myIm=Image.new('RGBA',(100,100))
myIm.getpixel((0,0))
for i in range(100):
for j in range(50):
myIm.putpixel((i,j),(0,255,0))
for i in range(100):
for j in range(50,100):
myIm.putpixel((i,j),ImageColor.getcolor('red','RGBA'))
print(myIm.getpixel((0,0)))
print(myIm.getpixel((0,50)))
myIm.save('Pixel_a.png') |
c42071d6c8c8a0a4eed90245bac1061976f67739 | raveltan/itp-git | /01-Introduction/Edward_Matthew - 2440032316/Number guessing game.py | 920 | 4.0625 | 4 | import random
# Intro to the game
player_name = input("Hello, what's your name?")
lower = int(input("Input lower bound here:"))
upper = int(input("Input upper bound here:"))
print("Hello.", player_name, "I'm thinking of a number between", lower, "and", upper, "Guess what it is! \n" )
print("You only have 7 tries for this. Best of luck!")
# Loops for the guesses and checks the validity of the inputs
number = random.randint(lower, upper)
number_of_guesses = 0
while number_of_guesses < 7:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Too low! try again")
if guess > number:
print("Whoa that's too high! try guessing lower")
if guess == number:
break
# Affirmation for the number guessing
if guess == number:
print("That's spot on! It took you", str(number_of_guesses), "tries!")
else:
print("Awhh that's too bad. The number was", number)
|
a4d50d0348455ac2e1dad0b38d3b34fb05e052b4 | zzb15997937197/leet-code-study | /algorithm_study/sort/exp/sort_exp_02.py | 3,210 | 3.9375 | 4 | '''
比较三种排序算法的效率
'''
import random
import datetime
from distlib.compat import raw_input
def swap(array, ele1, ele2):
temp = array[ele1]
array[ele1] = array[ele2]
array[ele2] = temp
# 冒泡排序
# 大的数往右侧移动,外循环从大到小
def bubble_sort(array):
for i in range(len(array) - 1, -1, -1):
for j in range(0, i):
if array[j] > array[j + 1]:
swap(array, j, j + 1)
return array
# 大的数往左侧移动,外循环从小到大。
def left_bubble_sort(array):
for i in range(0, len(array) - 1):
for j in range(0, len(array) - i - 1):
if array[j] < array[j + 1]:
swap(array, j, j + 1)
return array
'''
以上两种方式,都是从0位到未排序好的那一位之间的元素之间,进行两两比较,有一边倒的趋势。
'''
# 选择排序
def selection_sort(array):
for out in range(0, len(array)):
min_val = out
for j in range(out, len(array)):
if array[min_val] > array[j]:
swap(array, min_val, j)
return array
# 插入排序
def insert_sort(array):
for i in range(1, len(array)):
temp = array[i]
j = i
while j > 0 and array[j - 1] >= temp:
swap(array, j, j - 1)
# temp与j-1交换位置后,再向前比较,如果小的话,那么就继续向前交换位置
j = j - 1
return array
class ArrayBub(object):
def __init__(self):
self.array = []
self.nums = 0
def add_ele(self, element):
self.array.append(element)
self.nums += 1
return self
def remove_ele(self, element):
self.array.remove(element)
self.nums -= 1
return self
def travel_array(self):
return [x for x in self.array]
# 删除所有元素
def remove_all_elements(self):
for out in range(0, self.nums):
self.array.remove(self.array[out])
return self
if __name__ == "__main__":
while True:
bubble = ArrayBub()
# 初始化10000个数,5000个有序的数+5000个随机数,再次比较性能
for i in range(0, 5000):
bubble.array.append(i)
for i in range(0, 5000):
bubble.array.append(random.randint(0, 10000))
r = bubble.travel_array()
print(r)
number = raw_input("please input a number:")
start = datetime.datetime.now()
sort_name = ""
if number == "1":
print("冒泡排序")
sort_name = "冒泡排序"
r = bubble_sort(r)
elif number == "2":
print("选择排序")
sort_name = "选择排序"
r = selection_sort(r)
elif number == "3":
print("插入排序")
sort_name = "插入排序"
r = insert_sort(r)
else:
print("非法输入!", SystemExit)
end = datetime.datetime.now()
print(sort_name + "后的结果为:", r)
print(sort_name + "花费的总时间为:", end - start)
## 结果: 选择排序时间< 插入排序时间< 冒泡排序时间
|
64a1e085fd18a5c57d184a39e6273acc3f27b548 | AK-1121/code_extraction | /python/python_3961.py | 140 | 3.59375 | 4 | # Generating a list of functions in python
>>> basis = [ (lambda x,n=n: n*x) for n in [0, 1, 2] ]
>>> print basis[0](1)
0
|
b3dd4fba5fdb774e2db822286b0d4e7a35c56185 | codebuzzer01/Amazing-Python-Scripts | /Remove_POS_hindi_text/hindi_POS_tag_removal.py | 1,258 | 3.6875 | 4 | import string
import nltk
import sys
import os
user_input=input(' Enter file location of your Tagged Hindi Text: ')
#C:\Users\ZAVERI SANYA\Desktop\Amazing-Python-Scripts\Remove_POS_hindi_text\\Tagged_Hindi_Corpus.txt
assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
fp=open(user_input,mode="r",encoding="utf-8") #opens the hindi_tagged_corpus.txt file
print("Hooray we found your file!")
user_answer= input (' Enter file location where you wish to get your Only Hindi Text file: ')
#C:\Users\ZAVERI SANYA\Desktop\Amazing-Python-Scripts\Remove_POS_hindi_text\Only_Hindi.txt
fd=open(user_answer,mode="a",encoding="utf-8")
data=fp.read()
data_token=nltk.tokenize.word_tokenize(data) #data tokenization
words=[]
categories=[]
for i in data_token:
charc=i.split('|')
if(len(charc)>2):
ch=charc[2].split(".")
categories.append(ch[0]) #This gives all the categories of POS tags
if i not in string.punctuation and len(charc[0])>1:
words.append(charc[0]) #This gives the list of hindi words
str=""
for word in words:
str+=word+" " #it concatenates the words
fd.write(str) #writes to only_hindi.txt file
print("Hooray your Only Hindi Text file is ready...Please Check!")
fp.close()
fd.close()
|
0408a2911a46003fce5ca0cf227f0f0a75ee44ec | Saij84/AlgorithmicToolbox | /toolbox/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py | 1,245 | 3.96875 | 4 | # Uses python3
import time
def get_pisano_period(m):
val1 = 0
val2 = 1
seq_len = 0
while seq_len < m*m:
remainder = (val1 + val2) % m
val1 = val2
val2 = remainder
seq_len += 1
if val1 == 0 and val2 == 1:
return seq_len
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
def fibonacci_sum_fast(n, m):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
remainder = n % get_pisano_period(m)
for _ in range(remainder-1):
previous, current = current, previous + current
sum += current
return sum % 10
if __name__ == '__main__':
input = " 10"
n, m = map(int, input.split())
t0 = time.time()
print(fibonacci_sum_naive(n))
t1 = time.time()
print("Slow time: {}".format(t1-t0))
t0 = time.time()
print (fibonacci_sum_fast(n, m))
t1 = time.time()
print("fast time: {}".format(t1 - t0))
"""
00 01 02 03 04 05 06 07 08 09
00 01 01 02 03 05 08 13 21 34
00 01 02 04 07 13 21 34 55 89
""" |
7d8022911239a9b66cb382c45faf7304aba0bed4 | Lighting-Zhu/Deep_Learning_From_Scratch | /ch5demo1112.py | 1,260 | 4.0625 | 4 | class MulLayer: # 乘法层的实现
def __init__(self):
self.x=None
self.y=None
def forward(self,x,y):
self.x=x
self.y=y
out=x*y
return out
def backward(self,dout):
dx=dout*self.y
dy=dout*self.x
return dx,dy
class Addlayer:
def __init__(self):
pass
def forward(self,x,y):
out=x+y
return out
def backward(self,dout):
dx=dout*1
dy=dout*1
return dx,dy
# example
apple=100
apple_num=2
orange=150
orange_num=3
tax=1.1
# layer
mul_apple_layer=MulLayer()
mul_orange_layer=MulLayer()
add_apple_orange_layer=Addlayer()
mul_tax_layer=MulLayer()
# forward
apple_price=mul_apple_layer.forward(apple,apple_num)
orange_price=mul_orange_layer.forward(orange,orange_num)
sum_price=add_apple_orange_layer.forward(apple_price,orange_price)
with_tax_price=mul_tax_layer.forward(sum_price,tax)
# backward
dprice=1
dallprice,dtax=mul_tax_layer.backward(dprice)
dapple_price,dorange_price=add_apple_orange_layer.backward(dallprice)
dapple,dapple_num=mul_apple_layer.backward(dapple_price)
dorange,dorange_num=mul_orange_layer.backward(dorange_price)
#input
print(with_tax_price)
print(dapple_num,dapple,dorange_num,dorange,dtax)
|
43aaf6575d5a423e006fbe4360972d2868e7a8ff | ARWA-ALraddadi/python-tutorial-for-beginners | /08-How to Find Things Demos/08-replacing_patterns.py | 2,598 | 4.3125 | 4 | ## Replacing patterns
##
## The small examples in this demonstration show how regular
## expressions with backreferences can be used to perform
## automatic modifications of text.
from re import sub
## This example shows how to "normalise" a data representation.
## A common problem at QUT is that student numbers are
## represented in different ways, either n7654321, N7654321,
## 07654321 or 7654321. Here we show how to change all student
## numbers in some text into a common zero-prefixed format.
## (The pattern used is not very robust; it is reliable only
## if there are no numbers other than student numbers in the
## text.)
student_nos = \
'''Student 02723957 is to be commended for high quality
work and similarly for student n1234234, but student
1129988 needs to try harder.'''
print(sub('[nN0]?([0-9]{7})', r'0\1', student_nos))
# prints "Student 02723957 is to be commended for high quality
# work and similarly for student 01234234, but student
# 01129988 needs to try harder."
print()
## As another example of substitution and backreferencing, we
## return to the copyeditor's problem of identifying accidently
## duplicated words in text. Not all such phrases are mistakes
## so they need to be checked manually. The following script
## identifies doubled-words as before, but now surrounds them with
## asterisks to draw them to the attention of the proofreader.
## It also allows the two words to be separated by not only
## blank spaces but newline characters because such errors
## often occur at line breaks. Notice that both ends of the
## pattern are required to contain non-alphabetic characters to
## ensure that we don't match parts of words.
## The following paragraph contains several instances of accidental
## word duplication.
unedited_text = \
'''Some of the great achievements of of recording in
recent years have been carried out on on old records. In the
the early days of gramophones, many famous people including
Florence Nightingale, Tennyson, and and Mr. Glastone made
records. In most cases these records, where they could be
found, were in a very bad state; not not that they had
ever been very good by today's standards. By applying
electrical re-recording, engineers reproduced the now
now long-dead voices from the wax cylinders in to
to new discs, and these famous voices which were so nearly
lost forever are now permanently recorded.'''
print(sub(r'([^a-z])(([a-z]+)[ \n]+\3)([^a-z])', r'\1**\2**\4', unedited_text))
# prints "Some of the great achievements **of of** recording in
# recent years ..."
|
9152bfe32dd04d91cabc6350970c7420f0958e6f | jeffreypon/fileObjectExample | /writeFile.py | 233 | 3.625 | 4 | # will overwrite
with open('test2.txt', 'w') as f:
f.write('Test1')
#Move write file pointer position
f.seek(2)
f.write('wassup')
# will append
"""
with open('test2.txt', 'a') as f:
pass
print(f.closed)
""" |
a1c22d233b24fb4518eace1318f68224231112ca | SamiTumarov/MultiplayerChess | /ChessServer/Gamelogic.py | 2,420 | 3.671875 | 4 | import time
from Chess import Board
WHITE = 0
BLACK = 1
class Player:
def __init__(self, name, color, time_left):
self.time_left = time_left
self.name = name
self.color = color
self.started_on = None
def start_turn(self):
# Calculates time
self.started_on = time.time()
def end_turn(self):
# Calculates time
self.time_left -= (time.time() - self.started_on)
self.started_on = None
class Game:
def __init__(self, game_time):
self.white_player = None
self.black_player = None
self.turn = 0 # white
# Not changing, representing the time that was chosen for the game
self.game_time = game_time
self.game_over = False
self.board = Board()
def add_player(self, player):
if player.color == WHITE:
self.white_player = player
if player.color == BLACK:
self.black_player = player
def __getitem__(self, key):
# Allows doing something like Game[WHITE] -> returns white player
if key == WHITE:
return self.white_player
return self.black_player
def toggle_turn(self, move):
if self.turn == 1:
self.turn = 0
self.black_player.end_turn()
self.white_player.start_turn()
else:
self.turn = 1
self.white_player.end_turn()
self.black_player.start_turn()
start = time.perf_counter()
self.board.execute_string(move)
self.board.moves.append(move)
self.board.evaluate_game(self.turn)
if len(self.board.possible_moves) == 0:
# Game is over
self.game_over = True
def is_draw(self):
# If game is over, checks if it is a draw.
# Assumes game is indeed over
loser = self.turn
if loser == WHITE:
if not self.board.white_check:
# White has turn and has no moves, but is not in check.
# Therefore lost
return True
else:
if not self.board.black_check:
return True
return False
def get_player_with_turn(self):
if self.turn == 1:
return self.black_player
return self.white_player
def waiting_for_player(self) -> bool:
return not self.white_player or not self.black_player
|
eb960cab37ab3f23bcaacb305c48a1a931b30008 | rjtennismaster/SimpleNN | /neural_networks.py | 11,797 | 3.578125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
#sigmoid function to normalize predictions
def sigmoid(x):
return 1 / (1 + np.exp(-x))
#derivative of sigmoid
def sigmoid_prime(x):
return sigmoid(x) * (1 - sigmoid(x))
#generates a list of 3 random numbers between -2 and 2
def random_number_list():
num_list = []
for _ in range(3):
num_list.append(random.uniform(-2, 2))
return num_list
#2b
def mean_squared_error(vectors, bias_and_weights, classses, png_file_name):
df = pd.read_excel(vectors)
df.columns = ['petal_length', 'petal_width', 'species']
input_df = df.drop(columns = ['species'])
#input dataset
inputs = input_df.to_numpy()
species_list = df['species'].tolist()
#actual outputs
actual_outputs = np.array(species_list).T
#acknowledge passed weight parameters
synaptic_weights = np.array([bias_and_weights[1], bias_and_weights[2]]).T
#normalize product of inputs * synaptic weights
predictions = sigmoid(np.dot(inputs, synaptic_weights) + bias_and_weights[0])
#plot the predictions with their respective colors. 0 = veriscolor(blue) and 1 = virginica(red)
plt.grid()
for i in range(len(inputs)):
color = 'b'
if predictions[i] >= 0.5:
color = 'r'
plt.scatter([inputs[i][0]], [inputs[i][1]], color = color)
plt.title("Predictions")
plt.xlabel("pedal length")
plt.ylabel('pedal width')
plt.savefig(png_file_name)
#calculate mean squared error
squared_errors = np.square(predictions - actual_outputs)
sum_of_squared_errors = np.sum(squared_errors)
result = sum_of_squared_errors / squared_errors.size
print('mean squared error for this dataset:')
print(result)
return result
#2e. Plots difference between decision boundaries of 999th and 1000th iteration
def summed_gradients(vectors, bias_and_weights):
df = pd.read_excel(vectors)
df.columns = ['petal_length', 'petal_width', 'species']
#dataset
data = df.to_numpy()
print('Dataset:')
print(data)
bias = bias_and_weights[0]
w1 = bias_and_weights[1]
w2 = bias_and_weights[2]
iterations = 1000
learning_rate = 0.1
#gradient sum storage. index 0 is bias, 1, is w1, 2 is w2
gradients = [0, 0, 0]
for iteration in range(iterations):
if iteration == 998:
#update parameters (take a step)
bias = bias - (gradients[0] * learning_rate)
w1 = w1 - (gradients[1] * learning_rate)
w2 = w2 - (gradients[2] * learning_rate)
gradients = [0, 0, 0]
for j in range(len(data)):
point = data[j]
z = bias + point[0] * w1 + point[1] * w2
prediction = sigmoid(z)
actual = point[2]
#squared_error = np.square(prediction - actual)
#take derivative of obj func to get respective gradients, and add them to respective gradient sums
derror_dprediction = 2 * (prediction - actual)
dprediction_dz = sigmoid_prime(z)
dz_dbias = 1
dz_dw1 = point[1]
dz_dw2 = point[2]
derror_dz = derror_dprediction * dprediction_dz
#gradient of bias
derror_dbias = derror_dz * dz_dbias
#gradient of w1
derror_dw1 = derror_dz * dz_dw1
#gradient of w2
derror_dw2 = derror_dz * dz_dw2
#update gradient sums
gradients[0] += derror_dbias
gradients[1] += derror_dw1
gradients[2] += derror_dw2
mean_squared_error(vectors, [bias, w1, w2], [0, 1], 'decision1.png')
elif iteration == 999:
#update parameters (take a step)
bias = bias - (gradients[0] * learning_rate)
w1 = w1 - (gradients[1] * learning_rate)
w2 = w2 - (gradients[2] * learning_rate)
gradients = [0, 0, 0]
for j in range(len(data)):
point = data[j]
z = bias + point[0] * w1 + point[1] * w2
prediction = sigmoid(z)
actual = point[2]
#squared_error = np.square(prediction - actual)
#take derivative of obj func to get respective gradients, and add them to respective gradient sums
derror_dprediction = 2 * (prediction - actual)
dprediction_dz = sigmoid_prime(z)
dz_dbias = 1
dz_dw1 = point[1]
dz_dw2 = point[2]
derror_dz = derror_dprediction * dprediction_dz
#gradient of bias
derror_dbias = derror_dz * dz_dbias
#gradient of w1
derror_dw1 = derror_dz * dz_dw1
#gradient of w2
derror_dw2 = derror_dz * dz_dw2
#update gradient sums
gradients[0] += derror_dbias
gradients[1] += derror_dw1
gradients[2] += derror_dw2
mean_squared_error(vectors, [bias, w1, w2], [0, 1], 'decision2.png')
else:
#update parameters (take a step)
bias = bias - (gradients[0] * learning_rate)
w1 = w1 - (gradients[1] * learning_rate)
w2 = w2 - (gradients[2] * learning_rate)
gradients = [0, 0, 0]
for j in range(len(data)):
point = data[j]
z = bias + point[0] * w1 + point[1] * w2
prediction = sigmoid(z)
actual = point[2]
#squared_error = np.square(prediction - actual)
#take derivative of obj func to get respective gradients, and add them to respective gradient sums
derror_dprediction = 2 * (prediction - actual)
dprediction_dz = sigmoid_prime(z)
dz_dbias = 1
dz_dw1 = point[1]
dz_dw2 = point[2]
derror_dz = derror_dprediction * dprediction_dz
#gradient of bias
derror_dbias = derror_dz * dz_dbias
#gradient of w1
derror_dw1 = derror_dz * dz_dw1
#gradient of w2
derror_dw2 = derror_dz * dz_dw2
#update gradient sums
gradients[0] += derror_dbias
gradients[1] += derror_dw1
gradients[2] += derror_dw2
print('bias: ')
print(bias)
print('w1: ')
print(w1)
print('w2: ')
print(w2)
#3a & b. Trains the NN through gradient descent to reduce the error as much as possible (i.e. optimize decision boundary). Plots: Ending decision boundary, learning curve
def train_gradient_descent(vectors, bias_and_weights):
df = pd.read_excel(vectors)
df.columns = ['petal_length', 'petal_width', 'species']
#convert data set to numpy array
data = df.to_numpy()
print('Dataset:')
print(data)
bias = bias_and_weights[0]
w1 = bias_and_weights[1]
w2 = bias_and_weights[2]
#number of iterations, 10000 is standard
iterations = 10000
learning_rate = 0.1
#keep track of squared error at each iteration
squared_errors = np.array([])
#keep track of mean squared error so we can plot it eventually
mean_squared_errors = np.array([])
for i in range(iterations):
#use a random point in the dataset
random_num = np.random.randint(len(data))
point = data[random_num]
#decision boundary equation
z = bias + point[0] * w1 + point[1] * w2
prediction = sigmoid(z)
actual = point[2]
squared_error = np.square(prediction - actual)
squared_errors = np.append(squared_errors, squared_error)
mean_squared_errors = np.append(mean_squared_errors, (np.sum(squared_errors) / squared_errors.size))
#if the mean squared error is less than 0.001, we can stop and print out the values of the parameters
if mean_squared_errors[i] < 0.001:
print("we're ending early! ending parameters:")
print(' ')
print('bias: ')
print(bias)
print('w1: ')
print(w1)
print('w2: ')
print(w2)
return
#print the parameters whe we reach halfway through our iterations
if i == iterations / 2:
print('parameters halfway through: ')
print('')
print('bias: ')
print(bias)
print('w1: ')
print(w1)
print('w2: ')
print(w2)
#take the derivative of the objective func to get the gradients and update the parameters
derror_dprediction = 2 * (prediction - actual)
dprediction_dz = sigmoid_prime(z)
dz_dbias = 1
dz_dw1 = point[1]
dz_dw2 = point[2]
derror_dz = derror_dprediction * dprediction_dz
#gradient of bias
derror_dbias = derror_dz * dz_dbias
#gradient of w1
derror_dw1 = derror_dz * dz_dw1
#gradient of w2
derror_dw2 = derror_dz * dz_dw2
#figure out step sizes (how much we'll change each parameter)
bias_step_size = derror_dbias * learning_rate
w1_step_size = derror_dw1 * learning_rate
w2_step_size = derror_dw2 * learning_rate
#finally, change the weights based on the step size
bias -= bias_step_size
w1 -= w1_step_size
w2 -= w2_step_size
#print the values of the parameters if on last iteration
if i == (iterations - 1):
print('ending parameters:')
print(' ')
print('bias: ')
print(bias)
print('w1: ')
print(w1)
print('w2: ')
print(w2)
#plot the learning curve
plt.title('Learning Curve')
plt.xlabel('Iterations')
plt.ylabel('Mean Squared Error')
plt.plot(mean_squared_errors)
plt.savefig('learningCurve.png')
#plot the decision boundary and return mean squared error of whole data set
#mean_squared_error(vectors, [bias, w1, w2], [0, 1], 'ending decision.png') <--wanted to call this, but the plotting is acting wacky so I'll just call MSE with the printed weights
#3c
#starting decision boundary:
#random_starting_parameters = random_number_list()
#print('random starting parameters:')
#print(random_starting_parameters)
#mean_squared_error('irisdata.xlsx', random_starting_parameters, [0, 1], 'start_decision.png')
#train gradient func will let us know the parameters at halfway through & at the end so we can plug them in and plot the decision boundary
#train_gradient_descent('irisdata.xlsx', random_starting_parameters)
#now we know midway and ending parameters, so we can plug them into plotting func to visualize
#mean_squared_error('irisdata.xlsx', [-7.599015327148707, -4.490375476905719, 18.38132944550192] , [0, 1], 'midway_decision.png')
#mean_squared_error('irisdata.xlsx', [-11.468725816758589, -6.942480435029876, 27.791309218983198] , [0, 1], 'end_decision.png')
#some more arguments we tried to test the program
#train_gradient_descent('irisdata.xlsx', [-.000356765486754765, -0.00004500000009, 0.0003398])
#mean_squared_error('irisdata.xlsx', [-11.924946642784034, -6.755993497684189, 27.633176745966946], [0, 1], 'ending_decision.png')
#summed_gradients('irisdata.xlsx', [-.000356765486754765, -0.00004500000009, 0.0003398])
#mean_squared_error('irisdata.xlsx', [0, 2.4, 2.7], [0, 1])
#mean_squared_error('irisdata.xlsx', [-.000356765486754765, -0.00004500000009, 0.0003398], [0, 1], 'decision1.png')
|
9290e319f515f53affd69a6b519bfe9cb588f0e7 | hugohadfield/gajit | /gajit/regex_process.py | 2,529 | 3.5 | 4 |
import re
import hashlib
def process_to_symbols(text, inputs, intermediates, outputs):
# Get all the symbols
all_symbols = set(re.findall("[A-Za-z1-9]+\[\d+\]", text))
input_symbols = set()
output_symbols = set()
remapped_symbols = set()
# All the input symbols can be defined right at the start
ind = text.find('):') + 2
for inp in inputs:
for j in range(32):
symbol = inp + '\['+str(j)+'\]'
symbol_text = inp + '[' + str(j) + ']'
replacement = inp + '_'+str(j)
text = re.sub(symbol, replacement, text)
remapped_symbols.add(replacement)
input_symbols.add(symbol_text)
text = text[:ind]+'\n ' +replacement + ' = ' +symbol_text +text[ind:]
# We can leave all of the output symbols alone
for inp in outputs:
for j in range(32):
symbol = inp + '['+str(j)+']'
output_symbols.add(symbol)
# Get all the symbols other than the input, output
others = all_symbols.difference(input_symbols)
others = others.difference(output_symbols)
# For each symbol get the number
for symb in others:
splt = symb.split('[')
tx = splt[0]
numb = splt[1][:-1]
replacement = tx+'_'+numb
remapped_symbols.add(replacement)
text = text.replace(symb,replacement)
return common_subexpression_elimination(text)
def common_subexpression_elimination(text):
# Symbol * Symbol
# [A-Za-z]\w+\s\*\s[A-Za-z]\w+(?!\.)
reg_finder = "[A-Za-z]\w+\s\*\s[A-Za-z]\w+(?!\.)"
text2 = text + ' '
# Find all matching symbols
matches = list(set(re.findall(reg_finder, text2)))
# Find all associated replacements
replist = ["__".join(("".join(m.split())).split('*')) for m in matches]
for m, rep in zip(matches, replist):
# Generate a replacement
# Find first usage
x = text2.find(m)
# Step back to the start of the line
for i in range(len(text2)):
ind = x - i
if text2[ind] == '\n':
ind = ind + 1
break
text2 = text2[:ind] + ' ' + rep + ' = ' + m + '\n' + text2[ind:].replace(m,rep)
return text2
if __name__ == '__main__':
with open('example_rotor_lines_gajit.py','r') as fobj:
text = fobj.read()
inputs = ['L','M']
outputs = ['V']
intermediates = []
text = process_to_symbols(text, inputs, intermediates, outputs)
#print(text)
|
5a443104737ab9f043c0663708927aa3b638b5d9 | prashubarry/PyhtonWorkspace | /venv/LeetCode/RomanToDecimal.py | 761 | 3.75 | 4 | def value(r):
if (r=='I'):
return 1
if(r=='V'):
return 5
if(r=='X'):
return 10
if(r=='C'):
return 100
if(r=='L'):
return 50
if(r=='D'):
return 500
if(r=='M'):
return 1000
def romanToDecimal(str):
res=0
i=0
while(i<len(str)):
s1 = value(str[i])
if (i+1 < len(str)):
s2 = value(str[i+1])
if(s1 >= s2):
res= res+s1
i=i+1
else:
res = res +s2 -s1
i=i+2
else:
res = res+s1
i=i+1
return res
if __name__=='__main__':
input_string = input()
print(romanToDecimal(input_string)) |
7eab78c4ae7062ee5735a0079e12d45ed00f4155 | Coorjet/exercism_preludd | /robot-name/robot_name.py | 780 | 3.578125 | 4 | import random
import string
class Robot():
existingNames = set()
def __init__(self):
self.reset()
def reset(self):
self.name = self.getRandomName()
self.existingNames.add(self.name)
def getRandomName(self):
while True:
newName = self.computeRandomName()
if newName not in self.existingNames:
return newName
def computeRandomName(self):
computedName = ""
computedName += random.choice(string.ascii_uppercase)
computedName += random.choice(string.ascii_uppercase)
computedName += str(random.randrange(0,9))
computedName += str(random.randrange(0,9))
computedName += str(random.randrange(0,9))
return computedName |
42b57344323e6c1c38d7b3c359e47c3ec4c9970c | prateksha/Source-Code-Similarity-Measurement | /Extras/person/Correct/2.py | 681 | 3.5625 | 4 | class person():
a=[]
def __init__(self,name,parent,children):
self.name=name
self.parent=parent
self.children=children
person.a.append(self.name)
class family():
def __init__(self,headoffamily):
self.headoffamily=headoffamily
@property
def headoffamily(self):
return headoffamily.name
@property
def allnodes(self):
for i in person.a:
print(i)
def searchnode(n):
for i in person.a:
if(i==n.name):
print("exists")
return True
def allancestors(n):
for i in person.a:
if (i==n.name):
print(n.parent)
|
ad4570392d3dc97694e83d169303fdaa0f08e42a | gabriellaec/desoft-analise-exercicios | /backup/user_144/ch21_2019_08_19_13_23_29_727229.py | 155 | 3.828125 | 4 | conta = float(input("Qual o valor da conta do restaurante ? "))
conta_com_10 = conta * 1.1
print("Valor da conta com 10%: R${0:.2f}".format(conta_com_10)) |
f6bae91240a137adad4c775084ad9daf6c9aba8e | AndersOLDahl/optimal_influence | /Source/Main.py | 4,729 | 3.890625 | 4 | #!/usr/bin/python
import sys
import heapq
# Employee
ID = 0
BOSS_ID = 1
VALUE = 2
# Node data
NODE_LEAF = 0
NODE_CHILDREN = 1
NODE_VALUE = 2
# Priority queue data
QUEUE_LEAF = 0
QUEUE_VALUE = 1
# Start point for the priority queue (id = 1)
CEO = 1
# Priority queue class using heapq which is a binary heap. This will make
# finding the maximum very fast.
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
# Read data from the standard input. Assumes it comes in the right format.
def readSTDIN():
N, k = map(int, sys.stdin.readline().split(" "))
# Make ids match indexes
employees = [[0,0,0]]
for i in range(N):
line = sys.stdin.readline()[:-1].split(" ")
numbers = map(int, line)
employees.append(numbers)
return employees, k, N
# Find the leaf nodes from the data. These are the data points that never get
# mentioned as another node's BOSS_ID
def find_leaf_nodes(employees, N):
find_leaf_nodes = [True] * (N + 1)
leaf_nodes = []
for employee in employees:
if find_leaf_nodes[employee[BOSS_ID]] == True:
find_leaf_nodes[employee[BOSS_ID]] = False
for index, leaf in enumerate(find_leaf_nodes):
if leaf == True:
leaf_nodes.append(index)
return leaf_nodes
# Initalize important data for each node
# [0,[],0]
# - The leaf node that leads to the highest accumulated value from
# this node
# - Direct children from the node
# - Highest accumulated value from this node to a leaf node
def initalize_tree(employees, leaf_nodes, N):
data = [[0, [], 0] for _ in range(N+1)]
added_already = [False] * (N + 1)
for leaf in leaf_nodes:
next_node = employees[leaf][BOSS_ID]
accumulated_value = employees[leaf][VALUE]
data[leaf][NODE_LEAF] = leaf
data[next_node][NODE_CHILDREN].append(leaf)
data[leaf][NODE_VALUE] = accumulated_value
# Loop until the CEO, it might short circut beforehand
while(next_node != 0):
current_node = next_node
next_node = employees[current_node][BOSS_ID]
# If we have already added this node once, we do not
# need to add it again.
if(added_already[current_node] != True):
data[next_node][NODE_CHILDREN].append(current_node)
added_already[current_node] = True
accumulated_value += employees[current_node][VALUE]
# Change the stored accumulated value if it is greater than what we had
# before; otherwise, short circuit to avoid unnecessary looping
if (accumulated_value > data[current_node][NODE_VALUE]):
data[current_node][VALUE] = accumulated_value
data[current_node][NODE_LEAF] = leaf
else:
break
return data
# Find the maximum influence you can spread by picking k employees
def find_maximum_influence(data, employees, k, N):
# Used to stop if a calculation reaches a deleted node at any point
flag_deleted_nodes = [False] * (N + 1)
current_maximum = 0
# Push the CEO onto the priority queue
priority_queue = PriorityQueue()
priority_queue.push([data[CEO][NODE_LEAF], data[CEO][VALUE]], data[CEO][VALUE])
# Loop through k amount of times
for x in range (0, k):
# Pop off the max
temp = priority_queue.pop()
current_node = temp[QUEUE_LEAF]
current_maximum += temp[QUEUE_VALUE]
# Mark the leaf we are working with as deleted
flag_deleted_nodes[current_node] = True
next_node = employees[current_node][BOSS_ID]
# Loop until the CEO or a deleted node is reached
while(next_node != 0 and flag_deleted_nodes[next_node] != True):
current_node = next_node
# Flag that we have deleted the node
flag_deleted_nodes[current_node] = True
next_node = employees[current_node][BOSS_ID]
# Add the now seperate trees to the priority queue. Make sure they
# have not been deleted before doing so.
for e in data[current_node][NODE_CHILDREN]:
if (flag_deleted_nodes[e] != True):
priority_queue.push([data[e][NODE_LEAF], data[e][VALUE]], data[e][VALUE])
# Return the maximum influence for k iterations
return current_maximum
def Algorithm():
# Read the employees and make the id's match indexes. This will be easier to
# work with.
employees, k, N = readSTDIN()
# Keep track of all the leaf nodes in the tree
leaf_nodes = find_leaf_nodes(employees, N)
# Keep track of important computational data for all nodes
data = initalize_tree(employees, leaf_nodes, N)
print find_maximum_influence(data, employees, k, N)
if __name__ == "__main__":
Algorithm()
|
1dd066d8f624604b5623dcea847253fc16fc3922 | StefaniaSferragatta/HackerRankChallenges-ADM_HW1 | /HACKERRANK_Sets/simmetric_difference.py | 287 | 3.84375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
input()
s1=set(map(int, ((input().split()))))
input()
s2=set(map(int, ((input().split()))))
set1 = s1.difference(s2)
set2 = s2.difference(s1)
set3 = set1.union(set2)
output = sorted(set3)
for i in output:
print(i) |
a73a0c80cc6d4762b9405d30f3bfce77bbae917f | sunnivmr/tdt4110 | /oving7/tekstbehandling.py | 802 | 3.6875 | 4 | print("\na)")
def blokk_bokstaver(string):
return string.strip().upper()
print(blokk_bokstaver(" \n The Sky's Awake So I'm Awake \t "))
print("\nb)")
def splitt_ord(string, char):
return string.split(char)
print(splitt_ord("Hakuna Matata", 'a'))
print("\nc)")
s1 = "eat"
s2 = "I want to be like a caterpillar. Eat a lot. Sleep for a while. Wake up beautiful."
def func(s1, s2):
s = "My bed is a magical place where I suddenly remember everything I forgot to do."
if s1 in s2.lower():
s = "The more you weigh, the harder you are to kidnap. Stay safe. Eat cake."
print(s)
func(s1, s2)
print("\nd)")
def kult(char):
i = 1
while i <= 8:
print(char * i)
i += 1
i = 7
while i >= 1:
print(char * i)
i -= 1
kult('Z')
|
5895568ab504f433af3576fa826b39c68567ab65 | robrcc/Python-Utilities | /select_serial_port.py | 2,149 | 3.53125 | 4 | # list_serial_ports code from Thomas - https://stackoverflow.com/a/14224477
import sys
import glob
import serial
from checknumbers import *
def list_serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
# Port selection menu, returns string of port name or empty string
def choose_serial_port():
choice = ""
while choice != "X":
ports = list_serial_ports()
print("Available serial ports:")
for x in range(len(ports)):
print("[%d] %s" % (x, ports[x]))
print("[X] Exit")
choice = input("Select port: ")
if choice == "x" or choice == "X":
print("No port chosen.")
return ""
elif isInt(choice) and int(choice) in range(len(ports)):
return ports[int(choice)]
else:
print("Invalid choice.")
# Port speed selection menu, returns int of port speed or zero if none
def choose_port_speed():
speeds = [1200,2400,4800,9600,19200,38400,57600,115200]
choice = ""
while choice != "X":
print("Available port speeds:")
for x in range(len(speeds)):
print("[%d] %d" % (x, speeds[x]))
print("[X] Exit")
choice = input("Select port [ENTER for 9600]: ")
if choice == "x" or choice == "X":
print("No speed chosen.")
return 0
elif choice == "":
return 9600
elif isInt(choice) and int(choice) in range(len(speeds)):
return speeds[int(choice)]
else:
print("Invalid choice.")
def main():
p = choose_serial_port()
s = choose_port_speed()
print("Port:", p)
print("Speed:", s)
main() |
07422daf1dd191eedf4060d0c357e17575a018c5 | JoJo0259/Smol-Projects | /Set Game Solver/set_game_solver.py | 1,819 | 3.65625 | 4 | file1 = open("previous.txt", "r+")
answers = file1.readlines()
file1.close()
for l in answers:
print(l + "\n")
print("Press enter to start the solver.\nThis will erase the previous answers.\nClosing the program will keep the previous answers saved.")
input()
print("Starting solver......")
file1 = open("previous.txt", "w+")
class obj():
def __init__(self, color, shape, count, shade):
self.color = color
self.shade = shade
self.count = count
self.shape = shape
objects = {}
for i in range(12):
color, shape, shade, count = input().split(",")
new_obj = obj(color, shape, count, shade)
objects[i] = new_obj
for i in range(10):
one = objects[i]
for j in range(i+1, 11):
two = objects[j]
for k in range(j+1, 12):
three = objects[k]
if (one.color == two.color and one.color == three.color) or (one.color != two.color and one.color != three.color and two.color != three.color):
if(one.shape == two.shape and one.shape == three.shape) or (one.shape != two.shape and two.shape != three.shape and three.shape != one.shape):
if(one.count == two.count and two.count == three.count) or (one.count != two.count and two.count != three.count and three.count != one.count):
if(one.shade == two.shade and two.shade == three.shade) or (one.shade != two.shade and two.shade != three.shade and three.shade != one.shade):
print(str(i+1) + " " + str(j+1) + " " + str(k+1))
answers.append(str(i+1) + " " + str(j+1) + " " + str(k+1))
for l in answers:
file1.writelines(l)
file1.close()
print("\nPress enter to close the program.\nThis will save the current answers.")
input()
|
7d5ee6f08444eb0b05d62530b1cda86d72431b18 | DaHuO/Supergraph | /codes/CodeJamCrawler/CJ/16_0_2_abhigupta4_revenge_pancakes.py | 246 | 3.59375 | 4 | for case in range(input()):
str1 = raw_input()
ele = str1[0]
count = 0
for i in range(1,len(str1)):
if str1[i] != ele:
ele = str1[i]
count += 1
if ele == '-':
count += 1
print "Case #" + str(case + 1) + ": " + str(count) |
23bbfef93ff3e3f182291232a9114473712f3bdd | aparecida-gui/learning-python | /exercicios/sortRGB.py | 840 | 3.703125 | 4 | # Crie um programa que organize e imprima a lista a seguir colocando todos os 'R' juntos, depois todos os 'B' e por ultimo os 'G'.
# Ele também deve imprimir a versão da lista organizada em forma de string separada por ' - '
# A lista letras = ['R', 'B', 'R', 'R','B','G','G','B','G','R', ] deve gerar os 2 outputs abaixo
# ['R', 'R', 'R', 'R','B','B','B','G','G','G', ] e
# 'R - R - R - R - B - B - B - G - G - G'
listaLetras = ['R', 'B', 'R', 'R', 'B', 'G', 'G', 'B', 'G', 'R', ]
listaR = []
listaB = []
listaG = []
for lista in listaLetras:
if lista in 'R':
listaR.append('R')
if lista in 'B':
listaB.append('B')
if lista in 'G':
listaG.append('G')
print('>>>> listaR', listaR)
print('>>>> listaB', listaB)
print('>>>> listaG', listaG)
listaRBG = listaR + listaB + listaG
listaRBG.split('-')
|
17845921f8a4cec86e9e7251030852029f621a44 | fdavis/ideal-chainsaw | /python/test_primes.py | 433 | 3.71875 | 4 | import unittest
from primes import is_prime
class PrimesTestCase(unittest.TestCase):
"""tests for `primes.py`"""
def test_is_four_prime(self):
"""is four apropriately determined to not be prime?"""
self.assertFalse(is_prime(4))
def test_is_five_prime(self):
"""is five successfully determined to be prime?"""
self.assertTrue(is_prime(5))
if __name__ == '__main__':
unittest.main()
|
431b99839915ba1dc763e49818d518811cc6256b | edwaddle/profile | /Cipher/ceacer cipher.py | 1,733 | 4.03125 | 4 | import enchant
d = enchant.Dict("en_US")
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWUXYZ"
def encrypt(msg, key):
counter = 0
# Makes it so counter is set to zero, dont know what counter is
num = 0
# sets num to zero, dont know what it is
ciphertext = ''
# Leaves ciphertext blank, dont know what cipher text is
while counter < len(msg):
# counts the number of letters in the message and checks if it is less than counter or zero
symbol = msg[counter]
# set symbol to msg[counter] dont know what msg[counter] is
if symbol in LETTERS:
num = LETTERS.find(symbol)
# sets num as number of the letter
num = num + key
# sets num as num plus key, ????
if num >= len(LETTERS):
# if num has more numbers than Letters does
num = num - len(LETTERS)
# subtract the number of LETTERS from num
ciphertext = ciphertext + LETTERS[num]
# Set cipher text to Cipher text plus
else:
ciphertext = ciphertext + symbol
counter += 1
return ciphertext
text = input("Enter message to be encrypted: ")
shift = input("Enter shift: ")
cipher = encrypt(text.upper(), int(shift))
print(cipher)
def decrypt(msg):
possible_solutions = []
for i in range(26):
deciphertext = ''
for symbol in msg:
num = LETTERS.find(symbol) + i
if num >= len(LETTERS):
num = num - len(LETTERS)
deciphertext += LETTERS[num]
if d.check(deciphertext):
possible_solutions.append(deciphertext)
return possible_solutions
decipher = decrypt(cipher)
print(decipher)
|
b16ac44573979785877259a021fb71f86c24f80b | htcr/epipolar | /tri-derive.py | 402 | 3.5 | 4 | from sympy import *
def get_matrix(C):
C_list = list()
for i in range(3):
row = list()
for j in range(4):
item = ('%s%d%d' % (C, i, j))
row.append(item)
C_list.append(row)
return Matrix(C_list)
C1 = get_matrix('A')
w = Matrix([['w1'], ['w2'], ['w3'], ['1']])
x = Matrix([['x1'], ['y1'], ['1']])
result = Matrix(C1.dot(w)) - x
print(result) |
0903404277692d77b1b4c1b9075be223d3fb619a | luksos/iSA_python_basic | /2018.12.05_zajecia_07/class_file_diary.py | 1,703 | 3.765625 | 4 | """
!!!!!!!!!! NOT FINISHED !!!!!!!!
"""
"""
Program dzienniczka z opcjami dodawania, usuwanie i wyświetlania wszystkich wpisów.
Dodatkowe funkcje to np wyszukiwanie po dacie lub treść.
Przeglądanie wpisów poprzez wybór "następny", "poprzedni"
"""
import pickle
import sys
diary_file = 'diary'
def menu():
options = """OPCJE:
1 - przeczytaj pamiętnik
2 - dodaj wpis
3 - usuń wpis
4 - wyszukaj wpis
5 - wyjdź z programu
"""
print(options)
choice = 0
while choice not in (1, 2, 3, 4, 5):
try:
choice = int(input("Podaj co chcesz zrobić: "))
except ValueError:
choice = 0
return choice
def read_diary(file):
with open(file, 'rb') as picklefile:
data = pickle.load(picklefile)
return data
def add_diary_entry(file):
date = input("Podaj datę: ")
body = input("Podaj treść: ")
new_entry = {'date': date, 'body': body}
old_entries = read_diary(diary_file)
diary_list = []
diary_list.append(old_entries)
diary_list.append(new_entry)
with open(file, 'rb') as picklefile:
picklefile.seek(0)
pickle.dump(diary_list, picklefile)
def del_diary_entry(file):
date = input("Podaj datę: ")
data = read_diary(file)
def search_diary_entry():
None
def main():
choice = menu()
if choice == 1:
print("Oto Twoje wpisy:")
diary = read_diary(diary_file)
print(diary)
elif choice == 2:
add_diary_entry(diary_file)
elif choice == 3:
del_diary_entry()
elif choice == 4:
search_diary_entry()
elif choice == 5:
print("Do zobaczenia...")
sys.exit()
main()
|
0b8077ab9c5f35b9b45e8b291d8eec8107c4b0f1 | smistry2920/ece2524 | /HW4/change_grade.py | 792 | 3.78125 | 4 | #!/usr/bin/env python
import os, sys
#argument 1 is string
#argument 2 is number
#argument 3 is file
#Used standard search and replace if the name is found
def ch_grade(sys):
error = "Error: Not enough arguments"
if len(sys.argv) < 3:
output.write(error)
else:
string = sys.argv[1]
number = sys.argv[2]
input = sys.stdin
output = sys.stdout
if len(sys.argv) > 3:
input = open(sys.argv[3])
if len(sys.argv) > 4:
output = open(sys.argv[4], 'w')
for s in input.xreadlines():
output.write(s.replace(string, number))
return (string, number)
if __name__=='__main__':
from sys import stdin,stdout,stderr
#string = sys.argv[1]
#number = sys.argv[2]
(string,number) = ch_grade(sys)
stderr.write(number)
stderr.write(string)
|
7090efe3ff1dd55cdedaccb9839994084c5d8ac4 | mhealey/AIND | /aind-sudoku/solution.py | 7,093 | 3.5 | 4 | assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(A, B):
"""Cross product of elements in A and elements in B."""
return [x_ + y_ for x_ in A for y_ in B]
boxes = cross(rows,cols)
diagonals = [['A1', 'B2', 'C3', 'D4', 'E5', 'F6', 'G7', 'H8', 'I9'],
['A9', 'B8', 'C7', 'D6', 'E5', 'F4', 'G3', 'H2', 'I1']]
row_units = [cross(r, cols) for r in rows]
column_units = [cross(rows, c) for c in cols]
square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]
unitlist = row_units + column_units + square_units + diagonals
units = dict((s, [u for u in unitlist if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any values
if values[box] == value:
return values
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers.
"""
# Find all instances of naked twins by first locating all the entres of length = 2
nonDiag = row_units + column_units + square_units
for unit in nonDiag:
boxGroup = [(box1,box2) for box1 in unit for box2 in unit if values[box1]==values[box2] and len(values[box1])==2 and box1 != box2]
if len(boxGroup) > 0:
for i in range(len(boxGroup)):
box1 = boxGroup[i][0]
box2 = boxGroup[i][1]
vals = values[box1]
##peerGroup = peers[box1].intersection(peers[box2])# & peers[box2]
for peer in unit:
if peer != box1 and peer !=box2:
for val in vals:
assign_value(values,peer,values[peer].replace(val,""))
return values
def grid_values(grid):
"""
Convert grid into a dict of {square: char} with '123456789' for empties.
Args:
grid(string) - A grid in string form.
Returns:
A grid in dictionary form
Keys: The boxes, e.g., 'A1'
Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.
"""
dct = dict(zip(boxes,grid))
nums = '123456789'
for key in dct:
if '.' in dct[key]:
dct[key] = nums
return dct
def display(values):
"""
Display the values as a 2-D grid.
Args:
values(dict): The sudoku in dictionary form
"""
# Define width of board (id 9 values, two bars)
width = 1 + max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else ' ') for c in cols) )
if r in 'CF': print(line)
return
def eliminate(values):
""" Processes values dictionary and eliminates all other peer choices if
"""
for key, value in values.items():
if len(value)==1:
kys = peers[key]
for key2 in kys:
if value in values[key2]:
assign_value(values,key2,values[key2].replace(value,""))
return values
def only_choice(values):
""" Remove numbers, when there is only one choice amongst a unit group. This can also accomplished
by going through the dictionary of peers """
for unit in unitlist:
for num in cols:
unitLst = [unt for unt in unit if num in values[unt]]
if len(unitLst)==1:
assign_value(values,unitLst[0],num)
return values
def reduce_puzzle(values):
stalled = False
while not stalled:
# Check how many boxes have a determined value
solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
# Your code here: Use the Eliminate Strategy
values = eliminate(values)
# Your code here: Use the Only Choice Strategy
values = only_choice(values)
# Check how many boxes have a determined value, to compare
solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
# If no new values were added, stop the loop.
stalled = solved_values_before == solved_values_after
# Sanity check, return False if there is a box with zero available values:
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
def search(values):
values = reduce_puzzle(values) # Get the initial reduction, prior to performing any search
# If values has any issues, return failed
if values is False:
return False
# if all values have a length of 1, solved!
count = 0
for key, value in values.items():
if len(value) > 1:
count+=1
if count==0:
return values
# Find the first place to search. Beginning with the square with the least options in order to maximize our search
# speed.
minn = 100
for key, value in values.items():
if len(value) < minn and len(value) > 1:
n = value
s = key
## As shown in the solutions.py file from the course, this can also be done as a one line list
## comprehension. For accuracy, I've left my solution as is
## n, s = min((len(values[s]),s) for s in boxes if len(values[s]) > 1)
for value in values[s]:
new = values.copy()
new[s] = value
temp = search(new)
if temp:
return temp
def solve(grid):
"""
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. False if no solution exists.
"""
values = grid_values(grid)
values = reduce_puzzle(values)
values = naked_twins(values)
values = search(values)
return values
if __name__ == '__main__':
diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
display(solve(diag_sudoku_grid))
#display(solve())
try:
from visualize import visualize_assignments
visualize_assignments(assignments)
except SystemExit:
pass
except:
print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
|
649443732a6389410cb0d24ac0b52d20a00f04b4 | apollyonl/IntroZero | /Problemas Python/Problema3.py | 416 | 3.734375 | 4 | a1 = float (input ("Precio por libra paquete A: "))
a2 = float (input ("Porcentaje magro del paquete A: "))
b1 = float (input ("Precio por libra paquete B: "))
b2 = float (input ("Porcentaje magro del paquete B: "))
cla = a1/a2
clb = b1/b2
print("Costo de carne Paquete A: ",cla)
print("Costo de carne Paquete B: ",clb)
if cla > clb:
print("El paquete B es el mejor")
else:
print("El paquete A es el mejor")
|
92f94a51e5508ab7b42fe68b17b27506b2337e51 | pasolano/dsq | /Linked_List.py | 11,647 | 3.734375 | 4 | class Linked_List:
class __Node:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
def __init__(self):
self.__header = self.__Node(None)
self.__trailer = self.__Node(None)
self.__header.next = self.__trailer
self.__trailer.prev = self.__header
self.__size = 0
def __len__(self):
return self.__size
def append_element(self, val):
new_node = self.__Node(val)
self.__trailer.prev.next = new_node
new_node.prev = self.__trailer.prev
self.__trailer.prev = new_node
new_node.next = self.__trailer
self.__size += 1
def insert_element_at(self, val, index):
if self.__size == 0:
pass
elif self.__size <= index or index < 0:
raise IndexError
current = self.__header.next
cur_index = 0
while cur_index != index:
current = current.next
cur_index += 1
new_node = self.__Node(val)
current.prev.next = new_node
new_node.prev = current.prev
current.prev = new_node
new_node.next = current
self.__size += 1
def remove_element_at(self, index):
if self.__size <= index or index < 0:
raise IndexError
current = self.__header.next
cur_index = 0
while cur_index != index:
current = current.next
cur_index += 1
current.prev.next = current.next
current.next.prev = current.prev
current.next = None
current.prev = None
self.__size -= 1
return current.val
def get_element_at(self, index):
if self.__size <= index or index < 0:
raise IndexError
current = self.__header.next
cur_index = 0
while cur_index != index:
current = current.next
cur_index += 1
return current.val
def rotate_left(self):
if self.__size == 0:
return
current = self.__header.next
current.next.prev = self.__header
self.__header.next = current.next
self.__trailer.prev.next = current
current.prev = self.__trailer.prev
current.next = self.__trailer
self.__trailer.prev = current
def __str__(self):
if self.__size == 0:
return '[ ]'
current = self.__header.next
cur_index = 0
result_str = '[ '
while cur_index < self.__size - 1:
result_str += str(current.val) + ', '
current = current.next
cur_index += 1
result_str += str(current.val) + ' ]'
return result_str
def __iter__(self):
self.current = self.__header
return self
def __next__(self):
if self.current.next is self.__trailer:
raise StopIteration
self.current = self.current.next
return self.current.val
if __name__ == '__main__':
import random
# creates three different types of lists
def create_empty():
return Linked_List()
def create_one():
one_ll = Linked_List()
one_ll.append_element(random.randint(0,10000))
return one_ll
def create_many():
many_ll = Linked_List()
for i in range(0, 10):
many_ll.append_element(random.randint(0,10000))
return many_ll
# manually create list to ensure the string representation is correct. ensures that
# the string representation and method usage aren't messing up in a way that coincidentally
# makes it seem they're working (not knowing the true values in lists with random values
# this a possibility)
manual_ll = Linked_List()
manual_ll.append_element(5)
manual_ll.append_element(3)
manual_ll.append_element(6)
manual_ll.append_element(4)
manual_ll.insert_element_at(8, 2)
manual_ll.remove_element_at(3)
print('Expecting String: [ 5, 3, 8, 4 ]:')
print(manual_ll)
empty_ll = create_empty()
one_ll = create_one()
many_ll = create_many()
# negative index in each linked list for each indexed method (should raise exception)
print('Insert Element with Negative Indices (lists shouldn\'t change):\nEmpty Linked List:')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.insert_element_at(1, -1)
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.insert_element_at(1, -1)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.insert_element_at(1, -1)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
print('Remove Element with Negative Indices:\nEmpty Linked List:')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.remove_element_at(-1)
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.remove_element_at(-1)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.remove_element_at(-1)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
print('Get Element with Negative Indices:\nEmpty Linked List:')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.get_element_at(-1)
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.get_element_at(-1)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Node Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.get_element_at(-1)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
# new intact lists
empty_ll = create_empty()
one_ll = create_one()
many_ll = create_many()
# index too large for each linked list for each indexed method (should raise exception)
# doesn't assume the list class passed the previous tests
print('Insert Element with Indices Too Large:\nEmpty Linked List:')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.insert_element_at(1, 1)
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.insert_element_at(1, 1)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.insert_element_at(1, 9)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
print('Remove Element with Indices Too Large:\nEmpty Linked List:')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.remove_element_at(1)
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.remove_element_at(2)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.remove_element_at(10)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
print('Get Element with Indices Too Large:\nEmpty Linked List:')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.get_element_at(1)
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.get_element_at(2)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Node Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.get_element_at(10)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
# test all indexed methods on all three lists with valid indices
# could make into a loop but ultimately it wouldn't make the code anymore readable because
# there isn't an obvious loop possible
print('Insert Element with Valid Indices:\nEmpty Linked List (Error Expected):')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.insert_element_at(1, 0)
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List (Error Expected):')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.insert_element_at(1, 0)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.insert_element_at(1, 8)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
empty_ll = create_empty()
one_ll = create_one()
many_ll = create_many()
print('Remove Element with Valid Indices:\nEmpty Linked List (Error Expected):')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.remove_element_at(0) # error expected
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.remove_element_at(0)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.remove_element_at(9)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
# recreate empty just to make sure the it hasn't been modified by remove element before
# testing it in get element
empty_ll = create_empty()
one_ll = create_one()
many_ll = create_many()
print('Get Element with Valid Indices:\nEmpty Linked List (Error Expected):')
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + '):')
empty_ll.get_element_at(0) # error expected
print(str(empty_ll) + ' (Size: ' + str(len(empty_ll)) + ')\n')
print('One Node Linked List:')
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + '):')
one_ll.get_element_at(0)
print(str(one_ll) + ' (Size: ' + str(len(one_ll)) + ')\n')
print('Ten Node Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.get_element_at(9)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
# recreate Many Nodes List
many_ll = create_many()
# test remove method on index 0, a middle index, and the last index
print('Remove Index 0:\nTen Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.remove_element_at(0)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
# recreate many ll
many_ll = create_many()
# remove middle index on Many Nodes List
print('Remove Index 5:\nMany Nodes Linked List:')
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + '):')
many_ll.remove_element_at(5)
print(str(many_ll) + ' (Size: ' + str(len(many_ll)) + ')\n')
# test for loop (__iter__, __next__) and see if it matches what __str__ returns
manual_ll = Linked_List()
manual_ll.append_element(4)
manual_ll.append_element(3)
manual_ll.append_element(8)
manual_ll.append_element(7)
for i in manual_ll:
print(i.val)
print(manual_ll)
# call size, test tail append, print, and call size to see if it changed
many_ll = create_many()
print('Size of 10 Nodes Linked List (should be 10): ' + str(len(many_ll)))
many_ll.append_element(6)
print('Size of 10 + 1 Nodes Linked List (should be 11): ' + str(len(many_ll)) + '\n')
# recreate standard list set
empty_ll = create_empty()
one_ll = create_one()
many_ll = create_many()
# test the length method and see if it returns length (without sentinels)
print('__len__ of an Empty List: ' + str(len(empty_ll)))
print('__len__ of a One Node List: ' + str(len(one_ll)))
print('__len__ of a Many Nodes List: ' + str(len(many_ll))) |
16d442c830ed2f5eb16a8c14c6c52514963e2af5 | simplg/jupyter | /pendu.py | 3,096 | 3.9375 | 4 | from random import randrange
LISTE_MOTS = [
"POMMES",
"ARBRE",
"ECOLE",
"INTELLIGENCE",
"ARTIFICIELLE"
]
MAX_TRIES = 6
print("Salut et bienvenue dans le jeu du pendu !")
print("Vous avez jusqu'à 6 essais pour deviner les lettres avant de nous donner la réponse finale.")
input("Dès que vous êtes prêts, appuyez sur entrée...")
rand = randrange(0, len(LISTE_MOTS))
# mot à trouver
word_to_guess = LISTE_MOTS[rand]
# lettres dans le mot à trouver
# cette variable est nécessaire afin de contourner le problème des doublons mais aussi d'optimiser les performances de recherche
liste_lettre = list(set(word_to_guess))
# liste des lettres devinees
guessed_letters = []
# on initialise une variable i qui sera incrémenté à chaque nouvel essai
i = 0
# on affiche pour la première fois le mot à deviner
print("# " * len(word_to_guess))
# on boucle tant que le nombre d'essaie (i) est inférieur à 6 ET qu'il reste toujours des lettres à deviner
while i < MAX_TRIES and len(liste_lettre) > 0:
# variable contenant la lettre que l'utilisateur veut deviner ce tour
letter = ""
# Tant que l'utilisateur n'envoie pas une seule lettre ou que cette lettre a déjà été envoyé,
# on continue à lui demander de taper une lettre
while len(letter) != 1 or letter in guessed_letters:
letter = input("Taper une lettre : ").upper()
# on affiche un message d'erreur pour les deux cas (plusieurs lettres ou lettre déjà deviné )
if letter in guessed_letters:
print("Attention : vous avez déjà deviné cette lettre !\n")
elif len(letter) != 1:
print("Erreur : vous ne devez taper qu'une seule lettre !\n")
# une fois que les vérifications sont faîtes, on ajoute la lettre aux lettres devinés
guessed_letters.append(letter)
# si la lettre est présente dans le mot à trouver
if letter in liste_lettre:
# on enlève la lettre de la liste des lettres dans le mot à trouver
liste_lettre.remove(letter)
# on boucle sur les lettres du mot afin d'afficher le mot (ex: # # # # X # )
for l in word_to_guess:
# si la lettre du mot à deviner est présente dans la liste des lettres qui nous reste à deviner
if l in liste_lettre:
# on affiche "# "
print("# ", end="")
else:
# sinon, ça veut dire que la lettre a été deviné donc on l'affiche
print(f"{l} ", end="")
# on affiche le nombre d'essai qu'il reste à l'utilisateur
print(f"\nIl vous reste {MAX_TRIES - i - 1} essais...\n")
# puis on incrémente le tour de 1
i += 1
# A la fin, lorsque l'utilisateur n'a plus d'essaie ou lorsqu'il ne lui reste plus de lettres à deviner
# on lui demande de nous proposer le mot en entier
guessed = input("Devinez maintenant le mot : ").upper()
# si le mot correspond à celui qu'il fallait deviner
if guessed == word_to_guess:
# on affiche gagné
print("GAGNÉ !")
else:
# sinon on affiche perdu
print("PERDU !!!")
print(f"Le mot était '{word_to_guess}' !")
|
778625df672007683d50412ce17b46aa8c68dd9f | CrabBucket/Super-Competitive-Competivie-Programming | /icpc_2019_1/icpc_2019_1.py | 539 | 3.75 | 4 | import sys
def reverse(n, base):
result = 0
while n > 0:
result *= base
result += n % base
n //= base
return result
def isPalindrome(n, base):
return n == reverse(n, base)
def length(n, base):
length = 0
while n > 0:
length += 1
n //= base
return length
for line in sys.stdin:
unpack = line.split()
base, n = int(unpack[0]), int(unpack[1])
count = 0
while not isPalindrome(n, base) and count <= 500:
n = n + reverse(n, base)
count += 1
if count > 500:
print(">500")
else:
print(count, length(n, base))
|
34d0933bed526255814aca9fc97fd125cd5062b0 | readonPust/Practice-Python | /py_LAMDA_function.py | 542 | 4.03125 | 4 | '''
*lambda function has no name.
* lambda function is called "Anonymous function",
* Not powerfull as named function.
* lambda function work with single Expression/Single line Code.
** lambda function Syntax:
"(lambda parameter : expression)(argument)"
'''
#At first named function given below:
def cal(a,b): #This is called named function.cz we use function name.
return a+b
sum=cal(10,5)
print("The sum is:",sum)
#lambda function given below:
rule=(lambda a,b: a*a+2*a*b+b*b)(2,3)
print(rule)
#Or:
print((lambda a,b:a+b)(2,3))
|
f6bb3a89c31f307e91da613e30b60be28b8689f4 | rebeccanjagi/bootcamp-7 | /andela_labs/reverse_string.py | 420 | 4.5 | 4 | def reverse_string(string):
'''
A function, reverse_string(string), that returns the reverse of the string provided.
If the reverse of the string is the same as the original string,
as in the case of palindromes, return true instead.
'''
rev_string = ""
if string is not "":
for b in string:
rev_string = b+rev_string
if rev_string == string:
return True
return rev_string
else:
return None
|
65751b3bbc351aea69f0c612ed4d558a7ea33a0a | samkrimmel/CalcProject.py | /Calc1.py | 668 | 3.8125 | 4 | #calc RRAM, LRAM, MRAM
from math import *
a = float(input('Enter left bound'))
b = float(input('Enter right bound'))
n = int(input('Enter a number of subintervals'))
f = input('Enter the function')
LRAM = 0.0
RRAM = 0.0
MRAM = 0.0
TRAM = 0.0
SRAM = 0.0
x = a
dX = (b-a)/n
for i in range(n):
x1 = x
f1 = eval(f)
LRAM = LRAM + f1*dX
x = x+dX
x2 = x
f2 = eval(f)
RRAM = RRAM + f2*dX
TRAM = TRAM + ((f2+f1)/2)*dX
x = (x1 +x2)/2
fm = eval(f)
MRAM = MRAM + fm*dX
SRAM = SRAM + ((dX/3)*(f1+(4*fm)+f2))/2
x = x2
print('LRAM =',LRAM,'RRAM =',RRAM,'MRAM =', MRAM, 'Trapezoidal Rule =', TRAM, "Simpson's Rule =", SRAM) |
50a00498ccb31b22a9b345682202bbddc9716304 | Jay-Patil1/Coding | /Code With Harry/Python Tuts/tut42 (Self and __init__()[Constructors]).py | 992 | 3.984375 | 4 | # SELF AND __INIT__() (CONSTRUCTORS)
class Employee:
no_of_leaves = 8
def __init__(self, aname, asalary, arole): # This is a constructor. Which takes arguements.
self.name = aname
self.salary = asalary
self.role = arole
# We will create a function in the class.
def printdetails(self): # Self is the object worked upon.
return(f"Name is {self.name}, Salayr is {self.salary} and Role is {self.role}")
harry = Employee("Harry",355, "Instructor")
rohan = Employee("Rohan",555, "Student")
harry.name = "Harry"
harry.salary = 445
harry.role = "Instruntor"
rohan.name = "Rohan"
rohan.salary = 4554
rohan.role = "Student"
print(rohan.printdetails()) # This makes the 'rohan' go into the function.
print(harry.printdetails())
# Constructors
harry = Employee("Harry",355, "Instructor") # This goes to init. If theres no init it doesnt work . As the class doesn't take arguements.
print(harry.salary) |
49df59b9e4b381f32a680530e2e77f2983ef7ff5 | way2arun/datastructures_algorithms | /src/arrays/findPairs.py | 1,749 | 3.90625 | 4 | """
K-diff Pairs in an Array
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
0 <= i, j < nums.length
i != j
a <= b
b - a == k
Example 1:
Input: nums = [3,1,4,1,5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input: nums = [1,2,3,4,5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: nums = [1,3,1,5,4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Example 4:
Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3
Output: 2
Example 5:
Input: nums = [-1,-2,-3], k = 1
Output: 2
Constraints:
1 <= nums.length <= 104
-107 <= nums[i] <= 107
0 <= k <= 107
https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/559/week-1-october-1st-october-7th/3482/
"""
from collections import Counter
from typing import List
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
# Solution 1 - 56 ms
count = Counter(nums)
if k > 0:
res = sum([i + k in count for i in count])
else:
res = sum([count[i] > 1 for i in count])
return res
"""
# Solution 2 - 76 ms
ans, seen = set(), set()
for x in nums:
if x - k in seen: ans.add(x)
if x + k in seen: ans.add(x + k)
seen.add(x)
return len(ans)
"""
# Main call
solution = Solution()
nums = [1,2,3,4,5]
k = 1
print(solution.findPairs(nums,k)) |
a23a8468b703317276ff3c921f6999d66f40b557 | zeroistfilm/week01 | /gyojin/11_최댓값.py | 239 | 3.71875 | 4 |
tempList = list()
for i in range(9):
tempList.append(int(input()))
maximum = tempList[0]
for i in range(9):
if tempList[i] > maximum:
maximum = tempList[i]
print(maximum)
print(tempList.index(maximum) + 1)
|
e4c32f0bb3e3fe74435a195aae239fbbabd70cae | aj03794/python-pocs | /classes/class_method.py | 997 | 3.859375 | 4 | # This does not work
# class MyClass(number):
class MyClass(number):
# print('some_param', some_param)
def method(self):
print('instance method called')
return 'instance method called', self
@classmethod
def classmethod(cls):
print('class method called')
return 'class method called', cls
@staticmethod
def staticmethod():
print('static method called')
return 'static method called'
# Does not work
# myClass = MyClass(1)
myClass = MyClass()
# myClass.method()
# myClass.classmethod()
# myClass.staticmethod()
# print('--------------------------------')
# # Can also do
# MyClass.method(myClass)
# # Works
# print('--------------------------------')
# MyClass.staticmethod()
# MyClass.classmethod()
# # Fails
# MyClass.method()
# Class methods
# Because the class method only has access to this cls argument,
# it can’t modify object instance state
# Instance methods
# Can access instance state through the |
e4b0c9fc806eefde9c16447a88de89fb5e88ba30 | beatobongco/MITx-6.00.1x | /Week_5/fe_2_int_set.py | 1,431 | 4.03125 | 4 | class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
def member(self, e):
"""Assumes e is an integer
Returns True if e is in self, and False otherwise"""
return e in self.vals
def remove(self, e):
"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
return '{' + ','.join([str(e) for e in self.vals]) + '}'
def intersect(self, other):
r = intSet()
for x in other.getValues():
if x in self.getValues():
r.insert(x)
return r
def getValues(self):
return self.vals
def __len__(self):
return len(self.getValues())
def __eq__(self, other):
return self.getValues() == other.getValues()
a = intSet()
a.insert(1)
a.insert(1)
a.insert(2)
b = intSet()
b.insert(3)
b.insert(2)
c = intSet()
c.insert(2)
assert len(a) == 2
assert len(b) == 2
assert len(c) == 1
assert a.intersect(b) == c
|
f344cce1133b4b405b09b648c84bd27fd19a7e87 | borisboychev/SoftUni | /Python_OOP_Softuni/Inheritance_Lab/venv/random_list.py | 278 | 3.5625 | 4 | from random import choice
class RandomList(list):
def get_random_element(self):
random_el = choice(self)
self.remove(random_el)
return random_el
""""Test Code"""
ll = RandomList([1, 2, 3, 4])
print(ll.get_random_element())
ll.append(5)
ll.pop()
|
8028b765198dcb56e17ad09de6d60c700c611395 | facelessuser/ColorHelper | /lib/coloraide/spaces/prismatic.py | 1,921 | 3.5625 | 4 | """
Prismatic color space.
Creates a Maxwell color triangle with a lightness component.
http://psgraphics.blogspot.com/2015/10/prismatic-color-model.html
https://studylib.net/doc/14656976/the-prismatic-color-space-for-rgb-computations
"""
from ..spaces import Space
from ..channels import Channel
from ..cat import WHITES
from ..types import Vector
from .. import algebra as alg
import math
from typing import Tuple
def srgb_to_lrgb(rgb: Vector) -> Vector:
"""Convert sRGB to Prismatic."""
l = max(rgb)
s = sum(rgb)
return [l] + ([(c / s) for c in rgb] if s != 0 else [0, 0, 0])
def lrgb_to_srgb(lrgb: Vector) -> Vector:
"""Convert Prismatic to sRGB."""
rgb = lrgb[1:]
l = lrgb[0]
mx = max(rgb)
return [(l * c) / mx for c in rgb] if mx != 0 else [0, 0, 0]
class Prismatic(Space):
"""The Prismatic color class."""
BASE = "srgb"
NAME = "prismatic"
SERIALIZE = ("--prismatic",) # type: Tuple[str, ...]
EXTENDED_RANGE = False
CHANNELS = (
Channel("l", 0.0, 1.0, bound=True),
Channel("r", 0.0, 1.0, bound=True),
Channel("g", 0.0, 1.0, bound=True),
Channel("b", 0.0, 1.0, bound=True)
)
CHANNEL_ALIASES = {
"lightness": 'l',
"red": 'r',
"green": 'g',
"blue": 'b'
}
WHITE = WHITES['2deg']['D65']
def is_achromatic(self, coords: Vector) -> bool:
"""Test if color is achromatic."""
if math.isclose(0.0, coords[0], abs_tol=1e-4):
return True
white = [1, 1, 1]
for x in alg.vcross(coords[:-1], white):
if not math.isclose(0.0, x, abs_tol=1e-5):
return False
return True
def to_base(self, coords: Vector) -> Vector:
"""To sRGB."""
return lrgb_to_srgb(coords)
def from_base(self, coords: Vector) -> Vector:
"""From sRGB."""
return srgb_to_lrgb(coords)
|
efcfc05c070658d0797d87c517409f977e2c9fdb | wilbertbarr2/robotsvsdino | /robot_.py | 582 | 3.84375 | 4 | class Robot:
def __init__(self):
self.name = ''
self.health = '100'
self.power_level = '35'
self.weapon_type = ''
self.attack_power = '14'
#setting robot name to prompt user:
def set_robot_name(self):
response = input()
self.name = response
print(f'Robot Name is Now {self.weapon_type}')
#setting weapon to user prompt:
def set_weapon_type(self):
response = input('what type of Weapon would you like?')
self.weapon_type = response
print(f'Weapon type is now {self.weapon_type}')
|
57af116d0ec729b98500dfaeb199e9d038a71005 | Sasha1152/Training | /power_of_power.py | 496 | 3.75 | 4 | import time
def power_of(power):
cache = {}
def hidden(x):
start = time.time()
if x in cache:
print('Using cached data {} sec'.format(round(time.time() - start, 3)))
return cache[x]
else:
cache[x] = x**power**power
print('Calculating power of...{} sec'.format(round(time.time() - start, 3)))
return cache[x]
return hidden
p7 = power_of(7)
p7(2)
p7(2)
p7(4)
p7(4)
p7(6)
p7(6)
p7(36)
p7(36)
|
2a7d3415cad8f7773b0eadb615fd41bc8904bfba | karaltan/Uzaktan-Egitim-Python-Programlama-1.Donem | /7-07.01.2021/borc.py | 218 | 3.671875 | 4 | alınan_borc=float(input('bankadan aldığınız borcu giriniz:'))
odenen_borc=float(input('bankaya verilen parayı giriniz:'))
kalan_borc=(alınan_borc)-(odenen_borc)
print("kalan borc:{0}".format(kalan_borc)) |
b16d507bce58a7d840c6fb195d3c6ba876157e7c | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/389.py | 476 | 4.09375 | 4 | import string
def word_count(phrase):
'''
Given a phrase, count the occurrences of each word.
'''
word_count_dictonary = {}
for word in phrase.split():
word = word.strip(string.punctuation).lower()
if word == '':
continue
if word not in word_count_dictonary:
word_count_dictonary[word] = 1
else:
word_count_dictonary[word] = word_count_dictonary[word] + 1
return word_count_dictonary
|
d5d74ddbdbf0b855a414f336a0e013fef3b9cf9f | BartekDzwonek/PracaDomowa1 | /Homework3.py | 396 | 3.734375 | 4 | #!/usr/bin/env python3
class Kwiatek:
def __init__(self, kolor, nazwa):
self.kolor = kolor
self.nazwa = nazwa
def wyswietl(self):
print("Kolor kwiatka to {} a jego nazwa to {}".format(self.kolor, self.nazwa))
kolor = input("Podaj kolor kwiatka: ")
nazwa = input("Jak nazywa sie kwiatek: ")
kwiatek = Kwiatek(kolor, nazwa)
kwiatek.wyswietl()
|
531baa00c98d2a8eb30e2bb6d23442821b016070 | arvidbt/KattisSolutions | /python/aaah.py | 138 | 3.671875 | 4 | jon = int(input().count("a"))
doctor = int(input().count("a"))
if jon >= doctor:
print("go")
if jon < doctor:
print("no") |
00b96b10ab0418df58fa5918ce3d007d7bf46a59 | nickfrasco/C200 | /Assignment5/romanc.py | 564 | 3.859375 | 4 | # input paramter: a roman numeral as a string
# return the number equivalent
def roman_to_number(n):
roman_value = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
integer_value = 0
for i in range(len(n)):
if i > 0 and roman_value[n[i]] > roman_value[n[i-1]]:
integer_value += roman_value[n[i]] - 2 * roman_value[n[i-1]]
else:
integer_value += roman_value[n[i]]
return integer_value
n = ["XCIX", "LXXXVIII", "XII", "IX", "XXXVIII", "XXXIX"]
for i in n:
print(roman_to_number(i))
|
ea0587c7c97dbfb9cae445361d35d567c6932151 | alfonsovgs/test-arara | /multiple_brackets.py | 1,506 | 3.890625 | 4 | def is_token_valid(token):
return token in ['(', ')', '[', ']']
def is_bracket_open(token):
return token in ['(', '[']
def is_bracket_close(token):
return token in [')', ']']
def tokens_match(previous_token, current_token):
if previous_token == '[' and current_token == ']':
return True
elif previous_token == '(' and current_token == ')':
return True
return False
def multiple_brackets(strParam):
# Get only valid tokens
tokens = [token for token in strParam if is_token_valid(token)]
tokens_proc = []
brackets_counter = 0
# tokens should be [()] or (()]
if tokens:
for token in tokens:
if is_bracket_open(token):
tokens_proc.append(token)
elif is_bracket_close(token):
if tokens_proc:
previous_token = tokens_proc[-1]
# if previus token match with current close token is a correct match
if tokens_match(previous_token, token):
tokens_proc.pop()
brackets_counter += 1
else:
# token doesn't match correctly
return 0
else:
return 0 # token doesn't match correctly
else:
# Without tokens
return 1
return f'1 {brackets_counter}'
if __name__ == "__main__":
# keep this function call here
print(multiple_brackets(input()))
|
99bcb4d92035a96e05b3d38818ddaafac08a9620 | andriidem308/python_practice | /myalgorithms/LinkedListWithCurrent.py | 941 | 3.796875 | 4 | class Node:
def __init__(self, item):
self.item = item
self.next = None
class ListWithCurrent:
def __init__(self):
self.head = None
self.current = None
def empty(self):
return self.head is None
def reset(self):
self.current = self.head
def next(self):
if self.empty():
raise Exception
else:
self.current = self.current.next
def current(self):
if self.empty():
return None
else:
return self.current.item
def insert(self, item):
new_node = Node(item)
if self.empty():
self.head = new_node
self.current = new_node
else:
new_node.next = self.current.next
self.current.next = new_node
def __str__(self):
return str(self.current())
|
76bee081751ea87cb53ecab2da98f7f036498994 | shivansh-max/Algos | /Random/Si.py | 231 | 3.921875 | 4 | money = float(input("MONEY : "))
percent = float(input("PERCENT : "))
years = float(input("YEARS : "))
extra = input("EXTRA : ")
intrest = money * percent * years
if extra == "y":
intrest += money
print(f"INTREST : {intrest}") |
0265aa34c583430466c72b36ceba7be112afa942 | saxenasamarth/BootCamp_PythonLearning | /week7/DS/String/is_rotated.py | 203 | 4.125 | 4 | # Check if a string is rotated version of other
def is_rotated(str1, str2):
new_str = str2+str2
return str1 in new_str
print(is_rotated("hello", "llohe"))
print(is_rotated("hello", "llheo")) |
cf267950ab940292e98fa6a09a3f55254778e8a9 | aakashsharan/Word-Game | /computer.py | 2,950 | 4.21875 | 4 | from play import *
class Computer:
def __init__(self):
self.game = Game()
def comp_choose_word(self, hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand: dictionary (string -> int)
wordList: list (string)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: string or None
"""
# return the best word you found.
max_score_initial = 0
best_score_word = None
for word in wordList:
if self.game.is_valid_word(word, hand, wordList):
this_score = self.game.get_word_score(word, n)
if this_score >= max_score_initial:
max_score_initial = this_score
best_score_word = word
return best_score_word
def comp_play_hand(self, hand, wordList, n):
"""
Allows the computer to play the given hand, following the same procedure
as playHand, except instead of the user choosing a word, the computer
chooses it.
1) The hand is displayed.
2) The computer chooses a word.
3) After every valid word: the word and the score for that word is
displayed, the remaining letters in the hand are displayed, and the
computer chooses another word.
4) The sum of the word scores is displayed when the hand finishes.
5) The hand finishes when the computer has exhausted its possible
choices (i.e. compChooseWord returns None).
hand: dictionary (string -> int)
wordList: list (string)
n: integer (GAME_HAND_SIZE; i.e., hand size required for additional points)
"""
should_break = False
total_points = 0
while self.game.calculate_hand_len(hand) > 0:
print "Current hand: ",
self.game.display_hand(hand)
comp_input = self.comp_choose_word(hand, wordList, n)
if comp_input == None:
should_break = True
break
else:
if not self.game.is_valid_word(comp_input, hand, wordList):
print "Invalid word, please try again."
else:
score = self.game.get_word_score(comp_input, n)
total_points += score
print '"' +str(comp_input) + '"' + " earned " + str(score) + " points. " + "Total: " + str(total_points) + " points."
hand = self.game.update_hand(hand, comp_input)
should_break = True
if should_break:
print "Total score: " + str(total_points) + " points."
|
2b3f6b76fc611dce5703f4c0c10845957ef73bf3 | jayantrane/Blockchain | /Assignment 1/assignment.py | 4,057 | 3.6875 | 4 | #!/usr/bin/python2.7
# -*- coding: latin-1 -*-
import hashlib
import argparse
from datetime import datetime
TARGET_DIFFICULTY = 6 # No of preceding zeros required
# Define Values from arguments passed
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="""
Blockchain Assignment:
Hi There! This is a simple assignment to showcase how Blockchain mining works.
So let's get started!
Lets assume a blockchain for Attendance. Every Block consists of the userid, timestamp and nonce.
So this is a Proof of Work based Blockchain where to get your attendance you need to compute the
nonce such that the hash of the block(it's string representation) meet certain criteria.
In our case the hexadecimal representation of the hash needs to have atleast 6 preceding zeros to pass!
Do note that the timestamp is taken automatically so ensure that you calculate the nonce
for the block that will be created on the day you have to submit the assignment!
For calculating the nonce you can try anything you want. You can manually try different values for nonce
(highly encouraged :P) or write a script to do it for you,
The only thing that matters is that you get the first 6 hex values of the hash to be zero.
The Block string representation is as follows: "Block: ['timestamp':{}, 'userid':{}, 'nonce':{}]"
Timestamp is in the format 'YYYY:MM:DD'
For calculating the hash we use SHA256 algorithm.(https://emn178.github.io/online-tools/sha256.html)
One Solved Example:
For 1st September 2019, Id: 160000000 the nonce is 51383180. Try running:
python mining_assignment.py -id 160000000 -n 51383180 -d 2019:09:01
So your task is to calculate the nonce(a integer value) for your Registration ID
for the given submission date to complete this assignment!
""",
epilog="PS: Extra Credits for those who can exceed the passing criteria! :P",
)
parser.add_argument(
"-id",
"--user-id",
required=True,
type=int,
help="Your Registration ID (ex: 160000000)",
default=16000000,
)
parser.add_argument(
"-n",
"--nonce",
required=True,
type=int,
help="Nonce that you have calculated (has to be a integer)",
default=0,
)
parser.add_argument(
"-d",
"--date",
type=str,
help="Date in the format 'YYYY:MM:DD'",
default=datetime.now().strftime("%Y:%m:%d"),
)
args = parser.parse_args()
class Block:
""" The header of a block """
def __init__(self, timestamp, userid, nonce):
# The user ID of the person creating the block (Format: "1610x00xx")
self.userid = str(userid)
# The approximate creation time of this block (date in format "YYYY:MM:DD")
self.timestamp = str(timestamp)
# The value of nonce
self.nonce = int(nonce)
def __str__(self):
return "Block: ['timestamp':{}, 'userid':{}, 'nonce':{}]".format(
self.timestamp, self.userid, self.nonce
)
def dhash(s):
""" sha256 hash """
if not isinstance(s, str):
s = str(s)
s = s.encode()
return hashlib.sha256(s).hexdigest()
def is_proper_difficulty(target_difficulty, blockhash):
pow = 0
for c in blockhash:
if not c == "0":
break
else:
pow += 1
if pow < target_difficulty:
return False
return True
if __name__ == "__main__":
block = Block(args.date, args.user_id, args.nonce)
print(
hashlib.sha256(
"Block: ['timestamp':2019:09:01, 'userid':160000000, 'nonce':12345678]".encode()
).hexdigest()
)
print(block)
print("Hash:", dhash(block))
if is_proper_difficulty(TARGET_DIFFICULTY + 2, dhash(block)):
print("============= Awesome! Extra marks for extra effort! :P =============")
elif is_proper_difficulty(TARGET_DIFFICULTY, dhash(block)):
print("++++++++++ Assignment Done! ++++++++++")
else:
print("Does not meet criteria, Keep Trying!")
|
91a8e533d59ad6f48158d64598571ef214da8a27 | bema97/home_work | /ch3task_1.py | 259 | 4.09375 | 4 | text=(input('Please, write any text: '))
lower=upper=0
letter=(len(text))
for i in text:
if "a"<=i<="z":
lower +=1
elif "A"<=i<="Z":
upper +=1
print("the letters % is"%(lower/letter*100))
print("the letters % is"%(upper/letter*100)) |
4f7bd81910a56bb39bac7d4cbd366e73778cd59a | lschoe/mpyc | /demos/helloworld.py | 1,718 | 3.59375 | 4 | """Demo Hello World in MPyC.
Example usage from the command line:
python helloworld.py -M3
to run the demo with m=3 parties on localhost.
When run with m parties, a total of m(m-1)/2 TCP connections will be created between
all parties, noting that TCP connections are full-duplex (bidirectional). So there are
no connections when run with m=1 party only, there is one connection for m=2 parties, and
there are three connections for m=3 parties.
With all m parties running on localhost, your OS may run out of available ports for large m,
and the program will therefore not terminate properly. For example, the default range for
dynamic (private) ports on Windows is 49152-65535, which will take you to around m=180 parties,
before exhausting the available ports. The range for dynamic ports can be increased like this,
requiring administrator privileges:
netsh int ipv4 set dynamicport tcp start=16000 num=48000
Now run the demo (as a nice stress test) with m=300, for a total of 44850 TCP connections:
python helloworld.py -M300 -T0
It it essential to use threshold t=0 (or, maybe t=1). Otherwise the time needed to set up the
PRSS (Pseudoranom Secret Sharing) keys, which is proportional to (m choose t) = m!/t!/(m-t)!,
will be prohibitive.
Alternatively, since the PRSS keys are not actually used in this simple demo, the demo can also
be run with PRSS disabled:
python helloworld.py -M300 --no-prss
This way there is no need to lower the threshold t.
"""
from mpyc.runtime import mpc
mpc.run(mpc.start()) # connect to all other parties
print(''.join(mpc.run(mpc.transfer('Hello world!'))))
mpc.run(mpc.shutdown()) # disconnect, but only once all other parties reached this point
|
201ec75cb1b46d92e00633e83a728bc29eef18dc | pritam1997/python-test-4 | /q5.py | 99 | 4 | 4 | s = input("Enter word : ")
r = [x for x in s]
r.reverse()
s=str()
for i in r:
s=s+i
print(s) |
d4c35f4240098ae6e0129c10564792788a8f89e3 | de1iza/splay-tree | /src/splay_tree.py | 4,505 | 3.515625 | 4 | from typing import TypeVar, Generic
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, key: T):
self.left = None
self.right = None
self.key = key
# returns size of subtree
def size(self) -> int:
left_size: int = 0 if self.left is None else self.left.size()
right_size: int = 0 if self.right is None else self.right.size()
return left_size + right_size + 1
# returns height of subtree
def height(self) -> int:
left_height: int = -1 if self.left is None else self.left.height()
right_height: int = -1 if self.right is None else self.right.height()
return max(left_height, right_height) + 1
class SplayTree:
def __init__(self, key: T = None):
if key is None:
self.root = None
else:
self.root = Node(key)
# left rotate helper
def __rotate_left(self, node: Node) -> Node:
tmp_node: Node = node.right
node.right = tmp_node.left
tmp_node.left = node
return tmp_node
# right rotate helper
def __rotate_right(self, node: Node) -> Node:
tmp_node: Node = node.left
node.left = tmp_node.right
tmp_node.right = node
return tmp_node
# splay helper function
def __splay_left(self, root: Node, key: T) -> Node:
if root.left is None:
return root
if key < root.left.key:
root.left.left = self.__splay(root.left.left, key)
root = self.__rotate_right(root)
elif key > root.left.key:
root.left.right = self.__splay(root.left.right, key)
if root.left.right is not None:
root.left = self.__rotate_left(root.left)
if root.left is None:
return root
return self.__rotate_right(root)
# splay helper function
def __splay_right(self, root: Node, key: T) -> Node:
if root.right is None:
return root
if key < root.right.key:
root.right.left = self.__splay(root.right.left, key)
if root.right.left is not None:
root.right = self.__rotate_right(root.right)
elif key > root.right.key:
root.right.right = self.__splay(root.right.right, key)
root = self.__rotate_left(root)
if root.right is None:
return root
return self.__rotate_left(root)
# splay key in the tree where node is a root
def __splay(self, node: Node, key: T) -> Node:
if node is None:
return None
if key < node.key:
return self.__splay_left(node, key)
elif key > node.key:
return self.__splay_right(node, key)
return node
# inserts key.
# if it was in the tree does nothing
def insert(self, key: T) -> None:
if self.root is None:
self.root = Node(key)
return
if self.root.key == key:
return
self.root = self.__splay(self.root, key)
if key < self.root.key:
tmp_node: Node = Node(key)
tmp_node.left = self.root.left
tmp_node.right = self.root
self.root.left = None
self.root = tmp_node
else:
tmp_node: Node = Node(key)
tmp_node.right = self.root.right
tmp_node.left = self.root
self.root.right = None
self.root = tmp_node
# removes key from the tree.
# if key wasn't in the tree does nothing
def remove(self, key: T) -> None:
if self.root is None:
return
self.root = self.__splay(self.root, key)
if key != self.root.key:
return
if self.root.left is None:
self.root = self.root.right
else:
tmp_node: Node = self.root.right
self.root = self.root.left
self.__splay(self.root, key)
self.root.right = tmp_node
# returns True is key is in the tree
def find(self, key: T) -> bool:
if self.root is None:
return False
self.root = self.__splay(self.root, key)
return key == self.root.key
# returns size of the tree
def size(self) -> int:
if self.root is None:
return 0
return self.root.size()
# returns size of the tree (tree with 1 node has 0 height)
def height(self) -> int:
if self.root is None:
return -1
return self.root.height()
|
34b946452942ae1422c21b6f0ac1326a4c4dab83 | RatherBland/homecooked-tools | /osint/email.py | 2,256 | 3.890625 | 4 | import sys, argparse
desc = "Create permutations of possible emails from first and lastname combinations.\n" \
"Example: python3 {} --file names.txt --domain example.com --output results.txt".format(sys.argv[0])
parser = argparse.ArgumentParser(description = desc)
parser.add_argument("--output", "-o", help="File path to output results")
required = parser.add_argument_group('required arguments')
parser.add_argument("--file", "-f", help="File you want to parse names from", required=True)
parser.add_argument("--domain", "-d", help="Email domain that should be appended", required=True)
args = parser.parse_args()
f = open(args.file, "r")
results = []
def generate_emails(name, domain):
if 3 > len(name.split()) > 1:
fnln = name.split()[0] + name.split()[1] + "@" + domain
fnpln = name.split()[0] + "." + name.split()[1] + "@" + domain
fn1c = name.split()[0] + name.split()[1][:1] + "@" + domain
fnp1c = name.split()[0] + "." + name.split()[1][:1] + "@" + domain
fn2c = name.split()[0] + name.split()[1][:2] + "@" + domain
fnp2c = name.split()[0] + "." + name.split()[1][:2] + "@" + domain
fn3c = name.split()[0] + name.split()[1][:3] + "@" + domain
fnp3c = name.split()[0] + "." + name.split()[1][:3] + "@" + domain
fn = name.split()[0] + "@" + domain
flln = name.split()[0][:1] + name.split()[1] + "@" + domain
flpln = name.split()[0][:1] + "." + name.split()[1] + "@" + domain
results.extend([fnln, fnpln, fn1c, fnp1c, fn2c, fnp2c, fn3c, fnp3c, fn, flln, flpln])
if args.output is not None:
store = open(args.output, "a+")
store.write("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n".format(fnln,fnpln,fn1c,fnp1c,fn2c,fnp2c,fn3c,fnp3c,fn,flln,flpln))
store.close()
else:
print(fnln)
print(fnpln)
print(fn1c)
print(fnp1c)
print(fn2c)
print(fnp2c)
print(fn3c)
print(fnp3c)
print(fn)
print(flln)
print(flpln)
for name in f.readlines():
generate_emails(name, args.domain)
print("{} lines output to {}".format(len(results), args.output))
f.close()
|
387be4bb06ac381933e379f80641be9dd994ff5b | linlufeng/LufengLearnPython | /PycharmProjects/lession5/hello1.py | 2,192 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Python 列表(List)
'''
序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组。
序列都可以进行的操作包括索引,切片,加,乘,检查成员。
此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。
'''
# 访问列表中的值
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7]
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
# 更新列表
list = []
list.append('lin')
list.append('lu')
list.append('feng')
print list
list.pop(0)
print list
# 删除列表元素
del list[-1]
print list
'''
Python列表脚本操作符
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。
如下所示:
Python 表达式 结果 描述
len([1, 2, 3]) 3 长度
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 组合
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重复
3 in [1, 2, 3] True 元素是否存在于列表中
for x in [1, 2, 3]: print x, 1 2 3 迭代
'''
list3 = ['a', 'b', 'c']
list4 = ['e', 'f', 'g']
print cmp(list3, list4)
print len(list3)
print max(list3)
print list3.count("c")
print list3.index('b')
list3.insert(1, 'p')
print list3
list3.reverse()
print list3
list3.sort()
print list3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.