text stringlengths 37 1.41M |
|---|
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
rw = RandomWalk(100)
rw.fill_walk()
# sets the dimensions for the plot
plt.figure(figsize=(5, 5))
plt.plot(rw.x_values, rw.y_values,lw=1, )
# plot the first and last points /// Green = start /// Red = End
plt.... |
from math import *
def parite(a):
if(a%2==0):
print('le nombre est pair')
else:
print('le nombre est impaire')
def polynome(a,b,c):
d = pow(b,2) - 4 * a * c
print(d)
if(d==0):
s = -b / 2*a
float(s)
print(s, 'est la solution ')
elif(d > 0):
sa =... |
import pandas as pd
import numpy as np
df = pd.DataFrame([['dog', True, 5],
['cat', False, 1]],
columns=['animal', 'bark', 'age'])
df.head()
# np.where(df['animal'] > 2, True, False)
df['hasError']= np.where(df['age'] > 2, 'True', 'False' )
df.head()
print df |
import math
x=25
#y=5
#a=x+y
#b=x-y
#c=x/y
#d=x%y
#print("Addition is :",a)
#print("Subtraction is :",b)
#print("Division :",c)
#print("Module is :",d)
#print(math.sqrt(x))
#greeting = "hello"
#name = "Siva"
#message = greeting +" "+ name
#print(message)
# Boolean or Logical variabls
# != or <>
#==
#<
#>
#<=
#>=
#... |
###################
# Midterm
# Due: Tuesday, November 28 2017
###################
# Array Almost Product
#
# Write a function that, given a list of integers, will return a list of
# integers 'output' wherein the value of output[i] is the product of all the
# numbers in the input array except for input[i].
#
# You wil... |
help(round)
round(1.56666,ndigits=4)
help(print)
a = 10
b = 20
print(a,b,sep=' xYx ', end='\t', flush=True)
print(10)
import sys
import time
for i in range(10):
print(i, end =' ')
sys.stdout.flush()
time.sleep(1)
for i in range(10):
print(i, end=' ', flush=True)
def least_difference(a, ... |
# Import everything from DriveLibraries to allow interaction with the robot, and to create a Robot object
from DriveLibraries import *
# Used for running a mission in a killable way
import multiprocessing
# Some things need delays
from time import sleep
# Define variables with null values so they can be used as global ... |
"""
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
Consider use range(#begin, #end) method
"""
if __name__ == '__main__':
begi... |
# This file holds the minimax implementation.
import random, sys, math
from state import State, X, O, BLANK
# Return the move which the A.I. should take for the current state of the board.
# @arg state should be an instance of state.State
# @arg depth is the limit on the search depth. It is not supported at this time... |
#print("Elegir una operacion:\n1:area del circulo\n2:Ley de gases nobles\n3:formula de la distancia en MRUV\n4:ley dde gravitacion universal\n5:Pitagoras\n6:volmen del cilindro\n7:area del triagulo")
def sumar(a,b):
sum = a + b
return sum
def restar(x,y):
resta = x - y
return resta
def multiplicar(x... |
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def... |
"""
用for循環實現1~100之間的偶數求和
Version: 0.1
Author: 骆昊
Date: 2018-03-01
"""
sum = 0
# 可以產生一個2到100的偶數序列,其中的2是步長,即數值序列的增量。
for x in range(2, 101, 2):
sum += x
print(sum)
|
def mensagem():
print('CALCULADORA')
print('+ ADIÇÃO ')
print('- SUBTRAÇÃO')
print('* MULTIPLICAÇÃO')
print('/ DIVISÃO')
print('Pressione outra tecla para sair')
def operacao(op, x, y):
if (op == '+'):
return (x + y)
if (op == '-'):
return (x - y)
if (op == '*'):
... |
#get numbers
a = float(input())
b = float(input())
#store them in a tuple
tup = (a ,b)
print(tup)
#swap the numbers
(a, b) = (b, a)
print(tup) |
# annual_salary = float(input("Enter your annual salary:\n>>>"))
# portion_saved = float(input("Enter the percent of your salary to save, as a decimal: )\n>>>"))
# total_cost = float(input("Enter the cost of your dream home:\n>>>"))
# portion_down_payment = float(total_cost)*0.25
# current_savings = 0.0
# annual_rate... |
Given: Two positive integers a and b
, each less than 1000.
Return: The integer corresponding to the square of the hypotenuse of the right triangle whose legs have lengths a
and b.
def hypo(a, b):
return math.sqrt(a**2 + b**2) |
#!/usr/bin/python
# This will be a tutorial in lists. Adding, remove, slicing, and dicing. This will also be a
# straight script. No functions here. Notice it also has the "she-bang" open which means it
# can be run independently. so, instead of "python allaboutlist.py", it can be ran (on Linux)
# ./allaboutlists.py (... |
#reverse using list method
list=[1,2,3,4]
list.reverse()
print(list)
#print uppercase letter of a string
string="Hello WorlD"
for i in string:
if(i.isupper()):
print(i)
#split on user input from comma and made a list of it
a=input("enter a string") #eg--1,2,33,566
l=[]
l1=[]
for i in a:
... |
#make a list
l1=[]
n=int(input("no of inputs"))
for i in range (0,n):
a=input()
l1.append(a)
print(l1)
#add two list
l2=['google','apple','facebook','microsoft','tesla']
l3=[]
b=len(l2)
c=n+b;
for i in range(0,n):
l3.append(l1[i])
for j in range(0,5):
l3.append(l2[j])
print(l3)
#cou... |
def getTable():
table = []
for i in range(3):
line = input().split()
table.append(line)
return table
x = False
o = False
verify = False
countX = 0
countO = 0
quant = int(input())
for i in range(quant):
tab = getTable()
for h in range (3):
for t in range (3):
if(... |
from bst import BST
from lista import LinkedList
from random import randint
import time
ONE_SECOND = 1000
REPEATS = 10
instances = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]
def fill_increasing(size):
array = []
for i in range(size):
array.append(i)
return array
... |
from typing import List
class Result():
"""
This is a version of the monad Result
Habitually, we should not be able to access the ok value, or the error value.
It's one of the core concept of a monad.
A monad is like a box. You always need to pass the box to other function, and
when you want... |
#! coding: utf-8
import time # import time module
import datetime # import datetime module
time.clock() # Set clock start
print(time.ctime()) # print current time in format 'Tue May 24 14:09:17 2016’
print(time.localtime().tm_year) # Current time year
print(time.localtime().tm_yday) # Current year day
print(ti... |
#!/usr/bin/python
# Electricty CSV Parser and Calculator
import argparse
import csv
import datetime
def rates_calc(_file):
"""
Takes a csv of the rates on a per day basis and their cost per kWh
Returns a 2 dimential list of kWh X time period X per day
"""
with open(_file, 'rb') as ratesfile:
... |
from time import sleep
from threading import *
class Hello(Thread):
# To use Thread we need to use "run" method. Other name will not work here
def run(self):
for i in range(5):
print("Hello")
sleep(1)
class Hi(Thread):
def run(self):
for i in range(5):
... |
class Competition:
__raise_amount = 1.10
def __init__(self, name, prize):
self.__name = name
self.__prize = prize
def get_name(self):
return self.__name
def get_prize(self):
return self.__prize
def raise_prize(self):
self.__prize = self.__prize * self.__ra... |
import unittest
from coin import coin_check
class CoinTest(unittest.TestCase):
def test_for_quartar(self):
coin = coin_check({'weight': 5.670, 'diameter': .955,
'thickness': 1.75}, 'QUARTER')
assert coin == True
def test_for_penny(self):
coin = coin_check({... |
def permute(arr, l, r): # n!
if l == r:
print(arr)
for i in range(l,r+1):
arr[l], arr[i] = arr[i], arr[l]
permute(arr, l+1, r)
arr[l], arr[i] = arr[i], arr[l]
def combination(arr):
pass
arr = [1, 2, 3]
permute(arr,0,2)
combination(arr) |
# https://leetcode.com/problems/same-tree/
class node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def issame(root1, root2):
if root1 and root2:
if root1.data != root2.data:
return False
return issame(root1.left, root2... |
# example of training a final classification model
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import MinMaxScaler
# generate 2d classification dataset
X, y = make_blobs(n_samples=100, centers... |
import collections, itertools, random
class ChessGame:
"""
Controller class to be used with ChessGUI.py. All logic for chess game
should be implemented here.
TODO: implement castling and en passant in _get_piece_moves. Pawns also need to
be able to move two spots at the beginning of the game... |
print 'This is a test file for Fizzbuzz:'
for i in range(1,20): # Test with range from 1 to 19.
if not i % 15: # When a % b is none-zero, true.
print 'FizzBuzz',
elif not i % 5: # The if elif structure must be ordered from least occured scenerio.
print 'Buzz',
elif not i % 3:
print 'Fizz',
else: print i, ... |
from node import Node
class Queue:
def __init__(self, value):
self.first = Node(value)
self.last = self.first
self.length = 1
def enqueue(self, value):
new_link = Node(value)
if self.length == 0:
self.first = new_link
self.last = new_link
... |
# Zadanie 1 - while
# Napisz mini-encyklopedię Trójmiasta
# Program powinien prosić użytkownika o podanie pojęcia dopóki nie wpisze on komendy "koniec"
# Wszystkie hasła i komendy powinny być obsługiwane niezależnie od wielkości liter.
# W odpowiedzi na znane hasła powinien wypisać odpowiednią informację (treść dowolna... |
"""
Euler 23
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
"""
import timeit
start_time = timeit.default_timer()
import math
def divisors(n):
yield 1
largest = int(math.sqrt(n)) + 1
for i in range(2, largest):
if n % i == 0:
yield ... |
"""
########## CS 229 Machine Learning ###########
########## Programming Assignment 4 ##########
Parts of the code (cart and pole dynamics, and the state
discretization) are adapted from code available at the RL repository
http://www-anw.cs.umass.edu/rlr/domains.html
This file controls the pole-balancing simulati... |
import numpy as np
import pandas as pd
def read_csv(csv_handle):
raw_data = np.loadtxt(csv_handle, delimiter=',')
try:
cols = raw_data.shape[1]
except:
raise ValueError('Wrong data shape. Got shape {}.'\
'Need a shape of the form (Rows,Cols).'
... |
def fact(n):
f = 1
if n < 0:
print(" Factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
f = f*i
print("The factorial of",n,"is",f)
k=int(input("... |
# NamedTuplesDemo2.py
from collections import namedtuple
# 命名工厂
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
s1 = Student('Tom', 16, 'male', 'Tom16@gmail.com')
print(s1) |
"""
Armstrong Number
Define a function that allows the user to check whether a given number is
armstrong number or not.
Hint: To do this, first determine the number of digits of the given number.
Call that n. Then take every digit in the number and raise it to the nth
power. Add them, and if your an... |
"""
This file provides a class that can be ''trained'' on training data, and then produce new
aggregate features for both training and test data. ''Training'' this class simply consists
of it memorizing various statistics.
Features constructed by this class are primarily inspired by:
"A data mining based system for c... |
from abc import ABCMeta, abstractmethod
class AbstractAuthenticator(metaclass=ABCMeta):
def __init__(self):
"""
Every authenticator has to have a name
:param name:
"""
super().__init__()
@abstractmethod
def authorise_transaction(self, customer):
"""
... |
"""
Some simple functions to generate new features by combining existing features
@author Dennis Soemers
"""
def pair_equality(dataframe, column_1, column_2, new_feature_name):
"""
Adds a new binary feature to an existing dataframe which, for every row,
is 1 if and only if that row has equal values in tw... |
import pymysql
# 本文件名讲解:
# i insert 插入
# u update 更新
# d delete 删除
# 连接数据库
conn = pymysql.connect('139.199.99.154','root','toor','py_test', charset='utf8')
# 创建游标
cursor = conn.cursor()
# 数据库查询语句
# 插入userid为1的这行,username为name1(如果userid为1这行已有数据,会报错)
sql_insert = "insert into user (userid,username) values(1,'name1')... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 9 17:25:36 2017
@author: Yash.Zalavadia
"""
class algo(object):
def linearSearch(self,no,myList):
count = 0
for x in myList:
if no==x:
return count
count += 1
def binarySear... |
# -*- coding: utf-8 -*-
from bankapp.printer import Printer
"""
"""
__author__ = 'Marius Kristiansen'
__email__ = 'mariukri@nmbu.no'
class ATM(object):
users = {"marius": 1234}
accounts = {"marius": 5000}
def __init__(self, user):
self.current_user = user
self.balance = None
se... |
from Tkinter import *
from math import sin, sqrt, exp, cos, tan, atan, asin, acos, pi
from numpy import linspace
import matplotlib
import pylab
def remove_spaces(str):
out = ''
for a in str.split(' '):
out += a
return out
def GUI(function):
root = Tk()
function_entry = Entry(root, width = 20)
f... |
def findchar(letter,list):
newlist=[]
for word in list:
if letter in word:
newlist.append(word)
print newlist
findchar('a',['hello','world','my','name','is','Anna'])
|
class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed=max_speed
self.miles = 0
def displayinfo(self):
print "Price: {} Speed: {} Miles: {}".format(self.price, self.max_speed, self.miles)
return self
def ride(self):
print "Riding"
self.miles +=10
return self
... |
import sqlite3
import random
# define actions
actions = {
'AVG': "SELECT AVG(num) from nums",
'MAX': "SELECT MAX(num) from nums",
'MIN': "SELECT MIN(num) from nums",
'SUM': "SELECT SUM(num) from nums",
}
prompt = """
Select the operation that you want to perform:
AVG
MAX
MIN
SUM
exit
"""
while True:
... |
"""
This script returns the current system time.
"""
# Firstly we import the datetime library which contains a range of useful
# utilities for working with dates
import datetime
# Using the datetime library, we can get the current datetime stamp,
# and then call the time() function in order to retrieve the time
time... |
list=[]
n=int(input("Enter the length of the list:"))
for i in range(n):
x=int(input("Enter the value:"))
list.append(x)
list.sort()
print(list)
Target=int(input("Enter the target:"))
if Target==x:
print("Target is found")
else:
print("Target is not found")
|
string=input("Enter the string:")
revstring=string[::-1]
if string==revstring:
print("string is palindrome")
else:
print("not a palindrome") |
N=int(input("enter no:"))
list1=[1]
for i in range(N):
if i==0:
list1.append(list1[i-1])
else:
list1.append(list1[i-2]+list1[i-1])
print list1
|
input_str=str(input("Enter input letter:="))
pattern=str(input("Enter pattern:="))
transition_table=[[0 for i in range(len(input_str))]for j in range(len(pattern)+1)]
print pattern
print input_str
print transition_table
def put_into_transition_table1(transition_table1,i1,j1):
transition_table1[j1]=i1+1
retu... |
AT=[10,11,10.15,10.10]
DT=[10.30,12,11.15,12.30]
AT.sort()
DT.sort()
AT_DT=AT+DT
print AT_DT
AT_DT.sort()
print AT_DT
def count_platform(AT,AT_DT,DT):
AT1=AT
cnt1=0
cnt2=0
print AT1
j=0
k=0
for i in range(len(AT_DT)):
if AT1==[]:
return(len(DT))
else:
... |
# https://leetcode.com/problems/maximum-depth-of-binary-tree/
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
queue = collections.deque([root])
depth = 0
while queue:
depth += 1
for _ in range(len(queue)):
... |
# https://leetcode.com/problems/reconstruct-itinerary/
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
graph = collections.defaultdict(list)
for a, b in sorted(tickets):
graph[a].append(b)
route = []
def dfs(a):
# iterate until t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import numpy
def mandelbrot(x, y, maxit):
"""
Computes real and imaginary numbers, number of iterations
returns value of current iteration.
Takes input of complex numbers:
x - real value
y - imaginary value
maxit - maximum i... |
from bokeh.plotting import square, output_server, show
from bokeh.objects import ServerDataSource
import bokeh.transforms.ar_downsample as ar
"""
In order to run this example, you have to execute
./bokeh-server -D remotedata
the remote data directory in the bokeh checkout has the sample data for this example
In addi... |
#so python can graph scatter plot
import matplotlib.pyplot as plt
#so python can read the image
import matplotlib.image as img
#clear all previous graphs
plt.clf()
#open file
QuakeData = open("currentQuakes.txt")
#read and skip the line
QuakeData.readline()
#make lists of coordinates
LAT = []
LON... |
import pygame
class piece():
def __init__(self, row, col, color, direction):
self.radius = 8
self.row = row
self.col = col
self.color = color
self.x = 0
self.y = 0
self.calxy()
self.direction = direction
def calxy(self):
len... |
import math
memory = {}
validCommands = ["Add", "Subtract", "Multiply", "Divide", "Sin", "Arcsin", "Cos", "Arccos", "Tan", "Arctan", "Sqrt", "Exp", "Ln"]
def getValueForInput(input):
if(isinstance(input, str)):
if(input in memory):
return memory[input]
return int(input)
def getInput():... |
#Recurrent Neural Network
#Part 1 - Data PreProcessing
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the training set
dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:,1:2].values
#Feature scali... |
# 44. Wildcard Matching
# ---------------------
#
# Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'`
# where:
#
# * `'?'` Matches any single character.
# * `'*'` Matches any sequence of characters (including the empty sequence).
#
# The matching s... |
# 51. N-Queens
# ------------
#
# The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack
# each other.
#
# Given an integer `n`, return *the number of distinct solutions to the **n-queens puzzle***.
#
# ### Constraints:
#
# * `1 <= n <= 9`
#
# Source: http... |
import sys
def parse_line(line):
"""
Uses the results of the inputted file to create commands used to extract nucleotide strings. Used to calculate recombination hotspot motif occurrences.
"""
line = line.split()
return("../breakseq/samtools-0.1.19/samtools faidx ~/data/hg38.fa " + line[0] + ":" +... |
import sqlite3
con = sqlite3.connect(r"e:\classroom\python\aug16\hr.db")
cur = con.cursor()
# take input
id = input("Enter job id :")
cur.execute("delete from jobs where id = ?",(id,))
if cur.rowcount == 1:
print("Deleted Successfully!")
con.commit()
else:
print("Sorry! Invalid Job Id!")
con.close(... |
sum = 0
i = 1;
while i <= 5:
try:
n = int(input("Enter a number :"))
sum += n
i += 1
except ValueError:
print("Sorry! Invalid number! Please enter valid number.")
print("Sum = ", sum)
|
def isodd(n):
# print("Value = ", n)
return n % 2 == 1
num = [10, 20, 30, 44, 55, 6, 77, 99]
oddnums = filter(isodd, num)
# for n in oddnums:
# print(n)
oddnums = filter(lambda n: n % 2 == 1, num)
for n in oddnums:
print(n)
|
def zero(num):
print(id(num))
num = 0
print(id(num))
def insert(lst, value):
lst.insert(0, value)
a = 10
print(id(a))
zero(a)
print(a)
l = [10, 20]
insert(l, 5)
print(l)
|
num = int(input("Enter a number :"))
fact = 1
for i in range(2,num + 1):
fact *= i
print(f"Factorial of {num} is {fact}")
|
print("What two numbers would you like to add?")
n1 = input()
n2 = input()
n1 = int(n1)
n2 = int(n2)
print("The sum of the numbers is", n1+n2, "!") |
#Write one of Python that takes this list and makes a new list
# that has only the even elements of this list in it
#predefined list
#can also use [y**2 for y in range(1,11)]
a = [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = ([x for x in a if x % 2 == 0])
print(b)
#one line code
#print(x for x in [y**2 fo... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def countPairs(self, root, distance):
"""
:type root: TreeNode
:type distanc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/03/11
# @Author : yuetao
# @Site :
# @File : LeetCode227_基本计算器II.py
# @Desc :
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
stack = []
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/03/20
# @Author : yuetao
# @Site :
# @File : LeetCode173_二叉搜索树迭代器.py
# @Desc :
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/26
# @Author : yuetao
# @Site :
# @File : LeetCode85_最大的矩型.py
# @Desc :
"""
单调栈思想,同84题解法相似
参考解法:https://leetcode-cn.com/problems/maximal-rectangle/solution/dan-diao-zhan-fa-ba-wen-ti-zhuan-hua-che-uscz/
"""
class Solution(object):
def... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/27
# @Author : yuetao
# @Site :
# @File : LeetCode205_同构字符串.py
# @Desc :
"""
输入: s = "egg", t = "add"
输出: true
record_map 记录映射的值
used_char 字符是否被映射
"""
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: st... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-12-01 20:46
# @Author : Letao
# @Site :
# @File : LeetCode378_有序矩阵中第K小的元素.py
# @Software: PyCharm
# @desc :
import heapq
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/7 0007 21:18
# @Author : Letao
# @Site :
# @File : LeetCode332_图的DFS.py
# @Software: PyCharm
# @desc :
import collections
class Solution(object):
res = []
def findItinerary(self, tickets):
"""
:type tickets: List[List[... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/29 0029 18:32
# @Author : Letao
# @Site :
# @File : LeetCode6_Z字形变换.py
# @Software: PyCharm
# @desc :
"""
找间隔规律
每行进行循环
"""
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/04/26
# @Author : yuetao
# @Site :
# @File : LeetCode1011_在D天内送达包裹的能力.py
# @Desc :
class Solution(object):
def shipWithinDays(self, weights, D):
"""
:type weights: List[int]
:type D: int
:rtype: int
"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/01/06
# @Author : yuetao
# @Site :
# @File : 二叉搜索树的后序遍历序列.py
# @Desc :
"""
分治算法
"""
class Solution(object):
def verifyPostorder(self, postorder):
"""
:type postorder: List[int]
:rtype: bool
"""
def ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-11-08 21:15
# @Author : Letao
# @Site :
# @File : LeetCode122_买卖股票的最佳时机II.py
# @Software: PyCharm
# @desc :
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/03/10
# @Author : yuetao
# @Site :
# @File : 希尔排序.py
# @Desc :
"""
"""
class Solution(object):
def sort_gap(self, nums):
length = len(nums)
gap = int(length/2)
while gap > 0:
for i in range(gap, length):... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
flag = True
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: Tre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/09/08
# @Author : yuetao
# @Site :
# @File : NC62_平衡二叉树.py
# @Desc :
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/6 0006 19:32
# @Author : Letao
# @Site :
# @File : 小红书.py
# @Software: PyCharm
# @desc :
"""
10
2 3 4
5 3 2 6
"""
class Solution:
def deal(self,X, L ,T, N, N_NUMS):
dp = [float("inf")] * (X+1)
if L > max(N_NUMS):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/14 0014 18:36
# @Author : Letao
# @Site :
# @File : LeetCode20_有效的括号.py
# @Software: PyCharm
# @desc :
import collections
class Solution(object):
bracket_map = {
")": "(",
"]": "[",
"}": "{"
}
def isValid(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/4 0004 17:47
# @Author : Letao
# @Site :
# @File : LeetCode1315.py
# @Software: PyCharm
# @desc : 祖父节点值为偶数的节点和
# https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent/
# Definition for a binary tree node.
class TreeNode(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/03/05
# @Author : yuetao
# @Site :
# @File : LeetCode232_用栈实现队列.py
# @Desc :
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.enter = []
self.out = []
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-11-04 22:48
# @Author : Letao
# @Site :
# @File : LeetCode56_合并区间.py
# @Software: PyCharm
# @desc :
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/15 0015 23:10
# @Author : Letao
# @Site :
# @File : LeetCode36_有效独数.py
# @Software: PyCharm
# @desc :
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/03/10
# @Author : yuetao
# @Site :
# @File : 冒泡排序.py
# @Desc :
"""
每一趟选择一个最大值
"""
class Solution(object):
def BubbleSort(self, nums):
length = len(nums)
for i in range(length-1):
#遍历的次数
for j in rang... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-12-15 23:08
# @Author : Letao
# @Site :
# @File : LeetCode738_单调递增的数字.py
# @Software: PyCharm
# @desc :
"""
单调栈,遇小变9,前一位-1
"""
class Solution(object):
def monotoneIncreasingDigits(self, N):
"""
:type N: int
:rtype: ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/01/25
# @Author : yuetao
# @Site :
# @File : 队列的最大值.py
# @Desc :
import collections
import heapq
class MaxQueue(object):
def __init__(self):
self.value = collections.deque()
self.heap = []
def max_value(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/10 0010 20:56
# @Author : Letao
# @Site :
# @File : LeetCode1123.py
# @Software: PyCharm
# @desc :最深叶节点的最近公共祖先
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/03/27
# @Author : yuetao
# @Site :
# @File : LeetCode61_旋转链表.py
# @Desc :
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def rotateRight(self, head, ... |
"""
递归找出所有
"""
import queue
from collections import defaultdict,deque
class Solution(object):
def countSubTrees(self, n, edges, labels):
"""
:type n: int
:type edges: List[List[int]]
:type labels: str
:rtype: List[int]
"""
"""
以 0 点为根,构造多叉树,层次遍历
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.