content stringlengths 7 1.05M |
|---|
# Time: O(n)
# Space: O(n)
# hash table
class Solution(object):
def isConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return max(nums)-min(nums)+1 == len(nums) == len(set(nums))
# Time: O(nlogn)
# Space: O(1)
# sort
class Solution2(object):
def is... |
nome = 'Francenylson' # nunca 1nome=
idade = 50
e_maior = idade > 18
altura = 1.85
peso = 93
imc = (peso/(altura*2))
print(nome, 'tem', idade, 'anos de idade e seu imc é', imc) #primeira possibilidade
print(f'{nome} tem {idade} anos de idade e seu imc é {imc}') #segunda possibilidade
print(f'{nome} tem {idade} anos ... |
# following description appears in levenshtein distance offered by git
# at https://github.com/git/git/blob/master/levenshtein.c
# This function implements the Damerau-Levenshtein algorithm to
# calculate a distance between strings.
#
# Basically, it says how many letters need to be swapped, substituted,
# dele... |
#!/usr/bin/python
# title :text_expansion.py
# description :This script contains the definition of a recursive function
# that expands a given text (to a max level) based on the
# pre-defined mapping.
# author :Hongbo Wang
# date :20170820
# version ... |
class StandardIWH:
def __init__(self, w: float) -> None:
"""Standard Inertia Weight Handler.
Parameters
----------
w : float
Inertia weight.
"""
self.w = w
def __call__(self, iteration: int) -> float:
"""Returns the inertia weight unchang... |
def gcd(a, b):
x, y, u, v = 0, 1, 1, 0
while a:
q, r = b // a, b % a
m, n = x - u * q, y - v * q
b, a, x, y, u, v = a, r, u, v, m, n
return b, x, y
def inv(a, m):
b, x, _ = gcd(a, m)
if b != 1:
return None
else:
return x % m
def enc(txt, k):
return... |
n = int(input())
login = []
logout = []
for i in range(n):
data = input().split()
login.append(data[0])
logout.append(data[1])
# print(login)
# print(logout)
user_num = 0
user_hot = 0
start_time = ''
end_time = ''
for hour in range(0, 24):
for minute in range(60):
time_now = f'{hour:02}:{minute... |
class Minimax():
def __init__(self, depth, board, captures, moves, parent, alpha, beta):
self.depth = depth
self.board = board
self.captures = captures
self.moves = moves
self.parent = parent
self.alpha = alpha
self.beta = beta
|
class Solution:
def minArea(self, image: List[List[str]], x: int, y: int) -> int:
if len(image) == 0 or len(image[0]) == 0 :
return 0
left, right, up, down = 0, 0, 0, 0
start, end = 0, y
while start + 1 < end :
mid = (start + end) //2
if ... |
# Video Quality Weights (vqw)
# At this file you can set the weighted order of the quality
# of the streams you prefer. This means that the first available will be served.
#
twitchVQW = [
"480p30",
"360p30",
"160p30",
"720p60",
"720p30",
"chunked",
"audio_only"
]
vimeoVQW = [
"360p",
... |
files = [
"top_level.vhd",
"interface_mngr.vhd",
"filter.vhd",
"../wb_irq/debounce.vhd",
"../wb_irq/rstgen_syscon.vhd",
"irq_mngr.vhd",
"../wb_irq/imx51_wb16_wrapper.vhd",
"../obtr_hdl/mult9x9.vhd",
"../obtr_hdl/hsvfilter.vhd"
]
|
class BigOne():
def __init__(self):
self.bla = 'bla!'
def hello(self):
print('hello!')
class SmallOne():
def check(self, bigOneName):
bigOneName.hello()
testBig = BigOne()
testSmall = SmallOne()
testSmall.check(testBig) |
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
d = {}
ans = 0
for i in range(n):
if(a[i]==0):
if(b[i]==0):
ans+=1
continue
if(-b[i]/a[i] in d):
d[-b[i]/a[i]]+=1
else:
d[-b[i]/a[i]]=1
if(len(d)!=0): ans += max... |
class InvoicePermissionSetterMixin:
def __init__(self):
if self.__class__.__name__[:5] == 'Sales':
self.permissions_required = ['sales_permissions']
else:
self.permissions_required = ['purchase_permissions']
return super().__init__(); |
n= input('NUMS= ').split(',')
n=list(map(lambda x: int(x),n))
indx=input('INDEX= ').split(',')
indx=list(map(lambda x: int(x),indx))
a=0
raw=[]
print(type(indx[1]))
for i in indx:
raw.insert(i,n[a])
a+=1
print(raw)
|
del_items(0x80082CB0)
SetType(0x80082CB0, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x80082CCC)
SetType(0x80082CCC, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x80082CD8)
SetType(0x80082CD8, "void Remove96__Fv()")
del_items(0x80082D10)
SetType(0x80082D10, "void AppMain()")
del_items(0x80082DD4)
SetType... |
lista = []
#pegar o último valor da lista: lista[len(lista) - 1] -> Na lista, a última posição
# OU : lista[-1]
for contador in range(0, 5):
numero = int(input(f'Digite um número {contador}: '))
if contador == 0 or numero > lista[-1]:#Se o nº for a primeira vez ou se os próximos
#forem maiores que o qu... |
input = open(
'/Users/krishjain/Desktop/AdventOfCode/Day 6/input.txt', "r").read()
input = input.split("\n\n")
countForEachGroup = []
for i in input:
listOfAnswersToWhichAnsweredYes = []
x = i.split("\n")
if "" in x:
x.remove("")
numberOfRepeatingChars = len(set.intersection(*[set(e) for... |
soma = 0
cont = 0
for c in range(1,7):
num = int(input('digite um numero pela {}°vez:'.format(c)))
if num % 2 == 0:
soma += num
cont += 1
print('Voce digitou {} números PARES, A soma dos números é {}'.format(cont, soma))
|
filename_prefix = 'Rebuttal-SawyerLift-ADR-BC-Smoothing'
xlabel = 'Environment steps (2M)'
ylabel = "Average Discounted Rewards"
max_step = 2000000
max_y_axis_value = 110
legend = False
data_key = "train_ep/rew_discounted"
bc_y_value = 34.77
plot_labels = {
"Ours": [
'Rebuttal_Ours_Lift_1234_smart-river-67... |
class BaseConnector:
def __init__(self):
self._action_results = []
self._containers = []
self._artifacts = []
self._config = {}
self._is_poll_now = False
self._state = {}
def is_poll_now(self):
return self._is_poll_now
def add_action_result(self, act... |
first_number = 1+1+6
second_number=105+10
total= first_number + second_number
print(total)
x = 10
print(x)
|
# Small alphabet o using function
def for_o():
""" *'s printed in the shape of o """
for row in range(5):
for col in range(5):
if row%4 ==0 and col %4 !=0 or row%4 !=0 and col %4 ==0:
print('*',end=' ')
else:
print(' ',end=' ')
pri... |
# Copyright 2021 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... |
class Solution:
def arrangeWords(self, text: str) -> str:
s = text.split()
s[0] = s[0].lower()
n = len(s)
lis = [(len(s[i]), i) for i in range(n)]
lis.sort()
ans = []
ans.append(s[lis[0][1]].title())
for i in range(1, n):
ans.appen... |
def get_c_air(T: float) -> float:
"""
Returns:
空気の定圧比熱, J/(kg・K)
"""
return 1006.0
def get_rho_air(t: float) -> float:
"""
Returns:
空気の密度, kg/m3
"""
return 1.293 / (1.0 + t / get_abs_temp())
def get_g() -> float:
"""
Returns:
重力加速度, m/s**2
"""
... |
# Filter the beat at 3kHz
filtered = beat.low_pass_filter(3000)
# Mix loop2 with a reversed, panned version
loop = loop2.reverse().pan(-0.5).overlay(loop2.pan(0.5))
# Mix our filtered beat with the new loop at -3dB
final = filtered.overlay(loop2 - 3, loop=True) |
class LetterDigitCount(object):
def __init__(self, sentence):
self.sentence = sentence
def counter(self):
d = {"DIGITS": 0, "LETTERS": 0}
for x in self.sentence:
if x.isdigit():
d["DIGITS"] += 1
elif x.isalpha():
d["LETTERS"] += 1
... |
"""
*Function*
An operator which produces a substance.
"""
|
def get_max_possible(coins, amount=0, turn=True):
if not coins:
return amount
if turn:
alt_1 = get_max_possible(coins[1:], amount + coins[0], False)
alt_2 = get_max_possible(coins[:-1], amount + coins[-1], False)
return max(alt_1, alt_2)
first, last = coins[0], coins[-1]
... |
load(":common.bzl", _zip_src = "zip_src", _pkg_merge = "pkg_merge", _cue_deps_attr = "cue_deps_attr")
def _cue_cmd_outputs(output_name):
"""Get map of cue_cmd outputs.
Note that the arguments to this function are named after attributes on the rule.
Args:
output_name: The rule's `output_name` attribut... |
# to check if value is in the list
def check(list, value):
if value in list:
return True
return False
|
'''Aula 21, Funções part 2'''
print('--ESCOPO DE VARIÁVEIS--')
def teste(b):
global a # obriga o programa a não criar outra variável dentro da função, e usa a variável global especificada.
a = 8 # (a) uma variável local, pois está dentro de uma função (caso não tenha sido declarada como global no início)
... |
class YarhBase:
def __init__(self, parent):
self.parent = parent
def html(self):
raise NotImplementedError()
def yarh(self):
raise NotImplementedError()
def findparent(self, **kwargs):
keys = ["type"]
findable = False
for kwarg in kwargs:
i... |
# -*- coding:utf-8 -*-
"""
-------------------------------------------------------------------------------
Project Name : ESEP
File Name : reynolds.py
Start Date : 2022-03-25 07:46
... |
"""
Hash tables are a type of data structure in which the address or the index value of the data element is generated from a hash function.
That makes accessing the data faster as the index value behaves as a key for the data value. In other words Hash table stores key-value pairs but the key is generated through a ha... |
class Eleve:
def __init__(self, nom, prenom, notes=list()):
self.nom = str(nom)
self.prenom = str(prenom)
self.notes = notes
def ajouterNote(self, x):
self.notes.append(x)
def moyenne(self):
tot = sum(self.notes)
if tot == 0:
return 0
ret... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 10:57:56 2020
@author: celine.gross
"""
puzzle = [15,5,1,4,7,0]
def nth_number(data, n):
# Store initial numbers read aloud
numbers = {d:[i+1] for i, d in enumerate(data)}
last = data[-1]
# Start deducing new numbers until nth
for i in range(len(d... |
#To use this classes we need to change the variable export FLASK_ENV=...(development, production or testing) in the terminal
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = "Super_secret_nobody_knows_key"
DB_NAME = "production-db"
DB_USERNAME = "root"
DB_PASSWORD =... |
SURVEY_LIST_GET = {
'tags': ['기숙사'],
'description': '설문조사 리스트 불러오기(학생 학년에 따라 필터링됨)',
'parameters': [
{
'name': 'Authorization',
'description': 'JWT Token',
'in': 'header',
'type': 'str',
'required': True
}
],
'responses': {
... |
def insertionSort(lst,n):
for i in range(1,n):
temp = lst[i]
j = i-1
while(lst[j]>temp and j>=0):
lst[j+1]=lst[j]
j=j-1
lst[j+1]=temp
lst = list(map(int,input().split()))
n = len(lst)
print('Before : ',lst)
insertionSort(lst,n)
print('After : ',lst) |
expected_output = {
'evi': {
103: {
'bd_id': {
103: {
'dg_addr': {
'10.3.1.254': {
'source': {
'V:2000103 Vlan103': {
'eth_tag': 0,
... |
button_style = """
QPushButton {
color: rgb(212, 212, 212);
border: none;
background-color: rgb(51, 59, 72);
text-align: center;
}
QPushButton:hover {
color: rgb(255,255,255);
background-color: rgb(63, 73, 89);
}
... |
"""In gym, the RAM is represented as an 128-element array, where each element in the array can range from 0 to 255
The atari_dict below is organized as so:
key: the name of the game
value: the game dictionary
Game dictionary is organized as:
key: state variable name
value: the element in the RAM array... |
class A:
pass
class B(A):
pass
assert issubclass(A, A)
assert issubclass(B, A)
assert not issubclass(A, B)
class MCNotSubClass(type):
def __subclasscheck__(self, subclass):
return False
class NotSubClass(metaclass=MCNotSubClass):
pass
class InheritedNotSubClass(NotSubClass):
pass
... |
# Copyright (c) 2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#### Printable characters utilities
def is_printable(b):
return b >= 32 and b < 127
def prchr_(b):
if is_printable(b):
... |
# Created by MechAviv
# Map ID :: 940011100
# Eastern Region of Pantheon : East Sanctum
sm.showEffect("Effect/Direction10.img/effect/tuto/BalloonMsg2/0", 1200, 0, -120, -2, -2, False, 0)
sm.sendDelay(1200)
sm.setSpeakerID(3000132)
sm.removeEscapeButton()
sm.setSpeakerType(3)
sm.sendNext("Just put that on your little... |
"""Print vs. Return in Functions
Here are two valid functions. One returns a value and one simply prints a value, without returning anything. Test run this code and experiment to understand the difference.
"""
# this prints something, but does not return anything
def show_plus_ten(num):
print(num + 10)
# this re... |
# Created by Martin Strohalm, Thermo Fisher Scientific
# init main repository
CONVERTERS = {}
def register(tag):
"""Registers converter by given tag."""
def reg(cls):
"""Registers given class."""
CONVERTERS[tag] = cls
CONVERTERS[tag.lower()] = cls
CONVERTERS[ta... |
__author__ = 'hs634'
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self):
self.root = None
def add_node(self, data):
return Node(data)
def insert(self, root, data):... |
class ProcessPriorityClass(Enum,IComparable,IFormattable,IConvertible):
"""
Indicates the priority that the system associates with a process. This value,together with the priority value of each thread of the process,determines each thread's base priority level.
enum ProcessPriorityClass,values: AboveNormal... |
"""
Liczby wymierne są reprezentowane przez krotkę (l, m). Gdzie: l - liczba całkowita oznaczająca
licznik, m - liczba naturalna oznaczająca mianownik. Proszę napisać podstawowe operacje na ułamkach,
m.in. dodawanie, odejmowanie, mnożenie, dzielenie, potęgowanie, skracanie, wypisywanie i wczytywanie.
"""
def addition... |
# 新增属性到流文件
flowFile = session.get()
if flowFile != None:
# Get attributes
greeting = flowFile.getAttribute("greeting")
message = greeting + ", Script!"
# Set single attribute
flowFile = session.putAttribute(flowFile, "message", message)
# Set multiple attributes
flowFile = session.putAllA... |
print ("Calculator")
n1 = int(input("Give the first number:"))
n2 = int(input("Give the second number:"))
while True:
print ("(1) +\n(2) -\n(3) *\n(4) /\n(5) Change numbers\n(6) Quit\nCurrent numbers: ", n1,n2)
choice = int (input("Please select something(1 - 6):"))
if (choice == 1 ):
result = ... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( n ) :
C = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] ;
for i in range ( n + 1 ) :
... |
TEXT = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
URL = "http://www.pythonchallenge.com/pc/def/map.html"
def shiftby2(s):
shifted = ord(s)
if ('a' ... |
# Copyright 2013-2020 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 PyPydeps(PythonPackage):
"""Python module dependency visualization."""
homepage = "https://pypi.python.org... |
# https://www.hackerrank.com/challenges/validating-named-email-addresses/problem?h_r=profile
#input
n = int(input())
e =[input() for _ in range(n)]
#name
name = [i.split()[0] for i in e]
#user
user = [i.split()[1].split('@')[0].replace('<','') for i in e]
#email
email = [i.split()[1].split('@')[1].split('.')[0] for i ... |
"""
@author: Deniz Altinbuken, Emin Gun Sirer
@note: Example counter
@copyright: See LICENSE
"""
class Counter:
def __init__(self, value=0):
self.value = value
def decrement(self):
self.value -= 1
def increment(self):
self.value += 1
def getvalue(self):
return self.val... |
def skew(genome):
cg = 0
list_cg = []
for i in range(len(genome)):
if genome[i] == 'C':
cg-= 1
if genome[i] == 'G':
cg += 1
list_cg.append(cg)
return list_cg
def min_skew(genome):
skew_rel = skew(genome)
minimo = min(skew_rel)
a = [i+1 for i i... |
# Imprimiendo todas las letras excepto la 'p' and 's'
i = 0
a = 'datospordatos'
while i < len(a):
if a[i] == 'p' or a[i] == 's':
i += 1
continue
print('letra actual :', a[i])
i += 1 |
m = float(input('digite uma distância em metros: '))
print(f'a medida de {m}m corresponde a')
km = m / 1000
hm = m / 100
dam = m / 10
dm = m * 10
cm = m * 100
mm = m * 1000
print(km, 'km')
print(hm, 'hm')
print(dam, 'dam')
print(m, 'm')
print(dm, 'dm')
print(cm, 'cm')
print(mm, 'mm')
|
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * n
for bk in bookings:
res[bk[0] - 1] += bk[2]
if bk[1] < n:
res[bk[1]] -= bk[2]
for i in range(1, n):
res[i] += res[... |
n = int(input('DIGITE UM NUMERO'))
n2 = int(input('Digite outro'))
r = n + n2
print(r)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# References:
# http://code.activestate.com/recipes/510399-byte-to-hex-and-hex-to-byte-string-conversion/
# http://stackoverflow.com/questions/606191/convert-byte-array-to-python-string
# some utf8 characters conflict with the format of XML, which causes error while parsin... |
def ConsoleGenerator():
num = input()
while len(num):
yield float(num)
num = input()
total_sum = 0
for number in ConsoleGenerator():
total_sum += number
print(f'Sum of entered numbers is {total_sum}')
|
def third_party_workspace():
native.new_git_repository(
name = "aerospike_common",
build_file = str(Label("//third_party:aerospike-common.BUILD")),
commit = "5b459384e6bd98b0fe39e63ab1604c0359ae9507",
remote = "https://github.com/aerospike/aerospike-common.git"
)
native.new_... |
class Testclass():
def main(self):
variable = True
if __name__ == "__main__":
module_level_attribute = True
|
# 141, Суптеля Владислав
# Дата: 20.02.20
# 9. Дано двозначне число. Знайти суму і добуток його цифр.
l = int(input("Введите двузначное число: "))
a = l % 10 # остаток от деления числа == последнее число
l = l // 10 # избавляемся от последнего числа
b = l % 10 # redo
print("【Сумма】 = ", a+b)
print("【Произведение】... |
# 4- Desenvolva uma classe para representar um usuário no sistema, sabendo que esta classe será utilizada para verificação no momento do login e também como estrutura para armazenar os dados do usuário durante a sessão de uso do aplicativo.
class Usuario:
def __init__(self, Email, password, name, born, sex, cpf):
... |
class Node:
def __init__(self, value):
self.value = value
self.next_element = None
#Cycles through the linked list and prints out each value
def display(self):
while self != None:
print(self.value)
self = self.next_element
#Creates a lis... |
"""is_valid module."""
def is_valid(exp: str) -> bool:
"""Validate if expression is a valid identifier.
Args:
exp: string to be validated
Returns:
True: if is a valid identifier.
False: if is not a valid identifier.
"""
if not isinstance(exp, str):
return False
... |
order_total = 247
# ternary operator
discount = 25 if order_total > 100 else 0
print(order_total, discount)
|
class TokenStream(object):
class _Mark(object):
def __init__(self, parent, pos):
self.__parent = parent
self.__pos = pos
#
def resetToMark(self):
self.__parent._pos = self.__pos
#
#
def __init__(self, tokens:list):
self._data = list(tokens)
self._pos = 0
#
def __iter__(self):
for v i... |
#maior e menor numero
n1 = int(input('Digite um Numero: '))
n2 = int(input('Digite Outro: '))
n3 = int(input('Digite o Último: '))
maior = 0
menor = 0
if n1 > maior:
maior = n1
menor = n1
if n2 > maior:
maior = n2
if menor > n2:
menor = n2
if n3 > maior:
maior = n3
if menor > n3:
menor = n3
p... |
#=================================================================#
class BdryData(object):
"""
Information for boundary conditions
"""
def __init__(self):
self.bsaved = {}
self.Asaved = {}
def __repr__(self):
return ", ".join("'{}': {}".format(attr, value) for attr, value i... |
# Problem0009 - Special Pythagorean triplet
#
# https://github.com/agileshaw/Project-Euler
def product():
for i in range(1000):
for j in range(i+1, 1000):
for k in range(j+1, 1000):
if i*i + j*j == k*k and i + j + k == 1000:
return i * j * k
if __name__ ==... |
#CvModName.py
modName = "BUG Mod"
displayName = "BUG Mod"
modVersion = "4.4 [Build 2220]"
civName = "BtS"
civVersion = "3.13-3.19"
def getName():
return modName
def getDisplayName():
return displayName
def getVersion():
return modVersion
def getNameAndVersion():
return modName + " " + modVersion
def getDispl... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
try:
number = int(input("Find the square root of an integer: "))
guess = float(input("Initial guess: "))
tolerance = float(input("Tolerance: "))
original_guess = guess
count = 0
previous = 0.0
while abs(previous - guess) > tolerance:
previous = guess
quotient = number / gue... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 16:57:10 2021
@author: Administrator
"""
|
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.word_id = -1
self.palindrome_word_ids = []
class Trie:
def __init__(self):
self.root = TrieNode()
@staticmethod
def is_palindrome(word: str) -> bool:
retur... |
# encoding: utf-8
# module parser
# from /usr/lib/python3.5/lib-dynload/parser.cpython-35m-x86_64-linux-gnu.so
# by generator 1.145
""" This is an interface to Python's internal parser. """
# no imports
# Variables with simple values
__copyright__ = 'Copyright 1995-1996 by Virginia Polytechnic Institute & State\nUniv... |
#
# PySNMP MIB module RIVERSTONE-NOTIFICATIONS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RIVERSTONE-NOTIFICATIONS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:57:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
class Solution:
def reformat(self, s: str) -> str:
"""String.
Running time: O(n) where n == len(s).
"""
a, n = [], []
for i in s:
if 'a' <= i <= 'z':
a.append(i)
else:
n.append(i)
if abs(len(a)-len(n)) > 1:
... |
# Demonstrates simple function
#combines first name and last name with a blank between
def printName(firstName, lastName):
fullName = firstName + " " + lastName
print(fullName)
#Adds one to a number and print it
def printIncrement(number):
number = number + 1
print("The number is now ",number)
first ... |
"""
This file contains constants that the bot works with.
If you wish to add or edit a constant, please make sure to comment the meaning of the constant and the reason for the edit (if applicable).
"""
CONFIRM_REACTION_EMOJI = '🟢' # Reaction emoji used to confirm actions
CANCEL_REACTION_EMOJI = '🟥' # Reaction emoji ... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
input()
a='0'+input()+'0'
print('YNEOS'[a.count('000')>0 or a.count('11')>0::2]) |
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768
SCREEN_TITLE = "Arcade Community Platformer"
# Constants used to scale our sprites from their original size
TILE_SCALING = 0.5
CHARACTER_SCALING = TILE_SCALING * 2
COIN_SCALING = TILE_SCALING
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING
# Shooting ... |
class RiotRefuseError(Exception):
"""Raised when the client refuses to connect to the local server"""
pass
class RiotTimeoutError(Exception):
"""Raised when the client refuses to connect to the local server"""
pass
class RiotAuthError(Exception):
"""Usually raised when the client is not authenticate... |
#!/usr/bin/env python2
# coding: utf-8
class MountPointIndex(str):
def __new__(clz, s):
if isinstance(s, int):
s = '{s:0>3}'.format(s=s)
if len(s) != 3 or not (0 <= int(s) <= 999):
raise ValueError('invalid mount point index: {s}'.format(s=s))
return super(Mount... |
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
"""
dp[i][j] means the max profit can achieve at days j with at most j transcations
|1.T[i][j-1] do nothing at jth day
dp[... |
'''
Exploring your working directory
50xp
In order to import data into Python, you should first have an idea of what files
are in your working directory.
IPython, which is running on DataCamp's servers, has a bunch of cool commands,
including its magic commands. For example, starting a line with ! gives you
complete ... |
#!/usr/bin/env python
"""
Udacity conference server-side Python App Engine app user settings
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '727907205051-573gc5ahpho4tq7tloct49fpttktkkg8.apps.googleusercontent.com'
|
"""
企业发放的奖金跟据利润提成,
利润(i)小于等于10w元时,奖金可提10%;
利润高于10w元时小于等于20w,高于10w的部分可提成7.5%;
利润高于20w元时小于等于40w,高于20w的部分可提成5%;
利润高于40w元时小于等于60w,高于40w的部分可提成3%;
利润高于60w元时小于等于100w,高于60w的部分可提成1.5%;
利润高于100w,高于100w的部分可提成1%;
"""
def get_bonus():
# 定义奖金
bonus = 0
# 获取输入利润
profit = int(input("请输入利... |
class A:
...
print(A.__bases__) # (<class 'object'>,)
|
#creating a dictionary
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
# changing or adding elements in dictionary
my_dict['age'] = 27
print(my_dict)
my_dict['address'] = 'Downtown'
print(my_dict)
#deleting elements from dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}... |
# An array of numbers arranged on a regular grid with a variable number of axes
a = [
[
[1, 2],
[3, 4],
],
[
[5, 6],
[7, 8],
]
] |
autoref_rst = """
Graphics
========
.. index ::
single: Graphics
This is the reference documentation for the graphics modules.
"""
__all__ = ['spikeparams', 'spikeplot', 'spikesum', 'spiketimehistogram'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.