blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
ec7ac4602b1185182120e7f2c667c50ac72555b0
Tharani-Ganapathy/PycharmPython
/leet_code_practice/assign_cookies.py
1,091
3.71875
4
# Assume you are an awesome parent and want to give your children some cookies. # But, you should give each child at most one cookie. # Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; # and each cookie j has a size sj. # If sj >= gi, we can assign the cooki...
0769157c87bdb7be2bf32d47cd2572856d22c32a
ChrisWise07/Python_Caesar_Cipher
/geektechstuff_brute_caesar_v2
1,969
3.96875
4
#!/usr/bin/python3 # geektechstuff # brute force Caesar # encrypted string to brute force enc_string = 'qgmj skkayfewfl, addmkljagmk ugvw tjwscwj, ak lg jwkwsjuz s uahzwj lzsl zskh32!n3adu73y2xlk2k37i3-k839xxe4052p56jko5\zaep525mmg4a50s$3qj4m-065?r5h/o5cz.?u' def alphabet(): # letters of alphabet (English) le...
d20f324fa7c47c376171aba8481e0960ec3b5c67
dzj212/ehealth
/tools/correlation.py
2,391
3.609375
4
## correlation.py # # Process and graph two signals and calculate the correlation factor between them # # # Usage: python correlation.py [input_file_1] [input_file_2] # # @param input_file_1 The file with low sample frequency # @param input_file_2 The file with high sample frequency # import sys import csv imp...
d9d43b943dd3dd38d8c0584f1fac139ad181b38c
aJns/cao19
/E4/ex04_01.py
1,970
4.21875
4
""" This coding exercise involves checking the convexity of a piecewise linear function. You task is to fill in the function "convex_check". In the end, when the file is run with "python3 ex04_01.py" command, it should display the total number of convex functions. """ # basic numpy import import num...
a962c85fd9b98874f4d9a974af4122600cc1e901
nucle0tides/Code-Camp
/Objects/objects.py
697
4.03125
4
""" Objects """ class Vehicle(object): num_wheels = None def __init__(self, name, vehicle_type): self.name = name self.vehicle_type = vehicle_type def __str__(self): return "I am {} the {}!".format(self.name, self.vehicle_type) def vroom(self): raise NotImplementedError("A generic car doesn't make a...
ed58c820e98fbd847a176a0d6500f8a72dbca205
AnilMeena1512/Algorithms
/Binary_search.py
424
3.984375
4
def binarysearch(arr,x,low,high): while low<=high: mid=low+(high-low)//2 if arr[mid]==x: return mid elif arr[mid]<x: low=mid+1 else: high=mid-1 return -1 arr= [3, 4, 5, 6, 7, 8, 9] x = 4 result = binarysearch(arr,x,0,len(arr)-1)...
86fcfcfdac8cae6aec1188981d1cc36e95343b68
hdd2k/adventOfCode
/2020/day2/day2.py
1,767
3.609375
4
# Day 2, 2020 def solve(input_lines): print(f"######### Day 2") from collections import namedtuple, Counter Range = namedtuple('range', ['start', 'end']) LineInfo = namedtuple('lineInfo', ['range', 'letter', 'pw']) # read / parse input def parseRange(rangeStr): startNum, endNum =...
61dfe2ff9e9079dcd99cc21955a84a9c3a47c6da
hdd2k/adventOfCode
/2018/09/9.py
1,465
3.59375
4
########################## # Imports ########################## import fileinput import re from itertools import cycle from collections import deque ########################## # Read input - 10 players; last marble is worth 1618 points: high score is 8317 ########################## gameInfo = [] for line in fileinput....
66c9bf90096a510a80271198fa41def37694cd09
hdd2k/adventOfCode
/2020/day3/day3.py
1,718
3.640625
4
# Day 2, 2020 def solve(input_lines): print(f"######### Day 3") # 1 down, 3 right colCount, rowCount = len(input_lines[0]), len(input_lines) # get input + parse into 2D matrix -> don't need to do since string can be indexed just the same way # util function for wrap around indexing ...
6965a3ca8629883cab1eb43cc95582a12b1af544
inwenis/diseaseDiagnoser
/program.py
301
3.640625
4
import time symptoms = input("Enter your symptoms and press [enter]") if symptoms: print("processing...") print("accessing wikipedia...") print("accessing google...") time.sleep(2) # pretend you're actually doing something print("You have cancer"); input("Press [enter] to exit")
b17367e840f6347b4a09c25f2b2a9b4b87df6096
vishalbelsare/discovery-of-physics-from-data
/code/helpers/differentiation.py
6,663
4
4
""" Functions for performing numerical differentiation. """ import numpy as np from scipy import signal def differentiate( X, t, diff_method="forward difference", smoother=None, window_length=35 ): """ Approximate the derivative of set of 1D data points using finite difference methods Parameters...
90671de897edbbddb2f548f6116d6bb122b40449
depromeet/algorithm-meet
/028_POSTFIX_EXPRESSION/jeemyeong-0918.py
1,260
3.578125
4
class StackClass: def __init__(self, itemlist=[]): self.items = itemlist def isEmpty(self): if self.items == []: return True else: return False def peek(self): return self.items[-1:][0] def pop(self): return self.items.pop() def pu...
1d2f00653e56044d97a1cee136471d5efa10bedb
depromeet/algorithm-meet
/041_COMMAND_PROMPT/gyu_1032.py
442
3.515625
4
def find_pattern(given): total = len(given) pattern = given[0] to_compare = len(pattern) for i in range(1, total): for j in range(to_compare): if given[i][j] != pattern[j]: pattern = pattern[:j] + '?' + pattern[j + 1:] return pattern if __name__ == '__main__': ...
ae312fa254dcd98fc0d4aef514dce2a3605dc46d
depromeet/algorithm-meet
/029_IRON_STICK/jeemyeong-10799.py
897
3.609375
4
class StackClass: def __init__(self, itemlist=[]): self.items = itemlist def isEmpty(self): if self.items == []: return True else: return False def peek(self): return self.items[-1:][0] def pop(self): return self.items.pop() def pu...
93344bf6433bbbbecf99e28b3064d045acc6f7a5
FreemanWillaim/ProjectLogAnalysis
/vagrant/News/news.py
4,536
3.515625
4
#!/usr/bin/env python3 import psycopg2 # Imports the psycopg2 library. # A method to connect to the news database. def connect(): try: conn = psycopg2.connect("dbname=news") return conn except Exception as err: print(err) # A method that accepts the result of an sql query, # and two headers. ...
1b9f0b4ecb4f3d99531d5bb236dd4313967c2efa
teopalmer/computer-graphics
/lab1/main.py
3,151
3.78125
4
# Тема: Множества точек # # Программа находит и изображает нек. кол-во окружностей # # ========================================================================== # # Входные данные: Результат: # # Дв...
c6752bd1584f1b9e37e6c1bb9d9f97ca9a6fadcb
haydenbanting/EA-NQueens
/population/phenotype.py
1,186
3.546875
4
import numpy as np ''' Basic solution object to the 8-Queens problem. Each Phenotype has an associated genotype which representes the solution as a vector, and an associated fitness. ''' class Phenotype: def __init__(self, genotype): self.age = 0 self.genotype = genotype self.fitness, se...
b1aa1aaea35202adc4745a95ce79efdf6656a0c3
mebaca/Homework_12
/steps_counter.py
266
3.703125
4
d = float(input("Bitte geben Sie die zurückgelegte Strecke in Metern ein: ")) sl = float(input("Bitte geben Sie ihre Schrittlänge in Metern ein: ")) def steps(d,sl): x = float(d / sl) return x print("Sie haben " + str(steps(d,sl)) + " Schritte gemacht!")
d6092d20ceaa0ae7a41b1e51041dc3df67efcb06
leorolland/Allocateur-ProcRess-Graph
/test.py
727
3.5
4
import networkx as nx import matplotlib.pyplot as plt import time if __name__ == "__main__": G = nx.Graph() tableNoeuds = [] ind = 0 """ while (True): nom = input("Ajouter un noeud (entrez un nombre): ") # Ajout du noeud G.add_node(nom) tableNoeuds.insert(ind,nom) ind = ind + 1 if len(G.nodes) > 1...
a180fee18367bb9d46221848cc5fb7021721ed46
azimbaldiwala/BinarySearchVisualization
/main.py
4,977
4.1875
4
from colorama import Fore # Returns 1 if element found, -1 if not found! def binarySearch(numbers: list, low, high, element: int): # Check if high is greater than low (0 in most of the cases!) if high >= low: mid = low + (high - low) // 2 # If element found at mid! if int(numbers[mid]...
db8ff6044de38cc3251573022cabcc60c7427d36
herzenuni/sem3-assignment2-1-11217-lloudb
/example_sort.py
1,446
3.96875
4
def gen_random_lst(length, min_val=1, max_val=10000): """ Возвращает список случайных чисел. Возвращает список случайных чисел от 1 до 10000, но позволяет пользователю определять свой диапазон """ import random rand_lst = [random.randint(min_val, max_val) for i in range(length...
abc38e143229409c14d24e9054228eec6e33387d
hjjiang/Vending-Machine
/Money.py
1,488
3.640625
4
class Money(object): def __init__(self, value, amount): self.value = value self.amount = amount self.TotalAmount = value * amount def getTotalAmount(self): return self.TotalAmount def getAmount(self): return self.amount def addAmount(self, amoun...
32d60e578d02d8ca4143f7d291e21716c8f2df13
Jormungendr/LintCode
/1.py
1,557
3.5
4
# TODO Rewrite it to C++ import math class Solution: """ @param: : an int @param: : an int @return: if N can be expressed in the form of sum of K primes, return true; otherwise, return false. """ def isSumOfKPrimes(n, k): def findSu(num): array = set() for n in ra...
e499ff30852124b2107ca50e094d80f1db6c5608
CodeGirl33/Python
/ODIGame.py
1,236
3.703125
4
from os import sys from sys import exit from random import choice import time #options_england = ['lbw', 'boundaries', 'SIX!', 'OUT!'] #options_india = ['dropped', 'caught', 'yorker', 'maiden'] # print("India lost the toss, and has been put into batting / fielding") # print("""England have won the toss, you are the ...
240eb05cb07e5f3e952a4ae97fc6c3a7854acc45
krithikV/vaccineregistration
/mae.py
542
3.625
4
from sys import stdout def get_part_of_day(hour): global time if 5 <= hour <= 11: time = "Morning" elif 12 <= hour <= 17: time = "Afternoon" elif 18 <= hour <= 22: time = "Evening" else: time = "error" return time # If you want to use current hour:...
31354ef2d29a65998ffd2e64810145dec1a4d9ff
oscar-wildin-out/yahtzee
/New_Roll.py
1,477
3.9375
4
import random class Die(object): def roll(self): return random.randint(1, 6) d = Die() def keeper(): keeper = raw_input("Which dice (numbered 1-5) would you like to keep? ") if len(keeper) == 0: result = 0 else: keeper_list = keeper.split(',') keeper_array = map(int,ke...
c2e9dfccb81cc8b86e5c9e72c6376e2b2c5f034c
Sugandha9140/Prison-Break
/version17.pyde
43,087
3.515625
4
#We have to create maze because DON FUCKING DIDNT DO IT (use maze6) import random import os import time add_library('sound') path = os.getcwd() #game.complete is used to check the last game.state, and you can enter the next door when if game.state == "prison" and game.complete = "last game's game.state" #you can...
e6423fd4ee40e7aa90b661f3720a2b4cb8321234
mikeykh/prg105
/10.2/question.py
1,309
3.765625
4
class Question: def __init__(self, question="", a="", b="", c="", d="", correct_ans="", user_ans=""): self.__question = question self.__a = a self.__b = b self.__c = c self.__d = d self.__correct_ans = correct_ans self.__user_ans = user_ans def set_questi...
a8f4111a73420359faa0c067e4c82f6533860e4a
mikeykh/prg105
/11.1/office_furniture.py
1,744
3.796875
4
# the OfficeFurniture class holds general information # about office furniture for sale # it will be the parent class for desks, chairs, ect. class OfficeFurniture(object): """ accepts material, length, width, height, and price """ def __init__(self, category, material, length, width, height, pric...
ca00bc72743cb5168f449a4e7032d3cfdcb884c4
mikeykh/prg105
/13.1 Name and Address.py
2,405
4.25
4
# Write a GUI program that displays your name and address when a button is clicked (you can use the address of the school). The program’s window should appear as a sketch on the far left side of figure 13-26 when it runs. When the user clicks the Show Info button, the program should display your name and address as sho...
a2f82639d7a3d84317e5d0c3bfe6e5d8b9ea91dc
mikeykh/prg105
/Automobile Costs.py
2,135
4.59375
5
# Write a program that asks the user to enter the # monthly costs for the following expenses incurred from operating # his or her automobile: loan payment, insurance, gas, oil, tires and maintenance. # The program should then display the total monthly cost of these expenses, # and the total annual cost of these expense...
6fb090b1ed6b0893e5ac72746255261aa820eaee
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex054.py
235
4
4
total = 0 for c in range(1, 8): idade = int(input('Digite sua idade: ')) if idade >= 18: total += 1 if total == 0: print('Ningúem é maior de idade') print('{} pessoas são maiores de idade'.format(total))
082a4740d7b5ec1662a784db0cc9604bc0aeef67
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex038.py
372
4.03125
4
n1 = int(input('Digite o primeiro número: ')) n2 = int(input('Digite o segundo número: ')) n3 = int(input('Digite o terceiro número: ')) if n1 > n2 and n1 > n3: print('O primeiro número é maior') elif n2 > n1 and n2 > n3: print('O segundo número é maior') elif n1 == n2 == n3: print('Todos são iguais') else...
d47872433fa91d598a9ddda2a66c61e20d7427ed
pemedeiros/python-CeV
/pacote-download/CursoemVideo/Aulas/aula09.py
500
4.0625
4
frase = 'Curso em video python' print(frase[3]) print(frase[4:13]) print(frase[:15]) print(frase[5:]) print(frase[4:21:2]) print(frase.count('o')) print(len(frase)) print(frase.replace('python', 'arroz')) print('Curso' in frase) print(frase.find('Curso')) print(frase.split()) dividido = frase.split() print(dividido[2])...
c549b371e1c1a36905f24bd9e3344ff9ff64ab4a
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex088.py
461
3.515625
4
from random import randint from time import sleep jogo = [] lista = [] tot = 1 qtd = int(input('Quantos jogos você quer fazer? ')) while tot <= qtd: cont = 0 while True: n = randint(1, 60) if n not in jogo: jogo.append(n) cont += 1 if cont >= 6: break...
fd9f73884a3c52c8951b5f974ceb44a21f27021e
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex079.py
395
4.09375
4
lista = [] while True: val = int(input('Digite o valor: ')) if val not in lista: lista.append(val) print('Valor adicionado') else: print('Valor não adicionado') opcao = input('Deseja continuar?[S/N]').upper() if opcao == 'S': print('Continuando...') if opcao == 'N...
c33533fd6b15d5d6a75cc3fe5c7382ff304e2ba3
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex084.py
880
3.671875
4
dado = [] pessoas = [] maior = c = menor = 0 while True: dado.append(str(input('Nome: '))) dado.append(float(input('Peso: '))) c += 1 if c == 1: maior = menor = dado[1] else: if dado[1] >= maior: maior = dado[1] if dado[1] <= menor: menor = dado[1] ...
6faac8d564be087f55749b66f010dae75928169f
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex092.py
762
3.71875
4
from datetime import date data_atual = date.today() ano_atual = '{}'.format(data_atual.year) ano_int = int(ano_atual) trabalhador = {} trabalhador['nome'] = input('Nome: ') trabalhador['idade'] = ano_int - int(input('Ano de nascimento: ')) trabalhador['ctps'] = int(input('Carteira de Trabalho: (0 não tem)')) if trabalh...
034a9c71587828d1403dc8fc2db4faac9e73dae0
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex075.py
601
3.828125
4
'''for c in range(0,4): n = int(input('Digite um valor:')) c += 1 nmrs = (n) print(nmrs)''' n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) n3 = int(input('Digite o terceiro número: ')) n4 = int(input('Digite o último número: ')) numeros = (n1,n2, n3, n4) print(numeros) vzs = nume...
615591c4b0b32f1451e0a02523c6b097fd6e463c
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex049.py
237
3.953125
4
from time import sleep for c in range(0, 2): num1 = int(input('Digite o primeiro valor: ')) num2 = int(input('Digite o segundo valor: ')) s = num1 * num2 print('A entre {} e {} é: {}'.format(num1, num2, s)) sleep(2)
4d1eb496a57b3ebcaa7508253d52dd6cec0017ee
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex050.py
404
3.734375
4
t = 0 np = 0 for c in range(0, 6): n1 = int(input('Digite um numero: ')) if n1 % 2 == 0: t += n1 np += 1 if np == 0: print('Você não digitou nenhum número par, portanto, o seu total é 0.') elif np == 1: print('Você digitou {} número par. O seu total é {}.'.format(np, t)) else: print...
ff1eff12f0ed5253562d5f0715cdbb4ee159c3cb
pemedeiros/python-CeV
/pacote-download/CursoemVideo/ex101.py
386
3.96875
4
def voto(idade): from datetime import date ano_int = date.today().year anos = ano_int - idade if anos < 16: return f'Com {anos}: O VOTO É NEGADO' elif 16 <= anos < 18 or anos > 65: return f'Com {anos}: O VOTO É OPCIONAL ' else: return f'Com {anos}: O VOTO É OBRIGATÓRIO' ...
7800e3ebc0895925b9a370fe0563a4942395f033
huangyuzhen/let
/13/13.py
576
3.5625
4
class Solution: def romanToInt(self, s: str) -> int: nDict = { "I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000, "IV":4, "IX":9, "XL":40, "XC":90, "CD":400, "CM":900 } i = 0 length = len(s) number = 0 while i < length: ns =...
cea5b123dcbc64d3dfb9dfa3095664e270de18a5
huangyuzhen/let
/47/47.py
822
3.5625
4
class Solution(object): def backtrack(self, nums, t = 0, one = [], visited = []): if t == self.maxN: self.result.append(tuple(one)) return uniq = set() for i in range(self.maxN): if i in visited or nums[i] in uniq: continue uni...
68e93ab02131053cc3ac5f92bb765d647a84b8df
huangyuzhen/let
/94/95.py
2,244
3.84375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def insertBST(self, root, n): if not root: return TreeNode(n) if root.val == n: return Fal...
63d3aea61a29d1779a8b8efa8b2805987e4d8765
huangyuzhen/let
/100/111.py
1,050
3.921875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 ...
5f319f9dc941b0d917cf65ea285e099d86fadadb
huangyuzhen/let
/15/15.py
799
3.9375
4
from typing import List class Solution: def sumBackTrack(self, t = 0, count = 0, currentSum = 0, xList = []): if count == 3 and currentSum == 0: xList.sort() self.result.add(tuple(xList)) return if count > 3 or t == self.length: return # 选择此元素...
b5be7124d0c5d50b9390310db03b64967a3756e1
huangyuzhen/let
/92/92b.py
1,101
3.8125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseNt(self, head, n): tail = head.next head.next = None if not tail or n == 1: self.suffix = tail ret...
7311ef2862e5c82c64ff6667f458cd006420c870
huangyuzhen/let
/100/109.py
1,305
3.8125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): ...
8d2daaade99232f664c3a332f991bef1983921bc
huangyuzhen/let
/180/189b.py
774
3.5625
4
class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. """ length = len(nums) k = k % length if k == 0: return count = 0 start = 0 ...
3131a6abd4b600e018bcaf1fea4b7423e368db10
hashahid/Scripting-Language-Compiler
/nodes.py
16,062
3.78125
4
from globals import global_scope, function_name_to_body class SemanticError(Exception): """ This is the class of the exception that is raised when a semantic error occurs. """ # These are the nodes of the abstract syntax tree. class Node(object): """ A base class for nodes. All other classes her...
a024445ad40df6cda322c6bb7aa1b2efafbd9cd3
AngelValAngelov/Python-Advanced-Exercises
/Lists as Stacks and Queues - Lab/01. Reverse Strings.py
247
4.34375
4
def reversed_string(text): s = list() for letter in text: s.append(letter) new_s = list() while s: char = s.pop() new_s.append(char) return "".join(new_s) print(reversed_string(input()))
58248cc36adb0fc8e4b413c864d9a4cdc09812df
AngelValAngelov/Python-Advanced-Exercises
/Functions Advanced - Lab/07. Chairs.py
721
3.734375
4
def chair_combinations(names, size): def chair_combinations_internal(names, size, combination, all_combinations): if len(combination) == size: all_combinations.append(combination[::]) return for i in range(len(names)): name = names[i] combinatio...
6af09fc6da119e6525d6135d21fb4244b754a7cf
AngelValAngelov/Python-Advanced-Exercises
/Tuples and Sets - Exercise/04. Count Symbols.py
214
3.671875
4
text = input() signs = {} for sign in text: if sign not in signs: signs[sign] = 0 signs[sign] += 1 for sign, quantity in sorted(signs.items()): print(f"{sign}: {quantity} time/s")
0b0910a88190a7b8a8fd0d093f66192dbcd0d1e6
AngelValAngelov/Python-Advanced-Exercises
/Comprehensions - Lab/05. Filter Numbers.py
223
3.546875
4
num_start = int(input()) num_end = int(input()) divisors = [x for x in range(2, 10)] result = [x for x in range(num_start, num_end + 1) if len([True for z in range(2, 11) if x % z == 0]) > 0] print(result)
60cfc23f4dc793c9d5fb3e93bbe8dff6a720b6d7
AngelValAngelov/Python-Advanced-Exercises
/Comprehensions - Exercise/05. Diagonals.py
355
3.75
4
rows = int(input()) matrix = [[int(x) for x in input().split(", ")] for x in range(rows)] first = [matrix[x][x] for x in range(rows)] second = [matrix[x][-x - 1] for x in range(rows)] print(f"First diagonal: {', '.join(str(x) for x in first)}. Sum: {sum(first)}") print(f"Second diagonal: {', '.join(str(x) for ...
313888c9034c1cc85d8821e6745684aec92a01ef
MikkoHolfeld88/beginning_python
/basic/map_lambda.py
703
3.6875
4
from math import sin, cos, tan def quadrat(a): return a*a numbers = (1,2,3,4,5,6,7,8,9,10) map_a = map(quadrat,numbers) # map(funktion,sequenz bzw. daten) liste_map_a = list(map_a) print(liste_map_a) # using lambda result = list(map(lambda a : a*a ,numbers)) print(result) # multiple lists for map num1 = [...
0351e2aceff0995cee742e95c1503f69c6322bdc
MikkoHolfeld88/beginning_python
/tkinter/button_counter.py
480
3.640625
4
import tkinter as tk counter = 0 def counterLabel(label): counter = 0 def count(): global counter counter += 1 label.config(text=str(counter)) label.after(1000,count) count() mainWindow = tk.Tk() mainWindow.title("Sekunden zählen") label = tk.Label(mainWindow, fg="dark gre...
bed530a0389019f8bfaceea7bc538bc55dd2d9eb
Calathea7/whiteboarding-practice
/reverse_llist.py
1,698
3.90625
4
# class Solution: # def reverseList(self, head: ListNode) -> ListNode: # current = head # prev_node = None # while current: # current.next = prev_node # prev_node = current # current = current.next # head = prev_node # return head # De...
96ed6feaf59796961f8f5228a5402dcc7c70698b
Asilva-01/PythonEstudos
/Aulas_Modulo_Magico_6_2.py
301
4.15625
4
def main(): numero_escolhido = 3 numero_magico = int(input("Valor escolhido pelo magico: ")) if numero_magico > numero_escolhido: print("Diminua o chute") elif numero_magico < numero_escolhido: print("Aumente o chute") else: print("Você acertou") main()
8e0514735ebb6ae3bc841aaed70b19a64cd759e2
Asilva-01/PythonEstudos
/teste05112020_01.py
181
4.03125
4
num = int(input("digite o numero:" )) cont = 1 soma2 = 0 while cont <= num: soma1 = 1 / cont soma2 = soma2 + (soma1**2) cont = cont + 1 print("{:.6f}".format(soma2))
28ca81d214caf452645cca60b375190f6c2c999b
murilobdio/Atividade1-AED2
/scripts/funcoes_emparelhamento.py
842
3.671875
4
# ============================================================================= # Funções # ============================================================================= import os, sys sys.path.append(os.getcwd()) import numpy as np from decimal import * #Função de espalhamento por divisão def EspalhamentoPorDivisao(k...
4275450169850819490ce0f029f09a7ab7df0c13
njhanley/adventofcode
/2021/01/part2.py
478
3.5625
4
import re def read(filename): with open(filename) as file: return file.read() def match(string, pattern, function): return [function(*match.groups()) for match in re.finditer(pattern, string)] def parse(filename, pattern, function): return match(read(filename), pattern, function) data = pars...
03f7354c5cee150635b0976d4b6ccbb98b717d7c
njhanley/adventofcode
/2021/10/part1.py
676
3.671875
4
import re def read(filename): with open(filename) as file: return file.read() def match(string, pattern, function): return [function(*match.groups()) for match in re.finditer(pattern, string)] def parse(filename, pattern, function): return match(read(filename), pattern, function) left = "([{...
94b32a95cb692d0b58998c8ebb6980fb83b7d266
bea3853/python
/jogo.py
987
3.859375
4
import random chute = 0 chances = 7 tentativas = 1 jogador = '' numero_secreto = random.randint(1, 100) print('Você terá sete chances para adivinhar o número') jogador = input('Digite seu nome: ') print('Chute um número entre 1 e 100') while tentativas <= 7: chute = int(input('Digite o número: ')) if chute < ...
df13b4cb9ca5edf9da8bbe1d9edfadce2686e4e6
vladvasiliu/polyominoes
/polyominoes/generators.py
1,943
3.53125
4
from polyominoes.polyomino import first_polyomino, Polyomino from polyominoes.transformations import rotations, reflections, normalise from datetime import datetime def neighbours(x, y): yield x+1, y yield x-1, y yield x, y+1 yield x, y-1 def children(polyomino): """ The children of a polyomino...
0161da09fbf147c8799104d402179d228bc032a3
malhisaab13E13/SnakesNLadders
/main.py
3,818
4.28125
4
# Import randint module from random library to generate random numbers. from random import randint def get_players_list(): """Asks for Player names and Returns a Players list""" player_list = [input('Please enter name of player number 1: '), input('Please enter name of player number 2: ')] ...
88826e82ba9470b88b50ccf7cbfccaf2499fc53e
phamtm/project-euler
/prime.py
392
3.546875
4
import math # using the sieve of eratothenes def prime_table(limit): sievebound = math.floor((limit-1)/2) # last index of sieve crosslimit = int(math.floor(math.sqrt(limit)-1)/2) sieve = [True for i in range(0, sievebound)] for i in range(1, crosslimit): # i is not marked, hence prime if sieve[i]: for m in ...
f9a5745dda335ab340b9f451d01bf4ec84287276
shadiqurrahaman/python_DS
/leet-code/multyply_string.py
794
3.796875
4
def multiply(str1,str2): str_to_int = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} int_to_str = {0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9'} len_str1 = len(str1)-1 num1=0 for i in str1: num1+=str_to_int[i]*(10**len_str1) len_str1-=1 # print(num1)...
7e3530dbb4d7cf4e46c324c7113a5a29157d94c4
shadiqurrahaman/python_DS
/linklist/remove_nth_from_last.py
736
3.828125
4
class Node: def __init__(self,data): self.data = data self.next = None class linklist: def printList(self,head): while(head): print(head.data,end=' ') head = head.next print('') def removefromLast(self,n,head): headp = head headr = hea...
f2b94660239c6fa96843a0d999ffe0c40b13bfa4
shadiqurrahaman/python_DS
/tree/basic_tree.py
1,644
4.15625
4
from queue import Queue class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def __init__(self): self.root = None self.queue = Queue() def push_tree(self,data): new_node = Node(data) if self.root ...
3a30e84be7d56e058c210c0e8ef579888693cc28
shadiqurrahaman/python_DS
/array/find_pivot_element.py
431
3.96875
4
def find_pivot(arr,low,high): if high<low: return -1 if high==low: return low mid = int((low+high)/2) print(mid) if mid<high and arr[mid]>arr[mid+1]: return mid if mid>low and arr[mid]<arr[mid-1]: return (mid-1) if arr[low]>arr[mid]: return find_pivot(...
47097ecd1a8fd257d2da1bfcb0911ef97a3ed465
shadiqurrahaman/python_DS
/backtracking/unique_permue.py
693
3.53125
4
def permuteUnique(nums): res = [] nums.sort() dfs(nums, [], res) return res def dfs(nums, path, res): if not nums: res.append(path) for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: continue dfs(nums[:i]+nums[i+1:], path+[nums[i]], res) print...
d70ec27c75aece2fb8f793be1b7b77a4a1c236ce
shadiqurrahaman/python_DS
/test/remove_duplicate2.py
732
3.671875
4
# def remove(arr): # start = 1 # counter = 1 # check = arr[0] # result = 1 # while(start<len(arr)): # if check ==arr[start] and counter<2: # result+=1 # start+=1 # counter+=1 # elif check!=arr[start]: # check = arr[start] # start+=1 # result+=1 # counter=1 # ...
6f37edc9c2a2a326b53118f47afce49498c88c66
shadiqurrahaman/python_DS
/heap/if_tree_is_heap.py
592
3.9375
4
class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def check(self,root): queue = [] queue.append(root) while(queue): temp = queue.pop(0) if temp.left is None or temp.right is None: return "not a heap" elif (temp.lef...
2ee0efd646f0690b332cad085b33c4bc49c41db7
shadiqurrahaman/python_DS
/array/rotate_array.py
513
3.734375
4
class job: def rotate(self,list,d): temp = [] for i in range(0,d): temp.append(list[i]) counter = 0 for i in range(0,len(list)): if (i >= len(list)-d): list[i] = temp[counter] counter+=1 else: list[i] = list[i+d] # for i in range(d,0): # list[len(lis...
859fe59a076a52e20bcca3ffdcab13dd52a61a8a
shadiqurrahaman/python_DS
/backtracking/generate_parentheses.py
209
3.6875
4
def make(strp,n,open,close): if close==n: print(strp) return else: if open>close: make(strp+'}',n,open,close+1) if open<n: make(strp+'{',n,open+1,close) return make('',2,0,0)
102320308536f8e660ccbf62c3339f8d317085ad
shadiqurrahaman/python_DS
/Binary-tree/pree_order_postorder.py
1,484
3.734375
4
class Node: def __init__(self,val): self.val = val self.left = None self.right = None class Tree: def maketree(self,preorder,inorder): if not inorder: return temp = preorder.pop(0) if temp: root = Node(temp) for ind,val in enum...
42bdb9112e4da51886d739fc5736960a50719835
shadiqurrahaman/python_DS
/test/remove_dupliacte_list.py
680
4.0625
4
class Node: def __init__(self,data): self.data=data self.next = None def RemoveD(self,node): head1 = node head2 = node.next while(head2): if head1.data!=head2.data: head1.next = head2 head1 = head1.next head2 = head2.next else: head2 = head2.nex...
f04b6fb85b65bc04174c8b437ba7998e6972d386
shadiqurrahaman/python_DS
/leat-code/look_and_count.py
593
3.546875
4
def Look_and_count (nums): if nums==1: return '1' if nums==2: return '11' result = 11 index=1 while(index<nums-1): temp_result = str(result) re = '' counter = 1 for i in range(len(temp_result)-1): if temp_result[i]==temp_result[i+1]: ...
5072697a248dd3e56322550a2dd2a02d82abff3a
shadiqurrahaman/python_DS
/leet-code/uzly.py
168
3.53125
4
def uzly(n,a,b,c): i=2 counter = 1 while(1): if (i%a==0 or i%b==0 or i%c==0) and counter==n: return i counter+=1 i+=1 print(uzly(3,2,3,5))
61be4f81601f34c90a0e1bb17e419d7052025e6e
shadiqurrahaman/python_DS
/test/find_rotate_duplicate.py
759
3.890625
4
def search(arr,min,max,target): mid = (min+max)//2 if mid<=0 or mid>=len(arr)-1: return False if arr[mid]==target or arr[min]==target or arr[max]==target: return True elif arr[mid]>arr[min] and target<arr[mid] and target>arr[min]: return search(arr,min,mid,target) elif arr[mid]<ar...
d524faf55b9efd58c6509cf6f0c3e2ec5d03bb48
shadiqurrahaman/python_DS
/leet-code/valid_parenthesis.py
733
3.71875
4
def Find_is_valid(arr): arr = arr.replace(' ','') if arr=='': return True if len(arr)<2: return False paran = { '(':1,')':-1,'{':2,'}':-2,'[':3,']':-3 } stack = [] index = 1 stack.append(paran[arr[0]]) while(len(arr)>index): if len(arr)-index<len(stack): ...
c5f053126711857aa87be123552a14627b7d1e9a
shadiqurrahaman/python_DS
/linklist/Link_list_swap.py
1,204
3.9375
4
class Linklist: def __init__(self): self.head = None class Node(object): def __init__(self,data): self.data = data self.next = None def insert_data(self,data): return self.Node(data) def print_list(self): temp = self.head while(temp): print(temp.data) temp = te...
38e90d882910b6a133a3275b0fc2f52ec80b01fb
shadiqurrahaman/python_DS
/Binary-tree/leavel_order.py
968
3.8125
4
class Node: def __init__(self,val): self.val = val self.left = None self.right = None def levelOrder(self,root): result = [] queue = [] queue.append(root) counter = 0 counter2 = 1 while queue: tempre = [] while coun...
b14f4ec9e28ff50997a0f7b6375e177c15a01c08
shadiqurrahaman/python_DS
/array/array_rotate_one_by_one.py
367
3.96875
4
class job: def rotate(self,arr): temp = arr[0] for i in range(0,len(arr)-1): arr[i] = arr[i+1] arr[len(arr)-1] = temp return arr if __name__ == "__main__": arr = [1,2,3,4,5,6,7] job = job() arr = job.rotate(arr) arr = job.rotate(arr) arr = job.rotate(...
4ed237d4503a0595e8805d924403c9a5453e30d7
SheyMouse/100Games
/published/100Games_002_YourInterplanetaryAge.py
2,463
4.0625
4
# # 100 Games Project # # See http://mousesmusings.blogspot.co.uk/search/label/100%20Games for more information # Inspired by Jennifer Dewalt's 180 websites in 180 days - http://jenniferdewalt.com/ # # # Your Interplanetary Age # # 1. Ask the user's age # 2. Return their age in years of each of the ...
036cd2ed530dd55114190fd6d59a04ea93ae0dd8
jetli123/python_files
/廖雪峰-python/廖雪峰-内建函数之map()和reduce().py
3,300
4.1875
4
# -*- coding: utf-8 -*- """ map()函数接收两个参数,一个是函数,一个是 Iterable, map 将传入的函数依次作用到序列的每个元素,并把结果作为新的 Iterator 返回。 """ import logging logging.basicConfig(level=logging.INFO) """map()""" # 比如我们有一个函数 f(x)=x^2 # ,要把这个函数作用在一个 list [1, 2, 3, 4, 5, 6, 7, 8, 9]上, # 就可以用 map()实现如下 def f(x): return x * x r = map(f, [1, 2, 3...
80ccc65227fafa80fc7c89c31b1030ed7bf6ace7
jetli123/python_files
/廖雪峰-python/廖雪峰-getattr()、setattr()和hasattr().py
1,675
4.375
4
# -*- coding: utf-8 -*- """仅仅把属性和方法列出来是不够的,配合 getattr()、setattr()以及 hasattr(),我们可以直接操作一个对象的状态:""" class MyDog(object): def __init__(self, x, y): self.x = x self.y = y def power(self): print self.x * self.y obj = MyDog(9, 2) obj.power() """紧接着,可以测试该对象的属性""" print hasattr(obj, 'y') ...
fc182455342872797154b93b1e7f9b43a148df78
jetli123/python_files
/廖雪峰-python/廖雪峰-高阶函数.py
262
3.5625
4
# -*- coding: utf-8 -*- # 既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以 # 接收另一个函数作为参数,这种函数就称之为高阶函数。 def add(x, y, f): return f(x) + f(y) print add(-2, -4, abs)
3e4521c6473dda86bb1d926e411cbe3c8c7fa367
jetli123/python_files
/廖雪峰-python/廖雪峰-MySQL操作.py
1,396
3.5
4
# -*- coding: utf-8 -*- """ 由于 MySQL 服务器以独立的进程运行,并通过网络对外服务,所以, 需要支持 Python 的 MySQL 驱动来连接到 MySQL 服务器。MySQL 官 方提供了 mysql-connector-python 驱动,但是安装的时候需要给 pip 命令 加上参数--allow-external: $ pip install mysql-connector-python --allow-external """ # 导入 MySQL 驱动: import mysql.connector # 注意把 password 设为你的 root 口令: conn = mysql.c...
b5bc70ffb388b8e022763e404187d7d60b56db0e
jetli123/python_files
/廖雪峰-python/廖雪峰-面向对象之定制类-__str__.py
1,815
4.21875
4
# -*- coding: utf-8 -*- __author__ = 'JetLi' # -*- __str__ -*- class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name: %s)' % self.name __repr__ = __str__ # 直接显示变量调用的不是__str__(),而是__repr__(),两者的 # 区别是__st...
f7aeed5d41501daf842a6bd455b3042c028843bb
jetli123/python_files
/Python基础教程/ss.py
564
3.796875
4
# -*- coding: utf-8 -*- __metaclass__ = type class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print("Ahaaa, I'm hungry!") self.hungry = False else: print("No, thanks!") class SongBird(Bird): def __init__(self)...
3811095bcc1d2ea7da9b0b8e4a2384973054ab33
jetli123/python_files
/Python基础教程/linux-diff.py
1,287
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """This is diffrent two file""" import difflib import sys def main1(): # create file test1 test1 = """test1: I love you OK, I know, thank you very much! Please go to my home tonight folow me. """ test1_lines = test1.splitlines() # create...
123c032edcf3c3f86b49ee8c9dba5fd2afffa631
jetli123/python_files
/廖雪峰-python/廖雪峰-面向对象之类的继承和多态.py
1,539
4.4375
4
# -*- coding: utf-8 -*- """在 OOP 程序设计中,当我们定义一个 class 的时候,可以从某个现有的 class 继承,新的 class 称为子类(Subclass),而被继承的 class 称为基 类、父类或超类(Base class、 Super class)。""" class Animal(object): # Animal 是两个子类 dog 和 cat 的父类 def runs(self): print('Animal is running...') """当子类和父类都存在相同的 runs()方法时,我们说,子类的 runs()覆盖了 父类的 runs()...
e04a84d69a2f2cbff4b66bbc3e9afb16fb78657b
jetli123/python_files
/Python基础教程/Python教程-get方法.py
327
3.6875
4
labels = { 'phone': '110-02034', 'addr': 'Beijing' } name = raw_input('Name: ') request = raw_input('Phone number (p) or address (a)? ') key = request if request == 'p': key = 'phone' if request == 'a': key = 'addr' label = labels.get(key) result = labels.get(key, 'key') print "%s's %s is %s." % (name, label, r...
8ce41fff55efa5590736d34c3cd3e3c8f12a778d
jetli123/python_files
/廖雪峰-python/廖雪峰-多进程Linux下的fork.py
1,294
3.546875
4
# -*- coding:utf-8 -*- """Unix/Linux 操作系统提供了一个 fork()系统调用,它非常特殊。普通的 函数调用,调用一次,返回一次,但是 fork()调用一次,返回两次,因 为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程), 然后,分别在父进程和子进程内返回。""" # Python 的 os 模块封装了常见的系统调用,其中就包括 fork,可以在 # Python 程序中轻松创建子进程 import os print 'Process (%s) start...' % os.getpid() # Only works on Unix/Linux/Mac: pid = os.for...
91a29c4d16ea8e3459bf94a3303e090dd67617e3
jetli123/python_files
/廖雪峰-python/廖雪峰-面向对象之调用不存在的属性__getattr__()方法.py
1,549
4.15625
4
# -*- coding: utf-8 -*- """当调用不存在的属性时,比如 score, Python 解释器会试图调用 __getattr__( self, 'score')来尝试获得属性,这样,我们就有机会返回 score 的值""" """注意,只有在没有找到属性的情况下,才调用__getattr__,已有的属性, 比如 name,不会在__getattr__中查找。""" class Student(object): def __init__(self): self.name = 'Michael' def __getattr__(self, attr): if a...
94151785eb7b1c42f74aa0b4c5286f412bbbbdb4
Rockatanskyy/MITx
/FirstWeek.py
794
3.96875
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 3 17:51:31 2017 @author: Uri G Fernandez """ print('hello world') print('no se porque se hacen tantos renglones') x=int(input('Enter an Integer: ')) if x%2==0: print('') print('Even') else: print('Odd') print('Donde with conditional') x=...
1b6764ad01e51d627d6639b756cb3b9f3428be01
Farashi25/Python
/oopProduct.py
2,415
3.765625
4
class Product(object): def __init__(self, price, itemname, weight, brand, cost, status): self.itemname = itemname self.weight = weight self.brand = brand self.cost = cost self.status = status self.price = price self.tax = .05 def sell(self):...