blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
37a0f93ac1edcf603418a28c35b5204c20f45409
khoipn1504/Practices
/Data Structures/Sorting and Selection/QuickSort.py
519
4
4
def quickSort(inputList): processList = inputList.copy() # dòng này là để thuật toán không ảnh hưởng List gốc bên ngoài if len(processList) < 2: return processList pivot = processList.pop() lowList = [] highList = [] for i in processList: if i < pivot: lowList.a...
84789747d282e9a72adbf3b7cac8b9659ad46ea2
akshayskumar94/Stock-Details-of-Tesla-and-Gamestop-DV
/Python Project 1- Extracting and Visualizing Stock Data.py
3,600
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # Extracting and Visualising Stock and Revenue Data # ***Using Tesla and Gamestop as example*** # Entering 2021 we have seen a huge surge in the share prices of Tesla and Gamestop, Let us compare this surge with the quarterly revenue data for the respective companies using Data...
beb65d91449d6aa32bce7b1d10d2264e3ab5f5ea
Levintsky/topcoder
/python/leetcode/locked/1102_answer.py
938
3.515625
4
""" Since heappop() only pop the smallest number from the queue, but what I want is the element with the highest score so far, so I change all scores to negative number, so that I can pop the element with highest score. Notice: memo is used to store the cells that have been visited. """ class Solution: def maximu...
66d708b47773445f60ec800651a2b768ba11675c
zhrcosta/string-functions
/reverse_string_method_1.py
250
4.3125
4
def reverseString(string): # Função para inverter os caracteres de uma STRING método 1 reversed = "" for index in range(1, len(string)+1): reversed += string[-index] return reversed print(reverseString("zhrcosta"))
1b7e0ab5398dd3ef24558a6c4804274104beffc5
chullee123/learnPython
/pythonScripts/MIT6.00.1x/unit1/alphabetString.py
643
4.125
4
""" Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. """ s = "abcdefghijklmnopqrstuvwxyz" highest = "" def getIfNext(s, i, c = ""): currentString = s[i] c += currentString if i+1 >= len(s): return...
ccbc930c8468c54eb05c74d8db0d198109de3be9
danyaeche/simple_todo_list-
/todo_list.py
1,284
3.890625
4
class Todo_list(object): def __init__(self): self.items_dict = {} self.counter = 0 def add_item(self, item): if type(item) != str: print("input item has to be a string") elif item in self.items_dict: pass else: self.counter += 1 self.items_dict[item] = self.counter def edit_item(self, i...
cd0505699a00ee2e329797df12349aa658714de3
niyaznigmatullin/nncontests
/utils/IdeaProject/archive/unsorted/2015.05/2015.05.16 - IPSC 2000/e.py
108
3.5625
4
def fact(n): return 1 if n == 0 else n * fact(n - 1) print(fact(300) // fact(50) // fact(250))
287de0f286cc95e46efd818d43cb48f8341e9546
Ylfcynn/Python_Practice
/quantify_words.py
2,777
4.09375
4
""" Write a function that quantifies word occurrences in a given string. >>> quantify_words("Red touching black is a friend of Jack, Red touching yellow can kill a fellow.") Lexis: 'a', occurrences: 2 Lexis: 'black', occurrences: 1 Lexis: 'can', occurrences: 1 Lexis: 'fellow', occurrences: 1 Lexis: 'friend', occurrenc...
6f5d94a4b46cc10c2b0a0603ea517aab6ba58930
vsham20/hackerrank
/second_largest.py
333
3.6875
4
__author__ = 'vaishali' # Enter your code here. Read input from STDIN. Print output to STDOUT N = int(raw_input()) A = map(int,raw_input().split(" ")) first, second = None, None for n in A: if n > first: first, second = n, first elif first > n > second: second = n print second #def second_large...
e8150d2ee944b6795c252b3c281fec7d0708a731
rahil1303/Hackerrank_Python_Solutions_Repository
/String_Validators.py
372
4
4
#### You are given a string . ##Your task is to find out if the string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters. s = str(input()) print(any(a.isalnum()) for a in s) print(any(a.isalpha()) for a in s) print(any(a.isdigit()) for a in s) print(any(a.islowe...
848aa4f4a8da11c94bda810393aead647ef56461
JakobKallestad/Python-Kattis
/src/tester2.py
404
3.640625
4
from collections import deque, defaultdict def bfs(adj, start, goal): visited = set() parentOf = defaultdict(int) queue = deque while queue: current = queue.pop() for nbr in adj[current]: if nbr not in visited: visited.add(nbr) parentOf[nbr] ...
5d93f3b2f75baa24314b65ee08104457628cb928
DenisaGal/Syneto-Lab
/Lab2_HW/HW2_E2.py
283
4.28125
4
capitals = { 'Timis': 'Timisoara', 'Bihor': 'Oradea', 'Arad': 'Arad', 'Hunedoara': 'Deva', 'Caras-Severin': 'Resita', } def judet(capital): for c in capitals: if(capitals[c] == capital): return c return 'Unknown' print(judet('Arad'))
e3b6bcc3d57ca36c85b6116f9beb9e1a74f8ac08
adamandersen/learnpythonthehardway
/ex15.py
557
3.90625
4
from sys import argv # take one argument in. Any text file script, filename = argv; # prompt format prompt = '> ' # open the passed textfile txt = open(filename); # print the textfile name to the console print "Here's your file %r:" % filename; # read the open textfile and print the context in the console print tx...
39853c4e1ef2950b255bf433ef5b3127161aa1d7
mpereza42/toy-robot-task
/test/test_toyrobotinterpreter.py
1,631
3.53125
4
import unittest from unittest.mock import Mock, call from inputparser import InputParser from toyrobotinterpreter import ToyRobotInterpreter from toyrobot import ToyRobot class Test(unittest.TestCase): def testName01(self): """ Testing ToyRobotInterpreter place() handler """ toy = ToyRobot() ...
e549eacb5a552d3124bab1c0a90ec3ee3c1dfbdb
L-Glogov/crypto-python
/freqAnalysis.py
2,483
3.65625
4
# Frequency Finder # # Based on chapter 19 of Cracking Codes with Python by Al Sweigart # https://www.nostarch.com/crackingcodes/ (BSD Licensed) ETAOIN = 'ETAOINSHRDLCUMWFGYPBVKJXQZ' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def getLettersCount(message): # Returns a dictionary with keys of single letters and value...
5e1281580da0e8e37870bfcec89eba9f42f6d292
jernej555/adventofcode
/day4/Day4.py
2,641
3.546875
4
# https://adventofcode.com/2020/day/4#part2 import re with open("input.txt") as f: lines = f.read() passports = lines.split("\n\n") def propertyCheck(passportProperties): isValid = True for property in passportProperties: split = property.split(":") if split[0] == "byr": isVa...
0b70c2280931cf4f88fce27f1a8eb1b119d45928
joelmedeiros/studies.py
/Fase19/Challange91.py
390
3.5625
4
from random import randint from time import sleep from operator import itemgetter dice = {} for i in range(1,5): dice[f'player{i}'] = randint(1, 6) print(f'The player{i} got {dice[f"player{i}"]} in the dice') sleep(0.5) i = 1 ranking = sorted(dice.items(), key=itemgetter(1), reverse=True) for player, value...
43c2063674be6e5452d27797beca0ad19e98f49c
DanielDJAM/imw
/ut2/a3/program2.py
245
3.65625
4
import sys num = int(sys.argv[1]) sequence=0 if num < 0: sys.exit('Error. Solo admite números positivos') else: for loop1 in range(1, num+1): value1 = loop1 ** 2 sequence = sequence + value1 print(sequence)
7dd2d3ce1269075970f34d3f57041b55ed549232
rbracht/Rock_Physics_python
/LogManipulation/PyExamples/TkButtonPythonExample.py
367
3.75
4
import Tkinter import tkMessageBox top = Tkinter.Tk() def helloCallBack(): tkMessageBox.showinfo( "Hello Python", "Hello World you know not what is to be coming next") B = Tkinter.Button(top, width=7, padx=20, pady=20, bg ="black", activebackground="green", activeforeground="yellow", fg="white", text ="Hello", co...
fd89810819b26f68793bc1c895b58360b28a23a5
calmcat/Algorithm
/insertion_sort.py
250
3.796875
4
def insertion_sort(A): for j in xrange(1, len(A)): key = A[j] i = j-1 while i >= 0 and A[i] > key: A[i+1] = A[i] i = i-1 A[i+1] = key A = [31, 41, 59, 26, 41, 58] insertion_sort(A) print A
1b3e5d7a9c71f962d40fdb4c769a9885dc409739
jacob-hudson/ProjectEuler
/python/euler.py
304
3.609375
4
#!/usr/bin/env python def soe(n): is_prime = [True]*n is_prime[0] = False is_prime[1] = False for i in xrange(2,int(n**0.5+1)): index = i*2 while index < n: is_prime[index] = False index = index+i prime = [] for i in xrange(n): if is_prime[i] == True: prime.append(i) return prime
4ee4fa4cd5223a913096f8562e8b3dd495908c34
msaf1980/scan
/fill_borders.py
6,203
3.640625
4
#!/usr/bin/python import sys, os from PIL import Image, ImageDraw # Try to clean black borders of scanned image (usually black & white) # !!!! wery alfa state, not tested on color or grayscale images #xborder1 = 80 #yborder1 = 80 #xborder2 = 80 #yborder2 = 80 #threshold = 30 bw_threshold = 80 ...
e329fd14e69ce7bb5fdc63c235a32bc589f33e85
PemLer/Journey_of_Algorithm
/leetcode/501-600/T572_isSubtree.py
690
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: if not s or not t: return False def is_same(a, b): ...
ac2b0a090d1e08ec129053ee92db8a912c9a35be
dbsgh9932/TIL
/variable/01_variable.py
528
3.609375
4
# 변수의 값을 저장 # 변수=값 result = 10 print(result) # 화면에 변수값을 출력하는 명령어 result = 'a' print(result) # 여러개의 변수에 여러개의 값을 한번에 저장 가능 # 변수1, 변수2, 변수3,...=값1, 값2, 값3 # 파이썬 코드는 맨 앞칸에서 시작 (공백x) a,b,c,d=1,2,3,4 print(a) print(b) print(c) print(d) # 변수이름 = 실제값이나 값이 들어있는 식별자도 가능 e,f,g=a,b,c a,b=10,20 #a,b 값은? 10 20 print(a) a,b=b,a #...
ec505ce2f31ceb36096d4f9aa91a094b26640d9c
rcanepa/cs-fundamentals
/python/interview_questions/odd_man_out.py
1,041
4.1875
4
"""Given an unsorted array of integers where every integer appears exactly twice, except for one integer which appears only once. Implement an algorithm that finds the integer that appears only once.""" def find_odd_integer(integers): """The time complexity of this algorithm is O(N), where N is the number of ...
5e3a18d135dd8c68f2eb310c0a81bfffd2f8ed74
mentecatoDev/python
/UMDC/03/08b.py
703
3.984375
4
""" Ejercicio 08b Potencias de 2 b) Escribir una función que, dados dos números naturales pasados como parámetros, devuelva la suma de todas las potencias de 2 que hay en el rango formado por esos números (0 si no hay ninguna potencia de 2 entre los dos). Utilizar la función es_potencia_de_dos, descrita en el punto an...
fe2f7b6cc0272571d36c2209459aa68de19a6026
dagar/project_euler
/problem_37.py
804
4
4
#! /usr/bin/env python from common import isprime def truncate_left(number): N = str(number) return int(N[1:]) def truncate_right(number): N = str(number) return int(N[:-1]) def truncatable_prime(n, truncate_fn): N = str(n) original_n = N while True: if isprime(int(N)): ...
9ee97d097427800e0fde72a9500793d970b1e67e
Mark-Gustincic/Bioinformatics-in-Python
/Research Programming/Basic DNA-Protein Statistics/Protein Coordinates.py
5,531
3.984375
4
#!/usr/bin/env python3 # Name: Mark Gustincic # Group Members: Thomas Richards (tarichar) import math class ProteinCoordinates : """ Author: David Bernick Date: March 21, 2013 This class calculates angles and distances among a triad of points. Points can be supplied in any dimensi...
51bf182f27477df8771a14d5eb199bfd2392a772
getabear/leetcode
/合并K个排序链表.py
3,037
3.84375
4
from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None class Solution1: def mergeKLists(self, lists: List[ListNode]) -> ListNode: def merge(list1,list2): #功能,和并两个排序链表 ret=ListNode(None) res=ret #返回值 temp=ret ...
84d3cf93690246057b1ed6e70e6a4cbf53d0f184
berkkurt/PythonTryouts
/deneme.py
285
3.640625
4
print("bu bir denemedir") def berk(): pass num1 = 10 def toplama(num1, num2): num1 = 1 return num1 + num2 def çıkarma(num1, num2): pass berk() print(toplama(2, 3)) for x in range(100, -1): if x == 80: continue print(x) def rrr(): pass
fb8502d74927d8fa67cf756cc0f682c5a83fe506
dkippes/Python-Practicas
/Introduccion a Python/condicionales-encadenados.py
342
3.953125
4
x=1 y=2 #Encadenando if x < y: print(x, "es menor que", y) elif x > y: print(x, "es mayor que", y) else: print(x, "es igual a", y) #Anidando -> dificultan la lectura del programa if x == y: print(x, "es igual a", y) else: if x < y: print(x, "es menor que", y) else: print(x, "...
083f063bcb96b2af4e43b4e3c88c3e6abaf355ca
jrbella/python_open_work
/more_functions.py
1,168
3.625
4
#imports #basic function for area def area(a, b): return a * b print(area(4,5)) #explicit function argument def area_2(a,b): try: if(isinstance(a, (int, float)) and isinstance(b, (int, float))): return a * b else: return (float(a) * float(b)) except ValueError: ...
c05ea0a19880e8f0d13529cd0ed08036adbde963
Luke-Kelly/CodeCraft2018Python
/something.py
265
3.796875
4
print("What year were you born?") born = raw_input() born = int(born) print("What year would you like to see your age?") year = raw_input() year = int(year) ageIn2050 = year - born print("In " + str(year) + " you will be " + str(ageIn2050) + " years old!")
87ffa0d2edf57a63d057cda63627ecaff0edcab7
alexcatmu/CFGS_DAM
/PRIMERO/python/ejercicio43 listasF.py
316
3.921875
4
''' hasta que no F seguir con - \ | / ''' #programa F #variables array = ["-","\ ","|","/"] valor = "" cont = 0 #codigo while (valor != "F"): print (array[cont]) #array_final.append(array[cont]) cont = cont + 1 if (cont > 3): cont = 0 valor = input() #print (array_final)
5425c442348c9a7d14f5a6e95ca61f051f6e15dc
victorrenop/algorithm-analysis-final-assignment
/algorithm_analysis_final_assignment/data_structures/tree/tree.py
765
3.59375
4
from abc import ABCMeta, abstractmethod class Tree(metaclass=ABCMeta): @abstractmethod def insert(self, key: object, val: int, current_root: object = None) -> None: pass @abstractmethod def search_key(self, key: object) -> object: pass @abstractmethod def search_...
44ffe20f4909d58a2c218ee53be667e4d723fdbd
iyuandeng/LearningPython
/pycharmprojects/zodiac.py
705
3.578125
4
# # 根据出生日期判断星座 # zodiac_name = (u'摩羯座',u'水瓶座',u'双鱼座',u'白羊座',u'金牛座',u'双子座', # u'巨蟹座',u'狮子座',u'处女座',u'天秤座',u'天蝎座',u'射手座') # zodiac_days = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22), # (7,23),(8,23),(9,23),(10,23),(11,23),(12,23)) # (month,day) = (12,6) # zodiac_day = list(filter(lambda x: x<=(month,day),z...
95b3b3f152090b50133ca63c6e63f6c573357d10
dcandrade/machine-learning-a-z
/1 - Data Preprocessing/data-preprocessing_template.py
567
3.625
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing datasets dataset = pd.read_csv("Data.csv") X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 3].values #Splitting in training and testing sets from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = tra...
e1d41cf9634505b2757fdc26d30923b568b9812e
orazioc17/python-avanzado
/generators.py
602
3.671875
4
from time import sleep def fibonacci_generator(max=None): n1 = 0 n2 = 1 counter = 0 max = max while True: if max: if n1 + n2 > max: break if counter == 0: counter += 1 yield n1 elif counter == 1: counter += ...
135c820971838480e4137c76242f98209c8237c0
vishsanghishetty/LC-Python
/medium/Generate Parentheses/solution.py
715
3.671875
4
# Time complexity: O(2^(2n)) # Approach: Simple recursion solves the problem. We need to make sure that whenever we want to insert closing bracket, then number opening brackets must be less than number of closing brackets. class Solution: def stringGenerator(self, i, j, rem, ans): if i == 0 and j == 0: ...
4484e6c9cdeda15a3d9772b8acbd77444a6d7ed9
esouzasp/1-data_science_foundations_I
/data_science_mod002_class002_lesson041 (using dictionary).py
371
4
4
elements = {'hydrogen': 1, 'helium': 2, 'carbon': 6} print elements print elements['hydrogen'] print elements['carbon'] #print elements['lithium'] #keyError print 'lithium' in elements elements['lithium'] = 3 #add new+value elements['nitrogen'] = 8 #add new+value print elements elements['nitrog...
ca1e87d5dc6740aa5ede54542318f1d20249ff69
antoniojkim/AlgLib
/Algorithms/Greedy/Odd One Out/odd_one_out.py
401
4.03125
4
# -*- coding: utf-8 -*- from typing import List def odd_one_out(A: List[int]) -> int: """ Given a list of integers where every single element repeats an even number of times except for one element who repeats an odd number of times. The following algorithm finds the element that repeats an odd...
32176c8cddaf92810ecf01472065f2dc7528a1c2
tcooi/solutions
/kattis/hissingmicrophone.py
265
3.671875
4
from sys import stdin input = list(stdin.readline().rstrip('\n')) hiss = False for x in range(0, len(input)-1): if input[x] == "s" and input[x+1] == "s": hiss = True break if hiss: print("hiss") else: print("no hiss")
12b49d9d3ce4a8bb9867f9c169ebe7673fee5740
JeffFirmin/Projects
/Théorie des jeux/joueur.py
575
3.734375
4
class Joueur: def yes(self): return False def lancer_pierre(self): # La fonction pour le lancer de pierre print("nombre de pierres restantes", chateau.pierre) chateau.nb_pierre_envoyee = int( input("Nombre de pierre à envoyer ?")) # Si on entre plus de pierres qu'on en ...
ad70e7504cf2b84171c34db5703588844d7032cf
rayankikavitha/InterviewPrep
/leetcode/560_Subarray_Sum_Equals_K.py
1,975
3.8125
4
""" Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 https://leetcode.com/problems/subarray-sum-equals-k/solution/ The idea behind this approach is if you are caluclating the cumulative sum ...
c6161cd5bab4cff004f3bdb9477bfd396a07de06
Springo/AdventOfCode2018
/d13.py
5,703
3.515625
4
def readFile(filename): lines = [] with open(filename, 'r') as f: for line in f: lines.append(line[:-1]) return lines lines = readFile("d13input.txt") #lines = readFile("test.txt") grid = [] c_list = [] locs = dict() for y in range(len(lines)): line = lines[y] g_line = [] fo...
1be0bc2dc5cd95f50e32a632ea5dfdb0b910d665
shinhn/python_web_basic
/python_basic/8_exception_hadling.py
2,168
3.578125
4
# 예외 종류 # linter : 코드 스타일, 문법 체크 # syntaxError : 잘못된 문법 # ZeroDivisionError : 0 나누기 에러 # IndexError : 인덱스 범위 오버 # keyError : 주로 딕셔너리에서 발생 # AttributeError : 모듈, 클래스에 있는 잘못된 속성 사용시에 예외 # ValuError : 참조 값이 없을 때 발생 # FileNotFoundError : 파일이 현재 경로에 없을 때 발생 # TypeError # 예외 처리 # try : 에러가 발생할 가능성이 있는 코드 실행 # except : 에러명1 ...
5d08a71776a0c76be59401da041e5e55111f3cca
huyndo/Learning-python
/Chapter 2/area_rectangle.py
157
4.15625
4
height = int(input("Please input rectangle height ")) width = int(input("Please input rectangle width ")) area = height * width print("The area is: ", area)
cf2422b5dd44196d3ef280cce4967cd8cbd0cc0a
boknowswiki/mytraning
/lintcode/python/0541_zigzag_iterator_II.py
761
3.640625
4
#!/usr/bin/python -t class ZigzagIterator2: """ @param: vecs: a list of 1d vectors """ def __init__(self, vecs): # do intialization if necessary self.q = [v for v in vecs if v] """ @return: An integer """ def next(self): # write your code here v = self.q....
e7ce55fb26707864d310ca2d792e8260ab2d8075
gabrielwai/Exercicios-em-Python
/ex076.py
563
3.546875
4
listagem = ('Pão', 3.50, 'Leite', 4, 'Lápis', 1.75, 'Borraha', 2, 'Caderno', 15.9, 'Estojo', 25, 'Transferidor', 4.2, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.3, 'Livro', 34.9) print('-'*40) print(f'{"LISTAGEM DE PREÇOS":^40}') #print('{:^40}'.format('LISTAGEM DE PREÇ...
34ae2d65c7eb8f1f79156edb4487da0911be7642
cudjoeab/Object-Oriented_Programming-3
/02-Inheritance_Pt1/people.py
678
4.125
4
class Person: def __init__(self, name): self.name = name def __str__(self): return f'Hi, my name is {self.name}!' class Instructor(Person): def teach(self): return f'An object is an instance of a class.' class Student(Person): def learn(self): return f'I get...
92b1bcd1c245d9108ddfd26364888037437bf476
smorenburg/python
/src/old/variations.py
388
3.75
4
#!/usr/bin/env python3 message = input('Enter a message: ') print('Lowercase:', message.lower()) print('Uppercase:', message.upper()) print('Capitalized:', message.capitalize()) print('Title', message.title()) words = message.split() print('Words:', words) sorted_words = sorted(words) print('Alphabetic first word:'...
27a906a0b15d03dc8073017fa5ee3f37442dce54
vidaljose/pruebasPython
/modulos/funciones_matematicas.py
285
3.765625
4
"""Este modulo permite realizar opeaciones matematicas""" def sumar(op1,op2): print("El resultado de la suma es ",op1 + op2) def restar(op1,op2): print("El resultado de la suma es ",op1 - op2) def multiplicar(op1,op2): print("El resultado de la suma es ",op1 * op2)
790d3ad9bf9414a2619558dd78fe7190d507e3bd
NikitaFir/Leetcode
/Contains Duplicate II.py
611
3.5
4
class Solution(object): def containsNearbyDuplicate(self, nums, k): elems = {} for i in range(0, len(nums)): if nums[i] in elems: value = elems[nums[i]] if i - value <= k: return True else: ...
d43e8cc4a9d05faf1cd602688dd109700a72cd46
mashilu/hello-python
/pytest/file_test/file_reader.py
286
3.625
4
# -*- coding: utf-8 -*- if __name__ == '__main__': with open('text_files/pi_digits.txt') as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip().lstrip() print(pi_string) print(len(pi_string))
7d1ea0afc67ddc00ffd27ad923d48677eaf42b00
stevenfisher22/python-exercises
/Homework 16 Nov 2018/16-nov-2018.py
1,401
3.734375
4
#// DICTIONARIES # myContactList = { # 'dog' : 'Savannah', # 'wife' : 'Amanda', # 'me' : 'Steven', # 12 : 'Whatever' ## This segment throws an error: # 'friends' : { # 'first_name' : 'Brent' # 'last_name' : 'Hibbard' # } # } # dog = myContactList['dog'] # print(dog) #// ...
139b588593bfe7f95dbfb91c090cf8f8c3441812
Utukoori/Innomatics_Internship
/Day_5/Regex_substitution.py
190
3.890625
4
import re for line in range(int(input())): string = '' string = re.sub(r'(?<= )&&(?= )','and',input()) string = re.sub(r'(?<= )\|\|(?= )','or',string) print (string)
fcd49db4681f68160c2a7b8380208f62a58c026c
vpunugupati/CodingPuzzles
/LeetCode/LongestSubString.py
376
3.765625
4
def LongestSubString(s): print(s) ar = [] maxlength = 0 for ch in s: if (ch in ar): ar = ar[ar.index(ch)+1:] ar.append(ch) if(len(ar) > maxlength): maxlength = len(ar) return maxlength if maxlength > len(ar) else len(ar) if __name__ == "__main__": ...
19a77b99ee116d2b3d43b754387dbd5dc6a80535
logancyang/lintcode
/biTree/inorder.py
1,548
4.03125
4
# inorder from biTree import * """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: Inorder in list which contains node values. """ ## non-r...
f4b58c3f1e07886f2816efeacf12b31f3e513832
awaz456/Python_aasignment_-nov25-
/Happy Birthday.py
225
3.5
4
def happy(name, style_char='-'): nam = 'Happy Birthday to you\n' last = 'Dear' print(style_char*25) print("{0}{0}{0}{1} {2} {0}".format(nam, last, name)) print(style_char*25) happy("Sagar Dai \n")
fde5ea13e7a7865c3938ac758f9faf1b0430945e
xizhang77/LeetCode
/Previous/31_Next_Permutation.py
1,222
4.3125
4
''' Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are s...
5fcdeec815a95ddce27f76af3a1d0851b845e609
BenDeBrasi/InterviewPrep
/CTCI/Linked Lists/LinkedList.py
1,609
3.828125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self, head = None, tail = None): self.head = head if head == None: self.size = 0 self.next = head else: self.size = 1 se...
6c8d6bc5f55311cdff12f874fd2f5fd618c6669c
mex3/fizmat-v
/3799.py
1,081
4.15625
4
#http://informatics.mccme.ru/mod/statements/view3.php?id=3962&chapterid=3799#1 #РЕКУРСИЯ! #РЕКУРСИЯ! #this code works #and I don't know why we have to use recursion def IsPrime(n): for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True if IsPrime(int(input())): ...
6e3c12ac862240bf41a28c9ceb3577844229c11f
sabrikrdnz/LYK-17-Python-Examples
/38recursivesil.py
237
3.8125
4
import os dizin = input("Dizin?") def listele(path): dosyalar = os.listdir(path) for dosya in dosyalar: print(dosya) if os.path.isdir(os.path.join(path,dosya)): listele(dosya) listele(os.path.join(path,dosya) listele(dizin)
c5af6a6e7549de89672e8aa4e636801fa82f95fc
TheBoys2/MainHub
/Andrew/Biz-Sim/Main.py
7,969
3.640625
4
import pickle, random from replit import clear from time import sleep from product101 import Product import sys, os player = "" password = "" name = "" sales = 0 money = 0 unity = 0 pro101 = "" debt = 0 def bills(): global money spendings = random.randint(400, 800)*random.randint(1,4) clear() print("\n") ...
868e0e55c9f00f0aeb5120739bc1664745045592
Trietptm-on-Coding-Algorithms/leetcode-6
/regular-expression-matching/sol1.py
2,846
3.71875
4
#!/usr/bin/env python3 # https://leetcode.com/problems/container-with-most-water class Foo: @classmethod def compute(self, s, p): # ~~~~~ snip to leetcode # replace a*a*a*...a* -> a* i = 0 p2 = '' lenp = len(p) while i<lenp: if i<lenp-1 and p[i+1]=='...
5c5b4ed03328f2e9b639e731fd50cf456cb3959e
markeganfuller/xkcd936
/xkcd936.py
546
3.5
4
#!/usr/bin/env python3 """Quick implementation of XKCD 936.""" import random import sys def xkcd936(length): """Quick implementation of XKCD 936.""" with open('/usr/share/dict/words') as f: words = [line.strip() for line in f.readlines()] words = [w for w in words if "'" not in w] for _ in r...
12dfbae2a9752164e68019b6f8053b61d7781add
Vi5iON/MiniProjects
/RockPaperScissor/Rock_Paper_Sci.py
2,894
3.765625
4
''' Table for game results. ----------------------- (y)computer | rock(1) paper(2) scissor(3) user(x) | -------------------------------------------------- rock(1) | 1,1 1,2 1,3 | l w -------------------------------------------------- paper(2) | ...
8e51f660d30416889497ffd9b6f09d5cf4b3b069
mchellmer/pythonfun
/lib/helloworld.py
144
3.671875
4
class HelloWorld: def __init__(self): self.name = "Hello Bot" def sayHello(self): return 'hello world my name is'+self.name
36bfa4cd73198831dbaefa722d80ad830da0db63
alindsharmasimply/Python_Practice
/sixtyNinth.py
601
3.5625
4
from collections import OrderedDict import string letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] myList = range(1, 21) print list(myList) # Imp 1 myList2 = range(10, 201, 10) print list(map(str, myList2)) # Imp 2 myList3 = [1, 3, 3, 4, 5, 6, 6] print list(OrderedDict.fromkeys(myList3)) # Imp 3 d = {"...
de50887196ca9c4c84ef8d9469a2da8cd99053e6
Grumblesaur/euler
/helper.py
706
4
4
from math import sqrt wheel = [2,4,2,4,6,2,6,4,2,4,6,6, 2,6,4,2,6,4,6,8,4,2,4,2, 4,8,6,4,6,2,4,6,2,6,6,4, 2,4,6,2,6,4,2,4,2,10,2,10] prime_list = [2, 3, 5, 7] def fibonacci(n): if (n <= 1): return n curr = 2 prev = 1 for i in range (2, n - 1): temp = curr curr += prev prev = temp return curr def is_p...
165ff407d0d5f1288cdc6385bf8bd4d751aed2e0
dmitrijbozhkov/ProbabilisticInformationRetrievalAssignments
/homework_1/cosine_sim_template.py
3,838
3.625
4
#! /usr/bin/python # -*- coding: utf-8 -*- """Rank sentences based on cosine similarity and a query.""" from argparse import ArgumentParser import numpy as np def get_sentences(file_path): """Return a list of sentences from a file.""" with open(file_path, encoding='utf-8') as hfile: return hfile.r...
d194a2f9fb9e435bd4c58610ffdfb8fad195fb52
jityong/AdventOfCode2020
/solutions/day5.py
1,302
3.84375
4
class Day5: # O(n) time solution, where n is the number of seats. O(1) space # https://adventofcode.com/2020/day/5#part2 def binary_search(self, l, r, directions, idx): if idx >= len(directions): return l mid = int((l+r)/2) if directions[idx] == 'F' or directions[idx] == ...
8ff8f262eb1581bcf0a396d94d16d458cf1e57af
adam2392/eegdatastorage
/alchemy/dataparse/reader.py
906
3.53125
4
import os import numpy as np import pandas as pd class CSVReader(object): def __init__(self, datafile): self.datafile = datafile # strcols = ['gender', 'hand dominant', 'center'] def loadcsv(self): data = pd.read_csv(self.datafile) # first off convert all columns to lower case data.columns = map(str.l...
a07d2aca57a1e6d2cc719a125da5d222d71681de
baybird/DSA
/divisible.py
1,092
4.09375
4
# Problem : Divisibility test # Description : Determining whether one whole number is divisible by another or not. # For example : 11 is not divisible by [2,5,7] # 9 is divisible by [2,5,7] # Author : Robert Tang # Email : bayareabird@gmail.com # Created : 6/16/2017 # Pyt...
31706f1e6823cc2d9b0a549b5699e7bb6239c0f1
luisferlc/prework-datamex-2019
/solution prework scripts/04 bus.py
874
4.0625
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 23 15:41:31 2019 @author: luisf """ """ 04 bus """ stops = [(10, 0), (4, 1), (3, 5), (3, 4), (5, 1), (1, 5), (5, 8), (4, 6), (2, 3)] # 1. Calculate the number of stops. print(len(stops)) # 2. Assign a variable a list whose elements are the number of passengers in each...
05c12a07d42fa45436c18f177ac2e2cc72a12539
iswanulumam/cp-alta
/python/2-live-code/13-string-acak.py
578
3.578125
4
def remove_string(str, ch): newstring = '' for j in range(len(str)): if str[j] == ch: newstring += str[j+1:] break newstring += str[j] return newstring def string_acak(stringSatu, stringDua): for i in stringSatu: stringDua = remove_string(stringDua, i) if len(stringDua) > 0: retur...
c87f7b8901967bfc38ba60fbba37270730a9073f
ceorourke/HB-CodingChallenges
/hackbright_challenges/medium/zeromatrix.py
1,436
4.34375
4
"""Given an NxM matrix, if a cell is zero, set entire row and column to zeroes. A matrix without zeroes doesn't change: >>> zero_matrix([[1, 2 ,3], [4, 5, 6], [7, 8, 9]]) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] But if there's a zero, zero both that row and column: >>> zero_matrix([[1, 0, 3], [4, 5, 6], [7, 8,...
2b3242df55aab1f96d08033cf9e52d5ca4162241
xushubo/fluent_python
/5_21_functool_operator.py
202
3.578125
4
from functools import reduce from operator import mul def fact(n): return reduce(lambda a, b: a*b, range(1, n+1)) def fact1(n): return reduce(mul, range(1, n+1)) print(fact(5)) print(fact1(5))
54901c5f3d79e604de9a859eab761093cc0f7dd9
yearing1017/Algorithm_Note
/leetcode/Hot-100/python/dcecs.py
526
4.15625
4
""" 给定一个二叉树,检查它是否是镜像对称的。 例如: 1 / \ 2 2 / \ / \ 3 4 4 3 """ class Solution: def isSymmetric(self, root): if not root: return True return self.dfs(root.left, root.right) def dfs(self, left, right): if not left and not right: return True if ...
84e62582b4305e519cf259b8cf96c673a1798208
CianLR/hashcode-2018
/ciara_no_hurry_reverse.py
1,230
3.578125
4
from get_input import * import random class Car: def __init__(self): self.available_time = 0 self.pos = (0, 0) self.queue = [] def dist(p1, p2): x1, y1 = p1 x2, y2 = p2 return abs(y2 - y1) + abs(x2 - x1) def calculate_finish(car, ride): start = car.available_time + dist(car.pos, ride.start) if ride.star...
793bfd81ec00681b0f3abd5da99e98e0dc5c449e
ajimonsiji/DataStructureandAlgorithm
/QueueLinkedList.py
1,283
3.640625
4
from ExceptionClass import * class LinkedQueue: class _Node: __slot__ = '_element','_next' def __init__(self, element, next): self._element = element self._next = next def __init__(self): self._head = None self._size = 0 def is_empty(self): return self._size == 0 def __len__(self): return se...
9d9f22f1c2c14b8ce87de41f901a3489383fb4cf
BlogCreator/miniblog
/database/query.py
2,367
4.25
4
import sqlite3 import os class DB: insert_disc = { "blog":"insert into blog (title,file,pic,desc,date,cls) values(?,?,?,?,?,?)", "click":"insert into click (blog_title,number) values(?,?)", "cls":"insert into cls (name) values(?)", "comment":"insert into comment (article_title,name,...
7267b3ab7da72b8c1631ead6bd6a05d261f07bb4
Iftakharpy/Colt-Steele-Datastructures-and-Algorithms
/Section-11 Bubble Sort/bubble_sort.py
944
4.1875
4
#inplace sort #O(n^2) def bubble_sort(array): #Unoptimized for i in range(len(array)): for j in range(len(array)-1): if array[j]>array[j+1]: #swap array[j],array[j+1] = array[j+1],array[j] return array #inplace sort #optimized but still O(n^2) def optimized_...
f0cb484085f1aa6365e65c7b7bf8d1c4e4b5702d
ethan2000hao/ethan
/inputAndTry/inputAndTry.py
538
3.640625
4
import types list = [1,2,3,45,64,45] def so(): while True: try: str_num = input('input a number:') num=float(str_num) print(num) break #若输入的正确,则退出,错误执行except下面代码 except: print('您输入的内容不规范,请重新输入:') a = num if a >8: del list[...
9f21ab858ec0a500157092c75cd54be1a96ead72
ompraka158/pythonData
/classConcept4.py
443
3.828125
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 2 10:30:05 2018 @author: ompra """ class B: def show(self): super().show() print("Second Class") class A: _a=0 # can be private to this class using double underscore else it is protected def show(self): print("First Class"...
116e4173904aff66aee88a5377f60fed007613cc
ahmed100553/Problem-List
/maxMultiple.py
499
4.40625
4
''' Given a divisor and a bound, find the largest integer N such that: N is divisible by divisor. N is less than or equal to bound. N is greater than 0. It is guaranteed that such a number exists. ''' def maxMultiple(divisor, bound): return bound-(bound%divisor) ''' Example For ...
b54036003e5e1313d6863aafc4438fcc6e9b4df4
soarhigh03/baekjoon-solutions
/solutions/prob10430/solution_python.py
541
3.828125
4
""" Problem 10430 https://www.acmicpc.net/problem/10430 """ def solve(input_1, input_2, input_3): """solves problem""" return ((input_1 + input_2) % input_3, (input_1 % input_3 + input_2 % input_3) % input_3, (input_1 * input_2) % input_3, (input_1 % input_3 * input_2 % inp...
efc269fac8fce68389cfd01979cf8e1a8ca308b1
luca-tansini/advanced_programming
/Lab7/goldbach.py
523
3.78125
4
def isprime(n): i = 2 while(i**2 <= n): if(n%i==0): return False i+=1 return True def primegenerator(n,m): for x in range(n,m): if(isprime(x)): yield x def goldbach(n): if(n <= 2 or n%2): raise ValueError("Arguments must be even!") c = n//2 for i in primegenerator(c...
ec0f3bed5d96dee3b1adc8a5f8d77049468c866b
DamianLC/210CT
/210CT Week 1.py
1,631
4.15625
4
import random ##function to randomly shuffle a list of numbers def randShuffle(n): shuffledLst = [] #empty list while len(n) > 0: randNum = random.choice(n) #picks a random number shuffledLst.append(randNum) #adds the number to the list ...
67ca5ce884f379ed86f0566c4f8a89ab024231f8
MphoGololo/TechnicalAssesment
/tests/core.py
1,098
3.96875
4
''' Python 3 program to find sum of digits in factorial of a number Two functions are used for this functionality. 1. Function to multiply x with large number stored in vector. Result is stored in vector. 2. findSumOfDigits takes the input and returns sum of digits in n! ''' import numpy as np def multiply(vector...
899b429a6149e7566c7cc2d88cb70b97827b61c0
KnightChan/LeetCode-Python
/Permutations II.py
963
3.828125
4
class Solution: # @param num, a list of integer # @return a list of lists of integers def permuteUnique(self, num): ''' Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2]...
aba10085832e51c6e136a42c7fe513f90a7732ea
petrkropotkin/python_lessons
/snakify/6_while loop/the length of the sequence.py
582
4.09375
4
# Given a sequence of non-negative integers, where each number is written in a separate # line. Determine the length of the sequence, where the sequence ends when the integer is equal # to 0. Print the length of the sequence # (not counting the integer 0). The numbers following the number 0 should be omitted. # -...
da6ac8d9b6daec90e53606f5532693412ca82333
Amit-S-Jain/Python_Programming
/Python_Data_Structures/filehandle6.py
380
3.921875
4
#Count the Nmuber of lines in any file with try Catch Block filename = input("Enter the File Name: ") try: fileopen = open(filename) except : print("Sorry, File Not Available!!!") quit() countl = 0 countc = 0 for x in fileopen: countl = countl + 1 for y in x: countc = countc + 1; print("Nmuber o...
a9c65846719d27d3762c37e7c3877bc863a37e8b
joao-lucas-dev/atv-python
/04.py
1,140
4.21875
4
class Funcionario: #construtor def __init__(self, nome, salarioBruto, imposto): self.nome = nome self.salarioBruto = salarioBruto self.imposto = imposto #método para calcular o salário líquido def SalarioLiquido(self): return float(self.salarioBruto - self.imp...
b99cda322a33538518a20f96212c8acf919d51e4
michalstypa/cowait
/cowait/tasks/schedule/schedule_definition.py
2,360
3.640625
4
from datetime import datetime class ScheduleDefinition(object): def __init__(self, schedule): parts = schedule.split(' ') if len(parts) != 5: raise ValueError('Invalid schedule syntax') self.minute, self.hour, self.date, self.month, self.dow = parts # run a check to v...
e25de8b07e2449f5be7cc2df8284cf8815bbd99a
TheFutureJholler/TheFutureJholler.github.io
/module 6-Tuples/tuple_delete.py
321
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 31 20:38:37 2017 @author: zeba """ tup = ('physics', 'chemistry', 1997, 2000); print(tup) del tup print ("After deleting tup : ") print(tup) '''This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more '''...
ddb5580ae01c0e275c70e7433bf29db20ad000ed
cecadud/python-workshop
/AlquilerAutos/model/Carro.py
5,690
3.9375
4
class Carro: """ Clase que representa un carro de alquiler """ KILOMETRAJE_REPARACION = 100000 # Constante que representa el kilometraje minimo para reparación MAXIMO_KILOMETRAJE = 500000 # Kilometraje máximo del carro para poder ser alquilado MINIMO_NUM_ALQUILER = 20 # Mínimo número de veces...
91034674d978bf5525e64678ca56d57c66397a2a
Ananthu/think-python-solutions
/9.03.py
192
3.9375
4
word = str("steven") string = str("qx") def avoids(word, string): for letter in string: if letter in word: return False return True print avoids(word, string)
e9929a8a5af50bba2e1a55e1b3af275a95525896
GINK03/atcoder-solvers
/arc002_a.py
147
3.53125
4
Y = int(input()) if Y%400 == 0: print('YES') exit() if Y%100 == 0: print('NO') exit() if Y%4 == 0: print('YES') exit() print('NO')
ca0285ab474a9b123b20f7aba5394cb65c085866
charlesluch/Code
/Scripting_tutes_labs/Lab_9 (named 8)/q1.py
442
4.1875
4
# 1. Modify the stack class in the lecture notes to make a queue class. Name it “queue”. #! /usr/bin/env python3 class Queue(object): # "A class implementing a queue data structure." def __init__(self): self.thequeue = [] def queue(self, a): # "Make a value enter the back of the queue thequeue[0]." self....