text stringlengths 37 1.41M |
|---|
import turtle
class Draw3D:
def __init__(self, edges, verticies):
self.edges = edges
self.verticies = verticies
self.t = turtle.Turtle()
self.s = turtle.Screen()
def show3D(self):
#init turtle
self.s.title("3D")
self.s.screensize(800,800,bg="white")
... |
# Enter your code here.
num_test_cases = int(input())
for i in range(num_test_cases):
test_str = input()
even_ind_char = ''
odd_ind_char = ''
for j in range(len(test_str)):
if j % 2 == 0:
even_ind_char += test_str[j]
else:
odd_ind_char += test_str[j]
print(... |
#Given an array of integers, find the one that appears an odd number of times.
#There will always be only one integer that appears an odd number of times.
#Attempt 1
numberList = (1, 4, 2, 9, 7, 8, 9, 3, 1)
def find_it(seq):
'''Returns the intger that appears an odd number of times
input: An array ... |
#Implementing and testing a Binary Sort Algorithm
def binarysort(array,element):
beg = array[0]
end = array [-1]
mid = array[0] + array[-1] // 2
if element == mid:
return len(array) // 2
for i in array:
if element < mid:
beg = array[0]
end ... |
# Write a function which returns the same words between 2 arrays storing fruits.
# In the list storing the similarities return the longest fruit and shortest fruit
listoffruits = ["Cherry", "Mango", "Apple", "Peach", "Grapefruit", "Guava", "Banana", "Plum", "Grape", "Orange",
"Lemon", "Jackfruit"]
... |
#Implementing and testing a Quick Sort Algorithm
def quickSort(array):
if len(array) <= 1:
return array
else:
y = array.pop()
low = []
high = []
for x in array:
if x > y:
high.append(x)
else:
low.append(x)
return quic... |
#Attempt 1
def remove_duplicate_words(s):
half = s.split()
uw = []
for i in half:
checker = i
if i == i:
uw.append(i)
return uw
#return ' '.join(unique_word)
print(remove_duplicate_words("my cat is my cat fat")) |
#No user input is implemented here, this is only
#for illustration/testing purposes
#The matrix-turning is implemented here by layers:
# a counter runs from the center of the matrix
# towards the outer of it, and every layer
# is rotated at a time
#Function for rotation of matrix by 90deg
def turned(original_matrix):... |
import json
with open('precipitation.json') as file:
rain_levels = json.load(file)
print(rain_levels) #printing all data for all stations
# precipitation values for Seattle
seattle_levels = [0]*12
for entry in rain_levels:
if entry['station'] == 'GHCND:US1WAKG0038':
#seattle_levels.append(entry)
... |
import maze
import pygame
class GameLoop():
# General settings
screen_width = 800
screen_height = 600
# Running flag for main loop
running = True
font = None
clock = pygame.time.Clock()
m = maze.Maze((25, 25))
# Handle events
def events(self):
# Check event queue... |
from Classes_Of_Properties import dict_of_props, dict_of_rail, water_works, electric_company, go, go_to_jail, chance, community_chest, income_tax, luxury_tax, jail
from Properties import panda_of_placements
import random
import pandas as pd
class Player:
def __init__(self, name):
self.name = name
... |
#register
#-first name, last name, password, email
#-generate user id
#login
# - account number, email and password
#bank operations
#Initializing the system
import random
database ={} #dictionary
def init():
print("Welcome to Bank PHP")
haveAccount = int(input("Do you have an ... |
#basic implementation of a tree node class.
class Tree_Node(object):
def __init__(self, id):
self.__parent = None;
self.__children = None;
self.__id = id;
def append(self, child):
if (self.__children != None):
if (child in self.__children):
... |
class Characteristics:
def __init__(self, sample):
self.sample = sample
self.size = len(sample)
def mean(self):
s = 0
for elem in self.sample:
s += elem
return s / self.size
def variance(self):
mean = self.mean()
s = 0
for elem in... |
N=int(raw_input())
Z=N
R=0
while(N>0):
D=N%10
R=R*10+D
N=N//10
if(Z==R):
print("yes")
else:
print("no")
ANOTHER PROGRAM
n=raw_input()
N=n[::-1]
if(n==N):
print("Yes")
else:
print("No")
|
N=input()
if N%7==0:
print("yes")
else:
print("no")
|
#!/usr/bin/python3
import csv
import sys
import sqlite3
import re
import os
def parse(filename, c):
csvreader = csv.reader(open(filename, 'r', encoding='UTF-8', newline=''), delimiter=',')
for row in csvreader:
# ignore headers
try:
if not int(row[0]):
continue
... |
from functools import reduce
def append(list1: list, list2: list) -> list:
return list1 + list2
def concat(lists: list) -> list:
result = []
for i in lists:
if i:
if type(i) is list:
result.extend(i)
else:
result.append(i)
return result
... |
from itertools import islice
from functools import reduce
def largest_product(series: str, size: int):
if size == 0:
return 1
if not series.isdigit() or size > len(series) or size < 0:
raise ValueError("Size cannot less than zero AND must be equal or less than series' length")
generate_s... |
from itertools import islice
def slices(series: str, length: int):
result = []
if not series or length > len(series) or length < 1:
raise ValueError("Series cannot be empty AND slice length must be more than 0 but less or equal than the series' length")
generate_series = (islice(series, i, No... |
from operator import add, mul, sub, truediv
from re import findall
OPERATIONS_DICT = {
"plus": add,
"minus": sub,
"multiplied": mul,
"divided": truediv
}
def answer(question: str) -> int:
question = question.lower()
equation = findall(r'what is (.+)\?', question)
if not equation:
... |
def is_isogram(string):
# replace hyphens and spaces from string, then make it lowercase
string = string.replace("-", "").replace(" ", "").lower()
if len(string) != len(set(string)):
return False
return True
|
def rotate(text:str, key:int):
result = ""
for char in text:
if char.isupper():
result += chr((ord(char) + key-65) % 26 + 65) # Because A-Z is 65-90 (26 in total) in unicode
elif char.islower():
result += chr((ord(char) + key-97) % 26 + 97) # Because a-z is 97-122 in un... |
NODE, EDGE, ATTR = range(3)
class Node:
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge:
def __init__(self, src, dst, attrs):
self.src = src
self... |
from collections import Counter
def find_anagrams(word: str, candidates: list):
# Lower the word, split it to list of characters, then map it to a dictionary
map_word = Counter(list(word.lower()))
anagrams = []
for candidate in candidates:
# Exclude the candidate if it has the exact same word... |
def response(hey_bob):
hey_bob = hey_bob.strip()
# If you address him without actually saying anything
if hey_bob.isspace() or hey_bob == "":
return "Fine. Be that way!"
# If you YELL AT HIM
if hey_bob.isupper():
# Yelling but ends with question mark
if hey_bob[-1] == "... |
VOWELS = ("a", "i", "u", "e", "o")
SPECIALS = ("xr", "yt")
SUFFIX = "ay"
def translate(text: str):
text = text.lower().split()
return " ".join(translate_word(word) for word in text)
def translate_word(word: str):
return arrange_word(word) + SUFFIX
def arrange_word(word: str):
if word.startswith(VOWEL... |
###########Question3###########################################################
'''
Question 3
Given an undirected graph G, find the minimum spanning tree within G.
A minimum spanning tree connects all vertices in a graph with the smallest
possible total weight of edges.
Vertices are represented as unique strings.
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
# search for <table> tags and parses all text within the tags
tables = pd.read_html("https://en.wikipedia.org/wiki/1998_in_film")
# print the number of DataFrames in the list
len(tables)
# In[2]:
df_1998oct = tables[8]
df_1998oct.tail(25)
# I... |
# sort algorthms and methods for reference
# selection_sort
# sorting an array from smallest to largest
def find_smallest(arr):
smallest = arr[0] # store smallest value
smallest_index = 0 # store index of smallest value
# start from the second item
for i in range(1, len(arr)):
if arr[i] < smal... |
"""
Electricity bill estimator v2.0 by Kyaw Phyo Aung (13822414)
"""
tariff_costs = {"11": "0.244618", "31": "0.136928"}
tariffs = []
def fun_one():
print("Electricity bill Estimator")
cents = float(input("Enter cents per kWh: "))
dailyuse = float(input("\nEnter daily use in kWh: "))
days = float(input(... |
"""
Program to calculate and display a user's bonus based on sales.
If sales are under $1,000, the user gets a 10% bonus.
If sales are $1,000 or over, the bonus is 15%.
"""
sales = float(input("Enter Sales: S$ \n"))
tenbounus = sales*0.1
fifteen = sales*0.15
while sales > 0 :
if sales < 1000 :
sales += ten... |
income_list = []
income_total_list = []
profit = 0
income = 0
def main():
calculate_income()
print("")
print("Income Report")
print("--------------")
user_output()
def calculate_income():
try:
mmcount = 1
totalincome = 0
print("How many months?")
months = int(i... |
from prac_08.taxi import Taxi
from prac_08.silverservicetaxi import SilverServiceTaxi
MENU = """Let's Drive!
q)uit, c)hoose taxi, d)rive
"""
current_taxi = None
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2), SilverServiceTaxi("Hummer", 200, 4)]
bill_to_date = 0
def main():
global bill_to_date
... |
def verificar_senha(s):
"""
Verifica se s é a senha correta
:param s: Senha a ser testada
:return: True se s for a senha correta
"""
return s == senha
def contar_semelhanca(s):
"""
Conta quantos digitos são semelhantes entre s e a senha correta
:param s: Senha a ser comparada com a... |
# a = '北京,南京,天津'
# b = list(a) # 字符串列表化
# # c = ','.join(b) # 列表字符串化
# d = a.split(',') # split对单词列表化不是对每个字母
# print('b is :', b)
# print('d is :', d)
#
# # print('c is:', c)
#
# for i in d:
# print(i)
import copy
m = [34,94,35,78,45,67,23,90,1,0]
t = copy.deepcopy(m)
# 求m个最大的数值及其索引
max_number = []
max_index = ... |
from tkinter import *
root = Tk()
root.geometry("655x333")
root.title("Register yourself to join our Dance academy")
def getvals():
print(f"You have enter your first name as : {fnamevalue.get()}")
print(f"You have enter middle name as : {mnamevalue.get()}")
print(f"You have enter last name as : {lnamevalu... |
import random
import string
def main():
size = int(input("How many digits will your password have?\n"))
chars = string.ascii_letters + string.digits + "!@#$%&*()-ç^{}[];:/<>|=+,."
rnd = random.SystemRandom()
print("\nPassword: ")
print("".join(rnd.choice(chars) for i in range(size)))
if __name... |
#Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#and write a program that prints out all the elements #of the list that are less than 5.
a.sort(reverse=True)
print(a.index(89))
for i in range(len(a)):
print( str(i)+': '+str(a[i]))
max = 0;
for item in a:
if item>max:
max =... |
def gcd_iter(a, b):
c = min(a, b)
# 当a除以c余数为0,并且b除以c余数为0时,while条件为False or False,即跳出循环
while a % c != 0 or b % c != 0:
c -= 1
return c
print(gcd_iter(2, 12))
print(gcd_iter(6, 12))
print(gcd_iter(9, 12))
print(gcd_iter(17, 12)) |
# 利用http://pythontutor.com可视化工具
def fixed_month_pay(balance, annnual_interest_rate):
"""
函数接收2个参数,分别是贷款总额, 年利率
"""
# 将贷款的年利率转换为月利率
month_interest_rate = annnual_interest_rate / 12
# 为while循环设置一个旗帜为True,如果满足条件则把旗帜变为False,退出循环
flag = True
# 设置精确度
epsilon = 0.01
# 假设不产生利息,那么每个月还款额为贷款总额/12
low =... |
funcionario = int(input())
horas = int(input())
valor_horas = float(input())
salary = horas * valor_horas
print(f'NUMBER = {funcionario}')
print(f'SALARY = U$ {salary:.2f}')
|
# user defined-exceptions
# an exception handler class for operand errors
# and extend or inherits CalculatorError
from calculatorerror import CalculatorError
class OperandError(CalculatorError):
""" exception handler for operand error """
def __init__(self, operand):
self.operand = operand
def ... |
import os.path
def addPainting():
while True:
melyik_fajl=input("\n\tMelyik fájlban szeretne menteni?irja be a nevét, és kiterjesztését: ")
if os.path.isfile(melyik_fajl):
break
print("\tNem létezik a fájl, próbálja újra!")
f=open(melyik_fajl, 'a')
festmenynev=input("\tÍr... |
"""
The primary goal of this file is to demonstrate
a simple unittest implementation.
"""
import unittest
from triangle import classify_triangle
class TestTriangleInputs(unittest.TestCase):
"""
Test the inputs of the triangle function.
"""
def test_invalid_string_input(self):
"""
Tes... |
from main import el_length as L, usiliya as arrayUsiliy, uz_num as el, gestkosti as array
# Валидность
def pravilnoLi(name, flt, mns, null, one):
# Убираем пробелы
name = name.strip()
# Пустая строка
if name == '':
name = None
warning = print('Вы ввели пустую строку. Повторите попытку в... |
#!/usr/bin/python3
import itertools
import math
import threading
N = 0
m = 0
DIRECT = 0
INFERIOR = 1
INVERSE = 2
SUPERIOR = 3
BLOCK_TYPES = [DIRECT, INFERIOR, INVERSE, SUPERIOR]
result = None
THREADS = 4
def generate_all_posibilities(nr_of_blocks):
"""
Generates all possible block types variations
:pa... |
class animal():
def run(self):
print("Animal is running")
class cat(animal):
def run(self):
print("cat is running")
def run_two_times(self,animal):
animal.run()
animal.run()
oneCat=cat()
oneCat.run()
print(isinstance(oneCat,cat))
print(dir(animal))
|
############## 07/11/2019
# 1. weather类中包含方法:1.输入daytime返回可见度,2.根据input返回温度
class WeatherSearch():
def __init__(self, input_daytime):
self.input_daytime=input_daytime
def search_visibility(self):
visible_degree=0
if self.input_daytime=="morning":
visible_degree=2
if s... |
list = ['Pizza', 'Burgers', 'Chips']
print("Here are the items in the food list:")
print(list)
print()
change = input("Which item should I change? ")
new = input("Enter the new value: ")
print()
if change in list:
i = list.index(change)
list.remove(change)
list.insert(i, new)
print("Here is the revised ... |
# Lina Kang
# 1072568
# HW 03 PS 1 - Stock Transaction Program
# receive input from user regarding the stocks
def userInput()->(str, int, float, float, float):
name = input("Enter Stock name: ")
shares = int(input("Enter Number of shares: "))
purchasePrice = float(input("Enter Purchase price: "))
selli... |
def main():
print("Enter 5 numbers: ")
numbers = []
for x in range(5):
temp = int(input(""))
numbers.append(temp*10)
for x in range(4, -1, -1):
print(float(numbers[x]), end =" ")
if __name__ == "__main__":
main()
|
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("yes")
|
class Weapon:
def __init__(self, name, damage):
'''Sätter namn och damage'''
self.name = name
self.damage = damage
def __str__(self):
'''Returnerar en läsbar sträng för objekt i Weapon'''
return "- {}".format(self.name)
|
import requests
a = raw_input('Enter currency to convert from ?')
a = a.upper()
b = raw_input('Enter currency to convert to ?')
b = b.upper()
c = float(raw_input('Enter value to convert ?'))
url = ('https://currency-api.appspot.com/api/%s/%s.json') % (a, b)
print url
r = requests.get(url)
rate= r.json()['rate']
pr... |
q=input()
c=0
for i in q:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
c+=1
if c>0:
print("yes")
else:
print("no")
|
count=0
a=0
while count<10:
if a%2==0:
print(a)
count=count+1
a=a+1
|
b=eval(input(" enter breadth :"))
h=eval(input(" height :"))
ar=.5*b*h
print("square is ",ar)
|
quite = "brexit"
while quite == "brexit":
set1= input("Say rock ,paper or scizzor:")
set2= input("Say rock ,paper or scizzor:")
f = [set1,set2]
if len(f) != 0 :
while set1 == set2 :
print ("Draw");break
while set1 != set2 :
if "rock" in f and "scizzor... |
#in chi tra lai mot trong hai gia tri true or false
strA=('rabiloo')
strB=('u')
strC=strB in strA
#lay chuoi cat chuoi
print(strC)
print(strA[0])
print(strA[-2])
print(strA[len(strA)-1])
strD=strA[3:len(strA)]
print(strD)
#cat theo [tu:den:buoc nhay]
strE = strA[None:None:3]
print(strE)
#in ra chuoi
e='My name is %s %... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
import numpy as np
# 18. Sắp xếp các hàng theo thứ tự giảm dần của giá trị (numeric value) của cột thứ 3
# Viết chương trình thực hiện nhiệm vụ trên.
# Dùng lệnh sort để xác nhận (trong bài tập này, kết quả của chương trình của bạn với lệnh sort có thể khác nhau do có thể có ... |
import random
import numpy
import math
#########MAIN##########
#Returns a randomly weighted matrix
def generate_weights(size):
weights = []
for i in xrange(0,size):
weights.append([float("{0:.1f}".format(random.uniform(-0.5, 0.5))), float("{0:.1f}".format(random.uniform(-0.5, 0.5)))])
return n... |
def check_integer(num):
if 45 < num < 67:
return num
raise NotInBoundsError
def error_handling(num):
try:
print(check_integer(num))
except NotInBoundsError as exc:
print(exc) |
# the list "walks" is already defined
# your code here
sum = 0
for w in walks:
sum = sum + w["distance"]
print(sum // len(walks)) |
def count(numbers, target):
res = 0
for i in numbers:
if i == target:
res += 1
return res
numbers_i = input().split(' ')
target_i = input()
print(count(numbers_i, target_i))
|
text = input()
print(text.strip("*_~`"))
# if text.startswith("**") and text.endswith("**"):
# print(text[2:-2:])
# elif text.startswith("*") and text.endswith("*"):
# print(text[1:-1:])
# elif text.startswith("~~") and text.endswith("~~"):
# print(text[2:-2:])
# elif text.startswith("`") and text.endswith(... |
from .htmlbuilder import HtmlBuilder
class TableGen(HtmlBuilder):
""" This Module allows to create tables
"""
def __init__(self, ClassName):
""" Loads constructor of superclass and constructs HtmlCode
with a table skeleton
"""
super().__init__(ClassName)
# Construct t... |
#!/usr/bin/python
'''
Writes plots for mach. learning presentation
'''
def gauss(x, sigma, x0, A):
import numpy as np
return A * np.exp(-(x - x0)**2 / (2.0 * sigma**2))
def gauss_1st_deriv(x, sigma, x0, A):
''' Returns the first derivative of a Gaussian. See gauss_4thderiv.nb
mathematica code.
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
def helper(arr, start, end):
if start... |
class Solution:
# Time complexity O(N*MlogM) | Space complexity O(1)
def groupAnagrams(self, strs):
anagram = {}
for i, s in enumerate(strs):
sortedString = "".join(sorted(s))
group = anagram.get(sortedString, [])
group.append(s)
ana... |
class Solution:
# Time Complexity - O(2^n) | Space Complexity - O(n)
def recursion(self, n):
self.cache = {}
return self.recursionHelper(0, n)
def recursionHelper(self, i ,n):
if i > n:
return 0
if i == n:
return 1
if i in self.cache:
return self.cache[i]
ways = self.recursionH... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
# ================================
# ================================
# ================================
def confusion_matrix(gt, pred) -> np.ndarray:
"""
Returns confusion matrix of classification on a set of objects, specifically
a matr... |
"""
print('Hello world')
a = 1
b = 'this is a string'
c = [1, 2, 3, 4]
d = (5, 6, 7, 8)
e = {'name': 'Perry', 'number': 1}
print(a)
print(b)
print(c)
print(d)
print(len(c))
c.append(42)
print(c)
c.append('will this work?')
print(c)
print(e)
print(e['name'])
e['number'] += 9000
print(e['number'])
for n in c:
for ... |
# a=int(input("Enter the age :"))
# if a>=18:
# print("Eligible to vote")
# else:
# print("Not eligible to vote")
#
# # Find the odd or even
# a=int(input('enter the number'))
# if a%2==0:
# print('the given number is even')
# else:
# print('the number is odd')
# print even numbers from 1 to 100
# ... |
# # Q1 Create a new list with values and find the length of it
# l = [10,20,30,90,10,10,40,50]
# print(l)
# print(type(l))
# print(len(l))
# #
# # # Q2 Create a new list with values and find the length of it
# l=[105,205,305,405,505,605,705,805]
# print(len(l))
# #
# # # Q3 Create a new list with values and find the... |
import time
import random
def swap(arr, a, b):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
#O(N^2)
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(len(arr)):
if arr[i] <= arr[j]:
swap(arr, i, j)
return arr
#O(N^2)
def selectionSort(arr):
for i... |
# Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.
#
# Return the minimum number of steps to make t an anagram of s.
#
# An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
#
#
# Example... |
# -*- coding:utf-8 -*-
# Given a string, your task is to count how many palindromic substrings in this string.
#
# The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
#
# Example 1:
#
#
# Input: "abc"
# Output: 3
# Explanation: Thre... |
# You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.
#
# You can return the answer in any order.
#
#
# Example 1:
#
#
# Input: s = ... |
# There are a total of n courses you have to take labelled from 0 to n - 1.
#
# Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.
#
# Given the total number of courses numCourses and a list of the prerequisite pairs, return the ... |
# You are given an integer array nums sorted in ascending order (with distinct values), and an integer target.
#
# Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
#
# If target is found in the array return its index, otherwise, return -1.
#
#
... |
# You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.
#
# Return the intersection of these two interval lists.
#
# A closed interval [a, b] (with a < b) denotes the... |
# -*- coding:utf-8 -*-
# You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
#
# Return the number of servers that ... |
# Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
#
# Return the quotient after dividing dividend by divisor.
#
# The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate... |
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
#
#
# Example 1:
#
#
# Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
#
#
# Example 2:
#
#
# Input: nums = [1]
# Output: 1
#
... |
# For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:
#
# For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
#
# Given N, return any beautiful array A. (It is guaranteed that one exists.)
#
#
#
# Example 1:
#
#
# Input: 4
# Outp... |
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
#
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
#
# How many possible unique paths are there?... |
# -*- coding:utf-8 -*-
# Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
#
# Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
#
# You may return any answer array that satisfies this condition.
#
#
#
# Ex... |
# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
#
# Find all the elements of [1, n] inclusive that do not appear in this array.
#
# Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra ... |
# Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library... |
# There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
#
# A province is a group of directly or indirectly connected cities and no other cities outside of the group.... |
# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
#
# Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
#
# The order of output does not matter.
#
# Example 1:
#
# Input:
# s: "cbaebabacd" p: "abc"
... |
# Given an integer array nums, return the length of the longest strictly increasing subsequence.
#
# A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
#... |
# Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
#
# Note:
#
#
# Given target value is a floating point.
# You are guaranteed to have only one unique value in the BST that is closest to the target.
#
#
# Example:
#
#
# Input: root = [4,2,5,1,3], ... |
# Given a positive integer K, you need to find the length of the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.
#
# Return the length of N. If there is no such N, return -1.
#
# Note: N may not fit in a 64-bit signed integer.
#
#
# Example 1:
#
#
# Input: K = 1
# Output: 1... |
# Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
#
# Example 1:
# Given tree s:
#
#
# ... |
# You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
#
# Given n, find the total number of full staircase rows that can be formed.
#
# n is a non-negative integer and fits within the range of a 32-bit signed integer.
#
# Example 1:
#
# n = 5
#
# ... |
# -*- coding:utf-8 -*-
# Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
#
#
# Example 1:
#
#
# Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
# Output: [1,... |
# Given an integer n, return true if it is a power of three. Otherwise, return false.
#
# An integer n is a power of three, if there exists an integer x such that n == 3x.
#
#
# Example 1:
# Input: n = 27
# Output: true
# Example 2:
# Input: n = 0
# Output: false
# Example 3:
# Input: n = 9
# Output: true
# Example 4... |
# Given a list of non-negative integers nums, arrange them such that they form the largest number.
#
# Note: The result may be very large, so you need to return a string instead of an integer.
#
#
# Example 1:
#
#
# Input: nums = [10,2]
# Output: "210"
#
#
# Example 2:
#
#
# Input: nums = [3,30,34,5,9]
# Output: "953... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.