content
stringlengths
7
1.05M
"""タプル基礎 タプルのアンパックの考え方を用いた要素の交換 [説明ページ] https://tech.nkhn37.net/python-tuple-basic/#i """ data1 = 'A' data2 = 'B' print(f'data1: {data1}, id(data1): {id(data1)}, ' f'data2: {data2}, id(data2): {id(data2)}') # 要素の交換 data1, data2 = data2, data1 print(f'data1: {data1}, id(data1): {id(data1)}, ' f'data2: {dat...
expected_output = { "ip_statistics": { "ip_rcvd_total": 2823, "ip_rcvd_local_destination": 2823, "ip_rcvd_format_errors": 0, "ip_rcvd_checksum_errors": 0, "ip_rcvd_bad_hop": 0, "ip_rcvd_unknwn_protocol": 0, "ip_rcvd_not_gateway": 0, "ip_rcvd_sec_failur...
experiment_ID = "transfer_learning_6" mc_run_number = 50 babbling_time = 3 number_of_refinements = 5 errors_all_A_A = np.zeros([2, number_of_refinements+1, mc_run_number]) errors_all_A_B = np.zeros([2, number_of_refinements+1, mc_run_number]) errors_all_B_B = np.zeros([2, number_of_refinements+1, mc_run_number]) stiff...
__all__ = ['EvaluationDistance'] # Work in progress class EvaluationDistance: def __init__(self): self.arg_map = {} def set_arg_map(self, value): self.arg_map.update(value) def preprocess(self, x): raise NotImplementedError def calculate_distance(self, x1, x2): rais...
salario = float(input()) if salario >= 0 and salario <= 2000: print("Isento") else: valor_ir = 0 if salario > 4500: valor_ir += (salario - 4500) * 0.28 salario = 4500 if salario >= 3000.01 and salario <= 4500: valor_ir += (salario - 3000.01) * 0.18 salario = 3000 ...
############################################################################ # Parse our Dataset # We pass the path to the Input-File and return a INT-Array with # The lines of the Input-File as Entries of the Array ############################################################################ def getReadings(inputFi...
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/Infousa.ipynb (unless otherwise specified). __all__ = ['totemp', 'totemp', 'totemp', 'totemp', 'sml', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'biz1', 'biz1', 'biz1', 'biz1', 'biz1', 'biz2', 'biz2', 'biz2', 'biz2', ...
#!/usr/bin/env python NAME = 'Teros (Citrix Systems)' def is_waf(self): if self.matchcookie(r'^st8id='): return True return False
#/usr/bin/env python # -*- coding: utf-8 -*- def makeSplash(splash, key): """ take as imput the *splash* dictionary and the realtive key to generate a splash page based on the dict keys :param dict splash: :param string key: :return: raw notebok to be rendered as html :rtype: str ...
def mouly(word,num): final = [] for elm in word: for selm in word: fnum = abs(elm-selm) if fnum !=0 and fnum == num: templst = [elm,selm] if templst[::-1] not in final: final.append([elm,selm]) if len(final) >0: ret...
for _ in range(int(input())): f = [] for _ in range(int(input())): s = input().split() if s[1] == 'chirrin' and s[0] not in f:f.append(s[0]) elif s[1] == 'chirrion' and s[0] in f:f.remove(s[0]) f.sort() print('TOTAL') print(*f,sep="\n")
# n = n # time = O(n) # space = O(1) # done time = 20m class Solution: def findTheWinner(self, n: int, k: int) -> int: res = 0 for i in range(1, n + 1): res = (res + k) % i return res + 1
REGIONS = { 'ABC': 'Africa', 'JKLMNPR': 'Asia', 'STUVWXYZ': 'Europe', '123457': 'North America', '6': 'Oceania', '89': 'South America', }
# day_2/if_main.py def example_function(): string = 'Hello' if __name__ == '__main__': print('DEBUG: only want to see this debug if im running this file') return string """ If you check if the current script is the main script you can execute code in it and not have to worry about it executing th...
friends = [] for count in range(3): name = input("Enter friend's name: ") friends.append(name) str_friends = ", ".join(friends) print('Your friends are: ' + str_friends)
def make_me_a_sandwich(): get_bread() get_butter_knife() get_peanut_butter() spread_pb_on_bread() get_bread() get_butter_knife() get_peanut_butter() spread_jelly_on_bread() put_on_other_bread() def cleanup(): print("Put away peanut butter") print("put away jel...
''' Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' i = 0 f = True while (f): i = i + 1 p1 = [c for c i...
'''input 3 4 2 7 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': a = int(input()) b = int(input()) h = int(input()) print(int((a + b) * h / 2))
def path_to_root(node): path = [] while node is not None: path.append(node) node = node.parent return path def lowest_common_ancestor(first, second): '''Finds the lowest common ancestor of two nodes in a binary tree. >>> from utils.binary_tree import Node >>> tree = Node.from_...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-20 Last_modify: 2016-03-20 ****************************************** ''' ''' Find the contiguous subarray within an arr...
def setup(app): app.add_crossref_type( directivename="setting", rolename="setting", indextemplate="pair: %s; setting", ) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
l = list(map(int, input().split())) score = 0 current = 1 for i in l: if i == 0: break elif i == 1: current = 1 score += current else: if current == 1: current = 2 else: current += 2 score += current print(score)
# Config k = 15 # output sampling size count = 100 # experiment times output_type = 1 input_file_path = 'macReversedSample.csv'
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- author by pekingzcc -*- # -*- date : 2017-05-19 -*- """配置文件 """ # 利用一个正则就可以直接采集代理IP的站点 PROXY_SITES_BY_REGX = { 'urls': [ 'http://ab57.ru/downloads/proxyold.txt', 'http://www.proxylists.net/http_highanon.txt', 'http://www.atomintersoft.co...
# Description # Given an unsorted array nums, reorder it in-place such that # # nums[0] <= nums[1] >= nums[2] <= nums[3].... # Please complete the problem in-place. # # Have you met this question in a real interview? # Example # Given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. # Approach #1 ...
# factorial calculation using recursion def calculateFactorial(x): if x == 1: return 1 else: return (x * calculateFactorial(x-1)) num = 20 facorial_number = calculateFactorial(num) print("Factorial of ", num, "is 1 * 2 * 3 * 4 = ", facorial_number)
def oneline(inputArray): return max([inputArray[i]*inputArray[i+1] for i in range(len(inputArray) - 1)]) def expanded(inputArray): ''' EXPLANATION ------------------------------------------------------------------- The previous solution uses a list comprehension that accomplishes the same as b...
def quadratic_f(x): ''' test objective ''' return x[0]**2 + 10 * x[1]**2 + x[0] * x[1] def quadratic_g(x): ''' test constraint g(x) <= 0 ''' return 1 - x[0] - x[1]
''' URL: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons Time complexity: O(nlogn) Space complexity: O(1) ''' class Solution(object): def findMinArrowShots(self, points): """ :type points: List[List[int]] :rtype: int """ if len(points) in (0, 1): ...
DATA = [ ("Load JS/WebAssembly", 2, 2, 2, 2, 2), ("Load /tmp/lines.txt", 225, 222, 218, 209, 202), ("From JS new Fzf() until ready to ....", 7825, 8548, 1579, 2592, 15069), ("Calling fzf-lib's fzf.New()", 1255, 3121, 963, 612, 899), ("return from fzfNew() function", 358, 7, 0, 18, 1), ("sea...
# Copyright (C) 2015 Haruhiko Matsuo <halm.matsuo@gmail.com> # # Distributed under the MIT License. # See accompanying file LICENSE or copy at # http://opensource.org/licenses/MIT """Library of pyproffx"""
""" In this program, we need to copy all the elements of one array into another. This can be accomplished by looping through the first array and store the elements of the first array into the second array at the corresponding position. """ n = int(input("Enter the elements of the array: ")) arr = input() # ...
class Tree: """Abstract base class representing a tree structure.""" # ------------------------ nested Position class ------------- class Position: """An abstraction representing the location of a single element.""" def element(self): """Return the element stored at this Positi...
# Christina Andrea Putri - Universitas Kristen Duta Wacana #Buatlah algoritma dan program yang dapat menentukan jenis tunjangan dan tambahan gaji yang didapat karyawan # Tunjangan anak hanya didapatkan oleh karyawan yang sudah menikah dan memiliki anak # Tunjangan keluarga hanya diberikan kepada karyawan laki-laki yan...
# -*- coding: utf-8 -*- __author__ = 'Stephen Larroque' __email__ = 'LRQ3000@gmail.com' # Definition of the version number version_info = 2, 3, 1 # major, minor, patch, extra # Nice string for the version (mimic how IPython composes its version str) __version__ = '-'.join(map(str, version_info)).replace('-', '.').s...
# 최솟값 만들기(그리디) def solution(a, b): a.sort() b.sort(reverse=True) n = len(a) s = 0 for i in range(n): m = a[i] * b[i] s += m return s a = [1, 4, 2] b = [5, 4, 4] print(solution(a, b))
""" Overview: Meta information for app package. """ #: Title of this project (should be `dgdvapp`). __TITLE__ = "dgdvapp" #: Shown name of this project. __SHOWN_NAME__ = '测试数据生成与分析工具' #: Version of this project. __VERSION__ = "1.0.0" #: Short description of the project, will be included in ``setup.py``. __DESCR...
class Solution: def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ cons=[0,0] for num in nums: if num==1:cons[1]+=1 else:cons[1]=0 cons[0]=max(cons[0],cons[1]) return cons[0]
# Project Euler - Question 2 - Even Fibonacci Numbers # Each new term in the Fibonacci sequence is generated by # adding the previous two terms. By starting with 1 and 2, # the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do # n...
#!/usr/bin/python3 # coding: utf-8 """Válvula de alimentacao""" class ValvulaAlimentacao(): """Válvula de alimentacao""" nivel_maximo = 6.0 nivel_agua = 0 def __init__(self): """ Construtor """ print("Construtor da válvula de alimentação") self.capacidade_vazao = 1.1 s...
def rule(event): return (event['resource'].get('type') == 'gcs_bucket' and event['protoPayload'].get('methodName') == 'storage.setIamPermissions') def dedup(event): return event['resource'].get('labels', {}).get('project_id', '<PROJECT...
# model settings model = dict( type='ResNetTransformer', pretrained=dict( encoder_pretrained=dict( backbone_pretrained='open-mmlab://res2net101_v1d_26w_4s'), decoder_pretrained=dict( transformer_pretrained='Default') ), ffnn_hidden_dims=[512], ffnn_num_layers...
# # PySNMP MIB module CISCOSB-LBD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-LBD-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:22:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
def newton( function, function1, startingInt ): # function is the f(x) and function1 is the f'(x) x_n = startingInt while True: x_n1 = x_n - function(x_n) / function1(x_n) if abs(x_n - x_n1) < 0.00001: return x_n1 x_n = x_n1 def f(x): return (x ** 3) - 2 * x - 5 ...
# This code is licensed under the MIT License (see LICENSE file for details) def _make_command(*elements): return ' '.join(map(str, elements)) def wait_high(pin): return _make_command('wh', pin) def wait_low(pin): return _make_command('wl', pin) def wait_change(pin): return _make_command('wc', pin) ...
lst_of_languages = ['Spanish', 'English', 'Arabic', 'Dutch'] print(lst_of_languages) # Accessing Elements in a List & Using Individual Values from a List. print(f'{lst_of_languages[0]} is my native language.') # Modifying Elements in a List lst_of_languages[-1] = 'French' print(lst_of_languages) # Appending Elements...
# -*- coding: utf-8 -*- class Solution: def countPrimeSetBits(self, L, R): def countSetBits(n): result = 0 while n: n &= n - 1 result += 1 return result result = 0 primes = {2, 3, 5, 7, 11, 13, 17, 19} for n in r...
# 4. (Função com retorno sem parâmetro) Faça um programa contendo uma função/método que leia o lado de um quadrado e retorne sua área, area = lado². def calcular(): lado = float(input('Digite o lado do quadrado: ')) area = lado * lado print() return area def main(): print('Área do quadrado: {:.2f}...
n1 =int(input('Primeiro Número:')) n2 = int(input('Segundo Número:')) s = n1 + n2 print('A soma entre {} e {} vale {}'.format(n1, n2, s))
print('======= LOJAS BABYLU ========\n') valor = input('Valor das compras: ') if valor.isalpha(): print('\n\033[31mApenas caracteres NUMERICOS são aceitos!\033[m') else: valor = float(valor) print('\n','-'*30,'\n') print('FORMAS DE PAGAMENTOS.') print(''' [ 1 ] á vista dinheiro/cheque [ 2 ] á v...
FILE_FIELD = 'file' # TODO: Change to '_file' ? FLASK_REQ_FILE_FILED = 'file' RESULT_FIELD = 'result' # TODO: Change to '_result' _SOURCE = '_source' _ARGS = '_args' _JSON = '_json' _ROUTE = '_route'
#I love my family # message = 'I love Connie' # String Mvariable lovestring = 'I love Connie' print(lovestring) #variable number My_integer1=40 _integer2_my = 80 print(My_integer1) print(My_integer1 + _integer2_my + 200) print(_integer2_my) My_integer1 = 20 _integer2_my = 40 print (My_integer1) print(My_integer1 + _in...
table = [ ('a', 0x1E, 0x9E), ('b', 0x30, 0xB0), ('c', 0x2E, 0xAE), ('d', 0x20, 0xA0), ('e', 0x12, 0x92), ('f', 0x21, 0xA1), ('g', 0x22, 0xA2), ('h', 0x23, 0xA3), ('i', 0x17, 0x97), ('j', 0x24, 0xA4), ('k', 0x25, 0xA5), ('l', 0x26, 0xA6), ('m', 0x32, 0xB2), ('n', 0...
datasets = { 'era-interim': { 'class': 'ei', 'dataset': 'interim', 'expver': '1', 'grid': '0.75/0.75', 'stream': 'oper'}}
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n ) : s = set ( ) sum = 0 for i in range ( n ) : if arr [ i ] not in s : s.ad...
def main(): # squares = [] # for i in range(1, 101): # if i % 3 != 0: # squares.append(i**2) # list comprehension donde numeros al cuadrado no sean multiplo de 3. squares = [i**2 for i in range(1, 101) if i % 3 != 0] print('Reto 1') print(squares) print('*'*30) ...
# A configuration file for the Docker image POSTGRES = dict( database = 'wikidata', host = 'db', port = 5432, user = 'postgres', password = 'postgres', ) METADATA_DIR = '/src/metadata'
website = "http://www.sadikturan.com" course = "Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 saat)" # print(len(course)) (65) # print(website[7:10]) okey # print(website[22:25]) okey result = course[:15] result = course[-15:] # ffdk # result = course[::-1] name = 'Bora' surname = 'YILMAZ' age = '32' j...
""" This class contains details around the contents of a server, mostly based on its type. Will contain one of the following: - Files - Contain a set of metadata for a file - Banks Accounts - Contain metadata for account - Databases - Contains a list of tables/rows """ class Contents: def __init__(self, contents:...
# http://www.faqs.org/rfcs/rfc1071.html def checksum(source_string): sum = 0 countTo = (len(source_string)/2)*2 count = 0 while count < countTo: thisVal = ord(source_string[count + 1])*256 + ord(source_string[count]) sum = sum + thisVal sum = sum & 0xffffffff # Necessary? ...
# Shibboleth authentication settings SHIBBOLETH_LOGOUT_URL = '/Shibboleth.sso/Logout?target=%s' SHIBBOLETH_LOGOUT_REDIRECT_URL = '/administration/accounts/logged-out' SHIBBOLETH_REMOTE_USER_HEADER = 'HTTP_SHIB_UID' SHIBBOLETH_ATTRIBUTE_MAP = { # Automatic user fields 'HTTP_SHIB_GIVENNAME': (False, 'first_name...
class MaxSumSubArray: def maxSum(self, array): max = runSum = array[0] for num in array[1:]: runSum += num if(num > runSum): runSum = num if (max < runSum): max = runSum return max if __name__ == '__main__': maxSumSubAr...
n = int(input('Digite um número inteiro: ')) # se você precisar das variáveis depois use o primeiro comando # se for apenas para mostrar o resultado, como é esse o caso, use o segundo a = n - 1 s = n + 1 print('O antecessor de {} é {} e seu sucessor é {}!'.format(n, a, s)) # print('O antecessor de {} é {} e seu suce...
lista_compras = [] print("### Aplicativo de lista de compras ###") print(" ") print("Digite os produtos que deseja adicionar na lista e tecle <ENTER>") print("Para terminar e imprimir a lista, digite -1 e tecle <ENTER>") print(" ") r = input("Digite o primeiro item da lista: ") while r != "-1": lista_compras.appen...
""" 0621, 第9题: 题目描述: 判断一个数字是不是回文数 Input: 121 Output: true Input: -121 Output: false Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. """ class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False else: n...
class RangeModule: def __init__(self): self.ranges=[] def addRange(self, left: int, right: int) -> None: #print('add range '+str(left)+', '+str(right)) index=bisect_left(self.ranges, [left, right]) end=index while end<len(self.ranges): if self.rang...
''' Created on Mar 6, 2019 @author: hzhang0418 ''' ''' for each individual dataset, get its excluded attributes '''
def calculateStats(numbers): compStats = {'avg': 0 , 'min': 0,'max': 0 } if not numbers: compStats['avg'] = 'nan' compStats['min'] = 'nan' compStats['max'] = 'nan' else: for num in numbers: compStats['avg'] += num compStats['min'] = min(numbers) ...
""" 파일 이름 : 2948.py 제작자 : 정지운 제작 날짜 : 2017년 7월 31일 """ # 입력 tempList = input().split(' ') day = int(tempList[0]) month = int(tempList[1]) # 계산 totalDay = 0 for num in range(1, month): if num in (1, 3, 5, 7, 8, 10, 12): totalDay += 31 elif num == 2: totalDay += 28 # 윤년이 아니다 else: totalDay += 30 totalDay += d...
print(longpoll[pack['userid']]['object']) if 'reply_message' in longpoll[pack['userid']]['object']: kickid = longpoll[pack['userid']]['object']['reply_message']['from_id'] else: kickid = longpoll[pack['userid']]['object']['fwd_messages'][0]['from_id'] data = {'access_token':config['group_token'],'chat_id':pack['toho'...
class DECK: SEVEN = 7 EIGHT = 8 JACK = "Jack" VALUES = [SEVEN, EIGHT, 9, 10, JACK, "Queen", "King", "Ace"] SUITS = ["♦", "♥", "♠", "♣"] class LOG: FMT = "%(name)-20s%(lineno)-3s %(funcName)-17s: %(message)s".format()
def toolchain_container_sha256s(): return { ########################################################### # Base images # ########################################################### # gcr.io/cloud-marketplace/google/debian8:latest "de...
''' Bucket Sort Bucket sort works as follows: 1. Set up an array of initially empty "buckets". 2. Scatter: Go over the original array, putting each object in its bucket. 3. Sort each non-empty bucket. 4. Gather: Visit the buckets in order and put all elements back into the original array. https://en...
""" Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Example: 9 / \ 7 15 / \ \ 3 8 20 ...
CREATE_NEW_USER = "CREATE TABLE user{}(bot_name text NOT NULL, " \ "greeting text NOT NULL, " \ "delay text NOT NULL, " \ "active text NOT NULL," \ "second_greeting text NOT NULL," \ "token text NOT NULL," \ "use...
CONTENT = """Welcome to WhiteFly! =================== Create Change ------------- Create the change by editing the files **update.sql** and **rollback.sql**. Setting Environments ------------- Run below command to add a new environment: ``` whitefly env add <env-name> <connection-str> ``` Commit Change ----------...
class GithubUser: def __init__(self): self.id = None self.githubLogin = None self.userLogin = None def from_record(self, record): self.id = record[0] self.githubLogin = record[1] self.userLogin = record[2]
def ehprimo(n): if n == 1 or n == 2: return True t = int(n**0.5 + 2) for i in range(2, t): if n % i == 0: return False return True n, m = [int(x) for x in input().split()] p1 = p2 = 0 while not p1: if ehprimo(n): p1 = n else: n -= 1 while not p2: if ehprimo(m): p2 = m else: m -= 1 print(p...
class Settings(): """Uma classe para armazenar todas as configurações da Invasão Alienígina. """ def __init__(self) -> None: """Inicializa as configurações do jogo.""" # Configurações da tela self.screen_width = 1200 self.screen_height = 800 self.bg_color = ...
class MatrixCache: """ Possibility to store matrices in a Python cache outside of Visum. """ def __init__(self, logging): self.logging = logging self.matrix_cache = {} self.prob_matrices = {} self.skims_cache = {} def add_skim_to_cache(self, key, values): ...
n = int(input()) for i in range(n): e = str(input()) print(int(e[2:4]) + int(e[5:8]) + int(e[11:13]))
# -*- coding: utf-8 -*- template_engine_file_str = "no feature ospf" config_result = [["no feature ospf"], [{}]] initial_config = [ "\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:33:48 2019\n!Time: Wed Dec 4 15:33:55 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname n9k-...
#!/usr/bin/env python3 with open("input") as f: expenses = [int(num.strip()) for num in f.readlines()] def part1(expenses, target=2020): seen = set() for value in expenses: if target - value in seen: return value * (target - value) seen.add(value) def part2(expenses: set): ...
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: n = len(nums) res = [] def back(S): if len(S) == n: res.append(self.mycopy(S)) return for i in nums: if i not in S: S.append(i) ...
_base_ = './kd_resnet18_resnet50_cifar100_equal.py' # model settings model = dict( adaptive=True, adaptation = dict(out_channels=[256, 512, 1024, 2048], in_channels=[64, 128, 256, 512]), distill_losses=[ dict(type='FeatureMap', mode='feature', loss_weight=1.0), dict(type='SoftmaxRegression',...
""" Create new series holding images of the same slice location. If images are selected from multiple studies then a new series is created inside each study. """ def enable(weasel): return False def main(weasel): images = weasel.images() studies = images.parent.parent for study in studies: img...
a = 5 #chk>{{{ #chk>gANDIEfymvjN9EowcCGj+XNtin7uihFyNxXkbW2Myny7GZzJcQAugAN9cQAoWAwAAABfX2J1aWx0aW5z #chk>X19xAWNidWlsdGlucwpfX2RpY3RfXwpYAQAAAGFxAksFdS4= #chk>}}} print(a) #o> 5
def task411(string): strList = string.split() result = '' for word in strList: if len(word) > 5: result += word + ' ' return result def task411_main(): print( """ Задание 4 "Строки" 1. Пусть дана строка, состоящая из слов, пробелов и знаков препинания. На основании этой...
__author__ = 'Robert Eviston' def caesar(s, k, decrypt=False): if decrypt: k = 26 - k r = "" for i in s: if (ord(i) >= 65 and ord(i) <= 90): r += chr((ord(i) - 65 + k) % 26 +65) elif (ord(i) >= 97 and ord(i) <= 122): r += chr((ord(i) - 97 + k) % 26 + 97) el...
def get_tree_h(tree): if not isinstance(tree, BST): raise ValueError("input must be a binary search tree") h = 0 curnodes = [tree.head] nextnodes = [] while len(curnodes) > 0: for n in curnodes: if n.right: nextnodes.append(n.right) if n.left:...
# -*- coding: utf-8 -*- """ Created on Thu Dec 7 20:05:53 2017 @author: User """ #without helper functions def draw(a,b): c, d = 0, b for i in range(b): print(a*b) b -= 1 if b == 0: print('============', end="") for i in range(d): print(a*c) c ...
def dict_generator(words_dict): def _generator(field: dict, strategies): for n in words_dict: yield n return _generator
""" Tablica T[8][8] zawiera liczby naturalne. Proszę napisać funkcję, która sprawdza czy można wybrać z tablicy niepusty podzbiór o zadanej sumie. Warunkiem dodatkowym jest aby żadne dwa wybrane elementy nie leżały w tej samej kolumnie ani wierszu. Do funkcji należy przekazać wyłącznie tablicę oraz wartość sumy, funkcj...
# Modularização # Contagem de caracteres em dicionarios # quais são os caracteres de uma string e quantas vezes eles aparecem? # foi removido o return já que foi usado oo retorno em print def contar_caracteres(s): """Função que conta os caracteres de uma string ex.: >>> contar_caracteres('ola') {'a':...
# x_2_8 # # func_a() ~ func_d()の関数を一つにまとめてfunc_x(5)を実行すると「5 * 4 * 3 * 2 * 1」を返すように修正してください # ヒント: 関数の中から自分自身の関数を呼び出します def func_a(n): return n * 1 def func_b(n): return n * func_a(n - 1) def func_c(n): return n * func_b(n - 1) def func_d(n): return n * func_c(n - 1)
class Solution(object): def merge(self, intervals): if not intervals: return [] length = len(intervals) if length == 1: return intervals intervals.sort(key=lambda x: x[0]) res = [intervals[0]] for i in range(length): if intervals[...
class Consumers: def __init__(self, consumer_id, consumer_name, consumer_age, consumer_cep, consumer_wallet): self.orders_errors = 0 self.consumer_id = consumer_id self.consumer_name = consumer_name self.consumer_age = consumer_age self.consumer_CEP = consumer_cep sel...
__name__ = 'notebook_autorun' name_url = __name__.replace('_', '-') __version__ = '0.1.7' __description__ = 'Auto run certain cells upon notebook start - if trusted' __author__ = 'oscar6echo' __author_email__ = 'olivier.borderies@gmail.com' __url__ = 'https://github.com/oscar6echo/{}'.format(name_url) __download_url_...
# Time: O(n) # Space: O(k) class Solution(object): def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ count = 0 lookup = {0: -1} for i, num in enumerate(nums): count += num ...
# Twitter keys and access tokens need to be specified once you create your twitter application. # The information in this file is meant for private use so be careful not to share your keys consumer_key = 'Enter consumer_key obtained from twitter' consumer_secret = 'Enter consumer_secret obtained from twitter' access_to...