blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8a10bbe5993e067ad7c4e05f3afb6f12f898ebcc | Ktsunezawa/Python-practice | /3step/1003/myclass.py | 534 | 3.59375 | 4 | class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
def bmi(self):
result = self.weight / (self.height*self.height)
print(self.name, 'のBMI値は', result, 'です。')
class BusinessPerson(Person):
def __init__(s... |
b46fa4ef979dd954dd3a0f4abc67a8dcdb693897 | Ktsunezawa/Python-practice | /3step/0803/date.py | 388 | 3.765625 | 4 | import datetime
today = datetime.date.today()
print('今日', today, 'です。')
birth = datetime.date(today.year, 6, 25)
ellap = birth - today
if ellap.days == 0:
print('今日は誕生日です!')
elif ellap.days > 0:
print('今年の誕生日まで、あと', ellap.days, '日です。')
else:
print('今年の誕生日は、', -ellap.days, '日、過ぎました。')
|
8209ce9707bf756f96a841aebf7e65cb8d719704 | snake-enthusiasts/obstacles | /ship.py | 2,809 | 3.90625 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""A class to manage the ship."""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
se... |
86013c6ed62eff4ef8fac4d5e3cadab1efec86ed | SyeedHasan/DesignPatterns_Stores | /BuilderPattern.py | 2,984 | 3.515625 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod, abstractproperty
from typing import Any
class ManufacturerBuilder(ABC):
@abstractproperty
def product(self) -> None:
pass
@abstractmethod
def gatherRawMaterials(self) -> None:
pass
@abstractmethod
def sti... |
44cc5b20276024979f97fb31cd221b90ba78e351 | Mahdee14/Python | /2.Kaggle-Functions and Help.py | 2,989 | 4.40625 | 4 | def maximum_difference(a, b, c) : #def stands for define
"""Returns the value with the maximum difference among diff1, diff2 and diff3"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
#If we don't include the 'return' keyword in a function that requires... |
22e1c292651076f8759e3c02be9d3be87ddab629 | latesandras/presentation | /guess_the_number.py | 514 | 4.09375 | 4 | # guess the number.
import random
random_num = random.randint(1,10)
tipp = -1
for i in range(0,10):
print("You have " + str(10 - i) + " try/tries left!")
tipp = int(input("Guess a number between one and ten!"))
if random_num == tipp:
print("YOU WIN!")
break
else:
print("T... |
1d3d1673beb1ab9484b4d54ee3bdd683830f3cf5 | dhanushkumar317/SmallProjects | /Remember the Number.py | 6,558 | 4.0625 | 4 | import random
print ("Welcome to the AkTech's new hit game. The game is simple. You are going to enter a number, add to tour previous number and remember it.\n" \
"For example if you said 3 you are going to type 3. on the next turn if you say 4 you are going to type 34. Good Luck :)\n")
class Number:
def __i... |
f7431a123608494028fcd31dfaea3544e0ba0302 | dhanushkumar317/SmallProjects | /Rock Paper Scissors.py | 2,220 | 4.0625 | 4 | import random
shapes = {"s": "✂", "p": "📄", "r": "🤘"}
def gameLogic():
print("Welcome to classic awesome Rock Paper Scissor.\nChoose a shape by entering its initial.\nEx r for Rock, s for Scissors and p for paper.\nGood luck :)\n")
playerName = input("Please enter your name: ").capitalize()
print("")
... |
f2fb8d9fecc42564d788534f7106dd30a189a5d4 | ajitnak/py_pgms_heap | /kth_closest_pts.py | 892 | 3.546875 | 4 | import heapq
class PointWithD:
def __init__(self, vertex, cord):
self.point = cord
self.dist = (cord[0]-vertex[0])**2 + (cord[1]-vertex[1])**2
def __cmp__(self, other):
return -cmp(self.dist, other.dist)
def kth_closest(vertex, points, k):
points_with_d = [PointWithD(vertex, point) for point in points]
... |
5497d0f4486bff95cff9edbba6cd4ddeef10e62c | luhang/pythonsample | /chap04/sec02/saveToZip.py | 2,876 | 3.625 | 4 | import zipfile, os # zipfileとosモジュールのインポート
def save_zip(folder):
'''
指定されたフォルダーをZIPファイルにバックアップする関数
folder : バックアップするフォルダーのパス
'''
# folderをルートディレクトリからの絶対パスにする
folder = os.path.abspath(folder)
# ZIPファイル末尾に付ける連番
number = 1 # 初期値は1
# ①バックアップ用のZIPファイル名を作成する部分
# ZIPファイル名を作成して、既存... |
edaec0f5fdd64b4e85959a15f9845c7790ff136d | wsqy/python_scripts | /codewars/0011.PI approximation.py | 1,964 | 3.5625 | 4 | """
The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using the following infinite series (Leibniz 1646–1716):
PI / 4 = 1 - 1/3 + 1/5 - 1/7 + ... which gives an approximation of P... |
f6ce6c42eabd1a2e6b8e3f7a8c292342da548e35 | Marce104lmeida/uni-dimob | /main.py | 1,121 | 3.703125 | 4 | # Autor: Marcelo Oliveira Almeida
# Email: marcelo.almeida1989@bol.com.br
# esse projeto te como objetivo unificar dois arquivos de dimob
# cada arquivo tem seu propio index iniciando sempre em 1
# para poder unificar corretamente o segundo arquivo precisa iniciar seu index a parti do utimo index no 1º arquivo
# então ... |
907be76ac18404845cd961f9ae0cc81992b11a62 | smithhmark/python_code_puzzles | /sequences/greatestspan.py | 1,544 | 3.515625 | 4 |
def simplest(vals):
sz = len(vals)
longest_so_far = 0
for ii, left in enumerate(vals):
for jj in range(sz-1, ii, -1):
right = vals[jj]
if right > left:
if jj - ii > longest_so_far:
longest_so_far = jj - ii
return longest_so_far
def li... |
c4aa4ca022a5d7f3cfdd56056d3ab2815d19877f | smithhmark/python_code_puzzles | /bst/tree.py | 3,558 | 3.8125 | 4 | from collections import deque
class Node():
def __init__(self, val=None):
self.left = None
self.right = None
self.val = val
class BST():
def __init__(self, vals=None):
self._root = None
if vals is not None:
for val in vals:
#print("inserting ... |
521f8e76b5aaedd37c21b034b24acc63d639e551 | smithhmark/python_code_puzzles | /hackerrank/buildastring/build.py | 9,978 | 3.71875 | 4 |
"""
https://www.hackerrank.com/challenges/build-a-string/problem
"""
import sys
import math
import bisect
"""
012345
ab12ab
"""
def _find_longest_ending_here(target, idx, min_len=1):
found = 0
found_at = -1
ss_len = min_len
ss = target[idx - (ss_len - 1):idx + 1]
#print(" matching from?", ss)
... |
8e657c30b9eba1c9e8642747ea19eb82ea845a7d | iamsubingyawali/WW84-MSLearn | /quiz.py | 3,528 | 4.09375 | 4 | print("\nWONDER WOMAN 1984 Quiz\n")
print("Which WONDER WOMAN 1984 character are you most like?")
print("To find out, answer the following questions.\n")
# ask the candidate a question
activity = input( "How would you like to spend your evening?\n(A) Reading a book\n(B) Attending a party\n\nAnswer: " )
if activity == ... |
0bd110a06a378f2666c6a2edfbfa365071048368 | chiragcj96/Algorithm-Implementation | /Design HashMap/sol.py | 3,427 | 4.125 | 4 | '''
Modulo + Array
As one of the most intuitive implementations, we could adopt the modulo operator as the hash function, since the key value
is of integer type. In addition, in order to minimize the potential collisions, it is advisable to use a prime number as
the base of modulo, e.g. 2069.
We organize the storag... |
63dd9893db75cab163145a0faea4993ae1735ebd | chiragcj96/Algorithm-Implementation | /Dynamic Programming/Pascal's Triangle/solution2.py | 887 | 3.796875 | 4 | '''
Dynamic Programming -
Here, instead of a complete n*n matrix, we only use a triangle (or upper diagonal triangle of the n*n matrix)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
which is
1 1 1 1 1
1 2 3 4 .
1 3 6 . .
1 4 . . .
1 . . . .
And we return the values out
Time: O(N^2)
Space: O(N^2)
'''
class Solution:
def gen... |
d9b0b3e681d7b127adeb7a8ac2c546dc907806a4 | chiragcj96/Algorithm-Implementation | /Reverse String/solution.py | 614 | 3.9375 | 4 | class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
Here,
time complexity - O(n)
Space complexity - O(2) or O(1) for i and temp
"""
temp = 0
i=0
while i<len(s)//2:
... |
b1a5b4059cab4acacb61663490afa3c912e74a11 | chiragcj96/Algorithm-Implementation | /Valid Anagram/solution2.py | 1,161 | 3.59375 | 4 | '''
Using one Dictinary
Increment by 1 if the key is found in s[i]
Decrement by 1 if the key is found in t[i]
return if all values of the dictionary are zero
'''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):
return False
dic1 = {}
for i... |
c0fe48dba070c8d9d5992a4c5ed56a1269bf5e37 | chiragcj96/Algorithm-Implementation | /Reverse Integer/Solution1.py | 1,298 | 3.71875 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
""By applying mathematical formula and generating the integer back in reverse order""
"""
result = 0 #The final result
multiplier = 10 ... |
be36b04d4be7bed05e5702384b95d400f94ef12f | abrusebas1997/CS2.2-Module4 | /code.py | 3,605 | 4.03125 | 4 | import math
def get_min(visited, table, neighbors):
#optional helper function to find next neighbor to look AttributeError
pass
def build_shortest_path(graph, start):
#return a shortest path table
table = {}
# take the form
#{vertex: [cost, previous]}
#{"Port Sarim": [0, ""],}
# Get vertices
#Init... |
6b6dae17b4cdb0af548f79350deb1e6657084552 | IamHehe/TrySort | /1.bubble_sort.py | 603 | 4.15625 | 4 | # coding=utf-8
# author: dl.zihezhu@gmail.com
# datetime:2020/7/25 11:23
"""
程序说明:
冒泡排序法
(目标是从小到大排序时)
最好情况:顺序从小到大排序,O(n)
最坏情况:逆序从大到小排序,O(n^2)
平均时间复杂度:O(n^2)
空间复杂度:O(1)
"""
def bubbleSort(arr):
for i in range(1, len(arr)):
for j in range(0, len(arr) - i):
if arr[j] > a... |
0ab3c263766f174b04f319ba773a14e1e56170da | IamHehe/TrySort | /5.merge_sort.py | 2,389 | 4.15625 | 4 | # coding=utf-8
# author: dl.zihezhu@gmail.com
# datetime:2020/7/26 12:31
"""
程序说明:
归并排序
(目标是从小到大排序时)
最好情况:O(n log n)
最坏情况:O(n log n)
平均时间复杂度:O(n log n)
空间复杂度:自上到下:因为需要开辟一个等长的数组以及使用了二分的递归算法,所以空间复杂为O(n)+O(log n)。自下向上:O(1)
稳定
"""
# 自上向下分,递归
def merge_sort(arr):
if len(arr) < 2:
re... |
25f48a1aa35d02ee6707be99e2622968aa01d00a | doudou110975/test | /test.py | 702 | 3.5625 | 4 | #01、环境搭建与检测
import cv2 as cv
import numpy as np
print("--------------Hi,python--------------")
src = cv.imread("D:/Python_instance/pythonface/6.jpg")
#打开一个窗口
#cv2.namedWindow(<窗口名>,x)
#x=cv2.WINDOW_AUTOSIZE-----默认大小,不能改动
#x=cv2.WINDOW_NORMAL
#或cv2.WINDOW_FREERATIO-----可以改动窗口大小
cv.namedWindow("input imag... |
918eb58500dd5f5f90182f78e024835fd69cc003 | lucaspereirag/cursosUdemy | /vetores_nao_ordenados.py | 1,896 | 3.5625 | 4 | import numpy as np
class VetorNaoOrdenado:
def __init__(self, capacidade):
self.capacidade = capacidade
self.ultima_posicao = -1
# np.empty cria um array vazio e com o tamanho agora definido pela própria capacidade e de nº inteiros
self.valores = np.empty(self.capacidade, dtype=int)... |
479c920dc6027a871e67d2a7f8068a75c157a92b | casualhuman/BasCalcs | /calcs/calculations.py | 1,498 | 4 | 4 | # This is where al the calculations snippets are located
# Ohms law calculations
def get_resistance(voltage, current):
try:
resistance_value = int(voltage) / int(current)
resistance_value = f'Resistance = {resistance_value:.3f} Ω'
except:
resistance_value = 'Current should... |
d990ed78e1ecc5dd47c002e438d23400c72badba | mochadwi/mit-600sc | /unit_1/lec_4/ps1c.py | 1,368 | 4.1875 | 4 | # receive Input
initialBalance = float(raw_input("Enter your balance: "))
interestRate = float(raw_input("Enter your annual interest: "))
balance = initialBalance
monthlyInterestRate = interestRate / 12
lowerBoundPay = balance / 12
upperBoundPay = (balance * (1 + monthlyInterestRate) ** 12) / 12
while True:
balan... |
b6be8e950be89b757dc9aee0552ffc17241ff1a3 | yo1995/Daily_agorithm_practices | /190816_ropes/ropes.py | 1,354 | 3.53125 | 4 | from typing import List
def combine_ropes(ropes: List[List[str]]) -> bool:
count = 0
prev = len(ropes)
ropes_remaining = ropes
while ropes_remaining:
print(ropes_remaining)
if count == prev:
return False
current_rope = [ropes_remaining[0][0], ropes_remaining[0][1]]
... |
00501186586870c783628486cf11ab2c03109d18 | yo1995/Daily_agorithm_practices | /190614_HW2_DFS_BFS/level_order_traversal.py | 296 | 3.703125 | 4 | from collections import deque
def level_order_traversal(r):
q = deque()
q.append(r)
while q:
top = q.popleft()
print(top.val)
if top.left:
q.append(top.left)
pass
if top.right:
q.append(top.right)
pass
|
aff991ee63136e6b3d1a179d715a5ef5ad8ddd30 | yo1995/Daily_agorithm_practices | /190623_HW4_Tree_Hash/problem2_check_duplicate_window.py | 423 | 3.6875 | 4 |
def check_duplicate(array, k):
s = set(array[:k])
if len(s) < k:
return True
l = len(array)
if l < k:
return False
for i in range(k, l):
top = array[i-k]
if array[i] in s:
return True
s.remove(top)
s.add(array[i])
return False
if __... |
966fe0602963d5fcaf9f25afcc9b9e6b97ab52b8 | yo1995/Daily_agorithm_practices | /190614_HW2_DFS_BFS/min_depth_btree.py | 1,605 | 3.890625 | 4 | from collections import deque
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def min_depth(root: TreeNode) -> int:
if not root:
return 0
else:
md = 0
q1 = deque()
q1.append(root)
... |
a93e1a26564de8dbffecf7b134ae97c175dd0951 | anandababugudipudi/Python-Programs | /Python DS/Generators.py | 1,227 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 31 16:46:44 2021
@author: anand
"""
def new(dict):
for key, value in dict.items():
return key, value
a = {1:"One", 2:"Two", 3:"Three"}
b = new(a)
# Generators in loops
def ex():
n = 3
yield n
n = n * n
yield n
v =... |
e01e1d79e79be4c9f12812f1fc320c34bf1a5df7 | anandababugudipudi/Python-Programs | /Python DS/Functions.py | 3,395 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 31 15:32:19 2021
@author: anand
"""
# First class objects, using functions as arguments
def func1(name):
return f"Hello {name}"
def func2(name):
return f"{name}, how you doing?"
def func3(func4):
return func4("Dear Learner")
print(func3(... |
601b2985f4780aee6eb336aefd21182268b3af7d | bledidalipaj/codefights | /challenges/python/awardedprizes.py | 4,763 | 3.515625 | 4 | """
At the county fair there is a contest to guess how many jelly beans are in a jar. Each entrant is allowed to submit a
single guess, and cash prizes are awarded to the entrant(s) who come closest without going over. In the event that there
are fewer guesses less than or equal to the answer than the number of prize... |
2ebfb0660341e2e574d002e7bc7562296b1cb3f2 | bledidalipaj/codefights | /challenges/python/sortit.py | 1,359 | 4.09375 | 4 | """
You are given a string, your goal is to rearrange its letters in alphabetical order. If the same letter is
present both in lowercase and uppercase forms in the initial string, the uppercase occurrence should go first
in the resulting string.
Example
For str = "Vaibhav", the output should be
sortIt(str) = "aabhi... |
c58f61175404a276ee72ec6be4b5f828a4a19f59 | bledidalipaj/codefights | /challenges/python/doublethemoneygame.py | 2,039 | 3.640625 | 4 | """
A group of n people played a game in which the loser must double the money of the rest of the players. The game has been played n
times, and each player has lost exactly once. Surprisingly, each player ended up with the same amount of money of m dollars.
Considering all that, find the amount of money each player ... |
73b89ce8f79dfe1a5b1e6ceaa76900c09e420428 | bledidalipaj/codefights | /challenges/python/sinarea.py | 983 | 3.890625 | 4 | """
You guys should probably know the simple y = sin(x) equation.
Given a range of x [start, end], your mission is to calculate the total signed area of the region in the xy-plane that
is bounded by the sin(x) plot, the x-axis and the vertical lines x = start and x = end. The area above the x-asix should
be added to... |
ec097380731f8137b8715b214fbeb94a9e054da5 | bledidalipaj/codefights | /challenges/python/issentencepalindrome.py | 2,120 | 4.0625 | 4 | """
As a high school student, you naturally have a favourite professor. And, even more natural, you have a least favourite
one: professor X!
Having heard that you're an experienced CodeFighter, he became jealous and gave you an extra task as a homework. Given a
sentence, you're supposed to find out if it's a palindr... |
6e9f7ffbe8ffcb7cbc7ddd2d493ee8cbfc1fe126 | bledidalipaj/codefights | /challenges/python/flowersandflorets.py | 3,618 | 4.15625 | 4 | """
You would like to create your own little farm. Since you're not an expert (yet!), you bought seeds of just two types of plants:
flowers and florets. Each pack of seeds was provided with the instructions, explaining when the plant can be planted.
In the instructions two dates are given, to and from, which denote t... |
7ea9ed580687c2d074abc5e1f185350fdbde7bdb | bledidalipaj/codefights | /challenges/python/friendlynumbers.py | 1,067 | 3.875 | 4 | """
Numbers x and y (x ≠ y) are called friendly if the sum of proper divisors of x is equal to y, and the other way round.
Given two integers x and y, your task is to check whether they are friendly or not.
Example
For x = 220 and y = 284, the output should be
friendly_numbers(x, y) = "Yes".
The proper divisors of ... |
fbaf789fbe6bfaede28d2b2d3a6a1673e229f57b | bledidalipaj/codefights | /challenges/python/holidaybreak.py | 2,240 | 4.375 | 4 | """
My kids very fond of winter breaks, and are curious about the length of their holidays including all the weekends.
Each year the last day of study is usually December 22nd, and the first school day is January 2nd (which means that
the break lasts from December 23rd to January 1st). With additional weekends at the... |
9d01048c217072623b64718f5b90a747cea12993 | shivamt91/theweatherapp | /weather.py | 1,288 | 3.59375 | 4 | import sys
import requests
import json
from today import today
from hourbyhour import hourbyhour
from monthly import monthly
def the_weather():
arguments = sys.argv
if len(arguments) == 2:
place = arguments[1]
type_of_forecast = 'today'
elif len(arguments) == 3:
place = arguments[... |
0bad5a8a7ee86e45043ef0ddf38406a9ee4d1032 | pmayd/python-complete | /code/exercises/solutions/words_solution.py | 1,411 | 4.34375 | 4 | """Documentation strings, or docstrings, are standard ways of documenting modules, functions, methods, and classes"""
from collections import Counter
def words_occur():
"""words_occur() - count the occurrences of words in a file."""
# Prompt user for the name of the file to use.
file_nam... |
1011b0a5d86b6aeb31c928bea06c55a679e61fa6 | pmayd/python-complete | /code/exercises/sum.py | 530 | 3.8125 | 4 | import doctest
def mysum(...):
"""The challenge here is to write a mysum function that does the same thing as the built-in sum function. However, instead of taking a single sequence as a parameter, it should take a variable number of arguments. Thus while we might invoke sum([1,2,3]), we would instead invoke mysu... |
95b308d6bdb204928c6b014c8339c2cc8693b7d7 | pmayd/python-complete | /code/exercises/most_repeating_word.py | 870 | 4.3125 | 4 | import doctest
def most_repeating_word(words: list) -> str:
"""
Write a function, most_repeating_word, that takes a sequence of strings as input. The function should return the string that contains the greatest number of repeated letters. In other words:
for each word, find the letter that appears the mo... |
e4ae96a91d9ab51a0fe4f82cc06afefe05a8dd77 | azapien22/Python3 | /sdex5.py | 1,099 | 4.0625 | 4 | # More Variables & Printing
# Removed "my_"
# Inch to cm & lbs to kg conversion w/ variables
# Used Round() Function
name = "Amaury Zapien"
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'white'
hair = 'brown'
print(f"let's talk about {name}.")
print(f"He's {height} inches ... |
59483e49c3cdf8fe1cf1871ec439b25ffd4daf15 | lisandroV2000/Recuperatorio-programacion | /ACT3.py | 784 | 4.15625 | 4 | #3. Generar una lista de números aleatoriamente y resuelva lo siguiente:
#a. indicar el rango de valores de la misma, diferencia entre menor y mayor
#b. indicar el promedio
#c. ordenar la lista de manera creciente y mostrar dichos valores
#d. ordenar la lista de manera decreciente y mostrar dichos valores
#e. hace... |
d35a2f95bb5ae84a53e6a294a4b4bd0d3257cebf | Rujabhatta22/pythonProject10 | /fgedh.py | 182 | 4.21875 | 4 | #what will be the output of following program? Rewrite the code using for loop to display same output.
n=6
i=0
for i in range(n):
i+=1
if i==3:
continue
print(i)
|
bdd724aebcb76e43df558cd91da8659a92b9f119 | enderdaniil/Python-Hangman-Game | /Game.py | 2,040 | 3.9375 | 4 | import random
cont = True
print("H A N G M A N")
s = input('Type "play" to play the game, "exit" to quit:')
while s == "play":
print()
lives = 8
words = ['python', 'java', 'kotlin', 'javascript']
current_word = random.choice(words)
current_word_cipher = ""
for i in range(len(current_word)):
... |
f07adcd069502be0f9f1d068efc3450d0476bc8d | paul0920/leetcode | /question_leetcode/1062_4.py | 896 | 3.71875 | 4 | def longestRepeatingSubstring(S):
"""
:type S: str
:rtype: int
"""
if not S:
return 0
n = len(S)
dp = [[0] * (n + 1) for _ in range(n + 1)]
max_len = 0
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if S[i - 1] != S[j - 1]:
dp[i]... |
5563bdc8958258d54d803bd3ed6fa6b92d25079d | paul0920/leetcode | /question_leetcode/716_1.py | 1,868 | 3.875 | 4 | # pop & top are O(1) average time complexity since every element gets into and out once
# of stack/heap/hashset
import heapq
class MaxStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.heap = []
self.popped_item = [... |
42363a0abd2702eff075bf6562d06d9c5b71b2e3 | paul0920/leetcode | /question_leetcode/366_1.py | 706 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import collections
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
... |
54557b4121d20c5a4e0c9c72de8dd2c0c75c1df9 | paul0920/leetcode | /question_leetcode/542_1.py | 1,296 | 3.5625 | 4 | import collections
def updateMatrix(mat):
"""
:type mat: List[List[int]]
:rtype: List[List[int]]
"""
if not mat:
return [0]
m = len(mat)
n = len(mat[0])
res = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
... |
903d9fd3fb364c3caa5f8d0f8d058ecc43ed4efb | paul0920/leetcode | /question_leetcode/53.py | 357 | 3.96875 | 4 | def maxSubArray(nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
curr_sum = nums[0]
max_sum = nums[0]
for num in nums[1:]:
curr_sum = max(curr_sum + num, num)
max_sum = max(max_sum, curr_sum)
return max_sum
nums = [-2, 1, -3, 4, -1, ... |
39ec479de101f14fe5f5bd374e3913a8889dd240 | paul0920/leetcode | /pyfunc/pop_reverse_demo.py | 154 | 3.71875 | 4 |
a = list("apple")
b = list("apple")
arr = ""
while a:
arr += a.pop()[::-1]
print arr[::-1]
arr = ""
while b:
arr = b.pop() + arr
print arr
|
243c538ea6878b65e70871d3efd8979e783f72bd | paul0920/leetcode | /pyfunc/scope_demo.py | 697 | 3.578125 | 4 | # JavaScript also has the following scope and IIFE concept,
# which are similar to Python
def my_func_a(i):
print i
def my_func_b():
# i = 3.14
print i
def closure(m):
def my_func_c():
print m
return my_func_c
arr2 = []
arr = []
for i in range(2):
arr2 += [my_func_a]
arr += ... |
ff2b554660c1cfb2024cfb9ea3189bfd07bc534f | paul0920/leetcode | /question_leetcode/287_1.py | 1,024 | 4 | 4 |
# Depending whether there is 0 in the array,
# the starting point is either from the largest index
# or the smallest index
# You must not modify the array (assume the array is read only).
# You must use only constant, O(1) extra space.
# Your runtime complexity should be less than O(n^2).
# There is only one duplicat... |
732412f6fc5b3ba1866a3f27f2e06f6cdc5c7711 | paul0920/leetcode | /question_leetcode/863_2.py | 853 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
def distanceK(self, root, target, K):
adj, res, visited = collections.defaultdict(list), [], set()
def dfs(node):
... |
ca62304801653fafa7fd08be36b4460ca6ab4c2b | paul0920/leetcode | /question_leetcode/96_3.py | 339 | 3.921875 | 4 | # Recursion (Top Down) using LRU cache
# import functools
from lru_cache import *
@lru_cache()
def numTrees(n):
if n <= 1:
return 1
res = 0
for root in range(0, n):
# numTrees(left) x numTrees(right)
res += numTrees(root) * numTrees(n - 1 - root)
return res
n = 19
# n = 3
... |
7ac8682141a5227f2f997800d5a79b7014122071 | paul0920/leetcode | /pyfunc/list_comprehensions_demo.py | 359 | 3.78125 | 4 | arr = [1, 2, 3]
box = []
for a in arr:
for b in arr:
box.append(a + b)
print box
print [a + b for a in arr for b in arr]
# If & Else
print [n if n % 2 else 'N' for n in range(10)]
# print [n for n in range(10) if n % 2 else 'N'] # Wrong usage
# If
print [n for n in range(10) if n % 2]
# print [n if n... |
60a2f315b6b59ae268775ec8205cdb08c6821fc1 | paul0920/leetcode | /question_leetcode/392_3.py | 463 | 3.609375 | 4 | def isSubsequence(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if not s:
return True
char_to_word = {s[0]: s}
for char in t:
if char not in char_to_word:
continue
word = char_to_word[char]
char_to_word.pop(char)
if len(word... |
5b5a842aa8be72e45c546b85ac13677048140c8c | paul0920/leetcode | /pyfunc/setdefault_demo.py | 513 | 3.984375 | 4 |
# dictionary.setdefault(key name, value)
#
# key name: Required.
# The key name of the item you want to return the value from
#
# value: Optional.
# If the key exists, this parameter has no effect.
# If the key does not exist, this value becomes the key's value
# Default value None
A = [1, 2, 1, 2]
first = {}
for i... |
be3aae6fbc28ede4f5567f33a4cdd1e1b7cd7378 | paul0920/leetcode | /question_leetcode/90_2.py | 745 | 3.796875 | 4 | # BFS
import collections
def subsetsWithDup(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return [[]]
# Need to sort the array first for handling duplicate cases
nums.sort()
queue = collections.deque([([], nums)])
res = []
while queue:
... |
bd8ecf82b91c96454c3ae44d7cece064a43e16fe | paul0920/leetcode | /question_leetcode/1110_1.py | 1,107 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def delNodes(self, root, to_delete):
"""
:type root: TreeNode
:type to_delete: List[int]
:rtype: List[T... |
e7d1059bfb6512fa09af065a267c649bc4d35391 | paul0920/leetcode | /question_leetcode/120_6_2.py | 699 | 3.5 | 4 | # Top -> down
# Time complexity: O(n^2), n: triangle layer counts
# Space complexity: O(n)
def minimumTotal(triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
dp = [[0] * n, [0] * n]
# dp = [[0] * (i + 1) for i in range(n)]
dp[0][0] = triangle[0][0]
fo... |
2cefa43ce01faae705b776c45df8f589999a37c9 | paul0920/leetcode | /question_leetcode/188.py | 628 | 3.8125 | 4 | def maxProfit(k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices or k == 0:
return 0
cost = [float("INF")] * k
profit = [0] * k
for price in prices:
for i in range(k):
if i == 0:
pre_cost = 0
e... |
c01ad77fcc9f0ebb2dd2df5eeaa46468d949b8a5 | paul0920/leetcode | /question_leetcode/120_1.py | 565 | 3.6875 | 4 | # DFS: traverse. TLE
# Time complexity: O(2^n), n: triangle layer counts
def minimumTotal(triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
return dfs(triangle, 0, 0, 0, float("INF"))
def dfs(triangle, x, y, path_sum, min_sum):
if x == len(triangle):
return min(min_sum, p... |
fa0a2e8e0ec8251c6d735b02dfa1d7a94e09c6b2 | paul0920/leetcode | /question_leetcode/1488_2.py | 1,538 | 3.984375 | 4 | import collections
import heapq
rains = [1, 2, 0, 0, 2, 1]
# 0 1 2 3 4 5
rains = [10, 20, 20, 0, 20, 10]
# min heap to track the days when flooding would happen (if lake not dried)
nearest = []
# dict to store all rainy days
# use case: to push the subsequent rainy days into the heap for wet lakes... |
fbf4ae9f1443d6b29e437fa2189dd169c7f3f24c | paul0920/leetcode | /question_leetcode/1269_1.py | 525 | 3.78125 | 4 | def numWays(steps, arrLen):
"""
:type steps: int
:type arrLen: int
:rtype: int
"""
return dfs(0, steps, arrLen)
def dfs(pos, steps, arrLen):
if pos < 0 or pos >= arrLen:
return 0
if steps == 0:
if pos == 0:
return 1
return 0
return (dfs(pos - ... |
5684a4252b5323f29d45a8431f20c153303c35c1 | paul0920/leetcode | /question_leetcode/81.py | 1,242 | 3.765625 | 4 |
# nums = [4, 5, 6, 7, 0, 1, 2]
# target = 3
# nums = [4, 5, 6, 7, 0, 1, 2]
# target = 0
nums = [1, 1, 3, 1]
target = 3
left = 0
right = len(nums) - 1
# "=" needs to be consider to cover the following case:
# nums = [1]; target = 1
while left <= right:
mid = (left + right) / 2
if nums[mid] == target:
... |
67fbaf8aa5039b3aa18ac23e79ff785fb5786a34 | paul0920/leetcode | /question_leetcode/208_2.py | 1,184 | 4.09375 | 4 |
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = {}
self.isWord = False
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
# Although this changes "self", it won't change the value of self in other me... |
94e06ea11880e0b11b09dcb752f1113a4566aad8 | paul0920/leetcode | /pyfunc/bisect_demo_1.py | 754 | 3.5625 | 4 | import bisect
A = [[[-1, 0], [3, -1], [4, 5]]]
print A[0]
# [3] always be the smallest one comparing to any [3, x]
print bisect.bisect(A[0], [3])
print bisect.bisect(A[0], [3, -2])
print bisect.bisect(A[0], [3, -1])
# print bisect.bisect_left(A[0], [3, -1])
print bisect.bisect(A[0], [3, 0])
print bisect.bisect(A[0]... |
c019ab5f9757264ecbd971a9f6ade7a679dacdb6 | paul0920/leetcode | /question_leetcode/652_1.py | 886 | 3.609375 | 4 | import collections
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.right.left = TreeNode(2)
root.right.right =... |
548084267c55bc7288149402ed3b65cd6035c228 | paul0920/leetcode | /question_leetcode/98_2.py | 689 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
... |
da63fed7f0dab65a4f916bad3872b1e59f18ade9 | paul0920/leetcode | /question_leetcode/199_1.py | 968 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import collections
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode... |
c08331ff1f9872acf02d15b8eeb73bfda6e34cb9 | paul0920/leetcode | /question_leetcode/706_3.py | 1,724 | 3.65625 | 4 | class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 1000
# bucket = (key array list, value array list)
self.buckets = [([], []) for _ in range(self.size)]
def get_hash_code(self, key):
return key % self.s... |
80faff682b05c7b56321b8761d088b062ee0e087 | paul0920/leetcode | /question_leetcode/270_2.py | 537 | 3.6875 | 4 | class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = TreeNode(4)
root.left = TreeNode(2)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right = TreeNode(5)
target = 3.714286
def find(node):
... |
64cabc4196e66bf562735ded2c66ed388f39ba09 | paul0920/leetcode | /question_leetcode/366_2.py | 693 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import collections
class Solution(object):
def findLeaves(self, root):
"""
:type root: TreeNode
... |
e9c7e2643386e25fb4206e3546af1b7b8fc40c6f | paul0920/leetcode | /question_leetcode/1197_2.py | 1,289 | 3.703125 | 4 | import collections
def minKnightMoves(x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
if (x, y) == (0, 0):
return 0
forward_queue = collections.deque([(0, 0)])
forward_visited = set([(0, 0)])
backward_queue = collections.deque([(x, y)])
backward_visited = set([(x,... |
8215c61fb101b6cbc853f5d28e615df960bfc0ab | paul0920/leetcode | /question_leetcode/16_1.py | 617 | 3.53125 | 4 |
nums = [0, 1, 2]; target = 0
nums.sort()
# Be careful of the last index in sum()
# The following is equivalent of nums[0] + nums[1] + nums[2]
sum_min = sum(nums[0:3])
for i in range(len(nums) - 2):
j, k = i + 1, len(nums) - 1
if i > 0 and nums[i] == nums[i - 1]:
continue
while j < k:
... |
3774581fca565cb1c78656e7b20abf79d6833d7c | paul0920/leetcode | /question_leetcode/148_2_1.py | 1,153 | 4 | 4 | # Top-Down method
from see_node import *
def merge(l, r):
dummy = cur = ListNode(0)
while l and r:
if l.val < r.val:
cur.next = l
l = l.next
else:
cur.next = r
r = r.next
cur = cur.next
cur.next = l if l else r
p_node(dummy.n... |
ab029089a8b2ab2c6c968fcd4f0b64f4b508c767 | paul0920/leetcode | /pyfunc/see_node.py | 446 | 3.6875 | 4 |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def c_node(arr):
dummy = ListNode(0)
dummy.next = node = ListNode(arr[0])
for n in arr[1:]:
node.next = ListNode(n)
node = node.next
return dummy.next
def p_node(head):
if not hea... |
4550d21f65e6d452062458d1058fa700b9e93103 | paul0920/leetcode | /question_leetcode/31_2.py | 1,035 | 3.734375 | 4 | def nextPermutation(nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
if not nums:
return []
# [1, 5, 8, 4, 7, 6, 5, 3, 1]
# ^ ^
# -> [1, 5, 8, 5, 7, 6, 4, 3, 1]
# ^ ^
... |
31cbbc0e9340596def44286e41eb1569ae611c07 | paul0920/leetcode | /question_leetcode/1644_1.py | 1,320 | 3.78125 | 4 | class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.res = None
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
... |
111c536fba28296ec4f2a93ab466360e57d839d6 | paul0920/leetcode | /question_leetcode/215_5.py | 1,471 | 4.25 | 4 | # Bucket sort algorithm
# Average time complexity: O(n)
# Best case: O(n)
# Worst case: O(n^2)
# Space complexity: O(nk), k: bucket count
# Bucket sort is mainly useful when input is uniformly distributed over a range
# Choose the bucket size & count, and put items in the corresponding bucket
nums = [3, 2, 1, 5,... |
0aa9a7c64282a574374fb4b9e9918215f0f013ec | paul0920/leetcode | /question_leetcode/48_2.py | 509 | 4.1875 | 4 |
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print row
m = len(matrix)
n = len(matrix[0])
# j only loops until i
for i in range(m):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# j only loops until n / 2
for i in range(m):
for j in range(n / 2):
... |
65b13cf4b6251e6060c8ccf34a63ab703f93fd2b | paul0920/leetcode | /pyfunc/lambda_demo_1.py | 251 | 4.15625 | 4 |
my_list = [1, 5, 4, 6]
print map(lambda x: x * 2, my_list)
print (lambda x: x * 2)(my_list)
print my_list * 2
# A lambda function is an expression, it can be named
add_one = lambda x: x + 1
print add_one(5)
say_hi = lambda: "hi"
print say_hi()
|
19b9054f704d916c6d35b6500919397476111ab2 | paul0920/leetcode | /question_leetcode/215_2.py | 548 | 3.796875 | 4 | # Bubble sort algorithm
# Time complexity: O( k(n - (k+1)/2) ); if k = n, O( n(n-1)/2 )
# Best case: O(n)
# Worst case: O(n^2)
# Space complexity: O(1)
# If j+1 > j, just swap and so on
# nums = [3, 2, 1, 5, 6, 4]
# k = 2
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6]
k = 4
for i in range(k):
for j in range(len(nums) ... |
c0c20ac1cb3fbaab0a412421cde30202daf5b808 | paul0920/leetcode | /question_leetcode/5_1.py | 294 | 3.671875 | 4 |
s = "babad"
s = "cbbd"
res = ""
def find_str(left, right):
while 0 <= left and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left + 1: right]
for i in range(len(s)):
res = max(res, find_str(i, i), find_str(i, i+1), key=len)
print res
|
3f57d2d24f381e2a5aa5ab8509d2ad5e81c98258 | paul0920/leetcode | /question_leetcode/1136_1.py | 1,245 | 3.5 | 4 | # Time complexity: O(n + m), m = len(relations) (edges)
import collections
def minimumSemesters(n, relations):
"""
:type n: int
:type relations: List[List[int]]
:rtype: int
"""
if not relations:
return 1
pre_to_current = {i: set() for i in range(1, n + 1)}
current_to_pre = {i... |
0fa527406b5d00b216e32648cc2991eb61d2b012 | paul0920/leetcode | /question_leetcode/254.py | 563 | 3.6875 | 4 | def getFactors(n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n <= 1:
return []
res = []
calculate_factors(res, [], n, 2)
return res
def calculate_factors(res, path, n, factor):
# To prevent from adding the case of number itself
if len(path) > 0:
res.appe... |
1d64c975e07beb51dcf12ed83c49b310cfe8f7a4 | paul0920/leetcode | /question_leetcode/525.py | 516 | 3.78125 | 4 | def findMaxLength(nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
count_to_index = {0: -1}
count = 0
max_len = 0
for i, num in enumerate(nums):
if num == 0:
count -= 1
else:
count += 1
if count not in ... |
046ca7d8531c5431092eaf09481734f3ed6ef3ab | paul0920/leetcode | /question_leetcode/1380.py | 383 | 3.765625 | 4 | matrix = [[1,10,4,2],[9,18,8,7],[15,16,17,12]]
mi = [min(row) for row in matrix]
# zip(*zippedList) is a great function to extract columns in 2D matrix
# It returns an iterator of tuples with each tuple having elements from all the iterables.
mx = [max(col) for col in zip(*matrix)]
mx_col = [col for col in zip(*matri... |
66228e9d8b171a24213e0b57c73ec63bf27f7054 | paul0920/leetcode | /question_leetcode/297_1.py | 1,714 | 3.671875 | 4 | class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = TreeNode(-1)
root.left = TreeNode(0)
# root.left.left = TreeNode(4)
# root.left.right = TreeNode(5)
# root.left.right.left = TreeNode(7)
# root.left.right.rig... |
e4c37eee96534a69fb1f98ad244eb97c996da646 | paul0920/leetcode | /question_leetcode/207_2.py | 679 | 3.75 | 4 | from collections import defaultdict
numCourses = 5
prerequisites = [[1, 0], [0, 1]]
g = defaultdict(list)
visit = [0 for _ in range(numCourses)]
for course, pre in prerequisites:
g[course].append(pre)
def dfs(course):
if visit[course] == 1:
return True
if visit[course] == -1:
return Fa... |
8b0d684472ff8ab6fda89b346c3c5b055047b7fc | paul0920/leetcode | /question_leetcode/785_2.py | 898 | 3.671875 | 4 | import collections
def isBipartite(graph):
"""
:type graph: List[List[int]]
:rtype: bool
"""
if not graph:
return False
node_color_lookup = {}
for i in range(len(graph)):
if i not in node_color_lookup:
node_color_lookup[i] = 1
if not DFS(i, grap... |
3050658fcb4ba27e9bf027c0ae6ecfe37b4f6b9b | junior-oliveira/missao-07 | /tratamento_dados/normalizacao.py | 387 | 3.515625 | 4 |
import numpy as np
def normalizar_dados(df):
'''
df - dataframe de valores a serem normalizados
df_norm - dataframe normalizado pelo mínimo e máximo valor
'''
# Normalização dos dados
x_float = df.astype('float')
norm_min_max = lambda x: (x - np.min(x))/(np.max(x) - np.min(x))
df_norm ... |
019c38213748b52f591033c022a6bfe7ab613e17 | RennanGaio/inteligenciaComputacional | /trabalho1/gradiente_descendente.py | 3,528 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Aluno: Rennan de Lucena Gaio
Codigo referente aos 4 exercícios 11 e 12 da lista 1 de IC2
"""
import numpy as np
import random
import matplotlib.pyplot as plt
'''
funções referentes ao gradiente descendente
não foi criada uma classe para esse problema por ele ser mais simples e as pergunta... |
521cc7aaba06cf5eea97727f96c2dccda656d100 | Anubhav27/python_handson | /Python_Smart/python_classes.py | 314 | 3.625 | 4 | __author__ = 'Anubhav'
class Student:
student_count = 0
def __init__(self,name):
self.name = name;
Student.student_count += 1
def getName(self):
return self.name
#s = Student("anubhav")
#print s.getName()
s = Student("anubh")
Student.__init__(s,'a')
print s.getName()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.