content
stringlengths
7
1.05M
# Leo colorizer control file for factor mode. # This file is in the public domain. # Properties for factor mode. properties = { "commentEnd": ")", "commentStart": "(", "doubleBracketIndent": "true", "indentCloseBrackets": "]", "indentNextLines": "^(\\*<<|:).*", "indentOpenBrackets": "...
#%% """ - Lonely Pixel I - https://leetcode.com/problems/lonely-pixel-i/ - Medium """ #%% """ Given a picture consisting of black and white pixels, find the number of black lonely pixels. The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively. A black...
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2022/2/9 17:05 # @Author : Gene Jiang # @File : dict_changan_vehicle.py # @Description: vehicles = [ { "Year": 2021, "Model": "UNI", "Series": "UNI-V", "Make": "Changan" }, { "Year": 2021, "Mode...
""" How to Use this File. participants is a dictionary where a key is the name of the participant and the value is a set of all the invalid selections for that participant. participants = {'Bob': {'Sue', 'Jim'}, 'Jim': {'Bob', 'Betty'}, } # And so on. history is a dictionary where a key is the name of ...
# Source : https://leetcode.com/problems/find-the-highest-altitude/ # Author : foxfromworld # Date : 13/11/2021 # First attempt class Solution: def largestAltitude(self, gain: List[int]) -> int: alt, ret = 0, 0 for g in gain: alt = alt + g ret = max(alt, ret) return...
def type_I(A, i, j): # Swap two rows A[i], A[j] = np.copy(A[j]), np.copy(A[i]) def type_II(A, i, const): # Multiply row j of A by const A[i] *= const def type_III(A, i, j, const): # Add a constant times row j to row i A[i] += const*A[j]
class Justifier: def justify(self, textIn): width = max(map(len, textIn)) return map(lambda s: s.rjust(width), textIn)
tournament = input() total_played = 0 total_won = 0 total_lost = 0 while tournament != "End of tournaments": games_per_tournament = int(input()) games_counter = 0 total_played += games_per_tournament for games in range(1, games_per_tournament + 1): desi_team = int(input()) other_team ...
class Bootstrap: '''Essential bootstrap cross validator, consistent with other splitter classes in sklearn.model_selection. Example: boot = Bootstrap(n_bootstraps = 3, random_state=1) for train, test in boot.split(X): print("Train:", X[train]," Test:", X[test]) ''' def __ini...
CHECKPOINT = 'model/checkpoint.bin' MODEL_PATH = 'model/model.bin' input_path = 'input/train.csv' LR = 0.01 scheduler_threshold = 0.001 scheduler_patience = 2 scheduler_decay_factor = 0.5 embed_dims = 128 hidden_dims = 128 num_layers = 1 bidirectional = False dropout = 0.2 out_dims = 128 Batch_Size = 64 Epochs = 100...
BASE_URL = "https://www.zhixue.com" # BASE_URL = "http://localhost:8080" INFO_URL = f"{BASE_URL}/container/container/student/account/" # Login SERVICE_URL = f"{BASE_URL}:443/ssoservice.jsp" SSO_URL = f"https://open.changyan.com/sso/login?sso_from=zhixuesso&service={SERVICE_URL}" CHANGE_PASSWORD_URL = f"{BASE_URL}/por...
print('----------------------------------------') print('PROCURANDO ALGARISMOS VIZINHOS IGUAIS...') print('----------------------------------------\n') print('Vamos brincar de detetive de algarismos?') x = input('s/n: ') if x == 'n': print('Então vai tomar no cu e chupar meu piru ..|.,') else: print('Ok! Vamo...
debug_defs = select({ "//:debug-ast": ["DEBUG_AST"], "//conditions:default": [] }) + select({ "//:debug-bindings": ["DEBUG_BINDINGS"], "//conditions:default": [] }) + select({ "//:debug-ctors": ["DEBUG_CTORS"], "//conditions:default": [] }) + select({ "//:debug-filters": ["DEBUG_FILTER...
# -*- coding: utf-8 -*- """ ASGI """
_prefix = 'MC__' JOB_DIR_COMPONENT_PATHS = { 'job_key': _prefix + 'JOB_KEY', 'job_meta': _prefix + 'JOB_META.json', 'job_spec': 'job_spec.json', 'entrypoint': 'entrypoint.sh', 'work_dir': 'work_dir', 'executed_checkpoint': _prefix + 'EXECUTED', 'completed_checkpoint': _prefix + 'COMPLETED',...
p=int(input('enter the principal amount')) n=int(input('enter the number of year')) r=int(input('enter the rate of interest')) d=p*n*r/100 print('simple interest=',d)
''' 删除二叉搜索树中的节点 给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。 返回二叉搜索树(有可能被更新)的根节点的引用。 一般来说,删除节点可分为两个步骤: 首先找到需要删除的节点; 如果找到了,删除它。 说明: 要求算法时间复杂度为 O(h),h 为树的高度。 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val ...
def add_to_parser(parser): parser.add_argument("-c", "--channel", type=str, dest="channel", help=""" If the CAN interface supports multiple channels, select which one you are after here. For example on linux this might be 1 ...
c = get_config() c.NotebookApp.ip = '{{IPYTHON_NB_LISTEN_ADDR}}' c.NotebookApp.port = {{IPYTHON_NB_LISTEN_PORT}} c.NotebookApp.open_browser = False c.NotebookApp.notebook_dir = u'{{IPYTHON_NB_DIR}}' c.NotebookApp.base_url = '{{HTTP_BASE_URL}}/{{IPYTHON_NB_PREFIX}}' c.NotebookApp.tornado_settings = {'static_url_prefix...
class Solution: def XXX(self, intervals: List[List[int]]) -> List[List[int]]: res=[] intervals.sort() res.append(intervals[0]) for i in range(1,len(intervals)): t=res[-1] if intervals[i][0]<=t[1]: res[-1][1]=max(intervals[i][1],res[-1][1]) ...
# Construa agora um algoritmo para implementação de um Pilha. Lembrando que na Pilha o último # elemento adicionado, será o primeiro elemento removido. class No: def __init__(self, dado): self.dado = dado self.proximo = None #valor nulo
#!/usr/bin/env python print("Hello World!") # commnads # $python hello.py # Hello World! # $python hello.py > output.txt # if file exists, old file is deleted, new file created with same name # if file doesn't exits, then new file is created # $python hello.py >> output.txt # if file exists, then result is appended...
n = int(input('\033[3;30;32mDigite um número para ver a sua tabuada: \033[m')) print('''--------------- {} x 1 = {} {} x 2 = {} {} x 3 = {} {} x 4 = {} {} x 5 = {} {} x 6 = {} {} x 7 = {} {} x 8 = {} {} x 9 = {} {} x 10 = {} ---------------'''.format(n, n, n, (n*2), n, (n*3), n, (n*4), n, (n*5), n, (n*6), n, (...
#!/usr/bin/env python3 def solution(n: int, a: list) -> list: """ >>> solution(5, [3, 4, 4, 6, 1, 4, 4]) [3, 2, 2, 4, 2] """ counters = [0] * n max_counter = n + 1 cur_max = 0 for num in a: if num == max_counter: counters = [cur_max] * n else: co...
nota1 = float(input('Digite a Primeira Nota: ')) nota2 = float(input('Digite a Segunda Nota: ')) n = (nota1 + nota2) / 2 print(f'Você tirou {n}') if n < 5.0: print('REPROVADO:') elif n > 6.9: print('APROVADO') else: print('RECUPERAÇÃO')
# Separate the construction of a complex object from its # representation so that the same construction process can create different representations. # Parse a complex representation, create one of several targets. # Allows you to build different kind of object by implementing the Steps, # to build on particular objec...
""" Contains modules related to the import of the data and formatting of the target Modules : - Start - Encode_Target """ __all__ = ['Load', 'Encode_Target']
""" 0914. X of a Kind in a Deck of Cards Easy In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where: Each group has exactly X cards. All the cards in each group have the same...
def dict_extract(value, var, ret_dict=None): """Search a list of nested dictionaries Args: value(obj): Object being searched for var(iterable): iterable containing dictionaries or lists ret_dict(dict): Highest depth dictionary containing value Yield: Dictionary containing d...
""" 16. 3Sum Closest Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. My opnion: I searched the internet for what the problem means. I ...
def high_and_low(numbers): # In this little assignment you are given a string of space separated numbers, # and have to return the highest and lowest number. result = [int(x) for x in numbers.split()] string = str(max(result)) + " " + str(min(result)) return string print(high_and_low("4 5 29 54 4 ...
class Clustering: def __init__(self): self._cluster = {} def _query(self, jpt): return self._cluster[jpt]
# https://codeforces.com/problemset/problem/705/A n = int(input()) love = 'I love it' hate = 'I hate it' result = '' if n == 1: print('I hate it') else: for num in range(1, n + 1): if num == n: if num % 2 != 0: result += hate else: result += lov...
#!/usr/bin/python S = input() P_score= S.split(" ") #print (S) for i in range (0,len(P_score)): P_score[i]= int(P_score[i]) List_J=[1 for m in range(0,len(P_score))]## set default List_J as "1" for i in range(0,(len(P_score)-1)): if P_score[i] < P_score[i+1]: List_J[i+1] = List...
"""A series of modules containing dictionaries that can be used in run.py""" def test_movie_set_1(): movie1 = { "name": "Apollo11", "rating": "G", "genre": "documentary", "length": 93 } movie2 = { "name": "Cars", "rating": "G", "genre": ...
# June 2021 # Author: J. Rossbroich """ misc.py Contains functions used by the adelie package """ def getattr_deep(obj, attrs): """ Like getattr(), but checks in children objects Example: X = object() X.Y = childobject() X.Y.variable = 5 getattr(X, 'Y.variable') -> Attri...
''' Contains keyword arguments and their default values for workflows. Used to auto-complete arguments that are missing in submitted workflows. Workflow items with all the given arguments are then parsed into actual Celery workflows by the workflow designer. 2020 Benjamin Kellenberger ''' ...
feed_template = ''' <html> <head> <title>Carbon Black {{integration_name}} Feed</title> <style type="text/css"> A:link {color: black;} A:visited {color: black;} A:active {color: black;} A:hover {underline; color: #d02828;} </style> <style> #config { font-family:"Trebuchet...
x=[9,2,10,1,-1,0,0,1] for i in range(len(x)-1): for j in range(len(x)-1): if x[j] > x[j+1]: x[j],x[j+1] = x[j+1],x[j] print(x) x=input() y={} for i in range(len(x)): if not x[i] in y : y[x[i]]=0 y[x[i]]+=1 print(y) x=input() y=len(x) y-=1 for i in range(round(len(x)/2)): if not ...
# # PySNMP MIB module IPV4-RIP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPV4-RIP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:45:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
# print "Hello" N times n=int(input()) if n>=0: for i in range(n): print("Hello") else: print("Invalid input")
############################################################################## # # Copyright (C) BBC 2018 # ############################################################################## events = [ { "prodState": "Maintenance", "firstTime": 1494707632.238, "device_uuid": "3cb330f3-afb0-4e25...
# Commodity and Equity Sector mappings sectmap = { 'commodity_sector_mappings':{ '&6A_CCB':('Currencies', 'G10 Currencies', 'G10 Currencies', 'G10 Currencies', 'AUD'), # AUD '&6B_CCB':('Currencies', 'G10 Currencies', 'G10 Currencies', 'G10 Currencies', 'GBP'), # GBP '&6C_CCB':('Currencies',...
# https://app.codesignal.com/arcade/intro/level-1/jwr339Kq6e3LQTsfa # Write a function that returns the sum of two numbers. def add(param1: int = 0, param2: int = 0) -> int: if ( isinstance(param1, int) and isinstance(param2, int) and -1000 <= param1 <= 1000 and -1000 <= param2 <= ...
n=int(input()) cus=[int(input()) for i in range(n)] m=int(input()) price=[int(input()) for i in range(m)] price.sort(reverse=True) cus.sort(reverse=True) answer=0 C,P=0,0 while C<n and P<m: if cus[C]>=price[P]: answer+=price[P] C+=1 P+=1 else: P+=1 print(answer)
# https://adventofcode.com/2021/day/17#part2 def solve(target): (x1, x2), (y1, y2) = target count = 0 for i in range(-1000, 1000): # wew, try bruteforce for j in range(1, x2+1): hit = check(j, i, target) if hit: count += 1 return count def check(a, b, target): (x1, x2), (y1, y2)...
vegetables = [ { "type":"fruit", "items":[ { "color":"green", "items":[ "kiwi", "grape" ] }, { "color":"red", "items":[ "str...
__all__ = ["reservation", "user_info", "calendar"] for _import in __all__: __import__(f"{__package__}.{_import}")
# Generated by h2py from Include\scintilla.h # Included from BaseTsd.h def HandleToUlong(h): return HandleToULong(h) def UlongToHandle(ul): return ULongToHandle(ul) def UlongToPtr(ul): return ULongToPtr(ul) def UintToPtr(ui): return UIntToPtr(ui) INVALID_POSITION = -1 SCI_START = 2000 SCI_OPTIONAL_STA...
# # @lc app=leetcode id=970 lang=python3 # # [970] Powerful Integers # # @lc code=start class Solution(object): def powerfulIntegers(self, x, y, bound): """ :type x: int :type y: int :type bound: int :rtype: List[int] """ r = [] if bound < 2: ...
class Environment(): """ This is used as an input to contruct the graph. """ def __init__(self, names, matrix, alpha, prop): self.names = names # Names of Subclone Colony (List) self.relations = matrix # Adj Matrix representing relations self.alpha = alpha self.pro...
"""Toyota Connected Services API exceptions.""" class ToyotaLocaleNotValid(Exception): """Raise if locale string is not valid.""" class ToyotaLoginError(Exception): """Raise if a login error happens.""" class ToyotaInvalidToken(Exception): """Raise if token is invalid""" class ToyotaI...
#Split string = "Teste de split dividindo por espaço" lista = string.split(' ') print(lista) for valor in lista: print(valor) juntarLista = ' '.join(lista) #juntando lista print(juntarLista) for indice , valor in enumerate(lista): print(indice , valor)
""" 警察vs土匪 """ class Gun(object): def __init__(self, model, damage): # 型号 self.model = model # 杀伤力 self.damage = damage # 子弹数量,默认为0 self.bullet_count = 0 # 重写str def __str__(self): return "型号:%s, 杀伤力:%s, 子弹数量:%s" % ( self.model, sel...
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/1296/A def odd(a,n): odd1 = a[0]%2 if odd1==1 and n%2==1: return 'YES' for i in range(1,n): if a[i]%2 != odd1: return 'YES' return 'NO' t = int(input()) for _ in range(t): n = int(input()) al = l...
def play_game(turns, start, nodes, max_cup_label): current_cup = start_label move = 0 while move < turns: # Snip out a sub graph of length 3 sub_graph_start = nodes[current_cup] pickup = [] cur = sub_graph_start for _ in range(3): pickup.append(cur) ...
# # @lc app=leetcode id=708 lang=python3 # # [708] Insert into a Sorted Circular Linked List # # https://leetcode.com/problems/insert-into-a-sorted-circular-linked-list/description/ # # algorithms # Medium (31.27%) # Likes: 269 # Dislikes: 283 # Total Accepted: 32K # Total Submissions: 102.5K # Testcase Example: ...
listTotal = [] listPar = [] listImpar = [] for c in range(1, 21): n = int(input("Digite um numero: ")) if n % 2 == 0: listTotal.append(n) listPar.append(n) else: listImpar.append(n) listTotal.append(n) print(f'{listTotal}\n{listPar}\n{listImpar}')
# -*- coding:utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Lice...
# Copyright (c) 2018 Huawei Technologies Co., Ltd. # 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 # # ...
# Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rt...
# -*- coding: utf-8 -*- """ @author: krakowiakpawel9@gmail.com @site: e-smartdata.org """ class Czlowiek: def __init__(self, imie, nazwisko): self.imie = imie self.nazwisko = nazwisko def info(self): print(f'{self.imie} {self.nazwisko}') class Pilkarz(Czlo...
# Задача 4. Вариант 45. # Напишите программу, которая выводит имя, под которым скрывается Борис Николаевич Кампов. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). Для хранения всех...
class A: def f1(self): print("F1 is working") def f2(self): print("F2 is working") class B(): def f3(self): print("F3 is working") def f4(self): print("F4 is working") class C(A,B): #Multiple Inheriatance def f5(self): print("F5 is working") a1=A() a1....
''' x=5 def verificar(): listaNomes=[''] while True: if x==0: listaNomes= [input(print("Digite um nome: "))] x-=1 else: print("Obrigado") break verificar() print(listaNomes) ''' #Variáveis em funções #Variáveis -> Globais...
# Input Cases t = int(input("\nTotal Test Cases : ")) for i in range(1,t+1): print(f"\n------------ CASE #{i} -------------") n = int(input("\nTotal Items : ")) m = int(input("Max Capacity : ")) v = [int(i) for i in input("\nValues : ").split(" ")] w = [int(i) for i in input("Weights : ").split(" ")] # Ta...
# https://www.hackerrank.com/challenges/candies/problem n = int(input()) arr = [int(input()) for _ in range(n)] candies = [1] * n for i in range(1, n): if arr[i - 1] < arr[i]: candies[i] = candies[i - 1] + 1 for i in range(n - 2, -1, -1): if arr[i + 1] < arr[i]: if i - 1 >= 0 and arr[i - 1] <...
"""A simple example for how to replace the provided artifact macro""" load("@mabel//rules/maven_deps:mabel.bzl", "artifact") def g_artifact(coordinate): return artifact(coordinate = coordinate, repositories = ["https://maven.google.com/"], type = "naive")
class DataFragment(object): def length(self): return 0; class ConstDataFragment(object): def __init__(self, name, data): self.data = data self.name = name def length(self): return len(self.data) class ChoiceDataFragment(object): def __init__(self): pass ...
#https://www.acmicpc.net/problem/1259 #자릿수 1개, 짝수개 홀수개 while True: n = input() if n == '0': break isPal = True for i in range(len(n)//2): if n[i] == n[-(i+1)]: continue else: isPal = False break if isPal: print('yes') else: ...
""" There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the maze, the bal...
class HttpStyleUriParser(UriParser): """ A customizable parser based on the HTTP scheme. HttpStyleUriParser() """
# -*- coding: utf-8 -*- """ Created on Mon Feb 5 19:13:44 2018 @author: farhan """ def draw(n): if n == 1: print(''' ------ | | | | ------ ''') if n ==2: print(''' ...
class SecretsManager: _boto3 = None _environment = None _secrets_manager = None def __init__(self, boto3, environment): self._boto3 = boto3 self._environment = environment if not self._environment.get('AWS_REGION', True): raise ValueError("To use secrets manager you ...
# coding: utf-8 #----------------------------------------------------------------- # Um programa que recebe o sexo de uma pessoa mas só # aceite os valores 'M' 'F'. Caso esteja errado o programa # deverá pedir a digitação até receber um valor correto. #----------------------------------------------------------------...
''' Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, dig...
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_Pbr_01_ape.py" OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AdamW_ClipGrad_AvgMaxMin_lmPbr_SO/cat" DATASETS = dict(TRAIN=("lm_pbr_cat_train",), TEST=("lm_real_cat_test",)) # bbnc10 # objects cat Avg(1) # ad_2 21.06 21.06 #...
# -*- coding: utf-8 -*- # index.urls def make_rules(): return [] all_views = {}
data = input() forum_dict = {} while not data == 'filter': topic = data.split(' -> ')[0] hashtags = data.split(' -> ')[1].split(', ') if topic in forum_dict.keys(): forum_dict[topic].extend(hashtags) else: forum_dict[topic] = hashtags data = input() hashtags_reg = input().split(', ...
def fector(x: int): if x == 0: return 1 else: return x * fector(x - 1) N = int(input()) print(fector(N))
a = 0 while a <= 10: print(a) a = a + 1 if True: pass # Operadores de comparação # Retorna verdadeiro (True) e falso (False) # igualdade (==) # atribuição (=) # diferenciação (!=) # marioridade (>) # maior e igual (>=) # menor e igual (<=)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 判断列表的所有数是否是素数(函数式) 将所有素数的元素打印为字典(函数式) author: gxcuizy date: 2018-10-19 """ def is_prime(num_list): """判断列表的数字是否为素数""" prime_result = [] for number_val in num_list: # 判断是否为素数 prime_status = get_is_prime(number_val) # 结果添加到列表中 ...
filename=os.path.join(path,'Output','Data','xls','WALIS_spreadsheet.xlsx') print('Your file will be created in {} '.format(path+'/Output/Data/')) ###### Prepare messages for the readme ###### # First cell date_string = date.strftime("%d %m %Y") msg1='This file was exported from WALIS on '+date_string # Second cell msg...
board_bounding_box = [[[-1245, -795], [-410, 310], [-455, 500.0]],\ [[-1245, -795], [-410, 310], [-545, 500.0]],\ [[-1245, -595], [-410, 310], [-585, 500.0]],\ [[-1345, -595], [-410, 310], [-642, 500.0]]] min_point_before_moving = [[-1245, -354.048022, -417],\ [-1201.1969772, -300...
"""Semantic versioning for the package qtools3.""" VERSION = (0, 3, 6) __version__ = '.'.join(map(str, VERSION))
class Door: status = 'undefined' def __init__(self, number, status, lock): self.number = number self.status = status self.lock = lock def open(self): """Door opened""" if self.lock == 'unlocked': self.status = 'opened' def close(self): """Do...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/icefire/ws/src/gscam/include;/usr/include/gstreamer-1.0;/usr/include/glib-2.0;/usr/lib/aarch64-linux-gnu/glib-2.0/include".split(';') if "/home/icefire/ws/src/gscam/include;/usr/include/gstreamer...
_NORMALIZING_FLOWS = {} class RegisterFlow(object): """Decorator to registor NormalizingFlow classes. Parameters ---------- flow_cls_name : str name of the NormalizingFlow class. This will be used in the `get_flow` method as the key for the class. Usage ----- >>> @flow_li...
n = int(input()) ans = (n * (n + 1)) // 2 ans = 4 * ans ans = ans - 4 * n ans = 1 + ans print(ans)
# # -*- coding: utf-8 -*- # # Copyright 2015-2020 NETCAT (www.netcat.pl) # # 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 a...
# ------------------------------ # 486. Predict the Winner # # Description: # Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be availabl...
def power_supply(network: list[list], plant: dict, lis=None) -> set: if not lis: lis = [] net = network.copy() for key, value in plant.items(): for [a, b] in tuple(net): if key in [a, b]: net.remove([a, b]) if value > 0: lis.append(a if...
# 6. (Função sem retorno com parâmetro) Faça uma função/método para a partir de um valor inicial e um valor final realizar o acumulo desse valores e apresentar o resultado. Não use vetor. Aqui deverá ocorrer para as duas variáveis, PASSAGEM DE PARÂMETRO POR VALOR. def somar(a, b): soma = a while a < b: a = a +...
class Contact: all_contacts = [] def __init__(self, name, email): self.name = name self.email = email Contact.all_contacts.append(self) class Supplier(Contact): def order(self, order): print("if this were a real system we would send " f"{order} order to {self.name}")
# 将一些姓名存储在列表中 names = ["Yang yahu","Gao tong","Hu jin","LI liusheng"] # 创建消息 message_0 = names[0] + "!" + "Youth is not a time of life; it is a state of mind; it is not a matter of rosy cheeks, red lips and supple knees; it is a matter of the will, a quality of the imagination, a vigor of the emotions; it is the fresh...
''' Created on Oct 22, 2018 @author: casey ''' class Segment(object): # # * Segments make up the tree. There is a base segment, then a root segment, then the tree expands into internal segments, until it gets to leaf segments. # * These segment types make it easier to traverse the tree during b...
class SingleLinkedNode: def __init__(self, datum): """Node in a single linked list :param datum: the datum associated with this node """ self.next_node = None self.datum = datum def __str__(self): return "datum={}; next={}".format( self.datum, ...
num = int(input("enter the number")) for i in range(2,num): if num%i==0: print("not prime") break else: print("prime")
class TicTacToe: def __init__(self): self.tab = ['.','.','.','.','.','.','.','.','.','.'] def curr_state(self): #obecny stan tablicy return ''.join(self.tab) def postaw_znak_o(self, x, y): #interfejs dla stawiania znaku przez gracza if x < 0 or x > 2 or y < 0 or y > 2 or...
ERR_EXCEED_LIMIT = "Not enough space" class NotEnoughSpace(Exception): pass