content stringlengths 7 1.05M |
|---|
"""
@no 169
@name Majority Element
"""
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = {}
for num in nums:
if count.get(str(num)):
count[str(num)] += 1
else:
cou... |
#Linear Search
class LinearSerach:
def __init__(self):
self.elements = [10,52,14,8,1,400,900,200,2,0]
def SearchEm(self,elem):
y = 0
if elem in self.elements:
print("{x} is in the position of {y}".format(x = elem,y = self.elements.index(elem)))
else:
... |
for t in range(int(input())):
L=list(map(int,input().split()))
sum=0
for i in L:
if i<40:
sum+=40
else :
sum+=i
print(f"#{t+1} {sum//5}")
|
"""
For strings, return its length.
For None return string 'no value'
For booleans return the boolean
For integers return a string showing how it compares to hundred e.g.
For 67 return 'less than 100' for 4034 return 'more than 100' or
equal to 100 as the case may be
For lists return the 3... |
class AgeBean:
def __init__(self, judgement_id=0,
age=''):
self._judgement_id = judgement_id
self._age = age
@property
def judgement_id(self):
return int(self.judgement_id)
@judgement_id.setter
def judgement_id(self, id):
self._judgement_id = id
... |
def reverse(head):
cur = head
pre = None
while cur:
nxt = cur.next
cur.next = pre
cur.pre = nxt
pre = cur
cur = nxt
return pre |
names = ['Anddy', 'Christian', 'Lucero', 'Yamile', 'Evelyn']
print(names)
print(names[0])
print(names[0:2])
#
numbers = [6, 2, 3, 45, 23, 3, 4, 55, 3, 2, 4456, 7, 98, 6, 64, 4, 321, 4, 323, 6, 68, 2, 2, 12, 4, 5]
largeNumber = numbers[0]
for number in numbers:
if number > largeNumber:
largeNumber = numb... |
class placeholder_optimizer(object):
done=False
self_managing=False
def __init__(self,max_iter):
self.max_iter=max_iter
def update(self):
pass |
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
@gem('Sapphire.LineMarker')
def gem():
def construct_token__line_marker__many(t, s, newlines):
assert (t.ends_in_newline is t.line_marker is true) and (newlines > 1)
t.s = s
t.newlines = newlines
class LineMarke... |
casos = int(input())
dentro = 0
fora = 0
for i in range(casos):
num = int(input())
if num >= 10 and num <= 20:
dentro += 1
else:
fora += 1
print('{} in\n{} out'.format(dentro, fora))
|
#Desafio 8
#Programa Conversor de Unidades
# (Dá para aprimorar mais tarde)
medida = float(input("Digite aqui uma medida em metros para obtê-la em centímetros e milímetros: "))
print(f"Sobre a medida {medida} metros, ela possui:\n {medida*100} centímetros,\n {medida*1000} milímetros ")
|
#https://www.hackerrank.com/challenges/quicksort2
'''
def quickSort(ar):
if len(ar) <2 : # 0 or 1
return(ar)
else:
p = ar[0]
less = []
more = []
for item in ar[1:]:
if item < p:
less.append(item)
else:
m... |
class User:
def __init__(self,username,password):
self.is_authenticated = False
self.username = username
self.password = password
|
def add(x):
def do_add(y):
return x + y
return do_add
add_to_five = add(5)
# print(add_to_five(7))
# print(add(5)(3))
def Person(name, age):
def print_hello():
print('Hello! My name is {}'.format(name))
def get_age():
return age
return {'print_hello': print_hello, 'ge... |
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort()
n=len(nums)
if n==0:
return []
dp=[[i,1] for i in range(n)]
last=0
maxm=0
for i in range(1,n):
for j in range(i-1,-1,-1):
if num... |
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def __str__(self):
return f'{self.title} {self.author} {self.price}'
def __call__(self, title, author, price):
self.title = title
self.author = au... |
class Solution:
@staticmethod
def naive(nums):
return nums+nums
|
ISCOUNTRY = 'isCountry'
def filter_country_locations(api_response, is_country=True):
"""
Filter the response to only include the elements that are countries.
This uses the 'api_response' object as input. Plain `list`s are also
valid, but they must contain the location elements, not the `items` ... |
"""
-------------------------------------------------------
config
flask config file
-------------------------------------------------------
Author: Dallas
ID: 110242560
Email: fras2560@mylaurier.ca
Version: 2014-09-18
-------------------------------------------------------
"""
DEBUG = True
|
aut = float(input('Digite a autura da parede em Metros: '))
lar = float(input('Digite a largura da parede em Metros: '))
are = aut * lar
print(f'A área da parede é {are}², considerando que cada litro de tinta pinta 2m² vc vai usar {are/2} Litros de tinta') |
"""
时间: 2019/12/31
作者: liyongfang@cyai.com
更改记录:
重要说明:
""" |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class DFUPrefix:
"""Generates the DFU prefix block"""
DFU_PREFIX_LENGTH = 11
DFU_PREFIX_SIZE_POS = 6
DFU_PREFIX_IMG_COUNT_POS = 10
def __init__(self, imageSize = 0, targetCount = 0):
# It looks like the DFU image size includes the DFU Prefix b... |
'''
Created on 25 Mar 2020
@author: bogdan
'''
class s1010hy_wiki2text(object):
'''
parsing wikipedia xml, extracting textual input
'''
def __init__(self):
'''
Constructor
'''
|
def pickform(num: int, wordforms: list):
"""
NOTE: Аргумент wordforms должен выглядеть так: ['(1) ключ', '(2) ключа', '(5) ключей']
-> Возвращает нужную форму слова для данного числа, например "1 велосипед" или "2 велосипеда"
"""
# Числа-исключения от 11 до 14
if 10 < num < 15: return wordforms[... |
"""
GCD
"""
# Find the greatest common denominator (GCD) of two number input by a user. Then print out 'The GCD of <first number> and <second number> is <your result>.'
print('Enter two numbers to find their greatest common denominator.')
user_input1 = input('First number: ')
user_input2 = input('Second number: ')
... |
#
# PySNMP MIB module CISCO-HSRP-EXT-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HSRP-EXT-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:42:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... |
"""Compute the square root of a number."""
def sqrt(x):
y = (1 + x)/2
tolerance = 1.0e-10
for i in range(10):
error = abs(y*y - x)
print(i, y, y*y, error)
if error <= tolerance:
break
# improve the accuracy of y
y = (y + x/y)/2
return y
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
... |
master_doc = 'index'
project = u'Infrastructure-Components'
copyright = '2019, Frank Zickert'
htmlhelp_basename = 'Infrastructure-Components-Doc'
language = 'en'
gettext_compact = False
html_theme = 'sphinx_rtd_theme'
#html_logo = 'img/logo.svg'
html_theme_options = {
'logo_only': True,
'display_version': F... |
a, b = input().split()
a = int(a[::-1])
b = int(b[::-1])
print(a if a > b else b)
|
ENDCODER_BANK_CONTROL1 = ['ModDevice_knob0', 'ModDevice_knob1', 'ModDevice_knob2', 'ModDevice_knob3']
ENDCODER_BANK_CONTROL2 = ['ModDevice_knob4', 'ModDevice_knob5', 'ModDevice_knob6', 'ModDevice_knob7']
ENDCODER_BANKS = {'NoDevice':[ENDCODER_BANK_CONTROL1 + ['CustomParameter_'+str(index+(bank*24)) for index in range(... |
# Time: O(nlogk)
# Space: O(k)
# You have k lists of sorted integers in ascending order.
# Find the smallest range that includes at least one number from each of the k lists.
#
# We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.
#
# Example 1:
# Input:[[4,10,15,24,26], [0,9,12... |
"""
This script is used for course notes.
Author: Erick Marin
Date: 10/05/2020
"""
# Arithemtic Operators
print(4 + 5) # Addition
print(9 * 7) # Multiplication
print(-1 / 4) # Divsion
# Division with repeating or periodic numbers
print(1 / 3)
# Floor division "//" rounds the result down to the nearest whol... |
# -*- coding: utf-8 -*-
class LoginError(Exception):
pass
|
''' maze block counts for horizontal and vertical dimensions'''
HN = 25
VN = 25
''' screen width and height '''
WIDTH = 600
HEIGHT = 600
''' configurations to fit the maze size regarding the block counts and its ratio with respect to the screen size '''
HSIZE = int(WIDTH*2./3.)
VSIZE = int(HEIGHT*2./3.)
HOFFSET = ... |
# -*- coding: utf-8 -*-
"""Top-level package for Needlestack."""
__author__ = """Cung Tran"""
__email__ = "minishcung@gmail.com"
__version__ = "0.1.0"
|
# md5 : 506fc4d9b83c53f867e483f9235de8f3
# sha1 : 0e90c892528abee5127e047b6ca037991267b9e0
# sha256 : 04deb949dd7601ee92a1868b2591c2829ff8d80e42511691bad64fd01374d7fe
ord_names = {
733: b'mF_ld_load_ldnames',
734: b'mFt_os_mm_set_cushion',
735: b'mFt_os_resource_delete_ru_entry',
795: b'mFt_os_thread_i... |
#Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar
n=float(input('Quantos reais voce tem na carteira?'))
s=n/5.51
print('com a quantidade de {} reais que voce tem,voce tem {:.2f} dólares atualmente'.format(n,s))
|
people = int(input())
name_doc = input()
grade_sum = 0
average_grade = 0
total_grade = 0
numbers = 0
while name_doc != "Finish":
for x in range(people):
grade = float(input())
grade_sum += grade
average_grade = grade_sum / people
print(f"{name_doc} - {average_grade:.2f}.")
name_doc ... |
year = int(input("Inserire l'anno: "))
if year % 4 == 0 and (year <= 1582 or year % 100 != 0 or year % 400 == 0):
print("L'anno è bisestile.")
else:
print("L'anno non è bisestile.") |
# Desenvolva um programa que leia as notas de um aluno, calcule e mostre a sua média.
primeira_nota = float(input("Primeira nota: "))
segunda_nota = float(input('Segunda nota: '))
media_aritmetica = (primeira_nota + segunda_nota)/2
print(f"A sua média foi de {media_aritmetica:.4f}")
|
neopixel = Runtime.createAndStart("neopixel","NeoPixel")
def startNeopixel():
neopixel.attach(i01.arduinos.get(rightPort),23,16)
neopixel.setAnimation("Ironman",0,0,255,1)
pinocchioLying = False
def onStartSpeaking(data):
if (pinocchioLying):
neopixel.setAnimation("Ironman",0,255,0,1)
else:
... |
def pprint_matcher(node, *args, **kwargs):
print(matcher_to_str(node, *args, **kwargs))
def matcher_to_str(
node, indent_nr: int = 0, indent: str = " ", first_line_prefix=None
) -> str:
ind = indent * indent_nr
ind1 = indent * (indent_nr + 1)
if first_line_prefix is None:
first_line_pref... |
class model4:
def __getattr__(self,x):
var_name = 'var_'+x
v = self.__dict__[var_name] if var_name in self.__dict__ else self.__dict__[x]
return v() if callable(v) else v
def chain(self,other):
for k,v in other.__dict__.items():
self.__dict__[k]=v
return self
if __name__=="__main__":
x = model4()
x.va... |
salario = float(input('Insira o salário do funcionário que receberá um aumento: '))
if salario <= 1250:
novoSalario = salario + (salario * 15 / 100)
else:
novoSalario = salario + (salario * 10 / 100)
print(f'Um funcionário com o salário de {salario}, após o aumento, passa a receber R${novoSalario:.2f}')
|
ACTION_GOAL = "goal"
ACTION_RED_CARD = "red-card"
ACTION_YELLOW_RED_CARD = "yellow-red-card"
actions = {ACTION_GOAL: "GOAL",
ACTION_RED_CARD: "RED CARD",
ACTION_YELLOW_RED_CARD: "RED CARD"}
class PlayerAction(object):
def __init__(self, player, action):
if not type(player) == dict... |
##!FAIL: TypeExprParseError[Paramètre 'dico' : Je ne comprends pas le type dictionnaire déclaré : il manque le type des clés et/ou des valeurs]@3:0
def dict_ajout(dico : Dict[int], k : K, v : V) -> Dict[K, V]:
""""""
rd : Dict[K, V]
rd = dico[:]
rd[k] = v
return rd
|
def main():
# Open file for output
outfile = open("Presidents.txt", "w")
# Write data to the file
outfile.write("Bill Clinton\n")
outfile.write("George Bush\n")
outfile.write("Barack Obama")
outfile.close() # Close the output file
main() # Call the main function
|
class NoCurrentVersionFound(KeyError):
"""
No version node of the a particular parent node could be found
"""
pass
class VersionDoesNotBelongToNode(AssertionError):
"""
The version that is trying to be attached does not belong to the parent node
"""
pass
|
def fb_python_library(name, **kwargs):
native.python_library(
name = name,
**kwargs
)
|
class Solution(object):
def findLUSlength(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
if len(a) > len(b):
return len(a)
elif len(a) < len(b):
return len(b)
elif a == b:
return -1
else:
... |
def square_of_two_count(num):
if(num == 2):
return 0
num //= 2
print("num is now", num)
return square_of_two_count(num) + 1
count = square_of_two_count(512)
print("final count:", count)
# That was a brief refresher because recursion can be messy
# : Define a function called multiply. Have it ... |
#program to display your details like name, age, address in three different lines.
name = 'Chibuzor darlington'
age = '19yrs'
address = 'imsu junction'
print(f'Name:{name}')
print(f'Age:{age}')
print(f'Address:{address}')
def personal_details():
name, age = "Chibuzor Darlington", '19yrs'
address = "imsu junctio... |
# Definition einer eigenen Klasse, hier die Klasse "Ding"
# ohne Attribute und Methoden
# im Anschluss wird ein Objekt mit zwei Attributen zugefügt
# --> Dynamische Erzeugung von Attributen
class Ding(object):
pass # Es wurden keine Attribute und Methoden definiert
#Hauptprogramm
kugel=Din... |
cache = {}
def get_page(url):
if cache.get(url):
return cache[url]
else:
data = get_data_from_server(url)
cache[url] = data
return data
|
"""This file contains all the code required to use the POSTGRES server so that bot has access to permanent storage"""
def createTable(cursor):
"""Creates specified table if it does not exist"""
command = "CREATE TABLE IF NOT EXISTS leaderboard (username varchar(50) NOT NULL, score INT NOT NULL)"
curso... |
##write a program that will print the song "99 bottles of beer on the wall".
##for extra credit, do not allow the program to print each loop on a new line.
bottles = 99
while bottles > 0:
if bottles == 1:
print(str(bottles) + " bottles of beer on the wall, " + str(bottles) + " bottle of beer.", end="... |
#Aula 9 do Curso Python em Video!
#Exercício da Aula 09!
#By Rafabr
''''''
print('\n'+'*'*80)
print('Aula 09 - Exemplos e Testes'.center(80)+'\n')
frase = input("Digite uma Frase para testar alguns métodos utilizados com Strings: ")
print(f'\nA frase digitada possui {len(frase)} caracteres!\n')
print('\t',end = ""... |
#!/usr/bin/env python
"""credentials - the login credentials for all of the modules are stored here and imported into each module.
Please be sure that you are using restricted accounts (preferably with read-only access) to your servers.
"""
__author__ = 'scott@flakshack.com (Scott Vintinner)'
# VMware
VMWARE_VCEN... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.head = None
def bft(self):
if self.head == None:
return
print("Bredth First Traversal")
ptr = self.head
... |
"""Embed utils."""
def recurse_while_none(element):
"""Recursively find the leaf node with the ``href`` attribute."""
if element.text is None and element.getchildren():
return recurse_while_none(element.getchildren()[0])
href = element.attrib.get('href')
if not href:
href = element.at... |
# Each frame has a name, and various associated roles. These roles have facet(s?) which take on values which are themselves sets of one or more frames.
class Frame:
# relations: a dictionary, key is role, value is other frames
def __init__(self, name, isstate=False, iscenter=False):
self.name = name
... |
class Contact:
def __init__(self, firstname, middlename, address, mobile, email):
self.firstname = firstname
self.middlename = middlename
self.address = address
self.mobile = mobile
self.email = email |
"""
Remove duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appears only once and return the new length.
Note that even though we want you to return the new length, make sure to change the original array as well in place
Do not allocate extra space for another a... |
# Copyright 2021 Edoardo Riggio
#
# 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 writin... |
class Path(object):
@staticmethod
def db_dir(database):
if database == 'ucf101':
# folder that contains class labels
# root_dir = '/data/dataset/ucf101/UCF-101/'
root_dir = '/data/dataset/ucf101/UCF-5/'
# Save preprocess data into output_dir
ou... |
HEALTH_CHECKS_ERROR_CODE = 503
HEALTH_CHECKS = {
'db': 'django_healthchecks.contrib.check_database',
}
|
DEFAULT_STEMMER = 'snowball'
DEFAULT_TOKENIZER = 'word'
DEFAULT_TAGGER = 'pos'
TRAINERS = ['news', 'editorial', 'reviews', 'religion',
'learned', 'science_fiction', 'romance', 'humor']
DEFAULT_TRAIN = 'news' |
def check(kwds, name):
if kwds:
msg = ', '.join('"%s"' % s for s in sorted(kwds))
s = '' if len(kwds) == 1 else 's'
raise ValueError('Unknown attribute%s for %s: %s' % (s, name, msg))
def set_reserved(value, section, name=None, data=None, **kwds):
check(kwds, '%s %s' % (section, value.... |
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
'''
changes to both lists
that means, they point to same object
once and then thrice
'''
'''
a = [1,2,3]
b = ([a]*3)
print(a)
print(b)
# same effect
# a[0]=11
b[0][0] = 9
print(a)
print(b)
#'''
'''
a = [1,2,3]
b = (a,)
print(a)
print(b)
#'''
|
# -*- coding: utf-8 -*-
# ==============================================================================
# AUTOGENERATED
# python.sdk.version - AUTOGENERATED
# VERSION.py - MAINTAINER's. Don't edit, if you don't know what are you doing
# ==============================================================================
V... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class BotAssert(object):
@staticmethod
def activity_not_null(activity):
if not activity:
raise TypeError()
@staticmethod
def context_not_null(context):
if not context:
... |
CHIP8_STANDARD_FONT = [
0xF0, 0x90, 0x90, 0x90, 0xF0,
0x20, 0x60, 0x20, 0x20, 0x70,
0xF0, 0x10, 0xF0, 0x80, 0xF0,
0xF0, 0x10, 0xF0, 0x10, 0xF0,
0x90, 0x90, 0xF0, 0x10, 0x10,
0xF0, 0x80, 0xF0, 0x10, 0xF0,
0xF0, 0x80, 0xF0, 0x90, 0xF0,
0xF0, 0x10, 0x20, 0x40, 0x40,
0xF0, 0x90, 0xF0, 0x... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def get_day():
return __day
def get_area():
return __area
__day = {
'월요일' : '월요일', '화요일' : '화요일', '수요일' : '수요일',
'목요일' : '목요일', '금요일' : '금요일', '토요일' : '토요일',
'일요일' : '일요일', '내일' : '내일', '모레' : '모레',
'글피' : '글피', '주' : '주', '주말' : '주말', '달' : '달',
}
__area = {
'진북동' :... |
with open('pi_digits.txt') as file_object:
contnts = file_object.read()
print(contnts.rstrip())
|
class Solution:
def _lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
temp = s.split(" ")
arr = list(filter(lambda x: x != '', temp))
if not arr:
return 0
return len(arr[-1])
def lengthOfLastWord(self, s):
l, r = len(... |
f=open('T.txt')
fw=open('foursquare.embedding.update.2SameAnchor.1.foldtrain.twodirectionContext.number.100_dim.10000000','w')
for i in f:
ii=i.split()
strt=ii[0]+'_foursquare'+' '
for iii in ii[1:]:
strt=strt+iii+'|'
fw.write(strt+'\n')
|
a = int(input("Enter a number1: "))
b = int(input("Enter a number2: "))
temp = b
b = a
a = temp
print("Value of number1: ", a , " Value of number2: ",b) |
"""
Initializes the view_helpers package
"""
|
""" Each module provides a `Simulation` class
based on `sapphire.Simulation`, but with specified governing equations.
The mesh, initial values, and boundary conditions are unspecified.
Therefore, the constructors have those as required arguments.
"""
|
"""Dependency specific initialization."""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@com_github_3rdparty_eventuals//bazel:deps.bzl", eventuals_deps = "deps")
load("@com_github_3rdparty_stout_borrowed_ptr//bazel:deps.... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331003200
# Subway :: Subway Car #3
GIRL = 1531067
sm.removeNpc(GIRL)
sm.warpInstanceIn(331003300, 0) |
model_parallel_size = 1
pipe_parallel_size = 0
distributed_backend = "nccl"
DDP_impl = "local" # local / torch
local_rank = None
lazy_mpu_init = False
use_cpu_initialization = False
|
"""
WaveletNode class represents one node in Wavelet tree data structure.
"""
class WaveletNode:
def __init__(self, alphabet, parent=None):
self.bit_vector = ''
self.alphabet = alphabet
self.left = None
self.right = None
self.parent = parent
""" Method for adding n... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Mumbling
#Problem level: 7 kyu
def accum(s):
li = []
for i in range(len(s)):
li.append(s[i].upper() + s[i].lower()*i)
return '-'.join(li)
|
# 0. Paste the code in the Jupyter QtConsole
# 1. Execute: bfs_tree( root )
# 2. Execute: dfs_tree( root )
root = {'value': 1, 'depth': 1}
def successors(node):
if node['value'] == 5:
return []
elif node['value'] == 4:
return [{'value': 5, 'depth': node['depth']+1}]
else:
return... |
AUTHOR = 'Zachary Priddy. (me@zpriddy.com)'
TITLE = 'Event Automation'
METADATA = {
'title': TITLE,
'author': AUTHOR,
'commands': ['execute'],
'interface': {
'trigger_types': {
'index_1': {
'context': 'and / or'
},
'index_3': {
'context': 'and / or'
},
... |
#Y
for row in range(11):
for col in range(11):
if (row==col) or (row==0 and col==10)or (row==1 and col==9)or (row==2 and col==8)or (row==3 and col==7)or (row==4 and col==6):
print("*",end=" ")
else:
print(" ",end=" ")
print()
|
def can_send(user, case):
return user.is_superuser or user == case.created_by
def nl2br(text):
return text.replace("\n", "\n<br>")
|
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
stack, i = [], 0
while i < len(num):
if not stack:
if num[i] != "0":
stack.append(num[i])
elif stack[-1] <= num[i]:
stack.append(num[i])
else:
... |
# Create a function named stringcases that takes a string and
# returns a tuple of four versions of the string:
# uppercased, lowercased, titlecased (where every word's first letter
# is capitalized), and a reversed version of the string.
# Handy functions:
# .upper() - uppercases a string
# .lower() - lowercases a... |
# Leo colorizer control file for eiffel mode.
# This file is in the public domain.
# Properties for eiffel mode.
properties = {
"lineComment": "--",
}
# Attributes dict for eiffel_main ruleset.
eiffel_main_attributes_dict = {
"default": "null",
"digit_re": "",
"escape": "\\",
"highlig... |
"""container_pull macro with improved API"""
load("@io_bazel_rules_docker//container:container.bzl", _container_pull = "container_pull")
load("//bazel/workspace:image_digests.bzl", "IMAGE_DIGESTS")
def container_pull(
name,
registry,
repository,
tag = None,
digest = None,
... |
"""
Telescope Spectral Response Class
===================================
This class calculates the output flux of an astronomical object as a funtion
of the 1.6 m Perkin-Elmer spectral response.
"""
class Telescope_Spectral_Response:
pass
|
"""Main module."""
def say(num: int):
"""
Convert large number to sayable text format.
Arguments:
num : A (large) number
"""
under_20 = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
... |
#!/usr/local/bin/python
# Code Fights Array Change Problem
def arrayChange(inputArray):
count = 0
for i in range(1, len(inputArray)):
diff = inputArray[i] - inputArray[i - 1]
if diff <= 0:
inputArray[i] += abs(diff) + 1
count += abs(diff) + 1
return count
def main... |
class LanguageSpecification:
def __init__(self):
pass
@staticmethod
def java_keywords():
keywords = ['abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const']
keywords += ['continue', 'default', 'do', 'double', 'else', 'enum', 'extends', 'final'... |
class MODAK_sql:
CREATE_INFRA_TABLE = "create external table \
infrastructure(infra_id int, \
name string, \
num_nodes int, \
is_active boolean, \
... |
"""
ZODB Browser has the following submodules:
diff -- compute differences between two dictionaries
testing -- doodads to make writing tests easier
cache -- caching logic
history -- extracts historical state information from the ZODB
state -- IStateInterpreter adapters for ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.