blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8d12fdf11f17b95ce032459aa3f543b359d42ac2
ramyasutraye/pythonprogram-1
/beginner level/2smallest.py
140
3.8125
4
a=[] no=int(input("enter the total number of elements")) for i in range(no): a.append(int(input("Enter next no :"))) a.sort() print(a[1])
5790d961d40d18031708732e6d05fa4c13e02a02
Hayliiel/_Python_
/Abstract Data Types/Container.py
2,971
4.375
4
# -*- code: utf-8 -*- """ The class that i made is a simple container, it has the basic functions of most of container type class. It can store elements, you can use the insert function to add multiple elements at time or one by one and, you can manipulate the existing elements inside of it, by using see function to search and the delete function to delete elements by index or name. """ # Iterative binary search, can import from my other file. def binary_iterative(element, list_1): list_1.sort() lower = 0 upper = len(list_1) - 1 while lower <= upper: mid = int((upper + lower) / 2) if element == list_1[mid]: return mid elif element < list_1[mid]: upper = mid - 1 else: lower = mid + 1 return False class Container: def __init__(self): # Default constructor self.elements_list = [] def print(self): # Prints the whole container, prints "Empty!" if the list is empty if len(self.elements_list) == 0: print("Empty! )=") else: print(self.elements_list) def insert(self, element): # Inserts the desired element on the container self.elements_list.append(element) def insert_many(self): # Inserts X elements on the container try: print("How many elements do you want to insert") quantity = int(input("--> ")) print("Elements to insert: ") for element in range(0, quantity): element = input("--> ") self.elements_list.append(element) except (TypeError, ValueError): print("Please insert a number") def see(self, element): # Searchs an element on the container and returns it's index and what is it (If found) index = binary_iterative(element, self.elements_list) if index == False: print("Element not found") else: print("Element found at index: ", index) print("The element is: ", self.elements_list[index]) def size(self): # Prints the size of the container, returns the size print("This container have", len(self.elements_list), "elements") return len(self.elements_list) def delete_index(self, index): # Deletes an element based on the index try: self.elements_list.pop(index) except IndexError: print("Index out of range") def delete_element(self, element): # Deletes an element based on its name try: self.elements_list.remove(element) except ValueError: print("Element not found") def clear(self): # Erases the whole container self.elements_list.clear() def main(): container_test = Container() print("Which element you want to insert: ") element = input("--> " ) container_test.insert(element) container_test.print() container_test.insert_many() container_test.print() container_test.size() container_test.delete_index(20) container_test.delete_index(5) container_test.delete_element("14284") container_test.delete_element("10") container_test.see("324") container_test.see("6") container_test.print() container_test.clear() container_test.print() if __name__ == '__main__': main()
cf5cfddb3d941ef40db811fd205f5bb807199c64
makeitwayne17/ECE-Casino
/BLACKJACK.py
3,240
3.984375
4
#Victor's Casino (for now, we just have Blackjack) import random def enter_casino(): #lets player input name and choose game print("Welcome to the ECE Casino!") print("What is you name?") user_name = raw_input(">") print("Hi %s, what game do you want to play today?")%user_name.capitalize() user_game = raw_input(">") if user_game.lower() in ("blackjack","black jack","21"): print("Gotcha! One game of BLACKJACK coming right up...") play_blackjack() else: print("Sorry! We do not have that game yet. Please come back another day.") #main function to play blackjack def play_blackjack(): #cards are dealt deck = shuffle_deck() player_hand = [] dealer_hand = [] player_hand.append(deck.pop()) dealer_hand.append(deck.pop()) player_hand.append(deck.pop()) dealer_hand.append(deck.pop()) #hands are shown, sums are computed print("Your current hand is %s.") % str(player_hand) player_sum = get_hand_sum(player_hand) print("Your current sum is %s.") % str(player_sum) print("The dealer's first card is the %s with the second card face down.") % str(dealer_hand[0]) dealer_sum = get_hand_sum(dealer_hand) #checking "natural blackjack" if(player_sum==21 and dealer_sum!=21): print("BLACKJACK! You automatically beat the dealer who has a hand of %s.") % str(dealer_hand) print("Congratulations!") elif(player_sum==21 and dealer_sum==21): print("BLACKJACK! But the dealer also has BLACKJACK with a hand of %s.") % str(dealer_hand) print("TIE GAME!") elif(player_sum!=21 and dealer_sum==21): print("You automatically lose to the dealer who has BLACKJACK with a hand of %s.") % str(dealer_hand) print("SORRY!") #player choice to HIT or STAND else: print("Do you wish to HIT or STAND?") player_choice = "" while(player_choice.lower()!="hit" and player_choice.lower()!="stand"): player_choice = raw_input(">") if(player_choice.lower()!="hit" and player_choice.lower()!="stand"): print("That is not a valid option! Please choose either HIT or STAND.") player_choice = raw_input(">") print(player_choice) #player HIT #player STAND def shuffle_deck(): #returns a freshly shuffled deck of cards (list) card_values = ['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King'] card_types = ['Spades','Diamonds','Hearts','Clubs'] deck = [] for i in card_types: for j in card_values: deck.append(j+' of '+i) random.shuffle(deck) print("A new deck of cards has been shuffled.") return deck def get_card_value(card,dealer=False): #returns the value of the drawn card (int) card = card.split(' ')[0] if card in ('Jack','Queen','King'): return int(10) elif(card=='Ace' and not dealer): print("You drew an ACE! Do you want the value to be 1 or 11?") choice = raw_input(">") while(True): if choice == '1': return int(1) elif choice == '11': return int(11) else: print("That is not a valid option! Please choose either 1 or 11.") choice = raw_input(">") elif(card=='Ace' and dealer): #better logic for choosing dealer ACE value!!! return int(1) else: return int(card) def get_hand_sum(hand): hand_sum = 0 for i in hand: hand_sum = hand_sum + get_card_value(i) return hand_sum #player enters the casino enter_casino()
625f59c9c724dae8851fef5bb3f6a9c517407136
Dharani-18/CODEKATA
/pgm/sumofdigits.py
84
3.546875
4
a=int(input()) sum=0 while a>0: r=a%10 sum=sum+r a=a//10 print(sum)
2de31586b0e3fccfeeec2d4927eab50206c0deb1
affaau/myexamples
/regex_example/clean_file.py
743
3.828125
4
'''Remove all non-alphanumberic character(s) in file name - replace with underscore '_' ''' import re import os def clean_filename(name): '''Replace non-alphanumberic character(s) with an underscore "_" ''' return re.sub(r'[\-\.,_ ]+', '_', name) def check_cleaned_filenames(ls): '''Pass in list of file names - print out how new names look like ''' for file in ls: f, e = os.path.splitext(file) fn = clean_filename(f) if e != '': ext = '.' + clean_filename(e[1:]) else: ext = '' print("file: '{}'".format(file)) print("new file: '{}{}'".format(fn, ext)) print('') if __name__ == '__main__': files = ["abc def- ghi_jkl. mno.pqr", " _d, 562. z_-,p", "apple"] check_cleaned_filenames(files)
0796539c4bfc0d5fcb403f01cbfeabd1cf0b6e92
0x0all/coding-challenge-practices
/python-good-questions/frequency_str.py
2,161
4.125
4
import string import collections input_text = """In bed we concocted our plans for the morrow. But to my surprise and no small concern, Queequeg now gave me to understand, that he had been diligently consulting Yojo, the name of his black little god, and Yojo had told him two or three times over, and strongly insisted upon it everyway, that instead of our going together among the whaling-fleet in harbor, and in concert selecting our craft; instead of this, I say, Yojo earnestly enjoined that the selection of the ship should rest wholly with me, inasmuch as Yojo purposed befriending us; and, in order to do so, had already pitched upon a vessel, which, if left to myself, I, Ishmael, should infallibly light upon, for all the world as though it had turned out by chance; and in that vessel I must immediately ship myself, for the present irrespective of Queequeg. I have forgotten to mention that, in many things, Queequeg placed great confidence in the excellence of Yojo's judgment and surprising forecast of things; and cherished Yojo with considerable esteem, as a rather good sort of god, who perhaps meant well enough upon the whole, but in all cases did not succeed in his benevolent designs.""" def word_freq(input_text): """ Performs a frequency count of words in a block of text Input: input_text : block of text Output: dictionary. keys are the unique words in the text values are the count of those words """ return collections.Counter([x.strip(string.punctuation).lower() for x in list(input_text.split())]) def top_N(word_dict, N=5): """ Selects the N most frequent words (i.e., the words with the highest count) from the word count dictionary Input: word_dict : dict returned by word_freq() N : number of items to select. Defaults to 5 Output: list of tuples. Each tuple is (word, count). E.g., ('coconut', 42) """ values = sorted(word_dict.items(), key=lambda x: x[1], reverse=True) return values[:N] if __name__ == '__main__': word_dict = word_freq(input_text) print top_N(word_dict)
a84fa1de2dd0718e341dd832b8016ba401833f3d
aksenof/infotecs
/algorithm.py
513
3.953125
4
def factorization(n): # функция для разложения числа на простые множители r = n i = 2 result_list = [] while i*i <= n: while n % i == 0: result_list.append(int(i)) n = n/i i = i+1 if n > 1: result_list.append(int(n)) # print(result_list) if len(result_list) == 1: result = "{} = 1 * {}".format(r, r) else: result = "{} = {}".format(r, ' * '.join(map(str, result_list))) if r < 2: result = "error, try again" return result
4aa712c5ba2fc9e8431ee181c850df1078fa8078
bensenberner/ctci
/dynamic_recursive/minCoins.py
479
3.71875
4
def minCoins(coinArr, n): # trying to make n cents using the coin denominations in coinArr table = [float('inf') for x in range(n+1)] table[0] = 0 for i in range(len(table)): for coin in coinArr: if coin <= i: if table[i-coin] != float('inf') and table[i-coin]+1 < table[i]: table[i] = table[i-coin]+1 return table[-1] def main(): coins = [6, 9, 20] n = 7 print(minCoins(coins, n)) main()
999fe101ac3ab6c15bea9e1233dbf31e990cb060
maturivinay/python_lee
/ICP_5/linear_expression.py
1,038
3.9375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt print(pd._version) # x = np.array([0,1,2,3,4,5,6,7,8,9]) # y = np.array([1,3,2,5,7,8,8,9,10,12]) dataframe = pd.read_excel('C:\\Users\matur\Desktop\\UMKC\python_lee\ICP_5\SimpleLinear Regression.xls') # print(dataframe.head[14]) x=dataframe.X y=dataframe.Y #mean value of x and y meanOfX = sum(x)/len(x) meanOfy = sum(y)/len(y) #calculating slope slope = np.sum((x - meanOfX)*(y - meanOfy))/np.sum(np.square(x-meanOfX)) #calculating intercept intercept = meanOfy - (slope * meanOfX) #y output yOutput = (slope * x) + intercept #change default fig size plt.figure(figsize=(10,10)) plt.scatter(x,y) plt.plot(x,y,"ro") # plotting the line made by linear regression plt.plot(x, yOutput, color="red",linewidth=4) plt.xlabel("X:national unemployment rate for adult males",fontsize=20) plt.ylabel("Y:national unemployment rate for adult females",fontsize=20) #font size of the number lables on the axes plt.xticks(fontsize=18) plt.yticks(fontsize=18) plt.show()
bd50d87e7693f9ccdd461849b2875df146ba02e3
mohrtw/algorithms
/algorithms/tests/test_graph.py
2,880
3.78125
4
import unittest from unittest import TestCase # from unittest import skip from algorithms.dataStructures.graph import graph class graphTest(TestCase): def setUp(self): arcList = [[1, 2], [1, 3], [1, 4], [2, 1], [3, 2], [3, 5], [5, 1]] self.G = graph(arcList) def test_can_check_if_vertex_is_in_graph(self): # returns True if vertex is in graph truthy = self.G.check_vertex(1) self.assertTrue(truthy) truthy = self.G.check_vertex(2) self.assertTrue(truthy) truthy = self.G.check_vertex(3) self.assertTrue(truthy) truthy = self.G.check_vertex(4) self.assertTrue(truthy) truthy = self.G.check_vertex(5) self.assertTrue(truthy) # returns False if vertex is not in graph truthy = self.G.check_vertex(0) self.assertFalse(truthy) truthy = self.G.check_vertex(-2) self.assertFalse(truthy) truthy = self.G.check_vertex(6) self.assertFalse(truthy) truthy = self.G.check_vertex('a') self.assertFalse(truthy) def test_can_check_if_arc_in_graph(self): v, a = 1, 2 truthy = self.G.check_arc(v, a) self.assertTrue(truthy) v, a = 3, 5 truthy = self.G.check_arc(v, a) self.assertTrue(truthy) v, a = 1, 5 truthy = self.G.check_arc(v, a) self.assertFalse(truthy, self.G.arcs) v, a = 0, 2 truthy = self.G.check_arc(v, a) self.assertFalse(truthy) def test_can_add_vertex_to_graph(self): v = 8 truthy = self.G.check_vertex(v) self.assertFalse(truthy) self.G.add_vertex(v) truthy = self.G.check_vertex(v) self.assertTrue(truthy) def test_can_add_arc_to_existing_vertex(self): v, a = 1, 5 truthy = self.G.check_vertex(v) and self.G.check_vertex(a) self.assertTrue(truthy) self.G.add_arc(v, a) truthy = self.G.check_arc(v, a) self.assertTrue(truthy) def test_remove_vertex(self): v = 1 truthy = self.G.check_vertex(v) self.assertTrue(truthy) self.G.remove_vertex(v) truthy = self.G.check_vertex(v) self.assertFalse(truthy) def test_remove_arc(self): v, a = 1, 2 truthy = self.G.check_arc(v, a) self.assertTrue(truthy) self.G.remove_arc(v, a) truthy = self.G.check_arc(v, a) self.assertFalse(truthy) truthy = self.G.check_vertex(v) self.assertTrue(truthy) truthy = self.G.check_vertex(a) self.assertTrue(truthy) def test_get_list_of_a_vertexs_arcs(self): v = 1 vArcs = self.G.get_arcs(v) self.assertEqual(vArcs, [2, 3, 4]) if __name__ == '__main__': unittest.main()
9bb4900d5f2fc16065e75343f70741f8631b5360
HectorGarciaPY/primer1.py
/IA9.3.py
281
3.796875
4
def comptarLletra(adn,lletra): cops=0 for i in adn: if i==lletra: cops=cops+1 return cops adn=["A","A","A","G","A","A","A","G","T","C","T","G","A","C","T","C","T","G","A","C"] lletra = input("Entra la lletra que vols comptar: ").upper() print(comptarLletra(adn,lletra))
2485e2980db6bb4b693b11459c76c67b33c18af1
ftorob/MisionTICS120210639-G09
/Ciclo 1/S120210503.py
4,881
4
4
# Declaramos la variable de tipo ENTERO var_int = 50 # Declaramos la variable de tipo FLOAT | DOBLE | Flotante o número decimal var_pi = 3.1416 # Declaramos la variable de tipo CADENA DE TEXTO | STRING var_str = "Grupo 39" # Declaramos a variable de tipo buleano FALSO | VERDADERO | 1 | 0 var_boo = False # corchete crear variable de diccionario {} var_dict = {"nombre":"juliana" , "apellido":"Correa" , "edad": 19} # Declaramos una variable de tipo TUPLA | TUPLE var_tup = (3, 4, 5, 7.8, 10) print(type(var_tup)) #print(type(var_dict)) para saber el tipo de variable sino se está seguro ''' print(type(var_int)) print(type(var_pi)) print(type(var_str)) print(type(var_boo)) print(type(var_dict)) ''' #Función DIR (Python tiene una función llamada dir que enumera los métodos disponibles para un objeto.) cadena = '¡Holi!' print(dir(cadena)) # Corchete para crear o modificar item del diccionario [] var_dict ["nombre"] = "Fernando" # agregar nuevo campo al diccionario var_dict["peso"] = 60 # eliminar un campo del diccionario var_dict.pop('apellido') # Imprimir una cadena de texto concatenada con variables print("El nombre de la persona es " + var_dict['nombre'] + " y tiene " + str(var_dict['edad']) + " años") print(var_dict) # hacer la lista vertical var_dict = { "nombre":"juliana" , "apellido":"Correa" , "edad": 19 } # f permite agregar variables a un string print(f"El nombre de la persona es {var_dict['nombre']} y tiene {var_dict['edad']} años") # se coloca el string y las variables luego con la función FORMAT print("El nombre de la persona es {} y tiene {} años".format(var_dict['nombre'], var_dict['edad'])) ''' para diccionarios ={} para listas=[] para tuplas=() ''' # Declarar variables FLOAT var1 = 1.20 print(var1) # Oligar a que lavariable sea un entero # Castiar variables de FLOAT o ENTERO (convertir de un dato a otro) var1 = int(var1) print(var1) ''' Errores al declarar variables - Dejar espacio var 1 = 8 - Usar caracteres especiales var@ = 8 - Usar número al inicio de la variable 1var = 8 - Usar guíon al medio var-1 (incorrecto) vs var_1 (correcto) var-1 = 8 ''' # Declarar tres variables con el mismo valor (Asignación de un solo valor a varias variables) num_1 = num_2 = num_3 = 200 print(num_3) # Declarar variables en sentido horizontal (Asignar varios valores a varias variables) num_x1, num_x2, num_x3 = 10, 85, 4.6 print(num_x3) print(num_x2) print(num_x1) ''' Operadores básicos + Suma - Resta * Multiplicación / División // División enteros ** Potencia () Parentesis ''' nota1 = 3.4 nota2 = 4 nota3 = 2.6 nota4 = 4.7 # Operaciones básicas var_suma = nota1 + nota2 + nota3 + nota4 #suma print(var_suma) var_resta = nota2 - nota4 #resta print(var_resta) var_multi = nota2 * nota1 #multiplicación print(var_multi) var_divi = nota4 / nota1 #división print(var_divi) var_divent = nota4 // nota1 #división entero print(var_divent) var_divres = nota4 % nota1 #residuo de la división print(var_divres) var_cuadrado = nota2 ** 2 #potencia al cuadrado print(var_cuadrado) var_cubico = nota2 ** 3 #potencia al cubo print(var_cubico) var_cinco = 2 ** 5 #potencia a la cinco print(var_cinco) var_raiz = var_cubico ** (1/2) #raiz cuadrada de un número print(var_raiz) # Orden en que ocurren las operaciones PEMDAS (PARENTESIS + EXPONENCIACIÓN + MULTIPLICACIÓN + DIVISIÓN + SUMA + RESTA) var_PEMDAS = 4 + 7 * 2 ** (5 - 10) / 2 print(var_PEMDAS) var_PEMDAS2 = 4 + 7 * 2 ** (10 - 5) / 2 print(var_PEMDAS2) promedio = ((nota1 + nota2 + nota3 + nota4)/4) print(promedio) print(round(promedio,2)) # Redonear a dos cifras print(round(promedio,1)) # Redondear a una cifra # Ejercicios rápidos # 1) ¿Que imprime el siguiente programa ? var_x1 = 43 var_x1 = var_x1 + 1 print(var_x1) # 2) Calcule el promedio de las siguientes variables var_a = 10 var_b = 4 var_c = 5.5 var_d = 67 # 3) Calcule el área y perímetro de un cuadrado var_lado = 38 var_area = var_lado ** 2 var_perimetro = var_lado * 4 print("El área del cuadrado es " + str(var_area) + " m2" + "y su perímetro es de " + str(var_perimetro) + " m.") var_promejer = (var_a + var_b + var_c + var_d)/4 print("El promedio de esos números es " + str(var_promejer)) # Funciones de Python promedio_fsum = (sum((nota1, nota2, nota3, nota4))/4) print(round(promedio_fsum,2)) print(int("2021") + 9) # Conveetir un str a número entero y sumarlo nota_max = max(nota1, nota2, nota3, nota4) # Máximo de un conjunto de datos print(nota_max) nota_min = min(nota1, nota2, nota3, nota4) # Mínimo de un conjunto de datos print(nota_min) help(max) # La función HELP me dice como debo construir una función x = range(5,100) print(x) print(len(x)) texto = "QF, QF" #cuenta el número de caracteres de una frase print(len(texto)) numb = (3, 4, 5, 6, 7) #cuenta el número de números en una lista o rango x = len(numb) print(x)
c1ccf5bdf2a6dcb35136f858270f398d8244c0e8
ABalanuta/challenges
/bus-station/solutions/bus-station-python-solution.py
900
3.734375
4
import os import sys import sys def fit(array, bus_length): pos = 0 bucket = 0 while pos < len(array): if array[pos]+bucket == bus_length: pos += 1 bucket = 0 elif array[pos]+bucket > bus_length: return False else: bucket += array[pos] pos += 1 if bucket == 0: return True else: return False if __name__ == "__main__": lines = sys.stdin.readlines() n = int(lines[0]) a = map(int, lines[1].split()) min_bus_len = 1 max_bus_len = sum(a) #print min_bus_len, max_bus_len #array that will store the possible bus lengths bus_lenghts = [] for l in range(min_bus_len, max_bus_len): #Exclude bus length if cannot fit the biggest group if max(a) > l: continue #Excludes if the groups do not fit exactly the bus elif not fit(a, l): continue else: bus_lenghts.append(l) bus_lenghts.append(max_bus_len) for l in bus_lenghts: print l,
95462e1db82382fbd37b421a7c20083bf20edb2f
adviksinghania/cfc-assignments-pyboot
/assignment-1/q7_e.py
243
3.53125
4
#!/usr/bin/env python3 # q7_e.py # 1 # 1 1 # 1 2 1 # 1 3 3 1 # 1 4 6 4 1 n = int(input('Enter a number: ')) for i in range(1, n + 1): c = 1 for j in range(1, i + 1): print(c, end=' ') c = c * (i - j) // j print()
894644a0e14cd3d95b3b2480bb2452cd8a3c362f
deepakmarathe/whirlwindtourofpython
/controlflow/for.py
316
4.25
4
# Control flow statements : for loop for i in [1, 2, 3]: print i print "---------done-----------" # range is a sequence/iterator for i in range(10): print i print "------ done -----" for i in range(5, 10): print i print "------ done ------" for i in range(5, 15, 2): print i print "------ done -------"
6e883828ed5f7900b04dfd3d521f3139b30f3a03
xiaohaiz1/PythonStudy
/Python编程思想/4.控制结构/控制流/while语句.py
617
3.625
4
''' while语句: 格式: while 表达式: 语句 逻辑:当程序执行到while语句时,首先计算“表达式”的值, 如果“表达式”的值为假,那么结束整个while语句, 如果表达式的值为真,则执行语句,再执行表达式,并判断真假,同理往上 直到为假跳出循环 ''' ''' 计算1+2+3+...+100 ''' sum = 0 num = 1 while num<=100: sum += num num +=1 print("sum =", sum) ''' 逐个打印字符串中的字符 ''' str = "lxr is a good man" index = 0 while index < len(str): print("str[%d] = %s" % (index, str[index])) index +=1
c9e2dcbe9ecbc147bcf16c057241384c2d093a10
sandymnascimento/Curso-de-Python
/Aula 15/ex070.py
714
3.546875
4
soma = contP = cont = p = 0 mbarato = '' while True: print('\033[1m=' * 25) print(' ' * 8, 'PY STORE') print('\033[1m=\033[m' * 25) nome = str(input('Digite o nome do produto: ')) preco = float(input('Digite o preço do produto: ')) while res not in 'sn': res = input('Deseja comprar outro produto? ').strip().lower()[0] soma += preco contP += 1 if preco > 1000: cont += 1 if mbarato == '' or preco < p: mbarato = nome p = preco if res == 'n': break print(f'Você comprou {contP} produtos e total da compra é R${soma:.2f}') print(f'{cont} produtos custam mais de R$1000,00') print(f'O produto mais barato é {mbarato} e custa R${p:.2f}')
36edf3841eb0b09cbb67c9041f8b18d4e4cdd381
bphillab/Five_Thirty_Eight_Riddler
/Riddler_20_02_21/Riddler_Express_20_02_21.py
1,106
4.125
4
""" From Nick Harper comes a question of tempered temperatures: On a warm, sunny day, Nick glanced at a thermometer, and noticed something quite interesting. When he toggled between the Fahrenheit and Celsius scales, the digits of the temperature — when rounded to the nearest degree — had switched. For example, this works for a temperature of 61 degrees Fahrenheit, which corresponds to a temperature of 16 degrees Celsius. However, the temperature that day was not 61 degrees Fahrenheit. What was the temperature? """ from math import floor, ceil def convert_C_to_F(C): return C * 9 / 5 + 32 def convert_F_to_C(F): return (F - 32) * 5 / 9 if __name__ == "__main__": for i in range(100): f_i_f = floor(convert_C_to_F(i)) f_i_c = ceil(convert_C_to_F(i)) i_str = list(str(i)) i_str.sort() f_i_c_str = list(str(f_i_c)) f_i_c_str.sort() f_i_f_str = list(str(f_i_f)) f_i_f_str.sort() if i_str == f_i_c_str or i_str == f_i_f_str: print("potential Cel: ", i, " ", convert_C_to_F(i), " ", f_i_f, " ", f_i_c)
7ad2fe4066ba0fc0c3dfa03d182dcf73d043e0c6
deesaw/PythonD-06
/Object Oriented Programming/classes1.py
1,425
3.953125
4
class Employee(object): company="Synechron" def __init__(self,eid,name,mobile): # constructor self.eid=eid self.name=name self.mobile=mobile def getmobile(self): print self.mobile def setmobile(self,mobile): self.mobile=mobile ramesh=Employee('223','Ramesh Sannareddy','9885970033') print type(ramesh) ramesh.getmobile() ramesh.setmobile('9866309211') ramesh.getmobile() print isinstance(ramesh,Employee) #class with static emp count class Employee(object): company="Cisco" __empcount=0 def __init__(self,id,name,mobile): # constructor self.id=id self.name=name self.mobile=mobile Employee.__empcount+=1 def get_mobile(self): print self.mobile def set_mobile(self,mobile): self.mobile=mobile ramesh=Employee('223','Ramesh Sannareddy','9885970033')#create a new employee print Employee.__empcount Employee._empcount=6789 print Employee.__empcount #class with static method get emp count class Employee(object): company="Cisco" _empcount=0 def __init__(self,id,name,mobile): # constructor self.id=id self.name=name self.mobile=mobile Employee._empcount+=1 def get_emp_count(): print Employee._empcount get_emp_count=staticmethod(get_emp_count) def get_mobile(self): print self.mobile def set_mobile(self,mobile): self.mobile=mobile def __str__(self):#used when the object is printed return str(self.id) + " " + self.name + " " + str(self.mobile) Employee.get_emp_count()
b96d8a11194a0d67febbd8bb256d288be2eb9a72
yaoshunqing/Python-fluent
/5/function.py
497
3.796875
4
# encoding= utf-8 # @Time : 2020/5/14 18:55 # @Author : Yao # @File : function.py # @Software: PyCharm def factorial(n): return 1 if n < 2 else n * factorial(n - 1) print(type(factorial)) def reverse(word): return word[::-1] print(reverse('Hello')) print(list(map(factorial, range(6)))) print(list(map(factorial, filter(lambda n: n % 2, range(6))))) #使用列表推导替换map或filter print([factorial(n) for n in range(6)]) print([factorial(n) for n in range(6) if n % 2 ])
af7835a8e563627d173153e9a3e0fb9bdde6768b
digipodium/string-and-string-functions-StutiLall12
/q23.py
185
4.3125
4
#ask user to enter a string and check if the string contains fyi str=input("enter a string") if str.__contains__('fyi'): print("fyi present") else: print("fyi not present")
6a032782f56d0390d8f0ce11044c867cc8637f15
snail15/AlgorithmPractice
/LeetCode/Python/countPrimes.py
476
3.5625
4
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ prime = [True for x in range(n)] primeCount = 0 for i in range(2, n): if prime[i] == True: primeCount += 1 current = i while current < n: prime[current] = False current += i return primeCount
38fc6d3695fbc09120dcb064e7bae234d8536f8b
derekjhunt/pygame_example_for_darren
/game.py
1,623
3.625
4
#!python # Let's import libraries import pygame from pygame.locals import * #import cars #import weapons #import land # Let's startthe game engine pygame.init() width, height = 900, 507 player_position = [220,180] keys = [False, False, False, False] # initalize the screen screen=pygame.display.set_mode((width, height)) # Load our character sprite player = pygame.image.load("files/sprites/5.png") level = pygame.image.load("files/tileset/level1.png") # The main game loop while 1: # let's wipe the screen so we can draw on it screen.fill(0) screen.blit(level,(0,0)) # Draw our player at these coordinates screen.blit(player,player_position) # update the screen pygame.display.flip() # loop through all of our events for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.quit() exit(0) # If we're pressing keys - WASD if event.type == pygame.KEYDOWN: if event.key==K_w: keys[0]=True elif event.key==K_a: keys[1]=True elif event.key==K_s: keys[2]=True elif event.key==K_d: keys[3]=True if event.type == pygame.KEYUP: if event.key==pygame.K_w: keys[0]=False elif event.key==pygame.K_a: keys[1]=False elif event.key==pygame.K_s: keys[2]=False elif event.key==pygame.K_d: keys[3]=False #move our guy around if keys[0]: player_position[1]-=5 elif keys[2]: player_position[1]+=5 if keys[1]: player_position[0]-=5 elif keys[3]: player_position[0]+=5
db5a403100b82ecce2cbc2f057dfe88bacfe2103
dineshbalachandran/mypython
/src/study/iterators.py
1,355
3.984375
4
''' Created on 20Jul.,2017 @author: DINESHKB ''' class Node(object): def __init__(self, value, left, right): self._value = value self._left = left self._right = right @property def value(self): return self._value @property def left(self): return self._left @left.setter def left(self, left): self._left = left @property def right(self): return self._right @right.setter def right(self, right): self._right = right def __iter__(self): return inorder(self) # a recursive generator def inorder(node): if node: for x in inorder(node.left): #print('left') yield x yield node for x in inorder(node.right): #print('right') yield x def generateTree(): root = Node(0, None, None) n = root for i in range(1, 5): l = Node(i, None, None) r = Node(i+10, None, None) n.left = l n.right = r n = l return root if __name__ == '__main__': root= generateTree(); it = iter(root) for j in it: print (j.value)
8cfee98c50a7548f5bb639028dd4677dc6959393
LegionAnkit/Gist_Of_Python
/Basics(conditional,iteration etc.)/LengthConverter1.py
203
4.15625
4
print("Enter the length in metre") metre=input() kms=float(metre)/1000 miles=kms/1.609 roundkms=round(kms,2) roundmiles=round(miles,2) print(f"{metre}m is equal to {roundkms}km and {roundmiles}mi")
0a6b8d0f2c4417082e3f307896a4093827ecfaf2
nikitabisht/AA6
/assign6.py
1,043
3.890625
4
#question1 for i in range(10): a=int(input("enter the values:")) print(i) #end #question2 while(True): print("nikita") #end #question3 l=[] a=int(input("enter the input")) b=int(input("enter the input")) l.append(a) l.append(b) for i in l: print(i**2) #question4 l=(([1,2],("string"),[1.2,1.3])) for i in (l): a=[] b=[] c=[] print(*l,sep="\n") break #end #question5 even_number=[] odd_number=[] for number in range (1,101): if number % 2 == 0: even_number.append(number) else : odd_number.append(number) print("even number :",even_number) print("odd number :",odd_number) #question6 for i in range(0,5): for j in range(0,i+1): print("*",end="") print() #question7 dictionary={'niki':'name','shivi':'name2'} for i in dictionary: dictionary.get(i) print(i) #question8 l=[] for i in range(0,5): num=int(input("enter the number:")) l.append(num) print(l) l2=[] a=int(input("enter the value:")) x=l.index(3) x=l.remove(3) print(l)
b9c9195c039b8ccb1ec17cf6215e5cd87f9105b7
gitzym/practice_code
/nowcoder_offer/29-minknum.py
1,887
3.640625
4
class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here if len(tinput) < k: return [] tinput.sort() return tinput[:k] class Solution_heap: def GetLeastNumbers_Solution(self, tinput, k): # write code here if len(tinput) < k: return [] heap = self.init_heap(tinput[0:k]) for y in tinput[k:]: if y < heap[0]: heap[0] = y heap = self.adjustHeap(heap) return sorted(heap) def init_heap(self,heap): for x in range(int((len(heap)/2)) - 1, -1,-1): print(x) heap[x:] = self.adjustHeap(heap[x:]) return heap def adjustHeap(self,heap): print('init :',heap) length = len(heap) last_node = int(length/2) - 1 i = 0 while i <= last_node: root = i left = 2 * i + 1 # right = left + 1 if left + 1 < length and heap[left + 1] > heap[left]: left += 1 # left: right node if heap[root] < heap[left]: heap[root], heap[left] = heap[left],heap[root] print(heap[root] , heap[left], heap[left] if left + 1 < length else -1) print('heap: ',heap) i += 1 print('--adjust done--') return heap class Solution_quickSort: def GetLeastNumbers_Solution(self, tinput, k): return self.quickSort(tinput)[:k] def quickSort(self, numbers): if len(numbers) <= 1: return numbers privot = numbers[0] left = [x for x in numbers[1:] if x <= privot] right = [x for x in numbers[1:] if x > privot] return left + [privot] + right ll = [4,5,1,6,2,7,3,8] # s = Solution_heap() s = Solution_quickSort() rr = s.GetLeastNumbers_Solution(ll,4) print(rr)
96f5857a2f9b326cc07402e06668da4ba3721306
Aasthaengg/IBMdataset
/Python_codes/p03289/s759699659.py
144
3.8125
4
S = input() if S[0] == 'A' and S.count('C', 2, -1) == 1 and S.replace('A', '').replace('C', '').islower(): print('AC') else: print('WA')
f54b3c57ce611577318e3aaa547613485cfc1047
cyrilvincent/pollen
/18-2-xor.py
342
3.6875
4
import numpy as np X=np.array([[0,0],[0,1],[1,0],[1,1]],dtype=float) y=np.array([0,1,1,0],dtype=float) from sklearn.neural_network import MLPClassifier mlp = MLPClassifier(hidden_layer_sizes=(3,3,3), activation="tanh", learning_rate="adaptive", alpha=1e-5) mlp.fit(X,y) print(mlp.score(X, y)) predictions = mlp.predict(X) print(predictions)
65b066eb78832b754c47d319faa7522a7875c976
HidoCan/Programlama_dilleri_yaz_okulu
/2018/b2018.py
353
3.78125
4
a = int(input("Mevcut Sicaklik : ")) while True: b = int(input("Tahmin Degeri 1: ")) c = int(input("Tahmin Degeri 2 : ")) if b >= c: continue else: min = a + b max = a + c print("Sicakligin alabilecegi min deger : ",min) print("Sicakligin alabilecegi max deger : ",max) break
3b98123c0fd6003ce099fb3d6471bf47830d79e8
sanjayait/core-python
/04-Chapter 4/funtion_in_func.py
159
3.578125
4
def greater(a,b): if a>b: return a return b def greatest(a,b,c): return greater(greater(a,b),c) print(greatest(106,105,25))
547bb53fbbe4d68c2ab59cf07cfe728e4b95921b
ekurpie/ekurpie.github.io
/Hashing and Nth Largest/tenthOrder.py
1,384
3.859375
4
import math import statistics import random def tenthOrder(A, ith = 10): """ This function returns the tenth order statistic from a list. It was created with the idea that a linear time median function could be used instead of the statistics.median as statistics.median creates substantial problems. :param A: :param ith: :return: """ if len(A) <= 5: B = sorted(A) return B[ith - 1] pivot = int(statistics.median(A)) q = 0 dif = float("inf") for i in range(len(A)): if abs(pivot - A[i]) < dif: dif = abs(pivot - A[i]) q = i pivot = A[q] A[q], A[0] = A[0], A[q] leftmark = 1 rightmark = len(A)-1 while True: while leftmark <= rightmark and A[leftmark] <= pivot: leftmark = leftmark + 1 while leftmark <= rightmark and A[rightmark] >= pivot: rightmark = rightmark - 1 if leftmark <= rightmark: A[leftmark], A[rightmark] = A[rightmark], A[leftmark] else: break A[0], A[rightmark] = A[rightmark], A[0] if ith > rightmark: return tenthOrder(A[rightmark+1:],ith - rightmark - 1) else: return tenthOrder(A[:rightmark],ith) lst = [] for i in range(30): lst.append(random.randint(0,1000)) print(lst) print(tenthOrder(lst)) b =sorted(lst) print(b) print(b[9])
f63674cef603fd6f462791733ed1566100dc0f56
cnlong/everyday_python
/19_chat-room/asyncio/test2.py
1,518
3.921875
4
""" 阻塞和await 1.使用async可以定义协程对象,使用await可以针对耗时的操作进行挂起,就像生成器里的yield一样,函数让出控制权。协程遇到await,事件循环将会挂起该协程,执行别的协程,直到其他的协程也挂起或者执行完毕,再进行下一个协程的执行 2.耗时的操作一般是一些IO操作,例如网络请求,文件读取等。我们使用asyncio.sleep函数来模拟IO操作。协程的目的也是让这些IO操作异步化。 3.遇到sleep,模拟阻塞或者耗时动作,让出控制权。即当遇到阻塞调用的函数时候,使用await方法将协程的控制权让出,以便loop调用其他的协程 """ import time import asyncio # 定义用于计算时间戳的函数 def now(): return time.time() # 定义一个函数,并且是协程对象,内部增加耗时动作 async def do_some_work(x): print("waiting:", x) # 通过asyncio.sleep函数模拟io操作,增加耗时动作 # 使用await对耗时动作进行挂起,类似于yield,函数让出主动权。 # 协程遇到await,事件循环挂起该协程,执行别的协程,直到其他的协程也挂起或者执行完毕,再进行下一个协程 await asyncio.sleep(x) return "Done after {}s".format(x) start = now() coroutine = do_some_work(2) loop = asyncio.get_event_loop() task = asyncio.ensure_future(coroutine) loop.run_until_complete(task) print("task ret:", task.result()) print("time:", now() - start)
7ae8e249de284b7f828fc4711fe379649920e003
deepubansal/books-python-wrappers
/books/model/InvoiceCreditedList.py
673
3.53125
4
#$Id$# class InvoiceCreditedList: """This class is used to create object for invoice credited list.""" def __init__(self): """Initialize parameters for invoice credited list object.""" self.invoices_credited = [] def set_invoices_credited(self, invoice_credited): """Set invoices credited. Args: invoice_credited(instance): Invoice credited. """ self.invoices_credited.append(invoice_credited) def get_invoices_credited(self): """Get invoices credited. Returns: list of instance: List of invoice credited. """ return self.invoices_credited
9fa85870b0fe4835f01c668eef7be4acef15ece2
dhsong95/programmers-algorithm-challenges
/2019 카카오 개발자 겨울 인턴십/징검다리 건너기.py
584
3.671875
4
def possible_to_cross(stones, k, n): jump = 0 for stone in stones: if stone < n: jump += 1 else: jump = 0 if jump >= k: return False return True def solution(stones, k): left = min(stones) right = max(stones) while left < right: middle = (left + right) // 2 if possible_to_cross(stones, k, middle): left = middle + 1 else: right = middle - 1 return right if __name__ == '__main__': assert solution([2, 4, 5, 3, 2, 1, 4, 2, 5, 1], 3) == 3
390e32caea8271bfef1394f1a9242332371ff4e7
m04kA/my_work_sckool
/pycharm/Для школы/tkinter/Snacke.py
7,011
3.5
4
from tkinter import * from random import randint import time row = int(input('Введите кол. строк: ')) col = int(input('Введите кол. колонок: ')) tk = Tk() tk.title('Game') canvas = Canvas(tk, width=600, height=600) canvas.pack() tk.wm_attributes('-topmost', 1) Snake = [[8, 4], [7, 4], [6, 4], [5, 4], [4, 4], [3, 4]] Dosk = [] food = [0, 0] lv = False pr = False dv = False verh = False def board(row, col): global Dosk side = 25 for i in range(row): Dosk.append([]) for j in range(col): Dosk[i].append('*') Dosk[i][j] = canvas.create_rectangle(50 + i * side, 75 + j * side, 50 + side + i * side,75 + side + j * side, fill='dark green') def zmeya(): for i in range(len(Snake)): if i == 0: canvas.itemconfig(Dosk[Snake[i][0]][Snake[i][1]], fill='red') else: canvas.itemconfig(Dosk[Snake[i][0]][Snake[i][1]], fill='blue') def right(evt): global pr global lv global dv global verh global food lv = False dv = False verh = False pr = True while pr == True: if Snake[0][0] < len(Dosk) - 1: Snake.insert(0, [Snake[0][0] + 1, Snake[0][1]]) canvas.itemconfig(Dosk[Snake[0][0]][Snake[0][1]], fill='red') canvas.itemconfig(Dosk[Snake[1][0]][Snake[1][1]], fill='blue') if Snake[0][0] == food[0] and Snake[0][1] == food[1]: canvas.itemconfig(Dosk[food[0]][food[1]], fill='red') food = [randint(0, len(Dosk) - 1), randint(0, len(Dosk[0]) - 1)] canvas.itemconfig(Dosk[food[0]][food[1]], fill='orange') score.config(text = score['text'][:6] + str(int(score['text'][6:])+1)) else: canvas.itemconfig(Dosk[Snake[len(Snake) - 1][0]][Snake[len(Snake) - 1][1]], fill='dark green') del Snake[len(Snake) - 1] tk.update() tk.update_idletasks() else: lv = False pr = False dv = False verh = False ''' canvas.delete("all") text = Label(tk, text='GAME OVER', bg='red') # Текст (просто текст в форме) text.place(300, 300) time.sleep(5) exit() ''' time.sleep(0.5) def dovn(evt): global pr global lv global dv global verh global food lv = False verh = False pr = False dv = True while dv == True: if Snake[0][1] < len(Dosk[0]) - 1: Snake.insert(0, [Snake[0][0], Snake[0][1] + 1]) canvas.itemconfig(Dosk[Snake[0][0]][Snake[0][1]], fill='red') canvas.itemconfig(Dosk[Snake[1][0]][Snake[1][1]], fill='blue') if Snake[0][0] == food[0] and Snake[0][1] == food[1]: canvas.itemconfig(Dosk[food[0]][food[1]], fill='red') food = [randint(0, len(Dosk) - 1), randint(0, len(Dosk[0]) - 1)] canvas.itemconfig(Dosk[food[0]][food[1]], fill='orange') score.config(text = score['text'][:6] + str(int(score['text'][6:])+1)) else: canvas.itemconfig(Dosk[Snake[len(Snake) - 1][0]][Snake[len(Snake) - 1][1]], fill='dark green') del Snake[len(Snake) - 1] tk.update() tk.update_idletasks() else: lv = False pr = False dv = False verh = False ''' canvas.delete("all") text = Label(tk, text='GAME OVER', bg='red') # Текст (просто текст в форме) text.place(300, 300) time.sleep(5) exit() ''' time.sleep(0.5) def left(evt): global pr global lv global dv global verh global food lv = True dv = False verh = False pr = False while lv == True: if Snake[0][0] > 0: Snake.insert(0, [Snake[0][0] - 1, Snake[0][1]]) canvas.itemconfig(Dosk[Snake[0][0]][Snake[0][1]], fill='red') canvas.itemconfig(Dosk[Snake[1][0]][Snake[1][1]], fill='blue') if Snake[0][0] == food[0] and Snake[0][1] == food[1]: canvas.itemconfig(Dosk[food[0]][food[1]], fill='red') food = [randint(0, len(Dosk) - 1), randint(0, len(Dosk[0]) - 1)] canvas.itemconfig(Dosk[food[0]][food[1]], fill='orange') score.config(text = score['text'][:6] + str(int(score['text'][6:])+1)) else: canvas.itemconfig(Dosk[Snake[len(Snake) - 1][0]][Snake[len(Snake) - 1][1]], fill='dark green') del Snake[len(Snake) - 1] tk.update() tk.update_idletasks() else: lv = False pr = False dv = False verh = False ''' canvas.delete("all") text = Label(tk, text='GAME OVER', bg='red') # Текст (просто текст в форме) text.place(300, 300) time.sleep(5) exit() ''' time.sleep(0.5) def up(evt): global pr global lv global dv global verh global food lv = False dv = False pr = False verh = True while verh == True: if Snake[0][1] > 0: Snake.insert(0, [Snake[0][0], Snake[0][1] - 1]) canvas.itemconfig(Dosk[Snake[0][0]][Snake[0][1]], fill='red') canvas.itemconfig(Dosk[Snake[1][0]][Snake[1][1]], fill='blue') if Snake[0][0] == food[0] and Snake[0][1] == food[1]: canvas.itemconfig(Dosk[food[0]][food[1]], fill='red') food = [randint(0, len(Dosk) - 1), randint(0, len(Dosk[0]) - 1)] canvas.itemconfig(Dosk[food[0]][food[1]], fill='orange') score.config(text = score['text'][:6] + str(int(score['text'][6:])+1)) else: canvas.itemconfig(Dosk[Snake[len(Snake) - 1][0]][Snake[len(Snake) - 1][1]], fill='dark green') del Snake[len(Snake) - 1] tk.update() tk.update_idletasks() else: lv = False pr = False dv = False verh = False ''' canvas.delete("all") text = Label(tk, text='GAME OVER', bg='red') # Текст (просто текст в форме) text.pack() time.sleep(5) exit() ''' time.sleep(0.5) board(row, col) zmeya() score =Label(tk, text = 'Счёт: 0', relief="solid",highlightthickness = 2) score.pack() canvas.itemconfig(Dosk[food[0]][food[1]], fill='orange') canvas.bind_all('<KeyPress-Left>', left) canvas.bind_all('<KeyPress-Up>', up) canvas.bind_all('<KeyPress-Down>', dovn) canvas.bind_all('<KeyPress-Right>', right)
81942a30e602c2b06f25bb851e6e9c4829dced09
MangeshSodnar123/python-practice-programs
/calculator.py
397
4.15625
4
import math num1 = int(input("enter first number \n")) num2 = int(input("enter second number \n")) operation = input("choose +, -, *, / \n") try: if "+" in operation: print(num1+num2) elif "-" in operation: print(num1-num2) elif "*" in operation: print(num1*num2) elif "/" in operation: print(num1/num2) except Exception as error: print(error)
75815a363f4bf46fac741fbdc622579622caa8c8
rohinrohin/python-lecture
/Day 1/Lecture/12_classify.py
325
3.96875
4
all = input("enter 3 sides of a triangle separated by space : ") #print(all.split()) (a, b, c) = all.split() a = int(a); b = int(b); c = int(c) equi = a == b == c iso = (a == b || b == c || c == a) and not equi scalene = not equi and not iso if equi : print ('equi') if iso : print('iso') if scalene: print('scalene')
9e987bb0fb94b5b850eba909cd4a749cffc91e02
michael-ritter/assignments-ma4502-S2019
/tsplib95/tsplib95/matrix.py
4,489
4.28125
4
# -*- coding: utf-8 -*- from . import utils class Matrix: """A square matrix created from a list of numbers. Elements are accessible using matrix notation. Negative indexing is not allowed. :param list numbers: the elements of the matrix :param int size: the width (also height) of the matrix :param int min_index: the minimum index """ def __init__(self, numbers, size, min_index=0): self.numbers = list(numbers) self.size = size self.min_index = min_index def __getitem__(self, key): return self.value_at(*key) def value_at(self, i, j): """Get the element at row *i* and column *j*. :param int i: row :param int j: column :return: value of element at (i,j) """ i -= self.min_index j -= self.min_index if not self.is_valid_row_column(i, j): raise IndexError(f'({i}, {j}) is out of bonuds') index = self.get_index(i, j) return self.numbers[index] def is_valid_row_column(self, i, j): """Return True if (i,j) is a row and column within the matrix. :param int i: row :param int j: column :return: whether (i,j) is within the bounds of the matrix :rtype: bool """ return 0 <= i < self.size and 0 <= j < self.size def get_index(self, i, j): """Return the linear index for the element at (i,j). :param int i: row :param int j: column :return: linear index for element (i,j) :rtype: int """ raise NotImplementedError() class FullMatrix(Matrix): """A complete square matrix. :param list numbers: the elements of the matrix :param int size: the width (also height) of the matrix :param int min_index: the minimum index """ def get_index(self, i, j): return i * self.size + j class HalfMatrix(Matrix): """A triangular half-matrix. :param list numbers: the elements of the matrix :param int size: the width (also height) of the matrix :param int min_index: the minimum index """ #: True if the half-matrix includes the diagonal has_diagonal = True def value_at(self, i, j): if i == j and not self.has_diagonal: return 0 i, j = self._fix_indices(i, j) return super().value_at(i, j) class UpperDiagRow(HalfMatrix): """Upper-triangular matrix that includes the diagonal. :param list numbers: the elements of the matrix :param int size: the width (also height) of the matrix :param int min_index: the minimum index """ has_diagonal = True def _fix_indices(self, i, j): i, j = (j, i) if i > j else (i, j) if not self.has_diagonal: j -= 1 return i, j def get_index(self, i, j): n = self.size - int(not self.has_diagonal) return utils.integer_sum(n, n - i) + (j - i) class LowerDiagRow(HalfMatrix): """Lower-triangular matrix that includes the diagonal. :param list numbers: the elements of the matrix :param int size: the width (also height) of the matrix :param int min_index: the minimum index """ has_diagonal = True def _fix_indices(self, i, j): i, j = (j, i) if i < j else (i, j) if not self.has_diagonal: i -= 1 return i, j def get_index(self, i, j): return utils.integer_sum(i) + j class UpperRow(UpperDiagRow): """Upper-triangular matrix that does not include the diagonal. :param list numbers: the elements of the matrix :param int size: the width (also height) of the matrix :param int min_index: the minimum index """ has_diagonal = False class LowerRow(LowerDiagRow): """Lower-triangular matrix that does not include the diagonal. :param list numbers: the elements of the matrix :param int size: the width (also height) of the matrix :param int min_index: the minimum index """ has_diagonal = False class UpperCol(LowerRow): pass class LowerCol(UpperRow): pass class UpperDiagCol(LowerDiagRow): pass class LowerDiagCol(UpperDiagRow): pass TYPES = { 'FULL_MATRIX': FullMatrix, 'UPPER_DIAG_ROW': UpperDiagRow, 'UPPER_ROW': UpperRow, 'LOWER_DIAG_ROW': LowerDiagRow, 'LOWER_ROW': LowerRow, 'UPPER_DIAG_COL': UpperDiagCol, 'UPPER_COL': UpperCol, 'LOWER_DIAG_COL': LowerDiagCol, 'LOWER_COL': LowerCol, }
042a1049ded83b8ca2d6955ff365d76ebc525f8a
sowmenappd/ds_algo_practice
/arrays_strings/rearrange_array.py
728
4.15625
4
print("Array rearrange such that arr[i] = i\n"); def rearrange(array): for i in range(len(array)): elem = array[i] if elem == -1: continue else: if elem == i: continue else: diffElem = array[elem] # array[elem] = elem array[i] = -1 while diffElem != -1 and array[diffElem] != i: if array[diffElem] == -1: array[diffElem] = diffElem break diffElem = array[diffElem] return array srt = [3, -1, -1, 0, 4] srt = [4, 3, 2, 1, 0] # srt = [-1, -1, 6, 1, 9, 3, 2, -1, 4,-1] print(rearrange(srt))
5aa42d7de882d624cf63cf7f82d343c79bf5a472
Big-Belphegor/python-stu
/Day04/Homework.py
7,320
3.75
4
__author__ = "Alien" class School(object): # 学校级别 def __init__(self,addr,course): self.addr = addr self.course = course self.students_Shanghai = [] self.students_Beijing = [] self.teachers_Shanghai = [] self.teachers_Beijing = [] def hire(self,obj_teacher): # 添加老师信息 if obj_teacher.addr == "上海": self.teachers_Shanghai.append(obj_teacher) elif obj_teacher.addr == "北京": self.teachers_Beijing.append(obj_teacher) def enroll(self,obj_student): # 添加学生信息 if obj_student.addr == "上海": self.students_Shanghai.append(obj_student) # print(self.students_Shanghai) elif obj_student.addr == "北京": self.students_Beijing.append(obj_student) # print(self.students_Beijing) class Classpro(School): # 班级级别 def __init__(self,addr,course,classname): super(Classpro,self).__init__(addr,course) self.classname = classname self.class_cost = {"Python":15000,"Linux":11000,"Go":20000} self.classnames = [] def enroll_class(self,obj_class): # 添加班级信息 if obj_class.classname == "Python" and obj_class.addr == "上海": self.classnames.append(obj_class) # print("您的课程总费用为:%s RMB" % self.class_cost["Python"]) elif obj_class.classname == "Linux" and obj_class.addr == "上海": self.classnames.append(obj_class) # print("您的课程总费用为:%s RMB" % self.class_cost["Linux"]) elif obj_class.classname == "Go" and obj_class.addr == "北京": self.classnames.append(obj_class) # print("您的课程总费用为:%s RMB" % self.class_cost["Go"]) else: print("您选择的课程还未开班,请耐心等待。") class Teacher(Classpro): # 老师级别 def __init__(self,addr,classname,course,name,salary,teacher_ID): super(Teacher,self).__init__(addr,classname,course) self.name = name self.salary = salary self.teacher_ID = teacher_ID def check_myprofile(self): # 打印老师相关信息 print(''' ----- Info of teacher %s ----- 员工ID: %s 姓名: %s 薪资: %s 课程: %s 班级: %s ''' % (self.name,self.teacher_ID,self.name,self.salary,self.course,self.classname)) def check_students(self): # 打印老师下学生信息 if self.addr == "上海": stu_list = self.students_Shanghai print(''' ----- Info of stduents ----- 学生名单: %s 学生人数: %s ''' % (stu_list, len(stu_list))) else: stu_list = self.students_Beijing print(''' ----- Info of stduents ----- 学生名单: %s 学生人数: %s ''' % (stu_list, len(stu_list))) class Student(Classpro): # 学生级别 def __init__(self,addr,course,classname,student_id,name): super(Student,self).__init__(addr,course,classname) self.students_id = student_id self.name = name def check_stuprofile(self): # 打印学生相关信息 print(''' ----- Info of yourself %s ----- 上课地址: %s 上课内容: %s 上课班级: %s 姓名: %s 学号: %s '''% (self.name,self.addr,self.course,self.classname,self.name,self.students_id)) def pay(self): # 课程学费支付(由于为练习程序,就以打印价格体现) if self.course in self.class_cost: print("您需要的学费为:%s" % self.class_cost[self.course]) else: print("信息错误,请确认后重试!") # 交互界面 while True: num = input(''' 1. 校园界面 2. 教师界面 3. 学生界面 ''') if num == '1': while True: x = input(''' 1. 创建学校 2. 创建教师 3. 退出 ''') if x == '1': # create school check_addr = input(''' ----- 学校地区选择 ---- 北京 上海 ''') if check_addr == "北京": check_course = input(''' Go ''') elif check_addr == "上海": check_course = input(''' Python Linux ''') else: print("请输入正确信息!") s1 = School(check_addr,check_course) elif x == '2': # create teacher teacher_addr = input('办公地址:') teacher_classname = input('所属班级:') teacher_course = input('教授课程:') teacher_name = input('姓名:') teacher_salary = input('薪资:') teacher_ID = input('员工账号:') t1 = Teacher(teacher_addr,teacher_classname,teacher_course,teacher_name,teacher_salary,teacher_ID) s1.hire(t1) elif x == '3': print("Bye!") break else: print("输入信息有误!") continue elif num == '2': while True: x = input(''' 1. 查看教师信息 2. 查看学生信息 3. 退出 ''') if x == '1': t1.check_myprofile() elif x == '2': t1.check_students() elif x == '3': print('Bye') break else: print("输入信息有误!") continue elif num == '3': while True: x = input(''' 1. 注册 2. 缴费 3. 退出 ''') if x == '1': # create student stu_addr = input(''' --- 上课地址 --- 上海 北京 ''') stu_course = input(''' --- 选择课程 --- Python Go Linux ''') stu_classname = input(''' --- 班级选择 --- Python Go Linux ''') stu_student_id = input('学号:') stu_name = input('姓名:') stu1 = Student(stu_addr,stu_course,stu_classname,stu_student_id,stu_name) s1.enroll(stu1) stu1.check_stuprofile() elif x == '2': stu1.pay() elif x =='3': print('Bye') break else: print('输入信息有误!') continue else: print('输入信息有误!') continue
9cf05d67336075d7806c3ca5284390168c5e478f
tbremm/Hacker_Rank_Python
/minimum_swaps__2.py
1,614
3.71875
4
# https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&h_r=next-challenge&h_v=zen&isFullScreen=true&playlist_slugs%5B%5D%5B%5D%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D%5B%5D%5B%5D=arrays&h_r=next-challenge&h_v=zen def minimumSwaps(arr): swaps = 0 arr = [x - 1 for x in arr] # Subtract one from each arr[x] so it matches the index val_dict = {x:i for i, x in enumerate(arr)} # Create lookup dict of sorted -> not sorted for i, x in enumerate(arr): # Enum arr so we can compare i and x if i != x: # This x doesn't belong at this index, so swap it out # Send x where it belongs (associated with it's matching index) # min_of_arr = min(arr[i + 1:]) # if arr[i] > min_of_arr: # min_index = arr[i + 1:].index(min_of_arr) # Get the index of the smallest remaining value # temp = arr[i] # arr[i] = arr[min_index] # arr[min_index] = temp # swaps += 1 return swaps test_arr = [7, 1, 3, 2, 4, 5, 6] # print(minimumSwaps(test_arr)) def other_minimum_swaps(arr): res = 0 arr = [x-1 for x in arr] value_idx = {x:i for i, x in enumerate(arr)} for i, x in enumerate(arr): if i != x: to_swap_idx = value_idx[i] value_idx[i] = i value_idx[x] = to_swap_idx arr[i], arr[to_swap_idx] = i, x res += 1 print(res) return res print(other_minimum_swaps(test_arr))
092a14a8089bf6f0e87c08651954ea723ecf26c6
EibboR-dev/AppDev-tRepository
/Personal-Info.py
361
3.859375
4
firstName = str( input("Input Your First Name: ")) lastName = str( input("Input Your Last Name: ")) strLocation = str( input ("Input Your Location: ")) intAge = int ( input("Input Your Age: ")) varSpace = " " print("You are " + firstName + varSpace + lastName + varSpace + ". You are from " + strLocation + ". You are " + str(intAge) + " years old.")
6a06efd4bc02089a3af52821bfa3ad049a994ddc
Nilesh-Devda/PythonCode
/Operators.py
139
4
4
a = 10 b = 5 if a > b: print("Correct") else: print("Incorrect") if a % 2 == 0: print("Even") else: print("Odd") print("Done")
f01229864b82be4df35567c0086ac45e9deee806
ganhan999/ForLeetcode
/中等61. 旋转链表.py
2,039
3.796875
4
""" 给定一个链表,旋转链表,将链表每个节点向右移动k个位置,其中k是非负数。 示例1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例2: 输入: 0->1->2->NULL, k = 4 输出: 2->0->1->NULL 解释: 向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步:0->1->2->NULL 向右旋转 4 步:2->0->1->NULL """ """ 遍历有多少节点的同时,形成一个环,之后(n - k % n - 1)个节点就是新的尾节点,(n - k % n)是新的头节点,再遍历断环。 """ #大神做法1 class Solution: def rotateRight(self, head: 'ListNode', k: 'int') -> 'ListNode': # base cases if not head: return None if not head.next: return head # close the linked list into the ring old_tail = head n = 1 while old_tail.next: old_tail = old_tail.next n += 1 old_tail.next = head#这里就形成一个环 # find new tail : (n - k % n - 1)th node # and new head : (n - k % n)th node new_tail = head for i in range(n - k % n - 1): new_tail = new_tail.next new_head = new_tail.next # break the ring new_tail.next = None#断环 return new_head """ 快慢指针,这样就只需要遍历一次 """ #大神做法2 class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head or not head.next or not k: return head tmp, count= head, 0 while tmp: tmp = tmp.next count += 1 k = k % count if k == 0: return head fast = slow = head for i in range(k): fast = fast.next while fast.next: fast = fast.next slow = slow.next newHead = slow.next slow.next = None fast.next = head return newHead
f1dd731b7ffff1026d2396d54b162bba7866a7d7
wonntann/skulpt
/test/run/t519.py
829
3.9375
4
l = ['h','e','l','l','o'] print l.index('l') print l.index('l', 2) print l.index('l', 3) print l.index('l', 2, 3) print l.index('l', 3, 4) print l.index('l', 2, -1) print l.index('l', 2, -2) print l.index('l', 3, -1) try: print l.index('l', 4) except ValueError as e: print repr(e) try: print l.index('l', -1) except ValueError as e: print repr(e) try: print l.index('l', 2, 2) except ValueError as e: print repr(e) try: print l.index('l', 3, 2) except ValueError as e: print repr(e) try: print l.index('l', 3, -2) except ValueError as e: print repr(e) try: print l.index('l', 3, 0) except ValueError as e: print repr(e) try: print l.index('l', 4.3) except TypeError as e: print repr(e) try: print l.index('l', 3, 0.6) except TypeError as e: print repr(e)
e22f9bdf28b108dba31547473b7e91daa4be9809
devinupreti/coding-problems
/longestSubstringDistinct.py
1,058
3.71875
4
# PROBLEM : Given an integer k and a string s, # find the length of the longest substring # that contains at most k distinct characters. # For example, given s = "abcba" and k = 2, the longest substring # with k distinct characters is "bcb". # Leetcode - Question 340 | DCP - #13 # Brute Force - O(N^3) # Time : O(n) | Space : O() from collections import defaultdict # doesnt throw error if key not in dict def longestSub(k, s): st = 0 # start counter = defaultdict(int) maxLen = 0 for index, val in enumerate(s): if counter[val] == 0: # New Char -> decrement k k -= 1 counter[val] += 1 while k < 0: # Now we have more than required distinct chars counter[s[st]] -= 1 if counter[s[st]] == 0: k += 1 st += 1 maxLen = max(maxLen, index - st + 1) return maxLen print(longestSub(2,"abcba")) # 3 print(longestSub(3,"aabacbebebe")) # cbebebe - 7
88878af75245f8251638c5d4015c4a74905aa2fc
eetuhietanen/KOODIT
/GUI.py
15,587
4.46875
4
# TIE-02100 Johdatus ohjelmointiin # Ilari Hildén, ilari.hilden@tuni.fi, opiskelijanumero: 282680 # Eetu Hietanen, eetu.hietanen@tuni.fi, opiskelijanumero: 284956 # GUI_ristinolla # TicTacToe with a graphical user interface. from tkinter import * NUMBER_OF_PLAYERS = 2 INFOTEXT = "This is TicTacToe. The rules are simple, there are two " \ "players who place their mark on the board alternately. When" \ " one of the players gets the desired amount of their mark in" \ " a row (vertically, horizontally or diagonally) he/she wins." \ " If the board fills up before either of the players gets to" \ " this point its a draw. You can choose the size of the" \ " game board (from three to ten) and the length of the straight" \ " required to win below. The winning length must be less or" \ " equal to the size of the board. You can always restart the" \ " game with the restart button and choose the variables again" \ " and start a new game with the new game button. The Start" \ " button starts the game and Quit button always quits the game." class InfoWindow: """ This class is for the info window. It starts on the program start up. It has the information about the program, for example the rules and the instructions about the program. It starts the game. """ def __init__(self): self.__infowindow = Tk() self.__infowindow.title("TicTacToe") self.__scroller = Scrollbar(self.__infowindow) self.__scroller.grid(row=0, column=5, ipady=26) self.__infotext = Text(self.__infowindow, height=6, width=30, yscrollcommand=self.__scroller.set, wrap=WORD, padx=10) self.__infotext.grid(row=0, column=0, columnspan=5) self.__infotext.insert(END, INFOTEXT) self.__infotext.config(state=DISABLED) self.__scroller.config(command=self.__infotext.yview) self.__startbutton = Button(self.__infowindow, text="Start!", command=self.start_game) self.__startbutton.grid(row=3, column=1, rowspan=3) self.__quitbutton = Button(self.__infowindow, text="Quit", command=self.quit) self.__quitbutton.grid(row=3, column=3) self.__scale_entry = Entry(self.__infowindow, width=5) self.__scale_entry.grid(row=2, column=1) self.__winning_lenght = Entry(self.__infowindow, width=5) self.__winning_lenght.grid(row=2, column=4) self.__scale_label = Label(self.__infowindow, text="Board size:") self.__scale_label.grid(row=2, column=0) self.__lenght_label = Label(self.__infowindow, text="Winning length:") self.__lenght_label.grid(row=2, column=3) self.__error_label = Label(self.__infowindow, text="") self.__error_label.grid(row=3, column=0, columnspan=5) def start_game(self): """ For starting the program. This methods checks for valid input and creates a new Board object with the specified values. :return: """ try: scale = int(self.__scale_entry.get()) winning_lenght = int(self.__winning_lenght.get()) if winning_lenght <= scale and 10 >= scale >= 3: self.__infowindow.destroy() board = Board(scale, winning_lenght) board.start() else: if winning_lenght > scale: self.__error_label.configure( text="Winning length must be less or equal to scale!") else: self.__error_label.configure( text="Please enter integers between three and ten!") self.__startbutton.grid(row=4, column=1) self.__quitbutton.grid(row=4, column=3) except ValueError: self.__error_label.configure( text="Please enter integers over three!") self.__startbutton.grid(row=4, column=1) self.__quitbutton.grid(row=4, column=3) def quit(self): """ Quits the program. :return: """ self.__infowindow.destroy() def start(self): """ For starting the main loop. :return: """ self.__infowindow.mainloop() class Board: """ This is a class for the game board. It stores the information about the board and reads the users commands. """ def __init__(self, board_size, winninglenght): self.__board_window = Tk() self.__board_window.title("TicTacToe") self.__board_size = board_size self.__winning_lenght = winninglenght self.__turn = 0 self.__mark_x = "X" self.__mark_o = "O" self.__disabled_buttons = 0 self.__new_game = Button(self.__board_window, text="New Game", command=self.new_game) self.__new_game.grid(row=0, column=0, columnspan=self.__board_size // 3) self.__restart = Button(self.__board_window, text="Restart", width=9, command=self.restart) self.__restart.grid(row=0, column=self.__board_size - self.__board_size // 3, columnspan=self.__board_size // 3) self.__quit = Button(self.__board_window, text="Quit", width=9, command=self.quit) self.__quit.grid(row=board_size + 1, column=0) self.__turn_label = Label(self.__board_window, text="X's turn") if self.__board_size % 2 == 0: self.__turn_label.grid(row=0, column=self.__board_size - self.__board_size // 2 - 1, columnspan=2) else: self.__turn_label.grid(row=0, column=self.__board_size - self.__board_size // 2 - 1) self.__board_buttons = [] # Data structure of the board. for row in range(self.__board_size): self.__board_buttons.append([]) for column in range(self.__board_size): new_button = Button(self.__board_window, height=3, width=9, relief="groove", command=lambda row_index=row, column_index=column: self.place_mark(row_index, column_index)) new_button.grid(row=row + 1, column=column, sticky=E) self.__board_buttons[row].append(new_button) def place_mark(self, row, column): """ Method for placing a mark on the board and disabling the button in question. Starts the winner checking system. :param row: The "row" index of the button pressed. :param column: The "column" index of the button pressed. :return: """ if self.__turn % NUMBER_OF_PLAYERS == 0: self.__board_buttons[row][column].configure(state=DISABLED, text=self.__mark_x) self.__turn_label.configure(text="O's turn") else: self.__board_buttons[row][column].configure(state=DISABLED, text=self.__mark_o) self.__turn_label.configure(text="X's turn") self.__turn += 1 self.__disabled_buttons += 1 self.horizontal_win_checker(row, column) def start(self): """ For starting the main loop. :return: """ self.__board_window.mainloop() def new_game(self): """ This method starts a new InfoWindow object and destroys the current board window. :return: """ self.__board_window.destroy() iw = InfoWindow() iw.start() def restart(self): """ This method restarts the current board. :return: """ for row in range(self.__board_size): for column in range(self.__board_size): self.__board_buttons[row][column].configure(state="normal", text="") self.__turn = 0 self.__disabled_buttons = 0 self.__turn_label.configure(text="X's turn") def horizontal_win_checker(self, row, column): """ This method checks if there are enough marks in a row for a win. It checks only for horizontal win and starts the checking from the latest placed mark. If there are no winners found starts the next checker. :param row: The "row" index of the button pressed. :param column: The "column" index of the button pressed. :return: """ marks_in_row = -1 # Checking for marks in row to right from pressed button. for i in range(self.__board_size - column): if self.__board_buttons[row][column + i]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break # Checking for marks in row to left from pressed button. for i in range(1 + column): if self.__board_buttons[row][column - i]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break if marks_in_row >= self.__winning_lenght: self.winner_found(row, column) else: self.vertical_win_checker(row, column) def vertical_win_checker(self, row, column): """ This method works on same principle as horizontal_win_checker but checks for vertical winners instead. :param row: The "row" index of the button pressed. :param column: The "column" index of the button pressed. :return: """ marks_in_row = -1 # Checking for marks in row down from pressed button. for i in range(self.__board_size - row): if self.__board_buttons[row + i][column]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break # Checking for marks in row up from pressed button. for i in range(1 + row): if self.__board_buttons[row - i][column]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break if marks_in_row >= self.__winning_lenght: self.winner_found(row, column) else: self.diagonal_win_checker_sw_ne(row, column) def diagonal_win_checker_sw_ne(self, row, column): """ This method works on same principle as horizontal_win_checker but checks for diagonal(from SW to NE) winners instead. :param row: The "row" index of the button pressed. :param column: The "column" index of the button pressed. :return: """ column_distance = self.__board_size - column row_distance = row + 1 marks_in_row = -1 # Calculating the shortest distance from board edges. if column_distance > row_distance: nearest_edge_ne = row_distance nearest_edge_sw = self.__board_size - column_distance + 1 else: nearest_edge_ne = column_distance nearest_edge_sw = self.__board_size - row_distance + 1 # Checking for marks in row to NE from pressed button. for i in range(nearest_edge_ne): if self.__board_buttons[row - i][column + i]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break # Checking for marks in row to SW from pressed button. for i in range(nearest_edge_sw): if self.__board_buttons[row + i][column - i]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break if marks_in_row >= self.__winning_lenght: self.winner_found(row, column) else: self.diagonal_win_checker_nw_se(row, column) def diagonal_win_checker_nw_se(self, row, column): """ This method works on same principal as horizontal_win_checker but check for diagonal(from NW to SE) winners instead. :param row: The "row" index of the button pressed. :param column: The "column" index of the button pressed. :return: """ column_distance = self.__board_size - column row_distance = self.__board_size - row marks_in_row = -1 # Calculating the shortest distance from board edges. if column_distance > row_distance: nearest_edge_se = row_distance nearest_edge_nw = self.__board_size - column_distance + 1 else: nearest_edge_se = column_distance nearest_edge_nw = self.__board_size - row_distance + 1 # Checking for marks in row to SE from pressed button. for i in range(nearest_edge_se): if self.__board_buttons[row + i][column + i]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break # Checking for marks in row to NW from pressed button. for i in range(nearest_edge_nw): if self.__board_buttons[row - i][column - i]["text"] \ == self.__board_buttons[row][column]["text"]: marks_in_row += 1 else: break if marks_in_row >= self.__winning_lenght: self.winner_found(row, column) else: self.draw() def winner_found(self, row, column): """ This method displays the winner and disables the buttons in a case of win. :param row: The "row" index of the button pressed. :param column: The "column" index of the button pressed. :return: """ winner = self.__board_buttons[row][column]["text"] self.__turn_label.configure(text=(winner, "won!")) for row in range(self.__board_size): for column in range(self.__board_size): self.__board_buttons[row][column].configure(state=DISABLED) def draw(self): """ Displays "draw" if the players draw. :return: """ if self.__disabled_buttons == self.__board_size ** 2: self.__turn_label.configure(text="Draw") def quit(self): """ Quits the game :return: """ self.__board_window.destroy() def main(): """ Starts the program. :return: """ iw = InfoWindow() iw.start() main()
cfd395d54bbb977b0cd7eb0a2dbfe6c4ffb47ae0
shuaaa/Markovs
/LinkedList.py
1,810
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 9 07:56:00 2020 @author: olamijojo """ # prints out the namespace dictionary called locals print(locals()) # prints memory location of the stored varibles d & j d = 'Dave' j = d # j = d implies we just copy d's reference over to j's namespace entry. print(id(d), id(j)) # changing assignment # Assignment changes what object a variable refers to, it does not have any # effect on the object itself. # This process is known as garbage collection. i.e reuse of memory locations # by reassignment. j = 'Smith' # removing mapping from a given name by delete func del d # Aliasing lst1 =[1, 2, 3] lst2 = lst1 lst2.append(4) lst1 # Shallow copy & deep copy # A shallow copy has its own top-level references, but those references #refer to the same objects # deep copy is a completely separate copy that creates both new references # and, where necessary, new data objects at all levels import copy b = [1, 2,[3 ,4], 6] c = b d = copy.copy(b) # creates a shallow copy e = copy.deepcopy(b) # create a deep copy print(b is c, b == c) print(b is d, b == c) print(b is c, b == e) b[0] = 0 b.append(7) c[2].append(5) print(b) print(c) print(d) # shallow copy does not get the append updates print(e) # shallow copy does not get the append updates """ Changing the top level of the list referred to by b causes c to change, since it refers to the same object. The top-level changes have no effect on d or e, since they refer to separate objects that are copies of b. Things get interesting when we change the sublist [3 , 4] through c . Of course b sees these changes (since b and c are the same object). But now d also sees those changes, since this sublist is still a shared substructure in the shallow copy. """
c70b83e5fadac95d54ad67811b337b65b8924e15
yvlian/algorithm
/python/设计模式/单例模式.py
3,853
3.859375
4
#装饰器实现 def Singleton(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @Singleton class A(object): a = 1 def __init__(self, x=0): self.x = x a1 = A(2) a2 = A(3) print(a1 is a2) #更简单方便的方法是,使用__new__实现 import threading class B(object): _instance_lock = threading.Lock()#当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突。 def __init__(self): pass def __new__(cls, *args, **kwargs): # @staticmethod __new__属于静态方法 print('__new__ is called.') if not hasattr(B, "_instance"): with B._instance_lock: if not hasattr(B, "_instance"): B._instance = object.__new__(cls) return B._instance obj1 = B() obj2 = B() obj1.__new__(B) #python中实例可以调用静态方法 # # def task(arg): # obj = B() # print('arg',obj) # # for i in range(10): # t = threading.Thread(target=task,args=[i,]) # t.start() ''' p.s. 闭包执行完成后,仍能保持住当前的运行环境。即:函数每次的执行结果,都是基于这个函数上次的运行结果(比如单例模式中的_instance) 1 单例模式 只允许创建一个对象,因此节省内存,加快对象访问速度,因此对象需要被公用的场合适合使用,如多个模块使用同一个数据源连接对象等等 2 单例的缺点 就是不适用于变化的对象,如果同一类型的对象总是要在不同的用例场景发生变化,单例就会引起数据的错误,不能保存彼此的状态。 用单例模式,就是在适用其优点的状态下使用 应用实例 1、全局唯一:比如生成全局唯一的序列号、网站计数器。 2、访问全局复用的惟一资源,如磁盘、总线等; 3、单个对象占用的资源过多,如数据库等; 4、系统全局统一管理,如Windows下的Task Manager; python的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件, 当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。 因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。 .pyc 文件是python的字节码文件。.pyc 文件是不能用文本编辑器进行编辑的。.pyc文件的内容与平台无关。 其优点是 .pyc 文件的执行速度要远快于 .py 文件。 至于为什么要有 .pyc 文件,这个需求太明显了, 因为 .py 文件是可直接看到源码的,若是软件开发商的话,不可能把源码泄漏出去? 所以,就需编译成 .pyc 后再发布。 .pyc文件默认情况下不会自动生成 若你在命令行直接输入“python path/to/projectDir”(假设projectDir目录含有“__main__.py”文件,以及其他将要调用的模块), 那么程序运行结束后便自动为当前目录下所有的脚本生成字节码文件,并保存于本地新文件夹__pycache__当中。 (这也有可能是IDE写小项目时自动生成.pyc文件的原因,不过问题描述略微暧昧。详情参见上面知乎问题板块) .pyd 文件并不是用 python 编写成的,.pyd 文件一般是其他语言编写的 python 扩展模块。 .pyd 文件是用 D 语言按照一定格式编写,并处理成二进制的文件。 # ''' # import time def cal_time(func): def inner(*args,**kargs): start = time.time() f =func(*args,**kargs) time.sleep(1) stop = time.time() print(stop-start) return f return inner @cal_time def add(a,b): # print(a+b) return a+b ans = add(1,2) print(ans)
c5444ab476405a8c06a722979cf61c97388d2489
gridl/Mcr_CodeFirst_Python
/session4/styled_app/styled_app.py
1,424
3.640625
4
from flask import Flask, render_template, request app = Flask("StyledDemoApp") @app.route("/") def say_hello(): """Example showing how to return an HTML template with a form, which sends data back to this Flask app using a POST request.""" return render_template("index.html", title="Home page") @app.route("/feedback", methods=["POST"]) def gather_feedback(): """Example showing how to retrieve data from POST requests. By default, when writing @app.route(...) on top of a function, it can only handle GET requests. As such, we need to explicitly specify that we want the function to handle POST requests with `method=["POST"]` bit.""" # a neat way for accessing data for both GET and POST requests! data = request.values return render_template("feedback.html", form_data=data, title="Feedback response") @app.route("/<name>") def say_hello_to(name): """Example showing how to take URL parameter and capture its value, as well as how to return a string back to the user's browser.""" return f"Hello {name}" @app.route("/hello/<name>") def show_hello_template(name): """Example showing to return and render an HTML template file back to the user's browser.""" return render_template("hello.html", person=name, title="Greetings") # "debug=True" causes Flask to automatically refresh upon any changes you # make to this file. app.run(debug=True)
82d087f35cd12a8eaf67408e783511d43e1203d7
ckallum/Daily-Coding-Problem
/solutions/#101.py
872
3.90625
4
from cmath import inf def is_prime(i, j): i_count = 0 for x in range(1, i // 2): if i % x == 0: i_count += 1 if i_count > 1: return False j_count = 0 for x in range(1, j // 2): if j % x == 0: j_count += 1 if j_count > 1: return False return True def find_primes(number): solution = (inf, inf) for i in range(2, int(number / 2) + 1): num1 = i num2 = number - i possible = is_prime(num1, num2) if possible: if num1 < solution[0]: solution = (num1, num2) elif num1 == solution[0] and num2 < solution[1]: solution = (num1, num2) return solution def main(): assert find_primes(4) == (2, 2) assert find_primes(8) == (3, 5) if __name__ == '__main__': main()
6bc0b2f921168afcd520543538d8f6037f0e136a
cdave1/experiments
/python/genprime.py
384
3.75
4
def genPrimes(n): primes = [2] for i in range(3,n,2): addprime = 1 for prime in primes: if (i % prime == 0): addprime = 0 break if addprime == 1: primes.append(i) for i in primes: print i genPrimes(100) genPrimes(1000) genPrimes(10000) genPrimes(100000) # faster with Miller-Rabin
f20a1077a543af9579d9380c12df9985c07b3cc7
ravisrhyme/CTCI
/sorting_algorithms/insertion_sort.py
1,158
4.375
4
""" Implementation of insertion sort Time Complexity : O(n^2) Space Complexity : O(1) """ __author__ = "Ravi Kiran Chadalawada" __email__ = "rchadala@usc.edu" __credits__ = ["Algorithm Design Manual","mycodeschool channel"] __status__ = "Prototype" def insertion_sort(element_list): """ Sorts by using insertion sort algorithm In every iteration w.r.t outer loop, we compare it with all previous elements, one at a time, a keep shifting left if element_list[i] is less than previous element.(Important to note that we swap one element at a time startign with immediate previous element. """ for i in range(1, len(element_list)): # Traverse across all elements for j in range(i,0,-1): # Traverse across all previous elements. if element_list[j] < element_list[j-1]: # Swap if current is less than previous swap(element_list,j,j-1) def swap(element_list,i,j): """ Swaps the elements position i and j in list """ temp = element_list[i] element_list[i] = element_list[j] element_list[j] = temp if __name__=='__main__': element_list = [9,8,7,2,3,6] print('Initial list:',element_list) insertion_sort(element_list) print("Sorted list :",element_list)
87bbf52f05f0ef4f6c8d0679e97b9986c84b1ef4
alefnula/tea
/tea/dsa/singleton.py
2,639
4.09375
4
import threading class SingletonMetaclass(type): """Singleton Metaclass. This metaclass is used for creating singletons. It changes the class __new__ method to maintain only one instance of the class, and tweaks the __init__ method to be executed only once (when the first instance of the class is created. Usage:: >>> class MySingleton(object, metaclass=SingletonMetaclass): ... '''Real singleton class. ... ... You have to set the metaclass to SingletonMetaclass, ... and define the __init__ function. Everything else will ... be done by metaclass. ... ''' ... def __init__(self, data): ... print("Initializing") ... self.data = data ... >>> # Only this actually happen >>> first = MySingleton("First initialization") Initializing >>> second = MySingleton("Second initialization") # This won't happen >>> first.data 'First initialization' >>> second.data 'First initialization' """ def __init__(cls, *args, **kwargs): super(SingletonMetaclass, cls).__init__(*args, **kwargs) cls._instance = None cls._lock = threading.Lock() def __call__(cls, *args, **kwargs): with cls._lock: if cls._instance is None: cls._instance = super(SingletonMetaclass, cls).__call__( *args, **kwargs ) return cls._instance @property def instance(cls): with cls._lock: return cls._instance class Singleton(metaclass=SingletonMetaclass): """Singleton class. Inherit from this class if you want to have a singleton class. Never use SingletonMetaclass! Usage:: >>> class EmptySingleton(Singleton): ... '''Singleton without __init__ method''' ... pass ... >>> first = EmptySingleton() >>> second = EmptySingleton() >>> assert id(first) == id(second) >>> >>> class InitSingleton(Singleton): ... '''Singleton with __init__ method''' ... def __init__(self, data): ... print("Initializing") ... self.data = data ... >>> # Only this actually happen >>> first = InitSingleton("First initialization") Initializing >>> second = InitSingleton("Second initialization") # This won't happen >>> first.data 'First initialization' >>> assert first.data == second.data """ pass
fbe24d1dee0bb04113e7589f338c0349c0c4c34a
shaguntyagi28/Game-
/project1.py
12,674
4.1875
4
print("\n\n\nWelcome to the most interesting quiz, The ShinChan Quiz\n") #questions with their respective options, choosing the correct option will lead you to another question. print(''' Q1 - what is the full name of shinchan? a - suzuki Nohara b - Shin Chan Nohara c - Shinnosuke Nohara ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" Correct!! :), you have got the right option! Moving ahead ") print(''' Q2 -Where do the shinchan and his family live? a - America b - Korea c - Japan ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" dont be silly ") print("The game has been terminated") elif answer == "c": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q3 -What is the name of his pet dog? a - Sheero b - puppy c - michan ''') answer = input().lower() if answer == "a": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q4 -Where Shinchan's grandparents live? a - Town b - Village c - roadside ''') answer = input().lower() if answer == "a": print(" dont be silly`!") print("The game has been terminated") elif answer == "b": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q5 -What is Shinchan's sister name? a - Hema walini b - Himawari Nohara c - Daisy ''') answer = input().lower() if answer == "a": print(" dont be silly`!") print("The game has been terminated") elif answer == "b": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q6 -where does the shinchan live in japan? a - Hokaido b - Bejing c - Tokyo ''') answer = input().lower() if answer == "a": print(" dont be silly`!") print("The game has been terminated") elif answer == "b": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "c": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q7 -Who is Shinchan's teacher among these options? a - Yoshinaga maam b - Matsuzaka maam c - Principal sir ''') answer = input().lower() if answer == "a": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q8 -What does Shinchan love to eat? a - Dora cakes b - Choco chips c - Prawns ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q9 - Which is Shinchan's favourite cartoon show? a - Doraemon b - Super Fairies c - Action Kamen ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" dont be silly`!") print("The game has been terminated") elif answer == "c": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q10 - Who is Shinchan's best friend? a - Wochan b - Kazama c - Masau ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q11 - what is the name of Shinchan's father? a - Harry b - kazama c - Bo ''') answer = input().lower() if answer == "a": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q12 - What colour T-shirt does Shinchan usually wear? a - Green b - Red c - Yellow ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q13 - Whom does Shinchan have a crush on? a - Nanako b - Mitsy c - Yoshinaga ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" dont be silly`!") print("The game has been terminated") elif answer == "c": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q14 - What is the shin chan's gang name? a - Kolta mary b - Raging bull c - Kasukabe defence group ''') answer = input().lower() if answer == "a": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "b": print(" dont be silly`!") print("The game has been terminated") elif answer == "c": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q15 - Who are yoshirin and michi? a - Shinchan's neighbours b - Shinchan's cousins c - Shinchan's teachers ''') answer = input().lower() if answer == "a": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q16 - What is the name of Shinchan's mother? a - Merry b - Mitsy c - Kachin ''') answer = input().lower() if answer == "a": print(" dont be silly`!") print("The game has been terminated") elif answer == "b": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q17 - Why did shinchan's mother beat him? a - because shin chan beat his sister b - because his mother hate him c - because shinchan is very nauty ''') answer = input().lower() if answer == "a": print(" dont be silly`!") print("The game has been terminated") elif answer == "b": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "c": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q18 -Shinchan is how much old? a - 5 b - 4 c - 6 ''') answer = input().lower() if answer == "a": print(" correct!! :), you have got the right option! Moving ahead ") print(''' Q19 -What vegetable does Shincan Hates the most? a - Spinach b - Only beans c - Capsicum and peas ''') answer = input().lower() if answer == "a": print(" dont be silly`!") print("The game has been terminated") elif answer == "b": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "c": print(" correct!! :), you have got the right option!\n Congratulations you completed the game successfully! :) :)") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "b": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "c": print(" dont be silly`!") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "c": print(" Nope - this is not the right answer :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "b": print(" dont be silly`!") print("The game has been terminated") elif answer == "c": print(" Nope - this is not the right answer :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "c": print(" dont be silly`!") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "b": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "c": print(" dont be silly`!") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "c": print(" dont be silly`!") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "c": print(" dont be silly`!") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "b": print(" Nope - this is not the right answer :( ") print("The game has been terminated") elif answer == "c": print(" dont be silly`!") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "c": print(" Nope - this is not the right answer :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "c": print(" Nope - this is not the right answer :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "b": print(" dont be silly ") print("The game has been terminated") elif answer == "c": print(" Nope - this is not the right answer :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated") elif answer == "c": print(" Don't be silly! :( ") print("The game has been terminated") else: print(" You didn't choose a, b or c :( ") print("The game has been terminated")
a64d96aead9f592b6165302b22889ca9e99aaee6
altonelli/interview-cake
/problems/python/reverse_string_inplace.py
493
4.125
4
# If not allowed to use the swap, use a temp variable def reverse_string_inplace(string): string_list = list(string) for idx in range(len(string_list) / 2): print(string_list[idx]) string_list[idx], string_list[len(string_list) - 1 - idx] = string_list[len(string_list) - 1 - idx], string_list[idx] print(string_list[idx]) return ''.join(string_list) def main(): print(reverse_string_inplace("reverse_string")) if __name__ == '__main__': main()
0f60ef56cec0ff15c0b95d2df0af2a739e58f17d
Jeroen263/AdvancedSim_A2
/Customer.py
316
3.53125
4
class Customer: def __init__(self, arr, arrq, queue, arrqueue): self.arrivalTime = arr self.queueJoinTime = arrq self.queue = queue self.arrivalQueue = arrqueue def __str__(self): return "Customer arrived at " + str(self.arrivalTime) + " at queue " + str(self.queue)
2d44aa6b1dddb37df079a59ba5bf5fff7017b31c
hsadler/zentype2
/app/server/service/keyboard.py
9,045
3.84375
4
# Keyboard Service from service.language import Language class Keyboard(): """ Keyboard Service. Provides a keyboard model and methods based on key layout and language configurations. """ # fingers LEFT_PINKY = 'LP' LEFT_RING = 'LR' LEFT_MIDDLE = 'LM' LEFT_INDEX = 'LI' LEFT_THUMB = 'LT' THUMB = 'T' RIGHT_THUMB = 'RT' RIGHT_INDEX = 'RI' RIGHT_MIDDLE = 'RM' RIGHT_RING = 'RR' RIGHT_PINKY = 'RP' # hands LEFT_HAND = [ LEFT_PINKY, LEFT_RING, LEFT_MIDDLE, LEFT_INDEX, LEFT_THUMB ] RIGHT_HAND = [ RIGHT_THUMB, RIGHT_INDEX, RIGHT_MIDDLE, RIGHT_RING, RIGHT_PINKY ] class Key(): def __init__( self, position, finger, difficulty=None, primary_char=None, secondary_char=None, ): self.position = position self.finger = finger self.difficulty = difficulty self.primary_char = primary_char self.secondary_char = secondary_char def get_finger(self): return self.finger def set_difficulty(self, difficulty): self.difficulty = difficulty def get_difficulty(self, char=None): return self.difficulty def set_characters(self, primary_char, secondary_char): self.primary_char = primary_char self.secondary_char = secondary_char def get_characters(self): return { 'primary': self.primary_char, 'secondary': self.secondary_char } def get_primary_char(self): return self.primary_char def get_secondary_char(self): return self.secondary_char def to_dict(self): return { 'position': self.position, 'finger': self.finger, 'difficulty': self.difficulty, 'primary_char': self.primary_char, 'secondary_char': self.secondary_char } # qwerty layout: # ` 1 2 3 4 5 6 7 8 9 0 - = D # T q w e r t y u i o p [ ] \ # C a s d f g h j k l ; ' R # S z x c v b n m , . / S # ct cm space cm # base keyboard model BASE_KEYBOARD_MODEL = [ # 1st row Key([0,0], LEFT_PINKY, 425), # ['`','~'] Key([0,1], LEFT_PINKY, 350), # ['1','!'] Key([0,2], LEFT_RING, 350), # ['2','@'] Key([0,3], LEFT_MIDDLE, 350), # ['3','#'] Key([0,4], LEFT_INDEX, 350), # ['4','$'] Key([0,5], LEFT_INDEX, 425), # ['5','%'] Key([0,6], RIGHT_INDEX, 425), # ['6','^'] Key([0,7], RIGHT_INDEX, 350), # ['7','&'] Key([0,8], RIGHT_MIDDLE, 350), # ['8','*'] Key([0,9], RIGHT_RING, 350), # ['9','('] Key([0,10], RIGHT_PINKY, 350), # ['0',')'] Key([0,11], RIGHT_PINKY, 425), # ['-','_'] Key([0,12], RIGHT_PINKY, 450), # ['=','+'] Key([0,13], RIGHT_PINKY, 450), # ['delete'] # 2nd row Key([1,0], LEFT_PINKY, 375), # ['tab'] Key([1,1], LEFT_PINKY, 275), # ['q','Q'] Key([1,2], LEFT_RING, 150), # ['w','W'] Key([1,3], LEFT_MIDDLE, 150), # ['e','E'] Key([1,4], LEFT_INDEX, 150), # ['r','R'] Key([1,5], LEFT_INDEX, 250), # ['t','T'] Key([1,6], RIGHT_INDEX, 250), # ['y','Y'] Key([1,7], RIGHT_INDEX, 150), # ['u','U'] Key([1,8], RIGHT_MIDDLE, 150), # ['i','I'] Key([1,9], RIGHT_RING, 150), # ['o','O'] Key([1,10], RIGHT_PINKY, 275), # ['p','P'] Key([1,11], RIGHT_PINKY, 400), # ['[','{'] Key([1,12], RIGHT_PINKY, 425), # [']','}'] Key([1,13], RIGHT_PINKY, 425), # ['\\', '|'] # 3rd row Key([2,0], LEFT_PINKY, 225), # ['capslock'] Key([2,1], LEFT_PINKY, 100), # ['a','A'] Key([2,2], LEFT_RING, 100), # ['s','S'] Key([2,3], LEFT_MIDDLE, 100), # ['d','D'] Key([2,4], LEFT_INDEX, 100), # ['f','F'] Key([2,5], LEFT_INDEX, 175), # ['g','G'] Key([2,6], RIGHT_INDEX, 175), # ['h','H'] Key([2,7], RIGHT_INDEX, 100), # ['j','J'] Key([2,8], RIGHT_MIDDLE, 100), # ['k','K'] Key([2,9], RIGHT_RING, 100), # ['l','L'] Key([2,10], RIGHT_PINKY, 100), # [';',':'] Key([2,11], RIGHT_PINKY, 225), # ['\'','"'] Key([2,12], RIGHT_PINKY, 275), # ['return'] # 4th row Key([3,0], LEFT_PINKY, 200), # ['left shift'] Key([3,1], LEFT_PINKY, 275), # ['z','Z'] Key([3,2], LEFT_RING, 275), # ['x','X'] Key([3,3], LEFT_MIDDLE, 200), # ['c','C'] Key([3,4], LEFT_INDEX, 200), # ['v','V'] Key([3,5], LEFT_INDEX, 300), # ['b','B'] Key([3,6], RIGHT_INDEX, 200), # ['n','N'] Key([3,7], RIGHT_INDEX, 200), # ['m','M'] Key([3,8], RIGHT_MIDDLE, 200), # [',','<'] Key([3,9], RIGHT_RING, 275), # ['.','>'] Key([3,10], RIGHT_PINKY, 275), # ['/','?'] Key([3,11], RIGHT_PINKY, 200), # ['right shift'] # 5th row Key([4,0], LEFT_PINKY, 425), # ['left fn'] Key([4,1], LEFT_PINKY, 425), # ['left control'] Key([4,2], LEFT_THUMB, 150), # ['left option'] Key([4,3], LEFT_THUMB, 125), # ['left command'] Key([4,4], THUMB, 50), # ['spacebar'] Key([4,5], RIGHT_THUMB, 125), # ['right command'] Key([4,6], RIGHT_PINKY, 150) # ['right option'] ] # keyboard layouts QWERTY = [ # 1st row ['`','~'], ['1','!'], ['2','@'], ['3','#'], ['4','$'], ['5','%'], ['6','^'], ['7','&'], ['8','*'], ['9','('], ['0',')'], ['-','_'], ['=','+'], ['delete'], # 2nd row ['tab'], ['q','Q'], ['w','W'], ['e','E'], ['r','R'], ['t','T'], ['y','Y'], ['u','U'], ['i','I'], ['o','O'], ['p','P'], ['[','{'], [']','}'], ['\\', '|'], # 3rd row ['capslock'], ['a','A'], ['s','S'], ['d','D'], ['f','F'], ['g','G'], ['h','H'], ['j','J'], ['k','K'], ['l','L'], [';',':'], ['\'','"'], ['return'], # 4th row ['left shift'], ['z','Z'], ['x','X'], ['c','C'], ['v','V'], ['b','B'], ['n','N'], ['m','M'], [',','<'], ['.','>'], ['/','?'], ['right shift'], # 5th row ['left fn'], ['left control'], ['left option'], ['left command'], ['spacebar'], ['right command'], ['right option'] ] def __init__(self, keyboard_layout, language=None): self.keyboard_layout = keyboard_layout self.language = Language(language) if language is not None else None self.keyboard_model = self.BASE_KEYBOARD_MODEL # configure keyboard keys base on configurations for i, keyboard_key in enumerate(self.keyboard_model): # set key characters based on keyboard layout key_chars = keyboard_layout[i] primary_char = key_chars[0] if len(key_chars) == 2: secondary_char = key_chars[1] else: secondary_char = None keyboard_key.set_characters(primary_char, secondary_char) # if language is set, adjust key difficulty score based on language if self.language is not None: key_char_frequency = self.language.get_letter_frequency( letter=primary_char.upper() ) if key_char_frequency is not None: init_score = keyboard_key.get_difficulty() to_deduct = init_score * (key_char_frequency / 100) adjusted_score = init_score - to_deduct keyboard_key.set_difficulty(adjusted_score) def get_key_from_character(self, char): for key in self.keyboard_model: chars = list(key.get_characters().values()) if char in chars: return key return None def calculate_key_transition_difficulty( self, char_1, key_1, char_2, key_2, round_to_int=False ): key_1_d = self.get_key_difficulty(char=char_1, key=key_1) key_2_d = self.get_key_difficulty(char=char_2, key=key_2) avg_difficulty = (key_1_d + key_2_d) / 2 # 1/4 is a magic number here base_trans_difficulty = avg_difficulty / 4 key_1_fing = key_1.get_finger() key_2_fing = key_2.get_finger() key_1_hand = 'left' if key_1_fing in self.LEFT_HAND else 'right' key_2_hand = 'left' if key_2_fing in self.LEFT_HAND else 'right' res = None # same key 2 times in a row if key_1 == key_2: res = base_trans_difficulty - (base_trans_difficulty / 3) # same finger on same hand elif key_1_fing == key_2_fing: res = base_trans_difficulty # same hand elif key_1_hand == key_2_hand: res = base_trans_difficulty - (base_trans_difficulty / 3) # otherwise, is different hand else: res = base_trans_difficulty - (base_trans_difficulty * 2/3) if round_to_int: return int(res) else: return res def get_key_difficulty(self, char, key): d = key.get_difficulty() if char == key.get_secondary_char(): shift_key = self.get_key_from_character(char='left shift') d = d + shift_key.get_difficulty() return d def get_keyboard_difficulty_for_word(self, word, round_to_int=False): keys_data = [] for char in word: k = { 'char': char, 'key': self.get_key_from_character(char) } # ignore keys that were not found if k['key'] is not None: keys_data.append(k) difficulty_vals = [] keys_data_len = len(keys_data) for index, key_data in enumerate(keys_data): # add key difficulty based on char k_difficulty = self.get_key_difficulty( char=key_data['char'], key=key_data['key'] ) difficulty_vals.append(k_difficulty) # add key transition difficulties if index < keys_data_len - 1: trans_difficulty = self.calculate_key_transition_difficulty( char_1=key_data['char'], key_1=key_data['key'], char_2=keys_data[index + 1]['char'], key_2=keys_data[index + 1]['key'] ) difficulty_vals.append(trans_difficulty) if round_to_int: return int(sum(difficulty_vals)) else: return sum(difficulty_vals)
78e5d17062d97389de59285b909a7ecf86a7d553
westgate458/LeetCode
/P0442.py
1,148
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 9 21:19:49 2020 @author: Tianqi Guo """ class Solution(object): def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ # Solution 1 beats 99.83%: mark all visited with extra space visited = [0]*len(nums) res = [] for num in nums: if visited[num-1]: res.append(num) else: visited[num-1] = 1 return res # Solution 2 beats 48.74%: find solution in-place # deal with each position in the array # ideally we want num[p] = p at each position after loop for p in xrange(len(nums)): # keep switching array elements, until one of the two occurs: # 1) num[p] = p, 2) number at target position is the same as current position while nums[nums[p]-1] != nums[p]: nums[nums[p]-1], nums[p] = nums[p], nums[nums[p]-1] # finally missing numbers will be filled with the numbers that appear twice return([num for p, num in enumerate(nums) if num - 1 != p])
90a042b1f1aabb64821ea5f385564e0a76a67a18
Aasthaengg/IBMdataset
/Python_codes/p02624/s003755111.py
77
3.5
4
N=int(input());a=0 for i in range(1,N + 1):b=N//i;a+=(b*(b+1)*i//2) print(a)
9ee48eb065112f15deade4bd8ae46c6c19bedc01
ce-sabo/python_trainning2
/make_datecolumns_and_split.py
588
3.765625
4
#必要なライブラリのimport import pickle import pandas as pd import datetime #CSVファイルを読み込みDataFrameにする df = pd.read_csv(rf"C:\Users\satoryo\Desktop\date_2020.csv", encoding="utf-8") #DateFrameのobjectの列からdatetime型の列を作成して追加する df["datetime"] = pd.to_datetime(df["date"]) #dateの列から年:Year、月:Month、日:Dayそれぞれの列を作成 df["Year"] = df["datetime"].dt.year df["Month"] = df["datetime"].dt.month df["Day"] = df["datetime"].dt.day #object列、date列を削除 df.drop(["date", "datetime"], axis=1)
a7692e246e0e9f6f36ff7fd9101d60b12458e2c0
everbird/leetcode-py
/2015/DeleteNodeInALinkedList_v0.py
855
4
4
#!/usr/bin/env python # encoding: utf-8 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def printl(root): if root: print root.val, printl(root.next) else: print class Solution: # @param {ListNode} node # @return {void} Do not return anything, modify node in-place instead. def deleteNode(self, node): pre = None h = node while h.next: h.val = h.next.val pre = h h = h.next pre.next = None if __name__ == '__main__': s = Solution() n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) root = n1 n1.next = n2 n2.next = n3 n3.next = n4 printl(root) print '-'*6 s.deleteNode(n3) printl(root)
a21e4aa2d0d2dfb008fba16eeec717bc156916e2
jizhi/jizhipy
/Math/DecomInt.py
398
3.578125
4
def DecomInt( cls, n ) : ''' n = int1 x int2 find int1 and int2 return: [int1, int2], .shape=(2, N) ''' import numpy as np n = int(round(n)) sign = 1 if(n>=0)else -1 if (n in [-1, 0, 1]) : return np.array([[1], [n]]) n = abs(n) a = np.arange(1, n) b = n / a m = a * b c = n - m a, b = a[c==0], b[c==0] ab = np.array([a, b])[:,:a.size/2+1][:,::-1] ab[1] *= sign return ab
9a5f6c18e3c6385b1cd3ee0259ff2286bc3884a7
Dymon-Klyn/Sanitation-App
/main.py
2,845
3.671875
4
# Tool to reenter society after COVID-19 # Make a GUI # Make a nice GUI a very nice GUI # We need a JSON File to keep track of the lists import json import tkinter as tk from tkinter import simpledialog # Look of the GUI """ | Welcome Back | ------------------------- | upcoming .... | | events completed | | curfew in... | | create new + | """ #JSON Functions def move_data(data, event, old, new): data[new].append(event) data[old].remove(event) def write_to_json(data, event, type): data[type].append(event) def delete_event(data, event, type): data[type].remove(event) def save_data(data): with open("data.txt", "w") as outfile: json.dump(data, outfile) def load_json_data(): with open("data.txt") as json_file: data = json.load(json_file) return data data = load_json_data() # Functions for the buttons go here def create(): answer = simpledialog.askstring("Input", "New Task", parent= main) # Json file should be here {upcoming:"answer"} write_to_json(data, answer, "events") save_data(data) # Displays the info on upcoming listbox.insert("end", answer) # This can be changed as we go along title = "Sanitation Alert" color = "red" root = tk.Tk() root.title(title) root.resizable(False, False) root.configure() # Main Frame main = tk.Frame(root, width = 70, height = 400 ) # Welcome Frame welcome_frame = tk.Frame(main, width = 70, height = 60) welcome_label = tk.Label(welcome_frame, text = "WELCOME BACK!", font = ("Times New Roman", 50)) spacer1 = tk.Frame(main, width = 70, height = 20) # Upcoming Frame upcoming_frame = tk.Frame(main, width = 70, height = 50, bg = color) listbox = tk.Listbox(upcoming_frame, width = 80, height = 5) for item in data["events"]: listbox.insert("end", item) spacer2 = tk.Frame(main, width = 70, height = 20) # Events Frame events_frame = tk.Frame(main, width = 70, height = 50, bg = "#A4F178") spacer3 = tk.Frame(main, width = 70, height = 20) # Curfew Frame curfew_frame = tk.Frame(main, width = 70, height = 50, bg = "#EFED85") spacer4 = tk.Frame(main, width = 70, height = 20) # Create Frame create_frame = tk.Frame(main, width = 70, height = 40) create_butt = tk.Button(create_frame, text = "Create New +", font = ("Times New Roman", 25), command = create) # Place all widgets on screen main.pack(fill="both", expand = True, padx = 30, pady = 30) welcome_frame.pack(fill = "x") welcome_label.grid(row = 0, column = 0) spacer1.pack(fill = "x") upcoming_frame.pack(fill = "x") listbox.pack() spacer2.pack(fill = "x") events_frame.pack(fill = "x") spacer3.pack(fill = "x") curfew_frame.pack(fill = "x") spacer4.pack(fill = "x") create_frame.pack(fill = "x") create_butt.grid(row = 0, column = 0) root.mainloop()
ab9705ac4f29e3782187d551d12479ac9ab0c133
Satriyahgpj27/SATRIYA-HENDRALOKA
/praktikum 5/praktikum 1/praktikum 05 no 1 dan 2.py
980
3.765625
4
#import library import time import math #scoring nilaiBahasaIndonesia = int(input("masukkan nilai bahasa indonesia anda disini")) time.sleep(1) if(nilaiBahasaIndonesia>0) and (nilaiBahasaIndonesia<100): if(nilaiBahasaIndonesia < 60): print("anda tidak lulus") elif(nilaiBahasaIndonesia >= 60): print("anda Lulus") else:(nilaiBahasaIndonesia < 0) print('invalid') time.sleep(2) nilaiIPA = int(input("masukkan nilai IPA anda disini")) time.sleep(1) if(nilaiIPA>0) and (nilaiIPA<100): if(nilaiIPA < 60): print("anda tidak lulus") elif(nilaiIPA >= 60): print("anda Lulus") else:(nilaiIPA < 0) print('invalid') time.sleep(2) nilaiMatematika = int(input("masukkan nilai Matematika anda disini")) time.sleep(1) if(nilaiMatematika>0) and (nilaiMatematika<100): if(nilaiMatematika < 70): print("anda tidak lulus") elif(nilaiMatematika >= 70): print("anda Lulus") else:(nilaiMatematika < 0) print('invalid')
b44210e974c01df066929568ecca6871b38e8c31
Habibur-Rahman0927/1_months_Python_Crouse
/Python All Day Work/04-05-2021 Days Work/Task_3_Directory_.py
702
3.75
4
import os # dir_1 = os.getcwd() # print('directory : ',dir_1) # dir_2 = os.getcwdb() # print(dir_2) # current Directory directory = os.getcwd() print("current Dir : ", directory) # # changing dircetory # os.chdir('E:\\Computer all Subject Study\\Python\\Python Crouse') # print('Current dir after change : ', os.getcwd()) # list dir files and folders print("current directory : ", os.getcwd()) dir_info = os.listdir() print("dir info: ", dir_info) # creating a new directory os.mkdir('Make_a_new_folder') print(os.listdir('Make_a_new_folder')) #rename a dir or file # os.rename('Make_a_new_folder', 'change_name_folder') # print(os.listdir()) os.remove('test.txt') print(os.listdir())
6d47164a532d256b475ffdcb96839375d88c11b4
thecodevillageorg/intro-to-python
/Python Day 9/exercise3.py
895
4.03125
4
subject1 = int(input("Enter the marks for the first subject: ")) subject2 = int(input("Enter the marks for the second subject: ")) subject3 = int(input("Enter the marks for the third subject: ")) subject4 = int(input("Enter the marks for the fourth subject: ")) # def function_name(parameters or arguments): """ sandwich - bread, meat, veggies def sandwich(bread,meat,veggies): sandwich = bread + meat + veggies return sandwich """ def grading_system(mark): if mark >= 80 and mark <=100: print("A") elif mark >= 60 and mark < 80: print("B") elif mark >= 50 and mark < 60: print("C") elif mark >= 45 and mark < 50: print("D") elif mark >= 25 and mark < 45: print("E") else: print("F") grading_system(subject1) grading_system(subject2) grading_system(subject3) grading_system(subject4)
00f4d068468d3f0609a4e352d481416db981fa91
jspahn/Python-Code
/Project-Euler/Finished Problems 1-25/21-AmicableNumbers.py
1,942
3.640625
4
# Project Euler # Problem 21: Amicable numbers # Let d(n) be defined as the sum of proper divisors of n # (numbers less that n which divide evenly into n). # If d(a) = b and d(b) = a, where a != b, then a and b # are an amicable pair and each of a and b are called amicable # numbers. # For example, the proper divisors of 220 are: # 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110; # therefore d(220) = 284. The proper divisors of 284 are: # 1, 2, 4, 71, 142; so d(284) = 220. # # Evaluate the sum of all amicable numbers under 10 000 # # Jeffrey Spahn # Created for Python 3.x import time def divisor_sum(number): """Finds the divisors of the number and returns the sum of the numbers""" div_sum = 0 divisors = [] for div in range(1, int(number**0.5) + 1): if number % div == 0: divisors.append(div) for d in divisors: div_sum += d + number //d div_sum -= number return div_sum # ------------------------------------------------------------ # Main # ------------------------------------------------------------ if __name__ == "__main__": start_time = time.time() n = 10000 to_check_number = [True] * (n+1) amicable_numbers = [] am_sum = 0 for i in range(1, n): if to_check_number[i]: a = divisor_sum(i) if i != a and i == divisor_sum(a): amicable_numbers.append((i, a)) am_sum += i + a to_check_number[i] = False if a < n: to_check_number[a] = False print(amicable_numbers) print("Their total sum: {}".format(am_sum)) print(" Completion time: {}".format(time.time() - start_time)) # Output # [(220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368)] # Their total sum: 31626 # Completion time: 0.4639449119567871
5b7e89b5355c631d4472b9647a2fd70c5847161a
rmwillow/WorkoutDatabase
/database.py
9,315
4.0625
4
# from .exercisesApi import exerciseList import sqlite3 from exercisesApi import exerciseApiResults import SqlQueries import os """ Class — A blueprint created by a programmer for an object. This defines a set of attributes that will characterize any object that is instantiated from this class. An object is created using the constructor of the class. This object will then be called the instance of the class. In Python we create instances in the following manner Instance = class(arguments) Object — An Instance of a class. This is the realized version of the class, where the class is manifested in the program. self represents the instance of the class. "__init__"This method called when an object is created from the class and it allow the class to initialize the attributes of a class """ class DataBase(object): def __init__(self, restart=False): """ :param restart: init calls on the data and restarts/refreshes it when it is set to True """ if not os.path.isfile("tutorial.db"): restart = True self.connection = sqlite3.connect("tutorial.db") self.cursor = self.connection.cursor() """ if set to true and the data base restarts it will drop all of the following tables""" if restart: self.cursor.execute('DROP TABLE IF EXISTS Exercises') self.cursor.execute('DROP TABLE IF EXISTS Muscles') self.cursor.execute('DROP TABLE IF EXISTS Users') self.cursor.execute('DROP TABLE IF EXISTS Workout') self.cursor.execute('DROP TABLE IF EXISTS Users_Workout') self.cursor.execute('DROP TABLE IF EXISTS Workout_Exercise') self.cursor.execute('DROP TABLE IF EXISTS Previous_Workouts') self.cursor.execute(SqlQueries.exercises_table) self.cursor.execute(SqlQueries.muscles_table) self.cursor.execute(SqlQueries.Users_Table) self.cursor.execute(SqlQueries.Workout_Table) self.cursor.execute(SqlQueries.Users_Workout_Table) self.cursor.execute(SqlQueries.Workout_Exercise_Table) """after it has dropped the tables it is set to create the new tables above""" """it than trys and executes muscle table id index which we created in my quieries.py using an input function of python called index. Index which searches for a given element from the entire list and returns the lowest index where the element appears, except/unless it already exists""" # try: # self.cursor.execute(muscles_table_id_index) # except Exception as exception: # print(exception) # print('this index already exists') """ for muscle and exercises table in exerciseApiResults dictionary it executes muscle_table_insert and inserts the value of muscle than it selects muscleId column from muscles table where muscle name equals to null. it than takes muscle id and uses fetchone which Fetches the next row in the list""" for muscle, exercises in exerciseApiResults.items(): self.cursor.execute(SqlQueries.muscles_table_insert, [muscle]) self.cursor.execute('select MuscleID from Muscles where MuscleName = ?', [muscle]) muscleId = self.cursor.fetchone()[0] for exercise in exercises: self.cursor.execute(SqlQueries.exercises_table_insert, [exercise, muscleId]) self.cursor.execute(SqlQueries.exercises_table_update_muscleid) self.cursor.execute('DELETE FROM Muscles WHERE MuscleID = 19;') self.connection.commit() def __del__(self): self.connection.close() def close(self): self.connection.close() def search_by_muscle(self, muscle): """ :param muscle: :return: the next row in the list of muscles """ results = [] self.cursor.execute(SqlQueries.search_by_muscle, [muscle]) sql_results = self.cursor.fetchall() for row in sql_results: results.append({'ExerciseName': row[0], 'ExerciseId': row[1]}) return results def search_by_exercise_id(self, exercise): """ :param exercise: list of exercises :return: the next row in the list of exercises """ results = [] self.cursor.execute(SqlQueries.search_by_exercise_id, [exercise]) sql_results = self.cursor.fetchall() for row in sql_results: results.append(row[0]) return results def search_by_firstname(self, firstname): """ :param firstname: :return: first name entered through user input """ try: self.cursor.execute('select UsersId from Users where UsersFirstName = ?', [firstname]) return self.cursor.fetchone()[0] except: return False def search_by_workout(self, workout): """ :param workout: :return: workout entered though user data base newly or previously, than fetching it from the next row in the list """ try: self.cursor.execute('select WorkoutID from Workout where WorkoutName = ?', [workout]) return self.cursor.fetchone()[0] except: return False def add_user(self, firstname, lastname): """ :param firstname: :param lastname: :return: firstName and Lastname from user input and inserts it into the database with user_table """ self.cursor.execute(SqlQueries.Users_Table_insert, [firstname, lastname]) self.connection.commit() def Workout_Table_insert(self, workoutName): """ :param workoutName: :return: workoutname that was inputed by the user and inserts it into workout_table """ self.cursor.execute(SqlQueries.Workout_Table_insert, [workoutName]) self.connection.commit() def Previous_Table_Workouts_insert(self, existingWorkout, workoutId, MultipleSelection): """ :param existingWorkout: :param workoutId: :param MultipleSelection: :return: """ self.cursor.execute(SqlQueries.Previous_Table_Workouts_insert, [existingWorkout, workoutId, MultipleSelection]) self.connection.commit() def Users_Workout_Table_insert(self, userId, workoutId): """ :param userId: :param workoutId: :return:it inerts userId and workoutId into user_workout_table assigning it a number in order of input being entered """ self.cursor.execute(SqlQueries.Users_Workout_Table_insert, [userId, workoutId]) self.connection.commit() def Workout_Exercise_Table_insert(self, workoutId, exerciseId): """ :param workoutId: :param exerciseId: :return: assigning workoutId and exerciseId into workout_exercise_table """ self.cursor.execute(SqlQueries.Workout_Exercise_Table_insert, [workoutId, exerciseId]) self.connection.commit() def search_by_workout_exercises(self, workoutId): """ :param firstname: :return: Fetches the next row in the table of exercises, which is first name and appends the results to an empty list """ results = [] self.cursor.execute(SqlQueries.search_by_workout_exercises, [workoutId]) sql_results = self.cursor.fetchall() for row in sql_results: results.append(row[0]) return results def search_by_WorkoutID(self, workoutName): results = [] self.cursor.execute(self.search_by_WorkoutID, [workoutName]) sql_results = self.cursor.fetchall() for row in sql_results: results.append(row[0]) return results def display_all_muscles(self): """ :return: returns the list of results and displays all muscles in that list """ results = [] self.cursor.execute('select MuscleName from Muscles') sql_results = self.cursor.fetchall() for row in sql_results: results.append(row[0]) return results def existingWorkout(self, Users_Workout, results=None): self.cursor.execute(self.search_by_previous_workouts, [Users_Workout]) sql_results = self.cursor.fetchall() for row in sql_results: results.append(row[0]) return results self.connection.commit() def search_by_previous_workouts(self, WorkoutName): results = [] self.cursor.execute(SqlQueries.Previous_Table_Workouts, [WorkoutName]) sql_results = self.cursor.fetchall() for row in sql_results: results.append(row[0]) return results def search_workout_by_userId(self, userId): results = [] self.cursor.execute(SqlQueries.search_workout_by_userId, [userId]) sql_results = self.cursor.fetchall() for row in sql_results: results.append({'WorkoutID': row[0], 'WorkoutName': row[1]}) return results
0bdcb681b9c0f22b858525391b3224c946a16bd8
fredy-glz/Ejercicios-de-Programacion-con-Python---Aprende-con-Alf
/02_Condicionales/04_CondicionalesPython.py
341
3.96875
4
# JOSE ALFREDO ROMERO GONZALEZ # 12/10/2020 num = int(input("Ingrese un numero: \n")) if(num % 2 == 0): print("Es par.") else: print("Es impar") # SOLUCION DE https://aprendeconalf.es/ n = int(input("Introduce un número entero: ")) if n % 2 == 0: print("El número " + str(n) + " es par") else: print("El número " + str(n) + " es impar")
fa3404e643730448011f1f4aa261431f8d2360c4
chdlkl/python
/function/func1.py
8,231
4.25
4
# 函数规则: # 函数代码块以def关键词开头,后接函数标识符名称(函数名)和圆括号() # 任何传入参数和自变量必须放在圆括号中间 # 函数内容以冒号起始,并且缩进 # return [表达式]结束函数。不代表达式的return相当于返回none # python1 def hello(): print ( " hello, world! " ) hello ( ) # 自定义函数用于输出信息 # python2 import math def area( r ): s = math.pi * r * r return s print ( " area = ", area(1.0) ) def print_luk( name ): return name print ( " name = ", print_luk( "luk" ) ) # 这样调用,return后面必须跟返回值,否则返回none # print_luk( "luk" ) # 这样调用函数,因为函数print_luk中无执行语句,就算有返回值,也无输出 # python3 # python传不可变对象 def ChangeInt(a): print ( ' before a = ', a ) a = 10 print ( ' after a = ', a ) return a b = 2 print ( " func value: ", ChangeInt(b) ) print ( " b = ", b ) # 经过测试,建议写print ( 函数名(参数) ),即print ( ChangeInt(b) ) # 如果写ChangeInt(b)不会输出信息 # python传入可变参数 def Changme( list1 ): list1.append( 1 ) # append()函数里面的参数为1个整数,或列表(字典等) print ( " in : ", list1 ) return list1 list2 = [ 10, 20, 30, 40 ] Changme( list2 ) # 如果写成Change( list2[:] ),则两者的id不同 print ( " out : ", list2 ) # 特别注意 def Changeme( mylist ): mylist = [1,2,3,4]; print ( " In function: ", mylist ) return mylist = [10,20,30,40]; Changeme( mylist ); print ( " Out function: ", mylist ) # 这样写也不会影响外部的mylist,这是因为外面的mylist为全局变量,Changeme函数中的mylist为局部变量,两者id不同 # python传入时不指定参数顺序 def printinfo(name, age): print(" name: ", name); print(" age: ", age); return; # 调用printinfo函数 printinfo( age = 50, name = "runoob" ) # 如果写成printinfo( 50, 'runoob' )则要按顺序 # python传入默认参数,在调用函数时,如果没有传递参数(fortran中的实参),则会使用默认参数。 def printinfo( name, age = 35 ): print ( " name: ", name ) print ( " age: ", age ) return printinfo( age = 50, name = 'luk' ) print ( "--------------------" ) # 当函数中虚参有数值,并且在程序内部过程有输出,只写printinfo()也会输出35 printinfo( name = 'luk' ) # python传入可变长度变量 def printinfo( arg1, *vartuple ): print ( " arg1: ", arg1 ) for var in vartuple: print ( " var: ", var ) return printinfo ( 10 ) printinfo ( 10, 20, 30 ) # python匿名函数 # 1. python使用lambda来创建匿名函数 # 2. lambda只是一个表达式,函数体比def简单 # 3. lambda函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数 sum1 = lambda arg1, arg2: arg1 + arg2 print ( " 10 + 20 = ", sum1( 10, 20 ) ) print ( " 20 + 30 = ", sum1( 20, 30 ) ) # return语句 def sum1( arg1, arg2 ): total = arg1 + arg2 print ( " in function: ", total ) return total print ( " out function: ", sum1( 10, 20 ) ) # 变量作用域 # python中,程序的变量并不是哪个位置都可以访问的,访问权限决定于这个变量在哪里赋值 # 变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。python的作用域一共有四种 # 1. L(Local) 局部作用域 # 2. E(Enclosing) 闭包函数外的函数中 # 3. G(Global) 全局作用域 # 4. B(Bulit-in) 内建作用域 x = int(2.9) # 内建作用域 g_count = 0 # 全局作用域 def outer(): o_count = 1 # 闭包函数外的函数中 def inner(): i_count = 2 # 局部作用域 # python中只有模块(module),类(class),以及函数(def,lambda),才会引入新的作用域 # 其他代码块(如if/elif/else/、try/expect、for/while等)是不会引入新的作用域,也就是说这些语句内定义的变量,外部也可以访问 # 下面例子中,msg变量定义在if语句块中,但外部还是可以访问的 if True: msg = ' I am lukailiang! ' print ( msg ) # 如果将msg定义在函数中,则它就是局部变量,外部不能访问 def test(): msg1 = ' error! ' # print ( msg1 ) 这句报错,因为在全局中没定义变量msg1 # 这里值得注意一下,将局部变量与全局变量的命名最好不一致,如果一致,有时会混淆 # 例如,上面如果在函数test中定义为msg,然后再print(msg),如果全局中定义了msg,就会输出全局中msg的值,而不是函数test中msg的值,这里注意一下 # 全局变量与局部变量 # 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域 # 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问 total = 0; # 这是一个全局变量 def sum( arg1, arg2 ): total = arg1 + arg2; # total在这里时局部变量 print ( " In function total is ", total ) return total; # 调用函数sum,输出函数执行语句结果 sum(10,20) print ( " Out function total is ", total ) # global 和 nonlocal 关键字 num = 1 def fun1(): global num # 说明num是全局变量和局部变量,意思是局部变量num改变后,全局变量中的num也会改变 print ( " before: num = ", num ) num = 123 # 修改num的值 print ( " after: num = ", num ) # 调用函数 fun1() # 如果要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量则需要nonlocal关键字 def outer(): num = 10 def inner(): nonlocal num # nonlocal关键字声明 num = 100 print ( " num = ", num ) # 调用函数inner inner() print ( " num = ", num ) # 调用函数outer outer() # lambda匿名函数也是可以用“关键字参数”进行参数传递,为了不记混淆,建议在调用函数的同时进行指定,例如g(x=1,y=2) g = lambda x, y: x**2 + y**2 print ( " g(2,3) = ", g(2,3) ) # 默认为g(x=2, y=3) print ( " g(y=3,x=2) = ", g(y=3,x=2) ) # 不选择默认时,需要指定 # 传入一个参数 g = lambda x=0, y=0: x**2 + y**2 print ( " g(2) = ", g(2) ) # 默认为g(x=2),y值为函数中y的值 print ( " g(y=3) = ", g(y=3) ) # 此时需要指定 # 下面这个例子证明全局变量在局部变量中仍然起作用(但是局部改变后并不影响外部的值),反之则不行 # 如果想通过改变局部变量的值,而改变全局变量的值,需要使用global b = 1 def ss(): a = 1 + b print ( " a = ", a ) # 第一次调用函数ss() ss() # 该变b的值 b = 10 # 再次调用ss() ss() # 严重注意:函数内能访问全局变量,但不能更新(修改)其值,除非使用global # 例如 a = 10 def test(): a = a + 1 print ( " a = ", a ) # test() # 这种情况报错,主要原因还是函数中局部变量a没有声明(fortran为初始化)或是非法修改全局变量a的值,记住,只能访问不能修改 a = 10 def sum(n): n = n + a # 访问全局变量的值 # 如果加下面一句会报错 # a = 1,不能修改全局变量的值 print ( " a = ", a, end = "," ) print ( " n = ", n ) sum(3) # 下面代码是变量作用域的例子 # 1. 局部作用域 x = int(3.3) x = 0 def outer(): x = 1 def inner(): x = 2 print ( " x = ", x ) # 执行结果为2,因为在函数inner内部找到了变量x inner() outer() # 2. 闭包函数外的函数中 x = int(3.3) x = 0 def outer(): x = 1 def inner(): i = 2 print ( " x = ", x ) # 在局部变量中找不到,去局部外的局部寻找 inner() outer() # 3. 全局作用域 x = int(3.3) x = 0 def outer(): o = 1 def inner(): i = 2 print ( " x = ", x ) # 在局部(inner函数),局部的局部(outer函数)中都没找到,去全局找 inner() outer() # 4. 内建作用域 x = int(3.3) g = 0 def outer(): o = 1 def inner(): i = 2 print ( " x = ", x ) inner() outer() # 寻找列表中绝对值最大的下标 myList = [-1,2,-3,4,6,-5] absList = ( map(abs, myList) ) #对于Python3.x需要用list函数对map的返回值转换为列表 absList = list ( absList ) print (absList) print ( absList.index( max( absList ) ) )
8da058b66d21f7c037e5a6d451ecbf9f6296a60b
manali027/Vocab_Building_App
/check.py
393
3.671875
4
'''file=open("data.txt",mode='r') with open("data.txt",mode='r') as file: for line in file: print(line)''' '''import linecache line_number=3 line=linecache.getline("data.txt",line_number) print(f"line number is {line_number} and the line is: {line}")''' with open("data.txt",mode='r') as file: f=file.readlines() for line in f: print (line.strip().split(":")[0])
7fd6ee9b4abac69f33322ca2014abc2f4973f026
sivaneshl/python_data_analysis
/applied_machine_learning/supervised_machine_learning/ridge_regression_regularization.py
1,094
3.875
4
# Ridge regression with regularization parameter: alpha import numpy as np from applied_machine_learning.fundamentals_of_machine_learning.adspy_shared_utilities import load_crime_dataset from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split scalar = MinMaxScaler() (X_crime, y_crime) = load_crime_dataset() X_train, X_test, y_train, y_test = train_test_split(X_crime, y_crime, random_state=0) X_train_scaled = scalar.fit_transform(X_train) X_test_scaled = scalar.fit_transform(X_test) print('Crime Dataset') print('Ridge regression - Effect of alpha regularization parameter') for this_alpha in [0, 1, 10, 20, 50, 100, 1000]: linridge = Ridge(alpha=this_alpha).fit(X_train_scaled, y_train) print('Alpha = {}'.format(this_alpha)) print('R-squared score (training): {:.3f}'.format(linridge.score(X_train_scaled, y_train))) print('R-squared score (test): {:.3f}'.format(linridge.score(X_test_scaled, y_test))) print('Number of non-zero features: {}'.format(np.sum(linridge.coef_ != 0)))
f133019735fca2370628d2196bfaee4b018224ad
syn7hgg/ejercicios-python
/11_5/3.py
513
3.71875
4
def es_primo(num): if num > 1: for i in range(2, int(num / 2) + 1): if (num % i) == 0: return False else: return True else: return False while True: try: num = int(input("Ingrese número (0 para salir): ")) if num == 0: break res = es_primo(num) if res: print("Es primo.") else: print("No es primo.") except ValueError: print("Debe ser entero: ")
4f387941ce630f1da2ccc653f9d8a1783fa7f5bf
hobbitsyfeet/PDR
/Stopwords/create_csv.py
1,035
3.625
4
import sys import csv import os # print 'Number of arguments:', len(sys.argv), 'arguments.' # print 'Argument List:', str(sys.argv) word_file = sys.argv[1] new_file = sys.argv[2] #populates file [argv 2] with a list of words from [argv 1] def populate_file(file): with open(file, 'w') as csv_file: writer = csv.writer(csv_file, delimiter=',', quotechar='\'', quoting=csv.QUOTE_ALL) writer.writerow(create_list(word_file)) csv_file.close() #returns a list of words from a file of words seperated by line. def create_list(file): with open(file, 'r') as wordlist: temp_list = [] for line in wordlist: if line not in ['\\n', '\\r', '\\ni', '',]: line = line.replace("\n","") if len(line) is not 0: temp_list.append(line) wordlist.close() return(temp_list) print("Checking for file...") if os.path.isfile(new_file): populate_file(new_file) else: f = open(new_file,"w") f.close() populate_file(new_file)
84b3ff61e0be43222eca0548af7dacd58d8620f2
szymon5816/test_name
/demo.py
1,055
3.859375
4
import unittest class TestDemo(unittest.TestCase): @classmethod def setUpClass(cls): print("#" * 30) print("Przed testem") print("#"*30) def setUp(self): print("Wykonanae przed każdym testem") def test_A(self): print("test A") def test_B(self): print("test B") def test_C(self): a= True self.assertTrue(a, "A is not Truee") def test_D(self): a = "alfa" b="alfa" self.assertEqual(a,b, "a is not egual b ") def test_E(self): a= 5 b=3 self.assertLess(a,b, "B is less than A ") def test_F(self): a=2 b=2 self.assertIs(a,b) def test_G(self): a=6 b=5 self.assertGreater(a,b,"a is not greater than b") def tearDown(self): print("Wykonane po każdym tescie") @classmethod def tearDownClass(cls): print("#" * 30) print("Po teście") print("#" * 30) if __name__ == '__main__': unittest.main()
1548be67abd038234f2af95e9aa96f0a27c9b2c7
dabinc/MoreLoopsWithinLoops
/src/m2_more_nested_loops_in_graphics.py
2,600
4.5
4
""" This project demonstrates NESTED LOOPS (i.e., loops within loops) in the context of TWO-DIMENSIONAL GRAPHICS. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and Dabin Choi """ # T ODO: 1. PUT YOUR NAME IN THE ABOVE LINE. import rosegraphics as rg def main(): """ Calls the other functions to test them. """ run_test_draw_upside_down_wall() def run_test_draw_upside_down_wall(): """ Tests the draw_upside_down_wall function. """ # Tests 1 and 2 are ALREADY DONE (here). window = rg.RoseWindow(550, 300, 'Upside-down wall, Tests 1 and 2') rectangle = rg.Rectangle(rg.Point(125, 230), rg.Point(155, 250)) draw_upside_down_wall(rectangle, 8, window) rectangle = rg.Rectangle(rg.Point(375, 175), rg.Point(425, 225)) draw_upside_down_wall(rectangle, 4, window) window.close_on_mouse_click() def draw_upside_down_wall(rectangle, n, window): """ See MoreWalls.pdf in this project for pictures that may help you better understand the following specification: Draws an "upside-down wall" on the given window, where: -- The BOTTOM of the wall is a single "brick" that is the given rg.Rectangle. -- There are n rows in the wall. -- Each row is a row of "bricks" that are the same size as the given rg.Rectangle. -- Each row has one more brick than the row below it. -- Each row is centered on the bottom row. Preconditions: :type rectangle: rg.Rectangle :type n: int :type window: rg.RoseWindow and n is nonnegative. """ # ------------------------------------------------------------------ # TOD O: 2. Implement and test this function. # Some tests are already written for you (above). # ------------------------------------------------------------------ ur=rectangle.corner_1 lr=rectangle.corner_2 urr=rectangle.corner_1 lrr=rectangle.corner_2 height=rectangle.get_height() width=rectangle.get_width() for k in range (n): for e in range (k+1): newrect= rg.Rectangle(ur,lr) newrect.attach_to(window) window.render(0.5) lr=rg.Point(lr.x+width, lr.y) ur=rg.Point(ur.x+width, ur.y) lrr = rg.Point(lrr.x-width/2, lrr.y-height) urr = rg.Point(urr.x-width/2, urr.y-height) lr=lrr ur=urr # ---------------------------------------------------------------------- # Calls main to start the ball rolling. # ---------------------------------------------------------------------- main()
f737817e550f2fdd593f511ab4485088700a420b
SuSFCTV/RaifhackDS
/feature_extractors/floor.py
3,244
3.5
4
from statistics import mean from typing import Optional import pandas as pd import numpy as np def floor_preprocess(df: pd.DataFrame) -> pd.DataFrame: preprocess_floor = df['floor'].apply(parse_floor) floor = 1.93 preprocess_floor = preprocess_floor.apply(lambda x: floor if pd.isna(x) else x) return preprocess_floor.apply(lambda x: np.log1p(x) if x > 0 else x) def parse_floor(floor: Optional[str]) -> Optional[int]: if floor is None or pd.isna(floor): return if type(floor) == float or type(floor) == int: return int(floor) floor = floor.lower() # todo check -1 examples floor = floor.replace('подвал', ',0,') floor = floor.replace('цоколь', ',0,') floor = floor.replace('-', ',') # drop extra symbols allowed_chars = '1234567890,.' floors = list(filter(lambda c: c in allowed_chars, floor)) floors = ''.join(floors).split(',') def safe_cast(number: str) -> Optional[int]: try: return int(float(number)) except ValueError: pass # drop not numbers floors = list(map(safe_cast, floors)) floors = list(filter(lambda floor: floor is not None, floors)) # calc mean floor if len(floors) == 0: return floor = int(mean(floors)) return floor if __name__ == '__main__': hard_cases = [ '1', '18.0', 'подвал, 1', '2', 'подвал', 'цоколь, 1', '1,2,антресоль', 'цоколь', '4', '5', 'тех.этаж (6)', '3', 'Подвал', 'Цоколь', '10', 'фактически на уровне 1 этажа', '6', '1,2,3', '1, подвал', '1,2,3,4', '1,2', '1,2,3,4,5', '5, мансарда', '1-й, подвал', '12', '15', '13', '1, подвал, антресоль', 'мезонин', 'подвал, 1-3', '8', '7', '1 (Цокольный этаж)', '3, Мансарда (4 эт)', 'подвал,1', '1, антресоль', '1-3', 'мансарда (4эт)', '1, 2.', '9', 'подвал , 1 ', '1, 2', 'подвал, 1,2,3', '1 + подвал (без отделки)', 'мансарда', '2,3', '4, 5', '1-й, 2-й', '18', '1 этаж, подвал', '1, цоколь', 'подвал, 1-7, техэтаж', '3 (антресоль)', '1, 2, 3', 'Цоколь, 1,2(мансарда)', 'подвал, 3. 4 этаж', 'подвал, 1-4 этаж', 'подва, 1.2 этаж', '2, 3', '-1', '1.2', '11', '36', '7,8', '1 этаж', '1-й', '3 этаж', '4 этаж', '5 этаж', 'подвал,1,2,3,4,5', '29', 'подвал, цоколь, 1 этаж', '3, мансарда' ] for case in hard_cases: print(case, '->', parse_floor(case))
d2dce500f9e3ec8c0347d43461a99a9439cd972d
MarinaFirefly/Python_homeworks
/5/at_lesson/square.py
975
4.125
4
#find squres of the simple numbers using map list_numers = [1,2,3,45,6,8,9,12,8,8,17,29,90,77,113] #function that calculates squares def sqrt_num(num): return num**2 #function that return new list consisting of simple numbers def dividers(list_num): new_list = [] for num in list_num: i = 2 cnt = 1 if num == 1 else 0 #take 1 as not simple number while i <= num/2: if num%i == 0: cnt+=1 #if num has dividors between 2 and num/2 cnt is equal 1 break #break if cycle find out some dividor between 2 and num/2 else: i+=1 if cnt == 0: new_list.append(num) return new_list print(list(map(sqrt_num, dividers(list_numers)))) #ugly method that uses 2 functions: 1 finds dividors and 2 makes a list of simple numbers (besides 1 is simple here) def div_for_num(num): return [i for i in range (1,num) if num%i == 0] def div_for_list(list_num): return [i for i in list_num if len(div_for_num(i))<2] print(list(map(sqrt_num, div_for_list(list_numers))))
85999b8cd57ff165560c5174a03539a34f6fcc0b
aultimus/project_euler
/14_longest_collatz_seq.py
1,176
3.859375
4
# http://projecteuler.net/problem=14 # The following iterative sequence is defined for the set of positive integers: # # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # # It can be seen that this sequence (starting at 13 and finishing at 1) # contains 10 terms. Although it has not been proved yet (Collatz Problem), # it is thought that # all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain? # # NOTE: Once the chain starts the terms are allowed to go above one million. def collatz(n): """ Returns number of values in collatz sequence starting at arg n""" count = 1 while n != 1: count += 1 if n % 2 == 0: # even n = n / 2 else: n = 3 * n + 1 return count def main(): m = 0 # max collatz chain size so far n = 0 # start of max collatz chain so far for i in xrange(1, 1000001): t = collatz(i) if t > m: n, m = i, t return n if __name__ == "__main__": print main()
9fbc247356aee27bc9a05249975047cd48db259a
zaimeali/Data-Structure-and-Algorithms
/Coding Interview/Google/problem3.py
1,324
3.8125
4
# Google Video https://www.youtube.com/watch?v=XKu_SEDAykw # [1, 2, 3, 9] no pair equal to 8 # [1, 2, 4, 4] => 4, 4 = 8 def solution1(arr, result): # Complexity: O(n) because it is linear # arr.sort() # if sorting then complexity will be O(N*logN) low = 0 high = len(arr) - 1 while low < high: val = arr[low] + arr[high] if val == result: return True, (arr[low], arr[high]) if val > result: high -= 1 if val < result: low += 1 return False def solution2(arr, result): # Linear Solution O(n) comp = set() for num in arr: if num in comp: return True, (num, result - num) comp.add(result - num) return False if __name__ == '__main__': arr1 = [1, 2, 3, 9] arr2 = [1, 2, 4, 4] arr3 = [7, 4, 1, 2] arr4 = [5, 2, 9, 3] result = 8 # if not sorted first sort # arr.sort() print("Solution 1:") print(solution1(arr1, result)) print(solution1(arr2, result)) print(solution1(arr3, result)) print(solution1(arr4, result)) print("-=-=-=-=-=-=-=-") print("Solution 2:") print(solution2(arr1, result)) print(solution2(arr2, result)) print(solution2(arr3, result)) print(solution2(arr4, result)) print("-=-=-=-=-=-=-=-")
5616ce6d5141b2379c4baa5a20fdb362039065e4
sandeepkp07/updates
/nov6-7/18.2.py
996
3.828125
4
import random class Cards(object): suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"] rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7","8", "9", "10", "Jack", "Queen", "King"] def __init__(self,suit=0,rank=2): self.suit = suit self.rank = rank def __str__(self): return ('%s of %s' % (Cards.rank_names[self.rank],Cards.suit_names[self.suit])) def __cmp__(self,other): t1 = self.suit,self.rank t2 = other.suit,other.rank return cmp(t1,t2) class Deck(Cards): def __init__(self): self.cards = [] for suit in range(4): for rank in range(1,14): card = Cards(suit,rank) self.cards.append(card) def __str__(self): res = [] for cards in self.cards: res.append(str(cards)) return '\n'.join(res) def pop_card(self): return self.cards.pop() def add_card(self,card): self.cards.append(cards) def shuffle(self): random.shuffle(self.cards) def sort(self): self.cards.sort() deck = Deck() deck.shuffle() deck.sort() print (deck)
1e7a98a75bbc1b0815f1db9f54589e2f70007c18
brentholmes317/Fire_Department
/fire_department/fire_department/fire_department.py
3,254
4.09375
4
from sys import exit import math """ The idea behind the fire_department function is to answer the following: If a town wishes to place a fire department so that the time for the firetrucks to get to any location in the town is minimized, where should they put the fire station? I wish to add to this problem that unoccupied lots may be added as potential locations but will not be considered as a place that the fire truck needs to be able to get to. I also will give the option to only place the fire department somewhere that is currently unoccupied. The input will be a cost matrix and an integer that tells me how many of the locations given are vacant and an integer that tells me if we are restricted to vacant lots (0 for restricted to vacant lots). The cost matrix will be set up so that the first k rows are vacant lots with the remaining rows being occupied spaces. This function is to be called by interactive programs one of which asks the user for to input the cost matrix as a list, the other of which will take the cost matrix as a file as input in the command line. """ def convert_integer(s): try: return int(s) except ValueError: return None def fire_department(matrix, number, vacant): rows = matrix[0].__len__() #this variable will tell us which locations we need to consider for the fire #department. We start by assuming we must consider all locations last_row = rows if vacant == 1: #we only consider vacant locations last_row = number else: pass #now we will find the distance from the first possible location to #the furthest non-empty property largest_distance = matrix[0][number] #initialize as the distance to the first-nonempty property answer = 0 #we start with the first lot as our answer. it may change. for j in range(number+1,rows): if(matrix[0][j] > largest_distance): largest_distance = matrix[0][j] for i in range(1,last_row): temp = matrix[i][number] #a variable that keeps track of row i's largest_distance for k in range(number, rows): #going through the matrix one row at a time if(matrix[i][k] > temp): temp = matrix[i][k] if(temp < largest_distance): largest_distance = temp answer = i print(f"The fire department should be placed in lot {answer}.") print(f"This location is no further than {largest_distance} from any occupied lot.") exit(0) def split_input(sequence): #this code will turn the line into a row of the matrix words = sequence.split(',') #a variable that indicates the splitting by commas failed. We will use this #to see if splitting by spaces also fails at which point we give up strike = 0 #checks if splitting by spaces worked if not we assign a strike for word in words: if(convert_integer(word) == None): strike = 1 if strike == 1: words = sequence.split() #checks if splitting by commas works. Either will do but we demand consistency for word in words: if(convert_integer(word) == None): print("Your input is improperly formatted.") exit(0) return words
f7c7c14716bd01e4d91f2ac87c628f72def1e824
lkuszal/licencjat
/caesar.py
2,737
4.03125
4
"""simple monoalphabetic rotation cipher with integer as key, and optional reference alphabet (by default full upperlatin) if reference alphabet is full lower/upper, ciphering will convert them both to same letter, but will keep capitalization""" # Written by Lukasz Cholodecki as part of 2021 thesis from pattern import MasterCipher alph_EN = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' class Caesar(MasterCipher): """simple cipher working by rotating whole alphabet by given shift value. Due to not using letter-specific method, any rot cipher with different alpabet can be used e.g. rot47 instead of simply shifting every letter of iterated text, we use maketrans methods due to much higher efficiency this method simply creates maketrans dicts by rotating given reference alphabet""" def __init__(self, enc_key, reference=alph_EN): try: enc_key = int(enc_key) % len(reference) except ValueError: assert enc_key.isnumeric() if reference.islower() or reference.isupper(): ci_table = str.maketrans(reference.lower() + reference, reference.lower()[enc_key:] + reference.lower()[:enc_key] + reference[enc_key:] + reference[:enc_key]) enc_key = -enc_key % len(reference) de_table = str.maketrans(reference.lower() + reference, reference.lower()[enc_key:] + reference.lower()[:enc_key] + reference[enc_key:] + reference[:enc_key]) else: ci_table = str.maketrans(reference, reference[enc_key:] + reference[:enc_key]) enc_key = -enc_key % len(reference) de_table = str.maketrans(reference, reference[enc_key:] + reference[:enc_key]) self.cipher_key = ci_table self.decipher_key = de_table self.reference = reference # cipher and decipher methodes use both same method from abc MasterCipher, by simply using string .translate method def cipher(self, plain_text): return super().cipher(plain_text) def decipher(self, ciphered_text): return super().decipher(ciphered_text) library = {"ROT13": ['13'], "ROT47": ('47', ('!"#$%&\'()*+,-./0123456789:;<=>?' '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))} if __name__ == "__main__": asd = Caesar(*library["ROT13"]) sad = Caesar(*library["ROT47"]) print(asd.cipher("Chron pulk twoj i szesc flag")) print(sad.cipher("Chron pulk twoj i szesc flag")) print(asd.cipher("Pueba chyx gjbw v fmrfp synt")) print(sad.cipher("r9C@? AF=< EH@; : DK6D4 7=28")) print(asd.decipher("Pueba chyx gjbw v fmrfp synt")) print(sad.decipher("r9C@? AF=< EH@; : DK6D4 7=28"))
1e25805145d0ac4ae4c43b245ddf9d1ee372133e
Ahamed-Sakir/NSL_AI_Training_Materials
/Python_Basic/Week1/Syntax.py
624
4.3125
4
# Basic String syntax name = "Sakir Ahamed" print(name) # We can use single quote also name1 = 'Bangladesh is my country' print(name1) # If we use single quote in a sentence then use '\' single_quote = 'This is Anannyar\'s property' print(single_quote) # User input user_input = input('Give your name:') print('This is your name:', user_input) # Output formatting number = 6 number_2 = 2 print(f'This is another number {number}, here is one also {number_2}') # Another way of formatting print('This is another number {0}, here is one also {1}'.format(number, number_2)) # Inplace Operator x = 6 x += 2 # x = x + 2 print(x)
d6097be507fe05e514deb7a51877dda47aa6fd13
ash/amazing_python3
/279-list-diff.py
287
3.890625
4
# Get the "difference" between the # two lists data1 = [10, 20, 30, 40, 50] data2 = [5, 10, 15, 20, 25] diff = list( set(data1).symmetric_difference( set(data2) ) ) print(diff) # only elements which are either in # the first or in the second lists, # but not in both
45a44d4554cf3c7f8d6a300c2e32324ec1d02679
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/crrlen001/piglatin.py
1,797
3.953125
4
def toPigLatin(s): return (translate(s)) def findFirstVowel(given_word): '''Returns the location of the first vowel in the given word.''' for i in range(len(given_word)): if checkVowel(given_word[i]) == True: return i def translateWord(input_string): '''Translates the word and returns the translation to the caller.''' firstVowel = findFirstVowel(input_string) if firstVowel == None: translated = ('a' + input_string + "ay") elif firstVowel == 0: translated = (input_string + "way") elif firstVowel >= 1: translated = (input_string[firstVowel:] + 'a' + input_string[:firstVowel] + "ay") else: translate = ('a' + input_string + 'ay') return translated def translate(inputWords): '''Accepts multiple words (separated by spaces) and will return the entire translated phrase.''' wordList = inputWords.split() translatedString = str() for word in range(len(wordList)): translatedString = (translatedString + translateWord(wordList[word]) + " ") return translatedString def checkVowel(char): '''Returns "True" if submitted charecter is a vowel.''' vowels="AaEeIiOoUu" for vowel_test in vowels: if char == vowel_test: return True return False def toEnglish(s): # MUST use a space between the quotations words = s.split(" ") ; # split based on space character for word in words: if word[-3:] == 'way': qq = word[:-3] return qq elif word[-3:] != 'way': x = word[:-2] y = x[::-1] z = y.index('a') a = y[:z] d = a[::-1] b = y[z+1:] rr = b[::-1] k = d+rr return k
372f84a17af618f4ae1778e031134bee09e2f8b3
2082033549/FCXPYN
/homework4/xiaoli_1.py
882
3.890625
4
# 2 定义一个函数,判断一个输入的日期,是当年的第几周,周几? 将程序改写一下,能针对我们学校的校历时间进行计算(校历第1周,2月17-2月23;校历第27周,8月17-8月23;); # from datetime import datetime # import time # dt= datetime.date(2019, 5, 9) # 用指定日期时间创建datetime # a=dt.isocalender() # print(a) # import datetime # a=datetime.date(2017, 12, 31).isocalendar() # print(a) import datetime def riqi(year,month,date): print(year,month,date,year,datetime.date(year,month,date).isocalendar()[1],datetime.date(year,month,date).isocalendar()[2]) def xiaoli(year,month,date): print(year,month,date,datetime.date(year,month,date).isocalendar()[1]-7,datetime.date(year,month,date).isocalendar()[2]) a=int(input("年份:")) b=int(input("月份:")) c=int(input("日期:")) riqi(a,b,c) xiaoli(a,b,c)
367978048089e595c36faa9cdd793a0a0f79fdba
Afsarsoft/python
/06_03_tuple.py
1,033
3.875
4
# pyright: strict from typing import List, Tuple # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # You can have tuples inside list to not be changed coordinates: List[Tuple[int, int]] = [(4, 5), (6, 7), (80, 34)] print(coordinates) print(coordinates[1]) for item in coordinates: print(item) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Tuples are comparable, comprasion is from left to right #from typing import Tuple tuple_01: Tuple[int, ...] = (0, 1, 2) tuple_02: Tuple[int, ...] = (5, 1, 2) print(tuple_01 < tuple_02) tuple_03: Tuple[int, ...] = (0, 1, 20000) tuple_04: Tuple[int, ...] = (0, 3, 4) print(tuple_03 < tuple_04) tuple_05: Tuple[str, ...] = ('Jones', 'Sally') tuple_06: Tuple[str, ...] = ('Jones', 'Sam') print(tuple_05 < tuple_06) tuple_07: Tuple[str, ...] = ('Jones', 'Sally') tuple_08: Tuple[str, ...] = ('Adams', 'Sam') print(tuple_07 < tuple_08) # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
f46df9325e6e2165adf3a10cfa6b73901c2442dc
skulshreshtha/Data-Structures-and-Algorithms
/Algorithms/symmetric_tree_BT.py
613
3.796875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def _isMirror(self, t1: TreeNode, t2: TreeNode) -> bool: if(t1 is None and t2 is None): return True if(t1 is None or t2 is None): return False return (t1.val == t2.val and self._isMirror(t1.left,t2.right) and self._isMirror(t1.right,t2.left)) def isSymmetric(self, root: TreeNode) -> bool: return self._isMirror(root,root)
c360132df92aaecad287cf1757b006dd8a7e65d4
JitinKansal/My-DS-code
/linkedlist_implementation.py
2,613
4.3125
4
# To create the new node. class Node: def __init__(self, data=None): self.data = data self.next = None # To perform the operation on the linked list. class Linkedlist: def _init__(self): self.head = None # A function to print the linked list. def printlist(self): print("THE LINKED LIST IS :") printl = self.head while printl is not None: print(printl.data) printl = printl.next # A function to add a node at the beginning of the linked list. def addbeg(self, newdata): NewNode = Node(newdata) NewNode.next = self.head self.head = NewNode print(newdata,"is added at beginning") # A function to add a node at the end/last of the linked list. def addlast(self, newdata): NewNode = Node(newdata) if self.head is None: self.head = NewNode print(newdata, "is added at end") return temp = self.head while temp.next: temp = temp.next temp.next = NewNode print(newdata, "is added at end") # A function to add a node in between of the linked list. def mid(self, a, newdata): temp = self.head for i in range(1, a): if temp.next is None: print(a,"node is absent so the newdata can not be added") return temp = temp.next NewNode = Node(newdata) NewNode.next = temp.next temp.next = NewNode print(newdata, "is added at the",a,"position") # A function to delete/remove a node from the linked list. def remove(self, key): temp = self.head if temp is not None: if temp.data == key: self.head = temp.next temp = None print(key, "is deleted from the linked list") return while temp is not None: if temp.data == key: break prev = temp temp = temp.next if temp == None: print(key, "is not present in the linked list. so, it can not be deleted") return prev.next = temp.next temp = None print(key, "is deleted from the linked list") l = Linkedlist() l.head = Node("1") l1 = Node("2") l2 = Node("3") l.head.next = l1 l1.next = l2 l.addbeg("0") l.addlast("5") l.mid(4, "4") l.mid(8, "6") l.addlast("6") l.printlist() l.remove("6") l.remove("7") l.printlist()
ec0a1ca0957abd633447f9a167f0e9b103ef122e
zhangyebai/LeetCode
/Python/palindrome_number.py
1,408
4
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ @Author 张夜白 At LeetCode Title: Palindrome Number Determine whether an integer is a palindrome. Do this without extra space.(Note this, no extra space) Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? There is a more generic way of solving this problem. Subscribe to see which companies asked this question """ class Solution(object): def isPalindrome(self, x: int)->bool: """ :type x: int :rtype: bool """ self.__init__() if x < 0: return False elif x == 0: return True base = 1 while x // base >= 10: base *= 10 while x != 0 and base != 0: if x // base != x % 10: return False # 每次loop将num去头去 x = (x % base) // 10 # 每次loop将base地板除100,因为num每次去掉头尾是2位 base //= 10 ** 2 return True if __name__ == '__main__': c = 1214151531 print(Solution().isPalindrome(1214151531))
2f071d61549ca8f7dde19610cba6f2c873325a78
pradeepreddybodha/MyPythonCodes
/LinearSearch.py
464
3.515625
4
from random import * def linear_search(nums): for j in li: globals()['pos'] += 1 if j == nums: return True break nums = int(input("Enter the number to search in the list: ")) li = [29, 53, 94, 54, 48, 52, 88, 58, 7] pos = 0 for i in range(1, 10): k = randint(1, 100) li.append(k) if linear_search(nums): print("Number found at position", pos) else: print("Number not found")
ebd25b693eb1501cb54f0a2fe3418e97b52a37ff
SimonFans/LeetCode
/String/L65_Valid Number.py
2,181
3.984375
4
Validate if a given string can be interpreted as a decimal number. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true " -90e3 " => true " 1e" => false "e3" => false " 6e-1" => true " 99e2.5 " => false "53.5e93" => true " --6 " => false "-+3" => false "95a54e53" => false Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: Numbers 0-9 Exponent - "e" Positive/negative sign - "+"/"-" Decimal point - "." Of course, the context of these characters also matters in the input. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. class Solution: def isNumber(self, s): """ :type s: str :rtype: bool """ s = s.strip() length = len(s) index = 0 # Deal with symbol if index < length and (s[index] == '+' or s[index] == '-'): index += 1 is_normal = False is_exp = True # Deal with digits in the front while index < length and s[index].isdigit(): is_normal = True index += 1 # Deal with dot and digits behind it if index < length and s[index] == '.': index += 1 while index < length and s[index].isdigit(): is_normal = True index += 1 # Deal with 'e' and number behind it if is_normal and index < length and (s[index] == 'e' or s[index] == 'E'): index += 1 is_exp = False if index < length and (s[index] == '+' or s[index] == '-'): index += 1 while index < length and s[index].isdigit(): index += 1 is_exp = True # Return true only deal with all the characters and the part in front of and behind 'e' are all ok return is_normal and is_exp and index == length
7d09070dc69b850da6a4a6512cd2fd3df057b776
Srinivas-Rao-au27/Accomplish_classes-
/coding-challenges/week12/day04/week12-day04-cc.py
3,821
4.09375
4
""" Q-1 ) Kth Largest Element in an Array https://leetcode.com/problems/kth-largest-element-in-an-array/ (5 marks) (Medium) Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 """ class Solution: def findKthLargest(self, nums, k): if not nums or not k or k < 0: return None minheap = [] for num in nums: if len(minheap) < k: heapq.heappush(minheap, num) else: if num > minheap[0]: heapq.heappop(minheap) heapq.heappush(minheap, num) return minheap[0] """ Q-2 )Kth Largest Element in a Stream (5 marks) https://leetcode.com/problems/kth-largest-element-in-a-stream/ (Easy) Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class: ● KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. ● int add(int val) Returns the element representing the kth largest element in the stream. Example 1: Input ["KthLargest", "add", "add", "add", "add", "add"] [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] Output [null, 4, 5, 5, 8, 8] Explanation KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); kthLargest.add(3); // return 4 kthLargest.add(5); // return 5 kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8 """ class KthLargest: def __init__(self, k, nums): self.heap = [] self.k = k for i in nums: if len(self.heap) < k: heapq.heappush(self.heap,i) else: if i > self.heap[0]: heapq.heappushpop(self.heap,i) def add(self, val): if len(self.heap) < self.k: heapq.heappush(self.heap,val) else: if val > self.heap[0]: heapq.heappushpop(self.heap,val) return self.heap[0] """ Q-3 )Minimum Cost of ropes (5 marks) https://practice.geeksforgeeks.org/problems/minimum-cost-of-ropes-1587115620/ 1 (Easy) There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost. Example 1: Input: n = 4 arr[] = {4, 3, 2, 6} Output: 29 Explanation: For example if we are given 4 ropes of lengths 4, 3, 2 and 6. We can connect the ropes in following ways. 1) First connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6 and 5. 2) Now connect ropes of lengths 4 and 5. Now we have two ropes of lengths 6 and 9. 3) Finally connect the two ropes and all ropes have connected. Total cost for connecting all ropes is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes. Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three strings of 3, 2 and 10), then connect 10 and 3 (we get two strings of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38. """ import heapq def minCost(arr, n): heapq.heapify(arr) res = 0 while(len(arr) > 1): first = heapq.heappop(arr) second = heapq.heappop(arr) res += first + second heapq.heappush(arr, first + second) return res if __name__ == '__main__': lengths = [ 4, 3, 2, 6 ] size = len(lengths) print("Total cost for connecting ropes is " + str(minCost(lengths, size)))
2ba01b9d6e7912ff67601acb1f17c86fbbcd0c9c
spak9/WICRPI
/CH4/sp.py
1,351
3.75
4
# From Reis's Writing Compilers 2nd Edition # Grammer: # S -> AC # A -> ab # C -> cC # C -> d import sys tokenindex = -1 token = '' def main(): try: parser() except RuntimeError as emsg: print(emsg) def advance(): global tokenindex, token tokenindex += 1 # increment index # check if we're at the end of string or given no input string if (len(sys.argv) < 2 or tokenindex >= len(sys.argv[1])): token = ''; # the end else: token = sys.argv[1][tokenindex] # advance to next token (character) def consume(expected): if (expected == token): advance() else: raise RuntimeError(f'Expecting: {expected}') def parser(): # prime token with first token advance() S() # check if we've finished input string, that is # S() will eventually chain all calls to end, therefore # if we end up with another token after S(), input doesn't # end with 'd' if token != '': print('Garbage following <S>-string') def S(): A() C() def A(): consume('a') consume('b') def C(): if (token == 'c'): advance() C() # if we reach 'd' token, then we've come to the end of the grammar and input string elif token == 'd': advance() else: raise RuntimeError('Expecting c or d') main()
53a1384c779d76a1c39ef8ccccf59a07db7243a1
hilings/leetcode
/python/070.py
494
3.640625
4
# 070 # Climbing Stairs # 2015-12-23 ##################################################### class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 0: return 0 last2, last1 = 1, 1 for i in range(2, n+1): last2, last1 = last1, last1+last2 return last1 ##################################################### sol = Solution() n = 4 z = sol.climbStairs(n) print(z)
ae65996d6e1a8bdff4b39fd35ac44ad98289ab12
techgymjp/techgym_python_en
/Ef3z.py
1,419
3.890625
4
import random hands = ['rock', 'scissors', 'paper'] results = {'win': 'win', 'lose': 'lose', 'draw': 'draw try again'} def start_message(): print('Start \'rock-paper-scissors\'') def is_hand(number): if number >= 0 and number <= 2: return True else: return False def get_player(): print('Input your hand') input_message = '' index = 0 for hand in hands: input_message += str(index) + ':' + hand if index < 2: input_message += ', ' index += 1 return int(input(input_message)) def get_computer(): return random.randint(0, 2) def get_hand_name(hand_number): return hands[hand_number] def view_hand(your_hand, computer_hand): print('My hand is ' + get_hand_name(your_hand)) print('Rival\'s hand is ' + get_hand_name(computer_hand)) def get_result(hand_diff): if hand_diff == 0: return 'draw' elif hand_diff == -1 or hand_diff == 2: return 'win' else: return 'lose' def view_result(result): print(results[result]) def play(): your_hand = get_player() while not is_hand(your_hand): your_hand = get_player() computer_hand = get_computer() hand_diff = your_hand - computer_hand view_hand(your_hand, computer_hand) result = get_result(hand_diff) view_result(result) if result == 'draw': play() start_message() play()
3a52c48f7761bcb9833b1c90c7f7fd3fa0659226
sky-tanaka/GitVsc
/if_sample3-6.py
299
4
4
#キーボードから数値を入力 a=int(input("a=")) if a==1: #aが1だった場合の処理 print("aは1です!") elif a==2: #aが2だった場合の処理 print("aは2です!") else: #aが1でも2でもなかった場合の処理 print("aは1,2以外の数")