content stringlengths 7 1.05M |
|---|
#
# Copyright 2017 Vitalii Kulanov
#
class ClientException(Exception):
"""Base Exception for Dropme client
All child classes must be instantiated before raising.
"""
pass
class ConfigNotFoundException(ClientException):
"""
Should be raised if configuration for dropme client is not specif... |
# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for c... |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
if not s :
return ""
s = list(s)
st = []
for i,n in enumerate(s):
if n == "(":
st.append(i)
elif n == ")" :
if st :
st.pop()... |
#Given a sorted array and a target value, return the index if the target is found. If not, return the index
#where it would be if it were inserted in order.
#You may assume no duplicates in the array.
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:... |
class PoolArgs:
def __init__(self, bankerBufCap, bankerMaxBufNumber, signerBufCap, signerBufMaxNumber, broadcasterBufCap, broadcasterMaxNumber, stakingBufCap, stakingMaxNumber, distributionBufCap, distributionMaxNumber, errorBufCap, errorMaxNumber):
self.BankerBufCap = bankerBufCap
self.BankerMaxBuf... |
# Signal processing
SAMPLE_RATE = 16000
PREEMPHASIS_ALPHA = 0.97
FRAME_LEN = 0.025
FRAME_STEP = 0.01
NUM_FFT = 512
BUCKET_STEP = 1
MAX_SEC = 10
# Model
WEIGHTS_FILE = "data/model/weights.h5"
COST_METRIC = "cosine" # euclidean or cosine
INPUT_SHAPE=(NUM_FFT,None,1)
# IO
ENROLL_LIST_FILE = "cfg/enroll_list.csv"
TEST_L... |
class Mac_Address_Information:
par_id = ''
case_id = ''
evd_id = ''
mac_address = ''
description = ''
backup_flag = ''
source_location = []
def MACADDRESS(reg_system):
mac_address_list = []
mac_address_count = 0
reg_key = reg_system.find_key(r"ControlSet001\Control\Class\{4d3... |
"""Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string S1 of length 26. S1 is indexed from 0 to 25. Initially, your finger is at index 0.
To type a character, you have to move your finger to the index of the desired character. The time taken t... |
# Vencedor do jogo da velha
# Faça uma função que recebe um tabuleiro de jogo da velha e devolve o vencedor. O tabuleiro é representado por uma lista de listas como o mostrado a seguir:
# [['X', 'O', 'X'], ['.', 'O', 'X'], ['O', '.', 'X']]
# Note que a lista acima é idêntica a:
# [
# ['X', 'O', 'X'],
# ... |
# ***************************************************************************************
# ***************************************************************************************
#
# Name : processcore.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 22nd December 2018
# Purpose : Convert vocabulary.as... |
"""
https://www.codewars.com/kata/56269eb78ad2e4ced1000013/train/python
Given an int, return the next 'integral perfect square', which is an integer n such that sqrt(n) is also an int.
If the given int is not an integral perfect square, return -1.
"""
def find_next_square(sq: int) -> int:
sqrt_of_sq = sq ** (1/2... |
class Ledfade:
def __init__(self, *args, **kwargs):
if 'start' in kwargs:
self.start = kwargs.get('start')
if 'end' in kwargs:
self.end = kwargs.get('end')
if 'action' in kwargs:
self.action = kwargs.get('action')
self.transit = self.end - self.start
def ledpwm(self, p):
c = 0.181+(0.0482*p)+(0.00... |
"""Foreign Key Solving base class."""
class ForeignKeySolver():
def fit(self, list_of_databases):
"""Fit this solver.
Args:
list_of_databases (list):
List of tuples containing ``MetaData`` instnces and table dictinaries,
which contain table names as in... |
"""
predefined params for openimu
"""
JSON_FILE_NAME = 'openimu.json'
def get_app_names():
'''
define openimu app type
'''
app_names = ['Compass',
'IMU',
'INS',
'Leveler',
'OpenIMU',
'VG',
'VG_AHRS',
... |
def read_paragraph_element(element):
"""Returns text in given ParagraphElement
Args:
element: ParagraphElement from Google Doc
"""
text_run = element.get('textRun')
if not text_run:
return ''
return text_run.get('content')
def read_structural_elements(elements):
"""... |
def average_speed(s1 : float, s0 : float, t1 : float, t0 : float) -> float:
"""
[FUNC] average_speed:
Returns the average speed.
Where:
Delta Space = (space1[s1] - space0[s0])
Delta Time = (time1[t1] - time0[t0])
"""
return ((s1-s0)/(t1-t0));
def average_acceleration(v1 : flo... |
def set_material(sg_node, sg_material_node):
'''Sets the material on a scenegraph group node and sets the materialid
user attribute at the same time.
Arguments:
sg_node (RixSGGroup) - scene graph group node to attach the material.
sg_material_node (RixSGMaterial) - the scene graph material ... |
# Debug or not
DEBUG = 1
# Trackbar or not
CREATE_TRACKBARS = 1
# Display or not
DISPLAY = 1
# Image or Video, if "Video" is given as argument, program will use cv2.VideoCapture
# If "Image" argument is given the program will use cv2.imread
imageType = "Video"
# imageType = "Image"
# Image/Video source 0 or 1... |
#! /usr/bin/env python3
"""Context files must contain a 'main' function.
The return from the main function should be the resulting text"""
def main(params):
if hasattr(params,'time'):
# 1e6 steps per ns
steps = int(params.time * 1e6)
else:
steps = 10000
return steps
|
class NamingUtils(object):
""" A collection of utilities related to element naming. """
@staticmethod
def CompareNames(nameA, nameB):
"""
CompareNames(nameA: str,nameB: str) -> int
Compares two object name strings using Revit's comparison rules.
nameA: The first obje... |
# Description: Class Based Decorators
"""
### Note
* If you want to maintain some sort of state and/or just make your code more confusing, use class based decorators.
"""
class ClassBasedDecorator(object):
def __init__(self, function_to_decorate):
print("INIT ClassBasedDecorator")
self.function_... |
# Task 09. Hello, France
def validate_price(items_and_prices):
item = items_and_prices.split('->')[0]
prices = float(items_and_prices.split('->')[1])
if item == 'Clothes' and prices <= 50 or \
item == 'Shoes' and prices <= 35.00 or \
item == 'Accessories' and prices <= 20.50:
... |
#ask user to enter a positive value (pedir al usuario que ingrese un valor positivo)
a = int(input("please enter a positive integer: "))
#if value entered is negative print "not a positive number" and stop (si el valor introducido es una impresion negativa "no es un número positivo" y se detiene)
while a < 0:
prin... |
{
'name': 'Clean Theme',
'description': 'Clean Theme',
'category': 'Theme/Services',
'summary': 'Corporate, Business, Tech, Services',
'sequence': 120,
'version': '2.0',
'author': 'Odoo S.A.',
'depends': ['theme_common', 'website_animate'],
'data': [
'views/assets.xml',
... |
class ValidationException(Exception):
pass
class NeedsGridType(ValidationException):
def __init__(self, ghost_zones=0, fields=None):
self.ghost_zones = ghost_zones
self.fields = fields
def __str__(self):
return f"({self.ghost_zones}, {self.fields})"
class NeedsOriginalGrid(Needs... |
#import sys
#file = sys.stdin
file = open( r".\data\nestedlists.txt" )
data = file.read().strip().split()[1:]
records = [ [data[i], float(data[i+1])] for i in range(0, len(data), 2) ]
print(records)
low = min([r[1] for r in records])
dif = min([r[1] - low for r in records if r[1] != low])
print(dif)
names = [ r[0] for... |
class ApiOperations:
"""
Class to extract defined parts from the OpenApiSpecs definition json
"""
def __init__(self, resource, parts=None):
"""
Extract defined parts out of paths/<endpoint> (resource) in the OpenApiSpecs definition
:param resource: source to be extracted from
... |
"""
MIRA API config
"""
MODELS = [
{
"endpoint_name": "mira-large",
"classes": ["fox", "skunk", "empty"]
},
{
"endpoint_name": "mira-small",
"classes": ["rodent", "empty"]
}
]
HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Cont... |
class Int_code:
def __init__(self, s, inputs):
memory = {}
nrs = map(int, s.split(","))
for i, x in enumerate(nrs):
memory[i] = x
self.memory = memory
self.inputs = inputs
def set(self, i, x):
self.memory[i] = x
def one(self, a, b, c, mod... |
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='OTEMobileNetV3',
mode='small',
width_mult=1.0),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='NonLinearClsHead',
num_classes=1000,
in_channels=576,
hid_channels=... |
class BaseNode:
pass
class Node(BaseNode):
def __init__(self, offset, name=None, **opts):
self.offset = offset
self.end_offset = None
self.name = name
self.nodes = []
self.opts = opts
def __as_dict__(self):
return {"name": self.name, "nodes": [node.__as_dict... |
def foo():
print("I'm a lovely foo()-function")
print(foo)
# <function foo at 0x7f9b75de3f28>
print(foo.__class__)
# <class 'function'>
bar = foo
bar()
# I'm a lovely foo()-function
print(bar.__name__)
# foo
def do_something(what):
"""Executes a function
:param what: name of the function to be executed... |
# 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... |
n, m = [int(e) for e in input().split()]
mat = []
for i in range(n):
j = [int(e) for e in input().split()]
mat.append(j)
for i in range(n):
for j in range(m):
if mat[i][j] == 0:
if i == 0:
if mat[i][j+1] == 1 and mat[i][j-1] == 1 and mat[i+1][j] == 1:
... |
CONNECTION_STRING = '/@'
CHUNK_SIZE = 100
BORDER_QTY = 5 # minimun matches per year per player for reload player
ATP_URL_PREFIX = 'http://www.atpworldtour.com'
DC_URL_PREFIX = 'https://www.daviscup.com'
ATP_TOURNAMENT_SERIES = ('gs', '1000', 'atp', 'ch')
DC_TOURNAMENT_SERIES = ('dc',)
DURATION_IN_DAYS = 18
ATP_CSV_PAT... |
def digitsProduct(product):
"""
Given an integer product, find the smallest
positive (i.e. greater than 0) integer the
product of whose digits is equal to product.
If there is no such integer, return -1 instead.
Time Complexity: O(inf)
Space Complexity: O(1)
"""
number = 1
... |
numero = input('\nInsira um numero de 0 a 9999: \n')
if not numero.isnumeric():
print('Condição inválida, insira apenas números\n')
elif len(numero) == 1:
print('\nA unidade do número {} é {}\n'.format(numero, numero[-1]))
elif len(numero) == 2:
print('\nA unidade do número {} é {}'.format(numero, n... |
# 15. replace() -> Altera determinado valor de uma string por outro. Troca uma string por outra.
texto = 'vou Treinar todo Dia Python'
print(texto.replace('vou','Vamos'))
print(texto.replace('Python','Algoritmos')) |
"""
Singly linked lists
-------------------
- is a list with only 1 pointer between 2 successive nodes
- It can only be traversed in a single direction: from the 1st node in the list to the last node
Several problems
----------------
It requires too much manual work by the programmer
It is too error-prone (this is a ... |
class Email:
def __init__(self):
self.from_email = ''
self.to_email = ''
self.subject = ''
self.contents = ''
def send_mail(self):
print('From: '+ self.from_email)
print('To: '+ self.to_email)
print('Subject: '+ self.subject)
print('Contents: '+ s... |
n, x = map(int, input().split())
ll = list(map(int, input().split()))
ans = 1
d_p = 0
d_c = 0
for i in range(n):
d_c = d_p + ll[i]
if d_c <= x:
ans += 1
d_p = d_c
print(ans) |
def fill_the_box(*args):
height = args[0]
length = args[1]
width = args[2]
cube_size = height * length * width
for i in range(3, len(args)):
if args[i] == "Finish":
return f"There is free space in the box. You could put {cube_size} more cubes."
if cube_size < args[i]:
... |
#!/usr/bin/env python3
#Antonio Karlo Mijares
# return_text_value function
def return_text_value():
name = 'Terry'
greeting = 'Good Morning ' + name
return greeting
# return_number_value function
def return_number_value():
num1 = 10
num2 = 5
num3 = num1 + num2
return num3
# Main program
if __name__ == '__ma... |
"""
for x in range(10):
print(x)
for x in range(20, 30):
print(x)
for x in range(10,100,5):
print(x)
for x in range(10,1,-1):
print(x)
print(range(10))
"""
frutas = ["maçã", "laranja", "banana", "morango"]
for x in range(len(frutas)):
print(frutas[x])
for fruta in frutas:
print(fruta)
|
{
"variables": {
"HEROKU%": '<!(echo $HEROKU)'
},
"targets": [
{
"target_name": "gif2webp",
"defines": [
],
"sources": [
"src/gif2webp.cpp",
"src/webp/example_util.cpp",
"src/web... |
with open("day6_input.txt") as f:
initial_fish = list(map(int, f.readline().strip().split(",")))
fish = [0] * 9
for initial_f in initial_fish:
fish[initial_f] += 1
for day in range(80):
new_fish = [0] * 9
for state in range(9):
if state == 0:
new_fish[... |
def merge_sort(ls: list):
# 2020/9/19 二路归并排序
length = len(ls)
if length <= 1:
return ls
idx = length // 2
piece1 = ls[:idx]
piece2 = ls[idx:]
piece1 = merge_sort(piece1)
piece2 = merge_sort(piece2)
sorted_ls = []
# 2020/9/19 合并的算法
while len(piece1) != 0 and len(pie... |
# [Root Abyss] Guardians of the World Tree
MYSTERIOUS_GIRL = 1064001 # npc Id
sm.removeEscapeButton()
sm.lockInGameUI(True)
sm.setPlayerAsSpeaker()
sm.sendNext("We need to find those baddies if we want to get you out of here.")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("But... they all left")
sm.setPlayerAsSpeake... |
# 11 List Comprehensions
products = [
("Product1", 15),
("Product2", 50),
("Product3", 5)
]
print(products)
# prices = list(map(lambda item: item[1], products))
# print(prices)
prices = [item[1] for item in products] # With list comprehensions we can achive the same result with a clenaer code
print(pric... |
# ArrayBaseList.py
# 배열 기반 리스트 클래스
class ArrayBaseList :
def __init__(self) :
self.list = []
self.count = 0
# 배열 기반 리스트 삽입 함수
def add(self, data) :
self.list.append(data)
self.count += 1
# 배열 기반 리스트 탐색 함수
def search(self, data) :
return [index for index, s... |
class orgApiPara:
setOrg_POST_request = {"host": {"type": str, "default": ''},
"port": {"type": int, "default": 636},
"cer_path": {"type": str, "default": ''},
"use_sll": {"type": bool, "default": True},
"a... |
#!/usr/bin/python3
#-----------------bot session-------------------
UserCancel = 'You have cancel the process.'
welcomeMessage = ('User identity conformed, please input gallery urls ' +
'and use space to separate them'
)
denyMessage = 'You are not the admin of this bot, conversatio... |
(n,m) = [int(x) for x in input().split()]
loop_range = n + m
set_m = set()
set_n = set()
for _ in range(n):
set_n.add(int(input()))
for _ in range(m):
set_m.add(int(input()))
uniques = set_n.intersection(set_m)
[print(x) for x in (uniques)]
|
class bcolors():
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OK = '\033[92m'
WARNING = '\033[96m'
FAIL = '\033[91m'
TITLE = '\033[93m'
ENDC = '\033[0m'
|
# Exercício Python 105: Analisando e gerando Dicionários
# Faça um programa que tenha uma função notas() que pode receber várias notas de alunos
# e vai retornar um dicionário com as seguintes informações:
#
# - Quantidade de notas
# - A maior nota
# - A menor nota
# - A média da turma
# - A situação (opcional)
#
# Adi... |
nz = 512 # noize vector size
nsf = 4 # encoded voxel size, scale factor
nvx = 32 # output voxel size
batch_size = 64
learning_rate = 2e-4
dataset_path_i = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox.thinned"
dataset_path_o = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_... |
# -*- coding: utf-8 -*-
# author:lyh
# datetime:2020/5/28 22:28
"""
394. 字符串解码
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcb... |
class Fiz_contact:
def __init__(self, lastname, firstname, middlename, email, telephone, password, confirmpassword):
self.lastname=lastname
self.firstname=firstname
self.middlename=middlename
self.email=email
self.telephone=telephone
self.password=password
sel... |
"""
igen stands for "invoice generator".
The project is currently inactive.
"""
|
def main():
with open("number.txt", "r") as file:
data = file.read()
data = data.split("\n")
x = [row.split("\t") for row in data[:5]]
print(function(x))
def function(x):
sum=0
for el in x[0:]:
sum += int(el[0])
return sum
if __name__=="__main__":
main();
|
a = input()
b= input()
print(ord(a) + ord(b))
|
def prastevila_do_n(n):
pra = [2,3,5,7]
for x in range(8,n+1):
d = True
for y in range(2,int(x ** 0.5) + 1):
if d == False:
break
elif x % y == 0:
d = False
if d == True:
pra.append(x)
return pra
def ... |
args_global = ['server_addr', 'port', 'timeout', 'verbose', 'dry_run', 'conn_retries',
'is_server', 'rpc_plugin', 'called_rpc_name', 'func', 'client']
def strip_globals(kwargs):
for arg in args_global:
kwargs.pop(arg, None)
def remove_null(kwargs):
keys = []
for key, value in kwar... |
datasetFile = open("datasets/rosalind_ba1e.txt", "r")
genome = datasetFile.readline().strip()
otherArgs = datasetFile.readline().strip()
k, L, t = map(lambda x: int(x), otherArgs.split(" "))
def findClumps(genome, k, L, t):
kmerIndex = {}
clumpedKmers = set()
for i in range(len(genome) - k + 1):
km... |
class Token:
def __init__(self, word, line, start, finish, category, reason=None):
self.__word__ = word
self.__line__ = line
self.__start__ = start
self.__finish__ = finish
self.__category__ = category
self.__reason__ = reason
@property
def word(self):
... |
# Node types
TYPE_NODE = b'\x10'
TYPE_NODE_NR = b'\x11'
# Gateway types
TYPE_GATEWAY = b'\x20'
TYPE_GATEWAY_TIME = b'\x21'
# Special types
TYPE_PROVISIONING = b'\xFF' |
#!/usr/bin/env python
# encoding: utf-8
"""
merge_intervals.py
Created by Shengwei on 2014-07-07.
"""
# https://oj.leetcode.com/problems/merge-intervals/
# tags: medium, array, interval
"""
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
# Have no idea how to do this
# import sys
# sys.path.insert(0, '../../data_structures')
# import node
def intersection(l1: Node, l2: Node) -> Node:
l1_end, len1 = get_tail(l1)
l2_end, len2 = get_tail(l2)
if l... |
# NAVI AND MATH
def power(base, exp):
res = 1
while exp>0:
if exp&1:
res = (res*base)%1000000007
exp = exp>>1
base = (base*base)%1000000007
return res%1000000007
mod = 1000000007
for i in range(int(input().strip())):
ans = "Case #" + str(i+1) + ': '
N = int(inpu... |
class Manifest:
def __init__(self, definition: dict):
self._definition = definition
def exists(self):
return self._definition is not None and self._definition != {}
def _resolve_node(self, name: str):
key = next((k for k in self._definition["nodes"].keys() if name == k.split(".")[-... |
print('=====================')
print(' 10 Termos de um PA')
print('=====================')
p = int(input('Primeiro Termo: '))
r = int(input('Razão: '))
for loop in range(p, ((r * 10) + p), r):
print('{} ->' .format(loop), end=' ')
print('Acabou') |
preço = float(input('Digite o preço do produto: R$'))
d = preço * 0.05
vD = preço - d
print('Valor original R${:.2f}, desconto de 5% é igual à R${:.2f}, seu novo preço é R${:.2f}'.format(preço, d, vD)) |
load(":import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "commons_fileupload_commons_fileupload",
artifact = "commons-fileupload:commons-fileupload:1.4",
artifact_sha256 = "a4ec02336f49253ea50405698b79232b8c5cbf02cb60df3a674d77a749a1def7"... |
class Node:
props = ()
def __init__(self, **kwargs):
for prop in kwargs:
if prop not in self.props:
raise Exception('Invalid property %r, allowed only: %s' %
(prop, self.props))
self.__dict__[prop] = kwargs[prop]
for prop... |
sort = lambda array: [sublist for sublist in sorted(array, key=lambda x: x[1])]
if __name__ == "__main__":
print(sort([
("English", 88),
("Social", 82),
("Science", 90),
("Math", 97)
]))
|
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
de = []
for i in range(0, len(nums), 2):
pair = []
pair.append(nums[i])
pair.append(nums[i + 1])
arr = [nums[i + 1]] * nums[i]
de += arr
return de
|
class SubCommand:
def __init__(self, command, description="", arguments=[], mutually_exclusive_arguments=[]):
self._command = command
self._description = description
self._arguments = arguments
self._mutually_exclusive_arguments = mutually_exclusive_arguments
def getCommand(self)... |
def read_file(filepath):
with open(filepath,'r') as i:
inst = [int(x) for x in i.read().replace(')','-1,').replace('(','1,').strip('\n').strip(',').split(',')]
return inst
def calculate(inst,floor=0):
for i,f in enumerate(inst):
floor += f
if floor < 0: break
... |
"""Exceptions for the Luftdaten Wrapper."""
class LuftdatenError(Exception):
"""General LuftdatenError exception occurred."""
pass
class LuftdatenConnectionError(LuftdatenError):
"""When a connection error is encountered."""
pass
class LuftdatenNoDataAvailable(LuftdatenError):
"""When no dat... |
def test_check_left_panel(app):
app.login(username="admin", password="admin")
app.main_page.get_menu_items_list()
app.main_page.check_all_admin_panel_items()
|
#
# PySNMP MIB module ALVARION-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALVARION-SMI
# Produced by pysmi-0.3.4 at Mon Apr 29 17:06:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
_QUEUED_JOBS_KEY = 'projects:global:jobs:queued'
_ARCHIVED_JOBS_KEY = 'projects:global:jobs:archived'
def list_jobs(redis):
return {job_id.decode() for job_id in redis.smembers(_QUEUED_JOBS_KEY)}
def remove_jobs(redis, job_id_project_mapping):
for job_id, project_name in job_id_project_mapping.items():
... |
#!/usr/bin/env python3
a = []
b = []
s = input()
while s != "end":
n = int(s)
if n % 2 == 1:
a.append(n)
else:
print(n)
s = input()
i = 0
while i < len(a):
print(a[i])
i = i + 1
|
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""config.py: Default configuration."""
# Server:
SERVER = 'wsgiref'
DOMAIN = 'localhost:7099'
HOST = 'localhost'
PORT = 7099
# Meta:
# Note on making it work in localhost:
# * Open a terminal, then do:
# - sudo gedit /etc/hosts
# * Enter the desired localhost alias for... |
# Copyright 2021 The XLS 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 or agreed to in writ... |
print('\033[1;32mANALISANDO DADOS\033[m')
jogador = dict()
gols = list()
jogadores = list()
print('-=' * 50)
while True:
gols.clear()
jogador['nome'] = str(input('Nome do jogador: '))
partidas = int(input('Quantas partidas esse jogador jogou: '))
for cont in range(1, partidas + 1, +1):
partida =... |
class InvalidBitstringError(BaseException):
pass
class InvalidQuantumKeyError(BaseException):
pass
|
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
ans = []
nums.sort()
for i in range(0, len(nums)-2):
if nums[i] > 0:
break
if i > 0 and nums[i-1] == nums[i]:
contin... |
def sum_all(ls):
sum = 0
if(len(ls) != 2):
print("Invalid input")
else:
ls.sort()
start = ls[0]
end = ls[1]
if(start == end):
sum = 2 * start
else:
for i in range(start, end+1):
sum += i
ret... |
# Primitive reimplementation of the buildflag_header scripts used in the gn build
def _buildflag_header_impl(ctx):
content = "// Generated by build/buildflag_header.bzl\n"
content += '// From "' + ctx.attr.name + '"\n'
content += "\n#ifndef %s_h\n" % ctx.attr.name
content += "#define %s_h\n\n" % ctx.at... |
# Space: O(n)
# Time: O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root):
if (root is None) or (root.left is None an... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'statement_listleftPLUSMINUSleftMULTIPLYDIVIDEAND ATOM BANG BOOL COLON COMMA DIVIDE ELIF ELSE END EQUAL EXIT FUN GT ID IF IMPORT LBRACE LBRACKET LPAREN LT MAC MINUS MULT... |
print('Sequência de Fibonacci')
print('='*24)
t = int(input('Número de termos da sequência: '))
print('='*24)
c = 3
termo1 = 0
termo2 = 1
print('A sequência é ({}, {}, '.format(termo1, termo2), end='')
while c <= t:
termo3 = termo1 + termo2
print('{}'.format(termo3), end='')
print(', ' if c < t else '', end... |
b = float(input('\033[36mQual a largura da parede? \033[m'))
h = float(input('\033[32mQual a altura da parede? \033[m'))
a = b * h
print('\033[36mSua parede tem dimensão {} x {} e sua área é de {:.3f}m².\033[m'.format(b, h, a))
print('\033[32mPara pintar essa parede, você precisará de {}L de tinta.\033[m'.format(a ... |
#!/usr/bin/env python3
NUMBER_OF_MARKS = 5
def avg(numbers):
return sum(numbers) / len(numbers)
def valid_mark(mark):
return 0 <= mark <= 100
def read_marks(number_of_marks):
marks_read = []
for count in range(number_of_marks):
while True:
mark = int(input(f'Enter mark #{coun... |
class Vertex:
'''This class will create Vertex of Graph, include methods
add neighbours(v) and rem_neighbor(v)'''
def __init__(self, n): # To initiate instance Graph Vertex
self.name = n
self.neighbors = list()
self.color = 'black'
def add_neighbor(self, v): # To add... |
"""
https://leetcode.com/contest/weekly-contest-281/problems/count-integers-with-even-digit-sum/
Tags: Weekly-Contest_281; Brute-Force; Easy
"""
class Solution:
def countEven(self, num: int) -> int:
ans = 0
for i in range(1, num + 1):
s = str(i)
# Digit Sum
... |
"""191. Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/
"""
class Solution:
def hammingWeight(self, n: int) -> int:
def low_bit(x: int) -> int:
return x & -x
ans = 0
while n != 0:
n -= low_bit(n)
ans += 1
return ans
|
input = [1, 1, 1, 1, 1, 1, 1, 4, 1, 2, 1, 1, 4, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 3, 1, 1, 2, 1, 2, 1, 3, 3, 4, 1, 4, 1, 1, 3, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 4, 1, 5, 1, 1, 1, 3, 1, 1, 5, 3, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 4, 1, 2, 2, 1, 1, 1, 3, 1, 2, 5, 1, 4,... |
def none_check(value):
if value is None:
return False
else:
return True
def is_empty(any_type_value):
if any_type_value:
return False
else:
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.