content
stringlengths
7
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of Advent of Code 2020 # https://github.com/scorphus/advent-of-code-2020 # Licensed under the BSD-3-Clause license: # https://opensource.org/licenses/BSD-3-Clause # Copyright (c) 2020, Pablo S. Blum de Aguiar <scorphus@gmail.com> def part1(lines): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 7 19:05:20 2017 @author: xg7 """ #Question2 #Q2.1 # l = [1, 1, 2.1, 2.5] # #l = [1, 1, 1, 2, 2, 2, 1, 1, 1, 2.5] # d = {1:3, 2:5.5, 6:2.0, 4:2.0} def remove_non_int(l): for e in l[::-1]: if type(e) != int: l.remove(e) ...
def origin_translation(A, p, x0=None, eps=1e-8, max_steps=1000, verbose=False): _I = identity(A.shape[0]) BLOCK = 0 eig = p x = x0 for k in range(int(max_steps)): eig_prev = eig BLOCK = 1 x = linalg.solve(A - eig * _I, x) q = argmax...
a = list(map(int, input().split())) count = 0 for i in range(len(a)): if a[i] > 0: count += 1 print(count)
# 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 recoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-p...
age = input("How old are you babe?") race = input("What race are you?") identity = input("How do you identify yourself. a no:") print(f"So if you are {age} old, and you are from {race}, you identify as {identity}")
# *args def some_func(*args): print(args) some_func(1, 2, 3) some_func("peter", "george") some_func(True, False) def f(*args): current_min = args[0] for x in args: if x < current_min: current_min = x print(current_min) f(1, 2, 3, 4, 5, 6) # 1 f(1, 2, 3, 4, 5, 6, -4) # -4 # ...
#how to open files my_files=open("people1.txt") files=my_files.read() print(files) my_files.close() #method-2 # with open("people1.txt","r") as file: # print(file.read()) # file.close() # with open("people1.txt", "r") as file: # data = file.readlines() # for line in data: # word = line....
class Streak: """ Captures checking streaks of the trip. Checking streaks are contiguous checkin sequences separated by given number of days of checking discontinuities """ def __init__(self, first_date, last_date, days, days_gap): self.first_date = first_date self.last_date = last_d...
nums = [1, 2, 3, 4, 5] # iter, next 를 직접 호출해서 # 잘 동작하는지 실행해봅시다. it = iter(nums) print(next(it)) print(next(it)) print(next(it)) print(next(it)) print(next(it)) # 여기서 중단됨 print(next(it))
# Level: Easy def isPalindrome(x: int) -> bool: if x < 0: return False y = x back_num = 0 while y > 0: back_num = back_num * 10 + y%10 y = y//10 if x == back_num: return True return False if __name__ == "__main__": x = 12321 print(isPalindrome(x))
def exercise_1(inputs): # DO NOT CHANGE THIS LINE """ This functions receives the input in the parameter 'inputs'. Change the code, so that the output is sqaure of the given input. p, q, r = inputs p => ['t101', 't102', 't103'] q => ['s101', 's102', 's103'] r => { 'l101':[...
if __name__ == '__main__': for t in range(int(input())): x1, y1, x2, y2 = map(int, input().split()) print((x2 - x1) * (y2 - y1) + 1)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: flag = True def f(root): nonlocal flag ...
def get_dict_first_key(dictionary): return next(iter(dictionary)) # ### MAP SIZE MAP_SIZE_DICT = { "TINY_MAP": "Tiny map", "SMALL_MAP": "Small map", "MEDIUM_MAP": "Medium map", "LARGE_MAP": "Large map", "HUGE_MAP": "Huge map", "GIGANTIC_MAP": "Gigantic map", "LUDIKRIS_MAP": "Ludikris m...
""" lec 2 this is a regional comment """ #print("hello world") # this is a single line comment #print(type( 123 ) ) #print( type(123.) ) #print(type ("123") ) #print("Tom's cat") #print( "Hello " + "World" ) #my_int = 123 #print(my_int) #my_int = 321 #print(my_int) my_str = "hello world" print(my_str.upper(...
#!/usr/bin/python ROOT_URL = 'http://numismatics.org/' SEARCH_URL = 'ocre/results?q=' JSON_API_URL = 'ocre/id/' NOMISMA_URL = 'http://nomisma.org/id/' BRITISH_MUSEUM_URL = ( 'http://collection.britishmuseum.org/' 'id/person-institution/' ) BRITISH_MUSEUM_NAMES_BY_ID = { '53770': 'Horus', '54025': 'Isis...
"""Get Score of Table strategy """ def get_score(table, board): """get_score """ board_info = board.get_board_info() size = board.size score = 0 for y in range(size): for x in range(size): score += table[y][x] * board_info[y][x] return score
salario: float; novoSalario: float; aumento: float porcentagem: int salario = float(input("Digite o salario da pessoa: ")) if salario <= 1000: porcentagem = 20 elif salario <= 3000: porcentagem = 15 elif salario <= 8000: porcentagem = 10 else: porcentagem = 5 aumento = salario * porcentagem / 100 nov...
# # Copyright 2021 Google LLC # # 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,...
username = 'admin' password = 'garahasia' if (username == 'admin') and (password == 'rahasia'): print('user berhasil login') else: print('user gagal login')
args_converter = lambda row_index, rec: \ {'text': rec['text'], 'size_hint_y': None, 'height': 25, 'cls_dicts': [{'cls': ListItemButton, 'kwargs': {'text': rec['text']}}, {'cls': ListItemLabel, 'kwargs': {'text': r...
""" Link: https://www.geeksforgeeks.org/find-the-missing-number/ """ # pylint: disable=invalid-name def find_missing_number(array): """ :param array: given integer array from 1 to len(array), missing one of value :return: The missing value Method: Using sum of list plus missing number subtract the lis...
self.description = "upgrade package overwriting existing unowned file with directory" lp1 = pmpkg("pkg1") self.addpkg2db("local", lp1) self.filesystem = ["file"] p = pmpkg("pkg1", "1.0-2") p.files = ["file/"] self.addpkg2db("sync", p) self.args = "-S pkg1" self.addrule("PACMAN_RETCODE=1") self.addrule("PKG_VERSION...
#!python3 # Copyright (C) 2016 Chris Liebert def getConglomerates(x, y, z): a,b,c,d,e,f,g,h = 0,0,0,0,0,0,0,0 collections = [] num_collections = 0 a = 0 while x >= 0 and y >= 0 and z >= 0: b = 0 bx,by,bz = x,y,z while x >= 0 and y >= 0 and z >= 0: c = 0 ...
# Thirdparty Solution Analysis # https://www.martinkysel.com/codility-commonprimedivisors-solution def gcd(p, q): if q == 0: return p return gcd(q, p % q) def hasSameFactors(p, q): if p == q == 0: return True denom = gcd(p,q) while (p != 1): p_gcd = gcd(p,denom) ...
x = int(input('Enter any three number : ')) y = int(input()) z = int(input()) if x > y and x > z: print(str(x)+' is the greatest number among the three numbers') elif y > x and y > z: print(str(y)+' is the greatest number among the three numbers') elif z > x and z > y: print(str(z)+' is the greatest number ...
# rules for variable names: # 1. name cannot start with a number # 2. there can be no spaces in the name, use _ instead # 3. can't use any of the symbols: !@#$%^&*()-+~<>,' # 4. it's considered best practice (PEP8) that names are lowercase # 5. avoid using word words that have special meaning in python like "list" and...
# ## There are three cans, all don't have scale, and the capacity respectively are 12 liter, 8 liter, 5 liter, ## at initial: the 12 liter one with full liquid, the others two are empty # ## Find a solution to get two cans of 6 liter liquid. # def equipartition(): def gcd(a, b): if str(a).isdigit() and str(b)...
# Lv-677.PythonCore # -Задано чотирицифрове натуральне число. # - Знайти добуток цифр цього числа. # - Записати число в реверсному порядку. # - Посортувати цифри, що входять в дане число x = int(input('Напишiть чотирицифрове натуральне число: ')) while len(str(x)) != 4: print("Error") x = int(input("Напишiть ч...
#!/usr/local/bin/python3 # 0, 1, 1, 2, 3, 5, 8, 13, 21... def fibonacci(quantidade): resultado = [0, 1] for _ in range(2, quantidade): resultado.append(sum(resultado[-2:])) return resultado if __name__ == '__main__': # Listar os 20 primeiros números da sequência for fib in fibonacci(20):...
class MapModel: def __init__(self, id, riot_map_id, name, notes): self.id = id self.riot_map_id = riot_map_id self.name = name self.notes = notes
# Time: O(n) # Space: O(1) class Solution(object): def secondHighest(self, s): """ :type s: str :rtype: int """ first = second = -1 for c in s: if not c.isdigit(): continue d = int(c) if d > first: ...
class Hyperparameter: logdir = 'logdir' weights_dir = 'weights' data_dir = 'datasets' rate = 22050 batch_size = 1 generator_lr = 0.0002 discriminator_lr = 0.0001 lambda_cycle = 10 lambda_identity = 5 num_mceps = 36 duration = 5.0 n_frames = 128 output_size = 512 n...
t = int(input()) for _ in range(t): n,k,d = map(int, input().split()) # Taking n integers and storing it in list arr = list(map(int, input().split())) # Finding sum of all elements inside array total = sum(arr) # Floor division would give the answer but # see to it that doesn't excede d, ...
class SimpleDisjointSet(): #Simple Disjoint Set Data Structure def __init__(self, nodes): self.prev = {} #Keep track of parent of nodes for node in nodes: self.prev[node] = node def find(self, node): #Return root of Set if self.prev[node] == node: return node ...
user = input("rock, paper or scissors: ") actions = ["rock", "paper", "scissors"] print ("You chose", (user)) if user == "rock": print ("The computer chose paper") print ("tough luck, paper covers rock ") elif user == "scissors": print ("The computer chose rock") print ("GG, you lost") elif user == "paper": ...
class Singleton: _instance = None def __init__(self): # Singleton pattern must prevent normal instantiation raise Exception("Cannot directly instantiate a Singleton. Access via get_instance()") @classmethod def get_instance(cls): # This is the only way to access the one and onl...
with open(r"advent_of_code\input2.txt", 'r') as f: intcode = list(map(int,f.read().split(","))) def step_one(intcode): # for i in range(0, len(intcode)-1, 4): pointer = 0 while intcode[pointer] != 99: opcode = intcode[pointer] noun = intcode[pointer+1] verb = intcode[pointer+2] ...
img = "2212222102022220222221222222221022220210202222222222222212222222222222221222222222222202221212222212220222202222220222222222212212212222212222220222222222222012022220222222222222222122221222212222222222222222222222222222221222222222222202221212222212220222222222220222222222222212212222212222222222222212222012222...
# FAÇA UM ALGORITIMO QUE LEIA O SALARIO DE UM FUNCIONARIO E MOSTRE SEU NOVO SALARIO COM 15% DE AUMENTO sal = float(input('Digite seu salário: ')) percentual = sal * 0.15 # sal*15/100 aumento = sal + percentual print('Seu salário era: ', sal, 'com o aumento ficou: ', aumento)
"""Config: like config: type: map repo: path: ./repo map_md: map.md sorted : true """ # pylint: disable=C0116,R0903,E0401,W0703,W1201,redefined-outer-name,missing-function-docstring,E0401,C0114,W0511,W1203,C0200,C0103,W1203 class Config: """Config""" def __init__(self, map_yaml_path, persist_fs): ...
def run(): LIMIT = 100000000 counter = 0 power = 2**counter while power < LIMIT: print('2 a la ' + str(counter) + ' = ' + str(power)) counter += 1 power = 2**counter def forloop(): name = input('Type your name: ') # for char in range(len(name)): # print(name[cha...
""" n个数字的可重复排列 已知n等于4 """ n=4 count = 0 for i1 in range(1, n + 1): for i2 in range(1, n + 1): for i3 in range(1, n + 1): for i4 in range(1, n + 1): count+=1 print(f"{i1},{i2},{i3},{i4}") print(f"共{count}种方案")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Read input a = int(input()) b = int(input()) # Get min and max m = max(a, b) t = min(a, b) # Addition loop r = 0 while t > 0: r += m t -= 1 # Print result print(r)
# -*- coding: utf-8 -*- """ samsara_sdk.constants ~~~~~~~~~~~~~~~~~~~~~ Samsara SDK client constants """ # Samara specific HTTP Header PUBLISHED_TIMESTAMP_HEADER = "X-Samsara-publishedTimestamp" API_PATH = '/v1/events' DEFAULT_CONFIG = { # a samsara ingestion api endpoint "http://samsara-ingestion.lo...
class Solution: def isPowerOfFour(self, num: int) -> bool: """ Other solution: There are 2 criteria for a number to be power of 4: is power of 2: n&(n-1) == 0 even number of "0" in binary format For example, 4 in binary is "100". 100&011 == 0 there a...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.results = [] def _dfs(self, root, cur_path): if root.left == None and root.right == None: ...
# -*- coding: utf-8 -*- ufUpdate = 0x01 ufLine = 0x02 ufView = 0x04 smExtend = 0x01 smDouble = 0x02 sfSearchFailed = 0xFFFFFFFF cmFind = 82 cmReplace = 83 cmSearchAgain = 84 cmCharLeft = 500 cmCharRight = 501 cmWordLeft = 502 cmWordRight = 503 cmLineStart = 504 cmLineEnd = 505 cmLineUp = 506 cmLineDown = 507 cmPag...
"""Tournament view.""" class TournamentView: """Class managing tournament displays.""" def __init__(self) -> None: """Class initializer.""" pass def get_view_name(self) -> str: """Return name for input. Returns: str: Information for name """ r...
# -*- coding: utf-8 -*- ''' File name: code\names_scores\sol_22.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #22 :: Names scores # # For more information see: # https://projecteuler.net/problem=22 # Problem Statement ''' Using names....
l=int(input("enter length of rectangle:")) b=int(input("enter width of rectangle:")) perimeter=(l+b)*2 area=l*b print("perimeter=",perimeter) print("area=",area)
class Solution: """ @param s: The first string @param t: The second string @return: true or false """ def anagram(self, s, t): t = list(t) for ss in s: if ss not in t: return False t.remove(ss) if not t: ...
""" Module for holding XML templates for DirectPayOline requests. """ # XML templates # ================XML templates (header and footer)================ header_xml = """ <?xml version="1.0" encoding="utf-8"?> <API3G> <CompanyToken>{company_token}</CompanyToken> <Request>{request_type}</Request> """ f...
f=input("Input the Filename: ") x=f.split(".") y=x[-1] if(y=="py"): z=("Python") elif(y=="txt"): z=("Text file") elif(y=="docx"): z=("Word file") else: z=("INVALID") print("The extension of the file is: ",z)
# https://codeforces.com/problemset/problem/4/C n = int(input()) d = {} for i in range(0, n): s = input() if s in d: print(s+str(d[s])) d[s] += 1 else: print("OK") d[s] = 1 # n = input() # l = [] # for _ in range(int(n)): # val = input() # if val in l: # ind ...
class FreqStack: def __init__(self): self.heap = [] self.count = collections.Counter() self.push_count = 0 def push(self, x: int) -> None: self.count[x] += 1 self.push_count += 1 heapq.heappush(self.heap, (-self.count[x], -self.push_count, x)) def pop(self) ...
#se copian las tablas de las bases aqui class Tabla(object): def __init__(self, basedatos,nombre,columna,modo): self.base=basedatos #nombre base self.tabla = nombre #nombre tabla self.columnas = columna #numero de columnas self.modo=modo #modo en que se guardo la tabla b ...
def get_stats(): """Statistic about given file: number of lines, number of empty lines, number of lines with 'z', number of 'z' letter, number of lines with 'and'""" file = input("File: ") dict_result = { 'total_lines': 0, 'empty_lines': 0, 'z_lines': 0, 'z_letters': 0,...
# Python program for implementation of Shell Sort # Shell sort is an algorithm that first sorts the elements far apart # from each other and successively reduces the interval # between the elements to be sorted. It is a generalized version of insertion sort.''' def shellSort(values): # Start with a somewhat bi...
x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(input()) a = max(x1, x2) - min(x1, x2) b = max(y1, y2) - min(y1, y2) area = a * b perimeter = 2 * (a + b) print(area) print(perimeter)
BLACKLIST = [ # PRESF --------------------------- 'SetTime', 'DateTime', 'ExternalTemperature', 'CONDUCTIVITY', 'QUARTZ_PRESSURE_SENSOR_SERIAL_NUMBER', 'USE_STOP_TIME', 'USE_START_TIME', 'IOP_MA', 'DEVICE_VERSION', 'LAST_SAMPLE_T', 'QUARTZ_PRESSURE_SENSOR_RANGE', 'LAS...
""" This constant file was automatically generated by a quick script I wrote for the enum part and h2py for the constant part. It aims to help out remembering the enum values and constants, but probably as bugs... please refer to the actual documentation for the correct values (if something is not working) and feel fr...
# 创建列表 numbers = list(range(1,21,2)) print(numbers) # 打印 for number in numbers: print(number)
class Simulation(): """模拟类 Attributes: data: 数据源。调用 :func:`simulate` 方法后,会返回处理后的数据集,否则返回原始数据集。 symbol: 股票代码 callbacks: 处理数据时会使用到的回调 :class:`callbacks.CallBack` 集合。 """ def __init__( self, data, symbol, callbacks=[], ): ...
def largest_prime_factor(n): i = 2 while i * i <= n: if n % i == 0: n //= i else: i += 1 return n if __name__ == '__main__': T = int(input()) for _ in range(T): n = int(input()) print(largest_prime_factor(n))
__title__ = "lpipe" __version__ = "4.0.2" __summary__ = "AWS Lambda framework for writing clear, minimal Python FAAS" __author__ = "Charlie Mathews" __author_email__ = "cmathews@mintel.com" __maintainer__ = "Charlie Mathews" __maintainer_email__ = "cmathews@mintel.com" __uri__ = "https://github.com/mintel/lpipe"
def digit_prod(n): if n%10==n: return n else: return n%10 * digit_prod(n//10) if __name__ == "__main__": n=32146 print(digit_prod(n))
# -*- coding: utf-8 -*- """ Created on Wed May 18 20:26:49 2016 @author: ericgrimson """ def search(L, e): def bSearch(L, e, low, high): if high == low: return L[low] == e mid = low + int((high - low)/2) if L[mid] == e: return True if L[mid] > e: ...
def increment(number, by=2): # Increment always by 2, if not provided with any value process = number + by return process result = increment(number=5) print(result)
# https://leetcode.com/problems/combinations/ # Given two integers n and k, return all possible combinations of k numbers out of # the range [1, n]. # You may return the answer in any order. ################################################################################ # dfs class Solution: def combine(self,...
class FilterTagsTestMixin(object): def assert_have_filter_tags(self, category, value): filter_tags = self.find('#filter-tags').text.lower() filter_tags.should.contain(category.lower()) filter_tags.should.contain(str(value).lower()) def assert_no_filter_tags(self): self.find_all(...
# Ethan def solveQuad(eqn): a, b, c = 0,0,0 # Return Values shape, roots, completedSq, turningPoint, yIntercept = "", [], "", "", 0 def validation(): # Validate User Input global a,b,c try: # Try to Parse Values of a, b and c a = eqn[0:eqn.find("x^2")] if "x+" in...
''' Created on 1.12.2016 @author: Darren '''''' Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. For example: Given the following binary tree, 1 <--- / \ 2 3 <--- \ ...
# BFS, Map, overtime class Solution: def cutOffTree(self, forest): """ :type forest: List[List[int]] :rtype: int """ height = len(forest) if height == 0: return 0 width = len(forest[0]) if width == 0: return 0 trees = []...
# -*- coding: utf-8 -*- """Top-level package for D3b Airflow Plugins for Cavatica.""" __author__ = """Mark Welsh""" __email__ = 'welshm3@chop.edu' __version__ = '0.1.1'
#Exercício Python 076: Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular. tupla = ("Lápis", 1.75, "Caneta", 2.00, "Caderno", 10.50, "Borracha", 0.50) for c in range(0, len(tupla)): ...
def stage(ctx): return { "parent": "root", "triggers": { "parent": True }, "parameters": [], "configs": [], "flow_label": "0.#{KK_FLOW_SEQ}", "jobs": [{ "name": "tarball", "steps": [{ "tool": "git", ...
#! /bin/env python3 ''' Functional wrapper around the bitwise operators. Designed to make their use more intuitive to users not familiar with the underlying C operators. Extends the functionality with bitmask read/set operations. The inputs are integer values and return types are 16 bit integers or boolean. bit indexe...
__title__ = 'Flask-SSS' __description__ = 'Server-Side Sessions for Flask implemented as a SessionInterface.' __version__ = '0.1.0' __author__ = 'Steve McCartney' __author_email__ = 'python@reconvergent.com' __license__ = 'Apache 2.0' __url__ = 'https://github.com/stevemccartney/flask-sss'
# Purpose: constant values # Created: 10.03.2011 # Copyright (c) 2011-2018, Manfred Moitzi # License: MIT License # --- For Unix --- # 0: undefined Rises an error. # 1: ascii $20-$7F,%%c,%%d,%%p Only # 2: iso8859_1 Western Europe(Unix) $20-$FF,%%c,%%d,%%p # 3: iso8859_2 Central Europ...
# Time: 0(n) | Space: O(n) # Input: "aba" # Output: True # Input: "abca" # Output: True # Explanation: You could delete the character 'c'. def isPalindrom(s): i = 0 j = len(s)-1 while i < j and s[i] == s[j]: i+=1 j-=1 return i>=j class Solution: def validPalindrome(self, s: str...
# говнокод mut_set, all_set = set(), set() N = int(input()) for j in range(int(input())): mut_set.add(input()) all_set |= mut_set for i in range(1, N): st_set = set() for j in range(int(input())): st_set.add(input()) mut_set &= st_set all_set |= st_set print(len(mut_set)) for i ...
def userClick(): #get coordinates of mouse click x,y = pg.mouse.get_pos() #get column of mouse click (1-3) if(x<width/3): col = 1 elif (x<width/3*2): col = 2 elif(x<width): col = 3 else: col = None #get row of mouse click (1-3) if(y<height/3): ...
# import os JWT_SECRET_KEY = "9e4a7c7020769b8dab4aa38774bc57a454ecf739d62bf46d0ca77e053bbc5cbb" JWT_ALGORITHM = "HS256" JWT_EXPIRATION_TIME_IN_MIN = 60 * 24 * 5 TOKEN_DESCRIPTION = "It verifies username and password from db and returns jwt token" TOKEN_SUMMARY = "It returns jwt token" DB_HOST = "localhost" DB_USER =...
class DPANodeTypeSpecification: def is_satisfied_by(self, dpa_node): classname = dpa_node.__class__.__name__ return (classname == 'DPANode')
def empty(x): if x: return False else: return True
# O(n^2) def reverse_string(string): if len(string) == 0: return string return reverse_string(string[1:]) + string[0] if __name__ == '__main__': print(reverse_string('Eashan'))
__all__ = ('Validator',) class Validator(object): def validate(self, arg_list, starting_index): raise NotImplementedError
# This code is linked with 'Challenge_16.py'. def max_finder(a_list): max_in_list = a_list[0] for index in range(1, len(a_list)): if a_list[index] > max_in_list: max_in_list = a_list[index] return max_in_list
# -*- coding: utf-8 -*- # リスト型 param = [1, 2, 4, 8, 16] introduction = 'my name is python' # 差し替え param[3] = 10 print(param[:])
##Variable Assignment and Printing #Strings #Quotes 'single quotes' #Generally used for regular expressions such as dict keys or SQL "Double quotes" #Used for representing Strings #Printing x = "Hello World!" # Assigns statement/String "Hello World!" to var x print(x) # Prints current value of instantiated var #form...
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ 这题要解决的问题是,必须有个地方记录判断结果,但又不能影响下一步的判断条件; 直接改为 0 的话,会影响下一步的判断条件; 因此,有一种思路是先改为 None,最后再将 None 改为 0; 从条件上看,如果可以将第一行、第二行作为记录空间,那么,用 None 应该也不算违背题目条件; """ rows = len(matrix) cols = len(...
N, M = map(int, input().split()) C = list(map(int,input().split())) INF = 10**10 dp = [[INF]*(N+1) for _ in range(M+1)] dp[0][0] = 0 for m in range(M): for n in range(N+1): if n-C[m]>=0: dp[m+1][n] = min(dp[m+1][n-C[m]]+1, dp[m][n]) else: dp[m+1][n] = dp[m][n] print (dp[M][N]...
#!/usr/bin/python3 def print_reversed_list_integer(my_list=[]): if my_list: for i in range(len(my_list) - 1, -1, -1): print("{:d}".format(my_list[i]))
class BinaryImage(object): def __init__(self,b): self.b=b def _determineColorValue(self): v = 255*self.b return ("#%02x%02x%02x" % (v, v, v))
x:int = 1 y:int = 2 a:bool = True b:bool = False c:str = "" d:str = "" b = a printf("%d", x != y) x = y printf("%d", x == y) x = 2 y = 2 printf("%d", x == y) x = y = 0 printf("%d", x == 0) printf("%d", y == 0) printf("%d", a == b) b = False printf("%d", a != b) printf("%s", c) printf("%s", d) d = c = "123" printf("...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Echos A Input - Usage: Echo <text>""" imports = () reqcoms = () def func(root, display, *args, **kwargs): display.insert("end", "") for arg in args: if arg == "\\n": display.insert("end", "") else: display.in...
nota1 = float (input("Informe a primeira nota: ")) nota2 = float (input("Informe a segunda nota: ")) nota3 = float (input("Informe a terceira nota: ")) nota4 = float (input("Informe a quarta nota: ")) media = (nota1+nota2+nota3+nota4) / 4 print("A média é: {}" .format(media))
n,m,*a=map(int,open(0).read().split()) s=set(a) dp=[0,1]+[0]*n mod=1000000007 for i in range(2,n+2): if (i-1) not in s: dp[i]=(dp[i-1]+dp[i-2])%mod print(dp[n+1])