blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e0b02db8a013d07a39ccc35f2ce95b9622f8d9d1
HaoboChen1887/leetcode
/tree/99_recover_binary_search_tree/99.py
1,721
3.703125
4
# Morris inorder traversal # 循环至当前节点为空 # 如果当前节点左孩子为空,则输出当前节点并将其右孩子作为当前节点 # 如果当前节点左孩子不为空 # 在当前节点的左子树中找到当前节点在中序遍历中的前驱节点 # 如果前驱节点的右孩子为空 # 将它的右孩子设为当前节点 # 当前节点更新为当前节点的左孩子 # 如果前驱节点的右孩子为当前节点 # 将它的右孩子设为空(恢复树的形状) # 输出当前节点 # 当前...
0ed3accae23066e474e749ad328023cb2c2316ac
HaoboChen1887/leetcode
/binary_search/33_search_in_rotated_sorted_array/33.py
1,227
3.984375
4
class Solution: # since we don't know how the array is rotated, we need a special strategy to determine # whether we go to the left or the right when doing binary search # the method is compare nums[mid] with nums[right] # if nums[mid] < nums[right] it means the right half is in order # if nums...
fc5414b24fa35acd2b50d09250b93b9efb09e5f7
HaoboChen1887/leetcode
/tree/102_binary_tree_level_order_traversal/102.py
674
3.703125
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 levelOrder(self, root: TreeNode) -> List[List[int]]: stack, res = [root], [] wh...
3a41a3ba23785fc607ef54d02bb4fe82a480bf36
tjasakpetric/GuessTheNumber
/guessthenumber.py
1,491
4.1875
4
# -*- coding: utf-8 -*- """ Igra ugani skrito število, posodobljena Avtor: Tjaša K. Petrič Računalnik bo izbral naključno število. Poskusi so omejeni na 4, nato napiše skrito število. """ import random def start(): hidden_number = random.randint(10, 90) attempts = 1 print "Let's play a game! Can you gue...
6e8449b3af3e103b9427f0bc39d997765a17bc81
KOHJeongHwan/TIL
/알고리즘/1976번_union.py
1,349
3.6875
4
# 특정 원소가 속한 집합을 찾기 def find_parent(parent, x): # 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출 if parent[x] != x: # parent[x] = find_parent(parent, parent[x]) return find_parent(parent, parent[x]) # return parent[x] return x # 두 원소가 속한 집합을 합치기 def union_parent(parent, a, b): a = find_parent(p...
ecd0dae39980ea2497b6bbbf0975b39b1b775779
dmadourie/Final-Project-CSS225
/adventuregame225.py
2,419
4.21875
4
from turtle import done username = input("What is your name?") print("Hello", username, "I hope you are ready, because it is going to be wild!") print("This game involves mystery of someone who's moved in next to someone who isn't as normal as others") # Chapter 1 # In the small town of Greenport, New York, a ne...
d4c7138d36add156aaf2456c197e81da50b2682a
oooookeyyyyy/BST
/BST.py
1,255
3.8125
4
class Node: def __init__(self, key : int): self.key = key self.left = None self.right = None def inorder(node : Node): if node is not None: inorder(node.left) print(node.key) inorder(node.right) def preorder(node : Node): if node is not None: print(node.key) preorder(node.left) pr...
50e4047d03429eb1e89228cbe8ed67c8f4c8a0d8
DavidGtzLeal/Massive
/myhelp.py
830
3.640625
4
def ask_help(): print("Welcome to Massive") print("") print("To send mass emails you have to follow the following steps:") print("") print("1. Open the file list.xlsx and edit it so that in the Mail column there are the emails of the people you want this message to reach. Then, in columns A1, A2 and...
bad62aee457df7c077f1f4e2013bdad02eba97d9
SupasanKomonlit/Run_for_Help
/input_data.py
799
3.59375
4
import arcade, arcade.key class Input_Character: def __init__(self): super().__init__() all_count = 97 self.upper_dictionary = {} self.lower_dictionary = {} lower_count = 97 upper_count = 65 while all_count < 123: self.upper_dictionary[all_count] ...
7bf802f460bd953446cb7e9c1bc5f6939f149df4
mosco/geodesic-knn
/dijkstra.py
1,455
3.515625
4
import numpy as np import scipy.sparse.csr import heapdict heap_pop_count = 0 def dijkstra(W, seed_index): ''' Input: W: n by n scipy.sparse.csr_matrix Edge *symmetric* weight matrix. We use the scipy.sparse.csgraph convention that non-edges are denoted by non-entries. ...
8b38d6cb625e37f3cc2eb5bfb817691d7a7f4142
jingjiwuwei/Day1_CodingTraining
/day1_hashtable.py
1,591
3.953125
4
import random import time """第一种方法: 使用hash表""" # 每隔一秒生成一个随机数 def gen_random_num(): time.sleep(1) random_num = random.randint(0, 100) return random_num # hash表存储随机数信息 random_dict = dict() # 插入的时间 insert_time = 0 # 同步系统的当前时间 cur_time = 0 # 最终的输出结果 res_list = [] if __name__ == '__main...
b552e65e8481aed475c6a060d9705854d0307e61
NtateLephadi/csc1015f_assignment_9
/rfunction.py
328
4
4
def reverse_string (sentence): new_sent = "" for i in range (len (sentence)-1,-1,-1): new_sent = new_sent + sentence[i] return new_sent def main (): sent = input ("Enter a sentence: ") print (reverse_string (sent)) print (reverse_string (sent+sent)) ...
ccedab4dbd4d9e8ff675d0f4d5bf8ee839a5cac7
aconstantinou123/binary_search_tree
/binary_search_tree.py
5,805
3.828125
4
from node import Node class BST: root = None def insert(self, key, value): new_node = Node(key, value) if self.root is None: self.root = new_node else: current = self.root parent = None while True: parent = current ...
b8e972174c0859b33ed896dfe29d8118624d71f5
rotan96/pewpewpew
/utils.py
3,378
3.671875
4
import pygame, random, math, variables #these are general functions that all classes can use def writeText(text, loc, color, size, screen): #Taken with minor adjustments from #https://www.pygame.org/docs/tut/tom/games2.html font = pygame.font.SysFont("Verdana", size) text = font.render(text, True, colo...
a7448806894cbb13366ac6d264e7f1a6d1871412
johnpavlovich/PythonCodingChallenges
/palidromes.py
253
3.984375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 9 13:54:29 2021 @author: john.pavlovich """ import re def is_palindrome(user_input): normal = ''.join(re.findall(r'[a-z]+', user_input.lower())) reverse = normal[::-1] return normal==reverse
1c7621783f27b385835802a6443f1aafd43d1c82
jeevi/miscPython
/gcd.py
243
4.125
4
arr = [[1, [], [2, 3]], [[4]], 5] print flatten(arr) def flatten(arr): for x in arr: if isinstance(x, list): for y in flatten(x): yield y else: yield flatten(x) print flatten(arr)
57197e2b3ce6914a3f394119d748e3ec3d036f5d
davesantiarlom/AirBnB_clone_V2
/web_flask/3-python_route.py
1,199
3.78125
4
#!/usr/bin/python3 """ This script starts a Flask web application """ from flask import Flask app = Flask(__name__) @app.route('/', strict_slashes=False) def hello_hbnb(): """ Print the following message upon connecting to Flask at the above app.route """ return "Hello HBNB!" @app.route('/hbnb', str...
60f9379fc304f62f59ec8686c0303ef782f00e67
jjlis/kurs_katowice
/dzień 2/Zadanie14.py
949
3.796875
4
# liczba_min = 0 -> 0 nie może byc min. # None określa nieznane dane liczba_min = None if liczba_min is None: print("Tak") # is True is False is None x = "Napis 1" y = "Napis 1" # id -> jest to identyfikator obiektu w pamięci print(id(x), id(y)) # is jest głębszym porównaniem bierze równiez pod uwagę identyfika...
c82d90f4987b5e14114a41314b3d661bc6935a6a
jjlis/kurs_katowice
/dzien 4/zadanie_10.py
560
3.90625
4
# Napisz funckje ktora jako argument przyjmie liste list i zwroci liste bedaca ich polaczeniem. # # flatten([[1, 2], [3,4]] -> [1,2,3,4] # dodatkowo- sprobuj napisac funckcje ktora moze przyjac wiele argumentow, ktore sa listami i zwroci ich polaczenie. def flatten(*elements): # Przyklad if len(elements) == 1: ...
d4b51ea2ecbd9b430dbd97520e0419b6a3624992
jjlis/kurs_katowice
/dzień 2/kolekcje_zadanie1.py
104
3.515625
4
x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10,) print(x[1]) print(x[-2]) print(x[2:7]) print(x[::3]) print(x[::-2])
e7c86b28e509a8fe9fe564cbf450d2359fd3ee4b
jjlis/kurs_katowice
/dzien 4/zadanie_11.py
835
3.953125
4
# Napisz funkcje largest_difference, ktora przyjmie liste elementow i zwroci najwieksza roznice miedzy nimi # # largest_difference([1,2,3, 10]) == 9 # napisz funkcje largest_difference2, ktora zadziala podobnie ale argumenty podajemy osobno a nie w liscie # largest_difference2(1,2,3, 10) == 9 def largest_difference(e...
c4c364954af043961ae48041b76040585a2fb9b0
bangalorebyte-cohort22/WeekendAssignment-2
/prince/dbman.py
1,290
3.71875
4
#!/usr/bin/env python3 ''' Manages the database part ''' import json import re # Loading the json file (complete list of cities) FIN = open('databases/city.list.json', 'r') DB = json.load(FIN) FIN.close() def get_code(search): ''' For getting city id. ''' search = "".join(re.sub(r' +', ' ', search)) sear...
563b49449ffdb53101c1c7724d19b0fc837d1272
ArchanaRaghu512/Python-Practice
/Desktop/python prac/createLink.py
284
3.71875
4
''' program : create links Author: Archana ''' heroes = ['batman', 'superman', 'wonderwoman', 'aquaman'] for i in heroes: print(i) url = 'www.heroes.com' for i in heroes: print(url+'/'+i+'.txt') urll = [] for i in heroes: links = url+'/'+'.txt' urll.append(links)
a20edd9015a244b8d83d350644b4314a4450fcd6
alexacevedo/python
/SQlite/musique_bd.py
4,022
3.96875
4
# coding: utf8 # SQLite with Python """ programme: musique_bd.py - Le programme qui va afficher à l'écran la liste numérotée des artistes dans la BD. - Le programme va afficher la liste des albums d'un artiste en particulier (en saisissant son numéro au clavier) - Le fichier input_data.txt contient des données sur ...
6bcf7e9fe13025369552c7308f90677a70341f45
QingHuan-0526/leetcode-Python
/stack/leetcode225_MyStack.py
968
4
4
""" leetcode 225 用队列实现栈 """ import collections class MyStack: def __init__(self): """ Initialize your data structure here. """ self.stack = collections.deque() def push(self, x: int) -> None: """ Push element x onto stack. """ self.stack.append(...
df9f90289de348e43b100d8670ae208c5ad069f6
JakubGornicz/wizualizacja-danych
/zadania-python/zadanie#6.09.py
376
3.796875
4
import numpy as np # Wykorzystaj poznane na zajęciach funkcje biblioteki Numpy i stwórz # macierz 5x5, która będzie zawierała kolejne wartości ciągu Fibonacciego. def fib(n): a, b = 0, 1 for i in range(0, n): a, b = b, a + b return a n = 5 mat = np.arange(1, n*n+1) for i in range(0,n*n) : mat[...
82759989deac888632a24fc645495c70949232b3
JakubGornicz/wizualizacja-danych
/zadania-python/zadanie#5.11.py
330
3.796875
4
def fib( ): a, b = 0, 1 while True: yield a a, b = b, a + b a = fib( ) #aby pokazać jak działa generator, wypisujemy np. pierwsze 50 wyrazów #ale ponieważ jest on oparty na pętli "while True" możemy policzyć watość #dowolnego elementu tego ciągu for i in range(50): print(next(a))
c69834a4e517a7056919a3d4da155b726627241b
dhruvghulati-zz/unsupervised-learning-workshop
/mnist_pca_knn.py
1,826
3.703125
4
from __future__ import print_function from sklearn.datasets import fetch_mldata from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np # Download the MNIST digits dataset and store in the va...
e43073c2762c47a0568546fd1d25a6324917c423
OneTesseractInMultiverse/python-class-group-1
/Objetos/curriculum_objetos.py
6,958
3.71875
4
# --------------------------------------------------------------------------- # CLASE ESTUDIO # --------------------------------------------------------------------------- # Definición básica de una clase # Los nombres de las clases son lo único que utiliza CamelCase class Estudio(object): # Constructor en Py...
e8cb41866df934cc3e640f682d894efb7247f1bd
OneTesseractInMultiverse/python-class-group-1
/s-clase2/ciclo-for.py
1,062
4
4
""" print(range(5,10)) total_impares = 0 # por cada [variable] in [range/collection]: for numero in range(5, 27): if numero % 2 != 0: print(numero) total_impares+=1 print("El total de impares es {}".format(total_impares)) for num in range(1, 10): for factor in range(1, 10): resultado_mu...
fd6e35978dae3080aecb87e1bf64a4a443eae1e8
OneTesseractInMultiverse/python-class-group-1
/Semana8/encapsulamiento.py
2,664
3.890625
4
class Engine(object): # ------------------------------------------------ # Constructor # ------------------------------------------------ def __init__(self, type, hp, brand): self.__type = type # Diesel, Gas, Electric self.__hp = hp # Horse Power self.__brand = brand se...
c9524c46f10dbfb55a32bf3bf691613daf9a9660
OneTesseractInMultiverse/python-class-group-1
/Estructuras/diccionarios.py
1,184
3.71875
4
import pprint # Vamos a empezar declarando un diccionario vacío diccionario_vacio = {} # un diccionario con valores establecidos como literales datos_personales = { "nombre": "John", "apellido": "Smith", "edad": 20, "carreras": [ "Computación", "Física" ], "universidad": { ...
2a140acc6ed27e3d5c69135593d167191d7daabd
mfem/PyMFEM
/mfem/common/arg_parser.py
624
3.625
4
from argparse import ArgumentParser class ArgParser(ArgumentParser): def __init__(self, *args, **kwargs): self.argument_list = [] ArgumentParser.__init__(self, *args, **kwargs) def add_argument(self, *args, **kwargs): ArgumentParser.add_argument(self, *args, **kwargs) self.arg...
bf67fba18e4014ac8d2dd46cb2a6d5e0244a48eb
MaratAnvarych/AppliedPythonAtom
/homeworks/homework_01/hw1_arrsearch.py
324
3.671875
4
#!/usr/bin/env python # coding: utf-8 def find_indices(input_list, n): length = len(input_list) i = 0 while i < length: j = i+1 while j < length: if input_list[i] + input_list[j] == n: a = (i, j) return a j += 1 i += 1 ret...
d33c0188984fcc76e229dee16561b1eab3c2377f
ssiedu/python-multithreading
/mt-5.py
1,045
3.71875
4
import time; import threading; def square(numbers): indsq=threading.current_thread().ident; print("Square Indent : "+str(indsq)); name=threading.currentThread().getName(); for n in numbers: time.sleep(.10); print("SQUARE By - "+name+" : "+str(n*n)); def cube(numbers): indcb...
8b4b6563c7ca0545c75364d5877ca5a43a1931ec
lukew3/pythonGpaCalculator
/gpa.py
1,879
3.796875
4
def lettersToNumbers(listName): i = 0 number = 0 length = len(listName) while (i < length): letter = listName[i] if (listName == normalGrades): number = convertToGP(letter, number) elif (listName == apGrades): number = convertToGP(letter, number) + 1 ...
20fe81d5b51384fc82478b37e8eceec633378134
Cherchercher/magic
/tests/test_flatten_array.py
1,193
3.5
4
#!/usr/bin/python from context import flatten_array_recursive def run_test_flatten_array(): # defined test input and expected output test_array_1 = [[1, 2, [3]], 4] test_array_1_result = [1, 2, 3, 4] test_array_2 = [[[[1]]]] test_array_2_result = [1] test_array_3 = [[[[-1]]]] test_array_3_...
cd8acaf54f7895c9e2947bfa6a2d94f8dcd9de01
osamajomaa/MARC
/database/DB.py
6,510
3.65625
4
""" Author: Osama Jomaa Date: 2014-2015 Version: 1.0 This module contains functions necessary to connect to MARC DB. """ import pymongo from sets import Set def Connect(): """ Connects to a mongo database by reading the following parameters from utils/db_creds.txt file: 1) Server's address (1st line)...
aea44b2c7542508f295e07812fc721034513608d
roxolea5/pythonRefresh
/Sesion2/reto3.py
171
3.734375
4
#Numeros de la serie fibonacci hasta el 100 num1 = 0 num2 = 1 while num1 < 1000: print (num1, end=' ') fib = num1 + num2 num2 = num1 num1 = fib
ccc22ff9f39f6f7de729a89b937b6bb06fd74b70
roxolea5/pythonRefresh
/PreWork1/basicsyntax.py
403
4
4
#print instruction print ("Hi people") #More than 1 instruction on python require ";" and is not recommended print ("Hi people"); print ("i don't like ';' on Python") #This is a comment #variable declaration my_name = "Hi my name is Roxana" print(my_name) #spliting codeline \ your_name = "This is your\ splitted na...
a33cbe6c4700b5e09c10ef190f40315611e38433
roxolea5/pythonRefresh
/Sesion3/reto_modulo.py
239
3.640625
4
from math import sqrt, factorial, gcd as max_com_div root = 25 fact = 6 print('La raiz de {} es {}'.format(root, sqrt(root))) print('El factorial de {} es {}'.format(fact, factorial(fact))) result = max_com_div(8,32,40) print(result)
6817f90614105b6cccf3174bf8ceff64360b0c5e
Paarth-go/university-lectures
/artificial-intelligence-basic/maze-solve-genetic-algorithm/src/solve_maze.py
5,398
3.6875
4
import src.setup as setup from src.position import Position from src.population import Population import random """ Solve the Maze: try to find a path from start to target in the maze which has some obstacles. Use Genetic Algorithm """ # Create a maze, and obstacle(x, y, vertical) def create_maze(): mutation_rat...
80461ab822e663ef9eb3a9de871eeba21a7db3ae
anusky95/leetcode
/Contest/1652. Defuse the Bomb.py
2,697
3.71875
4
""" 1652. Defuse the Bomb Easy 8 7 Add to List Share You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. If k > 0, replace the...
2207b0f64f99408840321fe10a6eae0efe23be69
league-python-student/level0-module1-RedHawk1967
/_03_if_else/_5_circle_calculator/circle_calculator.py
882
4.5625
5
from tkinter import simpledialog, messagebox, Tk import math # Write a Python program that asks the user for the radius of a circle. # Next, ask the user if they would like to calculate the area or circumference of a circle. # If they choose area, display the area of the circle using the radius. # Otherwise, displ...
501db94a19e69c4d08ff52d3bb58d5ab29b69f30
victor99z/Python3_CeV
/Desafios/des_007.py
161
3.765625
4
nota1 = float(input('insira a 1ª nota: ')) nota2 = float(input('Insira a 2ª nota: ')) calc = (nota1+nota2)/2 print('A média das notas é {:.2f}'.format(calc))
cae3c219e78e2533639c0b2ac41b5026e7899ad8
victor99z/Python3_CeV
/Desafios/des_31.py
230
3.84375
4
km = float(input("Informe a kilometragem da viajem: ")) if km > 200: print("Você irá pagar {:.2f} pela viajem de {}km's".format(km*0.45,km)) else: print("Você irá pagar {:.2f} pela viajem de {}km's".format(km*0.50,km))
72c98eba14ef4c82877658ae1b18be6a3c542cbd
victor99z/Python3_CeV
/Desafios/des_35.py
372
4
4
r1 = float(input("Informe o valor da reta 1º ")) r2 = float(input("Informe o valor da reta 2º ")) r3 = float(input("Informe o valor da reta 3º ")) if r2-r3 < r1 < r2+r3 and r1-r3 < r2 < r1+r3 and r1-r2 < r3 < r1+r2: print("Pode-se formar triângulos com as retas {} {} {}".format(r1,r2,r3)) else: print("Infelizm...
2baa923cc906159701b06c0c3c0508b15bfa0ca1
victor99z/Python3_CeV
/Desafios/des_32.py
381
3.890625
4
ano = int(input("Informe um ano ")) calc1 = ano % 4 # tem que ser multiplo de 4 calc2 = ano % 400 # tem que ser multiplo de 400 calc3 = ano % 100 # Não pode ser multiplo de 100 if calc1 == 0 and calc3 != 0: print("O ano de {0} é bissexto".format(ano)) elif calc3 == 0: print("O ano de {0} é bissexto²".format(a...
0945af0fd71fba7356def62848cda0aff7658462
victor99z/Python3_CeV
/Desafios/des_010.py
143
3.671875
4
valor = float(input('Insira o valor em reais: ')) calc = valor/3.27 print('O valor em dólares que você poderá comprar é ${} '.format(calc))
18d076bf7bad0fd72ab04f09886b27e32ad07afe
niwanshu16/FDSP2019
/Day11/day11.py
1,007
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon May 20 16:01:41 2019 @author: KIIT """ import matplotlib.pyplot as plt # Reshaping an array import numpy as np l = list(map(int,input().split())) x = np.array(l) x = x.reshape(3,3) print(x.ndim) print(x) # using normal # mean,sd,no.of entries inc...
cdc280916d60bfc0cec6dda73fbcfea458c1df23
niwanshu16/FDSP2019
/Day1/fact.py
134
4.125
4
'''Factorial of a number ''' a = int(input()) fact=1 while a>=1: fact*=a a-=1 print("Factorial is {}".format(fact)) input()
f1063878175f7a491bc9cb81cb62b4b7f6f86589
Lukeyong26/chatroom
/test.py
141
3.609375
4
dictionary = {} name = "luke" value1 = 2 value2 = 3 dictionary[name] = value1 name2 = "luke" dictionary[name2] = value2 print(dictionary)
ce0ca004d5f200f2cd55c1c569b37c3895c57d57
VictorECM/python-challenge
/PyBank/main.py
2,768
3.71875
4
import os import csv csvpath = os.path.join("..","Resources","budget_data.csv") #read header and then the other lines of data into either dictionary or list # not working in having only one list with row and column, have to split the data #months = [row for row in reader] # print(header) # print(data) pnl = [] cha...
207e9b13459d5a1bee3f544d3fb4dfd1a913f9e3
lawvs/Algorithm-Training
/leetcode/821.shortest-distance-to-a-character.py
901
3.734375
4
#!/bin/python3 # -*- coding: utf-8 -*- ''' leetcode #821 shortest-distance-to-a-character 字符的最短距离 https://leetcode-cn.com/problems/shortest-distance-to-a-character/ 76 / 76 个通过测试用例 执行用时:80 ms ''' class Solution: def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: L...
394c5d0d6100430f80ac004f0af0f0f0bfb2f762
lawvs/Algorithm-Training
/leetcode/875.koko-eating-bananas.py
2,461
3.875
4
#!/usr/bin/env python3 ''' leetcode #875 koko-eating-bananas 爱吃香蕉的珂珂 https://leetcode-cn.com/contest/weekly-contest-94/problems/koko-eating-bananas/ ''' import math def isEnough(piles, eatingSpeed, H): # assert(len(piles) < H) # assert(piles[i] > 0) # assert(piles[i] > piles[i - 1]) // sorted if eating...
4aa4d0fa01b3dc04a51cedc28bc5c04a146113f2
lawvs/Algorithm-Training
/mioj/91.py
2,738
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 不要乱改代码 https://code.mi.com/problem/list/view?id=91 ''' class DisjointSet: ''' 并查集 ''' parent = None rank = None dictMode = False def __init__(self, l=0, dictMode=False): self.dictMode = dictMode # list mode # if l ...
e838ca993a982618b2a32ac7522d7d836522d531
lawvs/Algorithm-Training
/leetcode/104.maximum-depth-of-binary-tree.py
661
3.921875
4
#!/usr/bin/env python3 ''' leetcode #104 maximum-depth-of-binary-tree 二叉树的最大深度 https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/ ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None...
f2548c82eeb8f8772ff904a5664946355a8ab046
reihan35/inital_subpath_stream_isomorphism
/bfs_hamissi.py
1,439
3.75
4
from queue import Queue def neighbours(node,E): n = [] for i in range(0,len(E[node])): if E[node][i]==1: n.append(i) return n def bfs(gprim,start): visited = [] for x in range(0,len(gprim)): visited.append(0) queue = [] all_paths = [] queue.append([start]) ...
32ea83697a8e823eb2f9e657159e5e3271edcc3b
tgkei/Algorithm_study
/by_python/algospot/quadtree.py
420
3.71875
4
def solve(): global pos if s[pos] == 'w' or s[pos]=='b': return s[pos] else: pos+=1 top_left = solve() pos+=1 top_right = solve() pos+=1 bottom_left = solve() pos+=1 bottom_right = solve() return 'x'+bottom_left + bottom_right +...
198b5bf879ccf3e62603a940f91d758a16e7e788
tgkei/Algorithm_study
/by_python/programmers/int_triangle.py
711
3.53125
4
def dfs(col, row, n): global cache global global_triangle if col >= n or row >= n: return 0 if cache[row][col] != -1: return cache[row][col] ret = dfs(col, row+1, n) ret = max(ret, dfs(col+1, row+1, n)) cache[row][col] = global_triangle[row][col] + ret return cache[r...
c52b16cf6e12b50c62239c2210a0403e69e3ad29
tgkei/Algorithm_study
/by_python/week5/9012.py
280
3.71875
4
for _ in range(int(input())): inputs = input() result = 0 for par in inputs: if par == '(': result+=1 else: result -=1 if result <0: break if result==0: print("YES") else: print("NO")
b9be9d9a6160c1edee54de9139de2f6f788b658b
tgkei/Algorithm_study
/by_python/daily/1.py
630
3.59375
4
def solution(input_array): left = [-1 for _ in range(len(input_array))] right = [-1 for _ in range(len(input_array))] left_mul = 1 right_mul = 1 for i in range(len(input_array)): left_mul *= input_array[i] right_mul *= input_array[-(i+1)] left[i] = left_mul right[-(i+...
426c212871e96df3d7d65235826c855df7ea0510
tgkei/Algorithm_study
/by_python/2020wintercoding/2.py
921
3.6875
4
def solution(encrypted_text, key, rotation): ALPHA = "abcdefghijklmnopqrstuvwxyz" tmp = dict() tmp2 = dict() idx = 1 for alpha in ALPHA: tmp[alpha] = idx tmp2[idx] = alpha idx += 1 answer = "" rotation %= len(encrypted_text) if rotation > 0: encrypted_...
c30832092701a722242f7ff9fe3ee467d2329d7b
tgkei/Algorithm_study
/by_python/programmers/camera.py
427
3.546875
4
def solution(routes): answer = 1 routes.sort(key=lambda x: x[0]) end = routes[0][1] for route in routes[1:]: if route[0] > end: answer += 1 end = route[1] else: end = min(route[1], end) answer = answer if answer else 1 return answer if __n...
e03ebf4ea216684076772207c6e145c4c87aa447
tgkei/Algorithm_study
/by_python/kakao/1.py
799
3.6875
4
def check_stack(stack): result = 0 while len(stack) >= 2 and stack[-1] == stack[-2]: stack.pop() stack.pop() result += 2 return result def solution(board, moves): answer = 0 stack = [] pos = dict() for row,r_value in enumerate(board): for column,value in enum...
5afd076a70bcd05810d663eedd300f64ab43cb17
tgkei/Algorithm_study
/by_python/programmers/43238.py
454
3.5625
4
def solution(n, times): answer = 0 times.sort() start = times[-1] * n end = times[0] * n while start < end: mid = start + end // 2 total = 0 for time in times: total += mid // time if total >= n: answer = mid end = mid else...
2544289bdcfe34def5537f5ec97cdf9ec8e77ec9
aleksandra312/PythonExercises
/21_extract_full_name/extract_full_name.py
185
3.578125
4
def extract_full_names(people): """Return list of names, extracting from first+last keys in people dicts.""" return [f"{person['first']} {person['last']}" for person in people]
bcfe01d8c45cb66fa386cacdd3a087d5ca12052f
jesseyli/Coding-Practice
/problem1.py
873
3.703125
4
# This problem can be solved by finding the maximum of the maximum products that end at each # index of A. Let maxProd(A[i]) be the maximum product that ends at A[i] and let minProd(A[i]) # be the minimum product that ends at A[i]. At each index i, the maximum product will either be # A[i], A[i]*minProd(A[i-1]), or A...
a95766c5a2bfe1fc7ce54cb5e7e8594f1d58c97f
dhivya134/Python-workshop
/Practice Probelms/conditional.py
1,462
4.09375
4
#question 1 a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) if a<b: print("The smallest number is : ",a) else: print("The smallest number is : ",b) print() #question2 n= int(input("Enter the number : ")) if n%2==0: print(n,"is an even number") else: ...
13fa8d659959acdecae89aeb42fc1a563f591352
PyLadiesPoznanAdvanced/work-schedule
/person.py
2,510
3.578125
4
class Person: """Klasa Person. Klasa służy do tworzenia instancji Person. Zawiera metody potrzebne do automatycznego wypełniania grafiku pracy (schedule). """ def __init__(self, name, schedule): """Konstruktor klasy Person. :param name: nazwisko :param schedule: grafik pr...
3a0c28f9ba9769c07421af6f9874ed77a510af1f
utep-cs-systems-courses/python-intro-JaAguayo
/wordCount.py
1,054
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import sys inputFname = sys.argv[1] outputFname = sys.argv[2] word_count = {} #open input file with open(inputFname, 'r') as inputFile: for line in inputFile: # get rid of newline characters line = line.strip() # split line on whit...
a65b514a09589aab7674804458ba354f83a7188f
yidapa/PyCase
/pycase/case.py
1,055
4.15625
4
# -*- coding: utf-8 -*- # @Date : 2019-05-26 # @Author : Peng Shiyu import argparse def convert_upper(text): text = text.title() return text.replace("_", "") def convert_lower(text): lst = [] for index, char in enumerate(text): if char.isupper() and index != 0: lst.append("...
91a456d12817c9d82b33b12a06d890a6e7509334
seahawks97/ReverseCheck
/new_checker.py
2,503
4.03125
4
# Steven Tucker # 25 November 2018 # New, fully functional palindrome checker def main(): while True: # gets string and integer numbers num = get_number() int_num = int(num) # Gets the number into a list of its integers, and a reversed, usable list my_list = [int...
af45018ac5eb171a9e6be1c00e027410aafd8b7f
phops2010/SimpleNeuralNetwork
/SimpleNN/__init__.py
11,974
4.5
4
""" Simple Neural Network Module that can be used to learn about how neural networks work. Please feel free to modify anything you see, as this is a very simple module. Its not intended to be used for any hardcore deep learning, and not robust enough to handle erroneous outputs. It is however fully functional and can b...
832f123c8938ca9920a84cd257b2ff3d4d7643f8
AK-171261/python-datastructures-programs
/reverse_content.py
893
4.125
4
# Python Program to Reverse the Content of a File using Stack import os class Stack: def __new__(cls, *args, **kwargs): return super(Stack, cls).__new__(cls) def __init__(self): self.arr = [] def push(self, val): return self.arr.append(val) def is_empty(self): retu...
51a61bb3f04fcf328e64011737fb9f2d67d80e95
edufreitas-ds/Datacamp
/02 - Intermediate Python/00 - Matplotlib/00 - Video - Basic plots with Matplotlib.py
838
3.84375
4
""" BASIC PLOTS WITH MATPLOTLIB - Visualization - Data Structure - Control Structures #Customize the flow of your scripts and algorithms. - Case Study DATA VISUALIZATION - Very important in Data Analysis - Explore data - Report insights * GapMinder, Wealth and Health of nations """ """ MA...
ec948ed60b2c509752eb824bf90702ef8daedd6d
edufreitas-ds/Datacamp
/02 - Intermediate Python/01 - Dictionaries and Pandas/04 - Video - Dictionaries, Part 2.py
1,116
4.15625
4
""" RECAP """ world = {"afghanistan":30.55, "albania":2.77, "algeria":39.21} print(world["albania"]) world = {"afghanistan":30.55, "albania":2.77, "algeria":39.21, "albania":2.81} # The last pair that you specified was kept in the resulting dictionary print(world) """ KEYS HAVE TO BE "IMMUTABLE" OBJECTS ...
5e4e26a09153a6decb081483c4b844d09caff7da
edufreitas-ds/Datacamp
/01 - Introduction to Python/03 - NumPy/13 - Explore the baseball data_adapted.py
1,223
3.59375
4
""" It's again available as a 2D Numpy array np_baseball, with three columns. The Python script in the editor already includes code to print out informative messages with the different summary statistics. Can you finish the job? """ import numpy as np height = np.round(np.random.normal(1.75, 0.20, 5000), ...
76b723d07f7980f52fa0a1943e2d6ade05f49d6f
edufreitas-ds/Datacamp
/01 - Introduction to Python/01 - Python Lists/06 - Subset and calculate.py
723
4.625
5
"""After you've extracted values from a list, you can use them to perform additional calculations. Take this example, where the second and fourth element of a list x are extracted. The strings that result are pasted together using the + operator:""" x = ["a", "b", "c", "d"] print(x[1] + x[3]) # Create the area...
e0d3491802bc9423694a3ed0a90c42562f529db1
okpy/jassign
/tests/test_strip.py
1,303
3.734375
4
from jassign.to_ok import replace_solutions examples = [ (( "def square(x):\n" " y = x * x # SOLUTION NO PROMPT\n" " return y # SOLUTION\n" "\n" "nine = square(3) # SOLUTION" ), ( "def square(x):\n" " ...\n" "\n" "nine = ..." ...
d77f18a8bb8a7b1b414e968fec45019a54ab00b2
aluchici/cmi-class-apr-2021
/session5/sample_api/mongo_mediator.py
5,180
3.5
4
import json from dataclasses import field from typing import List from bson import json_util from pymongo import MongoClient class MongoMediator: def __init__(self, conn_string: str = None, collection_name: str = "general"): self.__client = MongoClient(conn_string) self.__collect...
c80c74abdfaca8e10d508d96948665ac5fb0b8a6
JasonG-FR/python-text-calculator
/basicfunc.py
2,635
3.96875
4
# This file is for basic functions and small functions that would be in func.py. import logging from cprint import cprint if __name__ == "__main__": print("Please do not run any of these files directly. They don't do anything useful on their own.") def getNum(): #ask for two numbers and then return to function ...
1b5600132ed31bc475c59ad1e23c247c83dcaca3
lynnprosper/leetcode
/[leetcode]033-Search in Rotated Sorted Array[二分查找].py
1,111
3.609375
4
''' 1. 原题 https://leetcode.com/problems/search-in-rotated-sorted-array/ 2. 思路 题意:一个有序列表在某个位置前后两部分被调换,求出给定值的索引下标。 思路:题目要求时间复杂度log(n), 显然要用二分法。 我们依然考虑中间值n[mid], 如果其小于最右值,那么右部分是有序的。 否则左部分有序。这样不断在某部分查找即可。 ''' class Solution: def search(self, nums: List[int], target: int) -> int: left, right = 0, len(nums)-...
e33968128d2e13c89e2c78ca57e12ecc43b3e54e
lynnprosper/leetcode
/[leetcode]048-Rotate Image[数学逻辑].py
1,003
3.8125
4
''' 1. 原题 https://leetcode.com/problems/rotate-image/ 2. 思路 给出一个方阵,将其顺时针旋转90度后,输出结果。 限定条件,空间复杂度为常量。 显然,最容易想到的是一圈圈的交换元素旋转。不过代码实现有点复杂。 可以慢慢观察,矩阵先以副对角线交换后,再水平居中翻转,就能实现。 也可以先主对角线,再竖直居中对调。 ''' class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matri...
eb9d84c7ded66582173f14648e3e5d616a36bde2
giorgil/dejavu
/dejavu/containers.py
5,935
3.8125
4
"""Useful container classes. According to Stroustrup: (http://www.research.att.com/~bs/glossary.html#Gcontainer) container - (1) object that holds other objects. (2) type of object that holds other objects. (3) template that generates types of objects that hold other objects. (4) standard library template such as vec...
dc8a33066b7130c49b1a88f51e0694bf6ce74d52
youthlx/ToLuLu
/lesson/3_operate_control/for.py
1,614
3.765625
4
# -*- coding:utf-8 -*- # author xin.luo # for,while是用于遍历的,或者理解为循环操作,主要针对两种数据类型,一种是list/tuple,一种是dict # 它的基本格式是 # for item in items: # do sth for item # 下面我们分别对list/tuple和dict来做遍历 # 遍历list WEEK = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for day in WEEK: print(day) # 遍历dict CH...
10f98d908cf715d80043d19a0c06bdcf52c0d83a
TheWildMonk/turtle-crossing-capstone-project
/scoreboard.py
675
3.734375
4
from turtle import Turtle FONT = ("raleway", 16, "bold") LEVEL = 0 class Scoreboard(Turtle): def __init__(self): super().__init__() self.level = LEVEL self.color("#009432") self.penup() self.hideturtle() self.goto(-260, 260) self.write(f"LEVEL: {self.level}...
04b7c560b8523d6a477bff758b5e4c6b62e87152
the-carpnter/algorithms
/no_consonants.py
833
3.78125
4
# Iterative Solution def consonants(string): count = 0 for i, ch in enumerate(string): if ch.isalpha() and ch.lower() not in 'aeiou': count += 1 return 'The no of consonants: ' + str(count) # Recursive Solution def cons(string, i=0, count=0): if string[i].isalpha() and string[i].low...
8b79236f92d1249fe3ced4eb3c7858e1bd72dd24
SpencerHoGD/Public_Code
/query.py
5,211
3.96875
4
import sqlite3 def get_students_course(cursor, course): ''' 联合course和student_course表筛选出选了该课程学生的学生号。 并且联合student和student_course筛选出选了该课程学生的名字。 ''' sql = ("SELECT a.student_name, c.course_name FROM \ student AS a JOIN student_course AS b JOIN course AS c \ ON a.student_no = b.student_no...
e1ed31ce8ac2a446bc4441fd970b049817212cdc
Drux-maker/python
/funcionesdeordensuperior.py
304
3.546875
4
def seleccion(operacion): def suma(n,m): return n+m def multiplicacion(n,m): return n*m if operacion == "suma": return suma elif operacion == "multi": return multiplicacion fGuardada = seleccion("multi") print (fGuardada(3,4))
f981b317b57317219e40f343f905a581e4a51371
Drux-maker/python
/listas.py
323
4.09375
4
lista = [1,"Dos", 3] #un conjunto de datos ordenados buscar = 0 if buscar in lista: print (lista.index(buscar)) else: print ("No esta en la lista") iterable = [1,2,3,4] lista.extend(iterable) print (lista.pop(1)) lista.remove(3) lista.reverse() print (lista.count(1)) print (lista[0]...
99340083f465dc05954fbeae049105981ee1311f
soo-pecialist/GeorgiaTech_CSE
/02_2018_Spring/ISYE6740_Computational Data Analysis _ Machien Learning/HW4_code/prpy/trees.py
6,918
3.515625
4
""" prpy module trees.py Jason Corso (jcorso@acm.org) This module has been programmed to support teaching an introduction to pattern recognition course. Contains tree classifiers """ # local imports import datatools # global imports import numpy as np kDT_MaxDepth = 5 # maximum depth we'll grow a decision tre...
f293b698647439dc85f60140b2a0b84e4001654b
BharaniSri10/DSA-Together-HacktoberFest
/stacks/Medium/BalancedParenthesis.py
1,769
3.921875
4
#User function Template for python3 class Solution: #Function to check if brackets are balanced or not. def ispar(self,x): # code here stack = [] for char in x : if (char in ["(" , "{" , "["]): stack.append(char) ...
9a9e981d92c77feac5579f72ddd6e5a95dd2a6c0
BharaniSri10/DSA-Together-HacktoberFest
/Arrays/Easy/buy_and_sell_stock_1.py
490
3.59375
4
def maxProfit(prices): min_so_far = prices[0] max_profit = 0 n = len(prices) for i in prices : min_so_far = min(min_so_far , i) profit = i - min_so_far max_profit = max(max_profit , profit) if(max_profit == 0): return -1 return max_profit arr = [] n ...
7389484e0bd223e599d38b5a40c40ad5235a5994
Leonidas-from-XIV/sandbox
/fizzbuzz.py
602
3.59375
4
import sys def divisible(num, factor): return num % factor == 0 def divide(num, a, b): if divisible(num, a) and divisible(num, b): return "FB" elif divisible(num, a): return "F" elif divisible(num, b): return "B" else: return str(num) def process_line(a, b, n): ...
02dcb9387c9c741c945c42df86e9b05d6c567050
kcaras/ConversationalHumor
/humor/utils/word_manipulation.py
4,238
3.609375
4
import collections import csv from typing import Dict, List, Tuple import nltk.tokenize from utils.file_access import CORNELL_BASE_FOLDER, file_exists, HUMOR_VALUES_FILE, MOVIE_CONVERSATIONS_FILE, MOVIE_LINES_FILE, open_data_file, STARTER_LINES_FILE def build_word_indices(words: List[str]) -> Tuple[Dict[str, int], D...
a6ffba71603dec114460e87d0950eb00e89dec72
Alec-Tan/SudokuSolver
/solver.py
6,019
4.09375
4
import random def new_blank_board(): """ Creates a new sudoku board with no numbers entered. Returns: List of List of int: A 2D array which represents a sudoku board. """ return [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0...
4398d222399a97c9b66ce6491c6b33c8d00d2731
gmoore016/Project_Euler
/Complete/Problem005.py
4,645
3.765625
4
""" Gideon Moore 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? (Note: I think the dynamic programming here is likely overkill for an input of only 20 continuo...
6b18954112b25fa1fcd4fdf37370638da5f02e55
ofhellsfire/python-notes
/notes/concurrency/threads/deadlock.py
1,279
3.765625
4
"""This demonstrates deadlock in action. Thread A Dictionary Thread B wait ------> var_a <--- set \ / ========= / \ set ------> var_b <--- wait ...
87719835e91bc1a1215c9ebff94d4e98d346a2dc
ofhellsfire/python-notes
/notes/fundamentals/classes/super_in_base_class_tip.py
967
3.8125
4
# Non supered items class Foo: def __init__(self): print('Foo class init') class Bar: def __init__(self): print('Bar class init') class Baz: def __init__(self): print('Baz class init') class Uno(Foo, Bar, Baz): def __init__(self): super().__init__() pri...