content
stringlengths
7
1.05M
# Copyright (c) 2022 Jakub Vesely # This software is published under MIT license. Full text of the license is available at https://opensource.org/licenses/MIT class RemoteKeyboardBase: """ this class is a base class for remote keyboards/controls (IR or the BLE one) example of usage can be found in examples/___...
maze = ' ******* * **** * **** * *** *# *** *** *** *********' g = '' s = '' for i in range(0, len(maze)): g += maze[i] if (i+1)%8==0: g += s + '\n' s = '' print(g)
class Error(Exception): pass class FieldLookupError(Error): pass class BadValueError(Error): pass class DocumentClassRequiredError(Error): pass class FieldError(Error): pass
# pylint: disable=missing-docstring,too-few-public-methods class AbstractFoo: def kwonly_1(self, first, *, second, third): "Normal positional with two positional only params." def kwonly_2(self, *, first, second): "Two positional only parameter." def kwonly_3(self, *, first, second): ...
#paste your api_hash and api_id from my.telegram.org api_hash = "exxxxxxxxxx" api_id = xxxx entity = "tgcloud"
# Server Specific Configurations server = { 'port': '8558', 'host': '0.0.0.0' } # Pecan Application Configurations app = { 'root': 'vouch.controllers.root.RootController', 'modules': ['vouch'], 'debug': False, # this 'guess' also strips off the extension from the resource path. 'guess_cont...
def shakehand(): rest() i01.startedGesture() ##move arm and hand i01.setHandSpeed("left", 0.65, 0.65, 0.65, 0.65, 0.65, 1.0) i01.setHandSpeed("right", 0.65, 0.65, 0.65, 0.65, 0.65, 1.0) i01.setArmSpeed("right", 0.75, 0.85, 0.95, 0.85) i01.setArmSpeed("left", 0.75, 0.85, 0.95, 0.85) i01.setHeadSpeed(1.0,...
# Copyright (c) 2013 Huan Do, http://huan.do class FrameContextManager(object): def __init__(self, frame, visitor): self.frame = frame self.visitor = visitor def __enter__(self): self.visitor.current_frame = self.frame return self.frame def __exit__(self, *_): sel...
# wczytanie napisow with open('../dane/NAPIS.TXT') as f: data = [] for word in f.readlines(): data.append(word[:-1]) # zbior slow rosnacych growing = [] # przejscie po slowach for word in data: # przejscie po literach i sprawdzenie czy aktualna wartosc ASCII litery jest wieksza niz poprzednej ...
sum = lambda a, b : a + b print(sum(3,4)) def sum1(a, b): return a + b print(sum1(4, 5)) myList = [lambda a, b : a + b, lambda a, b : a * b] print(myList) print(myList[0]) print(myList[0](3, 4)) print(myList[1](3, 4))
# pylint: disable=missing-docstring def baz(): # [disallowed-name] pass
# c:\Users\i341972\Desktop\git_repos\enaml\enaml\core\parse_tab\parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\x7f\xdd\xc1Pb\x9c\xa9\xeb\xac\xc9\xad\xb5=\x06\x80j' _lr_action_items = {'LPAR':([0,1,6,7,9,13,14,16,18,24,28,29,30,31,33,35,...
repeat = int(input()) for x in range(repeat): div1, div2, uplim = map(int, input().split()) divisor = div1 * div2 for i in range(divisor, uplim + 1, divisor): print(i) if x != repeat - 1: print()
""" 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 1: Input: list = null, x = 0 Output: null Explanation: The empty list Satisfy the cond...
DFLT_TOURN_PART_NAME = 'Unknown' GANG_LEADER = 'Gang Leader' GROUP_NAMES = {'Thug 1': 'Thugs', 'Robber 1': 'Robbers'} SURNAME_PARTS = [ 'bai', 'cai', 'cao', 'chang', 'chen', 'cheng', 'cui', 'dai', 'deng', 'ding', 'dong', 'du', 'duan', 'fan', 'fang', 'fen...
class NegativeInteger(Exception): pass def pascalTriangle(n,r): a=[[1],[1,1]] for i in range(2,n+1): for j in range(r+1): if j<=i: if j==0: a.append([1]) elif i==j: a[i].append(1) else: ...
lista = [2, 5, 9, 4] lista[2] = 3 lista.append(7) lista.sort() print(lista) lista.sort(reverse=True) print(lista) print(f'Essa lista tem {len(lista)} elementos') lista.insert(2, 0) print(lista) lista.pop(1) print(lista) lista.insert(2, 2) print(lista) lista.remove(2) #remove a primeira ocorrência print(lista)
###################### #### Midterm-1 ####### ###################### def midterm1(): print("Midtem 1: ") weight1 = int(input("Weight (0-100)? ")) score1 = int(input("Score earned? ")) is_score_shifted1= int(input("Were scores shifted (1=yes, 2=no) ? ")) if is_score_shifted1 == 1: sh...
''' Created on 07.11.2019 @author: JM ''' class TMC4361_register_variant: " ===== TMC4361 register variants ===== " "..."
load( "//:repositories.bzl", "com_github_scalapb_scalapb", "io_bazel_rules_scala", "io_grpc_grpc_java", "scalapb_runtime", "scalapb_runtime_grpc", "scalapb_lenses", "rules_proto_grpc_repos", ) def scala_repos(**kwargs): rules_proto_grpc_repos(**kwargs) io_grpc_grpc_java(**kwargs...
def scope_demo(): # definition of variable is local to do_local(), and so doesn't survive # when method goes out of scope. (This draws a weak warning that the local # variable is not used.) def do_local(): spam = "local spam" # definition of variable is specifically not local to do_nonlo...
# WAP to demonstrate simple exception handling in Python def ExceptionHandling(): try: a += 10 except NameError as e: print(e) def main(): ExceptionHandling() if __name__ == "__main__": main()
SECRET_KEY = 'gk2ptgp9mB' SALT = 'SALT' PERM_FILE = 'perms.json' UPLOAD_FOLDER = 'uploads' DB_FILE = 'db.db'
# variavel soma = 0 lista = [] # entrada number1 = int(input()) number2 = int(input()) # adicionando em uma lista para ordenar lista.append(number1) lista.append(number2) lista = sorted(lista) # percorre intervalo de numeros e soma os numeros que não são divisiveis por 13 for i in range(lista[0], lista...
TURTLEBOT_RADIUS = 0.176 # loaded config default_config = { 'PLANE_URDF': ".\\data\\py_data\\plane.urdf", 'BLOCK_URDF': ".\\data\\py_data\\boston_box.urdf", 'BLOCK_DYN_URDF': ".\\data\\py_data\\boston_box_fl.urdf", 'TURTLEBOT_URDF': ".\\data\\py_data\\turtlebot.urdf", ...
"""Parsing Destinations from phone numbers. Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same d...
# Uses python3 def get_fibonacci_last_digit_naive(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % 10 def get_digit_fast(n): if n <= 1: return n prev, curr = 0, 1 for _ i...
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"] first = suitcase[0:2] # The first and second items (index zero and one) print(first) middle = suitcase[2:4] # Third and fourth items (index two and three) print(middle) last = suitcase[4:6] # The last two items (index four and five)
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """ Migrations Utility Module. Place here your migration helpers that is shared among number of migrations. """
def extrair_linha(nome_do_arquivo): with open(nome_do_arquivo) as arquivo: #print(arquivo.readlines()) return arquivo.readlines()[0] #READLINES LÊ O ARQUIVO INTEIRO E NESTE CASO RETORNA APENAS O PRIMEIRO TERMO DO ARRAY GERADO ; coloque o return comentado e acine o print para ver primeira_linha = e...
# https://leetcode.com/problems/decode-ways/submissions/ # https://leetcode.com/problems/decode-ways/discuss/253018/Python%3A-Easy-to-understand-explanation-bottom-up-dynamic-programming class Solution_recursion_memo: def numDecodings(self, s): L = len(s) def helper(idx, memo): ...
# Implement the function interval_intersection below. # You can define other functions if it helps you decompose and solve # the problem. # Do not import any module that you do not use! # Remember that if this were an exam problem, in order to be marked # this file must meet certain requirements: # - it must contain ...
# Copyright 2019 Google Inc. All Rights Reserved. # # 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 ...
# negative elements [-1,0,1] -> [0,1,1] # same elements [-2,-2,0,2] -> [0,2,2,2] """ 977. 有序数组的平方 给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。 示例 1: 输入:nums = [-4,-1,0,3,10] 输出:[0,1,9,16,100] 解释:平方后,数组变为 [16,1,0,9,100] 排序后,数组变为 [0,1,9,16,100] 示例 2: 输入:nums = [-7,-3,2,3,11] 输出:[4,9,9,49,121] 提示: 1 <= num...
def distance(str1: str, str2: str) -> float: """ The Levenshtein distance is a string metric for measuring the difference between two sequences. It is calculated as the minimum number of single-character edits necessary to transform one string into another """ n, m = len(str1), len(str2...
num = int(input('Digite um número: ')) cont = 0 for c in range(1,num+1): if num % c == 0: print('\033[34m{}\33[m'.format(c),end=' ') cont += 1 else: print('\033[35m{}\033[m'.format(c),end=' ') if cont == 2: print('\nO número {} é primo!'.format(num)) else: print('\nO número {} NÃ...
#!/usr/bin/env python3 all_cases = [[[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], ...
def CountWithPseudocounts(Motifs): t = len(Motifs) k = len(Motifs[0]) count = {} # insert your code here for symbol in "ACGT": count[symbol] = [] for j in range(k): count[symbol].append(1) for i in range(t): for j in range(k): symbol = Motifs[i][j...
DEBUG = True SECRET_KEY = 'trinity kevin place' SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/angular_flask.db'
def cb(result): print('Service has been created') heartbeatTimeout = 15 payload = {'tags': ['tag1', 'tag2', 'tag3']} d = client.services.register('serviceId', heartbeatTimeout, payload) d.addCallback(cb) reactor.run()
# Code generated by font-to-py.py. # Font: DejaVuSans.ttf version = '0.26' def height(): return 20 def max_width(): return 20 def hmap(): return False def reverse(): return False def monospaced(): return False def min_ch(): return 32 def max_ch(): return 126 _font =\ b'\x0a\x00\x0c\x...
DEFAULT_MAPPING = { "login": "login", "password": "password", "account": "account", } MODULE_KEY = "click_creds.classes.ClickCreds"
def filter_comments(source): buffer = [] comment_depth = 0 for ch in source: if ch == "[": comment_depth += 1 elif ch == "]": assert comment_depth > 0 comment_depth -= 1 else: if comment_depth == 0: buffer.append(ch) ...
if __name__ == "__main__": im = 256 ih = 256 print("P3\n",im," ",ih,"\n255\n") for j in range(ih, 0, -1): for i in range(im): r = i / (im-1) g = j / (ih -1) b = 0.25 ir = int(255.999 * r) ig = int(255.999 * g) ib = int(255....
def maxRepeating(str): l = len(str) count = 0 res = str[0] for i in range(l): cur_count = 1 for j in range(i + 1, l): if (str[i] != str[j]): break cur_count += 1 # Update result if required if cur_count > ...
dot3StatsTable = u'.1.3.6.1.2.1.10.7.2.1' dot3StatsAlignmentErrors = dot3StatsTable + u'.2' dot3StatsFCSErrors = dot3StatsTable + u'.3' dot3StatsFrameTooLongs = dot3StatsTable + u'.13' dots3stats_table_oids = [dot3StatsFCSErrors, dot3StatsAlignmentErrors, dot3StatsFrameTooLongs]
x1 = 1 y1 = 0 x2 = 0 y2 = -2 m1 = (y2 / x1) print(f'X-intercept = {x1, x2} and Y-intercept = {y1, y2}\nSlope = {m1}') # 8
""" 题目:输入一棵二叉树的根节点 判断该树是不是平衡二叉树 如果某二叉树中任一节点的左右子树的深度相差不超过1 则它就是一棵平衡二叉树 思路:基于coding_interview_55.py脚本内函数 遍历节点 求出任意节点的左右子树的深度 判断其深度之差不超过1 这样算法复杂度为O(n^2) 存在重复遍历 """ class Solution(object): def IsBalancedBinaryTree(self, root): if root is None: return True leftDepth = self.TreeDepth(root.left...
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # 20 вариант # Дано предложение. Определить, сколько в нем одинаковых соседних букв. if __name__ == '__main__': a = input("Введите предложение: ") b = '' count = 1 for i in range(len(a)): if a[i] == b: count += 1 else: ...
# ~/dev/py/fieldz/littleBigTest.py """ This has been hacked down from bigTest.py by eliminating field types that we can't handle yet. """ LITTLE_BIG_PROTO_SPEC = """ protocol org.xlattice.fieldz.test.littleBigProto message bigTestMsg: # required fields, unnumbered vBoolReqField vbool vEnumReqField ven...
"""p2 server constants""" # Matches full Request Path, starting with leading slash TAG_SERVE_MATCH_PATH = 'serve.p2.io/match/path' # Matches relative Request Path, without leading slash TAG_SERVE_MATCH_PATH_RELATIVE = 'serve.p2.io/match/path/relative' # Matches request Hostname TAG_SERVE_MATCH_HOST = 'serve.p2.io/matc...
# سم الله الرحمن الرحيم def add_numbers(a, b): return a + b print(add_numbers(1,2)) print(add_numbers(3,4)) print(add_numbers(6,7))
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on: 2021/07/10 12:48 @Author: Merc2 '''
# -*- coding: utf-8 -*- """Classes for AWS accounts.""" # import boto3 # from botocore.exceptions import ClientError class OrgAccount: """Manage AWS Accounts from AWS Organizations.""" def __init__(self, SESSION): """Create an OrgAccount object.""" self.session = SESSION self.org = ...
class Xbpm(Device): x = Cpt(EpicsSignalRO, 'Pos:X-I') y = Cpt(EpicsSignalRO, 'Pos:Y-I') a = Cpt(EpicsSignalRO, 'Ampl:ACurrAvg-I') b = Cpt(EpicsSignalRO, 'Ampl:BCurrAvg-I') c = Cpt(EpicsSignalRO, 'Ampl:CCurrAvg-I') d = Cpt(EpicsSignalRO, 'Ampl:DCurrAvg-I') total = Cpt(EpicsSignalRO, 'Ampl:Cur...
# # PySNMP MIB module V2H124-24-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/V2H124-24-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:33:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
def func(): a = (input("enter a letter : ")) if a.isalpha(): print("alphabet") else: print("NO") func()
class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int """ bitmap = [0] * len(words) mask = 0x01 ans = 0 for i in xrange(0, len(words)): word = words[i] for c in word: ...
class Solution: def getWinner(self, arr: List[int], k: int) -> int: nums = deque(arr) win_count = 0 winner = nums[0] while True: a = nums.popleft() b = nums.popleft() if a > b: if winner == a: win_count ...
class Solution: def fb(self, A): d3 = A % 3 == 0 d5 = A % 5 == 0 if d3 and d5: return "FizzBuzz" elif d3: return "Fizz" elif d5: return "Buzz" else: return str(A) # @param A : integer #...
l=[0]*10 for i in range(len(l)): l[i]=i*2 print(0 in l) print(1 in l) print(2 in l) print(3 in l) print(4 in l)
#import os #import glob #modules = glob.glob(os.path.dirname(__file__)+"/*.py") #__all__ = [ os.path.basename(f)[:-3] for f in modules] __user_users_tablename__ = 'users' __user_users_head__ = 'admin' __user_online_tablename__ = 'online' __user_online_head__ = 'online' __user_admingroup_tablename__ = 'admingroup' __use...
# https://adventofcode.com/2020/day/13 infile = open('input.txt', 'r') earliest_time_to_depart = int(infile.readline()) buses = [] for bus in infile.readline().rstrip().split(','): if bus != 'x': buses.append(int(bus)) buses.sort() infile.close() earliest_bus = -1 minimum_wait_time = max(buses) for bus in...
class Caja: def __init__(self, base, altura, profundidad): self.base = base self.altura = altura self.profundidad = profundidad def calcularVolumen(self): """Se realiza el cálculo del Volumen""" return self.base * self.altura * self.profundidad base = 5 altura = 3 ...
# pcinput # input functions that check for type # Pieter Spronck # These functions are rather ugly as they print error messages if something is wrong. # However, they are meant for a course, which means they are used by students who # are unaware (until the end of the course) of exceptions and things like that. # Thi...
class Chord(object): def __init__(self): self.tones = [] def add_tone(self, tone): self.tones.append(tone)
n = int(input()) print('+', end='') for i in range(n-2): print(' -', end='') print(' +') for k in range(n-2): print('|', end='') for row in range(n-2): print(' -', end='') print(' |') print('+', end='') for j in range(n-2): print(' -', end='') print(' +')
#堆排序 """ 二叉堆的定义,堆顶元素即二叉堆的根节点一定是最大或最小元值, 输出堆顶元素后,再将剩余元素调整为二叉堆,继而再次输出堆顶元素 """ def HeapAdjustDown(lst,start,end): #temp保存当前节点 temp = lst[start] #2*start+1是序号为start的节点左子节点的编号 child = 2*start + 1 while child <= end: #找到堆中的叶子节点左右节点中最大的那个 if child+1 <= end and lst[child+1] > lst[child]: ...
d = int(input("Enter the decimal number:")) m = d r,t = 0,[] while(d>0): r = d % 8 t.append(chr(r+48)) d = d//8 t = t[::-1] print("The octal of the decimal number",m,"is",end = " ") for i in range(0,len(t)): print(t[i],end='')
# Authors: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # # License: BSD (3-clause) class Bunch(dict): """ Container object for datasets: dictionnary-like object that exposes its keys as attributes. """ def __init__(self, **kwargs): ...
class Ship(): def __init__(self, name, ship_head, ship_size): self.ship_head = ship_head self.name = name self.size = ship_size self.generate_position() #pensar numa nova nomenclatura def generate_position(self): self.position = [] ship_column = self.ship...
def lambda_handler(event, context): message = 'Hello {} {}! Keep being awesome!'.format(event['first_name'], event['last_name']) #print to CloudWatch logs print(message) return { 'message' : message }
# Copyright 2019 The Bazel Authors. All rights reserved. # # 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 la...
"""Example of creating new training data from a larger data set""" # Data (Daily stock prices in $) price = [[9.9, 9.8, 9.8, 9.4, 9.5, 9.7], [9.5, 9.4, 9.4, 9.3, 9.2, 9.1], [8.4, 7.9, 7.9, 8.1, 8.0, 8.0], [7.1, 5.9, 4.8, 4.8, 4.7, 3.9]] # One-liner sample = [line[::2] for line in price] ...
# python 3.7.4 """ I used an iterative approach. List comprehension would create a very long lists. This approach tend to have less iteration when you hit a prime factor because the initial number will be divided at every hit. In the worst case we have n iteration in prime_factors function because we have inserted a pr...
''' Questão 2: Faça um programa que contenha uma tupla com 20 valores, e retorne no console: quantos e quais desses valores são strings, quantos e quais desses valores são inteiros, quantos e quais desses valores são reais, e por final todos que não se encaixaram nos parâmetros anteriores, todos com suas respectivas ...
#imported from https://bitbucket.org/pypy/benchmarks/src/846fa56a282b0e8716309f891553e0af542d8800/own/fannkuch.py?at=default # the export line is in fannkuch.pythran #runas fannkuch(9);fannkuch2(9) #bench fannkuch(9) def fannkuch(n): count = range(1, n+1) max_flips = 0 m = n-1 r = n check = 0 p...
# -*- coding: utf-8 -*- """ lantz.errors ~~~~~~~~~~~~ Implements base classes for instrumentation related exceptions. They are useful to mix with specific exceptions from libraries or modules and therefore allowing code to catch them via lantz excepts without breaking specific ones. :copyr...
# Copyright 2020-2021 The MathWorks, Inc. # Configure MATLAB_DESKTOP_PROXY to extend for Jupyter config = { # Link the documentation url here. This will show up on the website UI # where users can create issue's or make enhancement requests "doc_url": "https://github.com/mathworks/jupyter-matlab-proxy", ...
# Ex1 def naturalSum(min, max): __min = min __max = max __value = 0 for x in range(__min, __max + 1): if x%7 == 0 or x%9 == 0: __value += x return __value print("natural sum to 20: " + str(naturalSum(0,20))) print("natural sum to 10000: " + str(naturalSum(0,10000)))
print(2) for i in range(3, 101): found = False for j in range(2, i // 2 + 1): if i % j == 0: found = True break if not found: print(i)
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ #end_pymotw_header print('Importing example package')
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 def transform(logdata): if 'errorCode' in logdata or 'errorMessage' in logdata: logdata['event']['outcome'] = 'failure' else: logdata['event']['outcome'] = 'success' try: name = lo...
"""This file defines the unified tensor framework interface required by DGL. The principles of this interface: * There should be as few interfaces as possible. * The interface is used by DGL system so it is more important to have clean definition rather than convenient usage. * Default arguments should be avoided. *...
class CustomBaseException(Exception): errcode = 1000 errmsg = 'Server Unkown Error.' def __init__(self, errmsg=None, errcode=None, **kw): if errmsg: self.errmsg = errmsg if errcode is not None: self.errcode = errcode self.kw = kw def __str__(self): ...
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class BotWrapper: def __init__(self): self.bot = None def se...
""" Color Definitions ===== Copyright (c) 2015 Andrés Rodríguez and KivyMD contributors - KivyMD library up to version 0.1.2 Copyright (c) 2019 Ivanov Yuri and KivyMD contributors - KivyMD library version 0.1.3 and higher For suggestions and questions: <kivydevelopment@gmail.com> This file is distributed und...
#! /usr/bin/python # -*- coding: iso-8859-15 -*- for n in (1, 6): c = n ** 2 print(n,c)
class RandomMock: """Callable object returning given sequence of "random" numbers. Can be substituted instead of random.random() function to test the behavior of algorithm in case random generator returns some specific sequence of values. I.e. to make these tests deterministic. See randfunc= paramet...
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The head of linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """ ...
# dp class Solution: def numSquares(self, n: int) -> int: dp = [float("inf")] * (n + 1) dp[0] = 0 for i in range(1, n + 1): j = 1 while j * j <= i: dp[i] = min(dp[i], dp[i - j * j] + 1) j += 1 return dp[n]
# --- # jupyter: # jupytext: # cell_markers: region,endregion # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- 1+2+3 # region active="" # This is a raw cell # endregion # This is a markdown cell
""" :Author(s) Ryan Forster: This file contains constants from Tables 2 and 4 from "Understanding M-values" By Erik C. Baker, P.E. Used for the calculation of gradient factors """ # m naught values for haldane are all 2.0 HALDANE_M_NAUGHT = 2.0 ''' Haldane M value constant ''' ZHL16A_N_DELTA = [1.9082, 1.7928, ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def tree2str(self, t: TreeNode) -> str: if not t: return '' left = '({})'.format(self.t...
_constant_id = 0 def _create_constant_id(): global _constant_id _constant_id += 1 return f'<Game Constant (id={_constant_id})' text_relative_margin_size = _create_constant_id() margin_relative_text_spawn = _create_constant_id() mutable_text_size = _create_constant_id() default_font_path = 'nsr.ttf'
#!/usr/bin/env python # coding: utf-8 # In[1]: def contnum(n): # initializing starting number num = 1 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1):...
numero = int(input('Digite um nimero:')) tb1 = numero*1 tb2 = numero*2 tb3 = numero*3 tb4 = numero*4 tb5 = numero*5 tb6 = numero*6 tb7 = numero*7 tb8 = numero*8 tb9 = numero*9 tb10 = numero*10 print('-'*12) print('a taboada de {} é, \n {} \n {} \n {} \n {} \n {}'.format(numero, tb1, tb2, tb3, tb4, tb5)) pr...
class PlayerInfo: def __init__(self, manager): self.window = manager.window self.game = manager.game self.manager = manager self._bottom_index = 0 self._top_index = 0 self.bottom_num_pages = 3 self.top_num_pages = 2 def __call__(self): self.setup_...
""" .. module:: tr064.version :synopsis: tr-064 version .. moduleauthor:: Benjamin Füldner <benjamin@fueldner.net> """ __version__ = '0.1.1'
""" Doc string """ def asdf(): pass