blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
2a9849f6d1bccb0f01b738aca69132c5bfe73817
|
c42-arun/leetcode
|
/src/add_two_numbers/solution.py
| 1,481 | 3.953125 | 4 |
# from list_node import ListNode
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
condition = True
l3 = ListNode(0)
l3_head = l3
while condition:
total = l1.val + l2.val + carry
placeVal = total - 10 if total > 9 else total
carry = 1 if total > 9 else 0
l3.val = placeVal
condition = True if l1.next is not None else False
if condition:
l1 = l1.next
l2 = l2.next
l3.next = ListNode(0)
l3 = l3.next
return l3_head
if __name__ == '__main__':
# [5, 7, 4]
l1 = ListNode(5)
l1_head = l1
l1.next = ListNode(7)
l1 = l1.next
l1.next = ListNode(4)
# [7, 2, 1]
l2 = ListNode(7)
l2_head = l2
l2.next = ListNode(2)
l2 = l2.next
l2.next = ListNode(1)
sn = Solution()
ret_list_node = sn.addTwoNumbers(l1_head, l2_head)
answer = [ret_list_node.val]
while ret_list_node.next is not None:
answer.append(ret_list_node.next.val)
ret_list_node = ret_list_node.next
print(answer)
|
bca8f17a5f46a0933088a4668016666e95516321
|
palomaYPR/Introduction-to-Python
|
/CP_P25_TablasAuto.py
| 205 | 3.71875 | 4 |
# EUP que calcule las tablas de multiplicar en automatico del 1 - 10
print('Tablas ')
for i in range(1,11):
print('\nTABLA DEL ',i)
for j in range(0,11):
print(i,' x ',j,' = ',(i*j))
|
8017cf993539357b68d5c0ca3fa4d1ed9a90d997
|
palomaYPR/Introduction-to-Python
|
/CP_P21-2_NumerosLetra.py
| 655 | 3.96875 | 4 |
#EUP que pida ingresar números del 1-10 y te regrese ese numero en letra. Si el número se sale del rango debera mandar
# un mensaje advirtiendo esto.
number = int(input('Ingresa un número entre 1-10: '))
if number == 1:
print('Uno')
elif number == 2:
print('Dos')
elif number == 3:
print('Tres')
elif number == 4:
print('Cuatro')
elif number == 5:
print('Cinco')
elif number == 6:
print('Seis')
elif number == 7:
print('Siete')
elif number == 8:
print('Ocho')
elif number == 9:
print('Nueve')
elif number == 10:
print('Diez')
else:
print('El número se encuentra fuera del rango')
|
a18806eeb1213b7fae5c963fdbf08a307d7d3fc2
|
palomaYPR/Introduction-to-Python
|
/CP_P21-1_TipoOperadores.py
| 418 | 4.125 | 4 |
# EUP que permita ingresar dos números y un operador, de acuerdo al operador ingresado se realizara la debida
# operacion.
num1 = int(input('Ingresa el 1er número: '))
num2 = int(input('Ingresa el 2do número: '))
ope = str(input('Ingresa el operador: '))
if ope == '*':
res = num1 + num2
elif ope == '/':
res = num1 / num2
elif ope == '+':
res = num1 + num2
else:
res = num1 - num2
|
f9c25e2e6239587a86696c5e868feca3ab8beac0
|
palomaYPR/Introduction-to-Python
|
/CP_P14_AreaCirculo.py
| 282 | 4.125 | 4 |
# Elabora un programa que calcule el area de un circulo
# Nota: Tome en cuenta que la formula es A = (pi * r^2)
import math
message = input('Ingresa el radio del circulo: ')
r = int(message)
area = math.pi * r**2
#area = math.pi * math.pow(r,2)
print('El area es: ',area)
|
05e29979c5f56e8b81848f90bea8c0079a0a4650
|
palomaYPR/Introduction-to-Python
|
/CP_P32_ListaPos.py
| 492 | 3.78125 | 4 |
# EUP que pida ingresar y se detenga cuando se ingrese uno postivo. Mostrar cuantos se ingresaron en total y cuantos
# positivos y negativos.
num = []
pos = 0
neg = 0
n = int(input('Ingresa un números (0 para finalizar): '))
while n != 0:
if n > 0:
pos += 1
else:
neg += 1
num.append(n)
n = int(input('Ingresa un números (0 para finalizar): '))
print(f'Se introdujeron: {len(num)} elementos')
print(f'Positivos: {pos} & negativos: {neg}')
|
cc0ef2f43fecae492ce286cafdeef3a153266d83
|
neetukumari4858/function
|
/que 7.py
| 162 | 4.0625 | 4 |
function=input("enter string")
name=input("enter string")
def string(x,y):
if len(x)>len(y):
print(x)
else:
print(y)
string(function,name)
|
d4a8cd543636b4375918bfe64430df051604c4da
|
nachoaz/Data_Structures_and_Algorithms
|
/Stacks/balanced_brackets.py
| 745 | 4.15625 | 4 |
# balanced_brackets.py
"""
https://www.hackerrank.com/challenges/balanced-brackets
"""
from stack import Stack
def is_balanced(s):
if len(s) % 2 == 1:
return 'NO'
else:
stack = Stack()
counterparts = {'{':'}', '[':']', '(':')'}
for char in s:
if char in counterparts:
stack.push(char)
elif stack.is_empty() or counterparts[stack.pop()] != char:
return 'NO'
return 'YES' if stack.is_empty() else 'NO'
def main():
n = int(input())
for _ in range(n):
bracket_string = input()
output = is_balanced(bracket_string)
print(output)
if __name__ == '__main__':
main()
|
3a6a59691cea9f4a66c6d714ff102be381599577
|
nachoaz/Data_Structures_and_Algorithms
|
/Arrays/check_permutation.py
| 1,897 | 3.921875 | 4 |
# given two strings, check if one is a permutation of the other
# string_a is a permutation of string_b if it's made up of the same letters,
# just in different order.
# to determine if string_a and string_b are made up of the same characters, we
# could compare sorted(string_a) and sorted(string_b).
# another thing we could do is to compare character counts.
# the first approach would take O(nlogn) time (using timsort), but would either
# require that we alter the input or that we make a copy of it (making a copy
# would require O(n) space where n is the length of the string
# the second approach would require making a dictionary, which would require
# O(n) space, and would require making n constant-time checks, and so would take
# O(n) time.
# therefore, we choose the second approach but short-circuit if the strings
# aren't of same length
from collections import defaultdict
def get_char_counts(my_string):
counts = defaultdict(int)
for char in my_string:
counts[char] += 1
return counts
def check_permutation(string_a, string_b):
if len(string_a) != len(string_b):
return False
else:
a_counts = get_char_counts(string_a)
b_counts = get_char_counts(string_b)
return all([a_counts[char] == b_counts[char] for char in string_a])
def main():
# testing
test_inputs = [
('hello', 'elloh'),
('terminal', 'nalimert'),
('cat', 'dog'),
('house', ' house')
]
correct_outputs = [
True,
True,
False,
False
]
for i, test_input in enumerate(test_inputs):
if check_permutation(*test_input) == correct_outputs[i]:
print "Test #{} passed.".format(i+1)
else:
print "ATTENTION: Test #{} failed".format(i+1)
if __name__ == '__main__':
main()
|
eb50a25f2527c3a5f4f473274ba29ab838e35dd0
|
nachoaz/Data_Structures_and_Algorithms
|
/Stacks/stack_with_max_api.py
| 692 | 3.640625 | 4 |
# stack_with_max_api
"""
Implements a stack with a O(1)-time operation to get the max of the stack.
"""
from stack import Node, Stack
class StackWithMaxAPI(Stack):
def __init__(self, node=None):
super(StackWithMaxAPI, self).__init__(node)
self.maxs = Stack(node)
def push(self, data):
super(StackWithMaxAPI, self).push(data)
if data >= self.max():
self.maxs.push(data)
def pop(self):
popped_val = super(StackWithMaxAPI, self).pop()
if popped_val == self.max():
self.maxs.pop()
return popped_val
def max(self):
return self.maxs.peek() if self.maxs.top is not None else float('-inf')
|
2b8596603b363eac7b4f0e85cc06405b2c8df87b
|
nachoaz/Data_Structures_and_Algorithms
|
/Linked_Lists/singly_linked_list.py
| 2,828 | 3.90625 | 4 |
# singly_linked_list.py
class SinglyLinkedListNode():
"""A node with a data and next attribute."""
def __init__(self, dat, next_node=None):
self.data = dat
self.next = next_node
def __str__(self):
return "| {} |".format(self.data)
def __repr__(self):
return self.__str__()
class SinglyLinkedList():
"""A singly linked list with only a head attribute."""
def __init__(self):
self.head = None
def __str__(self):
if self.is_empty():
list_string = "List is empty!"
else:
current_node = self.head
list_string = str(current_node)
while current_node.next:
list_string += " --> " + str(current_node.next)
current_node = current_node.next
return list_string
def __repr__(self):
return self.__str__()
def __len__(self):
length = 0
current_node = self.head
while current_node is not None:
length += 1
current_node = current_node.next
return length
def is_empty(self):
"""Returns true if list is empty. Takes O(1) time, O(1) space."""
return self.head is None
def insert_val_at_head(self, val):
"""Inserts val at head of linked list. Takes O(1) time, O(1) space."""
previous_head = self.head
self.head = SinglyLinkedListNode(val, next_node=previous_head)
def insert_val_at_tail(self, val):
"""Inserts val at tail of linked list. Takes O(n) time, O(1) space."""
if self.is_empty():
self.head = SinglyLinkedListNode(val)
else:
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = SinglyLinkedListNode(val)
def remove_from_head(self):
"""Removes node at head of linked list. Takes O(1) time, O(1) space."""
if self.is_empty():
print("Nothing to remove! List is empty.")
else:
node_to_remove = self.head
self.head = node_to_remove.next
node_to_remove.next = None
del node_to_remove
def remove_from_tail(self):
"""Removes node at tail of linked list. Takes O(n) time, O(1) space."""
if self.is_empty():
print("Nothing to remove! List is empty.")
else:
behind_node = self.head
if behind_node.next:
ahead_node = behind_node.next
while ahead_node.next:
behind_node = behind_node.next
ahead_node = ahead_node.next
behind_node.next = None
del ahead_node
else:
self.head = None
del behind_node
|
e4a6dafd7b4971ce1630310eacdf133b767aa5fe
|
5l1v3r1/Learning-Python
|
/py4e-exercise-7.11-1.py
| 255 | 4.0625 | 4 |
prompt = str.lower(input('What is the name of the file to read? '))
try:
fhand = open(prompt)
except:
print('Please choose an existing file')
exit()
for line in fhand:
#if line.startswith('From:'):
line = line.upper()
print(line)
|
57fcb2897f806a3b77f5935294190cf7991b0b80
|
5l1v3r1/Learning-Python
|
/p4e-pg-81.py
| 359 | 3.890625 | 4 |
prompt = str.lower(input('What is the name of the file to read? '))
try:
fhand = open(prompt)
except:
print('Please choose an existing file')
exit()
count = 0
for line in fhand:
if line.startswith('From:'):
line = line.rstrip()
count = count + 1
#print(line)
print('Total count in file: %s' %prompt, 'is %d.' %count)
|
440ed54a0706c75f07a42b5f9da346cb4bba1321
|
Anupam-2309/Numerical-analysis
|
/Inverse Power method.py
| 1,211 | 3.53125 | 4 |
from sympy import *
A=Matrix([[-1,1,0],[1,-1,1],[0,1,-1]])
M=A**-1
X0=Matrix([[1], [1],[1]])
Zero=zeros(3,1)
print("Your Matrix is A =: ")
a=pprint(M)
print(" ")
print("Intial Vectors is X0 =: ")
b=pprint(X0)
print(" ")
print("------------Iteration-0------------")
AX=M*X0
print("A*X0 = ",AX.evalf(3))
L1=max(AX)
print("λ1 =",L1.evalf(2))
X1=(AX/L1)
print("X1 =",X1.evalf(2))
print(" ")
Z=X0.evalf(2)-X1.evalf(2)
while Z!=Zero:
for i in range(1,10):
X0=X1
AX=M*X0
L1=max(AX)
X1=(AX/L1)
print(" ")
print("------------Iteration-"+str(i)+"------------")
print("A*X"+str(i)+" = " ,AX.evalf(3))
print(" ")
print("New Eigen Value and Eigen Vectors ...")
print(" ")
print("λ"+str(i+1)+" = ",L1.evalf(3))
print("X"+str(i+1)+" = ",X1.evalf(3))
print(" ")
Z=X0.evalf(2)-X1.evalf(2)
else:
print(" ")
print("-----------------------------------------------------------")
print("Largest Eigen value is : ",L1.evalf(3))
print("And Eigen Vector is : ",X1.evalf(3))
print("Smallest Eigen value is : ",1/L1.evalf(3))
|
71e18ee05051d083fa00285c9fbc116eca7fb3f3
|
bayl0n/Projects
|
/stack.py
| 794 | 4.25 | 4 |
# create a stack using a list
class Stack:
def __init__(self):
self.__stack = list()
def __str__(self):
return str(self.__stack)
def push(self, value):
self.__stack.append(value)
return self.__stack[len(self.__stack) -1]
def pop(self):
if len(self.__stack) > 0:
temp = self.__stack[len(self.__stack) - 1]
self.__stack.pop(len(self.__stack) - 1)
return temp
else:
return None
def top(self):
if len(self.__stack) > 0:
return self.__stack[len(self.__stack) - 1]
else:
return None
if __name__ == "__main__":
myStack = Stack()
print(myStack.push("Banana"))
print(myStack.pop())
print(myStack.top())
print(myStack)
|
cf82efd8c4ce0f6afb1d647c240b6e2d0d3bc01c
|
belwalter/clases_programacion_i
|
/clase3.py
| 3,278 | 4.15625 | 4 |
#! CICLOS - FUNCIONES y MODULOS - ESTRUCTURAS DE DATOS - STRING
#! Array o vectores (estatico) --> Listas dinamicas
import mis_funciones
datos = [2, 3, 4, 7, 0, 1, 56, 6]
mis_funciones.agregar(datos, 100)
print(datos)
#! Ciclos while (condicionado) for (finito)
# nombre = input('ingrese su nombre ')
# while(nombre != '' and nombre != 'carlos'):
# print('hola', nombre)
# nombre = input('ingrese su nombre ')
# for i in range(0, 6):
# nombre = input('ingrese su nombre ')
# print(i, nombre)
# if(100 in datos):
# print('esta en la lista')
# else:
# print('no esta en la lista')
# for numero in datos:
# if(numero == 45):
# print('45 esta en la lista')
# nombre = input('ingrese nombre de persona ').capitalize()
# datos.append(nombre)
# datos.append('Ana')
# datos.append('julieta')
# datos.insert(6, 'Mariano')
# datos.reverse()
# datos.sort()
# datos.remove("carlos")
# print(type(datos), len(datos))
# datos[4] = 100
# print(datos)
# cadena = " hola MUNDO desde python con vs code"
# print(cadena.capitalize())
# print(cadena.title())
# print(cadena.upper())
# print(cadena.lower())
# print(cadena.replace("o", 'r'))
# print(cadena.split())
# print(cadena.split('o'))
# print(cadena.rstrip())
# print(cadena.find('python2'))
# print(len(cadena))
# if("mundo" == 'Mundo'):
# print('verdadero')
# else:
# print('falso')
# nombre = input('ingrese su nombre ').title().split()
# print(nombre)
# if(nombre == 'Juan'):
# print('algo')
# cantidad = 18
# for i in range(0, cantidad):
# numero = int(input('ingrese un numero '))
# if(numero % 2 == 0 and numero % 3 == 0):
# print('es multiplo de 2 y de 3')
# datos = [['walter', 34], ['tito', 20], ['ana', 54]]
# for i in range(0, len(datos)):
# print(i, datos[i][0], datos[i][1])
# for persona in datos:
# print(persona[0], persona[1])
# for i in range (0, 3):
# nombre = input("ingrese su nombre ").capitalize()
# anio_nacimiento = int(input("ingrese año de nacimiento "))
# edad = 2021 - anio_nacimiento
# datos.append([nombre, edad])
# if(edad >= 18):
# print(nombre,"ES MAYOR DE EDAD")
# else:
# print('es menor de edad')
# for persona in datos:
# print(persona[0], persona[1])
# #! acumulador
# suma = 0
# #! contador
# aprobado = 0
# for i in range(0, 18):
# # nombre = input('ingrese el nombre del alumno ')
# nota = float(input("ingrese la nota del alumno"))
# if(nota >= 6):
# suma += nota #! suma = suma + nota
# aprobado += 1 #! aprobado = aprobado + 1
# print("aprobó la materia")
# else:
# print("no aprobó la materia")
# print('el promedio es', suma/aprobado)
# maximo = int(input('ingrese un numero '))
# for i in range(0, 4):
# numero = int(input('ingrese un numero '))
# if(numero > maximo):
# maximo = numero
# print('el maximo es', maximo)
# positivos = 0
# negativos = 0
# numero = int(input('ingrese un numero '))
# while(numero != 0):
# if(numero > 0):
# positivos += 1
# else:
# negativos += 1
# numero = int(input('ingrese un numero '))
# print('cantidad de positivos', positivos)
# print('cantidad de negativos', negativos)
|
16ad91f6e6452bd77f78d2083ffb5d54f140044a
|
belwalter/clases_programacion_i
|
/clase_poo.py
| 5,245 | 3.875 | 4 |
#! Programación orientada a objetos
#! Componentes: Clases, Objetos y Mensajes
#! Caracteristicas: Encapsulamiento, Herencia, Polimorfismo
#! Sobrecarga, Constructor, Ocultamiento de la informacíon
class Persona(object):
"""Clase que representa a una persona."""
def __init__(self, apellido, nombre, edad=None, email=None, n_cuenta=None):
self.__apellido = apellido
self.__nombre = nombre
self.__edad = edad
self.__email = email
self.__n_cuenta = n_cuenta
def apellido(self):
return self.__apellido
def email(self):
return self.__email
def set_email(self, mail):
"""Cambia el valor del atributo mail."""
self.__email = mail
@property
def edad(self):
return self.__edad
@edad.setter
def edad(self, edad):
"""Cambia el valor del atributo mail."""
if(type(edad) is int):
self.__edad = edad
else:
print('la edad debe ser entero')
def mostrar_datos(self):
"""Muestra los datos de cada persona."""
print(self.__apellido, self.__nombre, self.__email)
# from consumo_api import get_charter_by_id
# per1 = get_charter_by_id(20)
# persona0 = Persona(per1['name'], per1['height'])
persona1 = Persona('Perez', 'Maria', email='asdasd@asda.com')
# persona2 = Persona('Gonzalez', 'Maria', 23)
# persona3 = Persona('Caseres', 'Julieta')
# persona3.set_email("123@123.com")
# persona1.mostrar_datos()
# persona2.mostrar_datos()
# persona3.mostrar_datos()
# persona2.edad = 45
# print(persona2.edad)
# print(persona1.apellido, persona1.nombre)
# print(persona2.apellido, persona2.nombre)
# print(persona3.apellido, persona3.nombre)
# print(persona1)
# print(persona2)
# print(persona3)
# print(persona1.apellido == persona3.apellido)
#! Herencia: agrupar objetos de distinta clase
#! que se comportan de manera similar
# class Animal():
# def __init__(self, nombre, especie, cantidad_patas):
# self.nombre = nombre
# self.especie = especie
# self.cantidad_patas = cantidad_patas
# a1 = Animal('caballo', 'mamifero', 4)
# a2 = Animal('pinguino', 'mamifero', 2)
# a3 = Animal('serpiente', 'reptil', 0)
# class Alumno(Persona):
# def __init__(self, fecha_inscripcion, apellido, nombre, edad=None, email=None, n_cuenta=None):
# self.__fecha_inscripcion = fecha_inscripcion
# Persona.__init__(self, apellido, nombre, edad, email, n_cuenta)
# def inscribirse(self):
# print('el alumno se esta inscribiendo a una materia')
# def mostrar_datos(self):
# print(self.apellido(), 'se incribio a cursar en:', self.__fecha_inscripcion)
# class Docente(Persona):
# def __init__(self, cantidad_materias, apellido, nombre, edad=None, email=None, n_cuenta=None):
# self.__cantidad_materia = cantidad_materias
# Persona.__init__(self, apellido, nombre, edad, email, n_cuenta)
# def mostrar_datos(self):
# print(self.apellido(), self.__cantidad_materia)
# def dictar_clase(self):
# print('el docente esta dictanto una cátedra...')
# a = Alumno('01-03-2021', 'perez', 'juan')
# d = Docente(4, 'alvarez', 'maria')
# personas = [a, persona1, d]
# for elemento in personas:
# elemento.mostrar_datos()
class FormaGeometrica():
def __init__(self, nombre, x, y, color):
self.nombre = nombre
self.x = x
self.y = y
self.color = color
def area(self):
print('metodo para calcular el area')
def perimetro(self):
print('metodo para calcular el perimetro')
def info(self):
print(self.nombre, self.color)
class Reactangulo(FormaGeometrica):
def __init__(self, base, altura, nombre, x, y, color):
self.base = base
self.altura = altura
FormaGeometrica.__init__(self, nombre, x, y, color)
def area(self):
return self.base * self.altura
def perimetro(self):
return 2 * self.altura + 2 * self.base
from math import pi
class Circulo(FormaGeometrica):
def __init__(self, radio, nombre, x, y, color):
self.radio = radio
FormaGeometrica.__init__(self, nombre, x, y, color)
def area(self):
return pi * self.radio ** 2
def perimetro(self):
return 2 * pi * self.radio
class Triangulo(FormaGeometrica):
def __init__(self, base, altura, altura2, nombre, x, y, color):
self.base = base
self.altura = altura
self.altura2 = altura2
FormaGeometrica.__init__(self, nombre, x, y, color)
def area(self):
return self.base * self.altura / 2
def perimetro(self):
return self.base + self.altura + self.altura2
formas = []
r1 = Reactangulo(3, 6, 'rectangulo 1', 5, 7, 'rojo')
formas.append(r1)
r2 = Reactangulo(5, 4, 'rectangulo 2', 15, 70, 'azul')
formas.append(r2)
c1 = Circulo(9, 'circulo 1', -6, 21, 'negro')
formas.append(c1)
c2 = Circulo(2, 'circulo 2', -16, 2, 'violeta')
formas.append(c2)
t1 = Triangulo(3, 1, 4, 'triangulo 1', 4, 0, 'amarillo')
formas.append(t1)
for elemento in formas:
elemento.info()
print('area:', elemento.area())
print('perimetro:', elemento.perimetro())
|
fb0a30bbb716607382307096a431e1bcc190c88e
|
qiaostone/simple_search_engine
|
/CloudProject/mapperword.py
| 975 | 3.890625 | 4 |
#!/usr/bin/env python
# Use the sys module
import sys
# 'file' in this case is STDIN
def read_input(file):
# Split each line into words
for line in file:
words_list = line.split(";")
# tr = temp_sec[2].split(" ")
# tres = tr[1][1:]
# # print(res)
# res = tres.split("?")[0]
for word_item in words_list:
if word_item.strip() != "":
temp_word = word_item.split(",")
word_name = temp_word[0]
position = temp_word[1]
yield (word_name.strip(), position.strip())
def main(separator='\t'):
# Read the data using read_input
data = read_input(sys.stdin)
# Process each word returned from read_input
for word in data:
# Process each word
try:
print '%s%s%s%s%d' % (word[0], separator, word[1], separator, 1)
except Exception:
pass
if __name__ == "__main__":
main()
|
75aa041bb410a16855ce0101a9f576c57731e51a
|
alpyspayzhansaya/sprint2-TDD
|
/Client.py
| 705 | 3.671875 | 4 |
"""
private
protected
economy memory slots
"""
class Client(object):
"""
Why client?
"""
__slots__=('__dict__','_id')
def __init__(self, id, card_number):
"""
:param id:
:param card_number:
"""
self._id = id # protected variable
self.__card_number = card_number # private variable
def change_private_argument_not_properly(self,card_number):
"""
:param card_number:
:return:
"""
self.__card_number = card_number
def change_private_argument(self,card_number):
"""
:param card_number:
:return:
"""
self._Client__card_number = card_number
|
649d99f1102245585adaa9c43bf2aa7f7628b269
|
Tribruin/AdventOfCode
|
/2019/Day22.py
| 1,468 | 3.765625 | 4 |
#!/usr/local/bin/python3
deckSize = 10007
checkValue = 2019
class Deck:
def __init__(self, sizeOfDeck):
self.deck = list(range(sizeOfDeck))
return
# def size(self):
# return len(self.deck)
def printDeck(self):
print(self.deck)
def reverseShuffle(self):
print("Reversing Deck")
self.deck.reverse()
def cutN(self, n):
print(f"Cutting Deck at {n}")
if n > 0:
x = n
else:
x = len(self.deck) + n
tempCut = self.deck[0:x]
tempCut2 = self.deck[x:]
self.deck = tempCut2 + tempCut
def incrementN(self, n):
print(f"Dealing with Increment {n}")
newDeck = list(range(len(self.deck)))
pos = 0
for i in range(len(self.deck)):
newDeck[pos] = self.deck[i]
pos += n
if pos > len(self.deck):
pos = pos - len(self.deck)
self.deck = newDeck
def findValue(self, value):
return self.deck.index(value)
def main():
deck = Deck(deckSize)
r = open("Day22-Input.txt", "r")
for line in r:
if line[0:3] == "cut":
n = int(line[4:])
deck.cutN(n)
elif line[0:9] == "deal into":
deck.reverseShuffle()
else:
n = int(line[20:])
deck.incrementN(n)
# deck.printDeck()
print(deck.findValue(checkValue))
if __name__ == "__main__":
main()
|
425d1c80339adac44ee5a37f9cab83a2855c0106
|
Toodoi/Tic-Tac-Toe-Game
|
/tic_tac_toe.py
| 2,698 | 3.921875 | 4 |
import sys
class TicTacToeGame(object):
board = [[None, None, None], [None, None, None], [None, None, None]]
turn = True # Use boolean switching to alternate between turns instead of -1 and 1
def reset_game(self):
print('\n Game reset')
# Reset turn
self.turn = True
# Reset self.board
for i in range(3):
for j in range(3):
self.board[i][j] = None
def play(self):
# Game loop
while 1:
move_position = self.get_player_move()
# Place move on self.board
self.board[move_position[0]][move_position[1]] = 'X' if self.turn else 'O'
self.print_board()
# Check for win condition
# Check horizontal win condition
for i in range(3):
checkh = set(self.board[i])
if len(checkh) == 1 and self.board[i][0]:
print('Player {} wins horizontally!'.format(self.board[i][0]))
return
# Check vertical win condition
for i in range(3):
checkv = set([self.board[0][i], self.board[1][i], self.board[2][i]])
if len(checkv) == 1 and self.board[0][i]:
print('Player {} wins vertically!'.format(self.board[0][i]))
return
# Check diagonal win condition
if self.board[1][1] and ((self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]) or (self.board[2][0] == self.board[1][1] and self.board[1][1] == self.board[0][2])):
print('Player {} wins diagonally!'.format(self.board[1][1]))
return
# Toggle turn
self.turn = not self.turn
def print_board(self):
for row in self.board:
print([v if v else '-' for v in row])
def get_player_move(self):
"""
Get coordinates form player input
"""
while 1:
user_input = input('~~~ Player {}, please choose your square by specifying row,column coordinates: '.format(1 if self.turn else 2))
if user_input == 'exit':
print('Exiting game')
sys.exit()
if user_input == 'board':
self.print_board()
elif user_input == 'reset':
self.reset_game()
self.print_board()
else:
if len(user_input) != 3:
print('\nYour coordinates were not valid. Try again. \n')
continue
else:
try:
coordinates = [int(i)-1 for i in user_input.split(',')]
# Validate coordinates are valid
if self.board[coordinates[0]][coordinates[1]]:
print('\nSorry that square has already been played...\n')
continue
if any(coordinate < 0 or coordinate > 2 for coordinate in coordinates):
print('\n Coordinates are out of bounds')
continue
return coordinates
except ValueError:
print('\nInput values must be numbers between 1 and 3 inclusive.\n')
game = TicTacToeGame()
game.play()
|
15198370140d3b04074d6647eda200767cc2479d
|
rahulpawargit/UdemyCoursePractice
|
/Tuples.py
| 290 | 4.1875 | 4 |
"""
Tuples are same as list. The diffferance between list and tuples. Tuples are unmutalble. Tuples add using parenthesis
"""
my_tuple=(1, 2, 3, 4,3, 3, 3)
print(my_tuple)
print(my_tuple[1])
print(my_tuple[1:])
print(my_tuple[::-1 ])
print(my_tuple.index(3))
print((my_tuple.count(3)))
|
cfec128cbbbcdc608bd8ff51da135a0e8b1ede28
|
rahulpawargit/UdemyCoursePractice
|
/ListManage.py
| 468 | 3.765625 | 4 |
"""
Lists are orderder items witch comes with brackets and seperated with comma
"""
lst=['Rahul', 'Mahesh', 'Vishal']
print(lst)
lst[1]="Gaurav"
print(lst)
print(lst[::-1])
print
lst2=[1,4,5,6,7,8,]
sum_lst=lst2[1]+ lst2[4]
print(sum_lst)
sum_lst2=lst[1]+lst[2]
print(sum_lst2)
print("**************")
list=["bmw", "Audi", "Toyoto"]
print(len(list))
list.append("Mercedeez")
print(list)
list.pop()
print(list)
print(list[::-1])
list.sort()
print(list)
|
4f76902788467b5463d0f2f69cf1dc19282eb42a
|
rahulpawargit/UdemyCoursePractice
|
/Class_Object.py
| 349 | 3.8125 | 4 |
"""
Object is a instace of class
"""
class car(object):
def __init__(self, make,year):
self.makeof_Car=make,
self.year=year
# c1=car("bmw")
# print(c1.makeof_Car)
# c1=car("hyundai")
# print(c1.makeof_Car)
c2=car('Maruti', 2019)
print(c2.makeof_Car)
print(c2.year)
c3=car("Innova", 2020)
print(c3.makeof_Car)
print((c3.year))
|
dc4d5579d9154b73b3a5f55c6b58463f83269f10
|
SProv7615/UNCO-Projects
|
/Pre-2021/2018Python_Final_Project/Python Final Project/Scene3DragonWings.py
| 13,551 | 3.734375 | 4 |
################################################################################
# Dragon Wings Class #
# #
# PROGRAMMER: Kevin Ritter & Stephen Provost #
# CLASS: CG120 #
# ASSIGNMENT: Final Project #
# INSTRUCTOR: Dean Zeller #
# TA: Robert Carver #
# SUBMISSION DATE: 12/01/18 #
# #
# DESCRIPTION: #
# This program is a class that draws Dragon Body, and Wings #
# that can move. It appears to fly above the forest. #
# #
# EXTERNAL FILES: #
# This program is called by the following: #
# Scene3DragonTester.py, to be tested when building. #
# Scene3.py, the story runner file. #
# #
# COPYRIGHT: #
# This program is (c) 2018 Kevin Ritter and Stephen Provost. This is #
# original work, without use of outside sources. #
################################################################################
from tkinter import *
import random
# Define a class called DragonWings
class DragonWings:
#####################################################################
# __init__ #
# #
# purpose: #
# initialize attributes to parameters #
# parameters: #
# canvas -- the canvas to draw the forest #
# name -- name of the stripe, used as a tag for animation #
# dragonColor -- the color of the dragon wings #
# return value: none #
#####################################################################
def __init__ (self, canvas, name="DragonWings", dragonColor="gray1"):
self.c = canvas
self.name = name
self.DWcenter = 0
self.DWmiddle = 0
self.dragonColor = dragonColor
self.flap = 1
self.flapDir = "up"
#####################################################################
# draw DragonWings 1 #
# #
# purpose: #
# Draws dragon wings instance with its initial #
# location and color. #
# parameters: #
# none #
# return value: none #
#####################################################################
def drawDragonWings1(self, x, y, size):
# all coordinates are procedurally chosen based on initial x, y
# this allows the dragon's initial position to change
self.DWcenter = x
self.DWmiddle = y
self.size = size
LeftWingCoords = ( (x - 7*size, y), (x - 3.5*size, y - size),
(x - size, y - 1.5*size), (x - 0.75*size, y + size),
(x - 1.25*size, y + size/4), (x - 1.5*size, y + size/8),
(x - 2.25*size, y + size/2), (x - 2.75*size, y + size),
(x - 4.5*size, y + size) )
RightWingCoords = ( (x + 7*size, y), (x + 3.5*size, y - size),
(x + size, y - 1.5*size), (x + 0.75*size, y + size),
(x + 1.25*size, y + size/4), (x + 1.5*size, y + size/8),
(x + 2.25*size, y + size/2), (x + 2.75*size, y + size),
(x + 4.5*size, y + size) )
self.c.create_polygon(LeftWingCoords, fill = self.dragonColor,
width=0, tag=self.name)
self.c.create_polygon(RightWingCoords, fill = self.dragonColor,
width=0, tag=self.name)
self.drawDragonBody(self.DWcenter, self.DWmiddle, self.size)
self.c.update()
#####################################################################
# draw DragonWings 2 #
# #
# purpose: #
# Draws dragon wings instance with its secondary #
# location and color. #
# parameters: #
# none #
# return value: none #
#####################################################################
def drawDragonWings2(self, x, y, size):
# all coordinates are procedurally chosen based on initial x, y
# this allows the dragon's initial position to change
self.DWcenter = x
self.DWmiddle = y
self.size = size
LeftWingCoords = ( (x - 5.5*size, y - 3*size), (x - 3.75*size, y - 1.25*size),
(x - size, y - 1.5*size), (x - 0.75*size, y + size),
(x - 1.25*size, y + size/4), (x - 1.5*size, y + size/8),
(x - 2*size, y + size/4), (x - 2.5*size, y + size/2),
(x - 3.5*size, y + size/2), (x - 4.75*size, y - size/3) )
RightWingCoords = ( (x + 5.5*size, y - 3*size), (x + 3.75*size, y - 1.25*size),
(x + size, y - 1.5*size), (x + 0.75*size, y + size),
(x + 1.25*size, y + size/4), (x + 1.5*size, y + size/8),
(x + 2*size, y + size/4), (x + 2.5*size, y + size/2),
(x + 3.5*size, y + size/2), (x + 4.75*size, y - size/3) )
self.c.create_polygon(LeftWingCoords, fill = self.dragonColor,
width=0, tag=self.name)
self.c.create_polygon(RightWingCoords, fill = self.dragonColor,
width=0, tag=self.name)
self.drawDragonBody(self.DWcenter, self.DWmiddle, self.size)
self.c.update()
#####################################################################
# draw DragonWings 3 #
# #
# purpose: #
# Draws dragon wings instance with its tertiary #
# location and color. #
# parameters: #
# none #
# return value: none #
#####################################################################
def drawDragonWings3(self, x, y, size):
# all coordinates are procedurally chosen based on initial x, y
# this allows the dragon's initial position to change
self.DWcenter = x
self.DWmiddle = y
self.size = size
LeftWingCoords = ( (x - 6*size, y - size), (x - 3.75*size, y - size),
(x - size, y - 1.5*size), (x - 0.75*size, y + size),
(x - 1.25*size, y + size/4), (x - 1.5*size, y + size/8),
(x - 2*size, y + size/4), (x - 2.5*size, y + size/2),
(x - 3.5*size, y + size), (x - 5.25*size, y) )
RightWingCoords = ( (x + 6*size, y - size), (x + 3.75*size, y - size),
(x + size, y - 1.5*size), (x + 0.75*size, y + size),
(x + 1.25*size, y + size/4), (x + 1.5*size, y + size/8),
(x + 2*size, y + size/4), (x + 2.5*size, y + size/2),
(x + 3.5*size, y + size), (x + 5.25*size, y) )
self.c.create_polygon(LeftWingCoords, fill = self.dragonColor,
width=0, tag=self.name)
self.c.create_polygon(RightWingCoords, fill = self.dragonColor,
width=0, tag=self.name)
self.drawDragonBody(self.DWcenter, self.DWmiddle, self.size)
self.c.update()
#####################################################################
# draw DragonBody #
# #
# purpose: #
# Draws dragon body instance with its initial location #
# and color. #
# parameters: #
# none #
# return value: none #
#####################################################################
def drawDragonBody(self, x, y, size):
# all coordinates are procedurally chosen based on initial x, y
# this allows the dragon's initial position to change
self.DWcenter = x
self.DWmiddle = y
self.size = size
BodyCoords = ( (x - 0.75*size, y + size), (x - size, y - 1.5*size),
(x, y - 3*size), (x + size, y - 1.5*size),
(x + 0.75*size, y + size) )
self.c.create_polygon(BodyCoords, fill = self.dragonColor,
width=0, tag=self.name)
self.c.update()
#####################################################################
# DragonWings Flap #
# #
# purpose: #
# Draws alternating dragon wings instance between initial #
# and its secondary location and color. #
# parameters: #
# none #
# return value: none #
#####################################################################
def DragonWingsFlap(self, x, y, size):
# all coordinates are procedurally chosen based on initial x, y
# this allows the dragon's initial position to change
self.c.delete(self.name)
if self.flap == 1:
self.drawDragonWings1(self.DWcenter, self.DWmiddle, self.size)
self.flap += 1
self.flapDir = 'up'
elif self.flap == 2 and self.flapDir == 'up':
self.drawDragonWings3(self.DWcenter, self.DWmiddle, self.size)
self.flap += 1
elif self.flap == 2 and self.flapDir == 'down':
self.drawDragonWings3(self.DWcenter, self.DWmiddle, self.size)
self.flap -= 1
else:
self.drawDragonWings2(self.DWcenter, self.DWmiddle, self.size)
self.flap -=1
self.flapDir = 'down'
#####################################################################
# moveDown #
# #
# purpose: #
# moves the Layer to down the specified distance #
# parameters: #
# dist -- distance to move #
# prevDelay -- amount of delay before the move (default of 0) #
# afterDelay -- amount of delay after the move (default of 0) #
# return value: none #
#####################################################################
def moveDown(self, dist, prevDelay=0, afterDelay=0):
self.c.after(prevDelay)
self.c.update()
self.c.move(self.name, 0, dist)
self.DWmiddle += dist
self.c.update()
self.c.after(afterDelay)
self.c.update()
|
992a9f723d43e27012f62d83e67d7a488741feb1
|
marcossilvaxx/ExercicioPosGreve
|
/ExercicioPosGreve/Questao4.py
| 155 | 3.90625 | 4 |
numero = eval(input("Informe o nmero:\n"))
soma = 0
for i in range(1, numero + 1):
soma = soma + i
print("O resultado obtido foi:", soma)
|
eaf66f2ee31f24966109d140a68b825fd834c8e5
|
Charlie-lusie/codes
|
/LastKNumbers.py
| 1,059 | 3.515625 | 4 |
# -*- coding:utf-8 -*-
import random
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
result = []
if (len(tinput) == 0 or k <= 0 or k > len(tinput)): return result
pos, start, end = -1, 0, len(tinput) - 1
while(pos != k - 1):
if (pos > k - 1): end = pos - 1
else: start = pos + 1
pos, tinput = self.exchange(tinput, start, end)
return tinput[0:k]
def exchange(self, input, st, en):
pos = st
pick_one_element = random.randint(st, en)
input[pick_one_element], input[en] = input[en], input[pick_one_element]# pick one and put it to the end
for i in range(st, en):
if (input[i] <= input[en]):
if (pos != i):
input[pos], input[i] = input[i], input[pos]#exchange numbers
pos += 1
input[pos], input[en] = input[en], input[pos]
return pos, input
A = Solution()
b = A.GetLeastNumbers_Solution([4,5,1,6,2,7,3,8], 4)
print(b)
|
eb850b1cea873c9e77d028604c8e3fafb5e33e73
|
darksoul985/Algorithms
|
/lesson_7_task_1.py
| 1,579 | 3.921875 | 4 |
#-*-coding: utf-8-*-
'''
1). Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами
на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы.
Примечания:
● алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных,
● постарайтесь сделать алгоритм умнее, но помните, что у вас должна остаться сортировка пузырьком.
Улучшенные версии сортировки, например, расчёской, шейкерная и другие в зачёт не идут.
'''
import random
def bubble_sort(date: list):
n = 1
while n < len(date):
for i in range(len(date) - 1):
if date[i] > date[i + 1]:
date[i], date[i + 1] = date[i + 1], date[i]
n += 1
return date
def bubble_sort2(date: list):
for i in range(len(date)-1): # кажется for должен быть быстрее
for j in range(i, len(date)-1):
if date[j] > date[j + 1]:
date[j], date[j + 1] = date[j + 1], date[j]
return date
MAX = 100
MIN = -100
LENGTH_ARR = 20
arr = [random.randrange(MIN, MAX) for i in range(LENGTH_ARR)]
print(arr)
print(bubble_sort(arr))
print(bubble_sort2(arr))
|
a7a71f54738641283bb9cbf763d581cdea778666
|
darksoul985/Algorithms
|
/lesson_3_task_3.py
| 1,011 | 3.78125 | 4 |
# -*- coding: utf-8 -*-
'''
3. В массиве случайных целых чисел поменять местами минимальный
и максимальный элементы.
'''
from random import randint
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 100
arr = [randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
arr_copy = []
for i in arr: # Создаем список уникальных значений
if i not in arr_copy:
arr_copy.append(i)
max_el = MIN_ITEM
min_el = MAX_ITEM
for i in arr_copy: # Находим минимальный и максимальный значения
if i > max_el:
max_el = i
if i < min_el:
min_el = i
print(f'Первоначальный список {arr}')
for idx, val in enumerate(arr): # Заменяем
if val == min_el:
arr[idx] = max_el
elif val == max_el:
arr[idx] = min_el
print(f'Список с замененными элементами {arr}')
|
8cab0d9b484ed21bbc1501b40c2d1881c23e5685
|
taeryu0627/face_mask_detector
|
/lab_data/image_paste.py
| 1,038 | 3.546875 | 4 |
#마스크 이미지를 원본 이미지에 합성하는 코드
import face_recognition
from PIL import Image, ImageDraw
#이미지 열어주기
image_path = '../data/without_mask/0.jpg'
mask_image_path = '../data/mask.png'
face_image_np = face_recognition.load_image_file(image_path) # 이미지를 일단 불러오기만,,
face_locations = face_recognition.face_locations(face_image_np, model='hog')
face_image = Image.fromarray(face_image_np)
draw = ImageDraw.Draw(face_image)
for face_location in face_locations: # 각 얼굴 위치([(46, 114, 108, 52)])들이 face location 안에 들어감
top = face_location[0]
right = face_location[1]
bottom = face_location[2]
left = face_location[3]
mask_image = Image.open(mask_image_path)
a=int(((right+left)/2)-(right-left)//2)
b=int(bottom*(3/4))
num1=right-left
num2=(bottom-top)
mask_image = mask_image.resize((num1, num2))
draw.rectangle(((left, top), (right, bottom)), outline=(255,9,220), width=10)
face_image.paste(mask_image,(a,b), mask_image)
face_image.show()
|
df0dc20b8cf0e323deb906f3aaee6b22fce8d985
|
cgMuro/auto-image-captioning
|
/app/app.py
| 1,932 | 4.03125 | 4 |
import streamlit as st
from PIL import Image
# Import functions to make the prediction
from predict import model, tokenizer, maxlength
from predict import extract_features, generate_description
# Call all the necessary function needed to generate the caption
def get_caption(img):
# Extract features
with st.spinner('Extracting features from image...'):
img = extract_features(img)
# Get description
with st.spinner('Generating description...'):
description = generate_description(model, tokenizer, img, maxlength)
# Remove start and end sequences
description = ' '.join(description.split()[1:-1])
return description
# Set title
st.title('Auto Image Captioning')
# Add sidebar with explanation
st.sidebar.header('What is this and how does it work?')
st.sidebar.write('''
This is an application that uses a neural network to auto caption images.
You can upload an image and by clicking the button below it get a caption from the model.
*Please note* that since the dataset I used to train the model was relatively small (due to the lack of computationally resources), sometimes it can be quite wrong.
If you want to know more about this project and the code behind it check it out on [GitHub](https://github.com/cgMuro/auto-image-captioning).
''')
# Get image
input_image = st.file_uploader("Upload an image to caption", type=["png", "jpg", "jpeg"])
if input_image:
# Display uploaded image
input_image = Image.open(input_image)
st.image(input_image, use_column_width=True)
if st.button('Get Caption!'):
# Get description of the image
input_image_resized = input_image.resize((224, 224)) # Resize image
description = get_caption(input_image_resized)
# Write caption
st.write(f'**{description}**')
# Draw celebratory balloons
st.balloons()
|
e882447582ce286a0adce06d98c27203b0f595f4
|
TheDitis/TurtleFun
|
/TurtleFun/outward_turtle_1.0.py
| 1,011 | 3.5625 | 4 |
import turtle
angle = 5
collist2 = ['red', 'crimson', 'orangered', 'darkorange', 'orange', 'gold', 'yellow', 'greenyellow', 'lawngreen', 'limegreen', 'springgreen', 'mediumspringgreen', 'aquamarine', 'turquoise', 'aqua', 'deepskyblue', 'dodgerblue', 'mediumslateblue', 'mediumpurple', 'blueviolet', 'darkviolet', 'purple', 'mediumvioletred']
linewidth = 1
rate = 0.01
instant = 1
def setup_turtle():
turtle.bgcolor('black')
turtle.tracer(10, 1)
if instant:
turtle.tracer(0, 0)
turtle.pensize(linewidth)
turtle.pendown()
def loop():
for i in range(10000):
colsel = i % len(collist2)
turtle.color(collist2[colsel])
fwdamt = rate * i
turtle.forward(fwdamt)
# forward_color_split(fwdamt)
turtle.left(angle)
turtle.exitonclick()
def forward_color_split(totlen):
for i in range(len(collist2)):
divamt = totlen / len(collist2)
turtle.color(collist2[i])
turtle.forward(divamt)
setup_turtle()
loop()
|
f8be6b325e51f76b7ff82ff402bfd16a16d621f3
|
iceterminal/python
|
/Phone Bill.py
| 829 | 4 | 4 |
###Cell Phone Bill Calculator###
print ("")###Just to add more space###
print ("")###Just to add more space###
print ("The Economy plan includes $30 unlimited voice and text, 1 GB data for $10, and $6 for every GB over.")
print ("The Normal plan includes $30 unlimited voice and text, 5 GB data for $30, and $4 for every GB over.")
print ("")###Just to add more space###
plan = input ("What plan would you like? Type 'a' for Economy plan, or 'b' for Normal plan. > ")
d = int (float ("How many gigabytes of data do you use? > "))
if (plan == a):
and (d <= 1):
bill = (30+10)
and (d > 1):
bill = (30+10+(6*d))
if (plan==b):
and (d <= 5):
bill = (30+30)
and (d > 5):
bill = (30+5+(4*d))
print ("Your bill totals out to be," bill "dollars")
|
2ddc2876dc0797dfb98135926df05b4ab408060e
|
putheac/python-fun
|
/data_structures/tuples.py
| 848 | 4.0625 | 4 |
#10.2 Write a program to read through the mbox-short.txt and figure out
#the distribution by hour of the day for each of the messages. You can
#pull the hour out from the 'From ' line by finding the time and then
#splitting the string a second time using a colon.
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
#Once you have accumulated the counts for each hour, print out the counts,
#sorted by hour as shown below.
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts=dict()
for line in handle:
if line.startswith('From '):
words = line.split()
time_parts = words[5].split(":")
hour = time_parts[0]
counts[hour] = counts.get(hour, 0) + 1
lst = list()
for key, val in counts.items():
lst.append((key,val))
lst.sort()
for val, key in lst:
print val, key
|
54749a99e2d1d13fa81cc857fc94adc4aa572e0b
|
Bryson14/AdvancedAlgo
|
/src/Final/prob1.py
| 2,608 | 3.78125 | 4 |
"""
You have solar panels that are mounted on a pole in your front yard. They have three settings that tip the panels at
different angles with respect to the horizontal. As the seasons change, the settings allow you to capture more solar
energy by better aligning the tipping angle of the panels with the position of the sun in the sky. Let these settings
be called 0, 1, and 2.
You are given the following:
A table that maps the day-of-year (1 to 366) and the setting (0, 1, 2) to an estimate of the energy you could collect.
Let this table be E[d, s], 0 < d <= 366, and 0 <= s < 3. So E[d, s] will return the amount of energy you could collect
if the panels are in setting s on day-of-year d.
Design an algorithm that will work out the days you should change from one setting to another over the year in order
to maximize your solar energy collection. Note: You can only make a maximum of four changes in settings in a year.
"""
import numpy as np
days = 4
E = np.reshape(np.random.random(days*3), (days, -1))
settings = [0, 1, 2]
print(E)
def solar_panels(day, curr_set, changes):
if day >= days:
return 0.0
# there are no more changes
if changes >= 4:
return sum(E[day:,curr_set])
today_value = E[day][curr_set]
return today_value + max(solar_panels(day + 1, setting, changes + (setting != curr_set)) for setting in settings)
def solar_dp(curr_set, days):
change_limit = 4
settings = 3
# create cache
c = np.zeros((days, settings, change_limit))
# fill in base cases
for i in range(days):
for j in range(settings):
c[i, j, change_limit - 1] = sum(E[i:, j])
for i in range(days):
for j in range(settings):
for k in range(change_limit):
c[i, j, k] = E[i][j] + max(c[i + 1, setting, k + (setting != curr_set)] for setting in range(settings))
return max(c[days])
def traceback(c, days, best_setting):
curr = (0, best_setting, 0)
for i in range(days):
m = max(c[curr[0] + 1, j, :] for j in range(3))
next_curr = location(m)
if next_curr[2] != curr[2]:
print(f"At day {curr[0]}, panels changed to position{next_curr[1]}")
else:
print(f"Panels continued at postiion {next_curr[1]}")
print(f" {E[i]} energy was gained today to make the total so far {E[next_curr]}")
print(f"best Path resulted in {max(c[days])} gained")
print(solar_panels(0, 0, 0))
print(solar_panels(0, 1, 0))
print(solar_panels(0, 2, 0))
print(solar_dp(0, len(E)))
print(solar_dp(1, len(E)))
print(solar_dp(2, len(E)))
|
186ea3c70994726a8b6fe9ea2d00c44e116cbc16
|
zaochnik555/Python_1_lessons-1
|
/lesson_02/home_work/hw02_easy.py
| 2,044 | 4.125 | 4 |
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
print("Задача 1")
fruit_list=["яблоко", "банан", "киви", "арбуз"]
for x in range(0, len(fruit_list)):
print('%d.'%(x+1), '{:>6}'.format(fruit_list[x].strip()))
# Задача-2:
# Даны два произвольные списка.
# Удалите из первого списка элементы, присутствующие во втором списке и выведите результат.
print("\nЗадача 2")
list1=[i**2 for i in range(10)]
list2=[i**2 for i in range(0,20,2)]
print('Список 1:',list1)
print('Список 2:',list2)
i=0
while i<len(list1):
if list1[i] in list2:
list1.pop(i)
i-=1
i+=1
print('Решение 1:',list1)
#другое решение
list1=[i**2 for i in range(10)]
list2=[i**2 for i in range(0,20,2)]
print('Решение 2:',list(set(list1) - set(list2)))
# Задача-3:
# Дан произвольный список из целых чисел.
# Получите НОВЫЙ список из элементов исходного, выполнив следующие условия:
# если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два.
# и выведите результат
print("\nЗадача 3")
list4=[i**2 for i in range(0,25,3)]
list5=[]
print('Исходный список:',list4)
for el in list4:
if el%2==0:
list5.append(el/4)
else:
list5.append(el*2)
print('Результат:',list5)
|
6db8951807791fd2c0cd6abd598c3099aeaf8a44
|
ranisharma20/My_file
|
/village_qu4.py
| 607 | 3.671875 | 4 |
def file1():
file1=open("delhi.txt","r")
c=0
for i in (file1):
c=c+1
print(i)
file1.close()
def file2():
file2=open("shimla.txt","r")
d=0
for j in (file2):
d=d+1
print(j)
file2.close()
def file3():
file3=open("others.txt","r")
e=0
for k in (file3):
e=e+1
print(k)
file3.close()
def main():
user_choice=input("enter the village name = ")
if user_choice=="delhi":
file1()
elif user_choice=="shimla":
file2()
elif user_choice=="other":
file3()
else:
pass
main()
|
a667df21ea15fc0c732eacbbe7499bf997663a2b
|
deepanshu3131/Project-Euler
|
/2.py
| 302 | 3.609375 | 4 |
# -*- coding: utf-8 -*-
# @Author: deepanshu
# @Date: 2016-05-02 03:42:40
# @Last Modified by: deepanshu
# @Last Modified time: 2016-05-02 03:45:17
t=int(input())
for i in range (t):
n=int(input())
a,b,sum=1,2,0
while b<=n:
if b%2==0: sum+=b
a , b = b , a+b
print(sum)
|
cac5be02d171d144119f1b42fa090e2c47a3e0f0
|
lgknasupra/fichas
|
/Exercicios/FP1/ex2.py
| 108 | 3.828125 | 4 |
num1 = int(input("Numero 1:"))
num2 = int(input("Numero 2:"))
valor = int((num1 - num2) * num1)
print(valor)
|
ec8ba36cf075cfaf41c5df51a943564de1703c84
|
wqdchn/geektime
|
/algorithm-40case/array-linkedlist/swap_nodes_in_pairs.py
| 1,204 | 3.734375 | 4 |
# @program: PyDemo
# @description: https://leetcode.com/problems/swap-nodes-in-pairs/submissions/
#Given a linked list, swap every two adjacent nodes and return its head.
#You may not modify the values in the list's nodes, only nodes itself may be changed.
#Example:
#
#Given 1->2->3->4, you should return the list as 2->1->4->3.
#
# @author: wqdong
# @create: 2019-08-05 15:16
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
pre, pre.next = self, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
return self.next
def createList(self):
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
return head
s = Solution()
# 1
head = s.createList()
head = s.swapPairs(head)
while(head != None):
print(head.val)
head = head.next
|
f3c5782e00d49413ffec55a8503235e35cc7ac33
|
wqdchn/geektime
|
/algorithm-40case/array-linkedlist/remove_linked_list_elements.py
| 1,333 | 3.53125 | 4 |
# @program: PyDemo
# @description: https://leetcode.com/problems/remove-linked-list-elements/
# @author: wqdong
# @create: 2019-11-06 21:09
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements1(self, head, val):
dummy = ListNode(-1)
dummy.next, prev = head, dummy
while prev.next:
if prev.next.val == val:
prev.next = prev.next.next
else:
prev = prev.next
return dummy.next
def removeElements2(self, head, val):
if head == None: return None
temp = self.removeElements2(head.next, val)
if head.val == val: return temp
head.next = temp
return head
def createList(self):
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
return head
s = Solution()
head = s.createList()
head = s.removeElements1(head, 3)
while (head != None):
print(head.val)
head = head.next
head = s.createList()
head = s.removeElements2(head, 3)
while (head != None):
print(head.val)
head = head.next
|
c0c34cd6ff8852436f2762e9ea3bf21617397291
|
wqdchn/geektime
|
/algorithm-40case/array-linkedlist/container_with_most_water.py
| 1,442 | 3.53125 | 4 |
# @program: PyDemo
# @description: https://leetcode.com/problems/container-with-most-water/
# @author: wqdong
# @create: 2019-11-05 08:48
class Solution:
def maxArea_1(self, height): # Time Limit Exceeded
result = 0
for i in range(0, len(height)):
for j in range(i + 1, len(height)):
result = max(result, min(height[i], height[j]) * (j - i))
return result
def maxArea_2(self, height): # Runtime: 152 ms, faster than 36.03%
result, left, right = 0, 0, len(height) - 1
while left < right:
result = max(result, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return result
def maxArea_3(self, height): # Runtime: 144 ms, faster than 72.17%
left = 0
right = len(height) - 1
result = 0
while left < right:
if height[left] < height[right]:
area = height[left] * (right - left)
left += 1
else:
area = height[right] * (right - left)
right -= 1
if area > result:
result = area
return result
s = Solution()
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(s.maxArea_1(height))
print(s.maxArea_2(height))
print(s.maxArea_3(height))
|
918b830a1adfc0f24b16879e956f0c1769acde12
|
wqdchn/geektime
|
/algorithm-40case/array-linkedlist/intersection_of_two_linked_list.py
| 1,056 | 3.609375 | 4 |
# @program: PyDemo
# @description: https://leetcode.com/problems/intersection-of-two-linked-lists/
# @author: wqdong
# @create: 2020-01-31 09:48
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# Runtime: 164 ms, faster than 75.79% of Python3 online submissions for Intersection of Two Linked Lists.
def getIntersectionNode(self, headA, headB):
if not headA and not headB: return None
a, b = headA, headB
while a is not b:
a = headB if a is None else a.next
b = headA if b is None else b.next
return a
sl = Solution()
temp = ListNode(8)
a = ListNode(4)
a.next = ListNode(1)
a.next.next = temp
a.next.next.next = ListNode(4)
a.next.next.next.next = ListNode(5)
b = ListNode(5)
b.next = ListNode(0)
b.next.next = ListNode(1)
b.next.next.next = temp
b.next.next.next.next = ListNode(4)
b.next.next.next.next.next = ListNode(5)
rs = sl.getIntersectionNode(a, b)
if rs:
print(rs.val)
|
5c62584177146dbd867f534923fe37e38d865051
|
bogdan-evtushenko/codes_competition
|
/algorithms/battleship/Algorithm1.py
| 665 | 3.859375 | 4 |
def shipsPlacement():
# (size (1-4), [coords (x, y)(0-9) )], route ('left', 'right', 'top', 'bottom') )
return (
[4, [0, 0], 'right'],
[3, [2, 0], 'right'],
[3, [9, 2], 'top'],
[2, [0, 5], 'bottom'],
[2, [0, 9], 'bottom'],
[2, [7, 9], 'left'],
[1, [0, 7], 'right'],
[1, [5, 3], 'right'],
[1, [5, 7], 'right'],
[1, [3, 9], 'right']
)
def algorithm(matrix):
# matrix[x][y] == '-1' - empty
# matrix[x][y] == '-' - miss
# matrix[x][y] == '+' - hit
for x in range(10):
for y in range(10):
if matrix[x][y] == '-1':
return x, y
|
8958e044b9a14f969edbe14eba49a06de6858277
|
jnotor/data_encoding_2021
|
/arithmetic+coding_quiz/a_code.py
| 928 | 3.984375 | 4 |
def calc_interval(freq, word):
low = 0
high = 1
for char in word:
Range = high - low
high = low + Range * freq[char]['higher']
low = low + Range * freq[char]['lower']
print(char, ':', low, high)
return low, high
def get_char_freq(word):
freq = {}
for char in word:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
# calculate probability of chars
for char in freq:
freq[char] /= len(word)
i = 0
freq_intervals = {}
for char in freq:
h_bound = l_bound if i > 0 else 1
l_bound = h_bound - freq[char]
freq_intervals[char] = {'lower' : l_bound, 'higher' : h_bound}
i += 1
return freq_intervals
def main():
code_word = "ohio"
freq_d = get_char_freq(code_word)
print(calc_interval(freq_d, code_word))
if __name__ == '__main__':
main()
|
8b13cb1e0cf41374ae16f29a8c2b3570cad9d309
|
nagamiya/AtCoder
|
/ABC162/162a.py
| 95 | 3.5 | 4 |
import re
# input
n = input()
if (re.match('.*7.*', n)):
print("Yes")
else:
print("No")
|
f0a24a3a5150c95a39f0ee1c578e7e9c3dcf1379
|
devakar/codes
|
/coding/fib.py
| 136 | 3.640625 | 4 |
def fib(n):
if n==1:
return 1
elif n==0:
return 0;
else:
return (fib(n-1)+fib(n-2))
for i in range(10):
print fib(i)
|
717ffcdd4454ea3efa2ae03c5b19c25521830f88
|
Rohit-dev-coder/AlgoCodes
|
/MigratingBirds0.py
| 733 | 3.578125 | 4 |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the migratoryBirds function below.
def migratoryBirds(arr):
dict = {}
for no in arr:
if no not in dict.keys():
add = {no: arr.count(no)}
dict.update(add)
mvalue = 0
mkey = 0
print(dict)
for key,value in dict.items():
if value > mvalue :
mkey = key
mvalue = value
if value == mvalue:
if mkey > key :
mkey = key
mvalue = value
return mkey
if __name__ == '__main__':
arr_count = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = migratoryBirds(arr)
print(result)
|
d30ab0a04c542d2f169c3c3a6a0b0abca68b43cd
|
suastegui10/lps_compsci
|
/problem_sets/loops.py
| 191 | 3.984375 | 4 |
print("enter your favorite number")
n = int(raw_input())
while n != 14:
print("i don't like that number- please try another number")
else:
n == 14
print("that is the best number")
|
4a1a96234f55b6e74cbf7b814ecb9161d3eec217
|
marinamarsh/lab2
|
/lab2.py
| 416 | 3.59375 | 4 |
mas = [4, 7, 2, 3, 1, 5, 9, 8]
def find_min(mas):
min = mas[0]
for z in mas:
if z < min:
min = z
return min
def arf_min(mas):
s = 0
for z in mas:
s = s + z
s = s / len(mas)
return s
print("Mинимума в массиве:", (find_min(mas)))
print("Среднее арифметическое с массиве:", (arf_min(mas)))
|
a16da30994782b43ce082c038e006c5edbd9c7a2
|
rkhood/advent_of_code
|
/2021/day01.py
| 389 | 3.65625 | 4 |
"""
Count the number of times a depth measurement increases
"""
def num_increases(report):
depths = report.split()
return sum(d2 > d1 for d1, d2 in zip(depths, depths[1:]))
if __name__=="__main__":
report = """
199
200
208
210
200
207
240
269
260
263
"""
print(num_increases(report))
|
80f74d2267de5fc393563cbd211272282be690d3
|
LiChan239/Lottery-QuickPick
|
/lottery.py
| 3,521 | 3.9375 | 4 |
"""
Program: lottery.py
Anthor: Li Chan
Project: Lottery Quick Pick
This program generates 5 random numbers between 1 and 50. By clicking the Quick Pick button,the computer randomly selects the numbers for you.
"""
from tkinter import *
import random
# This function generates 5 random numbers between 1 and 50.
def pickNum():
lottoNum = []
for i in range(5):
number = random.randint(1, 50)
lottoNum.append(number)
return lottoNum
class Lottery(Frame):
"""This class represents GUI-based Lottery numbers generator."""
def __init__(self):
"""Set up the window and the widgets."""
Frame.__init__(self)
self.master.title("Lottery Game")
# Set up the heading
self.grid()
self._label = Label(self, text = "Welcome to New York Lottery", fg = "red",
font = ("Arial", 25), justify = "center")
self._label.grid(row = 0, column = 0, columnspan = 6)
# Set up the entry fields for selected numbers
self.grid_rowconfigure(2, minsize=20)
self._Num1Var = IntVar()
self._Num1Entry = Entry(self, textvariable = self._Num1Var, bd=10, insertwidth=0.2,
width = 10, font = ("Arial", 15))
self._Num1Entry.grid(row = 3, column = 1)
self._Num2Var = IntVar()
self._Num2Entry = Entry(self, textvariable = self._Num2Var, bd=10, insertwidth=0.2,
width = 10, font = ("Arial", 15))
self._Num2Entry.grid(row = 3, column = 2)
self._Num3Var = IntVar()
self._Num3Entry = Entry(self, textvariable = self._Num3Var, bd=10, insertwidth=0.2,
width = 10, font = ("Arial", 15))
self._Num3Entry.grid(row = 3, column = 3)
self._Num4Var = IntVar()
self._Num4Entry = Entry(self, textvariable = self._Num4Var, bd=10, insertwidth=0.2,
width = 10, font = ("Arial", 15))
self._Num4Entry.grid(row = 3, column = 4)
self._Num5Var = IntVar()
self._Num5Entry = Entry(self, textvariable = self._Num5Var, bd=10, insertwidth=0.2,
width = 10, font = ("Arial", 15))
self._Num5Entry.grid(row = 3, column = 5)
# Set up button to quick pick 5 ramdom numbers
self.grid_rowconfigure(15, minsize=50)
self._button1 = Button(self, text = "Quick Pick", fg = "green",
font = ("Arial", 15), command = self._quickPick)
self._button1.config(height = 1, width = 15)
self._button1.grid(row = 5, column = 1, columnspan = 2)
# Set up button to clear the selected numbers
self.grid_rowconfigure(15, minsize=50)
self._button2 = Button(self, text = "Reset", fg = "blue",
font = ("Arial", 15), command = self._reset)
self._button2.config(height = 1, width = 15)
self._button2.grid(row = 5, column = 3, columnspan = 2)
def _quickPick(self):
"""Event handler for the Quick Pick button"""
numbers = pickNum()
self._Num1Var.set(numbers[0])
self._Num2Var.set(numbers[1])
self._Num3Var.set(numbers[2])
self._Num4Var.set(numbers[3])
self._Num5Var.set(numbers[4])
def _reset(self):
"""Reset all the selected numbers when clicking the Reset button"""
self._Num1Var.set(0)
self._Num2Var.set(0)
self._Num3Var.set(0)
self._Num4Var.set(0)
self._Num5Var.set(0)
def main():
"""Initialize and pop up the window."""
Lottery().mainloop()
main()
|
2452f2ac0ccceb1cdb02880202bb70918eba9f03
|
dumalang/python-cheatsheet
|
/1.5.classes.py
| 622 | 3.921875 | 4 |
class myClass():
def method1(self):
print("myClass method 1")
def method2(self, someString):
print("myClass method 2 " + someString)
def method3(self, someString=""):
print("myClass method 3 " + someString)
class childClass(myClass):
def method1(self):
myClass.method1(self)
print("myClass method 1")
def method2(self, someString):
print("myClass method 2 ")
def main():
c = myClass()
c.method1()
c.method2("wkwk")
c.method3()
print("=" * 10)
d = childClass()
d.method1()
d.method2("wkwk")
d.method3()
main()
|
f7ec1c0eca2e27e733473040f284640f75c37a80
|
flahlee/Coding-Dojo
|
/pythonFundamentals/string_list.py
| 586 | 4.125 | 4 |
#find and replace
words = "It's thanksgiving day. It's my birthday, too!"
day = 'day'
print words.find(day)
print words.replace(day, "month")
#min and max
x = [2,54,-2,7,12,98]
print min(x)
print max(x)
#first and last
x = ["hello", 2, 54, -2, 7, 12, 98, "world"]
newX= [x[0],x[7]]
print newX
#new list
'''sort list first- split list in half-
push the list created from the first half to position O of the list created from the second half'''
x = [19,2,54,-2,7,12,98,32,10,-3,6]
x.sort()
print x
first_half= x[len(x)/2]
second_half= x[len(x)/2:]
print first_half
print second_half
|
15c90b67aa7916557275303e16bd8d69f0d8f919
|
Zangdarr/PPD_calcul_de_pi
|
/part_of_pi.py
| 647 | 3.53125 | 4 |
"""
Calcul d'une partie du nombre pi
Stockera le resultat dans un fichier tmp_result{numero de l'unité de calcul}
"""
import sys
if __name__ == "__main__" :
starting_value = int(sys.argv[1])
step_value = int(sys.argv[2])
max_value = int(sys.argv[3])
FILE_TMP = "tmp_result" + str(starting_value)
print("START from {0} with {1} steps".format(starting_value,step_value))
result = 0
i = starting_value
while(i<max_value):
etape1 = (-1)**i
etape2 = (2 * i) + 1
result = result + (etape1 / etape2)
i = i + step_value
f = open(FILE_TMP, "a")
f.write("%s\n" % result)
|
91b6ea82c9d5900f456618f178c0725bb9cca9b8
|
shuaijunchen/Python3
|
/basic/recu.py
| 212 | 3.921875 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, porduct):
if num == 1:
return porduct
return fact_iter(num-1, num * porduct)
print(fact_iter(1000,1))
|
75f2c8f77f19883b41af604e0bb70318243efcd5
|
Sameer19A/Python-Basics
|
/HelloWorld.py
| 243 | 4.28125 | 4 |
#Compulsory Task 3
name = input("Enter your name: ")
age = input("Enter your age: ")
print(name) #prints user entered name
print(age) #prints user entered age
print("") #prints a new empty line
print("Hello World!")
|
286cb30b15f984cb922dc229773e6e2eda569ddd
|
Shreyasi2002/CODE_IN_PLACE_experience
|
/Section2-Welcome to python/8ball.py
| 954 | 4.1875 | 4 |
"""
Simulates a magic eight ball.
Prompts the user to type a yes or no question and gives
a random answer from a set of prefabricated responses.
"""
import random
RESPONSES = ["As I see it, yes.", "Ask again later.", "Better not to tell you now."
, "Cannot predict now.", "Concentrate and ask again.", "Don't count on it."
, "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no."
, "My sources say no.", "Outlook not so good.", "Outlook good.", "Reply hazy, try again."
, "Signs point to yes.", "Very doubtful.", "Without a doubt.", "Yes."
, "Yes - definitely.", "You may rely on it."]
TOTAL_RESPONSES = 19
def main():
question = input("Ask a yes or no question: ")
num = 0 # to represent the index of the RESPONSES list
while question != "":
num = random.randint(0, TOTAL_RESPONSES)
print(RESPONSES [num])
question = input("Ask a yes or no question: ")
if __name__ == "__main__":
main()
|
91cc4ff7b8e7e275ba61d799d81c8eecb7587b7c
|
Shreyasi2002/CODE_IN_PLACE_experience
|
/CoreComplete/leap.py
| 930 | 4.4375 | 4 |
"""
Example of using the index variable of a for loop
"""
def main():
pass
def is_divisible(a, b):
"""
>>> is_divisible(20, 4)
True
>>> is_divisible(12, 7)
False
>>> is_divisible(10, 10)
True
"""
return a % b == 0
def is_leap_year(year):
"""
Returns Boolean indicating if given year is a leap year.
It is a leap year if the year is:
* divisible by 4, but not divisible by 100
OR
* divisible by 400
Doctests:
>>> is_leap_year(2001)
False
>>> is_leap_year(2020)
True
>>> is_leap_year(2000)
True
>>> is_leap_year(1900)
False
"""
# if the year is divisible by 400, it is a leap year!
if is_divisible(year, 400):
return True
# other wise its a leap year if its divisible by 4 and not 100
return is_divisible(year, 4) and not is_divisible(year, 100)
if __name__ == '__main__':
main()
|
99e5183af9ac4d1eb9f7d3579de5884ab707cc5a
|
Shreyasi2002/CODE_IN_PLACE_experience
|
/Assignment1/Midpoint.py
| 1,061 | 3.578125 | 4 |
from karel.stanfordkarel import *
"""
File: Midpoint.py
------------------------
Place a beeper on the middle of the first row.
"""
def main():
"""
Your code here
"""
paint_corner(CYAN)
move_to_wall()
paint_corner(CYAN)
turn_around()
move_if()
while corner_color_is(BLANK):
steps_to_midpoint()
turn_around()
move_if()
put_beeper()
move_to_wall()
turn_around()
clear_color()
move_to_beeper()
def steps_to_midpoint():
while corner_color_is(BLANK):
move_if()
turn_around()
move_if()
paint_corner(CYAN)
move_if()
def turn_around():
turn_left()
turn_left()
def move_if():
if front_is_clear():
move()
def move_to_wall():
while front_is_clear():
move()
def clear_color():
while front_is_clear():
paint_corner(BLANK)
move()
paint_corner(BLANK)
def move_to_beeper():
turn_around()
while no_beepers_present():
move()
if __name__ == '__main__':
run_karel_program('Midpoint8.w')
|
ff64e3d1c5a24b8bb632ea566b77f57f105895fd
|
Shreyasi2002/CODE_IN_PLACE_experience
|
/Files/dictwriter_example.py
| 336 | 3.53125 | 4 |
import csv
def write_data():
with open("data.csv", "w") as f:
columns = ['x', 'y']
writer = csv.DictWriter(f, fieldnames=columns)
writer.writeheader()
writer.writerow({'x': 1, 'y': 2})
writer.writerow({'x': 2, 'y': 4})
writer.writerow({'x': 4, 'y': 6})
def main():
write_data()
if __name__ == "__main__":
main()
|
96ca5bd25da8c95b57dd8e40220403795d4113fc
|
eduardoleyvah/calculadora2017
|
/TestCalculadora.py
| 6,764 | 3.5625 | 4 |
import unittest
from calculadora import Calculadora
class CalculadoraTest(unittest.TestCase):
def setUp(self):
self.operaciones = Calculadora()
def test_sumar_2_mas_2_igual_4(self):
self.operaciones.suma(2, 2)
self.assertEquals(self.operaciones.obtener_resultado(),4)
def test_sumar_1_mas_12_igual_13(self):
self.operaciones.suma(1, 12)
self.assertEquals(self.operaciones.obtener_resultado(),13)
def test_sumar_3_mas_3_igual_6(self):
self.operaciones.suma(3, 3)
self.assertEquals(self.operaciones.obtener_resultado(),6)
def test_sumar_menos1_mas_2_igual_1(self):
self.operaciones.suma(-1, 2)
self.assertEquals(self.operaciones.obtener_resultado(),1)
def test_sumas_l_mas_2_igual_dato_invalido(self):
self.operaciones.suma('L', 2)
self.assertEquals(self.operaciones.obtener_resultado(),'datos incorrectos')
def test_valor_de_inicio_es_igual_a_cero(self):
self.operaciones.suma(0,2)
self.assertEquals(self.operaciones.obtener_resultado(), 'No se aceptan ceros')
def test_no_se_aceptan_numeros_mayores_a_diezmil(self):
self.operaciones.suma(5,10001)
self.assertEquals(self.operaciones.obtener_resultado(),'No se aceptan numeros mayores a 10000')
def test_restar_5_menos_4_igual_1(self):
self.operaciones.resta(5,4)
self.assertEquals(self.operaciones.obtener_resultado(),1)
def test_restar_3_menos_3_igual_0(self):
self.operaciones.resta(3,3)
self.assertEquals(self.operaciones.obtener_resultado(),0)
def test_restar_segundo_numero_mayor(self):
self.operaciones.resta(2,5)
self.assertEquals(self.operaciones.obtener_resultado(),'El segundo numero no debe ser mayor al primero')
def test_restar_8_menos_N_datos_invalidos(self):
self.operaciones.resta(8,'N')
self.assertEquals(self.operaciones.obtener_resultado(),'datos incorrectos')
def test_multiplicar_3_por_2_igual_6(self):
self.operaciones.multiplicacion(3,2)
self.assertEquals(self.operaciones.obtener_resultado(),6)
def test_multiplicar_menos2_por_2_igual_menos4(self):
self.operaciones.multiplicacion(-2,2)
self.assertEquals(self.operaciones.obtener_resultado(),-4)
def test_multiplicar_menos2_por_menos2_igual_4(self):
self.operaciones.multiplicacion(-2,-2)
self.assertEquals(self.operaciones.obtener_resultado(),4)
def test_multiplicar_0_por_5_no_se_acepta(self):
self.operaciones.multiplicacion(0,5)
self.assertEquals(self.operaciones.obtener_resultado(),'No se aceptan ceros')
def test_multiplicar_R_por_7_datos_incorrectos(self):
self.operaciones.multiplicacion('R',7)
self.assertEquals(self.operaciones.obtener_resultado(),'datos incorrectos')
def test_division_4_entre_2_igual_2(self):
self.operaciones.division(4,2)
self.assertEquals(self.operaciones.obtener_resultado(),2)
def test_division_1_entre_10_igual_0(self):
self.operaciones.division(1,10)
self.assertEquals(self.operaciones.obtener_resultado(),0)
def test_divison_H_entre_1_datos_incorrecots(self):
self.operaciones.division('H',1)
self.assertEquals(self.operaciones.obtener_resultado(),'datos incorrectos')
def test_division_1_entre_0_indeterminacion(self):
self.operaciones.division(1,0)
self.assertEquals(self.operaciones.obtener_resultado(),'Indeterminacion')
def test_division_1_entre_menos1_igual_menos1(self):
self.operaciones.division(1,-1)
self.assertEquals(self.operaciones.obtener_resultado(),-1)
def test_raiz_de_5_igual_2punto2(self):
self.operaciones.raiz(5,0)
self.assertEquals(self.operaciones.obtener_resultado(),2.2)
def test_raiz_de_0_igual_0punto0(self):
self.operaciones.raiz(0,0)
self.assertEquals(self.operaciones.obtener_resultado(),0.0)
def test_raiz_de_menos1_no_se_pueden_negativos(self):
self.operaciones.raiz(-1,0)
self.assertEquals(self.operaciones.obtener_resultado(),'No se puede sacar raiz de un numero negativo')
def test_raiz_de_L_datos_incorrectos(self):
self.operaciones.raiz('L',0)
self.assertEquals(self.operaciones.obtener_resultado(),'datos incorrectos')
def test_potencia_de_5_al_cuadrado_igual_25(self):
self.operaciones.potencia(5,2)
self.assertEquals(self.operaciones.obtener_resultado(),25)
def test_potencia_de_3_a_la_j_datos_incorrectos(self):
self.operaciones.potencia(3,'j')
self.assertEquals(self.operaciones.obtener_resultado(),'datos incorrectos')
def test_potencia_de_2_a_la_menos2_no_se_pueden_negativos(self):
self.operaciones.potencia(2,-2)
self.assertEquals(self.operaciones.obtener_resultado(),'No se aceptan negativos')
def test_potencia_de_3_a_la_11_no_se_pueden_mayores_a_10(self):
self.operaciones.potencia(3,11)
self.assertEquals(self.operaciones.obtener_resultado(),'No se aceptan exponentes mayores a 10')
def test_edad_menor_a_0_no_existes(self):
self.operaciones.edad(-1)
self.assertEquals(self.operaciones.obtener_resultado(),'No existes')
def test_edad_menor_a_13_eres_ninio(self):
self.operaciones.edad(10)
self.assertEquals(self.operaciones.obtener_resultado(),'Eres ninio')
def test_edad_menor_a_18_eres_adolescente(self):
self.operaciones.edad(15)
self.assertEquals(self.operaciones.obtener_resultado(),'Eres adolescente')
def test_edad_menor_a_65_eres_adulto(self):
self.operaciones.edad(33)
self.assertEquals(self.operaciones.obtener_resultado(),'Eres adulto')
def test_edad_menor_a_120_eres_adulto_mayor(self):
self.operaciones.edad(105)
self.assertEquals(self.operaciones.obtener_resultado(),'Eres adulto mayor')
def test_edad_mayor_a_120_eres_mummra(self):
self.operaciones.edad(200)
self.assertEquals(self.operaciones.obtener_resultado(),'Eres Mumm-Ra')
if __name__ == '__main__':
unittest.main()
"""
>>> suma(2,2)
4
>>> suma(3,3)
6
>>> suma(-1,2)
1
>>> suma('L',2)
'datos incorrectos'
>>> suma(0,2)
'No se aceptan ceros'
>>> suma(5,10001)
'No se aceptan numeros mayores a 10000'
>>> resta(5,4)
1
>>> resta(3,3)
0
>>> resta(2,5)
'El segundo numero no debe ser mayor al primero'
>>> resta(8,'N')
'datos incorrectos'
>>> multiplicacion(3,2)
6
>>> multiplicacion(-2,2)
-4
>>> multiplicacion(-2,-2)
4
>>> multiplicacion(0,5)
'No se aceptan ceros'
>>> multiplicacion('R',7)
'datos incorrectos'
>>> division(4,2)
2
>>> division(1,10)
0
>>> division('H',1)
'datos incorrectos'
>>> division(1,0)
'Indeterminacion'
>>> division(1,-1)
-1
>>> raiz(5,0)
2.2
>>> raiz(0,0)
0.0
>>> raiz(-1,0)
'No se puede sacar raiz de un numero negativo'
>>> raiz('L',0)
'datos incorrectos'
>>> potencia(5,2)
25
>>> potencia(3,'j')
'datos incorrectos'
>>> potencia(2,-2)
'No se aceptan negativos'
>>> potencia(3,11)
'No se aceptan exponentes mayores a 10'
>>> edad(-1)
'No existes'
>>> edad(10)
'Eres ninio'
>>> edad(15)
'Eres adolescente'
>>> edad(33)
'Eres adulto'
>>> edad(105)
'Eres adulto mayor'
>>> edad(200)
'Eres Mumm-Ra'
"""
|
163378723f74ed14830c7d8962b2ad8dab2fdd2c
|
elaeon/dama_ml
|
/src/dama/utils/seq.py
| 343 | 3.734375 | 4 |
from itertools import islice, chain
def grouper_chunk(n, iterable):
"grouper_chunk(3, '[1,2,3,4,5,6,7]') --> [1,2,3] [4,5,6] [7]"
it = iter(iterable)
while True:
chunk = islice(it, n)
try:
first_el = next(chunk)
except StopIteration:
return
yield chain((first_el,), chunk)
|
d3c9754c8666e8bf95f191e7e4bba9249a10df59
|
Maryam200600/Task2.2
|
/4.py
| 299 | 4.21875 | 4 |
# Заполнить список ста нулями, кроме первого и последнего элементов, которые должны быть равны единице
for i in range(0,101):
if i==0 or i==100:
i='1'
else:
i='0'
print(i, end=' ')
|
b36d16ad2ad7b809319c1fd8104215429cf55365
|
AnthonyChupin/homework2
|
/HW5/05_5.py
| 542 | 3.8125 | 4 |
"""Создать (программно) текстовый файл, записать в него программно набор чисел,
разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран"""
f_obj = open('05_5.txt', 'w+', encoding='utf-8')
my_str = '10 1 20 49 4'
f_obj.write(''.join(my_str))
f_obj.seek(0)
my_list = f_obj.readline().split(' ')
my_sum = 0
for el in my_list:
my_sum += int(el)
print(my_sum)
|
6409f7f1edd4ddf0c97f02bfa6ef05eee998fdb5
|
AnthonyChupin/homework2
|
/HW6/06_4.py
| 3,089 | 4.125 | 4 |
"""
Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты:
speed, color, name, is_police (булево). А также методы: go, stop, turn(direction),
которые должны сообщать, что машина поехала, остановилась, повернула (куда).
Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar.
Добавьте в базовый класс метод show_speed, который должен показывать текущую скорость
автомобиля. Для классов TownCar и WorkCar переопределите метод show_speed.
При значении скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться сообщение
о превышении скорости
"""
class Car:
def __init__(self, speed, color, name, is_police):
self.name = name
self.speed = speed
self.color = color
self.is_police = is_police
def go(self):
print('Машина поехала')
def stop(self):
print('Машина остановилась')
def turn(self, direction=None):
print('Машина повернула на ', direction)
def show_speed(self):
print('Скорость машины: ', self.speed)
def get_status(self):
if self.is_police:
print('Это полицейская машина')
class TownCar(Car):
def show_speed(self):
if self.speed > 60:
print('Превышена скорость! ','Скорость машины: ', self.speed)
else:
print('Скорость машины: ', self.speed)
class SportCar(Car):
def get_status(self):
print('Это спортивная машина')
class WorkCar(Car):
def show_speed(self):
if self.speed > 40:
print('Превышена скорость! ', 'Скорость машины: ', self.speed)
else:
print('Скорость машины: ', self.speed)
class PoliceCar(Car):
def sirena(self):
print('Сирена включена')
town_car = TownCar(65, 'red', 'kia', False)
sport_car = SportCar(120, 'blak', 'ferrari', False)
police_car = PoliceCar(70, 'green', 'ford', True)
work_car = WorkCar(41, 'yellow', 'kamaz', False)
print(town_car.name, ' ', town_car.color,)
town_car.show_speed()
town_car.get_status()
town_car.stop()
print('----------------------------')
print(sport_car.name, ' ', sport_car.color,)
sport_car.show_speed()
sport_car.get_status()
sport_car.go()
print('----------------------------')
print(police_car.name, ' ', police_car.color,)
police_car.show_speed()
police_car.get_status()
police_car.turn('право')
print('----------------------------')
print(work_car.name, ' ', work_car.color,)
work_car.show_speed()
work_car.get_status()
work_car.turn('лево')
print('----------------------------')
|
c57ba040e3a4ecf48cb8042a90838bf53e036967
|
AnthonyChupin/homework2
|
/HW5/05_4.py
| 950 | 3.546875 | 4 |
"""Создать (не программно) текстовый файл со следующим содержимым:
One — 1
Two — 2
Three — 3
Four — 4
Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные.
При этом английские числительные должны
заменяться на русские. Новый блок строк должен записываться в новый текстовый файл."""
f_obj = open('05_4.txt', encoding='utf-8')
n_obj = open('05_41.txt', 'w', encoding='utf-8')
my_dict = {'One': 'Один',
'Two': 'Два',
'Three': 'Три',
'Four': 'Четыре'}
txt = ''
for line in f_obj:
txt = my_dict.get(line.split(' ')[0]) + line.split(' ')[1] + line.split(' ')[2]
n_obj.write(''.join(txt))
f_obj.close()
n_obj.close()
|
dfbc9f808feea559a989c356afd6f44b9fd016bd
|
eignatenkov/adventofcode2018
|
/day_01.py
| 584 | 3.5625 | 4 |
def sum_up(filename):
total = 0
with open(filename) as f:
for line in f:
total += int(line)
return total
def first_twice(filename):
seen_freqs = {0}
cur_freq = 0
while True:
with open(filename) as f:
for line in f:
cur_freq += int(line)
if cur_freq in seen_freqs:
return cur_freq
else:
seen_freqs.add(cur_freq)
if __name__ == "__main__":
print(sum_up('data/day01_input.txt'))
print(first_twice('data/day01_input.txt'))
|
3431b3a8e248affafafabd9b346f9ca145564a96
|
dnlglsn/hacker_rank
|
/coin_change_problem.py
| 1,920 | 3.640625 | 4 |
# https://www.hackerrank.com/challenges/coin-change
def mocked_raw_input(fpOrString):
def set_raw_input_string(fpOrString):
if type(fpOrString) is str:
for line in fpOrString.split('\n'):
yield line
else:
for line in open(fpOrString):
yield line
yield_func = set_raw_input_string(fpOrString)
def next_func():
return next(yield_func)
return next_func
def get_min_coins(coins, value, z=0):
# print '\t' * z, 'value', value
retVal = []
if value in coins:
result = {value: 1}
# print '\t' * z, 'value in coins', result
if result not in retVal:
retVal.append(result)
for coin in coins:
if value % coin == 0:
result = {coin: value // coin}
# print '\t' * z, 'found list', result
if result not in retVal:
retVal.append(result)
for coin in coins:
if value - coin >= min(coins):
# print '\t' * z, 'recursing coin %s for value %s' % (coin, value -
# coin)
results = get_min_coins(coins, value - coin, z + 1)
if results:
for result in results:
result[coin] = result.get(coin, 0) + 1
if result not in retVal:
retVal.append(result)
return retVal
# Mock out raw_input
s = '''4 3
1 2 3'''
raw_input = mocked_raw_input(s)
# Read the inputs
value, _ = map(int, raw_input().split())
coins = set(map(int, raw_input().split()))
print value, coins
results = get_min_coins(coins, value)
print len(results), results
# Mock out raw_input
s = '''10 4
2 5 3 6'''
raw_input = mocked_raw_input(s)
# Read the inputs
value, _ = map(int, raw_input().split())
coins = set(map(int, raw_input().split()))
print value, coins
results = get_min_coins(coins, value)
print len(results), results
|
edf4a58d87d2c5cef9a6e06e2ace05ad5096268d
|
djoo1028/Euler
|
/euler01.py
| 1,636 | 4.3125 | 4 |
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
def findSum(arg1):
a = arg1 # input value will be range for the summation
arr3 = [] # multiple of 3
for i in range(1,x+1): # Remove 0 and include the last spot
if 3 * i > x: # If the value is greater than range than break for loop
break
else:
arr3.append(3 * i) # add in to the list
print(list(arr3))
arr5 = [] # multiple of 5
for i in range(1,x+1):
if 5 * i >= x:
break
else:
arr5.append(5 * i)
print(list(arr5))
arr = arr3 + arr5 # Add two list which have multiple of 3 and 5
noDup = []
for i in arr: # Remove duplicate numbers
if i not in noDup: # If a number does not exist add and if number is exist move to next index
noDup.append(i)
print(list(noDup)) # checke
SSum = sum(noDup) # Sum all numbers in list
print(SSum)
#Second idea(shorter version)
def findSumShort(arg1):
a = arg1
sum = 0
for i in range(a):
if (i % 3 == 0) or (i % 5 == 0): # I do not have to think about duplicates because this statement check element at the same time.
# For example, if i = 15 then T or T is True so 15 will be added sum.
sum += i
print(sum)
x = int(input())
findSum(x)
findSumShort(x)
|
558abfaa8a01ab53b54a2b2caed49b9364000a71
|
sls19050/proj_wrangle_osm
|
/find_best_place_to_live/query.py
| 4,426 | 4.15625 | 4 |
"""
Uses the CustomSeattle.db and
finds the best apartment to live in Capitol Hill, Seattle by minimizing cost of living,
where cost of living is defined by the sum of the following two metrics;
-Daily cost of walking to work
-Daily cost of losing sleep
"""
import sqlite3
from math import sin, cos, sqrt, atan2, radians
# function to print data output to a text file
def print_results(data, limiter_on=True):
limiter = 10
with open('result_viewer.txt','w') as fp:
if limiter_on:
for d in data:
if limiter < 0:
return 0
fp.write(",".join(str(item) for item in d))
fp.write('\n')
limiter -= 1
else:
for d in data:
fp.write(",".join(str(item) for item in d))
fp.write('\n')
# function to execute SQLite queries to solve the problem
def query1():
#To calculate distance given a pair of lat and lon
#To be used as DIST() in thee following SQL queries
#Function obtained from : https://stackoverflow.com/questions/19412462/getting-distance-between-two-points-based-on-latitude-longitude
def dist(lat1, lon1, lat2, lon2):
R = 3959 #Earth radius in miles
dlon = radians(lon2 - lon1)
dlat = radians(lat2 - lat1)
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
return distance
#To calculate the score of the apartment based on:
# 1, distance to work, 2 distance to the nearest bar
#To be used as SCORING() in the following SQL queries
def scoring(b_dist, w_dist):
# assume that bars generate about 90 decibels within 30 ft (or 0.00568182 miles) of the area,
# and that the intensity of the noise is inversely proportional to the squared distance from the source,
# as suggested in http://hyperphysics.phy-astr.gsu.edu/hbase/Acoustic/invsqs.html#c1
noise = 90 * (0.00568182/b_dist)**2
if noise <= 60: # typical decibel value for normal conversations = 60, from: http://www.noisemonitoringservices.com/decibels-explained/
b_score = 0 # I fall asleep during such noise environment easily, hence no impact to my sleep
else:
b_score = 5 * (noise - 60) + 50 # I arbitarily defined this cost equation
w_score = 2 * w_dist * 1/3 * 35 # cost of walking to work (back and forth), assume my time is worth $35/hr & It takes me 1hr to walk 3miles
return b_score + w_score
con = sqlite3.connect("../sqlite_dbs/CustomSeattle.db")
con.create_function("dist", 4, dist)
con.create_function("scoring", 2, scoring)
cur = con.cursor()
# query for obtaining lat and lon for all bars in the area
sql_cmd = """
CREATE TEMP VIEW bar_pos AS
SELECT n.id, nt2.value AS name, n.lat, n.lon
FROM nodes_tags AS nt1
JOIN nodes_tags AS nt2
ON nt1.id = nt2.id
JOIN nodes AS n
ON n.id = nt1.id
WHERE nt1.key = 'amenity'
AND nt1.value = 'bar'
AND nt2.key = 'name';
"""
cur.execute(sql_cmd)
# query for obtaining lat and lon for all apartments in the area
sql_cmd = """
CREATE TEMP VIEW apt_pos AS
SELECT n.id, n.lat, n.lon, nt2.value AS name
FROM nodes_tags AS nt
JOIN nodes_tags AS nt2
ON nt.id = nt2.id
JOIN nodes AS n
ON n.id = nt.id
WHERE
(nt.key = 'building' OR nt.value = 'residential')
AND nt.value LIKE 'apartment%'
AND nt2.key = 'name'
UNION
SELECT wt.id, AVG(n.lat) AS lat,
AVG(n.lon) AS lon, wt2.value AS name
FROM ways_tags AS wt
JOIN ways_tags AS wt2
ON wt.id = wt2.id
JOIN ways_nodes AS wn
ON wt.id = wn.id
JOIN nodes AS n
ON n.id = wn.node_id
WHERE
(wt.key = 'building' OR wt.value = 'residential')
AND wt.value LIKE 'apartment%'
AND wt2.key = 'name'
GROUP BY wt.id;
"""
cur.execute(sql_cmd)
# to obtain distance to the nearest bar and distance to work for each apartment
# workplace lat and lon = 47.6148943 & -122.321752517
sql_cmd = """
CREATE TEMP VIEW A_B_dists AS
SELECT A.id, A.lat, A.lon, A.name AS A_name, B.name AS B_name,
MIN(dist(A.lat, A.lon, B.lat, B.lon)) AS b_dist,
dist(A.lat, A.lon, 47.6148943, -122.321752517) AS w_dist
FROM apt_pos AS A
JOIN bar_pos AS B
GROUP BY A.id;
"""
cur.execute(sql_cmd)
# to rank all apartments by their score,
# where score is the daily cost, and therefore the lower the better
sql_cmd = """
SELECT A_name,
scoring(b_dist, w_dist) AS score
FROM A_B_dists
ORDER BY score
"""
data = cur.execute(sql_cmd)
print_results(data, False)
con.close()
if __name__ == "__main__":
query1()
|
d3ad13106495f12e8dabe861f3af24a37063584b
|
abhijeet811/Programming_for_Data_Science_using_Python
|
/Project -2/Abhijeet Dutta Python Project/bikeshare.py
| 9,966 | 3.921875 | 4 |
import time
import pandas as pd
import numpy as np
import json
CITY_DATA = {'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv'}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
1. (str) city - name of the city to analyze
2. (str) month - name of the month to filter by, or "all"
to apply no month filter
3. (str) day - name of the day of week to filter by, or "all"
to apply no day filter
"""
print(' Hello! Let\'s explore some US bikeshare data! ')
# get user input for city (chicago, new york city, washington).
# HINT: Use a while loop to handle invalid inputs
city = None
city_filter = ['chicago', 'new york', 'washington']
while city not in city_filter:
city = input("\nFilter data by city\n[ Chicago, "
"New York or Washington ] : ").lower()
# get user input for month (all, january, february, ... , june)
month = None
month_filter = ['all', 'january', 'february', 'march',
'april', 'may', 'june']
while month not in month_filter:
month = input("\nFilter data by month\n[ all, january, february,"
"march, april, may, or june ] : ").lower()
# get user input for day of week (all, monday, tuesday, ... sunday)
day = None
day_filter = ['all', 'sunday', 'monday', 'tuesday',
'wednesday', 'thursday', 'friday', 'saturday']
while day not in day_filter:
day = input("\nFilter data by day of the week\n['all', "
"'sunday', 'monday', ...., 'saturday'] : ").lower()
print('-'*78, '\n')
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day
if applicable.
Args:
1. (str) city - name of the city to analyze
2. (str) month - name of the month to filter by, or "all"
to apply no month filter
3. (str) day - name of the day of week to filter by, or "all"
to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
print()
print(" Filters applied : "
"[ {}, {}, {}] ".format(city, month, day).center(78, '*'))
print()
# load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month and day of week from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.day_name()
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
if 'Start Time' in df.columns:
print()
print(' Calculating The Most Frequent Times '
'of Travel '.center(78, '='))
start_time = time.time()
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# display the most common month
# -------------------START--------------------------
# extract month from the Start Time column to create an month column
df['month'] = df['Start Time'].dt.month
# find the most most common month
popular_month = df['month'].mode()[0]
print('Most common Month'.ljust(3, '.'), popular_month)
# --------------------END---------------------------
# display the most common day of week
# -------------------START--------------------------
# extract day from Start Time column to create an day_of_week column
df['day_of_week'] = df['Start Time'].dt.day_name()
# find the most common day of week
popular_day = df['day_of_week'].mode()[0]
print('Most common day of the week'.ljust(3, '.'), popular_day)
# --------------------END---------------------------
# find the most common start hour
# -------------------START--------------------------
# extract hour from the Start Time column to create an hour column
df['hour'] = df['Start Time'].dt.hour
# display the most common start hour
popular_hour = df['hour'].mode()[0]
print('Most common Start Hour'.ljust(3, '.'), popular_hour)
# --------------------END---------------------------
print("\nThis took {} seconds.".format((time.time() - start_time)))
print('-'*78, '\n')
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print()
print(' Calculating The Most Popular Stations and Trip '.center(78, '='))
start_time = time.time()
print(' Station Stats '.center(78, '-'))
# display most commonly used start station
if 'Start Station' in df.columns:
# -------------------START--------------------------
print('Most commonly used Start '
'station '.ljust(3, '.'), df['Start Station'].mode()[0])
# --------------------END---------------------------
# display most commonly used end station
if 'End Station' in df.columns:
# -------------------START--------------------------
print('Most commonly used End '
'station '.ljust(3, '.'), df['End Station'].mode()[0])
# --------------------END---------------------------
# display most frequent combination of start station and end station trip
if 'Start Station' in df.columns and 'End Station' in df.columns:
# -------------------START--------------------------
df['route'] = df['Start Station'] + ' -> ' + df['End Station']
print('Most frequent route '.ljust(3, '.'), df['route'].mode()[0])
# --------------------END---------------------------
print("\nThis took {} seconds.".format((time.time() - start_time)))
print('-'*78, '\n')
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print()
if 'Trip Duration' in df.columns:
print(' Calculating Trip Duration '.center(78, '='))
start_time = time.time()
# Trip Duration stats:
# -------------------START--------------------------
print(' Trip Duration stats '.center(78, '-'))
print('Max Travel Time '.ljust(3, '.'), df['Trip Duration'].max())
print('Min Travel Time '.ljust(3, '.'), df['Trip Duration'].min())
# display mean travel time
print('Avg Travel Time '.ljust(3, '.'), df['Trip Duration'].mean())
print('Most Travel '
'Time '.ljust(3, '.'), df['Trip Duration'].mode()[0])
# display total travel time
print('Total Travel Time '.ljust(3, '.'), df['Trip Duration'].sum())
# --------------------END---------------------------
print("\nThis took {} seconds.".format(time.time() - start_time))
print('-'*78, '\n')
def user_stats(df):
"""Displays statistics on bikeshare users."""
print()
print(' Calculating User Stats '.center(78, '='))
start_time = time.time()
# Display user stats
# -------------------START--------------------------
# Display counts of user types
if 'User Type' in df.columns:
print(' User type stats '.center(78, '-'))
print(df['User Type'].value_counts())
# print()
# Display counts of gender
if 'Gender' in df.columns:
print(' Gender stats '.center(78, '-'))
df['Gender'].replace(np.nan, 'not disclosed', inplace=True)
print(df['Gender'].value_counts(dropna=False))
# print()
# Display earliest, most recent, and most common year of birth
if 'Birth Year' in df.columns:
print(' Age stats '.center(78, '-'))
print('Earliest Birth '
'Year '.ljust(3, '.'), int(df['Birth Year'].min()))
print('Most recent Birth '
'Year '.ljust(3, '.'), int(df['Birth Year'].max()))
print('Most common Birth '
'Year '.ljust(3, '.'), int(df['Birth Year'].mode()[0]))
# --------------------END---------------------------
print("\nThis took {} seconds.".format((time.time() - start_time)))
print('-'*78, '\n')
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
# Display raw_data
row = 5
raw_data = input('Would you like to see raw data? '
'Enter (yes / no) : ').lower()
df['Start Time'] = df['Start Time'].dt.strftime('%Y-%m-%d %H:%M:%S')
# print(df.info()) for testing
while raw_data == 'yes':
# print(df.head(5).to_dict('index')) show first 5 row as dictionary
print(json.dumps(df.head(row).to_dict('index'), indent=1))
raw_data = input('Would you like to see more '
'raw data? Enter (yes / no) : ').lower()
row += 5
restart = input('\nWould you like to restart? '
'Enter (yes / no) : ').lower()
if restart.lower() != 'yes':
print()
print(' Python Script Terminated '.center(78, '*'))
print()
break
if __name__ == "__main__":
main()
|
0a186e9f92527a8509f7082f2f4065d3b366e957
|
vinnyatanasov/naive-bayes-classifier
|
/nb.py
| 3,403 | 3.6875 | 4 |
"""
Naive Bayes classifier
- gets reviews as input
- counts how many times words appear in pos/neg
- adds one to each (to not have 0 probabilities)
- computes likelihood and multiply by prior (of review being pos/neg) to get the posterior probability
- in a balanced dataset, prior is the same for both, so we ignore it here
- chooses highest probability to be prediction
"""
import math
def test(words, probs, priors, file_name):
label = 1 if "pos" in file_name else -1
count = 0
correct = 0
with open(file_name) as file:
for line in file:
# begin with prior (simply how likely it is to be pos/neg before evidence)
pos = priors[0]
neg = priors[1]
# compute likelihood
# sum logs, better than multiplying very small numbers
for w in line.strip().split():
# if word wasn't in train data, then we have to ignore it
# same effect if we add test words into corpus and gave small probability
if w in words:
pos += math.log(probs[w][0])
neg += math.log(probs[w][1])
# say it's positive if pos >= neg
pred = 1 if pos >= neg else -1
# increment counters
count += 1
if pred == label:
correct += 1
# return results
return 100*(correct/float(count))
def main():
# count number of occurances of each word in pos/neg reviews
# we'll use a dict containing a two item list [pos count, neg count]
words = {}
w_count = 0 # words
p_count = 0 # positive instances
n_count = 0 # negative instances
# count positive occurrences
with open("data/train.positive") as file:
for line in file:
for word in line.strip().split():
try:
words[word][0] += 1
except:
words[word] = [1, 0]
w_count += 1
p_count += 1
# count negative occurrences
with open("data/train.negative") as file:
for line in file:
for word in line.strip().split():
try:
words[word][1] += 1
except:
words[word] = [0, 1]
w_count += 1
n_count += 1
# calculate probabilities of each word
corpus = len(words)
probs = {}
for key, value in words.iteritems():
# smooth values (add one to each)
value[0]+=1
value[1]+=1
# prob = count / total count + number of words (for smoothing)
p_pos = value[0] / float(w_count + corpus)
p_neg = value[1] / float(w_count + corpus)
probs[key] = [p_pos, p_neg]
# compute priors based on frequency of reviews
priors = []
priors.append(math.log(p_count / float(p_count + n_count)))
priors.append(math.log(n_count / float(p_count + n_count)))
# test naive bayes
pos_result = test(words, probs, priors, "data/test.positive")
neg_result = test(words, probs, priors, "data/test.negative")
print "Accuracy(%)"
print "Positive:", pos_result
print "Negative:", neg_result
print "Combined:", (pos_result+neg_result)/float(2)
if __name__ == "__main__":
print "-- Naive Bayes classifier --\n"
main()
|
39e15681eadf3a931be47d00d69dc194e6ded96b
|
Heraklesss/RepositorioPython_005
|
/ciclofor.py
| 501 | 4.03125 | 4 |
#crear un ciclo for que permita ingresar para n numeros, donde n es un numero ingresado x teclado.
#calcular y mostrar: cantidad de numero pares y cantidad de numeros impares.
veces = int (input("Cuantos numeros ingresa?: "))
par=0
impar=0
for x in range(veces):
nume = int (input("ingrese un numero : "))
if (nume%2==0):
par=par+1
elif(nume%2!=0):
impar=impar+1
print("La cantidad de numero pares es: " + str(par))
print("La cantidad de numero impares es: " + str(impar))
|
e6902a6ee31baa299a2e41068bdb4c9da4763e66
|
vivian2yu/leet-code
|
/leet-code-idea/TowSum.py
| 531 | 3.59375 | 4 |
__author__ = 'vivian'
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = {};
if len(nums) < 2:
return False
for i in range(len(nums)):
if nums[i] in left:
return [left[nums[i]], i]
else:
left[target - nums[i]] = i
if __name__ == '__main__' :
nums = [3,2,4]
target = 6
Solution().twoSum(nums, target);
|
1a816e03c814853db8ee05bb5d64b3318222a81a
|
osmangani37/Python_Tutorial
|
/IBM_NLP/Test.py
| 703 | 3.6875 | 4 |
import re
findout=re.compile("i*")
print(findout.findall("Osman is a good boy"))
print(re.split("[a-e]", "Hi this is Osman"))
print(re.sub("shi", "dim", "I am Shirin. yes it is Shirin",flags=re.IGNORECASE))
regex=r"([a-zA-Z]+) (\d+)"
match=re.search(regex, "I was born on June24")
try:
print(match.start(),match.end())
except:
print("Not Present")
def checkPresent(date):
if (not date):
print("Empty")
else:
regex=r"([a-zA-Z]+) (\d+)"
match=re.search(regex,date)
try:
print(match.start(),match.end())
except:
print("Not Present")
checkPresent("")
checkPresent("I was born on June 24")
|
37a422387d9c238dd9c5d48d01597e3c28c18404
|
izabela9525/BIM-BOOM
|
/Functions2.py
| 158 | 3.53125 | 4 |
def welcome():
print("Hello... Welcome to Python...")
welcome()
def sum(a, b):
c = a + b
print("Sum of 2 Numbers: - " + str(c))
sum(25, 25)
|
f82be2fec1efde894d62dabbbe9b7c1d3fbd514b
|
izabela9525/BIM-BOOM
|
/Loops in python.py
| 136 | 4.03125 | 4 |
# For Loop with Final Range
# take input from the user
number = input("Pls enter number - ")
for i in range(int(number)):
print(i)
|
c1265ee93618e43cbec0d174c381ba280be4de31
|
izabela9525/BIM-BOOM
|
/increment_loop.py
| 333 | 3.90625 | 4 |
# For Loop with Starting and Final Range
# Increment - 3 pozycja wyświetla co drugą liczbe
#for i in range(1,10,2):
# print(i)
# Aby wyświetlać numeracje wstecz 3 liczba musi być na minusie.
#for i in range(10,0,-1):
# print(i)
number = input("PLS enter number - ")
for i in range(10,0,-1):
print(int(number) *1)
|
068fb7a95c0d33b8e9fbc9e90ec77d9590e307a1
|
izabela9525/BIM-BOOM
|
/and.py
| 152 | 4.03125 | 4 |
num = input("Please enter your number - ")
num = int(num)
if(num != 100):
print("This is Valid number ")
else:
print("This is INvalid number ")
|
d1cb1b922a83a6e94b9d61c13f37887804178988
|
TonyJenkins/cfs2160-2018-python-public
|
/02/circle.py
| 165 | 4.4375 | 4 |
"""
Find the area of a circle.
"""
from math import pi
radius = float (input ('Enter the radius of the circle: '))
print ('The area is', pi * radius * radius)
|
2e1027f23d83f26820df819c55dc50c725414f37
|
TonyJenkins/cfs2160-2018-python-public
|
/04/sweet_divider.py
| 283 | 3.890625 | 4 |
sweets = int (input ('How many sweets are there? '))
bag_size = int (input ('How many sweets fit in each bag? '))
full_bags = sweets // bag_size
left_over = sweets % bag_size
print ('You will get', full_bags, 'full bags.')
print ('There will be', left_over, 'sweets spare.')
|
f0b39ddce7802ef09e39599f494c3461fc18007f
|
rati90/mjeraarmjera
|
/service/trustorNot.py
| 2,590 | 4.15625 | 4 |
def hands_table_clear(table, said_cards):
"""
for some decisions clears table and say lists
:param tuple player_hands_table_say not cleared table and say
:return tuple player_hands_table_say cleared table and say
"""
table.clear()
said_cards.clear()
return table, said_cards
def do_you_trust(player_hands_table_say: tuple, player: int):
"""
The function takes next players choices Yes, No, or Add
and depend on it give cards to players and removes
:param player_hands_table_say tuples that included three lists
:param player the player that made previous decision
:return player_hands_table_say tuple modified depend on choices
"""
all_players_cards = player_hands_table_say[0]
table = player_hands_table_say[1]
said_cards = player_hands_table_say[2]
next_player = player + 1
while True:
choice = input( f"Player N {player + 2} Do you trust? choice \"Yes\" or \"No\" or \"Add\" to add more cards:")
if choice == "Yes":
print(table, said_cards)
if sorted(table[len(said_cards)-1:]) == sorted(said_cards):
hands_table_clear(table, said_cards)
break
else:
if len(all_players_cards) > next_player:
all_players_cards[next_player].extend(table)
hands_table_clear(table, said_cards)
break
elif len(all_players_cards) == next_player:
all_players_cards[0].extend(table)
hands_table_clear(table, said_cards)
break
elif choice == "No":
if sorted(table[len(said_cards)-1:]) == sorted(said_cards):
if len(all_players_cards) > next_player:
all_players_cards[next_player].extend(table)
hands_table_clear(table, said_cards)
break
elif len(all_players_cards) == next_player:
all_players_cards[0].extend(table)
hands_table_clear(table, said_cards)
break
else:
all_players_cards[player].extend(table)
hands_table_clear(table, said_cards)
break
elif choice == "Add":
said_cards.clear()
return player_hands_table_say
else:
print("Please write right answer, Yes, No, or add\n")
continue
print("print here2")
return player_hands_table_say
|
c041cb6faa773a16878b086c289196b9bd1c46b6
|
Alex112525/Neural-Network-with-Python
|
/Neural_Network.py
| 3,454 | 3.671875 | 4 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_circles
# Create layers
class NeuralLayer:
# Receive number of connections, number of neurons and activation function
def __init__(self, n_connections, n_neurons, act_fun):
self.act_fun = act_fun
# self.bias = np.random.rand(1, n_neurons) * 2 - 1 # Generate a random vector with values from -1 to 1
self.bias = np.ones([1, n_neurons]) # Generate a vector of one for bias
self.weight = np.random.rand(n_connections, n_neurons) * 2 - 1 # Initialize the weights with random values
# Create Neural Network
def create_nn(_topology, act_fun):
nn_layers = []
for l in range(len(_topology)-1):
nn_layers.append(NeuralLayer(_topology[l], _topology[l + 1], act_fun))
return nn_layers
# Train function
def train(_neural_net, x, y, cost_fun, learn_r=0.05, _train=False):
# forward pass
out = list([x])
for layer in range(len(_neural_net)):
z = np.dot(out[-1], _neural_net[layer].weight) + _neural_net[layer].bias
a = _neural_net[layer].act_fun[0](z)
out.append(a)
if _train:
# Backward pass (Back propagation)
deltas = []
for layer in reversed(range(len(_neural_net))):
a = out[layer + 1]
if layer == len(_neural_net) - 1:
# Delta Last layer
deltas.insert(0, cost_fun[1](a, y) * _neural_net[layer].act_fun[1](a))
else:
# Delta with respect to previous layer
deltas.insert(0, np.dot(deltas[0], _W.T) * _neural_net[layer].act_fun[1](a))
_W = _neural_net[layer].weight
# Gradient decent
_neural_net[layer].bias = _neural_net[layer].bias - (np.mean(deltas[0], axis=0, keepdims=True) * learn_r)
_neural_net[layer].weight = _neural_net[layer].weight - (np.dot(out[layer].T, deltas[0]) * learn_r)
return out[-1]
# Activation Functions
sigmoid = (lambda x: 1 / (1 + np.e ** (-x)), # Sigmoid function
lambda x: x * (1 - x)) # Derived from function
# Cost Function
e2_mean = (lambda yp, yr: np.mean((yp - yr) ** 2),
lambda yp, yr: 2 * (yp - yr))
if __name__ == "__main__":
# Create Dataset
n = 200 # Dates
p = 2 # Characteristics
X, Y = make_circles(n_samples=n, factor=0.5, noise=0.09) # Generate the dataset
Y = Y[:, np.newaxis]
topology = [p, 4, 8, 1] # Topology of NeuralNet
neural_net = create_nn(topology, sigmoid)
loss = []
for i in range(500):
pY = train(neural_net, X, Y, e2_mean, learn_r=0.099, _train=True)
if i % 5 == 0:
#print(pY)
loss.append(e2_mean[0](pY, Y))
print(i, ": ",loss[-1])
res = 60
_x0 = np.linspace(-1.5, 1.5, res)
_x1 = np.linspace(-1.5, 1.5, res)
_Y = np.zeros((res, res))
for i0, x0 in enumerate(_x0):
for i1, x1 in enumerate(_x1):
_Y[i0, i1] = train(neural_net, np.array([[x0, x1]]), Y, e2_mean)[0][0]
plt.pcolormesh(_x0, _x1, _Y, cmap="coolwarm")
plt.axis("equal")
plt.scatter(X[Y[:, 0] == 0, 0], X[Y[:, 0] == 0, 1], c="skyblue") # Visualize the data
plt.scatter(X[Y[:, 0] == 1, 0], X[Y[:, 0] == 1, 1], c="salmon")
plt.draw()
plt.pause(0.1)
plt.clf()
|
303d1f821d682538ac66f94ba978a242294b3c00
|
domarps/Siruseri_Advertising_Hoardings
|
/siruseriSkyline.py
| 2,132 | 3.9375 | 4 |
import collections
import re
class SetElement:
def __init__(self):
self.parent = self
def root(self):
if self.parent is self:
return self
else:
return self.parent.root()
def union(self, other):
self.root().parent = other.root()
# Building has width, height, index
Building = collections.namedtuple('Building', 'w h i')
def main():
numbuildings = int(input("How many buildings: "))
buildings = []
for n in range(numbuildings):
(w, h) = re.match(r"([0-9]+) ([0-9]+)", input("w h: ")).groups()
buildings.append(Building(int(w), int(h), n))
sets = [SetElement() for elem in buildings]
by_height = sorted(buildings, key=lambda n: n.h, reverse=True)
max_i = len(buildings) - 1
max_S = 0
max_start = -1
max_end = max_i + 1
for elem in by_height:
# Union with previous/next if shorter or equal
# If we merge with both, both get the same root due to union
if elem.i > 0 and elem.h <= buildings[elem.i - 1].h:
sets[elem.i].union(sets[elem.i - 1])
if elem.i < max_i and elem.h <= buildings[elem.i + 1].h:
sets[elem.i].union(sets[elem.i + 1])
# Now we know which set we belong to, just find our root
cur_root = sets[elem.i].root()
# Accumulator and walk index
cur_w = elem.w
cur_i = elem.i
while cur_i > 0 and cur_root is sets[cur_i - 1].root():
cur_w += buildings[cur_i - 1].w
cur_i -= 1
low_i = cur_i
cur_i = elem.i # reset index
while cur_i < max_i and cur_root is sets[cur_i + 1].root():
cur_w += buildings[cur_i + 1].w
cur_i += 1
high_i = cur_i
# latest addition is shortest building, so elem.h is cur_h
cur_S = cur_w * elem.h
if cur_S > max_S:
max_S = cur_S
max_start = low_i
max_end = high_i
print("S: {}, start: {}, end: {}".format(max_S, max_start, max_end))
if __name__ == "__main__":
main()
|
d960c27c5ae53bc1ae5cf65445dab2265fc7d7e4
|
mohitsharma98/LeetCode30DayChallenge
|
/HappyNumber.py
| 870 | 3.5625 | 4 |
"""
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the
sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly
in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
"""
class Solution:
def isHappy(self, n: int) -> bool:
#Define a set with all visited Sums
visited = set()
#Loop through the digits until n!=1 and there is any new number in n
while n!=1 and n not in visited:
visited.add(n)
n = sum(map(lambda x:int(x)**2, str(n)))
return not n in visited
|
76c546a57cef782b6d6abcf5bccfc09a4d8c1f34
|
mingyyy/python-spark-tutorial
|
/rdd/sumOfNumbers/SumOfNumbersProblem.py
| 551 | 3.734375 | 4 |
import sys
from pyspark import SparkContext
if __name__ == "__main__":
'''
Create a Spark program to read the first 100 prime numbers from in/prime_nums.text,
print the sum of those numbers to console.
Each row of the input file contains 10 prime numbers separated by spaces.
'''
sc = SparkContext('local[1]', "textfile")
lines = sc.textFile('in/prime_nums.text')
nums = lines.flatMap(lambda line: line.split('\t'))
s = nums.reduce(lambda x, y: int(x)+int(y))
print(f'Sum of first 100 prime number is: {s}')
|
b9a6c4a74fff98eb517712d57e184c601bdf55ff
|
bluewhale1207/my_leetcode
|
/python/find_val_from_matrix.py
| 704 | 3.609375 | 4 |
#在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
#请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
def func(arr, value):
length = len(arr)
i =0
j = length - 1
while True:
if arr[i][j] == value:
return True
while j >= 0 and arr[i][j] > value:
j -= 1
while i <= length -1 and arr[i][j] < value:
i += 1
if j < 0 or i > length -1:
return False
print func([[1,4,7,10,15], [2,5,8,12,19], [3,6,9,16,22], [10,13,14,17,24], [18,21, 23, 26, 30]], 6)
|
5922c587ef2d0ecd4e8aed3a87b910368a14f335
|
bluewhale1207/my_leetcode
|
/python/search_range.py
| 2,471 | 3.90625 | 4 |
'''
https://leetcode.com/problems/search-for-a-range/
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
'''
class Solution(object):
def searchRange(self, nums, target):
# Runtime: 44 ms
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if target not in nums:
return [-1, -1]
return [nums.index(target), nums.index(target) + nums.count(target)-1]
def searchRange(self, nums, target):
# Runtime: 64 ms
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if target not in nums:
return [-1, -1]
return [nums.index(target), len(nums) - nums[::-1].index(target) -1 ]
def searchRange(self, nums, target):
# Runtime: 44 ms
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
start , end = 0, len(nums) -1
while start < end:
mid = (start+ end) / 2
if target <= nums[mid]:
end = mid
else:
start = mid +1
if nums[start] != target:
return [-1, -1]
left = start
start , end = 0, len(nums[left:])
while start < end:
mid = (start+ end) / 2
if target < nums[left+mid]:
end = mid
else:
start = mid +1
return [left, left+start-1]
def searchRange(self, nums, target):
# Runtime: 48 ms
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
start , end = 0, len(nums) -1
while start < end:
mid = (start+ end) / 2
if target <= nums[mid]:
end = mid
else:
start = mid +1
if nums[start] != target:
return [-1, -1]
range = [start]
start , end = 0, len(nums)
while start < end:
mid = (start+ end) / 2
if target < nums[mid]:
end = mid
else:
start = mid +1
return range + [start -1]
|
6ab7e7c0e911cfdd2374988300fdc5a05016f225
|
jaredalbright/simplePasswordGenerator
|
/generator.py
| 1,451 | 4.0625 | 4 |
import random
class Password:
def __init__(self,sequence,limit):
'''
No return
initializes variables
'''
self.sequence = sequence
self.limit = limit
def create_password(self):
'''
Returns password
Opens the text file for the word list and reads as a list.
Then creates a password at random based on the sequence of data types.
'''
#opens words.txt and turns it into a list
with open('words.txt') as f:
words = f.read().splitlines()
dict_length = len(words)
symbols = ['!','@','%','&','*'] #list can be changed, these were used just to test the program
password = ''
#this loop iterates through the list of data types the concatenates a random value for each element to the string
for element in self.sequence:
if element == "Word":
key = random.randint(0,dict_length-1) #not sure the -1 was necessary but I believe random int covers [a,b] rather than [a,b-1]
password += words[key].capitalize()
elif element == "Number":
password += str(random.randint(0,9)) #turns the int to a string for the sake of concatenation
elif element == "Symbol":
key = random.randint(0,len(symbols) - 1)
password += str(symbols[key])
return password
|
288424c361175aeef3d0b2dcaa55304ee9b5f05c
|
alinalihassan/nordcloud-assignment
|
/test/test_point.py
| 709 | 3.921875 | 4 |
import unittest
from src.main import Point
class PointTestCase(unittest.TestCase):
def test_point_validity(self):
point = Point(7, -14)
self.assertEqual(point.x, 7)
self.assertEqual(point.y, -14)
def test_point_equality(self):
point1 = Point(0, 0)
point2 = Point(0, 0)
point3 = Point(0, 1)
self.assertEqual(point1, point2)
self.assertNotEqual(point1, point3)
def test_point_distance(self):
point1 = Point(-7, -4)
point2 = Point(17, 6.5)
print(point1.get_distance_to(point2))
self.assertEqual(point1.get_distance_to(point2), 26.196373794859472)
if __name__ == '__main__':
unittest.main()
|
36ef9e91bf2e7b65d9a253fcb3dc0fe1f96b290e
|
segejung/webapptest2
|
/app/lib/parsers/api_parser.py
| 1,061 | 3.59375 | 4 |
from json import JSONDecodeError
import requests
import pandas as pd
from flatten_json import flatten
class APIParser:
"""Takes in url and json_format (flat, structured)"""
def __init__(self, url, json_format):
self.url = url
self.json_format = json_format
def parse(self):
"""Parse the file at given url and returns the generated csv file path
Returns:
a list of strings. Each string is the output of CSV file content
"""
r = requests.get(self.url)
try:
data = r.json()
except JSONDecodeError:
raise Exception("Sorry, url didn't return json")
except:
raise Exception("Something went wrong")
if self.json_format == 'flat':
if isinstance(data, list):
for i, d in enumerate(data):
data[i] = flatten(d)
else:
data = flatten(data)
df = pd.json_normalize(data)
ret = []
ret.append(df.to_csv())
return ret
|
3493e43f4475187b025b8d3d6fc2a96d5fd1c9b8
|
Iris11/MITx--CMITx--6.00.1x-Introduction-to-CS-and-Programming-Using-Python
|
/Problem Set 2_3.py
| 644 | 3.875 | 4 |
##Problem Set 2-2
##20150627
#balance, annualInterestRate
epsilon = 0.01
lower = balance / 12
upper = balance * ((1 + annualInterestRate / 12.0) ** 12) / 12.0
result = (lower + upper) / 2.0
def rest(monthlyPayment):
rest_balance = balance
for m in range(12):
interest = (rest_balance - monthlyPayment) * annualInterestRate / 12.0
rest_balance = rest_balance + interest - monthlyPayment
return rest_balance
while abs(rest(result)) >= epsilon:
if rest(result) < 0:
upper = result
else:
lower = result
result = (lower + upper) / 2.0
print ("Lowest Payment: " + str(round(result, 2)))
|
e370e41e77e42d4d753c3dd0fc0d6749205b1b17
|
orbicularis/UMpython
|
/python09/pythonCH9.py
| 2,914 | 4.03125 | 4 |
##fr2eng = dict()
##fr2eng['one'] = 'un'
##print(fr2eng['one'])
##vals = list(fr2eng.values())
##word = 'brontosaurus'
##d = dict()
##for letter in word:
## if letter not in d:
## d[letter] = 1
## else:
## d[letter] = d[letter] + 1
##
##print(d)
##counts = { 'chuck': 1, 'annie': 42, 'jan': 100}
##print(counts.get('annie', 0))
##word = 'brontosaurus'
##d = dict()
##for letter in word:
## d[letter] = d.get(letter, 0) + 1
##print(d)
## EXERCISE 2 - this searches the text file for a from and pulls a word out
##mbox = open('mbox-short.txt')
##count = dict()
##
##for line in mbox:
## newLine = line.find('From ')
## if newLine is not 0:
## continue
## else:
#### print(line)
## line = line.split()
## newLine = line[2]
#### print(newLine)
##
## for days in newLine.split():
## if days not in count:
## count[days] = 1
## else:
## count[days] += 1
##
##print(count)
##EXERCISE 3 - thsi is a histogram of email addresses
##
##mbox = open('mbox-short.txt')
##count = dict()
##
##for line in mbox:
## newLine = line.find('From ')
## if newLine is not 0:
## continue
## else:
#### print(line)
## line = line.split()
## newLine = line[1]
#### print(newLine)
##
## for email in newLine.split():
## if email not in count:
## count[email] = 1
## else:
## count[email] += 1
##
##print(count)
##EXERCISE 4 - same as 3 except finds highest sender
##
##mbox = open('mbox-short.txt')
##count = dict()
##
##for line in mbox:
## newLine = line.find('From ')
## if newLine is not 0:
## continue
## else:
#### print(line)
## line = line.split()
## newLine = line[1]
#### print(newLine)
##
## for email in newLine.split():
## if email not in count:
## count[email] = 1
## else:
## count[email] += 1
##
##
##hiScore = 0
##key = None
##for score in count:
## if count[score] > hiScore:
## hiScore = count[score]
## entry = score
##print(entry, hiScore)
##EXERCISE 5 - same as 3 except finds highest sender account
mbox = open('mbox-short.txt')
count = dict()
for line in mbox:
newLine = line.find('From ')
if newLine is not 0:
continue
else:
## print(line)
amper = line.find('@')
## print(amper)
endspot = line.find(' ',amper)
## print(endspot)
domain = line[amper+1:endspot]
## print(domain)
if domain not in count:
count[domain] = 1
else:
count[domain] += 1
print(count)
##hiScore = 0
##key = None
##for score in count:
## if count[score] > hiScore:
## hiScore = count[score]
## entry = score
##print(entry, hiScore)
|
34db48d075ff3f9aefc37f1caf019bb613ffce1d
|
orbicularis/UMpython
|
/python14/party.py
| 299 | 3.71875 | 4 |
## THIS IS A STANDALONE PROGRAM TO DEMONSTRATE INHERITANCE - party6.py LINKS TO IT
class PartyAnimal:
x = 0
name = ''
def __init__(self, nam):
self.name = nam
print(self.name,'constructed')
def party(self) :
self.x = self.x + 1
print(self.name,'party count',self.x)
|
b6da7440bda14d20522ac823b3a2ea8c2c8f7d26
|
fstoltz/P-uppgift2019
|
/koden MED MasterRegister/registerMall.py
| 3,552 | 3.5 | 4 |
"""
Författare: Fredrik Stoltz
Datum: 17/11-2019
"""
import time
class Register():
def __init__(self, namn, personLista=None):
#“””Skapa register”””
self.__namn = namn
self.__personLista = [] #denna lista ska innehålla person objekt
def skrivUtAlla(self):
#Skriver ut alla personer i sin lista”
namnLista = []
for person in self.__personLista:
#print("---------------------")
#print(person)
namnLista.append(person.getFornamn())
namnLista.sort()
#print(namnLista)
#print(self.__personLista)
for namn in namnLista:
self.sok(namn, "LETA")
print("---------------------")
def skrivSamtligDataTillFil(self):
data = ""
for person in self.__personLista:
data = data + person.skrivTillFil()
return data
def antalPersoner(self):
return len(self.__personLista)
def laggTillKontakt(self, nyKontakt):
self.__personLista.append(nyKontakt)
def getNamn(self):
return self.__namn
def sok(self, keyword, typ):
#print(keyword + "AR HAR")
#Generisk sökfunktion som försöker hitta en matchning av keyword på något i sin personLista, vid flera träffar returneras dessa träffar, vid en träff returneras just den träffen, vid ingen träff returneras (Kunde ej hitta.).
keyword = keyword.lower()
for person in self.__personLista:
if(person.getFornamn().lower() == keyword or person.getEfternamn().lower() == keyword or person.getNummer() == keyword or person.getAddress().lower() == keyword):
if(typ == "LETA"):
print(person)
elif(typ == "TABORT"):
self.__personLista.remove(person)
print(person.getFornamn() + " " + person.getEfternamn() + " har tagits borts.")
elif(typ == "ANDRA"):
#Jag tycker det är viktigare att kunna söka med enkla termer och sen knappa igenom om man hamnade på fel person
#än att behöva komma ihåg hela namnet på personen för att kunna ta bort den
self.andraPaKontakt(person)
print("---------------------\n")
def andraPaKontakt(self, person):
print("---> Du ändrar just nu på kontakten '"+person.getFornamn()+" "+person.getEfternamn()+"'. Är det rätt person?(ja/nej)")
if(input().lower() == "ja"):
usrin1 = input("---> Vill du byta telefonnummer(ja/nej)?").lower()
if(usrin1 == "ja"):
person.setNummer(self.validateInput(input("Ange nytt nummer: "), "NUM"))
print("Telefonnummret har uppdaterats.")
usrin1 = input("---> Vill du byta address(ja/nej)?").lower()
if(usrin1 == "ja"):
person.setAddress(input("Ange ny address: "))
print("Addressen har uppdaterats.")
def validateInput(self, theInput, typ):
if(typ == "NUM"):
theInput.strip()
numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
cleanedInput = ""
for char in theInput:
if char in numbers:
cleanedInput += char
return cleanedInput
def getPersonLista(self):
return self.__personLista
def taBortPerson(self, kontakt):
#“Går igenom sin personLista och tar bort kontakt från den”
pass
|
5c58debe7983432af51176392a8969ce8a7260e2
|
xbx1/useful
|
/python/threading-python3/timer.py
| 462 | 3.5625 | 4 |
#!/usr/bin/python3
from threading import Thread
import time
count = 0
def timer(name, n):
global count
while True and count < 10:
print("{} : {} ".format(name, time.strftime('%Y-%m-%d %X',time.localtime())))
time.sleep(n)
count += 1
if __name__ == "__main__":
t1 = Thread(target=timer, args=('Thread1', 1))
t2 = Thread(target=timer, args=('Thread2', 2))
t1.start()
t2.start()
t1.join()
t2.join()
|
38e5299bf0a90a134e918328b8d915c73a53d3c0
|
li563042811/Job_test
|
/wenyuan_test.py
| 658 | 3.5 | 4 |
import sys
def Find_minnum(list,sum,num):
if len(list)==0:
return -1
if sum in list:
num+=1
if sum < list[0] and sum != 0:
return -1
if sum>list[0] and sum<list[-1]:
for i in range(len(list)):
if list[i]>sum:
list.pop(i)
if sum > list[-1]:
list_last=list[-1]
num+=1
return Find_minnum(list,sum-list_last,num)
return num
if __name__ == "__main__":
line=sys.stdin.readline().strip()
list = list(map(int, line.split(',')))
sum = int(sys.stdin.readline().strip())
list.sort()
print(Find_minnum(list,sum,0))
|
ab6848a5ae9fdc7c67c92feebb9f00c8a77f5899
|
li563042811/Job_test
|
/cars.py
| 338 | 3.9375 | 4 |
cars=['bmw','audi','toyuta']
cars_1='bmm'
print(cars_1 in cars)
alien={'color':'green','points':5}
print(alien['color'])
print(alien['points'])
print(alien)
alien['x']=1
alien['y']=2
print(alien)
alien['color']='red'
print(alien)
for key,value in alien.items():
print('\nkey:'+key)
print('value:'+str(value))
|
08879034ad9098f49eb98e6f7b618b40419e0e41
|
ychang0821/mycode
|
/rpggame/game.py
| 6,121 | 3.625 | 4 |
#!/usr/bin/python3
import random
fuel_level = 20
#an rocksack, which is initially empty
rocksack = []
# unnecessary item list pool
item_list = ['water','coffee','rifle','camelbak','knife',
'alexa echo','boots','tent','key','laptop',
'asu','flashlight','food', 'pfizer vaccine','sword',
'radio station']
# all required items
f_list = ['cac card', 'mre', 'ignition key', 'space suit', 'diaper']
new_list = f_list.copy()
#a dictionary linking a city to other cities
cities = {
'Seattle' : {
'south' : 'Tacoma',
'east' : 'Bellevue',
'north' : 'Lynwood',
'west' : 'Bremerton',
'item' : []
},
'Tacoma' : {
'north' : 'Seattle',
'south' : 'JBLM',
'item' : []
},
'Bellevue' : {
'west' : 'Seattle',
'item' : []
},
'Lynwood' : {
'south' : 'Seattle',
'item' : []
},
'Bremerton' : {
'east' : 'Seattle',
'item' : []
},
'JBLM' : {
'north' : 'Tacoma',
'item' : []
},
}
def showInstructions():
#print a main menu and the commands
print('''
F you COVID! Let's go to Mars!
In this game, you need to go to different cities to collect items to launch the rocket locate at JBLM to go to Mars. Your fuel level start at 20, each movement between cities will cost 1 point of fuel. If the fuel level is 0, game will be terminated. You can collect at most 10 items. You need 5 necessary items to launch the rocket. Good luck!!
========
Commands:
go [direction]
get [item]
drop [item]
''')
def showStatus():
print('---------------------------')
getMap()
print('Your fuel level is ' + str(fuel_level))
print('You are in the ' + currentCity)
print('Rocksack : ' + str(rocksack))
#print an item if there is one
if "item" in cities[currentCity]:
print(f"You see a {cities[currentCity]['item']}")
print("---------------------------")
def itemInit(city):
random.shuffle(item_list)
random.shuffle(new_list)
for i in range(3):
cities[city]['item'].append(item_list.pop())
cities[city]['item'].append(new_list.pop())
random.shuffle(cities[city]['item'])
def launch():
for item in f_list:
if item in rocksack:
continue
else:
return False
return True
# def show_map():
# for key in cities[currentCity]:
# if key != "item":
# print(f"{key} : {cities[currentCity][key]}")
def getMap():
map = {
"Lynwood": " ",
"Seattle": " ",
"Bellevue": " ",
"Bremerton": " ",
"Tacoma": " ",
"JBLM": " "
}
for key in map:
if key == currentCity:
map[key] = "You are Here!"
print(f"""
N
↑
W ← + → E
↓
LYNWOOD S
{map["Lynwood"]}
BREMERTON SEATTLE BELLEVUE
{map["Bremerton"]}{map["Seattle"]}{map["Bellevue"]}
TACOMA
{map["Tacoma"]}
JBLM
{map["JBLM"]}
""")
def spaceship():
print("""
|
/ \
|--o|
|---|
/ \
| U |
| S |
| A |
|_______|
|@| |@|
./@\./@\.
||| |||
||| |||
""")
def dead():
print("""
.---.
./ \.
( () () )
\ M /
|HHH|
'---'
Sucker... you run out of fuel!
💀💀💀💀GAME OVER!💀💀💀💀
""")
showInstructions()
itemInit('Seattle')
itemInit('Tacoma')
itemInit('Bellevue')
itemInit('Bremerton')
itemInit('Lynwood')
#start the player in the 'Seattle'
currentCity = 'Seattle'
#loop forever
while True:
showStatus()
#get the player's next 'move'
#.split() breaks it up into an list array
#eg typing 'go east' would give the list:
#['go','east']
move = ''
while move == '':
move = input('>')
move = move.lower().split(" ", 1)
if (move[0] != 'go' or move[0] != 'get' or move[0] != 'drop') and len(move) == 1:
print('Bad input, please use a legit command')
#if they type 'go' first
elif move[0] == 'go':
if move[1] in cities[currentCity]:
currentCity = cities[currentCity][move[1]]
fuel_level -= 1
else:
print('You can\'t go that way!')
if move[0] == 'get' :
#if the room contains an item, and the item is the one they want to get
if len(rocksack) >= 10:
print('Full rocksack, Can\'t get ' + move[1] + '!' + 'drop something first')
elif "item" in cities[currentCity] and move[1] in cities[currentCity]['item']:
#add the item to their rocksack
rocksack += [move[1]]
#display a helpful message
print(move[1] + ' got!')
#delete the item from the city
cities[currentCity]['item'].remove(move[1])
#otherwise, if the item isn't there to get
else:
#tell them they can't get it
print('Can\'t get ' + move[1] + '!')
if move[0] == 'drop':
if move[1] in rocksack:
cities[currentCity]['item'].append(move[1])
print(move[1] + ' drop!')
rocksack.remove(move[1])
else:
#tell them they can't get it
print('Can\'t drop ' + move[1] + '!')
# if move[0] == 'map':
# show_map()
## Define how a player can win
if currentCity == 'JBLM':
launchable = launch()
if launchable == True:
spaceship()
print('Congratulations! You collected all the items you need to go to Mars!! Enjoy the trip!! ')
break
else:
print("You don't have all the necessary items to launch the rocket")
elif fuel_level == 0:
dead()
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.