text
stringlengths
37
1.41M
import pandas as pd import altair as alt import streamlit as st @st.cache def get_UN_data(): AWS_BUCKET_URL = "https://streamlit-demo-data.s3-us-west-2.amazonaws.com" df = pd.read_csv(AWS_BUCKET_URL + "/agri.csv.gz") return df.set_index("Region") try: df = get_UN_data() except urllib.error...
"""Building QA suitable for GCD game.""" import math import random from brain_games.qa import QA NUMBER_INTERVAL = (1, 100) HOW_TO_ANSWER_INSTRUCTION = 'Find the greatest common divisor of given numbers.' def gen_gcd_qa(operand1: int, operand2: int): """Create QA.""" question = '{0} {1}'.format( op...
import matplotlib.pyplot as pltdef bresenham(x1,y1,x2, y2): m = 2 * (y2 - y1) slope_error = m - (x2 - x1) y=y1 for x in range(x1,x2+1): print("(",x ,",",y ,")\n") slope_error =slope_error + m if (slope_error >= 0): y=y+1 slope_error =slope_error - 2 * (x2 - x1) x1= int(input())x2= int(input())y1= int(i...
def intersect(*args): res=[] for x in args[0]: if x in res: continue for other in args[1:]: if x not in other: break #This is a for...else construct. #The else is executed after the for, but only if the for terminates normally (not by a break). else: r...
#Look at this link to learn about checking broken links # https://www.webucator.com/blog/2016/05/checking-your-sitemap-for-broken-links-with-python/ #I start from a url. Collect all the links in that page looking at 'a' tag. #Then I remove the links which do not have any href attribute. #Then I request all url and che...
#Check permute.txt for an explanation about how permute1 works. def permute1(seq): if not seq: print('empty sequence') return [seq] #empty list else: res=[] for i in range(len(seq)): rest = seq[:i] + seq[i+1:] # Delete current node for x in permute1(rest)...
def isPrime(y): if y <= 1: #by definition prime numbers are integers > 1 print(y, ' not prime') else: x = y // 2 while x > 1: if y % x == 0: print(y, ' has factor ', x) break x -= 1 else: print(y, ' is prime') ...
# __contains__ example class Iters: def __init__(self, value): self.data = value def __getitem(self, i): print('get[%s]' % i, end='') return self.data[i] def __iter__(self): print('iter =>', end='') self.ix = 0 return self def __next__(self): print('next: ', end='') if self.ix == len(self.data): ra...
# overloading __getitem__ can be used to implement iteration, list comprehension, map calls too # to implement iteration remember __iter__ is the preferred way, rather than __getitem__ # run in Python 3 class StepperIndex: def __getitem__(self, i): return self.data[i] X = StepperIndex() X.data = "Spam" ...
# Example showing how to implement private attribute # It can be done in different, and better, ways class PrivateExc(Exception): pass class Privacy: def __setattr__(self, attrname, value): if attrname in self.privates: raise PrivateExc(attrname, self) else: self.__dict__[attrname] = value # Avoid loops by...
#The same result can be achieved with a custom function, a map and a list comprehension #Using a custom Function res = [] for x in 'spam': res.append(ord(x)) print('Function result: ', res) #Using map res = list(map(ord, 'spam')) print('Map result: ', res) #Using list comprehension res = [ord(x) for x in 'spa...
#In Python functions are objects so I can do things like this one print('*** Functions are objects ***') def echo(message): print('Message from echo: ', message) echo('Direct Call') x = echo x('Indirect Call') #Arguments are passed by assigning objects, therefore I can pass a function as an argument print('*** P...
# Инкапсуляция — ограничение доступа к составляющим объект компонентам (методам и переменным). # Модификаторы доступа в Python используются для модификации области видимости переменных по умолчанию. Есть три типа модификаторов доступов в Python ООП: # публичный — public; # приватный — private; # защищенный — protecte...
''' Scenario: In 1937, a German mathematician named Lothar Collatz formulated an intriguing hypothesis (it still remains unproven) which can be described in the following way: take any non-negative and non-zero integer number and name it c0; if it's even, evaluate a new c0 as c0 ÷ 2; otherwise, if it's odd, evaluate a...
class Stack: def __init__(self): self.stackList = [1] stackObject = Stack() print(len(stackObject.stackList)) ''' Declaring a variable "stackList" inside the constructor of the Class stack '''
import hashlib import random class Algorithms : def caesar(): def encrypt(datas, difficulty) : encrypted_datas = "" if len(datas) == 0 : print ("The datas who are being encrypted in the caesar algorithm get a size of 0 bits...
nterms = int(input("How many terms? ")) n1 = 0 n2 = 1 count = 0 if nterms<=0: print("Enter valid number of terms") elif nterms==1: print("Fibonacci series upto " + str(nterms) + " is:") print(n1) else: print("Fibonacci series is:") while count<nterms: print(n1) next = n1 + n2 ...
import math def RadixSort(a, radix=10): """a为整数列表, radix为基数""" K = int(math.ceil(math.log(max(a), radix))) # 用K位数可表示任意整数 bucket = [[] for i in range(radix)] # 不能用 [[]]*radix for i in range(1, K + 1): # K次循环 for val in a: bucket[int(val % (radix ** i) / (radix ** (i - 1)))].appen...
def sanitize(word: str, allowed_characters: list) -> str: for c in word: if c not in allowed_characters: word = word.replace(c, '') return word def generate_email(name: str) -> str: name = name.lower() if name == 'de lillo silvana': return 'silvana.delillo@unipg.it' if...
# Dictionaries dogs = {"Fido": 8, "Sean": 17, "Jane": 4} print(dogs) del(dogs["Sean"]) # delete an item from dictionary for dog in dogs.keys(): print(dog) for dog in dogs.values(): print(dog) for dog in dogs.items(): print(dog)
import unittest from linked_list.py import * class TestCase(unittest.TestCase): def test_empty_list(self): self.assertEqual(empty_list(), None) def test_add(self): self.assertEqual(add(Pair(5, Pair(10, "mt")), 2, 7.5), Pair(5, Pair(10, Pair(7.5, "mt")))) self.assertEqual(add(Pair(5, Pair...
from vec import Vec from mat import Mat def identity(D, one): """ Given a set D and the field's one, returns the DxD identity matrix """ return Mat((D,D), {(d,d):1 for d in D}) def keys(d): """ Given a dict, returns something that generates the keys; given a list, returns something that generates the...
import csv import os #empty lists total_votes = [] candidates = [] candidate_1 = [] candidate_2 = [] candidate_3 = [] candidate_4 = [] electionFilePath = os.path.join("Resources/" + "election_data.csv") #read csv with open(electionFilePath ) as csvFile: csvReader = csv.reader(csvFile, delimiter=",") csvRow ...
def min3(num1,num2,num3): if ((num1 < num2) and (num1 < num3)): return num1 elif ((num2 < num1) and (num2 < num3)): return num2 else: return num3 print(min3(4,7,5)) print(min3(4,5,5)) print(min3(4,4,4)) print(min3(-2,-6,-100)) print(min3("Z","B","A"))
from typing import * import fractions as fr class Matrix: """A matrix like in linear algebra _elements: the elements in a matrix denoted as a list of lists. _augmented: whether the last column is augmented or not. Follows Matrix[row_num][col_num] """ _elements: List[List[fr.Fraction]] _aug...
# 10家店 一个2包辣条 1包1元 money = 0 count = 1 while count <= 10: mark = 1 # 一共买了几次 while mark <= 2: money = money + 1 mark += 1 print("走了%d"%count) count += 1 print("一共花了%f元"%money)
account = "yiwangxi" pwd = "123456" isLoop = True count = 0 while isLoop: myAccount = input("请输入帐号") myPwd = input("请输入密码") if myAccount == account and myPwd == pwd: print("登录成功") lcoation =int(input("请选择英雄 0ADC 1肉 3法师")) if lcoation == 0: print("鲁班大师") elif lcoation == 1: print("程咬金") eli...
# 这是服务器的帐号和密码 account = 123456 pwd = "abc" #这是你输入的帐号和密码 myAccount = int(input("请输入帐号:\n")) myPwd =input("请输入密码\n") if myAccount == account and myPwd == pwd: print("登录成功") elif myAccount != account: print("帐号错误") elif myPwd != pwd: print("密码错误") else: print("系统泡妞去啦")
class bank: accNum = 0 opnBal = 0 curBal = opnBal cusName = "John Doe" def __init__(self): print("hi from init") def update(self, a, o, n): self.accNum = a self.opnBal = o self.curBal = self.opnBal self.cusName = n def display(self): print("...
''' adapted from Kimmo's previous year's slides thank you Kimmo for the example ''' import asyncio import time async def count(task_id): print("One {}".format(task_id)) await asyncio.sleep(task_id) # Any IO-intensive task here print("Two {}".format(task_id)) async def main(): # it shows that they are actually ex...
product = [] while True: name = input('請輸入商品名稱') if name == 'q': break price = input('請輸入商品價格') product.append([name, price]) #print(product) for p in product: print(p[0], '的價格是', p[1])
import abc import random class Plaintext(object): __metaclass__ = abc.ABCMeta def __init__(self): super().__init__() def __call__(self): plaintext = self.generate() return plaintext.strip() @abc.abstractmethod def generate(self): pass class VarLengthPlaintext(Plaintext): def __init__(self, word...
n=100 for i in range(n): i=i+1 if (i%3)==0 and (i%5)==0: print "fizzbuzz" elif (i%3)==0: print "fizz" elif (i%5)==0: print "buzz" else: print str(i)
import string import random from Bio.SubsMat import MatrixInfo aminoacid_list = "ARNDCEQGHILKMFPSTWYV" aminoacid_prob = { "A": 0.0826, "Q": 0.0393, "L": 0.0965, "S": 0.0660, "R": 0.0553, "E": 0.0674, "K": 0.0582, "T": 0.0535, "N": 0.0406, "G": 0.0708, "M": 0.0241, "W": 0.0109, "...
# -*- coding: utf-8 -*- """ Created on Wed Nov 28 14:58:31 2018 @author: aantao """ import numpy import matplotlib.pyplot as plt def plot_random_walk(n): if not isinstance(n,int): raise ValueError("Number of steps must be an integer") else: walk_array=numpy.zeros(n) for i in range(1,l...
import datetime """ This is a docstring. This function creates a file based on the datetime and inputs 'Hello' as a string. The filename is printed in format dd-MMM-YYYY. The script then outputs the name of the file into the cmd """ #filename = "sample1.txt" dateTimeObj = datetime.datetime.now() filename1 = dateTimeObj...
import unittest from src.swap_vowel_case import swap_vowel_case as swap class TestSwapVowelCase(unittest.TestCase): def test_swap_vowel(self): self.assertEqual(swap(" "), " ") self.assertEqual(swap("C Is AlIvE!"), "C is alive!") self.assertEqual(swap("to"), "tO") self.assertEqual(sw...
def reverse(sentence): if type(sentence) != str: raise ValueError('Please provide a valid string input.') return " ".join(sentence.split(' ')[::-1])
def what_is(number): if number == 42: return 'everything' elif number == 42 * 42: return 'everything squared' else: return 'nothing'
def generate_pairs(m, n): if type(m) != int: raise ValueError(f"m ({m}) provided is not a valid integer.") if type(n) != int: raise ValueError(f"m ({n}) provided is not a valid integer.") pairs = [] for parent_number in range(m, n + 1, 1): for child_number in range(parent_number...
def multiple(number): if type(number) != int: raise ValueError('Please provide a valid integer.') message = '' if number % 3 == 0: message = 'Bang' if number % 5 == 0: message += 'Boom' if number % 3 != 0 and number % 5 != 0: message = 'Miss' return message
# coding=utf-8 from plp import PLP plp = PLP() def basic_form(word): ids = plp.rec(word) if not ids: return word return plp.bform(ids[0]) def deogonkify(word): """The word must be lowercase.""" substitutions = { u'ą': 'a', u'ć': 'c', u'ę': 'e', u'ł': 'l'...
# 13. Decapitalize # This method can be used to turn the first letter of the given string into lowercase. def decapitalize(str): return str[:1].lower() + str[1:] print(decapitalize('FooBar')); # 'fooBar' print(decapitalize('FooBar')); # 'fooBar'
# 5. Print a string N times # This snippet can be used to print a string n times without having to use loops to do it. n = 2; s ="Programming"; print(s * n); # ProgrammingProgramming
""" Task 1: Instructions Use our friend's data to create a dictionary. To do so, you will need to perform the following steps. Create a list of years from 2011 to 2020 and a list durations of the average movie lengths our friend provided (103, 101, 99, 100, 100, 95, 95, 96, 93, and 90). Create a dictionary movie_dict,...
""" Generic Square Class """ class Square: """This class represents a simple Square object.""" def __init__(self, size, pos, pen_size=5, pen_color="red", fill_color="blue"): """Constructor - create an instance of Square.""" self._size = size self._pos = pos self._pen_size = pe...
import pandas as pd import numpy as np # ------------------------ # Creating Empty DataFrame # ------------------------ df = pd.DataFrame() print(df) print('----------------------------------') # ---------------------------- # Creating DataFrame From Lists # ---------------------------- print('Creating DataFrame From ...
''' Create an instance of the class Model which solves a differential equation using a feed forward neural network. The initialization necessits: _ a function f defining the dynamic of the system (i.e. y'=f(x,y)) _ the trial solution used Optionnal arguments are: _ the size of the hidden layers, given as a...
import random import string import sys file = open('C:\_dev\GitHub\Hangman\words.txt', 'r') words = file.read().split('\n') file.close() random = random.randint(1, 200)+1 word = list(words[random]) #randomly generated word tempword = list(word) available = string.ascii_lowercase guess = [] #the word the pla...
# 노래의 정보를 담는 클래스 class Song: def __init__(self): self.name = "" self.lyrics = "" self.auth = "" def setName(self, name): self.name = name.replace("?", "") def setLyrics(self, lyrics): self.lyrics = lyrics def setAuth(self, auth): self.auth...
def is_prime(n): if n % 2 == 0: return False p = 3 while p < n**0.5+1: if n % p == 0: return False p += 2 return True def nth_prime(n): prime = 2 count = 1 iter = 3 while count < n: if is_prime(iter): prime = iter count += 1 iter ...
a = input("choose the starting number\n") b= input("choose the end\n") c=reduce(lambda x, y: x+y, range(a,b)) print "the sum of these given range is "+str(c)
import tkinter def key_down(e): key = e.keysym if key == "Up": draw_road(0, -5) if key == "Down": draw_road(0, 5) BORD_COL = ["white", "silver", "gray"] def draw_road(di, updown): canvas.delete("ROAD") h = 24 y = 600 - h for i in range(23, 0, -1): uw ...
from Tkinter import * def ShowChoice(): if v.get() == '1': import YouVsPc if v.get() == '2': import PcVsYou app = Tk() app.title('Application') app.geometry('300x300') title = Label( app , width = 10, text = "Lines'game", font=("Helvetica", 36), bd = 10, fg = 'red' , height = 2, relief=RAISED...
distance = int(input('Сколько километров спортсмен пробежал в первый день? ')) goal = int(input('Какое количество километров спортсмен должен пробежать в сумме? ')) total = distance days = 1 print(f'{days}-й день: {distance} км') while total < goal: distance = 1.1 * distance total = total + distance days +...
__author__ = 'Samuel' # # WRONG (SLOW) # primes = [] last = 0 primes.insert(last, 2) def NextPrime(): global last, primes number = primes[last] found = False while not found: number += 1 found = True for x in range(2, number - 1): if (number % x == 0): ...
#!/usr/bin/env python # coding: utf-8 # ## Multiple revolutions on Lambert's problem # # After the implementation of Izzo's algorithm in *poliastro*, it is possible to solve the Lambert's # problem with a multiple revolution solution. Let us remember first what is this problem about and which # applications does it h...
# Simple 3D Mesh example ### # `go.Mesh3d` draws a 3D set of triangles with vertices given by `x`, `y` and `z`. If only coordinates are given, an algorithm such as [Delaunay triangulation](https://en.wikipedia.org/wiki/Delaunay_triangulation) is used to draw the triangles. Otherwise the triangles can be given using t...
#!/usr/bin/env python # coding: utf-8 # # Solving a discrete boundary-value problem in scipy # # TAGS: Ordinary differential equations # # AUTHORS: Nikolay Mayorov # ## Mathematical formulation # We consider a nonlinear elliptic boundary-value problem in a square domain $\Omega = [0, 1] \times [0, 1]$: # $$ # \Delta...
""" ================================================== Plot variance and regularization in linear models ================================================== """ import numpy as np # Smaller figures from matplotlib import pyplot as plt ############################################################ # We consider the si...
#!/usr/bin/env python # coding: utf-8 # # Solving a Laplace problem with Dirichlet boundary conditions # ### Background # In this tutorial, we will solve a simple Laplace problem inside the unit sphere with Dirichlet boundary conditions. Let $\Omega$ be the unit sphere with boundary $\Gamma$. Let $\nu$ be the outwar...
def is_positive(i): if i > 0: return True else: return False a = -10; if is_positive(a) == True: print('aの値は正です') else: print('aの値は負またはゼロです')
import random from pendulum import Pendulum, DoublePendulum from RK_DAE_solver import ERK_DAE1 from methods import Euler, ExplicitMidpoint, RK4, DOPRI5 def random_initial_values(p_mag, m_mag=5): """Returns tuple of random initial values of mass `m`, and positional coordinates `x` and `y`. Prefers initia...
#!/usr/bin/env python # coding: utf-8 # # Going to Mars with Python using poliastro # # <img src="https://docs.poliastro.space/en/latest/_images/logo_text.png" /> # # This is an example on how to use [poliastro](https://github.com/poliastro/poliastro), a little library I've been working on to use in my Astrodynamics...
""" Plot fitting a 9th order polynomial ==================================== Fits data generated from a 9th order polynomial with model of 4th order and 9th order polynomials, to demonstrate that often simpler models are to be prefered """ import numpy as np from matplotlib import pyplot as plt from matplotlib.colors...
class StudentCard: def __init__(self, id, name): self.__id = id self.__name = name def get_name(self): return self.__name def get_id(self): return self.__id a = StudentCard(12345, '鈴木太郎') #print(a.__id) #print(a.__name) print(a.get_id()) print(a.get_name())
#!/usr/bin/python3 def divisible_by_2(my_list=[]): rslt = [] for i in range(0, len(my_list)): if my_list[i] % 2 == 0: rslt.append(True) else: rslt.append(False) return rslt
#!/usr/bin/python3 def uppercase(str): for i in str: if ord(i) >= 97 and ord(i) <= 122: j = ord(i) - 32 else: j = ord(i) print("{:c}".format(j), end="") print(end="\n")
#!/usr/bin/python3 def multiply_by_2(a_dictionary): nd = dict(a_dictionary) for key in nd: nd[key] = nd[key] * 2 return (nd)
#!/usr/bin/python3 def remove_char_at(str, n): f = "" lenth = len(str) for i in range(0, lenth): if i == n: continue else: f = f + str[i] return (f)
def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 print('dx is', dx) print('dy is', dy) return 0.0 retVal=distance(100,200,30,40) print('retVal=', retVal)
"""This script takes in real estate data and cleans it up for regression analysis Todo: *Build a column with the S&P/Case-Shiller National Home Price Index value *Build a column with inflation adjustment for ClosingPrice """ import pandas as pd import numpy as np import argparse features = {'Exterior' : ['Po...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2019/5/22 20:08 # @Author : wuzushun # @File : rmployee.py from abc import ABCMeta,abstractmethod class Employee(object,metaclass=ABCMeta): """员工""" def __init__(self,name): """ 初始化方法 :param name:员工名称 """ self._na...
from sqlalchemy import create_engine from sqlalchemy import Column, MetaData, Table from sqlalchemy import Integer, String, ForeignKey from sqlalchemy.orm import mapper, sessionmaker class User(object): """""" #---------------------------------------------------------------------------- def __init__(self, name, fu...
def number_list(increment): i = 0 last_num = increment * 10 numbers = [] while i < last_num: print "At the top i is %d" % i numbers.append(i) i += increment print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num def second_number_l...
''' This gets links to websites from PAS You only get about 20 objects here as that is how many are per page. Created on Aug 3, 2016 @author: maltaweel, modified by tcrnmar ''' from bs4 import BeautifulSoup import urllib2 from urlparse import urlparse import re class PasSearchOnePage(object): def __init__...
#!/usr/bin/python import numpy as np from keras.models import Sequential from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.layers.core import Flatten, Dense import input_data mnist = input_data.read_data_sets("Mnist_data/", one_hot=True) X_train = mnist.train.images.reshape(-1, 28, 28) Y_train =...
numero_factorial = int(input("Ingrese un número entero positivo: ")) num = numero_factorial if (numero_factorial <= 0): print ("Resultado = 1") elif (numero_factorial > 1): i = 1 resultado_factorial = 1 while numero_factorial > i: resultado_factorial = resultado_factorial * numero_factorial ...
""" Returns a pair with letters and totals accordingly to a list of strings and letters """ def count_occurrences(string, letter, count): if len(string) == 0: return count else: if string[0] == letter: count += 1 return count_occurrences(string[1:], letter, count) def get_let...
# 2 # print('Hello World') # print('Welcome To Python') name = raw_input("What is your name?") print("Hello {0}").format(name) print(name.lower()) print(name[0].upper() + name[1: len(name)].lower() ) print(name[1:4]) # my_list = [1,2,3,4,5,6] # print(sum(my_list)) # count = 0 # for i in my_list: # count +...
def number_p(x,y): i = 0 numbers = [] while i < x: print ("At the top of i is %d" % i) numbers.append(i) i = i+y print ("Numbers now: ", numbers) print ("At the bottom of i is %d" % i) print ("The numbers are: ") for num in numbers: print ...
def cheese_and_crackers (cheese_count, boxes_of_crackers): print ("You have %d cheeses" % cheese_count) print ("You have %d boxes of crackers" % boxes_of_crackers) print ("Man, That's enough for the party") print ("Get a blanket\n") print ("We can just give the function numbers directly:") chees...
num1=input("enter integer number") num2=input("enter integer number") sum= int(num1)+int(num2) print(sum)
# # @lc app=leetcode id=268 lang=python # # [268] Missing Number # # https://leetcode.com/problems/missing-number/description/ # # algorithms # Easy (48.43%) # Likes: 940 # Dislikes: 1357 # Total Accepted: 286.3K # Total Submissions: 588.9K # Testcase Example: '[3,0,1]' # # Given an array containing n distinct n...
# # @lc app=leetcode id=415 lang=python # # [415] Add Strings # # https://leetcode.com/problems/add-strings/description/ # # algorithms # Easy (43.73%) # Likes: 420 # Dislikes: 147 # Total Accepted: 100K # Total Submissions: 227.9K # Testcase Example: '"0"\n"0"' # # Given two non-negative integers num1 and num2 ...
# # @lc app=leetcode id=401 lang=python # # [401] Binary Watch # # https://leetcode.com/problems/binary-watch/description/ # # algorithms # Easy (45.32%) # Likes: 376 # Dislikes: 634 # Total Accepted: 64.9K # Total Submissions: 142.9K # Testcase Example: '0' # # A binary watch has 4 LEDs on the top which represe...
# # @lc app=leetcode id=107 lang=python3 # # [107] Binary Tree Level Order Traversal II # # https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ # # algorithms # Easy (46.84%) # Likes: 745 # Dislikes: 139 # Total Accepted: 231.2K # Total Submissions: 490.5K # Testcase Example: '[3,9,20...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 24 13:51:59 2019 @author: portiajohnson """ #Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment each month. #balance - the outstanding balance on the credit card #annualInterest...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: r...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify roo...
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n <= 2: return n a, b = 1, 2 while n > 2: a, b, n = b, a+b, n-1 return b
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :r...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def closestValue(self, root, target): """ :type root: TreeNode :type target: float :rtype...
class TwoSum(object): def __init__(self): """ initialize your data structure here """ self.mapi = {} def add(self, number): """ Add the number to an internal data structure. :rtype: nothing """ self.mapi[number] = 1 if number not in self...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def addTwoNumbers(self, l1, l2): carry = 0 dummy = ListNode(None) cur ...
class Solution: # @param {string} s # @return {string} def longestPalindrome(self, s): stri, maxi = '#' + '#'.join(list(s)) + '#', 0 center, p = 0, [1]*len(stri) for i in range(len(stri)): p[i] = min(p[2*center-i], center+p[center]-i) if i < center+p[center] else 1 ...
class Solution(object): def longestIncreasingPath(self, matrix): """ :type matrix: List[List[int]] :rtype: int """ if not matrix: return 0 dp = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] def traverse(matrix, r, c, dp): if dp[...
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals, res = sor...
# Find the count of duplicate character fruit = "acclec" i = 0 for idx in range(len(fruit)): if fruit[idx] == 'c': i += 1 print(i)