content stringlengths 7 1.05M |
|---|
def extraerDatos(dato):
palo = dato[0:1] # Se extrae el primer caracter correspondiente a un palo
aux = dato.split(palo)
valor = int(aux[1]) # Se extra el valor del caracter
if (valor >= 10): # En el envido las cartas de 10 para arriba suman cero
valor = 0
r... |
class Life:
def __init__(self, width, height):
self.width = width
self.height = height
self.frame = [[0 for x in range(width)] for y in range(height)]
def import_frame(self, fname):
with open(fname, 'r') as f:
lines = f.readlines()
for i, line in enumerate(l... |
class Estadistica:
def __init__(self):
self.bodega_saladillo = []
self.bodega_saladillo_hora = []
self.bodega_andina = []
self.bodega_andina_hora = []
self.camiones_t2 = []
self.error_bodega = 0
self.barcos_puerto = []
self.ocupacion_trenes = []
... |
autoalias = {\
"OOO DREES + SOMMER": "000 DREES SOMMER",\
"ESMIRA JAMALKHANOVA": "16006",\
"3S MADENCILIK SERAMIK INSAAT NAKLI": "3S MADENCILIK SERAMIK INSAAT",\
"AAT HOLDING SP. Z.O.O.": "AAT HOLDING SP OO",\
"AAT HOLDING SP. Z O.O.": "AAT HOLDING SP OO",\
"AGRO WEST LLC / AQRO-VEST MMM": "AGRO WEST",\
"AQRO-VEST MMM"... |
# Write a program that reads in three strings and sorts them lexicographically.
# Enter a string: Charlie
# Enter a string: Able
# Enter a string: Baker
# Able
# Baker
# Charlie
string1 = str(input("Enter a string: "))
string2 = str(input("Enter a string: "))
string3 = str(input("Enter a string... |
"""
Implements utility functions.
"""
def list_to_string(l: list) -> str:
"""
:param list l: A list to serialize.
:return str: The same list, as a string.
"""
return ', '.join([str(v) for v in l])
def string_to_list(s: str) -> list:
"""
:param str s: A serialized list.
:return list: ... |
# -*- coding: utf-8 -*-
"""
photolog.controller
~~~~~~~~~~~~~~~~~~~
photolog 어플리케이션에 적용될 URI를 라우팅하는 controller 패키지 초기화 모듈.
:copyright: (c) 2013 by 4mba.
:license: MIT LICENSE 2.0, see license for more details.
"""
__all__ = ["login", "photo_upload", "photo_show","register_user", "twitter"]
|
"""
A palindromic number reads the same both ways. The largest palindrome made from the
product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def test_is_palindrome():
assert is_palindrome(111) == True
assert is_palindrome(121) == True... |
#!/usr/bin/env python
#coding: utf-8
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
for x in s:
if x == '(' or x == '{' or x == '[':
stack.append(x)
else:
if not stack: return False
y = stack.pop()
... |
def doSubtraction():
a=30
b=20
print(a-b)
doSubtraction()
#This is Code for Subtraction
|
o = int(input())
c = -1
for i in range(1000000000000):
i = str(i)
t = 0
for j in range(len(i)):
k = abs(int(i[j - 1]) - int(i[j]))
if k > 1:
t = 1
break
if t:
continue
c += 1
if c == o:
print(i)
break
|
print('hello world')
for item in [1,2,3,4,5,6,'foo','bar','baz']:
print('eh')
class MyCustomClass(object):
arg = None
def __init__(arg):
self.arg = arg
def my_method(self):
return self.arg + 1
def more_python(self):
return 1 + 1 + 2
def new_method():
return self.arg * arg
... |
class DocumentDocstring:
def __init__(self, expression):
self._exp = expression
self._docstring = expression.value.s
def title(self):
return self._docstring.split('\n')[0]
def body(self):
b = []
skipped_lines = 1
for s in self._docstring.split('\n'):
... |
class Solution:
def romanToInt(self, s: str) -> int:
res = 0
last = None
for d in s:
if d == 'M':
res += 800 if last == 'C' else 1000
elif d == 'D':
res += 300 if last == 'C' else 500
elif d == 'C':
res += 80... |
print('Entre com dois valores: ')
v1 = float(input('1º Valor: '))
v2 = float(input('2º Valor: '))
op = 0
while op != 5:
op = int(input("""\nO que você deseja fazer com esses dois números:
[ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Saber qual é o maior valor
[ 4 ] Digitar novos números
[ 5 ] Sair do ... |
s = 1
valor = soma = 0
for c in range(2, 101):
valor = s / c
soma += valor
print(f'{soma+1:.2f}')
|
#!/usr/bin/env python
"""
CREATED AT: 2021/12/06
Des:
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list
https://leetcode.com/explore/learn/card/linked-list/213/conclusion/1225/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Medium
Tag:
See:
"""
# Definition for a Node.
class Node:
... |
a = 18
b = 13
print(a-b)
# Answer should be 5
|
# Question: https://projecteuler.net/problem=115
M = 50
T = 10**6
DP1 = []
DP2 = []
for i in range(M):
DP1.append(1)
DP2.append(0)
while DP1[-1] + DP2[-1] <= T:
DP1_i = DP1[-1] + DP2[-1]
DP2_i = DP1[-M] + DP2[-1]
DP1.append(DP1_i)
DP2.append(DP2_i)
print(len(DP1) - 1)
# ---
# Even better r... |
"""packer_builder/specs/builder/distros/debian.py"""
# pylint: disable=line-too-long
def debian_spec(**kwargs):
"Debian specs."
# Setup vars from kwargs
builder_spec = kwargs['data']['builder_spec']
distro = kwargs['data']['distro']
version = kwargs['data']['version']
bootstrap_cfg = 'prese... |
# -*- coding: utf-8 -*-
"""
@Author: Lyzhang
@Date:
@Description:
"""
VERSION, SET, USE_GPU, CUDA_ID = 10, 200, True, 3
HIDDEN_SIZE, Head_NUM, GCN_LAYER, K, RNN_LAYER, RNN_TYPE = 384, 2, 2, 64, 2, "GRU"
USE_ELMo, USE_POS = True, True
Partial_IN = False
TOKEN_SCORE = False
LR, LR_DECAY = 0.001, False
BATCH_SIZE, N_EPOC... |
expected_output = {
'event_num': {
2: {
'event_name': '_wdtimer',
'value': '180'
},
}
}
|
d = {}; print(len(d))
d = {'k1':'v1', 'k2':'v2'}; print(len(d))
print(iter(d))
for i in iter(d): print(i)
|
print('===== \033[31mDESAFIO 02\033[m =====')
dia = input('Dia = ')
mes = input('Mes = ')
ano = input('Ano = ')
print('Voce nasceu no dia \033[33m{}\033[m de \033[33m{}\033[m de \033[33m{}\033[m. Correto?'.format(dia, mes, ano))
|
#
# PySNMP MIB module ENVIRONMENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENVIRONMENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:05:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# def combine_all(input):
# check1 = False
# check2 = False
# check3 = False
# if len(input) > 0:
# if input[0] == 'a':
# check1 = True
#
# main_s = []
# tmp_dict = {}
# for item in input:
# tmp_dict[item] = "0"
# if item not in ['a', 'b']:
# r... |
"""palavras = ("aprender", "programar", "linguagem", "python", "curso",
"gratis", "estudar", "praticar", "trabalhar", "mercado",
"programador", "futuro")
for p in palavras:
print(f"\n Na palavra {p.upper():-<20} temos:", end="")
for letra in p:
if letra.lower() in "aeiou":
... |
myApp = App("chrome.app")
if not myApp.window(): # chrome not open
App.open("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")
wait(10)
myApp.focus()
wait(1)
wait("1392883544404.png", FOREVER)
click("1392883741646.png")
type("http://10.112.18.28/testcases/symbol/BoxMarkerSymbol.html\n")
w... |
#!/usr/bin/env python
appd_auth = {
'controller': '',
'account': '',
'user': '',
'password': ''
}
APPD_APP = ''
APPD_TIER = ''
|
print("Hello World!")
print ("Hello Again")
print("I like typing this.")
print("This is fun.")
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')
print('this command will print one line')
print('this\n command\n will\n print\n multiple\n lines')
# print('nevermind')
# --O... |
""" Python single line for loop """
# Generate a list of numbers range 0-10
number_list = [x for x in range(10)]
print("Number list: ", number_list)
# Generate a list of numbers range 0-10
even_number_list = [x for x in range(10) if x % 2 == 0]
print("Even number list: ", even_number_list)
# Multiple two lists
# It ... |
if __name__ == '__main__':
print("Estou sendo Executado diretamente no terminal")
print(__name__)
else:
print("Estou sendo importado e executado por outro código")
print(__name__) |
"""
entrada
a-->int-->a
b-->int-->b
c-->int-->c
salida
respuesta-->str-->resultado
"""
a, b, c, d = map(int, input("Digite los 4 datos: ").split())
if d==0 :
resultado = (a-c)**2
elif d>0 :
resultado = ((a-b)**3)/d
print("El resultado es: "+str (resultado))
|
# Not runnable
end_point = "team/frc254"
url = f"https://www.thebluealliance.com/api/v3/{end_point}"
"https://www.thebluealliance.com/api/v3/team/frc254"
|
#Faça um programa que tenha uma função chamada contador(), que receba 3 parâmetros: inicio, fim e passo e realize a contagem.
#seu programa tem que realizar três contagens através da função criada:
# a - De 1 até 10, de 1 em 1
def contador(inicio, fim, passo):
for c in range(inicio, fim+1, passo):
print(f'... |
class DoublyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
self.prev = None
def to_str(head):
data = []
while head:
data.append(str(head.data))
head = head.next
return ', '.join(data)
def reverse_recursive(head):
if h... |
class Piece:
def __init__(self, index: int, piece_hash: bytes,
piece_length: int, block_length: int):
self.index = index
self.hash = piece_hash
self.piece_length = piece_length
self.block_length = block_length
self.blocks = [Block(i, i*block_length, block_le... |
'''
4 7
47 74 44 77
474 744 444 774 477 747 447 777
4와 7로만 이루어진 x자리 수를 만드는 법:
x-1 자리 수의 뒤에 4와 7을 붙인다.
이 원리를 이용해서 K번째 작은 수가 몇 자리인지,
그 자릿수에서 몇 번째 숫자인지 알 수 있음.
'몇 번째 숫자인지'를 이진수로 바꿔서
0을 4로, 1을 7로 치환한 후에
'몇 자리인지'가 되도록 앞에 4를 붙여주면 됨.
'''
# input
K = int(input())
# process
# K번째 작은 수가 몇 자리의 몇 번째 숫자인지 계산
cnt = 0
digit ... |
a = list1[0]
list1[0] = "def"
list1.remove ( 3 )
list1.append ( 4 )
print ( list1 )
del list1[1:2]
print ( list1 )
|
def handleNumbersList(numsList: list, initialValues: tuple) -> list:
'''
Retorna apenas os maiores valores lista selecionada
-> numsList: lista selecionada
-> initialValues: (tam_lista, Elementos que serão tirados)
'''
#Atribuindo às variáveis os valores inseridos
size = initialValues[0]
... |
n = int(input())
v = []
trocas = 0
for i in range (n):
for j in range (5): #para coletar os elementos do vetor
v.append(int(input()))
for j in range (5): #para ordenar o vetor
for k in range (4):
if v[k] > v[k+1]:
t = v[k]
v[k] = v[k+1]
... |
junk_drawer = [3, 4]
# Using the list provided, add a pen, a scrap paper, a 7.3 and a True element
____
# ____
# ____
# ____
# What's the length of the list now?
# Save it in an object named drawer_length
# ____ = ____
# Slice the junk_drawer object to include the element 4 to scrap paper
# Save this in an ob... |
# dictionary = {key: value for element in iterable}
fruits = ['apple', 'kiwi', 'banana', 'orange', 'apricot']
fruit_dict = {element: len(element) for element in
fruits if len(element) > 5}
print('\n'.join("{} {}".format(element, leng) for (element, leng) in fruit_dict.items())) |
#ex050: Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o.
#Não consegui raciocinar pra fazer.
#c vai se repetir 6 vezes (1, 7).
#conforme vc digita um número, a variável 'num' recebe um novo valor.
#Porém, ela vai a... |
'''Memoization decorator for functions taking one or more arguments.
Copyright (c) 2018-2019 Machine Zone, Inc. All rights reserved.
'''
def memoize(f):
"""Memoization decorator for functions taking one or more arguments."""
class Memodict(dict):
'''Helper class derived from dict'''
def __i... |
class QueryOperatorProcessor(object):
def __init__(self, dispatcher):
self.dispatcher = dispatcher
def process(self, child_nodes):
raise NotImplementedError()
def _process_node(self, node):
return self.dispatcher.dispatch(node)
def _process_all_nodes(self, nodes):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: exceptions.py
"""
自定义错误类
"""
__all__ = [
'HTMLCoderError',
'TietukuUploadError',
]
class HTMLCoderError(Exception):
""" 编码器错误 """
class TietukuUploadError(HTMLCoderError):
"""
调用上传图片的 api ,请求状态码非 200
4001 上传凭证无效。 检查生成Toke... |
print("000560_04_02_ExceptionОбработка")
print()
print("000560_04_02_ex.01_ExceptionОбработка")
try:
# num1 = float(input("Введите первое число: "))
# num2 = float(input("Введите второе число: "))
num1 = 1
num2 = 0
print("Done calculation:")
print (num1/num2)
# print("Done calculation")
exc... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 Akumatic
#
# https://adventofcode.com/2021/day/17
def read_file(filename: str = "input.txt") -> list:
with open(f"{__file__.rstrip('code.py')}{filename}", "r") as f:
lines = [s[2:].split("..") for s in f.read().strip().replace("target area: ", "").split("... |
x = 0;
for i in range(1000000):
x = x + 1;
|
N = int(input())
a = list(map(int, input().split()))
t = []
for i in range(N):
t.append([a[i], i])
t.sort(key=lambda x: x[0])
for i in t[::-1]:
print(i[1] + 1)
|
#retomando clase pasada
#Estructura de datos
#################################
#listas
otra_lista = [1, 2, 3, 4 , 5, 6]
#Accediendo a los elementos de una lista
print(otra_lista[0])
print(otra_lista[-1])
#Slicing
print(otra_lista[0:3])
print(otra_lista[3:])
copia_lista = otra_lista
copia_lista.append(7)
print(o... |
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
dp = [1]*len(nums)
for i in range(1,len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max( dp[i], dp[j]+1 )
return max(dp)
class S... |
r1 = int(input('Digite o comprimento da reta 1: '))
r2 = int(input('Digite o comprimento da reta 2: '))
r3 = int(input('Digite o comprimento da reta 3: '))
if ((r1+r2)>=r3) and ((r1+r3)>=r2) and ((r3+r2)>=r1):
if r1 == r2 and r1 == r3:
print("As retas formam um triangulo equilátero")
elif r1!=r3 and r1!... |
"""
https://leetcode.com/problems/find-first-palindromic-string-in-the-array
"""
# define an input for testing purposes
words = ["def", "ghi"]
# actual code to submit
def solution(words: str) -> str:
for word in words:
if word == word[::-1]:
return word
return ""
# use print statement t... |
def can_make_arithmetic_progression(arr):
arr = sorted(arr)
prev_diff = arr[1] - arr[0]
for i in range(1, len(arr)):
difference = arr[i] - arr[i - 1]
if not difference == prev_diff:
return False
prev_diff = difference
return True
print(can_make_arithmetic_progre... |
"""Exceptions for NS."""
class NSError(Exception):
"""Generic NS exception."""
pass
class NSConnectionError(NSError):
"""NS connection exception."""
pass
|
#__________________ Script Python - versão 3.8 _____________________#
# Autor |> Abraão A.da Silva
# Data |> 05 de Março de 2021
# Paradigma |> Procedural
# Objetivo |> Dá boas vindas
#___________________________________________________________________#
def mostrar_mensagem(msg):
"A função mostrará a mensage... |
""" This module holds some frequently used alogs """
# @param a and b two integers
# @return int gcd(a, b)
def gcd(a, b):
""" compute gcd a and b"""
if a == 0:
return b
if b == 0:
return a
return gcd(b, a % b)
# @param three integers a, b, m
# @return integer a^b mod m
def modulo_... |
model_status = [
{ 'code': 0, 'description': 'Model uploaded'},
{ 'code': 1, 'description': 'File csv uploaded'},
{ 'code': 2, 'description': 'Send to elm'},
{ 'code': 3, 'description': 'Training', 'perc': 0},
{ 'code': 4, 'description': 'Done'}
] |
class CmfParseError(Exception):
def __init__(self, parseinfo, msg):
self.message = '({}:{}) Error: {}'.format(
parseinfo.line + 1, parseinfo.pos, msg)
def __str__(self):
return self.message
|
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def Watermelon(i):
w =i
result = "YES" if w%2 == 0 and w > 2 else "NO"
print(result + " " + str(i))... |
matrix = ["1.1 2.2 3.3", "4.4 5.5 6.6", "7.7 8.8 9.9"]
def transpose(matrix):
return [" ".join(row.split()[i] for row in matrix) for i in range(len(matrix))]
print(transpose(matrix))
|
print('Meta definition')
class Meta(type):
def __new__(mcs, name, bases, namespace):
print('Meta __new__:', mcs, name, namespace)
ret = type.__new__(mcs, name, bases, namespace) # class creation
print('Meta __new__ ret:', ret)
return ret
def __init__(cls, name, bases=None, na... |
print("Input: ",end="")
a, b, t = 2020, 2021, int(input())
for i in range(t):
n = int(input("\n"))
def sum(x, a, b, check, n):
if x > n:
return
if check[x]:
return
check[x] = True
sum(x + a, a, b, check, n)
sum(x + b, a, b, check, n)
def... |
class PROJECT(object):
NAME = "leafytracker"
DESC = "A set of tools to aggregate Leafy Games' developer posts for PULSAR: Lost Colony."
URL = "https://github.com/TomRichter/leafytracker"
VERSION = "0.0.0"
|
"""while 语句
@see: https://docs.python.org/3/tutorial/controlflow.html
@see: https://docs.python.org/3/reference/compound_stmts.html#the-while-statement
只要条件保持为真,while循环就会执行。
在Python中,像在C中一样,任何非零整数值都为真;零是错误的。
条件也可以是字符串或列表值,实际上可以是任何序列;任何长度非零的都为真,空序列为假。
示例中使用的测试是一个简单的比较。
标准比较操作符的写法与C中相同:<(小于)、>(大于)、==(等于)、<=(小于或等于)、>=(... |
"""
This is the rank system based on the regression model we built
"""
def survival_score(timeSurvived, duration, winPlace):
"""
survival_score = 80% * survival time score + 20% * win place score
: type timeSurvived: int -- participant time survived
: type duration: int -- match duration time
: type winPlace: ... |
a=input().split(" ")
b=input().split(" ")
A=0
B=0
for i in range(len(a)):
num1=int(a[i])
num2=int(b[i])
if(num1>num2):
A+=1
elif(num1<num2):
B+=1
print(A, B)
|
""" Beta code translation tables. """
class BetaCode:
""" This class converts Beta Code to UTF-8.
It was written based on:
"The TLG® Beta Code Manual", last updated January 14, 2016, tlg@uci.edu
http://stephanus.tlg.uci.edu/encoding/BCM.pdf """
# 1. Alphabets and Basic Punctuation
# Section ... |
# app config
APP_CONFIG=dict(
SECRET_KEY="SECRET",
WTF_CSRF_SECRET_KEY="SECRET",
# Webservice config
WS_URL="http://localhost:5058", # ws del modello in locale
DATASET_REQ = "/dataset",
OPERATIVE_CENTERS_REQ = "/operative-centers",
OC_DATE_REQ = "/oc-date",
OC_DATA_REQ = "/oc-data",
PREDICT_REQ = "/p... |
#encoding:utf-8
subreddit = 'mildlyvagina'
t_channel = '@r_mildlyvagina'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
# Sets the appearance of the vehicles front wheels to 40°. Vehicle physics will not be affected.
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FR_Wheel, 40.0)
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FL_Wheel, 40.0)
|
'''
1-Crie uma função que receba dois parâmetros e realize sua soma, subtração, adição e multiplicação.
2-Informe esses resultados através de um print ao usuário dentro da função.
'''
def operacoes(a,b):
soma = a + b
sub = a - b
mult = a * b
div = a / b
print("Soma: ", soma)
print("Subtraç... |
num1, num2 = list(map(int, input().split()))
if num1 < num2:
print(num1, num2)
else:
print(num2, num1)
|
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
Num1 = 100
Num2 = 100
while Num1 < 994:
Num2 = 100
while Num2 < 1000:
Product = Num1 *... |
#!/usr/bin/env python3.4
# coding: utf-8
class MixinMeta(type):
"""
Abstract mixin metaclass.
"""
|
def main():
print('Hola, mundo')
if __name__ =='__main__':
main()
|
env = None
pg = None
surface = None
width = None
height = None
# __pragma__ ('opov')
def init(environ):
global env, pg, surface, width, height
env = environ
pg = env['pg']
surface = env['surface']
width = env['width']
height = env['height']
tests = [test_transform_rotate,
te... |
__author__ = 'vcaen'
class Item(object):
def __init__(self, title, short_desc, desc, picture):
self.title = title
self.short_desc = short_desc
self.desc = desc
self.picture = picture
class Work(Item):
def __init__(self, title, short_desc, desc, date_begin, date_end, company... |
# https://leetcode.com/problems/counting-words-with-a-given-prefix/
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
res = 0
for each in words:
if len(each) >= len(pref):
if each[:len(pref)] == pref:
res += ... |
class RollingHash:
def __init__(self, text, pattern_size):
self.text = text
self.pattern_size = pattern_size
self.hash = RollingHash.hash_text(text, pattern_size)
self.start = 0
self.end = pattern_size
self.alphabet = 26
def move_window(self):
if self.end... |
# 继承
# python支持多重继承
# 默认继承object类
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print('姓名:{0},年龄:{1}'.format(self.name, self.age))
# 定义子类
class Student(Person):
def __init__(self, name, age, stu_no):
super().__init__(... |
class ImageAdapter:
@staticmethod
def to_network_input(dataset):
return (dataset - 127.5) / 127.5
@staticmethod
def to_image(normalized_images):
images = normalized_images * 127.5 + 127.5
return images.astype(int)
|
BULBASAUR = 0x01
IVYSAUR = 0x02
VENUSAUR = 0x03
CHARMANDER = 0x04
CHARMELEON = 0x05
CHARIZARD = 0x06
SQUIRTLE = 0x07
WARTORTLE = 0x08
BLASTOISE = 0x09
CATERPIE = 0x0a
METAPOD = 0x0b
BUTTERFREE = 0x0c
WEEDLE = 0x0d
KAKUNA = 0x0e
BEEDRILL = 0x0f
PIDGEY = 0x10
PIDGEOTTO = 0x11
PIDGEOT = 0... |
class Solution:
"""
@param num: an integer
@return: the complement number
"""
def findComplement(self, num):
ans = 0
digit = 1
while num > 0:
ans += abs(num % 2 - 1) * digit
num //= 2
digit *= 2
return ans
|
# -*- coding: utf-8 -*-
class Exchange(object):
"""docstring for Exchange"""
def __init__(self):
self.trades = False
def getTrades(self):
return self.trades
# @abstractmethod
def calcTotal(self, controller):
pass
|
# -*- coding: utf-8 -*-
# author: Minch Wu
"""RECUR.PY.
define some functions in recursive process
"""
def hanoi(n: int, L=None):
"""hanoi.
storage the move process
"""
if L is None:
L = []
def move(n, a='A', b='B', c='C'):
"""move.
move the pagoda
"""
i... |
input()
A = {int(param) for param in input().split()}
B = {int(param) for param in input().split()}
print(len(A-B))
for i in sorted(A-B):
print(i, end = ' ')
|
languages = ['Chamorro', 'Tagalog', 'English', 'russian']
print(languages)
languages.append('Spanish')
print(languages)
languages.insert(0, 'Finish')
print(languages)
del languages[0]
print(languages)
popped_language = languages.pop(0)
print(languages)
print(popped_language)
popped_language = languages.pop(0)
prin... |
'''
Created on Oct 5, 2011
@author: IslamM
'''
|
"""
Given a string and a set of characters, return the shortest substring containing all the characters in the set.
For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci".
If there is no substring containing all the characters in the set, return null.
"""
no_of_chars ... |
SOURCES = {
"activity.task.error.generic": "CommCareAndroid",
"app.handled.error.explanation": "CommCareAndroid",
"app.handled.error.title": "CommCareAndroid",
"app.key.request.deny": "CommCareAndroid",
"app.key.request.grant": "CommCareAndroid",
"app.key.request.message": "CommCareAndroid",
... |
data = {
'slug': 'region12',
'name': 'Region XII',
'description': 'SOCCSKSARGEN',
'provinces': {
'cotabato': {
'slug': 'cotabato',
'name': 'Cotabato',
'municipalities': {
'alamada': {
'slug': 'alamada,',
... |
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
targetSum -= root.val
if targetSum == 0:
if (root.left is None) and (root.right is None):
return True
return self.has... |
# -*- coding: utf-8 -*-
# @Author: jpch89
# @Email: jpch89@outlook.com
# @Date: 2018-06-27 23:59:30
# @Last Modified by: jpch89
# @Last Modified time: 2018-06-28 00:02:38
formatter = '{} {} {} {}'
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(Tru... |
'''2. Write a Python program to compute the similarity between two lists.
Sample data: ["red", "orange", "green", "blue", "white"], ["black", "yellow", "green", "blue"]
Expected Output:
Color1-Color2: ['white', 'orange', 'red']
Color2-Color1: ['black', 'yellow'] '''
def find_similiarity(list1, list2):
list3 = lis... |
def get_client_ip(request):
client_ip = request.META.get('REMOTE_ADDR', '')
return client_ip
|
url = "https://customerportal.supermicro.com/Customer/ContentPages/CustOrders.aspx"
orderType = "//select[@id='ContentPlaceHolder1_ddlSearchType']"
fromDate = "//input[@id='ContentPlaceHolder1_txtFrom']"
customerId = "//select[@id='ContentPlaceHolder1_ddlCustomerID']"
searchIcon = "//a[@id='linkSearch']"
orderTable = "... |
# -*- coding: utf-8 -*-
BK_SDK_JSON = ".sdk.json"
BK_SDK_JSON_FIELDS = ['buildType', 'projectId', 'agentId', 'secretKey', 'gateway', 'buildId', 'vmSeqId']
# openapi相关
AUTH_HEADER_DEVOPS_BUILD_TYPE = "X-DEVOPS-BUILD-TYPE"
AUTH_HEADER_DEVOPS_PROJECT_ID = "X-DEVOPS-PROJECT-ID"
AUTH_HEADER_DEVOPS_BUILD_ID = "X-DEVOPS-BUI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.