content
stringlengths
7
1.05M
class VposConfigurationError(Exception): pass
{ 'includes': ['common.gypi'], 'conditions': [ ['OS == "win"', { 'variables': { 'application_platform%': 'Win32', 'renderers%': ['Direct3D11', 'GL4'], 'audio%': 'XAudio2', 'input_devices%': ['DirectInput'], }, }], ['OS == "mac"', { 'variables': { ...
#coding:utf-8 ''' filename:exchange_keys_and_values.py chap:4 subject:10 conditions:a dict solution:exchanged keys and values ''' origin_dict = {'book':['python','djang','data'],'author':'laoqi','publisher':'phei'} def ishashable(obj): try: hash(obj) return True exce...
class Input_data(): def __init__(self): self.s='' def getString(self): self.s = input() def printString(self): print(self.s.upper()) strobj=Input_data() strobj.getString() strobj.printString()
'''8. Faça um programa que receba o valor de um depósito e o valor da taxa de juros, calcule e mostre o valor do rendimento e o valor total depois do rendimento de um mês.''' #entrada deposito = float(input('valor de deposito: ')) juros = float(input("Taxa de juros: ")) #processamento rendimento = deposito * juros / ...
class Solution: def minSessions(self, tasks: List[int], sessionTime: int) -> int: n = len(tasks) initial_state = int('0b'+'1'*n,2) dp = {} def find_dp(state): if state in dp: return dp[state] if state == 0: dp[state] = (1, 0) ...
#AGNET # 該当のチャンネルのID ID_CHANNEL_README = 771383900814573598 #たすきる ID_ROLE_TSKL = 671354476044615680 #たすきる用ちゃんねるID(とつかんり) ID_TSKILL = 624668843444273164 #とつ予定(とつかんり) ID_totu = 739498595329376487 #とつ予定じゃり ID_totu2 = 750321508219355227 #さーばーID ID_SRV = 539773033724772362 #agnet ID_agnet = 549971775828656168 ID_alist =...
""" Given a binary tree, find the root-to-leaf path with the maximum sum. """ class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def find_paths(root): res = [] cur_path = [] find_max(root, res, cur_path, 0) return res max_sum = ...
print('Grocery list:') print('"add" to add items and "view" to view list') grocery_list = [] while True: command = input('Enter command: ') if command == 'add': to_add = input('Enter new item: ') grocery_list.append(to_add) # elif stands for "else if" elif command == 'view': for ...
class Solution: # @return an integer def uniquePaths(self, m, n): if ((m == 0) or (n == 0)): return 0 if (n > m): return self.uniquePaths(n, m) row = [1] * m for i in range(1, n): # print row r2 = [1] last = 1 ...
""" For a given positive integer n determine if it can be represented as a sum of two Fibonacci numbers (possibly equal). Example For n = 1, the output should be fibonacciSimpleSum2(n) = true. Explanation: 1 = 0 + 1 = F0 + F1. For n = 11, the output should be fibonacciSimpleSum2(n) = true. Explanation: 11 = 3 + 8 ...
# @Title: 最长回文子串 (Longest Palindromic Substring) # @Author: KivenC # @Date: 2019-06-12 15:25:33 # @Runtime: 136 ms # @Memory: 13.1 MB class Solution: def longestPalindrome(self, s: str) -> str: # # way 1 # # 从回文串的中心向两边扩展,O(n^2) # # 分奇数串和偶数串 # if len(s) < 2: # return s ...
# # Copyright (C) 2018 The Android Open Source Project # # 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...
class PrintDictResults: def __init__(self, dict_of_sorted_words): self.list_of_sorted_words = dict_of_sorted_words def print_items(self, counter): print(f'{counter + 1}. "{self.list_of_sorted_words[counter][1]}" : {self.list_of_sorted_words[counter][0]}') def get_all_words(self): f...
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None #Binary Tree class BinaryTree(object): def __init__(self, root): self.root = Node(root) def search(self, find_val): """Return True if the value is in the tre...
def iterative_levenshtein(string, target, costs=(1, 1, 1)): """ piglaker modified version : return edits iterative_levenshtein(s, t) -> ldist ldist is the Levenshtein distance between the strings s and t. For all i and j, dist[i,j] will contain the Levenshtein...
# TODO: this may want to move to Invoke if we can find a use for it there too? # Or make it _more_ narrowly focused and stay here? class NothingToDo(Exception): pass class GroupException(Exception): """ Lightweight exception wrapper for `.GroupResult` when one contains errors. .. versionadded:: 2.0 ...
def tail(xs): """ Напишете функция в Python, която взима списък и връща нов списък, който се състои от всички елементи **без първия** от първоначалния списъка. **Не се грижете, ако списъка е празен** >>> tail([1, 2, 3]) [2, 3] >>> tail(["Python"]) [] """ pass
class Button(object): def __init__(self, url, label, get=''): self.url = url self.label = label self.get = get
class Solution: def getFormattedEMail(self, email): userName, domain = email.split('@') if '+' in userName: userName = userName.split('+')[0] if '.' in userName: userName = ''.join(userName.split('.')) return userName + '@' + domain def numUniqueEmail...
class SendResult: def __init__(self, result={}): self.successful = result.get('code', None) == '200' self.message_id = result.get('message_id', None)
# -*- coding: utf-8 -*- """ Created on Wed Jan 3 10:27:50 2018 @author: James Jiang """ all_lines = [line.rstrip('\n') for line in open('Data.txt')] def has_two_pairs(string): for i in range(len(string) - 1): pair = string[i:i + 2] if (pair in string[:i]) or (pair in string[i + 2:]): ...
#1 celsius=float(input("请输入一个摄氏度:>>")) fahrenheit=(9 / 5) *celsius + 32 print("华氏温度为:%.1f" % fahrenheit) #2 radius=float(input("请输入圆柱体的半径:>>")) length=float(input("请输入圆柱体的高:>>")) area= radius*radius*3.14159265 volume=area*length print("The area is %.4f" % area ) print("The volume is %.1f" % volume) #...
######################################################## # Copyright (c) 2015-2017 by European Commission. # # All Rights Reserved. # ######################################################## extends("BaseKPI.py") """ Transmission usage (%) ---------------------- Indexed by * sco...
"""Dummy SMTP API.""" class SMTP_dummy(object): # pylint: disable=useless-object-inheritance # pylint: disable=invalid-name, no-self-use """Dummy SMTP API.""" # Class variables track member function calls for later checking. msg_from = None msg_to = None msg = None def login(self, login...
""" MECHANICAL PARAMETERS """ s0_step_per_rev = 27106 s1_step_per_rev = 27106 pitch_travel_rads = 0.5 yaw_travel_rads = 1.2 pitch_center_rads = 0.21 yaw_center_rads = 0.59 default_vel_radps = 2.5 default_accel_radps2 = 20 trigger_min_pwm = 40 trigger_max_pwm = 120 trigger_hold_s = 0.5 """ PI PINOUTS """ half_press...
def square_of_number(): number = "179" number_for_sum = "179" for i in range (49): number = number + number_for_sum number = int(number) number = number ** 2 print(number) square_of_number()
# [카카오] 오픈채팅방 def solution(record): answer = [] id_dict = {} for query in record: q = query.split(" ") if len(q) >= 3: id_dict[q[1]] = q[2] for query in record: q = query.split(" ") if q[0] == "Enter": answer.append(f"{id_dict[q[1]]}님이 들어왔습니다.") ...
# -*- coding: utf-8 -*- # @Time : 2021/8/6 15:01 # @Author : zc # @Desc : json格式的response序列化成实例对象异常 class SerializeResponseException(Exception): def __init__(self, err_msg): super().__init__(self, err_msg)
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lower-case En...
aeki_config = { "AEKI_HOST": "localhost", # rename to hostname for cgi if you like "IOT_HOST":"localhost" # assumes iot test device is also on local host }
def is_divisible(number): divisible = [num for num in range(2, 11) if number % num == 0] return True if divisible else False start = int(input()) end = int(input()) print([int(_) for _ in range(start, end + 1) if is_divisible(_)])
""""" Path to the Image Dataset directories """"" TR_IMG_DIR = './WORKSPACE/DATASET/annotation/' GT_IMG_DIR = './WORKSPACE/DATASET/annotation/' """"" Path to Numpy Video directories """"" TR_VID_DIR = './WORKSPACE/DATA/TR_DATA/' GT_VID_DIR = './WORKSPACE/DATA/GT_DATA/' """"" Path to Numpy batches directories """"...
""" Quality Control Tools | Cannlytics Author: Keegan Skeate <keegan@cannlytics.com> Created: 2/6/2021 Updated: 6/23/2021 License: MIT License <https://opensource.org/licenses/MIT> Perform various quality control checks and analyses to ensure that your laboratory is operating as desired. TODO: - Trend an...
# Goal: # # Find the sums of subsections of an array # Change an element of the array and don't recalculate everything if __name__ == '__main__': arr = [1,2,3,4,5] print('here')
""" # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ class Solution: dairy = {} def cloneGraph(self, node: 'Node') -> 'Node': if not node: return None ...
inputFile = "day6/day6_1_input.txt" # https://adventofcode.com/2021/day/6 if __name__ == '__main__': print("Lanternfish") with open(inputFile, "r") as f: fishArray = [int(num) for num in f.read().strip().split(",")] # for part2... not needed to read array again from file origFishArray = fishA...
INITIAL = 'INITIAL' CONNECTING = 'CONNECTING' ESTABLISHED = 'ESTABLISHED' ACCEPTED = 'ACCEPTED' DECLINED = 'DECLINED' ENDED = 'ENDED' ERROR = 'ERROR'
# Static data class for character stats class Zhongli: level = 90 talentLevel = 8 # Base stat values baseHP = 14695 baseATK = 251 baseCritRATE = 0.05 baseCritDMG = 0.5 # Ability MVs and frame counts class Normal: # Normal attack spear kick hop combo frames = 140 #m...
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
class Environment(object): def ask(self, prompt, default=None, starting=None): pass def ask_values(self, prompt, values, default=None, starting=None): pass def ask_directory(self, prompt, default=None, starting=None): pass def ask_completion(self, prompt, values, starting=Non...
x = float(input("Enter Number: ")) if(x % 2) == 0 and x > 0: print("The number you entered is positive and even.") elif(x % 2) == 0 and x < 0: print("The number you entered is negative and even.") elif(x % 2) != 0 and x > 0: print("The number you entered is positive and odd.") elif(x % 2) != 0 and x < 0: ...
""" AiiDA Plugin Template Adapt this template for your own needs. """ __version__ = '0.3.4'
#Ask user for name name = input("What is your name?: ") #Ask user for the age age = input("How old are you? ") #Ask user for city city = input("What city do you live in? ") #Ask user what they enjoy hobbies = input("What are your hobbies?, What do you love doing? ") #Create output text using placeholders to concat...
class Info: """ Allows to print out information about the application. """ def commands(): print('''Main modules: imu | Inertial Measurement Unit (GPS, gyro, accelerometer) gps | GPS gyro | Gyroscope accel | Accelerometer ...
print('Analisador de números') print('=-=' * 15) n1 = int(input('Digite o primeiro número: ')) n2 = int(input('Digite o segundo número: ')) if n1 > n2: print('O número {} é maior que o número {}'.format(n1, n2)) elif n2 > n1: print('O número {} é maior que o número {}'.format(n2, n1)) else: print('Os dois v...
print(''' Exercício 71 da aula 15 de Python Curso do Guanabara Day 24 Code Python - 23/05/2018 ''') print('{:^30}'.format('BANCO DO CIRINO')) print('=' * 30) n = int(input('Qual o valor para sacar? R$ ')) total = n nota = 50 # começar de cima para baixo na estrutura qtdNota = 0 while True: if tota...
def second_task(**context): print("This is ----------- task 2") return "hoge======" def third_task(**context): output = context["task_instance"].xcom_pull(task_ids="python_task_2") print("This is ----------- task 3") return "This is the result : " + output
""" MARKDOWN --- YamlDesc: CONTENT-ARTICLE Title: python builtin class attributes MetaDescription: python object oriented programming class builtin attributes __doc__, __name__, __module__, __bases__ example code, tutorials MetaKeywords: python object oriented programming class builtin attributes __doc__, __name__, __m...
''' Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/ Author : Yuan Wang Date : 2018-07-21 /********************************************************************************** *Given a binary tree, find its maximum depth. * *The maximum depth is the number of nodes along the longest path from the ...
#Faça um Programa que leia um vetor de 5 números inteiros e mostre-os. lista=[] for i in range(1, 6): lista.append(int(input('Digite um número: '))) print(lista)
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ======================== SBPy Vega Sources Module ======================== Descriptions of source Vega spectra. """ # Parameters passed to Vega.from_file. 'filename' is a URL. After # adding spectra here update __init__.py docstring and # docs/sbpy...
def divide_by_four(input_number): return input_number/4 result = divide_by_four(16) # result now holds 4 print("16 divided by 4 is " + str(result) + "!") result2 = divide_by_four(result) print(str(result) + " divided by 4 is " + str(result2) + "!") def calculate_age(current_year, birth_year): age = current_yea...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Here is the class that controls the bot. It also contains various value manipulation, and one function that lets the bot play one round, from first roll until hold. The intelligence is basically how many rolls the bot is going to do on one round. The easier level on t...
##################### ### Base classes. ### ##################### class barrier: synonyms = ["wall"] m_description = "There is a barrier in the way." def __init__(self, passable=False): self.passable = passable def __str__(self): return self.m_description def ...
g1 = "#5d9e6d" g2 = "#549464" g3 = "#498758" g4 = "#3d784b" b1 = "#5f7ab8" b2 = "#5a70a3" b3 = "#4d67a3" r4 = "#262626" w1 = "#f0f0f0" w2 = "#d9d9d9" w3 = "#e6e6e6" r1 = "#707070" r2 = "#595959" r3 = "#404040" r4 = "#262626" l1 = "#d95757" l2 = "#d99457" l3 = "#d97857" v1 = "#664f47" v2 = "#4a3d39" v3 = "#382f2c" v4 = ...
useless_facts = ["Most American car horns honk in the key of F.", "The name Wendy was made up for the book 'Peter Pan.'", "Barbie's full name is Barbara Millicent Roberts.", "Every time you lick a stamp, you consume 1/10 of a calorie.", "The average person falls asleep in seven minutes.", "Studies s...
description = 'Some kind of SKF chopper' pv_root = 'LabS-Embla:Chop-Drv-0601:' devices = dict( skf_drive_temp=device('nicos.devices.epics.pva.EpicsReadable', description='Drive temperature', readpv='{}DrvTmp_Stat'.format(pv_root), monitor=True, ), skf_motor_temp=device('nicos.devic...
class BaseSelector: def __init__(self): pass def select_model(self, X, y, total_time, learners=None, metric=None, save_directory=None): """ Find the best model with its hyperparameters from the autotf's...
# # 5. Алфавитный переводчик номера телефона. Многие компании используют телефонные # # номера наподобие 555-GET-FOOD, чтобы клиентам было легче запоминать эти номера. # # На стандартном телефоне буквам алфавита поставлены в соответствие числа следующим # # образом: А,В и С=2 ; D,Е и F=З. phone_num = input('nnn-XXX-XXX...
# Given a list x of length n, a number to be inserted into the list and a position where to insert the number # return the new list # e.g given [2, 3, 6, 7], num=8 and position=2, return [2, 3, 8, 6, 7] # for more info on this quiz, go to this url: http://www.programmr.com/insertion-specified-position-array-0 def ins...
"""This module contains exceptions defined for Rhasspy Desktop Satellite.""" class RDSatelliteServerError(Exception): """Base class for exceptions raised by Rhasspy Desktop Satellite code. By catching this exception type, you catch all exceptions that are defined by the Hermes Audio Server code.""" cla...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ python系统内的异常 +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- Buffer...
# Implementor class drawing_api: def draw_circle(self, x, y, radius): pass # ConcreteImplementor 1/2 class drawing_api1(drawing_api): def draw_circle(self, x, y, radius): print('API1.circle at %f:%f radius %f' % (x, y, radius)) # ConcreteImplementor 2/2 class drawing_api2(drawing_api): d...
class Solution: # @param {integer} k # @param {integer} n # @return {integer[][]} def combinationSum3(self, k, n): nums = range(1, 10) self.results = [] self.combination(nums, n, k, 0, []) return self.results def combination(self, nums, target, k, start, result): ...
X = int(input()) Y = int(input()) soma = 0 if X > Y: troca = Y Y = X X = troca sam = X while sam <= Y: if sam%13 != 0: soma = soma + sam sam += 1 print(soma)
pMMO_dna_seq = 'ATGAAAACTATTAAAGATAGAATTGCTAAATGGTCTGCTATTGGTTTGTTGTCTGCTGTTGCTGCTACTGCTTTTTATGCTCCATCTGCTTCTGCTCATGGTGAAAAATCTCAAGCTGCTTTTATGAGAATGAGGACTATTCATTGGTATGACTTATCTTGGTCTAAGGAAAAGGTTAAAATAAACGAAACTGTTGAGATTAAAGGTAAATTTCATGTTTTTGAAGGTTGGCCTGAAACTGTTGATGAACCTGATGTTGCTTTTTTGAATGTTGGTATGCCTGGTCCTGTTTTTATTAGAAAAG...
"""MEF Eline Exceptions.""" class MEFELineException(Exception): """MEF Eline Base Exception.""" class EVCException(MEFELineException): """EVC Exception.""" class ValidationException(EVCException): """Exception for validation errors.""" class FlowModException(MEFELineException): """Exception for ...
# Copyright (c) 2021 homuler # # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. """Proto compiler Macro for generating C# source files corresponding to .proto files """ def csharp_proto_src(name, proto_src, deps): "...
c = int(input('digite o primeiro numero: ')) b = int(input('digite o segundo numero: ')) a = int(input('digite o terceiro numero: ')) cores= {'vermelho': '\033[0;31m', 'azul' : '\033[1;34m', 'zero': '\033[m' } # qual o maior maior = a if b > c and b > a: maior = b if c > b and c > a: maior = c p...
# coding=utf-8 common_mysql_config = { 'user': 'root', 'passwd': '', 'host': '127.0.0.1', 'db': 'autotrade', 'connect_timeout': 3600, 'charset': 'utf8' } yongjinbao_config = {"account": "帐号", "password": "加密后的密码"} guangfa_config = {"username": "加密的客户号", "password": "加密的密码"} yinghe_config = {...
""" A website requires the users to input username and password to register. Write a program to check the validity of password input by users. """ """Question 18 Level 3 Question: A website requires the users to input username and password to register. Write a program to check the validity of password input by users. ...
class ACCOUNTS(): def __init__(self): self.CodeChef = { "username": "username", "password": "password" } self.Hackerrank = { "username": "username", "password": "password", "tracks": ["python"] # Available (...
# TODO: implement a page_parser that uses nlp and stats to get a good read of a file. class page_parser(object): """ a multi purpose parser that can read these file types """ def __init__(self): pass
# Source and destination file names. test_source = "data/math.txt" test_destination = "math_output_html.html" # Keyword parameters passed to publish_file. reader_name = "standalone" parser_name = "rst" writer_name = "html" # Extra setting settings_overrides['math_output'] = 'HTML' settings_overrides['stylesheet_path...
''' Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Ex...
def test_valid(cldf_dataset, cldf_logger): assert cldf_dataset.validate(log=cldf_logger) def test_parameters(cldf_dataset): assert len(list(cldf_dataset["ParameterTable"])) == 100 def test_languages(cldf_dataset): assert len(list(cldf_dataset["LanguageTable"])) > 4000
description = 'setup for the status monitor' group = 'special' _expcolumn = Column( Block('Experiment', [ BlockRow( # Field(name='Proposal', key='exp/proposal', width=7), # Field(name='Title', key='exp/title', width=20, # istext=True, maxlen=20), Field(name...
"""Bazel rules and macros for running tsec over a ng_module or ts_library.""" load("@npm//@bazel/typescript/internal:ts_config.bzl", "TsConfigInfo") load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo") load("@npm//tsec:index.bzl", _tsec_test = "tsec_test") TsecTsconfigInfo = provider(fields = ["src", ...
def shellSort(alist): gap = len(alist) // 2 while gap > 0: for i in range(gap, len(alist)): val = alist[i] j = i while j >= gap and alist[j - gap] > val: alist[j] = alist[j - gap] j -= gap alist[j] = val gap //= 2
############################################################################# # # # Module of BFA that manages server statistics in realtime # # ############################################################################# """ This module implements the real-time logging of in-game statistics specifically for one curre...
#!/usr/bin/env python3 def foo(): a = 10 # infer that b is an int b = a assert b == 10 print(b) if __name__ == "__main__": foo()
""" Faça um programa que pergunte a hora aousuário e, baseando-se na hora descrita, exiba a saudação apropriada. """ x=1 while x!=0: #Entra no try caso seja digitado um numero inteiro try: horas=int(input('Que horas são? ')) if horas>=0 and horas<=11: print('Bom dia!') x...
x="There are %d types of people."%10 binary="binary" do_not="don't" y="Those who know %s and those who %s."%(binary,do_not) print(x) print(y) print("I said: '%s'."%y) hilarious=False joke_evaluation="Isn't that joke so funny?! %r" print (joke_evaluation % hilarious) w="This is the left side of ..." e="a string with a r...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- ANSI_COLORS ...
def printVal(state, name): val = state[name] print("%s:" % state.fuzzy_names[name], val) def print_all(state): printVal(state, "var_default") printVal(state, "var_default_override") printVal(state, "var_default_override_twice") printVal(state, "var_default_override_twice_and_cli") def regis...
# -*- coding: utf-8 -* """ some rule """ class MaxTruncation(object): """MaxTruncation:超长截断规则 """ KEEP_HEAD = 0 # 从头开始到最大长度截断 KEEP_TAIL = 1 # 从头开始到max_len-1的位置截断,末尾补上最后一个id(词或字) KEEP_BOTH_HEAD_TAIL = 2 # 保留头和尾两个位置,然后按keep_head方式截断 class EmbeddingType(object): """EmbeddingType:文本数据需要转换的emb...
class AbstractException(Exception): """Abstract exception for project""" def __init__(self, code, message): """ Constructor :param int code: error code :param str message: error message """ self._code = code self._message = message @property def...
""" https://leetcode.com/problems/rectangle-overlap/ A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner. Two rectangles overlap if the area of their intersection is positive. To be clear, two rec...
class Node(): def __init__(self,data): self.data=data self.ref=None class LinkedList(): def __init__(self): self.head=None def Print_ll(self): n=self.head if n is None: print("LinkedList is empty") else: while n is not None: ...
#!/usr/bin/env python3 #encoding=utf-8 #------------------------------------------------ # Usage: python3 3-desc-state-inst.py # Description: descriptor for attribute intercept #------------------------------------------------ class InstState: # Using instance state, (object) in 2.X def __get__(self, inst...
bind = "0.0.0.0:5000" backlog = 2048 workers = 1 worker_class = "sync" threads = 16 spew = False reload = True loglevel = "debug"
for t in range(int(input())): n=int(input()) if n%2==0: print(int(n/2-1)) else: print(int(n//2))
value1 = int(input()); value2 = value1//100 if value1 % 2==0 and value2 % 2==0: print("Even") elif value1 % 2==0 and value2 % 2==1: print("Even Odd") elif value1 % 2==1 and value2 % 2==1: print("Odd") elif value1 % 2==1 and value2 % 2==0: print("Odd Even")
# Задача 4. Вариант 7. # Напишите программу, которая выводит имя, под которым скрывается Мария Луиза Чеччарелли. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). Для хранения всех не...
""" VARIÁVEIS DE CONFIGURAÇÃO DO BOT True PARA ATIVAR E False PARA DESATIVAR """ escrever_nos_campos = True # PREENCHE OS CAMPOS COM AS RESPOSTAS modo_de_aprendizado = False # APRENDE NOVAS RESPOSTAS SALVANDO AS RESPOSTAS DOS OUTROS JOGADORES clica_botao_avaliar_respostas = True # CLICA NO BOTÃO "AVALIAR" clic...
class Solution: def lemonadeChange(self, bills: List[int]) -> bool: money = [0, 0, 0] for x in bills: if x == 5: money[0] += 1 if x == 10: if money[0] >= 1: money[1] += 1 money[0] -= 1 ...
config = {} with open("config.txt", "r") as f: lines = f.readlines() for line in lines: key, value = line.split("=") value = value.replace("\n", "") config[key] = value print(f"Added key {key} with value {value}") user_key = input("Which key would you like to see? ") if user_ke...
# A little bit of molecular biology # Codons are non-overlapping triplets of nucleotides. # ATG CCC CTG GTA ... - this corresponds to four codons; spaces added for emphasis # The start codon is 'ATG' # Stop codons can be 'TGA' , 'TAA', or 'TAG', but they must be 'in frame' with the start codon. The first stop codon ...
#生成器的创建,区分迭代器、生成器、推导式、生成器表达式 l_01 = [x for x in range(10)] #列表推导式 print(l_01) l_02 = (x for x in range(10)) #列表生成器表达式 print(l_02) class Fib: def __init__(self): self.prev = 0 self.curr = 1 def __iter__(self): #Fib是迭代对象, 因为Fib实现了__iter__方法 -->类/对象 return self def __next__(self...