blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fcfe98f9fda82e4872e7036298f956f60da316d5
Vigneshg98/Guvi
/checkpnz.py
151
3.921875
4
inp = int(input()) if inp > 0 : print("Positive") elif inp < 0 : print("Negative") elif inp == 0: print("Zero") else : print("Invalid Input")
8382180cf9b5c3fe6de91d0f08f9f296c85392d7
rohaneden10/luminar_programs
/files/a2.py
272
3.59375
4
list=[] f=open("messi","r") sum=0 for lines in f: list.append(int(lines.rstrip("\n")))#intilay read as astring and we convert it to integer for i in list: sum+=i print(list) print(sum) #rstrip is used to remove end characters #lstrip used to remove first character
0fdcf381fa095c08c5fb678d5480ae8086a956c9
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4352/codes/1793_3141.py
166
3.71875
4
from numpy import* v = array(eval(input("digite numeros: "))) n = sum(v[0:]) m = (((v[0]**(1/6) + v[1]**(1/6) + v[2]**(1/6) + v[n-1]**(1/6))**6)/n) print(round(m, 2))
7cc445b3f3b104c8f890455e80bb4ea11a805134
velugotiss/Python-Deep-Learning
/ICP1/arithmetic.py
339
3.890625
4
var1 = input("Give the numbers to add") var2 = input() sum = float(var1)+float(var2) subs = float(var1)-float(var2) mult = float(var1)*float(var2) div = float(var1)/float(var2) mod = float(var1)%float(var2) print("sum :{0} \nsubstraction :{1} \n multiplication : {2}\n division : {3}\n modulus : {4}" .format(sum,subs,mult,div,mod))
13c2f8a6de4a0ec7544c903e53465b31572e8cb5
josebummer/ugr_programacion_tecnica_y_cientifica
/Relacion Listas/ej1.py
1,325
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 21 18:41:39 2018 @author: jose """ import numpy as np from time import time # ============================================================================= # Ejercicio 1 # Escribe una función sumNumLista(numeros) que sume todos los números de una # lista. Compara el tiempo entre usar o no range. # ============================================================================= #Funcion que dada una lista, devuelve la suma de los valores de la lista. def sumNumLista(numeros): suma = 0 for n in numeros: suma += n return suma def sumNumListaRange(numeros): suma = 0 for i in range(len(numeros)): suma += numeros[i] return suma #Rellenamos la lista con valores aleatorios. l = [] for i in range(20): l.append(np.random.randint(0,10)) #Calculamos la suma start_time = time() for i in range(100000): suma = sumNumLista(l) elapsed_time = time() - start_time start_time2 = time() for i in range(100000): suma = sumNumListaRange(l) elapsed_time2 = time() - start_time2 #Mostramos el resultado print('La suma total de los elementos es '+str(suma)) print("El proceso sin range ha tardado: "+str(elapsed_time)) print("El proceso con range ha tardado: "+str(elapsed_time2))
86c034ba8ee4c6b30f3869d80d610b03b2955b8f
xukangjune/Leetcode
/solved/326. 3的幂.py
398
3.71875
4
""" 此题不用循环或者递归来做,在整数范围最大的3的n次幂为3^19==1162261467。所以所有3的幂都可以整除它,其它的数则不能。 """ class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ return 1162261467 % n == 0 if n > 0 else False solve = Solution() print(solve.isPowerOfThree(81))
00309f1a0478496f39abce568d00e03f39476df5
woskar/automation
/files/files.py
4,145
4.0625
4
""" # Reading and Writing files Folder names and filenames are not case sensitive on Windows and macOS but they are on Linux. Windows: root C:\ and backslashes \ as separators Linux and Mac: root /. and forwardslashes / as separators use os.path.join() function (import os) os.path.sep returns the separator used on the operating system Current working directory (cwd): os.getcwd() change cwd with: os.chdir('new path') . for this directory .. for the parent directory ./ at the start of a relative path is optional: ./spam.txt and spam.txt are the same. create new directories: os.makedirs('new path') pass e.g. /delicious/waffles to create two new folders os.path.abspath(pathname) returns string of the path of pathname os.path.isabs(pathname) returns true if path is absolute os.path.relpath(path, start) returns string of a relative path from the start to path, if start is not provided, then current working directory is used as start path os.path.dirname(path) returns string of everything before the last / in path os.path.basename(path) returns string of everything after last / in path so path is composed of dirname/basename, basename is filename os.path.split(path_to_file) returns tuple of (dirname, basename) to split at every / use pathname.split(os.path.sep) os.path.getsize(pathname) returns size of file in pathname in bytes os.listdir(pathname) returns list of filename strings for each file in pathname combine the two to get the total size in a path (here cwd): totalSize = 0 for filename in os.listdir('.'): totalSize = totalSize + os.path.getsize(filename) # check path validity os.path.exists(path) returns true if path exists os.path.isfile(path) returns true if path argument exists and is a file os.path.isdir(path) returns true if path argument exists and is a folder use for example to check if a hard drive is connected # reading/writing following functions applicable to plaintext files which contain only basic text characters like .txt or .py files other files are binary files, pdfs, images, executables etc Three steps of reading or writing: 1. call open(path, 'r') to return a file object (in reading 'r' plaintext mode (default) or write 'w' or append 'a') if path does not exist yet, file will be created 2. call read() method on file object, returns one string with all the text, or write(), pass a string with the text to write, or readlines(), returns list of strings with lines, newline characters \n have to be added manually 3. close file by calling close() on the file object # shelve module allows to save variables/data from python programs to binary shelf files for later re-load import shelve shelfFile = shelve.open('mydata') # create shlef object for writing ('w' not needed with shelve) cats = ['Zophie', 'Pooka', 'Simon'] # an example variable shelfFile['cats'] = cats # make changes to shelf file as if it was a dictionary shelfFile.close() # close the file when you're done # running this will create a mydata.db file openShelfFile = shelve.open('mydata') # open file for reading openShelfFile['cats'] # retrieve data saved with key cats list(openShelfFile.values()) # get list of stored values (cast to get true list and not list-like values) list(openShelfFile.keys()) openShelfFile.close() # close file again use pretty printing to save variables in correct formatted form saving the code to a .py file lets you import the data like a normal module import pprint cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}] pprint.pformat(cats) # optional, returns a formatted string with cats-dictionary fileObj = open('myCats.py', 'w') fileObj.write('cats = ' + pprint.pformat(cats) + '\n') fileObj.close() # now our file is a .py module and can be imported like any other module import myCats # import myCat.cats # returns the stored data myCat.cats[0] # returns first element in list benefit of a .py file: is text file, can be read and modified with any simple editor only for basic data types like integers, floats, strings, lists, dictionaries for most applications, shelve module preferred file objects cannot be encoded as text """
5a3391e392f90e7acfa3720323a6024e55109263
thomasharms/exxcellent_challenge
/challenge_exsolutions.py
5,831
3.5625
4
import pandas as pd import os.path ''' Task Weather Challenge is solved by class Weather_Data in order to run it use the predefined instantiation in line 137 Task Football Challenge is solved by class Football_Data in order to run it use the predefined instantiation in line 139 just run the file to see both solutions printed to stdout ''' class Weather_Data(): __data_path = 'src/main/resources/de/exxcellent/challenge/' __data_file = 'weather.csv' def __init__(self): # read csv data into DataFrame self.data self.read_weather_data_from_csv() # compute min-max temperature distance for each day and assign it # into DataFrame column self.data['difference'] self.compute_min_max_distance() # select smallest temperature min-max distance by day # assign it to self.min_difference self.get_min_temperature_distance_by_day() # assigns a DataFrame (matrix) containing the weather data to self.data def read_weather_data_from_csv(self): # check if file exists at the location in path if os.path.isfile(str(self.__data_path)+str(self.__data_file)): # assign csv data to pandas DataFrame self.data = pd.read_csv(str(self.__data_path)+str(self.__data_file)) else: #TODO might be deleted in deployment # in case there is no file... give some hint to user what went wrong print("File does not exist. Please check the path and file location. Run program out of folder programming-challenge.") # assign the distance from min_temperature_value to maxtemperature_value into a column in DataFrame # new column is named "difference" and can be referenced in that fashion def compute_min_max_distance(self): if not self.data.empty: self.data['difference'] = abs(self.data['MxT'] - self.data['MnT']) else: #TODO might be deleted in deployment print('No data exists.') # select the day with smallest difference in temperature min-max distance by day and # assign it to self.min_difference def get_min_temperature_distance_by_day(self): if not self.data['difference'].empty: # idxmin() returns index of the row where column 'difference' has the minimum value # loc[] returns the row of this index and we need the value in row 'Day' try: self.min_difference = int(self.data.loc[self.data['difference'].idxmin()]['Day']) # in case something goes wrong provide an explanation #TODO might be deleted in deployment except Exception as e: print('Could not select minimal temperature difference due to: %s' % (str(e))) else: # in case the column self.data['difference'] does not exists explain... #TODO might be deleted in deployment print('An error occured while selecting the minimal temperature difference by day') class Football_Data(): __data_path = 'src/main/resources/de/exxcellent/challenge/' __data_file = 'football.csv' def __init__(self): # read csv data into DataFrame self.data self.read_football_data_from_csv() # compute goal difference and assign it # into DataFrame column self.data['difference'] self.compute_goal_difference() # select smallest amount of goal distance by team # assign it to self.min_difference self.get_min_goal_difference_by_team() # assigns a DataFrame (matrix) containing the weather data to self.data def read_football_data_from_csv(self): # check if file exists at the location in path if os.path.isfile(str(self.__data_path)+str(self.__data_file)): # assign csv data to pandas DataFrame self.data = pd.read_csv(str(self.__data_path)+str(self.__data_file)) else: # in case there is no file... give some hint to user what went wrong print("File does not exist. Please check the path and file location. Run program out of folder programming-challenge.") # assign the goal difference into a column in DataFrame # new column is named "difference" and can be referenced in that fashion def compute_goal_difference(self): if not self.data.empty: self.data['difference'] = abs(self.data['Goals'] - self.data['Goals Allowed']) else: # TODO: provide some hint for debug purposes... might be deleted in deployment print('No data exists.') # select the team with smallest amount of goal difference and assign it to self.min_difference def get_min_goal_difference_by_team(self): if not self.data['difference'].empty: # idxmin() returns index of the row where column 'difference' has the minimum value # loc[] returns the row of this index and we need the value in row 'Team' try: self.min_difference = self.data.loc[self.data['difference'].idxmin()]['Team'] # in case something goes wrong provide an explanation #TODO might be deleted in deployment except Exception as e: print('Could not select team with smallest amount of goal difference due to: %s' % (str(e))) else: # in case the column self.data['difference'] does not exists explain... #TODO might be deleted in deployment print('An error occured while selecting the smallest goal difference by team') weather_challenge = Weather_Data() print(weather_challenge.min_difference) football_challenge = Football_Data() print(football_challenge.min_difference)
dd5ff5267967aad8ffe8386e4c53bc0a6967b116
panditdandgule/DataScience
/NLP/Hands on Natural Language Processing/Python Basics/Dictionaries.py
713
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 6 08:36:13 2019 @author: pandit """ #Key -Value Pairs dict1={} #Adding elements of the dictionary dict1['Apple']='Apple is a fruit' dict1['Orange']='Orange is a fruit' dict1['Car']='Cars are fast' dict1['Python']='Python is a snake' #Printng dictionary elements print(dict1) print(dict1['Apple']) print(dict1['car']) print(dict1['python']) print(dict1.get('jython','Does not exist')) #Deleting elements del dict1['Apple'] #Length of dictionary print(len(dict1)) #List of keys and Values listOfKeys=list(dict1.keys()) listOfValues=list(dict1.values()) #looping throug list for key in dict1.keys(): print(dict1[key])
0d27ec9567e71022e998d60597d5ac0f7e9ff88a
lalisnats/Proyecto-Programacion
/pro1.py
3,347
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 22 18:23:58 2019 @author: lovelace """ # Librerias importadas import time ############################################################################## # Clases class day: """ Clase day: Crea un objeto de tipo day cuyos atributos son horas, minutos, segundos y el nombre del dia """ def __init__(self, h = 0, m = 0, s = 0, name = None, num = 0): self.h = h self.m = m self.s = s self.name = name self.num = num def __str__(self): b = str(self.h) + "," + str(self.m) + "," + str(self.s) return b class month: """ Clase month: Crea un objeto tipo month cuyos atributos son dias y nombre del mes """ def __init__(self, days, name, num): self.days = [day(0,0,0,None,i) for i in range(1, days + 1)] self.name = name self.num = num class year: """ Clase year: Crea un objeto de tipo year cuyos atibutos son tipo de año y el nombre del año """ def __init__(self, name): self.month = [] self.month.append(month(31, "Enero", "01")) if (int(name) % 4 == 0): self.month.append(month(29, "Febrero", "02")) else: self.month.append(month(28, "Febrero", "02")) self.month.append(month(31, "Marzo", "03")) self.month.append(month(30, "Abril", "04")) self.month.append(month(31, "Mayo", "05")) self.month.append(month(30, "Junio", "06")) self.month.append(month(31, "Julio", "07")) self.month.append(month(31, "Agosto", "08")) self.month.append(month(30, "Septiembre", "09")) self.month.append(month(31, "Octubre", "10")) self.month.append(month(30, "Noviembre", "11")) self.month.append(month(31, "Diciembre", "12")) self.name = name ############################################################################## # Funciones ############################################################################## # Bloque principal de instrucciones hora = time.strftime("%H:%M:%S") fecha = time.strftime("%a/%d/%m/%Y") x = hora.split(":") h = x[0] m = x[1] s = x[2] y = fecha.split("/") diana = y[0] dianu = y[1] me = y[2] añ = y[3] #print(x) #print(y) año = year(y[3]) #print(len(año.month)) #print(año.name) # for i in año.month: # # print(i.name, i.num) # for j in i.days: # print(j.num, end = " ") # print() for i in año.month: if i.num == me: for j in i.days: if j.num == int(dianu): j.name = diana dias = [] for i in range(0, 6): dias.append("Mon") dias.append("Tue") dias.append("Wed") dias.append("Thu") dias.append("Fri") dias.append("Sat") dias.append("Sun") ############################################################################### while dias[int(dianu) - 1] != diana: del dias[0] while len(dias) > len(año.month[3].days): del dias[-1] #print(len(dias)) for i in range(0, len(año.month[3].days)): año.month[3].days[i].name = dias[i] # print(año.month[3].name) # print() #for o in año.month[3].days: # print(o.name, o.num) #for j in año.month: #print(i.name, i.num) for k in j.days: print(k.name, end = " ") print()
b5174e0b5e5c716b8d1ea136f627a6f67512a0aa
welchbj/almanac
/almanac/types/comparisons.py
1,129
3.625
4
from typing import Any, Type from typing_inspect import is_union_type, get_args def is_matching_type( _type: Type, annotation: Any ) -> bool: """Return whether a specified type matches an annotation. This function does a bit more than a simple comparison, and performs the following extra checks: - If the ``annotation`` is a union, then the union is unwrapped and each of its types is compared against ``_type``. - If the specified ``_type`` is generic, it will verify that all of its parameters match those of a matching annotation. """ # Look for an easy win. if _type == annotation: return True # If annotation is Union, we unwrap it to check against each of the possible inner # types. if is_union_type(annotation): if any(_type == tt for tt in get_args(annotation, evaluate=True)): return True # If both the global type and the argument annotation can be reduced to # the same base type, and have equivalent argument tuples, we can # assume that they are equivalent. # TODO return False
fabe2b9606c05bf757667397660e03440bd548a1
jasmineagrawal/pythonprogram
/distance_between_2points.py
292
3.890625
4
x=(int(input(" entre the x coordinate of first point: "))) y=(int(input(" entre the y coordinate of first point: "))) p=(int(input(" entre the x coordinate of second point: "))) q=(int(input(" entre the y coordinate of second point: "))) d=((p-x)**2+(q-y)**2)**0.5 print("distance=" +str(d))
3e9a9d314525b8206363c470438e4f81088c6ea3
VihaanVerma89/pythonCodes
/codingBat/string-1/left2.py
173
3.8125
4
def left2(string): if len(string) < 2 : return string else: return string[2:]+string[:2] print left2('Hello') print left2('java') print left2('hi')
5f6f434b431bef2be907450dd288ad17542626f9
nilbsongalindo/APA
/Heap Sort/heap_sort.py
1,000
3.828125
4
def root(i): return int (i - 1) / 2 def left_child(i): return 2 * i + 1 def right_child(i): return 2 * i + 2 def max_heapfy(arr, n, i): #heapfy biggest = i left = left_child(i) #left_node right = right_child(i) #right_node #Checking if right node is greater than root if right < n and arr[biggest] < arr[right]: biggest = right #Checking if left node is greater than root if left < n and arr[biggest] < arr[left]: biggest = left #Checking if 'i' is the largest. T if biggest != i: arr[i], arr[biggest] = arr[biggest], arr[i] max_heapfy(arr, n, biggest) def build_max_heap(arr): n = len(arr) for i in range(n, -1, -1): max_heapfy(arr, n, i) def heap_Sort(arr): n = len(arr) build_max_heap(arr) #swap the first and the last node, then remove the last one for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] max_heapfy(arr, i, 0) def main(): arr = [2, 10, 8, 0, 4] heap_Sort(arr) print(arr) if __name__ == '__main__': main()
d9390d50fa9f06b09508f8a7527a6ce8be4cbe63
watsy0007/projecteuler
/p_7.py
512
3.796875
4
# https://zh.wikipedia.org/wiki/質數定理 from utils import is_prime def prime_by_index(number, index): prime_index = 0 for (idx, v) in enumerate(range(2, number)): if is_prime(v): prime_index += 1 print(v, prime_index) if index == prime_index: return v def run(): print(prime_by_index(10_000_000, 10_002)) # 100 001st if __name__ == '__main__': run() # 太慢了 # python p_7.py 0.31s user 0.02s system 97% cpu 0.338 total
c0aaafa3173f369d4675e0dde6084c1ec4d51488
mukoedo1993/Python_related
/python_official_tutorial/chap4_7/chap4_7_1.py
851
4.6875
5
""" The function can be called in several ways: 1: Similar to C++ """ i = 5 def f(arg=i): print(arg) i = 6 f() ''' Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the argument passed to it on subsequent calls: ''' def f1(a,L=[]): L.append(a) return L print(f1(1)) print(f1(2)) print(f1(3)) # If you don't want the default to be shared between subsequent calls, you can # write the function like this instead: def f2(a,L=None): L = [] L.append(a) return L print(f2(1)) print(f2(2)) print(f2(3)) """ log: (base) zcw@mukoedo1993:~/python_related_clone/Python_related/python_official_tutorial/chap4_7$ python chap4_7_1.py 5 [1] [1, 2] [1, 2, 3] [1] [2] [3] """
29620b218318d8374396353802a5f2b78c2b8358
driellevvieira/ProgISD20202
/Dayalla_Marques/A4/ProgramasAula4.py
3,378
3.953125
4
logicValue = int(input("Você está usando máscara?\n")) if(logicValue): print("Parabéns!\n") print("Fim do programa!!") ################################################################################### logicChocolate = int(input("Você gosta de chocolate?\n")) logicCafe = int(input("Você gosta de café?\n")) if(logicChocolate and not logicCafe): print("Você gosta de chocolate e não gosta de café\n") if(not logicChocolate and not logicCafe): print("Você não nao gosta de chocolate e não gosta de café\n") if(logicChocolate and logicCafe): print("Você gosta de chocolate e de café\n") if(not logicChocolate and logicCafe): print("Você não gosta de chocolate e nem de café\n") print("Fim de programa!!") ##################################################################################### strChocolate = input("Você gosta de chocolate?\n") strCafe = input("Você gosta de café?\n") if(strChocolate == "s" and strCafe == "n"): print("Você gosta de chocolate e não gosta de café\n") if(strChocolate == "n" and strCafe == "n"): print("Você não gosta de chocolate e nem de café\n") if(strChocolate == "s" and strCafe == "s"): print("Você gosta de chocolate e de café\n") if(strChocolate == "n" and strCafe == "s"): print("Você não gosta de chocolate e sim de café\n") print("Fim de programa!!") ###################################################################################### encostouBarra1 = int(input("O rato encostou na barra 1?\n")) encostouBarra2 = int(input("O rato encostou na barra 2?\n")) if ( encostouBarra1 and not encostouBarra2 ): print("Foram adicionados 10mg de comida") if (not encostouBarra1 and encostouBarra2): print("Foram adicionados 20mg de comida") if (not encostouBarra1 and not encostouBarra2): print("Nenhuma comida foi adicionada") if (encostouBarra1 and encostouBarra2): print("Foram adicionados 40mg de comida") print("Fim de programa!!") #################################################################################### encostouBARRA1 = int(input("O rato encostou na barra 1?\n")) encostouBARRA2 = int(input("O rato encostou na barra 2?\n")) if ( encostouBARRA1 and not encostouBARRA2 ): print("Recebeu uma gota de líquido") elif (not encostouBARRA1 and encostouBARRA2): print("Recebeu duas gotas de líquido") elif (not encostouBARRA1 and not encostouBARRA2): print("Não recebeu nada") elif (encostouBARRA1 and encostouBARRA2): print("Recebeu comida") else: print("Fim de programa!!") ############################################################## variavelLogica = int(input("Você é uma pessoa legal?\n")) if(variavelLogica): print("Que bom. Continue assim\n") else: print("Seja legal\n") print("Fim de programa!!") numeroMenordigite = int(input('Digite um numero menor que 60: ')) if numeroMenordigite < 60: print ("Isso aí. Digitou certo\n") else: print ("Digitou errado") print("Fim de programa!!") ######################################################################################## escolhaAnimais = int(input("Digite '1' para rato e digite '2' para coelho: ")) if(escolhaAnimais==1): print("Você escolheu rato!") elif(escolhaAnimais==2): print("Você escolheu coelho!") else: print("Escolha um dos animaizinhos") print("Fim de programa!!")
7d12e596344bb2370d3e429eda917038a1538a66
gnool/datastructure-algorithms
/graph/maxflow/maxflow.py
5,070
4.25
4
# python3 import queue class Edge: """Edge of graph Attributes: start directed edge from start to end end capacity capacity flow flow """ def __init__(self, start, end, capacity): self.start = start self.end = end self.capacity = capacity self.flow = 0 class FlowGraph: """Max-flow graph Attributes: edges List of Edge instances Note: edges[u] and edges[v], where u is even, are a pair of entries to represent an edge and its reverse edge. The reverse edge only exists in the residual graph. graph Adjacency list representation fast_find Dictionary to find (u, v) in graph[u] """ def __init__(self, n): self.edges = [] self.graph = [[] for _ in range(n)] self.fast_find = {} def add_edge(self, from_, to, capacity): """Add a new edge to graph""" forward_edge = Edge(from_, to, capacity) backward_edge = Edge(to, from_, 0) self.fast_find[(from_,to)] = len(self.graph[from_]) self.graph[from_].append(len(self.edges)) self.edges.append(forward_edge) self.fast_find[(to,from_)] = len(self.graph[to]) self.graph[to].append(len(self.edges)) self.edges.append(backward_edge) def size(self): """Number of nodes in graph""" return len(self.graph) def add_flow(self, id_, flow): """Update flow of edge""" # id_ and id_ ^ 1 form a pair of forward and reverse edge self.edges[id_].flow += flow self.edges[id_ ^ 1].flow -= flow def max_flow(self, from_, to): """Implementation of Edmonds-Karp algorithm""" flow = 0 while True: previous = [None]*self.size() previous[from_] = from_ # Use breadth-first search q = queue.Queue() q.put(from_) while not q.empty(): # No need for further search if sink is reached if previous[to] != None: break cur = q.get() ids = self.graph[cur] for i in ids: edge = self.edges[i] # Forward edge if i % 2 == 0: if previous[edge.end] == None and edge.capacity > edge.flow: previous[edge.end] = cur q.put(edge.end) # Reverse edge (in residual graph) else: if previous[edge.end] == None and edge.flow != 0: previous[edge.end] = cur q.put(edge.end) # Update flow if there is an augmenting path in residual graph if previous[to] != None: # Find the minimum capacity along this path cur = to min_ = float('inf') while previous[cur] != cur: id_ = self.graph[previous[cur]][self.fast_find[(previous[cur], cur)]] edge = self.edges[id_] # Forward edge if id_ % 2 == 0: min_ = min(min_, edge.capacity - edge.flow) # Reverse edge (in residual graph) else: min_ = min(min_, -edge.flow) cur = previous[cur] # Update all edges along this path cur = to while previous[cur] != cur: id_ = self.graph[previous[cur]][self.fast_find[(previous[cur], cur)]] self.add_flow(id_, min_) cur = previous[cur] flow += min_ # Otherwise, return the maximum flow else: return flow def read_data(): """Get user input Format: Line 0: n m Line 1: s1 t1 c1 Line 2: s2 t2 c2 ... Line m: sm tm cm n: Number of nodes m: Number of edges s, t: Edge from node index s to node index t c: Edge capacity 1 <= s,t <= n (1-based indices) Note: source and sink indices must be 1 and n respectively """ vertex_count, edge_count = map(int, input().split()) graph = FlowGraph(vertex_count) edge_dict = {} # Preprocess the input (sum capacities from all u->v edges) for _ in range(edge_count): u, v, capacity = map(int, input().split()) if u == v: continue if v == 1: continue if (u, v) in edge_dict: edge_dict[(u, v)] += capacity else: edge_dict[(u, v)] = capacity # Add all edges to graph for (u, v), capacity in edge_dict.items(): graph.add_edge(u - 1, v - 1, capacity) return graph if __name__ == '__main__': graph = read_data() print(graph.max_flow(0, graph.size() - 1))
5757e7a9f4f46bc57ff9a93e4a5ab93db38f27ba
vaibhavumar/sudokuSolverOpenCV
/sudoku2.py
2,698
3.515625
4
from random import choice import numpy as np def is_eligible(sudoku, row_index, col_index, num): if num in sudoku[row_index,:] or num in sudoku[:,col_index]: return False if within_box(sudoku, row_index, col_index, num): return False return True def within_box(sudoku, row_index, col_index, num): switcher = {0:2, 1:1, 2:0} last_row_of_box = row_index + switcher.get(row_index % 3) last_col_of_box = col_index + switcher.get(col_index % 3) row_index -= row_index % 3 col_index -= col_index % 3 #actual checking if num in sudoku[row_index:last_row_of_box, col_index:last_col_of_box]: return True return False #======================================================================================================== def returnEmptyIndex(sudoku): for (row, col), value in np.ndenumerate(sudoku): if value == 0: return row, col return -1, -1 #======================================================================================================== def randomised_sudokuSolver(sudoku): row, col = returnEmptyIndex(sudoku) if row != -1: numbers = [i for i in range(1,10)] while len(numbers) > 0: num = numbers.pop(numbers.index(choice(numbers))) if is_eligible(sudoku, row, col, num): sudoku[row, col] = num _random = randomised_sudokuSolver(sudoku) if returnEmptyIndex(sudoku) == (-1, -1): #SUDOKU COMPLETE return True sudoku[row, col] = 0 else: return False def sudokuSolver(sudoku): row, col = returnEmptyIndex(sudoku) if row != -1: for num in range(1,10): if is_eligible(sudoku, row, col, num): sudoku[row, col] = num _random = sudokuSolver(sudoku) if returnEmptyIndex(sudoku) == (-1, -1): #SUDOKU COMPLETE return True sudoku[row, col] = 0 else: return False # #DRIVER # sudoku = np.array([ [7, 0, 0, 5, 0, 0, 0, 6, 8], # [0, 6, 2, 0, 0, 4, 0, 3, 0], # [3, 0, 0, 0, 6, 0, 2, 0, 0], # [0, 5, 0, 0, 0, 2, 7, 0, 9], # [1, 0, 9, 6, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 1, 0, 5, 0, 6], # [0, 0, 1, 0, 4, 0, 6, 7, 0], # [2, 8, 0, 1, 0, 7, 0, 0, 0], # [0, 0, 7, 0, 3, 0, 8, 0, 1]]) # randomised_sudokuSolver(sudoku) # print(sudoku)
9855f1c336267ece37f2858ce322811ab818997f
joselmjl19/pensamiento_computacional
/raiz_funciones.py
1,609
3.953125
4
def enumeracion(): objetivo = int(input('Escribe un entero: ')) respuesta = 0 while respuesta ** 2 < objetivo: respuesta += 1 if respuesta ** 2 == objetivo: print(f'La raiz cuadrada de {objetivo} es {respuesta}') else: print(f'{objetivo} no tiene una raiz cuadrada exacta') def binaria(): objetivo = int(input('Escribe un numero: ')) epsilon = 0.01 bajo = 0.0 alto = max(1.0 , objetivo) respuesta = (alto + bajo) / 2 while abs(respuesta**2 - objetivo) >= epsilon: if respuesta**2 < objetivo: bajo = respuesta else: alto = respuesta respuesta = (alto + bajo) / 2 print(f'La raiz cuadrada de {objetivo} es {respuesta}') def aproximacion(): objetivo = int(input('Escribe un numero: ')) epsilon = 0.01 paso = epsilon ** 2 respuesta = 0.0 while abs(respuesta **2 - objetivo) >=epsilon and respuesta <= objetivo: respuesta += paso if abs(respuesta **2 - objetivo) >= epsilon: print(f'No se encontro la raiz cuadrada {objetivo}') else: print(f'La raiz cuadrada de {objetivo} es {respuesta}') def menu(): print("""Elige una opcion para calcular la raiz cuadrada: 1 .- Enumeracion exahustiva 2 .- Aproximacion 3 .- Busqueda binaria """) def run(): opcion = int(input(menu())) if opcion == 1: enumeracion() elif opcion == 2: aproximacion() elif opcion == 3: binaria() else: print("Elige una opcion valida.") run() if __name__ == "__main__": run()
80898f9096ea030b2dfe1831f6aee90eba528d3e
CommanderCode/Daily-Problems
/Daily 364-dice roller.py
669
4
4
#I love playing D&D with my friends, and my favorite part is creating character sheets (my DM is notorious for # killing us all off by level 3 or so). One major part of making character sheets is rolling the character's stats. # Sadly, I have lost all my dice, so I'm asking for your help to make a dice roller for me to use! import random def dice(n,d): total = 0 for i in range(n): total += random.randint(1,d) return total roll = input("Type a dice roll in the form #d#, for example 3d6: ") split_roll = roll.split("d") number_of_dice =int(split_roll[0]) dice_type = int(split_roll[1]) result = dice(number_of_dice,dice_type) print (result)
1686261b21749f3a0de26e2317135029800b04e2
JeremyBakker/Efficiency
/test.py
2,682
3.546875
4
import unittest from learn import return_max_profit, binary_search, highest_product_of_three, \ is_unique, is_unique_without_addition, binary_gap, find_missing_element,\ integer_pairs, string_compression, check_permutation, isSubstring class TestProblemSolving(unittest.TestCase): def test_return_max_profit(self): self.assertRaises(IndexError, return_max_profit, []) self.assertEqual(return_max_profit([10, 7, 5, 8, 11, 9]), 6) self.assertEqual(return_max_profit([10, 11, 12, 13, 14, 15]), 5) self.assertEqual(return_max_profit([15, 14, 12, 6, 11, 25]), 19) self.assertEqual(return_max_profit([15, 14, 12, 6, 5, 4]), 0) def test_binary_search(self): self.assertTrue(binary_search(8, [1,2,8,45,1203819283])) self.assertFalse(binary_search(1, [2,3,5,7,89,120])) def test_highest_product_of_three(self): self.assertEqual(highest_product_of_three([1, 5, 20, -1]), 100) self.assertEqual(highest_product_of_three([-1, 1, -50, -2]), 100) self.assertRaises(IndexError, highest_product_of_three, [1,2]) def test_is_unique(self): self.assertRaises(ValueError, is_unique, '') self.assertEqual(is_unique("abcdefghijklmnop"), True) self.assertEqual(is_unique("aaabdflkjafna;lkj"), False) def test_is_unique_without_addition(self): self.assertEqual(is_unique("abcdefghijklmnop"), True) self.assertEqual(is_unique("aaabdflkjafna;lkj"), False) def test_binary_gap(self): self.assertEqual(binary_gap(1041), 5) self.assertEqual(binary_gap(20), 1) self.assertEqual(binary_gap(15), 0) def test_integer_pairs(self): self.assertEqual(integer_pairs([1,2,3,7,4,3,1,2]), 7) self.assertEqual(integer_pairs([2,2,3,3,7,7,8,4,3,3,5,6,4,5,6]), 8) def test_find_missing_element(self): self.assertEqual(find_missing_element([1,2,3,5]), 4) self.assertEqual(find_missing_element([1,2,3,4,5,6,7,8,9,11,12]), 10) def test_string_compression(self): self.assertEqual(string_compression('AABBBCAAAA'), 'A2B3C1A4') self.assertEqual(string_compression('abcdef'), 'abcdef') def test_check_permutation(self): self.assertEqual(check_permutation(['abba', 'baaa']), False) self.assertEqual(check_permutation(['abbacc', 'bccbaa']), True) def test_isSubstring(self): self.assertEqual(isSubstring("waterbottle", "erbottlewat"), True) self.assertEqual(isSubstring("dog", "cat"), False) self.assertEqual(isSubstring("dog", "god"), False) self.assertEqual(isSubstring("dog", "gdo"), True) if __name__ == '__main__': unittest.main()
a9a16c2f4034342795d105e3dfeff73ed19795cd
nnaeueun/Python_RaspberryPi
/0909/if/practice05.py
732
4.03125
4
#3개의 양수중 가장 큰 값 출력 num1 = int(input("1. 양의 정수 입력 : "))#값을 받아서 int형변환 num2 = int(input("2. 양의 정수 입력 : ")) num3 = int(input("3. 양의 정수 입력 : ")) if num1>0 and num2>0 and num3>0:#양수 조건 if num1>num2:#num1이 num2보다 클 때 if num1>=num3:#num1이 num3보다 크거나 같을때 print(num1)#num1출력 else:#num1이 num3보다 작을때 print(num3)#num3출력 elif num2>=num3:#num2가 num3보다 크거나 같을 때 print(num2)#num2출력 else:#num2가 num3보다 작을때 print(num3)#num3출력 else:#음수가 하나라도 있을때 print("양의 정수를 입력하세요.")
fdc11c48ff4bc889dca42c549fa98d697f027729
N07070/Projects
/Solutions/Python/social_network_suite.py
1,736
4.15625
4
#!/usr/bin/python3.4 # -*- coding: utf-8 -*- def days_limit(): jour = 1 jour_lim = int(input("Please input how many days you would like to cycle. >> ")) nbr_friends = 2 nbr_nvx_friends = 2 while jour <= jour_lim: nbr_friends = nbr_nvx_friends*2 nbr_nvx_friends = nbr_nvx_friends*2 jour += 1 print("On the "+str(jour)+" th day, John has "+str(nbr_friends)+" friends.") def friends_limit(): jour = 1 friends_lim = int(input("How many friends would you like John to have ? >> ")) nbr_friends = 2 nbr_nvx_friends = 2 while nbr_friends <= friends_lim: nbr_friends = nbr_nvx_friends*2 nbr_nvx_friends = nbr_nvx_friends*2 jour += 1 print("It would take "+str(jour)+" days for John to have "+str(friends_lim)+" friends.") def friends_10(): jour = 1 friends_lim = int(input("How many friends would you like John to have ? >> ")) nbr_friends = 2 nbr_nvx_friends = 2 while nbr_friends <= friends_lim: nbr_friends = nbr_nvx_friends*10 nbr_nvx_friends = nbr_nvx_friends*10 jour += 1 print("It would take "+str(jour)+" days for John to have "+str(friends_lim)+" friends.") def main(): user_choice = int(input("Would you to know : \n 1 - How many friend John will have in X days ? \n 2 - How many days will it take John to have X friends ? \n 3 -How many days will it take John to have X friends by gaining 10 friends per new friend ? \nPlease enter a number >> ")) if user_choice == 1: days_limit() elif user_choice == 2: friends_limit() elif user_choice == 3: friends_10() else: print("Okay then...") if __name__ == '__main__': main()
155894ab25a35da332c800af1590a2e38f65f658
dmytro-malyhin/University-Python
/HANGMAN.py
1,236
4.03125
4
print('You star to play') word = list(str(input('Please, input the word for second player - '))) massive_light = ['a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y'] Attempt = 5 letter = [] while True: for element in word: if element in massive_light: letter.append(element) elif element not in massive_light: letter.append('_') print(letter) break print() while Attempt > 0: word_vvod = str((input('Please input the letter in the word - '))) if word_vvod not in word: Attempt = Attempt - 1 print('This letter is not in the hidden word ') print('Your attempts: ', Attempt) if Attempt < 5: print('\n | ') if Attempt < 4: print(' O ') if Attempt < 3: print(' /|\ ') if Attempt < 2: print(' | ') if Attempt < 1: print(' / \ ') if Attempt == 0: print('Game over') elif word_vvod in word: letter.pop(int(word.index(word_vvod))) letter.insert(int(word.index(word_vvod)), word_vvod) print(letter) if letter == word: print('You win')
cb6f2f97ae7c5589ede4fa80f3fb2cd68cbd4965
mscaudill/Tutorials
/sql_zoo/3_SELECT_from_Nobel.py
3,345
3.578125
4
# -- Matt Caudill # nobel(yr, subject, winner) #1. Write a query for the nobel table that displays prizes in 1950. SELECT yr, subject, winner FROM nobel WHERE yr = 1950 #2. Who won the the 1962 Prize for literature SELECT winner FROM nobel WHERE yr = 1962 AND subject = 'Literature' #3. Find the year and subject of the Eistein's Nobel SELECT yr, subject FROM nobel WHERE winner = 'Albert Einstein' #4. Find the name of the Peace winners since the year 2000 inclusive SELECT winner FROM Nobel WHERE subject = 'Peace' AND yr >= 2000 #5. Find all cols of the literature prize winners for 1980 to 1989 inclusive SELECT yr, subject, winner FROM nobel WHERE subject = 'Literature' AND yr >= 1980 AND yr <= 1989 #6. Show all details of the following winners Roosevelt, Wilson, Carter SELECT * FROM nobel WHERE winner IN ('Theodore Roosevelt', 'Woodrow Wilson', 'Jimmy Carter') #7. Find the winners with the first name John SELECT winner FROM nobel WHERE winner LIKE 'John %' #8. Show the Physics winners for 1980 with the chemistry winners for 1984 SELECT * FROM nobel WHERE subject='Physics' AND yr = 1980 OR subject='Chemsitry' AND yr = 1984 #9. Show the winners for 1980 excluding Chemistry and Medicine SELECT * FROM nobel WHERE yr = 1980 AND subject NOT IN ('Chemsitry', 'Medicine') #10. How who won a medicine prize prior to 1910 togehter with Literature # prizes in 2004 and later SELECT * FROM nobel WHERE subject = 'MEDICINE' AND yr < 1910 OR subject='Literature' AND yr >= 2004 #11. Find All Details of the prize won by Peter Grünberg (compose + "u) SELECT * FROM nobel WHERE winner = 'Peter Grünberg' #12. Find all details for winner Eugene O'Neil (double quotes inside str) SELECT * FROM nobel WHERE winner = 'Eugene O''Neill' #13. List * for winners where winner starts with Sir. Show the most recent # first then by name order SELECT winner, yr, subject FROM nobel WHERE winner LIKE 'Sir %' ORDER BY yr DESC, winner #14. Show 1984 winneres and subject ordered by subject and winner name; but # list Chemistry and Physics last. SELECT winner, subject FROM nobel WHERE yr = 1984 ORDER BY subject IN ('Physics', 'Chemsitry'), subject, winner # Nobel Quiz # ############## #1. Find the winners names that begin with C and end with n SELECT winner FROM nobel WHERE winner LIKE 'C%' AND winner LIKE '%n' #2. How many chemistry awards were given between 1950 and 1960 SELECT COUNT(subject) FROM nobel WHERE subject = 'Chemistry' AND yr BETWEEN 1950 AND 1960 #3. Find the amount of years where no medicine awards were given SELECT COUNT(DISTINCT yr) FROM nobel WHERE yr NOT IN (SELECT DISTINCT yr FROM nobel WHERE subject = 'Medicine') #4. SELECT subject, winner FROM nobel WHERE winner LIKE 'Sir%' AND yr LIKE '196%' # This would give Table 3 #5. Show the year in which neither a Physics or Chemistry award was given SELECT yr FROM nobel WHERE yr NOT IN (SELECT yr FROM nobel WHERE subject IN ('Chemistry','Physics')) #6. Find years when medicine award was given but no peace or lit award was SELECT DISTINCT yr FROM nobel WHERE subject='Medicine' AND yr NOT IN (SELECT yr FROM nobel WHERE subject='Literature') AND yr NOT IN (SELECT yr FROM nobel WHERE subject='Peace') #7. Pick the table SELECT subject, COUNT(subject) FROM nobel WHERE yr='1960' GROUP BY subject # Gives table 4
b3b9b5dcaa4b4e0f715dcdb1298313aa6e425c6c
anuragseven/coding-problems
/online_practice_problems/Mathematical/Factorial.py
333
3.765625
4
# Given a positive integer, N. Find the factorial of N. class Solution: def factorial (self, N): if N==0: return 1 return N*self.factorial(N-1) class Solution2: def factorial (self, N): fact=1 for i in range(N,0,-1): fact=fact*i return fact
6878bb77a2c2ec31f86398ddd8d9795eb1f803c9
1Bitcoin/python-old
/TrashPython/подготовка/работа с массивами/create_kv_matrix_pascal_style.py
304
3.734375
4
''' создать за 2 цикл кв. матрицу (выше гл. диаг = *, ниже #, на диаг. @) ''' N = 5 a = [['@']*N for i in range(N)] for i in range(N): for j in range(N): if i != j: a[i][j] = '#' a[j][i] = '*' for row in a: print(row)
1bf196ff878b635583e7d4b5427b6f334d96fc09
minhntm/algorithm-in-python
/datastructures/list/challenge8_rearrange_positive_negative.py
982
4.21875
4
""" Problem Statement: Implement a function rearrange(lst) which rearranges the elements such that all the negative elements appear on the left and positive elements appear at the right of the list. Note that it is not necessary to maintain the order of the input list. Generally zero is NOT positive or negative, we will treat zero as a positive integer for this challenge! So, zero will be placed at the right. Output: - A list with negative elements at the left and positive elements at the right Sample Input: - [10,-1,20,4,5,-9,-6] Sample Output: - [-1,-9,-6,10,20,4,5] """ def rearrange(lst): # most_left_pos = 0 # for i in range(len(lst)): # if lst[i] < 0: # if i != most_left_pos: # lst[i] = lst[most_left_pos] # most_left_pos += 1 # return lst return [x for x in lst if x < 0] + [x for x in lst if x >= 0] if __name__ == '__main__': print(rearrange([10, -1, 20, 4, 5, -9, -6]))
a5aa6bc088eccd8b3d7685e314c89253ecaf4f5e
bigfatmouse9208/Algo_Study_Group
/Week8_Bit_Manipulation/leetcode_477.py
610
3.546875
4
""" Runtime: 476 ms, faster than 50.63% of Python3 online submissions for Total Hamming Distance. Memory Usage: 15.4 MB, less than 7.23% of Python3 online submissions for Total Hamming Distance. """ class Solution: def totalHammingDistance(self, nums: List[int]) -> int: if not nums: return 0 bin_nums = ["{:032b}".format(n) for n in nums] N , n = len(nums) , len(bin_nums[0]) res = 0 for i in range(n): ones = 0 for bn in bin_nums: ones += (bn[i] == '1') res += (N - ones) * ones return res
a2726a4c0ceb34fa05aaab3d05df2603445f543b
Simonthesun/comp
/asst/1/asst1.py
1,709
3.625
4
def swapchars(string): s = string.lower() most = 0 least = 0 most_letter = "" least_letter = "" new_string = "" letter_count = {} for letter in s: if letter in letter_count: letter_count[letter] = letter_count[letter] + 1 else: letter_count[letter] = 1 for key in letter_count: count = letter_count[key] if count > most: most = count most_letter = key least = most for key in letter_count: count = letter_count[key] if count <= least: least = count least_letter = key for letter in string: if letter == most_letter: new_string += least_letter elif letter.lower() == most_letter: new_string += least_letter.upper() elif letter == least_letter: new_string += most_letter elif letter.lower() == least_letter: new_string += most_letter.upper() else: new_string += letter return new_string def swapcat(n, *args): strings = [] ordered = [] catted = "" for string in args: strings.append(string) for count in args: length = 0 curr = "" for string in strings: if len(string) > length: length = len(string) curr = string ordered.append(curr) strings.remove(curr) i = 0 while i < n: catted += ordered[i] i += 1 return catted with open('states.txt') as f: lines = f.read().splitlines() abbrev = {} for state in lines: name = state.split(',')[0] abbreviation = state.split(',')[1] abbrev[abbreviation] = name def bluesclues(abbreviation): if abbreviation in abbrev: return abbrev[abbreviation] else: raise NameError('Not a valid state abbreviation') def bluesbooze(name): for abbreviation in abbrev: if abbrev[abbreviation] == name: return abbreviation raise NameError('Not a valid state name')
76d937eb21ed906c9d725cc3090e2f27c91a6cca
duncanp11111/Year_End2017
/OddsOn.py
626
3.859375
4
from random import randrange import time print ("Welcome to Odds On!") odds_on = input("what will you do if you lose?: ") odds = int(input("What are your odds?: ")) print ("Your odds are 1 to", odds) print ("Please select a number between 1 and", odds, "when the counter hits zero.") print ("Ready?") print ("3") time.sleep(0.5) print ("2") time.sleep(0.5) print ("1") time.sleep(0.5) usr_input = int(input("What is your number?:" )) bot = randrange(1, (odds+1)) print ("Bot's number is", bot) print ("Your number is", usr_input) if bot == usr_input: print ("Now you have to", odds_on, ". GLHF!") else: print ("Lucky!")
52e16e05b3945aad496426687a3fea6eb2c66f02
patrickmn/euler-python
/020.py
137
3.703125
4
#!/usr/bin/env python3 n = 100 result = 100 while n > 0: result = result * n n = n - 1 print(sum(int(x) for x in str(result)))
bb8bd8849e97f50fbc528d2ddc6cbb844ec821fc
lucasggln/Info
/Exercices/5/Compteur d'événement.py
141
3.515625
4
#Wiaux Bastien def count(events, i, j): count = 0 for a,b in events: if a == i and b == j: count += 1 return count
72ea79ae2e1984b7eb809ae8e0d13930b9543a0a
ChristineKutka/Python-Files
/obamafy (2).py
1,457
3.875
4
# You have a pic # You want to Obamafy it # You want to take pixels in the image and change their colors # [(0,1,74), (234, 123, 23)] # def randomfunction(obamas_address, cherish_middle_name, biggest_number_ever): # print(obamas_address) # randomfunction(??????) def obamafy (pixel_list): # if our pixel_list looks like this: [(0,1,74), (234, 123, 23)] # Do this (aka loop) for every pixel in the image (represented as a pixel list): for item in pixel_list: # item is going to look like this: (0,1,74) first # Calculate the intensity values # - add the red, green, and blue values intensity = item[0] + item[1] + item[2] # tuple = (1,2,3) # list = [1,2,3] # tuple[0] # give me 1 # Change the values so the pixel color changes # - Based on the rules below, change that pixel color from the original color to either dark blue, red, light blue, or yellow # If the intensity < 182, then it's dark blue # If the intensity is between 182 and 364, then it's red # If the intensity is between 364 and 546, then it's light blue # all other intensity values, it is yellow if intensity is < 182 then add dark blue to the new list else if intensity is >= 182 and < 364 then add red to the new list else if intensity is >= 364 and < 546 then add light blue to the new list else add yellow to the new list # return the pixel list i was given that i edited to contain the RGB values of the obamafied picture. return new list # [dark blue, dark blue]
19655962651e5ae53b73b0b1c685586b37c93dbd
ErikLevander/erle
/jenbe.py
818
3.5
4
import math # coding=utf-8 # print: investerat belopp print('Hur mycket vill du investera?') investment = float(input()) # print(investment) # input för att ta årsavkastning som input från user print('Hur många procent är årsavkastning?') annualReturn = int(input())/100 print(annualReturn) # print: antal år print('Hur många år vill du spara?') years = int(input()) # print(years) # investerat belopp x (1+årsavksatning)^antal år finalReturn = investment * (1 + annualReturn) ** years theFinalReturn = math.trunc(finalReturn) monthlyReturn = theFinalReturn / 12 theFinalMonthlyReturn = math.trunc(monthlyReturn / 12) print('Din besparing kommer efter ' + str(years) + ' år vara ' + str(theFinalReturn) + 'kr' + ' Såhär mycket får du varje månad på dina besparing ' + str(theFinalMonthlyReturn))
4fa6a5ee874c77ad1abf04db22e4732cb7daed2d
andyyang777/PY_LC
/448_FindAllNumbers.py
859
3.703125
4
# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elemen # ts appear twice and others appear once. # # Find all the elements of [1, n] inclusive that do not appear in this array. # # Could you do it without extra space and in O(n) runtime? You may assume the r # eturned list does not count as extra space. # # Example: # # Input: # [4,3,2,7,8,2,3,1] # # Output: # [5,6] # # Related Topics Array # 👍 3172 👎 260 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: l = len(nums) + 1 res = [] nums = set(nums) for x in range(1, l): if x not in nums: res.append(x) return res # leetcode submit region end(Prohibit modification and deletion)
6406fdcc7ed8b811dc8234e472a0c757885d58cc
hualazimi0425/squirrel
/88. Merge Sorted Array.py
1,005
4.46875
4
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # # The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has # enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Example: # # Input: # nums1 = [1,2,3,0,0,0], m = 3 # nums2 = [2,5,6], n = 3 # # Output: [1,2,2,3,5,6] def MergeSortedArray(nums1, m, nums2, n): p1 = m - 1 p2 = n - 1 # set pointer for nums1 p = m + n - 1 # while there are still elements to compare while p1 >= 0 and p2 >= 0: if nums1[p1] < nums2[p2]: nums1[p] = nums2[p2] p2 -= 1 else: nums1[p] = nums1[p1] p1 -= 1 p -= 1 # add missing elements from nums2 nums1[:p2 + 1] = nums2[:p2 + 1] # add the elements which are still remaining in nums2 return nums1 print(MergeSortedArray([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3))
99424a4ba768939ff8a4877e9e05f5f0aae53428
CeciliaMartins/-LingProg
/9-conteudoEtamanhoString.py
896
4.09375
4
##9 Faça um programa que leia 2 strings e informe o conteúdo delas ##seguido do seu comprimento. Informe também se as duas strings ##possuem o mesmo comprimento e são iguais ou diferentes no ##conteúdo. ##Exemplo: ##String 1: Brasil Hexa 2018 ##String 2: Brasil! Hexa 2018! ##Tamanho de "Brasil Hexa 2018": 16 caracteres ##Tamanho de "Brasil! Hexa 2018!": 18 caracteres ##As duas strings são de tamanhos diferentes. ##As duas strings possuem conteúdo diferente. string1 = "Brasil Hexa 2018" string2 = "Brasil! Hexa 2018!" tamanhoString1 = len(string1) tamanhoString2 = len(string2) if(tamanhoString1 != tamanhoString2): print("As duas strings são de tamanhos diferentes.") else: print("As duas strings são do mesmo tamanho.") if(string1 != string2): print("As duas strings possuem conteúdo diferente.") else: print("As duas strings possuem o mesmo conteúdo.")
607fd2ee99eaf29df7a77e964eb0848f4cd4b3c9
8Raouf24/bbc_english_test
/crashfile.py
883
3.8125
4
""" def test(corpus): print("\nWelcome to your english level test!\n Please before starting, identify yourself\n#########\n") # print("ID :") # ID = input() # print("Password:") # password = input() print(f"\n you are ready to start your test. Let's dive in !\n ") cpt_tr = 0 cpt = 0 for i in corpus.keys(): print(f"######## {i} ########\n") for j in corpus[i]: if i == "Compréhension Orale": pass # playsound(list(j.items())[0][0]) else: print(list(j.items())[0][0]) print(list(j.items())[0][1][0]) for k in list(j.items())[0][1][1]: print(k[0]) answer = input() cpt_tr += list(j.items())[0][1][1][int(answer)-1][1] cpt += 1 print(f"Votre score est de {cpt_tr}/{cpt}") """
7ab7b5f7b685e0292bd3dc6d44716e41122140eb
ashley0121/uband-python-s1
/homeworks/B17333/B17333-Aro-交作业/week3/day17-homework.py
528
3.515625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: xxx import turtle def main(): #设置一个画面 windows = turtle.Screen() #设置背景 windows.bgcolor('blue') #生成一个黄色乌龟 bran = turtle.Turtle() bran.shape('turtle') bran.color('yellow') turtle.reset() turtle.shape("circle") turtle.shapesize(5,2) turtle.settiltangle(45) turtle.fd(50) turtle.settiltangle(-45) turtle.fd(50) #开始你的表演 bran.speed(1) bran.circle(50, 360, 100) if __name__ == '__main__': main()
8eee8bad56bf54005002bfbb9b9ee5e4bffd1c1d
omnivaliant/High-School-Coding-Projects
/ICS3U1/Assignment #7 OOP 2/4-5-6 Class.py
17,858
4.375
4
#Author: Mohit Patel #Date: Nov. 27, 2014. #Purpose: To create a program that will roll and display 3 dice. #------------------------------------------------------------------------# import random from tkinter import* root = Tk() root.title("4-5-6 Dice Game") root.config(width=500,height=438,bg="sky blue") menubar = Menu(root) root.config(menu=menubar) Prompt = StringVar() Prompt.set(value = "Welcome to 4-5-6! Please enter a simulation mode, or a manual game!") Size = IntVar() Size.set(value = 50) #Global variables used to keep track of the score used in manual playthroughs. global wins global loses global points global nothings wins = 0 loses = 0 points = 0 nothings = 0 # Dice class # Fields: # value: A random integer between 1-6, representing the current face of the die. # size: An integer between 30-100. representing the relative size of the die on the GUI. # radius: A number used in the printing of the die, representing the radius of the dots in order for the die to look proportionate at all sizes. # gap: A number used in the printing of the die, representing the spaces around the dots in order for the die to look proportionate at all sizes. # Methods: # __str__: Allows the die to be printed by it's value. # getValue: Allows the manual entry of the die's value. # setValue: Sets the value of the die, according to an inputted value, and ensures validity. # setSize: Proportionally adjusts the size of the die, according to a size parameter, to it's size, radius, and gap. # roll: Sets the current die's value to a random integer between 1 and 6. # draw: Allows the current die to be drawn onto the board. class Dice: def __init__(self,size=100): # Constructor # Parameters: Size of the die. self.value = random.randint(1,6) self.size = size self.radius = size / 5 self.gap = self.radius / 2 def __str__(self): # __str__ # Purpose: Returns the string version of the current die value. # Parameters: None. return str(self.value) def getValue(self): # getValue # Purpose: Allows for manual input for the current die. # Parameters: None. self.value = getPositiveInteger(1,6) def setValue(self,inputValue=1): # setValue # Purpose: Sets the value of the die according to the getValue input, and ensures validity. # Parameters: The input value. if not(inputValue.isdigit()): inputValue = 1 elif int(inputValue) < 1 or int(inputValue > 6): inputValue = 1 self.value = inputValue def setSize(self,inputSize=50): # setSize # Purpose: Sets the size of the die according to the input, and adjusts radius and gaps according to the size. # Parameters: The size of the die. self.size = inputSize self.radius = inputSize / 5 self.gap = self.radius / 2 def roll(self): # roll # Purpose: Sets the value of the die randomly between 1 and 6. # Parameters: None. self.value = random.randint(1,6) def draw(self,canvas,x,y): # draw # Purpose: Sets the value of the die according to the getValue input. # Parameters: None. canvas.create_rectangle(x,y,x+self.size,y+self.size,fill="white",outline="black") if self.value % 2 == 1: canvas.create_oval(x+(2*self.gap)+(self.radius),y+(2*self.gap)+(self.radius),x+(2*self.gap)+(2*self.radius),y+(2*self.gap)+(2*self.radius),fill="black") if self.value > 1: canvas.create_oval(x+self.gap,y+self.gap,x+self.gap+self.radius,y+self.gap+self.radius,fill="black") canvas.create_oval(x+(3*self.gap)+(2*self.radius),y+(3*self.gap)+(2*self.radius),x+(3*self.gap)+(3*self.radius),y+(3*self.gap)+(3*self.radius),fill="black") if self.value > 3: canvas.create_oval(x+self.gap,y+(3*self.gap)+(2*self.radius),x+self.gap+self.radius,y+(3*self.gap)+(3*self.radius),fill="black") canvas.create_oval(x+(3*self.gap)+(2*self.radius),y+self.gap,x+(3*self.gap)+(3*self.radius),y+self.gap+self.radius,fill="black") if self.value == 6: canvas.create_oval(x+self.gap,y+(2*self.gap)+self.radius,x+self.gap+self.radius,y+(2*self.gap)+(2*self.radius),fill="black") canvas.create_oval(x+(3*self.gap)+(2*self.radius),y+(2*self.gap)+self.radius,x+(3*self.gap)+(3*self.radius),y+(2*self.gap)+(2*self.radius),fill="black") # Hand class # Fields: # firstDie: A Dice object representing the first die of the object. # secondDie: A Dice object representing the second die of the object. # thirdDie: A Dice object representing the third die of the object. # size: The size of each die in the hand; the entire hand is 3x the size for length, and 1x the size for width. # Methods: # __str__: Allows the hand to be printed out by its die's values, in the form 1-2-3. # getValue: Obtains the values for each of the individual die. # setValue: Sets the values for each of the individual die. # setSize: Proportionally adjusts the size of each of it's die, according to a size parameter, to it's size, radius, and gap. # sort: Arranges the die so it's values are in increasing order, from 1 to 6. # roll: Sets the current die's value to a random integer between 1 and 6. # draw: Allows all three dies to be drawn on the board, consecutively. # isWinner: Determines if the current hand wins; arranged in 4-5-6, 3-of-a-kind, or a pair and a 6. # isLoser: Determines if the current hand loses; arranged in 1-2-3, or a pair and a 1. # calcPoint: Returns the point value of the current hand; a pair and a number between 2-5 will give points between 2-5, according to the third die; 0 points if otherwise. # display: Prints a table according to if the hand has won, lost, earned points, or nothings. class Hand: def __init__(self,size=50): # Constructor # Parameters: Size of each die. self.firstDie = Dice() self.secondDie = Dice() self.thirdDie = Dice() self.size = size # __str__ # Purpose: Returns the string version of the current hand, in the form 4-5-6. # Parameters: None. def __str__(self): return str(self.firstDie) + "-" + str(self.secondDie) + "-" + str(self.thirdDie) # getValues # Purpose: Obtains the values of each die of the hand, through the console. # Parameters: None. def getValues(self): print("You will now enter the value for your first die.") self.firstDie.getValue() print("You will now enter the value for your second die.") self.secondDie.getValue() print("You will now enter the value for your third die.") self.thirdDie.getValue() # setValues # Purpose: Sets the values of each individual die according to inputted values. # Parameters: Manual values for firstDie, secondDie, and thirdDie. def setValues(self,firstDie,secondDie,thirdDie): self.firstDie.setValue(firstDie) self.secondDie.setValue(secondDie) self.thirdDie.setValue(thirdDie) # setSize # Purpose: Sets the size of each individual die, according to an inputted value. # Parameters: The size, in the range 30-100. def setSize(self,size=50): if size < 30 or size > 100: size = 50 self.firstDie.setSize(size) self.secondDie.setSize(size) self.thirdDie.setSize(size) # sort # Purpose: Arranges the value of each die in increasing order, from 1-6. # Parameters: None. def sort(self): first = self.firstDie.value second = self.secondDie.value third = self.thirdDie.value if min(first,second,third) == first: if min(second,third) == third: self.secondDie.value = third self.thirdDie.value = second elif min(first,second,third) == second: self.firstDie.value = second if min(first,third) == first: self.secondDie.value = first self.thirdDie.value = third else: self.secondDie.value = third self.thirdDie.value = first else: self.firstDie.value = third if min(first,second) == first: self.secondDie.value = first self.thirdDie.value = second else: self.secondDie.value = second self.thirdDie.value=first # roll # Purpose: Randomizes the value of each die, in an integer of 1-6. # Parameters: None. def roll(self): self.firstDie.roll() self.secondDie.roll() self.thirdDie.roll() # draw # Purpose: Draws each of the three die consecutively on a given canvas and x-y coordinates. # Parameters: Canvas, x-coordinate, and y-coordinate. def draw(self,canvas,x,y): self.firstDie.draw(canvas,x,y) self.secondDie.draw(canvas,x+self.firstDie.size,y) self.thirdDie.draw(canvas,x+2*(self.firstDie.size),y) # isWinner # Purpose: Determines if the current hand can win, which can only occur through a 4-5-6, 3-of-a-kind, or a pair and a 6. # Parameters: None. def isWinner(self): winner = False if self.firstDie.value == 4 and self.secondDie.value == 5 and self.thirdDie.value == 6: winner = True elif self.firstDie.value == self.secondDie.value and self.secondDie.value == self.thirdDie.value: winner = True elif self.firstDie.value == self.secondDie.value and self.thirdDie.value == 6: winner = True return winner # isLoser # Purpose: Determines if the current hand can lose, which can only occur through a 1-2-3, or a pair and a 1. # Parameters: None. def isLoser(self): loser = False if self.firstDie.value == 1 and self.secondDie.value == 2 and self.thirdDie.value == 3: loser = True elif self.firstDie.value == 1 and self.secondDie.value == self.thirdDie.value: loser = True return loser # calcPoint # Purpose: Determines if the current hand can earn points; if the hand is a pair and a number between 2-5, the points are 2-5; or else, 0 points. # Parameters: None. def calcPoint(self): point = 0 if self.firstDie.value == self.secondDie.value and self.thirdDie.value > 1 and self.thirdDie.value < 6: point = self.thirdDie.value return point # display # Purpose: Prints a table according to various values. # Parameters: Canvas, amount of wins, amount of loses, amount of points, amount of nothings, top left x coordinate, and top left y coordinate. def display(self,canvas,wins,loses,points,nothings,x=400,y=0): canvas.create_text(x,y,text="Wins: "+ str(wins),font=("Arial","12","bold")) canvas.create_text(x,y+50,text="Loses: " + str(loses),font=("Arial","12","bold")) canvas.create_text(x,y+100,text="Points: " + str(points),font=("Arial","12","bold")) canvas.create_text(x,y+150,text="Nothings: " + str(nothings),font=("Arial","12","bold")) #--------------------------------------------------------------------------# #Author: Mohit Patel #Date: September 29, 2014 #Purpose: To return a valid positive integer in the given range. #Parameters: The smallest and largest number outside the range of integers allowed. #Return Value: A positive integer within the given range. def getPositiveInteger (low = 0, high = 100): blnInRange = False strNumber = input("Please enter a positive number in the range "+str(low)+" to "+str(high)+ ": ") while blnInRange == False or strNumber.isdigit() == False: if strNumber.isdigit() == False: print("Your number is not a valid integer.") strNumber = input("Please re-enter an appropriate integer in the range "+str(low)+" to "+str(high)+ ": ") elif int(strNumber) < low or int(strNumber) > high: print("Your number is outside of the range " + str(low) + " to " + str(high)+".") blnInRange = False strNumber = input("Please re-enter an appropriate integer in the range "+str(low)+" to "+str(high)+ ": ") else: blnInRange = True number = int(strNumber) return number #--------------------------------------------------------------------------# #Author: Mohit Patel #Date: December 10, 2014 #Purpose: Allows the playing of the game manually; one hand at a time. #Parameters: The canvas to be drawn on, the size of the dies in the hand, the x and y coordinates inside the canvas of the die, # and the x and y coordinates in the canvas for the table. #Return Value: The results of one roll of a new hand. def manual(canvas,size,xDraw,yDraw,xTable,yTable): global wins global loses global points global nothings canvas.delete("all") myHand = Hand() myHand.sort() myHand.setSize(int(scaleSize.get())) myHand.draw(canvas,xDraw,yDraw) if myHand.isWinner(): wins = wins + 1 Prompt.set(value = "You win! :)") elif myHand.isLoser(): loses = loses + 1 Prompt.set(value = "You lose! :(") elif myHand.calcPoint() > 0: points = points + myHand.calcPoint() Prompt.set(value = "You earn: " + str(myHand.calcPoint()) + " points.") else: nothings = nothings + 1 Prompt.set(value = "You earn nothing!") myHand.display(canvas,wins,loses,points,nothings,xTable,yTable) #--------------------------------------------------------------------------# #Author: Mohit Patel #Date: December 10, 2014 #Purpose: Allows the simulation of the game of 10,000 hands. #Parameters: The canvas to be drawn on, and the x and y coordinates for the table inside the canvas. #Return Value: The results of the 10,000 simulated hand results. def simulation(canvas,xTable,yTable): #Resets the global variable values of the manual table results. canvas.delete("all") global wins global loses global points global nothings wins = 0 loses = 0 points = 0 nothings = 0 simWins = 0 simLoses = 0 simPoints = 0 simNothings = 0 myHand = Hand() myHand.setSize(int(scaleSize.get())) for count in range(1,10001): myHand.roll() myHand.sort() if myHand.isWinner(): simWins = simWins + 1 elif myHand.isLoser(): simLoses = simLoses + 1 elif myHand.calcPoint() > 0: simPoints = simPoints + myHand.calcPoint() else: simNothings = simNothings + 1 myHand.display(canvas,simWins,simLoses,simPoints,simNothings,xTable,yTable) Prompt.set(value = "Your simulation results are as follows: ") #--------------------------------------------------------------------------# #Author: Mohit Patel #Date: December 11, 2014 #Purpose: Gives helpful information about the game, through the console. #Parameters: The canvas. #Return Value: Helpful information, through the console. def aboutGame(canvas): helpGuide = "Welcome to the 4-5-6 dice game! Your goal is to try as win as many games as possible, by rolling a "+\ "hand containing 3 individial die, in order to win by either getting a 4-5-6, 3-of-a-kind, or a pair "+\ "and a 6. If you don't win, then there is a possibility that you can lose, which will only happen if "+\ "you get a 1-2-3 or a pair and a 1. If you have a pair but not a 1 or 6, you earn a certain amount of "+\ "points, dictated by your third die. Finally, if none of these options are available, you earn nothing! "+\ "Either play this game hand by hand, or simulate 10,000 trials to quickly see interesting data "+\ "trends. We hope you enjoy!" print(helpGuide) #############################GUI MAIN############################################################################################ # creates the menu with a file section, and a help section. filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="New Hand", command=lambda:manual(canvasManual,scaleSize.get(),xDraw=0,yDraw=0,xTable=400,yTable=40)) filemenu.add_command(label="Generate Tally", command=lambda:simulation(canvasManual,xTable=100,yTable=40)) filemenu.add_separator() filemenu.add_command(label="Exit",command=lambda:root.destroy()) menubar.add_cascade(label="File", menu=filemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", command=lambda:aboutGame(canvasManual)) menubar.add_cascade(label="Help", menu=helpmenu) #Rest of GUI objects canvasGame = Canvas(root, width = 800, height = 600,bg = "sky blue",highlightthickness=0) canvasGame.place(x=0,y=0) canvasGame.focus_set() canvasManual = Canvas(canvasGame,width=500,height=300,bg="sky blue",highlightthickness=0) canvasManual.place(x=0,y=85) lblPrompt = Label(canvasGame,textvariable=Prompt,width=30,height=4,font=("Arial","12","bold"),justify=LEFT,bg="sky blue",wraplength=300,anchor="nw") lblPrompt.place(x=0,y=0) scaleSize = Scale(canvasGame,from_=30,to=100,resolution = 1,orient=HORIZONTAL,bd=5,label="Dice size: ",font=("Arial","12","bold"),relief="groove",length=190) scaleSize.place(x=300,y=0) scaleSize.set(50) btnSimulation = Button(canvasGame,width=20,text="Simulation Mode",height=2,font=("Arial","12","bold"),command=lambda:simulation(canvasManual,xTable=100,yTable=40)) btnSimulation.place(x=0,y=385) btnManual = Button(canvasGame,width=20,text="Manual Roll",height=2,font=("Arial","12","bold"),command=lambda:manual(canvasManual,scaleSize.get(),xDraw=0,\ yDraw=0,xTable=400,yTable=40)) btnManual.place(x=290,y=385) mainloop()
b360ad9ff5bc8387434aff608b6f0c3390b9486a
pbarden/python-course
/Chapter 8/low_vals_out.py
539
3.75
4
def get_user_values(): list_len = int(input()) my_list = list() for n in range(0, list_len): my_list.append(int(input())) # print(my_list) my_max = int(input()) return my_list, my_max def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold): for n in user_values: if n <= upper_threshold: print(n) if __name__ == '__main__': user_values, upper_threshold = get_user_values() output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold)
453ffcdcfb0c005137a7f6c250c57b6b38311cde
shiraz19-meet/y2s18-python_review
/exercises/for_loops.py
116
3.546875
4
# Write your solution for 1.1 here! i=0 sum1=0 for i in range(101): sum1 = sum1 + i if i % 2 == 0: print(sum1)
fb6a7c62cd1cf33f9051570782873558f3c1f7ab
devLorran/Python
/ex0103.py
809
4.0625
4
'''Faça um programa que tenha uma função receba dois parametro opcionais: o nome de um jogador e quantos gols ele marcou O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente ''' def jgd(nome='<desconhecido>', gols=0): if nome == '<desconhecido>' and gols == 0: nome = '<desconhecido>' gols = 0 if nome != '' and gols != 0: nome = nome gols = gols print(f'O jogador {nome} fez {gols} gols na partida!') jogador = str(input('Digite o nome do jogador: ')).strip() gol = int((input('Digite o número de gols: '))).strip() print(jgd(jogador,gol)) '''if gol.isnumeric(): gol = int(gol) else: g = 0 if jogador.strip() == '': jgd(gols=g) else: jgd(jogador, g)'''
c4704652cbf5e7f493df006bf4dfe844ad56406d
sylvioneto/python_games
/guessit.py
1,636
4.1875
4
# author: sylvio.pedroza@gmail.com import random def play(): print("*****************************") print("Welcome to the guessing game!") print("*****************************") secret_number = random.randrange(1, 101); no_tentatives = 0 print("What difficult level you want to play?") print("(1) Easy, (2) Medium, (3) Hard") game_level = input("Level: ") if game_level == "1": no_tentatives = 10 elif game_level == "2": no_tentatives = 6 elif game_level == "3": no_tentatives = 3 for round in range(1, no_tentatives + 1): print("Tentatives {} of {} ".format(round, no_tentatives)) user_input = input("Type a number between 1 and 100: ") if len(user_input) == 0: continue user_input = int(user_input) print("You typed ", user_input) if user_input < 1 or user_input > 100: print("Number out of the range ", user_input) continue # go to next iteration user_won = user_input == secret_number higher = user_input > secret_number lesser = user_input < secret_number if(user_won): total_points = (no_tentatives - round) * 10 print("You won! :) Total points: ", total_points) break # step out the loop else: if(higher): print("You guess was higher") elif(lesser): print("You guess was lesser") print("The secret number was {}".format(secret_number)) print("End of game") # in case of this class execution directly if __name__ == "__main__": play()
f84462b5fcb7de3e875640c5a5fd17669848d950
jbobo/leetcode
/find_critical_nodes_iterative.py
3,328
3.875
4
#!/usr/bin/env python3 class Graph: edges = dict() def __init__(self): """Initialize a graph object with no edges. '""" self.edges = dict() def add_edge(self, parent, child): """Add an edge between two nodes to the graph. """ self.edges.setdefault(parent, []).append(child) # if child not in self.edges: # self.edges[child] = [parent] # else: # self.edges[child].append(parent) def get_children(self, node): """Get the children of the given node in the graph. Returns [] if the given node does not exist in the graph. Return a sentinel value of [-1] if you want to detect cycles. """ return self.edges.get(node, []) class stack_entry: def __init__(self, node, parent_node=None, depth=0): self.node = node self.parent_node = parent_node self.depth = depth def get_critical_edges(graph, root_node): critical_edges = [] node_depth = {} # Low-Link stack = [] root_entry = stack_entry(root_node, None, 0) stack.append(root_entry) # POST-ORDER DFS traversal of the graph. while stack: # Peek the stack. current_entry = stack[-1] node_depth[current_entry.node] = current_entry.depth # Get all children. for child in graph.get_children(current_entry.node): # IF: the child node is unexplored, add it to the stack. if child not in node_depth: child_entry = stack_entry( node=child, parent_node=current_entry.node, depth=current_entry.depth + 1 ) stack.append(child_entry) # POST-ORDER. Only process the current node AFTER all of its children. if stack[-1] == current_entry: # init min_depth min_depth = current_entry.depth # Remove the entry from the stack. stack.pop() # Get all children. for child in graph.get_children(current_entry.node): # IF: the child is not the parent node AND we have explored the child node. if child != current_entry.parent_node and child in node_depth: # IF: the child belongs to another SCC, then this edge is critical. child_depth = node_depth[child] if child_depth > current_entry.depth: critical_edges.append((current_entry.node, child)) # ELSE: update the current node's low-link (depth). min_depth = min(current_entry.depth, child_depth) # Update the current node's low-link (depth). node_depth[current_entry.node] = min_depth return critical_edges if __name__ == "__main__": undiscovered_graph = Graph() undiscovered_graph.add_edge("A", "B") undiscovered_graph.add_edge("B", "C") undiscovered_graph.add_edge("C", "A") undiscovered_graph.add_edge("B", "D") undiscovered_graph.add_edge("D", "E") undiscovered_graph.add_edge("E", "F") undiscovered_graph.add_edge("F", "G") undiscovered_graph.add_edge("G", "H") undiscovered_graph.add_edge("H", "E") print(get_critical_edges(undiscovered_graph, "A"))
3563a09eaa6272824069fcdf17699ca96a4a2fde
HighLvRiver/PythonLearning
/Study/python_basic_lambda_exp.py
1,344
3.765625
4
# coding: utf-8 # In[1]: t = lambda x:x*2+1 # In[2]: t(6) # In[3]: t = lambda x: print("test") # In[4]: t = lambda x: print("test: {}".format(x+3)) # In[5]: seq = [1,2,3,4,5] # In[6]: map(lambda num: num*3,seq) # In[7]: list(map(lambda num: num*3,seq)) # In[8]: filter(lambda num: num%2 == 0, seq) # In[9]: list(filter(lambda num: num%2 == 0, seq)) # In[10]: s = 'hello my name is Jayden' # In[11]: s.lower() # In[12]: s.upper() # In[13]: s.split() # In[14]: tweet = 'Go Sports! #Sports' # In[15]: tweet.split() # In[16]: tweet.split('#') # In[17]: tweet.split('#')[1] # In[18]: d = {'k1':1, 'k2':2} # In[19]: d # In[20]: d.keys() # In[21]: d.items() # In[22]: d.values() # In[23]: lst = [1,2,3] # In[24]: lst.pop() # In[25]: lst # In[26]: lst = [1,2,3,4,5] # In[27]: item = lst.pop() # In[28]: lst # In[29]: item # In[30]: first = lst.pop(0) # In[31]: lst # In[32]: first # In[33]: lst.append('new') # In[34]: lst # In[35]: 'x' in [1,2,3] # In[36]: 'x' in ['x','y','z'] # In[37]: x = [(1,2),(3,4),(5,6)] # In[38]: x # In[39]: x[0] # In[40]: x[0][0] # In[41]: x[0][1] # In[42]: for item in x: print(item) # In[43]: for (a,b) in x: print(a) # In[45]: for a,b in x: print(a) print(b) # In[ ]:
57157e98bcf796474136142d17f243f634fa3c4c
RyanCliff/Lucky_Unicorn
/01.yesno_checker_v2.py
536
4.09375
4
# Make Function def yes_no(question): valid = False while not valid: answer = input(question).lower() if answer == "yes" or answer == "y": print("start game") return answer elif answer == "no" or answer == "n": print("display instructions") return answer else: print("Please pick yes or no.") # Main Routine show_instructions = yes_no("Have you played the Lucky Unicorn game before? ") print("You chose {}".format(show_instructions))
33cf3217e2cad91dc9b65d2fb9edba95f3aa8f49
xanderyzwich/Playground
/python/tools/display/staircase.py
1,089
4.34375
4
""" Staircase This is a staircase of size : # ## ### #### Its base and height are both equal to . It is drawn using # symbols and spaces. The last line is not preceded by any spaces. Write a program that prints a staircase of size . Function Description Complete the staircase function in the editor below. Print a staircase as described above. Staircase has the following parameter(s): int n: an integer """ def staircase(size): return [print(' '*(size-i) + '#'*i) for i in range(1, size+1)] def tree(size): [print(' '*(size-i) + '#'*(2*i+1)) for i in range(size)] if __name__ == '__main__': staircase(4) staircase(10) tree(10) print(False == False in [False]) """ OUTPUT: # ## ### #### # ## ### #### ##### ###### ####### ######## ######### ########## # ### ##### ####### ######### ########### ############# ############### ################# ################### """
fa932d0d62926cdd68c1631b82451fdb982d723d
MirsadHTX/GUI
/GUI6.py
1,634
3.609375
4
import tkinter minVindue = tkinter.Tk() frame1 = tkinter.Frame(minVindue, bg="black") frame1.grid(row = 0, column = 0) frame2 = tkinter.Frame(minVindue, bg="blue") frame2.grid(row = 0, column = 1) frame3 = tkinter.Frame(minVindue, bg="yellow") frame3.grid(row = 0, column = 2) greenButton = tkinter.Button(frame1, text="Hej grøn", fg="green") greenButton.grid(row = 1, column = 1 ) redButton = tkinter.Button(frame1, text="Hej rød", fg="red") redButton.grid(row = 1, column = 2 ) blueButton = tkinter.Button(frame1, text="Hej blå ", fg="blue") blueButton.grid(row = 2, column = 2 ) blueButton2 = tkinter.Button(frame1, text="Hej blå", fg="blue") blueButton2.grid(row = 3, column = 3 ) textIn = tkinter.Entry(frame1) textIn.grid(row = 1, column = 3 ) greenButton = tkinter.Button(frame2, text="Hej grøn", fg="green") greenButton.grid(row = 1, column = 1 ) redButton = tkinter.Button(frame2, text="Hej rød", fg="red") redButton.grid(row = 1, column = 2 ) blueButton = tkinter.Button(frame2, text="Hej blå ", fg="blue") blueButton.grid(row = 2, column = 2 ) blueButton2 = tkinter.Button(frame2, text="Hej blå", fg="blue") blueButton2.grid(row = 3, column = 3 ) textIn = tkinter.Entry(frame2) textIn.grid(row = 1, column = 3 ) minCanvas1 = tkinter.Canvas(frame3, width=200, height=100) minCanvas1.grid(row = 1, column = 1 ) minCanvas2 = tkinter.Canvas(frame3, width=200, height=100) minCanvas2.grid(row = 1, column = 2 ) minCanvas1.create_line(0, 0, 200, 100) minCanvas1.create_line(0, 100, 200, 0, fill="red", dash=(4, 4)) minCanvas2.create_rectangle(50, 25, 150, 75, fill="blue") minVindue.mainloop()
55177357df2377ffe11ee7f08b9614689cb926a3
zjwyx/python
/day06/05_深浅copy.py
880
4.28125
4
# 赋值运算 # l1 = [1,2,3,[22,33]] # l2 = l1 # l1.append(666) # print(l1) # print(l2) # 浅copy # l1 = [1,2,3,[22,33]] # l2 = l1.copy() # l1.append(666) # print(l1,id(l1)) # print(l2,id(l2)) l1 = [1,2,3,[22,33]] l2 = l1.copy() l1[-1].append(666); print(id(l1[-1])) print(id(l2[-1])) print(l1,id(l1)) print(l2,id(l2)) # 深拷贝 # import copy # l1 = [1,2,3,[22,33]] # l2 = copy.deepcopy(l1) # l1[-1].append(666) # print(l1) # print(l2) # 面试必考 # 切片是浅copy l1 = [1,2,3,[22,33]] l2 = l1[:] l1[-1].append(666) print(l1) print(l2) # 浅copy:list dict :嵌套的可变的数据类型是同一个 # 深copy:list dict :嵌套的可变的数据类型不是同一个 # 今日总结 # id is == 三个方法要会用,知道是作什么的 # 集合:列表去重,关系测试 # 深浅copy:理解浅copy,深浅copy,课上练习整明白 # 预习内容
08b243ce35343dc5e97ee5ffcdcf2924ee4c23db
aldsouza4/Important-Questions
/Sorting Algorithms/scratchbook.py
1,601
3.796875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def traverse(root: Node): if root is None: return traverse(root.left) print(root.data) traverse(root.right) # root = Node(4) # root.left = Node(2) # root.left.left = Node(1) # root.left.right = Node(3) # root.right = Node(6) # root.right.left = Node(-5) # root.right.right = Node(-7) # root = Node(-9) # root.left = Node(6) # root.right = Node(-10) root = Node(1) root.left = Node(8) root.right = Node(6) root.left.left = Node(-7) root.left.right = Node(-10) root.right.left = Node(-9) class Info: def __init__(self, min=-float('inf'), max=float('inf'), ans=0, size=0, isBst=False): self.min = min self.max = max self.ans = ans self.size = size self.isBst = isBst # To check for the larget binary searh Tree in a Binary Tree def bstinbt(root: Node): if root is None: return Info() if root.left is None and root.right is None: return Info(root.data, root.data, 1, 1, True) leftbst = bstinbt(root.left) rightbst = bstinbt(root.right) curr = Info() curr.size = leftbst.size + rightbst.size + 1 if leftbst.isBst and rightbst.isBst and rightbst.min > root.data > leftbst.max: curr.min = min(rightbst.min, leftbst.min, root.data) curr.max = max(rightbst.min, leftbst.min, root.data) curr.ans = curr.size curr.isBst = True else: curr.ans = max(leftbst.ans, rightbst.ans) curr.isBst = False return curr
b2f21ec3ad9f7dff6802d56429b1e8221459ff26
Eduflutter/EXE_python
/EX - 106.py
1,053
3.859375
4
'''Faça um mini-sistema que utilize o interactive Help do Python. O usuário vai digitar o comonado e o manual vai aparecer. Quando o usuário digitar a palavra 'Fim', o programa se encerrará. OBS:Use cores.''' print('\33c') from time import sleep c = ('\33[m', # 0 - sem cor '\33[0;30;41m', # 1 - vermelho '\33[0;30;42m', # 2 - verde '\33[0;30;43m', # 3 - amarelo '\33[0;30;44m', # 4 - azul '\33[0;30;45m', # 5 - roxo '\33[7;30m', # 6 - branco ) def tit(msg, cor=0): tam = len(msg) + 4 print(f"{c[cor]}", end='') print('~'* tam) print(f' {msg}') print('~'*tam) print(f"{c[0]}", end='') sleep(1) def ajuda(cmd): tit(f'Acessando o manual do comando \'{cmd}\'', 4) print(c[6], end='') help(cmd) print(c[0]) sleep(2) #Programa principal comando = '' while True: tit("SISTEMA DE AJUDA PYHELP", 3) comando = str(input('Função aou Biblioteca > ')) if comando.upper() == 'FIM': tit("Até LOGO", 1) break else: ajuda(comando)
572b75b9c3b2badb1d141b9c47aff6c755b437ac
AgentZoy/sf_b3.13
/htmlgen.py
2,221
3.5
4
class Tag: def __init__(self, name='tag', is_single=False, output='', **attributes): self.name = name self.text = '' self.children = [] self.is_child = False self.attributes = attributes self.is_single = is_single self.output = output def __enter__(self): return self def __exit__(self, *args): if not self.is_child: child_str = '' for i in self.children: child_str += str(i) if self.is_single: print(f'<{self.name}{self.pretty_attr()}>') else: print(f'<{self.name}{self.pretty_attr()}>{child_str}</{self.name}>') def __iadd__(self, other): self.children.append(other) other.is_child = True return self def __str__(self): if self.children: child_str = '' for i in self.children: child_str += str(i) return f'<{self.name}{self.pretty_attr()}>{self.text}{child_str}</{self.name}>' else: if self.is_single: return f'<{self.name}{self.pretty_attr()}>' else: return f'<{self.name}{self.pretty_attr()}>{self.text}</{self.name}>' def pretty_attr(self): if self.attributes: attr_list = ' ' for attr, value in self.attributes.items(): if attr =='klass': attr = 'class' temp_value = '' for i in value: temp_value += i + ' ' value = temp_value[0:-1] attr_list += f'{attr}="{value}" ' return attr_list[0:-1] else: return '' class TopLevelTag(Tag): pass class HTML(Tag): def __enter__(self): return self def __exit__(self, *args): child_str = '' for i in self.children: child_str += str(i) if self.output: with open(self.output, 'w') as out_file: print(f'<html{self.pretty_attr()}>{child_str}</html>', file=out_file) else: print(f'<html{self.pretty_attr()}>{child_str}</html>')
380ff0abb455a579e96f5f3d9c42dded770cc0a9
rednur01/ProjectEuler
/003/main.py
1,073
3.96875
4
# Largest prime factor ### Helper function ### from math import sqrt, ceil def isPrime(n: int) -> bool: if n < 2: return False elif n == 2: return True elif n % 2 == 0: return False else: for i in range(3, ceil(sqrt(n))+1, 2): # Only check upto sqrt(n) since at least one prime root must be < sqrt(n) # Start at 3 and jump by 2 to skip testing for even factors if n % i == 0: return False return True def isFactor(to_check: int, N: int) -> bool: return N % to_check == 0 ### Computation ### def find_prime_factors(N: int): prime_factors: list[int] = [1] factor_reduced_N: int = N # For each prime factor found, divide the number by that factor # This factor-reduced number becomes the new limit # upto which to check for new prime factors i: int = 2 while factor_reduced_N >= max(prime_factors) and i <= factor_reduced_N: if isPrime(i) and isFactor(i, N): factor_reduced_N /= i prime_factors.append(i) i += 1 print(f"{N}: {prime_factors}") find_prime_factors(600851475143)
4fb2c1c7a6a3e7ea3270d78d7f4a1328684aacdc
marimachine/sample_test
/src/features/FeatureSelector.py
11,053
3.828125
4
# numpy and pandas for data manipulation import pandas as pd import numpy as np # visualizations import matplotlib.pyplot as plt import seaborn as sns # utilities from itertools import chain from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 class FeatureSelector(object): """ Class for performing feature selection for machine learning or data preprocessing. Implements four different methods to identify features for removal 1. Identifies features with a missing percentage greater than a specified threshold 2. Identifies features with a single unique value 2. Identifies features with a single unique value 3. Identifies collinear variables with a correlation greater than a specified correlation coefficient 4. Identifies features with the weakest relationship with the target variable """ def __init__(self, data, target): self.data = data self.target = target self.missing_stats = None self.corr_matrix = None self.unique_stats = None self.record_missing = None self.record_collinear = None self.record_single_unique = None self.features = self.data.drop([self.target], axis=1) self.base_features = list(self.features) self.removed_features = None # Dictionary to hold removal operations self.ops = {} def identify_missing(self, missing_threshold): """Find the features with a fraction of missing values above `missing_threshold`""" self.missing_threshold = missing_threshold # Calculate the fraction of missing in each column missing_series = self.data.isnull().sum() / self.data.shape[0] self.missing_stats = pd.DataFrame( missing_series).rename( columns={'index': 'feature', 0: 'missing_fraction'}) # Sort with highest number of missing values on top self.missing_stats = self.missing_stats.sort_values('missing_fraction', ascending=False) # Find the columns with a missing percentage above the threshold record_missing = pd.DataFrame( missing_series[missing_series > missing_threshold]).reset_index().rename( columns={'index': 'feature', 0: 'missing_fraction'}) to_drop = list(record_missing['feature']) self.record_missing = record_missing self.ops['missing'] = to_drop print('%d features with greater than %0.2f missing values.\n' % ( len(self.ops['missing']), self.missing_threshold)) def identify_single_unique(self): """Finds features with only a single unique value. NaNs do not count as a unique value. """ # Calculate the unique counts in each column unique_counts = self.data.nunique() self.unique_stats = pd.DataFrame( unique_counts).rename( columns={'index': 'feature', 0: 'nunique'}) self.unique_stats = self.unique_stats.sort_values('nunique', ascending=True) # Find the columns with only one unique count record_single_unique = pd.DataFrame( unique_counts[unique_counts == 1]).reset_index().rename( columns={ 'index': 'feature', 0: 'nunique'}) to_drop = list(record_single_unique['feature']) self.record_single_unique = record_single_unique self.ops['single_unique'] = to_drop print('%d features with a single unique value.\n' % len(self.ops['single_unique'])) def identify_collinear(self, correlation_threshold): """ Finds collinear features based on the correlation coefficient between features. For each pair of features with a correlation coefficient greather than `correlation_threshold`, only one of the pair is identified for removal. """ self.correlation_threshold = correlation_threshold self.corr_matrix = self.data.corr() high_corr_var = np.where(self.corr_matrix.abs() > correlation_threshold) high_corr_var = [(self.corr_matrix.index[x], self.corr_matrix.columns[y], round(self.corr_matrix.iloc[x, y], 2)) for x, y in zip(*high_corr_var) if x != y and x < y] if high_corr_var == []: record_collinear = pd.DataFrame() to_drop = [] else: record_collinear = pd.DataFrame( high_corr_var).rename( columns={0: 'corr_feature', 1: 'drop_feature', 2: 'corr_values'}) record_collinear = record_collinear.sort_values(by='corr_values', ascending=False) record_collinear = record_collinear.reset_index(drop=True) to_drop = list(record_collinear['drop_feature']) self.record_collinear = record_collinear self.ops['collinear'] = to_drop print('%d features with a correlation magnitude greater than %0.2f.\n' % ( len(self.ops['collinear']), self.correlation_threshold)) def identify_weakest_features(self, data, target, target_grouped, number_features): """ statistical test to remove features with the weakest relationship with the target variable """ X = data.drop([target, 'url_id', 'avg_ranking_score', target_grouped], axis=1) y = data[target] # apply SelectKBest class to extract top 20 best features bestfeatures = SelectKBest(score_func=chi2, k=20) fit = bestfeatures.fit(X, y) df_scores = pd.DataFrame(fit.scores_) df_columns = pd.DataFrame(X.columns) feature_scores = pd.concat([df_columns, df_scores], axis=1) feature_scores.columns = ['Features', 'Score'] # naming the dataframe columns feature_scores = feature_scores.sort_values(['Score'], ascending=False) # sorting the dataframe by Score # print(feature_scores.nlargest(20,'Score')) #print the 20 best features to_drop = list(feature_scores.nsmallest(number_features, 'Score')['Features']) self.feature_scores = feature_scores self.ops['weakest_features'] = to_drop data.drop(to_drop, axis=1, inplace=True) print(to_drop, '\n') print('%d features with the lowest score with the target variable removed\n' % ( len(self.ops['weakest_features']))) print("new shape of data:", data.shape) return data def plot_unique(self): """Histogram of number of unique values in each feature""" if self.record_single_unique is None: raise NotImplementedError( 'Unique values have not been calculated. Run `identify_single_unique`') # Histogram of number of unique values self.unique_stats.plot.hist(edgecolor='k', figsize=(7, 5)) plt.ylabel('Frequency', size=14) plt.xlabel('Unique Values', size=14) plt.title('Number of Unique Values Histogram', size=16) def plot_missing(self): """Histogram of missing fraction in each feature""" if self.record_missing is None: raise NotImplementedError("Missing values have not been calculated. Run `identify_missing`") # Histogram of missing values plt.style.use('seaborn-white') plt.figure(figsize=(7, 5)) plt.hist(self.missing_stats['missing_fraction'], bins=np.linspace(0, 1, 11), edgecolor='k', color='red', linewidth=1.5) plt.xticks(np.linspace(0, 1, 11)) plt.xlabel('Missing Fraction', size=14) plt.ylabel('Count of Features', size=14) plt.title("Fraction of Missing Values Histogram", size=16) def plot_collinear(self): """ Heatmap of the correlation values. If plot_all = True plots all the correlations otherwise plots only those features that have a correlation above the threshold """ if self.record_collinear is None: raise NotImplementedError('Collinear features have not been idenfitied. Run `identify_collinear`.') corr_matrix_plot = self.corr_matrix title = "All Correlations" f, ax = plt.subplots(figsize=(10, 8)) # Draw the heatmap with a color bar sns.heatmap(corr_matrix_plot, cmap="Blues") plt.title(title, size=14) def remove(self, methods): """Remove the features from the data according to the specified methods.""" features_to_drop = [] data = self.data if methods == 'all': print('{} methods have been run\n'.format(list(self.ops.keys()))) # Find the unique features to drop features_to_drop = set(list(chain(*list(self.ops.values())))) else: # Iterate through the specified methods for method in methods: # Check to make sure the method has been run if method not in self.ops.keys(): raise NotImplementedError('%s method has not been run' % method) # Append the features identified for removal else: features_to_drop.append(self.ops[method]) # Find the unique features to drop features_to_drop = set(list(chain(*features_to_drop))) features_to_drop = list(features_to_drop) # Remove the features and return the data data = data.drop(columns=features_to_drop) self.removed_features = features_to_drop print('Removed %d features.' % len(features_to_drop)) print('\n', features_to_drop) return data def identify_all(self, selection_params): """ Use all three of the methods to identify features to remove. """ # Check for all required parameters for param in ['missing_threshold', 'correlation_threshold']: if param not in selection_params.keys(): raise ValueError('%s is a required parameter for this method.' % param) # Implement each of the three methods self.identify_missing(selection_params['missing_threshold']) self.identify_single_unique() self.identify_collinear(selection_params['correlation_threshold']) # self.identify_weakest_features(selection_params['target'], selection_params['number_features']) # Find the number of features identified to drop self.all_identified = set(list(chain(*list(self.ops.values())))) self.n_identified = len(self.all_identified) print('%d total features out of %d identified for removal.\n' % (self.n_identified, self.data.shape[1])) def check_removal(self): """Check the identified features before removal. Returns a list of the unique features identified.""" self.all_identified = set(list(chain(*list(self.ops.values())))) print('Total of %d features identified for removal' % len(self.all_identified)) return list(self.all_identified)
a154838a2239f2932d086500ff1637185c0c36a6
dbgower/Project-3
/Lesson 2/mindstorms2.py
757
4.03125
4
import turtle def draw_square(some_turtle): for i in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_shapes(): window = turtle.Screen() window.bgcolor("red") brad = turtle.Turtle() brad.shape("triangle") brad.color("blue","yellow") brad.speed(3) for i in range(1,37): draw_square(brad) brad.right(10) #angie = turtle.Turtle() #angie.shape("arrow") #angie.color("blue") #angie.circle(100) #kevin = turtle.Turtle() #kevin.shape("square") #kevin.color("green") #triangle = 0 #while triangle < 3: # kevin.forward(100) # kevin.right(120) # triangle = triangle + 1 window.exitonclick() draw_shapes()
07a122061847eea5e6b98b2e731ea5cb48b8dde1
DorisBian/projectGit
/pythonPractice/FunctionalProgramming/Decorator2.py
489
3.8125
4
# 多个装饰器 # 定义函数:完成包裹数据 def make_bold(fn): def wrapped(): return "<b>"+fn()+"<b>" return wrapped # 定义函数:完成包裹数据 def make_italic(fn): def wrapped(): return "<i>"+fn()+"<i>" return wrapped @make_bold def test1(): return "hello world-1" @make_italic def test2(): return "hello world-2" @make_bold @make_italic def test3(): return "hello world-3" print(test1()) print(test2()) print(test3())
557eb9ba0a7a3e1cd380a22a2342fe35d6076f9c
xiaoxiyouran/20171205python3Grammer
/08-面向对象编程/08.01 建立一个对象.py
1,789
4.15625
4
class Student(object): ''' 类描述... ''' # 有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传 def __init__(self, name, score): # 第一个参数永远是self,表示创建的实例本身 self.__name = name # 把各种属性绑定到self,因为self就指向创建的实例本身 self.__score = score def print_score(self): # 普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数 print('%s: %s' % (self.__name, self.__score)) bart = Student('Bart Simpson', 59) lisa = Student('Lisa Simpson', 87) bart.print_score() lisa.print_score() print( bart._Student__name ) # 有实际内存 # <__main__.Student object at 0x10657f908> print( Student ) # <class '__main__.Student'> ###----------------------------------------------------------------------------------------------------------------- class(begin) ### TODO: 练习 class Student2(object): def __init__(self, name, gender): self.name = name self.__gender = gender def get_gender(self): return self.__gender def set_gender(self, gender): if gender != 'male' and gender != 'female': raise ValueError('bad gender input!') self.__gender = gender # 测试: bart = Student2('Bart', 'male') if bart.get_gender() != 'male': print('测试失败!') else: bart.set_gender('female') if bart.get_gender() != 'female': print('测试失败!') else: print('测试成功!') ###=================================================================================================================
14fc625ff19ae994f2be8613e89c0920883d922d
radi84/Python
/Controle de estacionamento/controle_estacionamento_v2.py
2,393
3.78125
4
cadastro_rotativo = [] vaga_rotativo = [] print('==' * 20 + ' Controle de estacionamento ' + '==' * 20 + '\n') # Inicialização do app iniciar_app = str(input('Iniciar programa? s/n: ')) # Função de entrada de dados def dados_cliente(): placa = str(input('Placa dados: ')) modelo = str(input('Modelo: ')) cor = str(input('Cor: ')) cliente = str(input('Nome cliente: ')) dados = {'placa': placa, 'modelo': modelo, 'cor': cor, 'Nome cliente': cliente} cadastro_rotativo.append(dados) vaga_rotativo.append(dados) def saida(): """ placa = str(input('Placa saida: ')) print('ok') user_saida = list(filter(lambda us: us['placa'] == placa, vaga_rotativo)) for u in user_saida: vaga_rotativo.remove(u)""" """def entrada(): placa = str(input('Placa entrada: ')) user = list(filter(lambda u: u['placa'] == placa, cadastro_rotativo)) for i in user: vaga_rotativo.append(i)""" while True: if iniciar_app == 's': print('=' * 130) print(' 1 - Entrada |' ' 2 - Saida |' ' 3 - Cadastros Rotativo |' ' 4 - Vagas Rotativo |' ' 5 - Sair |') print('=' * 130 + '\n') opc = int(input('Entre com a opção: ')) if opc == 1: if not cadastro_rotativo: dados_cliente() else: placa_comparacao = str(input('placa comparaçao: ')) for cad_rot in cadastro_rotativo: p_user = cadastro_rotativo[cad_rot].get('placa') if placa_comparacao == p_user: print(p_user) else: dados_cliente() break """p_user = list(filter(lambda u: u['placa'] == placa_comparacao, cadastro_rotativo)) for user in cadastro_rotativo: vaga_rotativo.append(p_user) if not p_user: print('Placa nao cadastrada.') dados_cliente() break""" elif opc == 2: print('Saida.') saida() elif opc == 3: for i in cadastro_rotativo: print(i) elif opc == 4: for i in vaga_rotativo: print(i) else: break
c219900365a93dae7d226d2414b534cd75d3b92a
AndriiLatysh/ml_course
/python_4/main.py
308
4.03125
4
# unique_values = set([1, 2, 2, 3]) # print(unique_values) capitals = {"Ukraine": "Kyiv", "Ireland": "Dublin"} capitals["USA"] = "Washington DC" print(capitals) capitals.pop("Ireland") print(capitals) for key, value in capitals.items(): print("{} -> {}".format(key, value)) print(capitals.items())
fc7972e0960d2c21fa7bb372aacc065050bbfc69
rishabhad/Python-Basics-
/practice11.py
163
3.625
4
#checkin the world count in sentence count=0 item=[x for x in input().split(' ')] for i in item : count=count+1 print (count) print(len(item))
fea30203d34abb48de06e05a6e5b261ec7919109
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/blcsau001/question2.py
484
4.1875
4
#Program that uses a recursive function to count the number of pairs of repeated characters in a string. #Saul Bloch #6 April 2014 user_string = input ("Enter a message:\n") def pairs (user_sentence): if len(user_sentence) == 0 or len(user_sentence) == 1: return 0 elif user_sentence[0] == user_sentence[1]: return 1 + pairs(user_sentence [2:]) else: return 0 + pairs(user_sentence[1:]) print ("Number of pairs:",pairs(user_string))
c1c6054b894de7aac468cd2290dee294f23475c8
ed1rac/Estrutura-de-dados
/normal/Pilha.py
1,587
3.828125
4
import unittest class Pilha: class Noh: def __init__(self, element, next): self.elemento = element self.next = next def __init__(self): self.cabeca = None self.tamanho = 0 def __len__(self): return self.tamanho def vazia(self): return self.tamanho == 0 def push(self, e): self.cabeca = self.Noh(e, self.cabeca) self.tamanho += 1 def pop(self): if self.vazia(): return None else: auxiliar = self.cabeca.elemento self.cabeca = self.cabeca.next self.tamanho -= 1 return auxiliar def top(self): if self.vazia(): return None else: return self.cabeca.elemento class Teste(unittest.TestCase): def teste_pop(self): pilha = Pilha() pilha.push(3) self.assertEqual(3, pilha.pop()) def teste_pop_null(self): pilha = Pilha() self.assertIsNone(pilha.pop()) def teste_cabeca(self): pilha = Pilha() self.assertIsNone(pilha.cabeca) def teste_push(self): pilha = Pilha() pilha.push(3) self.assertEqual(pilha.cabeca.elemento, 3) def teste_len(self): pilha = Pilha() valores = [1,2,3,4,5] for x in valores: pilha.push(x) self.assertEqual(len(valores),len(pilha)) def teste_top(self): pilha = Pilha() pilha.push(3) self.assertEqual(3,pilha.top()) if __name__ == '__main__': unittest.main()
8735a22a6a8bafc6b8a4ed152f2150bbcbf32c8b
MMingLeung/Python_Study
/chapter9/Tornado/tornado_study/part5/test1.py
3,636
3.703125
4
import re import copy # ############## 定制插件(HTML) ############## class TextInput(object): def __init__(self, attrs=None): if attrs: self.attrs = attrs else: self.attrs = {} def __str__(self): data_list = [] for k, v in self.attrs.items(): tpm = "{0}='{1}'" .format(k,v) data_list.append(tpm) tpl = '<input type="text" {0} />'.format(''.join(data_list)) return tpl class EmailInput(object): def __init__(self, attrs=None): if attrs: self.attrs = attrs else: self.attrs = {} def __str__(self): data_list = [] for k, v in self.attrs.items(): tpm = "{0}='{1}'" .format(k,v) data_list.append(tpm) tpl = '<input type="email" {0} />'.format(''.join(data_list)) return tpl class PassWordInput(object): def __init__(self, attrs=None): if attrs: self.attrs = attrs else: self.attrs = {} def __str__(self): data_list = [] for k, v in self.attrs.items(): tpm = "{0}='{1}'" .format(k,v) data_list.append(tpm) tpl = '<input type="password" {0} />'.format(''.join(data_list)) return tpl # obj = TextInput(attrs={'class':'btn'}) # print(obj) # ############## 定制字段(正则) ############## class Field(object): def __str__(self): if self.value: self.widget.attrs['value'] = self.value return str(self.widget) class CharField(Field): default_widget = TextInput regex = "\w+" def __init__(self, widget=None): self.value = None self.widget = widget if widget else self.default_widget() def valid_field(self, value): if re.match(self.regex, value): self.value = value return True else: return False class EmailField(Field): default_widget = EmailInput regex = "\w+@\w+" def __init__(self, widget=None): self.value = None self.widget = widget if widget else self.default_widget() def valid_field(self, value): if re.match(self.regex, value): self.value = value return True else: return False # ############## 定制Form(正则) ############## class BaseForm(object): def __init__(self, data): self.data = data self.fields = {} print(type(self).__dict__) #{'user': <__main__.CharField object at 0x101981710>, 'email': <__main__.EmailField object at 0x101981828>, '__doc__': None, '__module__': '__main__'} for name, field in type(self).__dict__.items(): print(name, field) # 如果字段是Field这个类,就要拷贝一份 if isinstance(field, Field): # 在对象设置,以便对象能够获取 print(111) new_field = copy.deepcopy(field) setattr(self, name, new_field) self.fields[name] = new_field def is_valid(self): flag = True for name ,field in self.fields.items(): user_input_val = self.data.get(name) result = field.valid_field(user_input_val) if not result: flag = False return flag # ############## 使用 ############## class LoginForm(BaseForm): user = CharField() email = EmailField() # request.POST 本质是字典 form = LoginForm({'user':'matt', 'email':'matt@gmail.com'}) print(form.user) print(form.email) print(form.is_valid())
1eccf57035082a2dc2e20273685fb9c2bd02c793
AntonAroche/DataStructures-Algorithms
/arrays/deleting-items.py
586
3.84375
4
# Given an array nums and a value val, remove all instances of that value in-place and return the new length. # # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # # The order of elements can be changed. It doesn't matter what you leave beyond the new length. def removeElement(nums, val): ind = len(nums) - 1 while(ind >= 0): if nums[ind] == val: nums.pop(ind) ind -= 1 return len(nums) nums =[0,1,2,2,3,0,4,2] val = 2 print(removeElement(nums, val)) print(nums)
d23aca102a1b280bf9192348be0740243495ac24
zplchn/m_amzn
/reviewed/citadel.py
10,459
3.640625
4
from typing import List import collections, heapq class ListNode: def __init__(self, x): self.val = x self.next = None class HashTable: def __init__(self, size): self.hm = [[] for _ in range(size)] def put(self, key, value): hash_key = hash(key) % len(self.hm) key_exists = False bucket = self.hm[hash_key] for i, (k, v) in enumerate(bucket): if key == k: key_exists = True bucket[i] = (key, value) break if not key_exists: bucket.append((key, value)) def get(self, key): hash_key = hash(key) % len(self.hm) bucket = self.hm[hash_key] for i, (k, v) in enumerate(bucket): if key == k: return v def delete(self, key): hash_key = hash(key) % len(self.hm) bucket = self.hm[hash_key] for i, (k, v) in enumerate(bucket): if key == k: del bucket[i] break class Solution: class MyCircularQueue: # tail always be the next insertion point, head always the head. circular just need to mod the size and # everything else would be the same as non-circular def __init__(self, k: int): """ Initialize your data structure here. Set the size of the queue to be k. """ self.k = k self.size = 0 # self.q = [0 * k] Cannot do this way because k is a int self.q = [0 for _ in range(k)] self.head = self.tail = 0 def enQueue(self, value: int) -> bool: """ Insert an element into the circular queue. Return true if the operation is successful. """ if self.isFull(): return False self.q[self.tail] = value self.tail = (self.tail + 1) % self.k self.size += 1 return True def deQueue(self) -> bool: """ Delete an element from the circular queue. Return true if the operation is successful. """ if self.isEmpty(): return False self.head = (self.head + 1) % self.k self.size -= 1 return True def Front(self) -> int: """ Get the front item from the queue. """ return self.q[self.head] if not self.isEmpty() else -1 def Rear(self) -> int: """ Get the last item from the queue. """ return self.q[self.tail - 1] if not self.isEmpty() else -1 def isEmpty(self) -> bool: """ Checks whether the circular queue is empty or not. """ return self.size == 0 def isFull(self) -> bool: """ Checks whether the circular queue is full or not. """ return self.size == self.k def lengthOfLongestSubstring(self, s: str) -> int: if not s: return 0 start = maxv = 0 hm = {} for i in range(len(s)): if s[i] not in hm or hm[s[i]] < start: maxv = max(maxv, i - start + 1) else: start = hm[s[i]] + 1 hm[s[i]] = i return maxv def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: if not s or k < 1: return 0 hm = {} left = maxv = 0 for i in range(len(s)): hm[s[i]] = hm.get(s[i], 0) + 1 while len(hm) > k: hm[s[left]] -= 1 if hm[s[left]] == 0: del hm[s[left]] left += 1 maxv = max(maxv, i - left + 1) return maxv def findItinerary(self, tickets: List[List[str]]) -> List[str]: # postorder dfs def dfs(s): while hm[s]: dfs(hm[s].pop()) res.append(s) res = [] hm = collections.defaultdict(list) #create graph using adjcency list for x, y in tickets: hm[x].append(y) # python does not have dict with key sorted, so need to sort ourselves for _, values in hm.items(): values.sort(reverse=True) # smaller at the end. so when pop() out first dfs('JFK') return res[::-1] class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random def copyRandomList(self, head: 'Node') -> 'Node': if not head: return head cur = head # 1. copy 1-> 1'-> 2 -> 2' while cur: node = self.Node(cur.val, None, None) node.next = cur.next cur.next = node cur = cur.next.next # 2. connect random cur = head while cur: cur.next.random = cur.random.next if cur.random else None cur = cur.next.next # 3. split cur = head dummy = pre = self.Node(0, None, None) while cur: pre.next = cur.next pre = pre.next cur.next = cur.next.next cur = cur.next return dummy.next def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if not head: return head dummy = ListNode(0) dummy.next = head l = r = dummy while n > 0: r = r.next n -= 1 while r and r.next: l = l.next r = r.next l.next = l.next.next return dummy.next def maxProfit(self, prices: List[int]) -> int: if len(prices) < 2: return 0 minv, res = prices[0], 0 for i in range(1, len(prices)): res = max(res, prices[i] - minv) minv = min(minv, prices[i]) return res def missingNumber(self, nums: List[int]) -> int: if not nums: return -1 res = 0 for i in range(len(nums)): res ^= (i + 1) ^ nums[i] return res # def isMatch(self, s: str, p: str) -> bool: def mergesort(self, nums: List[int]) -> List[int]: def sort(l, r): if l < r: m = l + ((r - l) >> 1) sort(l, m) sort(m + 1, r) merge(l, m, r) def merge(l, m, r): i, j, k = l, m + 1, 0 while i <= m and j <= r: if nums[i] < nums[j]: t[k] = nums[i] i += 1 else: t[k] = nums[j] j += 1 k += 1 while i <= m: t[k] = nums[i] k, i = k + 1, i + 1 while j <= r: t[k] = nums[j] k, j = k + 1, j + 1 nums[l:r+1] = t[0:k] if not nums: return nums t = [0 for _ in range(len(nums))] sort(0, len(nums) - 1) return nums def quicksort(self, nums: List[int]) -> List[int]: def sort(l, r): if l < r: p = partition(l, r) sort(l, p - 1) sort(p + 1, r) def partition(l, r) -> int: start, i, j = l, l + 1, r while True: while i <= j and nums[i] <= nums[start]: i += 1 while i <= j and nums[j] >= nums[start]: j -= 1 if i <= j: nums[i], nums[j] = nums[j], nums[i] else: nums[start], nums[j] = nums[j], nums[start] break return j if not nums: return nums sort(0, len(nums) - 1) return nums def findMedianSortedArrays4(self, nums1: List[int], nums2: List[int]) -> float: # o(log(m + n)) the point is every time cut half k list and find a half k in the next round until k == 1 def kth(nums1, nums2, k): if len(nums1) > len(nums2): return kth(nums2, nums1, k) if not nums1: return nums2[k - 1] if k == 1: return min(nums1[0], nums2[0]) off1 = min(k // 2, len(nums1)) off2 = k - off1 if nums1[off1 - 1] == nums2[off2 - 1]: return nums1[off1 - 1] elif nums1[off1 - 1] < nums2[off2 - 1]: return kth(nums1[off1:], nums2, k - off1) else: return kth(nums1, nums2[off2:], off1) m, n = len(nums1), len(nums2) l = m + n return (kth(nums1, nums2, (l + 1) // 2) + kth(nums1, nums2, (l + 2) // 2)) / 2 def maxProfit3(self, prices: List[int]) -> int: if not prices: return 0 buy1 = buy2 = float('-inf') sell1 = sell2 = 0 for p in prices: buy1 = max(buy1, -p) sell1 = max(sell1, p + buy1) buy2 = max(buy2, sell1 - p) sell2 = max(sell2, buy2 + p) return sell2 def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]: res = [] if not A or not B: return res i = j = 0 while i < len(A) and j < len(B): l = max(A[i][0], B[j][0]) r = min(A[i][1], B[j][1]) if l <= r: res.append([l, r]) if A[i][1] < B[j][1]: i += 1 else: j += 1 return res def topKFrequent(self, words: List[str], k: int) -> List[str]: res = [] if not words or k < 1: return res c = collections.Counter(words) # Counter most_common(n) return from biggest v. but when v is same, k is random order. So need to put in heap # to sort heap = [(-v, k) for k, v in c.items()] heapq.heapify(heap) return [heapq.heappop(heap)[1] for _ in range(k)] if __name__ == "__main__": s = Solution() nums = [2,6,-10,9, 100, -2, 8, 13] # print(s.mergesort(nums)) # print(s.quicksort(nums)) hm = HashTable(10) for x in nums: hm.put(x, x) for x in nums: if hm.get(x) != x: print('err') hm.delete(nums[0]) print(hm.get(nums[0]))
8505415b05ed15e01410897e2a4d390515e616a1
mifiamigahna/ANN
/01.py
1,185
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 18 16:30:39 2019 @author: mifiamigahna """ import numpy as np import matplotlib.pyplot as plt #1 x = np.arange(-50, 51) plt.subplot(121) plt.plot(x, np.square(x)) plt.subplot(122) plt.plot(x, np.sqrt(x)) plt.plot(x, -np.sqrt(x)) #2 x = np.arange(-10, 11) def FuncA(x): return 2 * x + 2 def FuncB(x): return 5 * np.square(x) + x def FuncC(x): return 11 * np.power(x, 3) + 2 * np.square(x) + 2 * x + 3 def FuncD(x): return np.exp(x) plt.figure plt.subplot(2,2,1) plt.plot(x, FuncA(x)) plt.subplot(2,2,2) plt.plot(x, FuncB(x)) plt.subplot(2,2,3) plt.plot(x, FuncC(x)) plt.subplot(2,2,4) plt.plot(x, FuncD(x)) m = np.arange(-1, 2) b = np.arange(-5, 10, 5) x = np.arange(-10, 11) plt.figure plt.subplot(331) plt.plot(x, m[0] * x + b[0]) plt.subplot(332) plt.plot(x, m[1] * x + b[0]) plt.subplot(333) plt.plot(x, m[2] * x + b[0]) plt.subplot(334) plt.plot(x, m[0] * x + b[1]) plt.subplot(335) plt.plot(x, m[1] * x + b[1]) plt.subplot(336) plt.plot(x, m[2] * x + b[1]) plt.subplot(337) plt.plot(x, m[0] * x + b[2]) plt.subplot(338) plt.plot(x, m[1] * x + b[2]) plt.subplot(339) plt.plot(x, m[2] * x + b[2])
2c18fd04063321918302c56e207d84518b23f901
HyeRRimm/Studying_Python
/CH4/4-1리스트와반복문/이론/aliase.py
420
4.21875
4
#1 x=5 y=x #주의: x=y 코드오류 왜냐면 y 정의X y=3 print(x) print(y) #2 aliase(가명) : x,y 값 동시 변화(하니까 코드작성시 유의해라~요정도) x=[1,2,3,4,5] y=x # y=[1,2,3,4,5] x=[1,2,3,4,5] y[2]=6 #y=[1,2,6,4,5] x=[1,2,3,4,5] print(x) print(y) #3 y만 변화 x=[1,2,3,4,5] y=list(x) #x 리스트를 복사해줌으로서 x리스트 건드리지 않고 y만 변화 y[2]=6 print(x) print(y)
e94893a05eb5ab6c8f93a809461db504be6eba24
jindtang/cs373
/quizzes/Quiz5.py
747
4.28125
4
#!/usr/bin/env python3 """ CS373: Quiz #5 (7 pts) """ """ ---------------------------------------------------------------------- 1. What is the output of the following? (6 pts) g1 f1 f2 g2 else finally g3 g1 f1 except finally g3 g1 f1 finally """ def f (n) : print("f1", end = " ") if n == 1 : raise KeyError() elif n == 2: raise TypeError() print("f2", end = " ") def g (n) : try : print("g1", end = " ") f(n) print("g2", end = " ") except KeyError : print("except", end = " ") else : print("else", end = " ") finally : print("finally", end = " ") print("g3") try : for n in [0, 1, 2] : g(n) except Exception : print()
e461ee40571936f59507237ce879b703c8e44f5b
rajan596/python-hacks
/matplotlib-tut.py
510
3.734375
4
# python 3 from matplotlib import pyplot as plt from matplotlib import style # styles style.use('ggplot') #style.use('dark_background') #style.use('grayscale') # points x=[1,2,3,4] y1=[2,5,6,7] y2=[1,2,5,7] y3=[1,2,3,4] # chart/graph style #plt.plot(x,y1,'b',linewidth=2,label='Y1') #plt.scatter(x,y2,color='g',label='Y2') #plt.plot(x,y3) plt.bar(x,y1,color='c',align='center') # settings plt.title('Chart') plt.ylabel('Y') plt.xlabel('X') plt.legend() #plt.grid(True,color='k') # finally sow plt.show()
612bf63604c13eff1a4543cf0d26463f552a3c59
dwbelliston/python_structures
/arrays/array.py
5,690
4.0625
4
#!/usr/bin/env python3 class Array(object): ''' An array implementation that holds arbitrary objects. ''' def __init__(self, initial_size=10, chunk_size=5): '''Creates an array with an intial size.''' self.content = alloc(initial_size) self.size_alloc = initial_size self.size_filled = 0 self.chunk_size = chunk_size def debug_print(self, file_write): '''Prints a representation of the entire allocated space, including unused spots.''' '''EX: 11 of 15 >>> a, e, r, o, I, o, d, u, s, a, u, null, null, null, null''' values = ', '.join(str(x) for x in self.content) print('{} of {} >>> {}'.format( self.size_filled, self.size_alloc, values)) file_write.writelines('{} of {} >>> {}\n'.format( self.size_filled, self.size_alloc, values)) def _check_bounds(self, index): '''Ensures the index is within the bounds of the array: 0 <= index <= size.''' # Cant be less than 0, and cant be greater than the last index if index >= 0 and index <= self.size_filled - 1: return True else: print('Error: {} out of bounds'.format(index)) return False def _check_increase(self): ''' Checks whether the array is full and needs to increase by chunk size in preparation for adding an item to the array. ''' if self.size_alloc == self.size_filled: # Set new size of allocated self.size_alloc = self.size_alloc + self.chunk_size # Allocate a new array temp_new_array = alloc(self.size_alloc) self.content = memcpy(temp_new_array, self.content, self.size_alloc) def _check_decrease(self): ''' Checks whether the array has too many empty spots and can be decreased by chunk size. If a decrease is warranted, it should be done by allocating a new array and copying the data into it (don't allocate multiple arrays if multiple chunks need decreasing). ''' empty_gap = self.size_alloc - self.size_filled if empty_gap >= self.chunk_size: # Set new size of allocated (Keeping array, just masking it to # be shorter) self.size_alloc = self.size_alloc - self.chunk_size def add(self, item): '''Adds an item to the end of the array, allocating a larger array if necessary.''' self._check_increase() # alloc more if needed self.content[self.size_filled] = item self.size_filled += 1 def insert(self, new_index, new_item): '''Inserts an item at the given index, shifting remaining items right and allocating a larger array if necessary.''' new_index = int(new_index) in_bounds = self._check_bounds(new_index) if in_bounds: self._check_increase() # alloc more if needed for i, item in reverse_enum(self.content): # shift right from new_index on if i < self.size_filled and i >= new_index: self.content[i + 1] = item self.content[new_index] = new_item self.size_filled += 1 def set(self, index, item): '''Sets the given item at the given index. Throws an exception if the index is not within the bounds of the array.''' index = int(index) in_bounds = self._check_bounds(index) if in_bounds: self.content[index] = item def get(self, index): '''Retrieves the item at the given index. Throws an exception if the index is not within the bounds of the array.''' index = int(index) in_bounds = self._check_bounds(index) if in_bounds: print(self.content[index]) def delete(self, index): '''Deletes the item at the given index, decreasing the allocated memory if needed. Throws an exception if the index is not within the bounds of the array.''' index = int(index) in_bounds = self._check_bounds(index) if in_bounds: self.content[index] = None self.size_filled -= 1 # Iterate over array to right, starting one past index, and drop # them down for i, item in enumerate(self.content[index + 1:self.size_filled + 1], start=index + 1): # replace last item with None if i == self.size_filled: # End of filled array, put None at end self.content[i] = None # Move the item back one self.content[i - 1] = item self._check_decrease() # alloc less if needed def swap(self, index1, index2): '''Swaps the values at the given indices.''' index1, index2 = int(index1), int(index2) in_bounds_1 = self._check_bounds(index1) in_bounds_2 = self._check_bounds(index2) if in_bounds_1 and in_bounds_2: self.content[index1], self.content[index2] = self.content[index2], self.content[index1] # Utilities def alloc(size): ''' Allocates array space in memory. This is similar to C's alloc function. ''' new_array = [None] * size return new_array def memcpy(dest, source, size): ''' Copies items from one array to another. This is similar to C's memcpy function. ''' for index, item in enumerate(source): dest[index] = item return dest def reverse_enum(L): for index in reversed(range(len(L))): yield index, L[index]
74ab48d2c5270f3ce54788b4a5a3d718c4d02ab0
sergeiissaev/Kattis-solutions
/icpcawards.py
478
3.6875
4
class Award: def __init__(self): input() self._print_winners() def _print_winners(self): awarded = 0 awarded_list = list() while awarded < 12: institution, team = list(map(str, input().rstrip().split())) if institution not in awarded_list: awarded_list.append(institution) awarded += 1 print(f"{institution} {team}") if __name__ == "__main__": Award()
dc8b7f536e3689fdba222cc8ed065d49ffa86768
Arunabha97/bank
/main.py
1,415
3.5625
4
import functions from os import system import database import cx_Oracle from connection import con,cur def main(): database.make_all_tables() database.reset_withdrawals() choice = 1 print("\n##### Welcome To ONLINE BANKING TERMINAL #####\n") while choice != 0: print("\t--- Main Menu ---\n ") print("1. Sign Up (New Customer) ") print("2. Sign In (Existing Customer) ") print("3. Admin Sign In ") print("4. Quit ") print("\nEnter Your Choice: ", end='') try: choice = int(input()) system('CLS') print("\n##### Welcome To ONLINE BANKING TERMINAL #####\n") except: system('CLS') print("\n##### Welcome To ONLINE BANKING TERMINAL #####\n") print("\tERROR: Invalid Input! ENTER AGAIN\n") choice = 1 continue if choice == 1: functions.sign_up(); elif choice == 2: functions.sign_in(); elif choice == 3: functions.admin_sign_in(); elif choice == 4: print("Saving Transaction ...\nClosing Terminal ...\n\n") break else: system('CLS') print("\n##### Welcome To ONLINE BANKING TERMINAL #####") print("ERROR: Unknown Choice! ENTER AGAIN\n") main()
da4d636c1456dfcbc78759c9e57888e660aef0d2
AL-8/ColorGuessGame
/app.py
190
3.84375
4
secret_word = "orange" guess = "" while guess != secret_word: guess = input("Guess Color: ") print("You win!")
b7c81967ea9203becee8b3ec8b6974c97e75bc28
ZSPASOV/softuni-python-fundamentals
/03-Lists-Basics-Lab/demo20-not-in.py
238
4.28125
4
# The "not in" keywords are used to check if an element is NOT in a list # my_list = [1, 2, 3, 4] if 5 not in my_list: print("The number 5 is not in the list") # The "not in" keywords are also mainly used with if-else statements
663aaeb2cb602de8c13c88200e181d35944b8d05
qbuch/python_szkolenie
/homework_4/string_int_counter.py
517
3.890625
4
#Napisz program, obliczający liczbę cyfr i liter w dowolnym ciągu znaków # np.“Tomek123” - 5 liter, 3 cyfry. Dane wejściowe wprowadza użytkownik po uruchomieniu programu. user_prompt = input("Hey, give me an input to count: ") letters = 0 digits = 0 for i in user_prompt: if(i.isalpha()): letters+=1 elif(i.isdigit()): digits+=1 #print("Your input has " + str(letters) + " letters and " + str(digits) + " digits.") print(f"Your input has {letters} letters and {digits} digits.")
543bbcde72b61692dfc61b9f8617d4b0e64dc008
AlKoAl/-10
/Hamming/Hamming.py
3,250
4.03125
4
string = input('Введите строку из 0 и 1') # Вводим последовательность 0 и 1 k = 0 while True: if k <= 2**k - len(string) - 1: break else: k += 1 string = ' ' + string[:] for i in range(1, k): string = string[: (2 ** i) - 1] + ' ' + string[(2 ** i) - 1:] # ставим пропуски на номера со степенями 2-ки def part_of_coding(digits): # поставит на пропуски цифры def func1(s): nonlocal score, digits while s * 2 ** i <= len(digits): if s == 1: if (s + 1) * 2 ** i > len(digits): for j in digits[s * 2 ** i:]: score += int(j) break else: for j in digits[s * 2 ** i: (s + 1) * 2 ** i - 1]: score += int(j) s += 2 func1(s) return () else: if (s + 1) * 2 ** i > len(digits): for j in digits[s * 2 ** i - 1:]: score += int(j) break else: for j in digits[s * 2 ** i - 1: (s + 1) * 2 ** i - 1]: score += int(j) s += 2 func1(s) return () for i in range((k - 1), -1, -1): score = 0 func1(1) if score % 2 == 0: digits = digits[:2 ** i - 1] + '0' + digits[2 ** i:] else: digits = digits[:2 ** i - 1] + '1' + digits[2 ** i:] return(digits) string = part_of_coding(string) print("Закодированная последовательность:", string) error = input("Введите изменённую последовательность с одной ошибкой:") error = error[2:] for i in range(k - 1, 1, -1): error = error[:(2**i - 3)] + error[(2**i - 2):] # Вырезали кодирующие биты while True: if k <= 2**k - len(error) - 1: break else: k += 1 error = ' ' + error[:] for i in range(1, k): error = error[: (2 ** i) - 1] + ' ' + error[(2 ** i) - 1:] error = part_of_coding(error) # снова пропуски заполняем цифрам print("Переприсвоение кодирующих бит:", error) i = 0 numbers = [] # Совпадение/несовпадение кодирующих битов while 2**i <= len(string): if error[2**i-1] == string[2**i-1]: numbers.append(0) i += 1 else: numbers.append(1) i += 1 sum = 0 for i in range(len(numbers)): sum += 2**i*numbers[i] print("Ошибочный бит:", sum) if sum == 0: # Изменяем ошибочный бит или не изменяем ничего error = error else: if error[sum - 1] == '1': error = error[: sum - 1] + '0' + error[sum:] elif error[sum - 1] == '0': error = error[: sum - 1] + '1' + error[sum:] error = error[2:] for i in range(k - 1, 1, -1): error = error[:(2**i - 3)] + error[(2**i - 2):] # снова убираем кодирующие биты print(error)
9edc10d077b8d049655d7ede5e9d76329ae8626a
rjtsg/StockExchangeAI
/StockSimPlay.py
4,420
3.921875
4
""" This file should let us choose a decision of buying, holding, selling a stock (if available). It will load in the close data from the AXP stock data. The game will take us from 2000 to 20001. Which means it simulates 1 year of stock trading. The user will start with an amount of cash of $10,000. He will see the first starting price for day 1, he can than decide to trade or not. After that he will see the closing price of that day and on wards will only see closing prices of the following days. After each trading day the user will see the following outputs: day number, cash money, stock owned, stock worth and total money. If the trading day is done the closing price will be presented. A good idea is to save trading dates, money gotten from trades, buying prices, selling prices. Calculate annual return of trader and that of the stock. It would be nice if some plot would be made. """ #To start of import the needed packages: import numpy as np import pandas as pd import sys import os import random import time #load in the AXP data and select data from 2000 to 2001: MainDirectory = os.getcwd() os.chdir('DataFiles') df = pd.read_excel('AXPData.xlsx') os.chdir(MainDirectory) #So now we only want to have the data of 2000-01-01 to 2000-12-31 roughly DataPrepTimeBegin = time.time() df1 = pd.DataFrame(data=None, columns=df.columns) counter = 0 for i in range(len(df)): datecheck = str(df.Date[i]) if datecheck[0:4] == '2000': df1.loc[datecheck] = df.iloc[i] #now we will have to flip it in order to make it easier for ourselfs (2000-01-01 is not the start date) df1 = df1.iloc[::-1] DataPrepTimeEnd = time.time() #we apperently start with 2000-01-03 I think it is because of weekends #So from here on we will have to build some while/for loop that goes on untill the end of the data is reached #It must containt buying and selling opertunities as described above! States = ['Buy','Sell','Do nothing'] #These are the actions the agent has StartingCapital = 1000 #The starting capital of the agent AXPshares = 0 #counter of the amount of AXPshares Cash = StartingCapital #Amount of cash, with which the agent can buy shares #df2 is going to be the datalog file of what the agent does: df2 = pd.DataFrame(data=None, columns = ['Day Number','Action','Cash','Stock Owned','Stock Worth','Net Worth','Closing Stock Price']) SimulationTimeBegin = time.time() print('The simulation Starts') for i in range(len(df1)): if i == 0: Decision = random.randint(0,2) #This decides the action the agent takes Action = States[Decision] #this is the corresponding action if Action =='Buy' and (Cash-df1['Open'].iloc[i])>0: AXPshares += 1 #for now it only buys one share at a time Cash -= df1['Open'].iloc[i] #removing money from the cash elif Action == 'Sell' and AXPshares > 0: AXPshares -= 1 #selling 1 share Cash += df1['Open'].iloc[i] #adding money to cash else: pass else: Decision = random.randint(0,2) #This decides the action the agent takes Action = States[Decision] #this is the corresponding action if Action =='Buy' and (Cash-df1['Open'].iloc[i])>0: AXPshares += 1 #for now it only buys one share at a time Cash -= df1['Open'].iloc[i] #removing money from cash elif Action == 'Sell' and AXPshares > 0: AXPshares -= 1 #selling 1 share Cash += df1['Open'].iloc[i] #adding money to cash else: pass #save the important stuff here: df2 = df2.append({'Day Number':i,'Action':Action,'Cash':Cash,'Stock Owned':AXPshares,'Stock Worth':AXPshares*df1['Close'].iloc[i],'Net Worth':Cash + AXPshares*df1['Close'].iloc[i],'Closing Stock Price':df1['Close'].iloc[i]},ignore_index=True) print('The simulation has finished') SimulationTimeEnd = time.time() #Saving the data on the right path: os.chdir('DataFiles') if not os.path.exists('SimulationTestData'): os.makedirs('SimulationTestData') os.chdir('SimulationTestData') df2.to_excel('1Stock1yearSim.xlsx') #For the user to see if everything went right os.chdir(MainDirectory) print('The total elapsed time for data preperation is: {}'.format(DataPrepTimeEnd - DataPrepTimeBegin)) print('The total elapsed time for the Simulation is: {}'.format( SimulationTimeEnd - SimulationTimeBegin))
ffd8966e04d388308f112952e762ed31df699ed7
Kapil1717/Python-Lab
/L8-DLL-All.py
3,661
3.765625
4
#121910313016 class Node: def __init__(self, next=None, prev=None, data=None): self.next = next self.prev = prev self.data = data class DoublyLinkedList: def __init__(self): self.head = None def append(self, new_data): new_node = Node(data = new_data) new_node.next = self.head new_node.prev = None if self.head is not None: self.head.prev = new_node self.head = new_node def addAtBack(self,new_data): new_node = Node(data = new_data) last = self.head new_node.next = None if self.head is None: new_node.prev = None self.head = new_node return while (last.next is not None): last = last.next last.next = new_node new_node.prev = last def addAfter(self,prev_node,new_data): if prev_node is None: print("Node doesn't exist!") return new_node = Node(data = new_data) new_node.next = prev_node.next prev_node.next = new_node new_node.prev = prev_node if new_node.next is not None: new_node.next.prev = new_node def delete(self,val): cur = self.head prev_node = None found = False while not found: if cur.data == val: found = True else: prev_node = cur cur = prev_node.next if prev_node is None: cur = cur.next else: prev_node.next = cur.next def length(self): cur = self.head total_nodes = 0 while cur is not None: total_nodes+=1 cur = cur.next print(total_nodes) def search(self,val): cur = self.head found = False while cur is not None and not found: if(cur.data == val): found = True else: cur = cur.next print(found) def min(self): cur = self.head if cur == None: print("List is empty!") else: min = cur.data while cur is not None: if(min > cur.data): min = cur.data cur = cur.next print(min) def max(self): cur = self.head if cur == None: print("List is empty!") else: max = cur.data while cur is not None: if(max < cur.data): max = cur.data cur = cur.next print(max) def printList(self): cur = self.head while cur: print(cur.data) cur = cur.next llist = DoublyLinkedList() llist.append(45) llist.append(18) llist.append(17) a = int(input('Enter the number you want to add at the begining: ')) llist.append(a) b = int(input('Enter the number you want to add at the ending: ')) llist.addAtBack(b) c = int(input("Enter the number you want to add after the node: ")) llist.addAfter(llist.head.next,c) d = int(input("Check whether this value is in the Linked List or not: ")) llist.search(d) print('Number of nodes in the DLL is: ') llist.length() print("DLL is: ") llist.printList() e = int(input("Enter the element you want to delete: ")) llist.delete(e) print("Linked list after the deletion: ") llist.printList() print("Minimum key in the Linked list is: ") llist.min() print("Maximum key in the Linked list is: ") llist.max()
f8ec96f4ab42db27b7e3f4daefbcc772c36d1f30
dsmith1974/edu-py-int
/ace/Challenge2.py
1,288
4.1875
4
# https://www.educative.io/module/lesson/data-structures-in-python/B137p8P75QW # Problem Statement # # Implement a function that merges two sorted lists of m and n elements respectively, into another sorted list. # Name it merge_lists(lst1, lst2). # # Input # # Two sorted lists. # # Output # # A merged and sorted list consisting of all elements of both input lists. # # Sample Input # # list1 = [1,3,4,5] # list2 = [2,6,7,8] # Sample Output # # arr = [1,2,3,4,5,6,7,8] # https://www.geeksforgeeks.org/python-list-sort/ # reverse, key # # https://www.geeksforgeeks.org/python-combining-two-sorted-lists/ # sorted() # heapq.merge class Challenge: def __init__(self): self.lst1 = [1,3,4,5] self.lst2 = [2,6,7,8] def merge_lists(self): ind1 = 0 ind2 = 0 while (ind1 < len(self.lst1) and ind2 < len(self.lst2)): if (self.lst1[ind1] > self.lst2[ind2]): self.lst1.insert(ind1, self.lst2[ind2]) ind1 += 1 ind2 += 1 else: ind1 += 1 if (ind2 < len(self.lst2)): self.lst1.extend(self.lst2[ind2:]) return self.lst1 def show(self): print(self.lst1) def run(self): self.merge_lists() self.show()
eb8490be3209b1f2467a2583b5b2c9c94a81416c
jO-Osko/Krozek-python
/srecanje3/fizzbuzz_obe.py
828
3.796875
4
# Uporabnik naj vpiše začetno število # Uporabnik naj vpiše končno število # Izpiši fizbuzz za števila med začetnim in končnim (lahko tudi padajoče) # 1, 2, Fizz, .... , 11 # 22, fizz, buzz, ...., 14 # Najprej preberite samo začetek in konec in izpišite samo st (brez fizzbuzz) zacetno = int(input("Vpiši začetek:")) konec = int(input("Vpiši konec:")) # Nastavimo si smer, ki jo bomo potrebovali v range if zacetno < konec: # ce je zacetno == konec je itak vseeno kaksna je smer smer = 1 else: smer = -1 for stevilo in range(zacetno, konec + smer, smer): if stevilo % 3 == 0 and stevilo % 5 != 0: print("Fizz") elif stevilo % 5 == 0 and stevilo % 3 != 0: print("Buzz") elif stevilo % 3 == 0 and stevilo % 5 == 0: print("Fizz Buzz") else: print(stevilo)
81045c32939f24b9aabc227325b73fe2c7ef3e5c
Kanupreet/Assignments
/task1/ques3.py
365
3.859375
4
print("Ques3") a = 25 b = 100 print("Original values of var1: " , a ) print("Original values of var2: " , b ) c=b b=a a=c print("After swapping with 3rd var") print("Final values of var1: " , a ) print("Final values of var2: " , b ) a , b = b, a print("After swapping without any var") print("Final values of var1: " , a ) print("Final values of var2: " , b )
165d224ca10d42abb73d853f4f41dbb5be0a2abb
huigoing/algorithm
/程序员面试宝典/33.碰撞的蚂蚁.py
868
3.671875
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 15:26:53 2019 @author: Tang """ ''' 题目描述 在n个顶点的多边形上有n只蚂蚁,这些蚂蚁同时开始沿着多边形的边爬行,请求出这些蚂蚁相撞的概率。 (这里的相撞是指存在任意两只蚂蚁会相撞) 给定一个int n(3<=n<=10000),代表n边形和n只蚂蚁,请返回一个double,为相撞的概率。 测试样例: 3 返回:0.75 思路:每个蚂蚁爬行的方向都有两个,即围绕多边形顺时针爬和逆时针爬,因此n个蚂蚁爬行的方法有2^n种。 只有当所有的蚂蚁按照同一个方向爬行才能保证所有的蚂蚁都不相撞,只有两种方法--都按逆时针或顺时针方向爬行。 所以相撞的概率为1 - (double)2 / (2 ^n) ''' def solution(n): sum=1<<n #左移 2*n return 1-2.0/sum
d49ca944df7235d90072c5f37ad89fb72e24a7b1
leizhen10000/learnPython
/python_improve/set_list.py
993
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by Zhen Lei on 2017/9/10 # set 是一个非常有用的数据接口。它与 list 的行为类似,区别在于 set 不能包含重复的值。 def show_repeat_key(): some_list = ['a', 'b', 'c', 'd', 'e', 'f', 'b', 'c', 'a'] duplicates = set([x for x in some_list if some_list.count(x) > 1]) print duplicates # 交集 def same_between_collection(): valid = set(['yellow', 'red', 'blue', 'green', 'black']) input_set = set(['red', 'brown']) print input_set.intersection(valid) # 比较两个集合的交集 # 差集 def difference_between_collection(): valid = set(['yellow', 'red', 'blue', 'green', 'black']) input_set = set(['red', 'brown']) print input_set.difference(valid) # 只会输出input_set 中不同的值 class SetAndList(): def __init__(self): pass if __name__ == '__main__': show_repeat_key() same_between_collection() difference_between_collection()
f93d28e3e7c6b5e6ffe9f23020e48e3b32ebc8a3
livetoworldlife/week01_pycodersnl
/3_Monthly_Expenses.py
404
3.859375
4
mon_inc=int(input("Write your monthly income value: ")) mon_exp=int(input("Write your monthly kitchen expenses: "))+\ int(input("Write your monthly education expenses: "))+\ int(input("Write your monthly clothing expenses: "))+\ int(input("Write your monthly transportation expenses: ")) print("your monthly expenses to the income = % "+str(mon_exp*100/mon_inc)) # The End
1df38b315160f6a467527359a4c5306ac9595576
eokeeffe/Python
/glob.py
308
3.609375
4
import os #merge all files in a directory into a single file path = 'Directory to read' listing = os.listdir(path) dictfile = open("somefile","w") for infile in listing: f = open(path+"\\"+infile,"r") for i in f.read(): dictfile.write(i) f.close() print "file: " + infile + " finished" dictfile.close()
953369a75b3abeea397a1c2f17c2dcf1c0813509
dinob0t/project_euler
/39.py
571
3.734375
4
import math def return_triangle_solutions(num): solns = 0 for a in range(1,num): for b in range(a,num): c = math.sqrt(a**2 + b**2) if is_whole(num) and a + b + c == num: solns += 1 return solns def is_whole(x): if x%1==0: return True return False def find_most_solns(max_num): current_max = 0 current_biggest = 0 for i in range(1,max_num): cur_solns = return_triangle_solutions(i) if cur_solns > current_biggest: current_biggest = cur_solns current_max = i return current_max if __name__ == "__main__": print find_most_solns(1000)
69e6b9c5d8ec1256c06d119ff6cb30cb179ff2a5
zhlinh/leetcode
/0001.Two Sum/solution.py
991
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-01-04 Last_modify: 2016-09-02 ****************************************** ''' ''' Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read the above updated description carefully. ''' class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} for i, v in enumerate(nums): if target-v in d: return [d[target-v], i] d[v] = i
ece65d366645fbccdaafcc2ecf0604f8c07755ee
ziyadalvi/PythonBook
/4Python Object Types/16MissingKeys(ifTests).py
1,183
4.5625
5
#as mappings, dictionaries support accessing items by key only. With sorts of #operations we've just seen. In addition, though, they also support type-specific #operations with method calls that are useful in variety of ocmmon usecases # For example, although #we can assign to a new key to expand a dictionary, fetching a nonexistent key #is still a mistake: D = {'a':1,'b':2,'c':3} print(D) print(D['a']) # print(D['d']) this will throw an error, as it is non existant array D['d'] = 99 print(D['d']) #The dictionary in membership expression allows us #to query the existence of a key and branch on the result with a Python if statement. #it consists of the word if, followed by an expression that #is interpreted as a true or false result print('f' in D) if not 'f' in D: print('missing') #Besides the in test, there are a variety of ways to avoid accessing nonexistent keys in #the dictionaries we create # 1: the get method # 2: the try statement # 3: the if/else epression value = D.get('x',0) #if x exists in D then print the value else assign 0 to value print(value) value = D.get('d',0) print(value) value = D['x'] if 'x' in D else 0 print(value)
6b16adea684b855a79a9462d6593d54b6bc786f2
pcowhill/Project-Euler-Python-Solutions
/Problem 12 Highly Divisible Triangle Number.py
514
3.828125
4
import math def pearl(divisors): current = 0 check = 0 adder = 1 track = 0 highest = 0 while check == 0: current = current + adder for i in range(1, int(math.sqrt(current))): if (current % i) == 0: track = track + 1 if track*2 > highest: highest = track*2 print(highest, current) if track*2 >= divisors: return current track = 0 adder = adder + 1
efe69eec4380f3041992e4b82eb1252f32876859
Purushotamprasai/Python
/Rohith_Batch/Operator/Logical Operator/001_understand.py
908
4.3125
4
# this file is understand for logical operators ''' Logical AND ---> and --------------------- Defination : ----------- if 1st input is false case then output is 1st input value other wise 2nd input value is the output Logical OR---> or --------------------- Defination : ----------- if 1st input is false case then output is 2st input value other wise 1st input value is the output Logicakl not ---> not --------------------- Defination : ----------- if 1st input is false case then output is True boolean data other wise False boolean data as on output ''' def main(): a = input("enter boolean data") # True b = input("enter boolean daata") # False print a ," logical and", b," is ", a and b print a , "logical or ",b, " is ", a or b print " logical not ", b ,"is " , not b if(__name__ =="__main__"): main()
ea127dc6ef04f1bc38719cef24fe90a1d9c258c4
psypig99/pyLec
/py3_tutorials/basic/037_lambda.py
268
4.125
4
""" lambda는 함수명이 존재하지 않으며 재활용성을 고려한 함수보다는 1회성으로 잠깐 사용하는 속성 함수라고 볼 수 있음 """ answer = lambda x: x**3 print(answer(5)) power = list(map(lambda x: x**2, (range(1,6)))) print(power)
e756bbf95d70e606d5e545e1918a1c386a1c7826
Simo0o08/Python-Assignment
/Python assignment/Module 4/Pattern/pattern1_12.py
285
3.765625
4
#Left Arrow Star Pattern n=int(input()) k=n i=n r=0 while(r<n): k=i while(k>=1): print("*",end=" ") k=k-1 i=i-1 print() k=i r=r+1 r=0 i=3 while(r<n-1): k=i while(k>1): print("*",end=" ") k=k-1 i=i+1 print() k=i r=r+1
5e3580db4235dd78feee73d89f447f2648c3ba12
AnubhavMadhav/Learn-Python
/20 Multithreading/usingSubClass.py
261
3.75
4
'''Create a Thread using sub class or we can say by extending the 'Thread' class''' from threading import Thread class MyThread(Thread): def run(self): i = 0 while i <= 10: print(i) i += 1 t = MyThread() t.start()
ffe1b836559137f9fb6183f07b1149087e8826fe
CateGitau/Python_programming
/ace_python_interview/lists/challenge_9.py
1,207
4.09375
4
# Rearrange Positive and Negative values ''' Implement a function which rearranges the elements such that all the negative elements appear on the left and positive elements appear on the right of the list. Note that it tis not necessary to maintain the sorted order of the input list NB: Zero in this case is trated as a positive integer ''' my_list = [10,-1,20,4,5,-9,-6] # My solution Using Auxiliary lists # O(n) def rearrange(lst): positive = [] negative = [] for i in lst: if i >= 0: positive.append(i) else: negative.append(i) return negative + positive print(rearrange(my_list)) # Rearranging in place def rearrange2(lst): leftMostElelent = 0 for curr in range(len(lst)): if (lst[curr] < 0): if (curr is not leftMostElelent): lst[curr], lst[leftMostElelent] = lst[leftMostElelent], lst[curr] leftMostElelent += 1 return lst print(rearrange2(my_list)) # Pythonic def rearrange(lst): # get negative and positive list after filter and then merge return [i for i in lst if i < 0] + [i for i in lst if i >= 0] print(rearrange([10, -1, 20, 4, 5, -9, -6]))
5db59819e2e75cd876a7cedf170b5339a51f9bf0
JayNemade/Python-Codes
/PProg2.py
430
3.8125
4
#Dealing with Strings sent = "Jay is {} yrs old" str = 'Hello, World' str2 = ' Hello World ' age = 14 print(str[4:8]) #strip() method to remove any whitespaces print(str2.strip()) #lower() and upper() method print(str.lower(),str.upper()) #replace() method print(str.replace("H","J")) #split() method to split a string into a array print(str.split(",")) #format() method to add a integer to a string print(sent.format(age))
f5fa16a4b2f3fc9f09f3b66c0b62bdfb8d8d2f01
Alin0268/Functions_in_Python
/Select_the_ith_smallest_element.py
1,208
3.78125
4
def select(my_list, start, end, i): """Find ith smallest element in my_list[start... end-1].""" if end - start <= 1: return my_list[start] pivot = partition(my_list, start, end) # number of elements in my_list[start... pivot] k = pivot - start + 1 if i < k: return select(my_list, start, pivot, i) elif i > k: return select(my_list, pivot + 1, end, i - k) return my_list[pivot] def partition(my_list, start, end): pivot = my_list[start] i = start + 1 j = end - 1 while True: while (i <= j and my_list[i] <= pivot): i = i + 1 while (i <= j and my_list[j] >= pivot): j = j - 1 if i <= j: my_list[i], my_list[j] = my_list[j], my_list[i] else: my_list[start], my_list[j] = my_list[j], my_list[start] return j my_list = input('Enter the list of numbers: ') my_list = my_list.split() my_list = [int(x) for x in my_list] i = int(input('The ith smallest element will be found. Enter i: ')) ith_smallest_item = select(my_list, 0, len(my_list), i) print('Result: {}.'.format(ith_smallest_item))
e8650be5da12d3b718f619ef95efbf3be2588ab6
PythonXiaobai1/python_project_1
/Task1.py
830
4.15625
4
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务1: 短信和通话记录中一共有多少电话号码?每个号码只统计一次。 输出信息: "There are <count> different telephone numbers in the records." """ #提取所有文件中的电话号码,并组成一个新集合 num = set() for nums in calls: num.add(nums[0]) num.add(nums[1]) for nums in texts: num.add(nums[0]) num.add(nums[1]) #计算集合长度 count = len(num) print("There are {} different telephone numbers in the records.".format(count))