content stringlengths 7 1.05M |
|---|
class OrderDetail(object):
def __init__(self, pro_id, pro_count, storage_detail, half_storage_detail):
self.pro_id = pro_id
self.pro_count = pro_count
self.storage_count = storage_detail.get(pro_id=self.pro_id).pro_count
self.half_storage_count = half_storage_detail.get(half_id=self... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class LeecoSlots(object):
"""Docstring for LeecoSlots. """
__slots__ = ("_year", "_month", "_day",)
def __init__(self, year, month, day):
"""Test slots: 紧凑的内部表示, 存储空间优化, 缺点不能添加新的属性
:year: TODO
:month: TODO
:day: TODO
""... |
# -*- coding: utf-8 -*-
# STYLE SHEET
TEXT_OFF = """
padding: 5px;
font:17px "나눔스퀘어_ac Bold";
color : #353F40;
"""
TEXT_ON = """
padding: 5px;
font:17px "나눔스퀘어_ac Bold";
color : rgb(240, 48, 30);
"""
WIDGET_BG_BLACK = """
background-color: rgb(0, 0, 0);
border-radius: 20px;
"""
WIDGET_BG_WHITE = """
background-col... |
x = [1,2,3,1]
print(type(x))
print(dir(x))
print('count:',x.count(1)) # 2, number of times the input occurs
print('index:',x.index(1)) # returns location of input (first occurance)
print(x,' : x')
try:
x[0] = 1.2 # lists are mutable
except(TypeError) as e:
print(e)
print(x,' : x[0]= 1.2')
x.append(7)
print(x,' ... |
valor = int(input('\033[32mdigite um numero inteiro: \033[m'))
print("""\033[33mEscolha a opção de converção
[1] binário
[2] octal
[3] hexadecimal\033[m""")
n = int(input('Digite sua opção: '))
cor = {'lin':'\033[m','red': '\033[31m','gre':'\033[32m','yel':'\033[33m', 'blu':'\033[34m'}
print('{}-={}'.format(cor['blu'... |
def solveQuestion(inputPath):
fileP = open(inputPath, 'r')
fileLines = fileP.readlines()
fileP.close()
instructions = {}
toChangeInstructions = []
counter = 0
for valueLine in fileLines:
[instruction, value] = valueLine.strip('\n').split(' ')
instructions[counter] =... |
# Definition for singly-linked list.
#class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return he... |
class EWMA:
"""
Exponentially weighted moving average
"""
def __init__(self, momentum=0.98):
# set params
self._running_val = None
self._momentum = momentum
def update(self, new_val):
# update running val
if self._running_val is not None:
self._ru... |
"""
To understand what's going on:
1. The Merge Sort Recursively breaks down a list of size N to
left and right, each of size N/2;
2. The new sliced lists are fed to cmp_sort that rearranges the
fed total list of size N with index to be sorted in the original list.
Since, Original list is Mutable - This Original list c... |
ERROR_API_VERSION_NOT_FOUND = ("API version found in neither request path (/api/v#) nor 'Accept' "
'header (version=#)')
ERROR_API_VERSION_UNSUPPORTED = 'Unsupported API version'
ERROR_EMPTY_REQUEST_BODY = 'Empty request body - valid JSON required'
ERROR_ONLY_JSON_REQUESTS = 'WandAPI on... |
# Code generated by font_to_py.py.
# Font: Ubuntu-R.ttf
# Cmd: font_to_py.py /usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf 16 -x ubuntu16.py
version = '0.33'
def height():
return 16
def baseline():
return 13
def max_width():
return 15
def hmap():
return True
def reverse():
return False
def mon... |
MERCADO_ABERTO = 1
MERCADO_FECHADO = 2
CAMPEONATO = 'campeonato'
TURNO = 'turno'
MES = 'mes'
RODADA = 'rodada'
PATRIMONIO = 'patrimonio'
|
firstname = input("Enter first person name:")
secondname = input("Enter second person name:")
name = firstname + secondname
name = name.replace(" ","")
#print(name)
list = []
for x in name:
count = name.count(x)
if count > 0:
list.append(count)
name = name.replace(x,"").strip()
#print(list)
d... |
n1 = int(input('Digite um número inteiro: '))
n2 = n1*2
n3 = n1*3
n4 = n1*4
n5 = n1*5
n6 = n1*6
n7 = n1*7
n8 = n1*8
n9 = n1*9
n10 = n1*10
print('A tabuada de {} é: \n{}x1={} \n{}x2={} \n{}x3={}'.format(n1, n1, n1, n1, n2, n1, n3)) |
DEPOSIT = "deposit"
DEPOSIT_STABLE = "deposit_stable"
MINT = "mint"
SEND = "send"
|
data = (
'ke', # 0x00
'keg', # 0x01
'kegg', # 0x02
'kegs', # 0x03
'ken', # 0x04
'kenj', # 0x05
'kenh', # 0x06
'ked', # 0x07
'kel', # 0x08
'kelg', # 0x09
'kelm', # 0x0a
'kelb', # 0x0b
'kels', # 0x0c
'kelt', # 0x0d
'kelp', # 0x0e
'kelh', # 0x0f
'kem', # 0x10
'keb', # ... |
Scale.default = Scale.chromatic
Root.default = 0
Clock.bpm = 80
print(Scale.names())
print(SynthDefs)
print(Samples)
print(FxList)
print(Attributes)
print(PatternMethods)
print(Clock.playing)
var.ch = var([7,0,5,0,3],[4,4,4,4,8])
~p1 >> play('x..t', room=1)
~p2 >> play('f', dur=PDur(3,16)*2, room=1)
~p3 >> play('<V>... |
hnefatafl = """50022222005
00000200000
00000000000
20000100002
20001110002
22011711022
20001110002
20000100002
00000000000
00000200000
50022222005"""
brandubh = """5002005
0002000
0001000
2217122
0001000
0002000
5002005"""
hnefatafl_args = (hnefatafl, False)
brandubh_args = (brandubh, True)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Process:
""" this class is representing the process"""
def __init__(self, idt, arr, exc):
self.idt = idt
self.arr = arr
self.arr_aux = arr
self.exc = exc
self.prt = -1
self.start_exc = -1
def idt(self):
return self.idt
def arr(self):
return self.... |
"""
Moved to seperate py2pydantic package
"""
raise DeprecationWarning("Moved to front.py2pydantic")
|
#
# PySNMP MIB module CPQHSV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQHSV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:27:33 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, 09:... |
# Python Program To Create Emp Class
# And Make All The Members Of The Emp Class Available To Another Class ie. Myclass
'''
Function Name : This Class Contain Employee Details.
Function Date : 17 Sep 2020
Function Author : Prasad Dangare
Input : String,Integer
Output : String,... |
pi = 3.1456
def funcao1(a, b):
return a + b
|
# -*- coding: utf-8 -*-
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
pos = 0
for i in range(len(nums)):
if nums[i]:
nums[i], nums[pos]... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
# 2. Sum Matrix Columns
# Write a program that reads a matrix from the console and prints the sum for each column on separate lines.
# On the first line, you will get matrix sizes in format "{rows}, {columns}".
# On the next rows, you will get elements for each column separated with a single space.
# rows, cols = [int... |
# -*- coding: utf-8 -*-
'''
Código do professor (um pouco modificado)
'''
n, k = map(int, input().split())
qD = [None] * n
for i in range(n):
qD[i] = [0] * n
for x in range(k):
i, j, d = map(int, input().split())
for a in range(n):
for b in range(n):
if abs(a - i) + abs(b -... |
__all__ = (
"TagScriptError",
"WorkloadExceededError",
"ProcessError",
"EmbedParseError",
"BadColourArgument",
)
class TagScriptError(Exception):
"""Base class for all module errors."""
class WorkloadExceededError(TagScriptError):
"""Raised when the interpreter goes over its passed charac... |
class RawSecurityDescriptor(GenericSecurityDescriptor):
"""
Represents a security descriptor. A security descriptor includes an owner,a primary group,a Discretionary Access Control List (DACL),and a System Access Control List (SACL).
RawSecurityDescriptor(flags: ControlFlags,owner: SecurityIdentifier,gr... |
##Patterns: E0100
class Test():
##Err: E0100
def __init__(self):
for i in (1, 2, 3):
yield i * i |
class ChromaprintNotFoundException(Exception):
pass
class FingerprintGenerationError(Exception):
pass
class WebServiceError(Exception):
pass
class FileNotIdentifiedException(Exception):
pass
|
'''
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
'''
class Solution(object):
def maxSubArray(self, nums):
"""
:typ... |
class Sample():
# class object attribute
# same for any instant of a class
species = 'mammal'
def __init__(self, my_breed, name, spots):
# attributes
# we take in the argument
# Assign it using self.attribute_name
self.breed = my_breed
self.name = name
#... |
# 23049 - WH 4th job advancement
BELLE = 2159111
GELIMERS_KEY_CARD = 4032743
SECRET_PLAZA = 310010000
sm.setSpeakerID(BELLE)
sm.sendNext("Did you destroy the Black Wings' new weapon? Nice work. I'm proud to have you in the Resistance.")
if sm.sendAskYesNo("But it's too early to celebrate. #p2154009# will show up with... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: bov.py
#
# Tests: mesh - 3D rectilinear, multiple domain
# plots - Pseudocolor, Subset, Label, Contour
# operators - Slice
#
# Programmer: Brad Whitlock
# Date: ... |
def record(data, source, target="_use_source_"):
if source in data:
# get source var value:
source_var_value = data[source]
# get target var name:
if target == "_use_source_":
target = source
# record variable:
_ttp_["vars"].update({target: source_var_valu... |
def print_formatted(number):
align = len(bin(number)[2:])
for num in range(1, number + 1):
n_dec = str(num)
n_oct = oct(num)[2:]
n_hex = hex(num)[2:].upper()
n_bin = bin(num)[2:]
print(n_dec.rjust(align), n_oct.rjust(align), n_hex.rjust(align), n_bin.rjust(align)) |
#T# the following code shows how to do an algebraic determination that a quadrilateral is a parallelogram
#T# create the points of the quadrilateral
A = (0, 0)
B = (5, 0)
C = (8, 2.4)
D = (3, 2.4)
#T# calculate the slopes of the four sides
m_AB = (B[1] - A[1])/(B[0] - A[0]) # 0.0
m_BC = (C[1] - B[1])/(C[0] - B[0]) # ... |
EXPECTED_CREATE_REQUEST = {
'ServiceDeskPlus(val.ID===obj.ID)': {
'Request': {
'Subject': 'Create request test',
'Mode': {
'name': 'E-Mail',
'id': '123640000000006665'
},
'IsRead': False,
'CancellationRequested': Fal... |
# Declaracion de constantes.
PESO_HOT_WHEELS_REMOLQUE_TIBURON = 300
PESO_FUNKO_FELPA = 390
PRECIO_BARRA_PAN = 8.90
DESCUENTO_PAN_VIEJO = 0.20
|
# From https://github.com/RLBot/RLBot/blob/master/src/main/python/rlbot/version.py
# Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
# https://stackoverflow.com/questions/458550/st... |
# Copyright 2010-2018, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... |
class EventHook(object):
def __init__(self):
self.__handlers = []
def __iadd__(self, handler):
self.__handlers.append(handler)
return self
def __isub__(self, handler):
self.__handlers.remove(handler)
return self
def fire(self, *args, **keywargs):
for h... |
# lec10prob2.py
# In lecture, we saw a version of linear search that used the fact that a set
# of elements is sorted in increasing order. Here is the code from lecture:
def search(L, e):
for i in range(len(L)):
if L[i] == e:
return True
if L[i] > e:
return False
return... |
TEMPLATES_LOADED = "app.templates.loaded"
EXAMS_LOADED = "app.exams.loaded"
TEMPLATE_DIALOG_PATH_KEY = "template.dialog.path"
REPORT_DIALOG_PATH_KEY = "report.dialog.path"
EXAM_DIALOG_PATH_KEY = "exam.dialog.path"
PROCEED_TEMPLATE_DIALOG_PATH_KEY = "exam.proceed.dialog.path"
TEMPLATE_IMAGE_ZOOM = "template.image.zoom"
... |
#!/usr/bin/env python
#
# 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, softwa... |
resultados = str(input())
apuesta = str(input())
aciertos = 0
mirar = 0
hola = apuesta[3]
for x in resultados:
if x == apuesta[mirar]:
aciertos += 1
mirar += 1
print(aciertos)
|
l = open('input.txt').read().splitlines()
draw = list(map(int, l[0].split(',')))
boards = []
for i in range((len(l) - 1) // 6):
b = []
for j in range(5):
b.append(list(map(int, l[i * 6 + j + 2].split())))
boards.append(b)
# transform to sets
board_sets = []
for b in boards:
cur_sets = [set(r) f... |
"""
Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
"""
class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
m = len(... |
"""
0621, 第12题:
题目描述: 将整数转换为罗马数字
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Input: 3
Output: "III"
Input: 4
Output: "IV"
Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3. #
Input: 1994
Output: "MCMXCIV"
Expl... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 1 09:03:04 2021
@author: shubhransu
"""
print(3*3+3/3-3)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 19 01:36:17 2022
@author: henry
"""
|
alien_0 = {'color': 'green', 'points':5}
print(alien_0['color'])
print(alien_0['points'])
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] =5
print(alien_0)
alien_0 = {'color':'green'}
print(f"The alien is {alien_0['color']}."... |
"""
Django settings for data_backend project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
# SECUR... |
error_msg = {
"usedemail": "Email has already been used",
"email_format": "Please input a valid email.",
"no_email": "Please provide an email",
"usedname": "Username has already been taken",
"shortname": "Username must have at least three characters",
"no_letter": "Username should have a letter.... |
# -*- coding: utf-8 -*-
# Downloaded from: http://data.iana.org/TLD/tlds-alpha-by-domain.txt
# Use `make update_tlds` to update this list.
# Version 2015110901, Last Updated Tue Nov 10 07:07:01 2015 UTC
def TLDs():
for tld in [
u'aaa',
u'aarp',
u'abb',
u'abbott',
u'abogado... |
# Python Program to find Area of a Triangle
a = float(input('Please Enter the First side of a Triangle: '))
b = float(input('Please Enter the Second side of a Triangle: '))
c = float(input('Please Enter the Third side of a Triangle: '))
# calculate the Perimeter
Perimeter = a + b + c
# calculate the semi-perimeter
s... |
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#This program is free software; you can redistribute it and/or modify it under the terms of the BSD 0-Clause License.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ... |
# Copyright (c) Project Jupyter.
# Distributed under the terms of the Modified BSD License.
__version__ = '0.7.16'
|
'''
@author: zhzj
Successione di Padovan
La successione di Padovan è la serie di numeri naturali P(n)
definita dai valori iniziali:
P(0) = P(1) = P(2) = 1
E per tutti i valori di n > 3 dalla relazione:
P(n) = P(n-2) + P(n-3)
I primi valori della successione sono:
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, …
Scrivere... |
# Exercico 1 - Dicionario
# Escreva programa que leia os dados de cerveja
# Cerveja: Marca, tipo , IBU , ABV , Volume , EBC
# Crie um dicionario para armazenar os dados
# Imprima os dados do dicionario (não dicionario completo)
marca = (input('Informe a marca da cerveja'))
tipo = (input('Informe o Tipo da cerveja'))
i... |
# encoding: utf-8
# module Autodesk.Revit.UI.Macros calls itself Macros
# from RevitAPIUI, Version=17.0.0.0, Culture=neutral, PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class ApplicationEntryPoint(UIApplication, IDisposable, IEntryPoint):
"""
For Revit ... |
#
# PySNMP MIB module CISCO-FABRICPATH-TOPOLOGY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-FABRICPATH-TOPOLOGY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:57:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
def mdc(m,n):
if n==0: return m
return mdc(n,m%n)
for k in range(int(input())):
A = input().split()
op = A[3]
A[0] = int(A[0])
A[1] = int(A[2])
A[2] = int(A[4])
A[3] = int(A[6])
res = [[],[]]
if op == '+':
res[0] = A[0]*A[3]+A[2]*A[1]
res[1] = A[1]*A[3]
elif ... |
# Mensagem Pessoal: use uma variável para representar o nome de uma pessoa e imprima uma mensagem para essa pessoa.
# Sua mensagem deve ser simples, como "Olá Eric, gostaria de aprender um pouco de Python hoje?"
nome = "eric"
print(f"Olá {nome.title()}, gostaria de aprender um pouco de Python hoje?")
|
class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
"""BFS.
"""
d = defaultdict(list)
for i in range(len(routes)):
for stop in routes[i]:
d[stop].append(i)
q = deque([(source, 0)])
v = ... |
''' Jonatan Paschoal 11/05/2020 - Crie um programa que receba nome de uma pessoa e verifique se ela te silva'''
print('---------------'*3)
nome = input('Digite o seu nome: ')
#------------------------------------------------------------
x = nome.lower()
y = 'silva' in x
#----------------------------------------------... |
class Arduino():
def __init__(self):
self._temperatura = 0.0 # atributos privados
self._presenca = 0
self._luminosidade = 0.0
@property # proppertys e setters
def temperatura(self): # acessa propriedade protegida (privada) e retorna o valor atual dela
return self._temper... |
description = 'Julabo F25 for the Huginn-sans.'
pv_root = 'SES-HGNSANS-01:WTctrl-JUL25HL-001:'
devices = dict(
T_julabo=device(
'nicos.devices.epics.pva.EpicsAnalogMoveable',
description='The temperature',
readpv='{}TEMP'.format(pv_root),
writepv='{}TEMP:SP1'.format(pv_root),
... |
__all__ = ["ExpressionError", "EmptySubExpressionError",
"ParenthesisError", "BadEscapedSymbolError",
"UnexpectedEndError"]
class ExpressionError(Exception):
"""Type for all errors which can happen while parsing."""
pass
class EmptySubExpressionError(ExpressionError):
pass
class ... |
name = 'Markov Bot'
username = '@MarkovZHBot'
self_id = 648433061
version = '0.9.9'
channel = 'local'
repo = 'https://github.com/oudoubleyang/MarkovZHBot'
bot_url = 'https://markov.gcp.o2y.cc'
brain_url = 'https://brain.gcp.o2y.cc'
renew_rate = 0.1
user_cool_threshold = 100 # per hour
chat_cool_threshold = 500
bl_tr... |
class Solution:
def checkRecord(self, n: int) -> int:
if n == 0: return 0
if n == 1: return 3
if n == 2: return 8
MAX = 1000000007
dp = [1, 2, 4]
i = 3
while i < n:
dp.append((dp[i - 1] + dp[i - 2] + dp[i - 3]) % MAX)
i += 1
... |
def make_version_string(version_info):
"""
Turn a version tuple in to a version string, taking in to account any pre,
post, and dev release tags, formatted according to PEP 440.
"""
version_info = list(version_info)
numbers = []
while version_info and isinstance(version_info[0], int):
... |
class House:
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, new_price):
if new_price > 0 and isinstance(new_price, float):
self._price = new_price
else:
print("Pleas... |
class FE_SCRIPTS:
_fesname = ""
_miniDesc = ""
_totalDesc = ""
_Opt = {}
_author = ""
def __init__(self, fesname,miniDesc,totalDesc,Opt,author):
self._fesname = fesname
self._miniDesc = miniDesc
self._totalDesc = totalDesc
self._Opt = Opt
self._... |
class HTMLParseError(Exception):
"""
A generic HTML parsing errors validators can throw.
"""
message: str
def __init__(self, message: str):
self.message = message
def __str__(self):
return "Parse Error: {}".format(self.message)
|
'''
import asyncio
import functools
import json
import platform
import re
import secrets
import time
from pathlib import Path
from aiohttp import web
import aiohttp
import multidict
from gd.typing import (
Any,
Awaitable,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Sequen... |
INVALID_MARKER = "✗"
STREAM_MARKER_PRIVATE = "P"
STREAM_MARKER_PUBLIC = "#"
STREAM_TOPIC_SEPARATOR = "▶"
# Used as a separator between messages and 'EDITED'
MESSAGE_CONTENT_MARKER = "▒" # Options are '█', '▓', '▒', '░'
QUOTED_TEXT_MARKER = "░"
MESSAGE_HEADER_DIVIDER = "━"
CHECK_MARK = "✓"
APPLICATION_TITLE_BAR_LINE = ... |
#
# PySNMP MIB module MERU-CONFIG-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MERU-CONFIG-QOS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:01:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
'''
1. Implemente um programa em Python que leia 15 números informados pelo usuário. Utilizando uma estrutura de pilha, realize as seguintes tarefas:
a) Se o número for impar, adicione na pilha.
b) Se o número for par, remova um elemento da pilha caso a pilha não seja vazia.
Ao final das 15 execuções, mostre a... |
argent = int(input())
prixLivre = int(input())
print(argent // prixLivre)
|
class Solution:
def maxWidthOfVerticalArea(self, points):
xs = sorted([x for x, y in points])
ans = 0
for i in range(len(xs) - 1):
ans = max(ans, xs[i+1] - xs[i])
return ans |
# -*- coding: utf-8 -*-
"""
Copyright () 2018
All rights reserved
FILE: count_sort.py
AUTHOR: tianyuningmou
DATE CREATED: @Time : 2018/4/11 上午9:53
DESCRIPTION: .
VERSION: : #1
CHANGED By: : tianyuningmou
CHANGE: :
MODIFIED: : @Time : 2018/4/11 上午9:53
"""
"""
计数排序
时间复杂度:O(d(r+n))
空间复杂度:O(rd+n)
算法稳定性:稳定
注:r代表... |
def meu_maximo(a=0, b=0, c=0, d=0, e=0):
return max((a, b, c, d, e))
def meu_maximo_infinito(**kwargs):
return max(kwargs.values())
dicionario = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
print(meu_maximo(**dicionario))
print(meu_maximo_infinito(**dicionario)) |
nome = input('Qual é o seu nome? ')
print('Prazer em te conhecer, {:=^20}!'.format(nome))
# :20(limite de letras)
# :>20(alinha para direita)
# :<20(alinha para esquerda)
# :^20(alinha no meio) |
while True:
try:
n = int(input())
v = []
for i in range(n):
v.append(float(input()))
print(sorted(v)[0])
except EOFError: break
|
#----
# Заметки
# TODO: все комплекты снаряжения переносим в output_tools. Так удобнее.
#----
# Железнодорожные инструменты (дистанции пути):
metadict_model['Оборудование дистанции пути'] = {
# TODO:
# Не используется.
# Да и не допилено, слишком современно для понях.
# ht... |
BOARD = 1
OUT = 1
IN = 1
HIGH = 1
LOW = 1
def setmode(*args, **kwargs):
print('moch gpio setmode')
def setup(*args, **kwargs):
print('moch gpio setup')
def output(*args, **kwargs):
print('moch gpio output')
def cleanup():
print('moch gpio clean up')
def setwarnings(*args, **kwargs):
print('set... |
"""
function 1 : find_pairs
@param list : list of numbers
@param sum : sum to find
@return pairs : list of pairs
@author : Josue Lubaki
"""
def find_pairs(list, sum):
pairs = []
for (i, a) in enumerate(list):
for (_, b) in enumerate(list[i+1:]):
if a + b == sum:
... |
class Shirt:
PRICE = 500
def __init__(self, quantity):
self._total_cost = quantity * Shirt.PRICE
print("Total cost:", self._total_cost)
if __name__ == "__main__":
shirt = Shirt(5); |
# structure of a node in a doubly linked list
class Node:
def __init__(self, val, next_node=None, prev_node=None):
"""
Node constructor, next and prev are optional
"""
self.val = val
self.next_node = next_node
self.prev_node = prev_node
def __str__(self):
... |
class GlobusError(Exception):
"""
Root of the Globus Exception hierarchy.
Stub class.
"""
class GlobusSDKUsageError(GlobusError, ValueError):
"""
A ``GlobusSDKUsageError`` may be thrown in cases in which the SDK
detects that it is being used improperly.
These errors typically indicate... |
__all__ = ["adjust_energy",
"check_imputed_energies",
"csv2hdf5",
"mergetelescopes.py",
"merge_wrapper",
"normalisation",
"process_star",
"process_superstar",
"root2csv",
"newmultidirs.py",
"remove_events",
... |
def lint_output(tool_xml, lint_ctx):
outputs = tool_xml.findall("./outputs/data")
if not outputs:
lint_ctx.warn("Tool contains no outputs, most tools should produce outputs.")
return
num_outputs = 0
for output in outputs:
num_outputs += 1
output_attrib = output.attrib
... |
BASE_URL = "https://www.codewars.com/"
USERNAME = "_behelit"
HEADERS = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/76.0.3809.100 "
"Safari/537.36",
}
DATA = {
"utf8": "",
"user[remember_me]": "true",
}
|
class DataObject:
header = ''
def __init__(self, name):
self.name = name
if self.name == None:
self.name = ''
self.print_str = ' ' * 20
self.calories = 0
self.cal_carbs = 0
self.cal_fat = 0
self.cal_protein = 0
self.carbs = 0
... |
__all__ = ["Definition", "find_file"]
class Definition(object):
'''
All Definitions should inherit this.
For a given subject and session within the API, the definition is used
to create a given mask, map, etc.
Definitions have an init function which the users uses to specify
how they want the ... |
"""
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can
represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
sea... |
def is_valid(i):
# check if the number at index i is valid, i.e. the sum of two numbers in the previous 25 numbers
test_range = xmas_data[i - preamble:i]
test_value = xmas_data[i]
for a in test_range:
if (b := test_value - a) in test_range and a != b:
return True
return False
... |
class ClassB(object):
def kw_1(self):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.