content stringlengths 7 1.05M |
|---|
# 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
# Using Recursion
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
levels = []
... |
# Marcelo Campos de Medeiros
# ADS UNIFIP 2020.1
# Patos-PB 20/03/2020
'''
O Hipermercado Tabajara está com uma promoção de carnes que é imperdível. Confira:
Até 5 Kg Acima de 5 Kg
File Duplo R$ 4,90 por Kg R$ 5,80 por Kg
Alcatra R$ 5,90 por Kg R$ 6,80 por... |
print('='*20, 'DESAFIO 011', '='*20) #ok
a = float(input('Vamos calcular a quantidade de tinta necessária para pintar uma parede. \n\nPara isso, me informe em metros a altura da sua parede: '))
l = float(input('Agora é necessária a largura da sua parede em metros: '))
print('A quantidade de litros de tinta nec... |
# Escreva um programa que leia um valor
# em metros, e mostre ele em centímetros
# e milímetros.
n1 = float(input('Valor em metros: '))
print('\tValor em kilômetros: {}'.format(n1 / 1000))
print('\tValor em hectômetros: {}'.format(n1 / 100))
print('\tValor em centímetros: {}'.format(n1 * 100))
print('\tValor em milim... |
class Settings():
"""Game settings class.
Sets up in-game parameters and the screen attributes.
"""
def __init__(self):
# Screen parameters:
self.screen_width, self.screen_height = 800, 600
self.bg_color = 200, 200, 200
self.scoreboard_height = 50
s... |
class NoTradeError(RuntimeError):
"""
Exception class to raise if no trades are yielded.
"""
class NotRunError(ValueError):
"""
Exception class to raise if strategy is not run.
"""
|
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class EncryptionModeEnum(object):
"""Implementation of the 'EncryptionMode' enum.
The psk encryption mode for the SSID ('wpa', 'wep' or 'wpa-eap')
Att... |
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
n = len(nums)
candidates = [x for x in range(1,n+1)]
for num in nums:
if candidates[num-1] == num:
candidates[num-1] = 0
else:
candidates[num-1] = num*2
cur... |
SCREEN_TITLE = "Arcade game"
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 960
CAMERA_WIDTH = 700
CAMERA_HEIGHT = 500
SPRITE_SCALING = 0.5
SPRITE_PIXEL_SIZE = 32
SPRITE_NATIVE_SIZE = 32
SPRITE_SIZE = int(SPRITE_NATIVE_SIZE * SPRITE_SCALING)
MAP_WIDTH = 120
MAP_HEIGHT = 100
# Movement speed of player, in pixels per frame and is... |
print((ord('a'))) # prints "97" (will also work in 2.x)
print((ord('π'))) # prints "960"
print((chr(97))) # prints "a" (will also work in 2.x)
print((chr(960))) # prints "π"
|
def check_categories(session, categories_list):
if "diagnosis_previous_choices" in session.checker:
for category in categories_list:
if category in session.checker["diagnosis_previous_choices"]:
return True
return False
|
#!/usr/bin/python
#
# Kazdy node oznacza pewien sp-graf.
# Liscie to pojedyncze krawedzie, type=edge.
# Node z type=series oznacza wynik polaczenia szeregowego.
# Node z type=parallel oznacza wynik polaczenia rownoleglego.
# Node z type=jackknife oznacza wynik operacji jackknife.
class Node:
"""The class defining ... |
# Config file to guide the execution of the provided code
config = {
# Top level module
'module': 'network.train.Train',
# Output data location
'target_path': 'logs/plush',
'override': True,
# Randomness seed for reproducability
'seed': 0,
# Dataset options
'train_dataset_con... |
# 1. Union of 2 fuzzy sets
# Example to Demonstrate the Union of Two Fuzzy Sets
a = dict()
b = dict()
max_set = dict()
a = {"a": 1 , "b": .3 , "c": .5 , "d": 0.2 }
b = {"a": 0.5 , "b": 0.4 , "c": 0.1 , "d": 1}
print('The First Fuzzy Set is :', a)
print('The Second Fuzzy Set is :', b)
for i, j in zip(... |
# Copyright 2019 GreenWaves Technologies, SAS
# 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 i... |
{
"targets": [
{
"target_name": "zlib_sync",
"dependencies": [
"deps/binding.gyp:zlib",
],
"sources": [
"src/zlib_sync.cc",
],
"include_dirs": [
"<!(node -e \"require('nan')\")",
... |
""":mod:`asuka.urls` --- URL resolver
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
__all__ = 'commit', 'repository', 'service_config_file'
def repository(app):
"""GitHub repository."""
return app.repository.html_url
def commit(commit):
"""Commit changeset page."""
return repository(commit.app) + '/co... |
class DeviceTypes:
BITBOX02 = "bitbox02"
BITCOINCORE = "bitcoincore"
BITCOINCORE_WATCHONLY = "bitcoincore_watchonly"
COBO = "cobo"
COLDCARD = "coldcard"
ELECTRUM = "electrum"
ELEMENTSCORE = "elementscore"
GENERICDEVICE = "other"
JADE = "jade"
KEEPKEY = "keepkey"
LEDGER = "led... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `opendata_cacem_dechets` package."""
def empty_test():
assert True
|
class Student:
def hello(self, name=None, email=None):
if name is not None:
print(f'Hello: {name}')
if email is not None:
print(f'Email: {email}')
else:
print('No value provided')
s = Student()
s.hello('Pop', 'pop@')
|
# model settings
model = dict(
type='FastRCNN',
backbone=dict(
type='ResNet_I3D',
pretrained=None,
pretrained2d=False,
depth=50,
num_stages=3,
spatial_strides=(1, 2, 2),
temporal_strides=(1, 1, 1),
dilations=(1, 1, 1),
out_indices=(2,),
... |
#
# PySNMP MIB module SVRCLU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SVRCLU-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
class Repository:
def register_data_loaders(self, registry):
return registry
|
# Crie um programa que peça 2 motas ao usuário e retorne a média destas notas.
print('=-' * 7, 'DESAFIO 6', '=-' * 7)
a = input('Nome do Aluno: ')
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2) / 2
print('A média do aluno(a) {} foi de {:.2f}.'.format(a, m))
|
'''
For 300 points, create a game of Tron Light Cycles inspired by this clip:
www.youtube.com/watch?v=-3ODe9mqoDE
One player will use the arrow keys to change the direction of a red square.
The other player will use the wasd keys to change the direction of a blue square.
If either player's square runs into the other ... |
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head):
if not head:
return head
init = head
while init.next:
if init.val == init.next.val:
init.next = init.next.next
else:
... |
"""
变量交换
"""
# 方法一:借助第三个变量
# bridegroom_name = "武大郎"
# bride_name = "潘金莲"
# temp = bridegroom_name
# bridegroom_name = bride_name
# bride_name = temp
# print("交换后的新郎:" + bridegroom_name) #
# print("交换后的新娘:" + bride_name) #
# 方法二:直接交换
# a , b = b , a
bridegroom_name = "武大郎"
bride_name = "潘金莲"
bridegroom_name, br... |
n1= float(input('Digite a primeira nota nota do aluno'))
n2= float(input('Digite a segunda nota nota do aluno'))
soma = n1+n2
media= soma/2
print('A média entre {} e {} do aluno foi: {:.1f}'.format(n1,n2,media)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017-2022 Anderson Bravalheri, Univertity of Bristol
# High Performance Networks Group
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Yo... |
# Python3 program to sort an array
# using bucket sort
def insertionSort(b):
for i in range(1, len(b)):
up = b[i]
j = i - 1
while j >= 0 and b[j] > up:
b[j + 1] = b[j]
j -= 1
b[j + 1] = up
return b
def bucketSort(input_list):
# Find maximum value in ... |
alpha=['ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ']
word = input()
num=0
for i in word:
for j in alpha:
if i in j:
num += alpha.index(j)+3
print(num)
|
def clamp(coord, lower, upper):
"""
Clamp coord to lay between lower and upper.
"""
return min(upper, max(coord, lower))
|
class Contest:
__slots__ = ('name', 'site_tag', 'site_name', 'url', 'start', 'length')
def __init__(self, name, site_tag, site_name, url, start, length):
"""Represents a competitive programming contest.
:param name: the name of the contest
:param site_tag: the site tag
:param s... |
#
# PySNMP MIB module DFL1660-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DFL1660-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:42:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
answer = 1000 - int(int(input())%1000)
if answer == 1000:
print(0)
else:
print(answer) |
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
z = x + y;
print('Sum of', x, 'and', y, 'is: ', z) |
#Conditional Tests
time = 'morning'
print("is it morning? i would say True")
print(time == 'morning')
print("is it not morning? i would say False")
print(time != 'morning')
print("is it evening then? i would say False")
print(time == 'evening')
time = 'afternoon'
print("if its not evening then it may be afternoon? I... |
""" Several mostly undocumented scripts with unknown functionality
.. todo:: Documentation of scripts is to sparse
.. todo:: link source code of scripts
"""
|
class WFError(Exception):
def __init__(self, msg):
super().__init__(msg)
self.message = msg
def __repr__(self):
return self.message
class WFFileUnsupportedFormat(WFError):
def __init__(self, msg=''):
txt = 'Unsupported Watchface file'
if msg:
txt += f':... |
class Enum(object):
def __new__(cls, *args, **kwargs):
raise AttributeError("Cannot create/instantiate enum data type")
def __init__(self):
raise AttributeError("Cannot create/instantiate enum data type")
|
"""
import requests
type = "all"
url = f"http://localhost:5000/notice?type={type}"
result = requests.get(url)
print(result)
"""
|
'''
crie um programa que leia varios numeros e coloqueos em uma lista
- diga quantos foram digitados
- a lista de valores ordenadas de forma decrescente
- se o valor 5 foi digitado e esta ou nao na lista
'''
lista = []
while True:
num = int(input("diga um numero"))
continuar = str(input("Quer continuar [S/N]" ... |
def get_text_after_another_text():
text1 = input("Insert some text: ")
included_text = input('Insert text that is included in the above text: ')
print(text1.split(included_text, 1)[-1])
# index = text1.find(included_text)
# if index > 0:
# print(text1[index + len(included_text):], end='')
... |
FILTERS = {}
def register_filter(name):
def wraps(f):
FILTERS[name] = f
return f
return wraps
|
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
ans, codex = [], defaultdict()
def translate(c: str) -> str:
if c not in codex:
codex[c] = chr(97 + len(codex))
return codex[c]
def compare(word: str) -> None... |
"""
Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths ... |
# for stmt
for i in range(5):
print("range(5) values =",i)
for i in range(1, 5):
print("range(1,5) values =",i)
for i in range(1, 11, 2):
print("range(1,11,2) values =",i)
|
print('====== DESAFIO 59 ======')
escolha = 2
opcao = 0
while escolha == 2:
valor = int(input('Digite 1º valor: '))
valor2 = int(input('Digite o 2º valor: '))
print('[1] Somar')
print('[2] Subtrair')
print('[3] Multiplicar')
print('[4] Dividir')
print('[5] Reiniciar')
print('[6] Sair')
... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for _ in[0]*int(input()):
n=int(input())
k=[x for x in range(1,31) if n%((2<<x)-1)<1][0]
print(n//((2<<k)-1)) |
# O(n)time | O(n) space
# count from index 1, length = 1; if not add to res; handle last case
def runLengthEncoding(string):
res = []
length = 1
for i in range(1, len(string)):
if string[i] != string[i - 1] or length == 9:
res.append(str(length))
res.append(string[i - 1])
... |
"""Contains Various Classes for storing telescope positions.
"""
class HorizontalPosition:
"""Contains horizontal on sky position (ra, dec).
ra in hours as float
dec in degrees as float
"""
def __init__(self, ra, dec):
"""Construct instance.
Input: instance
... |
"""
Constants and Enums used by Grading.
"""
class ScoreDatabaseTableEnum:
"""
The various database tables that store scores.
"""
courseware_student_module = 'csm'
submissions = 'submissions'
overrides = 'overrides'
class GradeOverrideFeatureEnum:
proctoring = 'PROCTORING'
gradebook ... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
__version__ = '0.2.4'
|
""" Calculate spins (2S) from spin multiplicities.
"""
def spin(mult):
""" Calculate the spin (2Ms) from using the spin multiplicity
which is equivalent to the number of unpaired electrons.
:param mult: multiplicity
:type mult: int
:rtype: int
"""
return mult - 1
|
#: Module purely exists to test patching things.
thing = True
it = lambda: False
def get_thing():
global thing
return thing
def get_it():
global it
return it
def get_prop():
return ThingClass.prop
class ThingClass(object):
prop = True
|
class Dog:
'''
表示狗的类
'''
def __init__(self, name, age, gender, height):
self.name = name
self.age = age
self.gender = gender
self.height = height
def jiao(self):
'''
狗叫的方法
'''
print('汪汪汪~~~')
def yao(self... |
class TestFactorize(unittest.TestCase):
def test_wrong_types_raise_exception(self) -> None:
"""
Проверяет, что передаваемый в функцию аргумент типа
float или str вызывает исключение TypeError.
"""
cases = ('string', 1.5)
for x in cases:
with self.subTest(x... |
__version__ = "1.0"
# from .miniglbase import genelist, location, glload
# import .miniglbase
__all__ = ["genelist", "location", "glload",]
|
def get(self,key):
if self.root:
res = self._get(key,self.root)
if res:
return res.payload
else:
return None
else:
return None
def _get(self,key,currentNode):
if not currentNode:
return None
elif currentNode.key == key:
return curr... |
# Useful script for splitting a concatenated SDF (for eg: those from PubChem)
# Courtesy of someone on StackOverflow
f= "compound" # name of SDF file from database
split_number= 1000 # required #molecules per chopped file
number_of_sdfs=0
i=0
j=0
f2=open(f+'_'+str(j)+'.sdf','w')
for line in open(f+'.sdf'):
f2.write(l... |
"""
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
... |
class Car(object):
def __init__(self, name='General', model='GM', vehicle_type=None):
self.speed = 0
self.name = name
self.model = model
self.vehicle_type = vehicle_type
if self.name in ['Porshe', 'Koenigsegg']:
self.num_of_doors = 2
else:
self.num_of_doors = 4
if self.vehic... |
# Author: btjanaka (Bryon Tjanaka)
# Problem: (CodeJam) 2020-1a-pascal-walk
# Title: Pascal Walk
# Link: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd74/00000000002b1353
# Idea: Since the i-th row of Pascal's triangle sums to 2^(i-1), we can
# represent n as a binary number and choose to traver... |
aux = 0
num = int(input("Ingrese un numero entero positivo: "))
if num>0:
for x in range(0,num+1):
aux = aux + x
print (aux) |
def max_steps(self, A):
steps = [0] * (A+1)
steps[0] = 0
steps[1] = 1
steps[2] = 2
p = 10**9+7
for i in range(3,A+1):
steps[i] = steps[i-1]%p ++ steps[i-2]%p
return steps[A]%p
|
s = 'RLLLLRRRLR'
count = 0
output = 0
for i in range(len(s)):
if s[i] == 'R':
count += -1
if count == 0:
output += 1
else:
count += 1
if count == 0:
output += 1
print(output) |
''' -------> Descrição do Exercício <-------
Exercício utilizando Listas
Faça um algoritmo que, através da digitação pelo teclado, armazene várias cidades e seus estados.
Exemplo da estrutura das listas:
lista_de_cidades lista_de_estados
0 PORTO ALEGRE RIO GRANDE DO SUL
1 CANOAS RIO GRANDE DO SUL
2 GRAVATAI RIO GR... |
print('calcule a sua media anual !')
n1=float(input('primeira nota ='))
n2=float(input('segunda nota ='))
n3=float(input('terceira nota ='))
n4=float(input('querta nota ='))
m=(n1+n2+n3+n4)/4
print(' a sua media anual é {:.1f}'.format(m))
if m >= 6.0:
print('aprovado')
else:
print('reprovado')
|
"""
SKNet:
同样是一个轻量级嵌入式的模块,其灵感来源是,我们在看不同尺寸不同远近的物体时,
视觉皮层神经元接受域大小是会根据刺激来进行调节的。那么对应于CNN网络,一般来说对于特定任务特定模型,
卷积核大小是确定的,那么是否可以构建一种模型,使网络可以根据输入信息的多个尺度自适应的调节接受域大小呢?
基于这种想法,作者提出了Selective Kernel Networks(SKNet)。
"""
|
set_name(0x8013570C, "GameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x80135714, "GetDamageAmt__FiPiT1", SN_NOWARN)
set_name(0x80135D0C, "CheckBlock__Fiiii", SN_NOWARN)
set_name(0x80135DC0, "FindClosest__Fiii", SN_NOWARN)
set_name(0x80135F4C, "GetSpellLevel__Fii", SN_NOWARN)
set_name(0x80135FC0, "GetDirection8__Fiiii", ... |
class BaseAuth:
RESERVED_KWARGS = ['verify']
def __init__(self, *args, **kwargs):
"""Create auth object and establish connection
Args:
**kwargs: Keyword arguments specific to Auth engine
"""
for k, v in kwargs.items():
if k not in self.RESERVED_KWARGS:
... |
"""
the Trivial FTP protocol
"""
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Password Encryption',
'version': '2.0',
'author': ['Odoo SA', 'FS3'],
'maintainer': 'Odoo SA',
'category': 'Extra Tools',
'description': """
Encrypted passwords
===================
Rep... |
def iter_fact(n):
'''
assumes that n is an int > 0
returns n!
'''
result = 1
while n > 1:
result *= n
n -= 1
return result
iter_fact(5)
|
def calculate_metrics(predictions, labels, adjust):
tp = 0
tn = 0
fp = 0
fn = 0
if adjust:
preds = adjust_predictions(predictions, labels)
for i in range(len(predictions)):
if preds[i] == 1 and labels[i] == 1:
tp = tp + 1
elif preds[i] == 0 and labels[i] == 0:
tn = tn + 1
elif p... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class SlackAdapterOptions:
"""
Class for defining implementation of the SlackAdapter Options.
"""
def __init__(
self,
slack_verification_token: str,
slack_bot_token: str,
... |
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='sweetberry'
# the names j2, j3, and j4 are the white banks on sweetberry
# Note that here the bank name in the mux position is optional
# as... |
class Snake:
"""
class representing the snake
"""
pass |
class Settings:
IPS = 1 # default IPS value, 1 image per second
WIDTH = 128
HEIGHT = 72
EXT = ".jpeg"
ROWS = 30
COLS = 30
FILENAME_FORMAT = "%04d{ext}"
PREFIX = ""
@classmethod
def load(cls, width=None, height=None, ips=None, ext=None, rows=None, cols=None, prefix=None):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 11:45:19 2017
@author: dhingratul
"""
class Node:
def __init__(self,key):
self.left=None
self.right=None
self.val=key
# create root
root = Node(1)
''' following is the tree after above statement
1
/ \... |
k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
ans=0
for i in range(1,d+1):
if i%k==0 or i%l==0 or i%m==0 or i%n==0:
ans+=1
print(ans) |
"""
Settings specific to Country module
"""
FLAG_SOURCE = 'https://raw.githubusercontent.com/cristiroma/countries' \
'/master/data/flags/SVG/{alpha_2}.svg?sanitize=true'
# put in global settings.py to override
GEOCODING_SERVICE = 'pelias'
# put in global settings.py to override
GEOCODER_PELIAS_URL = 'h... |
# -*- coding: utf-8 -*-
class ScrapbookException(ValueError):
"""Raised when an exception is encountered when operating on a notebook."""
class ScrapbookMissingEncoder(ScrapbookException):
"""Raised when no encoder is found to tranforming data"""
class ScrapbookDataException(ScrapbookException):
"""Ra... |
print('''
is_male = True
if is_male:
print("Male")
''')
is_male = True
if is_male:
print("Male")
print('''
is_male = False
if is_male:
print("Male")
''')
print('''
is_male = False
if is_male:
print("Male")
else:
print(" Not Male")
''')
print('''
is_male = True
is_... |
'''面试题45:把数组排成最小的数
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
----------------
Example:
input:[3,32,321]
output:321323
----------------
排序规则设计,规则证明(自反,对称,传递),算法证明,大数防治
'''
class NewString(object):
def __init__(self, string):
self.string = str(string)
def __lt__(self, other):
return s... |
class Item:
"""
This is out domain! The item hold the details of its inventory item
"""
def __init__(self, name, code, unit_price):
self.name = name
self.code = code
self.quantity = 0
self.unit_price = unit_price
self.total_price = 0
def increment(self):
... |
year = int(input("Which year do you want to check?\n"))
# **every** year that is evenly divisible by 4
# **except** every year that is evenly divisible by 100
# **unless** the year is also evenly divisible by 400
leap_1 = year % 4 == 0 # if result is equal 0 then leap year
non_leap_1 = year % 100 != 0 # but if resu... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 11:24:13 2019
@author: Administrator
"""
class Solution:
def countSubstrings(self, s: str) -> int:
count = 0#ans = []#
for k in range(len(s)):
m = 0
while 0<=k-m and k+m<=len(s)-1 and s[k-m] == s[k+m]:
count ... |
class Solution:
def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
seqs = [seq for seq in seqs if seq]
if not seqs:
return False
n = len(org)
degrees = [0] * (n + 1)
follows = collections.defaultdict(list)
seen = set()
... |
class OleFileError(IOError):
"""
Generic base error for this module.
"""
pass
class NotOleFileError(OleFileError):
"""
Error raised when the opened file is not an OLE file.
"""
pass
class OleFileIONotClosed(RuntimeWarning):
"""
Warning type used when OleFileIO is destructed... |
#define a value holder class
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
# function to verify matching case
# => True or False
def case(*args):
iterator = (arg == switch.value for arg in args)
return any(iterator)
# Switch example:
f... |
#Crie um pgm que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionario e todos os dicionários em uma lista. No final, mostre:
#A)Quantas pessoas foram cadastradas
#B)A média de idade do grupo
#C)Uma lista com todas as mulheres.
#D)Uma lista com todas as pessoas com idade acima da... |
fig, ax = plt.subplots(figsize=(8.8, 5))
points = plt.scatter(*Xpca.T, c=sp98_dept_filled.std(), cmap='cubehelix')
for (x, y), name in zip(Xpca, sp98_dept_filled.columns):
plt.annotate(name, (x,y))
plt.colorbar(label='Écart type des prix par station')
|
class ConvertNotation:
def __init__(self):
self.target_base = 2
self.from_base = 10
def number_to_base(self, number, from_base=None, base=None):
if number == '0':
return number
self.target_base = base if base else self.target_base
self.from_base = from_base i... |
produto = float(input('Qual o preço do produto? '))
percentual = float(input('Persentual do produto? '))
desconto = produto * (percentual / 100)
final = produto - percentual
print('o produto custa: {}. Menos o desconto de {}%. O preço fica: {}'.format(produto, percentual, final))
|
# Apr 12
class Solution:
def totalFruit(self, tree: List[int]) -> int:
left = 0
result = 0
seen = dict()
cur = 0
for i, n in enumerate(tree):
seen[n] = seen.get(n, 0) + 1
if len(seen) <= 2:
result = max(result, i - left + 1)
... |
class ExampleFaceDetector:
"""It doesn't really work!"""
def __init__(self, example_parameter):
self.example_parameter = example_parameter
@staticmethod
def detect_faces(_binary_data):
return [((110, 120), (130, 140)),
((220, 240), (230, 250)),
((300, 300... |
def campo(txt):
esp = len(txt) + 2
print('~'*esp)
print(f' {txt} ')
print('~'*esp)
campo('eeita porra consegui')
|
# cases where ComprehensionsAchievement should not unlock
# >> CASE
for _ in range(10):
pass
# >> CASE
set([4, 5, 6])
# >> CASE
{4, 5, 6}
|
class Z80BINFileHandler:
def __init__(self):
self.execAddr = 0x8000
self.baseAddr = 0x8000
def genS3Rec(self, startCh, addr, data, leng, offset):
s3Rec = startCh + "3" + "{:0>2x}".format(leng + 5)
csum = leng + 5
s3Rec += "{:0>8x}".format(addr)
csum +=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.