blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c5bdd7592dd2ddc1dcc479707c8838f77cc71af8 | 7hacker/data-structures-algorithms-in-python | /leetcode/k-diff-pairs-in-an-array.py | 1,738 | 3.8125 | 4 | #
# [532] K-diff Pairs in an Array
#
# https://leetcode.com/problems/k-diff-pairs-in-an-array
#
# Easy (25.19%)
# Total Accepted: 3377
# Total Submissions: 13366
# Testcase Example: '[3,1,4,1,5]\n2'
#
#
# Given an array of integers and an integer k, you need to find the number of
# unique k-diff pairs ... |
6c8187f46ec0216cb4504f7bfd14a4654b99bfc7 | 7hacker/data-structures-algorithms-in-python | /random/stack.py | 496 | 3.8125 | 4 | '''
Get a stack by using this Lib
'''
import sys
class Stack:
def __init__(self):
self.stack = list()
return
def push(self, item):
self.stack.append(item)
return
def pop(self):
return self.stack.pop(-1)
def peek(self):
return self.stack[-1]
def si... |
e36729fae7597118279482c1777ba24efc586ea4 | 7hacker/data-structures-algorithms-in-python | /random/regExMatcher.py | 987 | 4.03125 | 4 | '''
Build a regex Matcher for . (dot matches any single char) and * (asterix matches zero or more of the preceeding char). Given a string and a pattern(that contains dot and ansterix), output True or False if the string matches the pattern. Example : c*a*b matches aab and .* matches ab
'''
def recRegExMatch(s, pattern... |
d6eb18a36a1467957d251a86762727e74107a569 | 7hacker/data-structures-algorithms-in-python | /random/getMaxQueue.py | 1,981 | 3.75 | 4 | '''
How to build a Shell-esque Prompt interface using python
'''
from cmd import Cmd
class MaxQueue:
def __init__(self):
self.q = []
self.maxq = []
def queue(self,item):
self.q.append(item)
if len(self.maxq):
if item >= self.maxq[0]:
while len(self.m... |
2d1fccbc0513c2c280722116589d30a4fef69c05 | 7hacker/data-structures-algorithms-in-python | /random/rope_cut.py | 597 | 3.828125 | 4 | '''
cut a rope of size n such that the product of the cuts is maximized atleast one cut must be made example: rope of size = 4 the best cut is 2,2 (2 * 2 = 4) as opposed to 3,1 (3* 1 = 3) or 1,3 or 1,2,1, 2,1,1, 1,1,1,1
'''
def rope_cut(size, cache):
if size <= 1:
return cache[size]
else:
maxp = 0
k = 1
for ... |
27cfca1caa02903da5e176a3ee2f189246d7b99d | 7hacker/data-structures-algorithms-in-python | /random/brackets.py | 917 | 3.578125 | 4 | '''
http://stackoverflow.com/questions/727707/finding-all-combinations-of-well-formed-brackets
'''
d = dict()
def bracketsN(n, s,d, key):
if n == 1:
mid = "(" + s + ")"
behind = "()" + s
after = s + "()"
if mid not in d[key]:
d[key].append(mid)
if behind not in... |
bfa2e3c3305c3b7c85dea45aa31e3fb71bda8bb7 | 7hacker/data-structures-algorithms-in-python | /random/K_updates.py | 969 | 3.84375 | 4 | '''
You are given the length of an array filled with all zeros initially. Now additions(updations) will be performed over given ranges on this array. Each updation will include the range and the number to be added over that range and will be of the form: [start index, end index, increment]. You have to return the final... |
7cf9c11ddf502edf158f93cdf8224733df9e1a1b | 7hacker/data-structures-algorithms-in-python | /random/sumExists.py | 882 | 3.78125 | 4 | '''
is there a contiguous subarray with a given sum in an integer array?
'''
def sumExists(a, target):
start = 0
end = 1
target_check = a[start]
while end < len(a):
if target_check == target:
print "Found! " + str(start) + "," + str(end)
return True
elif target_check > target:
target_check = target_... |
0107a92a4ff83a459676ff5fa6eebd7ec411999a | 7hacker/data-structures-algorithms-in-python | /random/queue_using_doubly_linked.py | 2,262 | 4.15625 | 4 | '''
A queue using Linked list with forward and back pointers
'''
class Node:
def __init__(self):
self.data = None
self.next = None
self.prev = None
return
class Queue:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
return
... |
f14824d42220adf8d87c4328b7522cc3ed20ebeb | 7hacker/data-structures-algorithms-in-python | /random/printAllPathsTree.py | 1,505 | 3.921875 | 4 | '''
Given a binary tree, print out all of its root-to-leaf paths one per line
'''
import sys
class Node:
def __init__(self, val=None, l=None, r=None):
self.v = val
self.l = l
self.r = r
def isLeaf(self):
if self.l is None:
if self.r is None:
return ... |
e447dd851cd4b9e5704334bb2c6b9e425225970a | 7hacker/data-structures-algorithms-in-python | /random/graph_cycle.py | 2,137 | 3.96875 | 4 | '''
detect if a graph has a cycle or not
'''
from graph import Graph
def visit(node):
print("Visiting Node :" + str(node))
return
def detectCycle(g):
'''
#using clrs method of finding cycles by marking nodes by colors:
white(0) indicates this node was never seen
gray(1) indicates this node is... |
2cdd6e6f27845ab4ed6dc8efedb6762ee4a96436 | hugochang1/Tutorial | /Programming/Python/tutorial_text/15_thread.py | 4,268 | 3.578125 | 4 | # ----------------- log for threads -----------------
from threading import Lock
_log_lock = Lock()
def log(*a, **b):
with _log_lock:
print(*a, **b)
log("123")
# 123
import threading, time, sys
# ----------------- thread -----------------
def f1():
print("f1 start")
time.sleep(0.5)
print("f1 ... |
61ef311d29445f2694b8f95fdff48840ea1b6355 | 001nalan/python | /do_slice.py | 813 | 4.3125 | 4 | 题目:利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
解题思想:如何最后一位为空格,切片除去最后一位s=s[:-1]
如果首位为空格,切片除去首位s=s[1:]
def trim(s):
if s.isspace() or not s:
return ''
while s[0] == ' ':
s = s[1:]
while s[-1] == ' ':
s = s[:-1]
return s
if trim('hello ') != 'hello':
print('测试失败!'... |
a30490e3b8a8bf120b2c3f544cd4c29a706aeedb | yhnb3/Algorithm_lecture | /기본/Cage D18/all_pword.py | 339 | 3.828125 | 4 | T = int(input())
for test_case in range(1, T + 1):
s = input()
l = len(s)
for i in range(l // 2):
if s[i] == s[l - i - 1] or s[i] == '?' or s[l - i - 1] == '?':
pass
else:
print('#{} Not exist'.format(test_case))
break
else:
print('#{} Exist'.f... |
cf078ef3ad2765e3daf45d45be0f6fd52f95d40b | alexa289/DataVisHomework | /NUCHI2018_HMW3/PyParagraph/main.py | 3,644 | 3.9375 | 4 | #Import Modules
import os
import sys
import re
#Open txt file. "test.tx is the test from the homework readme sample.
# Insert here the txt file path
txtinput = os.path.join('raw_data', 'test.txt')
txtoutput = os.path.join('raw_data', 'testoutput.txt')
with open(txtinput, 'r') as file:
file_contents = file.read()
... |
de83afd9d72b4cdaa811af099e4742230fd59fd7 | python-kurs/exercise-2-LuiseMW | /second_steps.py | 1,938 | 4.46875 | 4 | # Exercise 2
# Satellites:
sat_database = {"METEOSAT" : 3000,
"LANDSAT" : 30,
"MODIS" : 500
}
print(sat_database)
# The dictionary above contains the names and spatial resolutions of some satellite systems.
# 1) Add the "GOES" and "worldview" satellit... |
caa784dc3ae689c1a4c0ef5deaff9bfc005f6924 | shuaiqixiaopingge/leetcode | /78_subset.py | 512 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 26 16:43:11 2019
@author: LiuZiping
"""
def subSet(nums):
res = []
subset = []
if len(nums) == 0:
return res.append(nums)
size = len(nums)
_backtrack(nums,subset, 0, size, res)
return res
def _backtrack(nums, subset, begin, size, res):
... |
3ab137edf91782d915efda6520d96de864a04a8e | shuaiqixiaopingge/leetcode | /98_isValidBST.py | 1,134 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 20:51:01 2019
@author: LiuZiping
"""
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root):
"""
param: root treeNode
return: ... |
94d83843d72dba4ae50ea69087ed0c30eee8f561 | shuaiqixiaopingge/leetcode | /15_3_sum.py | 1,067 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 20:05:40 2019
@author: LiuZiping
"""
def threeSum(nums):
length = len(nums)
if length <= 2:
return None
res = []
nums.sort()
for i in range(length - 2):
if nums[i] == nums[i - 1]:
continue
tmp = nums[i+1:]
... |
daaa293f3e8448a5712fd7284cc689c4bf343f76 | ceuity/deep_learning | /ReLU_function.py | 279 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 20:37:50 2020
@author: EVer
"""
import numpy as np
import matplotlib.pylab as plt
def relu(x):
return np.maximum(0, x)
x = np.arange(-5.0, 5.0, 0.1)
y = relu(x)
plt.plot(x, y)
plt.ylim(-0.1, 5.1)
plt.show() |
c13089f2a1caba2888a4d317599081928bb05e95 | Alexanderamiri/Golden-voyage | /IN3110/assignment5/coloring_example.py | 644 | 4.28125 | 4 | import sys
def color_print(text, code=5):
"""
Prints a piece of text in a fancy way. What fancy means depends on the
keyword argument code. Some possibilities are:
0;1: bold text
0;3: italics
0;4: underline
0;5: blinking text (only sane default)
0;7: "inverted" text
0;92: gre... |
6b901a2280c53e6b1e05c7b8e9e5b4f2b18a303f | Alexanderamiri/Golden-voyage | /IN3110/assignment4/Blur/blur_2.py | 1,134 | 3.5625 | 4 | import cv2
import time
from numpy import array, pad
def numpyblur(image): # Numpy implementation
"""A blur function to blur a specifically one part of an image with Numpy
Args:
image (uint32): padded source image
Returns:
A Blurred image of the source image
"""
image = pad(image,... |
89b33584f8cc30382d48a468bb49f05832465df5 | wcm95/Coursera_Algorithm | /DivideConquer/select.py | 1,499 | 3.5 | 4 | from merge_sort import merge_sort
def partition(x, start, end, p):
pivot = x[p]
swap(x, start, p)
i = start
for j in range(start, end-1):
if int(x[j+1])<=int(pivot):
swap(x, j+1, i+1)
i += 1
swap(x, start, i)
return i
def swap(x, i, j):
temp = x[i]
x[i]... |
ba8d38e05d6a4fa0a8dbd288a2eebfe9b2dc42d3 | wcm95/Coursera_Algorithm | /Graphs/DFS.py | 1,342 | 3.59375 | 4 |
# Contains topological ordering.
def dfs_loop(graph):
v = list(graph.keys())
n = len(v)
path= []
# We have to use mutable object like list to store the current number.
curr = [n]
ordering = dict(zip(v, [n]*n))
visited = dict(zip(v, [False]*n))
for vi in v:
if not visited[vi]:
... |
e6063c8329b85fd3f866c890ad4f2260be01041d | wcm95/Coursera_Algorithm | /DivideConquer/quick_sort.py | 1,750 | 3.75 | 4 | import numpy as np
from select import select
def choose_pivot_random(x, start, end):
from numpy.random import choice
np.random.seed(1)
return choice(range(start, end))
def choose_pivot_first(x, start, end):
return start
def choose_pivot_last(start, end):
return end-1
def choose_pivot_median3(x):... |
44dab3572beee4de8bbf156d6342a0de53d2768b | TaurusCanis/ace_it | /ace_it_test_prep/static/scripts/test_question_scripts/math_questions/math_T1_Q7.py | 2,995 | 3.96875 | 4 | import random, math
rand_num = random.randint(3,9)
plus_minus = random.choice([.5, -.5])
second_num = rand_num + plus_minus
lower_time_limit = min(rand_num, second_num)
upper_time_limit = max(rand_num, second_num)
miles = math.floor(second_num) * random.randint(4,8) * 10
question = f"<p>A truck driver took between {... |
fa0216f12650df115d26f372987bc7b5053581ed | TaurusCanis/ace_it | /ace_it_test_prep/static/scripts/test_question_scripts/math_questions/math_T1_Q8.py | 1,479 | 3.59375 | 4 |
question = "<p>When \\(r+s=13\\) and \\(2t+s=13\\) , what is the value of \\(t\\)?</p>\n",
options = [
{
"label":"13",
"value":"0"
},
{
"label":"5",
"value":"1"
},
{
"label":"-5",
"value":"2"
},
{
"label":"-7",
"value":"3"
},
{
"label":"It cannot be determined from the information given.... |
6c7ae910e86d8b523ef7c59f9b3161554645baac | StevenBryceLee/DS-Unit-3-Sprint-2-SQL-and-Databases | /module4-acid-and-database-scalability-tradeoffs/map_reduce.py | 359 | 3.609375 | 4 | from functools import reduce
my_list = [1,2,3,4]
# Coke classic
ssv = (sum([val for val in my_list])) / len(my_list)
# Coke, map_reduce flavor
squared_map = list(map(lambda x: x ** 2, my_list))
# Func for reduce
def mean(x1, x2):
return sum(x1 + x2) / 2
squared_reduce = reduce(mean, squared_map)
print(ssv)
pr... |
0a97bafd7b13e7207c33fed5061fd7306742bfc3 | terpator/study | /Списки/domashka_4.py | 656 | 4.15625 | 4 | """
Представьте в виде списка списков матрицу
[ 1, 2 , 3, 4]
[ 5, 6 , 7, 8]
[ 9,10, 11, 12]
[13,14, 15, 16]
Напишите программу, которая выведет эту матрицу на экран, вычислит и выведет сумму
элементов этой матрицы.
"""
mylist = [[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
for element i... |
76e15d2e684032771c75ae36e159b7e1c6ed3a3c | terpator/study | /Строки/domashka_5.py | 423 | 4.0625 | 4 | """
Вводится строка из слов, разделенных пробелами. Найти самое длинное слово и
вывести его на экран.
"""
text = input("Введите текст: ")
mylist = text.split()
longest = mylist[0]
for elem in mylist:
if len(elem) > len(longest):
longest = elem
print("Самое длинное слово: ", longest)
|
21ac676a2bd7eadca5718226bdb89e6a3dac7f43 | terpator/study | /Строки/domashka_3.py | 344 | 3.96875 | 4 | """
Напишите программу, которая вычислит сумму всех кодов символов строки.
"""
text = input("Введите строку:")
summa = 0
for char in text:
summa = summa + ord(char)
print("Сумма всех кодов символов строки равна ", summa)
|
d6af0d15b6e8e7d47ce7b24c267b15893a7943c5 | terpator/study | /Декораторы классов/domashka_10_2.py | 632 | 4.21875 | 4 | """
Создайте декоратор класса с параметром. Параметром должна быть
строка, которая должна дописываться (слева) к результату работы метода
__str__.
"""
def dec(text):
def inner(cls):
def __str__(self):
return text + " " + str(self.__str__)
cls.__str__ = __str__
retu... |
8a8411553e7d6d1bb76b2eeb20ba82e5097a2533 | terpator/study | /Кортежи и множества/domashka_2.py | 834 | 4.125 | 4 | """
Напишите программу, которая сгенерирует два списка. Один с числами кратными
3, другой с числами кратными 5. С помощью множеств создайте список с числами,
которые есть в обоих множествах.
"""
list_3 = []
list_5 = []
for i in range(1,50):
if i % 3 == 0:
list_3.append(i)
if i % 5 == 0:
... |
d1f17694cb4879e66102240fa2cad1afca750f47 | terpator/study | /Строки/domashka_4.py | 356 | 4.15625 | 4 | """
Выведите на экран 10 строк со значением числа Pi. В первой строке должно быть
2 знака после запятой, во второй 3 и так далее.
"""
import math
for i in range(10):
print("Число Pi равно {Pi:.{num}f}".format(Pi = math.pi, num = i + 2))
|
c45887de856fe35a493b592421572964c7aaff4c | terpator/study | /Функции. Часть 1/domashka_1.py | 487 | 3.953125 | 4 | """
Напишите функцию, которая вернет максимальное число из списка чисел.
"""
import random
def maxcalc(list_1):
maxnumber = list_1[0]
for num in list_1:
if num > maxnumber:
maxnumber = num
return maxnumber
mylist = []
for i in range(10):
mylist.append(random.randi... |
e0159b019e89e0b7147dd86dabeb1476e0ac8caa | terpator/study | /Словари/dop_domashka_2.py | 813 | 4.21875 | 4 | """
Напишите программу, которая переведет целое число (от 1 до 100) из римской
записи в обычные цифры.
Например: XXII -> 22
Подробнее: https://en.wikipedia.org/wiki/Roman_numerals
"""
number = int(input("Введите число от 1 до 100: "))
digits = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
ten... |
78a1d9fe7dfaeae16c8b2b2dc11cc38a46aaabba | terpator/study | /Условные операторы/dop_domashka_3.py | 968 | 4.28125 | 4 | """
Дано четырехзначное число. Проверить, является ли оно «счастливым билетом».
Примечание: счастливым билетом называется число, в котором, при четном
количестве цифр в числе, сумма цифр его левой половины равна сумме цифр его
правой половины. Например, рассмотрим число 1322. Его левая половина равна
13, а правая ... |
51f980fb1e4f8869981de0a9327b8951fc20faf0 | terpator/study | /Управление полями класса. Дескрипторы/domashka_11_2.py | 1,024 | 4.125 | 4 | """
Реализуйте функционал, который будет запрещать установку полей класса
любыми значениями, кроме целых чисел. Т.е., если тому или иному полю
попытаться присвоить, например, строку, то должно быть возбужденно
исключение.
"""
class AppleTree:
def __init__(self, __age):
self.__age = __age
... |
610cc954bd38601bba5549f5c135abd0e64c68fc | Bal983/cmpt317A1 | /scripts/car.py | 6,503 | 3.765625 | 4 | # _______________libraries_______________
import search
class Car:
# _______________attributes______________
# identifier - a numeric identifier for the car
# garageLocation - the coordinates of the garage location i.e. where the car starts and ends its route
# packageList - a list of packages for... |
60dbc2000be99f947052d5217957987e62652bb7 | theishshah/aoc2017 | /day3/day3.py | 940 | 3.5 | 4 | import math
def spiral_boi(num):
side_len = int(math.sqrt(num))
if side_len%2==0:
side_len += 1
else:
side_len += 2
v_dist = (side_len)/2
#off = (side_len*side_len)-num
off = num - (side_len - 2) **2
while off>side_len:
off -= side_len
h_dist = v_dist - off
... |
85b38bfc1844358dd3ddc385df579e81a8125889 | Bhavana03/Wise_elite | /Hacker rank Problems/twins.py | 465 | 3.625 | 4 | import math
def solve(n, m):
count = 0
for val in range(n,m):
if isprime(val):
if isprime(val + 2):
count = count + 1
print(val)
print(val+2)
return count
def isprime(num):
count = 0
for i in range(2,int(math.sqrt(num))+1):
... |
346293d4cd9d18baccb1d5ac378b53129cb16cd4 | Tang8560/Geeks | /Algorithms/1.Searching and Sorting/04.Interpolation_Search/Interpolation_Search.py | 802 | 3.640625 | 4 | The formula for pos can be derived as follows.
# Let's assume that the elements of the array are linearly distributed.
# General equation of line : y = m*x + c.
# y is the value in the array and x is its index.
"""
Now putting value of lo,hi and x in the equation
arr[hi] = m*hi+c ----(1)
arr[lo] = m*lo+c ----(2)
x =... |
2656ce6ad3050250f3cad447dd7cb59fed0e0025 | neela12345/neela | /python class ,objects,inheritance,polymorphism/polymorphsm with inheritance.py | 462 | 3.671875 | 4 | class bird:
def intro(self):
print('there are different types of birds')
def flight(self):
print('most of the birds can fly but some cannot')
class parrot(bird):
def flight(self):
print('parrots can fly')
class penguin(bird):
def flight(self):
print('penguin can... |
494308149c67f91a07aab07b37c5b149479fe8bb | MingiPark/BaekJoon-Python | /Dynamic Programming/9465.py | 702 | 3.5 | 4 | if __name__ == "__main__":
testCase = int(input())
for _ in range(testCase):
length = int(input())
col1 = [0] + list(map(int, input().split(' ')))
col2 = [0] + list(map(int, input().split(' ')))
case = list(zip(col1, col2))
value = [[0]*3 for _ in range(lengt... |
a3ace100d4e5c209e312001b40b498e9e11e4b40 | MingiPark/BaekJoon-Python | /Dynamic Programming/2156.py | 529 | 3.703125 | 4 | if __name__ == "__main__":
glass = int(input())
quantity = [0] * (glass + 1)
check = [0] * (glass + 1)
for i in range(1, glass + 1):
quantity[i] = int(input())
check[1] = quantity[1]
if glass >= 2:
check[2] = quantity[1] + quantity[2]
for j in range(3, glass ... |
7bab1249a877aa1ea0e4c443014a2e94dce136e7 | apapadoi/Numerical-Analysis-Projects | /First Project/Exercise1/secant.py | 2,650 | 4.4375 | 4 | def secant(f, x0, x1, eps=5e-6, max_iterations=50):
"""
Function that finds a root using Secant method for a given function f(x). The function finds the root of f(x)
with a predefined absolute accuracy epsilon. The function excepts two starting points x0,x1 that belong to an
interval [a,b] in which is k... |
43d1a69b41b5885e4a40f69a88c69d65553013cd | apapadoi/Numerical-Analysis-Projects | /First Project/Exercise1/newton_raphson.py | 2,505 | 4.4375 | 4 | def newton_raphson(f, fprime, x0, eps=5e-6, max_iterations=50):
"""
Function that finds a root using Newton's iteration for a given function f(x) with known derivative f'(x).
The function finds the root of f(x) with a predefined absolute accuracy epsilon. The function excepts a
starting poin... |
ee3a27bdc3816bfb583d5fabb7712bac62dd91f5 | ParthShirolawala/PythonAssignments | /Assignment3_ParthShirolawala/Question3a.py | 333 | 3.890625 | 4 | #Implement Bubble sort
input_list = [5,7,2,1,4,29,15]
n = len(input_list)
def bubblesort(input_list):
for i in range(n):
for j in range(n-i-1):
if input_list[j] > input_list[j+1]:
input_list[j], input_list[j+1] = input_list[j+1], input_list[j]
print input_list
bubblesor... |
ae2a954f82fd30184028c20cca11abf77f896cff | xiaonanln/myleetcode-python | /src/132. Palindrome Partitioning II.py | 1,197 | 3.59375 | 4 | """
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
"""
class Solution(object):
def minC... |
19445853768178e9aa80bf8ae19771757afb0954 | xiaonanln/myleetcode-python | /src/303. Range Sum Query - Immutable.py | 586 | 3.546875 | 4 | class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.accums = []
accum = 0
for n in nums:
accum += n
self.accums.append(accum)
print self.accums
def sumRange(self, i, j):
"""
:type ... |
eb8c2c7ee6a692a9a6846de52a596c813a21d97a | xiaonanln/myleetcode-python | /src/671. Second Minimum Node In a Binary Tree.py | 713 | 3.796875 | 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 findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
inf = float('inf')
def smv(root... |
9b5d37819fccbb05bee1ad2d57e4acddad14fca6 | xiaonanln/myleetcode-python | /src/86. Partition List.py | 714 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
shead, stail = None, None
gehead, getail = None, ... |
bb796278a517b6f90f53ab0ce193f423db63822d | xiaonanln/myleetcode-python | /src/Maximum Subarray.py | 469 | 3.5625 | 4 | # file encoding: utf8
class Solution:
# @param A, a list of integers
# @return an integer
def maxSubArray(self, A):
resultS = None
R = []
S = 0
for n in A:
if S < 0:
R = []
S = 0
S += n
R.append(n)
if resultS is None or result... |
9e02ec051f37fcd28117153b83b6ec87c7be5dae | xiaonanln/myleetcode-python | /src/Remove Nth Node From End of List.py | 583 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
if head is None: return None
nodes = []
p = head
while p :
... |
9b8be796b35c7b79a47976c9b052f12ebd480cee | xiaonanln/myleetcode-python | /src/690. Employee Importance.py | 702 | 3.71875 | 4 | """
# Employee info
class Employee(object):
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
... |
61b3b9d3bc0e6060e6e7091fa18b9cfcb01ada1c | xiaonanln/myleetcode-python | /src/124. Binary Tree Maximum Path Sum.py | 708 | 3.765625 | 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 __init__(self):
self.res = float('-inf')
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
""... |
4dcee4574f4da9239b83d4ff57ebfc237408465c | xiaonanln/myleetcode-python | /src/971. Flip Binary Tree To Match Preorder Traversal.py | 1,383 | 3.609375 | 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 flipMatchVoyage(self, root, voyage):
"""
:type root: TreeNode
:type voyage: List[int]
:rtype: List[int]
"""
... |
e8896dd4685846a29f6ae34a450cb02772fe7722 | xiaonanln/myleetcode-python | /src/Swap Nodes in Pairs.py | 793 | 3.703125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
dummy = ListNode(0)
p = dummy
while head:
if head.ne... |
d421449cd54f297506906cf8fe514c480bfcb974 | xiaonanln/myleetcode-python | /src/1008. Construct Binary Search Tree from Preorder Traversal.py | 693 | 3.796875 | 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 bstFromPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: TreeNode
"""
return self._constructPreorder(preorder, 0, len(preorder... |
04cc1229932e0fd86ca2ab51c622cbd980b540b6 | xiaonanln/myleetcode-python | /src/334. Increasing Triplet Subsequence - 2.py | 366 | 3.515625 | 4 | class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
a, b = float('inf'), float('inf')
for n in nums:
if n < a: a = n
elif n > a and n < b:
b = n
elif n > b:
return True
return False
print Solution().increasingTriplet([1, 2, 3, 4, 5])
p... |
b10ec4280dcabe1a5ed2108327ed619b12e43dd2 | xiaonanln/myleetcode-python | /src/Unique Binary Search Trees.py | 541 | 3.5 | 4 | class Solution:
# @return an integer
def numTrees(self, n):
R = [0] * max((n + 1), 3)
R[0] = 1
R[1] = 1
R[2] = 2
for i in xrange(3, n+1):
tr = 0
for h in xrange(0, i):
ln = h
rn = i - h - 1
# ... |
6f77f845c58a8d91278d50fc6f71444fd8e9b458 | xiaonanln/myleetcode-python | /src/224. Basic Calculator.py | 1,348 | 3.515625 | 4 | from collections import deque
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = deque()
ri = 0
while True:
tok, ri = self.readNext(s, ri)
if tok is None:
break
# print 'tok', tok
if isinstance(tok, int):
if not stack or stack[-1] not in '+-':
... |
41f5d24566f501d831d03384bb208bf341da9b4c | xiaonanln/myleetcode-python | /src/2. Add Two Numbers.py | 679 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from utils import ListNode, makelist, printlist
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
... |
1ee0c54d3df59454033db3b88d2e42e2d3eda7e9 | xiaonanln/myleetcode-python | /src/Palindrome Number.py | 842 | 3.828125 | 4 | class Solution1: # Accepted
# @return a boolean
def isPalindrome(self, x):
if x < 0: return False
smallDiv = 1
bigDiv = 1
while bigDiv * 10 <= x:
bigDiv *= 10
while bigDiv > 1:
bigd = x // bigDiv
smalld = x % 10
... |
496da86fbab665426ef6f7e1fb6ed55118a33c59 | xiaonanln/myleetcode-python | /src/306. Additive Number.py | 1,671 | 4.28125 | 4 | """
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
For example:
"112358" is an additive number because the digits can fo... |
3158bf9d2c7eb222af1ff28cfc93b0216446664c | xiaonanln/myleetcode-python | /src/285. Inorder Successor in BST.py | 719 | 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):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
if p.right... |
99e4213b366c7f3391b2cb5c804b88b973eaa9b9 | aadidubey7/python | /searching/binary-search.py | 845 | 4.03125 | 4 | def binarySearch(myItem, myList):
boolFound = False
bottom = 0
top = len(myList) - 1
intCount = 1
while bottom <= top and not boolFound:
middle = (bottom + top) // 2
if int(myItem) == int(myList[middle]):
boolFound = True
#print('found', myItem, 'at', middle, ... |
5342b43d5a2df7b4aef8d696ff2a649a28b27386 | zhaoyanbin123/PyCharmProgram | /testdemo/testdemo1/demo01.py | 254 | 3.71875 | 4 | # coding=utf-8
def format_str(s):
return s[:1].upper() + s[1::].lower()
print map(format_str, ['adam', 'LISA', 'barT'])
def format_str_1(s):
return s.capitalize()
print map(format_str, ['adam', 'LISA', 'barT'])
for i in [1,2,3]:
print i, |
28366dccbdbfa54399723373c24167e3b721ca1c | djcroissant/toy_problems | /string_permutation/string_permutation.py | 1,579 | 3.71875 | 4 | import string
class Solution():
"""
Input: two strings
Output: True if they are permutations of each other; Else False
Assumptions:
* Blank spaces are ignored
* Capitalization is ignored
* Duplicate letters are NOT ignored
* Punctuation is ignored
Examples:
Input: ["tacos... |
bc73a7e35b86ab8efc564c576c84bc232b0984fc | alirezahi/AlgorithmDesign | /Palindromic Square/Main.py | 1,013 | 3.625 | 4 | # def base10toN(num, base):
# converted_string, modstring = "", ""
# currentnum = num
# if not 1 < base < 21:
# return '0'
# if not num:
# return '0'
# while currentnum:
# mod = currentnum % base
# currentnum = currentnum // base
# converted_string = chr(48 + ... |
0055b03b22f7ba6ae9f1a78003da904db278ce1e | Beegie01/CALCULATOR | /calcapp.py | 1,298 | 4 | 4 | from simple_calc_OOP import *
from datetime import datetime
print('\n'*5, '\t\t\tOSAGIE CALC 2021')
print('\n'*2, '{t}\t\t\t{d}'.format(d=datetime.date(datetime.today()), t=datetime.time(datetime.today())))
# calculator is on
# calculator screen is set
calc = Calc()
CALCULATING = True
while CALCULATIN... |
a973388c55981d075f5cc3f90c014e8a6d674a91 | zhinan18/Python3 | /code/base/lesson11/11-9.py | 436 | 3.71875 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
my_ball = pygame.image.load("beach_ball.png") # load the image from a file
screen.blit(my_ball, [50, 50]) # draw or 'blit' it to the screen
pygame.display.flip()
running = True
while running:
... |
677d8b80490ef3728343a5103b5566d5cd3e08f9 | zhinan18/Python3 | /code/base/secret.py | 787 | 3.859375 | 4 | import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ("AHOY! I'm the Dm,.read Pirate Roberts, and I have a secret!")
print ("It is a number from 1 to 99. I'll give you 6 tries. ")
while guess != secret and tries < 6:
try:
guess = input("What's yer guess? ")
if int(guess) < secre... |
594a853f93f6826bf4c417922d823cc9ebad8417 | zhinan18/Python3 | /code/base/lesson19/circleai.py | 506 | 3.765625 | 4 | """
AI Name: Circle AI
Made by: Carter
Strategy: Drive in circles. Attack any robot in your path.
"""
class AI:
def __init__(self):
self.isFirstTurn = True
def turn(self):
if self.isFirstTurn:
self.robot.turnRight()
self.isFirstTurn = False
elif self.robot.... |
f4dc4ba5067ba2603cb351d72db6054763b35eb8 | zhinan18/Python3 | /code/base/lesson10/10-7.py | 454 | 3.609375 | 4 | class Game_object:
def __init__(self, name):
self.name = name
def pickUp(self):
pass
# put code here to add the object
# to the player's collection
class Coin(Game_object):
def __init__(self, value):
Game_object.__init__(self, "coin")
self.value = value
def spend(self, bu... |
77b1f5003adaf63fe989f1ab6de6b44a2da741e6 | zhinan18/Python3 | /code/base/lesson7/Listing_11-7.py | 932 | 3.84375 | 4 | dog_cal = 140
bun_cal = 120
ket_cal = 80
mus_cal = 20
onion_cal = 40
print("\tDog \tBun \tKetchup\tMustard\tOnions\tCalories") # print headings
# nested loops
count = 1
for dog in [0, 1]: # dog is the outer loop
for bun in [0, 1]:
for ketchup in [0, 1]:
for m... |
cd4de16b1308a2d25208d25cbb737fa741d0737b | zhinan18/Python3 | /code/base/lesson19/randomai.py | 470 | 3.796875 | 4 | """
AI Name: Random AI
Made by: Carter
Strategy:
Move around randomly.
Attack any robot in front of you.
"""
import random
class AI:
def __init__(self):
# Anything the AI needs to do before the game starts goes here.
pass
def turn(self):
if self.robot.lookInFront() == "bot":
... |
af3066e6c84e5193c65c887c695fc5ecbfc9ec55 | zhinan18/Python3 | /code/base/lesson8/try-4.py | 353 | 4.0625 | 4 | names = [] # 初始化列表
#print("Enter 5 names (press the Enter key after each name)")
for i in range(0, 5): #输入5个名字
names.append(input("add name"))
print("The name are " + names.__str__())
replace = int(input("Which one ?(1,5):"))
newName = input("New name:")
names[replace - 1] = newName
print("The name are " + names.... |
65ec4c5a6ea583448812e081ecfce3dcde121f11 | annagorbunova029/lesson1 | /info.py | 341 | 3.953125 | 4 | # lists = [3,5,7,9,10.5,'Python']
# print (len(lists))
# print (lists[0])
# features = {"city":"Москва",
# "temperature":20}
# print (features ["temperature"]-5)
# print(features)
# print(features.get("country"))
# print(features.get("Country","Россия"))
# features["date"]="27.05.2019"
# print(features)
# print(len(fe... |
ebca989f950cca9a7073c3d4049d1d7ab1225ef4 | xDannyCRx/Daniel | /DB.py | 248 | 3.640625 | 4 | import sqlite3
conn=sqlite3.connect('user.db')
c=conn.cursor()
c.execute('CREATE TABLE user(name text, age integer)')
c.execute('INSERT INTO user VALUES("user A" , 42)')
conn.commit()
c.execute('SELECT * FROM user')
print(c.fetchall())
conn.close() |
3acb521e79343ebfce817717a1a23c37afb54eee | xDannyCRx/Daniel | /Software profe.py | 310 | 3.796875 | 4 | option=int(input('Estudiantes registrados por nombre \n Agregar \n Si=' ))
lista=[]
while True:
if option == 1:
Nombre=input(' Nombre:')
Clase=input('Aula:')
lista.append=(Nombre)
lista.append=(Clase)
if option == 2:
break
print('Registro') |
2f035c48b0ba928ea2995cbeac4754a0c8405721 | mutahirqureshi/islam-buddy | /gmaps_API.py | 1,243 | 3.890625 | 4 | import requests
import json
_GMAPS_API_GEOCODE_URL = 'https://maps.googleapis.com/maps/api/geocode/json'
_GMAPS_API_GEOCODE_KEY = 'AIzaSyBC9cKscPGfI0Ge0uPJxO29ru0qLvxfcdA'
def GetGeocode(city, state, country):
"""Gets the longitude and latitude from the Google Maps Geocode API.
Performs a POST request on the Go... |
9f3ef021dd176dfbe562df866b3a4d9f2019a0d7 | huynhnhathao/python_monty_hall_simulation | /birthday.py | 529 | 3.921875 | 4 | import numpy as np
def birthday_problem(num_people: int, n: int, ) -> float:
"""
Randomly sample num_people peoples birthday from 1 to 355 n times and return the ratio of
birthday match/n
"""
count = 0
for i in range(0,n):
sample = np.random.randint... |
c89b7207e1e780bf062d36d28a477a766f7ccc93 | toledosuperman/Python-Lab | /week9quest6.py | 461 | 3.84375 | 4 | def vowels(v):
v = 0;
c = 0;
for char in v:
if ((ord(char) >= 65 and ord(char) <= 90) or (ord(char) >= 97 and ord(char) <= 122)):
if (char== 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u' or char == 'A' or char == 'E' or char== 'I' or char == 'O' or char == 'U'):
... |
df2ab450b235c0d34dbe741f5aeab93e252cbc5c | benbendaisy/CommunicationCodes | /python_module/examples/402_Remove_K_Digits.py | 1,312 | 3.65625 | 4 | class Solution:
"""
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
Example 1:
Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to... |
092be2bfaa172e778b0bba7ae4d24bc21d633aad | benbendaisy/CommunicationCodes | /python_module/examples/442_Find_All_Duplicates_in_an_Array.py | 817 | 4.125 | 4 | from typing import List
class Solution:
"""
Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses on... |
dc7dc183d35a17cb6d5cc79b1ca456d9941706c3 | benbendaisy/CommunicationCodes | /python_module/examples/2300_Successful_Pair_of_Spells_and_Potions.py | 1,686 | 4.15625 | 4 | from typing import List
class Solution:
"""
You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.
You are also given an integer success. A spe... |
5c2a65b2bdef80ce85727cb454ccfb24d9034d53 | benbendaisy/CommunicationCodes | /python_module/examples/692_Top_K_Frequent_Words.py | 1,768 | 3.984375 | 4 | import heapq
from collections import Counter
from typing import List
class Pair:
def __init__(self, word, freq):
self.word = word
self.freq = freq
def __lt__(self, p):
return self.freq < p.freq or (self.freq == p.freq and self.word > p.word)
class Solution:
"""
Given an a... |
776bb43643b1252624fec5f73f42c8a3a074221d | benbendaisy/CommunicationCodes | /python_module/examples/214_shortest_palindrome.py | 438 | 3.703125 | 4 | class Solution:
def shortestPalindrome(self, s: str) -> str:
if not s or len(s) <= 1:
return s
reversed_string = s[::-1]
for i in range(0, len(s)):
if s[: len(s) - i] == reversed_string[i:]:
return reversed_string[:i] + s
return ""
if __name... |
ddb9415a35d4f931bf1eaa985df255054876833f | benbendaisy/CommunicationCodes | /python_module/examples/64_Minimum_Path_Sum.py | 1,028 | 4 | 4 | from typing import List
class Solution:
"""
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
Input:... |
6329bd3dff8a0d6dc87e24cdd4476326d8a22626 | benbendaisy/CommunicationCodes | /python_module/examples/491_Non-decreasing_Subsequences.py | 1,438 | 4.09375 | 4 | from typing import List
class Solution:
"""
Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.
Example 1:
Input: nums = [4,6,7,7]
Output: [[4,6],[4,6,7],... |
e6ef1066747da1602d950734b19db28f40443733 | benbendaisy/CommunicationCodes | /python_module/examples/907_Sum_of_Subarray_Minimums.py | 2,927 | 3.65625 | 4 | import math
from typing import List
class Solution:
"""
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
Example 1:
Input: arr = [3,1,2,4]
Output: 17
... |
f67d364994c207046473a17f9703633b560fb054 | benbendaisy/CommunicationCodes | /python_module/examples/398_Random_Pick_Index.py | 1,441 | 4.1875 | 4 | import random
from collections import defaultdict
from typing import List
class Solution:
"""
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Implement the Solution class... |
a9587524a9461021fb06314deac7ce7782f337fe | benbendaisy/CommunicationCodes | /python_module/examples/87_Scramble_String.py | 2,355 | 4.125 | 4 | class Solution:
"""
We can scramble a string s to get a string t using the following algorithm:
If the length of the string is 1, stop.
If the length of the string is > 1, do the following:
Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x an... |
6bbf5b3a7fe1d636a62734d92b1abe23411ec2e9 | benbendaisy/CommunicationCodes | /python_module/examples/1345_Jump_Game_IV.py | 2,364 | 3.953125 | 4 | from collections import defaultdict, deque
from typing import List
class Solution:
"""
Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:
i + 1 where: i + 1 < arr.length.
i - 1 where: i - 1... |
b42d6f290fe5bf8f13294c708d683506e8309e67 | benbendaisy/CommunicationCodes | /python_module/examples/876_Middle_of_the_Linked_List.py | 913 | 4.21875 | 4 | # Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
"""
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle... |
a9525dc26f1c5ebe9d56d9d155ff67688d168582 | benbendaisy/CommunicationCodes | /python_module/examples/444_Sequence_Reconstruction.py | 3,178 | 4.125 | 4 | from collections import defaultdict, deque
from typing import List
class Solution:
"""
You are given an integer array nums of length n where nums is a permutation of the integers in the range [1, n]. You are also given a 2D integer array sequences where sequences[i] is a subsequence of nums.
Chec... |
35a4cea8a3f831af8900ded785c9b81b73d26573 | benbendaisy/CommunicationCodes | /python_module/examples/785_Is_Graph_Bipartite.py | 1,467 | 3.65625 | 4 | from typing import List
class Solution:
def isBipartite1(self, graph: List[List[int]]) -> bool:
n = len(graph)
color = [-1] * n
for node in range(n): # handle forrest (graph)
if color[node] == -1: # if there is a node that is not visited
stack = [node] # check g... |
b99a7b6247e947d81e7aad223f8d0505e54c7014 | benbendaisy/CommunicationCodes | /python_module/examples/445_Add_Two_Numbers_II.py | 2,919 | 4.03125 | 4 | # Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
"""
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes f... |
d0016a588fd3d62cc6587535572c354707cd3394 | benbendaisy/CommunicationCodes | /python_module/examples/337_House_Robber_III.py | 1,681 | 4.125 | 4 | # Definition for a binary tree node.
from functools import lru_cache
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
The thief has found himself a new place for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.