text stringlengths 37 1.41M |
|---|
'''
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the ... |
'''
We are given two sentences A and B. (A sentence is a string of space
separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list i... |
'''
Given an array of distinct integers arr, where
arr is sorted in ascending order, return the smallest
index i that satisfies arr[i] == i. If there is no such index, return -1.
'''
class Solution:
def fixedPoint(self, arr: List[int]) -> int:
for i in range(len(arr)):
... |
'''
You are given a 0-indexed integer array nums.
Swaps of adjacent elements are able to be performed on nums.
A valid array meets the following conditions:
The largest element (any of the largest elements if there are multiple) is at the rightmost position in the array.
The smallest element (any of the smallest ele... |
'''
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integ... |
'''
Given a two-dimensional integer list intervals of the form [start, end] representing intervals (inclusive), return their intersection, that is, the interval that lies within all of the given intervals.
You can assume that the intersection will be non-empty.
'''
class Solution:
def solve(self, intervals):
... |
'''
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the... |
'''
Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each l... |
'''
We define str = [s, n] as the string str which consists of the string s concatenated n times.
For example, str == ["abc", 3] =="abcabcabc".
We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.
For example, s1 = "abc" can be obtained from s2 = "a... |
'''
You are given an integer array nums consisting of 2 * n integers.
You need to divide nums into n pairs such that:
Each element belongs to exactly one pair.
The elements present in a pair are equal.
Return true if nums can be divided into n pairs, otherwise return false.
'''
class Solution:
def divideArray(se... |
'''
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the ... |
'''
Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s palindrome.
A Palindrome String is one that reads the same backward as well as forward.
'''
class Solution:
def minInsertions(self, S: str) -> int:
L = len(S)
DP... |
'''
You are given a string s consisting of lowercase English letters. A duplicate
removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be prove... |
'''
You are given an integer array nums.
In one move, you can choose one element of nums and change it to any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
'''
If the size <= 4, then just delete all the elements and either no or one element... |
'''
Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall.
Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Ali... |
'''
Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum
number of letters that must be inserted so that word becomes valid.
A string is called valid if it can be formed by concatenating the string "abc" several times.
'''
class Solution:
def ad... |
'''
You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before cours... |
'''
You are given a 0-indexed integer array books of length n where books[i] denotes the number of books on the ith shelf of a bookshelf.
You are going to take books from a contiguous section of the bookshelf spanning from l to r where 0 <= l <= r < n. For each index i in the range l <= i < r, you must take strictly f... |
'''
Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the n... |
'''
Given a string s, return its run-length encoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters.
'''
from itertools import groupby
class Solution:
def solve(self, s):
res = list()
for c, g in groupby(s):
res.append([len(list... |
#Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
def f(s,t):
s1, s2 = [],[]
for i in range(len(s)):
if s[i] == '#':
if s1:
s1.pop()
else:
s1.append(s[i])
for i in range(... |
'''
Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
'''
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
codes = set()
for i in range(len(s) - k + 1):
codes.add(s[i:i+k])
retur... |
'''
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.
You are given two arrays redEdges and blueEdges where:
redEdges[i] = [ai, bi] indicates that there is a directe... |
'''
You are given two integers m and n, which represent the dimensions of a matrix.
You are also given the head of a linked list of integers.
Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining ... |
'''
On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:
The north direction is the positive direction of the y-axis.
The south direction is the negative direction of the y-axis.
The east direction is the positive direction of the x-axis.
The west direction is the negative direction of ... |
'''
You are given a string word that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".
... |
'''
Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:
The height of the tree is height and the number of rows m should be equal to height + 1.
The number of columns ... |
'''
You are given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value val in the range [1, 2n - 1 - 1] has two children where:
The left node has the value 2 * val, and
The right node has the value 2 * val + 1.
You are also giv... |
'''
Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
'''
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
#a+c > b
#a+b > c
#b+c > a
nums.sort()
r... |
'''
You are given a 2D integer array stockPrices
where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A
line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent ... |
'''
Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.
For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.
Note... |
'''
You are given a 0-indexed array of string words and two integers left and right.
A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a', 'e', 'i', 'o', and 'u'.
Return the number of vowel strings words[i] where i belongs to the inclusiv... |
'''
Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.
'''
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
(x0, y... |
'''
You are given a positive integer n.
Continuously replace n with the sum of its prime factors.
Note that if a prime factor divides n multiple times, it should be included in the sum as many times as it divides n.
Return the smallest value n will take on.
'''
class Solution:
def prime_factors(self, n):
... |
'''
There is a special typewriter with lowercase English
letters 'a' to 'z' arranged in a circle with a pointer. A character
can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.
'''
class Solution:
def minTimeToType(self, word: str) -> int:
... |
'''
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
'''
class Solution:
def findDuplicateSubtrees(self, root: TreeNode... |
'''
Дан список чисел arr. Написать функцию perms, которая возвращает список из кортежей со всеми возможными перестановками из исходных чисел.
'''
import itertools
class Answer:
def perms(self, arr):
return list(itertools.permutations(arr))
|
'''
You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k.
Return the number of non-empty subarrays in nums that have a median equal to k.
Note:
The median of an array is the middle element after sorting the array in ascending order. If the array is of even leng... |
'''
The value of an alphanumeric string can be defined as:
The numeric representation of the string in base 10, if it comprises of digits only.
The length of the string, otherwise.
Given an array strs of alphanumeric strings, return the maximum value of any string in strs.
'''
#my own solution
class Solution:
def... |
'''
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Return the restaura... |
'''
You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.
You can perform the following operation at most maxOperations times:
Take any bag of balls and divide it into two new bags with a positive number of balls.
For example, a bag of 5 balls can b... |
'''
You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix.
Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if:
For each cell matrix[row][col] (0 <= col <= n... |
'''
Given two sparse vectors, compute their dot product.
Implement class SparseVector:
SparseVector(nums) Initializes the object with the vector nums
dotProduct(vec) Compute the dot product between the instance of SparseVector and vec
A sparse vector is a vector that has mostly zero values, you should store the spars... |
'''
Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
'''
class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str... |
'''
Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.
Alice and Bob... |
'''
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).
You are given a string answerKey, where answerKey[i] is the o... |
'''
An additive number is a string whose digits can form an additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
Given a string containing only digits, return true if it is an ... |
'''
You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.
Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and ... |
'''
You are given a string s consisting of n characters which are either 'X' or 'O'.
A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.
Return the minimum number of moves required so that all the char... |
'''
You have a binary tree with a small defect. There is exactly one invalid node where its right child incorrectly points to another node at the same depth but to the invalid node's right.
Given the root of the binary tree with this defect, root, return the root of the binary tree after removing this invalid node and... |
'''
A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the stri... |
'''
Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
answer[1] is a list of all distinct integers in nums2 which are not present in nums1.
Note that the integers in the lists may be returned i... |
'''
Given an array of distinct strings words, return the minimal possible abbreviations for every word.
The following are the rules for a string abbreviation:
Begin with the first character, and then the number of characters abbreviated, followed by the last character.
If there is any conflict and more than one word... |
'''
Design a text editor with a cursor that can do the following:
Add text to where the cursor is.
Delete text from where the cursor is (simulating the backspace key).
Move the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within... |
'''
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in
nums1 and nums2 are m and n respectively. You may
assume that nums1 has a size equal to m + n such that
it has enough space to hold additional elements from nums2.
'''
class Solutio... |
'''
You are given two 0-indexed strings word1 and word2.
A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j].
Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one... |
import numpy as np
import pandas as pd
from scipy.stats import norm
import pandas_datareader as web
import datetime
# If we want to calculate VaR for tomorrow
def value_at_risk(position, c, mu, sigma):
alpha = norm.ppf(1 - c)
var = position * (mu - sigma * alpha)
return var
# We want to calculate VaR in ... |
#ch4-1 list
L = ['Adam', 95.5, 'Lisa', 85, 'Bart', 59]
print L
#4-2 index list
L = [95.5,85,59]
print L[0]
print L[1]
print L[2]
print L[3]
#4-3 invert list
L = [95.5, 85, 59]
print L[-1]
print L[-2]
print L[-3]
print L[-4]
#4-4 insert to list
L = ['Adam', 'Lisa', 'Bart']
L.insert(2, 'Paul')
print L
#4-5 pop from ... |
a=0
b=0
c=0
d=0
e=0
while d==0 or c!=0:
e=int(input("dati cifra:"))
d=e%2
c=e%3
if(d==0):
b=e+a
a=b
print(b) |
import verify # Used for verifying that the algorithm is working as intended
'''
Selection Sort:
Selection sort takes an array and sorts a single element during each iteration.
It sets the left most unsorted value as the smallest value and iterates through the values.
If a value is the equal or greater to the smal... |
n = int(input("so dau: "))
m = int(input("so cuoi: "))
for i in range(n,m+1):
if i%2==0:
print(i) |
from turtle import *
speed (0)
shape("turtle")
color("green")
n = int(input("How many circles do you want to draw?"))
for i in range(n):
circle(100)
left(360/n)
mainloop() |
import random
word_list = ["Chelsea", "Poker", "Finance", "Electricity", "Lamp", "Excessive"]
#print("Here is my pretty awesome word list: ")
#print(*word_list, sep=", ")
loop = 2
while loop == 2:
word = random.choice(word_list)
shuffled = list(word)
random.shuffle(shuffled)
shuffled = ''.join(shuffl... |
print("hello world")
n = input("DOB please ")
print(n)
print("your age:",2018-n) |
from flask import Flask, jsonify, request,render_template
import sqlite3 as sql
con=sql.connect('user_database.db')
con.execute('CREATE TABLE IF NOT EXISTS User (ID INTEGER PRIMARY KEY AUTOINCREMENT,'
+ 'username TEXT, password TEXT)')
con.execute('CREATE TABLE IF NOT EXISTS SavedPass (ID INTEGER PRIMARY K... |
def speeding(x):
if x <= 50:
return "Pass"
elif x <= 55:
return "10 euros"
elif x <= 60:
return "20 euros"
elif x <= 65:
return "30 euros"
elif x <= 70:
return "40 euros"
elif x <= 75:
return "50 euros"
elif x <= 80:
ret... |
# def foo(*args):
# # for a in args:
# # a = a.upper()
# # print(a)
# print(f"the type of args is {type(args)}")
# print(*args, sep = "------") # print("a", "b", "c", "d", sep = "------")
# foo("a", "b", "c", "d")
#
# def sum_elements(*elements):
# sum_ = 0
# for e in elements:
# ... |
#ex1
before_ = [17, 11, 17, 11, 23, 7]
after_ = []
for i in before_:
if i not in after_:
after_.append(i)
print(after_)
#ex1.1
frst = [10, 12, 36, 44, 77, 85, 113, 231, 344, 4655, 789]
scnd = [10, 12, 35, 45, 77, 85, 113, 231, 340, 4655, 789, 2, 6]
res = []
for i in frst:
if i in scnd and i not in res... |
import random
computer_random = [1, 2, 3, 4, 5, 6, 7, 8, 9]
board = ["_","_","_",
"_","_","_",
"_","_","_",]
def board_function():
print(board[0] + "|" + board[1] + "|" + board[2])
print(board[3] + "|" + board[4] + "|" + board[5])
print(board[6] + "|" + board[7] + "|" + board[8])
def gamer... |
# print("Fahrenheit to celsus converter")
# fahrenheit = input("set the weather in fahrenheit: ")
# celsus = (int(fahrenheit) - 32) * 0.5556
# print(f"The weather in celsus is {celsus}")
# menu = input("What you want, pizza or Kebab? 1 for pizza(1500) 2 for kebab(1000)\n")
# sauce = input("Do you want any sauces, Ketc... |
import pandas as pd
filedata = 'data.csv'
#Read File :
data = pd.read_csv(filedata)
#Make an object out of an object:
data_Age = data["Age"]
#Make a list from object of data["Age"] from object of data:
# data_Age = data["Age"].tolist()
#Use python to find out how many players' age equal and over 30:
# A = []
# fo... |
"""Snake Game Python Tutorial
youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo
current time: 33:00
"""
import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
class cube(object):... |
print("type (q) = Exit")
while True:
user_input = input("type input")
if user_input == "q":
break
print(user_input) |
# -*- coding: utf-8 -*-
"""
There are six steps to making text appear on the screen:
1. Create a pygame.font.Font object.
2. Create a Surface object with the text drawn on it by calling the Font object’s render() method.
3. Create a Rect object from the Surface object by calling the Surface object’s get_rect() metho... |
"""
Jumping and variables
video: https://www.youtube.com/watch?v=2-DNswzCkqk&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5&index=2
1. constraing are where we can move
2. jumping
IF JUMPING: dont move left right
"""
import pygame
from pygame.locals import *
from rgb_color_dictionary import *
pygame.init()
#create window
... |
import pygame
pygame.init()
#---------display-------------
display_width = 800
display_height = 600
#color var
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
gameDisplay = pygame.display.set_mode((display_width,display_height))
#set title
pygame.display.set_caption('Race... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 16:29:01 2020
@author: crtom
https://www.youtube.com/watch?v=Qdeb1iinNtk&list=PLX5fBCkxJmm1fPSqgn9gyR3qih8yYLvMj&index=2
Pygame Tutorial - Making a Platformer ep. 2: Images, Input, and Collisions
"""
import sys
import pygame
from pygame.locals import*
import random
... |
import math
class Vector2:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "(%s, %s)"%(self.x, self.y)
def from_points(P1, P2):
return Vector2( P2[0] - P1[0], P2[1] - P1[1] )
def get_magnitude(self... |
keys_list = [1, 2, 3, 4, 5, 6]
values_list = ['Paul', 'Oxana', 'Angelina', 'Katerine', 'Maxime', 'asdasd', 2123, 12]
result_dict = {
}
def dict_from_keys(keys, values):
return dict(zip(keys, values + [None] * (len(keys) - len(values))))
print(dict_from_keys(keys_list, values_list))
|
import pandas as pd
trials = pd.read_csv('/Users/apple/desktop/manipulatingDataFrames/dataset/trials_01.csv')
print(trials)
trials = trials.set_index(['treatment', 'gender'])
print(trials) # NOTE: pivot cant work because of multi index
# unstack a multi-index(1)
unstack = trials.unstack(level='gender') # NOTE: level... |
def gcd(a,b):
if a==0:
return b
else:
return gcd(b%a,a)
print(gcd(35,15)) |
t=int(input())
if t==2:
print('NO')
else:
if t%2==0:
print('YES')
else:
print('NO')
|
import csv
def parse_csv(input_file):
with open(input_file, "r") as f:
reader = csv.reader(f, delimiter=",")
for i, line in enumerate(reader):
if i == 0:
continue #Skip the header
yield line
|
import unittest
from operator import itemgetter, attrgetter
class Person:
def __init__(self, first_name: str, last_name: str, age: int):
self.first_name = first_name
self.last_name = last_name
self.age = age
class People:
def __init__(self, *people: Person):
self.people = peo... |
with open('/usr/share/dict/words') as word_list:
vowels = {'a', 'e', 'i', 'o', 'u'}
for w in (word.strip() for word in word_list if vowels < set(word)):
print(w)
|
import unittest
def hex_to_int(v: str) -> int:
result = 0
for power, val in enumerate(reversed(v)):
result += int(val, 16) * (16 ** power)
return result
def hex_to_int_two(v: str) -> int:
result = 0
for power, val in enumerate(reversed(v)):
result += (convert_single_char(val) * ... |
import unittest
class User:
def __init__(self, name: str, secret: str):
self.name = name
self.secret = secret
class UserRepository:
__users = {}
def __init__(self, *users: User):
for user in users:
self.save(user)
def save(self, user: User):
self.__users... |
x = 41
def iseven(x):
if x % 2 == 0: print "even"
else: print "odd"
return " "
print "Number x = ", x, " is even? ", iseven(x)
def size2digits(x):
if x < 10 == 0: print "one digit"
elif x < 100: print "two digits"
else: print "too much digits"
return ""
print "Number = ", x, " size = ", size2digits(x)
print "Num... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 04 21:18:01 2015
@author: tianyi
"""
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
n = int(raw_input('input n:'))
for i in range(1,11):
if fib(i) < n:
print i, fib(i)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 04 21:27:40 2015
@author: tianyi
"""
def hanoi(n, A, B, C):
if n == 1:
print "move", n, 'from', A, 'to', C #移动过程
return 1
else:
count = hanoi(n - 1, A, C, B) #将前 n-1 个盘子, 通过 C, 从 A 移动到 B
print 'move', n,'from', A, 'to', C #移动过程 只... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 03 00:33:36 2015
@author: tianyi
"""
x = float(raw_input("please input x:"))
low = 0
high = x
guess = (low + high) / 2
while abs(guess ** 2 - x) > 1e-5:
if guess ** 2 < x:
low = guess
else:
high = guess
guess = (low + high) / 2
print g... |
from animal import Animal
class Reptile(Animal): # Inheriting from animal class
def __init__(self): # note the (self), if this is missing it can cause errors, check for this in exam
super().__init__() # super is used to inherit everything from the parent class, this may come up in the exam
self.col... |
'''
DFS
'''
import collections
from typing import List
def word_numbers(input):
"iterate on current element and each time keep append to your previos result"
digit_map = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv... |
from collections import deque
# Node class for holding the Binary Tree
class TreeNode:
def __init__(self, data=None):
self.val = data
self.left = None
self.right = None
self.next = None
def __str__(self):
return (f" {self.val}")
class Node:
def __init__(self, val)... |
from collections import defaultdict
class Trie:
def __init__(self):
self._end = '_end_'
self.root = defaultdict(dict)
def make_trie(self, *words):
for word in words:
current_dict = self.root
for letter in word:
current_dict = current_dict.setde... |
led.on()
if (number != 10): # != resend key
if (number < 10):
self.input_string += str(number)
elif (number == 14 or number == 15): # confire button
try:
self.state += 1
if (self.state == 0):
... |
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
... |
class SimplifyPath(object):
def simplifyPath(self, path):
"""
:param path: str
:return: str
tips: "/"->root directory
".."->upper directory
"."->current_directory
"""
subDirectories = path.split('/')
cur = '/'
for subDirect... |
class FindSubstring(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
dict = {}
num = len(words)
length = len(words[0])
res = []
for word in words:
if word not in dict... |
class CountAndSay(object):
def countAndSay(self, n):
if n == 1:
return '1'
else:
preSay = self.countAndSay(n - 1)
say, tmp, count, = '', preSay[0], 0
for char in preSay:
if char == tmp:
count += 1
els... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.