content stringlengths 7 1.05M |
|---|
"""
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from
top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 ... |
class BST():
def __init__(self,data):
self.key = data
self.lch = None
self.rch = None
def Print(self):
if self is None or self.key is None:
return
if self.lch:
self.lch.Print()
if self.rch:
self.rch.Print()
prin... |
i = 0
while True:
print(i)
i+=1 |
class Solution:
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
# 32 bits integer max
MAX = 0x7FFFFFFF
# 32 bits interger min
MIN = 0x80000000
# mask to get last 32 bits
mask = 0xFFFFFFFF
while b !=... |
"""
Task Score: 100%
Complexity: O(N * log(N))
"""
def solution(A):
"""
On the face of it this is quite simple, until you factor in negative
numbers.
Approach is very simple:
1. Sort array in descending order (or ascending if you like)
2. Take the max value in between the sum of the head of t... |
"""
python中的类和对象, 所有的类的祖先都是object和java是一样的
1- 前两种叫做经典类存在python 2.x中, 最后一种叫做新式类
2- python 2中类并没有父类,自己就是父类
3- 而python3中得class Person(object)存在父类,可以使用根类的方法
"""
class Person:
pass
class Person():
pass
class Person(object):
pass
"""
1- 实例方法的第一个形参是self自身,表示调用该方法的对象,谁调用谁就是self
2- 给一个**对象... |
def bbox_normalize(bbox, image_size):
return tuple(v / image_size[0] if i % 2 == 0 else v / image_size[1] for i, v in enumerate(bbox))
def bbox_denormalize(bbox, image_size):
return tuple(v * image_size[0] if i % 2 == 0 else v * image_size[1] for i, v in enumerate(bbox))
|
# Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
casa = float(input('Qual é o valor da casa? R$'))
salário = float(i... |
def calculateStats(numbers):
if len(numbers) == 0:
stat_dict = {"avg": "nan", "max": "nan", "min": "nan"}
else:
max_value = max(numbers)
min_value = min(numbers)
avg_value = round(sum(numbers) / len(numbers), 3)
stat_dict = {"avg": avg_value, "max": max_value, "min": min... |
data = (
None, # 0x00
None, # 0x01
None, # 0x02
None, # 0x03
None, # 0x04
'B', # 0x05
'P', # 0x06
'M', # 0x07
'F', # 0x08
'D', # 0x09
'T', # 0x0a
'N', # 0x0b
'L', # 0x0c
'G', # 0x0d
'K', # 0x0e
'H', # 0x0f
'J', # 0x10
'Q', # 0x11
'X', # 0x12
'ZH', # 0x13
'CH',... |
def solution(num):
"""Find the maximal sequence of consecutive ones"""
try:
num = int(num)
count = 0
if(num > 0):
while(num != 0):
num = (num & (num << 1))
count += 1
return count
except ValueError:
return 'Invalid input.'... |
jibunno = "red"
kimino = "green"
kari = jibunno
jibunno = kimino
kimino = kari
print(jibunno, kimino)
|
class LinkedStack:
class _Node:
__slots__ = '_element', '_next'
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
self._head = None
self._size = 0
def __len__(self):
return self._size
def i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
dice = []
for d1 in range(1, 7):
for d2 in range(1, 7):
dice.append((d1, d2))
n = 0
comb = []
for d1, d2 in dice:
if d1 + d2 == 7:
n += 1
comb.append((d1,d2))
print('%d combinations results in the sum 7' % n)
print(comb)
|
"""Sector and industries."""
SECTORS = [
{
"name": "Chemical",
"industries": [
{"name": "Other"},
{"name": "Basic Chemicals"},
{"name": "Specialty Products"},
{"name": "Pharmaceutical Products"},
{"name": "Consumer Products"},
{... |
nome = input('Digite seu nome: ').strip()
salario = float(input('Digite o valor do seu salário: '))
valor = float(input('Digite o valor do imóvel que deseja comprar: '))
tempo = int(input('Digite a quantidade de meses que deseja pagar o imóvel: '))
print(' ')
prest = valor / tempo
print(f'Valor da prestação: {prest}')... |
def selectionsort(L):
n = len(L)
for i in range(n-1):
max_index=0
for index in range(n - i):
if L[index] > L[max_index]:
max_index = index
L[n-i-1], L[max_index] = L[max_index], L[n-i-1]
|
class Constants:
WINDOW_BACKGROUND_RGB: str = '#393939' # this needs to be the same as in windowstyle.py
GREY_180_RGB: str = '#b4b3b3' # Text color
GREY_127_RGB: str = '#7f7f7f' # 127, 127, 127 disabled
GREY_90_RGB: str = '#5a5a5a' # 90, 90, 90 midlight
GREY_5C_RGB: str = '#026fb2' # button
... |
# ************************ compare_object_with_info.py ****************************** #
# #
# compare_object_with_info.py - #
# ... |
n = int(input())
arr = [int(x) for x in input().split()]
distinct = set(arr)
print(len(distinct)) |
class ZoneinfoError(Exception):
pass
class InvalidZoneinfoFile(ZoneinfoError):
pass
class InvalidTimezone(ZoneinfoError):
def __init__(self, name):
super(InvalidTimezone, self).__init__(
'Invalid timezone "{}"'.format(name)
)
class InvalidPosixSpec(ZoneinfoError):
d... |
class RenderQueue:
def __init__(self, window):
self.window = window
self.queue = []
def render(self):
if self.queue:
self.queue[0]()
def next(self):
self.queue = self.queue[1:]
def add(self, source):
self.queue.append(source)
def cl... |
def question(text, default=None, resp_type=None):
if default is None:
default_str = ''
else:
default_str = f'({default})'
resp = input(f'{text}{default_str}: ')
if not resp:
return default
if resp_type:
return resp_type(resp)
return resp
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.arrVal = []
self.arrTmp = []
def isSymmetric(self,root):
if root == None:
return True
num = 0
self.arrTmp.append(root)
while (len(self.arrTmp) !=... |
a,b,n,w=list(map(int,input().split()))
L = []
for i in range(1,n):
if a*i + b*(n-i) == w:
L.append(i)
if len(L) == 1:
print(L[0],n-L[0])
else:
print(-1) |
#!/usr/bin/env python3
def is_terminal(battle_data) -> bool:
return battle_data["ended"]
def get_side_value(side) -> float:
return sum(pokemon["hp"] / pokemon["maxhp"] for pokemon in side["pokemon"])
def get_heuristic_value(battle_data):
sides = battle_data["sides"]
return get_side_value(sides[1])... |
class Cartes:
couleur = ("bleu", "vert", "rouge", "jaune")
valeur = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "+2", "inversion", "passer", "stop")
def __init__(self, coul, val):
self.valeur = val
self.couleur = coul
def validation(self, val, coul):
if val > 0 or val < 14:
rais... |
class Connector:
"""We use this as a public base class. Customized connectors
inherit this class as a framework for building them.
.. note::
Base connector class class as framework for child classes.
"""
def __init__(self):
"""Instantiates the base connector.
"""
... |
inputs = [1,2,3,2.5]
weights1 = [0.2,0.8,-0.5,1.0]
weights2 = [0.5,-0.91,0.26,-0.5]
weights3 = [-0.26, -0.27, 0.17, 0.87]
bias1 = 2
bias2 = 3
bias3 = 0.5
output = [inputs[0] * weights1[0] + inputs[1] * weights1[1] + inputs[2] * weights1[2] + inputs[3] * weights1[3] + bias1,
inputs[0] * weights2[... |
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [1,2,3]
# number of items in list
print(f"number of items in l1 : {len(l1)}")
# compare lists , == compare the data element wise
print(l1 == l1)
print(l1 == l3)
print(l1 == l2)
|
# -*- coding: utf-8 -*-
"""
This program can calculate the hit and miss % using FIFO method.
Created on Wed Sep 4 16:42:16 2019
@author: tuhin Mitra
"""
# demo = """
# You Can Either enter string like this:
# 1,3,0,3,5,6
# or,
# You can Also Enter like this:
# 130356
# (for b... |
#!/usr/bin/env python3
"""
Two words form a “metathesis pair” if you can transform one into the other by
swapping two letters; for example, “converse” and “conserve”. Write a
program that finds all of the metathesis pairs in the dictionary.
"""
|
class CannotExploit(Exception):
pass
class CannotExplore(Exception):
pass
class NoSuchShellcode(Exception):
pass
|
# Fonte: https://leetcode.com/problems/sqrtx/
# Autor: Bruno Harlis
# Data: 18/08/2021
"""
Dado um número inteiro x não negativo, calcule e retorne a
raiz quadrada de x .
Como o tipo de retorno é um inteiro, os dígitos decimais são
truncados e apenas a parte inteira do resultado é retornada.
Nota: Você não tem permis... |
class TankBoard:
"""
Represents the board tanks are located on.
Attributes:
_height: height of the board
_width: width of the board
_board: 2D Array
"""
def __init__(self, width, height):
self._height = height
self._width = width
self._board = [[None f... |
def soma(lista):
if len(lista) == 0:
return 0
else:
return lista[0] +soma(lista[1:])
print(soma([1,2,3,4,5,6,7]))
def fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
|
#
# from src/eulerian.c
#
# Eulerian to eulerianNumber
#
def eulerianNumber(n, k):
if k == 0:
return 1
if k < 0 or k >= n:
return 0
return (k+1) * eulerianNumber(n-1,k) + (n-k) * eulerianNumber(n-1,k-1)
|
# go_board.py
class GoBoard:
EMPTY = 0
WHITE = 1
BLACK = 2
def __init__( self, size = 0 ):
self.size = size
if size > 0:
self.matrix = [ [ self.EMPTY for j in range( size ) ] for i in range( size ) ]
def Serialize( self ):
return {
'size' : self... |
"""
Default config for Workload Automation. DO NOT MODIFY this file. This file
gets copied to ~/.workload_automation/config.py on initial run of run_workloads.
Add your configuration to that file instead.
"""
# *** WARNING: ***
# Configuration listed in this file is NOT COMPLETE. This file sets the default
# configur... |
class QuoteInfo:
def __init__(self):
self.symbol = str()
self.exchange = str()
self.date = None
self.time = None
self.local_time = None
self.price = float()
self.volume = int()
self.changepct = float()
def __repr__(self):
d = []
... |
class City:
def __init__(self, name, lat, lon):
self.name=name;
self.lat=lat;
self.lon=lon; |
class InvalidInterface(Exception):
pass
class EmptyInterface(InvalidInterface):
pass
class NotAFileError(Exception):
pass
class MissingFileError(Exception):
pass
|
#генератор заданий
shifts = [r'\Opcode{ror}', r'\Opcode{rol}']
logics = [[r'\Opcode{or}', r'\Opcode{not}'], [r'\Opcode{nor}'], [r'\Opcode{nand}'], [r'\Opcode{xor}', r'\Opcode{or}']]
adds = [r'\Opcode{add}', r'\Opcode{sub}']
jumps = [r'\Opcode{jz}', r'\Opcode{jo}']
for shift in shifts:
for logic in logi... |
# 자연수 뒤집어 배열로 만들기
def solution(n):
answer = []
n = str(n) # string type casting
for i in reversed(range(len(n))):
answer.append(int(n[i]))
return answer
'''
테스트 1 〉 통과 (0.03ms, 10.3MB)
테스트 2 〉 통과 (0.03ms, 10.3MB)
테스트 3 〉 통과 (0.03ms, 10.4MB)
테스트 4 〉 통과 (0.02ms, 10.3MB)
테스트 5 〉 통과 (... |
'''
Given a set of distinct integers, nums, return all possible subsets (the power set).
'''
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = [[]]
for num in nums:
for j in range(len(result)):
... |
#! /usr/bin/env python3
a=[1, 4, 3, 53, 2]
print("list :", a)
print(a.pop()) #poping last element
print("pop element from list :", a)
a.append(21) #adding element in list
print("adding element in list :", a)
|
"""
This file contains ASCII art used in the Birthday Wisher program
"""
logo = """
,-----. ,--. ,--. ,--. ,--. ,--. ,--.,--. ,--.
| |) /_ `-... |
# Distinct powers
def koliko_potenc():
sez = []
for a in range(2, 101):
for b in range(2, 101):
sez.append(a ** b)
return sez
def izloci_iste(sez):
podvojeni = 0
for i in range(len(sez)):
if sez[i] in sez[:i] :
podvojeni += 1
return len(sez) - podvojeni
... |
# MIT 6.006 Introduction to Algorithms, Spring 2020
# see: https://www.youtube.com/watch?v=r4-cftqTcdI&list=PLUl4u3cNGP63EdVPNLG3ToM6LaEUuStEY&index=42
def max_score_prefix(in_list: list):
dp = [0] * (len(in_list) + 1)
in_list.insert(0, 1)
for i in range(1, len(in_list)):
dp[i - 1] = max(dp[i - 2],... |
def gen_perms_helper(array, current, subsets, index):
if index >= len(array):
subsets.append(current)
return
gen_perms_helper(array, current.copy(), subsets, index + 1)
current.append(array[index])
gen_perms_helper(array, current.copy(), subsets, index + 1)
def gen_perms(array):
su... |
class WireMap:
def __init__(self):
self.wire_map = {}
self.x = 0
self.y = 0
self.step_counter = 0
def move(self, steps, x_dir, y_dir):
while steps > 0:
self.x += x_dir
self.y += y_dir
self.step_counter += 1
self.wire_map[(... |
a = float(input('qual o primeiro numero? '))
b = float(input('qual o segundo numero? '))
c = float(input('qual o terceiro numero? '))
if a > b and a > c:
print('o numero {} é o maior de todos '.format(a))
if b > a and b > c:
print('o numero {} é o maior de todos '.format(b))
if c > b and c > a:
print('o num... |
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
for i in range(len(s)):
res = max(res,self.lp(s,i,i),self.lp(s,i,i+1),key=len)
return res
def lp(self,s,l,r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Priority(object):
def __init__(self, nlp, object):
self.object = object
self.matcher = object.matcher.Matcher(nlp.vocab)
self.matcher.add("Priority", None,
#important
[{'LOWER': 'important'}],
... |
#!/usr/bin/python3.5
# -*-coding:utf-8 -*
annee=int(input("Taper une année : "))
#yprint(type(annee))
if annee%4==0:
if annee%100==0:
if annee%400==0:
print(annee, "est une annee bissextile")
else:
print(annee, "n\'est pas une annee bissextile")
else:
print(annee, "est une annee bissextile")
else:
pri... |
class TileData(object):
def __init__(self, filename, z, x, y) -> None:
self.filename = filename
self.z = z
self.x = x
self.y = y
|
def f(x):
print(str(x))
i = input("書きたい事を書いてね")
f(str(i)) |
#! /usr/bin/env python
# coding: utf-8
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is not None:
return cls._instance
o = object.__new__(cls)
cls._instance = o
return o
@classmethod
def get_instance(cls):
... |
line_input = list(x for x in input())
num_list = list(int(x) for x in line_input if x.isnumeric())
words = list(x for x in line_input if not x.isnumeric())
take = list(num_list[x] for x in range(len(num_list)) if x % 2 == 0)
skip = list(num_list[y] for y in range(len(num_list)) if y % 2 == 1)
result = []
for i in range... |
class Sampleinfor:
def __init__(self, samplename, datafile, fregion, hotspots=list()):
self.samplename = samplename
self.datafile = datafile
self.hotspots = hotspots
self.fregion = fregion |
a=1
print( not isinstance(a,str))
if __name__ == "__main__":
codes = [1,2,3,4,5,6,7,8,9,10]
offset = 0
limit = 3
total = len(codes)
while offset < total:
print("offet:{} limit:{} partial codes:{}".format(offset,limit, codes[offset:offset+limit]))
offset += limit |
def func():
nums = [1,3,4,4,3]
sum = 0
# Converting nums to a set which gives us
s = set(nums)
# s = [1,3,4]
for i in s:
if nums.count(i)==1:
sum +=i
print(sum)
func() |
def test_register_function(fresh_db):
@fresh_db.register_function
def reverse_string(s):
return "".join(reversed(list(s)))
result = fresh_db.execute('select reverse_string("hello")').fetchone()[0]
assert result == "olleh"
def test_register_function_multiple_arguments(fresh_db):
@fresh_db.... |
#cAssume s is a string of lower case characters.
#Write a program that prints the longest substring of s in which the letters occur
# in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
#Longest substring in alphabetical order is: beggh
#In the case of ties, print the first subs... |
#!/usr/bin/env python
"""A module with the database time test mixin."""
class DatabaseTimeTestMixin(object):
"""A mixin for testing time-related methods of database implementations."""
def testNowPositive(self):
timestamp = self.db.Now()
self.assertGreaterEqual(timestamp, 0)
def testNowMonotnic(self):... |
class Solution:
def combinationSum2(self, candidates, target):
if not candidates or not target:
return []
result = []
cand = sorted(candidates)
N = len(candidates)
def dfs(remainder, curr_combo, start):
if remainder == 0:
result.append... |
template_file = 'gallery-template.md'
output_filename = 'gallery.md'
base_filename = 'http://alanpryorjr.com/visualizations/'
base_image_filename = '../visualizations/'
key_base = "bokeh_glyphs_{}"
glyph_names = ['annular_wedge', 'annulus','arc','asterisk','bezier', 'circle',
'circle_cross','circle_x','cross','diamon... |
# crie um programa onde o usuario possa digitar varios valores (perguntar se ele deseja continuar);
# cadastre esses numeros numa lista ; caso o numero já exista ele nao será adicionado
# mostrar todos os valores unicos digitados em ordem crescente
valores = []
while True:
n = int(input("Digite um valor: "))
... |
# Exercício 93 do Curso em Vídeo de Python
jogador = dict()
gol = []
partidas = totalgols = 0
print('-=' * 30)
jogador['nome'] = str(input('Nome do jogador: '))
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
for p in range(partidas):
gol.append(int(input(f' Quantos gols na partida {p + 1}? ... |
class BaseReporter(object):
"""Delegate class to provider progress reporting for the resolver.
"""
def starting(self):
"""Called before the resolution actually starts.
"""
def starting_round(self, index):
"""Called before each round of resolution starts.
The... |
'''
2^100
'''
n = 1
result = 1
while n <= 10:
result = result * 2
print(result)
n = n + 1
print('The final is', result)
|
# function to create a list (marks) with the content of every line, every item corresponds to a line with the same index
def scan(vp):
marks = []
for line in vp:
# defining positions of last start and end of general information
text_start = 0
text_end = 0
for idx, mark in enumera... |
# __ __ _ __ ____ _ _
# \ \ / / | |/ _| _ \ | (_)
# \ \ /\ / /__ | | |_| |_) | ___ | |_ _ __
# \ \/ \/ / _ \| | _| _ < / _ \| | | '_ \
# \ /\ / (_) | | | | |_) | (_) | | | | | |
# \/ \/ \___/|_|_| |____/ \___/|_|_|_| |_|
... |
def main():
print(add(1, 3))
def add(a: int, b: int):
return a + b
|
__version__ = "0.29.9"
__db_version__ = 7
__author__ = "Kristian Larsson, Lukas Garberg"
__author_email__ = "kll@tele2.net, lukas@spritelink.net"
__copyright__ = "Copyright 2011-2014, Kristian Larsson, Lukas Garberg"
__license__ = "MIT"
__status__ = "Development"
__url__ = "http://SpriteLink.github.com/NIPAP"
|
CSV_HEADERS = [
"externalID",
"status",
"internalID",
"rescueID",
"name",
"type",
"priBreed",
"secBreed",
"mix",
"sex",
"okwithdogs",
"okwithcats",
"okwithkids",
"declawed",
"housebroken",
"age",
"specialNeeds",
"altered",
"size",
"uptodate... |
load(
"@io_bazel_rules_scala//scala:providers.bzl",
_DepsInfo = "DepsInfo",
_ScalacProvider = "ScalacProvider",
)
def _compute_strict_deps_mode(input_strict_deps_mode, dependency_mode):
if dependency_mode == "direct":
return "off"
if input_strict_deps_mode == "default":
if dependenc... |
# Automatically generated
# pylint: disable=all
get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4Addres... |
class StringWriter(TextWriter, IDisposable):
"""
Implements a System.IO.TextWriter for writing information to a string. The information is stored in an underlying System.Text.StringBuilder.
StringWriter()
StringWriter(formatProvider: IFormatProvider)
StringWriter(sb: StringBuilder)
StringWri... |
# 8. With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155],
# write a program to make a list whose elements are intersection of the above given lists.
listA = [1, 3, 6, 78, 35, 55]
listB = [12, 24, 35, 24, 88, 120, 155]
setA = set(listA)
setB = set(listB)
insersaction_of_AB = setA... |
#encoding:utf-8
subreddit = 'WikiLeaks'
t_channel = '@r_WikiLeaks'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 15:11:02 2020
@author: dhaar01
"""
n = int(input())
s = set()
for i in range(n):
s.add(input())
print(len(s))
|
"""
Given a string, find the rank of the string amongst its permutations sorted lexicographically.
Assume that no characters are repeated.
Example :
Input : 'acb'
Output : 2
The order permutations with letters 'a', 'c', and 'b' :
abc
acb
bac
bca
cab
cba
The answer might not fit in an integer, so return your answer %... |
#
# PySNMP MIB module WWP-LEOS-PING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-PING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:38:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# Copyright (c) 2009 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.
{
'variables': {
'chromium_code': 1,
'chromium_root': '<(DEPTH)/third_party/chromium/src',
},
'targets': [
{
'target_name': 'inst... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"CoreClass": "00_core.ipynb",
"TSDataFrame": "01_TSDataFrame.ipynb"}
modules = ["core.py",
"TSDataFrame.py"]
doc_url = "https://alvaroof.github.io/nbdevtest/"
git_url = "https://github.... |
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
class Solution(object):
# @param a ListNode
# @return a ListNode
def swapPairs(se... |
class JobSummary(object):
"""
job summary data structure from job format in couchdb
"""
def __init__(self , jobStatus = None):
self.jobStatus = {
"success": 0,
"canceled": 0,
"transition": 0,
"queued": {"first": 0, "retry": 0},... |
N, K = map(int, input().split())
if K > 1:
diff = N-K
print(diff)
else:
print(0)
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("@bazel_skylib//lib:shell.bzl", "shell")
load("//antlir/bzl:oss_shim.bzl", "buck_genrule")
load("//antlir/bzl:shape.bzl", "shape")
load... |
def part1(data):
return score(combat(*parse(data)))
def parse(data):
players = []
for player, cs in enumerate('\n'.join(data).split('\n\n'), 1):
cards = [int(c.strip()) for c in cs.split('\n')[1:]]
players.append(cards)
return players
def combat(a, b):
if not a:
return b
... |
template = """
From: <{from_email}>
To: <{to_email}>
Subject: {subject}
{message}"""
print(template.format(
from_email = "a@example.com",
to_email = "b@example.com",
message = "Here's some mail for you. "
" Hope you enjoy the message!",
subject = "You have mail!"
))
|
"""
bitproto.grammars
~~~~~~~~~~~~~~~~~
Grammar rules.
"""
# fmt: off
r_optional_semicolon = """
optional_semicolon : ';'
|
"""
r_start = """
start : open_global_scope global_scope close_global_scope
"""
r_open_global_scope = """
open_global_scope :
"""
r_close_global_scope = """
close_global_s... |
# -*- coding: utf-8 -*-
"""
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
empty_list = list()
print(empty_list)
# %%
techs = ['python', 'java', 'c++', 'go', 'sql']
techs[0] = 'python 3.7'
print(techs)
# %%
numbers = [3, 5, 3, 5, 23]
print(numbers)
print(type(numbers))
# %%
mixed = ['python', 3.7, 4... |
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2020
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terce... |
"""modelinfo_cfg - TEPPr configuration
This is mutable object.
* one teppr cfg points to only one dataset
* one teppr cfg can have many trainings and respective evaluations, reportings
and tracks which of the training is published
* The sequence of trainings can be parallel schedule or sequence schedule.
* In case it ... |
input = """
#maxint = 10.
total_score(S,X) :- t, S==9, X = #max{ Y :score(Y) }.
total_score1(S,X) :- t, S=9, X = #max{ Y :score(Y) }.
"""
output = """
{}
"""
|
# 2021 June 13 13:48 - 14:06
# 10101
# 01010
# Naturally, the sum would be 11111, which is 100000 - 1.
# The essence then is to know the length of its bits representation.
class Solution:
def findComplement(self, num: int) -> int:
cnt = 0
orig = num
while num != 0:
num >>= 1
... |
# A way of notifying a number of observer classes depending on the state of observed class is changed.
class Subject:
"""What is observed"""
def __init__(self):
self._observers = []
def notify(self, modifier=None):
for observer in self._observers:
if modifier != observer:
... |
# Maior e menor valores
'''Faça um programa que leia três números
e mostre qual é o MAIOR e qual é o MENOR'''
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n3 = int(input('Digite mais um número: '))
# Verificando qual número é menor
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.