content
stringlengths
7
1.05M
class Node(object): def __init__(self, data, prev, next): self.data = data self.prev = prev self.next = next class ListOne(object): head = None tail = None size = 0 def display(self): current_node = self.head while current_node is not None: pri...
""" /* A crew of N players played a game for one time, and got some scores. They have to stand in the same positions after they played the game. There is a constraint that, the player-K score, should not be greater or smaller than both of his neighbors. To achieve this constraint, there are few steps to be followed a...
class UserPlofile: dir_path = 'user_plofile' class ColabPath: train = 'https://colab.research.google.com/drive/1padoMj3dW0lr9nkko2384XXXD37dVhDE' evacuate = 'https://colab.research.google.com/drive/1idRwx4c_5PcxpLmj0ZIyIG9BaLXnQAS8'
def func(arg, **kwargs): """main docstring. (only document this description!)""" return 1 class A: def foo(self, s): return
class Actor: def __init__(self, actor_full_name: str): if actor_full_name == "" or type(actor_full_name) is not str: self.full_name = None else: self.full_name = actor_full_name.strip() self.colleagues = [] def __repr__(self): return f"<Actor {self.full_...
""" 1273. Delete Tree Nodes Medium A tree rooted at node 0 is given as follows: The number of nodes is nodes; The value of the i-th node is value[i]; The parent of the i-th node is parent[i]. Remove every subtree whose sum of values of nodes is zero. After doing so, return the number of nodes remaining in the tree. ...
''' Python program to calculate body mass index ''' height = float(input("Input your height in Feet: ")) weight = float(input("Input your weight in Kilogram: ")) print("Your body mass index is: ", round(weight / (height ** 2), 2))
def superCalc(n1, n2): print(n1 + n2) print(n1 - n2) print(n1 * n2) print(n1 / n2) n1 = int(input("enter n1: ")) n2 = int(input("enter n2: ")) superCalc(n1, n2)
i = 2 a, b = 1, 1 while True: c = a + b a = b b = c i = i + 1 if len(str(c)) == 1000: print(c) break print(i)
def twoStacks(x, a, b): score = 0 total = 0 while total < x: if a != [] and b != []: if a[0] < b[0]: if total+a[0] < x: total += a.pop(0) score += 1 else: break else: i...
""" 1,2,9 9,2,1 1,3,8 8,3,1 1,4,7 7,4,1 1,5,6 6,5,1 2,8,2 2,3,7 7,3,2 2,4,6 6,4,2 5,2,5 3,6,3 3,4,5 ...
class Parser(object): """ The base class for all parsers. """ def __init__(self, token_list): self.token_list = token_list self._reset() def _reset(self): self.offset = 0 self.line = 0 self.error = '' def _get_next_token(self): if len(self.input...
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. INCLUDES = """ #include <openssl/ecdsa.h> """ TYPES = """ """ FUNCTIONS = """ int ECDSA_sign(int, const unsigned char *, int, unsigned c...
def getCensusPoints(sf, show=False): fields = sf.fields if show: print("Fields -> {0}".format(fields)) ipop=None for i,val in enumerate(fields): if val[0] == "DP0010001": ipop = i-1 break ihouse=None for i,val in enumerate(fields): if val[0] ...
# Copyright 2018 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # These devices are ina3221 (3-channels/i2c address) devices inas = [ # drvname, child, name, nom, sense, mux, is_calib ('in...
for _ in range(int(input())): n,m=input().split() n,m=int(n),int(m) green='G' red='R' gcost=3 rcost=5 arr=[] array1=[] array2=[] gcheck=[] rcheck=[] i=0 while(i<m): if(i%2==1): array1.append(red) array2.append(green) else: ...
# Solution to part 2 of day 3 of AOC 2020, Toboggan Trajectory. # https://adventofcode.com/2020/day/3 f = open('input.txt') whole_text = (f.read()) grid = whole_text.split() # Split string by any whitespace. tree_product = 1 for delta_x, delta_y in [(1, 1), (3, 1), (5, 1), (7, 1), (1, ...
# We want make a package of goal kilos of chocolate. # We have small bars (1 kilo each) and big bars (5 kilos each). # Return the number of small bars to use, # assuming we always use big bars before small bars. # Return -1 if it can't be done. def make_chocolate(small, big, goal): needed = goal - big * 5 ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2018 all rights reserved # """ Verify that we can specify the metaclass dynamically and the classes still get built properly """ class aspectOne(type): pass class aspectTwo(type): pass def classFactory(metaclass=type):...
# Copyright 2015 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Copyright 2015 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # GYP file for codec project. { 'targets': [ { ...
def incidence_matrix(edges, excpt=[]): """Return an incidence matrix as dict where 1 indicates a relationship between two nodes in a directed graph. Parameters ---------- edges: list Set of graph's edges excpt: list Set of nodes to exclude from matrix construction (d...
""" Scoped CSS Styles for the graphs page """ PAGE_STYLE = { "paddingBottom": "5em" } TITLE_STYLE = { "margin": "0.5em" } CHART_ITEM_STYLE = { "margin": "2em", }
class DeckNotFoundError(Exception): '''No deck with given id.''' class CardNotFoundError(Exception): '''No card with given id.''' class CardAlreadyExists(Exception): '''There is a card with the same question.'''
print("THIS CODE IS SHIT AND MAKES THE DATA 30% BIGGER") print("read the comment below to get the idea") exit() ## # # This script groups repetitions of characters # # methode: # encode the character and repetitions into 4bit as following: # 0bXXYY where # XX=number of repetitions: 0b00=1, 0b01=2, 0b10=3, 0b11=4 # Y...
#!/usr/bin/python # -*- coding: UTF-8 -*- # -------------------------- # Author flyou # Date 2017/2/22 22:38 # EMAIL fangjalylong@qq.com # Desc 函数 # -------------------------- class MyMath: def getMaxNum(a, b): return max(a, b) def getMinNum(a,b): return min(a,b)
''' implement Pascal's triangle by using generator 1 / \ 1 1 / \ / \ 1 2 1 / \ / \ / \ 1 3 3 1 / \ / \ / \ / \ 1 4 6 4 1 / \ / \ / \ / \ / \ 1 5 10 10 5 1 https://en.wikipedia.org/wiki/Pascal%27s_triangle ''' def triangles(n, line_num...
# Helper function to get the stop sign performance with moving left. def StopSignLeft(stopPlace, flag, x, y, Speed, prev_perf): place = stopPlace[1][0] Boundary1 = [[stopPlace[0][0], stopPlace[0][1]], [place-13, place-3]] Boundary2 = [[stopPlace[0][0], stopPlace[0][1]], [place-36, place-26]] Boundary3 ...
"""Classed and methods for comparing expected and published items in DBs""" class DBAssert: @classmethod def count_of_types(cls, dbcon, queried_type, expected, **kwargs): """Queries 'dbcon' and counts documents of type 'queried_type' Args: dbcon (AvalonMongoDB) ...
''' Day 5: Sunny with a Chance of Asteroids ''' def parse_intcode(intcode, input): i = 0 while i < len(intcode): if intcode[i] not in (1, 2, 3, 4, 5, 6, 7, 8, 99): instruction = int(str(intcode[i])[-2:]) if instruction in (1, 2, 4, 5, 6, 7, 8): param = list() ...
""" Module for jenkinsapi Plugin """ class Plugin(object): """ Plugin class """ def __init__(self, plugin_dict): assert(isinstance(plugin_dict, dict)) self.__dict__ = plugin_dict def __eq__(self, other): return self.__dict__ == other.__dict__
number_of_cards = int(input()) cards_values = list(map(int, input().split())) i = 0 j = number_of_cards - 1 k = 0 scores = [0, 0] while i <= j: if cards_values[i] > cards_values[j]: scores[k % 2] += cards_values[i] i += 1 k += 1 else: scores[k % 2] += cards_values[j] ...
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '8HR\xee\xd8K\xc1gX\xbc\x8cr\x1fy\xf4#' _lr_action_items = {'PEEK':([115,157,159,173,202,225,257,315,330,334,356,358,359,360,362,366,367,],[142,142,-90,-75,-74,-81,-89,-82,-87,-91,-83,-85,-...
""" Copyright 2018-present, Facebook, Inc. 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 agreed to in writing,...
def for_R(): """We are creating user defined function for alphabetical pattern of capital R with "*" symbol""" row=7 col=5 for i in range(row): for j in range(col): if j==0 or ((i==0 or i==3)and j<4) or j==4 and i>0 and i<3 or i-j==2: print("*",end=" ") ...
if person.bored(): x = [0] for j in range(100): step_x = random.randint(0,1) if step_x == 1: x.append(x[j] + 1 + 0.05*np.random.normal()) else: x.append(x[j] - 1 + 0.05*np.random.normal()) y = [0.05*np.random.normal() for j in range(len(x))] trace1 = go.Scatter( x=...
def main(): print(sum(list(range(5)))) print(pow(2,3)) def exp(root,power): """ root^power returns string of equation""" base = " x ".join(str(root)*power) print( chr(ord('c'))) return f"{base} = {pow(root,power)}" def enumerate_(): l = ["aff","adasf","asdasc"] print(list(enumerate...
b2bi_strings = { 19: "fK4vQqsDwbXp/Hyjlc2EsVthXQCr/wdvCo5ZwrlpJB5eCoDdhJpZkkL+5XbQS5CqG0dz/bvErrAAQzAh2GYKIN7I/fswVYOFBoz5JcJbzv+c00ChoGMsuxzki1iTfyCVuXG8P5zg7FhiLtKUAlNusocKFGkL3dfwvbKNXGUgRGRdOpp5TCAFj7rZOgrMApz5lzdkxBlb4mKBqqdP2MFEIMsKEPE96rCSRvvuYddLTzQx42yoCg49L2yDyd7Fx2p36v3Khz8NtO9ozeigXYULYMzmojkHnkQ6Zi6gUvzd...
# A variável "vis" recebe a posição na memória do bytes(5) vis = memoryview(bytes(5)) # Retorna o valor da variável print(vis) # Possível retorno --> <memory at 0x0000024B2DBA4D00> # Retorna o tipo print(type(vis)) # <class 'memoryview'>
# [기초-입출력] 정수 1개 입력받아 그대로 출력하기(설명) # minso.jeong@daum.net ''' 문제링크 : https://www.codeup.kr/problem.php?id=1010 ''' num = int(input()) print(num)
#! /usr/bin/python3.7 def les(): def slope(): y1 = float(input('What is y1?: ')) y2 = float(input('What is y2?: ')) x1 = float(input('What is x1?: ')) x2 = float(input('What is x2?: ')) slope = (y2 - y1)/(x2 - x1) b = ((slope * x1)*-1) + y1 print('y = {}x + {}...
""" Copyright Government of Canada 2020 Written by: Eric Marinier, National Microbiology Laboratory, Public Health Agency of Canada Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License at: htt...
a=int(input("Enter first number\n")) b=int(input("Enter second number\n")) c=int(input("Enter third number\n")) d=int(input("Enter fourth number\n")) e=int(input("Enter fifth number\n")) add=a+b+c+d+e print("The sum of first 5 even numbers is",add)
class EncryptedUser(object): """ EncryptedUser class """ def __init__(self, username, roles, secret = None, algorithm = None, salt = None): """ Init User class """ self.username = username self.roles = roles self.salt = salt self.secret = secret self.algorit...
class Solution: def numTeams(self, rating: List[int]) -> int: lless_rcd = {} rless_rcd = {} lgreater_rcd = {} rgreater_rcd = {} for i in range(len(rating)): lless_rcd[i] = 0 lgreater_rcd[i] = 0 rless_rcd[i] = 0 rgreater_rcd[i] =...
# Solution def even_after_odd(head): if head is None: return head even = None odd = None even_tail = None head_tail = None while head: next_node = head.next if head.data % 2 == 0: if even is None: even = head ...
# -*- coding: utf-8 -*- RESPONSE_MESSAGE = { 'update_success': "Acc-Up アカウント情報を更新しました。", 'create_success': "Acc-Up アカウントを作成しました。", }
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def postorder(self, root: 'Node') -> List[int]: if root is None: return [] stack, output = [root, ], [] while sta...
# -*- coding: utf-8 -*- """ A set of Python functions that have mixed input and output expectations Created on Thu Sep 3 11:30:28 2015 @author: djc """ # Lowercases an input string def toLower(s): if type(s) is not str: raise ValueError("Wrong input type: the parameter must be a string"); ...
class Spam(object): def __init__(self,value): self.value = value class Eggs(object): def __init__(self,value): self.value = value s = Spam(1) e = Eggs(2) if isinstance(s,Spam): print("s is Spam - correct") if isinstance(s,Eggs): print("s is Eggs - incorrect") if isinstance(e,Spam...
""" Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space? """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val ...
class RebarHookOrientation(Enum,IComparable,IFormattable,IConvertible): """ Orientation of a rebar hook relative to the path of the Rebar Shape. enum RebarHookOrientation,values: Left (1),Right (-1) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ ...
i = 28 print(f"i is {i}") f = 2.8 print(f"f is {f}") b = True # False print(f"b is {b}") n = None # Idea that variable have NO_VALUE print(f"n is {n}")
""" Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. ...
# Time: O(n^2) # Space: O(n) class Solution(object): def transformArray(self, arr): """ :type arr: List[int] :rtype: List[int] """ def is_changable(arr): return any(arr[i-1] > arr[i] < arr[i+1] or arr[i-1] < arr[i] > arr[i+1] ...
def make_sNum(niz): sNum = [] for z in niz: if z in ["[", "]"]: sNum.append(z) elif z == ",": continue else: sNum.append(int(z)) return sNum def add_sNum(s1, s2): return ["["] + s1 + s2 + ["]"] def explode(s): levi_zak = 0 for i in r...
name = 'Mike' age = 33 money = 9.75 # print using concatination print(name + ' is ' + str(age) + ' and has $' + str(money) + ' dollars.') # print using the .format() method for strings print("{0} is {1} and has ${2} dollars.".format(name, age, money)) # print using f-strings print(f'{name} is {age} and has ${money} ...
class BaseParser(object): def __init__(self): pass def parse(self, url, hxs, index): return None def parse_relative(self, url, hxs): pass def parse_paginate(self, url, hxs, cache_db): pass def get_value_from_response(self, hxs, query, index, default=""): _...
load("//:compile.bzl", "proto_compile") load("//:plugin.bzl", "proto_plugin") def d_proto_compile(**kwargs): # If package specified, declare a custom plugin that should correctly # predict the output location. package = kwargs.get("package") if package and not kwargs.get("plugins"): name = kwar...
class FetchResourceError(Exception): def __init__(self, msg): super(FetchResourceError, self).__init__( "error fetching resource: " + str(msg) )
#Written by: Karim shoair - D4Vinci ( Dr0p1t-Framework ) #This is a persistence script aims to to add your exe file to startup registry key #Start def F7212(exe): fp = get_output("echo %CD%") new_name = get_output("echo %random%%random%").strip() + ".exe" new_file_path = fp + "\\" + new_name try: command = 'REG ...
# Python program Tabulated (bottom up) version def fib(n): # array declaration f = [0]*(n+1) # base case assignment f[1] = 1 # calculating the fibonacci and storing the values for i in range(2 , n+1): f[i] = f[i-1] + f[i-2] return f[n] # Driver program to test the above function def main(): n =...
def test_complex_fields(user_advance_dataclass): data = { "name": "juan", "age": 20, "pets": ["dog"], "accounts": {"ing": 100}, "has_car": True, "favorite_colors": "GREEN", "md5": b"u00ffffffffffffx", } expected_data = { "name": "juan", ...
a = int(input("Введите целочисленное значение 1: ")) b = int(input("Введите целочисленное значение 2: ")) c = int(input("Введите целочисленное значение 3: ")) if (a <= b) and (c <= b): print("Наибольшее число", b) elif (b <= c) and (a <= c): print("Наибольшее число", c) elif (b <= a) and (c <= a): p...
class DataView(object): def __init__(self, view_id, name, description, datasets=[], column_names=[], columns=[]): """ Constructor. :param view_id: The ID of the data view :type view_id: str :param name: The name of the data view :type name: str :param descri...
TRAIN_MODE = False MODELPATH = './engine/data/trained_model/rel_first_model.pth' NUM_EPOCHS = 10000 BATCH_SIZE = 30 RELATION_FILE = "./engine/data/refer/relation_train.txt" GENOME_DICT = "./engine/data/procdata/genome_rel_dict.pkl" IMG_WIDTH = 800 TRAIN_PROC_MAX = 10000 VALID_PROC_MAX = 1000 DATA_SHUFFLE = True LEARN_...
''' Args: Returns: ''' ''' wxPython 是基于Python的跨平台GUI(图形用户交互界面)扩展库,对wxWidgets(C++)封装实现。 '''
conta = 0. # Mesma linha vai ser essa mesma = 23.0 dici_letra = { '.':.88, ',':.88, ' ':.49 } top = { 0:1.2, 1:1.2, 2:1.5, 3:1.5, 4:1.3 } palavra = ' sfaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' palavra = ' akkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk...
# -*- coding: utf-8 -*- # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) # 2017 MinIO, Inc. # # 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/lic...
supported_aminoacids = ["ALA", "ARG", "ASH", "ASN", "ASP", "CYS", "CYT", "GLH", "GLN", "GLU", "GLY", "HID", "HIE", "HIS", "HIP", "ILE", "LEU", "LYS", "LYN", "MET", "PHE", "PRO", "SER", "TRP", "THR", "TYR", "VAL", "ACE", "NMA"] aminoacids_3letter = ...
def get_r_string_samples_by_sample_group(order_list,samples_by_sample_groups): samples_by_sample_group_r_string = [] for sample_group in order_list: sample_group_samples = samples_by_sample_groups[sample_group] samples_by_sample_group_r_string.append("c(\"" + "\",\"".join(sample_group_samples)...
""" The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ """ The maximum base can be 9 because all n-digit numbers < 10^n. Now 9**23 has 22 digits so the maximum power can be...
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # This file is autogenerated and should not be modified manually. # Update versions/UpdateVersions.hs instead. sdk_versions = [ "1.0.0", "1.0.1", "1.1.1", "1.2.0", ...
N = int(input()) c = 1 for i in range(1, 10): for j in range(1, 10): if c != N: c += 1 continue print(str(j) * i) exit()
''' ## s3_enable_encryption What it does: Turns on encryption on the target bucket. Usage: AUTO: s3_enable_encryption <encryption_type> <kms-key-arn> (<kms-key-arn> should be provided only if <encryption_type> is KMS) Note: <encryption_type> can be one of the following: 1. s3 (for s3-managed keys) 2. kms (for customer ...
def main(): with open('adventofcode/twentytwenty/static_data/day5.txt', 'r') as f: lines = f.readlines() max_id, missing_ids = find_seat_numbers(lines) print('Max ID:', max_id) print('Missing IDs:', missing_ids) def find_seat_numbers(boarding_passes): """Determines the seat number of a boa...
# pylint: disable=W0613, C0111, C0103, C0301 """ The ui package. version: 3.4r7.0 ExtronLibraray version: 3.4r7 ControlScript version: 3.4.6 GlobalScripter version: 2.3.1.3 Release date: 3.10.2019 Author: Roni Starc (roni.starc@gmail.com) ChangeLog: v2.0 - Fixed some mistakes, updated GS v2.8.r3, added ...
pkgname = "libplist" pkgver = "2.2.0" pkgrel = 0 build_style = "gnu_configure" configure_args = ["--disable-static"] # prevent building python binding .a hostmakedepends = ["pkgconf", "automake", "libtool", "python", "python-cython"] makedepends = ["python-devel", "libglib-devel", "libxml2-devel"] pkgdesc = "Apple Prop...
def main(): # input N = int(input()) Ss = [*map(int, input().split())] Ts = [*map(int, input().split())] # compute for i in range(2*N): Ts[(i+1)%N] = min(Ts[(i+1)%N], Ts[i%N]+Ss[i%N]) # output print(Ss) print(Ts) for ans in Ts: print(ans) if __name__ == '__mai...
# Ke Chen # knutchen@ucsd.edu # Zero-shot Audio Source Separation via Query-based Learning from Weakly-labeled Data # The configuration file # for model training exp_name = "exp_zs_asp_full" # the saved ckpt prefix name of the model workspace = "/home/Research/ZS_ASP/" # the folder of your code dataset_path = "/home/...
class ImportInstance(Instance,IDisposable): """ An element created during either import or link operation in Autodesk Revit. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def getBoundingBox(self,*args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """ pass de...
class Error(Exception): """Error personalizado para mayor control en los programas. ATRIBUTOS: type = Especifica el tipo de error, en caso de ser un error lanzado por el usuario se sugiere utilizar el valor 'validacion'. message = Descripcion del error. c...
#!/bin/python # coding: utf-8 # Source: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml statuscodes = [ (100, "Continue"), (101, "Switching Protocol"), (102, "Processing"), (200, "OK"), (201, "Created"), (202, "Accepted"), (203, "Non-Authoritative Information"), ...
async def send_large_text(channel, contents): return_messages = [] content_lines = contents.splitlines(True) output = "" for line in content_lines: if len(output) > 1800: return_messages.append(await channel.send(output)) output = "" output += line if len(outp...
class Solution: """ @param N: a number @return: the number of prime numbers. 题目给定一个正整数N,你需要统计(1,N]之间所有整数质数分解后,所有质数的总个数。 Example 输入:6 输出:7 解释:2=2, 3=3, 4=2*2, 5=5, 6=2*3, 个数和为1+1+2+1+2=7 Notice 1<N<=100000 解题思路 利用一个递推的思路,例如40 = 4*10 ,那么40的质数分解个数等于4的质数分解个数加上10的质数分解个数。 开一个数组prime,prime[i]代表i的质数分解个数;当遍历到i...
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "("+str(self.x)+","+str(self.y)+")" class Rect: def __init__(self, p1, p2): self.lowerleft = p1 self.upperright = p2 def area(self): dx = upperright.x - lowerleft.x ...
# 63 # Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Exemplo: 0 – 1 – 1 – 2 – 3 – 5 – 8 print('-'*25) print('\33[32mSequência de Fibonacci\33[m') print('-'*25) n = int(input('Quantos termos você quer mostrar? ')) termo = 0 prox = 1 c...
# Copyright (c) 2020 Dell Inc. or its subsidiaries. # # 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...
class Solution: # dp[i] 为以下标 i 结尾的最长有效子字符串的长度。 # s[i] == ')' && s[i-1] == '(' # dp[i] = dp[i-2] + 2 # s[i] == ')' && s[i-1] == ')' && s[i - dp[i-1] - 1] == '(' # dp[i] = dp[i-1] + dp[i - dp[i-1] - 2] + 2 def longestValidParentheses(self, s: str) -> int: result = 0 dp = [0] * len(s) for i i...
""" 问题描述:给定一个整型数组arr和一个大于1的整数k。已知arr中只有1个数出现了1次, 其它的数都出现了k次,请返回只出现了1次的数。 要求: 时间复杂度为O(N),额外空间复杂度为O(1). 思路: k个k进制的数,无进位相加。比如2个相同的二进制的数,无进位相加,结果一定为0 """ class KGetter: @classmethod def num2ksys(cls, num, k): res = [0 for _ in range(32)] i = 0 while num != 0: res[i] = num % k...
FREQ = 10 # 1/delta_time based on recorded data SCENE_DUR = 5 # in seconds NUM_TS_PER_SCENE = FREQ * SCENE_DUR RADIUS_AROUND_AGENT = 50. # range to get surrounding objects, in meters ORDERED_COLUMNS = [ "timestamp", "id", "object_type", "center_x", "center_y", "heading", "status" ] # a ...
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'includes': [ '../../get_vivaldi_version.gypi' ], 'variables': { 'mac_product_name': 'Vivaldi', 'mac_packaging_dir': '<(PRODUC...
''' 2-CLAUSE BSD Copyright (c) 2017, apple502j All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of ...
def lerarquivo(conto): lista_palavras = list() try: a = open(conto, 'rt') except: print('Erro ao ler o arquivo!') else: for linha in a: texto = linha.split(' ') for palavra in texto: p = palavra.lower() lista_palavras.append...
#!/usr/bin/python # -*- coding: utf-8 -*- API_METHOD_PURCHASE='wallet.trade.buy' API_METHOD_REDEEM='wallet.trade.sell' API_METHOD_QUERY='wallet.trade.query' API_METHOD_CANCEL='wallet.trade.cancel' PAYMENT_STATUS_NOTSTARTED='Not Started' PAYMENT_STATUS_PAYSUCCESS='PaySuccess' PAYMENT_STATUS_SUCCESS='Success' PAYMENT_ST...
# Problem name : Plus One # Problem link : https://leetcode.com/problems/plus-one/ # Contributor : Shreeraksha R Aithal class Solution: def plusOne(self, digits: List[int]) -> List[int]: n = len(digits) i = -1 carry = 1 while i>=-n: digits[i] = digits[i] + carry ...
n = int(input()) a = list(map(int, input().split())) dp = [1] * n for i in range(1, len(a)): for j in range(i - 1, -1, -1): if a[j] == a[i]: dp[i] = max(dp[i], dp[j]) if a[j] < a[i]: dp[i] = max(dp[i], dp[j] + 1) print(max(dp)) print(dp)
"""Make this it's own package so unit tests run properly without having to mess with path variables, see: __ http://stackoverflow.com/questions/1896918/running-unittest-with-typical-test-directory-structure Note: run ``python -m unittest discover`` """
# https://leetcode.com/problems/deepest-leaves-sum/ # 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 def dl_sum_and_depth(root: TreeNode, depth: int) -> tuple[int, int]: if not roo...
n, p, s = map(int, input().split()) sets = list() for _ in range(s): sets.append(input().split()[1:]) for s in sets: if str(p) in s: print('KEEP') else: print('REMOVE')
# BOJ 1874 스택 수열 n = int(input()) target = [int(input()) for _ in range(n)] # 입력된 수열 origin = [] operation = [] i = 1 cnt = 0 while i <= n or origin: # print(f"i: {i}") # print(f"cnt: {cnt}") # print(f"origin: {origin}") # print(f"operation: {operation}") if i < target[cnt]: origin.append(...