text
stringlengths
37
1.41M
# Write a Python program to convert a list of tuples into a dictionary t1 = [("x", 1), ("x", 2), ("x", 3), ("y", 1), ("y", 2), ("z", 1)] d = {} for a,b in t1: d.setdefault(a,[]).append(b) print(d)
from itertools import groupby from collections import defaultdict import os class Connecting_Cities: def __init__(self, source, dest, textFile): self.source = source self.dest = dest self.textFile = textFile """ Paired cities fetched line wise from textfile and converted to adjac...
# 커피 함수 num=0; num=int(input("어떤 커피 드릴까요? (1:보통 2:설탕 3:블랙) ")) print("# 1. 뜨거운 물을 준비한다.") print("# 2. 종이컵을 준비한다.") if num==1: print("# 3.보통커피를 탄다.") elif num==2: print("# 3. 설탕커피를 탄다.") elif num==3: print("# 3. 블랙커피를 탄다.") else: print("# 3. 아무 커피나 탄다.") print("# 4. 물을 붓는다.") print("# ...
number=int(input("참석자의 수를 입력하시오:")) chickens=number beers=number*2 cakes=number*4 print("치킨의 수:",chickens) print("맥주의 수:",beers) print("케익의 수:",cakes)
##변수 선언 부분 money, c500, c100, c50, c10=0,0,0,0,0 ##메인(MAIN)코드 부분 money=int(input("교환할 돈을 얼마 입니까?")) c500=money//500 money%=500 c100=money//100 money%=100 c50=money//50 money%=50 c10=money//10 money%=10 print("\n 오백원짜리==> %d 개입니다." %c500) print(" 백원짜리==> %d 개입니다." %c100) print(" 오십원짜리==> %d 개입니다." %c...
# 변수 선언 부분 i,k, heartNum=0,0,0 numStr,ch, heartStr="","","" ## 메인(main) 코드 부분 numStr=input("숫자를 여러 개 입력하세요 : ") print("") i=0 ch=numStr[i] while True: heartNum=int(ch) heartStr="" for k in range(0,heartNum): heartStr+="\u2665" k+=1 print(heartStr) i+=1 i...
#gugudan chart reverse ##변수 선언 부분 i,k,guguLine=0,0,"" ## main code for i in range(9,1,-1): guguLine=guguLine+(" #%d단 "%i) print(guguLine) for i in range(1,10): guguLine="" for k in range(9,1,-1): guguLine=guguLine+str("%dX%d=%2d "%(k,i,k*i)) print(guguLine)
#1~100까지의 합을 구하되 3의 배수를 건너뛰고 더하는 프로그램 hap=0 for i in range(1,101): if i%3==0: continue hap+=i print("1~100까지의 합 %d"%hap)
##find a string between two strings. #return the string or None def find_substring( s, first, last ): try: start = s.find( first ) + len( first ) end = s.find( last, start ) if start >= 0 and end >= 0: return s[start:end] else: return None except ValueErro...
#!/usr/bin/env python # coding: utf-8 # In[1]: #!/usr/bin/env python # coding: utf-8 # In[2]: import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import stats # Assumptions: # # Two potential outcome per trial # # Probability of success is same across all trials # # Each trial i...
welcome = "Welcome to my Nightmare", "Alice Cooper", 1975 bad = "Bad Company", "Bad Company", 1974 budgie = "Nightflight", "Budgie", 1981 imelda = "More Mayehm", "Imilda May", 2011 metallica = "Ride the Lightning", "Metallica", 1984 metallica2 = ["Ride the Lightning", "Metallica", 1984] # title, artist, year = imelda ...
# The escape character split_string = "This string has been \nsplit over\nseveral\nlines" print(split_string) print() tabbed_string = "1\t2\t3\t4\t5" print(tabbed_string) print() print('The pet shop owner said "No, no, \'e\'s uh, ... he\'s resting".') print("The pet shop owner said \"No, no, \'e\'s uh, ... he's restin...
__author__ = 'dev' fruit = {"orange": "a sweet, orange, citrus fruit", "apple": "good for making cider", "lemon": "a sour, yellow, citrus fruit", "grape": "a small, sweet, fruit growing in bunches", "lime": "a sour, green, citrus fruit"} print(fruit) # fruitKeys = fruit.keys() # pr...
__author__ = 'dev' string = '1234567890' # for char in string: # print(char) # myIter = iter(string) # print(myIter) # # 1 # print(next(myIter)) # # 2 # print(next(myIter)) # # 3 # print(next(myIter)) # # 4 # print(next(myIter)) # # 5 # print(next(myIter)) # # 6 # print(next(myIter)) # # 7 # print(next(myIter)) ...
__author__ = 'dev' # # Tuples are an ordered set of data # # A tuple is imutable, unlike lists # # Tuples are not necessarily parenthesis where lists are square brackets # # but parenthesis are often used to remove ambiguity # # t = 'a', 'b', 'c' # # t is a tuple # print(t) # # but this print statement doesn't display...
__author__ = 'dev' # print('Hello World!') # print() # print(1 + 2) # print() # print(3*'hello') # print() # print(7*6) # print() # print('The End') # print() # print('Hello' + 'World') # print() # print("'Allo World") # print() # print('"hello" world...') # # greeting = 'Hello' # name = 'Chris' # print(greeting + ' '...
decimals = range(0, 100) my_range = decimals[3:40:3] print(my_range == range(3, 40, 3)) print(range(0, 5, 2) == range(0, 6, 2)) print(list(range(0, 5, 2))) print(list(range(0, 6, 2))) r = range(0, 100) print(r) for i in r[::-2]: print(i) print() for i in range(99, 0, -2): print(i) print() print(range(0, 100)[...
import typ @typ.typ(items=[int]) def radix_sort(items): """ >>> radix_sort([]) [] >>> radix_sort([1]) [1] >>> radix_sort([2,1]) [1, 2] >>> radix_sort([1,2]) [1, 2] >>> radix_sort([1,2,2]) [1, 2, 2] """ radix = 10 max_len = False tmp, placement = -1, 1 while not max_len: max_len = Tr...
import typ @typ.typ(items=[int]) def quick_sort(items): """ >>> quick_sort([]) [] >>> quick_sort([1]) [1] >>> quick_sort([2,1]) [1, 2] >>> quick_sort([1,2]) [1, 2] >>> quick_sort([1,2,2]) [1, 2, 2] """ if len(items) == 0: return [] left = 0 right = len(items) -1 temp_stack = [] te...
import typ @typ.typ(items=[int]) def cocktail_sort(items): """ >>> cocktail_sort([]) [] >>> cocktail_sort([1]) [1] >>> cocktail_sort([2,1]) [1, 2] >>> cocktail_sort([1,2]) [1, 2] >>> cocktail_sort([1,2,2]) [1, 2, 2] """ for k in range(len(items)-1, 0, -1): swapped = False for i in ran...
import typ @typ.typ(items=[int]) def heap_sort(items): """ >>> heap_sort([]) [] >>> heap_sort([1]) [1] >>> heap_sort([2,1]) [1, 2] >>> heap_sort([1,2]) [1, 2] >>> heap_sort([1,2,2]) [1, 2, 2] """ # in pseudo-code, heapify only called once, so inline it here for start in range((len(items)-2)...
# source: http://danishmujeeb.com/blog/2014/01/basic-sorting-algorithms-implemented-in-python import typ import random @typ.typ(items=[int]) def bubble_sort(items): """ >>> bubble_sort([]) [] >>> bubble_sort([1]) [1] >>> bubble_sort([2,1]) [1, 2] >>> bubble_sort([1,2]) [1, 2] >>> bubble_sort([1,2,...
# Changes a written number into an actual number. # assumes no things like "thousand million" or "billion billion" # commas and hyphens OK as long as there are spaces or hypnens between words def num_word(num): """Convert word to number Ok with hyphens, commas, ands : as long as there are spaces or hyphens...
import math #V1 """ iを1づつ増やし照合する。 {num % i, i++} """ def is_prime_v1(num: int) -> bool: if num <= 1: return False for i in range(2, num): if num % i == 0: return False return True #V2 """ 素数の照合を√iまでにする。 {num % √i, i++} """ def is_prime_v2(num: int) -> bool: if num <= 1:...
time = int(input('enter the number : ')) day = time // 86400 z = time % 86400 hrs = z // 3600 y = z % 3600 mn = y // 60 sec = y % 60 print(day, 'days and', hrs, 'hours and', mn, 'min and', sec, 'seconde')
#Importing necessary libraries import pandas as pd import streamlit as st from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import StandardScaler #Setting the header components def local_css(file_name): with open(file_nam...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 6 19:30:49 2021 @author: ironman """ class BST: def __init__(self,value): self.value=value self.left=None self.right=None def insert(self,value): currentnode=self while True: if ...
#! /usr/bin/env python import random def insertion_sort(unsorted_list): if len(unsorted_list) == 1: return unsorted_list j = 1 while j < len(unsorted_list): key = unsorted_list[j] i = j - 1 while i >= 0 and unsorted_list[i] > key: unsorted_list[i+1] = unsorted...
class DoubleLinkNode(object): def __init__(self, data=None): self.data = data self.front = None self.back = None class DoubleLink(object): def __init__(self, l=None): if l == None: self.data = DoubleLinkNode() pass else: self.head =...
## Dictionary # dict = {1:"one", 2:"two", 3:"four", 4:"five"} dict['3'] = "three" del dict[4] if(4 in dict): print("dict contains 4") else: print("dict doesn't contain 4") for k in dict.keys(): print(k,":",dict[k]) for tuple in dict.items(): print(tuple)
# For reduce from functools import reduce ## Lambda a = [1, 2, 3, 4] print(a) b = list(map(lambda x: x ** 2, a)) print(b) c = list(map(lambda x, y: x + y, a, b)) print(c) ## Filters ##condition d = list(filter(lambda x: x % 2 == 0, b)) print(d) ## Reduce e = reduce(lambda x,y: x+y, d) pri...
from Student import Student s = Student("melwin",123,25) s.display() s.course='python' #instance variable # Python's garbage collector runs during program execution # and is triggered when an object's reference count reaches # zero. An object's reference count changes as the number # of aliases that point to it ...
def bad_fibonacci(n): """Return the nth Fibonacci number.""" if n <= 1: return n else: return bad_fibonacci(n - 2) + bad_fibonacci(n-1) def fibonacci(n): if n <= 1: return n else: fib = [] for j in range(0, n): fib.append(fibonacci(j)) ret...
import Progression class GeometricProgression(Progression): """Iterator producing a geometric progression.""" def __init__(self, base=2, start=1): """Create a new geometric progression. base the fixed constant multiplied to each term (default 2) start the first term of the progre...
# Write a short recursive Python function that determines if a string s is a palindrome, that is, # it is equal to its reverse. For example, racecar and gohangasalamiimalasagnahog are palindromes. def is_palindrome(s): if len(s) <= 1: return True else: return s[0] == s[-1] and is_palindrome(s[...
# Write a pseudo-code description of a function that reverses a list of n integers, # so that the numbers are listed in the opposite order than they were before, # and compare this method to an equivalent Python function for doing the same thing. seq = [ k for k in range(0,10)] def reverse(data): for i in range(...
# Write a short Python function that takes a sequence of integer values and determines # if there is a distinct pair of numbers in the sequence whose product is odd. data = [k for k in range(0, 10)] cross_product = [(a, b) for a in data for b in data] results = {} for i in cross_product: n = i[0] * i[1] i...
# Describe a recursive algorithm to compute the integer part of the base-two logarithm # of n using only addition and integer division. def binary_log(n): if n < 2: return 1 else: return binary_log(n/2) + 1 binary_log(8)
# Write a Python class, Flower, that has three instance variables of type # str, int, and float, that respectively represent the name of the flower, # its number of petals, and its price. Your class must include a constructor # method that initializes each variable to an appropriate value, and your # class should inc...
def score(word): scores = { 1: 'aeioulnrst', 2: 'dg', 3: 'bcmp', 4: 'fhvwy', 5: 'k', 8: 'jx', 10: 'qz' } letters = {} for score, group in scores.items(): for l in group: letters[l] = score return sum([l...
cube = lambda x: x**3 #lambda function def fibonacci(n): #iterable li = [0,1] a,b = 0,1 if n == 0 : return [] elif n == 1: return [0] else: while len(li) < n: s = a + b li.append(s) a = b b = s return li ...
q = input("Do you agree? : ") if q.lower() in ["y", "yes"]: print("Agreed!") elif q.lower() in ["n", "no"]: print("Not Agreed!") else : print("Please write Yes or No!")
# Looping over a list names = ["Bastav", "Sam", "Johny"] for name in names: print(name) # Looping over a string name = "Bastav" for character in name: print(character)
fno = int(input("Enter the first number: ")) sno = int(input("Enter the second number: ")) if fno> sno : print(f"{fno} is greater than{sno}") elif sno>fno: print(f"{sno} is greater than {fno}") else: print("Both the number are equal!")
import numpy as np import scipy as np import pandas as pd import matplotlib.pyplot as plt def rv(value_list): return np.array([value_list]) def cv(value_list): return np.transpose(rv(value_list)) def f1(x): return float((2 * x + 3)**2) def df1(x): return 2 * 2 * (2 * x + 3) def f2(v): x = float...
import numpy as np class Module(): pass class ReLU(Module): """ ReLU """ def forward(self, Z, dropout_pct=0.): # Z is a column vector of pre-activations; # return A a column vector of activations keep_pct = 1 - dropout_pct mask = np.random.binomial(1, keep_pct, Z.s...
from time import sleep #because we want to print simultaneously both(Hello,Hi) from threading import * class Hello(Thread): #first thread def run(self): for i in range(5): print("Hello") sleep(1) class Hi(Thread): #second thread def run(self): for i in range(5): ...
from functools import reduce nums = [3,2,3,4,5,8,6,7,5] #filter is a in built function in python evens = list(filter(lambda n : n%2==0,nums)) doubles = list(map(lambda n : n*2,evens)) print(doubles) sum = reduce (lambda a,b : a+b,doubles) print(sum) print(evens) ''' Output [4, 8, 16, 12] 40 [2, 4, 8, 6] '''
class A: def __init__(self): print("in A Init") def feature1(self): print("Feature 1-A working") def feature2(self): print("Feature 2 working") class B: def __init__(self): print("in B Init") def feature1(self): pri...
class Car: wheels = 4 #Class Variable def __init__(self): self.mil = 10 #Insrance Variable self.com = "BMW" #Insrance Variable c1 = Car() c2 = Car() c1.mil = 8 print(c1.com , c1.mil, c1.wheels) print(c2.com , c2.mil, c2.wheels)
input_list = [int(i) for i in input("Список чисел ").split()] def reverse(list): if len(list) > 0: print(list[-1]) reverse(list[:-1]) else: print() reverse(input_list) input()
# Користувач вводить довжини двох катетів kat1 = float(input()) kat2 = float(input()) # Прорама виводить площу цього прямкутного трикутника print (kat1 * kat2 / 2)
point_1 = [int(i) for i in input('Введите через пробел \ две координаты 1ой точки: ').split()] point_2 = [int(i) for i in input('Введите через пробел \ две координаты 2ой точки: ').split()] def distance(point1, point2): return (((point2[0] - point1[0])**2) + (point2[1] - point1[1])**2)**0.5 print(distan...
from graphics import * win = GraphWin("Bresenham",1000,1000) def midPoint(X1,Y1,X2,Y2): # calculate dx & dy dx = X2 - X1 dy = Y2 - Y1 d = dy - (dx/2) x = X1 y = Y1 #print(x,",",y,"\n") while (x < X2): x=x+1 if(d < 0): ...
import json JSON_FILE ='./data.json' def Find_Index(_list, id): for i in _list: if i["id"] == id: return i return "data don't here" with open(JSON_FILE,'r') as fr: data = json.load(fr) INP = input("Enter your ID:") Value = Find_Index(data["Bio"],INP) print(Value)
#!/c/Users/christian/AppData/Local/Programs/Python/Python36/python import time import random import os low = 10 high = 101 def getBetween (low, high): return random.randint (low, high+1) def get1_10_1 (): return random.randint (1, 11) def get1_100_1 (): return random.randint (1, 101) def get1_100_10 ()...
# sisendid vanus = int(input("Sisesta enda vanus: ")) sugu = input("Sisesta oma sugu: ") treening = int(input("Sisesta treeningu tüüp: ")) # sugu kontroll ja max_pulsi_sageduse arvutamine if sugu == "M" or sugu == "m": max_pulsi_sagedus = 220 - vanus if sugu == "N" or sugu == "n": max_pulsi_sagedus = 206 - van...
from kitchen import Rosemary from kitchen.utensils import Bowl, Oven, Plate, BakingTray from kitchen.ingredients import Flour, Egg, Salt, Butter, Sugar, ChocolateChips, BakingPowder oven = Oven.use() #Remember to preheat the oven before we start oven.preheat(degrees=175) bowl = Bowl.use (name='batter') # Cream toget...
import math from math import sqrt import numbers def zeroes(height, width): """ Creates a matrix of zeroes. """ g = [[0.0 for _ in range(width)] for __ in range(height)] return Matrix(g) def identity(n): """ Creates a n x n identity matrix. """ I...
def check_brackets(input_string): br_opening = '{[(' br_closing = '}])' br_closes = dict(zip(br_closing, br_opening)) br_stack = [] for ch in input_string: if ch in br_opening: br_stack.append(ch) if ch in br_closing: if br_stack and br_closes[ch] == br_stack[...
def flatten(iterable, flattened=None): if flattened == None: flattened = [] for it in iterable: if type(it) in (list, set, tuple): flatten(it, flattened) else: flattened.append(it) return [el for el in flattened if el is not None]
def rotate(text, rot): alphabet = 'abcdefghijklmnopqrstuvwxyz' alow = [c for c in alphabet] aupp = [c for c in alphabet.upper()] cipher_dict = dict(zip(alow + aupp, alow[rot:] + alow[:rot] + aupp[rot:] + aupp[:rot])) return ''.join([cipher_dict[c] if c.isalpha() else c for c in text])
from selenium import webdriver from selenium.webdriver.support.ui import Select import time import math def calc(sum): return str(x+y) link = "http://suninjuly.github.io/selects1.html" browser = webdriver.Chrome() browser.get(link) num1 = browser.find_element_by_id("num1") x = int(num1.text) num2 = browser.find_el...
#!/usr/bin/python import sys sys.setrecursionlimit(922331728) denominations = [1, 5, 10, 25, 50] def making_change(amount, denominations, cache=None, current_amount=1): if amount == 0: return 1 if amount < 0: return 0 # init the cache if cache == None: # for each amount have ...
from room import Room from player import Player # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons", 'N'), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east.""", 'S', 'N', 'E')...
# Stepanov Nikita from random import randrange def start(): print( 'У одного из учеников не получается домашка и ' 'нужно помочь ему и разобрать ошибки. Для этого есть выход - ' 'нам нужен ментон Утка-тив 🦆 🕵️ , поможем?' ) option = '' options = {'да': True, 'нет': False} ...
def addition(num_list, index_first_num, index_second_num): # print(num_list) # print(num_list[index_first_num]) # print(num_list[index_second_num]) return num_list[index_first_num] + num_list[index_second_num] def multiple(num_list, index_first_num, index_second_num): return num_list[index_first_n...
import cv2 import numpy as np import os import canny def edge_mask(img, line_size, blur_value): ''' This functions creates an edge mask for given image using canny and dilation Input: img numpy array given image to create its edge mask Output: edges numpy array the edge mask of...
#csv and pickle module import import csv, pickle #definition of readcsv function that takes CSV's and processes information back to the user as variable a ###ONLY WORKS WHEN FILES ARE FORMATED AS CSV'S!!! def readcsv(filename): try: ###opens passed parameter filename and sorts using comma separation ...
# -*- coding: utf-8 -*- """ Created on Tue Oct 8 19:56:04 2019 Nathan Marshall An animated random walk where each step of the particle is in the direction of a random unit vector. """ #%% import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from random import gauss from matplotlib.animation import...
# -*- coding: utf-8 -*- """ Created on Tue Oct 29 13:38:36 2019 @author: David Engel The point of this code is to solve the LaPlace equation for a square in a square. """ #import necessary code import numpy as np import matplotlib.pyplot as plt #size of matix z=100 #creates the matrix with zeros shee...
# -*- coding: utf-8 -*- """ Created on Mon Sep 02 21:21:28 2019 @author: Vandi this doesn't work """ import numpy as np number = 600851475143 maximum = round(number**(1/2)) def isprime(number): prime = True for i in range(2, int(number**(1/2))): if number % i == 0: ...
# -*- coding: utf-8 -*- """ Created on Tue Aug 27 15:30:14 2019 Nathan Marshall Solution to Project Euler Problem 7 """ #%% def primefind(num, primes): ''' Updated prime number finder. Checks divisibility of a number by a list of prime numbers up to its square root. If it is not divisible by any of the...
# -*- coding: utf-8 -*- """ Created on Tue Oct 8 13:10:43 2019 Nathan Marshall Random walk in 1D """ #%% import numpy as np import matplotlib.pyplot as plt num_steps = 1000 dx = 1 x0 = 0 t = np.arange(0, num_steps+1) x = [x0] for i in range(0, num_steps): x.append(x[-1] + np.random.choice([-dx, dx])) fig1 = plt...
# -*- coding: utf-8 -*- """ Created on Thu Oct 24 13:55:18 2019 @author: David Engel The point of this code is to simulate particles with spins flipping up or down based off of the spin of nearby particles. """ #import necessary code import numpy as np import matplotlib.pyplot as plt import matplotlib.ani...
# -*- coding: utf-8 -*- """ Created on Thu Aug 29 14:12:32 2019 Nathan Marshall This algorithm finds the global minimum in a discrete function. It does this by indexing through the list of the values of the function and saving the minumum number that it finds. It is shown here finding the global minimum of x**2-5*x+6...
# -*- coding: utf-8 -*- """ Created on Sun Oct 13 17:52:15 2019 PHYS 639 >>> Assignments >>> Week 6 >>> ODE III HUYNH LAM """ #%% #(T1-T3) A particle starts at the origin and randomly moves either left or right with equal probability at each step. Write a code that simulates this process. #Plot position vs ...
# -*- coding: utf-8 -*- """ Created on Tue Aug 27 13:25:59 2019 Nathan Marshall Solution to Project Euler Problem 1 """ #%% import numpy as np mult3 = [] #lists to contain the multiples of 3 and 5 mult5 = [] for i in range(1, 1000): #loop through i values 1 to 999 if i % 3 == 0: #if i is divisible by three, add t...
# -*- coding: utf-8 -*- """ Created on Thu Aug 29 13:12:05 2019 Nathan Marshall This algorithm numerically evaluates the integral of a function f(x). Here it is shown evaluating the integral from 0 to pi of sin(x) """ #%% import numpy as np num = 1000 #number of x points to be generated xmin = 0 #minimum x value xmax ...
# importing libraries import speech_recognition as sr import pandas as pd import os from pydub import AudioSegment from pydub.silence import split_on_silence from rasa.nlu.training_data import load_data from rasa.nlu.config import RasaNLUModelConfig from rasa.nlu.model import Trainer from rasa.nlu...
# # @lc app=leetcode id=57 lang=python3 # # [57] Insert Interval # # https://leetcode.com/problems/insert-interval/description/ # # algorithms # Hard (32.73%) # Likes: 1471 # Dislikes: 172 # Total Accepted: 238.6K # Total Submissions: 721.7K # Testcase Example: '[[1,3],[6,9]]\n[2,5]' # # Given a set of non-overl...
# # @lc app=leetcode id=16 lang=python3 # # [16] 3Sum Closest # # https://leetcode.com/problems/3sum-closest/description/ # # algorithms # Medium (45.73%) # Likes: 1732 # Dislikes: 123 # Total Accepted: 436K # Total Submissions: 953.4K # Testcase Example: '[-1,2,1,-4]\n1' # # Given an array nums of n integers an...
# # @lc app=leetcode id=126 lang=python3 # # [126] Word Ladder II # # https://leetcode.com/problems/word-ladder-ii/description/ # # algorithms # Hard (20.79%) # Likes: 1701 # Dislikes: 243 # Total Accepted: 181.4K # Total Submissions: 834.8K # Testcase Example: '"hit"\n"cog"\n["hot","dot","dog","lot","log","cog"...
# # @lc app=leetcode id=305 lang=python3 # # [305] Number of Islands II # # https://leetcode.com/problems/number-of-islands-ii/description/ # # algorithms # Hard (40.15%) # Likes: 841 # Dislikes: 21 # Total Accepted: 76.8K # Total Submissions: 191.4K # Testcase Example: '3\n3\n[[0,0],[0,1],[1,2],[2,1]]' # # A 2d...
# # @lc app=leetcode id=200 lang=python3 # # [200] Number of Islands # # https://leetcode.com/problems/number-of-islands/description/ # # algorithms # Medium (45.10%) # Likes: 4620 # Dislikes: 173 # Total Accepted: 609.1K # Total Submissions: 1.3M # Testcase Example: '[["1","1","1","1","0"],["1","1","0","1","0"]...
# # @lc app=leetcode id=77 lang=python3 # # [77] Combinations # # https://leetcode.com/problems/combinations/description/ # # algorithms # Medium (52.54%) # Likes: 1336 # Dislikes: 66 # Total Accepted: 278.5K # Total Submissions: 520.5K # Testcase Example: '4\n2' # # Given two integers n and k, return all possib...
# # @lc app=leetcode id=354 lang=python3 # # [354] Russian Doll Envelopes # # https://leetcode.com/problems/russian-doll-envelopes/description/ # # algorithms # Hard (34.98%) # Likes: 981 # Dislikes: 37 # Total Accepted: 62.8K # Total Submissions: 178.5K # Testcase Example: '[[5,4],[6,4],[6,7],[2,3]]' # # You ha...
# # @lc app=leetcode id=64 lang=python3 # # [64] Minimum Path Sum # # https://leetcode.com/problems/minimum-path-sum/description/ # # algorithms # Medium (51.32%) # Likes: 2389 # Dislikes: 52 # Total Accepted: 340.6K # Total Submissions: 655.4K # Testcase Example: '[[1,3,1],[1,5,1],[4,2,1]]' # # Given a m x n gr...
# # @lc app=leetcode id=296 lang=python3 # # [296] Best Meeting Point # # https://leetcode.com/problems/best-meeting-point/description/ # # algorithms # Hard (57.00%) # Likes: 442 # Dislikes: 36 # Total Accepted: 34.7K # Total Submissions: 60.6K # Testcase Example: '[[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]' # # A g...
# # @lc app=leetcode id=737 lang=python3 # # [737] Sentence Similarity II # # https://leetcode.com/problems/sentence-similarity-ii/description/ # # algorithms # Medium (45.71%) # Likes: 492 # Dislikes: 31 # Total Accepted: 41.2K # Total Submissions: 90.1K # Testcase Example: '["great","acting","skills"]\n' + '...
# # @lc app=leetcode id=773 lang=python3 # # [773] Sliding Puzzle # # https://leetcode.com/problems/sliding-puzzle/description/ # # algorithms # Hard (57.38%) # Likes: 643 # Dislikes: 21 # Total Accepted: 36.8K # Total Submissions: 62.6K # Testcase Example: '[[1,2,3],[4,0,5]]' # # On a 2x3 board, there are 5 til...
# # @lc app=leetcode id=34 lang=python3 # # [34] Find First and Last Position of Element in Sorted Array # # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ # # algorithms # Medium (35.27%) # Likes: 2850 # Dislikes: 127 # Total Accepted: 448.4K # Total Submission...
# # @lc app=leetcode id=530 lang=python3 # # [530] Minimum Absolute Difference in BST # # https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ # # algorithms # Easy (52.58%) # Likes: 758 # Dislikes: 62 # Total Accepted: 83.3K # Total Submissions: 157.5K # Testcase Example: '[1,null,3,2]'...
# # @lc app=leetcode id=349 lang=python3 # # [349] Intersection of Two Arrays # # https://leetcode.com/problems/intersection-of-two-arrays/description/ # # algorithms # Easy (60.04%) # Likes: 701 # Dislikes: 1118 # Total Accepted: 329.6K # Total Submissions: 544.2K # Testcase Example: '[1,2,2,1]\n[2,2]' # # Give...
# # @lc app=leetcode id=212 lang=python3 # # [212] Word Search II # # https://leetcode.com/problems/word-search-ii/description/ # # algorithms # Hard (32.40%) # Likes: 2303 # Dislikes: 105 # Total Accepted: 196.4K # Total Submissions: 584.8K # Testcase Example: '[["o","a","a","n"],["e","t","a","e"],["i","h","k",...
# 291. Second Diameter # 中文English # Given a tree consisting of n nodes, n-1 edges. Output the second diameter of a tree, namely, the second largest value of distance between pairs of nodes. # Given an array edge of size (n-1) \times 3(n−1)×3, and edge[i][0], edge[i][1] and edge[i][2] indicate that the i-th undirected ...
# # @lc app=leetcode id=256 lang=python3 # # [256] Paint House # # https://leetcode.com/problems/paint-house/description/ # # algorithms # Easy (51.35%) # Likes: 744 # Dislikes: 78 # Total Accepted: 81.9K # Total Submissions: 158.9K # Testcase Example: '[[17,2,17],[16,16,5],[14,3,19]]' # # There are a row of n h...
# # @lc app=leetcode id=78 lang=python3 # # [78] Subsets # # https://leetcode.com/problems/subsets/description/ # # algorithms # Medium (58.50%) # Likes: 3130 # Dislikes: 73 # Total Accepted: 511.6K # Total Submissions: 869.2K # Testcase Example: '[1,2,3]' # # Given a set of distinct integers, nums, return all p...
# # @lc app=leetcode id=422 lang=python3 # # [422] Valid Word Square # # https://leetcode.com/problems/valid-word-square/description/ # # algorithms # Easy (37.17%) # Likes: 166 # Dislikes: 113 # Total Accepted: 28.8K # Total Submissions: 76.7K # Testcase Example: '["abcd","bnrt","crmy","dtye"]' # # Given a sequ...
from copy import deepcopy START_STATE = ([4]*6 + [0])*2 class PocketName: num_pockets = 14 p0_mancala = 6 p1_mancala = 13 p0_pockets = list(range(6)) p1_pockets = list(range(12,6,-1)) class GameState: def __init__(self, init_state=START_STATE, player_turn=0, stealing=True): self.s...