content
stringlengths
7
1.05M
# Accept one int and one float type value & display average a = int(input("Enter int no.: ")) b = float(input("Enter float no.: ")) c = (a+b)/2 print(f"Average value {c}")
class Solution: def minimizeError(self, prices: List[str], target: int) -> str: # A[i] := (costCeil - costFloor, costCeil, costFloor) # the lower the costCeil - costFloor, the cheaper to ceil it A = [] sumFloored = 0 sumCeiled = 0 for price in map(float, prices): floored = math.floor(pr...
# GENERATED VERSION FILE # TIME: Mon Oct 11 04:02:23 2021 __version__ = '1.2.0+f83fd55' short_version = '1.2.0' version_info = (1, 2, 0)
# -*- coding: utf-8 -*- # goma # ---- # Generic object mapping algorithm. # # Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk] # Version: 0.2, copyright Wednesday, 18 September 2019 # Website: https://github.com/sonntagsgesicht/goma # License: Apache License 2.0 (see LICENSE file) class B...
class InvalidServiceBusMessage(Exception): """ Raised when a message is not valid """ def __init__(self, reason='InvalidServiceBusMessage', description='The received message is not valid') -> None: self.reason = reason self.description = description super().__init__(self.reason)...
""" class attribute class method static method """ class Person: number_of_people = 0 def __init__(self, name) -> None: self.name = name Person.number_of_people += 1 Person.add_person() @classmethod def add_person(cls): cls.number_of_people + 1 @classmetho...
values = input("Enter comma separated values: ") list = values.split(",") tuple = tuple(list) #this is a forked branch print("list: {}".format(list)) print("tuple: {}".format(tuple))
def add_replicaset(instance, alias, roles, servers, status='healthy', all_rw=False, weight=None): r_uuid = '{}-uuid'.format(alias) r_servers = [] for s in servers: # servers = ['alias-1', 'alias-2'] r_servers.append({ 'alias': s, 'uuid': '{}-uuid'.format(s...
""" __version__.py ~~~~~~~~~~~~~~ Information about the current version of the street-situation-detection package. """ __title__ = 'street-detection' __description__ = 'street-detection - A python package for detecting streets' __version__ = '0.1.0' __author__ = 'Steven Mi' __author_email__ = 's0558366@htw-berlin.de'...
DEBUG = True SECRET_KEY = "kasih-tau-gak-ya" BUNDLE_ERRORS = True MONGO_HOST = 'mongo' MONGO_DBNAME = 'news-api' MONGO_PORT = 27017 JSONIFY_PRETTYPRINT_REGULAR = False
class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: ''' T: O(n log n), n = number of words S: O(n) ''' for punc in "!?',;.": paragraph = paragraph.replace(punc, ' ') words = paragraph.lower().strip().split() ...
# configuration file TRAINING_FILE_ORIGINAL = '../mnist_train.csv' TRAINING_FILE = '../input/mnist_train_folds.csv' TESTING_FILE = '../input/mnist_test.csv' MODEL_OUTPUT = "../models/"
# -*- coding: utf-8 -*- """ Created on Fri Jun 21 10:17:27 2019 @author: Administrator """ #class Solution: # def superPow(self, a: int, b: list) -> int: # B = 0 # b.reverse() # for k in range(len(b)): # B += b[k] * 10 ** k # # A = a**B#self.pow(a, B)# # ## ...
# -*- coding: utf-8 -*- class MunicipalityRecord(object): """ The base document class. Args: fosnr (int): The unique id bfs of the municipality. name (unicode): The zipcode for this address. published (bool): Is this municipality ready for publishing via server. logo (pyra...
"""The :func:`deephyper.nas.run.quick.run` function is a function used to check the good behaviour of a neural architecture search algorithm. It will simply return the sum of the scalar values encoding a neural architecture in the ``config["arch_seq"]`` key. """ def run(config: dict) -> float: return sum(config['a...
__all__ = [ "BoundHandler", "ClassHook", "Handler", "Hook", "Hookable", "HookableMeta", "HookDescriptor", "InstanceHook", "hookable", ]
class gen_config(object): vocab_size = 35000 train_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/" data_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/" buckets = [(5, 10), (10, 15), (20, 25), (40, 50)]
""" Problem Given two rectangles, determine if they overlap. The rectangles are defined as a Dictionary: r1 = { # x and y coordinates of the bottom-left corner of the rectangle 'x': 2, 'y': 4, # Width and Height of rectangle 'w': 5, 'h': 12 } If the rectangles do overlap, return the dictionary which de...
#!/usr/bin/env python # Assumption for the star format: # contain one or more 'data_*' blocks, for each block, # either ''' data_* loop_ item1 #1 ... itemn #n item1_data ... itemn_data ... item1_data ... itemn_data ''' # or ''' data_* item1 item1_data ... itemn itemn_data ''' def star_data(star): # return 2 d...
def get_book_info(book_id, books): """Obtain meta data of certain books. :param book_id: Books to look up :type: int or list of ints :param books: Dataframe containing the meta data :type: pandas dataframe :return: Meta data for the book ids :rtype: List[str], List[str], List[str] "...
""" 백준 24356번 : ЧАСОВНИК """ t1, m1, t2, m2 = map(int, input().split()) start = t1 * 60 + m1 end = t2 * 60 + m2 if start > end: end += 24 * 60 print(end-start, (end-start) // 30)
# # PySNMP MIB module TRANGOP5830S-RU-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGOP5830S-RU-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:19:36 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
class CarrinhoCompras: def __init__(self): self.produtos = [] def insere_produto(self, produto): self.produtos.append(produto) def lista_produtos(self): for produto in self.produtos: print(produto.nome, produto.valor) def soma_total(self): total = 0 ...
# Sage version information for Python scripts # This file is auto-generated by the sage-update-version script, do not edit! version = '8.3.beta3' date = '2018-05-27'
class Judge: PAPER_LIMIT = 7 def __init__( self, judge_id, first, last, email, phone, preferred_categories, is_paper_reviewer, presentation_availability, ): self.judge_id = judge_id # int self.first = first # str ...
# 单向循环链表 class CircularLinkedList(object): class __Node: def __init__(self, item, next=None): self.item = item self.next = next def __init__(self): self._head = None def is_empty(self): return self._head is None def add(self, item): node = Ci...
class dispatcher: name = 'dispatcher' def __init__(self, function_to_exec): self.function = function_to_exec return self.function def get_name(self): return self.name def function_one(a,b): return a + b def function_two(): return 'function two'
""" ice_pick.exceptions ~~~~~~~~~~~~~~~~~~~ This module implements contains the Ice Pick exceptions. Copyright 2014 Demand Media. 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 h...
class UniformExchange(object): def __init__(self, A): if not isinstance(A, (float, int)) or A <= 0: raise ValueError('Exchange constant must be positive float/int.') else: self.A = A def get_mif(self): # Create mif string. mif = '# UniformExchange\n' ...
""" Listas Aninhadas (Nested Lists) - Algumas linguagens de programação (C/Java) possuem uma estrutura de dados chamadas de arrays: - Unidimensionais (Arrays/Vetores); - Multidimensionais (Matrizes); Em Python nós temos as Listas numeros = [1, 'b', 3.234, True, 5] print(listas) print(type(listas)) # Como...
''' 第一个 % 后面的内容为显示的格式说明,6 为显示宽度,3 为小数点位数,f 为浮点数类型 第二个 % 后面为显示的内容来源,输出结果右对齐,2.300 长度为 5,故前面有一空格 ''' print("%6.3f" % 2.3) # 2.300 ''' x 为表示 16 进制,显示宽度为 10,前面有 8 个空格。 ''' print("%+10x" % 10) # +a ''' %s 字符串 (采用str()的显示) %r 字符串 (采用repr()的显示) %c 单个字符 %b 二进制整数 %d 十进制整数 %i 十进制整数 %o 八进制整数 %x ...
# model model = Model() i1 = Input("op1", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}, 0.8, 5") i2 = Output("op2", "TENSOR_QUANT8_ASYMM", "{1, 3, 3, 1}, 0.8, 5") w = Int32Scalar("width", 3) h = Int32Scalar("height", 3) model = model.Operation("RESIZE_BILINEAR", i1, w, h).To(i2) # Example 1. Input in operand 0, input0 = {i1: ...
def add(a, b): print(f"ADDING {a} + {b}") return a + b def subtract(a, b): print(f"SUBTRACTING {a} - {b}") return a - b def multiply(a, b): print(f"MULTIPLYING {a} * {b}") return a * b def divide(a, b): print(f"DIVIDING {a} / {b}") return a / b a = float(input("input a:")) b = float(...
# Description: Pass Statement in Python # Pass statement in for loop for var in range(5): pass # Pass statement in a while loop while True: pass # Busy-wait for keyboard interrupt (Ctrl + C) # This is commonly used for creating minimal classes: class MyEmptyClass: pass # Pass can also be ...
number_dict = { "0" : { "color" : (187,173,160), "font_size" : 45, "backgroud_color" : (205,193,180), "coordinate" : [(0,0), (0,0), (0,0), (0,0)] }, "2" : { "color" : (119, 110, 101), "font_size" : [70, 60, 50, 40], "backgroud_color" : (238, 228, 218), "coordinate" : [(40,10), (30,3), (25,2), (22,3)] }, "4...
""" Install the latest Windows binary wheel package from PyPI """ def install_gitfat_win(): """ Install the latest Windows binary wheel package from PyPI """ # TODO: Parse all available packages through PyPI Simple: # https://pypi.python.org/simple/git-fat/ raise NotImplementedError("TODO: Insta...
""" Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \\ / \\ 2 3 2 3 [1,2,3], [1,...
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ First = ['Q','W','E','R','T','Y','U','I','O','P'] SEC = ['A','S','D','F','G','H','J','K','L'] LAST= ['Z','X','C','V','B','N','M'] answer = [] f...
def eqindexMultiPass(data): "Multi pass" for i in range(len(data)): suml, sumr = sum(data[:i]), sum(data[i+1:]) if suml == sumr: yield i
## # 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。 # 这个地区只有一个入口,我们称之为“根”。 # 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。 # 一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 # 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。 # # 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。 # # 示例 1: # # 输入: [3,2,3,null,3,null,1] # # 3 # / \ # 2 3 # \ \ # 3 1 #...
class languages(): def __init__(self, fDic): self.fDic = fDic self.scripts = set(self.fDic.scripts) self.scripts.discard('dflt') def languageSyntax(self, script, language): return 'languagesystem %s %s;' %(script, language) def syntax(self): result = [self.language...
n = int(input()) for i in range(1,n+1): temp = n for j in range(1,i): print(temp,end="") temp = temp -1 for j in range(1,(2*n) - (2*i) + 2): print(n-i+1,end="") for j in range(1,i): temp = temp+1 print(temp,end="") print() for i in range(n-1,0,-1): temp ...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for i in range(len(s)): if s[i]=='(' or s[i]=='[' or s[i]=='{': stack.append(s[i]) elif s[i] == ')': if len(stack)>0 and ...
class Solution: def shortestPalindrome(self, s: str) -> str: temp = s + '#' + s[::-1] i = 1 l = 0 lps = [0] * len(temp) while i < len(temp): if temp[i] == temp[l]: lps[i] = l + 1 i += 1 l += 1 elif l != 0...
class Solution: """ @param nums: a list of integers @return: return a integer """ def singleNonDuplicate(self, nums): n = len(nums) l = 0 r = n - 1 while l < r: mid = l + (r - l) // 2 p1 = p2 = mid if mid > 0 and nums[mid] == nums[m...
l1 = [1, 3, 5, 7, 9] # list mutable (read write) t1 = (1, 3, 5, 7, 9) # tuple imutable (read only) def f(x): x.append(29) f(l1) print(l1) f(t1) print(t1)
# -*- coding: utf-8 -*- # Copyright © 2021 Michal K. Owsiak. All rights reserved. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTH...
""" Format for midterms(usually) and concepts tested 1. Tracing - higher order functions(*), function scope 2. Iteration/Recursion - Order Of Growth, writing iteration or recursion """ ################## #Order of Growth # ################## n = 100000000 k = 40000 """ Lists """ x = [i for...
# A list contains authorized users' discord IDs. OWNER = 184335517947658240 # foxfair # Staff AUTHORIZED = [ OWNER, 129405976020385792, # Auri 423991805156261889, # Kim 699053180079702098, # Gelica 266289895415218177, # Yang 294058604854509589, # Giana 107209352816914432, # Tooch ...
number = [i for i in range(1, 3001330+1)] # number = [i for i in range(1, 10)] number2 = number[:] last = len(number) % 2 != 0 while len(number) > 1: next_last = len(number) % 2 != last number = [j for i, j in enumerate(number) if i % 2 != last] last = next_last print('#1', number[0]) number = number2 ...
class PagingModifier: def __init__(self, Id: int = None, End: int = None, Start: int = None, Limit: int = None, ): self.Id = Id self.Start = Start self.End = End self.Limit = Limit
employee_file=open("employee.txt","w") #write mode- erases previous content employee_file.write("David - Software Developer") print(employee_file.readable()) #print(employee_file.read()) employee_file.close() #David - Software Developer # previous data and content is vanished
# Copyright 2020 The Cross-Media Measurement Authors # # 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 ...
# Copyright 2021 IBM 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 agreed t...
__author__ = 'Lena' class Group: def __init__(self, name, header, footer): self.name=name self.header=header self.footer=footer
TICKET_PRODUCTS = ''' query getTicketProducts { tutorialProducts { id type name nameKo nameEn desc descKo descEn warning warningKo warningEn startAt finishAt total remainingCount isSoldOut owner { profile { name nameKo n...
""" International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..","."...
# This resets variables every time the Supreme While Loop is reset # If you tried to mess around with this code, you'll find results/errors on the second time the While Loop is executed # Messing with this code will generally not break anything on the first topic that Indra talks About yesnorep = True ignoreinteract =...
""" 파일 이름 : 5063.py 제작자 : 정지운 제작 날짜 : 2017년 6월 23일 프로그램 용도 : 광고를 해야하는지 분석한다. """ # 입력 tc = int(input()) # tc의 수만큼 반복 for i in range(tc): # 입력 strList = input().split(' ') noAdProfit = int(strList[0]) adProfit = int(strList[1]) adCost = int(strList[2]) # 계산 및 출력 if noAdProfit > adProfit - adCost: print("do...
class AbstractRemoteDatabase(object): """ Abstract base class which all remote database connections must inherit from Defines the public interface of any implementation """ def connect(self, **kwargs): """Connect to the course info database """ raise NotImplementedErro...
__author__ = "Lucas Grulich (grulich@uni-mainz.de)" __version__ = "0.0.14" # --- Globals ---------------------------------------------------------------------------------------------------------- MONOSCALE_SHADOWLEVEL = 1 OAP_FILE_EXTENSION = ".oap" DEFAULT_TYPE = "ARRAY2D" SLICE_SIZE = 64 # --- Markers -------------...
# -*- coding: utf-8 -*- class Java(object): KEY = 'java' LABEL = 'Java' DEPENDENCIES = ['java', 'javac'] TEMP_DIR = 'java' SUFFIX = '.java' # javac {class_path} tmp/Estimator.java # class_path = '-cp ./gson.jar' CMD_COMPILE = 'javac {class_path} {src_dir}/{src_file}' # java {cl...
#Dictionaries Challenge 22: Database Admin Program print("Welcome to the Database Admin Program") #Create a dictionary to hold all username:password key-value pairs log_on_information = { 'mooman74':'alskes145', 'meramo1986':'kehns010101', 'nickyD':'world1star', 'george2':'booo3oha', 'admin00':'a...
class Inventory: def __init__(self): self._prisonKeys = False self._sunflowerSeeds = False self._guardiansMoney = False self._guardiansSword = False self._dragonsKey = False @property def prison_keys(self): return self._prisonKeys @prison_keys.setter ...
class Vulnerability: """ Class for representing necessary information about vulnerability. Dictionary is used for storing cvssv2 and cvssv3 because of constant access. cpe_type contains values: 'h' for hardware, 'a' for application, 'o' for operating system. """ def __in...
_close_methods = [] def session_close_method(close_method: callable) -> callable: """ A method that will be automatically called when the session closes. :param close_method: Method to call on session close. :return: The decorated method that will be called on session close. """ _close_met...
class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return None dummy = ListNode(-1) dummy.next = head pre = dummy cur = head while cur: num_dif = 0 dif = cur ## 每次都让dif和cur从同一个点开始 while di...
#!/usr/bin/env python # Copyright 2011 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...
def snail(array): temp_list = [] if array and len(array) > 1: if isinstance(array[0], list): temp_list.extend(array[0]) else: temp_list.append(array[0]) array.pop(0) for lis_index in range(len(array)): temp_list.append(array[lis_index][-1]) ...
def get_scale_factor(input_units, sampling_rate=None): if input_units=='ms': return 1e3 elif input_units=='s': return 1 elif input_units=='samples': if sampling_rate is None: raise ValueError('Must provide sampling_rate if input_units=="samples"') return sampling_...
config = {'luna_raw':'/root/ssd_data/LUNA/', 'luna_data':'/research/dept8/jzwang/dataset/LUNA16/combined/', 'preprocess_result_path':'/research/dept8/jzwang/dataset/HKU/preprocessed/numpy/', 'luna_abbr':'./labels/shorter.csv', 'luna_label':'./labels/lunaqualified_all.csv', ...
#! /usr/bin/python3 # -*- coding:utf-8 -*- """ Define functions relative to bcv. """ def checkBcv(bcv): """Check that a bcv is valid. Valid syntax: BBCCVV BBCCVV-vv BBCCVV-ccvv BBCCVV-BBccvv """ if len(bcv) == 6: return True elif len(bcv) == 9: re...
# https://www.codechef.com/SEPT20B/problems/TREE2 T = int(input()) for _ in range(T): x = input() l = list(map(int, input().split())) s = set(l) m = min(s) ops = len(s) if m: print(ops) else: print(ops-1)
#!/usr/bin/env 2. # -*- config: utf-8 -*- # В строке могут присутствовать скобки как круглые, так и квадратные скобки. Каждой # открывающей скобке соответствует закрывающая того же типа (круглой – круглая, # квадратной- квадратная). Напишите рекурсивную функцию, проверяющую правильность # расстановки скобок в этом слу...
class SessionGenerator(object): session: "TrainingSession" def __init__(self, training_cycle, fatigue_rating, current_training_max): load_size = self.determine_load_size( fatigue_rating, training_cycle.previous_large_load_train...
# -*- coding: utf-8 -*- """ @create: 2019-05-30 22:19:12. @author: ppolxda @desc: """ class Error(Exception): pass class InputError(Error): pass class DuplicateError(Error): pass class IndexExpiredError(Error): pass
DROPS = ((3, 'Pling'), (5, 'Plang'), (7, 'Plong')) def convert(number): """ Converts a number to a string according to the raindrop sounds. """ return "".join(sound for factor, sound in DROPS if number % factor == 0) or str(number)
filename = "CCaseScene.unity" subA = ("<<<<<<< Updated upstream\n") subB = ("=======\n") subC = (">>>>>>> Stashed changes\n") with open(filename, 'r+') as f: data = f.read() count = 0 # Iterate starts while True: # Find indexes start, end = data.index(subA), data.index(subB) # Slice string ...
# New feature in Python 3.8, assignment expressions (known as the walrus operator) # Assignment expression are written with a new notation (:=). This operator is often # called the walrus operator as it resembles the eyes and tusks of a walrus on its side. # # Video explanation: https://realpython.com/lessons/ass...
def solve(): A = int(input()) row = (A + 2) // 3 # from (100 100) to (100+row-1, 100) board = [] for _ in range(1000): board.append([0]*1000) I = J = 100 # [2, 999] for _ in range(1000): print('{} {}'.format(I, J)) I_, J_ = map(int, input().split()) if I_ == 0 and...
deleteObject = True editObject = True getObject = {'id': 1234, 'fingerprint': 'aa:bb:cc:dd', 'label': 'label', 'notes': 'notes', 'key': 'ssh-rsa AAAAB3N...pa67 user@example.com'} createObject = getObject getAllObjects = [getObject]
''' Created on Apr 27, 2015 @author: DHawkins ''' POSITION = [ {'abbrev': 'al', 'column': 7, 'row': 7, 'state': 'alabama'}, {'abbrev': 'ak', 'column': 1, 'row': 8, 'state': 'alaska'}, {'abbrev': 'az', 'column': 2, 'row': 6, 'state': 'arizona'}, {'abbrev': 'ar', 'column': 5, 'row': 6, 'state': 'arkansa...
# A ring buffer is a non-growable buffer with a fixed size. When the ring buffer is full # and a new element is inserted, the oldest element in the ring buffer is overwritten with # the newest element. This kind of data structure is very useful for use cases such as # storing logs and history information, where you typ...
HEADER_JSON_CONTENT = { 'Content-type': 'application/json', 'Accept': 'text/plain' } SUCCESS_MESSAGES = { 201: "Created Propertie: {title} in {provinces} province(s)", } ERROR_MESSAGES = { 422: { 'message': "Please, verify data for register this propertie" }, 404: { 'message': "Pr...
s = float(input('Qual o seu salário atual? R$')) a10 = s * (10/100) a15 = s * (15/100) if s >= 1250: print('Você receberá um aumento de 10%, seu novo salário será de R${:.2f}'.format(s+a10)) else: print('Você receberá um aumento de 15%, seu novo salário derá de R${:.2f}'.format(s+a15))
#!/usr/bin/env python def reverse(string): """Reverse a given string.""" return string[::-1] def main(): print(reverse('a')) print(reverse('abcd')) print(reverse('hello world')) if __name__ == '__main__': main()
jogador = {} soma = 0 gols = [] jogador['nome'] = str(input('Nome do Jogador: ')) jogador['njogos'] = int(input(f'Quanta partidas {jogador["nome"]} Jogou?')) for v in range(0, jogador['njogos']): temp = int(input(f'Quantos gols na partida {v}? ')) soma += temp gols.append(temp) jogador['gols'] = gols[:] p...
""" @file @brief Exceptions. """ class RenderException(Exception): """ Custom exception for all class and functions below. """ pass
# -*- coding: utf-8 -*- # This file is generated from NI-TClk API metadata version 255.0.0d0 functions = { 'ConfigureForHomogeneousTriggers': { 'documentation': { 'description': '\nConfigures the attributes commonly required for the TClk synchronization\nof device sessions with homogeneous trigg...
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' Description: Given an integer, write a function to determine if it is a power of two. Tags: Math, Bit Manipulation O(1) runtime; O(1) space ''' class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool "...
class Lease(object): """ A lease. :ivar id: ID of the lease :ivar ttl: time to live for this lease """ def __init__(self, lease_id, ttl, etcd_client=None): self.id = lease_id self.ttl = ttl self.etcd_client = etcd_client async def _get_lease_info(self, *, keys=Tru...
""" Given a set of complex values, find their product. Example For real = [1, 2] and imag = [1, 3], the output should be arrayComplexElementsProduct(real, imag) = [-1, 5]. The task is to calculate product of 1 + 1 * i and 2 + 3 * i, so the answer is (1 + 1i) * (2 + 3i) = -1 + 5i. """ def arrayComplexElementsProduc...
print(any([True, 1, ""])) print(all([True, 1, ""])) print(dict(zip([1, 2, 3], "abc")))
top = [2,3,4,5,6] # lst = [1,0,0,4,5] lst = [1,2,3,4,5] k = [9,9,0,0,0] lst1 = [8,3,9,6,4,7,5,2,1] lst2 = [10,11,12,8,3,9,6,4,7,5,2,1] lst3 = [8,9,3,6,7,4,5,2,1] lst4 = [8,3,9,6,4,7,5,2,1] k = [9,0,0,0,0,0,0,0] k = k[::-1] def main(): subtract_1(lst1, k) def helper1(lst, start): new_lst = lst[start:] ind...
#João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você fa...
day = '2' with open(f'2015/data/day_{day}.in', 'r', encoding='utf-8') as f: content = f.read().strip().split('\n') def make_tup(row): i = row.index('x') a = row[:i] row = row[i + 1:] i = row.index('x') b = row[:i] c = row[i + 1:] return int(a), int(b), int(c) def area(a, b, c): re...
def translate(): return "jQuery(document).ready(function(){jQuery('body').translate('%s');});" % request.args(0).split('.')[0] def changeLanguage(): session._language = request.args[0] #T.force(request.args[0]) #T.set_current_languages(str(request.args[0]),str(request.args[0]) + '-' + str(req...
def main(): square = int(input("Calculate square root of: ")) print("square root of " + str(square) + " is " + str(binsquareroot(square))) def binsquareroot(square): if square < 1: return "an imaginair number" if square == 1: return 1 left = 1 right = square mid =...
def update_game(api, game, step_fn): """ Takes care of doing one update tick: - call the player's AI - send actions chosen by AI :param api: API object to communicate with the server :param game: The current game's state. :param step_fn: function to call to execute the player's AI ...
# Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. # # Return the quotient after dividing dividend by divisor. # # The integer division should truncate toward zero. # # Example 1: # # Input: dividend = 10, divisor = 3 # Output: 3 # Example 2: # # Inpu...