blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
0539a2d561e0bb43b076b88480021dc634b588b2
ikostan/ProjectEuler
/Problems_1_to_100/Problem_35/problem_35.py
1,906
4
4
#!/usr/bin/python import time from utils.utils import print_time_log, is_prime def get_rotations(digit: int): """ The number, 197 has following rotations of the digits: 197, 971, and 719 :param digit: :return rotations: """ rotations = set() rotations.add(digit) digits = [d for ...
c2d6f4a602494c4bc1ca520b854a87d0d086f16b
ikostan/ProjectEuler
/Problems_1_to_100/Problem_43/tests/test_problem_43.py
1,164
3.515625
4
#!/usr/bin/python import unittest import os from Problems_1_to_100.Problem_43.problem_43 \ import main, has_sub_string_divisibility class MyTestCase(unittest.TestCase): print("Running unit tests from: " + os.path.basename(__file__) + "\n") def test_has_property_true(self): number = [...
cb1b4d26d24c00909154f998f9c257395ca956b1
ikostan/ProjectEuler
/Problems_1_to_100/Problem_43/problem_43.py
2,437
3.953125
4
#!/usr/bin/python import time import itertools from utils.utils import print_time_log def has_sub_string_divisibility(number): """ The number, 1406357289, is a 0 to 9 pandigital number. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is...
ba0f71a52b1c9412bede51e0fc46cee710f96d19
ikostan/ProjectEuler
/utils/utils.py
5,878
3.75
4
#!/usr/bin/python import time import platform import os import math # TODO: each method must have his own .py file # This function is used for logging processing time only # Shows how long it took in order to get the answer def print_time_log(start_time: time, result=''): end_time = time.time() - start_time ...
a1a9a0dfd810676cbbaede2bf64178c86fd24fdc
ikostan/ProjectEuler
/Problems_1_to_100/Problem_2/problem_2.py
530
3.796875
4
#!/usr/bin/python import time from utils.utils import print_time_log def find_even_fibonacci(max_num): start_time = time.time() nums = generate_fibonacci(max_num) result = sum([i for i in nums if i % 2 == 0]) print_time_log(start_time, result) return result # TODO: move this method into utils ...
5fc949bf2bbcaa4e7321cf28cddd26908f37fdac
dsryder/mission_to_mars
/mission_to_mars.py
15,658
4.03125
4
# coding: utf-8 # <h1>Mission to Mars</h1> # # In this assignment, you will build a web application that scrapes various websites for data related to the Mission to Mars and displays the information in a single HTML page. The following outlines what you need to do. # # <h3>Step 1 - Scraping</h3> # # Complete your...
b0124008213cdc4d3c7fdb80e77df5d848ad75c4
tgquintela/FirmsLocations
/FirmsLocations/Preprocess/aux_functions.py
468
3.78125
4
""" Auxiliary functions to perform the main functions showed in this module. """ import numpy as np def reverse_mapping(mapdict): "Function to reverse a mapping dict." r_mapdict = {} for e in mapdict.keys(): mapdict[mapdict[e]] = e return r_mapdict df, type_vals, n_vals, N_t, N_x = ...
5a8114485c3654363ca2d9930a63290501dff882
ajoykumarray1/django-react_assignment
/Assignment1/grade_calculate.py
410
3.953125
4
n = float(input("Enter Grade: ")) if n == 4: print("A+") elif n >= 3.75 and n <= 3.99: print("A") elif n >= 3.26 and n <= 3.74: print("A-") elif n >= 3.1 and n <= 3.25: print("B+") elif n >= 2.76 and n <= 3: print("B") elif n >= 2.51 and n <=2.75: print("B-") elif n >= 2.1 and n <= 2.5: prin...
e521c82b03842cbde5276eda18045c650c226784
421312525/lvming
/class04/Demo01.py
5,983
3.828125
4
''' @author:lvming @time:2021/6/17 ''' #异常和时间日期模块 #异常:程序在运行时如果报错了,停止,错误信息,异常 #程序停止并且提示错误信息,这个过程就叫抛出异常 #异常:为了程序的稳定性和健壮性 异常处理 就是针对突发情况做集中的处理 #语法结构 ''' try: 尝试的代码 except: 出现错误的处理 except BaseException as 变量名: 出现错误的处理 程序中不确定会不会出现问题的代码,就写在try: 如果程序出现问题,就执行except里面的代码 格式:要缩进 tab ''' #题目:要求用户输入整数 #用户输入 input string字...
e7adb11c7dd91da3cf365249dff16aa4115e344f
421312525/lvming
/class05/Demo02.py
7,047
3.796875
4
''' @author:lvming @time:2021/6/17 ''' #面向对象:私有的属性,私有的方法 封装,继承,多态,类方法,静态方法 #私有属性,方法 #场景:不愿意把对象的方法和属性公开的时候 #私有属性:不愿意公开属性 #私有方法:不愿意公开方法 #定义:属性或者方法的前面 加个__ age=18 __age=18 def open() def __open() # class Girl: # def __init__(self,name): # self.name=name # self.__age=18 # def __desc(self): #...
6b3830b91d9ecfd83b8ac6cd71f0c8ee0f277fbc
421312525/lvming
/blibli/Demo01.py
4,750
3.890625
4
''' @author:lvming @time:2021/6/17 ''' #算法 #递归的两个特点: 调用自身、结束条件 # def func3(x): # if x>0: # print(x) # func3(x-1) # # func3(5) # def func4(x): # if x>0: # func4(x-1) # print(x) # func4(5) # 递归实例:汉诺塔问题 # n=2时: # 1.把小圆盘从A移动到B # 2.把大圆盘从A移动到C # 3.把小圆盘从B移动到C # n个盘子时: # 1.把n-1个圆盘从A经过C移动...
7261d62dcdf7e6f80844215814e31d8fd7864b42
Alagu-Ramya/Speech-Recognition
/voice.py
415
3.6875
4
import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: print("Speak anything...") audio= r.listen(source) try: text=r.recognize_google(audio) if text.lower() in ["hello","hey","hola"]: print("Hello user how are you?") else: print...
d335e9df91d9bd822e2c9a065536e5e49d8d77db
Chingles2404/bogosort
/bogosort.py
554
3.875
4
import random def bogosort(): unsorted = input("Please input your list in the format \"1, 2, 3\"\n").split(", ") compare = sorted(unsorted) counter = 1 print(compare, unsorted) while compare != unsorted: print("Round " + str(counter)) temp = [] while len(unsorted) ...
e0f186e9af512b65a89579b881ee2d2eb15a4c4c
harahash/python_code
/genalgo.py
2,894
3.5
4
from random import * def initiation(): g = 0 s = [] count = 4 str_len = 4 #randint(5, 10) for i in range(0, count): chromosome = [] for j in range(0, str_len): j = randint(0, 1) ''' if j == 2: chromosome.append('#') el...
6c228a20feac003a930424d361545076e527e263
EnnyZakiyyah/-ChallengeWeek1Day3
/FibbonachiNumbers.py
331
3.765625
4
print("Fibbonachi Numbers".center(75, "=")) def fibonacci(n): if n < 1: return [n] SebelumN = fibonacci(n - 1) a1 = SebelumN[-2] if len(SebelumN) > 2 else 0 a2 = SebelumN[-1] if len(SebelumN) > 2 else 1 return SebelumN + [a1 + a2] angka = int(input("Input Angka : ")) print(fibonacci(a...
49ae31b0436534135aeca41c8c03b8a5617f51cf
MurasatoNaoya/Python-Fundamentals-
/Python Modules and Packages/one.py
1,122
3.9375
4
# Python is special in the fact that it runs all of the code on indentation level 0, no further questions asked. # In other languages, you define a main() piece of code that is always run automatically. # We have deal with built in functions and operators already, but we have yet to see a built in variable. #...
67cbd0b1515475aea9ff580518cdbacf20c5c9b0
MurasatoNaoya/Python-Fundamentals-
/Python Methods and Documentation/Args and Kwargs.py
3,947
4.34375
4
# When dealing with fucntions, you will eventually be setting arbitrary parameters for your functions. def myfunc(a,b): return sum((a,b))*0.05 # This functions returns 5% of the sum of a and b. If you are going to multiply anything too, it has to be at the back of the return statement. # Instead of just...
a6865c6ca008e9dcfad05a6642a12fee6392db8f
MurasatoNaoya/Python-Fundamentals-
/Python Advanced Modules/Python Regular Expressions I.py
3,232
4.34375
4
# First we need a string to scan through and match things to. text = "The agent's phone number is 020-823-1234. Call back!" # We can create a simple script to produce a booleon output if the string 'phone' is present. print('phone' in text) # But we an instead use a regular expression to serach for the w...
4bff238efa004620c7e712f89d535c32ee5b2455
MurasatoNaoya/Python-Fundamentals-
/Python Methods and Documentation/An Introduction to Functions in Python.py
5,397
4.4375
4
# You have to make a clear distinction about what functions are in not only Python, but programming languages as a whole. # The definition of a function is - a block organised, reusable that is used to perform a related action. # There are in-built functions, what we have dealt with so far. Like print(), len(), t...
cc0251039d13415b7d2170ba6d2a2cd8437c6fa3
MurasatoNaoya/Python-Fundamentals-
/Python Statements/For Loops.py
5,274
4.8125
5
# A 'for loop' is the execution of a piece of code, that iterates from a group of items. # The content of the object dicates what code is executed and the number of times it is executed. # For loops apply to any data type that can hold multiple items, like a list or dictionary for example. # Reading, for object_v...
224d9fa0622c1b7509f205fa3579a4b42a8a73a6
MurasatoNaoya/Python-Fundamentals-
/Python Object and Data Structure Basics/Print Formatting.py
1,397
4.59375
5
# Print Formatting ( String Interpolation ) - # .format method - print('This is a string {}'.format('okay.')) # The curly braces are placeholders for the variables that you want to input. # Unless specified otherwise, the string will be formatted in the order you put them in your .format function. print('T...
6249661d7b8780c819cd09d19fda0cfce614c303
lxmambo/caleb-curry-python
/31-sort-by-string-length.py
225
3.890625
4
strings = ['a','A','abc','ABC','HELLO','aBc','aBC','Abc'] strings.sort(key=len) print(strings) #another option using key inside sorted strings = ['a','A','abc','ABC','HELLO','aBc','aBC','Abc'] print(sorted(strings, key=len))
10e035aeebda0af60b091a21613eaf2f9e83f08e
lxmambo/caleb-curry-python
/59 -looping-through-key-value-pairs.py
581
4.0625
4
emails = { 'caleb':'caleb@gmail.com', 'gal':'g@hotmail.com', 'tim':'timmy@sapo.pt', } for key,elem in emails.items(): print(key,elem) conjunctions = { "for":0, "and":0, "nor":0, "but":0, "or":0, "yet":0, "so":0, } copletely_original_poem = """yet more two more times i feel...
ed3055e72174939e05677919b1f1a88c36e6c4e8
lxmambo/caleb-curry-python
/56-retrieve-data-dictionaries.py
302
3.703125
4
emails = { 'caleb':'caleb@gmail.com', 'gal':'g@hotmail.com', 'tim':'timmy@sapo.pt', } if 'caleb' in emails: print(emails['caleb']) else: print('not found') print(emails.get('caleb')) #if it doesn't exist returns 'none' print(emails.get('joao','no user found')) #this last one with personalized messa...
ac6c342051b769f641ab4420a4df2da8fb2717a3
lxmambo/caleb-curry-python
/23-reverse-list-algorithm.py
204
4
4
#reverse a list manually data = ["a","b","c","d","e","f","g","h"] index = 1 #integer division for index in range(len(data)//2): data[index], data[-index-1] = data[-index-1], data[index] print(data)
b31ab274315b8a8e060aaa6423c72f553d23dddf
lxmambo/caleb-curry-python
/29-sort-in-reverse-order.py
236
3.71875
4
data = [1,32,54,34,65,11,100,-1,3] data_sorted = sorted(data) #data_final = data_sorted.reverse() print(data_sorted) data_sorted.reverse() data_final = data_sorted[:] print(data_final) #another version print(sorted(data, reverse=True))
f62dd5c65eb6c397c7aa0d0557192b8a53768591
lxmambo/caleb-curry-python
/60-sets.py
557
4.15625
4
items = {"sword","rubber duck", "slice of pizza"} #a set cannot have duplicates items.add("sword") print(items) #what we want to put in the set must be hashable, lists are not conjunctions = {"for","and","nor","but","or","yet","so"} seen = set() copletely_original_poem = """yet more two more times i feel nor but or bu...
390e46a938f9b7f819a9e59f517a9de9848b387e
lxmambo/caleb-curry-python
/25-reverse-list-w-slice.py
308
4.15625
4
data = ["a","b","c","d","e","f","g","h"] #prints every 2 items print(data[::2]) #prints reversed print(data[::-1]) data_reversed = data data[:] = data[::-1] print(data) print(id(data)) print(id(data_reversed)) #doint the slice like this changes only the content of the list #but doesn't change de list...
917082ee4c1b887df885514dc3b320c836541eee
greggomann/mesos-healthcheck-benchmark
/histogram.py
318
3.53125
4
#!/usr/bin/env python3 import sys from collections import OrderedDict numdict = {} for line in sys.stdin: numstring = line.strip() num = int(numstring) value = numdict.setdefault(num, 0) numdict[num] = value + 1 for key in sorted(numdict): print("{:<10}{:=<{width}}".format(key, "", width=numdict[key]))
63349645c3b76fa40145efc1e4c343b0370145ba
rulibar/language-flash-cards-1
/lfc.py
1,578
3.515625
4
# imports import json import random # vars file = 'eng_esp2.json' # compile words list word_list = json.loads(open(file).read()) keys = list(word_list.keys()) lang1 = keys[0].capitalize() lang2 = word_list[keys[0]].capitalize() del word_list[keys[0]]; del keys[0] correct = 0 incorrect = 0 streak = 0 words = dict() n...
27f4fc077ccca758603382067d64ed536af1529b
alexweiranli/ApTimer
/aptimer_cal/calculation/diffusivity.py
1,141
3.59375
4
""" Calculate diffusivity """ import math class DiffFunc: def __init__(self, data): self.temp = data['temp'] # Temperature in Celsius degree self.tilt = data['tilt'] # Tilt of traverse from the c-axis def diffusivity(self): tilt = math.radians(self.tilt) dcl = 7.15 * 10 ...
68be102e7123a257f918119b8a05556479822a39
MaksPrykhodko/iasaedu
/main.py
1,359
3.890625
4
from account import Bank_account account_26001001010 = Bank_account(1000, 'USD', 26001001010, 'Tom Smith', 'Private Bank', 123456) choice = int(input('\t\tSelect your action number:' '\n1. View balance' '\n2. View info about account' '\n3. Take money' ...
bd1bc9992058552ef5545240822728bc63295f7a
rupamroy/python-basics-learning
/boolean.py
709
4.0625
4
python_course = True java_course = False int(python_course) == 1 int(java_course) == 0 str(python_course) == "True" aliens_found = None # this is similar to null, it id different then undefined number = 5 if number == 5: print("Number is 5") else: print("Number is NOT 5") if number: print("Number is de...
2d3809807ffb098ed66a076487eb123d7e4c9d5a
rupamroy/python-basics-learning
/exceptions.py
407
3.96875
4
student = { "name" : "Rupam", "student_id": 227704, "feedback": None } student["last_name"] = "Roy" try: last_name = student["last_name"] numbered_last_name = last_name + 3 except KeyError: print("error finding last name") except TypeError as error: print(error) print("cannot add number ...
a784a1e07c44897403ec4ec4020d993447a666f9
Damanpreet/Algorithms
/geeksforgeeks/unionbyrank.py
2,188
3.703125
4
from collections import defaultdict class Node: def __init__(self, parent, rank): self.parent = parent self.rank = rank class Tree: def __init__(self, vertices): self.vertices = vertices self.graph = defaultdict(lambda: []) def add_edge(self, i, j): self.graph[i].a...
92584ddcc6d180451b5c1b27326d670117bcc0aa
Damanpreet/Algorithms
/Spring19/dijkstra.py
2,336
3.9375
4
import sys class Graph: def __init__(self, VERTICES): self.graph = [[0]*VERTICES]*VERTICES self.parent = [None]*VERTICES self.distance = [sys.maxint]*VERTICES self.vertices = [False]*VERTICES def dijkstra(self, start_vertex): print('Begin finding path') ...
47c6b2977678e6b2361cc3716c43a98132d82f15
yennanliu/CS_basics
/leetcode_python/Design/encode-and-decode-tinyurl.py
8,653
4.34375
4
""" Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL. There i...
0bab822273ee47afc89bf12700e7d2b92e32b474
yennanliu/CS_basics
/leetcode_python/Array/array-nesting.py
7,155
3.953125
4
""" 565. Array Nesting Medium You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: The first element in s[k] starts with the selection of ...
4c129f3bd0bc14dad854c823e0467a8a91e83771
yennanliu/CS_basics
/leetcode_python/Tree/print-binary-tree.py
4,876
4.09375
4
""" LeetCode 655. Print Binary Tree Print a binary tree in an m*n 2D string array following these rules: The row number m should be equal to the height of the given binary tree. The column number n should always be an odd number. The root node's value (in string format) should be put in the exactly middle of the firs...
1c7817c78c414ebda3bc0225e6efa533f9e0406c
yennanliu/CS_basics
/leetcode_python/Depth-First-Search/max-area-of-island.py
5,385
3.859375
4
""" 695. Max Area of Island Medium You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the isla...
b7292e5eacee0ae28fb84778cb819b4aa547d0c0
yennanliu/CS_basics
/leetcode_python/Math/sum-of-square-numbers.py
1,969
3.859375
4
# V1 import math class Solution(object): def judgeSquareSum(self, c): mid_point = int(math.sqrt(c)) left = 0 right = mid_point """ the condition here should be "while left <= mid_point" instead of "for i in range(0, mid_point)" since it woule only run mid_point times if in for loop case However, setti...
8172298f69f0196bff1e1527afe2c2e4da22b57a
yennanliu/CS_basics
/leetcode_python/Bit_Manipulation/power-of-two.py
3,820
4.15625
4
""" 231. Power of Two Easy Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example ...
9f4386ce678560cf7a88fbb45335b9fa3e1ca7e7
yennanliu/CS_basics
/leetcode_python/Binary_Search_Tree/minimum-absolute-difference-in-bst.py
2,207
3.5625
4
# V0 # V1 # http://bookshadow.com/weblog/2017/02/26/leetcode-minimum-absolute-difference-in-bst/ # 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 getMinimumDiffere...
176db7faf112b894acf2ec630ef400189564fdd3
yennanliu/CS_basics
/leetcode_python/Depth-First-Search/find-leaves-of-binary-tree.py
3,025
3.96875
4
# V0 # V1 # https://blog.csdn.net/danspace1/article/details/87738403 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findLeaves(self, root: 'TreeNode') -> 'List[List[int]]': ...
8335193ef41e119cf50cd82f198250f4df3f5d95
yennanliu/CS_basics
/leetcode_python/Binary_Search/search-insert-position.py
3,415
4.09375
4
""" 35. Search Insert Position Easy Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [1,3,5,6], tar...
99d67aec305030c88f64b38a0eb4ea2d2cdb2eda
yennanliu/CS_basics
/leetcode_python/Linked_list/remove-duplicates-from-sorted-list.py
2,672
3.875
4
""" 83. Remove Duplicates from Sorted List Easy Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Example 1: Input: head = [1,1,2] Output: [1,2] Example 2: Input: head = [1,1,2,3,3] Output: [1,2,3] Constraints: T...
2f566006422473e7f59479532814903d5c8c4cc2
yennanliu/CS_basics
/leetcode_python/Recursion/validate-binary-search-tree.py
13,159
4.0625
4
""" 98. Validate Binary Search Tree Medium Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater tha...
035f1f2268be2f5036c3165105cd80fbdd7b78fa
yennanliu/CS_basics
/leetcode_python/Array/flatten-2d-vector.py
9,980
3.53125
4
""" 251. Flatten 2D Vector Medium Design an iterator to flatten a 2D vector. It should support the next and hasNext operations. Implement the Vector2D class: Vector2D(int[][] vec) initializes the object with the 2D vector vec. next() returns the next element from the 2D vector and moves the pointer one step forward...
336cea907d0bd5e226afd9be45bb249e2f1dd8f9
yennanliu/CS_basics
/leetcode_python/Recursion/second-minimum-node-in-a-binary-tree.py
5,330
3.625
4
# V0 # IDEA : DFS class Solution: def findSecondMinimumValue(self, root): result=[] self.dfs(root, result) result_=sorted(set(result)) return result_[1] if len(result_) > 1 else -1 def dfs(self,root, result): if not root: return self.dfs(root.left,...
0a0facae50109a7b0f48dd2f1e6dbfe1e4792bc6
yennanliu/CS_basics
/leetcode_python/Tree/construct-binary-tree-from-string.py
8,570
3.84375
4
""" Leetcode 536. Construct Binary Tree from String You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of pare...
d0c98cbd1b83411625f089ea91305017175effac
yennanliu/CS_basics
/leetcode_python/Breadth-First-Search/shortest-path-to-get-food.py
7,101
3.671875
4
""" [LeetCode] 1730. Shortest Path to Get Food # https://www.cnblogs.com/cnoodle/p/15645191.html You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an m x n character matrix, grid, of these different types of cells: '*' is ...
ee102ce9417bfdd8df72cf8d5b78cb2442a60bb6
yennanliu/CS_basics
/leetcode_python/Math/convex-polygon.py
1,974
3.921875
4
# LeetCode 469. Convex Polygon # Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition). # Note: # There are at least 3 and at most 10,000 points. # Coordinates are in the range -10,000 to 10,000. # You may assume the polygon formed by given p...
784d6b29b0738e8ff78fbb391f2f108a17e0b880
yennanliu/CS_basics
/leetcode_python/Binary_Search/find-peak-element.py
5,075
4.0625
4
""" 162. Find Peak Element Medium A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. You must writ...
28f5a632e04e15bba1f71836e27e426329a68cc8
yennanliu/CS_basics
/leetcode_python/Binary_Search/count-complete-tree-nodes.py
1,925
3.609375
4
# V0 # V1 # http://bookshadow.com/weblog/2015/06/06/leetcode-count-complete-tree-nodes/ # https://blog.csdn.net/fuxuemingzhu/article/details/80781666 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = No...
33f74d1bb555faa6d01048ca2d136b7fdd607349
yennanliu/CS_basics
/leetcode_python/Breadth-First-Search/binary-tree-level-order-traversal.py
8,551
3.96875
4
""" Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of...
70238d38bd6c3ed092ffa807166bffd2def09eec
yennanliu/CS_basics
/leetcode_python/Hash_table/pairs-of-songs-with-total-durations-divisible-by-60.py
4,485
3.59375
4
""" 1010. Pairs of Songs With Total Durations Divisible by 60 Medium You are given a list of songs where the ith song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with ...
14013c4493f7a3395b43a999d1c6f51c1bb6b57c
yennanliu/CS_basics
/leetcode_python/Linked_list/add-two-numbers-ii.py
7,259
3.984375
4
""" 445. Add Two Numbers II Medium You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leadin...
b3e12e8cf461042439764d958f75e2e10fb9d788
yennanliu/CS_basics
/leetcode_python/Math/permutation-sequence.py
2,884
3.515625
4
# V0 class Solution: def getPermutation(self, n, k): baselist = [i + 1 for i in range(n)] numperm = 1 for i in range(1, n + 1): numperm *= i string = "" for i in range(n): # i-th character numperm /= n - i idx = int((k - 1) / nu...
af6970d4ace977526f2026544edf83718beb447a
yennanliu/CS_basics
/leetcode_python/Dynamic_Programming/minimum-cost-to-merge-stones.py
5,957
3.96875
4
""" 1000. Minimum Cost to Merge Stones Hard There are n piles of stones arranged in a row. The ith pile has stones[i] stones. A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles. Return the minimum cost to merge all ...
7e054af896537a5f846a42d0f5ba51229b63d194
yennanliu/CS_basics
/leetcode_python/Sort/brightest-position-on-street.py
8,419
3.90625
4
""" 2021. Brightest Position on Street Medium A perfectly straight street is represented by a number line. The street has street lamp(s) on it and is represented by a 2D integer array lights. Each lights[i] = [positioni, rangei] indicates that there is a street lamp at position positioni that lights up the area from ...
df81cd3fc91020ca4c34fbde8e90846397c3b240
yennanliu/CS_basics
/leetcode_python/Breadth-First-Search/walls-and-gates.py
6,636
4.09375
4
""" You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distan...
02d504e4b5a9658e643c3d10a5dc13b7a2e427f5
yennanliu/CS_basics
/leetcode_python/Hash_table/group-shifted-strings.py
2,917
4.21875
4
""" Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. For...
619a5a5a16301c95c5bdf7b10b1bfd8f9dc3eb62
yennanliu/CS_basics
/leetcode_python/Depth-First-Search/number-of-provinces.py
12,000
3.6875
4
""" 547. Number of Provinces Medium There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no o...
f73fd17263ef3f95316115fcafa1813ac95ca9a0
yennanliu/CS_basics
/leetcode_python/Math/minimum-factorization.py
1,743
3.703125
4
# leetcode 625. Minimum Factorization # Given a positive integer a, find the smallest positive integer b whose multiplication of each digit equals to a. # If there is no answer or the answer is not fit in 32-bit signed integer, then return 0. # Example 1 # Input: # 48 # Output: # 68 # Example 2 # Input: # 15 ...
c0d8adf9841a72f02d317339c8b15257e5580665
yennanliu/CS_basics
/leetcode_python/Bit_Manipulation/total-hamming-distance.py
3,277
4.1875
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums. Example 1: Input: nums = [4,14,2] Output: 6 Explanation: In binary representation...
843c46de16ad22c10d8e8a5349bd55d40e6abe6b
yennanliu/CS_basics
/leetcode_python/Tree/convert-bst-to-greater-tree.py
8,296
3.625
4
""" 538. Convert BST to Greater Tree Medium Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies thes...
95a2115e6c29ee3c7d90c717dbe994769dfeeb73
yennanliu/CS_basics
/leetcode_python/Binary_Search/h-index-ii.py
4,123
3.859375
4
""" Follow up for H-Index: (274) What if the citations array is sorted in ascending order? Could you optimize your algorithm? Hint: Expected runtime complexity is in O(log n) and the input is sorted. ref : https://github.com/yennanliu/CS_basics/blob/master/leetcode_python/Sort/h-index.py """ # V0 # IDEA : BIN...
aa9a183e6d58feb44cd4fb4dbf4752473095d303
yennanliu/CS_basics
/leetcode_python/Breadth-First-Search/shortest-path-to-get-all-keys.py
5,930
4.21875
4
""" 864. Shortest Path to Get All Keys Hard You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall. '@' is the starting point. Lowercase letters represent keys. Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardin...
d6c617eaa8abfbbbcce4aaebdab9265bd6e80c98
yennanliu/CS_basics
/leetcode_python/Two_Pointers/minimum-number-of-swaps-to-make-the-string-balanced.py
6,796
4.25
4
""" 1963. Minimum Number of Swaps to Make the String Balanced Medium You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: It is the empty string, or It can be written as AB, where bo...
998c5b02a4e653b686985c216acc222a723d0d92
yennanliu/CS_basics
/leetcode_python/Math/find-the-derangement-of-an-array.py
1,845
3.671875
4
# LeetCode 634. Find the Derangement of An Array # In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position. # There's originally an array consisting of n integers from 1 to n in ascending order, you need to find the number of derange...
3ebae3bfa9916826465f381ad11b8667d22711c8
yennanliu/CS_basics
/leetcode_python/Math/complex-number-multiplication.py
2,515
4.09375
4
""" 537. Complex Number Multiplication Medium A complex number can be represented as a string on the form "real+imaginaryi" where: real is the real part and is an integer in the range [-100, 100]. imaginary is the imaginary part and is an integer in the range [-100, 100]. i2 == -1. Given two complex numbers num1 and...
66dd23f3a7ee27124e47baf1c7d55056ef412310
yennanliu/CS_basics
/leetcode_python/String/string-to-integer-atoi.py
13,223
3.625
4
""" 8. String to Integer (atoi) Medium Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if not already at the end o...
dbf005e674eeec4d1d02c7b83cbbfa12d8ae7f6f
yennanliu/CS_basics
/leetcode_python/Dynamic_Programming/flip-string-to-monotone-increasing.py
5,691
3.8125
4
""" 926. Flip String to Monotone Increasing Medium A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none). You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0. Return the minimum number of...
f9509c7c22c7df6c410b2686aa2f94f5fd6b800e
yennanliu/CS_basics
/leetcode_python/Tree/average-of-levels-in-binary-tree.py
4,940
3.96875
4
""" Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: root = [3,9,20,null,15,7] Output: [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on l...
818ffbb736d1ea751d8d5d51ff19bfe26a0a1db5
yennanliu/CS_basics
/leetcode_python/Array/employee-free-time.py
11,144
3.734375
4
""" LC 759 We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all employees, also in sor...
f105565a0fcbb71836af039291524be212b71878
yennanliu/CS_basics
/leetcode_python/Linked_list/reverse-linked-list.py
5,765
4.25
4
""" Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <=...
afe1844d313b1845f6bf58cf109cdc15dedc735f
yennanliu/CS_basics
/leetcode_python/Math/largest-triangle-area.py
1,703
3.625
4
# V1 # V2 # http://bookshadow.com/weblog/2018/04/09/leetcode-largest-triangle-area/ ### Shoelace formula ### : get the area of triangle from its 3 points # https://en.wikipedia.org/wiki/Shoelace_formula class Solution(object): def largestTriangleArea(self, points): """ :type points: List[List[i...
d508d272ebb753866fbcbc5d2e8c4a736b59c0ba
yennanliu/CS_basics
/leetcode_python/Array/max-increase-to-keep-city-skyline.py
3,892
3.609375
4
""" In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well. At the end, the “skyline” ...
15f775824d1a77b6451160c08c7eaf4b047d9f1b
yennanliu/CS_basics
/leetcode_python/Breadth-First-Search/course-schedule.py
26,504
3.71875
4
""" 207. Course Schedule Medium There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. For example, the pair [0, 1], indicates that t...
feddecfa96cf559c27fdcd63b01eb68cc0c5f780
yennanliu/CS_basics
/leetcode_python/Array/3sum-with-multiplicity.py
3,483
3.71875
4
# V0 # V1 # https://www.jiuzhang.com/solution/3sum-with-multiplicity/#tag-highlight-lang-python import collections class Solution: """ @param A: the given integer array @param target: the given integer target @return: the number of tuples """ def threeSumMulti(self, A, target): # Writ...
d62d7d36813e1cad3ea215dc12c568c4dabe5b3e
yennanliu/CS_basics
/leetcode_python/Hash_table/k-diff-pairs-in-an-array.py
6,108
3.8125
4
""" 532. K-diff Pairs in an Array Medium Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 0 <= i < j < nums.length |nums[i] - nums[j]| == k Notice that |val| denotes the absolut...
891042fa21e31d7895cbfb20aa2eca9ff30bf7ce
yennanliu/CS_basics
/leetcode_python/Array/missing-ranges.py
6,802
3.546875
4
""" LeetCode 163. Missing Ranges # https://www.goodtecher.com/leetcode-163-missing-ranges/ Description https://leetcode.com/problems/missing-ranges/ You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range. A number x is considered missin...
daca24279a2258e29258eb3f83ae2c8a0cc01c1b
yennanliu/CS_basics
/leetcode_python/String/string-compression.py
3,971
4.125
4
# Time: O(n) # Space: O(1) # Given an array of characters, compress it in-place. # The length after compression must always be smaller than or equal to the original array. # Every element of the array should be a character (not int) of length 1. # After you are done modifying the input array in-place, return the new ...
9cbbc6d4ed04f369ee8e60d30c0fb448fd8e984c
yennanliu/CS_basics
/leetcode_python/Hash_table/minimum-index-sum-of-two-lists.py
5,556
4.03125
4
# Time: O((m + n) * l), m is the size of list1, n is the size of list2 # Space: O(m * l), l is the average length of string # Suppose Andy and Doris want to choose a restaurant for dinner, # and they both have a list of favorite restaurants represented by strings. # # You need to help them find out their common intere...
4e2a77b9611c8885a882a290dc99070f53655c49
yennanliu/CS_basics
/leetcode_python/Dynamic_Programming/best-time-to-buy-and-sell-stock-iii.py
2,900
4.15625
4
""" 123. Best Time to Buy and Sell Stock III Hard You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the ...
fb3362aec98f0fa2bf02d000a8ccd04c1596dd73
yennanliu/CS_basics
/leetcode_python/Tree/increasing-order-search-tree.py
3,121
3.875
4
# V0 # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/82349263 # 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 increasingBST(self, root): """ ...
737766eabf360f7237801d5459501763579d4bbe
yennanliu/CS_basics
/leetcode_python/Breadth-First-Search/clone-graph.py
13,004
3.578125
4
""" 133. Clone Graph Medium Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; public List<Node> neighbors; } Test case format: For sim...
b00e4353930f26019f54d422ee5b4c456973ff6f
yennanliu/CS_basics
/algorithm/python/bubble_sort.py
3,465
3.9375
4
#--------------------------------------------------------------- # BUBBLE SORT #--------------------------------------------------------------- # V0 # LC 215 def bubble_sort(nums): _len = len(nums) for i in range(_len - 1): # since the last n element (idx = n) already minimum/maximum in every sort it...
e185c7e93737b1a1f6e9d16823cb231c740e72f3
yennanliu/CS_basics
/leetcode_python/Binary_Search/sqrtx.py
3,731
4.34375
4
""" Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5. Ex...
dfaaf51d6482ae661fa7a22c5234b06d6adff0e5
yennanliu/CS_basics
/leetcode_python/Math/powx-n.py
2,714
3.875
4
""" Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Example 1: Input: x = 2.00000, n = 10 Output: 1024.00000 Example 2: Input: x = 2.10000, n = 3 Output: 9.26100 Example 3: Input: x = 2.00000, n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Constraints: -100.0 < x < 100...
0a658b333a4be18621daf682968ad2aa6850e2d9
yennanliu/CS_basics
/leetcode_python/Math/find-greatest-common-divisor-of-array.py
1,785
3.921875
4
""" 1979. Find Greatest Common Divisor of Array Easy Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums. The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. Example 1: Input: nums = [2,5,6,9,1...
0c086bdedb0b8153d25db64421c33e0b44090fdd
yennanliu/CS_basics
/leetcode_python/Recursion/flatten-binary-tree-to-linked-list.py
4,159
3.828125
4
# V0 # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/70241424 class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ res = [] self.preOrder(root, res) for i ...
dc371b1c18d68079a5884906c6afb3214d4d9b8b
yennanliu/CS_basics
/leetcode_python/Linked_list/insert_into_a_cyclic_sorted_sorted_linked_list.py
7,256
3.859375
4
""" [LeetCode] 708. Insert into a Cyclic Sorted List # Insert into a Cyclic Sorted List linspiration Problem Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to any ...
4d922d8d7f97c6d6698666afdb81ee71a1dbf62d
yennanliu/CS_basics
/leetcode_python/Heap/least-number-of-unique-integers-after-k-removals.py
9,079
3.796875
4
""" 1481. Least Number of Unique Integers after K Removals Medium Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements. Example 1: Input: arr = [5,5,4], k = 1 Output: 1 Explanation: Remove the single 4, only 5 is left. Example 2: Input: arr =...
fca70a4535a7839a4062384f7ab89e7457a2d738
yennanliu/CS_basics
/leetcode_python/Math/power-of-three.py
766
3.734375
4
# V1 class Solution(object): def isPowerOfThree(self, n): if (n ==0 or n < 0): return False while n > 1: if n%3 != 0: return False n = int(n/3) #print (n) return True # V2 # Time: O(1) # Space: O(1) # import math # class Solution(o...
803828428d751973098b8c2c4d7eb89d10aa1cd4
yennanliu/CS_basics
/leetcode_python/Linked_list/merge-k-sorted-lists.py
7,076
4.125
4
""" You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example 1: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] m...
b38734205252616feb2d2ed1a66513aaf7efd282
yennanliu/CS_basics
/leetcode_python/Design/design-file-system.py
6,924
3.921875
4
""" 1166. Design File System Medium You are asked to design a file system that allows you to create new paths and associate them with different values. The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, "/leetcode" and "/leetcode/pr...
988e8f7f206bf6c1646aa1cda857481b28a9615b
yennanliu/CS_basics
/leetcode_python/String/number-of-segments-in-a-string.py
1,325
3.984375
4
# Time: O(n) # Space: O(1) # Count the number of segments in a string, # where a segment is defined to be a contiguous # sequence of non-space characters. # # Please note that the string does not # contain any non-printable characters. # # Example: # # Input: "Hello, my name is John" # Output: 5 # V0 # V1 # http:...
821324643f5f0b06cd98c081cfa86a0d5b881c85
yennanliu/CS_basics
/leetcode_python/Hash_table/two-sum.py
4,131
3.921875
4
""" 1. Two Sum Easy Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: num...
eef77dc4cf3fa497cf3b9d22ec868e5298577113
yennanliu/CS_basics
/leetcode_python/Stack/decode-string.py
8,624
3.953125
4
""" 394. Decode String Medium Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; ...