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
ee43a116e8951757f34048101d50a6e43c4eea49
wentao75/pytutorial
/05.data/sets.py
653
4.15625
4
# 堆(Sets)是一个有不重复项组成的无序集合 # 这个数据结构的主要作用用于验证是否包含有指定的成员和消除重复条目 # 堆对象还支持如:并,交,差,对称差等操作 # 可以使用大括号或set()方法来产生堆对象,不要使用{}来产生空的堆对象 # {}会产生一个空的字典而不是堆对象 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) 'orange' in basket 'crabgrass' in basket a = set('abracadabra') b = set('alacazam') a b a - b b - a a | b a & b a ^ b # 堆也支持队列导出式 a = {x for x in 'abracadabra' if x not in 'abc'} a
25ca539e5e7e3b489d10ec35eb0e3e5eb49a78d0
rcm2000/learn_algorithm
/code07-02.py
1,776
3.96875
4
##함수 def isQueueFull(): global SIZE, front, rear if (rear != SIZE - 1) and (front == -1): return False else: for i in range(front+1,SIZE): queue[i-1] = queue[i] queue[i] = None front -= 1 rear -= 1 return False def enQueue(data): global SIZE, front, rear if isQueueFull(): print('큐가 가득 찼습니다.') return rear += 1 queue[rear] = data def isQueueEmpty(): global SIZE, front, rear if front == rear: return True else: return False def deQueue(): global SIZE, front, rear if isQueueEmpty(): print('큐가비었습니다.') return None front += 1 data = queue[front] queue[front] = None return data def peek(): global SIZE, front, rear if isQueueEmpty(): print('큐가비었습니다.') return None front += 1 return queue[front] ##변수 SIZE = 5 queue = [None for _ in range(SIZE)] front, rear = -1,-1 select = -1 ##메인 if __name__ =="__main__": while(select != 4): select = int(input("선택하세요(1:삽입,2:추출,3:확인,4.종료)-->")) if(select == 1): data = input('입력할 데이터----->') enQueue(data) print('현 큐 상태',queue) elif (select == 2): data = deQueue() print('추출 데이터 = ',data) print('현 스택 상태', queue) elif (select == 3): data = peek() print('확인된 데이터 =',data) elif (select == 4): print('현 스택 상태', queue) exit else: print("1~4의 숫자만 이용가능합니다") continue
911ff63d9a725b1c278ce6e4499f1963d01e1e16
rcm2000/learn_algorithm
/code13-03.py
589
3.734375
4
## 함수 def binarySearch(ary,fData): pos = -1 start = 0 end = len(ary)-1 while (start <= end) : mid = ((start + end) //2) if ary[mid] == fData : return mid elif fData > ary[mid]: start = mid + 1 else: end = mid - 1 return pos ## 변수 dataAtr = [56,60,105,120,150,160,162,168,177,188] findData = 162 ## 메인 print('배열 ==>', dataAtr) position = binarySearch(dataAtr,findData) if position == -1: print('없음') else: print(findData,'는',position + 1,'번째 존재합니다.')
6cbfc9e2bd18f1181041287a56317200b1b789a8
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week7/Practice ActivityRecursionSolution5.py
925
4.46875
4
""" Example of a recursive function that inserts the character 'x' between all adjacent pairs of characters in a string """ def insert_x(my_string): """ Takes a string my_string and add the character 'x' between all pairs of adjacent characters in my_string Returns a string """ if len(my_string) <= 1: return my_string else: first_character = my_string[0] rest_inserted = insert_x(my_string[1 :]) return first_character + 'x' + rest_inserted def test_insert_x(): """ Some test cases for insert_x """ print "Computed:", "\"" + insert_x("") + "\"", "Expected: \"\"" print "Computed:", "\"" + insert_x("c") + "\"", "Expected: \"c\"" print "Computed:", "\"" + insert_x("pig") + "\"", "Expected: \"pxixg\"" print "Computed:", "\"" + insert_x("catdog") + "\"", "Expected: \"cxaxtxdxoxg\"" test_insert_x()
87f5557c82320e63816047943679b70effe5aecf
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week6/Inheritance2.py
437
4.25
4
""" Simple example of using inheritance. """ class Base: """ Simple base class. """ def __init__(self, num): self._number = num def __str__(self): """ Return human readable string. """ return str(self._number) class Sub(Base): """ Simple sub class. """ def __init__(self, num): pass obj = Sub(42) print obj
efaf6d26c8b60e755140beebcc1a7134c68dc6e5
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad10/text.py
431
3.625
4
from tkinter import * def iniciarVentana(): root = Tk() root.title("Text") root.iconbitmap('icono.ico') root.resizable(0, 0) text_area = Text(root) text_area.config(width=30, height=10, font=("Verdana", 45), padx=10, pady=10, selectbackground="yellow") text_area.pack() root.mainloop() # Metodo que hace visible la ventana if __name__ == "__main__": iniciarVentana()
7b04a899e538e742f6957fe6078a22107b1c23bb
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad2/listas.py
440
3.796875
4
matriz = [ [1, 1, 1, 3], #0 [2, 2, 2, 7], #1 [3, 3, 3, 9], #2 [4, 4, 4, 13] #3 ] #print(type(matriz)) #print(len(matriz)) #print(matriz) a = sum([8,3,4]) print(a) """matriz[1][-1] = sum(matriz[1][:3]) matriz[3][-1] = sum(matriz[3][:-1])""" print (matriz[0][0]) matriz[0][0] = sum(matriz[0][-3:]) matriz[1][0] = sum(matriz[1][-3:]) matriz[2][0] = sum(matriz[2][-3:]) matriz[3][0] = sum(matriz[3][-3:]) print(matriz)
8cbc6a384f66035c62485e1f80b9fb33143f3b5d
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad4/ejercicios-unidad4.py
5,068
4.21875
4
import math def obtener_lista_numeros(cadena): """Valida la entrada de usuario y devuelve una lista de numeros ingresados por teclado. Controla espacios en blanco Args: cadena (str): Entrada de usuario que representa los numeros. Returns: list: Lista de numeros que fueron extraidos de la entrada de usuario: input() """ # Saca una serie de elementos (numeros) desde la cadena. lista_numeros = cadena.split(',') if len(cadena) > 0 else [] # Controla los espacios en blanco lista_numeros = [elemento.strip(' ') for elemento in lista_numeros] if len( lista_numeros) > 0 else [] return lista_numeros if lista_numeros else [] def relacion(num1, num2): """[summary] Args: num1 (float): Primer numero num2 (float): Primer numero Returns: float: Estado 0,1 o -1 """ if num1 > num2: return 1 elif num1 < num2: return -1 else: return 0 def area_rectangulo(ba, al): """Calcula el area de un rectangulo. Args: base (float): Representa la base del rectangulo. altura (float): Representa la altura del rectangulo. Returns: float: Area del rectangulo """ return (ba*al) def area_circulo(radio): """Calcula el area de un circulo dado el radio. Args: radio (float): Radio del circulo Returns: float: El area del circulo """ return (radio**2) * math.pi def intermedio(): pass def separar(lista_numeros): """Separar numeros pares e impares Args: l ([list]): Lista de numeros Returns: [tupla(list)]: Retorna una tupla de listas """ lista_numeros_pares = [] lista_numeros_impares = [] lista_numeros.sort() for numero in lista_numeros: if numero % 2 == 0: lista_numeros_pares.append(numero) else: lista_numeros_impares.append(numero) return lista_numeros_impares, lista_numeros_pares def calcula_factorial(numero): # f (5) = 1 * 2 * 3 * 4 *5 """Factorial de un numero Args: numero (float): Numero del cual se genera el factorial : f(num) Returns: float: Retorna el factual del numero ingresado """ fact = 1.0 if numero >= 1: for e in range(1, numero+1): fact *= e return fact else: return 0 def menu(): """Presenta el menu principal de las operaciones matematicas. """ area = 0.0 while True: print("""MENU PRINCIPAL 1.- Area del Rectangulo 2.- Area del Circulo 3.- Relacion 4.- Separar 5.- Factorial S.- Salir """) opcion = input("Seleccion la operacion a realizar \n") if opcion == '1': base = float(input("Ingresa la base \n")) altura = float(input("Ingresa la altura \n")) #area = area_rectangulo(base, altura) area = area_rectangulo(al=altura, ba=base) print( f" El area del rectangulo de : {base} base * {altura} altura es = {area} ") if opcion == '2': radio = float(input("Ingresa la radio del circulo \n")) area = area_circulo(radio) print( ' El area del circulo de : {} es = {:3f} '.format(radio, round(area, 3))) if opcion == '3': numero_1 = float(input("Ingresa la primer numero \n")) numero_2 = float(input("Ingresa el segundo numero \n")) resultado = relacion(num2=numero_2, num1=numero_1) print(f" {numero_1} > {numero_2} : El resultado es {resultado}") if opcion == '4': entrada_usuario = input( " Ingresa los valores separados por una coma \n") # Dada la cadena que ingreso el usuario por teclado, extraer los numeros: Lista (str) lista_numeros = obtener_lista_numeros(entrada_usuario) # Convertir las cadenas de texto que representan los numeros a enteros : int numeros = [int(num) for num in (obtener_lista_numeros(entrada_usuario))] # La invocacion a la funcion separar que retorna 2 listas: pares e impares impares, pares = separar(numeros) print("La lista de pares es igual : ", pares) print("La lista de impares es igual : ", impares) elif opcion == '5': while True: entrada_usuario = input("Ingresa el numero para calcular el factorial: \n") if len(entrada_usuario) > 0: factorial = calcula_factorial(numero=int(entrada_usuario)) break print(f"El factorial del numero {entrada_usuario} es = {factorial}") elif opcion.upper() == 'S': caracter = input("Estas seguro de salir del programa : y/n \n") if caracter.lower() == 'y': break else: pass if __name__ == "__main__": menu()
6df83a3cfec4db1e245f94b8588886399c145f14
dacl010811/curso-python-jupyter
/ejercicios-clase/unidad9/biblioteca.py
1,464
3.921875
4
class Biblioteca(): lectores = [] # Atributo de clase def __init__(self, direccion, recepcion, nombre): print("Init") self.direccion = direccion self.recepcion = recepcion self.nombre = nombre def __str__(self): print("str") return (f" Direccion: {self.direccion} - Recepcion : {self.recepcion} - Nombre : {self.nombre} ") def __del__(self): print("del") print("Va a eliminar el objeto de la memoria : {}".format(self.nombre)) def obtener_lectores(self): self.lectores = ['Eugenio Espejo','Bolivar'] class Lector: libros_prestados = 0 multa = 0 def __init__(self, nombre, apellido, cedula, edad): self.nombre = nombre self.apellido = apellido self.cedula = cedula self.edad = edad class Libro: autor = [] def __init__(self, nombre, tipo, anno, editorial): self.nombre = nombre self.tipo = tipo self.anno = anno self.editorial = editorial class Autor: nombre = "" nacionalidad = "" fecha_nacimiento = "" def __init__(self): pass if __name__ == "__main__": biblioteca = Biblioteca("Quito", "Python", "Municipal") biblioteca.obtener_lectores() print("Lectores",biblioteca.lectores) print(biblioteca) biblioteca1 = Biblioteca("GYE", "HOla", "Municipal Gye") print("Lectores",biblioteca1.lectores) print(biblioteca1)
8f43e84679abf5fcd2a82816b011d9cca2fcde5c
mikefraanje/Programming-Blok1
/les3/pe3_3.py
253
3.953125
4
leeftijd = int(input('geef je leeftijd: ')) paspoort = input('Ben je nederlander? ') if leeftijd > 17 and paspoort== 'ja': print ('gefeliciteerd, je mag stemmen!') else: print('je mag niet stemmen, want je moet nederlander en 18 jaar oud zijn')
0babb63d5faccfb7e0abfa713d6538dc0b629834
mikefraanje/Programming-Blok1
/les6/pe6_2.py
510
3.578125
4
# Schrijf een nieuw programma waarin een list met minimaal 10 strings wordt ingelezen. Het programma # plaatst alle vier-letter strings uit de ingelezen list in een nieuwe list en drukt deze af. Inlezen van een # lijst kan met eval(input("Geef lijst met minimaal 10 strings: ")). lijst = ["boter", "kaas", "bier", "pizza", "thee", "drop", "koek", "cola", "boterham", "wijn"] nieuwe_lijst=[] for x in lijst: characters = len(x) if characters == 4: nieuwe_lijst.append(x) print(nieuwe_lijst)
37260be3734e89bfff5437f1104e809b392bc14d
mikefraanje/Programming-Blok1
/les3/pe3_2.py
147
3.6875
4
leeftijd = input('Geef je leeftijd') paspoort = input('Nederlands paspoort') if leeftijd > 18 and paspoort == 'ja' : print 'Je mag stemmen!'
bbb886305283fb3075719376a9f315fd8f8ada66
OlegPonomaryov/mymllib
/mymllib/_test_data/classification.py
800
3.625
4
"""Test data for classification models.""" # Classes: # 0 (A) - both x1 and x2 are high # 1 (B) - both x1 and x2 are low # 2 (C) - x1 is high, x2 is low X = [[24, 32], [3, 0], [19, 1], [17, 28], [0, 5], [27, 5], [20, 30], [2, 3], [22, 3]] y = [0, 1, 2, 0, 1, 2, 0, 1, 2] y_text = ["A", "B", "C", "A", "B", "C", "A", "B", "C"] # A one-hot version of the y y_one_hot = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]] # A binary version of the y with respect to the class 2 y_bin = [0, 0, 1, 0, 0, 1, 0, 0, 1] # An index from which the test part of the dataset starts test_set_start = 6
996ec39d2549387fc942be88971b907ea28e1b2b
OlegPonomaryov/mymllib
/mymllib/neural_networks/output_activations.py
2,482
3.6875
4
"""Different activation functions for neural networks.""" from abc import ABC, abstractmethod from mymllib.math.functions import sigmoid, log_loss, softmax, softmax_loss class BaseOutputActivation(ABC): """Base class for activation functions for output layer.""" @staticmethod @abstractmethod def activations(x): """Calculate activation function value. :param x: Function argument :return: Activation value """ pass @staticmethod @abstractmethod def loss(a, y): """Calculate loss function value. Neural network implementation expects its derivative with respect to the output activation function's argument to be (y_pred - y_actual). :param a: Activation values :param y: Actual values :return: Loss value """ pass class SigmoidOutput(BaseOutputActivation): """Sigmoid activation function for output layer.""" @staticmethod def activations(x): """Calculate sigmoid activation function value. :param x: Function argument :return: Activation value """ return sigmoid(x) @staticmethod def loss(a, y): """Calculate binary cross entropy loss function value. :param a: Activation values :param y: Actual values :return: Loss value """ return log_loss(a, y) class SoftmaxOutput(BaseOutputActivation): """Softmax activation function for output layer.""" @staticmethod def activations(x): """Calculate softmax activation function value. :param x: Function argument :return: Activation value """ return softmax(x) @staticmethod def loss(a, y): """Calculate cross entropy loss function value. :param a: Activation values :param y: Actual values :return: Loss value """ return softmax_loss(a, y) class IdentityOutput(BaseOutputActivation): """Identity activation function for output layer.""" @staticmethod def activations(x): """Calculate identity activation function value. :param x: Function argument :return: Activation value """ return x @staticmethod def loss(a, y): """Calculate squared error loss function value. :param a: Activation values :param y: Actual values :return: Loss value """ return 0.5*(a - y)**2
1089357cd0a34c9a7dd53f59c75ac9d6e154f206
busquedas/ejercicios-tecnicas
/ejercicio_7.py
996
4.09375
4
#Crear una calculadora. El usuario deberá ingresar un valor, luego una operación #(1 para sumar, 2 para restar, 3 para dividir, 4 para multiplicar) #y un segundo valor para completar el calculo. El sistema deberá mostrar el resultado. valor = input ("ingrese un valor: " + str ()) valor = float (valor) opcion = input ("1 para sumar, 2 para restar, 3 para dividir, 4 para multiplicar: " + str ()) opcion = int (opcion) sumar = 1 restar = 2 dividir = 3 multiplicar = 4 segundo_valor = input ("ingrese segundo valor: " + str ()) segundo_valor = float (segundo_valor) if (opcion == 1): valor_total_suma = float (valor + segundo_valor) print (valor_total_suma) elif (opcion == 2): valor_total_resta = float (valor - segundo_valor) print (valor_total_resta) elif (opcion == 3): valor_total_dividir = float (valor / segundo_valor) print (valor_total_dividir) elif (opcion ==4): valor_total_multiplicar = float (valor * segundo_valor) print (valor_total_multiplicar)
8560b816547fb7fa0dd5ef0f1f12b527ab543a67
busquedas/ejercicios-tecnicas
/ejercicio_13.py
472
3.859375
4
#Almacenar 5 números por teclado y mostrar el promedio de ellos. #tengo que empezar print ("ingrese 5 números por teclado: ") almacenar = [] numero1 = input ("1ero: " + str ("")) numero2 = input ("2do: " + str ("")) numero3 = input ("3ro: " + str ("")) numero4 = input ("4to: " + str ("")) numero5 = input ("5to: " + str ("")) numero6 = 5 almacenar.append ((int (numero1) + int (numero2) + int (numero3) + int (numero4) + int (numero5)) /int(numero6)) print (almacenar)
a4ae13c4e1865d32d4fb7729db2f53060ff2c323
bblodget/RaspberryPi
/minecraft/digit_wall.py
7,417
4.09375
4
""" File: digit_wall.py This module defines a class DigitWall which creates a wall that can display a 7-segment digit in a Minecraft world. It provides a method to update the digit that is displayed. Author: Brandon Blodget URL: https://github.com/bblodget/RaspberryPi Copyright (c) 2013, Brandon Blodget All rights reserved. """ from __future__ import division import RPi.GPIO as GPIO #################### # Module Constants #################### # DigitWall Dimensions WALL_WIDTH = 8 WALL_HEIGHT = 9 # Segment Dimensions SEG_LENGTH = 4 # Segment states (illumination) ON = True OFF = False # Number of bits to use NUM_BITS = 3 # used to index into DIGIT SEG_A = 0 SEG_B = 1 SEG_C = 2 SEG_D = 3 SEG_E = 4 SEG_F = 5 SEG_G = 6 # Define the segments used in each digit. # # ........ # ..xaax.. # ..f..b.. # ..f..b.. # ..xggx.. # ..e..c.. # ..e..c.. # ..xddx.. # .......* # # * is the origin. Left is positive x. Up is pos y. # x is overlap DIGIT = [ [ON, ON, ON, ON, ON, ON, OFF], [OFF, ON, ON, OFF, OFF, OFF, OFF], [ON, ON, OFF, ON, ON, OFF, ON], [ON, ON, ON, ON, OFF, OFF, ON], [OFF, ON, ON, OFF, OFF, ON, ON], [ON, OFF, ON, ON, OFF, ON, ON], [ON, OFF, ON, ON, ON, ON, ON], [ON, ON, ON, OFF, OFF, OFF, OFF], [ON, ON, ON, ON, ON, ON, ON], [ON, ON, ON, ON, OFF, ON, ON], ] #################### # Classes #################### class DigitWall: def __init__(self, mc, xpos, ypos, zpos, wall_block, digit_block, digit_value, bit_pin): # save a copy of the minecraft object self.mc = mc # position to place the wall # y is the vertical dimension self.xpos = xpos self.ypos = ypos self.zpos = zpos # blocks that the wall is made of self.wall_block = wall_block self.digit_block = digit_block # the initial digit value. self.digit_value = digit_value # initialize the segment fields self._init_segments() # initialize the bit blocks self._init_bit_blocks(bit_pin) # create the wall self._draw_wall() # draw the bit blocks self._draw_bits() def _init_bit_blocks(self, bit_pin): # location of the three bit blocks # which represent a 3-bit binary number. # bit_block[0] is LSB z = self.zpos - 14 self.bit_loc = [ (self.xpos+1,self.ypos,z), (self.xpos+3,self.ypos,z), (self.xpos+5,self.ypos,z) ] # Each bit block can be ON or OFF # initialize the states self.bit_state = [OFF, OFF, OFF] # Each bit controls a GPIO pin # This pin is asserted when the # the bit is on and deasserted when # the bit is off. self.bit_pin = bit_pin def _init_segments(self): # create block arrays that represent the segments self.segment = [ [], [], [], [], [], [], [] ] # ..xaax.. # ..f..b.. # ..f..b.. # ..xggx.. # ..e..c.. # ..e..c.. # ..xddx.. # .......* # # * is the origin. Left is positive x. Up is pos y. # x is overlap self._init_horiz_segment(SEG_A, 2, 7) self._init_vert_segment(SEG_B, 2, 4) self._init_vert_segment(SEG_C, 2, 1) self._init_horiz_segment(SEG_D, 2, 1) self._init_vert_segment(SEG_E, 5, 1) self._init_vert_segment(SEG_F, 5, 4) self._init_horiz_segment(SEG_G, 2, 4) def _init_horiz_segment(self, seg, x, y): # convert x,y to absolute coordinates x = x + self.xpos y = y + self.ypos + 1 # +1 because wall above floor z = self.zpos # define params to create seg using mc.setBlocks cmd self.segment[seg].append(x) self.segment[seg].append(y) self.segment[seg].append(z) self.segment[seg].append(x+SEG_LENGTH-1) self.segment[seg].append(y) self.segment[seg].append(z) def _init_vert_segment(self, seg, x, y): # convert x,y to absolute coordinates x = x + self.xpos y = y + self.ypos + 1 # +1 because wall above floor z = self.zpos # define params to create seg using mc.setBlocks cmd self.segment[seg].append(x) self.segment[seg].append(y) self.segment[seg].append(z) self.segment[seg].append(x) self.segment[seg].append(y+SEG_LENGTH-1) self.segment[seg].append(z) def _draw_wall(self): # ypos+1 because wall above floor self.mc.setBlocks(self.xpos, self.ypos+1, self.zpos, self.xpos+WALL_WIDTH-1, self.ypos+WALL_HEIGHT, self.zpos, self.wall_block) self._draw_digit(self.digit_value,ON) def _draw_digit(self, digit, on): block = self.wall_block if (on): block = self.digit_block seg_on = DIGIT[digit] i =0 # segment index for seg in self.segment: if (seg_on[i]): self.mc.setBlocks(seg[0], seg[1], seg[2], seg[3], seg[4], seg[5], block) i = i + 1 def _draw_bits(self): """ Redraws all the bit blocks based on their state. Also asserts GPIO pins for bits that are ON. Also calculates a new digit_value based on the state of the bits. """ new_value = 0 for i in range(NUM_BITS): if (self.bit_state[i] == ON): self.mc.setBlock(self.bit_loc[i][0], self.bit_loc[i][1], self.bit_loc[i][2], self.digit_block) GPIO.output(self.bit_pin[i],GPIO.HIGH) new_value = new_value + 2**i else: self.mc.setBlock(self.bit_loc[i][0], self.bit_loc[i][1], self.bit_loc[i][2], self.wall_block) GPIO.output(self.bit_pin[i],GPIO.LOW) self.digit_value = new_value def update(self, blockHits): """ Process blockHits events. Checks If any of the bit blocks have been touched. If so toggles them and redraws bit blocks and digit_wall to represent the new state. """ if blockHits: for blockHit in blockHits: x,y,z = blockHit.pos # check if a block_bit was touched for i in range(NUM_BITS): if (self.bit_loc[i][0] == x and self.bit_loc[i][1] == y and self.bit_loc[i][2] == z): # Erase the old wall digit self._draw_digit(self.digit_value,OFF) # Toggle the bit that was touched self.bit_state[i] = not self.bit_state[i] # Draw the bits. Also gets new # digit value self._draw_bits() # Draw the new wall digit self._draw_digit(self.digit_value,ON)
9a0d08c170b5495ec44ab846a7593a3671b74f9f
kmgumienny/Python-Practice-Udemy
/String Challenge.py
646
4.03125
4
# Create a program that takes an IP address entered at the keyboard # and prints out the number of segments it contains, and the length of each segment. ipAddress = input("Please enter an IP address ") printText = '' numNumbers = 0 numSegment = 1 for i in range(0, len(ipAddress)): if ipAddress[i] in '0123456789': numNumbers += 1 elif ipAddress[i] == '.': printText += 'Segment {} has a length of {}. '.format(numSegment, numNumbers) numSegment += 1 numNumbers = 0 if i == len(ipAddress) - 1: printText += 'Segment {} has a length of {}. '.format(numSegment, numNumbers) print(printText)
cbdff5a801c81d3e94cd908387a5fdbddf4ba561
edenpan/dissertation
/strategies/componentTradingRules/BollingerBandsStrategy.py
3,130
3.609375
4
# coding: utf-8 # autor:Eden # date:2018-08-03 # bb.py : Bollinger Bands is a volatility indicator that considers the fluctuations of stock price. # middle band: BBs calculates an n day moving average of past close price Avgt,n. # upper band: k times above the standard deviation of the middle band. # lower band: k times below the standard deviation of the middle band. # parameters: n: moving average length :[10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 75, 80, 90, 100, 125, 150, 175, 200, 250] # k: multiplier :[1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5] # Suppose the close price of trading day t is pt # singal: buy signal : the close price fall below the lower band # sell signal : a sell signal is generated when the close price is above the upper band import sys sys.path.append('../') import utils import itertools import pandas as pd import numpy as np class BollingerBandsStrategy: def __init__(self): self.strategyName = "BollingerBandsStrategy" def parseparams(self, para): n = [] k = [] temPara = para.split('-') n.append(int(temPara[-2])) k.append(float(temPara[-1])) return {'n': n, 'k': k} def score(self, row): if (row['middle'] == np.nan): return 0.0 # when today's adjclose is the highest price to buy if row['adjclose'] < row['lower']: return 1.0 # when today's adjclose is the lowest price to sell if row['adjclose'] > row['upper']: return -1.0 return 0.0 def checkParams(self, **kwargs): if 0 == len(kwargs): return False n = kwargs.get('n') k = kwargs.get('k') for i in n: if i <= 1: return False return True def defaultParam(self): # n = [10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 75, 80, 90, 100, 125, 150, 175, 200, 250] # k = [1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5] n = list(range(10,255)) k = utils.frange(1.5,2.6,0.1) parms = {'n': n, 'k': k} return parms #return the running result that whether buy or sell and the total stratey number base on the parameter that input def run(self, stockData, **kwargs): cnt = 0 scoreRes = pd.DataFrame() n = kwargs.get('n') k = kwargs.get('k') self.checkParams(**kwargs) for i in n: # if the params is valid just skip this one: # such as the situation that the data is not enough for the parameter. if len(stockData) <= i - 1: continue; ave = pd.Series(stockData['adjclose'].rolling(i).mean().values, index = stockData['datetime']) std = pd.Series(stockData['adjclose'].rolling(i).std().values, index = stockData['datetime']) for time in k: upper = ave + time * std lower = ave - time * std result = pd.concat([pd.Series(stockData['adjclose'].values, index = stockData['datetime']), ave, lower, upper], keys = ['adjclose','middle', 'lower', 'upper'], axis = 1) scoreRes[str(i) + '-' +str(time)] = result.apply (lambda row: self.score(row),axis=1) cnt = cnt + 1 return scoreRes, cnt if __name__=="__main__": stockDataTrain = utils.getStockDataTrain("0005", True) bb = BollingerBandsStrategy() params = bb.defaultParam() bb.run(stockDataTrain, **params)
70b3346ddb78d5d8e5f136bae52c8ebd0d25238c
vefakucukler/Imdb-Analysis
/ImdbAnalizi/pandas_imdb_analizi.py
1,578
3.71875
4
import pandas as pd df = pd.read_csv('imdb.csv') result = df result = df.columns #Dataset Hakkında Bilgi verir result = df.info #1- İlk 5 kaydı gösterir result = df.head() #2- İlk 10 kaydı gösterir result = df.head(10) #3- Son 5 kaydı gösterir result = df.tail() #4- Son 10 kaydı gösterir result = df.tail(10) #5- Sadece Movie_Title kolonunu getirir result = df["Movie_Title"] #6- Sadece Movie_Title kolonunun ilk 5 kaydını getirir. result = df["Movie_Title"].head() #7- Sadece Movie_Title ve Rating kolonlarının ilk 5 kaydını getirir. result = df[["Movie_Title","Rating"]].head() #8- Sadece Movie_Title ve Rating kolonlarının son 7 kaydını getirir. result = df[["Movie_Title","Rating"]].tail(7) #9- Sadece Movie_Title ve Rating kolonlarını içeren ikinci 5 kaydını getirir. result = df[5:][["Movie_Title","Rating"]].head() #Aynı işi yapıyor -> result = df[5:10][["Movie_Title","Rating"]] #10- Sadece Movie_Title ve Rating kolonunu içeren ve imdb puanı 8.0 ve üzerinde olan kayıtlardan ilk 50 tanesini getirir. result = df[df["Rating"] >= 8.0][["Movie_Title","Rating"]].head(50) #12- Yayın tarihi 2014 ile 2015 arasında olan filmlerin isimlerini getirir. result = df[(df["YR_Released"] >=2014 ) & (df["YR_Released"] <= 2015)][["Movie_Title","YR_Released"]] #13- Değerlendirme sayısı (Num_Reviews) 100.000 den büyük ya da imdb puanı 8 ile 9 arasında olan filmleri getirir. result = df[(df["Num_Reviews"] > 100000 ) | ((df["Rating"] >= 8.0) & (df["Rating"] <= 9.0))][["Movie_Title","Num_Reviews","Rating"]] print(result)
061cc8e04cdaba494f531e6f7efa6a5f9b882e8e
besenthil/Algorithms
/algoexpert/move_element_to_end.py
764
3.59375
4
# O(n) Time # O(1) Space def moveElementToEnd(array, toMove): #pythonic way current_index = 0 while current_index < len(array): if array[current_index] != toMove: array.insert(0, array.pop(current_index)) current_index += 1 return array # O(n) Time # O(1) Space def moveElementToEnd_2(array, toMove): current_index = 0 last_index = len(array)-1 while current_index < last_index: if array[last_index] == toMove: last_index -= 1 else: if array[current_index] == toMove: array[current_index], array[last_index]=array[last_index], array[current_index] last_index -= 1 else: current_index += 1 return array
2cb01f710d593d6e3be2cf77a8024817bb032ccb
besenthil/Algorithms
/algoexpert/sortedSquaredArray.py
100
3.5
4
# O(nlogn) Time # O(n) Space def sortedSquaredArray(array): return sorted(x ** 2 for x in array)
4fcf5d6c12648b420d72c50ccac1e39393347910
besenthil/Algorithms
/quicksort.py
839
3.734375
4
import random,datetime def partition(arr,low,high): pivot = arr[low] i = low j = high while i < j: while ((i <= high) and (arr[i] <= pivot)): i += 1 while arr[j] > pivot: j -= 1 if i < j: arr[i],arr[j] = arr[j],arr[i] else: break arr[low]=arr[j] arr[j] = pivot print (arr[low:pivot]) return j def quick_sort_recursive(arr,low,high): if high > low: #print(arr) pivot = partition(arr,low,high) quick_sort_recursive(arr,low,pivot-1) quick_sort_recursive(arr,pivot+1,high) def quick_sort(arr): quick_sort_recursive(arr,0,len(arr)-1) #print (arr) if __name__ == '__main__': N = int(input()) arr = list(map(int,input().split(' ')))[:N+1] quick_sort(arr) print (arr)
9cf4c0dd69fd5464b6de5877926e842f5d47fe13
besenthil/Algorithms
/symmetric_point.py
333
4.0625
4
def compute_symmetric_point(): coordinates = [] for _ in range(int(input())): coordinates.append(list(map(int,input().split()))) for coordinate in coordinates: print("{0} {1}".format(2*coordinate[2]-coordinate[0],2*coordinate[3]-coordinate[1])) if __name__ == "__main__": compute_symmetric_point()
703e36dd7548ded429c5e24e5fab313f21b800ef
besenthil/Algorithms
/algoexpert/nodeDepths.py
346
3.90625
4
def nodeDepths(root, level=0): if root is None: return 0 else: return level + nodeDepths(root.right, level + 1) + nodeDepths(root.left, level + 1) # This is the class of the input binary tree. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None
e34f2b59fe4b713e979a1d35c4660e1c26fe6764
Harshitanetam/std_deviation
/std_deviation.py
1,084
3.9375
4
import math #list of elements to calculate mean import csv with open('data.csv', newline='') as f: reader = csv.reader(f) file_data = list(reader) data = file_data[0] #getting the mean # data = [20,69,56,90,40,99,86,100,70,69,80,65,57,82,90,70,79,39,90,80,86,53,97,95,88,47,100,56,97,100] #list of x or y # data=[60,61,65,63,98,99,90,95,91,96] # finding mean def mean(data): n= len(data) total =0 for x in data: total += int(x) mean = total / n return mean # squaring and getting the values squared_list= [] for number in data: a = int(number) - mean(data) a= a**2 squared_list.append(a) # getting sum sum = 0 for i in squared_list: sum = sum +1 #dividing the sum by the total values result = sum/ (len(data)-1) #getting the diviation by taking square root of the result std_diviation = math.sqrt(result) print(std_diviation) # print("derived using predefind function",statistics .stdev(data))
c3d263e251fd73a1bb7c4c511ecd26225679fe3c
Thuhaa/PythonClass
/16-Aug/list_slicing.py
377
3.921875
4
kenya_uni = ["TUK", "UON", "Egerton", "Moi", "JKUAT", "KU"] # print the values in the list between index 2 and 4 print(kenya_uni[2:5]) # Expected Output: ["Egerton", "Moi", "JKUAT"] # Reversing a list print(kenya_uni[::-1]) # Expected Output: ["KU", "JKUAT", "Moi", "Egerton", "UON", "TUK"] # printing specific numbers in index 2 and 4 print(kenya_uni[2:5:2])
9f045af90875eea13a4954d2a22a8089fd07724a
Thuhaa/PythonClass
/28-July/if_else_b.py
713
4.21875
4
marks = int(input("Enter the marks: ")) # Enter the marks # Between 0 and 30 == F # Between 31 and 40 == D # Between 41 and 50 == C # Between 51 and 60 == B # Above 61 == A # True and True == True # True and False == False # False and False == False # True or True == True # True or False == True # False and False == False # Use elif If there is more than 2 condition if marks <= 30: print("The student has scored an F") elif marks > 30 and marks <=40: print("The student has scored a D") elif marks >40 and marks<=50: print("The student score a C") elif marks > 50 and marks <= 60: print("The student scored a B") else: print("The student scored and A")
d88cc40adb2c1fcb288b6af4f01c590c12b6788f
Gaurav-Pande/openshift-python
/GenderClassifier.py
4,356
3.5
4
# Lucien Rae 2017 # A classifier that predicts whether a name is male or female # Uses a DecisionTree Classifier # Data from a list of 258000 names, 50/50 ratio between male and female # Features are the digits that correspond with the letters in the name # Labels are the gender import csv from sklearn import tree from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn import model_selection from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC source = 'names.csv' flag = 0 class GenderClassifier: # turns a word into a list of digits @classmethod def wordToDigits(self,word): wordD = [-1]*10 # give default values to the digits for i in range(min(len(list(word)),10)): # cut off the word if it's more than 10 characters char = list(word)[i] number = ord(char.lower()) - 97 wordD[i] = (number) return(wordD) @classmethod def performanceMatrix(self,X_train,Y_train): models = [] #models.append(('LR', LogisticRegression())) models.append(('LDA', LinearDiscriminantAnalysis())) models.append(('KNN', KNeighborsClassifier())) models.append(('CART', DecisionTreeClassifier())) models.append(('NB', GaussianNB())) seed = 2 scoring = 'accuracy' results = [] names = [] for name, model in models: kfold = model_selection.KFold(n_splits=2, random_state=seed) cv_results = model_selection.cross_val_score(model,X_train,Y_train , cv=kfold, scoring=scoring) results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print(msg) @classmethod def accuracy(self,clf,X_test,Y_test): predictions = clf.predict(X_test) print("Accuracy: %.2f" % accuracy_score(Y_test, predictions)) @classmethod def predict(self,name): namesToTest = name.split() # import training data with open(source) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') names = [] sexes = [] for row in readCSV: name = row[1] sex = int(row[3] == 'boy') # 0 girl, 1 images names.append(name) sexes.append(sex) # gather and format features and labels X = [] for name in names: # turn names into digits nameD = GenderClassifier.wordToDigits(name) X.append(nameD) Y = sexes print("training data set") # split training / testing data X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.0002) # classifier #print(X_train) clf = tree.DecisionTreeClassifier() # decide classifier # from sklearn.neighbors import KNeighborsClassifier # clf = KNeighborsClassifier() # fit to classifier clf = clf.fit(X_train, Y_train) # find patterns in data print(sum(abs(clf.predict(X_test) - Y_test))) GenderClassifier.accuracy(clf, X_test, Y_test) #global flag #if flag==0: # GenderClassifier.performanceMatrix(X_train, Y_train) # flag=1 # Spot Chec k Algorithms print("predict value") genderName = {0: "Girl", 1: "Boy"} for nameToTest in namesToTest: predictedGender = genderName[int(clf.predict([GenderClassifier.wordToDigits(nameToTest)]))] print("Predicted Gender of %s: %s" % (nameToTest.title(),predictedGender)) return (nameToTest.title(),predictedGender)
ac9c8b4b870b5a72e4cc38267bc0e8238e699222
artikri/stp
/NextDate.py
1,300
3.734375
4
def isLeapYear(year): if year % 4 == 0: if year % 100==0: if year % 400==0: return 1 else: return 1 else: return 0 day = int(input("Enter day:")) mon = int(input("Enter mon:")) year = int(input("Enter Year:")) thirty = [4, 6, 9, 11] thirtyOne = [1, 3, 5, 7, 8, 10, 12] incrMon = 0 incrYear = 0 isLeap = isLeapYear(year) flag = 0 if (mon in thirty and day > 30) or (mon in thirtyOne and day > 31) or day <= 0 or mon <= 0 or mon > 12: flag = 1 else: if (day == 30 and (mon in thirty)) or (day == 31 and (mon in thirtyOne)): nxtDay = 1 incrMon = 1 else: nxtDay = day + 1 incrMon=0 if isLeap==1 and mon==2 and day==28: nxtDay=day+1 incrMon=0 elif isLeap==1 and mon==2 and day==29: nxtDay=1 incrMon=1 elif isLeap == 0 and mon==2 and day==28: nxtDay=1 incrMon=1 if incrMon==1 and mon==12: nxtMon=1 incrYear=1 elif incrMon==0: nxtMon=mon else: nxtMon=mon+1 if incrYear==1: nxtYear=year+1 else: nxtYear=year if flag ==1: print("Invalid Date") else: print("Next Day") print("Day:",nxtDay) print("Mon:",nxtMon) print("Year:",nxtYear)
ddccc907b7cc2cdea22874e8f41c9ec04eacc220
ritwiktiwari/algorithm-visualizer
/app.py
2,924
3.640625
4
from tkinter import * from tkinter import ttk import random from bubble_sort import bubble_sort # Main Window root = Tk() root.title("Sorting Algorithm Visualizer") root.maxsize(900,600) root.config(bg='black') # Variables selected_algorithm = StringVar() data = [] def draw_data(data, color_array): canvas.delete('all') canvas_height = 380 canvas_width = 600 x_width = canvas_width / (len(data) + 1) offset = 20 spacing = 10 normalized_values = [i/max(data) for i in data] for i, height in enumerate(normalized_values): x0 = i * x_width + offset + spacing y0 = canvas_height-height*340 x1 = (i+1) * x_width + offset y1 = canvas_height canvas.create_rectangle(x0,y0,x1,y1, fill=color_array[i]) canvas.create_text((x0+x1)//2,y0,anchor=SW, text=str(data[i])) root.update_idletasks() def generate(): global data data = [] min_val = int(min_entry.get()) max_val = int(max_entry.get()) size = int(size_entry.get()) for _ in range(size): data.append(random.randrange(min_val, max_val+1)) draw_data(data, ['red' for i in range(len(data))]) print("Algorithm "+ selected_algorithm.get()) def start(): global data time_tick = int(speed_scale.get()) bubble_sort(data, draw_data, time_tick) print("Start") # Frame UI_FRAME = Frame(root, height=200, width=600, bg='grey') UI_FRAME.grid(row=0, column=0, padx=10, pady=5) # Canvas canvas = Canvas(root, width=600, height=380, bg='white') canvas.grid(row=1, column=0, padx=10, pady=5) # UI Area # ROW:0 Label(UI_FRAME, text='Algorithm: ', bg='grey').grid(row=0, column=0, padx=5, pady=5, sticky=W) algorithm_menu = ttk.Combobox(UI_FRAME, textvariable=selected_algorithm, values=['Bubble Sort', 'Merge Sort']) algorithm_menu.grid(row=0, column=1, padx=5, pady=5, sticky=W) algorithm_menu.current(0) speed_scale = Scale(UI_FRAME, from_=0.1, to=2.0, length=200, digits=2, resolution=0.2, orient=HORIZONTAL, label='Select speed (seconds)') speed_scale.grid(row=0, column=2, padx=5, pady=5) Button(UI_FRAME, text="Start", command=start).grid(row=0, column=3, padx=5, pady=5) # ROW:1 Label(UI_FRAME, text='Size: ', bg='grey').grid(row=1, column=0, padx=5, pady=5, sticky=W) size_entry = Entry(UI_FRAME) size_entry.grid(row=1, column=1, padx=5, pady=5, sticky=W) Label(UI_FRAME, text='Min Value: ', bg='grey').grid(row=1, column=2, padx=5, pady=5, sticky=W) min_entry = Entry(UI_FRAME) min_entry.grid(row=1, column=3, padx=5, pady=5, sticky=W) Label(UI_FRAME, text='Max Value: ', bg='grey').grid(row=1, column=4, padx=5, pady=5, sticky=W) max_entry = Entry(UI_FRAME) max_entry.grid(row=1, column=5, padx=5, pady=5, sticky=W) Button(UI_FRAME, text="Generate", command=generate).grid(row=1, column=6, padx=5, pady=5) root.mainloop()
4e6708d3b8109a6fb5082eb4efb5d0590309f71a
yestodorrow/dataAnalysis
/firstCourse/hello.py
1,252
4.125
4
print("Hello Python") # 交互界面窗口 输入输出交互式 # 编写和调试程序 # 语法词汇高亮显示 # 创建、编辑程序文件 print("hello world") a=3 # 定时器 import time time.sleep(3) a=4 print(a) print(a) # 标量对象 # init 整数 # float 实数 16.0 # bool 布尔 True False # NoneType 空类型 x="this is liu Gang" y="he is a handsome boy" print(x+","+y) #变量 #赋值语句 x,y="liugang","very handsome" sentence =x+" "+ y print(sentence) #注意:分隔符只能是英文的半角逗号 #数字的类型 # 整数 浮点数 布尔型 复数(complex) # 5+3j complex(5,3) # 判断数据类型 # type() isinstance() # print(type(5.0),type(1E+3),type()) #转换数据类型 # int() 转换成整数 print(int(3.9)) # print(int(3.9)) print(3>2>1) #比较运算符 print(0) #数学运算的优先级 print(x,y,x+y*3) #字符串 同js #输入函数 # 如何在交互中变量赋值呢 x=input("name") print(x +" is very handsome") # 注意 语句返回值为字符串,可以通过类型转换 x=input("4") # print(x/4) print(int(4)/4) x=int(input("number")) height=float(input("your savings in wechat or 支付宝")) print(height) # print(x,sep=" ",end="\n") # print(x,y,sep="***",end="!") print("e")
e39be11bf340de1ffc975a2568c41538ad434495
hafenschiffer/UdemyPythonForPentesters
/nmapscanner.py
531
3.625
4
#!/usr/bin/env python3 #pip3 install python-nmap import sys import nmap def scanport(scanner, target, port): print('\nScanning %s for port %s' %(target, port)) result = scanner.scan(target, port) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: %s <ip>" % sys.argv[0]) sys.exit(1) else: target = sys.argv[1] ports = [21, 22, 80, 139, 443, 445, 3389, 8080] scanner = nmap.PortScanner() for port in ports: scanport(scanner, target, port)
198c27c7d2e676d844c3ff0958f7174b5ad95d89
marczakkordian/python_code_me_training
/02_flow_homework/02_while/02.py
485
3.640625
4
# Napisz prostą grę, w której użytkownik musi zgadnąć liczbę od 0 - 20 ukrytą w programie (np. secret_num = 5). # Pytaj użytkownika o podanie liczby tak długo, aż nie zgadnie. # defining secret number secret_num = 12 # defining user number variable user_num = int(input('Enter your number (1-20): ')) # loop with guessing number while secret_num != user_num: user_num = int(input('Sorry, try again: ')) # condition for winning case print('Congrats! You won the game')
4190a27fb1a36236b8279533eb51a6152fc84ad7
marczakkordian/python_code_me_training
/02_flow_homework/02_summary/05.py
1,293
3.96875
4
# Stwórz grę ciepło zimno. # Komputer losuje liczbę z zakresu od 1 do 100. # Użytkownik podaje swój traf. # Komputer odpowiada ciepło zimno, ale nie więcej niż 6 razy. # Jeśli użytkownik zgadnie wygrywa gracz. # Jeśli po 6 próbach użytkownik nie zgadnie - wygrywa komputer. import random ran_num = random.randrange(1, 100) usr_num = int(input('Type your number (1-100): ')) diff_init = 0 diff_num = 0 counter = 1 diff_init = abs(usr_num - ran_num) if usr_num == ran_num: print('Congrats! You won the game :)') elif diff_init <= 10: print('Hot!') else: print('Cold!') while counter <= 6 and usr_num != ran_num: usr_num = int(input('Type your next number: ')) diff_num = abs(usr_num-ran_num) diff_last = diff_init if usr_num == ran_num: print('Congrats! You won the game :)') elif diff_num == diff_init or diff_num == diff_last: counter = counter + 1 print('No change! Type different number.') elif diff_num <= diff_last: counter = counter + 1 diff_last = diff_num print('Hotter') elif diff_num >= diff_last: print('Colder!') counter = counter + 1 diff_last = diff_num print(f'Sorry, you reached maximum of attempts (6). Computer wins! Correct number: {ran_num}')
6528bce9faea44b6dc6326a8fdae56e584fb31ab
marczakkordian/python_code_me_training
/01_types_homework/04.py
1,199
4.09375
4
# Utwórz skrypt, który zapyta użytkownika o tytuł książki, nazwisko autora, liczbę stron, a następnie: # Sprawdź czy tytuł i nazwisko składają się tylko z liter, natomiast liczba stron jest wartością liczbową. # Użytkownicy bywają leniwi. Nie zawsze zapisują tytuły i nazwisko z dużej litery – popraw ich # Połącz dane w jeden ciąg book za pomocą spacji # Policz liczbę wszystkich znaków w napisie book book_tittle = input('Please enter your book tittle: ') lastname_of_author = input('Please enter a lastname of the author: ') pages_number = input("Please enter your book's pages number: ") check_isLetters_inTittle = str.istitle(book_tittle) print('Your tittle has only letters', check_isLetters_inTittle) check_isLetter_inLastname = str.istitle(lastname_of_author) print('Your lastname of the author has only letters', check_isLetter_inLastname) check_isNumber_inPages = str.isnumeric(pages_number) print('Your number of pages has only numbers', check_isNumber_inPages) seq = (book_tittle, lastname_of_author, pages_number) s = " " book = s.join(seq) print('All data into one string:', book) char_lenght = len(book) print("Total amount of chars:", char_lenght)
137638cb6c3ee7cd32d6d183e2bc898e1a2c8bd1
marczakkordian/python_code_me_training
/04_functions_homework/10.py
1,605
4.125
4
# Stwórz grę wisielec “bez wisielca”. # Komputer losuje wyraz z dostępnej w programie listy wyrazów. # Wyświetla zamaskowany wyraz z widoczną liczbą znaków (np. ‘- - - - - - -‘) # Użytkownik podaje literę. # Sprawdź, czy litera istnieje w wyrazie. Jeśli tak, wyświetl mu komunikat: # “Trafione!” oraz napis ze znanymi literami. # W przeciwnym wypadku pokaż komunikat: # “Nie trafione, spróbuj jeszcze raz!”. # Możesz ograniczyć liczbę prób do np. 10. import random words = ['python', 'java', 'science', 'computer', 'testing', 'learning'] secret_word = random.choice(words) print(secret_word) usr_guesses = '' word = '' fails = 0 def show_word_to_user(word, secret_word, usr_guesses, fails): turns = 0 while turns < 10: for i, char in enumerate(secret_word): if char in usr_guesses: word = word[:i] + char else: word = word[:i] + ''.join(char.replace(char, '- ')) fails += 1 print(word) word = '' if fails == 0: print("You Win") print(f'The correct word is: {secret_word}') break usr_guess = input("Type your letter: ").strip() usr_guesses += usr_guess if usr_guess in secret_word: print("Well done!") else: turns += 1 print("Sorry, try again!") print(f'You have {10 - turns} more guesses') if turns == 10: print("You Loose") if __name__ == '__main__': show_word_to_user(word, secret_word, usr_guesses, fails)
9132918faa63a4d2c62f1fb2a50b0c421797c217
marczakkordian/python_code_me_training
/01_types_homework/06.py
1,794
3.90625
4
# Przekopiuj zawartość import this do zmiennej. # >>> import this # Policz liczbę wystąpień słowa better. # Usuń z tekstu symbol gwiazdki # Zamień jedno wystąpienie explain na understand # Usuń spacje i połącz wszystkie słowa myślnikiem # Podziel tekst na osobne zdania za pomocą kropki s = "The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than " \ "implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than " \ "nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren\'t special enough to break " \ "the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly " \ "silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably " \ "only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you\'re Dutch.\nNow " \ "is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to " \ "explain, it\'s a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces " \ "are one honking great idea -- let\'s do more of those! " print(s) print(type(s)) print(len(s)) # 1 count appearance of 'better' counter = s.count('better') print('#1', 'better', counter) # 2 remove '*' character s_2 = s.replace('*', '') print('#2', s_2, '*', counter) # 3 change one occurrence of 'explain' to 'understand' s_3 = s.replace('explain', 'understand', 1) print('#3', s_3) # 4 remove spaces and replace them '-' character s_4 = s.replace(' ', '-') print('#4', s_4) # 5 split text using '.' separator s_5 = s.split('.') print('#5', s_5)
03f803d4d6528c47286a810901e4481e5185fd3e
marczakkordian/python_code_me_training
/10_OOP_concepts/05.py
1,097
3.75
4
# Stwórz abstrakcyjną klasę Pojazdy. Utwórz potomne klasy pojazdy np. Samochód, Rower, Autobus, Ciężarówki. # Dodaj opisy zgodne z tym jak te pojazdy są klasyfikowane. # Jaki rodzaj dokumentu jest potrzebny, by kierować poszczególnym pojazdem. from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmethod def description(self): pass @abstractmethod def show_license(self): pass class Car(Vehicle): license = 'B' def description(self): print("I've got 4 wheels and i cant weight over 3,5 tonnes") class Bike(Vehicle): license = 'None' def description(self): print("I've got 2 wheels and a pedals!") class Bus(Vehicle): license = 'D or D/E or D1 or D1+E' def description(self): print("I've got 4 wheels and can take more than 7 passengers!") class Truck(Vehicle): license = 'C or C+E' def description(self): print("I've got 4 or 6 wheels and can take a lot of cargo!") BMW = Car() BMW.description() print(f"You need license of {BMW.license} category to drive me")
66c416b409954077d2abed35fec39fe267cb176c
marczakkordian/python_code_me_training
/01_types/string.py
503
3.890625
4
# 1 result = str.isnumeric("1232a323") print(result) # 2 result2 = str.center("Python", 15, "*") print(result2) # 3 result3 = "Remove_this_string".strip("ing") print(result3) # 4 # 5 # 1.1 quote = 'Honesty is the first chapter in the book of wisdom.' print(len(quote)) print(quote[-7:-1]) middle = len(quote) // 2 print(middle) print(quote[0:middle]) print(quote[-1]) print(quote[middle::3]) print(quote[0::2]) print(quote[::-2]) print(quote[::-1]) print(quote.replace("wisdom", "friendship"))
1610aa340e7429d1ba3116f31461f592b3a3cf78
marczakkordian/python_code_me_training
/05_files_homework/02.py
375
3.53125
4
import os filename = 'example.txt' def create_or_overwrite_file(file): with open(filename, 'w+') as fopen: usr_range = int(input('Type the number of lines: ')) for i in range(usr_range): fopen.write("This is line %d\r\n" % (i + 1)) return os.stat(filename).st_size print('Size of file in bytes: ', create_or_overwrite_file(filename))
3ae6677865a6e401ad34555877857f480b6454cb
marczakkordian/python_code_me_training
/02_flow_homework/02_summary/02.py
602
3.9375
4
# Pobierz od użytkownika dowolny tekst i wyświetl tylko te znaki, które są na pozycjach parzystych. # Wykonaj na dwa sposoby - za pomocą pętli oraz przez sting slicing ( ‘abrakadabra’ -> ‘baaar’). import re usr_input = input('Type your string: ') cleaned_input = re.sub('[^A-Za-z]', '', usr_input.strip()) print('String slicing ==>', cleaned_input[1::2]) counter = 1 str_result = '' for name in cleaned_input: if counter % 2 == 0: counter = counter + 1 str_result = str_result + name else: counter = counter + 1 print(f'Loop result ==> {str_result}')
70507218fe55d8d425f4e88b82ab10ca08852538
marczakkordian/python_code_me_training
/03_collections_homework/03_dictionary/09.py
799
3.953125
4
# 5 użytkowników poproś o podanie 4 przedmiotów szkolnych, sprawdź czy przedmioty powtarzają się na listach. # Wyświetl najpopularniejszy przedmiot. (Uwzględnij fakt, że użytkownicy mogą zapisać przedmioty małymi, # drukowanymi lub zaczynając od dużej litery) import re import sys usr_num = 1 item_table = [] res_table = [] while usr_num <= 5: usr_input = input(f'User {usr_num} | Type your 4 school items and use semicolon as a separator : ').casefold().strip().split(';') for item in usr_input: item_table.append(item) usr_num = usr_num + 1 for element in item_table: count = item_table.count(element) temp = element, count res_table.append(temp) print(f'Most popular item with the number of occurrence is {max(res_table, key=lambda x: x[1])}')
4ebabef297dd4146c39908d9bcad7b5b2dddea81
tanay46/Code-eval
/src/SumDigits.py
289
3.75
4
''' Created on Jul 12, 2011 Given a positive integer, find the sum of its constituent digits. @author: tanay ''' from sys import argv f = open(argv[1]) text = f.readlines() for line in text: n = int(line) total = 0 while n>0: total+=n%10 n=n/10 print total
48c4f525c65c75bf3108786b0cc450a640c8090d
tanay46/Code-eval
/src/reverseSentence.py
367
3.625
4
''' Created on Jul 12, 2011 @author: tanay ''' from sys import argv f = open(argv[1]) text = f.readlines() for line in text: line= line.strip() if line != '': sentence = '' words = line.split(' ') words.reverse() for word in words: sentence+=' '+ word sentence = sentence.strip() print sentence
6795c4e6e07de121d7dce93da430830b71f0cb3e
akoschnitzki/Module-4
/branching-Lab 4.py
884
4.375
4
# A time traveler has suddenly appeared in your classroom! # Create a variable representing the traveler's # year of origin (e.g., year = 2000) # and greet our strange visitor with a different message # if he is from the distant past (before 1900), # the present era (1900-2020) or from the far future (beyond 2020). year = int(input("Greetings! What is your year of origin?")) # Add the missing quotation mark and an extra equal sign. ''' if year < 1900: ''' if year <= 1900: # Add the missing colon. print("Woah, that's the past!") # Add the missing quotation marks. '''elif year >= 1900 and year < 2020 : ''' elif year >= 1900 and year <= 2020: # Must add the word and to make the statement run. print("That's totally the present!") '''else: ''' elif year >= 2020: # Add the statement to print the years that are in the future. print("Far out, that's the future!!")
d8fae23b0d84264e3e62eb9b4051f60fe598ddf2
Ginju2019/Data_Science_Casestudy_Project2_S8_15_18
/piggy_bank.py
3,760
4.28125
4
import math class PiggyBank: #Pigg Bank def __init__(self): # initialize Piggy Bank current balance to zero self.balance_amt = 0 def addMoney(self, deposit_amount): """ Add the user deposited amount with current balance Parameters: deposit_amount (float): User deposited amount """ self.balance_amt = self.balance_amt + deposit_amount def withdrawMoney(self, withdraw_amount): """ Subtract the user withdrawal amount from current balance Parameters: withdraw_amount (float): User withdrawal amount """ self.balance_amt = self.balance_amt - withdraw_amount def getCurrentBalance(self): """ Return the Piggy Bank current balance Returns: float:balance_amt """ return self.balance_amt class Error(Exception): """Base class for other exceptions""" pass class WithdrawError(Error): """Raised when the withdrawal amount is more than account balance""" pass class NewPiggyBank(PiggyBank): def withdrawMoney(self, withdraw_amount): """ Overridden method - Subtract the user withdrawal amount from current balance with check for sufficient balance Parameters: withdraw_amount (float): User withdrawal amount """ if (self.balance_amt - withdraw_amount) > 0: self.balance_amt = self.balance_amt - withdraw_amount else: raise WithdrawError #Exception('Overdraft withdrawal Error. Cannot withdraw more than amount in account balance: {}'.format(self.balance_amt)) # main code print(" ") print("--------------------Start-------------------") piggyBankObj = NewPiggyBank() while True: print(" ") app_init = input("Start or End : ") if app_init.strip().lower() == "start": user_action = input("Add, Withdraw or Check : ") if user_action.strip() == "Add": print(" ") deposit = float(input("Add amount : ")) print(" ") piggyBankObj.addMoney(deposit) print("After adding, your updated balance is " + str(piggyBankObj.getCurrentBalance()) + " rupees") print("None") continue elif user_action.strip() == "Withdraw": print(" ") withdraw = float(input("withdraw amount: ")) print(" ") try: piggyBankObj.withdrawMoney(withdraw) print("After withdrawing, balance amount is " + str(piggyBankObj.getCurrentBalance()) + " rupees") print("None") except WithdrawError: print("Overdraft Withdrawal Error. Cannot withdraw amount that is more than your account balance amount") print("Your withdrawal amount is " + str(withdraw) + " rupees") print("Your current balance is " + str(piggyBankObj.getCurrentBalance()) + " rupees") print(" ") continue elif user_action.strip() == "Check": print(" ") print("Your current balance is " + str(piggyBankObj.getCurrentBalance()) + " rupees") print("None") continue else : print(" ") print("Invalid Input.Try again") continue elif app_init.strip() == "End" : print(" ") print("------------Program Ended-----------") print(" ") break else : print(" ") print("Invalid Input. Try again") continue
f0d8bcdd6544d7ac2f672244e1b6dec60486ebbe
andredoumad/DataStructuresAndAlgorithms
/MaxHeap.py
3,510
3.5625
4
# Andre Doumad import unittest, random # MaxHeap class MaxHeap(object): # heap def __init__(self): self.heap = [] # get parent index def getParent(self, i): return int((i-1)/2) # get left index def getLeft(self, i): return 2*i+1 # get right index def getRight(self, i): return 2*i+2 # has parent def hasParent(self, i): return self.getParent(i)>=0 # has left def hasLeft(self, i): return self.getLeft(i)<len(self.heap) # has right def hasRight(self, i): return self.getRight(i)<len(self.heap) # heapifyUp def heapifyUp(self, i): while self.hasParent(i) and self.heap[self.getParent(i)] < self.heap[i]: self.swap(i, self.getParent(i)) i = self.getParent(i) # heapifyDown def heapifyDown(self, i): while self.hasLeft(i): max_child_index = self.getMaxChildIndex(i) if max_child_index == -1: break if self.heap[max_child_index] > self.heap[i]: self.swap(i, max_child_index) i = max_child_index else: break # getMaxChildIndex def getMaxChildIndex(self, i): if self.hasLeft(i): left_index = self.getLeft(i) if self.hasRight(i): right_index = self.getRight(i) if self.heap[left_index] >= self.heap[right_index]: return left_index else: return right_index else: return -1 else: return -1 # swap def swap(self, a, b): self.heap[a], self.heap[b] = self.heap[b], self.heap[a] # popMax def popMax(self): if len(self.heap) == 0: return -1 root = 0 last_index = len(self.heap)-1 self.swap(0, last_index) root = self.heap.pop() self.heapifyDown(0) return root # push def push(self, key): if len(self.heap) ==0: self.heap.append(key) return self.heap.append(key) self.heapifyUp(len(self.heap)-1) # peek def peek(self): if len(self.heap)==0: return None else: self.heapifyDown(0) return self.heap[0] def printHeap(self): print(str(self.heap)) # unittest class unitTest(unittest.TestCase): def test_0(self): heap = MaxHeap() for i in range(0, 15): heap.push(random.randrange(0,150)) maxValue = 0 while maxValue != -1: print('') heap.printHeap() maxValue = heap.popMax() print(str(maxValue)) if __name__ == "__main__": unittest.main() ''' OUTPUT: [144, 140, 139, 75, 78, 122, 116, 30, 52, 30, 23, 20, 75, 81, 60] 144 [140, 78, 139, 75, 60, 122, 116, 30, 52, 30, 23, 20, 75, 81] 140 [139, 78, 122, 75, 60, 81, 116, 30, 52, 30, 23, 20, 75] 139 [122, 78, 116, 75, 60, 81, 75, 30, 52, 30, 23, 20] 122 [116, 78, 81, 75, 60, 20, 75, 30, 52, 30, 23] 116 [81, 78, 75, 75, 60, 20, 23, 30, 52, 30] 81 [78, 75, 75, 52, 60, 20, 23, 30, 30] 78 [75, 60, 75, 52, 30, 20, 23, 30] 75 [75, 60, 30, 52, 30, 20, 23] 75 [60, 52, 30, 23, 30, 20] 60 [52, 30, 30, 23, 20] 52 [30, 20, 30, 23] 30 [30, 20, 23] 30 [23, 20] 23 [20] 20 [] -1 . ---------------------------------------------------------------------- Ran 1 test in 0.001s OK '''
196b3dd4caed879919bab15e240794b92b5e1a3d
harrypotter0/Python-web-development
/assignments/akash.py
758
3.609375
4
# To run this, you can install BeautifulSoup # https://pypi.python.org/pypi/beautifulsoup4 # Or download the file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') # Retrieve all of the anchor tags spans = soup('span') s=0 numbers = [] for span in spans: print(int(span.string)) for span in spans: numbers.append(int(span.string)) for j in numbers : s=s+j print(s)
7fdd1016be8cc57629a8b1a2ce577d608fd8702b
wilfredgithuka/learn-python-the-hard-way
/ex13.py
412
3.609375
4
#Wilfred Githuka #Githuka.com #31 December 2016 #Exercise 13 from sys import argv #script, first, second, third = argv #fname, idno, age, weight = argv #name = raw_input ("Name") #idno = raw_input ("ID-No?") #age = raw_input ("age?") #weight = raw_input ("weight?") name, idno, age, weight = argv print "Your name is:", name print "Your ID number is:", idno print "Your age is:", age print "Your weight is:", weight
5a954acd1407b5c802cc4064cde5883515f972d3
atupal/codeforces
/contests/286_DIV2/ts.py
361
3.640625
4
# -*- coding: utf-8 -*- import sys reload(sys) #sys.setdefaultencoding("utf-8") s = input().strip() # columm是w位的字符串 for i in range(len(s)+1): for j in range(26): l = [ _ for _ in s ] l.insert(i, chr( ord('a') + j)) if ''.join( l[:len(l)/2] ) == ''.join( l[::-1][:len(l)/2] ): print (''.join(l)) exit(0) print ('NA')
fd4a6cca1323eb6439f3d3aa8548bb206f521d8d
jreis22/card_games
/src/core/cards/card.py
914
3.609375
4
from card_game_logic.cards.card_enums import Suit, Rank class PlayingCard(object): def __init__(self, suit: Suit, rank: Rank): self.suit = suit self.rank = rank def same_suit(self, other_card): if isinstance(other_card, PlayingCard): return other_card.suit == self.suit return False def is_greater(self, other_card, comparator): if isinstance(other_card, PlayingCard): return comparator(self, other_card) return False def __eq__(self, other_card): if isinstance(other_card, PlayingCard): return self.suit == other_card.suit and self.rank == other_card.rank return False def __str__(self): return self.rank.name + ' of ' + self.suit.name #card1 = PlayingCard(suit=Suit.HEARTS, rank=Rank.ACE) #print(card1) # card2 = PlayingCard(suit=Suit.HEARTS, rank=Rank.KING)
951e9e2022aa94ef5708f128238ed9b7835aee52
Tanya-Kr/python_simle_tasks
/task10/test.py
1,822
3.703125
4
import unittest from unittest import TestCase, main, TestSuite from package.task10 import calculation class AddTest(TestCase): def test_all_args_more_zero(self): num1 = 3 num2 = 5 expected = 8 actual = calculation.add(num1, num2) self.assertEqual(expected, actual) def test_all_args_less_zero(self): num1 = -3 num2 = -5 expected = -8 actual = calculation.add(num1, num2) self.assertEqual(expected, actual) def test_one_arg_less_zero(self): num1 = 3 num2 = -5 expected = -2 actual = calculation.add(num1, num2) self.assertEqual(expected, actual) class SubtractTest(TestCase): def test_all_args_more_zero(self): num1 = 3 num2 = 5 expected = -2 actual = calculation.subtract(num1, num2) self.assertEqual(expected, actual) def test_all_args_less_zero(self): num1 = -3 num2 = -5 expected = 2 actual = calculation.subtract(num1, num2) self.assertEqual(expected, actual) def test_one_arg_less_zero(self): num1 = 3 num2 = -5 expected = 8 actual = calculation.subtract(num1, num2) self.assertEqual(expected, actual) def suite_one_arg_less_zero(): suite = unittest.TestSuite() suite.addTest(AddTest.test_one_arg_less_zero) suite.addTest(SubtractTest.test_one_arg_less_zero) return suite def suite_all_args_more_zero(): suite = unittest.TestSuite() suite.addTest(AddTest.test_all_args_more_zero) suite.addTest(SubtractTest.test_all_args_more_zero) return suite if __name__ == '__main__': unittest.TextTestRunner().run(suite_one_arg_less_zero()) unittest.TextTestRunner().run(suite_all_args_more_zero())
53303f7123bbd2c1b2f8c07d9002bae85f3cb81a
TrevAnd1/Sudoku-Puzzle-Solver
/Sudoku/Sudoku Puzzle Solver.py
1,725
4.15625
4
import pygame import random from pygame.locals import ( K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, K_RIGHT, K_LEFT, K_UP, K_DOWN, K_KP_ENTER, K_ESCAPE, KEYDOWN, QUIT, ) WHITE = (0,0,0) SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 1000 # TODO : get user input to see how many numbers they want to start with given on the board and use that number in line 54 in a 'for' loop to interate through 'board' as many times as the user wants in their input class Board: board = [ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], ] def __init__(self): pass def drawBackground(self): # use pygame.draw.line() to make lines for the board pass def initializeBoard(self): # set 0's in board to random numbers between one and 10 so that they can be solved rand_row = random.randint(0,8) rand_col = random.randint(0,8) self.board[rand_row][rand_col] = random.randint(1,9) # TODO : check if the spot that it randomly chooses already has a number in it (if board[rand_row][rand_col] != 0) pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) running = True while running: screen.fill((WHITE)) for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False
89f9b01bac89aff46326b94b18d0837935166b24
dyb-py/pk
/com/baizhi/杜亚博作业/asda.py
3,555
3.59375
4
# def f1(): # a=[1,2] # return a # a=[1,2] # a.append(f1()[1]+f1()[0]) # print(a) # def f1(s,t,m,n): # if n==1: # print('%s-->%s'%(s,t)) # else: # #n-1 a-->c # f1(s,m,t,n-1) # #a-->b # print('%s-->%s'%(s,t)) # #n-1 c-->b # f1(m,t,s,n-1) # f1('a','b','c',3) # def f1(n): # if n==1: # n=0 # return 0 # elif n==2: # n=1 # return 1 # else: # n=f1(n-2)+f1(n-1) # return n # n=int(input('asd')) # for i in range(1,n+1): # print(f1(i),end=' \t') # class A(): # a=1 # b=2 # s1=A() # s1.a=3 # s2=A() # print(s1.a,s2.a) # A.a=5 # print(s1.a,s2.a) # A.b=6 # print(s1.b,s2.b) # def fun(s): # global start # start=time.time() # return s # # @fun # def main(): # for i in range(10000): # print('hello') # end=time.time() # print(end-start) # main() # def fun(s): # global start # start=time.time() # def f2(): # for i in range(10000): # print('hello') # end = time.time() # print(end - start) # return f2 # # @fun # def main(): # pass # main() # class Plug: # def __init__(self): # self.methods=[] # def plugIn(self,obj): # for method in self.methods: # obj.__dict__[method.__name__]=method # def plugOut(self,obj): # for method in self.methods: # del obj.__dict__[method.__name__] # class A(Plug): # def __init__(self): # super().__init__() # self.methods.append(self.p) # def p(self): # print('ppppp') # class B: # pass # a=A() # b=B() # a.plugIn(b) # b.p() # def f(a): # print(a) # def f1(f): # print('f1f1') # return f # return f1 # @f('aa') # def a(): # print('a') # a() # class F1(): # def __init__(self,f): # self.f=f # def __call__(self, *args, **kwargs): # print('f1') # return self.f() # @F1 # def a(): # print('aaa') # a() # import time # class Fun: # def __init__(self,f): # self.f=f # def __call__(self): # start=time.time() # self.f() # print(time.time()-start) # return # @Fun # import threading # import queue # import random # import time # l=[] # def send(name,q): # while 1: # n=random.randint(1,1000) # q.put(n) # print('{}说:这是数字{}'.format(name,n)) # r=q.get() # l.append(r) # time.sleep(2) # def rec(name): # count=0 # while 1: # r=l[count] # print('{}收到: 这是数字{}'.format(name,r)) # count+=1 # time.sleep(1) # # time.sleep() # if __name__=='__main__': # q=queue.Queue() # t1=threading.Thread(target=send,args=('老王',q),daemon=True) # t2=threading.Thread(target=send,args=('老赵',q),daemon=True) # t3=threading.Thread(target=send,args=('老钱',q),daemon=True) # t4=threading.Thread(target=rec,args=('老王',),daemon=True) # t5=threading.Thread(target=rec,args=('老赵',),daemon=True) # t6=threading.Thread(target=rec,args=('老钱',),daemon=True) # # t1.start() # t2.start() # t3.start() # t4.start() # t5.start() # t6.start() # # time.sleep(7) # def zhi(): # count=99 # while 1: # count += 1 # f=0 # for i in range(2,int(count**0.5)+1): # if count%i==0: # f=1 # if f==0: # yield count # a=zhi() # while 1: # print(next(a))
55ab453d18e2b12b64378fd70fc3843ec169eb29
Deepak10995/node_react_ds_and_algo
/assignments/week03/day1-2.py
901
4.4375
4
''' Assignments 1)Write a Python program to sort (ascending and descending) a dictionary by value. [use sorted()] 2)Write a Python program to combine two dictionary adding values for common keys. d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300}) ''' #ques 1 d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} def sorted_dict_increasing(d1): sorted_d1 = sorted(d1.items(),key= lambda x: x[1]) print(sorted_d1) sorted_d1 = sorted(d1.items(),key= lambda x: x[1],reverse=True) print(sorted_d1) return sorted_d1 sorted_dict_increasing(d1) # Ques 2 from collections import Counter d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} def dict_combine(d1,d2): d_combine = Counter(d1) + Counter(d2) print(d_combine) return d_combine dict_combine(d1,d2)
24f3091c067759e7cde9222bfb761a777da668df
Deepak10995/node_react_ds_and_algo
/coding-challenges/week06/day-1.py
2,263
4.28125
4
''' CC: 1)Implement Queue Using a linked list ''' #solution class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.last = None def enqueue(self, data): if self.last is None: self.head = Node(data) self.last = self.head else: self.last.next = Node(data) self.last = self.last.next def dequeue(self): if self.head is None: return None else: to_return = self.head.data self.head = self.head.next return to_return a_queue = Queue() while True: print('enqueue <value>') print('dequeue') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'enqueue': a_queue.enqueue(int(do[1])) elif operation == 'dequeue': dequeued = a_queue.dequeue() if dequeued is None: print('Queue is empty.') else: print('Dequeued element: ', int(dequeued)) elif operation == 'quit': break ''' 2)Implement Stack using a linked list ''' #solution class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def push(self, data): if self.head is None: self.head = Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node def pop(self): if self.head is None: return None else: popped = self.head.data self.head = self.head.next return popped a_stack = Stack() while True: print('push <value>') print('pop') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'push': a_stack.push(int(do[1])) elif operation == 'pop': popped = a_stack.pop() if popped is None: print('Stack is empty.') else: print('Popped value: ', int(popped)) elif operation == 'quit': break
9281945408c7377a7849bcc0bfffeb9e912df0bd
Deepak10995/node_react_ds_and_algo
/assignments/week03/day3-4.py
836
3.625
4
''' Assignment: c) https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem d) https://www.hackerrank.com/challenges/list-comprehensions/problem ''' # Ques (c) # find second maximum number def runner_up(n,arr): if n == 0 : return false else: sorted_arr = sorted(arr,reverse = -1) for i in range(len(sorted_arr)): if sorted_arr[i] != sorted_arr[i+1]: print (sorted_arr[i+1]) break else: continue if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) runner_up(n,arr) # Ques (d) # list-comprehensions def list_comprehension(x,y,z): arr = list([[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if ((i+j+k) != n)]) print(arr) list_comprehension(x,y,z)
94012a1a44d78faf11cfd7230fd10d694cf846ef
Deepak10995/node_react_ds_and_algo
/assignments/week04/day1-2.py
883
3.796875
4
''' Assignments 1) https://www.hackerrank.com/challenges/countingsort4/problem ''' #counting sort #!/bin/python3 import math import os import random import re import sys # Complete the countSort function below. def countSort(arr,n): count = 0 count_sort = 0 sorted_arr = list() string = '' for items in arr: if int(items[0]) > int(count_sort): count_sort = int(items[0]) if count < n/2: items[1] ='-' count += 1 for i in range(0,count_sort+1): sorted_arr.append([]) for items in arr: sorted_arr[int(items[0])].append(items[1]) for i in sorted_arr: for j in i: string += j+' ' print(string) if __name__ == '__main__': n = int(input().strip()) arr = [] for _ in range(n): arr.append(input().rstrip().split()) countSort(arr,n)
dc20ed1e85f83f4b9e1af3bcb1eeb40f7848f43f
ccappelle/TreebotFrontiers
/3by3/object.py
913
3.53125
4
SPHERE=0 CUBE = 1 BIG=0 SMALL = 1 def CreateSphere(posVec,radius,sizeType): #Create sphere object in one of three positions obj = CreateObject(posVec,SPHERE,radius,sizeType) return obj def CreateCube(posVec,length): obj = CreateObject(posVec,CUBE, length) return obj def CreateObject(posVec, myType, length,sizeType): obj = {} obj['length']=length obj['type'] = myType obj['x']=posVec[0] obj['y']=posVec[1] obj['z']=posVec[2] obj['sizeType'] = sizeType return obj def ChangeType(obj, newType): obj['type'] = newType return obj def ChangeLength(obj,newLength): obj['length']=newLength return obj def Save(obj,f): #Write sphere paramaters out to file f.write('(') f.write(str(obj['sizeType'])) f.write(',') f.write(str(obj['length'])) f.write(',') f.write(str(obj['x'])) f.write(',') f.write(str(obj['y'])) f.write(',') f.write(str(obj['z'])) f.write(',') f.write(')')
99ffabbbe487fb2b30fff35ef5b84ec832545227
ryanhofmann/ASTR5550
/hw3/hw3.py
3,517
3.53125
4
#!/usr/bin/env python3 import numpy as np from scipy import integrate from scipy import interpolate import matplotlib.pyplot as plt def f(x, p=2): """ Distribution function """ return x**(-p) def x(a, p=2): """ Inverse transform function """ return ((-p + 1)*a + 1)**(1/(-p + 1)) def P(k, lam=10): """ Poisson distribution function """ return lam**k*np.exp(-lam)/np.math.gamma(k+1) def rand_P(lam=10): """ Poisson RNG function Returns x(alpha) """ x = np.linspace(0,20,1000) y = [P(i) for i in x] alpha = integrate.cumtrapz(y, x, initial=0) x_int = interpolate.interp1d(alpha, x, fill_value='extrapolate') return x_int if __name__=="__main__": # Explicitly initialize RNG np.random.seed(42) # Problem 2 # Numerically integrate f(x) to obtain alpha x_sup = np.linspace(1,100,num=1000) alpha = integrate.cumtrapz(f(x_sup), x_sup, initial=0) # Interpolate alpha x_int = interpolate.interp1d(alpha, x_sup, fill_value='extrapolate') # Draw 10^5 random numbers in [0,1) N = 100000 a = np.random.rand(N) # Transform the uniform random numbers to the PDF x_an = x(a) a = np.random.rand(N) x_num = x_int(a) # Create analytic histograms bins = np.arange(100) + 1. y = N*bins**-2 figsize = (8,4) plt.figure(figsize=figsize) plt.subplot(121) plt.hist(x_an, bins=bins, color='blue') plt.plot(bins, N*f(bins), '-r', linewidth=2) plt.subplot(122) plt.hist(x_an, bins=bins, color='blue') plt.plot(bins, N*f(bins), '-r', linewidth=2) plt.loglog() plt.tight_layout() plt.savefig("analytic.eps") plt.savefig("analytic.png") plt.clf() # Create numerical histograms plt.figure(figsize=figsize) plt.subplot(121) plt.hist(x_num, bins=bins, color='blue') plt.plot(bins, N*f(bins), '-r', linewidth=2) plt.subplot(122) plt.hist(x_num, bins=bins, color='blue') plt.plot(bins, N*f(bins), '-r', linewidth=2) plt.loglog() plt.tight_layout() plt.savefig("numerical.eps") plt.savefig("numerical.png") plt.clf() # Problem 3 # Draw 10^5 random numbers from Poisson distribution x_int = rand_P() # Creates lookup table for x(alpha) a = np.random.rand(N) k = x_int(a) # Transforms uniform randoms to distribution # Create histogram 1 bins = np.arange(100)/5. y = np.array([N*P(i) for i in bins]) plt.figure(figsize=figsize) plt.subplot(121) plt.hist(k, bins=bins, color='blue') plt.plot(bins, y/5., '-r', linewidth=2) ax = plt.subplot(122) ax.hist(k, bins=bins, color='blue') ax.plot(bins, y/5., '-r', linewidth=2) ax.set_yscale("log") plt.tight_layout() plt.savefig("P1.eps") plt.savefig("P1.png") plt.clf() # Create histogram 2 k_np = np.random.poisson(lam=10, size=N) plt.figure(figsize=figsize) plt.subplot(121) plt.hist(k_np, bins=bins, color='blue') plt.plot(bins, y, '-r', linewidth=2) ax = plt.subplot(122) ax.hist(k_np, bins=bins, color='blue') ax.plot(bins, y, '-r', linewidth=2) ax.set_yscale("log") plt.tight_layout() plt.savefig("P2.eps") plt.savefig("P2.png") plt.clf() # Create histogram 3 a = np.random.rand(N) k = np.rint(x_int(a)) y = np.array([N*P(i) for i in bins]) plt.figure(figsize=figsize) plt.subplot(121) plt.hist(k, bins=bins, color='blue') plt.plot(bins, y, '-r', linewidth=2) ax = plt.subplot(122) ax.hist(k, bins=bins, color='blue') ax.plot(bins, y, '-r', linewidth=2) ax.set_yscale("log") plt.tight_layout() plt.savefig("P3.eps") plt.savefig("P3.png") plt.clf()
de19e44159a2ee8e49ed30eeaf405faa82f2e881
RiEnRiu/rer_learning_code
/interview/huffman_encode.py
3,139
3.984375
4
# a node is a dict with keys={'depth', 'weight', 'sub_trees'} # it is a leaf node if node['sub_trees'] is a weight value but not a list # 'depth' means the depth of this tree # 'weight' means the sum of all leaves in this tree # 'sub_trees' means all its children def _find_new_node_index(other_nodes,new_node): if len(other_nodes)<=2: for i in range(len(other_nodes)-1,-1,-1): this_node = other_nodes[i] if this_node['weight']>new_node['weight']: return i+1 elif this_node['weight']==new_node['weight'] and this_node['depth']>=new_node['depth']: return i+1 return 0 half_index = len(other_nodes)//2+1 left_nodes = other_nodes[:half_index] right_nodes = other_nodes[half_index:] if left_nodes[-1]['weight']>new_node['weight'] or left_nodes[-1]['weight']==new_node['weight'] and left_nodes[-1]['depth']>=new_node['depth']: if new_node['weight']>right_nodes[0]['weight'] or new_node['weight']==right_nodes[0]['weight'] and new_node['depth']<=right_nodes[0]['depth']: return half_index else: found_right = _find_new_node_index(right_nodes,new_node) return found_right+half_index else: found_left = _find_new_node_index(left_nodes,new_node) return half_index-found_left def _insert_new_node(other_nodes,new_node): if new_node['weight']>other_nodes[0]['weight'] or new_node['weight']==other_nodes[0]['weight'] and new_node['depth']<=other_nodes[0]['depth']: other_nodes.insert(0,new_node) return if other_nodes[-1]['weight']>new_node['weight'] or other_nodes[-1]['weight']==new_node['weight'] and other_nodes[-1]['depth']>=new_node['depth']: other_nodes.insert(-1,new_node) return index = _find_new_node_index(other_nodes,new_node) other_nodes.insert(index,new_node) return def _make_new_node(k_c): weight = 0 max_depth = -1 for node in k_c: weight+=node['weight'] max_depth = max_depth if node['depth']<max_depth else node['depth'] tree = {'depth':max_depth+1,'weight':weight,'sub_trees':k_c} return tree def _combine_last_k_node(sort_c,k): if len(sort_c)<=k: return _make_new_node(sort_c) new_node = _make_new_node(sort_c[-k:]) other_nodes = sort_c[:-k] _insert_new_node(other_nodes,new_node) return other_nodes def _encede_lenth(tree): if type(tree['sub_trees'])!=list: return 0 sum_len = tree['weight'] for sub_tree in tree['sub_trees']: sum_len+=_encede_lenth(sub_tree) return sum_len def huffman_encode(n,k,c): # nlogn c.sort(reverse=True) c = [{'depth':0,'weight':v,'sub_trees':v} for v in c] # n * logn while(type(c)!=dict): c = _combine_last_k_node(c,k) print('balanced tree = {0}'.format(c)) # logn min_len_encoded, min_max_len_s = _encede_lenth(c), c['depth'] return min_len_encoded, min_max_len_s if __name__=='__main__': n = 4 k = 2 c = [1,1,2,2] print('ans = {0}'.format(huffman_encode(n,k,c)))
a729758b2b951b8c38983b7dd5336c8f36f933da
DajkaCsaba/PythonBasic
/4.py
293
4.53125
5
#4. Write a Python program which accepts the radius of a circle from the user and compute the area. Go to the editor #Sample Output : #r = 1.1 #Area = 3.8013271108436504 from math import pi r = float(input("Input the radius of the circle: ")) print("r = "+str(r)) print("Area = "+str(pi*r**2))
198ac0807066f80ab712f7b4d33d0f9376ccfda2
cordunandreea/Probleme-Olimpiada-Clasa-9
/problema1.py
127
3.578125
4
x=int(input('nr total de pasari de la ferma:')) g=x//2 r=g//4 gs=x-g-r print(g,'gaini') print(r,'rate') print(gs,'gaste')
a5c57237975d714e0fad9f8dcbae46f429c978c5
NatalyaMotuzenko/BD_Lab
/BD_lab1/Routes.py
4,830
3.625
4
class Routes(object): # инициализация def __init__(self): self.routes = [] # добавление записи def add(self, route): self.routes.append(route) # вывод всех записей на экран def __str__(self): fullInfo = "" for ind, route in enumerate(self.routes): fullInfo = fullInfo + str(ind) + ". " + str(route) + "_____________________\n" return fullInfo # дополнительная функция для вывода записи с учетом параметра def changeInfo(fullInfo, ind, route): fullInfo = fullInfo + str(ind) + ". " + str(route) + "_____________________\n" ind += 1 return (fullInfo, ind) # вывод записи с учетом параметра на экран def strParameter(self, parameter, index): fullInfo = "" ind = 0 for route in self.routes: # routeID if route.routeID == parameter and index == "1": fullInfo, ind = Routes.changeInfo(fullInfo, ind, route) break # wherefrom if route.wherefrom == parameter and index == "2": fullInfo, ind = Routes.changeInfo(fullInfo, ind, route) continue # where if route.where == parameter and index == "3": fullInfo, ind = Routes.changeInfo(fullInfo, ind, route) continue # distance if route.distance == parameter and index == "4": fullInfo, ind = Routes.changeInfo(fullInfo, ind, route) continue # time if route.time == parameter and index == "5": fullInfo, ind, = Routes.changeInfo(fullInfo, ind, route) continue return fullInfo def exist(self, parameter, ind): if ind == "1": # проверка существования routeID for route in self.routes: if route.routeID == parameter: return True return False if ind == "2": # проверка существования wherefrom for route in self.routes: if route.wherefrom == parameter: return True return False if ind == "3": # проверка существования where for route in self.routes: if route.where == parameter: return True return False if ind == "4": # проверка существования distance for route in self.routes: if route.distance == parameter: return True return False if ind == "5": # проверка существования time for route in self.routes: if route.time == parameter: return True return False # удаление записей по параметру def delete(self, parameter, index, plans): ind = 0 while ind < len(self.routes): # routeID if self.routes[ind].routeID == parameter and index == "1": plans.delete(self.routes[ind].routeID, "2") # удаление связанного плана self.routes.pop(ind) break # wherefrom if self.routes[ind].wherefrom == parameter and index == "2": plans.delete(self.routes[ind].routeID, "2") # удаление связанного плана self.routes.pop(ind) continue # where if self.routes[ind].where == parameter and index == "3": plans.delete(self.routes[ind].routeID, "2") # удаление связанного плана self.routes.pop(ind) continue ind += 1 # подсчет количества пропущеных записей # модификация записи, заданной ID def modification(self, routeID, parameter, index): for route in self.routes: if route.routeID == routeID: if index == 1: route.wherefrom = parameter break if index == 2: route.where = parameter break if index == 3: route.distance = parameter break if index == 4: route.time = parameter break def lastID(self): try: return self.routes[len(self.routes) - 1].routeID except: return 1
8b0f85f98616cbcb53b4071df7c04122e1f9edfb
gtvanderkin/CSC-227-Final-Project-Water
/waterReader.py
902
3.875
4
def calcharge(gal, br): # This function defines the cost calculation, and returns it # There are different rates for 'R'esidential or 'B'usiness rates if br == 'R': if gal <= 6000: return gal * 0.005 else: return (6000 * 0.005) + 0.007 * (gal - 6000) else: if gal <= 8000: return gal * 0.006 else: return (8000 * 0.006) + 0.008 * (gal - 8000) # Opens the file, and initiates a list to store the contents myfile = open("water.txt", 'r') waterlist = [] # copy the file's information to the list for line in myfile: tempid, tempbr, tempgal = line.split(" ") waterlist.append([tempid, tempbr, tempgal]) # Calculate and display each entry and the total cost for x in waterlist: print("Account number: " + x[0] + " | Water charge: $" + "{:.2f}".format(calcharge(int(x[2]), x[1]))) myfile.close()
f00fa5c5febcd13d2399ec516fff6cd786151af8
mustard-seed/graph_algo
/test_undirectedGraph.py
415
3.5625
4
import undirected_graph.graph as graph if __name__ == '__main__': num_vertices = 13 edges = [ [0, 5], [4, 3], [0, 1], [9, 12], [6, 4], [5, 4], [0, 2], [11, 12], [9, 10], [0, 6], [7, 8], [9, 11], [5, 3] ] g = graph.UndirectedGraph(num_vertices, edges) output = g.toString() print(output)
812a7add94f621c196f8c68bdcb467d09f77d823
and117117/infa_2019_and117117
/lab3/event_bind.py
998
3.765625
4
from tkinter import * from random import randrange as rnd, choice import time root = Tk() root.geometry('800x600') canv = Canvas(root, bg='white') canv.pack(fill=BOTH, expand=1) colors = ['red', 'orange', 'yellow', 'green', 'blue'] score = 0 def new_ball(): """ Draw new ball with random coordinates (x, y), random radius, random color """ global x, y, r canv.delete(ALL) x = rnd(100, 700) y = rnd(100, 500) r = rnd(30, 50) canv.create_oval(x - r, y - r, x + r, y + r, fill=choice(colors), width=0) root.after(1000, new_ball) def click(event): """ xo, yo, hypo - sides of triangle (xo ** 2) + (yo ** 2) = (hypo ** 2) Pythagoras' theorem """ global score xo = x - event.x yo = y - event.y hypo = (xo ** 2 + yo ** 2) ** 0.5 if hypo <= r: score += 1 print('GOAL', score) else: score -= 1 print('MISSED', score) new_ball() canv.bind('<Button-1>', click) root.mainloop()
3de713f7ca2f61358268815be48dbe7a217db2ee
wojtbauer/Python_challenges
/Problem_2.py
865
4.125
4
#Question 2 # Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 # Then, the output should be: # 40320 # Factorial = int(input("Wpisz liczbę: ")) # wynik = 1 # # #if/elif solution! - option 1 # if Factorial < 0: # print("Wstaw wartość nieujemną!") # elif Factorial == 0: # print("0! = 1") # else: # for i in range(1, Factorial+1): # wynik = wynik*i # print(Factorial, wynik) #while solution! - option 2 # while Factorial > 0: # wynik = wynik * Factorial # Factorial = Factorial - 1 # print(wynik) #Function solution - option 3 def Fact(x): if x == 0: return 1 elif x > 0: return x * Fact(x-1) x = int(input("Wpisz liczbę: ")) print(Fact(x))
00a1a499a91fd85e4f67bb908624dee7ae148227
ejh243/MunroeJargonProfiler
/jargonprofiler/munroe.py
3,712
4.09375
4
''' Calculate a 'Munroe' score - what proportion of the text comes from the 1000 most common words in English. ''' from . import util import re def get_common(): ''' Opens the text file containing the list of 1000 most common words found at http://www.ef.co.uk/english-resources/english-vocabulary/top-1000-words/ removes the newlines and returns them as a list. ''' from pkg_resources import resource_stream text = [] with resource_stream(__name__, '1000common.txt') as f: for line in f: # Common words should be lowercase for consistency! text.append(line.decode().strip().lower()) return text # Get the most common 1000 words from the file, storing this as a module member. # So we don't need to load it each time we calculate a score. common = get_common() # Stem the words so that they match the form of our tokens stemmed_common = set(util.stem(common)) def munroe_score(text, exclusions='', verbose=True): ''' Takes raw text, tokenises and stems it, and compares the stems to the set of the stemmed 1000 most common words Returns the percentage of words that were in the list of common words e.g. if output is 0.61, 61% of words were in the list of the 1000 most common. ''' # Process exclusions if exclusions != '': exclusions = util.lowercase(re.findall('\w+', exclusions)) else: exclusions = [] # Find all words - alphanumeric strings not separated by punctuation of 1+ length words = re.findall('\w+', text) # Keep a record of how we tagged each item tags = ['' for w in words] # Identify proper nouns proper_nouns = util.tag_proper_nouns(text) # Identify acronyms acronyms = util.find_acronyms(text) # Tokenise and stem the words. Mark proper nouns and non-alphabetic words in the tag list. tokens = [] for i, word in enumerate(words): # Check if the word is a proper noun. If it is, mark it and put an empty string in the list of tokens if word in proper_nouns: tokens.append('') tags[i] = 'proper noun' elif word.lower() in exclusions: tokens.append('') tags[i] = 'excluded' elif word in acronyms: tokens.append('') tags[i] = 'acronym' else: token = util.tokenise(word) # If there is more than one token, it means the word was broken by a number, In this case, ignore it # If there are no tokens, it means that there were no alphabetic characters in the token. Ignore it if len(token) != 1: tokens.append('') tags[i] = 'not alphabetic' else: # Stem the word tokens.append(util.stem(util.lowercase(token))[0]) # Count the number of tokens that are in the most common 1000 words munroe = 0 for i, t in enumerate(tokens): if t != '': if t in stemmed_common: munroe+=1 tags[i] = 'common' else: tags[i] = 'not common' if len([t for t in tokens if t != '']) == 0: score = 1.0 else: score = munroe/len([t for t in tokens if t != '']) # If verbose, return some printed output if verbose: print('You have '+ str(len(words)) + ' words in your document') print('Of these, '+str(munroe)+' are in the most common 1000 words!') print('Score: '+str(100*score)+'%') return_dict = { 'score': score, 'tagged_words': dict(zip(words,tags)) } return return_dict
6fd67b08209d819f2d502bb65b0a8bbb0413f7c5
Kexin6/zergProject
/Demo1/package3/class2.py
961
3.921875
4
class Student(object): sum = 0 #和类相关的变量 # name = 'Someone' # age = 0 #Constructor def __init__(self, name, age): self.name = name self.age = age self.score = 0 # self.__class__.sum += 1 # print("当前学生总数: " + str(self.__class__.sum)) def doHomework(self): self.sum += 1 print('Homework') print("Method中的sum:" + str(self.sum)) print('self.name: ' + self.name) def trial(self): Student.sum += 1 self.__class__.sum += 1 self.sum += 1 #没用 @classmethod def plusSum(cls): cls.sum += 1 print(cls.sum) #print(self.name) @staticmethod def add(x,y): print('This is static method') print(Student.sum) # print(self.name) def __marking(self, score): self.score = score print("This student's score is: " + str(self.score))
decf9fca45f23a75d59f49cbe0c3d9cc1a73ecb9
JNieswand/tetris
/main.py
7,819
3.609375
4
#main import numpy as np import copy import matplotlib.pyplot as plt global SIZE_X, SIZE_Y SIZE_X = 10 SIZE_Y = 20 def turn_coordinate(coordinate): turn_matrix = np.array([[0, 1],[-1, 0]]) new_coord = np.matmul(np.array([coordinate.x, coordinate.y]), turn_matrix) return Coordinate(new_coord[0], new_coord[1]) class Coordinate: def __init__(self,x, y): self.x = x self.y = y def is_equal(self, coordinate): return self.x == coordinate.x and self.y == coordinate.y def add(self, coordinate): return Coordinate(self.x + coordinate.x, self.y + coordinate.y) def substract(self, coordinate): return Coordinate(self.x - coordinate.x, self.y - coordinate.y) class Game: def __init__(self): self.board = Board() self.falling_block = FallingBlock(self.board) self.inputhandler = InputHandler(self.falling_block) self.drawer = Drawer(self.board, self.falling_block) self.inputhandler.connect_pressevent( self.drawer.fig, self.inputhandler.on_press) self.over = False def update(self): self.falling_block.fall() if self.falling_block.laying_time >=3: self.board.place_falling_block(copy.deepcopy(self.falling_block)) self.falling_block.reset() self.board.update() if self.board.full == True: self.over = True self.drawer.draw() def lost(self): self.drawer.message_loose() class Board: def __init__(self): self.array = np.zeros((SIZE_X, SIZE_Y)) self.full = False def at(self, coordinate): return self.array[coordinate.x, coordinate.y] def is_in(self, coordinate): if (coordinate.x < 0 or coordinate.x >= SIZE_X or coordinate.y <0 or coordinate.y >= SIZE_Y): return False return True def place_falling_block(self, falling_block): for coord in falling_block.get_coordinates(): self.place_brick(coord) def place_brick(self, coordinate): self.array[coordinate.x, coordinate.y] = 1 def remove_brick(self, coordinate): self.array[coordinate.x, coordinate.y] = 0 def remove_row(self, index): self.array[:, 1:index +1] = self.array[:, 0:index] self.array[:, 0] = 0 def update(self): for index in np.arange(SIZE_Y): if np.sum(self.array[:, index]) == SIZE_X: self.remove_row(index) if np.sum(self.array[:, 0]) > 0: self.full = True class FallingBlock: def __init__(self, board): self.board = board self.reset() def reset(self): self.coordinate = Coordinate(int(SIZE_X/2), 0) geometries = np.array(["block", "t", "l", "l_inverted", "z", "z_inverted", "I"]) index = np.random.randint(geometries.size) self.geometry = get_falling_block_geometry(geometries[index]) self.laying_time = 0 def get_coordinates(self): return np.array([ self.coordinate.add(geometry_coord) for geometry_coord in self.geometry]) def fall(self): if self.can_move_to("down"): self.coordinate.y += 1 self.laying_time = 0 else: self.laying_time += 1 def local_to_global(self, coord): return coord.add(self.coordinate) def global_to_local(self, coord): return coord.substract(self.coordinate) def turn(self): turned_geometry = np.array([]) for coord in self.geometry: turned_geometry = np.append(turned_geometry, turn_coordinate(coord)) for moved_coord in turned_geometry: if not self.board.is_in(self.local_to_global(moved_coord)): return False if not self.board.at(self.local_to_global(moved_coord)) == 0: return False self.geometry = copy.deepcopy(turned_geometry) return True def move_left(self): if self.can_move_to("left"): self.coordinate.x -=1 def move_right(self): if self.can_move_to("right"): self.coordinate.x += 1 def can_move_to(self, direction): moved_coordinates = np.array([]) if direction == "left": moved_coordinates = np.array([Coordinate( coord.x -1, coord.y) for coord in self.get_coordinates()]) elif direction == "right": moved_coordinates = np.array([Coordinate( coord.x +1, coord.y) for coord in self.get_coordinates()]) elif direction == "down": moved_coordinates = np.array([Coordinate( coord.x, coord.y +1) for coord in self.get_coordinates()]) else: print("unknown input param") return False print(moved_coordinates) for moved_coord in moved_coordinates: if not self.board.is_in(moved_coord): return False if not self.board.at(moved_coord) == 0: return False return True def get_falling_block_geometry(geometry): if geometry == "block": return np.array([Coordinate(0,0), Coordinate(1,0), Coordinate(0,1), Coordinate(1,1)]) elif geometry == "t": return np.array([Coordinate(0,0), Coordinate(0,1), Coordinate(1,1), Coordinate(0,2)]) elif geometry == "l": return np.array([Coordinate(0,0), Coordinate(0,1), Coordinate(0,2), Coordinate(1,2)]) elif geometry == "l_inverted": return np.array([Coordinate(0,0), Coordinate(0,1), Coordinate(0,2), Coordinate(-1,2)]) elif geometry == "z": return np.array([Coordinate(0,0), Coordinate(0,1), Coordinate(-1, 1), Coordinate(-1,2)]) elif geometry == "z_inverted": return np.array([Coordinate(0,0), Coordinate(0,1), Coordinate( 1,1), Coordinate(1,2)]) elif geometry == "I": return np.array([Coordinate(0,0), Coordinate(0,1), Coordinate(0,2), Coordinate(0, 3)]) else: print("unknown geometry, print I instead") return np.array([Coordinate(0,0), Coordinate(0,1), Coordinate(0,2), Coordinate(0, 3)]) class InputHandler: def __init__(self, falling_block): self.falling_block = falling_block def connect_pressevent(self, figure, onpress): figure.canvas.mpl_connect('key_press_event', onpress) def connect_clickevent(self, figure, onclick): figure.canvas.mpl_connect('button_press_event', onclick) def on_press(self, event): if event.key == "left": self.falling_block.move_left() elif event.key == "right": self.falling_block.move_right() elif event.key == "down": self.falling_block.fall() elif event.key == "up": if not self.falling_block.turn(): print("Didnt Turn!") return class Drawer: def __init__(self, board, falling_block): self.board = board self.falling_block = falling_block self.draw_array = np.zeros((SIZE_X, SIZE_Y)) self.fig = plt.figure() self.ax = self.fig.add_subplot(111) self.draw() def draw(self): self.ax.clear() self.draw_array = copy.deepcopy(self.board.array) for coordinate in self.falling_block.get_coordinates(): self.draw_array[coordinate.x, coordinate.y] = 1.5 self.ax.imshow(np.swapaxes(self.draw_array, 0, 1), cmap = "Reds", vmax = "2") plt.show() self.fig.canvas.draw() def message_loose(self): self.ax.set_title("GAME OVER") if __name__ == "__main__": game = Game() game.update() while (not game.over): plt.pause(0.15) game.update() game.lost()
3343ed5fc69d1492b3c43d7efe74f5fd37e118c8
VeselinMetodiev/Chess-Game
/Main.py
2,430
3.515625
4
import pygame from os import sys from Constants import WIDTH, HEIGHT, SQUARE_SIZE, WHITE, BLACK from Game import Game from Algorithm import get_random_move FPS = 60 #window display WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Chess') #get the square clicked from mouse def get_row_col_from_mouse(pos): x, y = pos row = y // SQUARE_SIZE col = x // SQUARE_SIZE return row, col def set_text(string, coordx, coordy, fontSize): #Function to set text pygame.font.init() font = pygame.font.Font(pygame.font.get_default_font(), fontSize) text = font.render(string, True, WHITE) textRect = text.get_rect() textRect.center = (coordx, coordy) return (text, textRect) def writeGame(game): games = open("games.txt", "a", encoding='utf-8') games.write("\n \n \n") games.write(game.printGame()) games.close() def main(): run = True clock = pygame.time.Clock() #board = Board() game = Game(WIN) pause = False while run: clock.tick(FPS) if game.winner() != None: #Print who has won and wait for the user to press any key for new game output = game.winner() + " won the game! Press any key or quit!" totalText = set_text(output, HEIGHT // 2, WIDTH // 2 , 30) WIN.blit(totalText[0], totalText[1]) pause = True pygame.display.update() writeGame(game) #add the game in the games.txt file pygame.event.clear() while pause: pygame.init() event = pygame.event.wait() if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYUP: main() if game.turn == WHITE: new_board = get_random_move(game.get_board(), WHITE, game) game.ai_move(new_board) #Check if any event has happened for event in pygame.event.get(): if event.type == pygame.QUIT: run = False sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() row, col = get_row_col_from_mouse(pos) game.select(row, col) if(not pause): game.update() pygame.quit() sys.exit() main()
5d3dfbaf1c4e88e47273834ae7118582e9070951
VeselinMetodiev/Chess-Game
/Rook.py
2,134
3.828125
4
from Constants import WHITE_ROOK, BLACK_ROOK, WHITE from Piece import Piece class Rook(Piece): def __init__(self, col, row, color): Piece.__init__(self, col, row, color) self.moved = False if color == WHITE: self.image = WHITE_ROOK else: self.image = BLACK_ROOK def draw(self, win): win.blit(self.image, (self.x - self.image.get_width()//2, self.y - self.image.get_height()//2)) def valid_moves(self, board): moves = [] row = self.getRow() col = self.getCol() for i in range(row+1,8): if board.get_piece(i, col) == 0: moves.append((i, col)) elif board.get_piece(i, col).getColor() != self.color: #take a piece from the opponent moves.append((i, col)) break else: break for j in range(row-1, -1, -1): if board.get_piece(j, col) == 0: moves.append((j, col)) elif board.get_piece(j, col).getColor() != self.color: #take a piece from the opponent moves.append((j, col)) break else: break for k in range(col+1,8): if board.get_piece(row, k) == 0: moves.append((row, k)) elif board.get_piece(row, k).getColor() != self.color: #take a piece from the opponent moves.append((row, k)) break elif board.get_piece(row, k) != 0: break for m in range(col-1, -1, -1): if board.get_piece(row, m) == 0: moves.append((row, m)) elif board.get_piece(row, m).getColor() != self.color: #take a piece from the opponent moves.append((row, m)) break elif board.get_piece(row, m) != 0: break return moves def __repr__(self): if self.color == WHITE: return u'\u2656' else: return u'\u265C'
5d663b2b02ab3f51d646e0e1d53f6d5b352b6b35
Marcnuth/LM-ML
/split-captcha-py/src/xnp.py
3,869
3.53125
4
import numpy as np from operator import itemgetter ''' Return the indexes of max connected array in given array ''' def max_connected_array(arr, diagonal=True): nonzero_arr = np.nonzero(arr) nonzero_all = set(map(lambda x, y: (x, y), nonzero_arr[0], nonzero_arr[1])) nonzero_walked = set() scores = list() while nonzero_all - nonzero_walked: nonzero_towalk = nonzero_all - nonzero_walked neighbor = neighbor_indexs(nonzero_towalk.pop(), arr, diagonal) scores.append((len(neighbor), neighbor)) nonzero_walked = nonzero_walked.union(neighbor) scores = sorted(scores, key=itemgetter(0))[::-1] return scores[0][1] def neighbor_indexs(xy, arr, diagonal=True): arr_cpy = np.insert(arr, 0, 0, axis=0) arr_cpy = np.insert(arr_cpy, 0, 0, axis=1) arr_cpy = np.insert(arr_cpy, arr_cpy.shape[0], 0, axis=0) arr_cpy = np.insert(arr_cpy, arr_cpy.shape[1], 0, axis=1) x, y = xy[0] + 1, xy[1] + 1 neighbor = set() to_walk = set() to_walk.add((x, y)) while to_walk: item = to_walk.pop() x = item[0] y = item[1] # neighbor set means the item have been walked, so we donot need to walk again if item in neighbor: continue # not walked, just add to neighbor and walk neighbor.add((x, y)) if arr_cpy[x + 1, y]: to_walk.add((x+1, y)) if arr_cpy[x + 1, y + 1] and diagonal: to_walk.add((x+1, y+1)) if arr_cpy[x, y + 1]: to_walk.add((x, y+1)) if arr_cpy[x - 1, y + 1] and diagonal: to_walk.add((x-1, y+1)) if arr_cpy[x - 1, y]: to_walk.add((x-1, y)) if arr_cpy[x - 1, y - 1] and diagonal: to_walk.add((x-1, y-1)) if arr_cpy[x, y - 1]: to_walk.add((x, y-1)) if arr_cpy[x + 1, y - 1] and diagonal: to_walk.add((x+1, y-1)) return set([(_i[0] - 1, _i[1] - 1) for _i in neighbor]) ''' Return an tuple, which is (mins, maxs) mins: a sorted list of indexs which is minmums maxs: a sorted list of indexs which is maxmums ''' def discrete_extremes(arr): shrinked = [[arr[0], 1]] for i in range(1, arr.shape[0]): if arr[i] == shrinked[-1][0]: shrinked[-1][1] += 1 else : shrinked.append([arr[i], 1]) d1_shrinked = np.diff([i[0] for i in shrinked]) mins_shrinked = [i for i in range(1, d1_shrinked.shape[0]) if d1_shrinked[i] * d1_shrinked[i-1] < 0 and d1_shrinked[i] > 0] maxs_shrinked = [i for i in range(1, d1_shrinked.shape[0]) if d1_shrinked[i] * d1_shrinked[i-1] < 0 and d1_shrinked[i] < 0] mins, maxs = set(), set() hided = 0 for i in range(len(shrinked)): if i in mins_shrinked: for j in range(shrinked[i][1]): mins.add(i + hided + j) if i in maxs_shrinked: for j in range(shrinked[i][1]): maxs.add(i + hided + j) hided += (shrinked[i][1] - 1) mins = sorted(list(mins)) maxs = sorted(list(maxs)) return (mins, maxs) ''' Main: for test and examples ''' if __name__ == '__main__': # max connected array case1 = np.load('xnp.test.array.1') print max_connected_array(case1, diagonal=False) # tests & examples case1 = np.array([1,2,3,4,5,4,3,2,1,2,3,4,5,6,7,8,7,8,9,8,7,3,5,4,5,6,9]) assert discrete_extremes(case1) == ([8, 16, 21, 23], [4, 15, 18, 22]) case2 = np.array([1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,2,2,2,2,2,3]) assert discrete_extremes(case2) == ([15, 16, 17, 18, 19], [10, 11, 12, 13, 14]) case3 = np.array([0,0,0,0,1,9,2,1,9,0,0,0]) assert discrete_extremes(case3) == ([7], [5, 8]) case4 = np.array([0,1,0,-1,-2,9]) assert discrete_extremes(case4) == ([4], [1]) print 'ENJOY!'
521b998e165983de4be3342e7e5d354b03d096ac
eddgar10/codigosdebarrapersonalizado
/tecladogenera.py
2,827
3.84375
4
#!/usr/bin/python # -*- coding: utf-8 -*- #EDGAR ESPINOSA OCTUBRE 2021 #github.com/eddgar10/codigosdebarrapersonalizado #fuentes: #https://www.geeksforgeeks.org/how-to-generate-barcode-in-python/ #https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/ #https://barcode-labels.com/getting-started/barcodes/types/ #https://www.geeksforgeeks.org/python-randint-function/ #https://www.mclibre.org/consultar/python/lecciones/python-for.html #https://www.programiz.com/python-programming/methods/string/strip #https://careerkarma.com/blog/python-compare-strings/ #https://programminghistorian.org/es/lecciones/trabajar-con-archivos-de-texto # importar biblioteca EAN13 de modulo barcode from barcode import Code128 # import ImageWriter para generar un archivo imagen from barcode.writer import ImageWriter #importar biblioteca aleatoria import random cantidadagenerar= input("cantidad de codigos a generar: ")#en esta variable se asignan la cantidad de codigos nuevos a generar leidos de teclado banderaexistente = 0 #bandera que determina si el codigo ya ha sido generado para evitar duplicarlo #generando N cantidad de codigos leida for i in range(int(cantidadagenerar)): textocodigo=("SERV"+str(random.randint(0,9))+"T"+str(random.randint(10,99))+"E"+str(random.randint(100,999))+"C") #sintaxis de codigo genrado: "SERV"+ 0-9 + T + 10-99 + E + 100-999 + C print ("codigo nuevo generado: "+textocodigo) print("Buscando codigo repetido... ") buscarepetido = open('codigosgeneradosteclado.txt', 'r') #apertura de archivo existente para realizar busqueda de codigo generado Lines=buscarepetido.readlines() #apertura de archivo para lectura liena a linea for line in Lines: if textocodigo == line.strip(): #comparacion codigo generado con linea leida de archivo cpu banderaexistente = 1 #indica que el codigo generado ya existia en el archivo print("el codigo ya existe en la lista \n") break else: banderaexistente = 0 #indica que el codigo generado no existe en el archivo buscarepetido.close() #cierre de archivo de lectura if banderaexistente == 0: #bandera en 0 = no existe codigo generado en archivo escribenuevocodigo=open('codigosgeneradosteclado.txt','a') #apertura de archivo para añadir el nuevo codigo generado a la lista print("codigo nuevo agregado: "+textocodigo) print ("*********************") escribenuevocodigo.write(textocodigo+"\n") escribenuevocodigo.close() #cierre de archivo despues de añadir el nuevo codigo my_code = Code128(textocodigo, writer=ImageWriter()) #generacion de imagen con codigo de barras para el nuevo codigo generado my_code.save("TEC"+textocodigo) #escritura de file imagen con el codigo de barras
6952569826d810c9a9eae1dc5a3cca1365bd028a
ElenaVasylenko/PyReview
/basics/inheritance/Employee.py
1,758
3.890625
4
from abc import ABC, abstractmethod from datetime import date class Employee(ABC): def __init__(self, doc_id: str, name: str, birthday: str): self.__doc_id = doc_id self.name = name self.birthday = birthday print('employee created') @abstractmethod def get_duties(self): pass @abstractmethod def get_contract(self): pass class Engineer(Employee): def __init__(self, grade, doc_id: str, name: str, birthday: str): self.__grade = grade super().__init__(doc_id, name, birthday) print('engineer created') def get_duties(self): print('engineer duties') return 'engineer duties' def get_contract(self): print('engineer contract') return 'engineer contract' class BackendSWE(Engineer): def __init__(self, grade: str, doc_id: str, name: str, birthday: str, programming_language: str): self.__salary = 2000 self.programming_language = programming_language super().__init__(grade, doc_id, name, birthday) print('backend swe created') def get_duties(self): print('backend swe duties') return 'backend swe duties' def get_contract(self): print('backend swe contract') return 'backend swe contract' swe = BackendSWE(grade='middle', doc_id='fb541509', name='olena', birthday='18.03.98', programming_language='python') swe.get_duties() swe.get_contract() # access private variable of child class print(swe._BackendSWE__salary) print(swe._Engineer__grade) print(swe._Employee__doc_id) # _MangledGlobal__mangled = 23 # # class MangledGlobal: # def test(self): # return __mangled # # >>> MangledGlobal().test() # 23
c8f4db8845bf675f10b8cbb24773648475d06172
ElenaVasylenko/PyReview
/basics_test.py
726
3.75
4
# import re # import functools # l = [[1,2,3]] # # m = l.copy() # print(m) # l[0][1] = 'X' # print(l) # z = {1:'bill', 2:'age', 3:'22'} # v = list(z.values()) # print(v) # matrix = [[0, 2, 4, 5], [3, 1, 1, 8]] def main_diagonal(matrix :list): column_id = 0 diagonal = [] for row in matrix: if column_id < len(row): diagonal.append(row[column_id]) column_id += 1 return diagonal #print(main_diagonal(matrix)) from functools import reduce numbers = [2, 2, 1] # result = reduce(pow, numbers, 3) # print(result) # # print(list(reversed(range(1,6)))) def factorial(n): return reduce(lambda x, y: x*y, range(1, n+1), 1) print(factorial(7)) t = (2, 3, 4) print(t)
b1d9e5aa28778528f9305577f6e7a3a0604198c9
jackiehluo/projects
/numbers/change-return-program.py
951
3.796875
4
from math import floor def change(c, m): d = m - c dollars = int(floor(d)) coins = int((d - floor(d)) * 100) twenties = 0 tens = 0 fives = 0 ones = 0 quarters = 0 dimes = 0 nickels = 0 pennies = 0 if dollars > 0: twenties = dollars / 20 tens = (dollars % 20) / 10 fives = (dollars % 10) / 5 ones = (dollars % 5) if coins > 0: quarters = coins / 25 dimes = (coins % 25) / 10 nickels = (coins % 10) / 5 pennies = (coins % 5) return "Twenties: " + str(twenties) + "\n" + "Tens: " + str(tens) + "\n" + "Fives: " + str(fives) + "\n" + "Ones: " + str(ones) + "\n" + "Quarters: " + str(quarters) + "\n" + "Dimes: " + str(dimes) + "\n" + "Nickels: " + str(nickels) + "\n" + "Pennies: " + str(pennies) + "\n" c = float(raw_input("How much did the item cost? $")) m = float(raw_input("How much money did you give? $")) print change(c, m)
bf126961d6fef79b8a12837acd4f6baf93f4fb6e
jackiehluo/projects
/numbers/tax-calculator.py
440
3.90625
4
def calculate(cost, rate): tax = round(cost * (rate / 100), 2) total = round(cost * (1 + rate / 100), 2) return tax, total cost = float(raw_input("Enter the cost: $")) rate = float(raw_input("Tax Percentage: ")) try: tax, total = calculate(cost, rate) print "Tax: $" + str(tax) print "Total: $" + str(total) except: print "Something went wrong. Did you enter tax out of a hundred? For example, sales tax might be 8.25, not 0.00825."
8473a7a874e1bf2435049301d45064ecefe4f45d
jackiehluo/projects
/numbers/fibonacci-sequence.py
209
4.1875
4
from math import sqrt def fibonacci(n): return ((1 + sqrt(5)) ** n - (1 - sqrt(5)) ** n) / (2 ** n * sqrt(5)) n = int(raw_input("Enter a digit n for the nth Fibonacci number: ")) print int(fibonacci(n))
f9d9fd5fc21240bba11af8a5a30b2d0fb32b31cb
farnaztizro/computer-vision
/backpropagation/neuralnetwork.py
4,780
3.828125
4
import numpy as np class NeuralNetwork: # alpha value is applied during the weight update phase def __init__(self, layers, alpha=0.1): # initializes our list of weights for each layer self.W = [] # store layers and alpha self.layers = layers self.alpha = alpha # Our weights list W is empty, so let’s go ahead and initialize it for i in np.arange(0, len(layers) - 2): w = np.random.randn(layers[i] + 1, layers[i + 1] + 1) self.W.append(w / np.sqrt(layers[i])) # where the input connections need a bias term, but the output does not w = np.random.randn(layers[-2] + 1, layers[-1]) self.W.append(w / np.sqrt(layers[-2])) # useful for debugging def __repr__(self): # construct and return a string that represents the network architecture return "NeuralNetwork: {}".format("-".join(str(l) for l in self.layers)) # define sigmoid activation function def sigmoid(self, x): return 1.0 / (1 + np.exp(-x)) def sigmoid_deriv(self, x): return x * (1 - x) def fit(self, X, y, epochs=1000, displayUpdate=100): X = np.c_[X, np.ones((X.shape[0]))] # loop over the desired # of epochs for epoch in np.arange(0, epochs): # For each epoch we’ll loop over each individual data point # in our training set, make a prediction on the data point, # compute the backpropagation phase, and then update our weight matrix for (x, target) in zip(X, y): self.fit_partial(x, target) # check to see if we should display a training update if epoch == 0 or (epoch + 1) % displayUpdate == 0: loss = self.calculate_loss(X, y) print("[INFO] epoch={}, loss={:.7f}".format(epoch + 1, loss)) def fit_partial(self, x, y): # storing the output activations for each layer as our data point x forward propagates through the network A = [np.atleast_2d(x)] ### forward propagation phase # FEEDFORWARD: for layer in np.arange(0, len(self.W)): net = A[layer].dot(self.W[layer]) # compute the net output applying nonlinear activation function out = self.sigmoid(net) # add to our list of activations # A is the output of the last layer in our network(prediction) A.append(out) # BACKPROPAGATION # the first fase is to compute the difference between our predictions and true target value(error) # difference between predicted label A and the ground-truth label y error = A[-1] - y # apply the chain rule and build a liest od deltas # The deltas will be used to update our weight matrices, scaled by the learning rate alpha # [-1]: last entry in the list D = [error * self.sigmoid_deriv(A[-1])] # given the delta for the final layer in the network for layer in np.arange(len(A) - 2, 0, -1): delta = D[-1].dot(self.W[layer].T) delta = delta * self.sigmoid_deriv(A[layer]) D.append(delta) # since looped over our layers in reverse order we need to reverse deltas # tartibe vorudi haye d baraks D = D[::-1] # WEIGHT UPDATE PHASE for layer in np.arange(0, len(self.W)): # updating weight matrix(actual learning)=gradien descent self.W[layer] += -self.alpha * A[layer].T.dot(D[layer]) ## make prediction on testing set after network train on a given dataset # X:the data points we'll be predicting class labels for # addBias:e need to add a column of 1’s to X to perform the bias trick def predict(self, X, addBias=True): # initialize p p = np.atleast_2d(X) if addBias: # insert a column of 1's as the last entry in feature matrix p = np.c_[p, np.ones((p.shape[0]))] for layer in np.arange(0, len(self.W)): '''compute the output prediction by taking dot product between the current activation value p and wheight matrix then passing the value through the nonlinear activation func''' p = self.sigmoid(np.dot(p, self.W[layer])) # return the predicted value return p # calculate loss def calculate_loss(self, X, targets): # make prediction for the input data point then compute the loss targets = np.atleast_2d(targets) # make prediction on x predictions = self.predict(X, addBias=False) loss = 0.5 * np.sum((predictions - targets) ** 2) return loss
49e00035aa0f8b45dcca3c99f500d4300c066f81
MrHughesAvanti/GCSESummer
/selection.py
429
4.0625
4
import random number = random.randint(1, 10) guess = int(input("have a guess please: ")) for i in range(2): if guess > number: print("Sorry that's too high try a lower number") elif guess < number: print("Sorry that's too low try a higher number") else: print("Well done you got it") break guess = int(input("have a guess please: ")) print("bye")
fc560701f87c73692b9710ce0a8593f28788a6c8
Drake-Firestorm/Think-Python
/code/reverse_pair.py
1,143
3.984375
4
# Method 1: using in_reverse() def is_reverse(word1, word2): if len(word1) != len(word2): return False i = 0 j = len(word2) - 1 while j >= 0: if word1[i] != word2[j]: return False i = i + 1 j = j - 1 return True def reverse_pair1(t): for i in range(len(t)): for j in range(i, len(t)): if is_reverse(t[i], t[j]): print(t[i], t[j]) # Method 2: using in_bisect() def in_bisect(t, target): i = int(len(t) / 2) if len(t) == 0: return False elif target < t[i]: return in_bisect(t[:i], target) elif target > t[i]: return in_bisect(t[i+1:], target) else: return True def reverse_pair2(t): for word in t: rev_word = word[::-1] if in_bisect(t, rev_word): print(word, rev_word) def wordlist(): fin = open("words.txt") t = [] for line in fin: word = line.strip() t.append(word) return t # reverse_pair1(wordlist()) reverse_pair2(wordlist()) # Method 2 is much faster since it cuts down the search list each time in half.
411b26434e82a196319418b1fb65b2d4b7d4fa18
Drake-Firestorm/Think-Python
/code/anagram_db.py
754
3.859375
4
import anagram_sets_Allen_Downey import shelve def store_anagrams(d, filename): try: shelf = shelve.open(filename) for key, values in d.items(): if len(values) > 1: shelf[key] = values shelf.close() except: print("Error storing anagram") raise def read_anagram(word, filename): shelf = shelve.open(filename) word = "".join(sorted(word.lower())) anagrams = list() if word in d: anagrams = d.get(word) else: anagrams = -1 shelf.close() return anagrams if __name__ == "__main__": d = anagram_sets_Allen_Downey.all_anagrams("words.txt") # store_anagrams(d, "words_anagram") print(read_anagram("stop", "words_anagram"))
2266a4997eb486d1f00ce38df91d39f9b01e6502
Drake-Firestorm/Think-Python
/code/PokerHand.py
6,075
3.984375
4
"""This module contains a code example related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ """ from __future__ import print_function, division from Card_Allen import Hand, Deck from Card_Allen import Card class PokerHand(Hand): """Represents a poker hand.""" def suit_hist(self): """Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits. """ self.suits = {} for card in self.cards: self.suits[card.suit] = self.suits.get(card.suit, 0) + 1 def rank_hist(self): """Builds a histogram of the ranks that appear in the hand. Stores the result in attribute ranks. """ self.ranks = dict() for card in self.cards: self.ranks[card.rank] = self.ranks.get(card.rank, 0) + 1 def rank_count_hist(self): """Builds a histogram of the counts of ranks that appear in the hand. Stores the result in attribute count_ranks. """ self.rank_hist() self.count_ranks = dict() for val in self.ranks.values(): self.count_ranks[val] = self.count_ranks.get(val, 0) + 1 def has_flush(self): """Returns True if the hand has a flush, False otherwise. Note that this works correctly for hands with more than 5 cards. """ self.suit_hist() for val in self.suits.values(): if val >= 5: return True return False def has_pair(self): """Returns True if the hand has a pair, False otherwise. Note that this works correctly for hands with more than 5 cards. """ self.rank_count_hist() if self.count_ranks.get(2, 0) == 1: return True return False def has_twopair(self): """Returns True if the hand has two pairs, False otherwise. Note that this works correctly for hands with more than 5 cards. """ self.rank_count_hist() if self.count_ranks.get(2, 0) == 2: return True return False def has_three(self): """Returns True if the hand has three of a kind, False otherwise. Note that this works correctly for hands with more than 5 cards. """ self.rank_count_hist() if self.count_ranks.get(3, 0) == 1: return True return False def has_four(self): """Returns True if the hand has four of a kind, False otherwise. Note that this works correctly for hands with more than 5 cards. """ self.rank_count_hist() if self.count_ranks.get(4, 0) == 1: return True return False def has_full(self): """Returns True if the hand has full house, False otherwise. Note that this works correctly for hands with more than 5 cards. """ if self.has_three() and self.has_pair(): return True return False def has_straight(self): """Returns True if the hand has a straight, False otherwise. Note that this works correctly for hands with more than 5 cards. """ self.rank_hist() min_rank = 13 max_rank = 1 card_ranks = sorted(self.ranks.keys()) cards_count = len(card_ranks) for i in range(cards_count - 5 + 1): ranks = card_ranks[i:i+5] for rank in ranks: min_rank = min(min_rank, rank) max_rank = max(max_rank, rank) if max_rank - min_rank == 4: return True return False def has_straightflush(self): """Returns True if the hand has a straight flush, False otherwise. Note that this works correctly for hands with more than 5 cards. """ cards_count = len(self.cards) for i in range(cards_count - 5 + 1): ranks = PokerHand() for j in range(i, i+5): ranks.add_card(self.cards[j]) if ranks.has_straight() and ranks.has_flush(): return True return False def classify(self): if self.has_straightflush(): self.label = "Straight Flush" elif self.has_four(): self.label = "Four of a kind" elif self.has_full(): self.label = "Full House" elif self.has_flush(): self.label = "Flush" elif self.has_straight(): self.label = "Straight" elif self.has_three(): self.label = "Three of a kind" elif self.has_twopair(): self.label = "Two Pair" elif self.has_pair(): self.label = "Pair" else: self.label = "Highest Card" def PokerDeck(Deck): def deal_hands(self, hands=7, cards=5): h = list() for i in range(hands): hand = PokerHand() self.move_cards(hand, cards) hand.classify() h.append(hand) return h def hand_probablity(): prob = dict() n = 10000 hands = 10 cards = 5 for i in range(n): if i % 1000 == 0: print(i) deck = Deck() deck.shuffle() for j in range(hands): hand = PokerHand() deck.move_cards(hand, cards) hand.classify() classification = hand.label prob[classification] = prob.get(classification, 0) + 1 total = sum(prob.values()) print("Probability Percent") for key in sorted(prob, key=prob.get, reverse=True): print("%s: %.3f" % (key, prob.get(key) / total * 100)) if __name__ == '__main__': # make a deck deck = Deck() deck.shuffle() # # deal the cards and classify the hands # for i in range(7): # hand = PokerHand() # deck.move_cards(hand, 7) # hand.sort() # print(hand) # print(hand.has_flush()) # print('') hand_probablity()
cda9fd96188b3e9e86fe9345225796e5b1e00044
Drake-Firestorm/Think-Python
/code/reducible.py
2,490
4.09375
4
def make_word_dict(): """ Reads a word list and returns a word dictionary. :return: dictionary with words as keys """ fin = open("words.txt") d = dict() for line in fin: word = line.strip().lower() d[word] = d.get(word, 0) for letter in ["a", "i", ""]: d[letter] = letter return d def children(word, word_dict): """ Returns list of all words that can be formed by removing one letter. :param word: string :param word_dict: dictionary with words as keys :return: list of strings """ li = list() for i in range(len(word)): child = str(word[:i] + word[i+1:]) if child in word_dict: li.append(child) return li memo = dict() memo[""] = [""] def is_reducible(word, word_dict): """ Returns list of all reducible children of the word. Also updates memo dictionary with the reducible children A string is reducible if it has at least one child that is reducible. The empty string is also reducible. :param word: string :param word_dict: dictionary with words as keys :return: list of strings """ if word in memo: return memo[word] li = children(word, word_dict) red_child = list() for child in li: if is_reducible(child, word_dict): red_child.append(child) memo[word] = red_child return red_child def all_reducible(word_dict): """ Return list of all reductible words in the dictionary. :param word_dict: dictionary with words as keys :return: list of strings """ li = [] for word in word_dict: t = is_reducible(word, word_dict) if t != []: li.append(word) return li def print_trail(word): """ Print sequence of words which reduced this word to empty string. If more than one trail, it chooses the first. :param word: string :return: None """ if len(word) == 0: return print(word, end=" ") red_child = is_reducible(word, word_dict) print_trail(red_child[0]) def print_longest_words(word_dict): """ Finds the longest reducible words and prints them. :param word_dict: dictionary with words as keys :return: None """ reducible = all_reducible(word_dict) reducible.sort(key=len, reverse=True) for word in reducible[:10]: print_trail(word) print("\n") word_dict = make_word_dict() print_longest_words(word_dict)
b53251dd84c5f2f83b0b5af7fcba3a263a5defea
sowjanyadevdas7/python
/mathop.py
999
3.96875
4
a = int(input("enter a value:")) b = int(input("enter b value:")) def add(a , b): return(a + b) def sub(a , b): return(a - b) def mult(a , b): return(a * b) def division(a , b): return(a // b) def modulus(a , b): return(a % b) print("select operation:") print("1.add of a and b is:") print("2.sub of a and b is:") print("3.mult of a and b is:") print("4.division of a and b is:") print("5.modulus of a and b is:") choice = input("enter choice(1/2/3/4/5)") if choice == '1': print(a,"+",b,"=", add(a,b)) elif choice == '2': print(a,"-",b,"=", sub(a,b)) elif choice == '3': print(a,"*",b,"=", mult(a,b)) elif choice == '4': print(a,"//",b,"=", division(a,b)) elif choice == '5': print(a,"%",b,"==", modulus(a,b)) else: print("Invalid input") output: enter a value: 10 enter b value: 20 select operation: 1.add of a and b is: 2.sub of a and b is: 3.mult of a and b is: 4.division of a and b is: 5.modulus of a and b is: enter choice(1/2/3/4/5)1 10 + 20 = 30
344de2bd22b3a00639d6b89e35c17b7e0bec6da5
bosefalk/small_meal_planner
/meals_wrapper.py
685
3.53125
4
import meals import sys # Select four random meals and print them meal_list = meals.random() print('\n') print('\n') print('\n') print('Four chosen meals:') print(meal_list) print('\n') allowed_numbers = [1,2,3,4] selecting = True while selecting == True: user_input = input("select " + str(allowed_numbers) +", All, Exit" + '\n') if (user_input == 'Exit'): selecting = False if (user_input == "All"): for i in allowed_numbers: meals.update(meal_list, position=i) selecting = False if (user_input in str(allowed_numbers)): meals.update(meal_list, position = int(user_input)) allowed_numbers.remove(int(user_input))
9dba4ddee189dd1094f32328b6e5638eaaec16c9
sylviachan127/Python-Intro
/HW10.py
2,241
3.734375
4
#Yuen Han(Sylvia) Chan #Section: B01 #GTID: #902983019 #Email: ychan35@gatech.edu #I work on the entire HW by myself from Myro import* import time import math init() #This homework contains 2 functions, one is to calculates the G Force, #another one is to control robot with color. def gravitationalForce(): #This function calculates the graviational Force based on user input gravity = 0.0000000000667 mass1 = input("Please enter the known mass of object1 in kg") mass1ft = float(mass1) mass2 = input("please enter the known mass of object2 in kg") mass2ft = float(mass2) distance = input("Please enter the distance separating the objects' centers") distanceft = float(distance) fGrav = ((gravity*mass1ft*mass2ft)/(distanceft**2)) print("The force of gravitational attraction between object1 and object2 with a distace of {0:.1f} is {1:.3f} N".format(distanceft,fGrav)) def moveWithColor(n): #This function controls the robot's movement according for t in timer(n): p = takePicture() g = analysisPic(p) if g == "red": forward(1,1) elif g == "blue": backward(1,1) elif g == "green": rotate(1,1) def analysisPic(aPic): #This function returns the color result of the Picture to the moveWithColor function. rC=0 gC=0 bC=0 tC=0 bPercentage=0 gPercentage=0 colorI = "" for i in getPixels(aPic): r = getRed(i) g = getGreen(i) b = getBlue(i) if 100<r<255 and 60<g<110 and 50<b<120: rC +=1 tC +=1 elif r>100 and 200<g<270 and 170<b<210: gC +=1 tC +=1 elif 40<r<80 and 70<g<100 and 110<b<140: bC +=1 tC +=1 else: tC +=1 #These calculate the percentage of red, green, and blue pixels in the picture. rPercentage=rC/tC bPercentage=bC/tC gPercentage=gC/tC if rPercentage > 0.05: colorI = "red" elif bPercentage > 0.05: colorI = "blue" elif gPercentage > 0.05: colorI = "green" print(rPercentage,bPercentage,gPercentage,colorI) #This returns the color of the picture to the moveWithColor function return colorI
8cf092c3be2f448f4fc062ad93975f413aa607b9
grypyAndy/andelaTests
/stringlab.py
477
3.75
4
i='yes' j="Maybe" print (i*5) print(j*3+i*5) #the interview section applicant=input("Enter the applicant's name: ") interviewer=input("Enter the interviwer's name: ") time=input("Enter the appointment time: ") print(interviewer, "will interview", applicant, "at ", time) #entering numbers and getting a sum xstring=input("Enter a number: ") ystring=input("Enter a second number: ") x=int(xstring) y=int(ystring) print('The sum of ',x, ' and ',y,' is ',x+y, '.', sep='')
bad796cdceeeb2c1a3641944b82e1e51ab1e51ac
1071183139/biji
/5_python基础/1_字符串.py
2,201
3.859375
4
# 字符串的格式化输出 # username=input('请输入名字') # print('你的名字为%s'%username) #字符串的切片 name = 'abcdef' # print(name[0]) name = 'abcdef' # print(name[2:]) # 取 下标为2开始到最后的字符 name = 'abcdef' # print(name[1:-1]) # 取 下标为1开始 到 最后第2个 之间的字符 # print(name[::-1]) # fedcba 逆序 步长为1 # print(name[::-2]) # fdb 逆序 步长为2 # format函数 # str='{1}-{0}'.format('biao','zhang') # str='{} {}'.format('zhang','yang','cheng') # str='{name}-{age}'.format(name='yangmi',age=12) li=[1,2,3,4,5] str='{0[0]} {0[1]}'.format(li) # print(str) # 字符串常见的操作 # find 查找 有,返回下标,没有返回-1 # mystr.find(str, start=0, end=len(mystr)) mystr = 'hello world itcast and itcastcppm' # print(mystr.find('and')) # print(mystr.find('and',0,len(mystr))) # print(mystr.find('and',0,18)) # index 和find一样 没有会报错 # print(mystr.index('m',0,len(mystr))) # print(mystr.index('m',0,-1)) # count 返回str在start和end之间 在 mystr里面出现的次数 # mystr.count(str, start=0, end=len(mystr)) # print(mystr.count('p')) # replace 替换 str1替换成str2 mystr2='ha ha ha ha' # print(mystr2.replace('ha','Ha')) # print(mystr2.replace('ha','Ha',mystr2.count('ha'))) # print(mystr2.replace('ha','Ha',1)) #split 分割 以str 为分隔符切片mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串 # print(mystr.split(' ',2)) # print(mystr.split(' ')) # startswith endswith 判断字符串以什么开头,以什么结尾 # print(mystr.startswith('world')) # print(mystr.endswith('itcastcpp')) #lower upper 将转化为大写,转换为小写 # print(mystr.lower()) # print(mystr.upper()) # center ljust rjust 返回一个原字符串居中, 并使用空格填充至长度width的新字符串 # mystr.center(width) # print(mystr.center(100)) # strip 删除字符创左右两边的空格 # print(mystr.strip()) # join 加入 于将序列中的元素以指定的字符连接生成一个新的字符串。 str='' li=['1','2','3','4','5'] print(str.join(li)) print(type(str.join(li)))
5f849288cc936f586ecbf6daf928afdbac9b4948
1071183139/biji
/4_面试题/2_网上找的/1_大黄蜂面试题/5_高阶函数.py
711
4.09375
4
# map(f,list)是 Python 内置的高阶函数,它接收一个函数 f 和一个 list, # # 并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的可迭代对象并返回。 # li=[1,2,3,4,5] # def func(x): # return x * x # li1=map(func,li) # # li2=map(lambda x:x*x,li) # # # print(list(li1)) # print([i for i in li2]) # filter方法求出列表所有奇数并构造新列表a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]? # a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # res=filter(lambda i:i%2==1,a) # print([i for i in res]) from functools import reduce def add(x, y) : # 两数相加 return x + y res=reduce(add, [1,2,3,4,5]) # 计算列表和:1+2+3+4+5 print(res)
e4c76d2fc432ebb3f228aa6e88021e1fdeae6930
1071183139/biji
/7_py实用编程技巧/2_对象迭代和反迭代/2_3反向迭代.py
640
3.8125
4
class FloatRange: def __init__(self, start, end, step=0.1): self.start = start self.end = end self.step = step # 正向迭代器 def __iter__(self): t = self.start while t <= self.end: yield t t += self.step # 反向迭代器 def __reversed__(self): t = self.end while t >= self.start: yield t t -= self.step if __name__ == '__main__': print("正向序列") for x in FloatRange(1.0, 4.0, 0.5): print(x) print("反向序列") for x in reversed(FloatRange(1.0, 4.0, 0.5)): print(x)
b24e2b4d66157574392a9861bb2c68b86248607d
1071183139/biji
/3_简历/3_python操作excel/1_获取excel/5_遍历行和列中单元格的值 .py
586
3.65625
4
import openpyxl # 打开excel文件,获取工作簿对象 wb = openpyxl.load_workbook('example.xlsx') ws = wb.active # 当前活跃的表单 col_range = ws['B:C'] row_range = ws[2:6] # for col in col_range: # 打印BC两列单元格中的值内容 # for cell in col: # print(cell.value) # for row in row_range: # 打印 2-5行中所有单元格中的值 # for cell in row: # print(cell.value) # for row in ws.iter_rows(min_row=1, max_row=2, max_col=3): # 打印1-2行,1-3列中的内容 for cell in row: print(cell.value)
8a9d3d3ed9ec795f9f3bc61d66df424ad06118b8
aysebilgegunduz/Memcached_Load_Balancer
/webserver.py
2,801
3.515625
4
from flask import Flask from flask import make_response from flask import request from lib.cache import Cache import names import configparser config = configparser.ConfigParser() config.read("config.ini") MAX_USER = config.getint('Defaults', 'max_number_of_client') CACHE_1 = Cache(config.get('Defaults', 'memcache_address_1')) CACHE_2 = Cache(config.get('Defaults', 'memcache_address_2')) CURRENT_USER_NUMBER = 0 app = Flask(__name__) @app.route('/create_user') def create_user(): """ The main method for creating a new user. I don't create a new user actually. just randomly generate first name :return: """ global MAX_USER, CURRENT_USER_NUMBER if CURRENT_USER_NUMBER == MAX_USER: # Checking number of user created. return "Maximum number of user reached. Not creating a new user" CURRENT_USER_NUMBER += 1 # Increase user number. """ This is important. At the initial phase, I am creating N number of user. Those users will be written to the cache server equally. That means; Cache 1 and 2 will have N/2 number of user at initial phase I am using odd/even approach for this reason. """ if CURRENT_USER_NUMBER % 2 == 0: # Write this user to the cache 1. CACHE_1.create_user( CURRENT_USER_NUMBER, names.get_first_name() ) cache_server_id = 1 else: # Write this user to the cache 2. CACHE_2.create_user( CURRENT_USER_NUMBER, names.get_first_name() ) cache_server_id = 2 resp = make_response("Your user id = {0}".format(CURRENT_USER_NUMBER)) resp.set_cookie("user_id", str(CURRENT_USER_NUMBER)) resp.set_cookie("cache_server_id", str(cache_server_id)) return resp @app.route('/homepage') def home_page(): user_id = request.cookies.get('user_id') cache_server_id = request.cookies.get('cache_server_id') if cache_server_id == "1": name = CACHE_1.get_user(user_id) if name is None: if CACHE_2.get_user(user_id): resp = make_response("Hello {0}. Welcome back <3".format(name)) resp.set_cookie("user_id", str(user_id)) resp.set_cookie("cache_server_id", str(2)) return resp elif cache_server_id == "2": name = CACHE_2.get_user(user_id) if name is None: if CACHE_1.get_user(user_id): resp = make_response("Hello {0}. Welcome back <3".format(name)) resp.set_cookie("user_id", str(user_id)) resp.set_cookie("cache_server_id", str(1)) return resp else: return "cache_server_id can be only 1 or 2." resp = make_response("Hello {0}. Welcome back <3".format(name)) return resp
c4eb3c25ca77674db9f7f11884a94a5ddb60af2e
penicillin0/atcoder
/ABC/029/c.py
196
3.734375
4
def dfs(n, string): if n == N: print(string) else: dfs(n + 1, string + 'a') dfs(n + 1, string + 'b') dfs(n + 1, string + 'c') N = int(input()) dfs(0, '')
371da8bf4eb27baab5753fd7f86bb4d878f95ce2
penicillin0/atcoder
/ABC/142/a.py
84
3.5
4
n = int(input()) if n % 2 == 0: a = n // 2 else: a = n // 2 + 1 print(a/n)
c80f70c511c515dc0fbe42199aad5b42a936d54e
penicillin0/atcoder
/ABC/002/b.py
104
3.546875
4
W = input() ans = '' for w in W: if w not in ['a', 'i', 'u', 'e', 'o']: ans += w print(ans)
b8abe9896b291ba6ae31a9611f686d2c3e7c629b
penicillin0/atcoder
/ABC/144/d.py
277
3.6875
4
from math import atan from math import pi a, b, x = map(int, input().split()) if a * a * b / 2 <= x: ans = atan((2 * b) / a - 2 * x / (a ** 3)) ans = ans * 180 / pi else: ans = atan(2 * x / (a * (b ** (2)))) ans = ans * 180 / pi ans = 90 - ans print(ans)