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
2c0c67a3a450a75472a3393d74db0f7dc106b2b9
mlstack/e200-tm
/code/e200-predict_simple_linear_regression.py
4,709
3.953125
4
#! /c/Apps/Anaconda3/python """ [Title] Understanding Learning Process [Author] Yibeck Lee(Yibeck.Lee@gmail.com) [Program Code Name] e200-predict_simple_linear_regression.py [Description] - 교육생 실습용 [History] - 2019-05-01 : 최초 작성 - 2019-05-05 : Naming 표준화 개선 [References] - https://www.tensorflow.org - https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.htm """ from matplotlib import pyplot as plt feature = 10.0 Weight = 1.5 bias = 0.3 predictedLabel = Weight*feature + bias print('[Predicted Label] Weight({:4.1f})*feature({:4.1f}) + bias({:4.1f}) = '.format(Weight,feature,bias), predictedLabel) import numpy as np feature = [10.0, 20.0, 30.0] label = [10,12,18] Weight = 1.5 bias = 0.5 print('[feature] ',feature) print('[data type of feature]',type(feature)) print("========== Weight Adjustment [Step 0] ==========") predictedLabel = np.dot(Weight,feature) + bias print("[Predicted Labels] ", predictedLabel) print('[data type of prdictedLabel]',type(predictedLabel)) for i in range(len(feature)): print('[Initial Predicted Label] Weight({:4.1f})*feature({:4.1f}) + bias({:4.1f}) = '.format(Weight, feature[i],bias), predictedLabel[i]) plt.subplot(1,5,1) plt.title("Step0") plt.plot(feature, predictedLabel) plt.scatter(feature, label) def f_total_sum(feature, Weight, bias): total_sum = 0.0 for i in range(len(feature)): total_sum += Weight * feature[i] + bias return total_sum total_sum = f_total_sum(feature=feature, Weight=Weight, bias=bias) print('[total estimated sum] ',total_sum) print('[actual label]', ','.join(str(item) for item in label), '[total actual sum]',sum(label)) def f_Loss_MSE(feature, Weight, bias, label): total_error = 0.0 for i in range(len(feature)): total_error += (label[i] - (Weight * feature[i] + bias))**2 lossMSE = total_error / len(feature) return lossMSE lossMSE = f_Loss_MSE(feature=feature, Weight=Weight, bias=bias, label = label) print("[Loss] ", lossMSE) plt.subplot(1,5,2) plt.title("Step0") plt.plot(feature, predictedLabel) plt.scatter(feature, label) class SLR(object): def f_weight_adjust(self, feature, Weight, bias, label, learningRate): self.feature = feature self.Weight = Weight self.bias = bias self.label = label self.learningRate = learningRate self.deltaWeight = 0 self.deltaBias = 0 self.numObs = len(self.label) for i in range(self.numObs): self.deltaWeight -= 2*self.feature[i]*(self.label[i] - (self.Weight * self.feature[i] + self.bias)) self.deltaBias -= 2*(self.label[i] - (self.Weight * self.feature[i] + self.bias)) self.Weight -= (self.deltaWeight / self.numObs) * self.learningRate self.bias == (self.deltaBias / self.numObs) * self.learningRate return self.Weight, self.bias slr1 = SLR() learningRate = 0.0005 print("========== Weight Adjustment [Step 2] ==========") Weight, bias = slr1.f_weight_adjust(feature=feature, Weight=Weight, bias=bias, label=label, learningRate=learningRate) print('[Step1]','Weight=', Weight, 'bias=', bias) predictedLabel = np.dot(Weight, feature) + bias print("[PredictedValue] ", predictedLabel) lossMSE_learning_step_1 = f_Loss_MSE(feature=feature, Weight=Weight, bias=bias, label = label) print("Loss-MSE",lossMSE, "->", lossMSE_learning_step_1) plt.subplot(1,5,3) plt.title("Step2") plt.plot(feature, predictedLabel) plt.scatter(feature, label) print("========== Weight Adjustment [Step 3] ==========") Weight, bias = slr1.f_weight_adjust(feature=feature, Weight=Weight, bias=bias, label=label, learningRate=learningRate) print('[Step2]','Weight=', Weight, 'bias=', bias) predictedLabel = np.dot(Weight, feature) + bias print("[PredictedValue] ", predictedLabel) lossMSE_learning_step_2 = f_Loss_MSE(feature=feature, Weight=Weight, bias=bias, label = label) print(lossMSE, "->", lossMSE_learning_step_1, "->", lossMSE_learning_step_2) plt.subplot(1,3,3) plt.title("Step3") plt.plot(feature, predictedLabel) plt.scatter(feature, label) plt.show() print("========== Weight Adjustment [Step 4] ==========") Weight, bias = slr1.f_weight_adjust(feature=feature, Weight=Weight, bias=bias, label=label, learningRate=learningRate) print('[Step3]','Weight=', Weight, 'bias=', bias) predictedLabel = np.dot(Weight, feature) + bias print("[PredictedValue] ", predictedLabel) lossMSE_learning_step_3 = f_Loss_MSE(feature=feature, Weight=Weight, bias=bias, label = label) print(lossMSE, "->", lossMSE_learning_step_1, "->", lossMSE_learning_step_2, "->", lossMSE_learning_step_3) plt.subplot(1,5,4) plt.title("Step3") plt.plot(feature, predictedLabel) plt.scatter(feature, label) plt.show()
7a132fc02073113a1d2a39245b183b7350ed5625
ddelgadoJS/GameOfLife
/Algorithm.py
2,619
3.71875
4
from random import randint # Input: rows of grid, columns of grid. # Output: list of desired size, with random life organisms. # Creates array to contain the organisms. def createGrid(rows, columns): grid = [[0 for i in range(rows)] for j in range(columns)] for i in range(0, rows): for j in range(0, columns): grid[i][j] = randint(0, 1) return grid # Input: last generation grid. # Output: new generation grid. # Updates the grid with next generation. def newGeneration(grid): newGrid = [[0 for i in range(len(grid))] for j in range(len(grid[0]))] for i in range(0, len(grid)): for j in range(0, len(grid[0])): newGrid[i][j] = checkLife(i, j, grid) return newGrid # Input: organism to check. # Output: state of organism. # Checks if organism will be alive or dead in the next generation. def checkLife(i, j, grid): leftColumn, rightColumn, upRow, downRow = 0, 0, 0, 0 neighbors = 0 # The grid is circular. # If organism is in column 0, left column is last. if j - 1 < 0: leftColumn = len(grid[0]) - 1 else: leftColumn = j - 1 # If organism is in last column, right column is 0. if j + 1 == len(grid): rightColumn = 0 else: rightColumn = j + 1 # If organism is in first row, up column is last. if i - 1 < 0: upRow = len(grid) - 1 else: upRow = i - 1 # If organism is in last row, down row is 0. if i + 1 == len(grid): downRow = 0 else: downRow = i + 1 # Checking neighbors. # IMPROVE THIS if grid[upRow][leftColumn] == 1: neighbors += 1 if grid[upRow][j] == 1: neighbors += 1 if grid[upRow][rightColumn] == 1: neighbors += 1 if grid[i][leftColumn] == 1: neighbors += 1 if grid[i][rightColumn] == 1: neighbors += 1 if grid[downRow][leftColumn] == 1: neighbors += 1 if grid[downRow][j] == 1: neighbors += 1 if grid[downRow][rightColumn] == 1: neighbors += 1 # Checking alive cell. # 1. Any live cell with fewer than two live neighbors dies, as if by under population. # 2. Any live cell with two or three live neighbors lives on to the next generation. # 3. Any live cell with more than three live neighbors dies, as if by overpopulation. if grid[i][j] == 1: if neighbors < 2: return 0 elif neighbors > 3: return 0 else: return 1 # Checking dead cell. # 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. else: if neighbors == 3: return 1 else: return 0
a3e557867002df8136d341752f1664adc0e09009
Pato9/platzi-python
/introduccion_pensamiento_logico/fibonacci.py
330
3.984375
4
""" recursividad ejemplo fibonacci """ def fibonacci(n): """ Este metodo es demasiado ineficiente """ if n == 0 or n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) n = int(input('Ingrese un numero mayor a 0:')) if n>0: print(f'En el mes {n} habra un total de {fibonacci(n)}')
b15223561a2a94b5e76f30e405826e84071c6b7e
Pato9/platzi-python
/estadistica-computacional/probabilidades.py
2,476
3.625
4
import random def mayor_a_numero(cantidad_tiros,numero): dado = [1,2,3,4,5,6] numeros = [] for i in dado: if i>numero: numeros.append(i) if numero>0 and numero<7: total_dados = len(dado) total_posibilidades = len(numeros) print(f'{total_posibilidades}-{total_dados}') posibilidad = (total_posibilidades/total_dados)**cantidad_tiros return posibilidad*100 def bolas(colores): """ Ejercicio 1 probabilidad de obtener uno de color azul y el segundo sea de color rojo ya que uno depende de otra es un evento dependiente P(A y B) = P(A) * P(B|A) """ color1,color2 = colores print(color1,'-',color2) bolas = {"verde":3, "rojo":5, "azul":2} cantidad_bolas = 0 c_color_1 = 0 c_color_2 = 0 for color,valor in bolas.items(): cantidad_bolas+=valor if color1 == color: c_color_1 = valor elif color2 == color: c_color_2 = valor p_a = (c_color_1/cantidad_bolas) p_b_a = (c_color_2/(cantidad_bolas-1)) probabilidad = p_a * p_b_a return round(probabilidad*100,2) #print(p_a*100,'%') #def cantidad_simulaciones(cantidad_simulaciones): def dinero_helado(): """ Evendo independiente primer evento : el 8% de las personas de x lugar ganan mas de 1000usd segundo evento : el 60% le gustan los helados ¿si se selecciona una persona en este lugar cual es la posibilidad de que gane mas de 1000usd y le guste el helado """ p_a = 0.08 p_b = 0.6 probabilidad = p_a*p_b print(probabilidad*100,'%') #TODO: generar un sistema que tire dados de forma aleatoria en una cierta cantidad # de tiros y if __name__ == '__main__': #ejercicio 1 #numeros_tiros = int(input('Cuantas veces tiramos los datos')) #numero_mayor = int(input('Ingrese cuandas posibiliodades tiene a partir del numero :')) #print(mayor_a_numero(numeros_tiros,numero_mayor)) #ejercicio 2 #print('Los colores a elegir son verdes,rojos,azules') #print('vea la probabilidad de que la primera sea del color 1 y la segunda color 2') #input_color_1 = input('Ingrese primer color \n>') #input_color_2 = input('Ingrese segundo color \n>') #input_colores = [input_color_1.lower(),input_color_2.lower()] #print(bolas(input_colores)) #ejercicio 3 #dinero_helado()
b7e1cd08479672a4d231a4b8e7b12c61b195e32c
Pato9/platzi-python
/estadistica-computacional/barajas.py
1,333
3.609375
4
import random import collections PALOS = ["corazon","trebol","diamante","pica"] VALORES = ['as','1','2','3','4','5','6','7','8','9','10','J','Q','K'] def formar_baraja(): cartas = [] for palo in PALOS: for valores in VALORES: cartas.append((palo,valores)) return cartas def obtener_mano(barajas,tamano_mano): mano = random.sample(barajas,tamano_mano) return mano def main(tamano_mano,intentos): baraja = formar_baraja() manos = [] for _ in range(intentos): mano = obtener_mano(baraja,tamano_mano) manos.append(mano) pares = 0 for mano in manos: valores = [] for carta in mano: valores.append(carta[1]) counter = dict(collections.Counter(valores)) print(counter) for valor in counter.values(): if valor == 2: pares+=1 #solamente encontrara un par dentro de la mano break probabilidad = pares/intentos print(f'La probabilidad de encontrar pares en {tamano_mano} es de {probabilidad}') if __name__ == '__main__': #tamano_mano = int(input('Tamaño de la mano\n>')) #intentos = int(input('Cantidad de intentos\n>')) main(5,100)
d3eda4714e91b13bd5e007a57af5be14aacd9a78
Pato9/platzi-python
/introduccion_pensamiento_logico/aproximaciones.py
448
3.8125
4
""" aproximacion de soluciones """ objetivo = int(input('Ingrese un numero : ')) epsilon = 0.01 paso = epsilon**2 respuesta = 0.0 while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo: print(abs(respuesta**2-objetivo)) respuesta += paso if abs(respuesta**2 - objetivo) >= epsilon: print(f' No se encontro la raiz cuadrada de {objetivo}') else: print(f'La raiz cuadadra de {objetivo} es {respuesta}')
3af0b975d8fe1dd1f85a860fce8f9438933f9648
Rajat6697/hackerrank-30days-coding-challenge
/Day-3/apple_and_orange.py
1,324
4.03125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countApplesAndOranges' function below. # # The function accepts following parameters: # 1. INTEGER s # 2. INTEGER t # 3. INTEGER a # 4. INTEGER b # 5. INTEGER_ARRAY apples # 6. INTEGER_ARRAY oranges # def countApplesAndOranges(s, t, a, b, apples, oranges): apple_count= 0 orange_count= 0 for apple in apples: if s<=(apple+a)<=t: apple_count+=1 else: continue for orange in oranges: if s<=(orange+b)<=t: orange_count+=1 else: continue print(apple_count) print(orange_count) if __name__ == '__main__': first_multiple_input = input().rstrip().split() s = int(first_multiple_input[0]) t = int(first_multiple_input[1]) second_multiple_input = input().rstrip().split() a = int(second_multiple_input[0]) b = int(second_multiple_input[1]) third_multiple_input = input().rstrip().split() m = int(third_multiple_input[0]) n = int(third_multiple_input[1]) apples = list(map(int, input().rstrip().split())) oranges = list(map(int, input().rstrip().split())) countApplesAndOranges(s, t, a, b, apples, oranges)
ba9f96ccc40785bc8d4b07da88221b56f66585a3
PRAVEEN-ARAVENDAN/Self-Learning
/Python Data Structures/Praveen_Stack_Using_Linked_List.py
1,710
3.765625
4
''' STACK OPERATIONS s :- stack n :- node that is being pushed push(s,n) :- pushed at the top of the stack pop(s) :- removes the top element and returns it Note :- A stack is both Abstract Data Type(ADT) and Data Structure. ADT :- Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations. So a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT as a black box which hides the inner structure and design of the data type. ''' class Node(): def __init__(self, data): self.data = data self.next = None class Stack(): def __init__(self): self.head = None self.top = None def traversal(s): temp = s.head #temporary pointer to point to head a = '' while temp != None: #iterating over stack a = a+str(temp.data)+'\t' temp = temp.next print(a) def is_empty(s): if s.top == None: return True return False def push(s, n): if is_empty(s): #empty s.head = n s.top = n else: s.top.next = n s.top = n def pop(s): if is_empty(s): print("Stack Underflow") return -1000 else: x = s.top.data if s.top == s.head: # only one node s.top = None s.head = None else: temp = s.head while temp.next != s.top: #iterating to the last element temp = temp.next temp.next = None del s.top s.top = temp return x if __name__ == '__main__': s = Stack() a = Node(10) b = Node(20) c = Node(30) pop(s) push(s, a) push(s, b) push(s, c) traversal(s) pop(s) traversal(s)
e047b285aa5bf1b187187c52a22fae191836ed0f
chubaezeks/Learn-Python-the-Hard-Way
/ex19.py
1,804
4.3125
4
#Here we defined the function by two (not sure what to call them) def cheese_and_crackers (cheese_count, boxes_of_crackers): print "You have %d cheese!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" #We take that function and give it a number directly, so no need to define what's in the function #Just give the function numbers print "We can just give the funtion numbers directly:" cheese_and_crackers (20,30) #We can also create variables that contain numbers print "OR, we can use variables from our script:" amount_of_cheese = 10 amount_of_crackers = 50 #Then run the function by those variables cheese_and_crackers(amount_of_cheese, amount_of_crackers) #Or we can run calculations within the function too print "We can even do math inside too:" cheese_and_crackers(10 + 20, 5 +6) #Remember those variables we created earlier? We can also include them in the function #as well as numbers to run calculations print "And we can combine the two, variables and math:" cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) def me_and_you (chuba,mo): print "You love %d" % chuba print "I love %d" % mo print "We both love each other.\n" print "We can represent ourselves as numbers!:" me_and_you (100,100) print "We can add variables and use it within the function:" half_of_me = 0.5 half_of_you = 0.5 print " Let's work the math of both of us:" me_and_you (25+25, 25+25) print " We combine numbers and variables to get more of us:" me_and_you (half_of_me + 0.5, half_of_you + 0.5) me= 10 +10 you=10+10 print "What other combination can we run?:" me_and_you(half_of_me,half_of_you) print "What happens when we make a family?:" me_and_you(me + 1, you + 1)
5716d35b256e1fd21e84c40b28f1389817ebd777
saikotprof/thinkdiff
/coding-problems/binary-search.py
478
3.921875
4
def binary_search(arr, item): low = 0 high = len(arr) - 1 while low <= high: mid = int((low + high) / 2) if arr[mid] == item: return mid elif arr[mid] < item: low = mid + 1 else: high = mid - 1 return -1 if __name__ == '__main__': arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] assert binary_search(arr1, 10) == -1 assert binary_search(arr1, 5) == 4 assert binary_search(arr1, 1) == 0
8700663af1c7747f2a4a06f8526928122fd7b0c9
sadfool1/Sudoko_solver
/object-oriented-sudoku.py
4,700
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 31 21:26:25 2020 @author: jameselijah """ import numpy as np import random as rn import math import sys import traceback class board_creation: def __init__ (self): board = [ [1,3,2,4,5,6,7,8,9], [2,1,3,4,5,6,7,8,9], [1,2,3,4,5,6,7,8,9], [1,2,3,4,5,6,7,8,9], [1,2,3,4,5,6,7,8,9], [1,2,3,4,6,5,7,8,9], [1,2,3,4,5,6,7,8,9], [1,2,3,4,5,6,7,8,9], [1,2,3,4,5,6,7,8,9] ] self.board = board self.difficulty = None self.column_checker() def row(self, row): for ROW in range(len(self.board)): return self.board[row] def col(self, col): """ INPUT: BOARD & TARGET COLUMN OUTPUT: RETURN the column """ column = [] for i in range(9): temp = self.board[i][col] column.append(temp) return column def column_similarity (self, row, col): """ want to check if that exact column has other numbers similar to it. POSSIBLE OUTPUT: 1. None --> that number has no similar numbers in that column 2. [i, col, False] --> i, col will tell us where that exact coordinate of similarity in first encounter """ my_number = self.board[row][col] for i in range (9): if (i,col) == (row,col): continue elif self.board[i][col] == my_number: return [i, col, False] else: continue def column_checker(self): """ INPUT: BOARD OUTPUT: BOARD result. Main function is to fascilate the board column ==> constantly checking if the column is orrect or not """ for i in range(9): temp = set(self.col(i)) length_temp = len(temp) while length_temp < 9: self.fix_column(i) length_temp = len(set(self.col(i))) #update the value of length if length_temp < 9: continue else: break #for i in range(len(self.board)): # print (self.board[i]) return print (self.board) def fix_column(self, col): """ INPUT: BOARD & target column OUTPUT: FIXED BOARD & playable game """ counter = 0 for i in range(9): counter = counter + 1 for j in range(8): if counter < 9: if self.column_similarity(i, j) == None: #this is to show that there is NO similarity, then we just skip it continue elif self.column_similarity(i, j)[2] == False: temporary_row = self.board[i] for TARGET in range(len(temporary_row)): if temporary_row[TARGET] == temporary_row[j]: random_number = rn.randint(j+1, 8) temp = temporary_row[random_number] temporary_row[random_number] = temporary_row[TARGET] temporary_row[TARGET] = temp else: continue else: if self.column_similarity(i, j) == None: continue elif self.column_similarity(i, j)[2] == False: temporary_row = self.board[i] for TARGET in range(len(temporary_row)): if temporary_row[TARGET] == temporary_row[j]: random_number = rn.randint(j+1, 8) temp = temporary_row[random_number] temporary_row[random_number] = temporary_row[TARGET] temporary_row[TARGET] = temp if __name__ == '__main__': try: board_creation() #run the class except Exception as e: traceback.print_exc() sys.exit(1)
f7d2559874c974c92376fcdc0df311ae3fd05a41
DiegoCodes/Tarea_03
/TiendaDeVideo.py
593
3.6875
4
#encoding: UTF-8 #Autor: Diego Perez AKA DiegoCodes #Calculador de Precio por Peliculas #Suma el costo de las peliculas multiplicandolas por su precio correspondiente def calculateRentCost(new,normal): total = (45*new)+(27*normal) return total def main(): new = int(input("Ingrese cantidad de peliculas estreno rentadas")) normal = int(input("Ingrese cantidad de peliculas normales rentadas")) total = calculateRentCost(new,normal) print("Peliculas de estreno rentadas:",new) print("Peliculas normales rentadas:",normal) print("Total a Pagar: $",total) main()
11bd5c5854a6b42e651779862a4b7a5e6716b098
ziyunhai/zhuhai_air_show
/code/dataexport/Python/CrossBuild/extracter/nicefloat.py
3,576
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- import math class nicefloat(float): @staticmethod def str(num): if not num or num+1 == num or num != num: return float.__repr__(num) f, e = math.frexp(num) if num < 0: f = -f f = int(f*2**53) e -= 53 if e >= 0: be = 2**e if f != 2**52: r, s, mp, mm = f*be*2, 2, be, be else: be1 = be*2 r, s, mp, mm = f*be1*2, 4, be1, be elif e == -1074 or f != 2**52: r, s, mp, mm = f*2, 2**(1-e), 1, 1 else: r, s, mp, mm = f*4, 2**(2-e), 2, 1 k = 0 round = (f%2 == 0) while not round and r+mp*10 <= s or r+mp*10 < s: r *= 10; mp *= 10; mm *= 10; k -= 1 while round and r+mp >= s or r+mp > s: s *= 10; k += 1 l = [] while True: d, r = divmod(r*10, s) d = int(d) mp *= 10 mm *= 10 tc1 = round and r == mm or r < mm tc2 = round and r+mp == s or r+mp > s if not tc1: if not tc2: l.append(d) continue l.append(d+1) elif not tc2 or r*2 < s: l.append(d) else: l.append(d+1) break if k <= 0: l.insert(0, "0" * abs(k)) l.insert(0, "0.") elif k < len(l): l.insert(k, ".") else: l.append("0" * (k - len(l))) l.append(".0") if num < 0: l.insert(0, "-") return "".join([str(x) for x in l]) def __repr__(self): return self.str(self) def __str__(self): return self.str(self) def __neg__(self): return nicefloat(float.__neg__(self)) def __pos__(self): return nicefloat(float.__pos__(self)) def __abs__(self): return nicefloat(float.__abs__(self)) def __add__(self, other): return nicefloat(float.__add__(self, other)) def __radd__(self, other): return nicefloat(float.__radd__(self, other)) def __sub__(self, other): return nicefloat(float.__sub__(self, other)) def __rsub__(self, other): return nicefloat(float.__rsub__(self, other)) def __mul__(self, other): return nicefloat(float.__mul__(self, other)) def __rmul__(self, other): return nicefloat(float.__rmul__(self, other)) def __div__(self, other): return nicefloat(float.__div__(self, other)) def __rdiv__(self, other): return nicefloat(float.__rdiv__(self, other)) def __pow__(self, other): return nicefloat(float.__pow__(self, other)) def __rpow__(self, other): return nicefloat(float.__rpow__(self, other)) def __truediv__(self, other): return nicefloat(float.__truediv__(self, other)) def __rtruediv__(self, other): return nicefloat(float.__rtruediv__(self, other)) def __floordiv__(self, other): return nicefloat(float.__floordiv__(self, other)) def __rfloordiv__(self, other): return nicefloat(float.__rfloordiv__(self, other)) def __coerce__(self, other): return self, nicefloat(other) def __divmod__(self, other): div, mod = float.__divmod__(self, other) return nicefloat(div), nicefloat(mod) def __rdivmod__(self, other): div, mod = float.__divmod__(self, other) return nicefloat(div), nicefloat(mod)
965cd05ce217b1b5d27cefb89b62935dc250a692
hmkthor/play
/play_006.py
590
4.40625
4
""" Change a Range of Item Values To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values: """ thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermelon"] print(thislist) thislist = ["apple", "banana", "cherry"] thislist[1] = ["blackcurrant", "watermelon"] print(len(thislist)) print(thislist) thislist = ["apple", "banana", "cherry"] thislist[1:2] = ["blackcurrant", "watermelon"] print(len(thislist)) print(thislist)
a297dc7d2f114f089a2bda19c9267a9c3c133b00
honism/CP3-Thanaphol-Chaisorana
/Exercise21_Thanaphol_C.py
1,314
3.671875
4
from tkinter import * def Click(event): new_height = float(textboxHeight.get()) new_weight = float(textboxWeight.get()) BMI = new_weight/((new_height/100)**2) if BMI > 30.0: result.configure(text="BMI = %f = %s"%(BMI,"อ้วนมาก")) elif 25.0<=BMI<=29.9: result.configure(text="BMI = %f = %s" % (BMI, "อ้วน")) elif 23.0<=BMI<=24.9: result.configure(text="BMI = %f = %s" % (BMI, "น้ำหนักเกิน")) elif 18.6<=BMI<=22.9: result.configure(text="BMI = %f = %s" % (BMI, "น้ำหนักเปกติ เหมาะสม")) else: result.configure(text="BMI = %f = %s" % (BMI, "ผอมเกินไป")) window = Tk() window.title("Body Mass Index Calculate") Height = Label(window,text = "ส่วนสูง(cm):") Height.grid(row=0,column=0) textboxHeight = Entry(window) textboxHeight.grid(row=0,column=1) Weight = Label(window,text = "น้ำหนัก(Kg):") Weight.grid(row=1,column=0) textboxWeight = Entry(window) textboxWeight.grid(row=1,column=1) calculatebutton = Button(window,text="Calculate") calculatebutton.bind("<Button-1>",Click) calculatebutton.grid(column=0) result = Label(window,text="ผลลัพธ์") result.grid(row=2,column=1) window.mainloop()
f33d33a878f1a604bda43830403b2429b43a8039
srinidhi82/LPTHW
/strings3.py
361
3.765625
4
days = "Mon Tue Wed Thu Fri Sat Sun" months = "\nJan\nFeb\nMarch\nApril\nMay" #Below print here uses \ character to escape double quotes print ("I am \"Super\" tall") print("The days are:" , days) print ("here are the months:", months) print(""" Hey babe! I know what it says!! You said so e'h dont you dare hahaha Bye """)
3dacd128c23c8f43e64922ca50e1b90def030ba4
jignatius/QuickWeather
/QuickWeather/QuickWeather.py
1,517
3.8125
4
#! python3 # QuickWeather.py - Prints the weather for a location from the command line import json, requests, sys def current(location): # Download the JSON data from OpenWeatherMap.org's API url = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&APPID=2c72b19f0de8d493671eb73e9c4cf39c" % (location) response = requests.get(url) # Load JSON data into a Python variable weatherData = json.loads(response.text) # Print weather description w = weatherData['weather'] print('Current weather in %s' % (location)) print() print(w[0]['main'], '-', w[0]['description']) m = weatherData['main'] print('Current temperature is %3.2fC but feels like %3.2fC' % (m['temp'], m['feels_like'])) print() def forecast(location): url = "http://api.openweathermap.org/data/2.5/forecast?q=%s&APPID=2c72b19f0de8d493671eb73e9c4cf39c" % (location) response = requests.get(url) # Load JSON data into a Python variable weatherData = json.loads(response.text) w = weatherData['list'] print('Tomorrow:') print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description']) print() print('Day after tomorrow:') print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description']) print() def main(): # Compute location from the command line arguments if len(sys.argv) < 2: print('Usage: QuickWeather.py location') sys.exit() location = ' '.join(sys.argv[1:]) current(location) forecast(location) if __name__ == "__main__": main()
359ce1c69a952d51fd9024adade90be51e6ebb00
LiuPengPython/algorithms
/algorithms/strings/is_rotated.py
324
4.3125
4
""" Given two strings s1 and s2, determine if s2 is a rotated version of s1. For example, is_rotated("hello", "llohe") returns True is_rotated("hello", "helol") returns False accepts two strings returns bool """ def is_rotated(s1, s2): if len(s1) == len(s2): return s2 in s1 + s1 else: return False
661264a31181a11a7f61e209d0a93914081355b6
fabiogaluppo/AdventOfCode2020
/day_20.py
9,157
3.5625
4
#python day_20.py < .\input\input20.txt import sys import math import functools import itertools def readAllLines(): return [line.rstrip() for line in sys.stdin] TOP, RIGHT, DOWN, LEFT = 0, 1, 2, 3 def flip(rows): isString = isinstance(rows[0], str) if isString: rows = [list(row) for row in rows] for i in range(len(rows)): rows[i] = rows[i][::-1] #reverse if isString: rows = [''.join(row) for row in rows] return rows def rotateSquare(rows): #rotate 90 degrees clockwise i, j, k, l = 0, len(rows[0]), 0, len(rows) assert j == l, "Number of columns must be the same number of rows" isString = isinstance(rows[0], str) if isString: rows = [list(row) for row in rows] while i < j: for c in range(i, j - 1): rows[k + l - 1 - c][i], rows[k][c] = rows[k][c], rows[k + l - 1 - c][i] for r in range(k + 1, l): rows[r][i], rows[l - 1][r] = rows[l - 1][r], rows[r][i] for c in range(i + 1, j): rows[l - 1][c], rows[k + l - 1 - c][j - 1] = rows[k + l - 1 - c][j - 1], rows[l - 1][c] i = i + 1 j = j - 1 k = k + 1 l = l - 1 if isString: rows = [''.join(row) for row in rows] return rows class Tile: def __init__(self, id, rows): self._id = id self._rows = rows self._borders = self.__computeBorders(rows) def flip(self): self._rows = flip(self._rows) self._borders = self.__computeBorders(self._rows) def rotate(self): self._rows = rotateSquare(self._rows) self._borders = self.__computeBorders(self._rows) def deepcopy(self): return Tile(self._id, self._rows) def __borderToInt(self, xs): return int(''.join(['1' if x == '#' else '0' for x in xs]), 2) def __computeBorders(self, rows): #clockwise: TOP, RIGHT, DOWN, LEFT return [self.__borderToInt(rows[0]), self.__borderToInt([row[len(row) - 1] for row in rows]), self.__borderToInt(rows[len(rows) - 1]), self.__borderToInt([row[0] for row in rows])] @property def id(self): return self._id @property def rows(self): return self._rows @property def borders(self): return self._borders def __str__(self): return "Tile: {}".format(self._id) def __repr__(self): return self.__str__() def flipAll(tiles): for tile in tiles: tile.flip() def rotateAll(tiles): for tile in tiles: tile.rotate() def indexToRowCol(i, N): #square dimension N * N row, col = int(i / N), int(i % N) return (row, col) def rowColToIndex(row, col, N): #square dimension N * N return row * N + col def printRows(rows): print(''.join([(row + '\n') for row in rows]), sep = '') def testRotate(): a = ['ABC', 'DEF', 'GHI'] b = ['ABCD', 'EFGH', 'IJKL', 'MNOP'] c = ['ABCDE', 'FGHIJ', 'KLMNO', 'PQRST', 'UVXYZ'] d = ['AB', 'DE'] for x in [a, b, c, d]: print('before:') printRows(x) print('after:') printRows(rotateSquare(x)) def findSquareArrangementRec(tiles, acc, N): def generateTransitions(tile): #9 transitions - flips and rotations until the original source yield tile tile.flip() yield tile for _ in range(3): tile.flip() tile.rotate() yield tile tile.flip() yield tile tile.flip() tile.rotate() yield tile if tiles == []: return (True, acc) for i, t in enumerate(tiles): t = t.deepcopy() it = generateTransitions(t) for _ in range(8): t = next(it) if acc == []: acc.append(t) result = findSquareArrangementRec(tiles[:i] + tiles[i + 1:], acc, N) if result[0]: return result else: acc.pop() else: match = [] row, col = indexToRowCol(len(acc), N) #top if (0 <= row - 1 < N and 0 <= col < N): j = rowColToIndex(row - 1, col, N) t_ = acc[j] match.append(t.borders[TOP] == t_.borders[DOWN]) #right if (0 <= row < N and 0 <= col + 1 < N): j = rowColToIndex(row, col + 1, N) if (j < len(acc)): t_ = acc[j] match.append(t.borders[RIGHT] == t_.borders[LEFT]) #down if (0 <= row + 1 < N and 0 <= col < N): j = rowColToIndex(row + 1, col, N) if (j < len(acc)): t_ = acc[j] match.append(t.borders[DOWN] == t_.borders[TOP]) #left if (0 <= row < N and 0 <= col - 1 < N): j = rowColToIndex(row, col - 1, N) t_ = acc[j] match.append(t.borders[LEFT] == t_.borders[RIGHT]) if (all(match)): acc.append(t) result = findSquareArrangementRec(tiles[:i] + tiles[i + 1:], acc, N) if result[0]: return result else: acc.pop() #t = next(it) #don't need, because it was cloned and will be discarded return (False, acc) def findSquareArrangement(tiles): return findSquareArrangementRec(tiles, [], int(math.sqrt(len(tiles)))) def flatmap(f, xs): return itertools.chain.from_iterable(map(f, xs)) def identity(): return lambda x: x def countIf(xs, target): return functools.reduce(lambda acc, x: acc + (1 if x == target else 0), xs, 0) def readTiles(): lines = readAllLines() i = 0 tiles = [] while lines != []: t = lines[i:i+12] lines = lines[i+12:] id = int(t[0].split(' ')[1][:-1]) rows = t[1:-1] tiles.append(Tile(id, rows)) return tiles def cutBordersAndJoin(tiles): rows = [[row[1:-1] for row in tile.rows[1:-1]] for tile in tiles] N, M = int(math.sqrt(len(tiles))), len(rows[0]) temp = [] for row in range(N): for j in range(M): line = ''.join([rows[rowColToIndex(row, col, N)][j] for col in range(N)]) temp.append(line) return temp def findSeaMonsters(rows): def generateTransitions(rows): #9 transitions - flips and rotations until the original source yield rows rows = flip(rows) yield rows for _ in range(3): rows = flip(rows) rows = rotateSquare(rows) yield rows rows = flip(rows) yield rows rows = flip(rows) rows = rotateSquare(rows) yield rows def internalFindSeaMonsters(rows): #find in a square matrix N = len(rows) assert len(rows[0]) == N, "Number of columns must be the same number of rows" seaMonsterPattern = [" # ", "# ## ## ###", " # # # # # # "] H, W = len(seaMonsterPattern), len(seaMonsterPattern[0]) #scanning the pattern - to improve scanning, just jump pattern width if there is a match coords = [] for i in range(N - H): for j in range(N - W): for k in range(H): match = False for l in range(W): if seaMonsterPattern[k][l] == '#': match = rows[i + k][j + l] == seaMonsterPattern[k][l] if not match: break if not match: break if match: coords.append((i, j)) return coords it = generateTransitions(rows) for i in range(8): rows = next(it) coords = internalFindSeaMonsters(rows) if len(coords) > 0: return (coords, rows) return ([], rows) def day20_part1(): _, tiles = findSquareArrangement(readTiles()) N = int(math.sqrt(len(tiles))) corners = [tiles[rowColToIndex(0, 0, N)], tiles[rowColToIndex(0, N - 1, N)], tiles[rowColToIndex(N - 1, 0, N)], tiles[rowColToIndex(N - 1, N - 1, N)]] #DBG #print(corners) cornersMul = functools.reduce(lambda acc, t: acc * t.id, corners, 1) print(cornersMul) def day20_part2(): _, tiles = findSquareArrangement(readTiles()) rows = cutBordersAndJoin(tiles) coords, rows = findSeaMonsters(rows) #DBG #printRows(rows) #print(coords) flattenedGrid = list(flatmap(identity(), rows)) notPartOfSeaMonsters = countIf(flattenedGrid, '#') - len(coords) * 15 print(notPartOfSeaMonsters) if __name__ == "__main__": #day20_part1() #Your puzzle answer was 19955159604613. day20_part2() #Your puzzle answer was 1639.
a807409aea1617cedddcf09b6c6223b56affe77b
Si047p/movie_trailer
/media.py
650
4.0625
4
""" Defines media types with their attributes """ class Movie(): """Class stores the information related to a movie. Attributes: movie_title: The movie's title. poster_image: URL to the movie's poster or box art. trailer_youtube: URL to the movie's trailer on YouTube """ def __init__(self, movie_title, poster_image, trailer_youtube): """Inits SampleClass with title, image url and trailer url""" self.title = movie_title #Assign title self.poster_image_url = poster_image #Assign image url self.trailer_youtube_url = trailer_youtube #Assign trailer url
09764df12da53d7bbdcc732d52aa73c8938b42ed
togrba/dbtech
/lab2/menutest.py
19,649
3.734375
4
#!/usr/bin/python import pgdb import matplotlib import matplotlib.pyplot as plt import numpy as np from sys import argv class Program: def __init__(self): #PG-connection setup # local server: params = {'host':'localhost', 'user':'postgres', 'database':'postgres', 'password':''} self.conn = pgdb.Connection(**params) self.conn.autocommit=False # specify the command line menu here self.actions = [self.population_query, self.exit] # menu text for each of the actions above self.menu = ["Test hypotheses 🤔", "Exit"] self.explore_menu = ["Latitute", "Elevation"] self.cur = self.conn.cursor() def print_menu(self): """Prints a menu of all functions this program offers. Returns the numerical correspondant of the choice made.""" for i,x in enumerate(self.menu): print("%i. %s"%(i+1,x)) return self.get_int() def print_explore_menu(self): """Prints a menu of all functions this program offers. Returns the numerical correspondant of the choice made.""" for i,x in enumerate(self.explore_menu): print("%i. %s"%(i+1,x)) return self.get_explore_int() def get_int(self): """Retrieves an integer from the user. If the user fails to submit an integer, it will reprompt until an integer is submitted.""" while True: try: choice = int(input("Choose: ")) if 1 <= choice <= len(self.menu): return choice print("Invalid choice.") except (NameError,ValueError, TypeError,SyntaxError): print("That was not a number...") def get_explore_int(self): """Retrieves an integer from the user. If the user fails to submit an integer, it will reprompt until an integer is submitted.""" while True: try: choice = int(input("Choose: ")) if 1 <= choice <= len(self.explore_menu): return choice print("Invalid choice.") except (NameError,ValueError, TypeError,SyntaxError): print("That was not a number...") def exit(self): self.cur.close() self.conn.close() exit() def run(self): while True: try: self.actions[self.print_menu()-1]() except IndexError: print("Bad choice") continue def population_query(self): print("\nExplore population by:") if self.print_explore_menu() == 1: self.latitude_program() else: self.elevation_program() '''Elevation functions''' def elevation_program(self): minelv = 0 while True: try: if minelv == 0 or minelv < -30 or minelv > 4330: minelv = int(input("\nChoose the minimum elevation for a city to explore: ")) if -30 <= minelv <= 4330: maxelv = int(input("Choose the maximum elevation for a city to explore: ")) if -30 <= maxelv <= 4330: query = "SELECT name, country, elevation FROM city WHERE elevation >=%s AND elevation <=%s ORDER BY elevation" % (minelv, maxelv) self.cur.execute(query) self.print_elevation_options() [pop_data1, elv_data1, chosen_city1] = self.choose_city1_elevation() print("\nNow find a second city with") self.elevation_program_next(pop_data1, elv_data1, chosen_city1) print("Invalid choice. Choose an elevation between -30 and 4330") else: maxelv = int(input("Choose the maximum elevation for a city to explore: ")) if -30 <= maxelv <= 4330: query = "SELECT name, country, elevation FROM city WHERE elevation >=%s AND elevation <=%s ORDER BY elevation" % (minelv, maxelv) self.cur.execute(query) self.print_elevation_options() [pop_data1, elv_data1, chosen_city1] = self.choose_city1_elevation() print("\nNow find a second city with") self.elevation_program_next(pop_data1, elv_data1, chosen_city1) print("Invalid choice. Choose an elevation between -30 and 4330") except (NameError, ValueError, TypeError, SyntaxError): print("That was not a number...") def elevation_program_next(self, pop_data1, elv_data1, chosen_city1): minelv = 0 while True: try: if minelv == 0 or minelv < -30 or minelv > 4330: minelv = int(input("Minimum elevation: ")) if -30 <= minelv <= 4330: maxelv = int(input("Maximum elevation: ")) if -30 <= maxelv <= 4330: query = "SELECT name, country, elevation FROM city WHERE elevation >=%s AND elevation <=%s ORDER BY elevation" % (minelv, maxelv) self.cur.execute(query) self.print_elevation_options() [pop_data2, elv_data2, chosen_city2] = self.choose_city2_elevation(chosen_city1) print("\nPlotting data...\n") self.print_elv_plot(pop_data1, elv_data1, pop_data2, elv_data2, chosen_city1, chosen_city2) self.run() print("Invalid choice. Choose an elevation between -30 and 4330") else: maxelv = int(input("Maximum elevation: ")) if -30 <= maxelv <= 4330: query = "SELECT name, country, elevation FROM city WHERE elevation >=%s AND elevation <=%s ORDER BY elevation" % (minelv, maxelv) self.cur.execute(query) self.print_elevation_options() [pop_data2, elv_data2, chosen_city2] = self.choose_city2_elevation(chosen_city1) print("\nPlotting data...\n") self.print_elv_plot(pop_data1, elv_data1, pop_data2, elv_data2, chosen_city1, chosen_city2) self.run() print("Invalid choice. Choose an elevation between -30 and 4330") except (NameError, ValueError, TypeError, SyntaxError): print("That was not a number...") def print_elevation_options(self): city_data = [] country_data = [] elevation_data = [] result = [] data = self.cur.fetchall() if len(data) != 0: for r in data: city_data.append(r[0]) country_data.append(r[1]) elevation_data.append(float(r[2])) result.append(r) print("-----------------------------------") print("\n".join([", ".join([str(a) for a in x]) for x in result])) print("-----------------------------------") else: print("Oups, no cities within the given latitude") self.elevation_program() def choose_city1_elevation(self): pop_data1 = [] elv_data1 = [] print("\nNow pick one of these cities to compare to another") while True: try: if len(pop_data1) == 0: chosen_city1 = input("Type the name of the city: ") if len(chosen_city1) != 0: chosen_country1 = input("Type the country code for %s: " % chosen_city1) if len(chosen_country1) != 0: query = "SELECT city, country, year, population, elevation FROM popdata WHERE city LIKE '%s' AND country LIKE '%s'" % (chosen_city1, chosen_country1) self.cur.execute(query) data = self.cur.fetchall() for r in data: if (r[0]!=None and r[0]!=None): pop_data1.append(float(r[3])) elv_data1.append(float(r[4])) print("\nYou chose %s, %s at elevation %s" % (chosen_city1, chosen_country1, str(elv_data1).strip("[]"))) return [pop_data1, elv_data1, chosen_city1] else: print("Dropped tuple ", r) print("Hmm. Unknown city.") else: [pop_data2, elv_data2] = self.choose_city2_elevation(chosen_city1) except (NameError, ValueError, TypeError, SyntaxError): print("Hmm. Unknown city.") def choose_city2_elevation(self, chosen_city1): pop_data2 = [] elv_data2 = [] print("\nNow pick one of these cities to compare to %s" % (chosen_city1)) while True: try: if len(pop_data2) == 0: chosen_city2 = input("\nType the name of the city: ") if len(chosen_city2) != 0: chosen_country2 = input("Type the country code for %s: " % chosen_city2) if len(chosen_country2) != 0: query = "SELECT city, country, year, population, elevation FROM popdata WHERE city LIKE '%s' AND country LIKE '%s'" % (chosen_city2, chosen_country2) self.cur.execute(query) data = self.cur.fetchall() for r in data: if (r[0]!=None and r[0]!=None): pop_data2.append(float(r[3])) elv_data2.append(float(r[4])) print("\nYou chose %s, %s at elevation %s" % (chosen_city2, chosen_country2, str(elv_data2).strip("[]"))) return [pop_data2, elv_data2, chosen_city2] else: print("Dropped tuple ", r) print("Hmm. Unknown city.") # else: # print("OJ something went wrong. FIX ERROr") except (NameError, ValueError, TypeError, SyntaxError): print("Hmm. Unknown city.") def print_elv_plot(self, pop_data1, elv_data1, pop_data2, elv_data2, chosen_city1, chosen_city2): plt.scatter(elv_data1, pop_data1, label=chosen_city1) plt.scatter(elv_data2, pop_data2, label=chosen_city2) plt.ylabel("POPULATION") plt.xlabel("ELEVATION") plt.legend(loc='best') plt.title("HYPOTHESIS: The higher the elevation, the lower the population") plt.show() '''Latitude functions''' def latitude_program(self): minlat = 0 while True: try: if minlat == 0 or minlat < -90 or minlat > 90: minlat = int(input("\nChoose the minimum latitude for a city to explore: ")) if -90 <= minlat <= 90: maxlat = int(input("Choose the maximum latitude for a city to explore: ")) if -90 <= maxlat <= 90: query = "SELECT name, country, latitude FROM city WHERE latitude >=%s AND latitude <=%s ORDER BY latitude" % (minlat, maxlat) self.cur.execute(query) self.print_latitude_options() [pop_data1, lat_data1, chosen_city1] = self.choose_city1_latitude() print("\nNow find a second city with") self.latitude_program_next(pop_data1, lat_data1, chosen_city1) print("Invalid choice. Choose a latitude between -90 and 90") else: maxlat = int(input("Choose the maximum latitude for a city to explore: ")) if -90 <= maxlat <= 90: query = "SELECT name, country, latitude FROM city WHERE latitude >=%s AND latitude <=%s ORDER BY latitude" % (minlat, maxlat) self.cur.execute(query) self.print_latitude_options() [pop_data1, lat_data1, chosen_city1] = self.choose_city1_latitude() print("\nNow find a second city with") self.latitude_program_next(pop_data1, lat_data1, chosen_city1) print("Invalid choice. Choose a latitude between -90 and 90") except (NameError, ValueError, TypeError, SyntaxError): print("That was not a number...") def latitude_program_next(self, pop_data1, lat_data1, chosen_city1): minlat = 0 while True: try: if minlat == 0 or minlat < -90 or minlat > 90: minlat = int(input("Minimum latitude: ")) if -90 <= minlat <= 90: maxlat = int(input("Maximum latitude: ")) if -90 <= maxlat <= 90: query = "SELECT name, country, latitude FROM city WHERE latitude >=%s AND latitude <= %s ORDER BY latitude" % (minlat, maxlat) self.cur.execute(query) self.print_latitude_options() [pop_data2, lat_data2, chosen_city2] = self.choose_city2_latitude(chosen_city1) print("\nPlotting data...\n") self.print_lat_plot(pop_data1, lat_data1, pop_data2, lat_data2, chosen_city1, chosen_city2) self.run() print("Invalid choice. Choose a latitude between -90 and 4330") else: maxlat = int(input("Maximum latitude: ")) if -90 <= maxlat <= 90: query = "SELECT name, country, latitude FROM city WHERE latitude >=%s AND latitude <= %s ORDER BY latitude" % (minlat, maxelv) self.cur.execute(query) self.print_latitude_options() [pop_data2, lat_data2, chosen_city2] = self.choose_city2_latitude(chosen_city1) print("\nPlotting data...\n") self.print_lat_plot(pop_data1, lat_data1, pop_data2, lat_data2, chosen_city1, chosen_city2) self.run() print("Invalid choice. Choose a latitude between -90 and 90") except (NameError, ValueError, TypeError, SyntaxError): print("That was not a number...") def print_latitude_options(self): city_data = [] country_data = [] latitude_data = [] result = [] data = self.cur.fetchall() if len(data) != 0: for r in data: city_data.append(r[0]) country_data.append(r[1]) latitude_data.append(float(r[2])) result.append(r) print("-----------------------------------") print("\n".join([", ".join([str(a) for a in x]) for x in result])) print("-----------------------------------") else: print("Oups, no cities within the given latitude") self.latitude_program() def choose_city1_latitude(self): pop_data1 = [] lat_data1 = [] print("\nNow pick one of these cities to compare to another") while True: try: if len(pop_data1) == 0: chosen_city1 = input("Type the name of the city: ") if len(chosen_city1) != 0: chosen_country1 = input("Type the country code for %s: " % chosen_city1) if len(chosen_country1) != 0: query = "SELECT city, country, year, population, latitude FROM popdata WHERE city LIKE '%s' AND country LIKE '%s'" % (chosen_city1, chosen_country1) self.cur.execute(query) data = self.cur.fetchall() for r in data: if (r[0]!=None and r[0]!=None): pop_data1.append(float(r[3])) lat_data1.append(float(r[4])) print("\nYou chose %s, %s at latitude %s" % (chosen_city1, chosen_country1, str(lat_data1).strip("[]"))) return [pop_data1, lat_data1, chosen_city1] else: print("Dropped tuple ", r) print("Hmm. Unknown city.") else: [pop_data2, lat_data2] = self.choose_city2_latitude(chosen_city1) except (NameError, ValueError, TypeError, SyntaxError): print("Hmm. Unknown city.") def choose_city2_latitude(self, chosen_city1): pop_data2 = [] lat_data2 = [] print("\nNow pick one of these cities to compare to %s" % (chosen_city1)) while True: try: if len(pop_data2) == 0: chosen_city2 = input("\nType the name of the city: ") if len(chosen_city2) != 0: chosen_country2 = input("Type the country code for %s: " % chosen_city2) if len(chosen_country2) != 0: query = "SELECT city, country, year, population, latitude FROM popdata WHERE city LIKE '%s' AND country LIKE '%s'" % (chosen_city2, chosen_country2) self.cur.execute(query) data = self.cur.fetchall() for r in data: if (r[0]!=None and r[0]!=None): pop_data2.append(float(r[3])) lat_data2.append(float(r[4])) print("\nYou chose %s, %s at latitude %s" % (chosen_city2, chosen_country2, str(lat_data2).strip("[]"))) return [pop_data2, lat_data2, chosen_city2] else: print("Dropped tuple ", r) print("Hmm. Unknown city.") # else: # print("OJ something went wrong. FIX ERROr") except (NameError, ValueError, TypeError, SyntaxError): print("Hmm. Unknown city.") def print_lat_plot(self, pop_data1, lat_data1, pop_data2, lat_data2, chosen_city1, chosen_city2): plt.scatter(lat_data1, pop_data1, label=chosen_city1) plt.scatter(lat_data2, pop_data2, label=chosen_city2) plt.ylabel("POPULATION") plt.xlabel("LATITUDE (°)") plt.legend(loc='best') plt.title("HYPOTHESIS: The higher the latitude, the lower the population") plt.show() if __name__ == "__main__": print("========================================================================\nWE PRESENT TO YOU OUR HYPOTHESES FOR CITIES AROUND THE 🌍:\n\nThe higher the elevation, the lower the population\nThe higher the latitude (both +/- values), the lower the population\n") db = Program() db.run()
11465b97d86206fa2612a413f467bf000e1ae393
dscpesu/PESU-Chatter-Bot
/cleanup.py
513
3.703125
4
def clean(fname): c="" with open(fname,'r', encoding='utf8', errors ='ignore') as fin: fstring = fin.read().lower() # print(fstring) for i in range(len(fstring)-1): if fstring[i].isalpha() or fstring[i].isdigit() or fstring[i]=='.' or fstring[i]==',' or fstring[i]=="'"or fstring[i]=='-': c=c+fstring[i] elif fstring[i]=='\n': c=c+'\n' elif fstring[i]==" " and fstring[i+1]!=' ': #removes multiple spaces c=c+' ' return c
95c5317ca607b0c938c49ed2a35cde86280b9aed
fsf-silva-ferreira/python-projects
/2 - app_python/aula7_calculadora2.py
851
3.984375
4
#Função: Retorna valor #Método: Não retorna valor class Calculadora: #O método ini não é obrigatório # def __init__(self): # #o init não pode ficar vazio, por coloca-se o pass # pass def soma(self,valor_a,valor_b): return valor_a + valor_b def subtracao(self,valor_a,valor_b): return valor_a - valor_a def multiplicacao(self,valor_a,valor_b): return valor_a * valor_b def divisao(self,valor_a,valor_b): return valor_a / valor_b calculadora = Calculadora() print(calculadora.valor_a) print(calculadora.valor_b) print(calculadora.soma(10,2)) print(calculadora.subtracao(5,3)) print(calculadora.divisao(100,2)) print(calculadora.multiplicacao(10,5)) # print(soma(1,2)) # print(soma(3,25)) # print(subtracao(10,2)) # print(multiplicacao(10,2)) # print(divisao(10,2))
0ed8f79cb1d0d5e71e96066811c0211cca5d53ef
fsf-silva-ferreira/python-projects
/2 - app_python/aula9.py
2,691
3.640625
4
#Recomendado colocar o import no topo do arquivo #Assim, ele pode ser utilizado por qualquer método ou função import shutil def escrever_arquivo(nome_arquivo, texto): arquivo = open(nome_arquivo, 'w') arquivo.write(texto + '\n') arquivo.close() def atualizar_arquivo(nome_arquivo, texto): arquivo = open(nome_arquivo, 'a') arquivo.write(texto + '\n') arquivo.close() def ler_arquivo(nome_arquivo): arquivo = open(nome_arquivo, 'r') # O método read não tem parâmetro # O nome do arquivo já foi passado como parâmetro do método open texto = arquivo.read() print('Conteúdo do arquivo:\n{}'.format(texto)) return texto def media_notas(nome_arquivo): lista_media = [] print('1 - Ler arquivo de notas') aluno_nota = ler_arquivo(nome_arquivo) aluno_nota = aluno_nota.split('\n') print('2 - Aluno e notas em cada posição da lista: {} '.format(aluno_nota)) for x in aluno_nota: lista_notas = x.split(',') aluno = lista_notas[0] lista_notas.pop(0) #Função lambda para calcular a média de cada aluno media = lambda notas: sum([int(i) for i in notas]) / 4 lista_media.append({aluno: media(lista_notas)}) return lista_media def copia_arquivo(origem, destino): #Se o destino tiver apenas o diretório, copia com o mesmo nome do arquivo de origem shutil.copy(origem, destino) def move_arquivo(origem, destino): #Se o destino tiver apenas o diretório, copia com o mesmo nome do arquivo de origem shutil.move(origem, destino) if __name__ == '__main__': # diretorio = 'C:/python-projects/app_python/test.txt' # escrever_arquivo(diretorio, 'Primeira linha. \n') # atualizar_arquivo(diretorio, 'Segunda linha. \nTerceira linha. \n') # ler_arquivo(diretorio) # escrever_arquivo('notas.txt', 'Primeira linha. \n') # aluno = 'Cesar,7,9,3,8' # atualizar_arquivo('notas.txt', aluno) # ler_arquivo('notas.txt') nome_arquivo_notas = 'notas.txt' medias_origem = 'medias.txt' medias_destino = 'C:/python-projects/app_python/dir_copia/medias_copia.txt' dir_move = 'C:/python-projects/app_python/dir_move/medias_move.txt' lista_media = media_notas(nome_arquivo_notas) print('3 - Lista com nomes dos alunos e médias: {}'.format(lista_media)) #Grava em arquivo nome do aluno e média for media in lista_media: atualizar_arquivo(medias_origem, str(media)) print('4 - Ler arquivo de médias') ler_arquivo(medias_origem) copia_arquivo(medias_origem, medias_destino) move_arquivo(medias_origem, dir_move) teste = 'oiuoiu7uujejejej'.split('\n') print(teste)
9c38e7c7a66f7984d2f0179d9212791762314781
mjbouvet/REU-Summer-Project
/AccelLimiting.py
8,378
3.5
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import matplotlib.animation as anim from matplotlib.animation import FuncAnimation plt.rcParams['animation.ffmpeg_path'] = r'H:\Programs\FFmpeg\bin\ffmpeg.exe' FFMpegWriter = anim.writers['ffmpeg'] Writer = anim.FFMpegWriter(fps=10) #Generic Point Class class Point(object): def __init__(self,x,y): self.X = x self.Y = y def getX(self): return self.X def getY(self): return self.Y def setX(self, x): self.X = x def setY(self, y): self.Y = y #Math algorithm to solve for a quadratic equation given 3 values def calc_parabola_vertex(x1,y1,x2,y2,x3,y3): denom = (x1 - x2) * (x1 - x3) * (x2 - x3) A = (x3 * (y2-y1) + x2 * (y1-y3) + x1 * (y3-y2)) / denom B = (x3 *x3 * (y1-y2) + x2*x2 * (y3-y1) + x1*x1 * (y2-y3)) / denom C = (x2 * x3 * (x2-x3) * y1+x3 * x1 * (x3-x1) * y2+x1 * x2 * (x1-x2) * y3) / denom return A,B,C #Determine which subject to look at listOfSubjectNums = [1,4,5,6,7,8,10,11] def getSubjectDataframe(): subjectNum = input("Which Subject Would You Like to Review: ") if int(subjectNum) in listOfSubjectNums: return subjectNum else: print("The number you entered is not a valid subject number, please choose another") getSubjectDataframe() currentSubject = getSubjectDataframe() path = r'H:\Documents\HoustonData\On-road Driving Study\Quantitative Data' pathB = r'H:\Documents\TungAlgorithm\Driver-Predictions\ord\data\processed\baseline\pp' if(int(currentSubject) <= 10): currentDataFramePath = path + "\P0" + str(currentSubject) + ".csv" currentBaselinePath = pathB + "\P0" + str(currentSubject) + ".csv" else: currentDataFramePath = path + "\P" + str(currentSubject) + ".csv" currentBaselinePath = pathB + "\P" + str(currentSubject) + ".csv" currentDataFrame = pd.read_csv(currentDataFramePath) currentBaseline = pd.read_csv(currentBaselinePath) #Grouping for Subjects taken from Tung's study noAccelEffect = [1,4,8,10] accelEffect = [5,6,7,11] #Generate Histogram of pp ppCol = currentDataFrame['pp_nr5'] baselinePP = currentBaseline['pp_nr2'] ppColOmit = ppCol.dropna() baselinePPOmit = baselinePP.dropna() currentThreshold = ppColOmit.mean() ppColAdjusted = [] #Adjusts PP Data for Data for time in range(ppCol.size): if(pd.isna(ppCol[time])): ppColAdjusted.append(ppCol[time - 1]) else: ppColAdjusted.append(ppCol[time]) #plot of Histograms and Current Threshold sns.distplot(baselinePPOmit, hist=True, kde = True) sns.distplot(ppColOmit, hist=True, kde = True) plt.axvline(currentThreshold, color = 'red') plt.legend(['Stress Threshold']) plt.show() #Function to Get Slope def getSlope(A, B): return (B.getY() - A.getY())/(B.getX() - A.getX()) time = 6 timeArray = [] slopeArray = [] #Copy of Original Data to Be Used in Graphing accelData = list(currentDataFrame['Accelerator']) #Copy of Original Data to be Smoothed accelDataLine = [] accelDataLine = list(currentDataFrame['Accelerator']) #Determine Slope of Acceleration that on average causes stress while time < currentDataFrame['Time'].size - 1: if (ppColAdjusted[time] > currentThreshold and abs(accelData[time - 5] - accelData[time]) > 5): previousPoint = Point(time-5, accelData[time-5]) currentPoint = Point(time, accelData[time]) slope = abs(getSlope(previousPoint, currentPoint)) slopeArray.append(slope) time += 1 slopeAverage = sum(slopeArray)/len(slopeArray) time = 6 startingPointArray = [] #Determines the intervals in which the car is speeding up/slowing down and recording points to do quadratic regression while time < currentDataFrame['Time'].size - 1: if(ppColAdjusted[time] > currentThreshold and abs(accelData[time - 5] - accelData[time]) > 5): slopeTester = Point(time-5, accelData[time-5]) timeArray.append(time) startingAccel = accelDataLine[time] startingPoint = Point(time, startingAccel) startingPointArray.append(startingPoint.getX()) counter = time while(ppColAdjusted[counter] > currentThreshold and counter < len(ppColAdjusted) - 1): counter += 1 endPoint = Point(counter, accelDataLine[counter]) slope = getSlope(startingPoint, endPoint) if(abs(slope) + 1.75 < slopeAverage): time += 1 while(time <= counter): accelDataLine[time] = accelDataLine[time - 1] + slope time += 1 else: while(abs(getSlope(startingPoint, endPoint)) + 1.75 > slopeAverage and counter < currentDataFrame['Time'].size - 1): endPoint.setX(counter) endPoint.setY(accelDataLine[counter]) counter += 1 time += 1 while (time <= counter): accelDataLine[time] = accelDataLine[time - 1] + getSlope(startingPoint, endPoint) time += 1 else: time += 1 #Generates Max Value for Each Subject rangeMax = len(ppColAdjusted) + 1 #Adjust's Time to Start after Start-up Zone adjustedTime = [] for i in range (7,rangeMax): adjustedTime.append(i) #Adjusts Original Acceleration Curve to Match New Time Frame adjustedAcceleration = [] adjustedAccelerationCopy = accelData.copy() for i in range(6, rangeMax - 1): adjustedAcceleration.append(adjustedAccelerationCopy[i]) #Adjusts Smoothed Acceleration Curve to Match New Time Frame adjustedAccelerationData = [] adjustedAccelerationDataCopy = list(accelDataLine) for i in range(6,rangeMax -1): adjustedAccelerationData.append(adjustedAccelerationDataCopy[i]) #Adjusts PP Curve to match New Time Frame adjustedPPThresh = [] adjustedPPThreshCopy = list(currentDataFrame['pp_nr5']) for i in range (6, rangeMax-1): adjustedPPThresh.append(adjustedPPThreshCopy[i]) print(adjustedTime[0]) print(adjustedAccelerationData[0]) x_animData = [] y_animData = [] #Ploting of Different Graphs: [ax1 = Acceleration Curve Data, ax2 = PP Data] fig, ax1 = plt.subplots() ax1.set_xlabel('Time [s]', labelpad = 15, fontweight = 'bold', fontsize = 16) ax1.set_ylabel('Acceleration Pressure [$^\circ$]', color = 'red', labelpad = 15, fontweight = 'bold', fontsize = 16) ax1.plot(adjustedTime, adjustedAcceleration, color = 'red') line, = ax1.plot(adjustedTime[0],adjustedAccelerationData[0], color = 'black', linestyle = 'dashed') count = 0 ax1.axvspan(0,29, alpha=0.5, color = 'grey') ax2 = ax1.twinx() ax2.set_ylabel("Paranasal Persperation [$^\circ$$C^{2}$]", color = 'skyblue', labelpad=15, fontweight='bold', fontsize=16) ppThresh = currentDataFrame['pp_nr5'] ax2.plot(adjustedTime, adjustedPPThresh, color = 'skyblue') ax2.axhline(currentThreshold, linestyle = 'dotted', color = 'skyblue') pointPP, = ax2.plot(adjustedTime[0], adjustedPPThresh[0], "o", color = 'lime') x_animPoint = [] y_animPoint = [] def animation_frame(i): x_animData.append(int(adjustedTime[i])) y_animData.append(adjustedAccelerationData[i]) line.set_xdata(x_animData) line.set_ydata(y_animData) x = adjustedTime[i] y = adjustedPPThresh[i] pointPP.set_xdata(x) pointPP.set_ydata(y) return line, pointPP, fig.set_size_inches(20, 13, True) dpi = 100 animation = FuncAnimation(fig, func=animation_frame, frames=np.arange(0,rangeMax-7), interval=100, repeat = False) # def animation_frame2(j): # if(j > 106): # x_animData.append(int(adjustedTime[j])) # y_animData.append(adjustedAccelerationData[j]) # # line.set_xdata(x_animData) # line.set_ydata(y_animData) # # return line, # # animation2 = FuncAnimation(fig, func=animation_frame2, frames = np.arange(0, rangeMax-100), interval=10, repeat = False) # ax1.plot(adjustedTime, adjustedAccelerationData, color = 'black', linestyle = 'dashed') # def animatePoint(i): # x = adjustedTime[i] # y = adjustedPPThresh[i] # # pointPP.set_xdata(x) # pointPP.set_ydata(y) # # return pointPP, #pointAnim = FuncAnimation(fig, func = animatePoint, frames = np.arange(0, rangeMax-7), interval=250, repeat = False) fig.legend(["Original Acceleration Line", "Adjusted Acceleration Line", "Start-up Zone", "Paranasal Perspiration (PP) Signal", "PP Threshold"]) #animation.save('smoothedCurve.mp4', writer=Writer, dpi=dpi) plt.show()
b1a9fee52ca6eae1ee380a0d95491d735c7360bd
jeantardelli/wargameRepo
/wargame/designpatterns/strategies_traditional.py
1,633
4.15625
4
"""strategies_traditional Example to show one way of implementing different design pattern strategies in Python. The example shown here resembles a 'traditional' implementation in Python (traditional = the one you may implement in languages like C++). For a more Pythonic approach, see the file strategies_pythonic.py. This module is compatible with Python 3.6.x. RUNNING THE PROGRAM: Assuming you have python in your environment variable PATH, type the following in the command prompt to run the program: $ python name_of_the_file.py (Replace name_of_the_file.py with the name of this file) :copyright: 2020, Jean Tardelli :license: The MIT license (MIT). See LICENSE file for further details. """ from strategypattern_traditional_jumpstrategies import CanNotJump, PowerJump from traditional_dwarffighter import DwarfFighter from traditional_unitfactory import UnitFactory from traditional_unitfactory_kingdom import Kingdom if __name__ == '__main__': # Strategy Example print("Strategy Pattern") print("="*17) jump_strategy = CanNotJump() dwarf = DwarfFighter("Dwarf", jump_strategy) print("\n{STRATEGY-I} Dwarf trying to jump:") dwarf.jump() print("-"*56) # Optionally change the jump strategy later print("\n{STRATEGY-II} Dwarf given a 'magic potion' to jump:") dwarf.set_jump_strategy(PowerJump()) dwarf.jump() print("-"*56) # Factory example print("\nFactory Example") print("="*17) factory = UnitFactory() k = Kingdom(factory) elf_unit = k.recruit("ElfRider") print("Created an instance of: {0}".format(elf_unit.__class__.__name__))
792cf649ad2b7e7933e62c9cd9944a1563e5eb17
jeantardelli/wargameRepo
/wargame/gameutils.py
2,569
3.609375
4
"""wargame.gameutils This module contains some utility function for the game Attack of the Orcs This modue is compatible with Python 3.5.x and later. It contains supporting code for the book, Learning Python Application Development Packt Publishing. This is my version of the code, it is pretty much similar to the original author version. :copyright: 2020, Jean Tardelli :license: The MIT License (MIT). See LICENSE file for further details. """ import random def weighted_random_selection(obj1, obj2): """Randomly return one of the following, obj1 or obj2 :arg obj1: An instance of class AbstractGameUnit. It can be any object. The calling code should ensure the correct object is passed to this function. :arg obj2: Another instance of class AbstractGameUnit :return: obj1 or obj2 .. seealso:: :py:func:`weighted_random_selection_alternate` which is an alternative implementation that is used to demonstrate the importance of unit testing. """ selection = random.choices([id(obj1), id(obj2)], weights=[0.3, 0.7]) if selection[0] == id(obj1): return obj1 return obj2 def weighted_random_selection_alternate(obj1, obj2): """Randomly return one of the following, obj1 or obj2 or None. This function is an ALTERNATIVE implementation of `weighted_random_selection` It is created to just show the importance of unit testing. :arg obj1: An instance of class AbstractGameUnit. It can be any object. The calling code should ensure the correct object is passed to this function :arg obj2: Another instance of class AbstractGameUnit. See the comment for obj1 :return: obj1 or obj2 or None .. seealso:: * :py:func:`weighed_random_selection` * The unit test in the `wargame.test directory` -- :py:meth:`test_wargame.TestWarGame.test_injured_unit_selection` """ selection = random.choices([id(obj1), id(obj2), None], weights=[.3, .1, .6]) if selection[0] == id(obj1): return obj1 if selection[0] == id(obj2): return obj2 return None def print_bold(msg, end='\n'): """Convinience function to print a message in bold style Optionally you can also specify how the bold text should end. By default it ends with a new line character. :arg msg: Message to be converted to bold style :arg end: Tell how the printed string should end (newline, space etc) """ print("\033[1m" + msg + "\033[0m", end=end)
58647b7160c95a670f32f010947259d04515f706
jeantardelli/wargameRepo
/wargame/designpatterns/pythonic_adapter_foreignunitadaptermulti.py
1,300
3.65625
4
"""python_adapter_foreignunitadaptermulti This method represents an adapter class that will make other game units compatible between themselves. """ class ForeignUnitAdapterMulti: """Generalized adapter class for 'fixing' incompatible interfaces. :arg adaptee: An instance of the 'adaptee' class. For example, WoodElf is an adaptee as it has a method 'leap' when we expect 'jump'. :ivar foreign_unit: The instance of the adaptee class """ def __init__(self, adaptee): self.foreign_unit = adaptee def __getattr__(self, item): """Handle all the undefined attributes the client code expects. :param item: name of the attribute. :return: Returns the corresponding attribute of the adaptee instance (self.foreign_unit). """ return getattr(self.foreign_unit, item) def set_adapter(self, name, adaptee_method): """Convenience method to set a new attribute to this class :arg name: Name of the new attribute. :arg adaptee_method: The 'value' of the new attribute. Example: setattr(self, 'jump', 'foo_elf.leap') is equivalent to sayng self.jump = foo_elf.leap """ setattr(self, name, adaptee_method)
93b2af4c8f1a23483747d04ea3902c644b581543
jeantardelli/wargameRepo
/wargame/performance-study/pool_example.py
1,201
4.375
4
"""pool_example Shows a trivial example on how to use various methods of the class Pool. """ import multiprocessing def get_result(num): """Trivial function used in multiprocessing example""" process_name = multiprocessing.current_process().name print("Current process: {0} - Input number: {1}".format(process_name, num)) return 10 * num if __name__ == '__main__': numbers = [2, 4, 6, 8, 10] # Create two worker processes. pool = multiprocessing.Pool(3) # Use Pool.apply method to run the task using pools of processes #mylsit = [pool.apply(get_result, args=(num,) for num in numbers] # Use Pool.map method to run the task using the pool of processes #mylist = pool.map(func=get_result, iterable=numbers) # Use Pool.apply_async method to run the task results = [pool.apply_async(get_result, args=(num,)) for num in numbers] # The elements of results list are instances of Pool.ApplyResult # Use the object's get() method to get the final values. mylist = [p.get() for p in results] # Stop the worker processes pool.close() # Join the processes pool.join() print("Output: {0}".format(mylist))
d37a677d52bcb30328947235f0198a9447ddeb34
jeantardelli/wargameRepo
/wargame/GUI/simple_application_2.py
1,025
4.125
4
"""simple_application_2 A 'Hello World' GUI application OOP using Tkinter module. """ import sys if sys.version_info < (3, 0): from Tkinter import Tk, Label, Button, LEFT, RIGHT else: from tkinter import Tk, Label, Button, LEFT, RIGHT class MyGame: def __init__(self, mainwin): """Simple Tkinter GUI example that shows a label and an exit button. :param mainwin: The Tk instance (also called 'root' sometimes) """ lbl = Label(mainwin, text="Hello World!", bg='yellow') exit_button = Button(mainwin, text='Exit', command=self.exit_btn_callback) # pack the widgets lbl.pack(side=LEFT) exit_button.pack(side=RIGHT) def exit_btn_callback(self): """Callback function to handle the button click event.""" mainwin.destroy() if __name__ == '__main__': # Create the main window or Tk instance mainwin = Tk() mainwin.geometry("140x40") game_app = MyGame(mainwin) mainwin.mainloop()
3934697b86a6ce694c2f2304c9ed4f5147665362
tiago-gmfrr/PreviousClassesTmp
/Work/Telecom/huffman.py
2,672
3.515625
4
import math import sys class Node: def __init__(self, value, char, left=None, right=None, parent=None, code=None): self.value = value self.char = char self.right = left self.left = right self.code = code self.parent = parent def setChildren(self, left = None, right = None): self.right = left self.left = right def assignCode(node, tmp=""): if node.parent != None: np= node.parent node.code = str(np.code) + tmp #print(node.char, " : ", node.code) if node.left != None: assignCode(node.left, "0") if node.right != None: assignCode(node.right, "1") if node.left == None and node.right == None: print(hex(ord(node.char)), " : ", node.code) """ if node.left != None: if node.parent != None: #print(node.parent.code) if node.parent.code != "": node.code = "0" else: np = node.parent node.code = str(np.code) + "0" #print(node.char, " : ", node.code) assignCode(node.left) if node.right != None: if node.parent != None: if node.parent.code != "": node.code = "1" else: node.code = node.parent.code + "1" #print(node.char, " : ", node.code) assignCode(node.right) """ return node def huffman(charList): nodeList = [] for c in charList: n = Node(c[1], c[0]) nodeList.append(n) nodeList = sorted(nodeList, key=lambda item:item.value) while(len(nodeList) > 1): v1 = nodeList[0] v2 = nodeList[1] newNode = Node(v1.value + v2.value, v1.char+v2.char, v1, v2) v1.parent = newNode v2.parent = newNode nodeList.pop(1) nodeList.pop(0) nodeList.append(newNode) nodeList = sorted(nodeList, key=lambda item:item.value) tree = nodeList[0] tree.code="" codedList = assignCode(tree) """ for n in codedList: print(n.char, " : " ,n.code) """ return nodeList[0] fileNameRead = str(sys.argv[1]) fileNameWrite = str(sys.argv[2]) fileRead = open(fileNameRead, "r", encoding="UTF-8") fileWrite = open(fileNameWrite, "w", encoding="UTF-8") fileText = fileRead.read() charCount = {} for c in fileText: if c in charCount: charCount[c] = charCount[c] + 1 else: charCount[c] = 1 charCount = sorted(charCount.items(), key=lambda item:item[1]) h = huffman(charCount) # firstChild = Node(charCount[0][1], charCount[0][0]) # secondChild = Node(charCount[1][1], charCount[1][0]) # charCount.pop(0) # charCount.pop(1) # tree = Node(firstChild.value + secondChild.value, firstChild.char + secondChild.char, firstChild, secondChild) # charCount[tree.char] = tree.value # charCount = sorted(charCount.items(), key=lambda item:item[1]) # print(charCount)
ba49bd16e51daf62fdd46883e5593212aa28f9ec
no-bugs-only-features/Operating_Systems-CSCI_3753
/csci3104/Assignment2/Derek_Gorthy_Trie_Traversal/trieClass.py
5,070
4.03125
4
#LastName: Gorthy #FirstName: Derek #Email: derek.gorthy@colorado.edu from __future__ import print_function import sys # We will use a class called my trie node class MyTrieNode: # Initialize some fields def __init__(self, isRootNode): #The initialization below is just a suggestion. #Change it as you will. # But do not change the signature of the constructor. self.isRoot = isRootNode self.isWordEnd = False # is this node a word ending node self.isRoot = False # is this a root node self.count = 0 # frequency count self.next = {} # Dictionary mappng each character from a-z to the child node # w is the word passed to addWord # pos letter position def addHelper(self,w,pos): # The current letter (next) we are evaluating current_letter = w[pos] # Check and see if the next letter is a valid node if current_letter not in self.next: self.next[current_letter] = MyTrieNode(False) # If we have reached the end of the word if (pos + 1 == len(w)): self.next[current_letter].isWordEnd = True # Flag node as end of word self.next[current_letter].count = self.next[current_letter].count + 1 # Increment count else: self.next[current_letter].addHelper(w,pos + 1) # Call again if not at end of word return True # w is the word passed to addWord # pos letter position # i is a counter we increment with every call def lookupHelper(self,w,i,pos): # If we have exceeded the bound of the word we are looking for if i < len(w): current_letter = w[i] # Check the letter # Check is the next letter is valid node if current_letter in self.next: pos = self.next[current_letter].lookupHelper(w,i+1,pos) # Recursively call same function # This will be true is we are at the end of the word if ((i == len(w) - 1) & (self.next[current_letter].isWordEnd == True)): return pos + self.next[current_letter].count # Return the count return pos # If not at end of word, it will return the same as the return statement above else: return pos # Will return 0 if the word is not found def addWord(self,w): self.addHelper(w,0) return def lookupWord(self,w): f = self.lookupHelper(w,0,0) return f # Traverse tree to last inputted letter def locateLastNode(self,w,pos): # The current letter (next) we are evaluating current_letter = w[pos] # Return 0 if last node can't be found if current_letter not in self.next: return 0 else: # If we have found the end of the word if (pos + 1 == len(w)): return self.next[current_letter] # return the node of last letter we are given else: return self.next[current_letter].locateLastNode(w, pos + 1) # Otherwise recursively call # base is word we are given # myList is the list passed throughout the entire tree # cur is the updated string (path) in the tree until this point def autoCompleteDFS(self,base,myList,cur=None): # Save cur through recursive call rest = cur # Iterate through all next nodes for key in self.next.keys(): cur = rest # Reset cur to initial cur passed (restored after recursive call) cur += key # Add the current letter to pass # If it is the end of a word, add to the list if self.next[key].count > 0: myList.append((cur,self.next[key].count)) # If there are still paths to follow, recursively call if len(self.next.keys()) > 0: cur, myList = self.next[key].autoCompleteDFS(base,myList,cur) return cur, myList def autoComplete(self,w): autoCompleteList = [] # Initialize the list to return lastNode = self.locateLastNode(w,0) # Find the last node cooresponding to last letter # Check if the last node is valid if lastNode != 0: # Check to see if the word given is a valid word if lastNode.count > 0: autoCompleteList.append((w, lastNode.count)) w, autoCompleteList = lastNode.autoCompleteDFS(w,autoCompleteList,w) # Call the helper function return autoCompleteList if (__name__ == '__main__'): t= MyTrieNode(True) lst1=['test','testament','testing','ping','pin','pink','pine','pint','testing','pinetree'] for w in lst1: t.addWord(w) j = t.lookupWord('testy') # should return 0 j2 = t.lookupWord('telltale') # should return 0 j3 = t.lookupWord ('testing') # should return 2 lst3 = t.autoComplete('pi') print('Completions for \"pi\" are : ') print(lst3) lst4 = t.autoComplete('tes') print('Completions for \"tes\" are : ') print(lst4)
ee74967cf453cda9aedab57e104f512513684445
sakbarpu/mapsd
/create_list_of_countrynames_different_langs.py
993
3.921875
4
''' Using the country_list library create a list of all countries in many different languages (~620). Store them in a disk. (ONE TIME EXECUTION) ''' import sys, os from country_list import available_languages from country_list import countries_for_language out_dir = sys.argv[1] #create a dict for each language. for each language key load #the country names in that language as a list and store. countries = {} for lang in available_languages(): countries[lang] = [v for k, v in dict(countries_for_language(lang)).items()] #write country names list in a separate file for each language for lang, countrynames in countries.items(): with open(os.path.join(out_dir,lang+".txt"), "w") as out_f: for countryname in countrynames: out_f.write(countryname + "\n") #write 2 letter country codes for each language as well with open(os.path.join(out_dir,"country_codes.txt"), "w") as out_f: for country_code in dict(countries_for_language('en')).keys(): out_f.write(country_code + "\n")
174b3d0663c7e18f5ff4b3308ae34ed48300fee5
RobDBennett/cs-module-project-hash-tables
/applications/no_dups/no_dups.py
558
3.78125
4
def no_dups(s): clean = [] if s == "": return "" else: for word in s.split(): if word in clean: continue else: clean.append(word) answer = "" for word in clean: answer += word answer += " " return answer.strip() if __name__ == "__main__": print(no_dups("")) print(no_dups("hello")) print(no_dups("hello hello")) print(no_dups("cats dogs fish cats dogs")) print(no_dups("spam spam spam eggs spam sausage spam spam and spam"))
704b019ab855616adc2760ee6727a4ac6177bc8d
aleozlx/htcondor-workshop
/Mon/2.3/count.py
563
3.515625
4
#!/usr/bin/env python import os import sys import operator if len(sys.argv) != 2: print 'Usage: %s DATA' % (os.path.basename(sys.argv[0])) sys.exit(1) input_filename = sys.argv[1] words = {} my_file = open(input_filename, 'r') for line in my_file: line_words = line.split() for word in line_words: if word in words: words[word] += 1 else: words[word] = 1 my_file.close() sorted_words = sorted(words.items(), key=operator.itemgetter(1)) for word in sorted_words: print '%s %8d' % (word[0], word[1])
240c664a43e9066b04d56b0c1df6526708691196
VoThanhDanh95/JAIST_internship
/python/tictactoe_com_vs_player.py
7,727
3.84375
4
import random NTRIALS = 1000 # Number of trials to run SCORE_CURRENT = 1.0 # Score for squares played by the current player SCORE_OTHER = 1.0 # Score for squares played by the other player def drawBoard(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') def inputPlayerLetter(): letter = '' while not (letter == 'X' or letter == 'O'): letter = raw_input('Do you want to be X or O?').upper() if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] def whoGoesFirst(): if random.randint(0, 1) == 0: return 'computer' else: return 'player' def playAgain(): print('Do you want to play again? (yes or no)') return raw_input().lower().startswith('y') def makeMove(board, letter, move): board[move] = letter def isWinner(board, letter): return ((board[7] == letter and board[8] == letter and board[9] == letter) or (board[4] == letter and board[5] == letter and board[6] == letter) or (board[1] == letter and board[2] == letter and board[3] == letter) or (board[7] == letter and board[4] == letter and board[1] == letter) or (board[8] == letter and board[5] == letter and board[2] == letter) or (board[9] == letter and board[6] == letter and board[3] == letter) or (board[7] == letter and board[5] == letter and board[3] == letter) or (board[9] == letter and board[5] == letter and board[1] == letter)) def isBoardFull(board): for i in range(1, 10): if isSpaceFree(board, i): return False return True def getBoardCopy(board): dupeBoard = [] for i in board: dupeBoard.append(i) return dupeBoard def isSpaceFree(board, move): return board[move] == ' ' def getPlayerMove(board): move = ' ' while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)): print('What is your next move? (1-9)') move = raw_input() return int(move) def getMoveList(board): possibleMoves = [] for i in range(1, len(board)): if isSpaceFree(board, i): possibleMoves.append(i) return possibleMoves def isFinish(board): return isBoardFull(board) or isWinner(board, 'X') or isWinner(board, 'O') def trial(board, playerLetter): while not isFinish(board): moveList = getMoveList(board) makeMove(board, playerLetter, random.choice(moveList)) if playerLetter == 'X': playerLetter = 'O' else: playerLetter = 'X' drawBoard(board) pass def updateScores(scores, board, playerLetter): if isBoardFull(board): return lengthBoard = len(board) - 1 #drop position 0 of board coef = 1 if not isWinner(board, playerLetter): coef = -1 for i in range(1, lengthBoard+1): if board[i] == playerLetter: scores[i] += coef*SCORE_CURRENT elif board[i] != ' ': scores[i] -= coef*SCORE_OTHER pass def findBestMove(board, scores): moveList = getMoveList(board) if len(moveList) == 0: return best_move = moveList[0] best_score = scores[best_move] for i in moveList[1:]: if scores[i] > best_score: best_move = i best_score = scores[i] return best_move def decideMove(board, playerLetter, trials): scores = [0] * 10 for i in range(0, trials): dupeBoard = getBoardCopy(board) trial(dupeBoard, playerLetter) updateScores(scores, dupeBoard, playerLetter) print(scores[1:]) return findBestMove(board, scores) print('Welcome to Tic Tac Toe!') while True: theBoard = [' '] * 10 scores = [0] * 10 # playerLetter, computerLetter = inputPlayerLetter() # turn = whoGoesFirst() playerLetter = 'X' computerLetter = 'O' turn = 'player' gameIsPlaying = True while gameIsPlaying: if turn == 'player': drawBoard(theBoard) move = getPlayerMove(theBoard) makeMove(theBoard, playerLetter, move) if isWinner(theBoard, playerLetter): drawBoard(theBoard) print('Hooray! You have won the game!') gameIsPlaying = False else: if isBoardFull(theBoard): drawBoard(theBoard) print('The game is a tie!') break else: turn = 'computer' else: move = decideMove(theBoard, computerLetter, NTRIALS) makeMove(theBoard, computerLetter, move) if isWinner(theBoard, computerLetter): drawBoard(theBoard) print('The computer has beaten you! You lose.') gameIsPlaying = False else: if isBoardFull(theBoard): drawBoard(theBoard) print('The game is a tie!') break else: turn = 'player' if not playAgain(): break # drawBoard(board) # print(decideMove(board, 'X', NTRIALS)) # def getComputerMove(board, computerLetter): # if computerLetter == 'X': # playerLetter = 'O' # else: # playerLetter = 'X' # for i in range(1, 10): # copy = getBoardCopy(board) # if isSpaceFree(copy, i): # makeMove(copy, computerLetter, i) # if isWinner(copy, computerLetter): # return i # for i in range(1, 10): # copy = getBoardCopy(board) # if isSpaceFree(copy, i): # makeMove(copy, playerLetter, i) # if isWinner(copy, playerLetter): # return i # move = chooseRandomMoveFromList(board, [1, 3, 7, 9]) # if move != None: # return move # if isSpaceFree(board, 5): # return 5 # return chooseRandomMoveFromList(board, [2, 4, 6, 8]) # print('Welcome to Tic Tac Toe!') # while True: # theBoard = [' '] * 10 # playerLetter, computerLetter = inputPlayerLetter() # turn = whoGoesFirst() # print('The ' + turn + ' will go first.') # gameIsPlaying = True # while gameIsPlaying: # if turn == 'player': # drawBoard(theBoard) # move = getPlayerMove(theBoard) # makeMove(theBoard, playerLetter, move) # if isWinner(theBoard, playerLetter): # drawBoard(theBoard) # print('Hooray! You have won the game!') # gameIsPlaying = False # else: # if isBoardFull(theBoard): # drawBoard(theBoard) # print('The game is a tie!') # break # else: # turn = 'computer' # else: # move = getComputerMove(theBoard, computerLetter) # makeMove(theBoard, computerLetter, move) # if isWinner(theBoard, computerLetter): # drawBoard(theBoard) # print('The computer has beaten you! You lose.') # gameIsPlaying = False # else: # if isBoardFull(theBoard): # drawBoard(theBoard) # print('The game is a tie!') # break # else: # turn = 'player' # if not playAgain(): # break
2d7914e1feecc6a733a027503d4e46ba1f9a178b
VoThanhDanh95/JAIST_internship
/python/qlearning_tictactoe.py
11,117
3.59375
4
import random NTRIALS = 500 # Number of trials to run NUMBER_OF_GAMES = 200000 FIRST_TURN = 'player' # ALPHA = 0.3 # GAMMA = 0.9 # EPSILON = 0.3 ALPHA = 0.01 GAMMA = 0.9 EPSILON = 0.5 def drawBoard(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') def inputPlayerLetter(): letter = '' while not (letter == 'X' or letter == 'O'): letter = raw_input('Do you want to be X or O?').upper() if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] def whoGoesFirst(): if random.randint(0, 1) == 0: return 'computer' else: return 'player' def playAgain(): print('Do you want to play again? (yes or no)') return raw_input().lower().startswith('y') def makeMove(board, letter, move): board[move] = letter def isWinner(board, letter): return ((board[7] == letter and board[8] == letter and board[9] == letter) or (board[4] == letter and board[5] == letter and board[6] == letter) or (board[1] == letter and board[2] == letter and board[3] == letter) or (board[7] == letter and board[4] == letter and board[1] == letter) or (board[8] == letter and board[5] == letter and board[2] == letter) or (board[9] == letter and board[6] == letter and board[3] == letter) or (board[7] == letter and board[5] == letter and board[3] == letter) or (board[9] == letter and board[5] == letter and board[1] == letter)) def isBoardFull(board): for i in range(1, 10): if isSpaceFree(board, i): return False return True def getBoardCopy(board): dupeBoard = [] for i in board: dupeBoard.append(i) return dupeBoard def isSpaceFree(board, move): return board[move] == ' ' def getPlayerMove(board): move = ' ' while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)): print('What is your next move? (1-9)') move = raw_input() return int(move) def getMoveList(board): possibleMoves = [] for i in range(1, len(board)): if isSpaceFree(board, i): possibleMoves.append(i) return possibleMoves def chooseRandomMoveFromBoard(board): possibleMoves = getMoveList(board) if len(possibleMoves) != 0: return random.choice(possibleMoves) else: return None def isFinish(board): return isBoardFull(board) or isWinner(board, 'X') or isWinner(board, 'O') def switchPlayer(playerLetter): if playerLetter == 'X': return 'O' else: return 'X' def getAdvancedMove(board, moveList, playerLetter): for i in moveList: checkWinMoveBoard = getBoardCopy(board) if isSpaceFree(checkWinMoveBoard, i): makeMove(checkWinMoveBoard, playerLetter, i) if isWinner(checkWinMoveBoard, playerLetter): return i for i in moveList: checkWinMoveBoardOpponent = getBoardCopy(board) if isSpaceFree(checkWinMoveBoardOpponent, i): makeMove(checkWinMoveBoardOpponent, switchPlayer(playerLetter), i) if isWinner(checkWinMoveBoardOpponent, switchPlayer(playerLetter)): return i return -1 def trial(board, playerLetter): while not isFinish(board): moveList = getMoveList(board) advancedMove = getAdvancedMove(board, moveList, playerLetter) # if advancedMove == -1: # makeMove(board, playerLetter, random.choice(moveList)) # else: # makeMove(board, playerLetter, advancedMove) if advancedMove != -1: moveList.extend([advancedMove] * 5) if 5 in moveList: moveList.extend([5] * 3) makeMove(board, playerLetter, random.choice(moveList)) playerLetter = switchPlayer(playerLetter) # print # print # print # drawBoard(board) # drawBoard(board) pass q_X = {} q_O = {} def getQ(state, action, playerLetter): if playerLetter == 'O': if q_O.get((state, action)) == None: q_O[(state, action)] = 1.0 else: return q_O.get((state, action)) pass def updateScores(scores, move, board, playerLetter): if isBoardFull(board) and (not isWinner(board, 'X')) and (not isWinner(board, 'O')): scores[move] += 0.5 elif isWinner(board, playerLetter): scores[move] += 1 def reward(lastBoard, lastMove, r, resultBoard, playerLetter): # print('q_o_1', q_O) getQ(tuple(lastBoard), lastMove, playerLetter) prev = getQ(tuple(lastBoard), lastMove, playerLetter) # prev = for action in getMoveList(resultBoard): getQ(tuple(resultBoard),action,playerLetter) if isBoardFull(resultBoard): expect = 0 else: expect_list = [getQ(tuple(resultBoard), action, playerLetter) for action in getMoveList(resultBoard)] expect = max(expect_list) # print('score before update') # print(q_O.get((tuple(lastBoard),lastMove))) # print('score of arg max') # print([q_O.get(tuple(resultBoard),action) for action in expect_list]) # print('r', r) # print('q_O[(tuple(lastBoard), lastMove)]', q_O[(tuple(lastBoard), lastMove)]) # print('expect_list', expect_list) # print('prev', prev) # print('prev + ALPHA*(r + GAMMA*expect - prev)', prev + ALPHA*(r + GAMMA*expect - prev)) q_O[(tuple(lastBoard), lastMove)] = prev + ALPHA*(r + GAMMA*expect - prev) # print('score after update') # print(q_O.get((tuple(lastBoard),lastMove))) pass def decideMove(board, playerLetter, trials): # last_board = getBoardCopy(board) moveList = getMoveList(board) # print(moveList) if len(moveList) == 0: return if random.random() < EPSILON: print('exploration move') return random.choice(moveList) scores_array = [getQ(tuple(board), action, playerLetter) for action in moveList] # print('q_O') # print(q_O) max_score = max(scores_array) # print('scores ',scores_array) # print('decided move', scores_array.index(max_score)) if scores_array.count(max_score) > 1: list_index = [i for i in range(len(scores_array)) if scores_array[i] == max_score] index = random.choice(list_index) # print('score array', scores_array) # print('move list', moveList) # print('list index', list_index) # print('index random', index) # print('decided move', moveList[index]) else: index = scores_array.index(max_score) return moveList[index] print('Welcome to Tic Tac Toe!') computer_win = 0 player_win = 0 draw = 0 for i in xrange(0, NUMBER_OF_GAMES): #set up theBoard = [' '] * 10 scores = [0] * 10 playerLetter = 'X' computerLetter = 'O' turn = FIRST_TURN print(i) print('computer_win', computer_win) print('player win', player_win) print('draw', draw) gameIsPlaying = True while gameIsPlaying: if turn == 'player': # drawBoard(theBoard) # move = getPlayerMove(theBoard) move = chooseRandomMoveFromBoard(theBoard) # move = decideMove(theBoard, playerLetter, NTRIALS) makeMove(theBoard, playerLetter, move) if isWinner(theBoard, playerLetter): player_win += 1 reward(lastBoard, move, -1, theBoard, computerLetter) drawBoard(theBoard) gameIsPlaying = False else: if isBoardFull(theBoard): draw += 1 reward(lastBoard, move, 0.5, theBoard, computerLetter) # drawBoard(theBoard) # print('The game is a tie!') break else: turn = 'computer' else: lastBoard = getBoardCopy(theBoard) move = decideMove(theBoard, computerLetter, NTRIALS) # print('decided move', move) makeMove(theBoard, computerLetter, move) if isWinner(theBoard, computerLetter): computer_win += 1 reward(lastBoard, move, 1, theBoard, computerLetter) # drawBoard(theBoard) # print('The computer has beaten you! You lose.') # gameIsPlaying = False break else: if isBoardFull(theBoard): draw += 1 reward(lastBoard, move, 0.5, theBoard, computerLetter) # drawBoard(theBoard) # print('The game is a tie!') break else: turn = 'player' reward(lastBoard, move, 0, theBoard, computerLetter) pass for i in xrange(0, 2): #set up theBoard = [' '] * 10 scores = [0] * 10 playerLetter = 'X' computerLetter = 'O' turn = FIRST_TURN print(i) print('computer_win', computer_win) print('player win', player_win) print('draw', draw) gameIsPlaying = True while gameIsPlaying: if turn == 'player': drawBoard(theBoard) move = getPlayerMove(theBoard) # move = chooseRandomMoveFromBoard(theBoard) # move = decideMove(theBoard, playerLetter, NTRIALS) makeMove(theBoard, playerLetter, move) if isWinner(theBoard, playerLetter): player_win += 1 drawBoard(theBoard) gameIsPlaying = False else: if isBoardFull(theBoard): draw += 1 # drawBoard(theBoard) # print('The game is a tie!') break else: turn = 'computer' else: lastBoard = getBoardCopy(theBoard) move = decideMove(theBoard, computerLetter, NTRIALS) makeMove(theBoard, computerLetter, move) if isWinner(theBoard, computerLetter): computer_win += 1 reward(lastBoard, move, 1, theBoard, computerLetter) # drawBoard(theBoard) # print('The computer has beaten you! You lose.') # gameIsPlaying = False break else: if isBoardFull(theBoard): draw += 1 reward(lastBoard, move, 0.5, theBoard, computerLetter) # drawBoard(theBoard) # print('The game is a tie!') break else: turn = 'player' reward(lastBoard, move, 5, theBoard, computerLetter) pass print('computer win: ', computer_win) print('player win: ', player_win) print('draw: ', draw)
311401eb3c2861110b9cf9a1f60fb5ceb532e974
NastyaMelnik57/Coursera
/Algorithms/PointsCoverSorted.py
648
3.53125
4
import sys #we want to divide children in groups due to their ages in such way that the #largest difference in age of any two children in one gorup will be at most 1# #and we also want to minimize the number of groups #The task is equal to cover points on the axe with segments of length 1 def MinGroupsNaive(C): R = set() i = 1 n = len(C) - 1 while i <= n: (l, r) = (C[i], C[i]+1) R.add((l,r)) i += 1 while i <= n and C[i] <= r: i += 1 return len(R) if __name__ == '__main__': input = sys.stdin.read() C = [float(i) for i in input.split()] print(MinGroupsNaive(C))
c9a0fa2e3411fd1bb7789b2cb7619ef2dec427be
elaine84/evolve
/code/error.py
598
3.515625
4
import numpy as np def sq_err(w, u, rotation, cor): """ cor: the correlation matrix (of the axis aligned) Gaussian distribution. So cor is diagonal. We assume that each entry of cor is between 0.1 and 1 rotation: the rotation matrix applied to vectors drawn from N(0, cor) w, u : vectors in the transformed (rotated space) NOTE: All of cor, rotation, w, u should be declared as np.mat. cor and rotation are assumed to be nxn and w, u assumed to be nx1. Outputs: E_{y ~ N(0, rotation*cor*rotation^{-1}}[(w*y - u*y)^2] """ return (((w - u).T)*rotation*cor*(rotation.I)*(w - u))[0, 0]
87354e098b723749ba468f150239dc8f78e6f263
eamonbracht/Deforestation-Neural-Network
/raster.py
3,631
3.5
4
import rasterio import rasterio.plot import pyproj import numpy as np import matplotlib import matplotlib.pyplot as plt from rasterio.windows import Window class Raster: """Raster is used to manage importing, manipulating and visualizing raster files.""" def __init__(self, filepath, coords): """ Args: filepath (str): file path to location of .tif files coords (list): list of coordinates constraining the size of the raster to be read, beneficial for large rasters where memory is not large enough. 4 args (column_offset, row_offset, width, height). Note: Highly memory intensive to read large geographic rasters. Avoid importorting unclipped Hansen files. """ self.filepath = filepath self.coords = coords #: bool self.is_Window = False if not coords: # rasterio object self.raster = rasterio.open(self.filepath) else: self.is_Window = True self.raster = Window(*self.coords) self.print_details() def read(self): """Convert raster to array. Note: Do not read in excessively large rasters, use a window. Reading in rasters requires memory equivalent to the size of the file, uncompressed rasters for this project can exceed 12 gb easily. Returns: ndarray equivalent of the rasterio or window. """ if self.is_Window: with rasterio.open(self.filepath) as src: self.arr_raster = src.read(1, window = self.raster) else: self.arr_raster = self.raster.read(1, masked = True) def print_details(self): """Print details of raster file. Todo: * Return head of file, or sample of contents. """ print(self.raster,"\r") if not self.is_Window: print("{}\nAttributes: {}".format(self.raster.name,self.raster.count)) print("\nWidth: {}\nHeight: {}".format(self.raster.width, self.raster.height)) def stats(self): """Prints summary statistics about the raster file. Note: 0's are considered nulls by numpy, so they are not included. Todo * Fix issue with returning zeros. """ shape = self.arr_raster.shape total_array = self.arr_raster.size total = np.argwhere(self.arr_raster > -1).shape[0] print(np.unique(self.arr_raster)) print("Number of Elements: {}".format(total_array)) print("Number of Elements of interest: {}".format(total)) fmt = '{:<8}{:<20}{:<20}{}' unique = np.unique(self.arr_raster) print(fmt.format('', 'Element', 'Frequency', 'Percent')) for i, x in enumerate(unique): if(x != -1): Frequency = np.argwhere(self.arr_raster == x).shape[0] print(fmt.format(i, x, Frequency, round(100*(Frequency/total), 3))) def histogram(self): """Generates histogram showing the distribution of elements in the rasterio object. Does not work for numpy arrays. Yields: Histogram of distribution Note: Zero's are again not counted so they will not be represented in the histogram. """ show_hist(self.raster, bins=50, lw=0.0, stacked=False, alpha=0.3,histtype='stepfilled', title="Histogram") def destructor(self): """Closes raster file. Note: Note necessary unless encountering memory errors. This should be handled by the python compilier. """ self.raster.close()
c72fb1953ee65169041fa399508fbd5204986270
yeti98/LearnPy
/src/basic/TypeOfVar.py
978
4.125
4
#IMMUTABLE: int, ## Immutable vs immutable var #Case3: # default parameter for append_list() is empty list lst []. but it is a mutable variable. Let's see what happen with the following codes: def append_list(item, lst=[]): lst.append(item) return lst print(append_list("item 1")) # ['item 1'] print(append_list("item 2")) # ['item 1', 'item 2'] # Shouldn't use mutable var as a parameter def append_list(item, lst= None): if lst is None: lst = [] lst.append(item) return lst #Case2: don't use += for string, because string is immutable. Instead, use join() method msg= "" for i in range(1000): msg+= "hello" # each for loop, new msg varible created and that make RAM quickly full #Case1: //list is mutable def double_list(lists): for i in range(len(lists)): lists[i] = lists[i]*2 return lists lists = [x for x in range(1, 12)] doubled = double_list(lists) for i in range(len(lists)): print(doubled[i] / lists[i])
e37708d07875b90881d73d15dc6418878e174d37
erv4gen/Archive
/old_files/fun.py
897
3.671875
4
''''' измени алгоритм так, чтобы внути цикла рисовалось все правильно ''' import os import sys import random as r def forest(amount): foresthigh = [r.randrange(2,15) for i in range(amount)] myforest = ["" for i in range(amount)] for i in range(0,max(foresthigh)): branch = 1 for j in range(amount): f = foresthigh[j] - i v = (f * ' ', '#' * branch) myforest[j] += ''.join(v) branch += 2 #myforest += v * " " + "#" #myforest = str(myforest) # print(myforest, sep='\n') for i in myforest: print(i) def test(): l1 = ["1" for i in range(10)] l2 = ["2" for i in range(10)] l1.extend(l2) for i in l1: print(i) amount = r.randrange(2,5) print("lets create a forest with {} trees ".format(amount)) forest(amount) #test()
1212f1f829be75fb4a3d42186e61774b0c2fbee5
amandamurray2021/Programming-Semester-One
/labs/Topic08-Plotting/plotSquare.py
259
4.09375
4
# Q5 # Write a program that plots the function y = x² # Author: Amanda Murray import matplotlib.pyplot as plt import numpy as np xpoints = np.array(range(1,101)) ypoints = xpoints * xpoints # multiply each entry by itself plt.plot (xpoints, ypoints) plt.show()
0a050628c16cbebab0494a6b059db22633ff5c9a
amandamurray2021/Programming-Semester-One
/labs/Week04-flow/average.py
577
4.0625
4
# This program keeps reading numbers until the user enters 0 # It should then print out each of the numbers entered and the average of them. # Author: Amanda Murray numbers = [] # first number then we check if it is 0 in the while loop number = int(input("enter number (0 to quit): ")) while number != 0: numbers.append(number) # read the next number and check if 0 number = int(input("enter another (0 to quit): ")) for value in numbers: print (value) # I want average to be a float average = float(sum(numbers)) / len(numbers) print ("The average is", average)
e6d4e5704ff566eef48395633589e37bce88c83a
amandamurray2021/Programming-Semester-One
/labs/Week04-flow/round.py
495
3.953125
4
# This program rounds a student's decimal point percentage mark # and then prints out the corresponding grade # Author: Amanda Murray percentage = float(input("Enter the percentage: ")) if percentage < 39.4: # 39.4 or less print ("Fail") elif percentage <= 49.4: # between 39.5 to 49.4 print ("Pass") elif percentage <= 59.4: # between 49.5 to 59.4 print ("Merit 2") elif percentage <= 69.4: # between 59.5 to 69.4 print ("Merit 1") else: # from 69.5 to 100 print ("Distinction")
f797517592b2d09d2227375cdd81614b3da3b912
amandamurray2021/Programming-Semester-One
/labs/Topic07-Files/writeNumber.py
375
3.875
4
# Q2(b) # Write a function that reads in a number and overwrites the file with that number (count.txt). # Test the program to check that the file has been changed. # Author: Amanda Murray filename = "count.txt" def writeNumber(number): with open (filename, "wt") as f: # write takes a string so we need to convert f.write(str(number)) # test it writeNumber (3)
0243e8d54259a3cecd9e84443bae674a66f090f7
amandamurray2021/Programming-Semester-One
/labs/week06-functions/menu2.py
801
4.34375
4
# Q3 # This program uses the function from student.py. # It keeps displaying the menu until the user picks Q. # If the user chooses a, then call a function called doAdd (). # If the user chooses v, then call a function called doView (). def displayMenu (): print ("What would you like to do?") print ("\t (a) Add new student") print ("\t (v) View students") print ("\t (q) Quit") choice = input ("Type one letter (a/v/q):").strip () return choice def doAdd (): print ("in adding") def doView (): print ("in viewing") # main program choice = displayMenu () while (choice != 'q'): if choice == 'a': doAdd () elif choice == 'v': doView () elif choice != 'q': print ("\n\n please select either a, v or q") choice = displayMenu ()
ee17da886d3a69800522063531b656b37723620a
amandamurray2021/Programming-Semester-One
/labs/Topic08-Plotting/MakeList4.py
614
4.0625
4
# Q4 # Modify the program so that it increases all of the salaries by 5%. # Store these numbers in a different array. # Author: Amanda Murray import numpy as np minSalary = 20000 maxSalary = 80000 numberOfEntries = 10 np.random.seed(1) # seeding the random number generator ensuring data is the same each time the program is run. salaries = np.random.randint(minSalary, maxSalary, numberOfEntries) print (salaries) salariesMult = salaries * 1.05 # add 5% by multiplying by 1.05 print (salariesMult) # this returns a float array # to convert to an int array: newSalaries = salariesMult.astype(int) print (newSalaries)
206871298a6a25d6cde83d275cd2a074f1cce895
amandamurray2021/Programming-Semester-One
/labs/Week03/string.py
148
3.546875
4
# string.py # Lab 3.3 # This program reads in a string and outputs it # Author: Amanda Murray message = 'John said\t"hi"\nI said\t\t"bye"' print (message)
a3ca7ebf208720a4113b073b25815c7323f7b106
amandamurray2021/Programming-Semester-One
/pands-problem-sheet/secondstring.py
455
3.9375
4
# Weekly Task 3 # This program asks the user to input a string # It outputs every second letter from the string in reverse order # Author: Amanda Murray sentence = input("Please enter a sentence: ") print (sentence [::-1][::2]) # Example given: The quick brown fox jumps over the lazy dog. # We reverse the sentence by slicing the string with a negative index [::-1] # We add the number 2 as a new slice [::2] to count every second letter from the reverse order
b46a272da0167029a379ba99f8ad5dbd0e7ff482
amandamurray2021/Programming-Semester-One
/labs/Topic07-Files/createFile.py
142
3.515625
4
# Q2 # This program will create a count.txt file # Author: Amanda Murray with open ("count.txt", "x") as f: data = f.write("0") print (data)
65f762930b668b660ee2db90895a468a359bd32f
amandamurray2021/Programming-Semester-One
/pands-project2021/petallength.py
1,617
4.0625
4
# This program plots a histogram with petal length in cm on the x-axis and the amount of irises on the y-axis. # Using Seaborn's "hue" parameter, we pass the Iris species (class) as a third variable and save the resulting graph as a .png. # Author: Amanda Murray import matplotlib.pyplot as plt # a low level graph plotting library in Python import pandas as pd # a Python library used for working with datasets import seaborn as sns # A library that uses matplotlib underneath to plot graphs data = pd.read_csv('C:\\Users\\amand\\Desktop\\GMIT\\Programming\\pands-project2021\\iris.csv') # importing the .csv file sns.set_style("whitegrid") # setting the style of the histogram to include a grid sns.FacetGrid(data, hue = 'class', height = 5).map(sns.histplot, 'petal_length', bins = 5).add_legend(title = 'Species') # Using the Facet Grid, we can assign petal length to the x-axis and the amount of irises on the y-axis. # Using the 'hue' parameter, we can assign a third variable (class) in different colours. # height refers to the height in inches of the grid # Using sns.histplot to generate the histogram # Using bins to pool the data # Adding a legend for the colours plt.title ('Petal lengths of the iris species in the Iris data set') # set title plt.xlabel ('Petal length (cm)') # set title of x-axis plt.ylabel ('Number of irises') # set title of y-axis plt.subplots_adjust (top=.9) # adjust the size of the graph to prevent title being cut off plt.savefig ('C:\\Users\\amand\\Desktop\\GMIT\\Programming\\pands-project2021\\petal_length.png') # save the figure generated plt.show() # show the figure generated
f2b11078b232660a006f6eafb0338f23c173b70f
GavrilS/python-mini-projects
/mad-libs-generator/mad_libs_generator.py
1,467
3.859375
4
import random def create_stories(): weird_news = 'A sub was arrested this morning after he sub in front of sub. sub, had a history of sub, but' \ ' no one - not even his sub ever imagined he\'d sub with a sub stuck in his sub.' \ " I always thought he was sub, but I never thought he'd do something like this. Even his sub was surprised." \ " After a brief sub, cops followed him to a sub, where he reportedly sub in the fry machine." \ " In sub, a woman was charged with a similar crime. But rather than sub with a sub, she sub with a sub dog." \ " Either way, we imagine that after witnessing him sub there are probably a whole lot of sub that are going to need some therapy." weird_news_words = ['noun', 'verb', 'noun', 'name', 'verb', 'noun', 'verb', 'noun', 'part of the body', 'adjective', 'relative', 'activity', 'place', 'adjective/verb, past tense', 'month', 'verb', 'noun', 'verb, past tense', 'adjective', 'verb', 'plural noun'] stories = {0: [weird_news, weird_news_words]} return stories def mad_lib(): stories = create_stories() index = random.randint(0, len(stories) - 1) story = stories[index][0] words = stories[index][1] for word in words: input_word = input('Give me a ' + word + ': ') story = story.replace('sub', input_word, 1) print(story) mad_lib()
965ac8e3426b2700779db405a9f8da2bf479f17c
cwchange/interview-question
/num1/question_4.py
737
3.640625
4
""" 4. Given: words = [‘one’, ‘one’, ‘two’, ‘three’, ‘three’, ‘two’] Remove the duplicates. """ #Solution number one, by using numpy build in function. import numpy as np words = ['one', 'one', 'two', 'three', 'three', 'two'] new_words=np.unique(np.array(words)) print new_words #soltion number two class q_4: def __init__(self, array): self.array=array self.final=[] def insert(self): for i in self.array: if i not in self.final: self.final.append(i) if __name__ == "__main__": words=['one', 'one', 'two', 'three', 'three', 'two'] temp=q_4(words) temp.insert() print temp.final
a4f2a7688618ebd42ef67a9f350e55bb21089491
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/01 - Temel Bilgiler - Seviye 1/04 - percentage.py
365
3.859375
4
""" Bir sayı ve yüzde alan ve bu sayının yüzdesini veren bir fonksiyon yazın. """ def percentage(num, percent): return num * (percent/100) print(percentage(100,60)) print(percentage(10, 50)) print(percentage(10, 30)) print(percentage(10, 20)) print(percentage(5, 10)) print(percentage(5, 30)) print(percentage(5, 20)) print(percentage(7, 25))
581152e31c7db41497c55661eee0ad92026487cf
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/09 - Math Seviye 2/02 - basicCalculator.py
477
4.3125
4
"""İki sayı ve bir operatör (+, -, *, /) alan ve hesaplamanın sonucunu döndüren bir fonksiyon yazın.""" def calculate(num1, operator, num2): if operator == "+": return num1 + num2 elif operator == "-": return num1 - num2 elif operator == "*": return num1 * num2 elif operator == "/": return num1 / num2 print(calculate(5,"+",7)) print(calculate(5,"-",7)) print(calculate(5,"*",7)) print(calculate(5,"/",7))
3eb35bdb0ee2418cf7bdfdc6970ddbaf05137a1b
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/12 - Dictionaries Seviye2/08 - wordCountTracker.py
375
3.703125
4
"""Kelime Sayımı İzleyici Bir metin dizesi verildiğinde, dizede count her kelimenin kaç kez göründüğünü izleyen bir sözlük döndürün. """ def word_count(text): my_string = text.split() count = {} for item in my_string: if item in count: count[item] += 1 else: count[item] = 1 return count print(word_count("Deneme 1234"))
1f4677231483102e14e550023ca914280acf3a5c
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/06 - Lists Seviye 1/05 - insertLast.py
387
4.125
4
""" Alıştırma 4.1.5: Son Ekle Listenin son elemanı olarak insert_last eklenen adında bir fonksiyon yazın x. Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım.""" def insert_last(my_list, x): if len(my_list) >= 0: my_list.append(x) return my_list print(insert_last([3,4,6], 5))
7285749a1416052d7e08b52cbed0f5ea4b431c07
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/11 - Lists Seviye2/01 - prependGood.py
483
3.6875
4
""" İyinin Başına Hazırla prepend_good Listenin her öğesinin başına “good” dizesini getiren bir işlev yazın . Not: Geçirilen listenin her öğesinin bir dize olduğunu varsayabilirsiniz. Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım. """ def prepend_good(my_list): ls = [] for i in range(len(my_list)): ls.append("Good " + my_list[i]) return ls print(prepend_good(["1","2","3"]))
4cf599680e61c36244b7539c0695d60b6cb47853
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/01 - Temel Bilgiler - Seviye 1/08 - divisibleByValue.py
342
3.875
4
""" Değere Bölünebilme İki tamsayı alan bir fonksiyon yazın. İşlev, ilk tamsayının ikinci tamsayıya bölünüp bölünemeyeceğini kontrol edecek ve bir boole değeri döndürecektir. """ def divisible(num, divisor): if num % divisor == 0: return True else: return False print(divisible(10,10)) print(divisible(11,10))
40b495b2c03ef38929a129592c032ff53c8b53b7
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/06 - Lists Seviye 1/02 - removeLast.py
399
3.890625
4
"""remove_last Listeden son elemanı kaldıran bir fonksiyon yazın . Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım. """ def remove_last(my_list): if len(my_list) > 0: my_list.pop(-1) return my_list else: return my_list print(remove_last([0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0]))
6a74c4041ca5744dfd4baf0838379b07d08b1a5b
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/04 - Math Seviye 1/05 - finalVelocity.py
423
3.75
4
""" Son Hız Fizikte, bir nesnenin sabit ivmeyle hareket ederken son hızını (veya hızını) bulmak için aşağıdaki denklem kullanılabilir: vf = vi + at burada: vf= son hız vi= ilk hız a= hızlanma t= zaman İlk hız, ivme ve zaman verildiğinde, son hızı döndürecek bir fonksiyon yazın. """ def calculate_velocity(vi, a, t): return vi + a * t print(calculate_velocity(10,2,5))
d39156f96eeac77c4a9e1606b3566ae0afbb4f84
berkcangumusisik/CourseBuddiesPython101
/1. Hafta/05 - Lab Saati Uygulamaları/ornek1.py
1,012
4.40625
4
"""Python Hafta 1 - 1: CourseBuddies üniversitesi öğrencilerinin mezun olup olamayacağını göstermek için bir sistem oluşturmaya çalışıyor. Öncelikle durumunu öğrenmek isteyen öğrencinin, ismini yaşını ve not ortalamasını (0 - 100 arası) girmesi gerekiyor (input() fonksiyonu ile kullanıcıdan alıcak). eğer kullanıcının yaşı 17 ve 21 arasındaysa ve not ortalaması 80 ve üzeri ise okulunu tamamlayabilecek. eğer bu koşulları sağlamıyor ise okulunu tamamlayamayacaktır ve duruma göre ekrana bir çıktı gösterecektir (print() fonksiyonu ile) CourseBuddies Üniversitesinin böyle bir sisteme ihtiyacı var, Hadi sen de yardım et""" try: isim = input("İsminizi giriniz:") yas = int(input("Yaşınızı giriniz:")) ortalama = int(input("Not Ortalaması giriniz:")) if(yas>16 and yas <22 and ortalama>79 and ortalama<101): print("Sınıfı Geçti") else: print("Sınıfı Geçemedi") except: print("Lütfen bir sayı giriniz.")
7df313a3df931a978cd78c18ac1176d4c681dba0
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/03 - Strings - Seviye1/07 - replaceWithA.py
265
3.8125
4
""" A ile değiştirin Size merkezinde sesli harf bulunan 3 harfli kelimeler verilir. Kelimeyi 'a' ile değiştirilen sesli harfle döndüren bir işlev oluşturun. """ def replace_with_a(str): return str.replace(str[1:2],"a") print(replace_with_a("sey"))
0c8874c6ed0902384e7ba0790e5e1b28741868ba
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/13 - Lists Seviye 3/07 - sumTheLenghts.py
413
4.21875
4
""" Uzunlukları Topla Bir sum_the_lengths listedeki tüm dizelerin uzunluğunu toplayan adlı bir işlev yazın . Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım. """ def sum_length(my_list): length = 0 for string in my_list: length += len(string) return length print(sum_length(["python", "is", "fun"]))
c3f675e03651eb66f2b4444368cbe3d404ec4be3
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/05 - Döngüler Seviye 1/05 - average.py
377
3.703125
4
""" Ortalama Bu alıştırmada, başlangıç ​​değerinden bitiş değerine (her iki bitiş noktası dahil) kadar bir dizi sayının ortalamasını döndüreceksiniz. Örnek: find_average(10, 20) --> 15 find_average(0, 1000) --> 500 """ def find_average(start, end): ortalama = start -1 + end+1 ort = ortalama / 2 return ort print(find_average(10, 20))
029a98514a807917eb98b16dced8b95bd842ef3d
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/10 - Döngüler Seviye 2/03 - isDivisable.py
480
4.0625
4
"""Bölünebilir mi?4 puan Bu alıştırmada size bir bitiş değeri ve bir bölen veriliyor. Bölen ile bölünebilen pozitif tam sayıların sayısını bitiş değeri dahil olmak üzere döndürür. Örnek: is_divisible(10, 2) --> 5 is_divisible(10, 3) --> 3 """ def is_divisible(end, divisor): count = 0 for i in range(1 , end+1): if i % divisor == 0: count += 1 else: continue return count print(is_divisible(10, 2))
d26127cfacd2c5fce83c76931223a72c5df39aa7
nitishk111/InfyTQ-Python-Assignment
/InfyTQ_Assign20_3.py
435
3.515625
4
#PF-Prac-20 def ducci_sequence(test_list,n): #start writing your code here for i in range(n+1): a=test_list[0] test_list[0]=abs(test_list[1]-test_list[0]) test_list[1]=abs(test_list[2]-test_list[1]) test_list[2]=abs(test_list[3]-test_list[2]) test_list[3]=abs(test_list[3]-a) return test_list ducci_element=ducci_sequence([0, 653, 1854, 4063] , 3) print(ducci_element)
52e071a021c0b301e9e35df872f201bb7611fc09
nitishk111/InfyTQ-Python-Assignment
/Assignment14.2.py
436
3.9375
4
marks_table={'John':86.5,'Jack':91.2,'Jill':84.5,'Harry':72.1,'Joe':80.5} top=3 print("Top {} scorer of subject--".format(top),end=" ") for i,j in sorted(marks_table.items(),key=lambda x:x[1]): if top>0: print(i,end=" ") top-=1 print("\nAverage score of all students: ",end=" ") average=0 for i in marks_table.values(): average=average+i average=average/len(marks_table) print(str(average)+"%")
ee460ae9496830b62e21cb0af8eab25212034757
nitishk111/InfyTQ-Python-Assignment
/Assignment8.2.py
687
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 22 07:53:58 2020 @author: Nitish """ i=0 def num_convert(a): global i i+=1 if i%2==0: return a else: return int(a) speciality={'P':'Pediatrics','O':'Orthopedics','E':'ENT'} s=list(map(num_convert,input("Enter id and medical speciality visited by patient.").split())) p,o,e=0,0,0 for i in s: if i=="P": p+=1 elif i=="E": e+=1 elif i=="O": o+=1 if p>e: if p>o: print(speciality['P']) else: print(speciality["O"]) else: if e>o: print(speciality['E']) else: print(speciality["O"])
df132a59706cc953c09afdc91bdddf692e11a5a4
nitishk111/InfyTQ-Python-Assignment
/Assignment11.2.py
515
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 27 02:02:08 2020 @author: Nitish """ def fact(num): if num==0: return 1 else: return fact(num-1)*num num_list=list(map(int,input("Enter list: ").split())) strong_num=list() for i in num_list: b=0 j=i while i>0: a=i%10 i=i//10 b=b+fact(a) if j==b: strong_num.append(b) print("Strong numbers from the given list is/are: ",end="") for i in strong_num: print(i,end=" ")
dd32bd386f65c98a15f23d9a62b563eb8e48b96e
joscelino/Calculadora_estequiometrica
/Formula_Clapeyron/clapeyron_dinamica.py
1,121
4.125
4
variable = int(input("""Choose a variable: [1] Pressure [2] Volume [3] Number of moles [4] Temperature """)) R = 0.082 if variable == 1: # Inputs V = float(input('Volume (L): ')) T = float(input('Temperature (K): ')) n = float(input('Number of moles: ')) # Formula P = (n * R * T) / V # Printing print(f'The pressure is: {P} atm') elif variable == 2: # Inputs P = float(input('Pressure (atm): ')) T = float(input('Temperature (K): ')) n = float(input('Number of moles: ')) # Formula V = (n * R * T) / P # Printing print(f'The volume is: {V} L') elif variable == 3: # Inputs P = float(input('Pressure (atm): ')) T = float(input('Temperature (K): ')) V = float(input('Volume (L): ')) # Formula n = (P * V) / (R * T) # Printing print(f'The number of moles are: {n} .') elif variable == 4: # Inputs P = float(input('Pressure (atm): ')) V = float(input('Volume (L): ')) n = float(input('Number of moles: ')) # Formula T = (P * V) / (n * R) # Printing print(f'Temperature is: {T} K.')
1672bf091704e5347c6cce0fdee1b6f04de07b11
PureChocolate/aoc_2019
/day_1/fuel.py
307
3.6875
4
import math; total = 0 def fuelReq(m): global total if((math.floor(m/3) - 2) < 0): total += 0 else: m = int((math.floor(m/3)) - 2) total += m fuelReq(m) with open("masses.txt") as f: for line in f: line = int(line) fuelReq(line) print total
9684c8cde1681d9555563861cb92e332dee3f1a5
kenan666/Study
/算法总结/旋转链表.py
1,627
3.546875
4
''' 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例 2: 输入: 0->1->2->NULL, k = 4 输出: 2->0->1->NULL 解释: 向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步: 0->1->2->NULL 向右旋转 4 步: 2->0->1->NULL ''' ''' 示例1,1->2->3->4->5->NULL, k = 2 ,我们要找到3这个值,只要把它下一位为空,将下面一段链表和它这段链表连接起来 1->2->3->4->5->NULL ---> 1->2->3->NULL ---> 4->5->1->2->3->NULL 4->5->NULL 题目的意思是向右移动2位,换句话说, 以3作为链表头,把它前面的链表连在它后面!现在问题就是如何找3,我们发现链表的个数-k就是从链表头到3位置. 还有一个问题,就是如果k = 6其实就是相等于k=1;所以我们要防止循环. 问题变成了,1. 求链表长度;2. 找 num - num % k的位置 ''' def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head or not head.next or not k: return head num = 0 dummy = ListNode(0) dummy.next = head p1 = dummy p2 = dummy # 计算个数 while p1.next: num += 1 p1 = p1.next #print(num) # 找前一段链表 k = num - k % num #print(k) while k : p2 = p2.next k -= 1 # 连接 p1.next = dummy.next dummy.next = p2.next p2.next = None return dummy.next
8777dc9d9f622913fa80a73cbe61aa2ddfed7ecc
kenan666/Study
/算法总结/全排列2.py
832
3.875
4
''' 给定一个可包含重复数字的序列,返回所有不重复的全排列。 示例: 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ] ''' # 回溯法 def permuteUnique(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] visited = set() def backtrack(nums, tmp): if len(nums) == len(tmp): res.append(tmp) return for i in range(len(nums)): if i in visited or (i > 0 and i - 1 not in visited and nums[i-1] == nums[i]): continue visited.add(i) backtrack(nums, tmp + [nums[i]]) visited.remove(i) backtrack(nums, []) return res # 库函数法 itertools def permuteUnique(self, nums: List[int]) -> List[List[int]]: return list({p for p in itertools.permutations(nums)})
4dc64704e0577f4d03eeab4e3c55e4272c45b844
kenan666/Study
/算法总结/矩阵查找target.py
1,529
3.75
4
''' 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: 每行中的整数从左到右按升序排列。 每行的第一个整数大于前一行的最后一个整数。 示例 1: 输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 输出: true 示例 2: 输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 输出: false ''' def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix: return False row = len(matrix) col = len(matrix[0]) left = 0 right = row * col while left < right: mid = left + (right - left) // 2 if matrix[mid // col][mid % col] < target: left = mid + 1 else: right = mid #print(left,right) return left < row * col and matrix[left // col][left % col] == target # 方法二 利用矩阵,选择最左上角的数字进行目标对比查询 bool fina(int * matrix,int row,int cols,int number) { bool find = False; if (matrix != null && row >0 && col>0) { int row = 0; int col = col - 1; while( row <rows && col >= 0) { if (matrix [row * col + col] == number) { found = true; break; } else if (matrix [row * col + col] > number) --col; else ++row; } } return found; }
44f01bdd44239347a783d80b5b75f6e646f52029
kenan666/Study
/算法总结/三角形最小路径和.py
1,244
3.71875
4
''' 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 例如,给定三角形: [ [2], [3,4], [6,5,7], [4,1,8,3] ] 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 ''' #利用DFS深度优先遍历,从上到下扫描所有路径 def minimumTotal(self, triangle: List[List[int]]) -> int: self.res = float("inf") row = len(triangle) def helper(level,i,j,tmp): if level == row: self.res = min(self.res,tmp) return if 0 <= i <len(triangle[level]): helper(level + 1,i, i+1,tmp+triangle[level][i]) if 0 <= j <len(triangle[level]): helper(level + 1,j, j+1,tmp+triangle[level][j]) helper(0,-1,0,0) return self.res # 动态规划方法 自底向上遍历 从倒数第二行开始依次遍历,最后triangle[0][0]就是想要的结果 def minimumTotal(self, triangle): if len(triangle) == 0: return 0 row = len(triangle) - 2 for row in range(row, -1, -1): for col in range(len(triangle[row])): triangle[row][col] += min(triangle[row+1][col],triangle[row+1][col+1]) return triangle[0][0]
fb3fbd522eed6139a5098cb1a3c00cb964c6c20e
kenan666/Study
/算法总结/滑动窗口最大值.py
3,892
3.5625
4
''' 给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回滑动窗口中的最大值。  示例: 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 输出: [3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7   提示:你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。 ''' # 暴力法 ''' 直接的方法是遍历每个滑动窗口,找到每个窗口的最大值。一共有 N - k + 1 个滑动窗口,每个有 k 个元素,于是算法的时间复杂度为 O(Nk) ''' def maxSlidingWindow(self, nums: 'List[int]', k: 'int') -> 'List[int]': n = len(nums) if n * k == 0: return [] return [max(nums[i:i + k]) for i in range(n - k + 1)] ''' 时间复杂度:O(Nk)。其中 N 为数组中元素个数。 空间复杂度:O(N−k+1),用于输出数组。 ''' # -------参考大佬---------------困难题******************** # 双向队列 ''' 算法 ·处理前 k 个元素,初始化双向队列。 ·遍历整个数组。在每一步 : ·清理双向队列 : - 只保留当前滑动窗口中有的元素的索引。 - 移除比当前元素小的所有元素,它们不可能是最大的。 ·将当前元素添加到双向队列中。 ·将 deque[0] 添加到输出中。 ·返回输出数组。 ''' def maxSlidingWindow(self, nums: 'List[int]', k: 'int') -> 'List[int]': # base cases n = len(nums) if n * k == 0: return [] if k == 1: return nums def clean_deque(i): # remove indexes of elements not from sliding window if deq and deq[0] == i - k: deq.popleft() # remove from deq indexes of all elements # which are smaller than current element nums[i] while deq and nums[i] > nums[deq[-1]]: deq.pop() # init deque and output deq = deque() max_idx = 0 for i in range(k): clean_deque(i) deq.append(i) # compute max in nums[:k] if nums[i] > nums[max_idx]: max_idx = i output = [nums[max_idx]] # build output for i in range(k, n): clean_deque(i) deq.append(i) output.append(nums[deq[0]]) return output # 时间复杂度 O(N) 每次元素被处理两次-其索引被添加到双向队列中和被双向队列删除 # 空间复杂度 O(N) 输出数组使用了O(N - k + 1)空间,双向队列使用了O(k) # ------------另一种写法-------------- def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: size = len(nums) # 特判 if size == 0: return [] # 结果集 res = [] # 滑动窗口,注意:保存的是索引值 window = deque() for i in range(size): # 当元素从左边界滑出的时候,如果它恰恰好是滑动窗口的最大值 # 那么将它弹出 if i >= k and i - k == window[0]: window.popleft() # 如果滑动窗口非空,新进来的数比队列里已经存在的数还要大 # 则说明已经存在数一定不会是滑动窗口的最大值(它们毫无出头之日) # 将它们弹出 while window and nums[window[-1]] <= nums[i]: window.pop() window.append(i) # 队首一定是滑动窗口的最大值的索引 if i >= k - 1: res.append(nums[window[0]]) return res
3cc45146c9591b81518c36e858f88834a8eb3dd2
kenan666/Study
/算法总结/乘积最大子序列.py
1,009
3.53125
4
''' 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。 示例 1: 输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6。 示例 2: 输入: [-2,0,-1] 输出: 0 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 ''' ''' 由于负值最小值 * 负数可能会变成最大值,正值最大值 * 负数也可能会变成最小值,所以我们还要多一步骤保留最小值。 设 A[i] 为以 i 截止之子序列最大积,得转移公式A[i] = max(A[i - 1] * j, j) 考虑最小值成负数,故写成 A[i] = max(A[i - 1] * j, j, minv * j) 其中minv = min(A[i - 1] * j, j, minv * j)。 ''' def maxProduct(self, nums: List[int]) -> int: if nums == []: return 0 a = [0] * len(nums) a[0] = nums[0] minv = 0 for i,j in enumerate(nums): if i > 0: a[i] = max(a[i-1] * j, j, minv * j) minv = min(a[i-1] * j, j, minv * j) return max(a)
9c970cc27fdb11814ece3e945cd43fbba26630cf
kenan666/Study
/算法总结/二叉树相关例子.py
10,981
3.75
4
''' 给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] ''' # 解1 递归 def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] def helper(root): if not root: return helper(root.left) res.append(root.val) helper(root.right) helper(root) return res # 迭代 def inorderTraversal(self, root): res = [] stack = [] # 用p当做指针 p = root while p or stack: # 把左子树压入栈中 while p: stack.append(p) p = p.left # 输出 栈顶元素 tmp = stack.pop() res.append(tmp.val) # 看右子树 p = tmp.right return res ''' 给定一个二叉树,返回它的 前序 遍历。  示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] ''' # 解1 递归 依次输出根左右,递归进行 def preorderTraversal(self, root: TreeNode) -> List[int]: res = [] def helper(root): if not root: return res.append(root.val) helper(root.left) helper(root.right) helper(root) return res # 迭代 迭代:使用栈来完成,我们先将根节点放入栈中,然后将其弹出,依次将该弹出的节点的右节点,和左节点,**注意顺序,**是右,左,--栈是先入后出的,我们要先输出右节点,所以让它先进栈. def preorderTraversal(self, root: TreeNode) -> List[int]: res = [] if not root: return res stack = [root] while stack: node = stack.pop() res.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return res ''' 给定一个二叉树,返回它的 后序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1] ''' # 递归 左右根 def postorderTraversal(self, root: TreeNode) -> List[int]: res = [] def helper(root): if not root: return helper(root.left) helper(root.right) res.append(root.val) helper(root) return res # 迭代 改变入栈的顺序,刚才先序是从右到左,我们这次从左到右,最后得到的结果取逆 def postorderTraversal(self, root: TreeNode) -> List[int]: res = [] if not root: return res stack = [root] while stack: node = stack.pop() if node.left : stack.append(node.left) if node.right: stack.append(node.right) res.append(node.val) return res[::-1] ''' 给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] ''' # 递归 左根右 def inorderTraversal(self, root): res = [] def helper(root): if not root: return helper(root.left) res.append(root.val) helper(root.right) helper(root) return res # 迭代 def inorderTraversal(self, root): res = [] if not root: return res stack = [] cur = root while stack or cur: while cur: stack.append(cur) cur = cur.left cur = stack.pop() res.append(cur.val) cur = cur.right return res ''' 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层次遍历结果: [ [3], [9,20], [15,7] ] ''' # BFS 算法 广度优先遍历 ''' 广度优先搜索算法(英语:Breadth-First-Search,缩写为BFS),又译作宽度优先搜索,或横向优先搜索,是一种图形搜索算法。 简单的说,BFS是从根节点开始,沿着树的宽度遍历树的节点。如果所有节点均被访问,则算法中止。 实现算法 1、首先将根节点放入队列中。 2、从队列中取出第一个节点,并检验它是否为目标。 ·如果找到目标,则结束搜索并回传结果。 ·否则将它所有尚未检验过的直接子节点加入队列中。 3、若队列为空,表示整张图都检查过了——亦即图中没有欲搜索的目标。结束搜索并回传“找不到目标”。 4、重复步骤2。 广度优先搜索算法能用来解决图论中的许多问题,例如: 查找图中所有连接组件(Connected Component)。一个连接组件是图中的最大相连子图。 查找连接组件中的所有节点。 查找非加权图中任两点的最短路径。 测试一图是否为二分图。 ''' def levelOrder(self, root): if not root: return [] res.cur_level = [],[root] while cur_level: temp = [] next_level = [] for i in cur_level: temp.append(i.val) if i.left: next_level.append(i.left) if i.right: next_level.append(i.right) res.append(temp) cur_level = next_level return res # 二叉搜索树 ''' 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。 示例: 输入: 3 输出: [   [1,null,3,2],   [3,2,null,1],   [3,1,null,null,2],   [2,1,3],   [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 ''' ''' 递归 二叉搜索树, 一节点大于左子树节点, 小于右子树节点 所以我们节点是从1到n,当一个节点为val那么它的左边是<= val,右边是>=val, ''' def generateTrees(self, n: int) -> List[TreeNode]: if n == 0: return [] @functools.lru_cache(None) def helper(start, end): res = [] if start > end: res.append(None) for val in range(start, end + 1): for left in helper(start, val - 1): for right in helper(val + 1, end): root = TreeNode(val) root.left = left root.right = right res.append(root) return res return helper(1, n) # 不同的二叉搜索树 ''' 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 ''' ''' 动态规划 假设n个节点存在 令G(n)的从1到n可以形成二叉排序树个数 令f(i)为以i为根的二叉搜索树的个数 即有:G(n) = f(1) + f(2) + f(3) + f(4) + ... + f(n) n为根节点,当i为根节点时,其左子树节点个数为[1,2,3,...,i-1],右子树节点个数为[i+1,i+2,...n],所以当i为根节点时,其左子树节点个数为i-1个,右子树节点为n-i,即f(i) = G(i-1)*G(n-i), 上面两式可得:G(n) = G(0)*G(n-1)+G(1)*(n-2)+...+G(n-1)*G(0) ''' def numTrees(self, n: int) -> int: dp = [0] * (n + 1) dp[0] = 1 dp[1] = 1 for i in range(2, n + 1): for j in range(i): dp[i] += dp[j] * dp[i - j - 1] return dp[-1] # 验证二叉搜索树 ''' 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: 2 / \ 1 3 输出: true 示例 2: 输入: 5 / \ 1 4   / \   3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。   根节点的值为 5 ,但是其右子节点值为 4 。 ''' # 因为二叉搜索树中序遍历是递增的,所以我们可以中序遍历判断前一数是否小于后一个数. def isValidBST(self, root: TreeNode) -> bool: res = [] def helper(root): if not root: return helper(root.left) res.append(root.val) helper(root.right) helper(root) return res == sorted(res) and len(set(res)) == len(res) # 恢复二叉搜索树 ''' 二叉搜索树中的两个节点被错误地交换。 请在不改变其结构的情况下,恢复这棵树。 示例 1: 输入: [1,3,null,null,2]   1   /  3   \   2 输出: [3,1,null,null,2]   3   /  1   \   2 示例 2: 输入: [3,1,4,null,null,2] 3 / \ 1 4   /   2 输出: [2,1,4,null,null,3] 2 / \ 1 4   /  3 ''' ''' 这里我们二叉树搜索树的中序遍历(中序遍历遍历元素是递增的) 如下图所示, 中序遍历顺序是 4,2,3,1,我们只要找到节点4和节点1交换顺序即可! 这里我们有个规律发现这两个节点: 第一个节点,是第一个按照中序遍历时候前一个节点大于后一个节点,我们选取前一个节点,这里指节点4; 第二个节点,是在第一个节点找到之后, 后面出现前一个节点大于后一个节点,我们选择后一个节点,这里指节点1 3 / \ 4 1 \ 2 ''' # 迭代 def recoverTree(self, root: TreeNode) -> None: firstNode = None secondNode = None pre = TreeNode(float("-inf")) stack = [] p = root while p or stack: while p: stack.append(p) p = p.left p = stack.pop() if not firstNode and pre.val > p.val: firstNode = pre if firstNode and pre.val > p.val: #print(firstNode.val,pre.val, p.val) secondNode = p pre = p p = p.right # 相同的树 ''' 给定两个二叉树,编写一个函数来检验它们是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例 1: 输入: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] 输出: true 示例 2: 输入: 1 1 / \ 2 2 [1,2], [1,null,2] 输出: false 示例 3: 输入: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] 输出: false ''' # 迭代 def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: stack = [(q, p)] while stack: a, b = stack.pop() if not a and not b: continue if a and b and a.val == b.val: stack.append((a.left, b.left)) stack.append((a.right,b.right)) else: return False return True
a87fdf82d6f35de3a48b9788a4a904f1428372cc
kenan666/Study
/算法总结/二叉搜索树_节点删除.py
18,047
3.53125
4
#----------二叉搜索树 知识点-------- ''' 二叉查找树(Binary Search Tree),也称为二叉搜索树、有序二叉树(ordered binary tree)或排序二叉树(sorted binary tree), 是指一棵空树或者具有下列性质的二叉树: 1、若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值; 2、若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值; 3、任意节点的左、右子树也分别为二叉查找树; 4、没有键值相等的节点。 插入、删除、查找时间复杂度为 O(logN) * 最坏 O(n) ''' # ------二叉搜索树 查找------ ''' 在二叉搜索树b中查找x的过程为: 1、若b是空树,则搜索失败,否则: 2、若x等于b的根节点的数据域之值,则查找成功;否则: 3、若x小于b的根节点的数据域之值,则搜索左子树;否则: 4、查找右子树。 ''' #--------------------------------------- # Status SearchBST(BiTree T, KeyType key, BiTree f, BiTree &p) { # // 在根指针T所指二元查找樹中递归地查找其關键字等於key的數據元素,若查找成功, # // 則指针p指向該數據元素節點,并返回TRUE,否則指针指向查找路徑上訪問的最後 # // 一個節點并返回FALSE,指针f指向T的雙親,其初始调用值為NULL # if (!T) { // 查找不成功 # p = f; # return false; # } else if (key == T->data.key) { // 查找成功 # p = T; # return true; # } else if (key < T->data.key) // 在左子樹中繼續查找 # return SearchBST(T->lchild, key, T, p); # else // 在右子樹中繼續查找 # return SearchBST(T->rchild, key, T, p); # } #--------------------------------------- #---------二叉搜索树 节点插入------------ ''' 向一个二叉搜索树b中插入一个节点s的算法,过程为: 1、若b是空树,则将s所指节点作为根节点插入,否则: 2、若s->data等于b的根节点的数据域之值,则返回,否则: 3、若s->data小于b的根节点的数据域之值,则把s所指节点插入到左子树中,否则: 4、把s所指节点插入到右子树中。(新插入节点总是叶子节点) ''' #--------------------------------------------------- # /* 当二元搜尋樹T中不存在关键字等于e.key的数据元素时,插入e并返回TRUE,否则返回 FALSE */ # Status InsertBST(BiTree *T, ElemType e) { # if (!T) { # s = new BiTNode; # s->data = e; # s->lchild = s->rchild = NULL; # T = s; // 被插節点*s为新的根结点 # } else if (e.key == T->data.key) # return false;// 关键字等于e.key的数据元素,返回錯誤 # if (e.key < T->data.key) # InsertBST(T->lchild, e); // 將 e 插入左子樹 # else # InsertBST(T->rchild, e); // 將 e 插入右子樹 # return true; # } #--------------------------------------------------- #----------二叉搜索树 节点删除-------------- ''' 在二叉查找树删去一个结点,分三种情况讨论: 1、若*p结点为叶子结点,即PL(左子树)和PR(右子树)均为空树。由于删去叶子结点不破坏整棵树的结构,则只需修改其双亲结点的指针即可。 2、若*p结点只有左子树PL或右子树PR,此时只要令PL或PR直接成为其双亲结点*f的左子树(当*p是左子树)或右子树(当*p是右子树)即可, 作此修改也不破坏二叉查找树的特性。 3、若*p结点的左子树和右子树均不空。在删去*p之后,为保持其它元素之间的相对位置不变,可按中序遍历保持有序进行调整, 可以有两种做法:其一是令*p的左子树为*f的左/右(依*p是*f的左子树还是右子树而定)子树,*s为*p左子树的最右下的结点, 而*p的右子树为*s的右子树;其二是令*p的直接前驱(in-order predecessor)或直接后继(in-order successor)替代*p, 然后再从二叉查找树中删去它的直接前驱(或直接后继)。 ''' #------ C++ 版本------------------------------------- # Status DeleteBST(BiTree *T, KeyType key) { # // 若二叉查找树T中存在关键字等于key的数据元素时,则删除该数据元素,并返回 # // TRUE;否则返回FALSE # if (!T) # return false; //不存在关键字等于key的数据元素 # else { # if (key == T->data.key) // 找到关键字等于key的数据元素 # return Delete(T); # else if (key < T->data.key) # return DeleteBST(T->lchild, key); # else # return DeleteBST(T->rchild, key); # } # } # Status Delete(BiTree *&p) { # // 该节点为叶子节点,直接删除 # BiTree *q, *s; # if (!p->rchild && !p->lchild) { # delete p; # p = NULL; // Status Delete(BiTree *&p) 要加&才能使P指向NULL # } else if (!p->rchild) { // 右子树空则只需重接它的左子树 # q = p->lchild; # /* # p->data = p->lchild->data; # p->lchild=p->lchild->lchild; # p->rchild=p->lchild->rchild; # */ # p->data = q->data; # p->lchild = q->lchild; # p->rchild = q->rchild; # delete q; # } else if (!p->lchild) { // 左子树空只需重接它的右子树 # q = p->rchild; # /* # p->data = p->rchild->data; # p->lchild=p->rchild->lchild; # p->rchild=p->rchild->rchild; # */ # p->data = q->data; # p->lchild = q->lchild; # p->rchild = q->rchild; # delete q; # } else { // 左右子树均不空 # q = p; # s = p->lchild; # while (s->rchild) { # q = s; # s = s->rchild; # } // 转左,然后向右到尽头 # p->data = s->data; // s指向被删结点的“前驱” # if (q != p) # q->rchild = s->lchild; // 重接*q的右子树 # else # q->lchild = s->lchild; // 重接*q的左子树 # delete s; # } # return true; # } #------------------------------------------- #--- python版本 ----------------------------------------- def find_min(self): # Gets minimum node (leftmost leaf) in a subtree current_node = self while current_node.left_child: current_node = current_node.left_child return current_node def replace_node_in_parent(self, new_value=None): if self.parent: if self == self.parent.left_child: self.parent.left_child = new_value else: self.parent.right_child = new_value if new_value: new_value.parent = self.parent def binary_tree_delete(self, key): if key < self.key: self.left_child.binary_tree_delete(key) elif key > self.key: self.right_child.binary_tree_delete(key) else: # delete the key here if self.left_child and self.right_child: # if both children are present successor = self.right_child.find_min() self.key = successor.key successor.binary_tree_delete(successor.key) elif self.left_child: # if the node has only a *left* child self.replace_node_in_parent(self.left_child) elif self.right_child: # if the node has only a *right* child self.replace_node_in_parent(self.right_child) else: # this node has no children self.replace_node_in_parent(None) #----------------------------------------- # ----------二叉树遍历--------------- # 中序遍历(in-order traversal) def traverse_binary_tree(node, callback): if node is None: return traverse_binary_tree(node.leftChild, callback) callback(node.value) traverse_binary_tree(node.rightChild, callback) #--------------------------------------------------------------------------------- #-------------- 例题 -------------------------------------------- ''' 给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。 返回二叉搜索树(有可能被更新)的根节点的引用。 一般来说,删除节点可分为两个步骤: 首先找到需要删除的节点; 如果找到了,删除它。 说明: 要求算法时间复杂度为 O(h),h 为树的高度。 示例: root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。 一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。 5 / \ 4 6 / \ 2 7 另一个正确答案是 [5,2,6,null,4,null,7]。 5 / \ 2 6 \ \ 4 7 ''' # --- 题解---------- ''' 删除某一节点的情况有三种: 1.该节点无子节点 2.该节点只有一个子节点 3.该节点有两个字节点 ''' ''' 理解这个算法的关键在于保持 BST 中序遍历的顺序性,当待删除结点的左右结点都不为空的时候,让待删除结点的前驱结点或者后继结点代替被删除结点, 这样就能成为一棵树,并且还是 BST,否则就变成森林,或者不保持 BST 中序遍历的顺序性了。 ** 第一种情况----待删除节点的的左子树为空 5 5 / \ / \ 1 6 -----> 删除 6 节点 ------> 1 8 ---> 此时用 待删除 节点的 右子树 代替 6 就可以 \ \ \ / \ 3 8 3 7 9 / \ / \ / \ 2 4 7 9 2 4 ** 第二种情况-----待删除节点的右子树为空 5 5 / \ / \ 4 6 2 6 ---> 此时用 待删除 节点的 左子树 代替 4 就可以 / -----> 删除 4 节点 -------> / \ 2 1 3 / \ 1 3 ** 第三种情况------- 如果 待删除 节点的 左右子树 均不为空 ---> 处理方式1: 此时用 待删除 节点的 前驱节点 代替它 4 4 / \ / \ 2 8 2 7 / \ / \ ----> 删除 节点 8 ----> / \ / \ ---> 此时用 待删除 节点的 前驱节点 代替 8 就可以 1 3 6 10 1 3 6 10 / \ / \ / / \ 5 7 9 11 5 9 11 * 节点 7 是 节点 8 的 前驱节点 ** 第三种情况------- 如果 待删除 节点的 左右子树 均不为空 ---> 处理方式2: 此时用 待删除 节点的 后继节点 代替它 4 4 / \ / \ 2 8 2 9 / \ / \ ----> 删除 节点 8 ----> / \ / \ ---> 此时用 待删除 节点的 后继节点 代替 8 就可以 1 3 6 10 1 3 6 10 / \ / \ / \ \ 5 7 9 11 5 7 11 * 节点 9 是 节点 8 的 后继节点 ''' #-----------解1--- 前驱节点 代替被删除节点---------- # 方法1:用左子树中最大结点的代替被删除结点 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def deleteNode(self, root, key): if root is None: return None if key < root.val: root.left = self.deleteNode(root.left, key) return root if key > root.val: root.right = self.deleteNode(root.right, key) return root if root.left is None: new_root = root.right root.right = None return new_root if root.right is None: new_root = root.left root.left = None return new_root # 找到左子树中最大的 predecessor = self.__maximum(root.left) predecessor_copy = TreeNode(predecessor.val) predecessor_copy.left = self.__remove_max(root.left) predecessor_copy.right = root.right root.left = None root.right = None return predecessor_copy def __remove_max(self, node): if node.right is None: new_root = node.left node.left = None return new_root node.right = self.__remove_max(node.right) return node def __maximum(self, node): while node.right: node = node.right return node #------解2 --- 后继节点代替被删除节点------ # 方法2:用右子树中最小结点的代替被删除结点 class Solution: def deleteNode(self, root, key): if root is None: return None if key < root.val: root.left = self.deleteNode(root.left, key) return root if key > root.val: root.right = self.deleteNode(root.right, key) return root if root.left is None: new_root = root.right root.right = None return new_root if root.right is None: new_root = root.left root.left = None return new_root # 找到右子树中最小的结点,复制它的值 successor = self.__minimum(root.right) successor_copy = TreeNode(successor.val) successor_copy.left = root.left successor_copy.right = self.__remove_min(root.right) root.left = None root.right = None return successor_copy def __remove_min(self, node): if node.left is None: new_root = node.right node.right = None return new_root node.left = self.__remove_min(node.left) return node def __minimum(self, node): while node.left: node = node.left return node #-----------------参考其他解------------------- # ---- 递归求解----------- def deleteNode(self, root, key): if not root: return None; if root.val > key: root.left = self.deleteNode(root.left, key) elif root.val < key: root.right = self.deleteNode(root.right, key) else: if not root.left or not root.right: root = root.left if root.left else root.right else: cur = root.right while cur.left: cur = cur.left root.val = cur.val root.right = self.deleteNode(root.right, cur.val) return root # ----- 解 2 --- 参考 --- def deleteNode(self, root, key): def deleteNode_c(root): # 删除root中值为key的节点,并返回根结点 if root is None: return None if root.val == key: # 如果没有左子树和右子树,删除自己 if root.left is None and root.right is None: return None elif root.left is None: return root.right elif root.right is None: return root.left else: # 使用右边最小值替换掉当前节点,然后删除右子树的最小值 p = find_min_c(root.right) root.right = delete_min_c(root.right) p.left = root.left p.right = root.right return p elif root.val > key: # 去左子树中删除,并把自己的left指向删除后的左子树 root.left = deleteNode_c(root.left) return root else: root.right = deleteNode_c(root.right) return root def find_min_c(root): if root is None: return root p = root while p.left is not None: p = p.left return p def delete_min_c(root): # 删除root为根节点的树中的最小值 if root is None: return None elif root.left is None: # 此时为要删除的节点 return root.right else: root.left = delete_min_c(root.left) return root return deleteNode_c(root)
5162f393d11269f5242661d63feb8f52335f9d05
SBentley/random-gen
/random-gen.py
617
3.734375
4
from random import random class RandomGen(object): # Values that may be returned by next_num() _random_nums = [-1,0,1,2,3] # Probability of the occurence of random_nums _probabilities = [0.01,0.3,0.58,0.1,0.01] def next_num(self): ran = random() print(ran) lower = 0 higher = 0 for prob in self._probabilities: higher += prob print(f'{lower} - {higher}') if lower <= ran <= higher: print('hit') pass lower = higher pass ran = RandomGen() a = ran.next_num() print(a)
febf90deca77f9cba1d60c646d24f7a9dab06ef6
skyczhao/analysis-tools
/utils/dicts.py
889
3.703125
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Dicts # # @author tobin # @since 2018-06-22 """ 词典工具类 """ def double_set(d, k, v_k, v_v): """ 往词典对应key添加k-v :param d: 词典 :param k: 键 :param v_k: 值的key :param v_v: 值的value :return: """ if isinstance(d, dict): if k not in d: d[k] = dict() d[k][v_k] = v_v def append(d, k, v): """ 往词典对应key添加值 :param d: 词典 :param k: 键 :param v: 值 :return: """ if isinstance(d, dict): if k not in d: d[k] = [] d[k].append(v) def add(d, k, v=1): """ 词典对应key值数值操作 :param d: 词典 :param k: 键 :param v: 值 :return: """ if isinstance(d, dict): if k not in d: d[k] = 0 d[k] = d[k] + v
0f578a88114c31c6e6c982a42ed2ebf895f2908d
h3ll5ur7er/GoogleCTF2019Writeup
/BeginnersQuest/52_FriendSpaceBookPlusAllAccessRedPremium/pal_prime_finder.py
434
3.609375
4
def is_palindrome(n:str): for i in range(len(n)//2): if n[i] != n[-(i+1)]: return False return True with open("/root/Downloads/2T_part1.txt", "r") as primes: with open("palprimes.txt", "w") as palprimes: for line in primes.readlines(): numbers = line.split() for n in numbers: if is_palindrome(n): palprimes.write("{}\n".format(n))
745459107fc78e26612fdcd9b6ca56830de9a005
VincentVelthuizen/Menace
/user_interface/command_line.py
945
3.765625
4
import user_interface class CommandLine(user_interface.UI): symbol = [" ", "X", "O"] def render(self, board=None): row_strings = [] for row in range(3): values = [self.symbol[board.cell((row, col))] for col in range(3)] row_strings.append(" " + " | ".join(values) + " ") print("\n---|---|---\n".join(row_strings)) print("") def get_move(self, board): not_valid = True while not_valid: try: move = input("where would you like to move?") if len(move) != 1: raise ValueError return ord(move) except ValueError: print("please provide a single character") def add_score(self, winner): if winner in [1, 2]: player = self.symbol[winner] else: player = "Nobody" print("%s has won the game!" % player)
65f5ea882966a4b45913a081aa988142e3e35906
anaferreirapy/Python-para-Zumbis-2020
/Lista 1 - Início/L1 - ex11.py
207
3.75
4
#Sabendo que str( ) converte valores numéricos para string, calcule quantos dígitos há em 2 elevado #a um milhão. a = 2 ** 1000000 b = len(str(a)) print('2 elevado a 1000000, possui ',b,' dígitos.')
c3f231f64df2d9ec0c4167d6d9372380f7233496
anaferreirapy/Python-para-Zumbis-2020
/Lista 2 - Condicionais/L2 - ex3.py
991
3.65625
4
#João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de #seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do #estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você #faça um programa que leia a variável peso (peso de peixes) e verifique se há excesso. Se houver, gravar na #variável excesso e na variável multa o valor da multa que João deverá pagar. Caso contrário mostrar tais # variáveis com o conteúdo ZERO. kg = float(input('Informe a quantidade de kg de peixes:')) if kg > 50: multa = (kg - 50) * 4 excesso = kg - 50 print('a quantidade de kg de peixes excedeu! A quantidade excedida é de: ',excesso,'kg.') print(f'E o valor total da multa é de R$: {multa: .2f}') else: print('Quantidade dentro do padrão!') multa = 0 excesso = 0 print('Excesso: ',excesso,' e Multa: ',multa,'.')
94c010ca3c5552c7179cf220bdc566f66363f5ef
anaferreirapy/Python-para-Zumbis-2020
/Exercícios de aula/Condicionais/minutos telefone - if.py
584
3.546875
4
#Considere a empresa de telefonia Tchau. #ABaixo de 200 minutos, a empresa cobra R$ 0,20 por minuto. #ENtre 200 e 400 minutos, o preço é de R$ 0,18. #Acima de 400 minutos o preço por minuto é de R$ 0,15. #Calcule sua conta de telefone. min = int(input("Informe a quantidade de minutos consumidos:")) if min < 200: v = min * 0.20 print(f'O valor da sua conta é de: R$ {v: .2f}.') if min >= 200 and min <=400: v = min * 0.18 print(f'O valor da sua conta é de: R$ {v: .2f}.') if min > 400: v = min * 0.15 print(f'O valor da sua conta é de: R$ {v: .2f}.')
48ae1758c2351c27e71dfef24736c2d23b2ea9e7
anaferreirapy/Python-para-Zumbis-2020
/Lista 2 - Condicionais/L2 - ex7.py
625
3.984375
4
#Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a #ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida #em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem #compradas e o preço total. Obs. : somente são vendidos um número inteiro de latas. m2 = int(input('Informe o tamanho da área em metros quadrados:')) if m2 % 54 == 0: latas = m2 / 54 else: latas = int(m2 / 54) + 1 v = latas * 80 print(f'{latas} latas') print(f'Total: R$ {v: .2f}')
a56090aeb44d8a7969610f12e490c7644300f6e6
AshBringer47/kpi_labs
/Lab 6/Lab 6.py
412
3.59375
4
import os def main(): print_sum() def print_sum(): try: a = float(input("Gunawardana Shiron. IS-92. Please enter a, b, c.\na = ")) b = float(input("b = ")) c = float(input("c = ")) T = ex_sum(a, b, c) print(T) except KeyboardInterrupt: print("\nProgram executed.") def ex_sum(a, b, c): return (maxN(a, a + b) + maxN(a, b + c)) / (1 + maxN(a + b * c, 1.15))
3312f9fb4b30547b407ecfe0657dee5b55c1907b
bethanw10/advent-of-code
/Day 6 - Universal Orbit Map/Day6.py
2,874
3.5
4
class OrbitMap: def __init__(self, name): self.name = name self.children = [] self.parent = None def __repr__(self): return f"{self.name}" def find(self, name): if self.name == name: return self else: for child in self.children: match = child.find(name) if match is not None: return match return None def add_child(self, child): self.children.append(child) child.parent = self @property def orbit_count(self): return self.get_orbit_count()[0] def get_orbit_count(self): total = 0 num_nodes = 1 for child in self.children: child_total, num_child_nodes = child.get_orbit_count() total += child_total + num_child_nodes num_nodes += num_child_nodes return total, num_nodes def find_path(self, name): if self.name == name: return self else: for child in self.children: match = child.find(name) if match is not None: return match return None def find_path_to(self, name, path_stack): if self.name == name: return self else: for child in self.children: match = child.find_path_to(name, path_stack) if match is not None: path_stack.append(self.name) return match return None def find_path_between(self, from_name, to_name): from_path_stack = [] to_path_stack = [] self.find_path_to(from_name, from_path_stack) self.find_path_to(to_name, to_path_stack) path = [path for path in from_path_stack if path not in to_path_stack] + \ [path for path in to_path_stack if path not in from_path_stack] return path def find(orbit_maps, planet): for orbit_map in orbit_maps: match = orbit_map.find(planet) if match is not None: return match return None def main(): file = open("input.txt", "r") data = file.read().split('\n') orbit_maps = [] for orbit_data in data: planet, orbiter = orbit_data.split(')') planet_map = find(orbit_maps, planet) orbiter_map = find(orbit_maps, orbiter) if planet_map is None: planet_map = OrbitMap(planet) orbit_maps.append(planet_map) if orbiter_map is None: orbiter_map = OrbitMap(orbiter) else: orbit_maps.remove(orbiter_map) planet_map.add_child(orbiter_map) for orbit_map in orbit_maps: path_stack = orbit_map.find_path_between("YOU", "SAN") print(len(path_stack)) if __name__ == "__main__": main()
cbb075dff8a66b6438f708eb2055954c4d553d8c
AlonsoZhang/PythonHardWay
/ex25n.py
1,317
4
4
import ex25 sentence = "All good things come to those who wait." # words = break_words(sentence) words = ex25.break_words(sentence) sorted_words = ex25.sort_words(words) ex25.print_first_word(words) # 打印了个All ex25.print_last_word(words) # 打印了个wait. ex25.print_first_word(sorted_words) # 打印了个All。 ex25.print_last_word(sorted_words) # 打印了个who sorted_words = ex25.sort_sentence(sentence) ex25.print_first_and_last(sentence) # C:打印第一个All和最后一个字wait。 ex25.print_first_and_last_sorted(sentence) # D 打印第一个All和最后一个sorted的句子who。 print("-------- THE END ----------") print("---------下面是采用了from ex25 import *") from ex25 import * sentence = "All good things come to those who wait." # words = break_words(sentence) words = break_words(sentence) sorted_words = sort_words(words) print_first_word(words) # 打印了个All print_last_word(words) # 打印了个wait. print_first_word(sorted_words) # 打印了个All。 print_last_word(sorted_words) # 打印了个who sorted_words = sort_sentence(sentence) print_first_and_last(sentence) # C:打印第一个All和最后一个字wait。 print_first_and_last_sorted(sentence) # D 打印第一个All和最后一个sorted的句子who。 print("-------- THE END ----------")
2211dca301494ad9e517f0098e01263c047806a0
VB-Cloudboy/PythonCodes
/03-InputOutput/01-IO_Statement.py
689
3.921875
4
# A series of Input-Output Statement #01-Playing with String player = str(input("Enter a Player Name: ")) print('you just wrote: ', player) #02-Playing with Numbers player = int(input("Enter a Player Jersey Number: ")) print('you just wrote: ', player) #03-Palying with Multiple Numbers batsmen01 = str(input("Enter Player01 name: ")) batsmen02 = str(input("Enter Player02 name: ")) play01 = int(input("Enter a player jersey number: ")) play02 = int(input("Enter a player jersey number: ")) print("Please do not opt for {} and {} numbers".format(play01,play02)) #03-Floating with Numbers exp = float(input("What's the ICC cost of the player ? = ")) print("The Player cost is ", exp)
2df05235e11b4f969f147ffa6dcde19ceb0c0dec
VB-Cloudboy/PythonCodes
/10-Tuples/02_Access-Tuple.py
403
4.125
4
mytuple = (100,200,300,400,500,600,700,800,900) #1. Print specific postion of the tuples starting from Right print(mytuple[2]) print(mytuple[4]) print(mytuple[5]) #2. Print specific postion of the tuples starting from Left print(mytuple[-3]) print(mytuple[-5]) print(mytuple[-4]) #3. Slicing (Start: Stop: Stepsize) print(mytuple[:]) print(mytuple[1:3]) print(mytuple[::-3]) print(mytuple[-1::-5])
9cb69c3b0fdea7975347c1a00d28853b4b0c52a5
BillNguyen1999/Jumbled-Words
/se3xa3-project/src/main_start.py
3,207
3.875
4
## @file main_start.py # @author Muneeb Arshad, Shesan Balachandran, Bill Nguyen # @title main_start # @date April 4, 2021 from tkinter import * # Global Variables gameMode = "" difficulty = "" username = None ## @brief start_main_page # @details function is used to start and display the main menu page and initializes everything in order for the game to work def start_main_page(): ## @brief back function # @details This function is used to return back to the main menu def back(): main_window.destroy() start_main_page() ## @brief showbackButton function # @details This function is used to display the back button def showBackButton(): backButton = Button( main_window, image=img1, bg='#e6fff5', border=0, justify='center', command=back, ) backButton.grid(row=0, column=0, padx=20) ## @brief show enter usernmae function # @details This function is used to display the username setting def show_enter_username(): start_btn.destroy() leader_btn.destroy() quit_btn.destroy() lab_img.destroy() import UserGUI UserGUI.username_page(main_window) ## @brief show leaderboard function # @details This function is used to display the leaderboard UI def show_leaderboard(): start_btn.destroy() leader_btn.destroy() quit_btn.destroy() lab_img.destroy() import leaderBoard showBackButton() leaderBoard.show() ## @brief quit function # @details This function is used to quit the game def quit(): main_window.destroy() main_window = Tk() main_window.geometry("500x500+500+150") main_window.resizable(0, 0) main_window.title("Quizee --> Grow your kids with Quizee") main_window.configure(background="#e6fff5") main_window.iconbitmap(r'assets/quizee_logo_.ico') img0 = PhotoImage(file="assets/quizee_logo.png") img1 = PhotoImage(file="assets/back.png") lab_img = Label( main_window, image=img0, bg='#e6fff5', ) lab_img.pack(pady=(50, 0)) start_btn = Button( main_window, text="Start", width=18, borderwidth=8, fg="#000000", bg="#99ffd6", font=("", 13), cursor="hand2", command=show_enter_username, ) start_btn.pack(pady=(20, 10)) leader_btn = Button( main_window, text="Leaderboard", width=18, borderwidth=8, fg="#000000", bg="#99ffd6", font=("", 13), cursor="hand2", command=show_leaderboard, ) leader_btn.pack(pady=(20, 10)) quit_btn = Button( main_window, text="Quit", width=18, borderwidth=8, fg="#000000", bg="#99ffd6", font=("", 13), cursor="hand2", command=quit, ) quit_btn.pack(pady=(20, 10)) main_window.mainloop() start_main_page()
066eb690c9b39caaa1ee8729195360eb7d9f641e
maddyv/DSUPython
/connectstr.py
939
3.84375
4
def connectstr(): st=input("Enter the connect string: ") d1={"server":'',"dbname":'',"user":'',"passwd":''} i1=int(0) # Init counter and index vars i2=int(0) ctr=int(0); for j in range(0,len(st)): # Loop to check for = characters if st[j]=='=': ctr+=1 # char counter i1=j # Stores index of current = char for k in range(j,len(st)): # Checks for the next immediate semi colon if st[k]==';': i2=k break if ctr==1: # Assigns the obtained substring to the appropriate key based on counter d1["server"]=st[i1+1:i2] elif ctr==2: d1["dbname"]=st[i1+1:i2] elif ctr==3: d1["user"]=st[i1+1:i2] elif ctr==4: d1["passwd"]=st[i1+1:] return d1 print(connectstr()) # Prints the dictionary
7e1cb17eb84bb8c89eb3b7953d591e80df57fcc6
xinzhuanjing/Python
/data_type/eq.py
316
3.65625
4
class T: def __init__(self, data): self.data = data def __eq__(self, a): print("This is in __eq__") if self.data == a.data: return True; else: return False if __name__ == "__main__": a = T(1) b = T(1) print(a == b)
22b03632f410db181d6619a49ecb0c7850ee2369
xinzhuanjing/Python
/class/attribute_control.py
3,195
3.90625
4
# class Test: # A = 10 # def __init__(self): # self.a = 1 # def __getattribute__(self, item): # print("This is in __getattribute__") # return object.__getattribute__(self, item) # print("Instance: a = %s" % Test().a) # print("Instance: A = %s" % Test().a) # print("Class: A = %s" % Test.A) # #### # class Test: # A = 10 # def __init__(self): # self.a = 1 # def __getattribute__(self, item): # print("This is in __getattribute__") # return object.__getattribute__(self, item) # hasattr(Test(), "a") # getattr(Test(), "A") # #### # class Test: # def __init__(self): # self.a = 1 # def __getattribute__(self, item): # print("This is in __getattribute__") # if item not in super(Test, self).__getattribute__("__dict__"): # print("item: %s is not in __dict__" % item) # raise AttributeError # return super(Test, self).__getattribute__(item) # def __getattr__(self, item): # print("This is __getattr__") # print("Instance: a = %s" % Test().a) # print("Instance: b = %s" % Test().b) # #### # class Test: # def __init__(self): # self.a = 1 # def __getattribute__(self, item): # print("This is in __getattribute__") # if item not in super(Test, self).__getattribute__("__dict__"): # print("item: %s is not in __dict__" % item) # raise AttributeError # return super(Test, self).__getattribute__(item) # def __getattr__(self, item): # print("This is __getattr__") # hasattr(Test(), "b") # getattr(Test(), "c") # ##### # class Test: # def __init__(self): # self.a = 1 # def __setattr__(self, name, value): # print("This is __setattr__, name=%s, value=%s" % (name, value)) # self.__dict__[name] = value # test = Test() # test.a = 2 # test.b = 1 # ###### # class Test: # def __init__(self): # self.a = 1 # def __setattr__(self, name, value): # print("This is __setattr__, name=%s, value=%s" % (name, value)) # super(Test, self).__setattr__(name, value) # test = Test() # test.a = 2 # test.b = 1 # ####### # class Test: # def __init__(self): # self.a = 1 # def __setattr__(self, name, value): # print("This is __setattr__, name=%s, value=%s" % (name, value)) # super(Test, self).__setattr__(name, value) # test = Test() # setattr(test, "a", 2) # setattr(test, "b", 1) # ###### # class Test: # def __init__(self): # self.a = 1 # def __delattr__(self, item): # print("This is __delattr__, item=%s" % item) # self.__dict__.pop(item) # test = Test() # del test.a # print(test.__dict__) # ###### # class Test: # def __init__(self): # self.a = 1 # def __delattr__(self, item): # print("This is __delattr__, item=%s" % item) # super(Test, self).__delattr__(item) # test = Test() # del test.a # print(test.__dict__)
d2796e2e828c103194efb8389ca6e8be1d642b8f
xinzhuanjing/Python
/class/class_object_instance.py
3,211
4.15625
4
# class Test: # def __init__(self, a, b): # self.add_a = a # self.add_b = b # def add(self): # return self.add_a + self.add_b # ##################################### # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # class_object_new_reference = ClassTest # class_object_new_reference().echo() # ##################################### # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # def test(cls): # print("This is in test") # cls().echo() # test(ClassTest) # ################################### # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # def test(): # print("This is in test") # return ClassTest # class_object = test() # class_object().echo() # ############################## # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # test = {"a": ClassTest} # test["a"]().echo() # ########################## # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # class InternalTest: # def __init__(self): # print("InternalTest") # def echo(self): # print("This is in echo of InternalTest") # class_instance = ClassTest() # class_instance.echo() # class_instance.InternalTest().echo() # ########################### # def test(): # print("This is in test") # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # return ClassTest # class_object = test() # class_object().echo() # ############################### # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # class_instance_new_reference = ClassTest() # class_instance_new_reference.echo() # ########################### # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # def test(instance): # print("This is in test") # instance.echo() # test(ClassTest()) # ############################ # def test(): # print("This is in test") # class ClassTest: # def __init__(self): # print("This is in ClassTest") # def echo(self): # print("This is in echo") # return ClassTest() # class_object = test() # class_object.echo() # ##################### class ClassTest: def __init__(self): print("This is in ClassTest") def echo(self): print("This is in echo") test = {"a": ClassTest()} test["a"].echo()
60c6f0559d062bf319c84fc064b6422a0e160021
ml758392/python_tedu
/nsd2018-master/nsd1804/python/day02/if1.py
408
4.0625
4
if 3 > 10: print('yes') print('ok') else: print('no') # 任何非0数字都是True,值为0是False if -0.0: print('yes') if 0.1: print('0.1 yes') # 任何非空对象都是True,空是False: []/()/{}/'' if ' ': print('space ok') ##################################### a = 10 b = 20 if a < b: smaller = a else: smaller = b print(smaller) s = a if a < b else b print(s)