content stringlengths 7 1.05M |
|---|
class Movie:
"""
This is an abstract a movie structure
"""
def __init__(self, leading_actor='Leonardo DiCaprio',
supporting_actor='Brad Pitt',
run_time=130):
self.leading_actor = leading_actor
self.supporting_actor = supporting_actor
self.run_time = run_time
def who... |
"""f90nml.fpy
=============
Module for conversion between basic data types and Fortran string
representations.
:copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
:license: Apache License, Version 2.0, see LICENSE for details.
"""
def pyfloat(v_str):
"""Convert string repr of Fortr... |
f = input('Digite uma frase: ').lower().replace(' ', '')
cont = 0
i = 0
for c in range(len(f), 0, -1):
if f[i] == f[c-1]:
cont += 1
i += 1
if cont == len(f):
print('Temos um palíndromo')
else:
print('Não temos um palíndromo')
|
"""
104.二叉树的最大深度
时间复杂度:O(logn)
空间复杂度:O(1)
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.right = None
self.left = None
def createTreeNode(node_list):
if not node_list[0]:
return None
root = TreeNode(node_list[0])
Nodes = [root]
j = 1
for node... |
class Zone:
def __init__(self) -> None:
self._display_name = ""
self._offset = 0
def get_display_name(self) -> str:
return self._display_name
def get_offset(self) -> int:
return self._offset
|
'''
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
'''
class NumArray(object):
def __ini... |
def is_prime(n):
for x in range(2, n):
if n % x == 0:
return False
return True
def get_prime_numbers(n):
for x in range(n, 1, -1):
if is_prime(x):
yield x
def get_two_sum(primes, number):
for i, q in enumerate(primes):
next_values = primes[i + 1:]
... |
opcodes = {
'STOP': [0x00, 0, 0, 0],
'ADD': [0x01, 2, 1, 3],
'MUL': [0x02, 2, 1, 5],
'SUB': [0x03, 2, 1, 3],
'DIV': [0x04, 2, 1, 5],
'SDIV': [0x05, 2, 1, 5],
'MOD': [0x06, 2, 1, 5],
'SMOD': [0x07, 2, 1, 5],
'ADDMOD': [0x08, 3, 1, 8],
'MULMOD': [0x09, 3, 1, 8],
'EXP': [0x0a, 2... |
singular_to_plural_dictionary = {
"1": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"security-zone": "security-zones",
"time": "times",
"simple... |
class Node:
def __init__(self, node_id, lon, lat, cluster_id_belongto: int):
self.node_id = int(node_id)
self.lon = lon
self.lat = lat
self.cluster_id_belongto = cluster_id_belongto |
# cook your dish here
t = int(input()) # Taking the Number of Test Cases
for i in range(t): # Looping over test cases
n = int(input()) # Taking the length of songs input
p = [int(i) for i in input().split()] # Taking the list of song... |
print("Insert a string")
s = input()
print("Insert the number of times it will be repeated")
n = int(input())
res = ""
for i in range(n):
res = res + s
print(res)
|
#Twitter API Credentials
consumer_key = 'consumerkey'
consumer_secret = 'consumersecret'
access_token = 'accesstoken'
access_secret = 'accesssecret'
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class BerkeleyDb(AutotoolsPackage):
"""Oracle Berkeley DB"""
homepage = "https://www.oracle.com/database/technol... |
def findXorSum(arr, n):
Sum = 0
mul = 1
for i in range(30):
c_odd = 0
odd = 0
for j in range(n):
if ((arr[j] & (1 << i)) > 0):
odd = (~odd)
if (odd):
c_odd += 1
for j in range(n):
Sum += (mul * c_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class APIException(Exception):
"""
Base class for all API exceptions.
"""
pass
class APIError(APIException):
"""
An API error signifies a problem with the server, a temporary issue or some other easily-repairable
problem.
"""
pass
c... |
# Leia um frase completa e mostre quantas veze aparece a letra a, em qual posiçao aparece pela 1 vez
# em qual posição aparece pela ultima vez
frase = str(input('Digite uma frase qualquer: ')).upper().strip()
print(frase.count('A'))
print(frase.find('A')+1)
print(frase.rfind('A')+1) # Começa da direita para esquerda... |
#
# PySNMP MIB module CISCOSB-TBI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-TBI-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
n = int(input('Digite um número inteiro aqui: '))
n2 = float(input('Digite um número real ou flutuante aqui: '))
a = n + n2
b = n - n2
c = n * n2
d = n / n2
e = n // n2
f = n % n2
g = n ** n2
print('A soma desses dois números é {}. A subtração é {}. \nA multiplicação é {} e a divisão é {}. \nA divisão inteira é igual a... |
def pation(nums):
tmp = nums[0]
nums[0] = nums[1]
nums[1] = tmp
return 1
def main():
nums = [3,2,1]
p = pation(nums)
for n in nums:
print(n)
if __name__ == "__main__":
main()
|
def create_grades_dict(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
no_return_list = []
for item in data:
no_return_list.append(item.strip('\n'))
no_spaces_list =[]
for item in no_return_list:
no_spaces_list.append(item.replace(' ',''))
list_of... |
#: docstring for CONSTANT1
CONSTANT1 = ""
CONSTANT2 = ""
|
l, r = map(int, input().split(" "))
if l == r:
print(l)
else:
print(2)
|
class Session:
pass
class DB:
@staticmethod
def get_rds_host():
return '127.0.0.1'
def __init__(self, user, password, host, database) -> None:
pass
def getSession(self):
return Session
|
CHAR_PLUS = ord(b'+')
CHAR_NEWLINE = ord(b'\n')
def buffered_blob(handle, bufsize):
backlog = b''
blob = b''
while True:
blob = handle.read(bufsize)
if blob == b'':
# Could be end of files
yield backlog
break
if backlog != b'':
blob ... |
"""
Mock unicornhathd module.
The intention is to use this module when developing on a different computer than a Raspberry PI with the UnicornHAT
attached, e.g. on a Mac laptop. In such case, this module will simply provide the same functions as the original
uncornhathd module, however most of them will do absolutely ... |
# general I/O parameters
OUTPUT_TYPE = "images"
LABEL_MAPPING = "pascal"
VIDEO_FILE = "data/videos/Ylojarvi-gridiajo-two-guys-moving.mov"
OUT_RESOLUTION = None # (3840, 2024)
OUTPUT_PATH = "data/predictions/Ylojarvi-gridiajo-two-guys-moving-air-output"
FRAME_OFFSET = 600 # 1560
PROCESS_NUM_FRAMES = 300
COMPRESS_VIDEO =... |
class Coord(object):
"""
Represent Cartesian coordinates.
"""
def __init__(self, x=0, y=0):
self._x = x
self._y = y
class Data(object):
"""
Represent list of coordinates.
"""
def __init__(self):
self._data = []
|
#!/usr/bin/env python
globaldecls = []
globalvars = {}
def add_new(decl):
if decl:
globaldecls.append(decl)
globalvars[decl.name] = decl
|
class BaseClass:
def __str__(self):
return self.__class__.__name__
def get_params(self, deep=True):
pass
def set_params(self, **params):
pass
class BaseTFWrapperSklearn(BaseClass):
def compile_graph(self, input_shapes):
pass
def get_tf_values(self,... |
"""Utils for time travel testings."""
def _t(rel=0.0):
"""Return an absolute time from the relative time given.
The minimal allowed time in windows is 86400 seconds, for some reason. In
stead of doing the arithmetic in the tests themselves, this function should
be used.
The value `86400` is expo... |
#!/usr/bin/python
# encoding: utf-8
"""
作者:糖葫芦
创建时间:2020/3/2918:58
文件:__init__.py.py
IDE:PyCharm
""" |
# 289. Game of Life
class Solution:
def gameOfLife2(self, board) -> None:
rows, cols = len(board), len(board[0])
nextState = [row[:] for row in board]
dirs = ((0,1), (1,0), (-1,0), (0,-1), (-1,-1), (-1,1), (1,-1), (1,1))
for i in range(rows):
for j in range(cols)... |
# Задача 3. Вариант 6.
# Напишите программу, которая выводит имя "Самюэл Ленгхорн Клеменс", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
# Velyan A. S.
# 27.05.2016
print("Герой нашей сегодняшней программы - Сэмюэл Ленгхор... |
cache = {}
def binomial_coeff(n, k):
"""Compute the binomial coefficient 'n choose k'.
n: number of trials
k: number of successes
returns: int
"""
if k == 0:
return 1
if n == 0:
return 0
try:
return cache[n,k]
except KeyError:
cache[n,k... |
'''https://leetcode.com/problems/merge-two-sorted-lists/'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Iterative Solution
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = l3 = ListNo... |
q = {
'get_page_id_from_frontier': "UPDATE crawldb.frontier \
SET occupied=True \
WHERE page_id=( \
SELECT page_id \
FROM crawldb.frontier as f \
... |
#Faça um programa que mostre o preço de um produto, e mostre seu nvo preço com 5% de desconto.
preço = float(input('Qual o preço original? R$'))
desconto = preço*0.05
total = preço - desconto
print('Sendo o preço original R${:.2f}, com o desconto de 5% fica a R${:.2f}'.format(preço, total ))
#pode ser assim tb,[ descon... |
class NotarizerException(Exception):
def __init__(self, error_code, error_message):
super().__init__(error_message)
self.error_code = error_code
class NoSignatureFound(NotarizerException):
def __init__(self, error_message):
super().__init__(10, error_message)
class InvalidLabelSignat... |
#!/usr/bin/env python
"""
__init__
Module containing common components for creating
components.
"""
|
with open("input.txt", "r") as file:
numbers = list(map(int, file.readline().split(",")))
boards = []
line = file.readline() # throw away
while line:
board = []
for i in range(5):
line = file.readline()
board.append(list(map(int, filter(lambda x: len(x) > 0, line.... |
#
# PySNMP MIB module ELTEX-DOT3-OAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-DOT3-OAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:45:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
# operacoes matematica
x = 53
y = 42
# operacoes comuns
soma = x + y
mult = x * y
div = x / y
sub = x - y
# divisao inteira
div_int = x // y
# resto de Divisao
rest_div = x % y
# potencia
potencia = x ** y
print (soma)
print (mult)
print (div)
print (sub)
print ("Divisao inteira")
print (div_int)
print ("... |
class Secret:
def __init__(self):
self._secret=99
self.__top_secret=100
x=Secret()
x._secret
x.__top_secret
x._Secret__top_secret |
# Normal List = 39
# Last Card = 5
List = [\
{'eng_title':"SERMONE", 'han_title':"예배 시간",\
'description':"자신의 턴, <뱅!> 카드를 사용 금지."},\
{'eng_title':"ROULETTE RUSSA", 'han_title':"러시안 룰렛",\
'description':"이 카드가 발동한 순간, 보완관부터 시작해 순서대로 <빗나감!> 카드를 1장씩 버림. 만약 카드를 버리지 못할 경우, 그 플레이어는 생명령 2를 깎는다."},\
{'eng_title':"DEAD MAN"... |
### ML SPECIFIC FUNCTIONS
### FOR FEATURE ENGINEERING
# ENCODE EVENT -- 1--event, 0--no event
def bin_event(x):
x=int(x)
if(x!=0):
return 1
else:
return 0
# YES OR NO
def bin_weather(x):
x=float(x)
if(x>0):
return 1
else:
return 0
# BIN PRECIPITATION TYPE
def bi... |
class DependencyException(Exception):
def __init__(self, message, product):
super(Exception, self).__init__(message)
self.message = message
self.product = product
self.do_not_print = True
class SelfUpgradeException(Exception):
def __init__(self, message, parent_pid):
... |
for i in incorrect_idx:
print('%d: Predicted %d True label %d' % (i, pred_y[i], test_y[i]))
# Plot two dimensions
_, ax = plt.subplots()
for n in np.unique(test_y):
idx = np.where(test_y == n)[0]
ax.scatter(test_X[idx, 1], test_X[idx, 2], color=f"C{n}", label=f"Class {str(n)}")
for i, marker in zip(incor... |
# -*- coding: UTF-8 -*-
# Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
#
# Python, Python 3 all accepted.
# Maybe the ugliest code I have ever written since I learned Python.
class AddBinary(object):
def addBinary(self, a, b):
"""... |
# Copyright (c) 2012-2022, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
def validate_runtime_environment(runtime_environment):
"""
Validate RuntimeEnvironment for Application
Property: Application.RuntimeEnvironment
"""
VALID_RUNTIME_ENVIRONMENTS = ("SQL... |
y_a = [2, 2, -2, -2, -1, -1, 1, 1]
x_a = [1, -1, 1, -1, 2, -2, 2, -2]
s = []
start = list(map(int, input().split()))
stop = list(map(int, input().split()))
q = [start, None]
c = 0
def add_8_paths(p):
for a in range(8):
np = [p[0] + x_a[a], p[1] + y_a[a]]
if np not in q and np not in s and np[0] >... |
# Software released under the MIT license (see project root for license file)
class Header():
def __init__(self):
self.version = 1
self.test_name = "not set"
# ------------------------------------------------------------------------------
class Base:
def __init__(self):
pa... |
# This is an example of staring two servo services
# and showing each servo in a separate tab in the browsee
# Start the servo services
s1 = Runtime.createAndStart("Servo1","Servo")
s2 = Runtime.createAndStart("Servo2","Servo")
# Start the webgui service without starting the browser
webgui = Runtime.create("WebGui","... |
load("@halide//:halide_config.bzl", "halide_system_libs")
def halide_language_copts():
_common_opts = [
"-DGOOGLE_PROTOBUF_NO_RTTI",
"-fPIC",
"-fno-rtti",
"-std=c++11",
"-Wno-conversion",
"-Wno-sign-compare",
]
_posix_opts = [
"$(STACK_FRAME_UNLIMITED)",
"-fno-exce... |
# pylint: disable=missing-function-docstring, missing-module-docstring/
def compare_str_isnot() :
n = 'hello world'
a = 'hello world'
return n is not a
|
def calcOccurrences(itemset: list) -> int:
return len(list(filter(lambda x: x == 1, itemset)))
def calcOccurrencesOfBoth(itemset1: list, itemset2: list) -> int:
count: int = 0
for i in range(len(itemset1)):
if itemset1[i] == 1 and itemset2[i] == 1:
count += 1
return count
def support(*itemsets) -> float:
... |
# names = ['LHL','YB','ZSH','LY','DYC']
# # print(str(x[0]) + str(x[1]) + str(x[2]) + str(x[3]) + str(x[4]));
# for name in names:
# print(name.lower().title());
# print("SB:" + name);
# for name in names:
# print(name.lower().title());
# print("SB:" + name);
# for name in names:
# print(name.low... |
""" Version information for Lackey module
"""
__version__ = "0.7.4"
__sikuli_version__ = "1.1.0"
|
'''
@author: zhzj
Scrivere un programma che legge un intero positivo n da stdin e verifica se n è un numero mancante, perfetto o abbondante.
Chiamiamo S(n) la somma di tutti i divisori propri di n (1 incluso, n escluso).
Un numero n si dice perfetto se n = S(n), mancante se n > S(n), abbondante se n < S(n). Esempio:... |
# Source : https://leetcode.com/problems/minimum-moves-to-convert-string/
# Author : foxfromworld
# Date : 10/12/2021
# First attempt
class Solution:
def minimumMoves(self, s: str) -> int:
index = 0
ret = 0
while index < len(s):
if s[index] == 'X':
ret += 1
... |
def fact(n):
return 1 if n == 0 else n*fact(n-1)
def comb(n, x):
return fact(n) / (fact(x) * fact(n-x))
def b(x, n, p):
return comb(n, x) * p**x * (1-p)**(n-x)
l, r = list(map(float, input().split(" ")))
odds = l / r
print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3))
|
n, m = map(int, input().split())
for _ in range(n):
if input().find('LOVE') != -1:
print('YES')
exit()
print('NO')
|
# Created byMartin.cz
# Copyright (c) Martin Strohalm. All rights reserved.
class Enum(object):
"""
Defines a generic enum type, where values are provided as key:value pairs.
The key can be used to access the value like from dict (e.g. enum[key]) or
as property (e.g. enum.key). Each value must be un... |
# base path to YOLO directory
MODEL_PATH = "yolo-coco"
# initialize minimum probability to filter weak detections along with
# the threshold when applying non-maxima suppression
MIN_CONF = 0.3
NMS_THRESH = 0.3
# boolean indicating if NVIDIA CUDA GPU should be used
USE_GPU = True
# define the minimum safe distance (in p... |
# server.py flask configuration
# To use this file first export this path as SERVER_SETTINGS, before running
# the flask server. i.e. export SERVER_SETTINGS=config.py
LIRC_PATH = "/dev/lirc0"
SAVE_STATE_PATH = "/tmp/heatpump.state" |
cx = 0
cy = 0
fsize = 0
counter = 0
class FunnyRect():
def setCenter(self, x,y):
self.cx = x
self.cy = y
def setSize(self, size):
self.size = size
def render(self):
rect(self.cx, self.cy, self.size, self.size)
funnyRect0b = FunnyRect()
funnyRect0b1 = FunnyRect()
def setu... |
#
# PySNMP MIB module DVMRP-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:17:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
class Solution(object):
def combinationSum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
def combinationSumRecu(self, candidates, result, start, intermediate, target):
if target == 0:
result.a... |
print('==Analisador de uma Progressão Aritmética==')
a1 = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razão: '))
print('Os 10 primeiros termos dessa PA são: ')
cont = 0
termo = a1
while cont != 10:
cont += 1
if cont == 1:
print('{}, '.format(a1), end='')
else:
termo += r
... |
"""This file provides the PEP0249 compliant variables for this module.
See https://www.python.org/dev/peps/pep-0249 for more information on these.
"""
# Copyright 2012, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
# Follows the... |
_EVT_INIT = 'INITIALIZE'
EVT_START = 'START'
EVT_READY = 'READY'
EVT_CLOSE = 'CLOSE'
EVT_STOP = 'STOP'
EVT_APP_LOAD = 'APP_LOAD'
EVT_APP_UNLOAD = 'APP_UNLOAD'
EVT_INTENT_SUBSCRIBE = 'INTENT_SUBSCRIBE'
EVT_INTENT_START = 'INTENT_START'
EVT_INTENT_END = 'INTENT_END'
EVT_ANY = '*'
_META_EVENTS = (
_EVT_INIT, EVT_... |
#
# PySNMP MIB module ADTRAN-AOS-DESKTOP-AUDITING (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-DESKTOP-AUDITING
# Produced by pysmi-0.3.4 at Wed May 1 11:13:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
try:
raise ValueError("invalid!")
except ValueError as error:
print(str(error) + " input")
finally:
print("Finishd")
|
'''
Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato
Brasileiro de Futebol, na ordem de colocação. Depois mostre:
A) Apenas os 5 primeiros colocados.
B) Os últimos 4 colocados da tabela.
C) Uma lista com os times em ordem alfabética.
D) Em que posição na tabela está o time da Chapecoense.... |
if __name__ == "__main__":
a = [1,2,3]
i = -1
print(a[-1])
for i in range(-1,-4,-1):
print(a[i]) |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for build/chromeos/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API bui... |
N, W = map(int, input().split())
vw = [list(map(int, input().split())) for _ in range(N)]
dp = [[0] * W for _ in range(N)]
for i in range(N):
for w in range(W):
if w >= vw[i][1]:
dp[i + 1][w] = max(dp[i][w - vw[i][1]] + vw[i][0], dp[i][w])
|
valor = int(input("Informe um valor: "))
triplo = valor * 3
contador = 0
while contador<5:
print(triplo)
contador = contador + 1
print("Acabou!")
|
class IBindingList:
""" Provides the features required to support both complex and simple scenarios when binding to a data source. """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return IBindingList()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def AddIndex(self,propert... |
__author__ = 'alse'
def content_length_test(train_metas, test_examples):
max_length = 0.0
min_length = 1000.0
for metadata in train_metas:
if max_length < metadata.length * 1.0 / metadata.size:
max_length = metadata.length * 1.0 / metadata.size
if min_length > metadata.length ... |
while True:
op = input("Digite o Operador: ")
result = 0
if (op != '+') and (op != '-') and (op != '*') and (op != '/') and (op != '#'):
print("Operador invalido!")
else:
if op == '#':
print("Encerrando!")
break
n1 = float(input("Digite o valor 1: "))
... |
input = """
% Bug in rewrinting. Count is eliminated as it is considered isolated.
% Instead it must be considered as a false literal as the aggregate is
% always violated, and bug shouldn't be true.
c(1).
b(1).
bug :- c(Y), Y < #sum{ V:b(V) }.
"""
output = """
{b(1), c(1)}
"""
|
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
nums_copy = nums.copy()
ret = []
count = 0
for i in range(len(nums)):
nums.pop(i)
nums.insert(0, nums_copy[i])
count = 0
j = 1
while j < len(... |
""" Misc. code helper """
def _generate_unique_attribute(fun):
return "__init_%s_%s" % (fun.func_name, str(id(fun)))
def init_function_attrs(fun, **vars):
""" Add the variables with values as attributes to the function fun
if they do not exist and return the function.
Usage: self = init_function_attr(myFun, a... |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/betting-game/0
def sol(s):
"""
Update rules as per the statement
"""
ba = 1
n = len(s)
i = 0
t = 4
while i < n:
if t < ba:
return -1
if s[i] == "W":
t = t + ba
ba = 1
... |
#############################################################
# rename or copy this file to config.py if you make changes #
#############################################################
# change this to your fully-qualified domain name to run a
# remote server. The default value of localhost will
# only allow connect... |
# Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
# According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a desce... |
#住所録追加
def addAddress(name,address,tel,mail):
item = [name,address,tel,mail]
addressList.append(item)
print("登録しました。")
print()
#住所録表示
def showAddress(addressNum):
obj = addressList[addressNum-1]
print("名前:" + obj[0])
print("住所:" + obj[1])
print("電話番号:" + obj[2])
print("メールアドレス:" + o... |
# Kernel config
c.IPKernelApp.pylab = 'inline' # if you want plotting support always in your notebook
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.token = ''
c.NotebookApp.password = u''
c.notebookApp.open_browser = True |
"""
给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。
例如,如果这个列表是 ["time", "me", "bell"],我们就可以将其表示为 S = "time#bell#" 和 indexes = [0, 2, 5]。
对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 "#" 结束,来恢复我们之前的单词列表。
那么成功对给定单词列表进行编码的最小字符串长度是多少呢?
示例:
输入: words = ["time", "me", "bell"]
输出: 10
说明: S = "time#bell#" , indexes = [0, 2, 5] 。
来源:... |
# 3. Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21.
# Необходимо решить задание в одну строку.
# Подсказка: использовать функцию range() и генератор.
lister = [elem for elem in range(20, 241) if elem % 20 == 0 or elem % 21 == 0]
print(f"Результат {lister}")
|
def check_parity(a: int, b: int, c: int) -> bool:
return a%2 == b%2 == c%2
def print_result(result: bool) -> None:
if result:
print("WIN")
else:
print("FAIL")
a, b, c = map(int, input().strip().split())
print_result(check_parity(a, b, c))
|
class employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' +last + '@gmail.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
#instance variables contain data that is ... |
class Solution:
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
low, high, mid = 0, len(nums)-1, len(nums)-1 // 2
while high - low > 1:
count, mid = 0, (high + low) // 2
for k in nums:
if mid < k <= high... |
# @Title: 路径总和 III (Path Sum III)
# @Author: 18015528893
# @Date: 2021-02-08 12:46:49
# @Runtime: 756 ms
# @Memory: 16 MB
# 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
clas... |
def combinations(n, buttons):
"""
Известно в каком порядке были нажаты кнопки телефона, без учета повторов.
Напечатайте все комбинации букв,
которые можно набрать такой последовательностью нажатий.
"""
if n == '':
return ['']
new = []
# s = numbers[n[-1]]
for i in combination... |
"""
The `gcp_hpo.test` module contains some scripts to test how GCP behaves.
### Regression
The regression folder tests GCP on regression tasks. While `display_branin_function.py` and `simple_test.py` are mostly there to visualize what is happening,
`full_test.py` can be used to quantify its accuracy. More precisel... |
# Copyright (c) 2013, Tomohiro Kusumi
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and... |
'''
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
... |
while True:
try:
fruit_name = input("입력하고 싶은 숫자가 뭐에요?")
fruit_name = int(fruit_name)
if fruit_name < 10:
print("10보다 작은 숫자가 입력이 되었습니다")
else:
print("10보다 큰 숫자가 입력이 되었습니다.")
break
except:
print("숫자를 입력해주세요 ㅠㅠ")
continue
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.