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
d42ce491f5064e1bb2fb11445cfc45f3ea123519
zasiddiq/leetcode
/shuffle_array.py
376
3.71875
4
# https://leetcode.com/problems/shuffle-the-array/submissions/ def shuffle(nums, n): if len(nums) == 0: return list() s_list = [] p1 = 0 p2 = n while p2 < len(nums): s_list.append(nums[p1]) s_list.append(nums[p2]) p1 += 1 p2 += 1 return s_list if __name...
e0c20509e2b93426004aa65474d04b0809704eea
zasiddiq/leetcode
/k_removals_least_num.py
938
3.640625
4
# https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/ import heapq def findLeastNumOfUniqueInts(arr, k: int) -> int: hashmap = {} for i in range(len(arr)): if arr[i] in hashmap: hashmap[arr[i]]+=1 else: hashmap[arr[i]]=1 count_arr = [] ...
52c5d51c82defbac589198dfa3f23ba385eb5bb0
zasiddiq/leetcode
/two_sum.py
529
3.90625
4
def two_sum(nums: list, target: int) -> list: lookup = {} for index, item in enumerate(nums): if(target - item) in lookup: return [lookup[target-item],index] else: lookup[item] = index if __name__ == '__main__': print ( two_sum([11,15,2,7],9) ) # should be [2,3] ...
2f34175f35e847f0b976b00a0250ae638bdfc63c
zasiddiq/leetcode
/best_time_stock.py
557
3.578125
4
def max_profit(prices): if len(prices) == 0: return 0 smallest = prices[0] for p in prices: if p < smallest: smallest = p try: possible_buys = prices[prices.index(smallest)+1:] biggest = possible_buys[0] for i in possible_buys: if i > bigge...
106ea331ff3457dddf335b57fd33973807a48f0a
cheoljoo/problemSolving
/leetcode/minDistance_LCS.py
1,361
3.703125
4
class Solution: def minDistance(self, word1: str, word2: str) -> int: # find the longest matched substring between word1 and word2 # l1,l2 = 0 ,0 # table = [[0 for _ in range(len(word1)+1)] for _ in range(len(word2)+1)] # col : word1 , row : word2 # mx = 0 # for i in range(1...
8c8a26f48e339b6d2eab801c775ba4a38d21b8e8
cheoljoo/problemSolving
/leetcode/sortedArrayToBST.py
2,669
3.71875
4
from collections import defaultdict from re import A #import numpy as np import sys import argparse import math import random # https://www.daleseo.com/python-typing/ from typing import Optional from typing import Union from typing import List from typing import Final from typing import Dict from typing import Tuple f...
c30322db50e6886a5423bc47a9266a5094daa3c9
cheoljoo/problemSolving
/leetcode/removeDuplicates.py
1,482
3.59375
4
from collections import defaultdict #import numpy as np import sys import argparse import math import random # Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. class S...
14aba010052de3f558e3cd404e416819a082116d
cheoljoo/problemSolving
/leetcode/sortList2.py
3,575
3.515625
4
from collections import defaultdict import enum from re import A #import numpy as np import sys import argparse import math import random from tkinter import N # https://www.daleseo.com/python-typing/ from typing import Optional from typing import Union from typing import List from typing import Final from typing impo...
c74716e81f61f0d892a75e9936d765bbcf4b7fdb
cheoljoo/problemSolving
/leetcode/minimumDeleteSum.py
4,337
3.5625
4
from collections import defaultdict from collections import Counter import collections import enum from re import A #import numpy as np import sys import argparse import math import random from tkinter import N # https://www.daleseo.com/python-typing/ from typing import Optional from typing import Union from typing im...
cf062e92d05d4388805e90ac309a2614ac6b4137
cheoljoo/problemSolving
/leetcode/pseudoPalindromicPaths.py
1,165
3.96875
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 __init__(self): self.odd = {} self.oddCount = 0 self.ans = 0 def ps...
68e8d42f3308452e709a80a0fc61b08f9e9d01e5
connor4312/CSC148-assignment-2
/course_parser.py
1,901
3.90625
4
# Assignment 2 - Course Planning! # # CSC148 Fall 2014, University of Toronto # Instructor: David Liu # --------------------------------------------- # STUDENT INFORMATION # # List your group members below, one per line, in format # Connor Peet, 100108820 # # # # --------------------------------------------- from cour...
0706dc4d4fc86c5b8e21f73a842740eb5a39aed2
Desae/MontyHallGame
/MontyOOP.py
3,322
3.84375
4
from random import shuffle, randint class MontyHallGame: ''' Game that simulates the Monty Hall Problem Author: Aseda Addai-Deseh ''' def __init__(self): self.gifts = ["car", "goat", "goat"] # creating gifts list self.giftsCopy = [] # initializing game def initial...
ecd622acc7707aefa9444eeccb02fd8fe5cb0ea4
as-akshaya/100days-of-code
/string-swapcase.py
142
4.15625
4
sentence = input("enter the string:") #''.join(c.lower() if c.isupper() else c.upper() for c in sentence) new =sentence.swapcase() print(new)
2e141f89b2a6cefa0f1a247fd91f9d4f30fd7c4b
Messhias/python-codes
/7.4.py
382
4
4
pizza = '' ingriedients = [] pizza = input("Digite o nome da pizza: \n") print("Digite 'quit' para sair") while True: ingriedients.append(input("Digite os ingrientes: \n")) if input("Digite os ingrientes: \n") == 'quit' : break print("Você escolheu uma pizza de " + pizza.title() + " com os seguintes ingre...
99805dc0664c8c9edb7fe143e0cc17b4454fe95b
Messhias/python-codes
/9.1.py
407
3.84375
4
class Restaurant(): """ MODEL A DOG CLASS """ def __init__(self, name,cuisine): self.name = name; self.cuisine = cuisine; def open(self): """ MAKING DOG SIT """ print(self.name.title() + " is now open") def information(self): """ MAKING DOG ROLL OVER """ print(self.name.title() + " we cook " + sel...
a6236b7ffcc07e3ee6c5c4fd8f75ede61ffde8c8
Messhias/python-codes
/7.1.py
109
3.5625
4
car = input("What kind of car you want rent?\n") print("\nLet me see if I can find a " + car + " for you.")
441c0fd404dc784a53170d2ed72e2aea73c981e6
Messhias/python-codes
/name_cases.py
527
4
4
jon = 'Hello jon, did you like a litle python today?' print(jon) full_name = 'William Wallace' print(full_name.lower()) print(full_name.upper()) einstein_citacion = 'Albert Einstein say: "A person has never made a mistake him never tried make something new."' print(einstein_citacion) famous_person = 'Albert Eins...
240b015e9e20be1a87f05e4d4fa65236210ed5c4
Messhias/python-codes
/test_name_function.py
511
3.546875
4
import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): """ UNIT TESTS CASE CLASS """ def test_first_last_name(self): """ TEST FUNCTION GET_FORMATTED_NAME """ formatted_name = get_formatted_name('Janis','Joplin') self.assertEqual(formatted_name,'Janis Joplin') d...
164edac74acc97822dc77cf4f9ca97eef2e59a2d
Messhias/python-codes
/alines.py
791
3.828125
4
alien_0 = {'color':'green','points':5} print(alien_0['color']) print(alien_0['points']) print("The alien color is " + alien_0['color'] + ".") alien_0['color'] = "yellow" print("the alien is now " + alien_0['color'] + ".") alien_0 = {'x_position':0, 'y_position': 25, 'speed':"medium"} print("Original x position: "...
79b16682b720359c243690c50045c2aa03dcc536
Messhias/python-codes
/favorite_languages.py
394
3.78125
4
from collections import OrderedDict favorite_languages = OrderedDict() favorite_languages['jim'] = 'python' favorite_languages['sarah'] = 'c' favorite_languages['edward'] = 'ruby' favorite_languages['phil'] = 'python' for name, languages in favorite_languages.items(): print("\n" + name.title() +"'s favorite languag...
d533004105c85497617d59611b2f23b37ad94381
liff-123/testgit
/fff/烤地瓜.py
1,389
3.765625
4
#!/usr/bin/python #-*-conding:utf8-*- #烤地瓜 class Sweetpotato: #定义属性,一般用来完成一些初始化的工作 def __init__(self): self.cookedLevel=0 #0-3生的,3-5半生不熟,5-8已经考好了,>8烤成木炭了 self.cookedString='生的' #生熟的程度 self.condiments=[] ...
055cdeca346683b047bcf81539319b9f64a3ef01
liff-123/testgit
/fff/判断是否是回文.py
269
3.828125
4
#!/usr/bin/python #-*-conding:utf8-*- #判断是否是回文 12321是回文或者123321 123412不是 while True: a = input('>>>') b = list(a) c = list(reversed(b)) if b==c: print('回文') else: print('不是回文')
e843ef446bed3047fb8b88b6227eaeebbc3d956b
mniesiolowski/WSB_LAB3
/Zad5.py
822
3.5
4
import matplotlib.pyplot as plot import numpy as np import random n = int(input("Podaj n: ")) x = [round(random.uniform(0, 1), 2) for _ in range(n)] y = [round(random.uniform(0, -1), 2) for _ in range(n)] index = np.arange(n) fig, ax = plot.subplots() barX = ax.bar(index, x, 0.3, color="blue") barY = ax....
bf858501ca46d4396dca7dd639f6b8e8f0f2664a
mhoover/family_fun
/main.py
3,008
3.671875
4
#!/usr/bin/python ''' Main module to load interaction and game menu for play. ''' import random import time from family_fun import * from tic_tac_toe import print_ttt_board, get_new_ttt_value from connect_four import print_cf_board, get_new_cf_value decision_flag = False while not decision_flag: print('Would you...
be8561458e17cf7e4823baab271846905caf70f9
novalwardhana/digitalent-scholarship-data-engineer
/part-2-python/e-mini-project/a-mini-project.py
3,202
3.640625
4
# Step 1: Decrypt data ke dalam list dictionary fileHargaRumah = open("sample.txt", "r") dataHargaRumah = fileHargaRumah.readlines() fileHargaRumah.close() keyHargaRumah = dataHargaRumah[0].replace("\n","").split(",") hargaRumah = [] for baris in dataHargaRumah[1:]: barisHargaRumah = baris.replace("\n","").split(...
0ee0ca3054cc294f68a5079ba0e4b7937fb9624c
novalwardhana/digitalent-scholarship-data-engineer
/part-3-python/c-encapsulation/c-quiz.py
1,089
3.53125
4
class Karyawan: namaPerusahaan = "ABC" insentifLembur = 125000 def __init__(self, nama, usia, pendapatan): self.__nama = nama self.__usia = usia self.__pendapatan = pendapatan self.__pendapatanTambahan = 0 def getNama(self): return self.__nama def lembur(self)...
248f839f696a8212a5a58c25c1e3bc729bede3f3
Anandtripathy/Projects
/Personal_Projects/Dice_roll_simulator/dice_Roll_simulator.py
382
3.96875
4
import random #min_value=int(input("Enter the minimun value:")) #max_value=int(input("Enter the maximum value:")) min_value=1 max_value=6 again=True while again: (print(random.randint(min_value,max_value))) another_role=("want to role again") if another_role.lower()=="yes" or another_ro...
77709790b8794746bd1aba7f715ac35c8a4dc93b
cfaerie/ITSC-1950-Intro-Python
/AveGameScore.py
427
3.984375
4
#Program Name: Game Score Average #Date: 1/18/2013 #Developer: Rachel Sanford #Program will take input of 2 game scores from user #and give the user the average score1 = raw_input("What's your score in round one?") score2 = raw_input("What's your score in round two?") score1 = float(score1) score2 = float(score2) sum...
5a7e2e42c668c00f9b1d5e86c72ce4cc3c719dd9
Celedence/class
/properties.py
573
3.90625
4
class Human: def __init__(self, first, last, age): self.first = first self.last = last if age >= 0: self.age = age else: self.age = 0 def full_name(self): return f"{self.first} {self.last}" # @property # def age(self): # return ...
201a2cbfa51168e159fae14bf438adb71c2b129e
cmdellinger/Code-Fights
/Interview Practice/01 Arrays/isCryptSolution.py
1,213
4.1875
4
""" Codefights: Interview Prep - isCryptSolution.py Written by cmdellinger This function checks a possible solution to a cryptarithm. Given a solution as a list of character pairs (ex. ['A', '1']), the solution is valid of word_1 + word_2 == word_3 once decoded. See .md file for more information about cryptarithm...
b3ea4b626b6afb470c37d082edd5a451c4601ae3
LilCharles/ExamenLP
/EAEXAMEN.py
254
4.15625
4
lista = [] n = int(input(print("ingrese el largo de la lista: "))) while n < 1: n = input(print("ingrese el largo de la lista: ")) for i in range(2, n*2, 2): numero = i**3 lista.append(int(numero)) print(lista[0]) print(lista[1:-1]) print(lista[-1])
0bdfdddcdfb16e5e93d7a7450656b342803080d1
ntuecon/2018groupCE
/Old/Consumer Utility Optimization.py
2,184
4.0625
4
import numpy as np from scipy.optimize import minimize """Input goods and prices""" goods=np.array(["X1","X2"]) prices=np.array([3,4]) """Build and print a GoodsPrices dictionnary to make it clear""" GoodsPrices_dict={} for i in range(len(goods)): GoodsPrices_dict[goods[i]]=prices[i] print "Good prices: \n",Goods...
2401a3e39b4b03442129a3e0229641f2dd2a973b
ntuecon/2018groupCE
/economy/objects.py
1,560
4.03125
4
''' This file containns the classes for the objects of our economy - mainly goods and factors, bundels and allocations are This file is directly taken from Prof. Hendrik Rommeswinkel. ''' class Factor: ''' This is the factor class. Factors are defined by their parameter theta. ''' def __init__(self,th...
edcd28b4306e91b386cc564a9fb8dbe8fffe06e1
ntuecon/2018groupCE
/economy/economy.py
4,463
4.0625
4
''' This file contains the economy class of our model. Purpose of this class is to create an object that containes all information needed to define our economic model. ''' import numpy as np from scipy.optimize import minimize import economy from utility import CESUtility, ExpectedUtility, Social_Welfare from obje...
ad12588be2cb7c572a4b3a41999cf7dbf95ef57c
ntuecon/2018groupCE
/SocialPlanner/main.py
4,674
3.9375
4
#This is main file import ConsumerCES_class as Cons import ProducerCES as Pros import WelfareCES as Soc import numpy as np '''The part is just for the introduction.''' print "Welcome to the ECON world of CE group!" raw_input() print "Please follow us to set up all the details." raw_input() '''I'm asking the user to d...
f278ee826346b361b64a1c8a65d305f4dcb8b6ca
ntuecon/2018groupCE
/Old/Consumer_class.py
2,202
3.828125
4
class Consumer: """This class is the optimization of individual choice of consumer""" def __init__(self,GoodPrices,GoodPar,income): self.GoodPrices=GoodPrices #self.FacPrices=FacPrices self.GoodPar=GoodPar #self.FacPar=FacPar self.income=income """goods=np.array([...
94e79922480f9192037c6a92951a7c0f0acf4728
clunyes/androider
/src/language/python/oop/classdemo.py
910
3.875
4
class Student(object): def __init__(self,name,score): self.__name = name self.score = score def print_score(self): print('%s,%s' % (self.__name,self.score)) zhenghe = Student('张正鹤',50) zhenghe.print_score() zhenghe.age = 20 print('zhenghe age =',zhenghe.age) print(zhenghe) # zhenghe.__name 报错 # 需要注意的是,在Pyth...
dc704fbd6ae09499280a094d4777b67ff145744b
LouisLinY/study_blog
/python_blog/learn_code/PythonFullStack-master/Chapter03/threadDemo04.py
760
3.65625
4
# -*- coding: utf-8 -*- import threading balance = 100 lock = threading.Lock() def change(num, counter): global balance for i in range(counter): # 先要获取锁 lock.acquire() balance += num balance -= num # 释放锁 lock.release() if balance != 100: ...
4eadb8f8a12c98016b39a8def3f6f6260bf004ab
LouisLinY/study_blog
/python_blog/learn_code/PythonFullStack-master/Chapter03/gen01.py
434
3.921875
4
# -*- coding: utf-8 -*- def mygen(): print('gen() 1') yield 1 # 返回第一个值 print('gen() 2') yield 2 # 返回第二个值 print('gen() 3') yield 3 # 返回第三个值 gen = mygen() # 拿到一个生成器 print(next(gen)) # 取第一个值 print(next(gen)) # 取第二个值 print(next(gen)) # 取第三个值 print(next(gen)) #取不存在的第四个值,会抛出StopIteratio...
b010dee52813f23daf0f9bab41d217750674a453
RarefactionQ/Genesis
/Quest.py
2,194
3.609375
4
import Crewmate import Ship import random class Quest(object): id_counter = 0 def __init__(self): Quest.id_counter += 1 self.quest_id = Quest.id_counter self.intro = "" self.description = "" self.v_type = "" self.v_int = 0 self.f_type = "" self.f_...
e326b22e53c27a61e63d40c39c5ac00956ff861a
tlestang/PyBaMM
/pybamm/plotting/plot2D.py
1,905
3.75
4
# # Method for creating a filled contour plot of pybamm arrays # import pybamm from .quick_plot import ax_min, ax_max def plot2D(x, y, z, xlabel=None, ylabel=None, title=None, testing=False, **kwargs): """ Generate a simple 2D plot. Calls `matplotlib.pyplot.contourf` with keyword arguments 'kwargs'. For ...
62e3d1b1f2c4fac8a53d50b2ac9a97a787441536
johnhill1202/Python-Codes
/exercise-three.py
285
3.921875
4
names=[] notok=True while (notok): x=input("Enter a name: ") if(x == ""): notok=False else: names.append(x) print(names) for name in names: for letter in name: if(letter == "b"): print(name, " contains letter 'b'") break
bbf8affa2cd9efa2d79710e10c38afbe01e6e4ce
johnhill1202/Python-Codes
/exercise-nine.py
135
3.796875
4
name_1=input("Enter a string: ") name="" x=0 for letters in name_1: x+=1 for y in range(x-1,-1,-1): name+=name_1[y] print(name)
b7fd5bf1ef532bdb8e0b0eae5a69a19c54c9de82
davidissimo/pythonProject1
/Mood_checker.py
207
3.84375
4
mood = "uau" #Nervous if mood == "happy": print("It is great to see you happy!") elif mood == "Nervous": print("Take a deep breath 3 times.") else: print("I don't recognize this mood")
d3d896ab7792e435e156b9b2e9630b243af48da0
naguiluz/minigames-projects
/connect4-3.py
4,929
3.734375
4
import numpy as np import pygame #provides objects and functions for creating visuals and inputs import sys #general system functions ROW_COUNT = 6 COLUMN_COUNT = 7 BLUE = (0, 0, 255) #setting an RGB value for a bright blue BLACK = (0, 0, 0) #FUNCTIONS def create_board(): board = np.zeros((ROW_COUNT,...
f0d9d402eeda7162c1b35cef9d0da1090e3fc246
sunny4674156/python
/Q3.py
413
3.578125
4
# -*- coding: utf-8 -*- """ 題目: 請輸入迴圈敘述寫一程式,讓使用者輸入一個正整數a, 利用迴圈計算從1到a之間,所有5之倍數數字之總和 """ s = 0 A = int(input("請輸入正整數:")) print("所輸入的正整數為:",A) for i in range(1,A+1): if i % 5 == 0: s=s+i print("5的倍數總和:",s)
b7eb9bf3bf6dcf621a1e6591c2e86be792994895
jingl12/chengfab.py
/fib.py
361
3.875
4
# -*- coding: utf-8 -*- # @Author: 境 # @Date: 2018-11-17 16:56:26 ''' Python实现斐波那契数列 Python implements the Fibonacci sequence ''' #100内的斐波那契数列(Fibonacci Numbers in 100) lst = [0,1] for i in range(2,20): lst.append(lst[i-1] + lst[i-2]) if lst[i]>100: lst.pop(i) break print(lst) print('-'*20)...
5afa6339c2de753d89a665aa96ef55b22f98dea8
mayakota/KOTA_MAYA
/Semester_1/Lesson_09/Lab_09/FirstLetter.py
120
3.609375
4
words = ["fire", "earth", "water", "air", "wind"] def first (lst): for i in lst: print(i[0]) first(words)
53bc1949d4d989f076e481341e6c52fffb549da4
mayakota/KOTA_MAYA
/Semester_1/Lesson_05/5.01_ex_02.py
655
4.15625
4
height = float(input("What is your height?")) weight = float(input("What is your weight?")) BMI = 0 condition = "undetermined" def calcBMI(height,weight): global BMI,condition BMI = (weight/height) * 703 if BMI < 18.5 : condition = "condition is Underweight" elif BMI < 24.9 : condition...
4afe21977fa948c80e94cff25cfbe3717fdef776
mayakota/KOTA_MAYA
/Semester_1/Lesson_09/Lab_09/AverageNumber.py
365
3.875
4
numbers = [] import random for i in range (0, 10): numbers.append(random.randint(1, 100)) print("Numbers...") output = "" for i in numbers: output += str(i) + " " print(output) print(" ") def average(nums): sum = 0 for i in nums: sum += i return sum/len(nums) print("The average of the ...
9bfca2db61d14c15064ed7c42e3bdeb6714de64c
mayakota/KOTA_MAYA
/Semester_1/Lesson_05/5.02_ex06.py
559
4.25
4
def recursion(): username = input("Please enter your username: ") password = input("Please enter your password: ") if username == "username" and password == "password": print("correct.") else: if password == "password": print("Username is incorrect.") recursio...
27039c7ebebed5d87cc5b5258eabf85802fe7bb1
eroiyo/Practices
/Python/statistics/binomial.py
1,041
4.09375
4
def to_float(array): result=[] for x in array: x=float(x) result.append(x) result.sort() return result def probality_from_odds(odds): probability=float(odds/(1+odds)) return probability def permutation(number): result=[] true_result=1 while number>0: result....
f73d655ebe5f27aaa2c6a85d1d276994aa8c532d
eroiyo/Practices
/Python/statistics/Standard_Deviation.py
844
3.796875
4
import math def my_median(sample): n = len(sample) index = n // 2 if n % 2: return sorted(sample)[index] return sum(sorted(sample)[index - 1:index + 1]) / 2 def to_integer(array): result=[] for x in array: x=int(x) result.append(x) result.sort() return result def ...
80274cf26ff61f40c6dcc218c523a26f27f246fe
mohsinhassaan/Snake
/objects.py
2,033
3.734375
4
from collections import deque from typing import Deque, Tuple class apple(object): def __init__(self, pos): self.pos: Tuple[int, int] = pos class snake(object): def __init__(self, w: int, h: int): self.width: int = w self.height: int = h self.pieces: Deque[snake.__snake_bit] ...
86ff7bad36f128ea80bce6135b2b1e85085fb175
adityaabhiram3/Cricket_SImulation
/input_format1.py
2,169
3.625
4
import random import matplotlib.pyplot as plt overs = int(input("The desired game is of :")) balls = overs*6 over_rate = [] score_rate = [] wickets = 0 total_score = 0 individual_runs = [] e = [] team = ['Rohit','Dhawan','Kohli','Jadhav','Raina','Dhoni','Pandya','Bhuveneshwar','Bumrah','Chahal','Kuldeep'] fow = [] for ...
e91aba803e4ce7a5f936e5e8dce127fb499b9330
tizedesxx/Codecool_Tizedes
/ADayInCodecool.py
14,553
4.09375
4
import time print("Hello mister!") time.sleep(2) print() playername = input("Please enter your name! ") playername = playername.title() time.sleep(2) print() print("Hello {}!".format(playername)) input("Press ENTER to continue...") time.sleep(2) print() print("You're at home on a monday morning,") time.sleep(2) print("...
bf23188fb3c90c34da9d2b64ba6aeed16d623fd1
shashankgargnyu/algorithms
/Python/GreedyAlgorithms/greedy_algorithms.py
1,920
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file contains Python implementations of greedy algorithms from Intro to Algorithms (Cormen et al.). The aim here is not efficient Python implementations but to duplicate the pseudo-code in the book as closely as possible. Also, since the goal is to help students ...
8f2a974d5aa0eb91db1b2978ced812678e34f69f
LYoung-Hub/Algorithm-Data-Structure
/wordDictionary.py
2,039
4.125
4
class TrieNode(object): def __init__(self): self.cnt = 0 self.children = [None] * 26 self.end = False class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word): ...
94e67a4f39f3d08640323e4d3d3c1f620063e9d1
LYoung-Hub/Algorithm-Data-Structure
/flattenBinaryTree.py
839
3.875
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): stack = [] def flatten(self, root): """ :type root: TreeNode :rtype: None Do not return anything, mo...
0cb7e6c504eb6980fbe9ad71c39dc29fe9398ca1
LYoung-Hub/Algorithm-Data-Structure
/removeElement.py
738
3.6875
4
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ length = len(nums) if length == 0: return 0 left = 0 right = length - 1 while left < right: i...
958ee3e56ce76d4cfe0354381bee5631faaff641
LYoung-Hub/Algorithm-Data-Structure
/cloneGraph.py
863
3.609375
4
""" # Definition for a Node. """ class Node(object): def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors class Solution(object): visited = {} def cloneGraph(self, node): """ :type node: Node :rtype: Node """ if not node:...
1eed5d7f2ad2ab6fc0ff7190d43457daa1e7ca54
LYoung-Hub/Algorithm-Data-Structure
/lowwestCommonAncestorBST.py
697
3.90625
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 lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: Tr...
adf667e4aa17f59e71b00af1f901f291ea436cc3
LYoung-Hub/Algorithm-Data-Structure
/reorderLogs.py
699
3.515625
4
class Solution(object): def reorderLogFiles(self, logs): """ :type logs: List[str] :rtype: List[str] """ letter = [] digit = [] for s in logs: temp = s.split() if ord('a') <= ord(temp[-1][-1]) <= ord('z'): letter.append(...
774e7e1f8ffab68830784f37c1883288124ff3c2
LYoung-Hub/Algorithm-Data-Structure
/missingNumber.py
554
3.765625
4
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ nums.append(-1) i = 0 while i < len(nums): while nums[i] != i and nums[i] != -1: temp = nums[nums[i]] nums[nums[i]] = n...
1470c125a2ea5121b3d25173e11714a6219cf5fb
LYoung-Hub/Algorithm-Data-Structure
/insertionSortList.py
1,124
3.953125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return Non...
fcd93b3bfb9087b9e86fec50aba9b029fd0b2c0a
LYoung-Hub/Algorithm-Data-Structure
/BSTDoublyList.py
1,028
3.65625
4
""" # Definition for a Node. """ class Node(object): def __init__(self, val, left, right): self.val = val self.left = left self.right = right class Solution(object): seq = [] def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """...
96dfd3a633bd4a05171de7d36057d92cc6e5345f
LYoung-Hub/Algorithm-Data-Structure
/increasingTriplet.py
484
3.828125
4
class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ first = second = float('Inf') for num in nums: if num <= first: first = num elif num <= second: second = num ...
2cd4e5febaa06cb8e11673c4792f478784b38872
LYoung-Hub/Algorithm-Data-Structure
/divide.py
1,253
3.90625
4
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if dividend == 0: return 0 sign = True if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0): ...
6b76d16c0fd3ce0fd9a787b9a5df03976ec6fa1d
LYoung-Hub/Algorithm-Data-Structure
/diameterBinaryTree.py
741
3.8125
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): ans = 0 def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ ...
d942834c4b2c62a7b1aa11a67a69584ca38d677f
LYoung-Hub/Algorithm-Data-Structure
/copyRandomList.py
978
3.5625
4
""" # Definition for a Node. """ class Node(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ if no...
07a00174784084096ab488f90faf203d7714c9f0
LYoung-Hub/Algorithm-Data-Structure
/rectCover.py
314
3.78125
4
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number == 0 or number == 1 or number == 2: return number dp = [0, 1, 2] for i in range(3, number + 1): dp.append(dp[i - 2] + dp[i - 1]) return dp.pop()
6192c45530ea86237e2de4500647a3c9dcb069ae
LYoung-Hub/Algorithm-Data-Structure
/timeMap.py
1,566
3.671875
4
from collections import defaultdict class TimeMap(object): hash_set = {} def __init__(self): """ Initialize your data structure here. """ self.hash_set = defaultdict(list) def set(self, key, value, timestamp): """ :type key: str :type value: str ...
00abab3cfd3550b833b051fdf736768acea6cc74
LYoung-Hub/Algorithm-Data-Structure
/allNodesDistanceKInBinaryTree.py
978
3.65625
4
# Definition for a binary tree node. from collections import deque class TreeNode(object): def __init__(self, x): self.val = x self.par = None self.left = None self.right = None class Solution(object): def distanceK(self, root, target, K): """ :type root: Tree...
9d97174de2e8699cd15bb77360c6a24e009cf623
LYoung-Hub/Algorithm-Data-Structure
/accountsMerge.py
1,056
3.53125
4
from collections import defaultdict class DSU(object): def __init__(self): self.p = range(10001) def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): self.p[self.find(self.p[x])] = self.find(self.p[y])...
e7f82c3862be73fb592eae45debde12a47b29919
LYoung-Hub/Algorithm-Data-Structure
/combination.py
584
3.609375
4
class Solution(object): ans = [] def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ if k == 0 or n == k: return [] self.ans = [] self.backTracking([], n, k) return self.ans def backTrackin...
2dd4f257da33e48d8dff97be7d2f86613497d2d8
LYoung-Hub/Algorithm-Data-Structure
/delNodes.py
1,294
3.796875
4
# Definition for a binary tree node. from collections import deque class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def delNodes(self, root, to_delete): """ :type root: TreeNode :type to_del...
d1650f81f3ce121c27330d294d86c04443d5469d
LYoung-Hub/Algorithm-Data-Structure
/nextPermutation.py
1,093
3.75
4
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ length = len(nums) if length > 0: tail = length - 1 curr = tail while curr > 0...
8acfce1d6b4d7853b2c3f2b0b8b0cfaa0f1d8188
lb8ovn/CoffeeOOP
/Day4.py
1,180
3.90625
4
#Rock Paper Scissors import random computer_choice = random.randint(1,4) print('Choose Rock, Paper, or Scissors') human_choice = input() def choice_to_int(num): if num == 'Rock': human_choice = 1 elif num == 'Paper': human_choice = 2 elif num == 'Scissors': human_choice = 3 else:...
58d8518f009665f1f720b21db34b62894053849c
sravanneeli/Data-structures-Algorithms
/matrices_2d/lower_traingular.py
761
3.890625
4
# row major method class Matrix: def __init__(self, A=[], n=None): self.A = A self.n = n def set_value(m, i, j, x): if (i >= j): m.A[i*(i-1)//2+j-1] = x def display(m): for i in range(1, m.n+1): for j in range(1, m.n+1): if i >= j: print(m.A[i*(i...
9451f2d2160f8ae2e8165ef37ece118ca248f632
sravanneeli/Data-structures-Algorithms
/Interviewbit_Questions/Math/excel_column_title.py
570
3.84375
4
""" Problem Description Given a positive integer A, return its corresponding column title as appear in an Excel sheet. """ def convertToTitle(num): temp = '' alpha_dict = {i + 1: chr(ord('A') + i) for i in range(26)} while num > 0: digit = num % 26 if digit == 0: temp += 'Z' ...
cf90416b58d12338fb6c626109ef0ecf11c0807f
sravanneeli/Data-structures-Algorithms
/stack/parenthesis_matching.py
888
4.125
4
""" Parenthesis Matching: whether braces are matching in a string """ from stack.stack_class import Stack bracket_dict = {')': '(', ']': '[', '}': '{'} def is_balanced(exp): """ Check whether all the parenthesis are balanced are not :param exp: expression in string format :return: True or False ...
915dfdd13881f2b94cc941731079ea3d2b2086b2
sravanneeli/Data-structures-Algorithms
/stack/infix_to_postfix.py
1,395
3.75
4
from stack.stack_class import Stack class Conversion: def __init__(self, infix): self.size = len(infix) self.infix = infix self.st = Stack(self.size) self.postfix = "" self.prefix = "" self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} def infix_to_post...
2d1928b01e072fb127ed7fbfd3bfb8608e796abc
sravanneeli/Data-structures-Algorithms
/Arrays/reverse_array.py
481
4.03125
4
def reverse(arr): i = 0 j = len(arr) - 1 while i < j: arr[i], arr[j] = arr[j], arr[i] i += 1 j -= 1 return arr def checksorted(arr): for i in range(len(arr)-1): if arr[i] > arr[i+1]: return False return True def main(): arr = [4, 12, 9, 15, 6, ...
7adc19a75fd2fcdbb8f6138e396a18cfc62610f0
sravanneeli/Data-structures-Algorithms
/linked_list/doubly_linked_list.py
3,695
3.984375
4
class DoubleNode: def __init__(self, data): self.prev = None self.data = data self.next = None class DoublyLinkedList: def __init__(self): self.head = None def create(self, arr): """ Given a list of elements it creates doubly linked list :param arr:...
2e3a82dd75409883e76a08a8901f82155904c832
sravanneeli/Data-structures-Algorithms
/linked_list/display_linked_list.py
884
4.09375
4
from linked_list.linked_list_class import LinkedList, Node # Create Linked list from given array def create_ll(arr): ll = LinkedList() ll.head = Node(arr[0]) temp = ll.head for i in range(1, len(arr)): temp.next = Node(arr[i]) temp = temp.next return ll # Display Linked List Ele...
462016e1a081003b4ae0b76cdb67b454862fd6b1
sravanneeli/Data-structures-Algorithms
/Interviewbit_Questions/Binary_Search/square_root.py
442
4.09375
4
def SquareRoot(x): start = 0 end = x//2 ans = 1 if x == 1: return 1 while start <= end: mid = (start + end) // 2 if mid * mid == x: return mid if mid * mid < x: start = mid+1 ans = mid else: end = mid-1 retur...
53392264e7ca6df378f0c40995496bb8451a68eb
sravanneeli/Data-structures-Algorithms
/Interviewbit_Questions/Arrays/balance_array.py
815
3.734375
4
def balance(A): n = len(A) odd = 0 even = 0 leftOdd = [0] * n rightOdd = [0] * n leftEven = [0] * n rightEven = [0] * n for i in range(n): leftOdd[i] = odd leftEven[i] = even if i % 2 == 0: even += A[i] else: odd += A[i] # print...
7c811aba960dd8ebeb03863e298ba55f43a5ed3c
sravanneeli/Data-structures-Algorithms
/Sorting_Algorithms/merge_sort.py
1,321
4.15625
4
def merge(arr, start, mid, end): temp = [0] * (end - start + 1) i, j, k = start, mid + 1, 0 while i <= mid and j <= end: if arr[i] < arr[j]: temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 while...
46fe2a640740d758681f4cff963a0f8dc2bf87ff
lajospajtek/thought-tracker.projecteuler
/p302.py
2,977
4.15625
4
#!/usr/bin/python # -*- coding: Latin1 -*- # Problem 302 # 18 September 2010 # # A positive integer n is powerful if p^(2) is a divisor of n for every prime # factor p in n. # # A positive integer n is a perfect power if n can be expressed as a power of # another positive integer. # # A positive integer n is an Achi...
fcb8b4f928355896e0baa1d02acc6ddaddbe860f
lajospajtek/thought-tracker.projecteuler
/p023.py
2,218
3.9375
4
#!/usr/bin/python # -*- coding: latin-1 -*- # # Non-abundant sums # Problem 23 # # A perfect number is a number for which the sum of its proper divisors is # exactly equal to the number. For example, the sum of the proper divisors of # 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. # # A ...
b5a1bbfc92df82cc7108097ce51f4c5a5324fb77
lajospajtek/thought-tracker.projecteuler
/p043.py
1,358
3.578125
4
#!/usr/bin/python # -*- coding latin-1 -*- # The number, 1406357289, is a 0 to 9 pandigital number because it is made up # of each of the digits 0 to 9 in some order, but it also has a rather # interesting sub-string divisibility property. # Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we no...
db069f0bdb81b54b5ca7ab589fd8db33bff0368b
lajospajtek/thought-tracker.projecteuler
/p057.py
1,097
4.15625
4
#!/usr/bin/python # -*- coding: Latin1 -*- # Problem 057 # # It is possible to show that the square root of two can be expressed as an infinite continued fraction. # # √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... # # By expanding this for the first four iterations, we get: # # 1 + 1/2 = 3/2 = 1.5 # 1 + 1/(2 + ...
1c7c94fcdae7b41b4634934ad6610afe0691aa68
SantiEscoto/Python
/Listas.py
881
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 20 12:22:39 2020 @author: Lenovo """ #Listas x=[0,7,2,4] print(x) print(x[0]) print(x[1]) print(x[2]) print(x[3]) x.append(3) #Añadir un valor al conjunto de elementos print(x) print(x[4]) x.remove(3) #Quitar el valor que contenga ese número nombr...
a02ccb400bd557c00352d982dc968b5cbcd9cb31
SantiEscoto/Python
/EditorPersonajesING.py
3,199
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 10 11:29:22 2020 @author: Lenovo """ class PLAYER: def __init__(self,Name,Attack,Defense,Health): self.Name=Name self.Attack=Attack self.Defense=Defense self.Health=Health options=[0,1,2,3] characters=[] while True: ...
1e5c4c7bafa6e60a73556257b1bd52454a047de8
NoDisassemble/Python-3-Landfill
/howManyTimes.py
975
4.0625
4
import time print(''' -------------------------------------------------------------------------------- Description: A simple program that prints whatever you type for however many times you say. Keywords: [Python Word Repeater, Character Repeater] Dec 2016 v1.0 by NoDisassemble.me ----------------------------...
17cd65fc53769ec172c17c014180e72f96ec8288
rickh94/slackmentions
/slackmentions.py
3,415
3.8125
4
"""Defines functions for dealing with mentions in slack messages.""" import re from slackperson import SlackPerson from slackperson import SlackDataError def findpeople(text, userlist, silent=False): """Finds username mentions in slack text and creates SlackPerson objects for those people. Returns a list of t...
c4f94bcbc8166f59bf58acbb41584edd7368f3ca
mjavidiq/number-wordify
/number_to_words.py
788
4.0625
4
import wordifier import language.language_help as lang # Given a phone number, finds all possible wordifications of it # according to the specified dictionary and returns a possible # wordification. def number_to_words(number, fname = "./language/words_alpha.txt"): corpus = lang.import_dictionary(fname) #...
17d176613f38f4bd7c225828a386ea6e5efa47fe
ServioTRC/RebelCoders
/CodeChallenge2017v1/Triangle Trilemma.py
1,610
3.765625
4
import math cases = int(raw_input()) for i in range(1,cases+1): print "Case #"+str(i)+":", text = raw_input().split(" ") points = [] for j in range(len(text)): points.append(int(text[j])) a = math.sqrt((points[0]-points[2])**2+(points[1]-points[3])**2) b = math.sqrt((points[2]-points[4])...
9fecd010e2708d3066af7173b935a9cc4c03172a
sauravgsh16/DataStructures_Algorithms
/g4g/ALGO/Searching/Coding_Problems/31_find_position_of_element_in_sorted_infinite_array.py
786
4.0625
4
''' Find the position of an element in a sorted array of infinite number ''' ''' We need to find the lower and upper limit first. Once we have the boundary, we can apply binary search to find element ''' def binary_search(arr, low, high, x): if low > high: return -1 mid = low + ((high - low...
8394d93a3962473eee6cc9f4f79bc1e3c7f002cf
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Introduction/find_height_of_binary_tree_iterative.py
751
4.09375
4
''' Iterative method to find height of a binary tree ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def tree_height(root): if not root: return 0 q = [] q.append(root) height = 0 while True: nodec...