content stringlengths 7 1.05M |
|---|
class A:
def f(self):
return B()
a = A()
a.f() # NameError: name 'B' is not defined
b = B() # NameError: name 'B' is not defined
def f():
b = B()
f() # NameError: name 'B' is not defined
class B:
pass
|
'''Refaça o desafio 051, lendo o primeiro termo e a razão de uma PA, mostrando os 10 primeiros termos da progressão usando a estrutura while'''
# Paleta de cores:
cores = {'azul': '\033[1;34m',
'vermelho': '\033[1;31m',
'limpa': '\033[m'}
# Mensagem ínicial
print('{:^30}{}{}'.format(cores['azul'], '... |
def reverse_list(items):
start = 0
end = len(items) - 1
while start < end:
items[start], items[end] = items[end], items[start]
start += 1
end -= 1
return items
if __name__ == '__main__':
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(reverse_list(items))
|
#Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre
#1 a 10. O usuário deve informar de qual numero ele deseja ver a tabuada. A saída deve ser
#conforme o exemplo abaixo:
#o Tabuada de 5:
#o 5 X 1 = 5
#o 5 X 2 = 10
#o ...
#o 5 X 10 = 50
numero = int(input("Informe o numero para... |
# 迭代模式 - 迭代器框架
class BaseIterator:
"""迭代器"""
def __init__(self, data):
self.__data = data
self.toBegin()
def toBegin(self):
"""将指针移至起始位置"""
self.__curIdx = -1
def toEnd(self):
"""将指针移至结尾位置"""
self.__curIdx = len(self.__data)
def next(self):
... |
#!/usr/bin/python3
#
#
MAGIC_SEED = 1956
#PATH
TRAIN_PATH = 'train'
PREDICT_PATH = 'predict'
# Dataset properties
CSV_PATH="C:\\Users\\dmitr_000\\.keras\\datasets\\Imbalance_data.csv"
# Header names
DT_DSET ="Date Time"
RCPOWER_DSET= "Imbalance"
DISCRET =10
# The time cutoffs for the formation of the validation ... |
#pegando numero usuario
num1 = int(input('Digite um valor: '))
num2 = int(input('Digite outro valor: '))
num3 = int(input('Digite ultimo valor: '))
#Checando num1 maior
if num1 >= num2 and num1 >= num3:
print('O maior número é {}'.format(num1))
if num2 > num3:
print('O menor número é {}'.format(num3))
... |
def unsupervised_distr(distr):
variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != 'z'}
distr_unsupervised = distr.replace_var(**variables)
return distr_unsupervised, variables
def unsupervised_distr_no_var(distr):
variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != '... |
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
table = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
return len({''.join(table[ord(c) - ord('a')] for c ... |
#!/bin/python3
"""
Recommender algorithm
Weight sum of similarity vector
"""
WEIGHTS = [1, 1, 1, 1]
# rank, bgg_url, game_id, names, min_players, max_players, avg_time, min_time,
# max_time, year, avg_rating, geek_rating, num_votes, image_url, age, mechanic,
# owned, category, designer, weight
def recommend_simil... |
expected_output = {
"list_of_neighbors": ["192.168.197.254"],
"vrf": {
"default": {
"neighbor": {
"192.168.197.254": {
"address_family": {
"ipv4 unicast": {
"advertise_bit": 0,
... |
nome = str(input('Dogite o nome de sua cidade: ')).lower().strip()
city = nome.split()
print('Sua cidade começa com santos?')
print("santo" in city[0])
|
N, Q = map(int, input().split())
A = list(map(int, input().split()))
X = list(map(int, input().split()))
def two_pointers(x):
left = 0
sm = 0
ans = 0
for right in range(N):
sm += A[right]
while(sm > x):
sm -= A[left]
left += 1
ans += (right-left+1) # left... |
class RepositoryTests(TestCase):
"""Unit tests for Repository operations."""
fixtures = ["test_scmtools"]
def setUp(self):
super(RepositoryTests, self).setUp()
self.local_repo_path = os.path.join(os.path.dirname(__file__), "..", "testdata", "git_repo")
self.repository = Repository.objects.create(name="Git test... |
def check_paranthesis(inp):
stack = []
c = 1
for i in inp:
if i in ['(','[','{']:
stack.append(i)
c += 1
else:
if len(stack) == 0:
return c
elif (i == ')' and stack[-1] == '(') or (i == ']' and stack[-1] == '[') or (i == '}' and... |
# Bazel macro that instantiates a native cc_test rule for an S2 test.
def s2test(name, deps = [], size = "small"):
native.cc_test(
name = name,
srcs = ["%s.cc" % (name)],
copts = [
"-Iexternal/gtest/include",
"-DS2_TEST_DEGENERACIES",
"-DS2_USE_GFLAGS",
... |
#
# PySNMP MIB module CT-DAWANDEVCONN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CT-DAWANDEVCONN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:28:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
original=1
binario=0
while original!=0:
number=int(input("Insira um número de no máximo 5 algarismos: "))
original=number
while number>0:
mod=number%2
number=number//2
if original==((number*2)+mod):
binario=str(mod)
else:
binario=str(mod)+binario
p... |
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
def get_item(self):
return self.item
def get_next(self):
return self.next
def set_item(self, new_item):
self.item = new_item
def set_next(self, new_next):
self.next = n... |
class Solution(object):
# # Backtracking Approach - TLE
# def canJump(self, nums):
# """
# :type nums: List[int]
# :rtype: bool
# """
# return self.canJumpHelper(nums, 0)
#
# def canJumpHelper(self, nums, currentIdx):
# if currentIdx == len(nums) - 1:
... |
# The major optimization is to do arithmetic in base 10 in the main loop, avoiding division and modulo
def compute():
# Initialize
n = 1000000000 # The pattern is greater than 10^18, so start searching at 10^9
ndigits = [0] * 10 # In base 10, little-endian
temp = n
for i in range(len(ndigits)):
ndigits[i] = ... |
class Users:
def __init__(self, first_name='', last_name='',age='', email='', phone=''):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.email = email
self.phone = phone
def describe_user(self):
print('Tu nombre es: ', s... |
def parse_string_time(input_time: str) -> float:
total_amount = 0
times = _slice_input_times(input_time)
for _amount, duration_type in times:
amount = _to_float(_amount)
multiplier = _parse_multiplier(duration_type)
total_amount += amount * multiplier
return total_amount
def... |
"""
给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
示例 1:
输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/edit-distance
著作权归领扣网络所有。商业转载请联系官方授权,非... |
"""This module contains j2cl_js_provider helpers."""
load(
"@io_bazel_rules_closure//closure:defs.bzl",
"CLOSURE_JS_TOOLCHAIN_ATTRS",
"closure_js_binary",
"create_closure_js_library",
"web_library",
)
def create_js_lib_struct(j2cl_info, extra_providers = []):
return struct(
providers =... |
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
MAX, MASK = 0x7FFFFFFF, 0xFFFFFFFF
while b != 0:
a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
return a if a <= MAX else ~(a ^ MASK)
|
HITBOX_OCTANE = 0
HITBOX_DOMINUS = 1
HITBOX_PLANK = 2
HITBOX_BREAKOUT = 3
HITBOX_HYBRID = 4
HITBOX_BATMOBILE = 5
|
N, M = map(int, input().split())
A = list(map(int, input().split()))
threshold = sum(A) / (4 * M)
if len([a for a in A if a >= threshold]) >= M:
print('Yes')
else:
print('No')
|
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# exception
if len(strs) == 0:
return ""
# sort first!
strs.sort()
# strategy
# compare first and last string in sorted strings!
# pick first element ... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def _add(self, node, data):
if data <= node.data:
if node.left:
self._add(node.left, data)
... |
class SymbolMapper(object):
def __init__(self):
self.symbolmap = {0: '0', 1: '+', -1: '-'}
@staticmethod
def normalize(value):
return 0 if value == 0 else value / abs(value)
def inputs2symbols(self, inputs):
return map(
lambda value: self.symbolmap[SymbolMapper.nor... |
# -*- coding: utf-8 -*-
# author: ysoftman
# python version : 2.x 3.x
# desc : tuple test
def tuple_test():
# 튜플이 리스트와 다른점 1
# 표현시 () 를 사용한다. 리스트는 [] 사용
tp = (1, 'ysoftman', 7, 'abc')
print('tuple = ', tp)
# 튜플이 리스트와 다른점 2
# 튜플은 데이터 수정을 할 수 없다.
# 에러 발생
# del tp[1]
# 반면 리스트는 수정할 수... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# (c)2021 .direwolf <kururinmiracle@outlook.com>
# Licensed under the MIT License.
class AffNoteTypeError(Exception):
pass
class AffNoteIndexError(Exception):
pass
class AffNoteValueError(Exception):
pass
class AffSceneTypeError(Exception):
pass
cl... |
n = s = cont = 0
while True:
n = int (input('Digite um número[999 para finalizar]: '))
if n == 999:
break
s+=n
cont+=1
print(f'Você digitou {cont} números, a soma deles é {s}')
|
class RC4 :
def __init__(self):
self.S = []
def preprocess_hex_chars(self, text) :
"""
Preprocess text by decoding hex characters into ASCII characters
"""
preprocessed_text = ''
i = 0
while i < len(text) :
if '\\x' == text[i:i+2] :
... |
# Ignore file list
ignore_filelist = [
'teslagun.activeitem',
'teslagun2.activeitem',
]
ignore_filelist_patch = [
]
|
""" Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Le Petit Prince vient de débarquer sur la planète U357, et il apprend qu'il peut y voir de belles aurores boréales !
La planète U357 a deux soleils : les étoiles E1515 et E666. C'est pour cela que les tempêtes magnétique... |
#Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".
#make_abba('Hi', 'Bye') → 'HiByeByeHi'
#make_abba('Yo', 'Alice') → 'YoAliceAliceYo'
#make_abba('What', 'Up') → 'WhatUpUpWhat'
def make_abba(a,b):
return a+b+b+a |
# This is input for <FileUploadToCommons.py> that actually writes the content to Wikimedia commons using the API
#See https://pypi.org/project/mwtemplates/
# ===============BEGIN TEMPLETE======================
# Lets use a minimally filled {{Infomormation}} template - https://commons.wikimedia.org/wiki/Template:In... |
# funcao como parametro de funcao
# so imprime se o numero estiver correto
def imprime_com_condicao(num, fcond):
if fcond(num):
print(num)
def par(x):
return x % 2 == 0
def impar(x):
return not par(x)
# Programa Principal
# neste caso nao imprimira
imprime_com_condicao(5, par)
|
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
swaps = 0
for i in range(n):
temp=0
for j in range(n-1):
if a[j] > a[j+1]:
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
swaps+=1
if swaps==0:
print("Array is sorted in", swaps, "swaps."... |
t = int(input())
for i in range(t):
r = int(input())
length = r*5
width = length*0.6
left = -1*length*0.45
right = length*0.55
w = width/2
# print coordinates
print('Case '+str(i+1)+':')
# upper left
print("%.0f %.0f" % (left, w))
# upper right
print("%.0f %.0f" % (right,... |
myString = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
inTab = "yzabcdefghijklmnopqrstuvwx"
outTab = "abcdefghijklmnopqrstuvwxyz"
transTab = str.maketrans(i... |
class unitConversion():
def __init__(self, scale, offset) -> None:
self.scale = scale
self.offset = offset
def convertToSI(self, upper=True, isComposite=False):
if upper:
if isComposite:
return [self.scale, 0]
else:
return [self... |
def sortByHeight(a):
heights = []
# Store all the heights in a list
for i in range(len(a)):
if a[i] != -1:
heights.append(a[i])
# Sort the heights
heights = sorted(heights)
# Replace the heights in the original list
j = 0
for i in range(len(a)):
if a[i] != ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 09:54:51 2020
@author: bruger
"""
|
class Solution:
def reverseWords(self, set):
return ' '.join(set.split()[::-1])
if __name__ == "__main__":
solution = Solution()
print(solution.reverseWords("the sky is blue"))
print(solution.reverseWords(" hello world! "))
|
class SleuthError(Exception):
pass
class SleuthNotFoundError(SleuthError):
pass
|
def insertion_sort(nums: list[float]) -> list[float]:
for start in range(1, len(nums)):
index = start
while nums[index] < nums[index - 1] and index > 0:
nums[index], nums[index - 1] = nums[index - 1], nums[index]
index -= 1
return nums
|
# coding:utf-8
class FakeBot(object):
"""Fake Bot object """
def __init__(self):
self.msg = ''
def send_message(self, text='', **kwargs):
self.msg = text
class FakeUpdate(object):
def __init__(self):
self.message = FakeMessage()
class FakeMessage(object):
"""Docstri... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""Module for user fixtures"""
USER = {
'email': 'test_user@example.com',
'password': 'Password@1234',
}
USER_INVALID = {'email': '', 'password': ''}
SUPERUSER = {
'email': 'test_userII@example.com',
'password': 'password1234',
}
UNREGISTERED_USER = {
'email': 'unregistered@example1.com',
'p... |
class Term(str):
@property
def is_variable(self):
return self[0] == "?"
@property
def is_constant(self):
return self[0] != "?"
@property
def arity(self):
return 0
class ListTerm(tuple):
def __init__(self, *args):
self.is_function = None
tuple.__ini... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( a , b , k ) :
c1 = ( b - a ) - 1
c2 = ( k - b ) + ( a - 1 )
if ( c1 == c2 ) :
return 0
retu... |
"""Exceptions of the pygmx package."""
class InvalidMagicException(Exception): pass
class InvalidIndexException(Exception): pass
class UnknownLenError(Exception): pass
class FileTypeError(Exception): pass
class XTCError(Exception): pass
|
def get_locale_name(something, lang):
if type(something) == str:
pass
if type(something) == list:
pass
if type(something) == dict:
pass
|
phoneNumber = {}
x = int(input())
for i in range(x):
name, number = input().split()
phoneNumber[name] = number
for i in range(x):
query_name = input()
if query_name in phoneNumber.keys():
print(query_name + "=" + phoneNumber[query_name])
else:
print("Not found")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Control.py
#
class Control:
def __init__(self, TagName):
self._hosted = False # Is added to Form
self._script = '' # Javascript code (Used before added to Form)
self._id = '' # Used By Form to identify control Dont change
self._... |
AVAILABLE = [
{
'account_name': 'ExampleTwitterMarkovBot', # derived from https://twitter.com/ExampleTwitterMarkovBot
'corpora': ('example_corpus1', 'example_corpus2'),
'description': 'An example configuration for a bot instance',
'twitter_key': '', # twitter app API key
'twi... |
if __name__ == "__main__":
with open("input.txt", "r") as f:
input_list = f.readlines()
x = 0
y = 0
for input in input_list:
command, string_val = input.split(" ")
val = int(string_val)
if command == "forward":
x += val
... |
class TransactionError(Exception):
pass
class TransactionTimeoutError(Exception):
pass
class TransactionFinished(Exception):
pass
|
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
divisor_sum = 0
for divisor in range(2, n):
if n % divisor == 0:
divisor_sum += divisor
return divisor_sum +... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
def gcd(a: int, b: int) -> int:
# supposed a >= b
if b > a:
return gcd(b, a)
elif a % b == 0:
return b
return gcd(b, a % b)
|
def data_loader(f_name, l_name):
with open(f_name, mode='r', encoding='utf-8') as f:
data = list(set(f.readlines()))
label = [l_name for i in range(len(data))]
return data, label
|
# 2. Words Lengths
# Using a list comprehension, write a program that receives some text, separated by comma and space ", ",
# and prints on the console each string with its length in the following format:
# "{first_str} -> {first_str_len}, {second_str} -> {second_str_len},…"
print(', '.join([f"{word} -> {len(word)}" ... |
# TODO: maybe store them .sql files and read them as string
# example: https://cloud.google.com/blog/products/application-development/how-to-schedule-a-recurring-python-script-on-gcp
# def file_to_string(sql_path):
# """Converts a SQL file holding a SQL query to a string.
# Args:
# sql_path: String cont... |
def in_order_traversal(node, visit_func):
if node is not None:
in_order_traversal(node.left, visit_func)
visit_func(node.data)
in_order_traversal(node.right, visit_func)
def pre_order_traversal(node, visit_func):
if node is not None:
visit_func(node.data)
pre_order_trave... |
'''
Desenvolva um algoritmo que solicite seu ano de nacimento e o ano anoAtual
Calcule a idade e apresente na tela.
Para fins de simplificacao, despreze o dia e mes do ano. Apos o calculo
verifique se a idade e maior ou igual a 18 anos e apresente na tela a mensagen
informando que ja e possivel tirar a carteira de mot... |
#!/usr/bin/env python3
# Write a program that computes the GC fraction of a DNA sequence in a window
# Window size is 11 nt
# Output with 4 significant figures using whichever method you prefer
# Use no nested loops
# Describe the pros/cons of this algorith vs. nested loops
seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATAC... |
class Feature:
def __init__(self, name, selector, data_type, number_of_values, patterns):
self.name = name
self.selector = selector
self.pattern = patterns[data_type]
self.multiple_values = number_of_values != 'single' |
s = c = 0
while True:
n = int(input('Digite um número: '))
if n == 999:
break
s += n
c += 1
print(f'Você digitou \033[32m{c}\033[m e soma entre eles é iqual a \033[33m{s}.')
|
## rolling mean & variance
class OnlineStats:
def __init__(self):
self.reset()
def reset(self) -> None:
self.n = 0
self.mean = 0.0
self.m2 = 0.0
def update(self, x: float) -> None:
"""Update stats for new observation."""
self.n += 1
new_mean = self... |
def get_multiples(num=1,c=10):
# if n > 0: (what about negative multiples?)
a = 0
num2 = num
while a < c:
if num2%num == 0:
yield num2
num2 += 1
a += 1
else:
num2 += 1
multiples_two = get_multiples(2,3)
for i in multiples_two:
print(i)
default_multiples = get_multiples()
multiples_5 = g... |
# Copyright 2010-2011, RTLCores. All rights reserved.
# http://rtlcores.com
# See LICENSE.txt
class CmdArgs(list):
def __init__(self, value=[], cmd=None):
list.__init__(self, value)
self.cmd = cmd
def conv(self):
if(self.cmd == None):
return self
else:
r... |
def main() -> None:
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
INF = 1 << 60
min_length = [INF] * (1 << n)
remain = 1 << n
mi... |
"""A rich command line interface for PyPI."""
__name__ = "pypi-command-line"
__title__ = __name__
__license__ = "MIT"
__version__ = "0.4.0"
__author__ = "Arian Mollik Wasi"
__github__ = "https://github.com/wasi-master/pypi-cli"
|
"""
Name: MultiSURF.py
Authors: Gediminas Bertasius and Ryan Urbanowicz - Written at Dartmouth College, Hanover, NH, USA
Contact: ryan.j.urbanowicz@darmouth.edu
Created: December 4, 2013
Modified: August 25,2014
Description:
----------------------------------------------------------... |
# import libraries and modules
# provide a class storing the configuration of the back-end engine
class LXMconfig:
# constructor of the class
def __init__(self):
self.idb_c1 = None
self.idb_c2 = None
self.idb_c3 = None
self.lxm_conf = {}
self.program_name = "lx_allocator... |
{
"targets": [
{
"target_name": "priorityqueue_native",
"sources": [ "src/priorityqueue_native.cpp", "src/ObjectHolder.cpp", "src/index.d.ts"],
"cflags": ["-Wall", "-std=c++11"],
'xcode_settings': {
'OTHER_CFLAGS': [
'-std=c++11'
],
},
"conditions": [
... |
class User:
"""
User class for creating password locker account and logging in
"""
user_credentials = []
def __init__(self, fullname, username, password):
self.fullname = fullname
self.username = username
self.password = password
def save_user(self):
"""
... |
"""Breadth-first search shortest path implementations."""
def bfs_shortest_path(graph, x, y):
"""Find shortest number of edges between nodes x and y.
:x: a node
:y: a node
:Returns: shortest number of edges from node x to y or -1 if none exists
"""
if x == y:
return 0
v... |
'''
'''
print('\nNested Function\n')
def function_1(text):
text = text
def function_2():
print(text)
function_2()
if __name__ == '__main__':
function_1('Welcome')
print('\n closure Function \n')
def function_1(text):
text = text
def function_2():
print(text)
return function_2
if __name__ == '__main__... |
# def mul(a=1,b=3):
# c=a*b
# return c
# def add(a=1,b=2):
# c=a+b
# return c
class Student:
def __init__(self,first,last,kid):
self.fname = first
self.lname = last
self.kid = kid
self.email = first + '.' + last +'@tamuk.edu'
def firstname(self):
retur... |
def get_initial(name):
initial = name[0:1].upper()
return initial
first_name = input('Enter your first name: ')
first_name_initial = get_initial (first_name)
middle_name = input('Enter your middle name: ')
middle_name_initial = get_initial (middle_name)
last_name = input('Enter your last name: ')
last_name_... |
class Password:
'''
class of the password file
'''
def __init__(self, page, password):
self.page = page
self.password = password
'''
function for class properties
'''
'''
user properties
'''
user_password = []
def save_page(self):
Password.user_passwords.append(self)
'''
save pas... |
# Reescreva a função leiaInt() que fizemos no desafio 104, incluindo agora
# a possibilidade da digitação de um número de tipo inválido. Aproveite e crie
# também uma função leiaFloat() com a mesma funcionalidade.
# Funções
def leiaInt(msg):
while True:
try:
num = int(input(msg))
except... |
# This is the main settings file for package setup and PyPi deployment.
# Sphinx configuration is in the docsrc folder
# Main package name
PACKAGE_NAME = 'dstream_excel'
# Package version in the format (major, minor, release)
PACKAGE_VERSION_TUPLE = (0, 4, 6)
# Short description of the package
PACKAGE_SHORT_DESCRIPT... |
# -*- coding: utf-8 -*-
# @Time: 2020/1/5 6:22 下午
# @Author: GraceKoo
# @File: 35_search-insert-position.py
# @Desc:https://leetcode-cn.com/problems/search-insert-position/
class Solution:
def searchInsert(self, nums, target: int) -> int:
for i in range(0, len(nums) - 1):
if nums[i] == target:... |
while True:
try:
e = str(input()).strip()
c = e.replace('.', '').replace('-', '')
s = 0
for i in range(9):
s += int(c[i]) * (i + 1)
b1 = s % 11
b1 = 0 if b1 == 10 else b1
s = 0
if b1 == int(e[-2]):
for i in range(9):
... |
# Intersection of 2 arrays
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
counter = None
result = []
if len(nums1) < len(nums2):
counter = collections.Counter(nums1)
for n in nums2:
... |
class propertyDecorator(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
pd = propertyDecorator(100)
print(pd.x)
pd.x = 10
print(pd.x)
|
def test():
assert (
"span1.similarity(span2)" in __solution__ or "span2.similarity(span1)" in __solution__
), "你有计算两个span之间的相似度吗?"
assert span1.text == "不错的餐厅", "你有正确生成span1吗?"
assert span2.text == "很好的酒吧", "你有正确生成span2吗?"
assert (
0 <= float(similarity) <= 1
), "相似度分数是一个浮点数。你确定... |
countries = ["USA", "Spain", "France", "Canada"]
for country in countries:
print(country)
data = "Hello from python"
for out in data:
print(out)
for numero in range(8):
print(numero) |
# X = {
# "0xFF": {
# "id": 255,
# "name": "meta",
# "0x00": {
# "type_id": 0,
# "type_name": "sequence_number",
# "length": 2,
# "params": [
# "nmsb",
# "nlsb"
# ],
# "dtype": "int",
# ... |
def make_car(car_manufacturer,car_model,**Other_attributes):
Other_attributes['car_model']=car_model
Other_attributes['car_manufacturer']=car_manufacturer
return Other_attributes
print(make_car('Toyota','Rav 4',color='blue')) |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 22 16:21:21 2019
@author: x
"""
|
def find_largest_palindrome(range_start: int, range_end: int) -> int:
largest: int = 0
product: int
i: int
for i in range(range_start, range_end):
j: int
for j in range(range_start, range_end):
product = i * j
if is_palindrome(str(product)) and product > largest... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 Akumatic
#
# https://adventofcode.com/2020/day/18
def read_file() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [line.strip() for line in f.readlines()]
def evaluate(values: list, operators: list, precedence: bool) -> int... |
class AuthenticationError(Exception):
pass
class MarketClosedError(Exception):
pass
class MarketEmptyError(Exception):
pass
class InternalStateBotError(Exception):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.