text stringlengths 37 1.41M |
|---|
"""Defines the Transform type."""
import math
from typing import Optional
class Transform:
"""A mutable object that represents a 2D translation and rotation."""
def __init__(self, parent: Optional["Transform"] = None):
self._x = 0
self._y = 0
self._angle = 0
self._parent = p... |
"""This module defines a factory to spawn collectable heart containers."""
import pygame
from collectable_item import make_collectable_item
from player import Player
_extra_heart_image = pygame.image.load(
"images/extra_heart.png"
).convert_alpha()
def make_extra_heart(x: float, y: float):
"""Spawns a col... |
english_to_french = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}
print(english_to_french.keys())
print(list(english_to_french.keys()))
print(tuple(english_to_french.keys())) |
def decoder(alphabet, letter):
if letter == "a":
alphabet[0] += 1
elif letter == "b":
alphabet[1] += 1
elif letter == "c":
alphabet[2] += 1
elif letter == "d":
alphabet[3] += 1
elif letter == "e":
alphabet[4] += 1
elif letter == "f":
alphabet[5] +=... |
name = input()
for i in name:
if i.isupper():
print(i, end="") |
while True:
capital_letter = 0
small_letter = 0
numeric_letter = 0
space = 0
raw_data = input("")
if raw_data == "":
break
for i in range(0, len(raw_data)):
if raw_data[i] == " ":
space += 1
elif raw_data[i].isnumeric():
numeric_letter += 1
... |
def calc_time(char):
if 'A' <= char < 'D':
return 3
elif 'D' <= char < 'G':
return 4
elif 'G' <= char < 'J':
return 5
elif 'J' <= char < 'M':
return 6
elif 'M' <= char < 'P':
return 7
elif 'P' <= char < 'T':
return 8
elif 'T' <= char < 'W':
... |
count = input("");
a = list();
for i in range(0, int(count)):
raw_data = input("");
a.append(int(raw_data[0]) + int(raw_data[2]));
for i in a:
print(i);
|
import requests
city=input("Enter your city name:")
url='http://api.openweathermap.org/data/2.5/weather?q={}&appid=4e4049498f5fd8ac61f8460d94449a3b'.format(city)
res=requests.get(url)
data=res.json()
print(res)
#print(data)
Temperature=data['main']['temp']
Latitude=data['coord']['lat']
Longitude=data['coord']['lon']
... |
numbers=[1,2,3,4,5,6,7,8]
for x in numbers:
if x % 2==0:
print(x) |
def raise_both(value1,value2):
new_value1=value1**value2
new_value2=value2**value1
new_tuple=(new_value1,new_value2)
return new_tuple
result=raise_both(2,3)
print(result)
|
import turtle
my_turtle=turtle.Turtle()
def square(length,angle):
my_turtle.forward(length)
my_turtle.right(angle)
my_turtle.forward(length)
my_turtle.right(angle)
my_turtle.forward(length)
my_turtle.right(angle)
my_turtle.forward(length)
square(300,90)
|
# The tic-tac-toe game!
# Instructions
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
def display_instructions():
# Displaying game Instructions.
print \
"""
Welcome to Tic-Tac-Toe, a showdown between a Human Brain and an
Intelligent Computer.
... |
testu = [1, 2, 3, 4]
bla = [num for num in testu if num > 2]
print(bla)
foo = [
{ 'hello': 'world' },
{ 'hello': 'bar' },
]
baz = [item['hello'] for item in foo]
print(baz) |
class student (object):
def __init__(self,age,level, name ,grade=None):
self.name=name
self.age=age
self.level=level
self.grade=grade or {}
def setgrade(self,course, grade):
self.grade[course]=grade
def getGrade(self,course):
return self.grade[course]... |
#!/usr/bin/env python3
# Module Docstring
"""
REST API FUNCTIONS
This module would account for all possible
functions for REST API testing.
"""
# Rest API Custom Libraries
from rest_api_exception import StringSpaceException
# Function for validation of palindrome
def is_string_palindrome(string_var):
... |
from math import sqrt
class PrimeNumber():
def __init__(self):
super().__init__()
def isPrimeNumber(self, num):
if num == 1 or num == 0:
return 'Not prime'
for i in range(2, round(num / 2) + 1):
if num % i == 0:
return 'Not prime'
ret... |
# These are the emails you will be censoring. The open() function is opening the text file that the emails are contained in and the .read() method is allowing us to save their contexts to the following variables:
email_one = open("email_one.txt", "r").read()
email_two = open("email_two.txt", "r").read()
email_three ... |
"""Q18
Create a class Building
Create Appartment, House and Commercial Building class inheriting Building class.
"""
class Building:
def __init__(self,storey):
print("Building")
self.storey = storey
def storey(self):
return f"{self.storey} storey"
def greet(self):
return f"I got {self.storey}... |
"""
Q19
class Progression:
2 ”””Iterator producing a generic progression.
3
4 Default iterator produces the whole numbers 0, 1, 2, ...
5 ”””
6
7 def init (self, start=0):
8 ”””Initialize current to the first value of the progression.”””
9 self. current = start
10
11 def advance(self):
12 ”””Update self. curr... |
from ability import Ability
from weapon import Weapon
from spell import Spell
from armor import Armor
from hero import Hero
from team import Team
from random import choice
class Arena:
def __init__(self):
self.previous_winner = None
def create_ability(self):
name = ""
while l... |
from random import choice
class Team:
def __init__(self, name):
self.name = name
self.heroes = []
def remove_hero(self, name):
foundHero = False
for hero in self.heroes:
if hero.name == name:
self.heroes.remove(hero)
foundHero = Tru... |
"""
Tuples are like lists.
Tuples are immutable, but you can change lists
"""
my_list = [1,2,3]
print(my_list)
my_list[0] = 0
print(my_list)
my_tuple = (1,2,3,4,5,6)
print(my_tuple)
# my_tuple[0] = 0 Assignment not allowed
print(my_tuple[0])
print(my_tuple[1:])
print(my_tuple.index(4))
print(my_tuple.count(3))
t = ... |
and_output1 = (10==10) and (10 > 9)
and_output2 = (10==11) and (10 > 9)
and_output3 = (10!=10) and (10 <= 9)
or_output1 = (10==10) or (10 < 9)
or_output2 = (10==10) or (10 < 9)
or_output3 = (10!=10) or (10 < 9)
not_true = not(10 == 10)
not_false = not (10 > 10)
print(and_output1)
print(and_output2)
print(and_output3... |
"""
== value aquality
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
"""
bool_one = 10 == 20
not_equal = 10 != 10
greater_than = 10 > 9
less_equal = 10 <= 10
print(bool_one)
print(not_equal)
print(greater_than)
print(less_equal)
|
mark=int(input("give a positive number:"))
if mark > 100 or mark < 0:
print("Wrong input")
elif mark>=80:
print("it is A+")
elif mark>=70:
print("it is A")
elif mark>=60:
print("it is A-")
elif mark>=50:
print("it is B")
elif mark >= 40:
print("it is C")
elif mark >= 33:
print("it is D")
el... |
if __name__ == '__main__':
list= []
n=int(input("enter the number: "))
for i in range(0, n):
element=int(input("enter the number the element: "))
list.append(element)
print(list)
|
# Ask the user for a number and determine whether the number is prime or not.
def prime_check(a):
check = True
for i in range(2, a):
if a % i == 0:
check = False
break
return check
if __name__ == '__main__':
num = int(input('Enter the number: '))
check1 = prime_che... |
#Functions missing----
#Updating stock
#Function to get change from stock
def greedy(bal):
nickels=25
dimes=25
quarters=25
ones=0
fives=0
while bal>=25: #If money can be converted to quarters
print(bal//25,"quarter(s)")
quarters=quarters-(bal//25)
bal=bal%25
con... |
def computepay(hours,rate):
extra=(hours-40)*rate*1.5
if hours>40:
pay=extra+(40*rate)
else:
pay=hours*rate
print("Pay:",pay)
try:
hours=float(input("Enter Hours:"))
rate=float(input("Enter Rate:"))
except:
print("Please enter numeric input:")
exit()
computepay(hour... |
def investment(C,r,n,t):
p=C*((1+((r)/n))**(t*n))
return p
try:
C=float(input("Enter initial amount:"))
r=float(input("Enter the yearly rate:"))
t=float(input("Enter years till maturation:"))
n=float(input("Enter compound interest:"))
except:
print("Invalid input!!!")
exit()
print(f... |
from lab_python_oop.Circle import Circle
from lab_python_oop.Rectangle import Rectangle
from lab_python_oop.Square import Square
import pygame # another module loaded using pip
def main():
"""It's main function that is called after this module is launched."""
variant = 20 # variant number in your group
... |
import lab_python_oop.Rectangle as Rect
class Square(Rect.Rectangle):
__name = 'Квадрат'
def __init__(self, length, color):
self._length = length
self._width = length
self._color = color
@staticmethod
def get_name():
return Square.__name
def __repr__(self):
... |
from abc import ABC, abstractmethod, abstractproperty
class Business_lunch(ABC):
"""
Интерфейс Строителя объявляет создающие методы для различных частей объектов
Продуктов.
"""
@abstractproperty
def lunch(self):
"""Продуктом является ланч."""
pass
@abstractmethod
... |
# Import Sqlite3
import sqlite3 as sql
# Import de PrettyTable (affichage du tableau dans la console)
from prettytable import from_db_cursor
CREATE_ARTICLE_TABLE = "CREATE TABLE IF NOT EXISTS Articles(id INTEGER PRIMARY KEY, designation TEXT, prix INTEGER, quantité unitaire TEXT, acheteur TEXT REFERENCES Personne(id))... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 20 11:32:28 2021
@author: nitac
"""
score = input('成績?')
score= int(score)
if score >= 60:
print('及格')
else:
print('不及格')
score=int(input('成績?'))
if score>=90:
print('A')
elif score>=75:
print('B')
elif score>=60:
... |
parrot = "Norwegian Blue"
print(parrot[3])
age = 24
print("My age is " + str(age) + " years old")
print("My age is {0} years".format(age))
print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6}, and {7}".format(31, "January", "March", "May", "July", "August", "October", "December"))
for i in range(1, 12):
pri... |
"""
Написать функцию odd_sum, которая принимает список, который может состоять
из различных элементов.
Если все элементы списка целые числа, то функция должна посчитать сумму
нечетных чисел.
Если хотя бы один элемент не является целым числом, то выкинуть ошибку
TypeError с сообщением "Все элементы списка должны быть це... |
def bracket_matcher(my_input):
start = ["[","{","("]
close = ["]","}",")"]
stack = []
for i in my_input:
if i in start:
stack.append(i)
elif i in close:
position = close.index(i)
if ((len(stack) > 0) and (start[position] == stack[len(stack)-1])):
... |
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
should_take_the_poll = ('terry', 'simon', 'dave', 'phil')
for person in should_take_the_poll:
if person in favorite_languages.keys():
print(f'Thanks for responding to the poll, {person.title()}.')
else:
... |
while True:
word = input("You're stuck in an infinite loop! Enter the secret word to leave the loop: ")
if word == "chupacabra":
break
print("You've successfully left the loop!") |
greeting = 'Hello,'
greeting += '\nWhat brand of car are you lokking to rent? '
answer = input(greeting)
print(f"Let me see I can find you a {answer.title()}.")
|
print("+---"*3, end = "+\n")
print("| "*3, end = "|")
|
animals = [
'lions',
'tigers',
'jaguars'
]
for animal in animals:
print (animal,"are really cool!")
print('all of these animals are really cool!') |
"""A Data Provder that reads parallel (aligned) data.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.contrib.slim.python.slim.data import data_provider
from tensorflow.contrib.slim.python.slim... |
# scatterplot.py
import numpy as np
import pylab as pl
# Make an array of x values
x = [1, 2, 3, 4, 5]
# Make an array of y values fro each x value
y = [1, 4, 9, 16, 25]
# use pylab to plot x and y as cyan circle
pl.plot(x, y, 'co')
# show the plot on the screen
pl.savefig('temp1.png')
|
def encrypt(text,s):
result=''
l=len(text)
for i in range(l):
if (text[i].isupper()):
result+= chr((ord(text[i]) + s-65) % 26 + 65)
elif(text[i].islower()):
result+= chr((ord(text[i]) + s - 97) % 26 + 97)
else:
result+=text[i]
return result
t... |
def canSum(targetSum, numbers):
arr = [False] * (targetSum + 1)
arr[0] = True
for i in range(targetSum + 1):
if arr[i] == True:
for num in numbers:
if (i + num <= targetSum): arr[i + num] = True
return (arr[targetSum])
print(canSum(7, [2, 3]))
print(canSum(7, [5, 3, 4, 7]))
print(canSum(7, [2, 4]))
pri... |
#!/usr/bin/env python
# все файли на сервере из файла
import requests
def request(url):
try:
return requests.get("http://" + url)
except requests.exceptions.ConnectionError:
pass
target_url = "google.com"
with open("/root/subdomains.list", "r") as word_list_file:
for line in word_list_f... |
# Código funcional, aunque aún queda pendiente corregir detalles en cuanto a cómo se guardan los datos requeridos
# por el programa.
# -*- coding: cp1252 -*-
# from Tkinter import Tk, Label, Button, Entry, Text, StringVar
from tkinter import Tk, Label, Button, Entry, Text, StringVar
colorFondo = "#00F"
colorLetra = ... |
def absolute_value(num):
#this function returns the absolute value of entered numbers
if num>=0:
return num
else:
return-num
#output:2.7
print(absolute_value(2.7))
#output:4
print(absolute_value(4))
|
from graphs import Graph
def validPos(pos, board_size):
if pos < 0 or pos >= board_size:
return False
return True
def getNormalizedPos(x, y, board_size):
return (x * board_size) + y
def getPossiblePositions(posX, posY, board_size):
pos_offsets = [(-2,-1), (-1,-2), (1,-2), (2,-1), (2,1), (1,2)... |
""" Print Odds below n
"""
def odds_below_n(n):
print("______________")
for i in range(1, n, 2):
print(i)
def main():
odds_below_n(40)
main()
|
a = 90
b = 200
if a>b:
print("a is greater than b")
else :
print(" b is greater than a")
|
"""
Printing squares of first 100 numbers
"""
n = 100
for i in range(n):
print(i*i)
|
"""Factorial"""
def factorial(n):
"""Get the factorial of a given number.
Args
----
n : an integer
Returns
------
Returns an integer
"""
fact = 1
i = n
while i > 1:
fact *= i
i -= 1
return fact
|
# Calculating the Area of Circle
# Area of a circle is pi*r*r
pi = 3.14
r = float(input(" What is the radius of the circle : "))
Area_Of_The_Circle = pi * r * r
print(Area_Of_The_Circle) |
value_1 = 20
value_2 = 10
total_sum = (value_1 + value_2)
# Printing 20+10 = 30
print(str(value_1) + " + " + str(value_2) + " = " + str(total_sum))
# Printing 20-10 = 10
total_substraction = (value_1 - value_2)
print(str(value_1) + " - " + str(value_2) + " = " + str(total_substraction))
# Now Printing in forma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 20:00:48 2019
@author: Ruman
https://www.nltk.org/book/ch01.html
"""
import nltk
from nltk.book import *
#Nos permite obtener el Titulo del texto cargado
print(text2)
#Búsquedas de un termino sobre uno de los textos cargados.
text1.concordance... |
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = No... |
def largest_cnt_subarray(arr):
result = 0
tot_sum = 0
beg = 0
end = 0
sub = []
maxlen = 0
for i in range(len(arr)):
tot_sum += arr[i]
if tot_sum < 0:
tot_sum = 0
beg = i+1
if result < tot_sum:
result = tot_sum
... |
class vertex:
def __init__(self, key):
self.id = key
self.connTo = {}
def addNeighbor(self, nbr, weight = 0):
self.connTo[nbr] = weight
def getConnenctions(self):
return self.connTo.keys()
def getId(self):
return self.id
def getWeight(... |
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
prev_idx = i - 1
while prev_idx >= 0 and key < arr[prev_idx]:
print("key = ", key, end = "\n")
print("prev_idx = ", prev_idx, end = "\n")
print("i = ", i, end = "\n")
... |
import database
import math
class Rectangle(object):
def __init__(self, pt1, pt2):
x1, y1 = pt1
x2, y2 = pt2
self.left = min(x1, x2)
self.right = max(x1, x2)
self.top = max(y1, y2)
self.bottom = min(y1, y2)
def contains(self, pt3):
x3, y3 = pt3
return self.left <= x3 <= self.right and self.bottom... |
'''
author: ylavinia
String compression
Implement a method to perform basic string compression using the counts of
repeated characters.
Example:
Input: aabcccccaa
Output: a2b1c5a2
Assume the string has only uppercase and lowercase letters.
'''
def compress_string(astring):
char_and_freq = create_freq_list(astring... |
"""
适配器模式
"""
"""
将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本由于接口不兼容而不能一起工作的哪些类可以一起工作
两种实现方式
类适配器:使用多继承
对象适配器:使用组合
"""
from abc import ABCMeta,abstractmethod
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self,money):
pass
class Alipay(Payment):
def __init__(self,huabei=Fal... |
from abc import ABCMeta,abstractmethod
#接口,定义抽象类和抽象方法(子类必须实现父类的方法)
"""
抽象产品角色
"""
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self,money):
pass
#实现Payment接口
#最底层
"""
具体产品角色
"""
class Alipay(Payment): #具体产品角色
def __init__(self,huabei=False): #增加花呗支付
self.huabei=huab... |
#!/usr/bin/env python
import numpy as np
def sigmoid(x):
return 1.0 / (1 + np.exp(-x))
"""
def test_sigmoid():
x = 0
print("Input x: {}, the sigmoid value is: {}".format(x, sigmoid(x)))
"""
def main():
# Prepare dataset
train_features = np.array([[1, 0, 26], [0, 1, 25]], dtype=np.float)
train_labels = ... |
import cv2 # for image processing
import easygui # to open the filebox
import numpy as np # to store image
import imageio # to read image stored at particular path
import sys
import matplotlib.pyplot as plt
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import Ima... |
from pathlib import Path
import urllib.request as url
def get_cache_dir() -> Path:
"""
Returns a cache dir that can be used as a local buffer.
Example use cases are intermediate results and downloaded files.
At the moment this will be a folder that lies in the root of this package.
Reason for thi... |
import pygame
COLORS = {
"red" : (255, 0, 0),
"white" : (255, 255, 255),
"black" : (0, 0, 0),
"green" : (0, 255, 0),
"grey" : (100, 100, 100),
"orange" : (255, 125, 0)
}
class Game():
def __init__(self):
self.running = True
self.clock = pygame.time.Clock()
def init(sel... |
a=int(input("Enter first number : "))
b=int(input("Enter second number :"))
add=a+b
sub=a-b
mult=a*b
div=a/b
rem=a%b
fd=a//b
power=a**b
print("Addition of two number is ",add)
print("Subtraction of two number is ",sub)
print("Multipication of two number is ",mult)
print("Division of two number is ",div)
print("Remaind... |
k=1
for i in range(int(input())):
for j in range(i+1):
print(k,end=" ")
k+=1
print() |
def median(lst):
s = sorted(lst)
l = len(lst)
i = (l-1) // 2
if (l % 2):
return s[i]
else:
return (s[i] + s[i + 1])/2.0
lst=[]
n=input("Enter Number Of Input:")
for x in range(0,int(n)):
x=input("Your Input")
lst.append(x)
print(median(lst))
|
# Data import script
# Provide the name of a csv file as an argument and your data will be imported into the rollcall database
# The CSV should contain three fields:
# Participant ID or group number
# Participant Name
# Day of the week designation
#
# This is tailored towards different workshops that meet during the we... |
#!/usr/bin/python3
#Modules and Testing
#Section 7.4
#See modules_and_testing.py script which this file works in conjunction with.
#See which file this function is in
print(__name__)
#Creating a simple module
def first_half(s):
return s[:len(s)//2]
def last_half(s):
return s[len(s)//2:]
#Testing Modules
#S... |
#!/usr/bin/python3
#Loops and Iterables Section 5
#How to use a for loop
#Structure
'''
for var in array
run code
'''
s = "hello world"
a = [4, 6, 9]
# in keyword
print( 5 in a )
print( 4 in a )
print( "ello" in s )
#Ways to iterate over a list(array)
#Method 1: Include the array
for even_number in [2, 4, 6, 8... |
#!/usr/bin/python3
#Playing with beautifulSoup
import requests
from bs4 import BeautifulSoup
#Uses requests to get the html of a page
url = 'https://newyorktimes.com'
r = requests.get(url)
r_html = r.text
#Saves that html string as a BeautifulSoup object
#(Also specifies the parser to be used)
soup = BeautifulSoup(r... |
# Необходимо написать программу для кулинарной книги.
# Список рецептов должен храниться в отдельном файле в следующем формате:
# В одном файле может быть произвольное количество блюд.
# Читать список рецептов из этого файла.
# Соблюдайте кодстайл, разбивайте новую логику на функции и не используйте глобальных переменн... |
import argparse
import os
import re
from translate_html import translate_html
def translate_template(filename, target_language):
"""
Translates the text in an HTML file, including code snippets embedded
in that file, from English to another language.
:param filename str: the local path to an HTML fi... |
print "\n=Assignment2 Python Program="
def test1(x=26,y=49):
return (x*4)+(y%7)
# 1. Variable Number of Actual Parameters
print "\n1. variable number of actual parameters"
print "result : ", test1(3,5) # numbers as parameters
# 2. Parameter Correspondence
# 2.a Positional
print "\n2... |
#Designed to count phrases of words grouped in 2s
def group_text(text, group_size):
"""
groups a text into text groups set by group_size
returns a list of grouped strings
"""
word_list = text.split()
group_list = []
for k in range(len(word_list)):
start = k
end = k + group_s... |
#!/usr/bin/env python3
'''
Determines the tile proportions as a percentage for a given board.
'''
import sys,os,re
def main(args):
if len(args) < 2:
print("Usage: %s board boards..." % args[0])
return
for fn in args[1:]:
with open(fn) as fp:
#Skip first 8 lines
... |
import random
list1 = [9, 3, 63, 23, -12, 45, 9, -1, 23, 18, 73, 22, 109, -3, 5, 22]
list2 = []
for i in range(0, 15):
list2.append(random.randrange(10000))
list3 = []
for i in range(0, 15):
list3.append(round(random.uniform(-100.0, 100.0), 2))
def min(the_list):
"""
Find and return the minimum in ... |
import random
list1 = [9, 3, 63, 23, -12, 45, 9, -1, 23, 18, 73, 22, 109, -3, 5, 22]
list2 = []
for i in range(0, 15):
list2.append(random.randrange(10000))
list3 = []
for i in range(0, 15):
list3.append(round(random.uniform(-100.0, 100.0), 2))
def minAndMax(the_list):
"""
Find and return the minim... |
class BST:
def __init__(self, initVal=None):
self.value=initVal
if self.value:
self.left= BST()
self.right = BST()
else:
self.left = None
self.right = None
return
def isEmpty(self):
return (self.value == None)
def isLeaf(self):
return (self.left.isEmpty() and self.right.isEmpty())
def inse... |
"""
97. Maximum Depth of Binary Tree
中文
English
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example
Example 1:
Input: tree = {}
Output: 0
Explanation: The height of empty tree is 0.
Example 2:
Input... |
"""
184. Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
Example
Example 1:
Input:[1, 20, 23, 4, 8]
Output:"8423201"
Example 2:
Input:[4, 6, 65]
Output:"6654"
Challenge
Do it in O(nlogn) time complexity.
Notice
The result may be very large, so you need ... |
class MinStack:
def __init__(self):
self.stack = []
self.m = 999999999
"""
@param: number: An integer
@return: nothing
"""
def push(self, number):
self.stack.append(number)
if (number < self.m):
self.m = number
"""
@return: An integer
... |
"""
196. Missing Number
中文
English
Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array.
Example
Example 1:
Input:[0,1,3]
Output:2
Example 2:
Input:[1,2,3]
Output:0
Challenge
Do it in-place with O(1) extra memory and O(n) time.
"""
class Solution:
"""
@param nums: An... |
"""
488. Happy Number
中文
English
Write an algorithm to determine if a number is happy.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or ... |
class Solution:
"""
@param n: The number of digits
@return: All narcissistic numbers with n digits
"""
def getNarcissisticNumbers(self, n):
res = []
if (n == 1):
res.append(0)
for i in range(10**(n-1), 10**n):
if (self.isNarcissisticNumbers(i, n)):
... |
"""
76. Longest Increasing Subsequence
中文
English
Given a sequence of integers, find the longest increasing subsequence (LIS).
You code should return the length of the LIS.
Example
Example 1:
Input: [5,4,1,2,3]
Output: 3
Explanation:
LIS is [1,2,3]
Example 2:
Input: [4,2,4,5,3,7]
Output: 4
Explanatio... |
"""
142. O(1) Check Power of 2
中文
English
Using O(1) time to check whether an integer n is a power of 2.
Example
Example 1:
Input: 4
Output: true
Example 2:
Input: 5
Output: false
Challenge
O(1) time
"""
class Solution:
"""
@param n: An integer
@return: True or false
"""
def checkPowerOf... |
"""
175. Invert Binary Tree
中文
English
Invert a binary tree.Left and right subtrees exchange.
Example
Example 1:
Input: {1,3,#}
Output: {1,#,3}
Explanation:
1 1
/ => \
3 3
Example 2:
Input: {1,2,3,#,#,4}
Output: {1,3,2,#,4}
Explanation:
1 1
/ \ / \
2 3 => 3 2
... |
"""
109. Triangle
中文
English
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Example
Example 1:
Input the following triangle:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
Output: 11
Explanation: The minimum path sum from top to bottom i... |
"""
1011. Number of Lines To Write String
中文
English
We are to write the letters of a given string S, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths, an arr... |
"""
212. Space Replacement
中文
English
Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
Ex... |
"""
159. Find Minimum in Rotated Sorted Array
中文
English
Suppose a sorted array 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).
Find the minimum element.
Example
Example 1:
Input:[4, 5, 6, 7, 0, 1, 2]
Output:0
Explanation:
The minimum value in an array is 0.
E... |
"""
1143. Minimum Index Sum of Two Lists
中文
English
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, out... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.