text stringlengths 37 1.41M |
|---|
def is_pythagorean(a,b,c):
if a**2 + b**2 == c**2:
return True
else:
return False
def gen_triplets(sigma):
for a in xrange(1,sigma+1):
for b in xrange(1,sigma-a+1):
yield (a,b,1000-a-b)
def find_pythagorean_triplet(sigma):
for trip in gen_triplets(sigma):
if is_pythagorean(*trip):
return trip
|
from sklearn import preprocessing
def main():
# Trying out encoding
label_encoder = preprocessing.LabelEncoder()
input_classes = ['suzuki', 'ford', 'suzuki', 'toyota', 'ford', 'bmw']
label_encoder.fit(input_classes)
print("Class mapping:")
for i, item in enumerate(label_encoder.classes_):
... |
"""
salaries.regex.single_regex_utils
--------------
Regex to pull out salaries, with a hard-coded
guess at whether the salary rate is hourly, daily or pa.
Do `apply_model(row)` to load and apply the model to data.
Run `regex.py` in `jupyter lab` (with `jupytext` installed)
to see the model in action (it's surprisin... |
import random
from Player import Player
from Alien import Alien
class Map:
height = None
width = None
alienCount = None
map = None
aliens = []
player = None
def __init__(self, height, width, alienCount):
self.height = height +1 #+1 because of the border and the
self.width ... |
#!/usr/bin/env python
from sys import argv as arg
import os
##255 is 100% PCM Volume
#function that also calculates percentage of volume
def percentvol(value):
vol=int(value)*255/100
cmd="""amixer set 'PCM' """
os.system(cmd + ' ' + str(vol))
def percent(value):
vol=int(value)*255/100
yield vol
def volume(va... |
#-------------------------------------------------------------------------------
# Name: MapIt
#
# Author: Slick
# Created: 20/04/2020
#-------------------------------------------------------------------------------
'''Takes an address and shows it to you on google maps'''
import os, webbrowser, pypercl... |
import keyboard # using module keyboard
while True: # making a loop
if keyboard.is_pressed('q'): # if key 'q' is pressed
print'You Pressed A Key!'
break # finishing the loop
else:
pass
|
'''Problem : Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursio... |
import datetime
print("""Написать декоратор для подсчета времени выполнения функции""")
def decorator_func(func):
def wrapper(*args, **kwargs):
print('Получена функция {} в качестве аргумента'.format(func))
beg = datetime.datetime.now().timestamp()
return_val = func(*args, **kwargs)
... |
"""
Faça um programa que peça o primeiro nome do usuário. Se o nome tiver 4 letras ou
menos escreva "Seu nome é curto"; se tiver entre 5 e 6 letras, escreva
"Seu nome é normal"; maior que 6 escreva "Seu nome é muito grande".
"""
nome = input('Informe seu primeiro nome: ')
if len(nome) <= 4:
print('Seu nome é c... |
'''
Implement the 3-rounds simple DES cipher using Python.
You should submit file_name.pdf and file_name.py file in which file_name.pdf
contains the souce code and the running results of implemented ciphers,
and the file_name.py is the souce code of your implementation.
- sdes_genkey(): It outputs a key of rando... |
arr = [10, 15, 3, 7]
target = 17
def target_possible(arr, target):
arr = set(arr)
for num in arr:
if target - num in arr:
return True
return False
assert target_possible(arr, target) == True
|
# coursera-university-of-michigan-python-week-2-assigment
python basics course // DICTIONARY ACCUMULATION ASSIGNMENT
#PROBLEM1
Junior = {'SI 206':4, 'SI 310':4, 'BL 300':3, 'TO 313':3, 'BCOM 350':1, 'MO 300':3}
credits=0
for key in Junior:
credits=credits+Junior[key]
PROBLEM2
str1 = "peter piper picked a peck of... |
#Python For Kids Chapter 6 Challenge 4 Your Weight On The Moon
#Calculate weight on moon using 0.165. If you gained a kilo in weight every
#year for the next 15 years, what would your weight be at the end of the 15 years?
weight = 155
year = 1
for x in range(1,16):
new_weight = (weight + (x-1))*0.165
print("Year %... |
#Python for Kids Chapter 7 Recycling Your Code With Functions and Modules
#Modules are used to group functions, variables into more powerful programs.
import sys
#print(sys.stdin.readline())
def silly_age_joke():
print('How old are you?')
age = int(sys.stdin.readline())
if age >=10 and age <=13:
print('What is ... |
#Python for Kids Chapter 7 Recycling Your Code With Functions and Modules
#Functions have three parts: name, parameter, body
def testfunc(myname):
print('hello %s' % myname)
testfunc('Mary')
def testfunc2(fname, lname):
print('hello %s %s' % (fname, lname))
testfunc2('Mary', 'Smith')
firstname = 'Joe'
lastnam... |
#Python for Kids Chapter 9 Python's Built-in Functions
#your_calculation = input('Enter a calculation: ')
#eval(your_calculation)
my_small_program = '''print('ham') print('sandwich')'''
exec(my_small_program) |
#Python for Kids Chapter 8 Challenge 1 The Giraffe Shuffle
#Add funtions to the Giraffes class to move the giraffe's left and right feet forwardand backward.
class Things:
pass
class Inanimate(Things):
pass
class Animate(Things):
pass
class Animals(Animate):
def breathe(self):
print('breathing')
def move(s... |
#Kids for Python Chapter 8 How to Use Classes and Objects
#Inherited Functions
class Things:
pass
class Inanimate(Things):
pass
class Animate(Things):
pass
class Animals(Animate):
def breathe(self):
print('breathing')
def move(self):
print('moving')
def eat_food(self):
print('eating food')
class Ma... |
#practica7
#Modifica el programa de la práctica 6 metiendo el código de cifrado dentro de una función
#llamada cifracesar(texto,key) que devuelve el texto cifrado.
# Obtenemos mensaje a cifrar desde el usuario
# llamamos a upper para obtener sólo mayúsculas
texto = input("Mensaje: ").upper()
# Pedimos al usuario la ... |
#requiered libraries
import numpy
import matplotlib.pyplot as plt
#Initial parameters
alpha = 0.1 # Prey growing up rate
beta = 0.02 # Predator successful rate
gamma = 0.3 # Predator decrease rate
delta = 0.01 # Pretator hunting successful rate && feeding rate, cuanto alimenta cazar una presa
#Function euler (... |
#!/usr/bin/env python2.7
# 9/29/2017
# program to find solution to equation, namely f(x) = 0, using newton's
# method
import math
import time
# globals
APPROX = 0.1
TOL = 10**-5
N = 100
# functions we are using, namely f and f'
def f(x):
return math.pow((1+x),204)-440*x-1
def fprime(x):
return 204*math.po... |
import hangman_helper
import string
def update_word_pattern(word,pattern,letter):
"""The function receives a word, a pattern and a letter and returns the an
updated pattern containing the letter."""
if letter in word:
new_pattern=[]
for j in range(len(pattern)):
new_pat... |
dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'e':5,'f':6,'g':7,'h':8}
for i in dict2:
if i not in dict1:
d = {i:dict2[i]}
dict1.update(d)
print dict1
# dict1.update(dict2)
# print dict1
# print dict(dict1,**dict2)
print dict(dict1.items()|dict2.items())
|
def convert_to_hex(ascii_value):
return hex(ascii_value)
lst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = input()
lst.append(ele)
flag = 0
for j in range(0,n/2):
if(lst[j]!=lst[n-j-1]):
flag =1
break
if(flag==1):
print("not palindrome")
else:
... |
#!/usr/bin/python
# NOT TO SELF: FOr output formatting https://docs.python.org/3.0/tutorial/inputoutput.html
# CHANGE STRING TO DATE: http://stackoverflow.com/questions/16870663/how-do-i-validate-a-date-string-format-in-python
import os
import sys
import codecs
import datetime
tag=pid=name="NA"
dob=dod=sex="NA"
famc... |
"""
This module process and export data to a local folder in a computer
"""
import pandas as pd
from TextAnalysis_ProjectHero.date_cleaning import set_date
from TextAnalysis_ProjectHero.text_cleaning import process_text
def split_half(slice):
"""This function slpit dataframe into two smaller dataframes
based ... |
import os
file_name: str = 'employees.csv'
print(os.path.exists(file_name))
class Employee:
'''
A class used to represent an Animal
...
Attributes
----------
id: int
an integer representing an employee's id number
name: str
The name of the employee
dept: str
... |
#!/usr/bin/env python
# coding: utf-8
# # 파이썬 기본실습
# In[6]:
print("hello")
print("my name is kangjh")
# ## pandas 사용법
# In[5]:
get_ipython().system('pip install pandas')
# In[8]:
import pandas as pd
# In[12]:
names = ['Bob','Jessica','Mary','John','Mel']
births = [1986, 1752, 1956, 1958, 2016]
custom =... |
from turtle import Turtle
snake_positions = [(0, 0), (-20, 0), (-40, 0)]
move_distance = 20
up = 90
down = 270
right = 0
left = 180
class Snake:
def __init__(self):
self.snake_segments = []
self.create_snake()
self.head_of_snake = self.snake_segments[0]
def create_sna... |
#MiniApp 2: The Kivy File
#The goal of this app is to show how to set up and design in the Kv file, and go back over initializing the app class
#Below importing the proper kivy functions from the kivy library.
#To accurately find where and what to input for the function you want to import,
#consult Kivy API at http:/... |
scrab = dict(
a=1,
b=3,
c=3,
d=2,
e=1,
f=4,
g=2,
h=4,
i=1,
j=8,
k=5,
l=1,
m=3,
n=1,
o=1,
p=3,
q=10,
r=1,
s=1,
t=1,
u=1,
v=4,
w=4,
x=8,
y=4,
z=10,
)
name = input('Enter a word or name to find out how many scrabble points its worth: ')
score = sum(scrab.get(value,0) for value in name.lower())
print(f"Your word is worth... |
# Nome: Rodrigo Lopes da Silva Santos
# Nmec: 89180
from tree_search import *
class MyNode(SearchNode):
def __init__(self,state,parent,depth=0,cost=0,evalfunc=0,children=None):
# Inicializacao dos nodes
super().__init__(state, parent)
self.depth = depth
self.cost = cost
sel... |
class Node:
def __init__(self, k,v, l = None ,r =None):
self.key = k
self.value = v
self.left = l
self.right = r
def set_key(self, k):
self.key = k
def get_key(self):
return self.key
def set_value(self,v):
self.value = v
d... |
def exchange(i, j, a):
temp = a[i]
a[i] = a[j]
a[j] = temp
def partition(start,end,a):
i = start
wall = start
pivot = end - 1
while i < pivot:
if a[i] < a[pivot]:
#print 'a[i]: ',a[i],'< a[pivot]: ',a[pivot],"exchanging"
exchange(i, wall, a)
... |
N = int(input())
#print(N)
n = 1
answer = 0
if N == 1 :
print(1)
elif N >= 2 and N <= 7:
print(2)
else :
while 3*n*(n+1) < N-1 :
n += 1
answer = n + 1
print(answer)
|
M = int(input())
ball = 1
for x in range (M) :
X,Y = map(int,input().split())
if X == ball :
ball = Y
elif Y == ball :
ball = X
print(ball)
|
message=" "
if 1>2:
message="if only 1 were greater than two..."
elif 1>3:
message="elif stands for else if"
else:
message="when all else fails use else (if you want to)"
x=22
parity="even" if x%2==0 else "odd"
x=0
while x<10:
print(f"{x} is less than 10")
x+=1
#range(10 )is the num... |
document="merhabalar arkadaşalr nasılsınız!! Sizlere çok önemli bir haberim var"
word_counts={} #dictionnaire
for word in document: #document içerisindeki elemalar burada get ile kontrol yapar
previous_count=word_counts.get(word,0) # get(word,0)--> dictonnary içerisinde eleman yoksa 0 ıncı key ile oluşuy... |
weight =raw_input ('weight of watermelon is ')
weight =int(weight)
if weight%2!=0 or weight==2 :
print('No')
else:
print ('Yes') |
import unittest
def merge_sort(z, merge_algo='recursive'):
"""
Implementation of merge_sort algorithm: For details please visit:
https://en.wikipedia.org/wiki/Merge_sort
:param z: unsorted array
:type z: iterable
:param merge_algo: two merge algorithms can be used `iterative` or `recursive`
... |
import unittest
class Node(object):
"""
Representation of a singly linked list nodes
:param data: data to be stored in the node
:type data: object
:param next: pointer to the next node:
:type next: Node
"""
def __init__(self, data=None):
self.data = data
self.next = No... |
"""Convert a formatted JSON file into a string for use in a REST call"""
import json
import argparse
def stringify(d):
jsonstr = json.dumps(d, separators=(',', ':'))
return jsonstr.replace('"', '\\"').replace('\n', '\\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argum... |
def capitalize_indices(s, ind=[]):
"""
Given a string and an array of integers representing indices, capitalize all letters at the given indices.
"""
result = []
for index, item in enumerate(s):
if index in ind:
result.append(item.upper())
else:
result.append... |
easy_questions = [
{
'question': 'A 6 stringed instrument prominently used in rock and roll is a ',
'answer': 'guitar'
},
{ 'question': 'The president of the US is ',
'answer': 'Donald Trump'
},
{ 'question': 'We are on planet ',
'answer' : 'Earth'
},
{
... |
symbol = input('Input a symbol:')
while True:
num = int(input('Input an odd number:'))
if num%2 != 0:
break
NumberOfSpaces = int((num-1)/2)
NumberOfSymbol = 1
space = 1
while True:
if NumberOfSymbol == 1:
for i in range(NumberOfSpaces):
print(' ',end = '')
... |
# In the next cell, use filter and lambda to return a list that contains positive numbers only. The output should be:
#
# [1, 4, 5]
import langdetect
from langdetect import detect
from functools import reduce
numbers = [1, 4, -1, -100, 0, 5, -99]
positive_nums_only = list(filter(lambda x: x > 0, numbers))
print("Posit... |
#50.042 FCS Lab 6 template
# Year 2019
import random
def square_multiply(a, x, n):
res = 1
for i in bin(x).lstrip('0b'):
res = res * res % n
if (i == '1'):
res = res * a % n
# return 1
return res
def miller_rabin(n, a):
# n: number
# a: iterations to check
i... |
seq = input("Type a sequence: ")
if seq.find("D") == True OR seq.find("E") == True OR seq.find("F") == True OR seq.find("H") == True OR seq.find("I") == True OR seq.find("K") == True OR seq.find("L") == True OR seq.find("M") == True OR seq.find("N") == True OR seq.find("P") == True OR seq.find("Q") == True OR seq.find... |
from tkinter import *
from tkinter import filedialog
import os
import encryption
import database
from datetime import date
todayDate = str(date.today())
def choose_File():
filename = filedialog.askopenfilename()
entry1.insert(0,str(filename))
def performEncryption():
filePath = entry1.get()... |
#!/usr/bin/env python3
# The goal of the script is to read the CSV file and generate a report with the total number of people in each department.
# To achieve this, we will divide the script into three functions.
# First function: read_employees()
# [Step1] Convert employee data to dictionary
# read_employees()函式接收... |
'''
Пользователь вводит месяц в виде целого числа от 1 до 12.
Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
Напишите решения через list и через dict.
'''
in_month = int(input(f'Введите номер месяца: '))
print('Через list')
LST_YEAR = ['January', 'February', 'March', 'April', 'May', 'June', ... |
from collections import deque
import time
class Graph:
def __init__(self, directed=True):
self.edges = {}
self.directed = directed
def add_edge(self, node1, node2, __reversed=False):
try: neighbors = self.edges[node1]
except KeyError: neighbors = set()
neighb... |
#############################################
# name : Sandiya Venkatesh
# email : SAV49@pitt.edu
# date : Sep 25 2016
# class : CS0008-f2016
# instructor : Max Novelli (man8@pitt.edu)
##############################################
# Description:
# Starting with Python, Chapter 2, Exercise 3
# Notes :
# PROGRAM STA... |
def max_subarray(numbers):
best_sum = numbers[0]
current_sum = numbers[0]
for x in numbers[1:]:
if current_sum < 0 and x > 0:
current_sum = x
else:
current_sum = max(0 if x >= 0 else x, current_sum + x)
best_sum = max(best_sum, curre... |
def find_first_non_repeated(word_dict, letters):
"""
Case is not considered in whether a letter is repeated
Repetition is defined as any letter that occurs two or more times in sequence
Return the first non-repeated letter in a string."""
if len(letters) > 0:
for i in letters:
i... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 17:13:39 2019
@author: PKoora
"""
mystr="192.168."
for val in range(0,2):
mystr1=mystr
mystr1=mystr+str(val)+"."
for val1 in range(1,11):
mystr2=mystr1
mystr2=mystr1+str(val1)
print(mystr2)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 16:45:28 2019
@author: PKoora
"""
alist = ["google.com","unix.com","facebook.com","google.com","linkedin.com"]
unique_list = set(alist)
mylist=[]
for val in unique_list:
mylist.append(len(val))
print(mylist)
|
# -*- coding: utf-8 -*-
"""
umber of digits and letters
@author: PKoora
"""
mylet = 0
mydig = 0
mystr = input("Enter String:")
for char in mystr:
if char.isdigit():
mydig = mydig + 1
else:
mylet = mylet + 1
print("Letters:", mylet)
print("Digits:", mydig)
|
import random
from board import Board
#Take a player input and assign the marker as X or O
def player_input():
while True:
marker = input("Please pick a marker 'X' or 'O': ").upper()
if marker == 'X' or marker == 'O':
return marker
#Randomly decide which player goes first
def choose_fi... |
import re
class VersionChecker:
"""
A library to compare version
...
Attributes
----------
v1 : str
first version (input)
v2 : str
second version (input)
Methods
-------
patternCheck(v1, v2)
Validate pattern of the verion. It should have the following ... |
import re
def split_into_words(sentence):
regexp = "[^а-яА-Яё]"
sentence = re.sub(regexp, " ", sentence)
result = sentence.lower().split()
return result
|
#!/usr/bin python3
""" A simple chat TCP server """
import socket
import select
def broadcast_data(message):
""" Sends a message to all sockets in the connection list. """
# Send message to everyone, except the server.
for sock in CONNECTION_LIST:
if sock != SERVER_SOCKET:
try:
... |
import random
randomNumber = random.randint(0, 11)
print("What number am I thinking of?")
numberGuess = int(input())
while numberGuess != randomNumber:
if numberGuess > randomNumber:
print("No thats too high.")
numberGuess = int(input())
else:
print("No thats too low.")
numberGue... |
from math import sqrt
from heapq import heappop, heappush
TOP, BOTTOM, LEFT, RIGHT = 0, 1, 2, 3
Y, X = 0, 1
def find_path (source_point, destination_point, mesh):
"""
Searches for a path from source_point to destination_point through the mesh
Args:
source_point: starting point of the p... |
import random
import string
"""Defining the list of characters that contains all characters can creating by the keyboard"""
characters_list = list(string.printable)
"""Asking to user for length of password"""
length_of_pasword = int(input("Kaç haneli bir şifre oluşturmak istiyorsunuz ? \n"))
"""Creating a empty list... |
"""
This application takes the followers from the Twitter account. Creates a text document and save the followers.
Given sort sleep times for page load.
"""
import time
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
url = "https://twitter.com/login" # entering the logi... |
#!/usr/bin/env python3
from tkinter import *
# 常用数字和操作符的列表
legal_char = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'+', '-', '=', '*', '/', '^', '\x08', '\x7f', '\r']
calc_op = ['*', '/', '+', '-', '^']
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
def eval_proc(str_exp):
'''... |
"""
Author: Michael Moore
Date: 10/5/20
This program takes a number and a string and returns the string times the number
"""
def multiply_string(n, message):
"""
:param n: number parameter
:param message: string parameter
:return: returns message varible
"""
for i in range(0, n):
messag... |
"""class Dusman:
kalan_can=3
def saldır(self):
print("hücüüüüüüüm")
self.kalan_can-=1
def hayatta_mı(self):
if (self.kalan_can<=0):
print("öldür")
else:
print(str(self.kalan_can)+"canın kaldı")"""
"""class Dusman:
def __init__(self,i... |
import numpy as np
#DERS1
"""apoles=np.array([1,2,3,4,5,6,7,8,9]) #np arrayi tek parametresi var
py_multi=[[1,2,3],[4,5,6],[7,8,9]]
np_multi=apoles.reshape(3,3) #3 e 3 lik matris oluşturuyor
print(py_multi)
print(np_multi)"""
#DERS2
result=np.arange(1,10) #1 ile 10 arasında matris oluşturur
resu... |
import pandas as pd
import numpy as np
data={
"Column1":[1,2,3,4,5,6,7],
"Column2":[12,23,53,24,15,26,47],
"Column3":[13,22,32,43,45,66,77],
"Column4":[11,12,33,45,75,76,27],
"Column1":["ass","bdd","cas","asd","sdf","dsa","bgd"]
}
df=pd.DataFrame(data)
result=df
result=df["Col... |
"""
Solution for 1176. Diet Plan Performance
https://leetcode.com/problems/diet-plan-performance/
"""
class Solution:
"""
Runtime: 236 ms, faster than 100.00% of Python3 online submissions for Diet Plan Performance.
Memory Usage: 23.5 MB, less than 100.00% of Python3 online submissions for Diet Plan Perfor... |
"""
Solution for 282. Expression Add Operators
https://leetcode.com/problems/expression-add-operators/
"""
from typing import List
class Solution:
"""
Runtime: 800 ms, faster than 68.83% of Python3 online submissions for Expression Add Operators.
Memory Usage: 13 MB, less than 100.00% of Python3 online submissio... |
"""
Solution for 277. Find the Celebrity
https://leetcode.com/problems/find-the-celebrity/
"""
from collections import defaultdict
# The knows API is already defined for you.
# return a bool, whether a knows b
def knows(a: int, b: int) -> bool:
pass
class Solution:
"""
Runtime: 1816 ms, faster than 50.28% of Py... |
"""
Solution for 1295. Find Numbers with Even Number of Digits
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
"""
from typing import List
class Solution:
"""
Runtime: 52 ms, faster than 72.87% of Python3 online submissions for Find Numbers with Even Number of Digits.
Memory Usage: 12.8 MB... |
"""
Solution for 45. Jump Game II
https://leetcode.com/problems/jump-game-ii/
"""
class Solution:
"""
Runtime: 60 ms, faster than 51.45% of Python3 online submissions for Jump Game II.
Memory Usage: 14.4 MB, less than 7.50% of Python3 online submissions for Jump Game II.
"""
def jump(self, nums):
... |
"""
Solution for 405. Convert a Number to Hexadecimal
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
"""
class Solution:
"""
Runtime: 32 ms, faster than 88.97% of Python3 online submissions for Convert a Number to Hexadecimal.
Memory Usage: 13.8 MB, less than 50.00% of Python3 online submiss... |
"""
Solution for 1266. Minimum Time Visiting All Points
https://leetcode.com/problems/minimum-time-visiting-all-points/
"""
from typing import List
class Solution:
"""
Runtime: 52 ms, faster than 100.00% of Python3 online submissions for Minimum Time Visiting All Points.
Memory Usage: 12.7 MB, less than 100.00% ... |
"""
Solution for 17. Letter Combinations of a Phone Number
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
"""
class Solution:
"""
Runtime: 36 ms, faster than 81.75% of Python3 online submissions for Letter Combinations of a
Phone Number.
Memory Usage: 13.2 MB, less than 5.86% ... |
"""
Solution for 735. Asteroid Collision
https://leetcode.com/problems/asteroid-collision/
"""
class Solution:
"""
Runtime: 56 ms, faster than 88.84% of Python3 online submissions for Asteroid Collision.
Memory Usage: 14.1 MB, less than 5.00% of Python3 online submissions for Asteroid Collision.
"""
... |
"""
Solution for 1100. Find K-Length Substrings With No Repeated Characters
https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/
"""
class Solution(object):
"""
Runtime: 32 ms, faster than 87.31% of Python online submissions for Find K-Length Substrings With No Repeated Character... |
"""
Solution for 721. Accounts Merge
https://leetcode.com/problems/accounts-merge/
"""
from collections import defaultdict
from typing import List
class Solution:
"""
Runtime: 244 ms, faster than 44.73% of Python3 online submissions for Accounts Merge.
Memory Usage: 27.5 MB, less than 11.11% of Python3 online su... |
"""
Solution for 9. Palindrome Number
https://leetcode.com/problems/palindrome-number/
"""
class Solution:
"""
Runtime: 92 ms, faster than 83.29% of Python3 online submissions for Palindrome Number.
Memory Usage: 13.2 MB, less than 5.03% of Python3 online submissions for Palindrome Number.
"""
def ... |
"""
Solution for 204. Count Primes
https://leetcode.com/problems/count-primes/
"""
class Solution:
"""
Runtime: 488 ms, faster than 61.39% of Python3 online submissions for Count Primes.
Memory Usage: 25.3 MB, less than 79.31% of Python3 online submissions for Count Primes.
"""
def countPrimes(self... |
"""
Solution for Getting a Different Number
https://www.pramp.com/challenge/aK6V5GVZ9MSPqvG1vwQp
"""
def simple_linear_solution(arr):
"""
Simple yet optimal solution that runs in O(N) in time, O(N) in space
Args:
arr(list[int]):
Returns:
int:
"""
hash_table = set(arr)
min... |
"""
Solution for 1160. Find Words That Can Be Formed by Characters
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/
"""
from collections import Counter
class Solution:
"""
Runtime: 420 ms, faster than 100.00% of Python3 online submissions for Find Words That Can Be Formed by Characters... |
"""
Solution for 448. Find All Numbers Disappeared in an Array
"""
class Solution:
"""
Runtime: 136 ms, faster than 91.87% of Python3 online submissions for Find All Numbers Disappeared in an Array.
Memory Usage: 23.2 MB, less than 16.72% of Python3 online submissions for Find All Numbers Disappeared in an... |
"""
Solution for 966. Vowel Spellchecker
https://leetcode.com/problems/vowel-spellchecker/
"""
from typing import List
class Solution:
"""
Runtime: 180 ms, faster than 97.59% of Python3 online submissions for Vowel Spellchecker.
Memory Usage: 15.5 MB, less than 100.00% of Python3 online submissions for Vowel Spe... |
"""
Solution for 113. Path Sum II
https://leetcode.com/problems/path-sum-ii/
"""
# Definition for a binary tree node.
class TreeNode:
"""
Node object for a BT
"""
def __init__(self, x):
"""
Initialization method for a BT
Args:
x: int value for a node
"""
... |
"""
Solution for 295. Find Median from Data Stream
https://leetcode.com/problems/find-median-from-data-stream/
"""
import heapq
import bisect
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.list = []
self.low_heap, self.high_heap = [], []
def addNum(s... |
"""
Solution for 1023. Camelcase Matching
https://leetcode.com/problems/camelcase-matching/
"""
class Solution:
"""
Runtime: 36 ms, faster than 80.25% of Python3 online submissions for Camelcase Matching.
Memory Usage: 13.8 MB, less than 7.14% of Python3 online submissions for Camelcase Matching.
"""
... |
"""
Solution for 297. Serialize and Deserialize Binary Tree
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import de... |
"""
Solution for 582. Kill Process
https://leetcode.com/problems/kill-process/
"""
from collections import defaultdict
from collections import deque
from typing import List
class Solution:
"""
Runtime: 464 ms, faster than 97.55% of Python3 online submissions for Kill Process.
Memory Usage: 22.6 MB, less than 100... |
"""
Solution for 771. Jewels and Stones
https://leetcode.com/problems/jewels-and-stones/
"""
from collections import Counter
class Solution:
"""
Runtime: 36 ms, faster than 96.62% of Python3 online submissions for Jewels and Stones.
Memory Usage: 13.3 MB, less than 12.48% of Python3 online submissions for ... |
"""
Solution for 1146. Snapshot Array
https://leetcode.com/problems/snapshot-array/
"""
import bisect
class SnapshotArray:
"""
Runtime: 560 ms, faster than 100.00% of Python3 online submissions for Snapshot Array.
Memory Usage: 45 MB, less than 100.00% of Python3 online submissions for Snapshot Array.
... |
"""
Solution for 5296. All Elements in Two Binary Search Trees
https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
"""
import bisect
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.righ... |
"""
Solution for 581. Shortest Unsorted Continuous Subarray
https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
"""
class Solution:
"""
Runtime: 236 ms, faster than 83.62% of Python3 online submissions for Shortest Unsorted Continuous Subarray.
Memory Usage: 15.1 MB, less than 5.48% of Pyt... |
"""
Solution for 916. Word Subsets
"""
from collections import Counter
class Solution:
"""
Runtime: 1324 ms, faster than 12.43% of Python3 online submissions for Word Subsets.
Memory Usage: 16 MB, less than 89.52% of Python3 online submissions for Word Subsets.
"""
def wordSubsets(self, A, B):
... |
"""
Solution for 2. Add Two Numbers
https://leetcode.com/problems/add-two-numbers/
"""
# Definition for singly-linked list.
class ListNode:
"""
ListNode object for LinkedList
"""
def __init__(self, x):
"""
Initialization method
Args:
x: a value for the particular node... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.