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 |
|---|---|---|---|---|---|---|
00eb6a3c3a2fc9cb1f6d6318210ef3a7ff0cad8a | lpyhdzx/jianzhi-offer_python | /栈队列.py | 968 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/6/10 22:35
# @Author : liupeiyu
# @File : 栈队列.py
# 本质上分为两个栈,一个只用来push,但是pop的时候需要分为两部分,如果stack2不空的时候就必须从stack2里pop,只要当stack 空的时候,必须一次性
# 把stack1都放进stack2里,才能保证先进先出,因为后面再push的话都得stack2这一波全空了才能把stack1再第二波再放进来。stack1和stack2在pop的过程中类似于两个part
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self,x):
self.stack1.append(x)
def pop(self):
if self.stack2:
return self.stack2.pop()
else:
while self.stack1:
x = self.stack1.pop()
self.stack2.append(x)
return self.stack2.pop()
solu = Solution()
solu.push(1)
solu.push(2)
print(solu.pop()) |
94049619a7dcbe899ce12d673dd7502a895979d8 | felipearias2024/tp3-AED | /main.py | 8,304 | 3.640625 | 4 | from registro import *
import random
def menu():
print("1- Nuevos por precio")
print("2- Usados por calificación")
print("3- Distribución geográfica")
print("4- Total provincial")
print("5- Precio promedio de usados")
print("6- Compra ideal")
print("7- Comprar")
print("8- Salir")
print("---------------------------")
def validarMayorQue(min):
n = int(input("Ingrese la cantidad de publicaciones a buscar: "))
while n <= min:
print("Error!")
n = int(input("Ingrese una cantidad valida: "))
return n
def crearVector(n):
vec = [None] * n
for i in range(len(vec)):
codigo = random.randint(1, 100000)
precio = round(random.uniform(1, 100000), 2)
ubicacion = random.randint(1, 23)
estado = random.randint(0, 1)
cantidad = random.randint(0, 1000)
puntuacion = random.randint(1, 5)
publicacion = Publicacion(codigo, precio, ubicacion, estado, cantidad, puntuacion)
vec[i] = publicacion
return vec
def validarOpcion(msj, min, max):
opcion = int(input(msj))
while opcion < min or opcion > max:
print("Error!")
opcion = int(input(msj))
return opcion
def nuevosPorPrecio(vec):
v = [ ]
for i in range(len(vec)):
if vec[i].estado == 0:
v.append(vec[i])
return v
def ordenarPorPrecio(vec):
n = len(vec)
for i in range(n-1):
for j in range(i+1, n):
if vec[i].precio > vec[j].precio:
vec[i], vec[j] = vec[j], vec[i]
return vec
def ordenarPorCodigo(vec):
n = len(vec)
for i in range(n-1):
for j in range(i+1, n):
if vec[i].codigo > vec[j].codigo:
vec[i], vec[j] = vec[j], vec[i]
return vec
def usadosPorCalificacion(vec):
cont = [0] * 5
for i in range(len(vec)):
if vec[i].estado == 1:
puntuacion = vec[i].puntuacion
cont[puntuacion-1] += 1
return cont
def precioPromedioUsados(vec):
acu = 0
cont = 0
for i in range(len(vec)):
if vec[i].estado == 1:
acu += vec[i].precio
cont += 1
if cont != 0:
prom = round((acu/cont), 2)
return prom
else:
print("No hay publicaciones usadas")
def precioMayorPromedio(vec, precioprom):
for i in range(len(vec)):
if vec[i].estado == 1 and vec[i].precio > precioprom:
write(vec[i])
def menorPrecio(vec):
menor = None
for i in range(len(vec)):
if vec[i].estado == 0 and vec[i].puntuacion != 1:
if menor is None :
menor = vec[i].precio
elif vec[i].precio < menor:
menor = vec[i].precio
return menor
def buscarPorId(vec, cod):
ban = False
for i in range(len(vec)):
if vec[i].codigo == cod:
ban = True
print("Stock del producto: {0}".format(vec[i].cantidad))
cant = int(input("Ingrese la cantidad que desea comprar: "))
while vec[i].cantidad < cant:
print("No hay stock suficiente")
conf = int(input("¿Desea volver al menu o probar con otro producto?(0=volver al menu, 1=otro producto)"))
if conf == 1:
cod = int(input("Ingrese el codigo de la publicacion a buscar: "))
cant = 0
buscarPorId(vec, cod)
break
elif conf == 0:
return
else:
confirmacion = int(input("¿Desea realizar la compra?(0=si, 1=no)"))
if confirmacion == 0:
print("Gracias por su compra")
vec[i].cantidad -= cant
print("Stock actualizado del producto: {0} ".format(vec[i].cantidad))
else:
return
if ban == False:
print("Publicacion no encontrada")
def crearMatriz(vec):
mat = [[0] * 5 for i in range(23)]
for i in range(len(vec)):
fil = vec[i].ubicacion -1
col = vec[i].puntuacion -1
mat[fil][col] += 1
return mat
def ubicaciones(num, ubic):
return ubic[num]
def puntuacion(num, calif):
return calif[num]
def mostrarMatrizLista(mat, calif, ubic):
ban = False
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] != 0:
if ban == False:
print("---------------------------")
print(ubicaciones(i, ubic))
ban = True
print("\t", puntuacion(j, calif), ":", end=" ")
print(mat[i][j])
ban = False
def mostrarMatriz(mat, ubic, calif):
for f in range(len(mat[0])):
print("{:<4}".format('{:.5}'.format(puntuacion(f, calif))), end= " \t ",)
print( )
print("--------------------------------------------")
for i in range(len(mat)):
for j in range(len(mat[0])):
print("{:<5d}".format(mat[i][j]),end= " \t ",)
print(ubicaciones(i, ubic))
def totalProvincia(mat, index):
acu = 0
for i in range(len(mat[index])):
acu += mat[index][i]
return acu
def linearSearch(ubicaciones, prov):
for i in range(len(ubicaciones)):
if prov == ubicaciones[i]:
return i
def validarProvincia(prov, ubicaciones):
while prov not in ubicaciones:
print("La provincia ingresada no existe!")
prov = input("Ingrese la provincia a buscar(como se encuentra en la lista): ")
return prov
def test():
ban = False
ubicaciones = "Buenos Aires", "Catamarca", "Chaco", "Chubut", "Cordoba", "Corrientes", "Entre Rios", "Formosa", "Jujuy", "La Pampa", "La Rioja", "Mendoza", "Misiones", "Neuquen"\
, "Rio Negro", "Salta", "San Juan", "San Luis", "Santa Cruz", "Santa Fe", "Santiago del Estero", "Tierra del Fuego", "Tucuman"
calificaciones = "Mala", "Regular", "Buena", "Muy buena", "Excelente"
n = validarMayorQue(0)
vec = crearVector(n)
sorted = ordenarPorCodigo(vec)
for i in range(len(sorted)):
write(sorted[i])
opcion = 0
while opcion != 8:
print("---------------------------")
menu()
opcion = validarOpcion("Ingrese una opcion", 1, 8)
if opcion == 1:
v = nuevosPorPrecio(vec)
sorted = ordenarPorPrecio(v)
for i in range(len(sorted)):
write(sorted[i])
if opcion == 2:
cont = usadosPorCalificacion(vec)
for i in range(len(cont)):
print("Cantidad de publicaciones usadas con puntuacion {}: ".format(calificaciones[i]), cont[i])
if opcion == 3:
mat = crearMatriz(vec)
ban = True
forma = int(input("¿Como desea mostrar la matriz?(0: matriz, 1: lista): "))
if forma == 1:
mostrarMatrizLista(mat, calificaciones, ubicaciones)
elif forma == 0:
print("---------------------------")
mostrarMatriz(mat, ubicaciones, calificaciones)
if opcion == 4:
if ban == False:
print("Matriz no creada")
else:
for i in range(len(ubicaciones)):
print(str(i+1)+"-"+ubicaciones[i])
prov = input("Ingrese la provincia a buscar(como se encuentra en la lista): ")
validarProvincia(prov, ubicaciones)
index = linearSearch(ubicaciones, prov)
if index is not None:
tot = totalProvincia(mat, index)
print("El total de articulos de la provincia {}: {}".format(prov, tot))
if opcion == 5:
precioprom = precioPromedioUsados(vec)
print("Precio promedio de productos usados ${}".format(precioprom))
precioMayorPromedio(vec, precioprom)
if opcion == 6:
menor = menorPrecio(vec)
print("El menor precio para un producto de estado nuevo, omitiendo a los vendedores con calificacion mala es de {}: ".format(menor))
if opcion == 7:
cod = int(input("Ingrese el codigo de la publicacion a buscar: "))
buscarPorId(vec, cod)
if __name__ == "__main__":
test()
|
4dc1b42924226603a9d544b73b3d623753707593 | annarider/UdacityCS101 | /Lesson3/L3XQ6.py | 2,204 | 4.1875 | 4 | # Numbers in lists by SeanMc from forums
# define a procedure that takes in a string of numbers from 1-9 and
# outputs a list with the following parameters:
# Every number in the string should be inserted into the list.
# If the first number in the string is greater than or equal
# to the proceeding number, the proceeding number should be inserted
# into a sublist. Continue adding to the sublist until the proceeding number
# is greater than the first number before the sublist.
# Then add this bigger number to the normal list.
#Hint - "int()" turns a string's element into a number
'''
Pseudo code - brainstorm algorithm
create empty list
add first number to list
check proceeding number
if it's smaller than or equal to the first num:
then insert into it's own sub list
else if it's bigger than the first number:
just add it to the list as usual
next number:
if smaller than or equal to the first num:
insert into same list as sublist
else if it's bigger than first num:
just add to list as usual, not into sublist
continue until no more numbers
'''
def numbers_in_lists(string):
firstNum = int(string[0])
nLarge = True
list = [firstNum]
sub = []
i = 1
while i < len(string):
n = int(string[i])
# Proceeding num is smaller or equal to first number in list
# therefore add to list
if n <= firstNum:
sub.append(n)
else:
if sub:
list.append(sub)
list.append(n)
else:
list.append(n)
sub = []
firstNum = n
i += 1
if sub:
list.append(sub)
print list
return list
#testcases
string = '543987'
result = [5,[4,3],9,[8,7]]
print repr(string), numbers_in_lists(string) == result
string= '987654321'
result = [9,[8,7,6,5,4,3,2,1]]
print repr(string), numbers_in_lists(string) == result
string = '455532123266'
result = [4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]]
print repr(string), numbers_in_lists(string) == result
string = '123456789'
result = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print repr(string), numbers_in_lists(string) == result
|
e8a9ac79b5e6ce5c2a10b441b88746ca32753831 | yilverdeja/AI-in-a-row | /3d-tictactoe/player.py | 3,361 | 3.765625 | 4 | import math
import random
class Player():
def __init__(self, letter):
self.letter = letter
def makeMove(self, game):
pass
class HumanPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def makeMove(self, game):
while True:
rowPos = self.getPosition("row")
colPos = self.getPosition("col")
if game.makeMove((rowPos, colPos), self.letter):
return (rowPos, colPos)
else:
print("Must choose an empty position on the board!")
def getPosition(self, posType):
while True:
pos = int(input(posType+" (1-3): "))
if pos >= 1 and pos <= 3:
return pos-1
else:
print("Must choose a position between 1 and 3")
class AIPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def makeMove(self, game):
if game.isBoardEmpty():
# place randomly
pos = random.choice(game.getPotentialMoves())
if game.makeMove(pos, self.letter):
return pos
else:
raise Exception("Something is wrong. You should be able to make a move if the board is empty...")
else:
# minimax
depth = 5
eval = self.minimax(game, depth, -math.inf, math.inf, True)
if game.makeMove(eval["position"], self.letter):
return eval["position"]
else:
raise Exception("Something wrong with minimax output. It should be able to play the move.")
return
# minimax algorithm with alpha beta pruning
def minimax(self, gameState, depth, alpha, beta, isMaximizing):
maxPlayer = self.letter
minPlayer = "X" if maxPlayer == "O" else "O"
if depth == 0 or gameState.winner != None:
if gameState.winner == maxPlayer:
return {"score": 1*(gameState.getNumMovesLeft() + 1), "position": None}
elif gameState.winner == minPlayer:
return {"score": -1*(gameState.getNumMovesLeft() + 1), "position": None}
else:
return {"score": 0, "position": None}
elif gameState.isBoardFull():
# A tie
return {"score": 0, "position": None}
if isMaximizing:
bestPlay = {"score": -math.inf, "position": None}
player = maxPlayer
else:
bestPlay = {"score": math.inf, "position": None}
player = minPlayer
for posChild in gameState.getPotentialMoves():
gameState.makeMove(posChild, player)
eval = self.minimax(gameState, depth-1, alpha, beta, not isMaximizing)
gameState.undoMove(posChild, player)
eval['position'] = posChild
if isMaximizing:
if eval["score"] > bestPlay["score"]:
bestPlay = eval
alpha = max(alpha, eval["score"])
if beta <= alpha:
break
else:
if eval["score"] < bestPlay["score"]:
bestPlay = eval
beta = min(beta, eval["score"])
if beta <= alpha:
break
return bestPlay |
c91c855596a13ad55e55fe2b7bd8747a753ba94e | iuryferreira/python-data-structures | /data_structures/linked_list.py | 1,459 | 4.53125 | 5 | from data_structures.utils.data_structures_visualization import DataStructuresVisualization
class Node:
"""
This class implements the node used by the linked lists.
"""
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
"""
This class implements the Abstract Data Type (TAD'S) Linked List, with it's main operations.
Methods
-------
search(value)
Searches for a node.
search_previous(value)
Fetches the node previous to the one containing the searched value.
insert()
Insert a node.
remove()
Removes a node.
"""
def __init__(self):
self.head = None
def __repr__(self):
return "LinkedList: {0}".format(DataStructuresVisualization.linkedlist(self))
def search(self, value):
node = self.head
while node is not None and node.value != value:
node = node.next
return node
def search_previous(self, value):
node = self.head
while node is not None and node.next.value != value:
node = node.next
return node
def insert(self, node):
node.next = self.head
self.head = node
def remove(self, value):
if value == self.head.value:
self.head = self.head.next
else:
node_prev = self.search_previous(value)
node_prev.next = node_prev.next.next
|
aee5ae50097732ec9eb61b0766f46224a33e3bae | green-fox-academy/ilcsikbalazs | /week-04/day-3/Exercise_2/sum.py | 834 | 4.1875 | 4 | # Create a sum method in your class which has a list of integers as parameter
# It should return the sum of the elements in the list
# Follow these steps:
# Add a new test case
# Instantiate your class
# create a list of integers
# use the assertEquals to test the result of the created sum method
# Run it
# Create different tests where you
# test your method with an empyt list
# with a list with one element in it
# with multiple elements in it
# with a null
# Run them
# Fix your code if needed
class Sum:
def __init__(self):
self.sum_list=[]
def add_number(self,number=None):
if number == None:
return self.sum_list
else:
self.sum_list.append(number)
def return_list(self):
sum = 0
for i in self.sum_list:
sum += i
return sum
|
2c8042946b4e055a91887d7e2c2f6ccfed24fc7c | Walaleitor/Trabajo_TALF | /funciones.py | 5,244 | 3.71875 | 4 | import turtle
def validar(lista):
contador = 0
if len(lista) > 10:
for i in lista:
if i != "0" and i != "1":
contador += 1
if contador > 0:
lista = []
print ("vuelva a ingresar la lista")
return lista
else:
print("la lista se ingreso bien")
return lista
else:
lista = []
print("Ingrese una palabra mayor a 10")
return lista
##Se logro hacer que la lista generara otra lista con la regla exactamente1,
#falta hacer que dibuje muchas mas veces
def regla_exactamente1(lista):
dibujador = []
dibujador2 = []
size = len(lista)
print (lista)
for i in range(50):
for i in range(size):
if i == size -3:
if int(lista[size-3]) + int(lista[size-2]) + int(lista[size-1]) == 1:
dibujador.append(1)
else:
dibujador.append(0)
elif i == size -2:
if int(lista[size-2]) + int(lista[size-1]) + int(lista[0]) == 1:
dibujador.append(1)
else:
dibujador.append(0)
elif i == size -1:
if int(lista[-1]) + int(lista[0]) + int(lista[1]) == 1:
dibujador.append(1)
else:
dibujador.append(0)
else:
if int(lista[i]) + int(lista[i+1]) + int(lista[i+2]) == 1:
dibujador.append(1)
else:
dibujador.append(0)
print(dibujador)
dibujador2.append(dibujador)
lista = dibujador
dibujador = []
dibujar_turtle(dibujador2)
def regla_110(lista):
dibujador = []
dibujador2 = []
size = len(lista)
print (lista)
for i in range(50):
for i in range(size):
if i == size -3:
if int(lista[size-3]) + int(lista[size-2]) + int(lista[size-1]) == 2:
dibujador.append(1)
elif int(lista[size-3]) + int(lista[size-2]) + int(lista[size-1]) == 1:
if lista[i] == "1":
dibujador.append(0)
else:
dibujador.append(1)
else:
dibujador.append(0)
elif i == size -2:
if int(lista[size-2]) + int(lista[size-1]) + int(lista[0]) == 2:
dibujador.append(1)
elif int(lista[size-2]) + int(lista[size-1]) + int(lista[0]) == 1:
if lista[i] == "1":
dibujador.append(0)
else:
dibujador.append(1)
else:
dibujador.append(0)
elif i == size -1:
if int(lista[-1]) + int(lista[0]) + int(lista[1]) == 2:
dibujador.append(1)
elif int(lista[-1]) + int(lista[0]) + int(lista[1]) == 1:
if lista[i] == "1":
dibujador.append(0)
else:
dibujador.append(1)
else:
dibujador.append(0)
else:
if int(lista[i]) + int(lista[i+1]) + int(lista[i+2]) == 2:
dibujador.append(1)
elif int(lista[i]) + int(lista[i+1]) + int(lista[i+2]) == 1:
if lista[i] == "1":
dibujador.append(0)
else:
dibujador.append(1)
else:
dibujador.append(0)
print(dibujador)
dibujador2.append(dibujador)
dibujar_turtle(dibujador2)
lista = dibujador
dibujador = []
def dibujar_turtle(Lista):
anchodelapiz = 3
contador_filas = 0
rango_fila = range(len(Lista[0]))
#instanciando largo y ancho y velosidad del trasador
turtle.screensize(5000, 5000, "white")
turtle.tracer(0, 0)
turtle.resizemode("auto")
#crea objeto ventana para facilitar su uso
ventana = turtle.Screen()
ventana.bgcolor("lightgreen")
ventana.title("Automata Celular - Regla exactamente 1")
#crea el lapiz
lapiz = turtle.Turtle()
lapiz.color("blue")
lapiz.pensize(anchodelapiz)
lapiz.hideturtle()
lapiz.speed(0)
#Dos for anidados que divida las listas en sus elementos mas pequeños
for fila in Lista:
for i in rango_fila:
if fila[i] == 1:
#Si el caracter es 1 , escribe una cantidad x pixeles hacia la derecha
lapiz.fd(anchodelapiz)
print(lapiz.pos())
else:
#En el caso que el caracter es 0, el lapiz se sube y se mueve una cantidad x de pixeles para luego se rbajado
lapiz.penup()
lapiz.fd(anchodelapiz)
lapiz.pendown()
print(lapiz.pos())
#Una vez finalizado el dibujo de una linea, el lapiz vuelve a la posicion inicial pero x pixeles mas abajo
contador_filas += -anchodelapiz
lapiz.penup()
lapiz.goto(0,contador_filas)
lapiz.pendown()
|
d8ad1ee7030d5ce5ce93553b0dece0b45988bf6f | KoryHunter37/code-mastery | /python/leetcode/merge-two-sorted-lists/solution.py | 973 | 3.9375 | 4 | # https://leetcode.com/problems/merge-two-sorted-lists/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
l3 = None
root = []
while l1 is not None or l2 is not None:
best = None
if l1 is not None and l2 is None:
best = l1
l1 = l1.next
elif l1 is None and l2 is not None:
best = l2
l2 = l2.next
elif l1.val <= l2.val:
best = l1
l1 = l1.next
else:
best = l2
l2 = l2.next
if l3 is None:
l3 = best
root = l3
else:
l3.next = best
l3 = l3.next
return root
|
d9f957dcd80b69a877f7a829a9b89c0eef929f79 | julianaklulo/URI | /1019.py | 161 | 3.515625 | 4 | n = int(input())
horas = n / 3600
resto = n % 3600
minutos = resto / 60
resto = resto % 60
segundos = resto
print("%d:%d:%d" % (horas, minutos, segundos))
|
36211c09ade64910443f1f3ca40e2a81ec2709a0 | MMMclaughlin/Uno-Card-game | /user_interface.py | 5,002 | 4.34375 | 4 | #!/usr/bin/env python3
def say_welcome():
"""print welcome information"""
print_message("Welcome to Switch v1.1")
def print_game_menu():
"""tell user of the menu options"""
print("\nPlease select from one of the following options: [1-2]")
print("1 - New Game")
print("2 - Exit")
def print_player_info(player, top_card, hands):
"""Prints the info of the current players turn such as his/her hand
--Parameters:
Current player, the top card of the discard pile, each players hands sizes
"""
print("\nHANDS: " + str(hands))
print("PLAYER: " + player.name)
if not player.is_ai:
print('HAND: ' + ', '.join(str(card) for card in player.hand))
print('TOP CARD: ' + str(top_card))
def print_discard_result(discarded, card):
"""This outputs the information of which card was discarded and allow them to track the games history
Parameters:
Boolean if the card was able to be discarded
The card being discarded
"""
if discarded:
print("Discarded: " + str(card) + "\n")
else:
print("Unable to discard card: " + str(card))
def print_winner_of_game(player):
"""print winner information
--Parameters
Winning player
"""
print_message('\n'+80*'-')
print_message("Woohoo!!! Winner of the game is: " + player.name)
print_message(80*'-')
def say_goodbye():
"""say goodbye to my little friend"""
print_message("Goodbye!")
def print_message(msg):
"""takes an argument and outputs it
Parameters:
Any printable object to be output to the Player.
"""
print(msg)
# helper method for get_int_input method
def convert_to_int(string):
"""converts string to int
--parameters: takes a string
--returns the given string if possible as an integer or -1 to represent failure to do so
"""
result = -1
try:
result = int(string)
except Exception:
pass
return result
# methods get information from user
def get_int_input(min, max):
"""get int value from user
--parameters: takes a minimum integer and a maximum integer
if the given value is not less than maximum and greater than minimum or is not an integer we ask for an int again.
--returns:
the given integer value the user gives
"""
choice = -1
while choice < min or choice > max:
print("> ", end="")
choice = convert_to_int(input())
if choice < min or choice > max:
print(f"Try again: Input should be an integer between [{min:d}-{max:d}]")
return choice
def get_string_input():
"""get word from user
--returns:
the string a user gives"""
print("> ", end="")
s = input()
return s
def get_player_information(MAX_PLAYERS):
"""get player information
Parameters:
Max platers the game can take
Returns:
A list of player names
"""
import random
from players import Player, SimpleAI, SmartAI
# create players list
players = []
# how many human players?
print("\nHow many human players [1-4]:")
no_of_players = get_int_input(1, MAX_PLAYERS)
# for each player, get name
for i in range(no_of_players):
print("Please enter the name of player " + str(i + 1) + ":")
players.append(Player(get_string_input()))
ai_names = ['Angela', 'Bart', 'Charly']
# how many AI players? ensure there are at least 2 players
min = 1 if (len(players) == 1) else 0
max = MAX_PLAYERS - no_of_players
if not no_of_players==MAX_PLAYERS:
print(f"\nHow many ai players [{min:d}-{max:d}]:")
no_of_players = get_int_input(min, max)
# for each ai player, get name
for name in ai_names[:no_of_players]:
if random.choice([True, False]):
players.append(SimpleAI(name))
else:
players.append(SmartAI("Smart "+name))
return players
def select_card(cards):
"""select card from hand
parameters:
A list of cards the player is able to discard to fit the top card.
Returns:
A the card the user has chosen to discard
"""
print(f"Please select from one of the following cards: [1-{len(cards):d}]")
for i, card in enumerate(cards, 1):
print(str(i) + " - " + str(card))
# get choice
choice = get_int_input(0, len(cards))
# get card
if choice == 0:
return None
return cards[choice - 1]
def select_player(players):
"""select other player
Parameters:
The players in the game
Returns:
The chosen player
"""
print(f"Please select from one of the following players: [1-{len(players):d}]")
# print out for each player in players
for i in range(len(players)):
p = players[i]
print(f"{i + 1:d} - {p.name}={len(p.hand):d}")
# get choice
choice = get_int_input(1, len(players))
# get player
return players[choice - 1]
|
028ae51cbe20469ec011fcea3634b310fd3d7c9b | KurinchiMalar/DataStructures | /LinkedLists/BasicCircularLinkedListOperations.py | 5,257 | 3.890625 | 4 | __author__ = 'kurnagar'
import copy
import CircListNode
class CircList:
def __init__(self,head):
self.head = head
#self.head.set_next(self.head)
# Time Complexity : O(n)
def insert_at_beginning(self,data):
newnode = CircListNode.CircListNode(data)
if self.head == None:
return None
newnode.set_next(self.head.get_next())
current = self.head
while current.get_next() != self.head: # beginning.
current = current.get_next()
current.set_next(newnode)
self.head = newnode
# Time Complexity : O(n)
def insert_at_end(self,data):
if self.head == None:
return None
newnode = CircListNode.CircListNode(data)
if self.head.get_next() == self.head: # only one node
newnode.set_next(self.head)
self.head.set_next(newnode)
else:
current = self.head
while current.get_next() != self.head: # end
current = current.get_next()
current.set_next(newnode)
newnode.set_next(self.head)
# Time Complexity : O(n)
def insert_at_pos(self,pos,data):
newnode = CircListNode.CircListNode(data)
if self.head == None:
return None
if pos == 0:
self.insert_at_beginning(data)
else:
prev = None
current = self.head
count = 0
while current.get_next() != self.head:
prev = current
current = current.get_next()
count = count + 1
if count == pos:
prev.set_next(newnode)
newnode.set_next(current)
break
# Time Complexity : O(n)
def delete_at_beginning(self):
if self.head == None:
return None
current = self.head
while current.get_next() != self.head: # beginning.
current = current.get_next()
current.set_next(self.head.get_next())
self.head = self.head.get_next()
return True
# Time Complexity : O(n)
def delete_at_pos(self,pos):
if self.head == None:
return False
if pos == 0:
self.delete_at_beginning()
elif pos >= self.get_length_of_list():
return False
else:
prev = self.head
current = self.head.get_next()
count = 1
while current != self.head:
if count == pos:
prev.set_next(current.get_next())
break
prev = current
current = current.get_next()
count = count + 1
return True
# Time Complexity : O(n) Worst case
def search_data(self,data):
if self.head == None:
return False
if self.head.get_data() == data:
return True
current = self.head.get_next()
while current != self.head:
if current.get_data() == data:
return True
current = current.get_next()
return False
# Time Complexity : O(n)
def traverse_list(self):
current = self.head
count = 0
while current.get_next() != self.head:
print current.get_data(),
count = count + 1
current = current.get_next()
print current.get_data(),
print
return count+1
# Time Complexity : O(n)
def get_length_of_list(self):
current = self.head
count = 0
while current.get_next() != self.head:
count = count + 1
current = current.get_next()
return count+1
head = CircListNode.CircListNode(1)
#print CircListNode.CircListNode.__str__(head)
n1 = CircListNode.CircListNode(2)
n2 = CircListNode.CircListNode(3)
n3 = CircListNode.CircListNode(4)
n4 = CircListNode.CircListNode(5)
n5 = CircListNode.CircListNode(6)
n6 = CircListNode.CircListNode(7)
#orig_head = CircListNode.CircListNode(1)
#orig_head.set_next(n1)
head.set_next(n1)
n1.set_next(n2)
n2.set_next(n3)
n3.set_next(n4)
n4.set_next(n5)
n5.set_next(n6)
n6.set_next(head) # making it circular
clist = CircList(head) # initialize head and tail.
orig_clist = copy.deepcopy(clist)
length = clist.traverse_list()
#print ""+str(clist.get_length_of_list())
print "Length of orig list: "+ str(length)
print "----------------------------"
clist = copy.deepcopy(orig_clist)
clist.insert_at_beginning(9)
print "insert begin done. length: "+str(clist.traverse_list())
clist = copy.deepcopy(orig_clist)
clist.insert_at_end(9)
print "insert end done. length: "+str(clist.traverse_list())
clist = copy.deepcopy(orig_clist)
clist.insert_at_pos(1,77)
print "insert at pos done. length: "+str(clist.traverse_list())
print "----------------------------"
clist = copy.deepcopy(orig_clist)
print "List is . length: "+str(clist.traverse_list())
print "isFound: "+str(clist.search_data(7))
print "----------------------------"
clist = copy.deepcopy(orig_clist)
print "Deletion status:"+str(clist.delete_at_pos(7))
print "Deleted List is . length: "+str(clist.traverse_list())
print "----------------------------"
|
b920f4149dd5ca1bdadc85c6c698a72cdf01da5b | jsmith1610/FileBasedDatabase | /parks2.py | 21,490 | 3.953125 | 4 | #Python database project
#AnElizabeth Henry & Jacob Smith
import csv
import os.path
import re
import sys
from pathlib import Path
import configparser
record_size = 152
def main():
DbCheck = False #this is a boolean varible that checks if a database is open or not
DbNOTOPEN = True #this boolean is variable that is strictly for preventing the creation of new database while one is currenlty open
DbCREATED = False
loop = True
while loop:
menu_options()
choice = input("\nYour response here: ")
if choice == '1':
if(DbNOTOPEN): #if the user chooses the 1 menu option
file = input ("\nEnter in the database prefix you would like to create: ") #Prompt the user to say what file they are looking for
filename = file + '.csv'
print("You are creating a database called " + file)
creatDB(filename)
DbCREATED = True
else:
print("A Database is currently open. Close it to create another one.")
elif choice == '2':
if(DbCREATED): #if the user chooses the 2 menu option
DbCheck = True
DbNOTOPEN = False
print("You have picked option 2: Open database")
file = input("Please enter the prefix of a file you are wanting to open: ")
if not os.path.isfile(file + ".data" and file + ".config"):
print(file,"not found.")
exit() #NEEDS TO BE WORKED ON TO NOT EXIT THE PROGRAM
else:
print("data base is " + file + ".data and " + file + ".config found")
dfile = file + '.data' #save the file name with.data to dfile
cfile = file + '.config' #save the file name with .config to cfile
data = openCloseDB(dfile, 'open') #save the return files variable to data variable
config = openCloseDB(cfile, 'open') #save the return files variable to config varaible
if data == 'opened': #if data equals to opened
dataStore('.data',data)
else: #else meaning if config equals opened
dataStore('.data',data)
if config == 'closed': #if config equals closed
dataStore('.config',config)
else: #else meaning if config equals opened
dataStore('.config',config)
else:
print("No Database has been created or is currently open!")
elif choice == '3': #if the user chooses the 3 menu option
if(DbCheck):
print("Option 3")
file = input('Please enter the file perfix you are wanting to close: ')
end = input('Please enter either .data or .config on which you would like to close: ')
if end == '.data': #if the end from the user's input == .data
f = file + '.data' #make variabel F = file.data
data = openCloseDB(f,'close') #opens the function openClosedDB to close the certain .data file
dataStore('.data', data)
DbNOTOPEN = False
DbCheck = False
DbCREATED = False
elif end == '.config': #if the end from the user's input == .config
c = file + '.config' #make the variable C = file.config
config = openCloseDB(c, 'close') #opens the function openCloseDB to close the certain .config file
dataStore('.config', config)
DbNOTOPEN = False
DbCheck = False
DbCREATED = False
else:
print('Sorry that is not a file..') #if the file isn't available then print the statement
else:
print("No Database is currently open")
elif choice == '4': #if the user chooses the 4 menu option
if(DbCheck):
print("Option 4")
f = open("Parks.data", 'r')
print("\n------------- Running ID Search ------------\n")
ID = input ("\n Enter the ID for the Record you would like to pull up: ")
Record, Middle = binarySearch(f, ID)
if Record != -1:
print("ID ",ID,"found at Record",Middle)
print("Record", middle,":", Record,"\n")
else:
print("ID",ID,"not found in our records\n")
else:
print("No Database is currently open")
elif choice == '5': #if the user chooses the 5 menu option
if(DbCheck):
print("Option 5")
print("\n\n------------- Testing Update ------------\n\n")
update()
else:
print("No Database is currently open")
elif choice == '6': #if the user chooses the 6 menu option
if(DbCheck):
print("Option 6")
with open('Parks.data', 'r') as parkData: #opens the parks.data file
count = 0 #sets the count to 0
for line in parkData: #for loop that will loop through the lines in parkData
count += 1 #adds one to the value of count during every loop
if count %2 == 1: #if count module 2 equals 1
print (line) #print the line then it will skip the blanks because they will equal 0
if count == 20: #if the count equals 20 then break because we will have the 10 records we want.
break
else:
print("No Database is currently open")
elif choice == '7': #if the user chooses the 7 menu option
if(DbCheck):
print("Option 7")
insert()
else:
print("No Database is currently open")
elif choice == '8': #if the user chooses the 8 menu option
if(DbCheck):
print("Option 8")
delete()
else:
print("No Database is currently open")
elif choice == '9':
print('You are exiting the program.. Good Bye!')
loop = False
else: #if the user chooses a number that isn't a menu option
print("sorry that wasn't an option.. Good Bye!")
loop = False
exit()
def dataStore(filename, store):
if filename == '.data':
print(store)
elif filename == '.config':
print(store)
else:
print('sorry this file isn\'t in our system')
def menu_options():
#menu of operations
print("\nPlease pick on of the following to continue: ")
#1.create new database
print("1. Create new database")
#2. Open database
print("2. Open database")
#3.close database
print("3. Close database")
#4.display record
print("4. Display record")
#5.update record
print("5. Update record")
#6.create report
print("6. Create report")
#7.add a record
print("7. Add a record")
#8.delete a record
print("8. Delete a record")
print("9: exit")
def update():
ID = input('What is the ID of the record you would like to update? ')
f = open("Parks.data", 'r+')
Record, Middle = binarySearch(f, ID)
if Record != -1:
print("ID ",ID,"found at Record",Middle)
print("Record", middle,":", Record,"\n")
print('What is field would you like to update?')
print('1. Region')
print('2. State')
print('3. Code')
print('4. Visitors')
print('5. Type')
print('6. Name')
command = input('Enter in the number that corresponds with the field you want to update: ')
global State
global Region
global Type
global Name
global Code
global Visitors
f.seek(record_size * middle)
field = Record.split()
ID = field[0]
Region = field[1]
State = field[2]
Code = field[3]
Visitors = field[4]
Type = field[5]
Name = field[6]
if command == '1':
print('Region')
new = input('What are you wanting to change it to? ')
total = len(new)
if total > 2:
new =new[0:2]
Region = Region.replace(Region,new)
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37s} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors), file=f)
elif command == '2':
print('State')
new = input('What are you wanting to change it to? ')
total = len(new)
if total > 2:
new =new[0:2]
State = State.replace(State,new)
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37s} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors), file=f)
elif command == '3':
print('Code')
new = input('What are you wanting to change it to? ')
total = len(new)
if total > 4:
new =new[0:4]
Code = Code.replace(Code,new)
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37s} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors), file=f)
elif command == '4':
print('Visitors')
new = input('What are you wanting to change it to? ')
new =new.replace(' ','_')
total = len(new)
if total > 10:
new =new[0:10]
Visitors = Visitors.replace(Visitors,new)
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37s} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors), file=f)
elif command == '5':
print('Type')
new = input('What are you wanting to change it to? ')
new =new.replace(' ','_')
total = len(new)
if total > 37:
new =new[0:37]
Type = Type.replace(Type,new)
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37s} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors), file=f)
elif command == '6':
print('Name')
new = input('What are you wanting to change it to? ')
new =new.replace(' ','_')
total = len(new)
if total > 83:
new =new[0:83]
Name = Name.replace(Name,new)
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37s} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors), file=f)
else:
print('Sorry that is not an option!')
def creatDB(filename):
rec_total = 0
blank = 0
if not os.path.isfile(filename): #checks to see if the filename that the user typed in is real or not
print(filename,"not found")
exit() #exits the program if the file doesn't exist
else:
parksCsv = open(filename, 'r') #opens the parks.csv file in read mode
datafile = open('Parks.data', 'w+') #opens/creates a new file called parks.data in append/read mode
configfile = open('Parks.config','w') #opens/creates a new file called parks.config in writing/read mode
reader = csv.reader(parksCsv,delimiter=',') #reads in the parks.csv file to
fields = next(reader) #skips the first line and set that line as the fields
for fields in reader: #loop through the csv file
#sets the fields to their corresponding row
ID = fields[0]
Region = fields[1]
State = fields[2]
Code = fields[3]
Name = fields[4]
Type = fields[5]
Visitors = fields[6]
Name = Name.replace(" ","_")
Type = Type.replace(" ", "_")
#This prints the fields in fixed lengths
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors),file=datafile)
#prints the blank line inbetween every row in the data file
print('xxxxxxx xx xx xxxx xxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ,file=datafile)
blank = blank + 1
rec_total = rec_total + 1 #keeping track of the total number of records in the file
total = rec_total + blank
config = configparser.ConfigParser() #sets Config to the config parser library
config.add_section('Records') #adds a section to the config file called Records
config.set('Records','num_records',str(total)) #adds to the settings Records the variable num_records and sets that to the total which is converted to string
config.set('Records','record_size','152') #adds to the settings Records the variable record_size and sets that to 152
config.write(configfile) #sys.stdout #opens the configfile in write mode so that it can write the config settings
configfile.close() #closes the config file
def openCloseDB(file,command):
global dataf
global num_records
dataf = open(file,'r') #opening the file in read mode and saving it to dataf
openClose = command
if command == 'open': #if the command equals open
files = 'opened' #sets the file as opened so it can be returned once the function is completed
if file == 'Parks.config': #if the file is Parks.config
readConfig = configparser.ConfigParser() #sets readConfig to the config parser library
readConfig.read_file(dataf) #reads the park.config file
num_records = readConfig.getint("Records","num_records") #sets num_records to the int thats in section Records which is storing the num_records
record_size = readConfig.getint("Records","record_size") #sets record_size to the int thats in section Records which is storing the record_size
dataf.close() # closed the config file
files = 'closed' #sets the file as closed so it can be returned once the function is completed
else:
files = 'opened' #sets the file as opened so it can be returned once the function is completed
elif command == 'close':
dataf.close() #Close the file
files = 'closed' #sets the file as closed so it can be returned once the function is completed
return files #return the variable files
def insert():
global State
global Region
global Type
global Name
global Code
global Visitors
newRecordID = input('What is the ID number: ')
f = open("Parks.data", 'r+')
Record, Middle = binarySearch(f, newRecordID)
if Record != -1:
print("ID",newRecord,"Already exists\n")
else:
newRegion = input('What is the Region ')
regionTotal = len(newRegion)
if regionTotal > 2:
newRegion = newRegion[0:2]
newState = input('What is the State ')
stateTotal = len(newState)
if stateTotal > 2:
newState = newState[0:2]
newCode = input('What is the Code ')
codeTotal = len(newCode)
if codeTotal > 4:
newCode = newCode[0:4]
newVisitors = input('What is the Visitors ')
stateTotal = len(newVisitors)
if stateTotal > 10:
newVisitors = newVisitors[0:10]
newType = input('What is the Type ')
typeTotal = len(newType)
if typeTotal > 37:
newType = newType[0:37]
newName = input('What is the Name ')
nameTotal = len(newName)
if nameTotal > 83:
newName = newName[0:83]
newRecord = newRecordID +' ' + newRegion +' ' + newState + ' ' + newCode +' ' + newVisitors +' ' + newType +' ' + newName
field = newRecord.split()
ID = field[0]
Region = field[1]
State = field[2]
Code = field[3]
Visitors = field[4]
Type = field[5]
Name = field[6]
print("Record Inserted")
f.seek(record_size* (middle-1))
Region = Region.replace(Region,newRegion)
State = State.replace(State,newState)
Code = Code.replace(Code,newCode)
Visitors = Visitors.replace(Visitors,newVisitors)
Type = Type.replace(Type,newType)
Name = Name.replace(Name,newName)
print('{0:7s} {1:2s} {2:2s} {3:4s} {6:10s} {5:37s} {4:83s}'.format(ID, Region,State,Code,Name,Type,Visitors), file=f)
def delete():
ID = input('What is the ID of the record you would like to delete? ')
f = open("Parks.data", 'r+')
Record, Middle = binarySearch(f, ID)
if Record != -1:
print("Deleted Record")
f.seek(record_size* middle)
f.write('xxxxxxx xx xx xxxx xxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
f.close()
else:
print("ID",ID,"not found in our records\n")
# Get record number n (Records numbered from 0 to NUM_RECORDS-1)
def getRecord(f, recordNum):
record = ""
global num_records
global record_size
num_records = 748
Success = False
if recordNum >= 0 and recordNum < num_records:
f.seek(0,0)
f.seek(record_size * recordNum) #offset from the beginning of the file
record = f.readline()
Success = True
return " ".join(record.split()), Success
def binarySearch(f, name):
global middle
global record_size,num_records
count = 0
low = 0
num_records = 748
high=num_records-1
Found = False
Success = False
while not Found and high >= low and count != 12:
middle = (low+high) // 2
record, Success = getRecord(f, middle)
middleid = record.split()
if(middleid[0] == 'xxxxxxx' and num_records == middle+2):
return -1, middle
middleidnum = middleid[0]
while middleidnum == 'xxxxxxx':
middle += 1
count += 1
record, Success = getRecord(f, middle)
middleid = record.split()
middleidnum = middleid[0]
if count == 12:
return -1, middle
if middleidnum == name:
Found = True
print("Found")
if int(middleidnum) < int(name):
low = middle+1
if int(middleidnum) > int(name):
high = middle-1
if(Found == True):
return record, middle # the record number of the record
else:
return -1, middle
main() #runs the program all together
|
7bad9ee6a4667dfd408be284a35a2faed54a170f | dimastark/crypto-tasks | /1. shamir/main.py | 1,596 | 4 | 4 | from itertools import cycle
def main():
message = input('Сообщение для передачи: ')
# Алиса выбирает ключ шифрования - a
a_key = input('Ключ шифрования Aлисы: ')
# Алиса шифрует сообщение - E(a, M)
message = encrypt(a_key, message)
print('E(a, M): "{}"'.format(message))
# Боб выбирает ключ шифрования - b
b_key = input('Ключ шифрования Боба: ')
# Боб шифрует сообщение - E(b, E(a, M))
message = encrypt(b_key, message)
print('E(b, E(a, M)): "{}"'.format(message))
# Алиса - вычисляет D(a, E(b, E(a, M)))
message = decrypt(a_key, message)
print('D(a, E(b, E(a, M))): "{}"'.format(message))
# Боб - вычисляет D(b, D(a, E(b, E(a, M)))) и получает исходное сообщение
message = decrypt(b_key, message)
print('D(b, D(a, E(b, E(a, M)))): "{}"'.format(message))
def encrypt(key: str, m: str) -> str:
""" Шифр Виженера. Функция шифрования. """
result = ''
for char, key_char in zip(m, cycle(key)):
result += chr((ord(char) + ord(key_char)) % 2048)
return result
def decrypt(key: str, c: str) -> str:
""" Шифр Виженера. Функция расшифрования. """
result = ''
for char, key_char in zip(c, cycle(key)):
result += chr((ord(char) - ord(key_char) + 2048) % 2048)
return result
if __name__ == '__main__':
main()
|
ff694e07b8492aaf78ca2f0a11419178d66a2f53 | brakmic-aleksandar/coding-problems | /5.py | 913 | 4.25 | 4 | """
Challenge
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
Implement car and cdr."""
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
""" Pair is actually function generated by cons function
that takes as parameter another function with same parameters as cons,
this function implements function that returns pair functions first parameter and returns its value."""
def first(a, b):
return a
return pair(first)
def cdr(pair):
""" Same as above just for second value."""
def second(a, b):
return b
return pair(second)
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4
|
fcdb8c712a64d01d9fed946bcab573d5531cdff0 | aapetukhova/alfeya | /подготовка к кр/1.py | 894 | 3.515625 | 4 | ##на швили
##на дзе
##во сколько раз -дзе > -швили
import re
#чтение файла
def page(filename):
with open( filename, encoding='utf-8') as f:
lines = f.readlines()
return lines
#счет необходимого
def count( regex, links):
n = 0
for link in links:
r = re.search( regex, link)
if r:
n+=1
return n
def comparing(a, b):
t = a/b
print(t)
return t
def main():
file = page('short.html')
sh = count('<a href.+?>[А-Я].+? [А-Я].+? [А-Я].+?швили</a>', file)
dze = count('<a href.+?>[А-Я].+? [А-Я].+? [А-Я].+?дзе</a>', file)
comparing(dze, sh)
if __name__ == '__main__':
main()
##имя/фамилия/отчество
##^[А-Я].? [А-Я].? [А-Я].?
##
##ссылка
##<a href.+?>[А-Я].+? [А-Я].+? [А-Я].+?</a>
|
f58b1d35ad93c6b9368eeb37580f82e2a2451bc6 | leviroseb/Algoritmos-de-ordenamiento | /Python/SelectionSort.py | 390 | 4.0625 | 4 | #Selection Sort
def selectionSort(lista):
n = len(lista)
for i in range(0,n-1,1):
menor = i
for j in range(i+1,n,1):
if lista[j] < lista[menor]:
menor = j
temp = lista[menor]
lista[menor] = lista[i]
lista[i]=temp
lista = [36, 71, 16, 21, 73, 9, 0, 40, 66, 5]
selectionSort(lista)
print "Lista ordenada:"
print lista, "\n"
|
8298e34c85b9d6b9f1e16325bd8ee389411d5eed | Deepkumarbhakat/Python-Repo | /dictionary3.py | 242 | 3.734375 | 4 | # Below are the two lists convert it into the dictionary
# keys = ['Ten', 'Twenty', 'Thirty']
# values = [10, 20, 30]
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
dic={}
dic['Ten']=10
dic['Twenty']=20
dic['Thirty']=30
print(dic)
|
6bd33b4e2fa05f00a6a671f23250f04aa2d087b1 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/anagram/8886004077034aa4a0f51b9581f5a586.py | 676 | 4.25 | 4 | # words A and B are anagrams of each other iff each can be rearranged into the other. Equivalently, each can be rearranged into the same string. We can use Python's sort function to do this.
def string_to_list(string):
return [letter for letter in string]
def are_anagrams(first, second):
this=string_to_list(first.lower())
that=string_to_list(second.lower())
this.sort()
that.sort()
if this == that and (first.lower() != second.lower()):
return True
else:
return False
def detect_anagrams(word, candidates):
temp=[]
for candidate in candidates:
first=word
second=candidate
if are_anagrams(first, second) == True:
temp.append(candidate)
return temp
|
e1528d2ab971e0b953a524b60d4d2055e5f906a8 | kuzukawakonayuki/python_scripts | /script/py/騒音判定.py | 486 | 3.71875 | 4 | #coding: UTF-8
#式:(x-a)^2+(y-b)^2=>r^2
list1 = raw_input()
list2 = list1.split(" ")
a1 = int(list2[0])
b1 = int(list2[1])
r1 = int(list2[2])
N = int(raw_input())
roop = 0
while N > roop:
roop += 1
list3 = raw_input()
list4 = list3.split(" ")
x1 = int(list4[0])
y1 = int(list4[1])
ans1 = (x1-a1)**2
ans2 = (y1-b1)**2
ans = ans1 + ans2
r = r1**2
if ans < r:
print "noisy"
else:
print "silent"
|
e894975a793ea43d1a9c3a745d91be13506953d9 | weak-head/leetcode | /leetcode/p1165_single_row_keyboard.py | 333 | 3.625 | 4 | def calculateTime(keyboard: str, word: str) -> int:
"""
Time: O(n)
Space: O(1)
n - length of the word
"""
m = {key: ix for ix, key in enumerate(keyboard)} # O(1)
total = 0
prev = 0
for char in word:
loc = m[char]
total += abs(loc - prev)
prev = loc
return total
|
b0598dfb5b9752aef0dcc1309d723f84c7e34378 | osama-mohamed/python_projects | /algorithmes/merge_sort.py | 1,108 | 4.0625 | 4 | def merge_sort(array):
if len(array) > 1:
middle = len(array) // 2
left = merge_sort(array[:middle])
right = merge_sort(array[middle:])
i, j, array = 0, 0, []
while i < len(left) and j < len(right):
if left[i] < right[j]:
array.append(left[i])
i += 1
else:
array.append(right[j])
j += 1
array.extend(left[i:])
array.extend(right[j:])
return array
return array
data = [10, 8, 2, 5, 6, 7, 4, 3, 1, 9]
print(merge_sort(data))
def merge_sort(array):
if len(array) > 1:
middle = len(array) // 2
left = array[:middle]
right = array[middle:]
merge_sort(left)
merge_sort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
array[k] = left[i]
i += 1
else:
array[k] = right[j]
j += 1
k += 1
while i < len(left):
array[k] = left[i]
i += 1
k += 1
while j < len(right):
array[k] = right[j]
j += 1
k += 1
return array
data = [10, 8, 2, 5, 6, 7, 4, 3, 1, 9]
print(merge_sort(data)) |
84cd5cd59f5771733ab314d4197a3ddb9ed47670 | Nikhilskaria/python | /flow controls/decision making/secondlargest.py | 365 | 4.21875 | 4 | num1=int(input("enter a number"))
num2=int(input("enter a number"))
num3=int(input("enter a number"))
if(num1>num2&num1<num3)|(num1>num3&num1<num2):
print(num1, "is 2nd largest")
elif(num2>num3&num2<num3)|(num2>num1&num2<num3):
print(num2, "is 2nd largest")
elif(num1==num2)&(num2==num3):
print("numbers are same")
else:
print(num3,"is 2nd largest") |
2a5bdedb90f82403a7d505f3994d532740d5614e | Aasthaengg/IBMdataset | /Python_codes/p02406/s268932483.py | 174 | 3.875 | 4 | array = []
for i in range(3,int(input()) + 1):
if i % 3 == 0 or i % 10 == 3 or '3' in str(i):
array.append(i)
for i in array:
print('',"{0}".format(i),end='')
print() |
70923b4f850e5256d5de703bde467d59ff0a567c | pianoboy-rishul/Soft-Computing-AI-ML | /LogicGates.py | 3,092 | 3.9375 | 4 | ##...Rishul Ghosh...##
##...N230...##
##...Logic Gates Using Python...##
##...1. OR GATE...##
def OR(a,b):
if a==1:
return True
elif b==1:
return True
else:
return False
print(" ...OR GATE...")
print("A=FALSE, B=FALSE | A OR B = ",OR(0,0),"|")
print("A=FALSE, B=TRUE | A OR B = ",OR(0,1)," |")
print("A=TRUE, B=FALSE | A OR B = ",OR(1,0)," |")
print("A=TRUE, B=TRUE | A OR B = ",OR(1,1)," |")
print("______________________________________________________")
##...2. NOR GATE...##
def NOR(a,b):
if a==1:
return False
elif b==1:
return False
else:
return True
print(" ...NOR GATE...")
print("A=FALSE, B=FALSE | A NOR B = ",NOR(0,0)," |")
print("A=FALSE, B=TRUE | A NOR B = ",NOR(0,1),"|")
print("A=TRUE, B=FALSE | A NOR B = ",NOR(1,0),"|")
print("A=TRUE, B=TRUE | A NOR B = ",NOR(1,1),"|")
print("______________________________________________________")
##...3. NAND GATE...##
def NAND(a,b):
if a==1 and b==1:
return False
else:
return True
print(" ...NAND GATE...")
print("A=FALSE, B=FALSE | A NAND B = ",NAND(0,0)," |")
print("A=FALSE, B=TRUE | A NAND B = ",NAND(0,1)," |")
print("A=TRUE, B=FALSE | A NAND B = ",NAND(1,0)," |")
print("A=TRUE, B=TRUE | A NAND B = ",NAND(1,1),"|")
print("______________________________________________________")
##...3. AND GATE...##
def AND(a,b):
if a==1 and b==1:
return True
else:
return False
print(" ...AND GATE...")
print("A=FALSE, B=FALSE | A AND B = ",AND(0,0)," |")
print("A=FALSE, B=TRUE | A AND B = ",AND(0,1)," |")
print("A=TRUE, B=FALSE | A AND B = ",AND(1,0)," |")
print("A=TRUE, B=TRUE | A AND B = ",AND(1,1)," |")
print("______________________________________________________")
##...3. XOR GATE...##
def XOR(a,b):
if a==0:
if b==0:
return False
else:
return True
elif a==1:
if b==0:
return True
else:
return False
print(" ...XOR GATE...")
print("A=FALSE, B=FALSE | A XOR B = ",XOR(0,0),"|")
print("A=FALSE, B=TRUE | A XOR B = ",XOR(0,1)," |")
print("A=TRUE, B=FALSE | A XOR B = ",XOR(1,0)," |")
print("A=TRUE, B=TRUE | A XOR B = ",XOR(1,1),"|")
print("______________________________________________________")
##...COMBINATIONAL LOGIC GATE...##
def ANDandOR(a,b):
c=a*b*(a+b)
if c!=0:
return 1
else:
return 0
print(" ...COMBINATION OF (AND) AND (OR) GATES...")
print("A = 0, B = 0 | A ANDandOR B = ",ANDandOR(0,0),"|")
print("A = 0, B = 1 | A ANDandOR B = ",ANDandOR(0,1),"|")
print("A = 1, B = 1 | A ANDandOR B = ",ANDandOR(1,0),"|")
print("A = 1, B = 1 | A ANDandOR B = ",ANDandOR(1,1),"|") |
effb83a70b4c1dd7d3c81efb076eaffa503ce918 | jimiebolha/python | /execicio_if.py | 146 | 3.75 | 4 | vel = int(input("Qual a velocidade do carro? "))
multa = (vel - 120) * 5
if vel > 120:
print ("Voce esta sendo multado no valor de"), multa
|
288e2733b2042dafee8bea42bd71e0a009678010 | mai-mad/PythonLearning | /august/8.08.2020.py | 469 | 4.15625 | 4 | print ("cake")
# 1 2 3 4 ... 9
for x in range(1, 10):
print(x)
print("end.")
for x in range(9):
print(x+1)
print("end.")
# 0 2 4 6
for x in range(0, 7, 2):
print(x)
print("end.")
# from -3 till 3 with step 3
for x in range(-3, 4, 3):
print(x)
print("end.")
# sum from 2 till 9 with step 2 (2+4+6+8)
sum = 0
for i in range(2, 9, 2):
sum = sum + i
print(sum+1)
# mul 1*2*3*...*10 = 3m
mul = 1
for i in range(1, 11, 1):
mul = mul * i
print(mul) |
7c1e3fdcdaa6e37a8a681e455e46fd001489e49c | nd-0r/MusicTheory | /hw1/pyintro.py | 7,026 | 4.4375 | 4 | #############################################################################################################
#
# Homework 1 (Python Intro)
# MUS105
# Types, Loops, Conditionals, Functions
#
# Instructions:
# * For each of the functions below, read the docstring and implement the function as described.
# * Feel free to to add helper functions, but DO NOT MODIFY the descriptions of the original functions.
#
# * Absolutely NO import statements should be added, they will result in an automatic 0 (the autograder
# will break)
#
# * Some functions specify that certain built in functions may not be used. BE WARY OF THIS.
#
# * Have fun!
#
#############################################################################################################
def power(base, exp):
"""
Implement the math.pow function for integer powers. Note: exp can still be negative. This should be
handled properly. What other edge cases should we be careful of? Return base^exp as a float.
THIS IMPLEMENTATION SHOULD NOT USE: math.pow(base, exp) or base ** exp
:param base: number to raise to a given power
:type base: int
:param exp: power to raise the base to. NOTE: this number can be negative!
:type exp: int
:return: base to the exp power
:rtype: float
"""
# replace the line below with your code
out = float(base)
if(exp < 0):
if(base == 0):
raise ValueError("You can't raise 0 to a negative power")
out = 1
for x in range(-1, exp - 1, -1):
out *= (1 / base)
elif(exp == 0):
return 1.0
else:
for x in range(1, exp):
out *= base
return out
def list_sum(l):
"""
given a list l, return the sum of all the elements of l. You can assume that l only contains ints & floats.
:param l: list of floats/ints
:type l: list
:return: the sum of all the elements in l, AS A FLOAT
:rtype: float
"""
# replace the line below with your code
return float(sum(l))
def str_to_int(num_string):
"""
Turn a string into an integer. For this function, num_string can be a string representation of a number in either
binary, octal, decimal, or hexadecimal. Depending on the base, the string will start differently:
binary: "0b100" = 4 "0b" is first 2 characters
octal: "0o11" = 9 "0o" is first 2 characters
decimal: "10" = 10 no extra characters
hexadecimal: "0xa" = 10
For binary, octal, and hexadecimal, the string will always be longer than 2 (i.e. the base prefix, and then the
number. No matter the base, you are to correctly convert the string to an int and return it.
If the base is unrecognized (the first two are not numbers, and also are not '0b', '0o', or '0x', the function
should return -1.
Don't worry about negative numbers!
**hint** remember that the int() function can take multiple parameters. What was that second parameter?
:param num_string: string representation of the integer
:type num_string: str
:return: integer with the value represented in the string, or negative one if the base is unrecognized
:rtype: int
"""
# replace the line below with your code
if(num_string[0:2] == "0b"):
return int(num_string, 2)
elif(num_string[0:2] == "0o"):
return int(num_string, 8)
elif(num_string[0:2] == "0x"):
return int(num_string, 16)
elif(num_string[1:2].isdigit()):
return int(num_string)
return int(-1)
def print_christmas_tree(size):
"""
A christmas tree with size n is defined as a string having n + 1 rows, where the i'th row contains the (i-1)'th row's
number of stars + 2, arranged in a symmetrical manner. the 0'th row should have 1 star. the last (n'th) row should
be equivalent to the 0'th row (the trunk of the tree). the stars are asterisks: '*'. size is always >= 2.
Example of a size 4 tree:
*
***
*****
*******
*
The return should be a single string, with each row separated by '\n'. Mind the spacing in each row--there should
be spaces before the '*'s on each row, but not after.
size 4 tree as string:
" *\n ***\n *****\n*******\n *"
**hint** print out your tree to the console a few times to make sure the spacing is correct.
:param size: a number >=2
:type size: int
:return: string representation of a christmas tree
:rtype: str
"""
# replace the line below with your code
out = ""
for i in range(1, size + 1):
out += " " * (size - i)
out += "*" * (i * 2 - 1)+ "\n"
out += (" " * (size - 1)) + "*"
return out
def list_to_str(l):
"""
Implement the __str()__ function for the list class. This function should take a list, and convert
it to its string representation. You can assume that for each element in the list, the str() function
will give the appropriate string to use for the entire list string. Some examples of list strings:
[1, 2, 3, 4, 5, 6]
[True, False, True, True, False]
['hi', 'my', 'name', 'is']
* NOTICE: for string elements, the string itself is surrounded by single quotes. You are expected to
implement this. this is the only special case you should be aware of
* you will not be graded on the spacing of your string representation, i.e. [1,2,3] == [1, 2, 3] == [ 1, 2, 3 ]
* you can assume that there will be no nested lists/dictionaries/tuples nested in the list
* do NOT assume that all elements in the list are of the same type
* YOU ARE EXPECTED TO USE str() FOR EACH ELEMENT IN THE LIST
* DO NOT USE str() ON THE LIST ITSELF
:param l: list to convert to string
:type l: list
:return: string representation of that list
:rtype: str
"""
# replace the line below with your code
out = "["
for x in l[0:-1]:
if(type(x) == str):
out += "\'" + str(x) + "\', "
else:
out += str(x) + ", "
if(type(l[-1]) == str):
out += "\'" + str(l[-1]) + "\']"
else:
out += str(l[-1]) + "]"
return out
def remove_substring_instances(in_str, substr):
"""
given the string input, find all instances of substr and remove them from the input. Then, return the number of
instances of substr that were removed, as well as the new string with all instances of substr removed, as a tuple.
for example:
return num_instances, new_string
:param in_str: string to clean up
:type in_str: str
:param substr: substring to find and remove
:type substr: str
:return: a tuple where the first element is the number of elements removed, and the second is the string after
cleaning
:rtype: tuple
"""
# replace the line below with your code
count = 0
while substr in in_str:
in_str = in_str.replace(substr, "", 1)
count += 1
return (count, in_str) |
7028b2159ca4b3d91a1111c07ef187eebe6c54f8 | sssmrd/pythonassignment | /35.py | 241 | 4.46875 | 4 | #program to add an item in a tuple.
l=input("Enter the values in tuple=").split();
print("Before adding")
t=tuple(l)
print(t)
val=input("Enter item to be entered=")
l=list(t)
l.append(val);
t=tuple(l)
print("After adding")
print(t) |
61d7b53179ec40be86c4fae748a9f60133f68d91 | romanosaurus/Python-programming-exercises | /ex21.py | 1,047 | 4.5625 | 5 | '''
A robot moves in a plane starting from the original point (0,0).
The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
¡
The numbers after the direction are steps.
Please write a program to compute the distance from current position after a sequence of movement and original point.
If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
'''
import math
dif_position = {"UP": 0, "DOWN": 0, "LEFT": 0, "RIGHT": 0}
xori = 0
yori = 0
while True:
res = input()
if res:
res = res.split(' ')
if res[0] in dif_position:
dif_position[res[0]] += int(res[1])
else:
break
x = dif_position["UP"] - dif_position["DOWN"]
y = dif_position["LEFT"] - dif_position["RIGHT"]
res = int(math.sqrt(math.pow((xori - x), 2) + math.pow((yori - y), 2)))
print(res)
|
04fe570797dcd0b2f4e073163889e19592e8e619 | CrABonzz/AdventOfCode | /Development/problem3.py | 821 | 3.703125 | 4 | from functools import reduce
from typing import List
def count_slope_tree(grid: List[str], right_step: int, bottom_step: int, row: int, col: int) -> int:
if row >= len(grid):
return 0
if col >= len(grid[row]):
col -= len(grid[row])
is_tree = 1 if grid[row][col] == "#" else 0
return is_tree + count_slope_tree(grid, right_step, bottom_step, row+bottom_step, col+right_step)
def slope_statistics(grid, *args):
# Start point 0, 0
return [count_slope_tree(grid, right_step, bottom_step, 0, 0) for right_step, bottom_step in args]
def problem3():
with open(r"assets\p3_input.txt", 'r')as file_input:
grid = [line.strip() for line in file_input.readlines()]
print(reduce(lambda x, y: x * y, slope_statistics(grid, (3, 1), (1, 1), (5, 1), (7, 1), (1, 2))))
|
f83deaf063e9117bb82fb0b85d3bb066fb9cf633 | thorhilduranna/2020-3-T-111-PROG | /assignments/files/content_one_line.py | 611 | 4.1875 | 4 | def open_file(filename):
''' Opens the given file and returns the corresponding file object '''
file_object = open(filename, 'r')
return file_object
def process_file(file_object):
'''Reads the given file_object and returns its contents in a single string after removing white spaces'''
line_str = ""
for line in file_object:
line = line.strip()
line = line.replace(" ", "")
line_str += line
return line_str
# Main starts here
file_name = input("Enter filename: ")
file_object = open_file(file_name)
single_line = process_file(file_object)
print(single_line)
file_object.close() |
32600b874756421eb589ecf33909662b724ecfba | enria/algorithm-problem | /leetcode/206.反转链表.py | 693 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self) -> str:
h=self
while h:
print(h.val)
h=h.next
return ""
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head: return head
cur=head
n=head.next
cur.next=None
while n:
a=n.next
n.next=cur
cur=n
n=a
return cur
head = [1,2,3,4,5]
h=ListNode()
cur=h
for i in head:
n=ListNode(i)
cur.next=n
cur=n
s=Solution()
print(s.reverseList(h.next))
|
e3db638f7db849d51b8e95869f457da054138da9 | SteveChristian70/Coderbyte | /timeConvert.py | 379 | 4 | 4 | '''
Have the function TimeConvert(num) take the num parameter being passed
and return the number of hours and minutes the parameter converts
to (ie. if num = 63 then the output should be 1:3).
Separate the number of hours and minutes with a colon.
'''
def TimeConvert(num):
ans = (str(num / 60) + ":" + str(num % 60))
return ans
print TimeConvert(raw_input()) |
35baa4eb4b314e3ee4d070ece0dc68e06feed892 | ExcViral/evolutionary-algorithms | /binary-coded genetic algorithm/selection.py | 9,686 | 4.53125 | 5 | # A proportion of the existing population is selected to bread a new bread of generation. Parents with better fitness
# have better chances to produce offspring.
# NOTE: Please define a fitness function in fitness.py or this module will not work
# import necessary libraries
import numpy as np
import math
from bitarray import bitarray
from fitness import fitness
# ======================================================================================================================
# ===== Helper Functions ===============================================================================================
# ======================================================================================================================
def unique_rn_generator(low, high, n):
"""
Function to generate a list of unique random integers
This function uses numpy's random number generator to generate a list of random numbers, checks if all the numbers
in the list are unique, if they are unique, the list is returned. If they are not unique, then the list is generated
repeatedly until a list with unique numbers is generated.
:param low: (int) lowest (inclusive) acceptable random number
:param high: (int) highest (not inclusive) acceptable random number
:param n: (int) number of random numbers to be generated
:return: (list) containing 'n' unique random numbers
"""
r = np.random.randint(low, high, n)
while len(r) != len(set(r)):
r = np.random.randint(low, high, n)
return r
def round_up_to_even(f):
"""
This function rounds up a number to an even number.
The function just divides the value by 2, rounds up to the nearest integer, then multiplies by 2 again
:param f: (float) that is to be rounded up to an even number
:return: (int) input number rounded up to next even number
"""
return int(math.ceil(f / 2.) * 2)
# ======================================================================================================================
# ===== Selection Algorithms ===========================================================================================
# ======================================================================================================================
def tournament_selection(population, cp, k, mode):
"""
This function is an implementation of tournament selection algorithm
Runs a "tournament" among a few individuals chosen at random from the population and selects the winner (the one
with the best fitness) for crossover
Algorithm: Pick 'k' number of entities out of the pool, compare their fitness, and the best is permitted to
reproduce.
Selection pressure can be easily adjusted by changing the tournament size 'k'.
Deterministic tournament selection selects the best individual in each tournament.
:param population: (list of bitarray) containing chromosomes(bitarray) represented by genes(bit)
:param cp: (float) crossover probability, typically should be between 0.8 and 1
:param k: (int) number of members allowed to participate in each tournament that is held
:param mode: (string) to set whether working on minimization(pass: "min") or maximization(pass: "max") problem
:return: (list) containing indices of selected chromosomes from the population
"""
# check whether to minimize or maximize
if mode == "min":
flag = False
elif mode == "max":
flag = True
else:
raise ValueError("Incorrect mode selected, please pass 'min' or 'max' as mode")
# list that will keep track of selected indices, so that selection is done without replacement.
selected_indices = []
# number of parents to be selected
n = round_up_to_even(len(population)*cp)
# create a copy of original population alongwith their respective indices, because we will be removing winner of
# tournament from this array, and we need to preserve original indices of population members.
numbered_population = [[l, m] for l, m in zip(population, range(len(population)))]
# start selecting parents for crossover
for i in range(n):
# Generate k unique random numbers
if k < len(numbered_population):
r = unique_rn_generator(0, len(numbered_population), k)
# However, if the list is exhausted, i.e there are less than k unique members left, repetition is allowed
elif k >= len(numbered_population):
r = np.random.randint(0, len(numbered_population), k)
# empty list to store fitnesses of tournament participator members
fitnesses = []
# calculate fitness of each tournament paticipator and append it to fitnesses list
for a in r:
fitnesses.append(fitness(numbered_population[a][0]))
# Assume that index 0 is the fittest tournament participator, so set index = 0
index = 0
# Compare fitness of each tournament participator with fitness of participator on whom index is currently
# pointing, update index if fitness of non indexed participant is higher than indexed, else no change.
# if problem is of maximization
if flag:
for j in range(len(r)):
if fitnesses[index] < fitnesses[j]:
index = j
# if problem is of minimization
else:
for j in range(len(r)):
if fitnesses[index] > fitnesses[j]:
index = j
# Copy the original position of winner, and update it to selected_indices list
winner = numbered_population[r[index]][1]
selected_indices.append(winner)
# delete the winner from the numbered_population, i.e. ban it from further entering the tournament
del numbered_population[r[index]]
return selected_indices
def rank_selection(population, mode):
"""
This function is an implementation of rank selection algorithm
Rank selection first ranks the population and then every chromosome receives fitness from this ranking. Here,
selection is based on this ranking rather than absolute differences in fitness.
:param population: (list of bitarray) containing chromosomes(bitarray) represented by genes(bit)
:param mode: (string) to set whether working on minimization(pass: "min") or maximization(pass: "max") problem
:return: (list of bitarray) containing original chromosomes, but ranked in order according to their fitness
"""
# calculate fitness of all population members and store it in a new list fitnesses
fitnesses = [fitness(i) for i in population]
# now we have fitness of each population member, rank them according to their fitness, i.e. sort the population list
# according to the fitness values of population members, depending on whether it is minimization or maximization,
# sort ascending or descending.
# check whether to minimize or maximize
if mode == "max":
return [i for _, i in sorted(zip(fitnesses, population), reverse=True)]
elif mode == "min":
return [i for _, i in sorted(zip(fitnesses, population), reverse=False)]
else:
raise ValueError("Incorrect mode selected, please pass 'min' or 'max' as mode")
def roulette_wheel_selection(population, cp):
"""
This function is implementation of roulette wheel selection algorithm
Algorithm:
--[1] Calculate S = the sum of all finesses.
--[2] Generate a random number between 0 and S.
--[3] Starting from the top of the population, keep adding the finesses to the partial sum P, till P < S.
--[4] The individual for which P exceeds S is the chosen individual.
WARNING: This algorithm will fail where fitness can take a negative value, and maximum crossover probability should
be less than 0.95
:param population: (list of bitarray) containing chromosomes(bitarray) represented by genes(bit)
:param cp: (float) crossover probability, typically should be between 0.8 and 1
:return: (list) containing indices of selected chromosomes from the population
"""
# list that will keep track of selected indices, so that selection is done without replacement.
selected_indices = []
# number of parents to be selected
n = round_up_to_even(len(population) * cp)
# create a list of population fitness, alongwith original index of population member corresponding to that fitness
fitness_wIndices = [[fitness(l), m] for l, m in zip(population, range(len(population)))]
# initialize a variable for keeping track of sum of fitnesses
fitness_sum = 0
# start selecting parents for crossover
for i in range(n):
# calculate S = sum of all fitnesses
for j in fitness_wIndices:
fitness_sum = fitness_sum + j[0]
# generate a random number between 0 and S.
r = int(np.random.randint(0, fitness_sum, 1))
# Initializing variable for storing partial sums
partial_sum = 0
# starting from the top of the population, keep adding the finesses to the partial sum P, till P < S.
# The individual for which P exceeds S is the chosen individual.
for m in range(len(fitness_wIndices)):
partial_sum = partial_sum + fitness_wIndices[m][0]
if partial_sum > r:
# append index of the selected member to the list
selected_indices.append(fitness_wIndices[m][1])
# delete the selected element from the list, so that it does not get selected again
del fitness_wIndices[m]
break
fitness_sum = 0
return selected_indices
|
17d0db7609fb4b023a50bc0d44d8e170466e9a79 | anitazhaochen/nowcoder | /quick_sort.py | 859 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from myutils import *
def quickSort(arr, start, end):
if start >= end:
return
left = start
right = end
mid = arr[left]
while left < right:
while arr[right] >= mid and right > left:
right -= 1
arr[left] = arr[right]
while arr[left] <= mid and left < right:
left += 1
arr[right] = arr[left]
arr[left] = mid
quickSort(arr,start,left-1)
quickSort(arr, left+1,end)
if __name__ == "__main__":
for _ in range(100):
arr = [random.randint(-999,999) for _ in range(10) ]
arr1 = copy.deepcopy(arr)
arr1 = sorted(arr1)
quickSort(arr,0,len(arr)-1)
if arr1 != arr:
print(arr1)
print(arr)
print("failed")
exit()
print("success")
|
ab668d177513898b71270f9da62e0d865e7af28e | daniel-reich/ubiquitous-fiesta | /TCQkKzgi8FFYYG4kR_3.py | 251 | 3.90625 | 4 |
def camel_to_snake(s):
output = ""
for i in range(0,len(s)-1):
if s[i+1].isupper():
output+=s[i]+'_'
i+=2
else:
if s[i].islower():
output+=s[i]
else:
output+=s[i].lower()
return output+s[-1]
|
a685b5adf9eb2618325808d44bd643851ec9e6cf | dongyang2/hello-world | /lessons/complexNetwork_BigHomework/list2DTest.py | 682 | 3.90625 | 4 | list_2d = [[0 for col in range(63)]for row in range(63)]
list_2d[0][2] = 3
list_2d[0][3] = 2
list_2d[1][2] = 1
list_2d[1][3] = 4
print(list_2d[0]) # 按行的索引号打印
i = 0
while i < 63: # 按列打印
# print(list_2d[num][2])
i = i+1
count = 0
for j in list_2d:
count = count+1
# print(count) # 这里遍历list_2d只有63个元素说明每个j是一个一维list,所以就有了第二种按列打印的方法
# for each_c in list_2d: # 第二种按列打印
# print(each_c[2])
# list_2d.pop(0) # 按行的索引号删除
for j in list_2d:
j.pop(2)
# print(list_2d[0])
# print(list_2d[1])
|
7de174f0df92c4ecb4ab3db07bd0b7e9a53a4ade | woorim960/algorithm | /sort/merge.py | 1,327 | 3.625 | 4 | # 합병 정렬
def merge_sort(ls) :
n = len(ls) # 여러번 호출되기에 미리 선언해준다.
if n <= 1 : return ls # 리스트의 길이가 1이면 자기 자신 반환
u = merge_sort(ls[:n//2]) # 반으로 나눈 좌측 리스트
v = merge_sort(ls[n//2:]) # 반으로 나눈 우측 리스트
return merge(u, v) # 합병
# 합병 => 각 원소를 비교하여 크기 순으로 정렬하면서 합친다.
def merge(u, v) :
ls = [] # 정렬된 요소가 담길 리스트
i = j = 0 # 인덱스
u_max, v_max = len(u), len(v) # while문에서 매번 조건 검사시 len()을 호출하지 않도록 미리 할당
while i < u_max and j < v_max : # 비교가 마무리될 때까지 반복
# 작은 것 순서대로 삽입
if u[i] <= v[j] :
ls.append(u[i])
i += 1
else :
ls.append(v[j])
j += 1
# 비교 후 남은 리스트를 마지막에 합쳐준다.
if i > j :
ls += v[j:]
else :
ls += u[i:]
return ls
# 정렬할 리스트 입력
ls = list(map(int, input().split()))
# 실행
print( merge_sort(ls) )
|
c2e7abf76d6f9cd8dc144edd97413f0d4f2d16f5 | ahmedBou/Gtx-computing-in-python | /Loops/basic.py | 2,754 | 5 | 5 | # In the designated areas below, write the three for loops
# that are described. Do not change the print statements that
# are currently there.
print("First loop:")
for i in range(1, 11):
print(i)
# Write a loop here that prints the numbers from 1 to 10,
# inclusive (meaning that it prints both 1 and 10, and all
# the numbers in between). Print each number on a separate line.
print("Second loop:")
for i in range(-5, 6):
print(i)
# Write a loop here that prints the numbers from -5 to 5,
# inclusive. Print each number on a separate line.
print("Third loop:")
for i in range(1, 21):
if i % 2 == 0:
print("Third loop:", i)
# Write a loop here that prints the even numbers only from 1
# to 20, inclusive. Print each number on a separate line.
# Hint: There are two ways to do this. You can use the syntax
# for the range() function shown in the multiple-choice
# problem above, or you can use a conditional with a modulus
# operator to determine whether or not to print.
#############################################################
# Gtx solution
#The first two of these loops are relatively
#straightforward. We have a first item, a last item, and
#we're printing every item in between.
print("First loop:")
#This loop should print 1 to 10. Remember, the range()
#function includes the first argument but excludes the
#second argument. So, we have to make the second argument
#one larger than where we want to end:
for i in range(1, 11):
print(i)
print("Second loop:")
#This loop should print from -5 to 5. Really, it's the
#same as the previous one, but the start and end points
#are different. So, we just change the arguments to
#range():
for i in range(-5, 6):
print(i)
print("Third loop:")
#This third one is tricky, though. We want to print the
#even numbers only. We can do that two ways.
#One, we can use the syntax shown in the multiple choice
#exercise before this problem:
for i in range(2, 21, 2):
print(i)
#Notice that we've put three numbers into the range()
#function. The first one is our start number and the
#second is our end number as usual. The third, though,
#is the 'step' number. That means how many numbers
#should we advance each time the loop runs. By setting
#it to 2, we advance two numbers each time the loop
#runs: 2, 4, 6, 8, etc. We could also make this
#negative to run the loop backwards!
#The other way, though, is to check to see if each
#number in a more typical range is even, and only print
#it if it is:
for i in range(1, 21):
if i % 2 == 0:
print(i)
#This loop goes through all the numbers 1 through 21,
#but the print statement is under a conditional, and
#the conditional checks if the number is even. So, it
#only prints if the nubmer is even. |
11a4ae430a07ed9674b97afa89f07b96d771bbe0 | virgilraj/python-interview | /merge_tow_array_with_condition.py | 1,109 | 4.03125 | 4 | #Merge two arrays by satisfying given constraints
#Step 1 . curPos and J =0
#2. X[curPos] is zero and next element of X greater than Y element then replace zero with y element
#3. curPos++ and j++
#4. curpos element is zero and next element greater than zero and next element less than Y
#5. Swap curpos to next element and curPos++
#6. curpos element > 0 then curPos++
#7. replace last zero with Y array
def merge_two_sorted_array_replaces_zero(X,Y):
j = 0
curPos = 0
m = len(X)
n = len(Y)
for i in range(m-1):
if(X[curPos] == 0 and X[i+1] > Y[j]):
X[curPos] = Y[i]
curPos +=1
j +=1
elif(X[curPos] == 0 and X[i+1] >0 and X[i+1] < Y[j]):
X[curPos],X[i+1] = X[i+1],X[curPos]
curPos +=1
elif(X[curPos] > 0):
curPos +=1
#Replace Last zero elements
while(curPos < m and j < n):
X[curPos] = Y[j]
curPos +=1
j +=1
if __name__ == "__main__":
X = [0, 2, 0, 3, 0, 5, 6, 0, 0]
Y = [1, 8, 9, 10, 15]
merge_two_sorted_array_replaces_zero(X,Y)
print(X)
|
8f341d9be4519e3d53cc86c06a24303baf0d0e0d | Mainul-Fahim/Sapiens-with-Papyrus | /wallet/test.py | 3,126 | 3.5 | 4 |
from test_utils import WalletTestCase
#From TransactionTestCase on w_utils.py
from errors import InsufficientBalance
class BalanceTestCase(WalletTestCase):
def test_default_balance(self):
self.assertEqual(self.wallet.current_balance, 0)
class DepositTestCase(WalletTestCase):
def test_deposit(self):
"""Testing the basic wallet deposit operation."""
DEPOSIT = 100
self.wallet.deposit(DEPOSIT)
""" The wallet's current_balance should also reflect
the deposit's value."""
self.assertEqual(self.wallet.current_balance, DEPOSIT)
""" When creating a deposit, the wallet should create
a transaction equal to the value of the deposit."""
self.assertEqual(self.wallet.transaction_set.first().value, DEPOSIT)
class WithdrawTestCase(WalletTestCase):
def test_withdraw(self):
"""Testing the basic wallet withdraw operation on a
wallet that has an initial balance."""
INITIAL_BALANCE = 100
self._create_initial_balance(INITIAL_BALANCE)
WITHDRAW = 99
self.wallet.withdraw(WITHDRAW)
""" Testing that the wallet's current_balance that it
matches the wallet's initial balance - the
withdrawn amount."""
self.assertEqual(self.wallet.current_balance,
INITIAL_BALANCE - WITHDRAW)
""" When a withdraw transaction succeeds, a
transaction will be created and it's value should
match the withdrawn value (as negative)."""
self.assertEqual(self.wallet.transaction_set.last().value, -WITHDRAW)
def test_no_balance_withdraw(self):
"""Testing the basic wallet withdraw operation on a
wallet without any transaction.
"""
with self.assertRaises(InsufficientBalance):
self.wallet.withdraw(100)
class TransferTestCase(WalletTestCase):
def test_transfer(self):
"""Testing the basic tranfer operation on a wallet."""
INITIAL_BALANCE = 100
TRANSFER_AMOUNT = 100
self._create_initial_balance(INITIAL_BALANCE)
"""Creating a second wallet."""
wallet2 = self.user.wallet_set.create()
"""Transfering all the balance the first
wallet has."""
self.wallet.transfer(wallet2, TRANSFER_AMOUNT)
"""Checking that the first wallet has its balance"""
self.assertEqual(self.wallet.current_balance,
INITIAL_BALANCE - TRANSFER_AMOUNT)
"""Also checking that the second wallet has the
transferred balance."""
self.assertEqual(wallet2.current_balance, TRANSFER_AMOUNT)
def test_transfer_insufficient_balance(self):
"""Testing a scenario where a transfer is done on a
wallet with an insufficient balance."""
INITIAL_BALANCE = 100
TRANSFER_AMOUNT = 150
self._create_initial_balance(INITIAL_BALANCE)
"""Creating a second wallet."""
wallet2 = self.user.wallet_set.create()
with self.assertRaises(InsufficientBalance):
self.wallet.transfer(wallet2, TRANSFER_AMOUNT) |
0c690a39b1a866fb47d9295e288813dd78e8a2fc | PrianshuRai/AgeCalculator | /Age Calculator.py | 2,825 | 3.921875 | 4 | import tkinter as tk
from datetime import datetime, date
window = tk.Tk()
window.title("Age Calculator")
# main widgets
name = tk.Label(window, text="Name", font="Calibre, 12").grid(column=0, row=0, padx=10)
nameE = tk.Entry()
nameE.grid(column=1, row=0, ipadx=10, padx=10, sticky="e")
# age data
year = tk.Label(window, text="Year", font="Calibre, 12").grid(column=0, row=1, padx=10)
yearE = tk.Entry()
yearE.grid(column=1, row=1, ipadx=10, padx=10, sticky="e")
month = tk.Label(window, text="Month", font="Calibre, 12").grid(column=0, row=2, padx=10)
monthE = tk.Entry()
monthE.grid(column=1, row=2, ipadx=10, padx=10, sticky="e")
day = tk.Label(window, text="Date", font="Calibre, 12").grid(column=0, row=3, padx=10)
dayE = tk.Entry()
dayE.grid(column=1, row=3, ipadx=10, padx=10, sticky="e")
# functions
def age_cal():
user = nameE.get()
years = yearE.get()
months = monthE.get()
days = dayE.get()
current_date = datetime.now().date()
birth_date = date(int(years), int(months), int(days))
result = f"Hey {user.title()}! \n{calculation(current_date, birth_date)}"
title = tk.Text(font="Times 14", width=5, height=5, wrap="word")
title.grid(column=0, row=7, columnspan=2, padx=5, pady=5, sticky="news", ipadx=15, ipady=5)
title.delete(1.0, "end")
title.insert(tk.END, result)
def get_day():
# repeated code :(
user = nameE.get()
years = yearE.get()
months = monthE.get()
day_s = dayE.get()
birth_date = date(int(years), int(months), int(day_s))
# have to repeat the above code bcz it wasn't working earlier
day_nm = birth_date.strftime("%A")
msg = f"Hey {user.title()}!\nThe day on which you were born is-\n{day_nm}"
title = tk.Text(font="Times 14", height=5, width=5, wrap="word")
title.grid(column=0, row=7, columnspan=2, padx=5, pady=5, sticky="news")
title.delete(1.0, "end")
title.insert(tk.END, msg)
def calculation(first, second):
days = first - second
n_days = days.days
years = int(n_days / 365.25)
months = int((n_days % 365.25) / 30)
return f"Your age as of today is-\n{years} year(s), {months} month(s)"
# buttons are here
age_btn = tk.Button(window, text="Get Age", bg="green", fg="white", command=age_cal)
age_btn.grid(column=0, row=4, columnspan=2, padx=2, pady=2, sticky="news")
day_btn = tk.Button(window, text="Get Day", bg="blue", fg="white", command=get_day)
day_btn.grid(column=0, row=5, columnspan=2, padx=2, pady=2, sticky="news")
exit_btn = tk.Button(text="Exit", bg="grey", fg="white", command=lambda: window.destroy())
exit_btn.grid(column=0, row=6, columnspan=2, padx=2, pady=2, sticky="news")
# for setting focus on name entry
nameE.focus_set()
window.mainloop()
'''
days = 1329
years = days/365
weeks = (days % 365) / 7
days = days - ((years * 365) + (weeks * 7))
'''
|
7776e860337f9f827dffae623eadea263ac906fe | InsertCreativeNameHere/Ejemplos-Python | /Ciclos/31.py | 159 | 3.59375 | 4 | #Ejercicios con ciclos punto 31
#Javier Aponte 20172020036
r = int(input("Ingrese el numero por favor \n"))
for i in range(0,11):
print(r ,"x",i ,"=",r*i)
|
3862bc83e0dc81c8f065488534be5893bc9fda4e | alexlomu/Warm-Up-Python | /Entrega 1/bitcoin.py | 378 | 3.578125 | 4 | investment_in_bitcoin = 1.2
bitcoin_to_euros = 40000
def bitcoinToEuros(bitcoin_amount, bitcoin_value_euros):
euros_value = bitcoin_amount * bitcoin_value_euros
if euros_value < 30000:
print("El valor ha bajado de 30000, es aconsejable retirar.")
else:
print("El valor está por encima de 30000, es recomendable invertir.")
bitcoinToEuros(1, 25000) |
70ae99e35320e38848db5d87d89077854d3955bd | Vaibhhh/Python-Basics- | /Classes2.py | 335 | 3.6875 | 4 | class Car():
def __init__(self,modelname,yearm,price):
self.modelname=modelname
self.yearm = yearm
self.price = price
def price_inc(self):
self.price=int(self.price*1.15)
honda = Car('City',2017,1000000)
tata = Car('Bolt',2016,600000)
honda.cc = 1500
print(tata.__dict__)
honda.price_inc()
print(honda.price)
|
eab24f000ecc6b3bc252c710f186dbc768660116 | jorgepdsML/DIGITAL-IMAGE-PROCESSING-PYTHON | /PROYECTO_1/codigo3.py | 305 | 3.5 | 4 | """
este archivo es el tercer ejemplo en python
utilizando el IDLE
hola mundo
"""
#ingresar primera variable a
a=float(input("INGRESAR PRIMERA VARIABLE"))
#ingresar segunda variable c
c=float(input("INGRSAR SEGUNDA VARIABLE"))
#mostrar la suma de ambos numeros
b=a+c
print("LA SUMA ES : ",b )
|
ee8c8228cfa15a05063b323ad87b157b5825ea39 | sapnadeshmukh/Logical_QuestionsInPython | /electricBill.py | 352 | 4.03125 | 4 | unit=int(input("enter unit"))
if unit<=50:
amount =unit*0.50
print (amount)
elif unit>50 and unit<=150:
amount=unit*0.75
print (amount)
elif unit>150 and unit<=250:
amount=unit*1.20
print (amount)
elif unit>250:
amount=unit*1.50
print (amount)
sur_charge=amount*20/100
total_amount=amount+sur_charge
print ("electric bill will be",total_amount) |
2159734857d5cce55efc5551a420f448b563a64b | romerocesar/adventofcode | /expensereport.py | 689 | 3.96875 | 4 | 'https://adventofcode.com/2020/day/1'
import sys
def two(expenses):
'''finds two entries A and B that add up to 2020 and returns A*B'''
s = set(expenses)
for x in s:
if 2020-x in s:
return x*(2020-x)
def three(expenses):
'find three entries A, B and C that add up to 2020 and return A*B*C'
s = set(expenses)
for i in range(len(expenses)):
for j in range(i+1, len(expenses)-i-1):
a, b = expenses[i], expenses[j]
c = 2020-a-b
if c in s:
return a*b*c
with open(sys.argv[1]) as fp:
expenses = [int(x) for x in fp.readlines()]
print(three(expenses))
|
ee6ed840780522ab9ad69cc3a5cf6e20956b77b0 | diegorodriguezparra/Simulador-REOS | /Modelo Lanzamiento/errores.py | 3,945 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Team REOS
Clases para excepciones en los códigos del proyecto REOS.
"""
class ValorInadmisibleError(Exception):
'''
Error que se produce cuando un valor no tiene sentido real,
aunque matemáticamente siga siendo válido.
Parámetros
----------
diccionario : dictionary
Variable cuyo valor es inadmisible. Debe introducirse como
dict(nombre_variable=nombre_variable).
formato : string, opcional
Código de formato con el que se representa el valor inadmisible
de la variable. Por defecto, es un string vacío.
deberia_ser : string, opcional
Condición que el valor en cuestión no cumple y que lo hace
inadmisible. Por defecto es None.
Atributos
---------
message : string
Mensaje de error.
Ejemplos
--------
>>> valor_negativo = 2
>>> raise ValorInadmisibleError(dict(valor_negativo=valor_negativo))
ValorInadmisibleError: La variable valor_negativo tiene un valor
inadmisible: 2.
>>> raise ValorInadmisibleError(dict(valor_negativo=valor_negativo))
ValorInadmisibleError: La variable valor_negativo tiene un valor
inadmisible: 2. Debería ser negativo.
'''
def __init__(self, diccionario, formato='', deberia_ser=None):
variable = [str(var) for var in diccionario.keys()]
variable = variable[0]
if deberia_ser is None:
deberia_ser = ''
else:
deberia_ser = ' Debería ser ' + deberia_ser + '.'
self.message = ("La variable '" + variable +
"' tiene un valor inadmisible: "
+ format(diccionario[variable], formato) + '.'
+ deberia_ser)
Exception.__init__(self, self.message)
class IteracionError(Exception):
'''
Error que se produce cuando una iteración en un bucle produce una
excepción e identifica dicha iteración.
Parámetros
----------
iteracion
Valor de la variable de iteración cuando se produce la
excepción.
Atributos
---------
message : string
Mensaje de error.
'''
def __init__(self, iteracion, error=None):
if error is not None:
error_type = str(type(error))
error_type = error_type[:error_type.find('Error')+5]
error_type = error_type.split(sep='.')[1]
error_msg = error.message
else:
error_type = ''
error_msg = ''
self.message = ('El valor de la variable de iteración en el error es '
+ str(iteracion) + '.\n\n' + error_type + ': '
+ error_msg)
Exception.__init__(self, self.message)
class NoseError(Exception):
'''
Error que se produce cuando se asigna un valor inadmisible a la variable
tipo en la geometría del misil.
Parámetros
----------
tipo
Valor que se le ha dado al tipo de nariz.
Atributos
---------
message : string
Mensaje de error.
'''
def __init__(self, tipo):
tipo = str(tipo)
self.message = ('El tipo de nariz seleccionado para el lanzador, ' +
tipo + ', no existe.\n Ha de ser:' +
'\n\t0: Cono\n\t1:Ojiva Circular Tangente')
Exception.__init__(self, self.message)
class TimeDictionaryError(Exception):
'''
Error que se produce cuando no se define un diccionario temporal en el
programa principal.
Atributos
---------
message : string
Mensaje de error.
'''
def __init__(self):
self.message = ('No se ha introducido un diccionario válido.')
Exception.__init__(self, self.message) |
d2b1fb8b442b018a947b7a991313085c7a2d13bf | kkirsche/daily-coding-problems | /Problem2-2019-02-17/python/main.py | 825 | 3.78125 | 4 | from typing import List
from functools import reduce
def product(x: int, y: int) -> int:
return x * y
def product_of_list_except_at_index(list_in: List[int]) -> List[int]:
# create a list to store our results
list_out = []
# we want to calculate a new array for each item in the list
# to get the index we want to exclude for each iteration, we
# loop over the range using the list's length as the stopping value
for index in range(len(list_in)):
# create a new list which gathers all numbers EXCEPT the one at the
# index
list_in_except_index = list_in[:index] + list_in[(index + 1):]
# generate the product of all remaining items in the list
list_product = reduce(product, list_in_except_index)
list_out.append(list_product)
return list_out
|
358ba522114ffebcf203d837cd5bb4eaf9e81c84 | romachd1040/enigma | /All Practice/Count of EC2 Files.py | 461 | 4.03125 | 4 | import os
#path = input ("Enter Path to calculate Directory and file count:")
path="/home/ec2-user"
print(path)
fileCount = 0
dirCount = 0
for root, dirs, files in os.walk(path):
print('Looking in:',root)
for directories in dirs:
dirCount+=1
for Files in files:
fileCount+=1
print('Number of files',fileCount)
print('Number of Directories',dirCount)
print('Total Count Including both Directories and Files:',(dirCount +
fileCount))
|
0d7cd73e21524e7b23cfd7fc947cec7ce6953d12 | aprilxyc/coding-interview-practice | /leetcode-problems/1086-high-five.py | 2,694 | 3.546875 | 4 | class Solution(object):
# https://leetcode.com/problems/high-five/discuss/464841/Python-solution-with-hash
class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
stud_scores = {}
for i in items: # go through the items
if stud_scores.get(i[0]): # if the value exists
stud_scores[i[0]].append(i[1]) # append it to the list that exists in the value already
else:
stud_scores[i[0]] = [i[1]] # otherwise let it equal the value
for i in stud_scores.keys(): # go through the keys
stud_scores[i].sort(reverse=True)
stud_scores[i] = stud_scores[i][0:5]
stud_avg = {}
for i in stud_scores.keys():
stud_avg[i] = sum(stud_scores[i]) //5
stud_list = []
for i in stud_scores.keys():
stud_list.append(i)
stud_list.sort()
return [[i, stud_avg[i]] for i in stud_list]
# my own solution 11/01 (improved but struggles with remember to use .keys() and .values() for dictionary - would've made life so much easier if I remembered
def highFive(self, items: List[List[int]]) -> List[List[int]]:
stud_scores = {} #{1: [91], 92}
for i in items:
if i[0] not in stud_scores: #[[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
stud_scores[i[0]] = [i[1]] #
else:
stud_scores[i[0]].append(i[1])
result = []
for i in stud_scores.keys():
individual_score = stud_scores[i]
individual_score.sort(reverse=True)
average = sum(individual_score[:5]) // 5
result.append([i, average])
return sorted(result)
# correct data structure to use for this to make it faster is a priority queue
# using a priority queue limits it to 5 ids
# explanation of complexity:
# https://leetcode.com/problems/high-five/discuss/350178/is-complexity-n-log-5
class Solution(object):
def highFive(self, items):
"""
:type items: List[List[int]]
:rtype: List[List[int]]
"""
dic = {}
for idx,score in items:
if idx in dic:
h = dic[idx]
if len(h) < 5:
heapq.heappush(h, score)
else:
heapq.heappushpop(h, score)
else:
h = [score]
heapq.heapify(h)
dic[idx] = h
return [[idx, sum(res)//len(res) ] for idx, res in dic.items()]
|
078e99e14d85bbfc2bb49ab01a2245148a2755b9 | chang821606/storebook | /python_base/day15/exercise03.py | 328 | 3.53125 | 4 |
# 练习:定义函数,在控制台中获取成绩.
# 要求:如果异常,则继续获取成绩,直到正确为止.
def get_score():
while True:
try:
score = int(input("请输入成绩:"))
return score
except:
print("输入有误")
score = get_score()
print(score)
|
db1bf5ce48282b96228cb67f6fe590dea3a88d5c | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Trees/Checking_and_Printing/13_check_full_binary_tree_iterative.py | 723 | 4 | 4 | ''' Check is tree is full binary tree - Iterative '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def check_full(root):
q = []
q.append(root)
while len(q) > 0:
node = q.pop(0)
if not node.left and node.right:
return False
if node.left and not node.right:
return False
if node.right and node.left:
q.append(node.right)
q.append(node.left)
return True
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print check_full(root)
|
be8334c815cc34f088a92667413596006ef27522 | mnstewart232/Py-Practice | /Project 1-1.py | 3,198 | 3.90625 | 4 |
#(i) find the name of the original trainer
#(ii) given any nameTrainee (denoted as givenNameTrainee), find out who trained the givenNameTrainee and who the givenNameTrainee trains.
#If givenNameTrainee does not exist in your database, or if the givenNameTrainee is a newly trained customer who has never held a training session
#before; the program should print out 'There is no such givenNameTrainee!'.
#inputs:
# inputDataCert is a list of tuples of trainer/trainee pairs
# givenNameTraineeis the search parameter
#output:
# answer_p1_q1 is a dictionary containing the four fields indicated
def solution_p1_q1(inputDataCert, givenNameTrainee):
#Name of original trainer in the dataset, set to the first pair to start.
originalTrainer = inputDataCert[0][0]
print(f"originalTrainer = {originalTrainer}")
#Name of who trained givenNameTrainee
trainedBy = ''
#List of people trained by givenNameTrainee
trainedList = []
#Boolean flag for name checking
isGivenNamePresent = False
#Iterate thru the dataset and attempt to find the first trainer.
#It should be simple - for each tuple, check if the last trainer was a trainee.
# If so, update that variable. Eventually, the first trainer will be found.
for certificate in inputDataCert:
#Error checking
if (certificate[0] == givenNameTrainee or certificate[1] == givenNameTrainee):
isGivenNamePresent = True
#If/when the trainer's name is found
if (certificate[1] == givenNameTrainee):
trainedBy = certificate[0]
#If/when this person's trainees are found:
if (certificate[0] == givenNameTrainee):
trainedList.append(certificate[1])
#Finding the original trainer:
for each in inputDataCert:
if (each[1] == originalTrainer and each[0] != ''):
originalTrainer = each[0]
#print(f"each[0] (trainer) ={each[0]}, each[1] (trainee) = {each[1]}, and originalTrainer is now {originalTrainer}")
#check if givenNameTrainee is present in the dataset. If not, return with the error message.
if (isGivenNamePresent == False):
print(f"There is no such {givenNameTrainee}!")
return
#Expected formatting of the dictionary. Note the data type of the 'train' key is an array, all others are strings.
answer_p1_q1 = { 'originalTrainer': originalTrainer, 'givenNameTrainee': givenNameTrainee, 'trainedBy': trainedBy, 'train':trainedList}
return answer_p1_q1
def main():
#Test dataset
testInputDataCert = [('Harry', 'Tim'),('Jack', 'Gary'),('Jack', 'Harry'),('Taylor', 'Glory'),
('Maria','Jim'),('Jim', 'Taylor'),('Taylor', 'Jack'),('Jim', 'Sarah'),
('Jack', 'Gary')]
testInputDataCert2 = [('Jim', 'Taylor'), ('Taylor', 'Jack'), ('Jim', 'Sarah'),
('Taylor', 'Glory'), ('Jack', 'Harry'), ('Jack', 'Gary'),
('Harry', 'Tim'), ('', 'Maria'), ('Maria','Jim')]
#Call the function given the test dataset and test search parameter
print(solution_p1_q1(testInputDataCert2, 'Jim'))
return
#Call main
main()
|
8fdcd8dabb96cc7e93bbfec1d2c9b198b1578fc3 | dreamhomes/leetcode-programming | /Array/34_find_first_and_last_position_of_element_in_sorted_array.py | 419 | 3.671875 | 4 | # -*- coding: utf-8 -*-
'''
@date: 2020-02-08
@author: dreamhomes
@description:34. 在有序数组中查找元素的起始位置。
'''
def searchRange(nums: list, target: int) -> list:
if target not in nums:
return [-1, -1]
e = nums.index(target) + 1
while e < len(nums) and nums[e] == target:
e += 1
return [nums.index(target), e-1]
print(searchRange([5, 7, 7, 8, 8, 10], 8))
|
577e369920db432d6c52bac27792f2c7b5ddb5e0 | sk610/Learn-Python-3-The-Hard-Way | /Exercises/21-30/ex29.py | 811 | 3.8125 | 4 | people = 30
cats = 100
dogs = 45
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are dogs.")
if True:
print("test")
"""
Study Drills
1. What do you think the if does to the code under it?
It basically tells Python to read what each variable means and act based on the response.
2. To show that it belongs to that block of code.
3. It won't work. IndentationError.
4. Yes.
5. The answers will change.
"""
|
befce054f9c8a010c5f18ebbd308ce595a5a2b0e | IT-Department-Projects/PC-Project | /parallel code/k_means_linear.py | 8,851 | 3.515625 | 4 | #!/usr/bin/env python
import numpy as np
from PIL import Image
import random
class kmeans():
"""Cluster pixels by k means algorithm"""
def __init__(self, filepath, k = 10):
self.img = Image.open(filepath)
self.img.show()
self.k = k
# initialize pixel map = m x n array (row by column rather than x & y)
self.arr = np.array(self.img)
m, n, _ = self.arr.shape
idx_lst = [ (j,k) for j in xrange(m) for k in xrange(n) ]
k_vals = random.sample(idx_lst, self.k)
# initialize list containing dictionary of k starting values (centroids)
# must convert np array to hashable type (tuple) for key
# will append to list after each stage of clustering, so access most recent by [-1] index
self.d_k_clusters = { (k_mn + tuple(self.arr[k_mn])): [] for k_mn in k_vals }
self.d_k_clusters_lst = [self.d_k_clusters]
# 3D numpy array populated with arrays representing corresponding [row, column]
self.idx_arr = np.array(idx_lst).reshape((m, n, 2))
def minimize_distance(self, pixel, metric):
"""Given tuple representing pixel in image, return centroid that minimizes distance by given metric"""
dists = [ (k, metric(np.array(pixel), np.array(k))) for k in self.d_k_clusters.iterkeys() ]
# find tuple representing best k group by minimizing distance
best_k, _ = min( dists, key = lambda t: t[1] )
return best_k
def minimize_distance_arr(self, pixel, metric):
"""Given np array representing pixel in image, return centroid that minimizes distance by given metric"""
dists = [ (k, metric(pixel, np.array(k))) for k in self.d_k_clusters.iterkeys() ]
# find np array representing best k group by minimizing distance
best_k, _ = min( dists, key = lambda t: t[1] )
return best_k
def assign_pixels_for_loop(self, metric):
"""Clusters pixels by iterating over numpy array with for loop"""
def mn2mnrgb(self, t_mn):
"""Given (m,n) of pixel, returns np array of [ m, n, R, G, B ]"""
return np.append(t_mn, self.arr[t_mn[0], t_mn[1]])
for tup in ( (m,n) for m in xrange(0, self.arr.shape[0]) \
for n in xrange(0, self.arr.shape[1]) ):
# convert (m, n) of pixel location to ((m, n), (r, g, b))
tval = self.mn2mnrgb(tup)
# Append to dictionary value list corresponding to key of k-mean
# that minimizes distance by given metric
self.d_k_clusters[ self.minimize_distance( tval, metric ) ].append(tval)
def assign_pixels_nditer(self, metric):
"""Assign all pixels in image to closest matching group in self.d_k_groups, according to given distance metric, by iterating over numpy array of pixels with np.nditer method"""
#print 'assigning pixels'
#TODO: implement itertools.groupby before appending to dictionary ??
#clusters = []
#data = sorted()
# try iterating over numpy array by adding multi-index to nditer
# (iterates over 1-D array)
it = np.nditer(self.arr, flags=['multi_index'])
tval = []
# use C-style do-while in order to access index at each value
while not it.finished:
# it.multi_index yields (i, j, index of RGB val) - where index is 0,1,2
# it[0] at that index yields array(value, dtype=uint8)
# tval = [i,j] + [R,G,B]
i, j, rgb_i = it.multi_index
# initialize tval with i,j position in array
if rgb_i == 0:
tval = [i, j]
# accumulate successive R,G,B values onto tval
tval.append(int(it[0]))
# end of R,G,B values corresponding to that position i,j in array
if rgb_i == 2:
# update cluster dictionary with tval and clear for next value
self.d_k_clusters[ self.minimize_distance( tval, metric ) ].append(tval)
tval = []
it.iternext()
def assign_pixels_map(self, metric):
# try mapping array index onto r,g,b pixel value to generate array of (m,n,r,g,b) values
self.arr_extended = np.concatenate((self.idx_arr, self.arr), axis=2)
def update_clusters(pixelval):
self.d_k_clusters[ self.minimize_distance( pixelval, metric ) ].append(pixelval)
return pixelval
np.apply_along_axis(update_clusters, 2, self.arr_extended)
def generate_image(self, warholize=False):
"""Once all pixels have been assigned to k clusters, use d_k_clusters to generate image data, with new pixel values determined by mean RGB of the cluster, or random color palette if warholize=True"""
def mean_rgb(k):
"""Given key value in self.d_k_clusters, return k mean by averaging (r,g,b) value over all values in group"""
val_arr = np.array(self.d_k_clusters[k])
# returns np array of ints corresponding to R,G,B
return np.mean(val_arr, axis=0).astype(int)[-3:]
if warholize:
random_colors = random_color_palette(self.k)
self.new_arr = np.empty(self.arr.shape, dtype=np.uint8)
#print 'putting pixels'
for i, (k, v_lst) in enumerate(self.d_k_clusters.iteritems()):
#print '.'
pixelval = ( random_colors[i] if warholize else mean_rgb(k) )
for m, n, _r, _g, _b in v_lst:
self.new_arr[m, n] = pixelval
self.new_img = Image.fromarray(self.new_arr)
self.new_img.show()
def generate_image_2(self, warholize=False):
"""Once all pixels have been assigned to k clusters, use d_k_clusters to generate image data, with new pixel values determined by mean RGB of the cluster, or random color palette if warholize=True"""
def mean_mnrgb(v_lst):
"""Given list of values in self.d_k_clusters.values(),
return new centroid by averaging (m,n,r,g,b) over all values in group"""
new_centroid = np.mean( np.array(v_lst), axis=0 )
return tuple(new_centroid)
# iterating while changing dict causes weird behavior!
## update dictionary keys with new centroid values
#for k in self.d_k_clusters.iterkeys():
#self.d_k_clusters[mean_mnrgb(k)] = self.d_k_clusters.pop(k)
# updated centroids!
self.d_k_clusters_lst.append( { mean_mnrgb(v): v for v in self.d_k_clusters.itervalues() } )
self.d_k_clusters = self.d_k_clusters_lst[-1]
self.new_arr = np.empty(self.arr.shape, dtype=np.uint8)
if warholize:
random_colors = random_color_palette(self.k)
for i, (k, v_lst) in enumerate(self.d_k_clusters.iteritems()):
pixelval = ( random_colors[i] if warholize else [int(rgb) for rgb in k[-3:]] )
for m, n, _r, _g, _b in v_lst:
self.new_arr[m, n] = pixelval
self.new_img = Image.fromarray(self.new_arr)
self.new_img.show()
def euclidean_dist_np(p1,p2):
"""Compute Euclidean distance between 2 pts (np arrays) of any (equal) dimensions
using numpy's Linear Alg norm
IN: two np arrays
OUT: float"""
return np.linalg.norm(p1-p2)
# inspired by http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
def random_color_palette(n, RGB=True):
"""Generates a random, aesthetically pleasing set of n colors (list of RGB tuples if RGB; else HSV)"""
SATURATION = 0.6
VALUE = 0.95
GOLDEN_RATIO_INVERSE = 0.618033988749895
# see: https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB
def hsv2rgb(hsv):
h, s, v = hsv
# compute chroma
c = v*s
h_prime = h*6.0
x = c*( 1 - abs(h_prime %2 - 1) )
if h_prime >= 5: rgb = (c,0,x)
elif h_prime >= 4: rgb = (x,0,c)
elif h_prime >= 3: rgb = (0,x,c)
elif h_prime >= 2: rgb = (0,c,x)
elif h_prime >= 1: rgb = (x,c,0)
else: rgb = (c,x,0)
m = v-c
return tuple( int(255*(val+m)) for val in rgb )
# random float in [0.0, 1.0)
hue = random.random()
l_hues = [hue]
for i in xrange(n-1):
# generate evenly distributed hues by random walk using the golden ratio!
# (mod 1, to stay within hue space)
hue += GOLDEN_RATIO_INVERSE
hue %= 1
l_hues.append(hue)
if not RGB:
return [ (h, SATURATION, VALUE) for h in l_hues ]
return [ hsv2rgb((h, SATURATION, VALUE)) for h in l_hues ]
def implement(infile, k, warholize=False):
x = kmeans(infile, k=k)
x.assign_pixels_map(metric=euclidean_dist_np)
x.generate_image_2(warholize=warholize)
FILE_IN = 'lena.png'
K=90
if __name__ == "__main__":
implement(FILE_IN, K)
|
b35590837eeec1197117206f7790508276c4490c | SinCatGit/leetcode | /00077/combinations.py | 1,471 | 3.953125 | 4 | from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
"""
https://leetcode.com/problems/combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Parameters
----------
n: int
k: int
Returns
-------
List[List[int]]
Examples
--------
>>> sol = Solution()
>>> sorted(sol.combine(4, 2))
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3,4]]
Notes
-----
References
---------
.. [1] https://leetcode.com/problems/combinations/discuss/27024/1-liner-3-liner-4-liner
.. [2] https://leetcode.com/problems/combinations/discuss/27202/Fast-and-simple-python-code-.-recursive
"""
if k == 1:
return [[i] for i in range(1, n+1)]
if k == n:
return [list(range(1, n+1))]
if k < 1 or k > n:
return []
used = self.combine(n-1, k)
part = self.combine(n-1, k-1)
return used + [item+[n] for item in part]
def combineV01(self, n, k):
from itertools import combinations
return [ list(item) for item in combinations(range(1, n+1), k)]
|
c2497d26248860db4aafd4ee2bc68ede9b515f3b | tmcclintock/DND-Maths | /Random-Fighter/Skills.py | 356 | 3.5625 | 4 | """
This contains the random skills object,
which itself connects to a list of the
possible skills and also provides
the ability to select random feats.
"""
import random
class Skill(object):
def __init__(self,name,):
self.name = name
return
def __str__(self):
return "\t%s"%(self.name)
class Random_Skills(object):
|
e11ef1706d02444ff00d99dd7470a295a70d6a82 | YihaoGuo2018/leetcode_python_2 | /Convert Sorted Array to Binary Search Tree.py | 1,092 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
# Form an array out of the given linked list and then
# use the array to form the BST.
values = head
# l and r represent the start and end of the given array
def convertListToBST(l, r):
# Invalid case
if l > r:
return None
# Middle element forms the root.
mid = (l + r) // 2
node = TreeNode(values[mid])
# Base case for when there is only one element left in the array
if l == r:
return node
# Recursively form BST on the two halves
node.left = convertListToBST(l, mid - 1)
node.right = convertListToBST(mid + 1, r)
return node
return convertListToBST(0, len(values) - 1) |
f8788d53b197b71fe28834fdea352a8ee0e2ef82 | sashaobucina/interview_prep | /python/medium/longest_palindromic_substring.py | 3,888 | 3.984375 | 4 | def longest_palindrome_naive(s: str) -> str:
"""
# 5: Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Naive sol'n:
- Time complexity: O(n^3)
- Space complexity: O(1)
"""
N = len(s)
max_len = 1
start, end = 0, 0
def is_palindrome(L: int, R: int) -> bool:
while L < R:
if s[L] != s[R]:
return False
L += 1
R -= 1
return True
for L in range(N):
for R in range(L, N):
if (R - L + 1) > max_len and is_palindrome(L, R):
max_len = (R - L + 1)
start, end = L, R
return s[start: end + 1]
def longest_palindrome_dp(s: str) -> str:
"""
This solution uses a DP approach.
Recurrence relation:
- T[L][R] = T[L + 1][R - 1] && s[L] == s[R]
The row indices of the DP table signify the left pointer (L) of the string, and the column indices
of the DP table signify the right pointer (R).
Traverse L (rows) in reverse order, and R (columns) in regular order starting 2 spots from L.
eg "d a b b a d" -> perform check of T[L][R] == T[L + 1][R - 1] && s[L] && s[R]
| |_________| |
| L+1, R-1 |
| |
L R
DP sol'n:
- Time complexity: O(n^2)
- Space complexity: O(n^2)
"""
if not s:
return ""
N = len(s)
max_len = 1
start, end = 0, 0
# initalize memo table to store overlapping subproblems
dp = [[0 for _ in range(N)] for _ in range(N)]
# Base cases: T[L][L] = 1 and T[L][L + 1] = int(s[L] == s[L + 1])
for L in range(N):
dp[L][L] = 1
for L in range(N - 1):
if s[L] == s[L + 1]:
dp[L][L + 1] = 1
max_len, start, end = 2, L, L + 1
# Recurrence relation: T[L][R] = T[L+1][R-1] && s[L] == s[R]
for L in range(N - 1, -1, -1):
for R in range(L + 2, N):
if dp[L + 1][R - 1] and s[L] == s[R]:
dp[L][R] = 1
if (R - L + 1) > max_len:
max_len = (R - L + 1)
start, end = L, R
return s[start: end + 1]
def longest_palindrome(s: str) -> str:
"""
Start from middle index and expand from center until no longer a plaindrome. Run this twice for
even and odd case.
eg. even case -> "a a b b a a"
|
mid
eg. odd case -> "a a b d b a a"
|
mid
Optimized sol'n:
- Time complexity: O(n^2)
- Space complexity: O(1)
"""
if not s:
return ""
N = len(s)
start, end = 0, 0
def _expand_from_center(left: int, right: int) -> int:
L, R = left, right
while L >= 0 and R < N and s[L] == s[R]:
L -= 1
R += 1
return R - L - 1
for i in range(N):
l1 = _expand_from_center(i, i) # -> even case
l2 = _expand_from_center(i, i + 1) # -> odd case
max_len = max(l1, l2)
if max_len > (end - start):
start = i - (max_len - 1) // 2
end = i + max_len // 2
return s[start: end + 1]
if __name__ == "__main__":
assert longest_palindrome("cbbd") == "bb"
assert longest_palindrome_naive("cbbd") == "bb"
assert longest_palindrome_dp("cbbd") == "bb"
assert longest_palindrome("babad") in ["bab", "aba"]
assert longest_palindrome_naive("babad") in ["bab", "aba"]
assert longest_palindrome_dp("babad") in ["bab", "aba"]
assert longest_palindrome("heracecarls") == "racecar"
assert longest_palindrome_naive("heracecarls") == "racecar"
assert longest_palindrome_dp("heracecarls") == "racecar"
print("Passed all tests!")
|
8f4c4c6f79777c03e1ccee2fe249b4f3a177e0de | bsvonkin/Year9DesignCS4-PythonBS | /LoopDemo.py | 1,198 | 4.25 | 4 | #A loop is a programming structure that can repeat a section of code
#A loop can run the same code sxzctly over and over or with do,e thought it can generate a pattern
#There are two borad categories of loops
#Conditional Loops (While): There loop as a long as a condition is true
#Counted loops(for): These loop using a counter to keep track of how many of thr loop has run.
#You can use any loop in any situation, but usually from deign perspective there is a better loop in terms of coding
#If you kno in advance how many times a loop should run a COUNTED LOOP is usually a better choice
#If you don't know how many timed a loop should tun a CONDITIONAL LOOP is usually a better choice
print("************************************************")
#Taking Inputs
word = ""
while (len(word) < 6 or word.isalpha() == False):
#Loop block
word = input("Please input a word larger than 5 letters: ")
print(word.isalpha())
if (len(word) < 6):
print("Big Manz, I said less than five letters")
if (word.isalpha() == False):
print("Big Manz, I said a real word")
print(word+" is a seriously long word!")
#Do not use while loops to control inputs with GUI programs
|
83a38ae414251344edeb6c23303e9a0fb26e402c | jabedkhanjb/Hackerrank | /Python/Itertools/itertools.combinations().py | 944 | 4.03125 | 4 | """
# itertools.combinations()
# itertools.combinations(iterable, r)
# This tool returns the r length subsequences of elements from the input iterable.
# Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in
# sorted order.
# Task
# You are given a string S.
# Your task is to print all possible combinations, up to size k, of the string in lexicographic sorted order.
# Input Format
# A single line containing the string S and integer value k separated by a space.
# Constraints
# 0 < k <= len(S)
# The string contains only UPPERCASE characters.
# Output Format
# Print the different combinations of string S on separate lines.
# Enter your code here. Read input from STDIN. Print output to STDOUT
"""
from itertools import *
s,k = raw_input().split()
for j in range(1,int(k) + 1):
for i in combinations(sorted(s),int(j)):
print("".join(i))
|
cb0978074e6e2bc7aa059e093cc164555113a4ac | aymannc/LeetCode | /sum-of-left-leaves.py | 1,262 | 4.0625 | 4 | # Definition for a binary tree node.
"""
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
"""
import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sum_of_left_leaves(self, root: TreeNode) -> int:
if not root: return 0
some = 0
q = collections.deque([(0, root)])
while q:
type_n, head = q.popleft()
if type_n and head.left is None and head.right is None:
some += head.val
else:
if head.left is not None:
q.append((1, head.left))
if head.right is not None:
q.append((0, head.right))
return some
# root = TreeNode(3)
# root.right = TreeNode(20)
# root.right.right = TreeNode(7)
# root.right.left = TreeNode(15)
# root.left = TreeNode(9)
root = TreeNode(1)
root.right = TreeNode(2)
root.right.right = TreeNode(6)
root.right.left = TreeNode(5)
root.left = TreeNode(3)
root.left.left = TreeNode(4)
print(Solution().sum_of_left_leaves(root))
|
22c1f32c75e3ea2c9cb5ce3b76e57f6bd90d14b9 | mzhuang1/DemandManagement | /simulator/simulator/appliance.py | 27,596 | 3.671875 | 4 | #!/usr/bin/env python3
import datetime
import math
import random
from abc import ABC, abstractmethod, abstractclassmethod
from types import SimpleNamespace
import numpy
from . import applianceStatistics
from . import utils
from .constants import oneDay
from .profile import Profile
from .utils import minutesIn
# abstract base class for household appliances
class Appliance(ABC):
# current date and time in the simulation
currentDT: datetime.datetime
# an object for storing information between demand calculations
memory: SimpleNamespace
# appliance usage statistics
usageStatistics: applianceStatistics.ApplianceStatistics
# the electricity price for any given minute in the simulation
priceProfile: Profile
# the electricity demand of this appliance if it was smart
smartDemand: Profile
# the electricity demand of this appliance if it would charge as early as possible
uncontrolledDemand: Profile
# the electricity demand of this appliance if it would charge evenly over their use period
spreadOutDemand: Profile
# constructor, just prepares the variables
def __init__(self):
self.memory = SimpleNamespace()
self.priceProfile = Profile()
self.smartDemand = Profile()
self.uncontrolledDemand = Profile()
self.spreadOutDemand = Profile()
# creates a random appliance with the right parameters
@abstractclassmethod
def random(cls):
pass
# sets up the appliance for the simulation
def setUp(self, dt: datetime.datetime):
self.currentDT = dt
# generate usage for one day in the future
self.generateUsage(dt, dt + oneDay)
# moves ahead one day and does all the calculations that need to be done in that day
def tick(self):
# remove past, unneeded values from the profiles to free up some memory
self.priceProfile.prune(self.currentDT - oneDay)
self.smartDemand.prune(self.currentDT - oneDay)
self.uncontrolledDemand.prune(self.currentDT - oneDay)
self.spreadOutDemand.prune(self.currentDT - oneDay)
# generate appliance usage for one more day in the future
self.generateUsage(self.currentDT + oneDay, self.currentDT + 2 * oneDay)
# calculate the power demand for the next day
self.calculateDemand(self.currentDT, self.currentDT + oneDay)
# move ahead one day
self.currentDT += oneDay
# generates appliance usage for a given time interval
@abstractmethod
def generateUsage(self, fromDT: datetime.datetime, toDT: datetime.datetime):
pass
# calculates appliance power demand for a given time interval
def calculateDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
self.calculateSmartDemand(fromDT, toDT)
self.calculateUncontrolledDemand(fromDT, toDT)
self.calculateSpreadOutDemand(fromDT, toDT)
# calculates appliance power demand for a given time interval acting as if the appliance was smart
@abstractmethod
def calculateSmartDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
pass
# calculates appliance power demand for a given time interval acting as if if it would charge as early as possible
@abstractmethod
def calculateUncontrolledDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
pass
# calculates appliance power demand for a given time interval acting as if if it would charge evenly over the use period
@abstractmethod
def calculateSpreadOutDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
pass
# sets the electricity price profile for a given time interval
def setPriceProfile(self, dt: datetime.datetime, prices: numpy.ndarray):
self.priceProfile.set(dt, prices)
# abstract base class for battery-based household appliances (e.g. electric car)
class Battery(Appliance, ABC):
# appliance usage statistics
usageStatistics: applianceStatistics.BatteryStatistics
# the power with which the battery charges
chargingPower: float # kW
# constructor, just prepares the variables
def __init__(self, chargingPower: float = 0):
self.chargingPower = chargingPower
super().__init__()
# for each day keeps disconnection time, connection time and charge needed after the usage
self.memory.usages = dict()
# creates a random appliance with the right parameters
@classmethod
def random(cls):
chargingPower = cls.usageStatistics.randomChargingPower()
return cls(chargingPower=chargingPower)
# generates appliance usage for a given time interval
def generateUsage(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# we need to know the usage for one day ahead (at least the disconnect time)
for midnight in utils.midnightsBetween(fromDT, toDT+oneDay):
date = midnight.date()
if date not in self.memory.usages:
disconnectionTime, connectionTime = self.usageStatistics.randomUsageInterval(date)
# if the values are invalid make up an usage interval giving us as much charging time as possible
if disconnectionTime is None:
disconnectionTime = datetime.time(23, 59)
if connectionTime is None:
connectionTime = datetime.time(00, 00)
chargeNeeded = self.usageStatistics.randomNeededCharge(date)
self.memory.usages[date] = ((disconnectionTime, connectionTime), chargeNeeded)
# calculates appliance power demand for a given time interval acting as if the appliance was smart
def calculateSmartDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# for each day in the interval, it charges the battery in the minutes with the cheapest electricity available
for midnight in utils.midnightsBetween(fromDT, toDT):
date = midnight.date()
powerProfile = numpy.zeros(2*minutesIn(oneDay), dtype=float)
# get the needed charge and the interval when the battery is connected
((_, connectionTime), chargeNeeded) = self.memory.usages[date]
((disconnectionTime, _), _) = self.memory.usages[date + oneDay]
# get for how long the battery must be charged
chargePerSlot = self.chargingPower / 60 # kWh per minute
slotsToChargeCompletely = math.ceil(chargeNeeded / chargePerSlot)
# if it needs to be charged, charge it
if slotsToChargeCompletely > 0:
connectionSlot = connectionTime.hour * 60 + connectionTime.minute
disconnectionSlot = minutesIn(oneDay) + disconnectionTime.hour * 60 + disconnectionTime.minute
# if there is not enough time to charge the battery completely, just charge it all the available time
if disconnectionSlot - connectionSlot <= slotsToChargeCompletely:
powerProfile[connectionSlot:disconnectionSlot] = self.chargingPower
# otherwise pick enough of the cheapest time slots and charge the battery during those
else:
priceProfile = self.priceProfile.get(midnight, midnight+2*oneDay)
cheapestSlots = numpy.argpartition(priceProfile[connectionSlot:disconnectionSlot], slotsToChargeCompletely)[:slotsToChargeCompletely] + connectionSlot
powerProfile[cheapestSlots[:-1]] = self.chargingPower
lastSlotCharge = chargeNeeded - (chargePerSlot * (slotsToChargeCompletely - 1))
powerProfile[cheapestSlots[-1]] = lastSlotCharge * 60
self.smartDemand.add(midnight, powerProfile)
# calculates appliance power demand for a given time interval acting as if the battery wanted to charge as early as possible
def calculateUncontrolledDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# for each day in the interval, the appliance starts charging the battery as soon as it is connected to power
for midnight in utils.midnightsBetween(fromDT, toDT):
date = midnight.date()
powerProfile = numpy.zeros(2*minutesIn(oneDay), dtype=float)
# get the needed charge and the interval when the battery is connected
((_, connectionTime), chargeNeeded) = self.memory.usages[date]
((disconnectionTime, _), _) = self.memory.usages[date + oneDay]
# get for how long the battery must be charged
chargePerSlot = self.chargingPower / 60
slotsToChargeCompletely = math.ceil(chargeNeeded / chargePerSlot)
# if it needs to be charged, charge it
if slotsToChargeCompletely > 0:
connectionSlot = connectionTime.hour * 60 + connectionTime.minute
disconnectionSlot = minutesIn(oneDay) + disconnectionTime.hour * 60 + disconnectionTime.minute
# if there is not enough time to charge the battery completely, just charge it all the available time
if disconnectionSlot - connectionSlot < slotsToChargeCompletely:
powerProfile[connectionSlot:disconnectionSlot] = self.chargingPower
# otherwise start charging it as soon as it is available and charge until it's full
else:
powerProfile[connectionSlot:connectionSlot+slotsToChargeCompletely-1] = self.chargingPower
lastSlotCharge = chargeNeeded - (chargePerSlot * (slotsToChargeCompletely - 1))
powerProfile[connectionSlot+slotsToChargeCompletely] = lastSlotCharge * 60
self.uncontrolledDemand.add(midnight, powerProfile)
# calculates appliance power demand for a given time interval acting as if the battery wanted to charge as evenly as possible
def calculateSpreadOutDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# for each day in the interval, the appliance starts charging the battery as soon as it is connected to power
for midnight in utils.midnightsBetween(fromDT, toDT):
date = midnight.date()
powerProfile = numpy.zeros(2*minutesIn(oneDay), dtype=float)
# get the needed charge and the interval when the battery is connected
((_, connectionTime), chargeNeeded) = self.memory.usages[date]
((disconnectionTime, _), _) = self.memory.usages[date + oneDay]
# get for how long the battery must be charged
chargePerSlot = self.chargingPower / 60
slotsToChargeCompletely = math.ceil(chargeNeeded / chargePerSlot)
# if it needs to be charged, charge it
if slotsToChargeCompletely > 0:
connectionSlot = connectionTime.hour * 60 + connectionTime.minute
disconnectionSlot = minutesIn(oneDay) + disconnectionTime.hour * 60 + disconnectionTime.minute
# if there is not enough time to charge the battery completely, just charge it all the available time
if disconnectionSlot - connectionSlot < slotsToChargeCompletely:
powerProfile[connectionSlot:disconnectionSlot] = self.chargingPower
# otherwise charge it evenly over the whole connected period
else:
powerProfile[connectionSlot:disconnectionSlot] = chargeNeeded / ((disconnectionSlot - connectionSlot) / 60)
self.spreadOutDemand.add(midnight, powerProfile)
# abstract base class for accumulator-based household appliances (e.g. water heater, refrigerator)
class Accumulator(Appliance, ABC):
# appliance usage statistics
usageStatistics: applianceStatistics.AccumulatorStatistics
# the power with which the appliance charges
chargingPower: float # kW
# the charging capacity of the appliance
capacity: float # kWh
# constructor, just prepares the variables
def __init__(self, chargingPower: float, capacity: float, dischargingProfileScale: float):
super().__init__()
self.chargingPower = chargingPower
self.capacity = capacity
# variables for storing the state of the appliance between calculations
self.memory.dischargingProfileScale = dischargingProfileScale
self.memory.smart = SimpleNamespace()
self.memory.smart.currentCharge = random.random() * self.capacity
self.memory.uncontrolled = SimpleNamespace()
self.memory.uncontrolled.currentCharge = self.capacity
self.memory.spreadOut = SimpleNamespace()
self.memory.spreadOut.charging = random.choice([True, False])
self.memory.spreadOut.currentCharge = random.random() * self.capacity
# the profile of how the accumulator discharges (e.g. water heater cools down or gets used, fridge heats up)
self.memory.dischargingProfile = Profile()
# creates a random accumulator with the right parameters
@classmethod
def random(cls):
chargingPower = cls.usageStatistics.randomChargingPower()
# in this simulator we can't have an appliance which would charge up faster than in one minute
capacity = max(cls.usageStatistics.randomCapacity(), (1.1*chargingPower/60))
# stronger appliances are usually those which get used more, so scale the random discharging profile by the charging power of the appliance
dischargingProfileScale = cls.usageStatistics.randomDischargingProfileScale() * (chargingPower / cls.usageStatistics.averageChargingPower)
return cls(chargingPower, capacity, dischargingProfileScale)
# moves ahead one day and does all the calculations that need to be done in that day
def tick(self):
# remove past, unneeded values from the profiles to free up some memory
self.memory.dischargingProfile.prune(self.currentDT - oneDay)
super().tick()
# generates appliance usage for a given time interval
def generateUsage(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# generate how much will the accumulator discharge during that interval
dischargingProfile = self.usageStatistics.dischargingProfile.get(fromDT, toDT) * self.memory.dischargingProfileScale
self.memory.dischargingProfile.set(fromDT, dischargingProfile)
# calculates appliance power demand for a given time interval acting as if the appliance was smart
def calculateSmartDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# adapted from https://ktiml.mff.cuni.cz/~fink/publication/greedy.pdf
# asymptotically, this would be faster with prefix sum trees or union-find data structures
# but in Python that is actually spreadOuter than using a quadratic algorithm with numpy
# the limit preparation, which is linear, is spreadOuter than the actual algorithm anyway, so it doesn't matter
# get the cheapest slots in which to turn on the appliance so that it never discharges under its lower limit and never charges over its upper limit
# normally, the appliance doesn't charge more than it needs to, so at the end of the interval it would be charged barely above the lower limit
# then at the start of the next calculated interval it would need to charge more to catch up
# we calculate the charging profile with a bit of an overlap to avoid this
endMargin = oneDay
wantedSlots = utils.minutesBetween(fromDT, toDT)
totalSlots = utils.minutesBetween(fromDT, toDT+endMargin)
# the electricity prices in the interval
priceProfile = self.priceProfile.get(fromDT, toDT+endMargin)
# how much energy goes into the appliance each minute it's turned on
chargingRate = self.chargingPower / 60 # kWh per minute
# how much energy leaves the appliance each minute of the interval
dischargingRates = self.memory.dischargingProfile.get(fromDT, toDT+endMargin) / 60 # kWh per minute for each minute
startingCharge = self.memory.smart.currentCharge # kWh
# never discharge past 0 and never charge over the capacity
lowerTarget = 0 # kWh
upperTarget = self.capacity # kWh
# convert the limits and charging rates to integer steps
dischargingSum = numpy.cumsum(dischargingRates) # total kWh cumulatively discharged for each minute
lowerLimit = numpy.ceil((lowerTarget - startingCharge + dischargingSum) / chargingRate).astype(int)
upperLimit = numpy.floor((upperTarget - startingCharge + dischargingSum) / chargingRate).astype(int)
lowerLimit = numpy.maximum(lowerLimit, 0)
upperLimit = numpy.minimum(upperLimit, totalSlots)
# cut the limits to all the reachable charge values
for i in range(totalSlots - 1):
if lowerLimit[i+1] < lowerLimit[i]:
lowerLimit[i+1] = lowerLimit[i]
if upperLimit[i+1] < upperLimit[i]:
upperLimit[i+1] = upperLimit[i]
for i in reversed(range(totalSlots - 1)):
if lowerLimit[i] < lowerLimit[i+1] - 1:
lowerLimit[i] = lowerLimit[i+1] - 1
if upperLimit[i] < upperLimit[i+1] - 1:
upperLimit[i] = upperLimit[i+1] - 1
for i in range(totalSlots):
if lowerLimit[i] > i:
lowerLimit[i] = i
else:
break
for i in range(totalSlots):
if upperLimit[i] > i + 1:
upperLimit[i] = i + 1
else:
break
# the profile of how the appliance will charge, 1 for every slot it will charge, 0 otherwise
chargingProfile = numpy.zeros(totalSlots)
# starting point of the algorithm is 0
lowerLimit = numpy.concatenate(([0], lowerLimit))
upperLimit = numpy.concatenate(([0], upperLimit))
# the charging slots ordered from cheapest slot to most expensive slot
cheapestOrder = numpy.argsort(priceProfile)
for slot in cheapestOrder:
# if the appliance can be turned on at that slot, turn it on and update the limits
if lowerLimit[slot] < upperLimit[slot+1] and lowerLimit[slot] < lowerLimit[-1]:
chargingProfile[slot] = 1
# update the limits to what's newly possible now
lowerSlot = (lowerLimit > lowerLimit[slot]).argmax()
upperSlot = (upperLimit == upperLimit[slot+1]).argmax()
lowerLimit[lowerSlot:] -= 1
upperLimit[upperSlot:] -= 1
# save the new charge level for the appliance
self.memory.smart.currentCharge = startingCharge - dischargingSum[wantedSlots-1] + numpy.sum(chargingProfile[:wantedSlots]) * chargingRate
# get the power profile for the charging interval and save it
powerProfile = chargingProfile[:wantedSlots] * self.chargingPower
self.smartDemand.set(fromDT, powerProfile)
# calculates appliance power demand for a given time interval acting as if the accumulator wanted to stay as charged as possible
def calculateUncontrolledDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# simulates an uncontrolled charging algorithm, when an appliance wants to have as much energy stored as possible
# how much energy goes into the appliance each minute it's turned on
chargingRate = self.chargingPower / 60 # kWh per minute
# how much energy leaves the appliance each minute of the interval
dischargingRates = self.memory.dischargingProfile.get(fromDT, toDT) / 60 # kWh per minute for each minute
# never discharge past 0 and never charge over the capacity
upperLimit = self.capacity # kWh
# get the current charge from memory
charge = self.memory.uncontrolled.currentCharge
# the power profile for the interval
totalSlots = utils.minutesBetween(fromDT, toDT)
powerProfile = numpy.zeros(totalSlots)
# simulate the progression of charge during the interval
for slot in range(totalSlots):
charge -= dischargingRates[slot]
if charge + chargingRate < upperLimit:
charge += chargingRate
powerProfile[slot] = self.chargingPower
# save the new charge level to memory
self.memory.uncontrolled.currentCharge = charge
# save the calculated demand
self.uncontrolledDemand.set(fromDT, powerProfile)
# calculates appliance power demand for a given time interval acting as if the accumulator wanted to always charge completely and then discharge completely
def calculateSpreadOutDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# simulates a thermostat-based charging, when an appliance starts charging when it discharges past some threshhold, and stops charging when it's fully charged
# how much energy goes into the appliance each minute it's turned on
chargingRate = self.chargingPower / 60 # kWh per minute
# how much energy leaves the appliance each minute of the interval
dischargingRates = self.memory.dischargingProfile.get(fromDT, toDT) / 60 # kWh per minute for each minute
# never discharge past 0 and never charge over the capacity
lowerLimit = 0 # kWh
upperLimit = self.capacity # kWh
# get the current charge from memory
charge = self.memory.spreadOut.currentCharge
# get if we're charging right now from memory
charging = self.memory.spreadOut.charging
# the power profile for the interval
totalSlots = utils.minutesBetween(fromDT, toDT)
powerProfile = numpy.zeros(totalSlots)
# simulate the progression of charge during the interval
for slot in range(totalSlots):
charge -= dischargingRates[slot]
if charging:
if charge + chargingRate > upperLimit:
charging = False
else:
if charge <= lowerLimit:
charging = True
if charging:
charge += chargingRate
powerProfile[slot] = self.chargingPower
# save the new charge level and if it was charging and the end of the interval
self.memory.spreadOut.currentCharge = charge
self.memory.spreadOut.charging = charging
# save the calculated demand
self.spreadOutDemand.set(fromDT, powerProfile)
# abstract base class for machine-like household appliances (e.g. dishwasher, washing machine)
class Machine(Appliance, ABC):
# appliance usage statistics
usageStatistics: applianceStatistics.MachineStatistics
# constructor, just prepares the variables
def __init__(self):
super().__init__()
# for each day keeps time the appliance should start after, time it should finish by and the usage profile of that run of the appliance
self.memory.usages = dict()
# creates a random appliance with the right parameters
@classmethod
def random(cls):
return cls()
# generates appliance usage for a given interval
def generateUsage(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# for each day decide if the appliance will be used at all,
# and if so, generate the time the appliance should start after, time it should finish by
# and the usage profile of that run of the appliance
for midnight in utils.midnightsBetween(fromDT, toDT):
date = midnight.date()
if date not in self.memory.usages:
if random.random() < self.usageStatistics.usageProbabilities[date]:
startAfter = self.usageStatistics.randomStartAfter()
finishBy = self.usageStatistics.randomFinishBy()
powerUsageProfile = self.usageStatistics.randomUsageProfile()
self.memory.usages[date] = ((startAfter, finishBy), powerUsageProfile)
else:
self.memory.usages[date] = None
# calculates appliance power demand for a given time interval acting as if the appliance was NOT smart
def calculateSmartDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# for each day in the interval, calculate the best time to start the appliance so that the run would be the cheapest
for midnight in utils.midnightsBetween(fromDT, toDT):
date = midnight.date()
# the power profile of that day (plus some overlap)
powerProfile = numpy.zeros(2 * utils.minutesIn(oneDay))
# get the appliance usage for that day and act accordingly
usage = self.memory.usages[date]
if usage is not None:
# the price for the interval
priceProfile = self.priceProfile.get(midnight, midnight+2*oneDay)
# the slots in which the appliance is available for being turned on
((startAfter, finishBy), powerUsageProfile) = usage
startAfterSlot = startAfter.hour * 60 + startAfter.minute
finishBySlot = finishBy.hour * 60 + finishBy.minute + utils.minutesIn(oneDay)
# the length of the run of the appliance
runtime = powerUsageProfile.size
cheapestSlot = startAfterSlot
# if there is enough time to run the appliance, find the time to start at so that the run would be the cheapest
if finishBySlot - startAfterSlot > runtime:
# basically we have to try all the times between the starting and finishing slots to find the cheapest one
cheapestPrice = math.inf
for startingSlot in range(startAfterSlot, finishBySlot - runtime):
# calculate the price for if the appliance would be run starting at a given slot
slotPrice = numpy.dot(powerUsageProfile, priceProfile[startingSlot:startingSlot+runtime])
# if it's better than what we found so far, save it
if slotPrice < cheapestPrice:
cheapestSlot = startingSlot
cheapestPrice = slotPrice
# put the usage of the appliance at the right time in the power profile
powerProfile[cheapestSlot:cheapestSlot+runtime] = powerUsageProfile
# save the power profile
self.smartDemand.add(midnight, powerProfile)
# calculates appliance power demand for a given time interval acting as if the appliance wanted to be used as early as possible
def calculateUncontrolledDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# for each day in the interval, just run the appliance as soon as possible
for midnight in utils.midnightsBetween(fromDT, toDT):
date = midnight.date()
# the power profile of that day (plus some overlap)
powerProfile = numpy.zeros(2 * utils.minutesIn(oneDay))
# get the appliance usage for that day and act accordingly
usage = self.memory.usages[date]
if usage is not None:
((startAfter, _), powerUsageProfile) = usage
# the slots in which the appliance is available for being turned on
startAfterSlot = startAfter.hour * 60 + startAfter.minute
# the length of the run of the appliance
runtime = powerUsageProfile.size
# put the usage of the appliance at the right time in the power profile
powerProfile[startAfterSlot:startAfterSlot+runtime] = powerUsageProfile
# save the power profile
self.uncontrolledDemand.add(midnight, powerProfile)
# calculates appliance power demand for a given time interval acting as if the machine wanted to spread out its use across the whole possible interval
def calculateSpreadOutDemand(self, fromDT: datetime.datetime, toDT: datetime.datetime):
# for each day in the interval, just run the appliance in the middle of the available interval
for midnight in utils.midnightsBetween(fromDT, toDT):
date = midnight.date()
# the power profile of that day (plus some overlap)
powerProfile = numpy.zeros(2 * utils.minutesIn(oneDay))
# get the appliance usage for that day and act accordingly
usage = self.memory.usages[date]
if usage is not None:
# the slots in which the appliance is available for being turned on
((startAfter, finishBy), powerUsageProfile) = usage
startAfterSlot = startAfter.hour * 60 + startAfter.minute
finishBySlot = finishBy.hour * 60 + finishBy.minute + utils.minutesIn(oneDay)
# the length of the run of the appliance
runtime = powerUsageProfile.size
# the slot in which the appliance should start
startingSlot = startAfterSlot + max(0, (finishBySlot - startAfterSlot - runtime) // 2)
# put the usage of the appliance at the right time in the power profile
powerProfile[startingSlot:startingSlot+runtime] = powerUsageProfile
# save the power profile
self.spreadOutDemand.add(midnight, powerProfile)
# class representing an electric car
class Car(Battery):
usageStatistics = applianceStatistics.carStatistics[0]
@classmethod
def randomWithIndex(cls, index: int = 0):
usageStatistics = applianceStatistics.carStatistics[index]
chargingPower = usageStatistics.randomChargingPower()
car = cls(chargingPower=chargingPower)
car.usageStatistics = usageStatistics
return car
# class representing air conditioning
class AirConditioning(Accumulator):
usageStatistics = applianceStatistics.airConditioningStatistics
# class representing an electrical heating
class ElectricalHeating(Accumulator):
usageStatistics = applianceStatistics.electricalHeatingStatistics
# class representing a refrigerator
class Fridge(Accumulator):
usageStatistics = applianceStatistics.fridgeStatistics
# class representing a water heater
class WaterHeater(Accumulator):
usageStatistics = applianceStatistics.waterHeaterStatistics
# class representing a dishwasher
class Dishwasher(Machine):
usageStatistics = applianceStatistics.dishwasherStatistics
# class representing a washing machine
class WashingMachine(Machine):
usageStatistics = applianceStatistics.washingMachineStatistics
|
583d4af8af03eeb5bb9946551659666065dcc470 | ObsaSiyo/Algorithms-And-Data_Structures | /Arrays-and-String/Rotation.py | 210 | 3.859375 | 4 | # is s2 a rotation of s1
s1 = "foo"
s2 = "oof"
s3 = s2 + s2
s4 = "a"
s5 = "b"
s6 = s5 + s5
if s1 in s3:
print("True")
else:
print("False")
if s4 in s6:
print("True")
else:
print("False")
|
13297cc43ce611e97f5758d62e655e80745aad84 | metacogpe/neuralNetwork | /main.py | 3,125 | 3.828125 | 4 | '''
Welcome to my Playground! Here, you can run the Neural Network and even tinker with the parameters to discover new combinations and reach higher accuracies!
IMPORTANT NOTE :
> Repl will install a few libraries need to run this program. It'll take a few seconds only.
> You don't need to change anything else than the CHANGABLE PARAMETERS. But you can if you wish to. Go on, work your brains out.
> The output visuals will be automatically saved in the Files Tab on the left of the screen. You can access them from there.
Have fun!
'''
# Importing helper functions
from network_functions import *
from helpers import *
import matplotlib as mpl
# CHANGABLE PARAMETERS
TRAINING_SAMPLES = 1000 # Total number of training samples.
LAYER_DIMS = [16, 16, 1] # Note that the input Layer is predefined so you don't need to define it again.
EPOCHS = 2500 # Total number of Iterations.
LEARNING_RATE = 0.04 # Learning Rate to be used in Gradiend Descent.
ACTIVATION = 'relu' # Activations used in Neural Network. Try jumping between relu/sigmoid
print(f'''
Training Samples : {TRAINING_SAMPLES}
Layer Dimensions : {LAYER_DIMS}
Epochs : {EPOCHS}
Learning Rate : {LEARNING_RATE}
''')
# Creating Data
X, y = create_data(TRAINING_SAMPLES, 100)
plot_data([X, y], 'Dataset')
# Initializing Random Parameters
parameters = initialize_random_parameters(LAYER_DIMS, X)
# Few logs just to keep track of our training.
cost_log, epoch_log = [], []
# Creating the Network
nn = NeuralNetwork()
# Training
print("Initializing Training...")
for epoch in range(EPOCHS):
if epoch % 100 == 0 and epoch != 0:
LEARNING_RATE -= LEARNING_RATE/10 # This is called Learning Rate Decay. It is basically done to optimize our Training.
print("Epoch :", epoch)
# Feedforwarding
yhat, caches = nn.feedforward(X, parameters, ACTIVATION)
# Computing and saving the logs for plotting
cost = nn.cost(yhat, y)
cost_log.append(cost)
epoch_log.append(epoch+1)
# Back Propagation
grads = nn.backward_propagation(yhat, y, caches, ACTIVATION)
# Gradient Descent
parameters = nn.gradient_descent(parameters, grads, LEARNING_RATE)
predictions = yhat # yhat --> the predicted output
print()
print("********** Accuracy :", accuracy_score(predictions, y), "% **********")
print("// Graphs saved. Check the files tab.")
# Saving the Cost Function Graph
plot_cost_function(epoch_log, cost_log)
# Just another way to convert predictions to 0s and 1s
yhat = np.where(predictions<0.5, 0, 1)
# Saving our Predictions graph
plot_data([X, yhat], 'Prediction')
'''
Awesome! You just created your First Neural Network from Scratch!
NOTE:
> You might not be getting an amazing accuracy. That's because there are various things that we've skipped and various parameters that we haven't optimized just to not go beyond the scope of this article.
Though, you can try to tinker with the 3 parameters:
> TRAINING_SAMPLES
> LAYER_DIMS
> EPOCHS
> LEARNING_RATE
Lemmi hear your adventures and accuracies through your comments!
Peace out.
''' |
ad29e61cc0d6de983078600297f88ad1c5e2b081 | imckl/leetcode | /medium/82-remove-duplicates-from-sorted-list-ii.py | 2,707 | 3.8125 | 4 | # 给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class SolutionNotMine:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
dummy = ListNode(None)
dummy.next = head
slow = dummy
fast = dummy.next
while fast:
if fast.next and fast.next.val == fast.val:
tmp_val = fast.val
# 在快指针上,跳过所有值重复的节点
while fast and fast.val == tmp_val:
# 继续移动快指针
fast = fast.next
else:
# 慢指针 next 指向快指针 fast
slow.next = fast
# 当前慢指针设置为当前快指针
slow = fast
# 继续移动快指针
fast = fast.next
#
slow.next = fast
return dummy.next
# Runtime: 40 ms, faster than 97.68% of Python3 online submissions for Remove Duplicates from Sorted List II.
# Memory Usage: 13.9 MB, less than 8.00% of Python3 online submissions for Remove Duplicates from Sorted List II.
class Solution2:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
new_head = ListNode(None)
new_node = new_head
node = head
# 用于标记状态:节点值是否重复
same = False
while node:
# 如果有下一节点
if node.next:
# 如果当前节点值等于下一节点值,则标记为当前状态为节点值重复
if node.val == node.next.val:
# 激活状态
same = True
# 否则,如果当前状态为节点值重复
elif same:
# 重置状态
same = False
# 否则,当前节点不为重复值节点,添加至新链表中
else:
new_node.next = node
new_node = new_node.next
# 否则,检查当前状态是否为节点值重复;如果不是,啧添加至新链表中
elif not same:
new_node.next = node
new_node = new_node.next
node = node.next
# 截断
new_node.next = None
# 返回
return new_head.next
|
9341d0c36d44c2e4da4eb27620011167a6a122d2 | manusoler/code-challenges | /projecteuler/pe_24_lexicographic_permutations.py | 1,245 | 3.984375 | 4 | import functools
from utils.decorators import timer
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""
def nth_permutation(elems, n):
"""
Find nth lexicographic permutation of elems by calculating
the number of permutatios left for each position
elems array with elements to permutate, must be sorted
n the nth lexicographic permutation to find
"""
fact = lambda x: functools.reduce(lambda i,j: i*j, range(1,x+1))
pos, summ = 0, 0
permutation = ""
for i in reversed(range(1,len(elems))):
fact_i = fact(i)
while summ+fact_i < n:
summ += fact_i
pos += 1
permutation += str(elems[pos])
del(elems[pos])
pos = 0
return permutation + str(elems[0])
@timer
def main():
print(nth_permutation([i for i in range(0,10)], 1000000))
if __name__ == "__main__":
main() |
f744e608294b15dde4be49d95600e8058e44256f | superyanxi/CS61A | /hw01/hw01.py | 2,882 | 4.09375 | 4 | """ Homework 1: Control """
from operator import add, sub
def a_plus_abs_b(a, b):
"""Return a+abs(b), but without calling abs.
>>> a_plus_abs_b(2, 3)
5
>>> a_plus_abs_b(2, -3)
5
"""
if b < 0:
f = a-b
else:
f = a+b
return f(a, b)
def two_of_three(a, b, c):
"""Return x*x + y*y, where x and y are the two largest members of the
positive numbers a, b, and c.
>>> two_of_three(1, 2, 3)
13
>>> two_of_three(5, 3, 1)
34
>>> two_of_three(10, 2, 8)
164
>>> two_of_three(5, 5, 5)
50
"""
list1 = [a,b,c]
def find_max(list_x):
max_value = list_x[0]
for item in list_x:
if item > max_value:
max_value = item
return max_value
largest = find_max(list1)
del list1[list1.index(largest)]
second_lar = find_max(list1)
return (largest*largest+second_lar*second_lar)
def largest_factor(n):
"""Return the largest factor of n that is smaller than n.
>>> largest_factor(15) # factors are 1, 3, 5
5
>>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
40
>>> largest_factor(13) # factor is 1 since 13 is prime
1
"""
"*** YOUR CODE HERE ***"
half = int(n/2)
max_factor = 1
if n ==0:
return 'infinity ><'
for item in range(half+1)[1:]:
if n%item == 0:
max_factor = item
return max_factor
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and
false_result otherwise.
>>> if_function(True, 2, 3)
2
>>> if_function(False, 2, 3)
3
>>> if_function(3==2, 3+2, 3-2)
1
>>> if_function(3>2, 3+2, 3-2)
5
"""
if condition:
return true_result
else:
return false_result
def with_if_statement():
"""
>>> result = with_if_statement()
2
>>> print(result)
None
"""
if c():
return t()
else:
return f()
def with_if_function():
"""
>>> result = with_if_function()
1
2
>>> print(result)
None
"""
return if_function(c(), t(), f())
def c():
"*** YOUR CODE HERE ***"
return False
def t():
"*** YOUR CODE HERE ***"
print(1)
def f():
"*** YOUR CODE HERE ***"
print(2)
def hailstone(n):
"""Print the hailstone sequence starting at n and return its
length.
>>> a = hailstone(10)
10
5
16
8
4
2
1
>>> a
7
"""
"*** YOUR CODE HERE ***"
if (type(n) == int) & (n > 0):
run_n = 0
while n != 1:
run_n += 1
if n%2 == 0:
n = n/2
print(int(n))
else:
n = n*3+1
print(int(n))
return run_n
else:
print('re-enter the damn number')
|
9afad0fd5a5caaf8aa7a2cae950024b7ce5871e8 | wongxinjie/algs4py | /solution/fundamentals/solutions.py | 4,081 | 3.921875 | 4 | import string
import operator
def is_circular_rotation(s, t):
"""1.2.6
check is s and t is circular rotation
>>> s, t = 'ACTGACG', 'TGACGAC'
>>> is_circular_rotation(s, t)
True
>>> is_circular_rotation(s, 'TT')
False
"""
return len(s) == len(t) and ((s + s).find(t) != -1)
def parentheses(text):
"""1.3.4
check parentheses
>>> s = '[()]{}{[()()]}'
>>> parentheses(s)
True
>>> s = '[(])'
>>> parentheses(s)
False
"""
if len(text) % 2 != 0:
return False
ops = []
for c in text:
if c in ('(', '[', '{'):
ops.append(c)
else:
op = ops.pop()
if c == ')':
if op != '(':
return False
elif c == ']':
if op != '[':
return False
else:
if op != '{':
return False
return True
def complete(expression):
"""
complete expression
>>> s = '1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )'
>>> complete(s)
'( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )'
"""
data = []
operators = []
for n in expression:
if n >= '0' and n <= '9':
data.append(n)
elif n in ('+', '-', '*', '/'):
operators.append(n)
elif n == ')':
x = data.pop()
y = data.pop()
op = operators.pop()
rv = '( {} {} {} )'.format(y, op, x)
data.append(rv)
while operators:
op = operators.pop()
x = data.pop()
y = data.pop()
rv = '( {} {} {} )'.format(y, op, x)
data.append(rv)
return data.pop()
ARITHMETIC_OPERATORS = {
'*': operator.mul, '/': operator.truediv,
'+': operator.add, '-': operator.sub,
'^': operator.pow, '%': operator.mod,
'//': operator.floordiv
}
def infix_to_postfix(expression):
"""1.3.10
"""
prec = {
'^': 3, '*': 3, '/': 3,
'+': 2, '-': 2, '(': 1
}
postfixchar = string.digits + string.ascii_letters
operators = []
postfix = []
for token in expression.split():
if token in postfixchar:
postfix.append(token)
elif token == '(':
operators.append(token)
elif token == ')':
top_token = operators.pop()
while top_token != '(':
postfix.append(top_token)
top_token = operators.pop()
else:
while operators and prec[operators[-1]] >= prec[token]:
postfix.append(operators.pop())
operators.append(token)
while operators:
postfix.append(operators.pop())
return ' '.join(postfix)
def evaluate_postfix(expression):
"""1.3.11
"""
token_list = expression.split()
data = []
for token in token_list:
if token in string.digits:
data.append(int(token))
else:
x = data.pop()
y = data.pop()
op = ARITHMETIC_OPERATORS[token]
data.append(op(y, x))
return data.pop()
def nearest_distance_pair(array):
"""1.4.16
>>> l = [58.44, 79.18, 0.22, 99.15, 65.97, 26.31, 37.73, 2.82, 71.65, 90.03]
>>> nearest_distance_pair(l)
(0.22, 2.82)
"""
array = sorted(array)
x, y, distance = None, None, float("inf")
for n in range(len(array) - 1):
if (array[n+1] - array[n]) < distance:
x, y = array[n], array[n+1]
distance = y - x
return x, y
def find_peak_element(items):
size = len(items)
if size == 1:
return 0
if items[0] > items[1]:
return 0
if items[size-1] < items[size-2]:
return size - 1
low, high = 0, size - 1
while low < high:
mid = (high+low) // 2
if items[mid] < items[mid-1] and items[mid] < items[mid+1]:
return mid
elif items[mid] < items[mid+1]:
low = mid
else:
high = mid
if __name__ == "__main__":
import doctest
doctest.testmod()
|
e2ee8c39965c1e55c78722dcba52862715a476fc | soumitra9/Strings-1 | /custom_sort.py | 1,302 | 3.53125 | 4 | # Time Complexity : Add - O(n)
# Space Complexity :O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
'''
1. Make freq hashmap of each charchter in T
2. Iterate thru each charachter in S, and append it the number of frequency, also keep decreasing the frequency
as you append
3. Now all remainng charachters with frequency > 0, can be appended in any fashion
4. convert the list into String and return
'''
from collections import Counter
class Solution:
def customSortString(self, S: str, T: str) -> str:
if len(S)<1 or len(T)<1:
return
freqT = Counter(T)
#append the charachter based on the sequence in S, and based on the frequency
result = []
for i in S:
if i in freqT and freqT[i] > 0:
for j in range(freqT[i]):
result.append(i)
freqT[i] = 0
#remaining charachters can now be appended just by iterating through the dict
for j in freqT:
if freqT[j] > 0:
for k in range(freqT[j]):
result.append(j)
freqT[j] = 0
return "".join(result) |
95a8a943ea53bab4eef50f420ac9feb45a75dde8 | Uche-Clare/python-challenge-solutions | /Uche Clare/Phase 1/Python Basic 1/Day 9/Task 73.py | 102 | 3.53125 | 4 | def mid_point(x1, x2, y1, y2):
x = ((x1+x2)/2), ((y1 + y2)/2)
return x
print(mid_point(9, 3, 9, 5)) |
ec67f302120d10534e1eb68061edc4b7dc4a4f60 | Seb-code-cloud/Ikea_database | /IKEA_gruppe1Python.py | 2,942 | 3.671875 | 4 | #Program created by Sebastian Larsen
#date = 17/05-2021
import IKEA_Gruppe1Connect as thisDatabase
from beautifultable import BeautifulTable
import time
#connect to database
thisConn = thisDatabase.dbconnect()
#This function creates a beautifultable from the data reterived from IKEA DATABASE
def prettyprint(result):
table = BeautifulTable()
table.column_header = ["Costumer_ID", "Email", "Reg_date", "First_name", "Last_name", "Phone_number", "Password", "Country", "Default_shipping_Addr"]
for row in result:
table.rows.append(row)
print(table)
mycursor = thisConn.cursor()
mycursor.execute("select * From Customer")
myRecords = mycursor.fetchall()
# -----------------------------------------------
#Here the program ask user to add a new customer
def Create_new_user():
Email = input("Insert Email: \n")
First_name = input("Insert First name: \n")
Last_name = input("Insert Last name: \n")
Phone_number = int(input("Insert Phone_number: \n"))
Country = input("Insert Country: \n")
Password = input("Insert password: \n")
sql = " INSERT INTO Customer(Email, First_name, Last_name, Phone_number, Country, Password) VALUES (%s,%s,%s,%s,%s,%s)"
val = (Email, First_name, Last_name, Phone_number, Country, Password)
mycursor = thisConn.cursor()
mycursor.execute(sql, val)
thisConn.commit()
print("User succesfully created")
#-----------------------------------------------
#Here the program show the latest added user created
def Latest_added(result):
sql = """
SELECT
*
FROM
Customer
ORDER BY Customer_ID DESC
LIMIT 1
"""
mycursor = thisConn.cursor()
mycursor.execute(sql)
myRecords = mycursor.fetchall()
table = BeautifulTable()
table.columns.header = ["Customer info"]
table.rows.append(myRecords)
print(table)
#--------------------------------------------------
#Creating a variable called "title", that combined with the fuction below "hello" makes the program smooth
title = "\t\t\tMENU\t\t\t"
def hello():
print("\033[H\033[J")
print(title)
print("\n")
def main_menu():
hello()
options = [
"Print Customer table from IKEA DATABASE",
"Create new user",
"show latest user created",
"Exit Program\n"
]
print("Enter a number to select an option:\n")
for d, options in enumerate(options):
print("[" + str(d + 1) + "] " + options)
choice = int(input("Select an option [1] - [4]: "))
if choice in range(1,7):
if choice == 1:
time.sleep(1)
prettyprint(myRecords)
time.sleep(5)
main_menu()
elif choice == 2:
time.sleep(1)
Create_new_user()
time.sleep(4)
main_menu()
elif choice == 3:
time.sleep(1)
Latest_added(myRecords)
time.sleep(5)
main_menu()
elif choice == 4:
hello()
print("\n")
print("Quitting.....")
time.sleep(1.5)
exit()
else:
print("I dont know this action..")
time.sleep(2)
main_menu()
#her bliver funktionen main_menu() initialiseret
main_menu() |
681379a0ac398d82dee8f0f6c6d4d014e2d0c54c | yovana13/SoftUni | /Python Fundamentals/07. Dictionaries/Exercises 7 Dictionaries/Legendary Farming.py | 815 | 3.796875 | 4 | dict = {}
text = input().split()
print(text)
for key in range(1,len(text),2):
text[key]=text[key].lower()
if text[key] in dict:
dict[text[key]] += int(text[key-1])
else:
dict[text[key]] = int(text[key-1])
key_dict = {}
if "shards" in dict:
if dict["shards"]>250:
dict["shards"] -=250
print("Shards obtained!")
key_dict["shards"] = dict["shards"]
if "fragments" in dict:
if dict["fragments"]>250:
dict["fragments"] -=250
print("Fragments obtained!")
key_dict["fragments"] = dict["fragments"]
if "motes" in dict:
if dict["motes"]>250:
dict["motes"] -=250
print("Motes obtained!")
key_dict["motes"] = dict["motes"]
key_dict1 = sorted(key_dict.items(), key=lambda x: x[1])
print(key_dict)
print(key_dict1)
print(dict) |
af33755219e947522e3e3fc4a88158ac54748ec1 | kaenlee123/LEARNPYTHON | /novice2professional/defClassbird.py | 763 | 4.15625 | 4 | # coding=UTF-8
'''
#Created on 2016年7月10日@author: kaen
'''
'''=====================================调用绑定类'''
class bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry == True:
print('ahahhaha!')
self.hungry = False
else:
print('i have ate!')
b = bird()
print(b.eat())
print(b.eat())
class song_bird(bird):
def __init__(self):
self.sound = 'gagagaga!'
sb =song_bird()
try:
print(sb.eat())
except AttributeError as e:
print(e)
#out: song_bird instance has no attribute 'hungry'
class song_bird1(bird):
def __init__(self):
bird.__init__(self)
self.sound = 'gaggaga'
sb1 = song_bird1()
print(sb1.eat())
#out: ahahhaha!
|
00fef7edafd96636dfa62c390f6b54ce90236ecc | prashant956/workspace | /even.py | 136 | 4.21875 | 4 | num=int(input('enter a number:'))
if(num%2)==0:
print('num is even',format(num))
else:
print('num is odd',format(num))
|
d14b4e7aef6278bf4e09aa8635f95f4b85e4e3bd | kentfrazier/euler | /Python/p057.py | 1,260 | 4.125 | 4 | # It is possible to show that the square root of two can be expressed
# as an infinite continued fraction.
#
# sqrt 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
#
# By expanding this for the first four iterations, we get:
#
# 1 + 1/2 = 3/2 = 1.5
# 1 + 1/(2 + 1/2) = 7/5 = 1.4
# 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
# 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
#
# The next three expansions are 99/70, 239/169, and 577/408, but the
# eighth expansion, 1393/985, is the first example where the number
# of digits in the numerator exceeds the number of digits in the
# denominator.
#
# In the first one-thousand expansions, how many fractions contain a
# numerator with more digits than denominator?
from fractions import Fraction
def continued_fraction_gen():
current = Fraction(1,1)
yield current
while True:
new_denominator = current.numerator + current.denominator
new_numerator = new_denominator + current.denominator
current = Fraction(new_numerator, new_denominator)
yield current
if __name__ == "__main__":
from itertools import islice
print len([ frac for frac in islice(continued_fraction_gen(), 1000) if len(str(frac.numerator)) > len(str(frac.denominator)) ])
|
6dfc1cd4c04cbff9df9281e17e69cf670a8d2c9c | cokkiri/cobugagachi | /robin/2_7_2/problem_2_7_2.py | 1,798 | 3.625 | 4 | '''
이 문제의 경우 binary search를 연습하기 위해 일부러 binary search를 구현하는 방식으로 갔지만,
문제 구성상 target in total_list로 찾으면 한번에 해결되긴 한다.
'''
def main():
with open('input.txt', 'r') as fp:
lines = fp.readlines()
lines = [ line.strip() for line in lines ]
total_num = int(lines[0])
assert 1 <= total_num <= 1e6
total_list = list(map(int, lines[1].split(' ')))
assert len(total_list) == total_num and len([x for x in total_list if not (1 <= x <= 1e6)]) == 0
num_targets = int(lines[2])
assert 1 <= num_targets <= 1e5
targets = list(map(int, lines[3].split(' ')))
assert len(targets) == num_targets and len([x for x in targets if not (1 <= x <= 1e6)]) == 0
total_list.sort()
for target in targets:
result = binary_search(target, total_list, 0, total_num - 1)
if result is not None:
print('yes', end=' ')
else:
print('no', end=' ')
print('\n')
return
def binary_search(target, given_list, start, end):
# # 반복문을 이용한 풀이
# while start <= end:
# mid = (start + end) // 2
# if given_list[mid] == target:
# return mid
# elif given_list[mid] > target:
# end = mid - 1
# else:
# start = mid + 1
# return None
# 재귀함수를 이용한 풀이
if start > end:
return None
mid = (start + end) // 2
if given_list[mid] == target:
return mid
else:
if given_list[mid] > target:
end = mid - 1
else:
start = mid + 1
return binary_search(target, given_list, start, end)
if __name__ == '__main__':
main() |
82daf6036f0103c3a6054b92baab82f9a09bf795 | bishnu12345/python-basic | /classWork.py | 916 | 4.09375 | 4 | #WAP to display follow pattern
# ******
# ****
# **
# *
# length = int(input("Enter number of stars"))
# for i in range(0, length, 2):
# for j in range(length, i, -1):
# print("*", end="")
# print()
#WAP to display follow pattern
# 1
# 121
# 12321
# 1234321
# 123454321
# big_number = int(input('Enter biggest number: '))
# for i in range(0,big_number+1):
# for j in range(1,i+1):
# print(j,end='')
# for k in range(j,1,-1):
# print(k-1,end='')
#
# print()
#WAP to display follow pattern
# KATHMANDU
# ATHMAND
# THMAN
# HMA
# M
str='KATHMANDU'
length= len(str)
for i in range(0,int(length/2)):
for j in range(0,int(length/2)):
for k in range(length-1,int(length/2)):
print(i*' '+str[j:k])
print()
|
6ca97c5cc2e8ba8ffba889ebec8dd22a763ba6b5 | perrysou/ProjectEuler | /euler016.py | 648 | 3.921875 | 4 | def integerdigits(integer):
total = 0
while integer:
total += (integer % 10)
integer /= 10
return total
def powerdigit(power, powertodigits):
if power not in powertodigits:
powertodigits[power] = integerdigits(2**power)
return powertodigits[power]
def main():
powerdigits = {}
# t = int(raw_input().strip())
t = 1
while t:
# n = long(raw_input().strip())
n = 1000
print powerdigit(n, powerdigits)
t -= 1
if __name__ == '__main__':
# print "This program is being run by itself"
main()
else:
print 'I am being imported from another module'
|
8d24e6e281e01961b3634d7898eb75a5cf408337 | joyce-lam/prep | /linked_list/Q8.py | 1,251 | 4.0625 | 4 | #sort list
#Sort a linked list in O(n log n) time using constant space complexity.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def sortList(self, A):
def getMiddle(head):
slow = head
fast = head.next
while fast is not None:
fast = fast.next
if fast is not None:
fast = fast.next
slow = slow.next
return slow
def mergeTwoLists(A,B):
head = ListNode(0)
p = head
while A or B:
if A and B:
if A.val < B.val:
p.next = A
A = A.next
else:
p.next = B
B = B.next
p = p.next
if A == None:
p.next = B
break
elif B == None:
p.next = A
break
return head.next
def sortlist(A):
if not A.next:
return A
mid = getMiddle(A)
next_of_mid = mid.next
mid.next = None
left = sortlist(A)
right = sortlist(next_of_mid)
sortedList = mergeTwoLists(left, right)
return sortedList
return sortlist(A)
|
4c3918c167c185c0d58827a54bbd47d58e80b43d | batman950/shubh | /grades.py | 357 | 3.6875 | 4 | students = {"a": 70, "b": 90, "c": 65, "d": 45}
for i in students:
if students[i] > 80:
print("A", i, str(students[i]))
elif students[i] > 60 & students[i] < 80:
print("B", i, str(students[i]))
elif students[i] > 50 & students[i] > 60:
print("C", i, str(students[i]))
else:
print("fail", i, str(students[i]))
|
ef73c17fbbfcbf7475842ac0f9c19996a09ad98c | am009/TSCTF2021-Reverse | /TSCTF-baby-easy-UWP/decrypt.py | 1,959 | 3.875 | 4 |
class randomizer:
'''
完全二叉树的数组表示(层序遍历存放时),下标为x的节点的左孩子下标为2x,右孩子为2x+1。(下标从1开始)
加密是层序遍历转中序遍历。
'''
def __init__(self):
self.result = ''
self.to_encrypt = ''
self.length = 0
def traverse(self, root):
if root > self.length:
return
self.traverse(2*root)
self.result += self.to_encrypt[root-1]
self.traverse(2*root+1)
def randomize(self, s):
self.length = len(s)
self.to_encrypt = s
self.traverse(1)
return self.result
class derandomizer:
'''
解密时是建树,中序遍历的过程中填进去,
'''
def __init__(self):
self.result = []
self.to_decrypt = ''
self.length= 0
self.counter = 0
def traverse(self, root):
if root > self.length:
return
self.traverse(2*root)
self.result[root-1] = self.to_decrypt[self.counter]; self.counter += 1
self.traverse(2*root+1)
def derandomize(self, s):
self.length = len(s)
self.to_decrypt = s
self.result = ['a' for i in range(self.length)]
self.traverse(1)
return ''.join(self.result)
def xorer(s):
b = s.encode('ascii')
result = []
for i in b:
result.append(i ^ ord('U'))
return bytes(result)
def dexorer(b):
result = []
for i in b:
result.append(i ^ ord('U'))
return bytes(result).decode("ascii")
cipertext = b'cdee\nme\x17gfaabx\x164\x1d`\x10f6\x10>794;bf&g,e\x0cm'
randomized = dexorer(cipertext)
# print(randomized)
derandomized = derandomizer().derandomize(randomized)
print(derandomized)
# ------------
# derandomized = "347Baby03-5EasY18247CHEckln320860_0"
# randomized = randomizer().randomize(derandomized)
# print(randomized)
# xored = xorer(randomized)
# print(xored)
|
0516487a7b0aa2b00d5619862ea50f84a2a3c5ce | rafid009/sudoku | /sudoku.py | 3,054 | 3.5 | 4 | import sys
import time
from board import Board
def get_board(cells):
board = []
i = 0
temp = []
for s in cells:
if s >= "0" and s <= "9":
# print(s)
temp.append(s)
i = (i + 1) % 9
if i == 0 and len(temp) != 0:
board.append(temp)
temp = []
return board
def print_board(board):
print()
for r in board:
print(r)
print()
def get_boards (file_name):
f = open(file_name, "r")
f_lines = f.read().split('\n')
boards = [] #list of boards, each element is a tuple (no_and_difficulty : string, board : 2D_list)
i = 0
lim = len(f_lines)-11
while (i<=lim):
list_2d = []
for j in range(1,10):
sub = list(f_lines[i+j].strip())
sub.pop(3)
sub.pop(6)
list_2d.append(sub)
boards.append((f_lines[i].strip() , list_2d))
i+=11
return boards
def get_current_time_in_millis():
return int(time.time() * 1000)
if __name__ == "__main__":
if len(sys.argv) != 4:
print("invalid input")
sys.exit(0)
rules = [False, False, False, False, False, False]
boards = get_boards(sys.argv[1])
i = 1
solved = 0
for item in boards:
difficulty = item[0].split()[1]
board = item[1]
board_state = None
# inferences:
# 0 -> no inferences
# 1 -> naked and hidden singles
# 2 -> naked and hidden singles, doubles
# 3 -> naked and hidden singles, doubles, and triples
if int(sys.argv[3]) == 1:
rules[0] = True
rules[1] = True
elif int(sys.argv[3]) == 2:
rules[0] = True
rules[1] = True
rules[2] = True
rules[3] = True
elif int(sys.argv[3]) == 3:
rules[0] = True
rules[1] = True
rules[2] = True
rules[3] = True
rules[4] = True
rules[5] = True
print("difficulty: ", difficulty)
board_state = Board(board, rules)
start = get_current_time_in_millis()
# algorithms:
# 1 -> MCV
# 0 -> simple
if int(sys.argv[2]) == 1:
if board_state.solve_most_constraint_backtracking():
solved += 1
else:
print("could not solve")
print("Searches: ", board_state.expandedNodes)
print("Number of backtracks: ", board_state.num_backtracks)
else:
if board_state.solve_simple_backtracking():
solved += 1
else:
print("could not solve")
print("Searches: ", board_state.expandedNodes)
print("Number of backtracks: ", board_state.num_backtracks)
end = get_current_time_in_millis()
print("Time taken: ", (end - start), " ms")
print("\n")
i += 1
print("solved ", solved, " out of ", i, " puzzles")
|
9f9e6b53de2cecd2d1e25642f6c7af46bb87223a | Alexandre-cod/Ex2 | /exercicio2.py | 2,483 | 3.71875 | 4 | #este documento foi reservado para os comits das funções que o Academia sugeria para a resolução do codigo.
#cria baralho
def cria_baralho():
lista = []
espadas = '♠'
i=2
lista.append('A{}'.format(espadas))
while i<=10:
lista.append('{}''{}'.format(i,espadas))
i+=1
lista.append('J{}'.format(espadas))
lista.append('Q{}'.format(espadas))
lista.append('K{}'.format(espadas))
copas = '♥'
j=2
lista.append('A{}'.format(copas))
while j<=10:
lista.append('{}''{}'.format(j,copas))
j+=1
lista.append('J{}'.format(copas))
lista.append('Q{}'.format(copas))
lista.append('K{}'.format(copas))
ouros = '♦'
k=2
lista.append('A{}'.format(ouros))
while k<=10:
lista.append('{}''{}'.format(k,ouros))
k+=1
lista.append('J{}'.format(ouros))
lista.append('Q{}'.format(ouros))
lista.append('K{}'.format(ouros))
paus = '♣'
m=2
lista.append('A{}'.format(paus))
while m<=10:
lista.append('{}''{}'.format(m,paus))
m+=1
lista.append('J{}'.format(paus))
lista.append('Q{}'.format(paus))
lista.append('K{}'.format(paus))
return lista
#extrai naipes
def extrai_naipe(carta):
if carta[1] == '0':
naipe = carta[2]
if carta[1] != '0':
naipe = carta[1]
return (naipe)
#extrai o valor
def extrai_valor(carta):
if carta[1] == '0':
valor = '10'
else:
valor = carta[0]
return valor
#lista de movimentos possiveis
def lista_movimentos_possiveis(lista,i):
lista_result = []
if i > 0:
if (extrai_naipe(lista[i]) == extrai_naipe(lista[i-1])) or extrai_valor(lista[i]) == extrai_valor(lista[i-1]):
lista_result.append(1)
if i>2:
if (extrai_naipe(lista[i]) == extrai_naipe(lista[i-3])) or extrai_valor(lista[i]) == extrai_valor(lista[i-3]):
lista_result.append(3)
return lista_result
#empilha as cartas
def empilha(lista,ori,des):
valor = lista[ori]
lista.remove(valor)
lista[des] = valor
return lista
#checa se possui movimentos possiveis
def possui_movimentos_possiveis(baralho):
cartasmov = []
j = 0
while j<len(baralho):
if (lista_movimentos_possiveis(baralho,j)) != []:
cartasmov.append(baralho[j])
j+=1
if cartasmov == []:
return False
if cartasmov != []:
return True
|
f649ffe2d71e8bd2ded877e828321f6b5447127b | lchoward/Practice-Python | /Trees/SymmetricTree.py | 1,844 | 3.921875 | 4 | # Determine if a tree is symmetric
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# approach:
# (1) run bfs, passing depth as an argument
# (2) append values to an array, where arr[i] gives the level order traversal for nodes
# at depth = i, including null roots (node == None)
# (3) starting w/ depth = 1, check that arr[depth][j] = arr[depth][length - j - 1]
# (4) return True if make it through all checks
from collections import deque
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
dq = deque()
dq.append((root, 0))
hashmap = {}
def bfs(node, depth):
if node == None:
if depth not in hashmap:
hashmap[depth] = [None]
else:
hashmap[depth].append(None)
return
else:
if depth not in hashmap:
hashmap[depth] = [node.val]
else:
hashmap[depth].append(node.val)
dq.append((node.left, depth + 1))
dq.append((node.right, depth + 1))
return
# add all node values to the hashmap via bfs
while dq:
(curr_node, depth) = dq.popleft()
bfs(curr_node, depth)
# iterate through the hashmap
i = 1
while hashmap.get(i):
curr_len = len(hashmap[i])
if curr_len % 2 != 0:
return False
for j in range(int(curr_len / 2)):
if hashmap[i][j] != hashmap[i][curr_len - j - 1]:
return False
i += 1
return True |
7fa538d5f92a98a2efe4232bc76a821b2eebbb4f | anamdey03/Python-Basics | /AbstractMethod.py | 578 | 3.828125 | 4 | # Python by default doesn't support abstraction, ABC - Abstract Base Classes
from abc import ABC, abstractmethod
class Computer(ABC):
@abstractmethod
def process(self):
pass
class Laptop(Computer):
def process(self):
print("it's running")
class Desktop(Computer):
def process(self):
print("it's building")
def write(self):
print("it's writing")
class Programmer:
def work(self, com):
print("Solving Bugs")
com.process()
com1 = Laptop()
com2 = Desktop()
prog = Programmer()
prog.work(com2)
|
4d90dcca404fbcb2f42e390e943b7b46169ab857 | tallsam/shifting_hands | /baks/game.py | 8,724 | 3.75 | 4 | #!/usr/bin/python
#+'"
import shelve
class Item(object):
def __init__(self, name, description, material, item_type, weight, base_value, actions):
self.name = name
self.description = description
self.material = material #wood, gold, silver, food, steel
self.item_type = item_type #weapon, armour, healing, food
self.weight = weight
self.base_value = base_value
self.actions = actions
def __str__(self):
rep = "**You look at the " + self.name + "..\n"
rep += self.description + "\n"
rep += "It is made of " + self.material
rep += " and weighs about " + self.weight + " grams.\n"
return rep
def save(self, datafile):
item_data = {"material" : self.material,
"description": self.description,
"item_type" : self.item_type,
"weight" : self.weight,
"base_value" : self.base_value,
"actions" : self.actions
}
key = str(self.loc[0]) + "," + str(self.loc[1])
gamedata = shelve.open(datafile, "c")
gamedata[self.name] = item_data
gamedata.sync()
gamedata.close()
class Room():
def __init__(self, loc, title, description, exits, items, npcs, mobs):
self.loc = loc
self.title = title
self.description = description
self.exits = exits
self.items = items
self.npcs = npcs
self.mobs = mobs
def __str__(self):
rep = "** " + self.title + " **\n"
rep += self.description
rep += "\n Exits: "
for x in self.exits:
rep += x
rep += "\n Items: "
item_list = ""
if self.items:
for x in self.items:
item_list += x.name + ","
rep += item_list[:-1]
else:
rep += "None"
rep += "\n NPCs: "
npc_list = ""
if self.npcs:
for x in self.npcs:
npc_list += x + ","
rep += npc_list[:-1]
else:
rep += "None"
rep += "\n Mobs: "
mob_list = ""
if self.mobs:
for x in self.mobs:
mob_list += x + ","
rep += mob_list[:-1]
else:
rep += "None"
return "\n" + rep
def save(self, datafile):
room = {"loc" : self.loc,
"title" : self.title,
"description" : self.description,
"exits" : self.exits,
"items" : self.items,
"npcs" : self.npcs,
"mobs" : self.mobs}
key = str(self.loc[0]) + "," + str(self.loc[1])
gamedata = shelve.open(datafile, "c")
gamedata[key] = room
gamedata.sync()
gamedata.close()
def remove_item(self, item):
if item in self.items:
self.items.remove(item)
def get_items(self):
return self.items
class Map():
def __init__(self, datafile):
self.mapdata = {}
data = shelve.open(datafile, "r")
for key in data.keys():
loc = data[key]["loc"]
title = data[key]["title"]
description = data[key]["description"]
exits = data[key]["exits"]
items = data[key]["items"]
npcs = data[key]["npcs"]
mobs = data[key]["mobs"]
self.mapdata[key] = Room(loc, title, description,
exits, items, npcs, mobs)
def __str__(self):
rep = "Rooms\n\n"
for key in self.mapdata.keys():
print self.mapdata[key]
rep += "\n\n"
return rep
def move_ok(self, loc, dir):
if dir in self.mapdata[loc].exits:
return True
else:
return False
def get_room(self, loc):
return self.mapdata[loc]
class Hero():
def __init__(self, gamemap, loc):
self.loc = loc
self.loc_str = str(loc[0]) + "," + str(loc[1])
self.map = gamemap
self.inv = []
def __str__(self):
rep = "You are located at " + \
str(self.loc[0]) + \
"," + \
str(self.loc[1]) + \
"\n\n"
return rep
def look(self):
print self.map.get_room(self.loc_str)
def show_inv(self):
rep = "** Inventory **\n"
if self.inv:
for item in self.inv:
rep += item.capitalize() + "\n"
else:
rep += "Your inventory is empty!"
return rep
def pickup(self, item):
for room_item in self.map.mapdata[self.loc_str].items:
if room_item == item:
self.map.mapdata[self.loc_str].remove_item(item)
self.inv.append(item)
print "You picked up the " + item + "."
else:
print "That item is not here."
def examine(self, item):
not_here = 1
for room_item in self.map.mapdata[self.loc_str].items:
if room_item.name == item:
print room_item
not_here = 0
break
if not_here == 1:
print "That item is not here."
#if item in self.map.mapdata[self.loc_str].items:
# print item
#else:
# print "That item is not here."
def move(self, dir):
if self.map.move_ok(self.loc_str, dir):
if dir == "N":
self.loc = (self.loc[0] -1, self.loc[1])
self.loc_str = str(self.loc[0]) + "," + str(self.loc[1])
print "You moved North"
elif dir == "E":
self.loc = (self.loc[0], self.loc[1] + 1)
self.loc_str = str(self.loc[0]) + "," + str(self.loc[1])
print "You moved East"
elif dir == "S":
self.loc = (self.loc[0] + 1, self.loc[1])
self.loc_str = str(self.loc[0]) + "," + str(self.loc[1])
print "You moved South"
elif dir == "W":
self.loc = (self.loc[0], self.loc[1] - 1)
self.loc_str = str(self.loc[0]) + "," + str(self.loc[1])
print "You moved West"
else:
print "You cannot move that direction."
#direction constants
N, E, S, W = "N", "E", "S", "W"
datafile = "data/mymap.dat"
gold = Item("gold",
"This is a gold coin. It has a picture of a mountain\n" + \
"on one side and a dragon on the other.",
"gold",
"money",
"200",
"1",
["spend", "count"]
)
short_sword = Item("sword",
"This short sword has a diamond embeded in the hilt\n" +\
"and looks very, very sharp",
"silver",
"weapon",
"5000",
"300",
["swing", "wield", "sheath", "throw"]
)
rooma = Room((0, 0),
"Room A",
"A dark room",
(N, S),
[gold],
["Charles"],
())
roomb = Room((1, 0),
"Room B",
"A blue room",
(N),
[gold, short_sword],
(),
["Beggar"])
roomc = Room((-1, 0),
"Room C",
"A dingy room",
(S),
[gold],
["Storeman Al", "Pete"],
())
rooma.save(datafile)
roomb.save(datafile)
roomc.save(datafile)
start_loc = (0,0)
gamemap = Map(datafile)
hero = Hero(gamemap, start_loc)
while input != "quit":
hero.look()
input = str(raw_input(": ")).upper()
print
if input.upper() in (N, E, S, W):
hero.move(input)
elif input.upper() in ("LOC"):
print hero
elif input.upper() in ("I", "INV"):
print hero.show_inv()
elif input.upper() in ("HELP"):
print "n, e, s, w, loc, i, pu"
elif input.upper().split( )[0] in ("PU", "PICKUP"):
hero.pickup(input.lower().split( )[1])
elif input.upper().split( )[0] in ("EXAMINE"):
hero.examine(input.lower().split( )[1])
else:
print "I dont understand."
#myroom = Room([0,0], "My Bedroom", "This is a messy bedroom.", ("N", "S"))
#myroom.save(datafile)
#print myroom
|
6b7b629be7db064576cfbd67fd623d256bf7af47 | hc328195244/huangsama | /hw01/main.py | 159 | 3.765625 | 4 | for i in range(1,10):
for k in range(1,i):
print(end=" ") for j in range(i,10):
print('{0:1}{1:1}={2:<2}'.format(i,j,ij),end=' ')
print( )
|
4c6003b0bf63ab347dd5ee5af5160e0cc6ab0f20 | srilekha-gopisetti/100-days-python | /leap year or not program.py | 810 | 4.0625 | 4 | code 1
year=int(input("enter a year"))
if year%4==0:
if year%100!=0:
if year%400==0:
print("leap year")
else:
print("not a leap year")
else:
print("leap")
else:
print("not a leap year")
code 2
def fun(year):
if year%4==0:
if year%100!=0:
if year%400==0:
print("leap year")
else:
print("not a leap year")
else:
print("leap")
else:
print("not a leap year")
year=int(input("enter a year:"))
fun(year)
code 3
def fun1(year):
if year%4==0 and year%100!=0 and year%400==0:
return("leap")
else:
return("not leap")
year=int(input("enter a year:"))
print(fun1(year))
|
075fdd85b75880169d1650143e6af46dfa4cdad1 | Christopher-D-Ross/Python_Projects | /functions.py | 542 | 3.703125 | 4 | def sayHello(name, verbo):
print("Waddup "+ name +", I heard you tryna " + verbo + ".")
print("\n")
sayHello("Chris", "fly")
sayHello("Sadie", "vibe")
sayHello("Ock", "ride")
def sayHello():
print("hello")
def top_3(num1, num2, num3):
gone = num1 + num2 + num3 + 10 * 2
if gone > 20:
print("Your lucky number is %d." % gone)
print("\n")
else:
print("Your unlucky number is %d. But without darkness no one would see the light. Enjoy your unlucky day." % gone)
top_3(2,6,7)
top_3(1,1,2)
|
3520a918ebd1d0f5f5a625a69f7bca2d93641885 | juliafealves/codeforces-python | /567A/lineland-mail.py | 823 | 3.609375 | 4 | # coding: utf-8
# Author: Júlia Fernandes Alves <juliafealves@gmail.com>
# Handle: juliafealves
# Problem: A. Lineland Mail
from math import sqrt
# Distance between two points.
def distance(point_a, point_b):
return sqrt((point_a - point_b) ** 2)
number_cities = int(raw_input())
cities = map(int, raw_input().split())
for i in xrange(number_cities):
if i == 0:
min_cost = distance(cities[i], cities[i + 1])
max_cost = distance(cities[i], cities[-1])
elif i == len(cities) - 1:
min_cost = distance(cities[i], cities[i - 1])
max_cost = distance(cities[i], cities[0])
else:
min_cost = min(distance(cities[i], cities[i + 1]), distance(cities[i], cities[i - 1]))
max_cost = max(distance(cities[i], cities[0]), distance(cities[i], cities[-1]))
print '%i %i' % (min_cost, max_cost)
|
1c444d3d32c6da3b55fe7e303eac739784d2738c | BenjaminWijk/myScripts | /python/countPhrase.py | 1,184 | 3.734375 | 4 | import re
import os
import sys
pattern = re.compile(sys.argv[1])
count = 0
def get_file(filename):
with open(filename) as f:
return f.readlines()
def matches_pattern(line):
if re.search(pattern,line) != None:
return True
return False
#absolute path
path = os.getcwd()
#Add relative path if specified. Search specific file if path does not end on "/", otherwise search folder
additionalPathInfo = ""
if len(sys.argv) >= 3:
additionalPathInfo = sys.argv[2]
path += "/" + additionalPathInfo
filesToSearch = []
if not additionalPathInfo.endswith("/"):
filesToSearch.append(get_file(additionalPathInfo))
else:
for file in os.listdir(path):
#Don't search in script
if file == sys.argv[0]:
continue
filePath = additionalPathInfo + file
if not os.path.isfile(filePath):
continue
filesToSearch.append(get_file(filePath))
print("Number of files to search:" + str(len(filesToSearch)))
for file in filesToSearch:
for line in file:
if matches_pattern(line):
count = count+1
print("The phrase \""+ sys.argv[1] + "\" was found " + str(count) + " times.")
|
7c7f25b4527d4aa55890b40a14a83137a43d3b28 | CarolineSantosAlves/Exercicios-Python | /Exercícios/ex045GameJokenpo.py | 564 | 3.640625 | 4 | from random import randint
print('Bem vindo ao Game Jokenpô PY')
print('''Escolha sua jogada:
[1] PEDRA
[2] PAPEL
[3] TESOURA''')
jogador = int(input('Jogada: '))
maquina = randint(1, 3)
if jogador == 1 and maquina == 1:
jogador = 'PEDRA'
maquina = 'PEDRA'
print('EMPATE')
elif jogador == 1 and maquina == 2:
jogador = 'PEDRA'
maquina = 'PAPEL'
print('Eu venci')
elif jogador == 1 and maquina == 3:
jogador = 'PEDRA'
maquina = 'TESOURA'
print('Você venceu')
print('Eu escolhi {} e você escolheu {}'.format(maquina, jogador))
|
ad8717fdfcea29be641bfac9674ebeeb824f07c6 | VenturaCerqueira/Python-discovery | /07-atividade-Area-do-quadrado.py | 271 | 4.1875 | 4 | #Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
quad = float(input('Digite o valor de um lado do quadrado: '))
def calc_quad():
return f'O valor da area do quadrado é : {(quad*quad)*2}'
print(calc_quad()) |
f2dc41d7a628f61b6f0c9aabff7e621e9ddc27c1 | Santi0207/mapa-mental | /Peso y masa.py | 254 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 12 12:04:51 2021
@author: santi
"""
altura= int (input("ingrese su altura en cm:"))
peso= int (input ("ingrese su peso:"))
indice = peso/(altura*altura)
print ("su masa corporal es:", indice)
|
c8d51f33c41e988106f1f866c23182efe447918f | rifat6991/Projects- | /Python/Practice/Eg/Simple_Programs/ifexample.py | 178 | 3.609375 | 4 | x = str(input("enteR the PaSSword:"))
if x == ("beard"):
print("nice beard,WELCOME")
elif x == ("dog"):
print("nice dog,WELCOME")
else:
print("faak off na")
|
cbc0ba09ec9bdd6f9f3b361c3fd54e5cd91d7a9b | chewu0811/AE403-Angel | /lesson-clock.py | 392 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 1 11:06:09 2021
@author: Admin
"""
import turtle
tur = turtle.Turtle()
def writeNumber(num):
tur.penup()
tur.forward(200)
tur.write(num)
tur.back(200)
tur.pendown()
tur.seth(60)
for i in range(1, 13):
writeNumber(i)
tur.fight(30)
turtle.done()
turtle.exitonClick()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.