content
stringlengths
7
1.05M
class GraphAlgos: """ Wrapper class which handle the graph algorithms more efficiently, by abstracting repeating code. """ database = None # Static variable shared across objects. def __init__(self, database, start, relationship, end = None, orientation = 'NATURAL', rel_weight = None): ...
total = int(input()) b_num = 0 b_x = 0 b_y = 0 for i in range(total): num, x, y = map(int, input().split()) mn = num - b_num mx = abs(x - b_x) my = abs(y - b_y) if mn < mx + my: print("No") exit() else: if b_num % 2 == (mx + my) % 2: mn = num b_...
strMD5Salt = "vfkpbin1ix2rb88gfjebs0f60cbvhedl" dictURL = { "search/ershoufang": { "URL": "https://ajax.lianjia.com/map/search/ershoufang/?city_id={city_id}&group_type={group_type}&" "max_lat={max_lat}&min_lat={min_lat}&max_lng={max_lng}&min_lng={min_lng}&" "filters=%7B%7D&requ...
# uninhm # https://atcoder.jp/contests/abc164/tasks/abc164_c # dictionary a = {} ans = 0 n = int(input()) for _ in range(n): i = input() ans += a.get(i, 1) a[i] = 0 print(ans)
class UnionFind: def __init__(self, size): self.parent = list(range(size)) self.component = [[i] for i in range(size)] def root(self, i): if self.parent[i] != i: self.parent[i] = self.root(self.parent[i]) return self.parent[i] def unite(self, i, j): i, j = self.root(i), self.root(j...
class Print: """ A simple text-printing component """ def doPrint(self, v): print(v) @staticmethod def cfgr(builder): ## outputs builder.addInput('on').string_to_method(lambda obj: obj.doPrint)
#!/usr/bin/env python # -*- coding: utf-8 -*- class TClassStatic(object): obj_num = 0 def __init__(self, data): self.data = data TClassStatic.obj_num += 1 def printself(self): print("self.data: ", self.data) @staticmethod def smethod(): print("the number of obj is : "...
# This code is connected with '18 - Modules.py' def kgs_to_lbs(weight): return 2.20462 * weight def lbs_t_kgs(weight): return 0.453592 * weight
"""December 1st""" def sevenish_number(num): """Sevenish Number""" power_of_two = 0 sevenish = 0 while num > 0: val = pow(7, power_of_two) if num % 2 == 1 else 0 sevenish += val power_of_two += 1 num //= 2 return sevenish
""" ------------------------------------------------------------------------------ @file variable.py @author Milos Milicevic (milosh.mkv@gmail.com) @brief ... @version 0.1 @date 2020-08-26 @copyright Copyright (c) 2020 Distributed under the MIT software licens...
n=int(input()) arr=[] game=True for i in range(n): arr.append((input())) for j in range(n): if "OO" in arr[j]: print("YES") ind=arr[j].index("OO") if ind==0 and arr[j][ind+1]=="O": arr[j]="++|"+arr[j][3]+arr[j][4] if ind==3 and arr[j][ind+1]=="O": arr[j]=arr[j][0]+arr[j][1]+"|"+"++" game=False break...
# -*- coding: utf-8 -*- """ Created on Sat May 29 03:30:25 2021 @author: Septhiono """ year=int(input("Which year would you like to check?")) if year%4==0: if year%100==0: if year%400==0: print(f"{year} is a leap year") else: print(f"{year} is not a leap year")...
""" LeetCode Problem: 1095. Find in Mountain Array Link: https://leetcode.com/problems/find-in-mountain-array/ Language: Python Written by: Mostofa Adib Shakib """ class Solution: def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int: #binary search to find the peak mountain ...
"""Modules for user interfaces. Modules: ui -- Provide a base class for user interface facades. ui_cmd -- Provide a facade for a command line user interface. ui_tk -- Provide a facade for a Tkinter based GUI. ui_mb -- Provide a facade for a GUI featuring just message boxes. """
class A: def spam(self): print('A.spam') class B(A): def spam(self): print('B.spam') super().spam() # Call parent spam() class C: def __init__(self): self.x = 0 class D(C): def __init__(self): super().__init__() self.y = 1 d = D() print(d.y) class Bas...
foo = [25, 68, 'bar', 89.45, 789, 'spam', 0, 'last item'] print(foo[0], ' FIRST ITEM') print(foo[len(foo) - 1], ' LAST ITEM')
# Copyright 2017 Citrix Systems # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
""" Напишите программу, которая приветствует пользователя, выводя слово Hello, введенное имя и знаки препинания по образцу. Программа должна считывать в строковую переменную значение и писать соответствующее приветствие. Обратите внимание, что после запятой должен обязательно стоять пробел, а перед восклицательным знак...
""" get information of receptive field """ def get_receptive_field(neuron_index, layer_info, pad=(0, 0)): """ neuron_index: tuple of length 2 or int represented x axis and y layer_info: tuple of length 4 has information of receptive_field """ n, j, rf, start = layer_info if isinstance(neur...
"""This module regroups all exceptions tied to pyqtcli cli.""" class QresourceError(Exception): """Exception raised with problems concerning qresource node in qrc files.""" def __init__(self, arg): super(QresourceError, self).__init__() self.msg = arg def __str__(self): return sel...
valores = input().split() valores = list(map(int,valores)) h1, h2 = valores if(h1 == h2): print('O JOGO DUROU %d HORA(S)' %24) else: if(h2 < h1): print('O JOGO DUROU %d HORA(S)' %((24 - h1) + h2)) else: print('O JOGO DUROU %d HORA(S)' %(h2 - h1))
#1부터 100까지 3의 배수의 합계 # 클래스 선언부(객체지양 : 향후 코드 분석) #함수 선언부 # (전역)변수 선언부 (초기화) start,end,hap = [0] *3 #a,b=[],[] #메인 코드부 if __name__=='__main__' : for i in range(1,101) : if i % 3 ==0: hap += i else: pass # 같은 내용 # for i in range(1,101) : # if i % 3 !==0: ...
def WriteOBJ(filename, vertrices, vts, vns, facesV, facesVt, facesVn): f=file(filename,"w+") for vertex in vertrices: f.write("v ") for i in range(len(vertex)): f.write(str(vertex[i])) f.write(" ") f.write("\n") if len(vts) != 0: for vt in vts: ...
num1=10 num2=20 num3=30 num4=40 num5=50 num6=60 nihaoma=weijialan
#! Простые задачки. # 1. Даны два целых числа, отличных от нуля. Найдите их сумму, # произведение, разность, частное. def test_1(a, b): if str(a).isdigit() and str(b).isdigit(): return a + b, a * b, a - b, a / b return "Error" print(test_1(1, 4)) # 2. Поменяйте местами значения д...
""" EXERCÍCIO 056: Analisador Completo Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre: - A média de idade do grupo. - Qual é o nome do homem mais velho. - Quantas mulheres têm menos de 20 anos. """ continuar = True while continuar: pessoas = [] soma = 0 co...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __project__ = 'leetcode' __file__ = '__init__.py' __author__ = 'king' __time__ = '2020/2/22 20:37' _ooOoo_ o8888888o 88" . "88 (| -_- |) ...
while True: try: chars = input() # nums = int(chars) level0 = ['zero'] level1 = ['','one','two','three','four','five','six', 'seven',' eight','nine', 'ten'] level1_1= ['','eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixten', 'seventeen', 'eighteen', 'nineteen'] ...
'''Geração de HTML''' arquivo = open('ola.html','w',encoding='utf-8') arquivo.write('''<!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="utf-8"> <title>Titulo da pagina</title> </head> <body> Olá!!! </body> </html>''') arquivo.close()
items = [2, 25, 9] divisor = 12 for item in items: if item%divisor == 0: found = item break else: # nobreak items.append(divisor) found = divisor print("{items} contains {found} which is a multiple of {divisor}" .format(**locals()))
class Solution: def hIndex(self, citations): n = len(citations) at_least = [0] * (n + 2) for c in citations: at_least[min(c, n + 1)] += 1 for i in xrange(n, -1, -1): at_least[i] += at_least[i + 1] for i in xrange(n, -1, -1): if...
class ColumnRef: table = '' column = '' cascade_row = None def __init__(self, table, column, cascade_row=True): # cascade_row=True means that row in table should be removed # if value in column that owns reference is not found. # i.e, reference from stop_times.stop_id to stops....
""" Author: Cameron Tee A class keeping track of the game stats. Only one life in Flappy Bird. This class controls the game state (whether playing or not). """ class GameStats(): def __init__(self, settings): """ Initialise the gamestats object. """ self.settings = settings self.reset_stats(...
''' URL: https://leetcode.com/problems/move-zeroes/ Difficulty: Easy Title: Move Zeroes ''' ################### Code ################### class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ ...
numbers = [1,2,3,4,5,6,7,11] res = 0 for num in numbers: res = res + num print("with sum: ",sum(numbers)) print("without sum: ",res)
def remove_duplicates(S: str) -> str: r = S[0] for i in range(1, len(S)): if len(r) == 0: r += S[i] else: if r[-1] == S[i]: if len(r) == 1: r = '' else: r = r[:-1] else: r ...
f1, f2 = map(float, input().split()) flutuacao = 1.0 * (1.0 + f1/100) * (1 + f2/100) print("%.6f" % ((flutuacao - 1.0)*100))
class Primes: def __init__(self, first, last=None): self.curr = None if last is None: self.first = 2 self.last = first else: self.first = first self.last = last def __iter__(self): return self def __next__(self): if s...
# coding: iso-8859-1 -*- repete = 'sim' while repete == 'sim': frase = str(input('Digite uma frase para saber se é palindroma: ')).upper().strip() separa = frase.split() junto= ''.join(separa) reverso ='' for letra in range(len(junto)-1,-1,-1): reverso += junto[letra] if rever...
a, b = map(int, input().split()) while a != 0 and b != 0: if a > 0 and b > 0: print("primeiro") elif a < 0 < b: print("segundo") elif a < 0 and b < 0: print("terceiro") elif a > 0 > b: print("quarto") a, b = map(int, input().split())
# https://github.com/michal037 class Singleton: def __new__(cls, *_, **__): self = object.__new__(cls) cls.__new__ = lambda *a, **b: self return self def singleton(self): self.__class__.__new__ = lambda *c, **d: self ### EXAMPLE 1 ### EXAMPLE 1 ### EXAMPLE 1 ### EXAMPLE 1 ### EXAMPLE 1 ########## class My...
""" Write a function, connected_components_count, that takes in the adjacency list of an undirected graph. The function should return the number of connected components within the graph. depth first n = number of nodes e = number edges Time: O(e) Space: O(n) """ def count(graph): visited = set() count = 0 ...
class TriggerPool: def __init__(self): self.triggers = [] # Trigger list self.results = [] # Result list def add(self, trigger): """add one trigger to the pool""" self.triggers.append(trigger) def test(self, model, data): """test untested triggers""" ...
def climbStairs(n: int) -> int: stairs = [1, 1] for i in range(2, n + 1): stairs.append(stairs[-1] + stairs[-2]) return stairs[n]
text=input('Enter and check if your input is a palindrome or not: ') ltext=text.lower() rtext="".join((reversed(ltext))) if rtext==ltext: print('Your input is a palindrome.') else: print('Your input is not a palindrome.')
""" Running Successfully import unittest import math from PIL import Image from SyntheticDataset2.ImageCreator.specified_target_with_background import SpecifiedTargetWithBackground class SpecifiedTargetWithBackgroundTestCase(unittest.TestCase): def setUp(self): self.path_to_background = "tests/images/com...
def kmp(s): p = [-1] k = -1 for c in s: while k >= 0 and s[k] != c: k = p[k] k += 1 p.append(k) return p def period(s): k = len(s) - kmp(s)[-1] if len(s) % k == 0: return k return len(s) s = input() m = int(input()) p = period(s) print(m // p % (10**9 + 7))
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def split(self, head): slow = head fast = head slow_pre = head while fast and fast.next: slow_pre = slow ...
#!/usr/bin/python3 """ 插入排序 insert + sort """ def insert_sort(ds): for i in range(1, len(ds)): key = ds[i] j = i - 1 while j >= 0 and key < ds[j]: ds[j + 1] = ds[j] j -= 1 ds[j + 1] = key random_wait_sort = [12, 34, 32, 24, 28, 39, 5, 2...
""" File: circulararray.py Author: Brian Atwell Date: August 21, 2018 Descrioption: This a python implementation of a circular array using a list. This implementation could be used as a queue or an array. Copyright (c) 2018, Brian Atwell All rights reserved. Redistribution and use in source and binary forms, with or...
def solve(arr, duration): if len(arr) == 0: return 0 result = 0 start = arr[0] for i in range(1, len(arr)): if arr[i] - arr[i - 1] > duration: result += arr[i - 1] + duration - start start = arr[i] result += arr[-1] + duration - start return result A ...
class Solution: def setZeroes(self, matrix): rows, cols = set(), set() for i, r in enumerate(matrix): for j, c in enumerate(r): if c == 0: rows.add(i) cols.add(j) l = len(matrix[0]) for r in rows: matrix...
""" Base Controller for interacting with the Scene """ class BaseController: def __init__(self): super(BaseController, self).__init__() def start(self): raise NotImplementedError() def reset(self, scene_name=None): raise NotImplementedError() def step(self, acti...
#DESAFIO 13: REAJUSTE SALARIAL #Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. salário = float(input('Qual é o salário do funcionário? R$')) novo = salário + (salário * 15 / 100) print('Um funcionário que ganhava R${:.2f}, com 15% de aumento, passa a receber R${:.2...
counter = 0 b = 106700 c = 123700 step = 17 for target in range(b, c + step, step): flag = False d = 2 while d != target: e = target // d if e < d: break if target % d == 0: flag = True #print("d: {0:d} e: {1:d} b: {2:d}".format(d, e, target)) break ...
class Person: def __init__(self, name, age): self.name = name self.age = age def sayHello(self): print("Hello my name is {} and I am {} years old".format(self.name, self.age)) worker = Person("Alina", 21) print(worker.age) print(worker.name) worker.sayHello()
def partition(a,l,r): #assert: Previous proof but partitions between l and r # It considers the first element as a pivot and moves all smaller element to left of it and greater elements to right x=a[l] n=len(a) i=l j=r while(i<j): if a[i]>=x and a[j]<=x: a[i],a[j...
user_createaccount = []# Empty user_create account class User: def __init__(self,username,password,email): """ created insatances of the user class """ self.username = username self.email = email self.password = password User.user = {"username":self.usernam...
''' Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example: Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5 Runtime: 20 ms, faster...
# coding=utf-8 # See main file for licence # pylint: disable=W0401,W0403 # # by Mazoea s.r.o. # """ Tesseract constants. """ size_of_int32 = 4 NUM_CP_BUCKETS = 24 CLASSES_PER_CP = 32 NUM_BITS_PER_CLASS = 2 BITS_PER_WERD = (8 * size_of_int32) BITS_PER_CP_VECTOR = (CLASSES_PER_CP * NUM_BITS_PER_CLASS) WERDS_PER_CP...
# Copyright 2020 Rubrik, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distri...
def factorial(n): fact=1 for i in range(1,n+1): fact*=i print(fact) factorial(5)
print('''@#############################################################MMMMMMMMMMMMMMMMMMBBBBMMMMBB&AMBAHM###MMMMMMM# @hG&&AA&&A&G&&&&GG&AA&&&&&AAAAAA&&&G&&&GGhh&AAAG93XX39h93X225iiiS5SSSSSSSiSiSSisssssiisssi:.;s;iXX25Sii25SSA @hAAHAAHAHAAAAAAAAAAAAAAAAAAAAAAAHHHAAAG&&3Ssi5G&GG&&GG9333X2552222222255525rrSSS55SSSiSS5X;:...
class InvalidTraceHeader(Exception): """Thrown if a bad trace header was passed in.""" class InvalidMessageID(Exception): """Thrown if a bad message id was passed in."""
# SETTINGS FILE # TOKEN - discord app token # BOT PREFIX - no explanation needed (uhh I think) # API_AUTH - hypixel api auth # DB_CLIENT - your DB URI # DB_NAME - no explanation needed # APPLICATION_ID - discord app id TOKEN='' BOT_PREFIX='$' API_AUTH='' DB_CLIENT = '' DB_NAME = '' APPLICATION_ID=''
# -*- coding: utf-8 -*- class Symbol(object): def __init__(self, symbol): self.number = int(symbol['number']) self.numberEx = int(symbol['numberEx']) self.name = symbol['name'] self.var = symbol['var'] def __str__(self): return '\t\t\t\tNumber: {0} \n\t\t\t\tNu...
def mutate(soup): paragraphs = get_max_paragraph_set(soup) headline = soup.find('h1') html = str(headline) + '\n' for paragraph in paragraphs: html += str(paragraph) + '\n' return html def get_max_paragraph_set(soup): paragraph_map = build_paragraph_map(soup) key = get_max_key(paragraph_map) if key is None:...
a = 3 while a >= 3: print("CSK Wins") break user_input = input('Enter City') while user_input == 'Chennai': print('Chennai pasanga da') break user_in = input('Enter Country') while type(user_in) == str: if user_in == 'India': print('India is the best') break else: pri...
letters = 'aeiou' txt = input("Podaj tekst: ") txt = txt.casefold() count = {}.fromkeys(letters,0) for ch in txt: if ch in count: count[ch] +=1 print(count)
""" Theory > Instance vs Class > Attributes, methods, inheritance, polymorphism """ class Scout(): pass ratarca = Scout()
#!/usr/bin/python3 class Line: def __init__(self, x1, y1, x2, y2): self.x1 = int(x1) self.y1 = int(y1) self.x2 = int(x2) self.y2 = int(y2) self.rangex = abs(self.x2 - self.x1) self.rangey = abs(self.y2 - self.y1) def print(self): print(str(self.x1) + "," ...
# -*- coding: utf-8 -*- """ @time: 2020/3/19 10:31 上午 @desc: """ class SQLFormatError(Exception): pass class ParameterError(Exception): pass class ConnectError(Exception): pass class ExecuteError(Exception): pass
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: # handle exceptions if head==None or head.next==None: re...
# -*- coding: utf-8 -*- # Author: Daniel Yang <daniel.yj.yang@gmail.com> # # License: BSD 3 clause def demo(): # reference: https://scikit-learn.org/stable/modules/classes.html#module-sklearn.cluster # https://scikit-learn.org/stable/modules/clustering.html pass
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to demonstrate how to create lists # Lists can be created with data (each value is a list element) boysNames = ['John', 'Jim', 'Alex', 'Fred'] girlsNames = ['Sarah...
NL = b'\n' DATA_SIZE = 4 FRAME_SIZE = 4 HEADER_SIZE = DATA_SIZE + FRAME_SIZE TIMESTAMP_SIZE = 8 ATTEMPTS_SIZE = 2 MSG_ID_SIZE = 16 MSG_HEADER = TIMESTAMP_SIZE + ATTEMPTS_SIZE + MSG_ID_SIZE
# Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher # qual será a base de conversão: """ > 1 para binário > 2 para octal > 3 para hexadecimal """ num = int(input('Escolha um número para ser convertido: ')) print('[ 1 ] Converter para BINÁRIO') print('[ 2 ] Converter para OCTAL') p...
def run(df, docs): for doc in docs: doc.start("t11 - Transform Unique Id", df) # Creates a unique id df['nProcesso_agrupamento'] = str(df['nProcesso']) + '_' + str(df['agrupamento']) for doc in docs: doc.end(df) return df
numbers = [9, 8, 72, 22, 21, 81, 2, 1, 11, 76, 32, 54] def highest_num(numbers_in): highest = numbers_in[0] for count in range(len(numbers_in)): if highest < numbers_in[count]: highest = numbers_in[count] return highest highest_out = highest_num(numbers) print("The highest number...
with (a, c,): pass with (a as b, c): pass async with (a, c,): pass async with (a as b, c): pass
class FilasColumnas: def __init__(self, nombre, filas, columnas): self.nombre = nombre self.filas = filas self.columnas = columnas def getNombre(self): return self.nombre def getFilas(self): return self.filas def getColumnas(self): return s...
#!/usr/bin/env python # coding: utf-8 # Write a function to which would return the greatest common of factor. # # <b> Input : 18, 27</b> # # <b> return: 9 </b> # # # In[1]: # Get the smallest of the both inputs # Loop through the find the GCD# def gcd(x,y): small=min(x,y) for i in range(1,small+1): ...
''' 现在的调查问卷越来越多了,所以出现了很多人恶意刷问卷的情况,已知某问卷需要填写名字, 如果名字仅由大小写英文字母组成且长度不超过10,则我们认为这个名字是真实有效的,否则就判定为恶意填写问卷。 请你判断出由多少有效问卷(只要名字是真实有效的,就认为问卷有效)。 ''' def wenjian(lis): res = 0 for each in lis: l = len(each) if l > 10: continue if each.isalpha(): res += 1 print(res) ...
peple = ["gilbert", "david", "richard"] print("welcome to my parlor, " + peple[0]) print("welcome to my parlor, " + peple[1]) print("welcome to my parlor, " + peple[2]) print("richard is too stupid to come, so his not comming.") peple = ["gilbert", "david"] print("welcome to my parlor, " + peple[0]) print("wel...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyNvidiaMlPy(PythonPackage): """Python Bindings for the NVIDIA Management Library.""" homepage = "http://w...
# -*- coding: utf-8 -*- """052 - Progressão Aritmética Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1XxsY2LOjklht2ABKc1B0VXPOppV9E7Dh """ num = int(input('\nDigite o Primeiro número da PA: ')) razão = int(input('Digite a Razão da PA: ')) for c in ra...
#for c in range (1, 10): #print(c)''' #c = 1 #while c < 11: #print(c) #c += 1 n = 1 par = 0 impar = 0 while n != 0: n = int(input('digite um valor: ')) if n != 0: if n % 2 == 0: par += 1 else: impar += 1 print(f'Ímpar {impar}') print(f'Par {par}') pr...
BINDING_ADDRESS = ':1080' # <ADDRESS>:<PORT> BINDING_PORT = 1080 LOCAL_CERT_FILE = './local.pem' REMOTE_CERT_FILE = './remote.pem' BACKLOG = 128 LOG_LEVEL = 'info' BLOCK_SIZE = 2048 # in bytes STAFF_BINDING_ADDRESS = '127.0.0.1' STAFF_TCP_PORT = 32000 STAFF_UDP_PORT = 32000 STAFF_PROXY = '127.0.0.1:1080' ...
def return_after_n_recursion_one(n): return_after_n_recursion_one(n-1) def return_after_n_recursion_two(n): if n < 3: # Base return: identify a condition after which you will start returning return 'Cap' return_after_n_recursion_two(n-1) def return_after_n_recursion(n): if n < 3: # Base retu...
def KadaneAlgo(alist, start, end): #Returns (l, r, m) such that alist[l:r] is the maximum subarray in #A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x < #end. max_ending_at_i = max_seen_so_far = alist[start] max_left_at_i = max_left_so_far = start # max_right_at_i is alw...
# to allow api client save environment state to database. SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' # we use cached_db backend for longlive and fast sessions. SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' SESSION_COOKIE_NAME = 'sid' SESSION_COOKIE_AGE = 86400 * 60 # 2...
class GraphNode(object): def __init__(self, val): self.value = val self.children = [] def add_child(self, new_node): self.children.append(new_node) def remove_child(self, del_node): if del_node in self.children: self.children.remove(del_node) class...
"169.Majority Element" """Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2...
x = 'Hello "Prayuth"' # Single-Quote y = "Good Bye! 'Prayuth'" # Double-Quote z = x + y print(x) print(y) print(z)
# built in def hammingWeight(self, n): """ :type n: int :rtype: int """ return bin(n).count('1') # Using bit operation to cancel a 1 in each round # Think of a number in binary n = XXXXXX1000, n - 1 is XXXXXX0111. n & (n - 1) will be XXXXXX0000 # which is just remove the last significant 1 def h...
class Solution: def findMedianSortedArrays(self, nums1, nums2) -> float: x = len(nums1) y = len(nums2) if y < x: # Making sure nums1 is the smaller length array return self.findMedianSortedArrays(nums2, nums1) maxV = float('inf') minV = float('-inf') ...
# -*- coding: utf-8 -*- """生成改名文件""" def change_name_windows(name_dict, loc): with open(loc + '\\change_name.cmd', 'w') as f: loc = loc.replace('\\', r'\\') + r'\\' i = 0 for key in name_dict: i = i+1 old_name = str(key).split(r'/')[-1] tailor = old_name...
def substring_match(T, S): """ Simple substring matching. O(|S| * |T - S|) Time O(1) Space """ return any([T[idx:idx+len(S)] == S for idx in range(len(T) - len(S) + 1)]) """ for idx in range(len(T) - len(S) + 1): print(T[idx:idx + len(S)], S) if T[idx:idx + len(S)] == S: return True retur...
class BankAccount: def __init__(self, name, number, money): self.accountname = str(name) self.accountnumber = int(number) self.money = float(money) def show(self): msg = "Dear " + self.accountname + ", your account " + str(self.accountnumber) + " has " + str(self.money) + " remai...
def user_has_reporting_location(user): sql_location = user.sql_location if not sql_location: return False return not sql_location.location_type.administrative