content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
def simple_generator():
yield 1
yield 2
yield 3
simple_generator()
print(simple_generator)
print(simple_generator()) |
#
# PySNMP MIB module HH3C-VOICE-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VOICE-IF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# Python3 Finding Lowest Common Ancestor in Binary Tree ----> O(N)
def find_lca_bt(root, n1, n2):
if not root:
return None
left_lca = find_lca_bt(root.left, n1, n2)
right_lca = find_lca_bt(root.right, n1, n2)
if left_lca and right_lca:
return root
return left_lca if left_lca else right_lca
# Python3 Findi... |
class DF_Filter(dict):
'''
store and format query where clause
'''
def __init__(self,filter_value={}):
self['filter_list'] = []
def add(self,val):
self['filter_list'].append(val)
return self
def getFilter(self):
if len(self['filter_list'])==0:
ms... |
# F - номинал облигации
# C - купонная выплата
# P0 - приведенная внутренняя цена облигации
# n - число купонных доходов
n = 4
i0 = 0.1
c = 0.08
F = 100
r = 0.0001 * -5
C = c * F
p_koeffs = []
for t in range(1,n+1):
koeff = C/((1+i0)**t)
print(f"Коэфф при t={t}: {koeff}")
p_koeffs.append(koeff)
P0 = sum... |
def my_count(lst, e):
res = 0
if type(lst) == list:
res = lst.count(e)
return res
print(my_count([1, 2, 3, 4, 3, 2, 1], 3))
print(my_count([1, 2, 3], 4))
print(my_count((2, 3, 5), 3)) |
def mdc(x1, x2):
while x1%x2 != 0:
nx1 = x1
nx2 = x2
# Trocando os valores de variavel
x1 = nx2
x2 = nx1 % nx2 # x2 recebe o resto da divisao entre nx1 e nx2
return x2
class Fracao:
def __init__(self, numerador, denominador):
self.num = numerador
sel... |
cores = {"azul": '\033[36m',
"vermelho": '\033[31m',
"normal": '\033[m'}
sal1 = float(input('Qual é o salário do funcionário? R$'))
sal2 = sal1 * (10 / 100)
if sal1 <= 1250:
sal2 = sal1 + (sal1 * 15 / 100)
else:
sal2 = sal1 + (sal1 * 10 / 100)
print(f'Quem ganhava {cores["vermelho"]}R${sal1:.2... |
# ============================================================================#
# author : louis TOMCZYK
# goal : Definition of personalized Mathematics Basics functions
# ============================================================================#
# version : 0.0.1 - 2021 09 27 - derivati... |
def Bonjour(name):
print(f"Bonjour, {name} comment allez vous ?")
Bonjour("wassila")
|
"""
A simple package that does nothing.
"""
__version__ = '0.0.3'
|
# test async with, escaped by a break
class AContext:
async def __aenter__(self):
print('enter')
return 1
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc)
async def f1():
while 1:
async with AContext():
print('body')
break
... |
file_name = 'words_ex1~' # <= Error file name
try:
content = open(file_name, 'r', encoding='utf-8')
for line in content:
print(line)
except IOError as io_err:
print(io_err) # Output the exception message
# [Errno 2] No such file or directory: 'words_ex1~'
# You can use 'with' statement
with op... |
def product_sans_n(nums):
if nums.count(0)>=2:
return [0]*len(nums)
elif nums.count(0)==1:
temp=[0]*len(nums)
temp[nums.index(0)]=product(nums)
return temp
res=product(nums)
return [res//i for i in nums]
def product(arr):
total=1
for i in arr:
if i==0:
... |
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: Dictionary Programming Exercises 7.1
# Q1(e) solution
car = dict( {
'reg': "131 CN 6439",
'make': "Audi",
'model' : "A6",
'year' : 2013,
'kms' : 52... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 08 13:55:56 2017
@author: Keerthi
"""
# def subseq_gen(newsubseq):
# subseq.append(dum)
def subseq_rule(seq): # Import the subsequence
subseq = []
# Rule 1 - subsequence is derived by removing the first element from the sequence
if len(seq[0]) ... |
n = int(input())
continents = {}
for i in range(n):
str = input().split(' ')
if str[0] in continents:
if str[1] in continents[str[0]]:
continents[str[0]][str[1]].append(str[2])
else:
continents[str[0]][str[1]] = [str[2]]
else:
continents[str[0]] = {
... |
#! /usr/bin/python3
vorname = "Joe"
nachname = "Biden"
print("{0} {1} is elected!".format(vorname, nachname))
print("Hallo World!")
|
'''
Составить описание класса прямоугольников со сторонами, параллельными осям координат.
Предусмотреть возможность перемещения прямоугольников на плоскости,
изменения размеров,
построения наименьшего прямоугольника, содержащего два заданных прямоугольника,
и прямоугольника, являющегося общей частью (пересечением) двух... |
size(800, 800)
background(255)
noStroke()
# Startwert für den Kreisradius
# Dieser muss ein Vielfaches von 255 sein, damit alle 255 Farbtöne in den
# Farbverlauf einfließen können.
radius = 510
# Gehe alle Grautöne von Weiß nach Schwarz durch
for c in range(255, 0, -1):
# Ändere Farbe
fill(c)
# Zeichne e... |
class Node:
def __init__(self, valor):
self.valor = valor
self.hijo_izquierdo = None
self.hijo_derecho = None
self.altura = 0
class AVLTree:
def __init__(self):
self.raiz = None
def add(self, valor):
self.raiz = self._add(valor, self.raiz)
... |
p = 196732205348849427366498732223276547339
secret = REDACTED
def calc_root(num, mod, n):
f = GF(mod)
temp = f(num)
return temp.nth_root(n)
def gen_v_list(primelist, p, secret):
a = []
for prime in primelist:
a.append(calc_root(prime, p, secret))
return a
def decodeInt(i, primelist):
... |
# 编写一个 Java 程序在屏幕上输出 1!+2!+3!+……+10!的和。(循环)
cou = 0
for i in range(10):
cou += i
print("1!+2!+3!+……+10!=", cou) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
"""
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是... |
#숫자카드게임-1
#n,m을 공백으로 구분하여 입력받기
n, m = map(int, input().split())
result = 0
for i in range(n):
data = list(map(int, input().split()))
min_value = min(data)
result = max(result, min_value)
print(result) |
def for_e():
""" Pattern of Small Alphabet: 'e' using for loop"""
for i in range(5):
for j in range(5):
if i%4==0 and j not in(0,4) or j==0 and i in(1,2,3) or i==2 and j>1 or i==1 and j==4:
print('*',end=' ')
... |
#2
total=0
for number in range(1, 10 + 1):
print(number)
total = total + number
print(total)
#3
def add_numbers (x,y):
for number in range (x,y):
print (number)
tot= total+number
print(total)
add_numbers(10,45)
#4
def jamie_1(x,y):
total=0
for jamie in range(x,y+1):
print(... |
product_map = { 1: 'Original 1000',
3: 'Color 650',
10: 'White 800 (Low Voltage)',
11: 'White 800 (High Voltage)',
18: 'White 900 BR30 (Low Voltage)',
20: 'Color 1000 BR30',
22: 'Color 1000',
27: 'LIFX A19',
28: 'LIFX BR30',
29: 'LIFX+ A19',
30: 'LIFX+ BR30',
31: 'LIFX Z',
... |
x,y,z=0,1,0
print(x,',',y,end="")
for i in range(1,49):
z=x+y
print(',',z,end="")
x=y
y=z
|
salario = float(input('Qual é o seu atual salário?: R$'))
if salario > 1250:
aumento = 10
novosalario = salario * (1 + 10 / 100)
else:
aumento = 15
novosalario = salario * (1 + 15 / 100)
print('O valor do novo salário com um aumento de {}% é R${:.2f}'.format(aumento, novosalario))
|
# coding:utf-8
'''
COTOHA APIの認識結果を整形するためのスクリプト
'''
def clean_response(text): # 全角を半角に変換
OFFSET = ord('0')-ord('0') # 全角コードと半角コードの差分を取得
dic = {chr(ord('0')+i): chr(ord('0')+i-OFFSET) for i in range(10)} # 数字
dic.update({chr(ord('A')+i): chr(ord('A')+i-OFFSET) for i in range(26)}) # 英字大文字
dic.update(... |
class RocketNotEnoughInfo(Exception):
"""
Exception raised when not enough information is provided to fetch/find a Rocket.
"""
def __init__(self, message, errors=None):
# Call the base class constructor with the parameters it needs
super().__init__(message)
class RocketInfoFormat(Exc... |
def first_last(full_name):
first_name = ''
last_name = ''
has_been_a_space = False
for letter in full_name:
if letter == ' ':
has_been_a_space = True
elif has_been_a_space:
last_name = last_name + letter
else:
first_name = first_name + letter
... |
"""
for case if find caesar message bruteforce
"""
message = "GIEWIVrGMTLIVrHIQS"
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(letters)):
translated = ''
for symbol in message:
if symbol in letters:
num = letters.find(symbol)
num = num - key
if num <... |
class Pessoa:
olhos = 2 #atributs de classe
def __init__(self, *filhos, nome=None, idade=35): #dá um alt+enter
self.idade = idade #atributos de instância
self.nome = nome
self.filhos = list(filhos)
def Cumprimentar(self):
return 'Olá'
@staticmethod
def metodo_estatic... |
RUN_STRINGS = (
"Where do you think you're going?",
"Huh? what? did they get away?",
"ZZzzZZzz... Huh? what? oh, just them again, nevermind.",
"Get back here!",
"Not so fast...",
"Look out for the wall!",
"Don't leave me alone with them!!",
"You run, you die.",
"Jokes on you, I'm eve... |
""" Expose PV data """
#
# import logging
# from datetime import datetime, timedelta
# from typing import List
#
# from fastapi import APIRouter, Depends
# from nowcasting_datamodel.models import PVYield
# from nowcasting_datamodel.read.read_pv import get_latest_pv_yield, get_pv_systems
# from sqlalchemy.orm.session im... |
class Solution:
def word_pattern(self, pattern: str, str: str) -> bool:
words = str.split(" ")
return len(pattern) == len(words) and len(set(pattern)) == len(set(words)) == len(set(zip(pattern, words)))
|
print('Hello')
print('World')
# adding a keyword argument will get "Hello World" on the same line.
print('Hello', end=' ')
print('World')
# the "end=' '" adds a single space character at the end of Hello starts the next print right next ot it
print('cat', 'dog', 'mouse')
#the above will have a single spac... |
#
# PySNMP MIB module ASCEND-MIBINET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBINET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:27:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
def main():
s = input("")
x = s.isdigit()
print(x, end="")
main()
|
table = {"깍두기":1, "민혀기":2, "서주니":3}
print(table.keys())
print(table.values())
for item in table.items():
key = item[0]
value = item[1]
print(key, ":", value)
table["깍두기"] = 4
print(table) |
# 1. Two Sum
class Solution:
# Approach 1 : Naive
def twoSum1(self, nums, target):
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i, j]
return None
# Approach 2: Two-pass Hash Table
d... |
class Node:
pass
class Edge:
pass
class Graph:
pass
|
def highest_product_of_3(list_of_ints):
# initialize lowest to the minimum of the first two integers
lowest = min(list_of_ints[0], list_of_ints[1])
# initialize highest to the maximum of the first two integers
highest = max(list_of_ints[0], list_of_ints[1])
# initialize lowest_product_of_two and hi... |
ll = [1, 2, 3]
def increment(x):
print(f'Old value: {x}')
return x + 1
print(map(increment, ll))
for x in map(increment, ll):
print(x)
iter = map(increment, ll)
|
class MessageTypes:
InstrumentStateChange = 505
ClassStateChange = 516
Mail = 523
IndicativeMatchingPrice = 530
Collars = 537
SessionTimetable = 539
StartReferential = 550
EndReferential = 551
Referential = 556
ShortSaleChange = 560
SessionSummary = 561
GenericMessage = 592
OpenPosition = 59... |
# -*- coding: utf-8 -*-
# Scrapy settings for newblogs project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'newblogs'
SPIDER_MODULES = ['newblogs.spiders']
N... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 6 08:39:12 2021
@author: ELCOT
"""
"""
Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, ... |
def dig_pow(n, p):
"""
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
we w... |
route = [(1, -1), (1, 1), (1, -1), (-1, 1), (-1, 1), (1, -1), (1, -1), (1, 1), (-1, -1), (1, 1), (1, -1), (-1, 1), (1, -1), (-1, 1), (-1, 1), (-1, -1), (1, -1), (1, 1), (-1, -1), (1, -1), (1, -1), (1, 1), (1, -1), (-1, 1), (-1, 1), (-1, 1), (-1, -1), (1, -1), (1, -1), (1, 1), (-1, -1), (1, 1), (1, -1), (1, -1), (-1, -1... |
TEMPLATE = """\
# Include the license file
include LICENSE.md
include README.rst
# Include the data files
{include_data_files}
# Include the docs
# {include_docs_folder}
""" |
lista = [['edu', 'joao', 'luizr'], ['maria', ' aline', 'joana'],['helena', 'ed', 'lu']]
enumerada = list(enumerate(lista))
print(enumerada[1][1][2][0]) |
"""
Serialization is the process of converting a data structure or object into
a sequence of bits so that it can be stored in a file or memory buffer, or
transmitted across a network connection link to be reconstructed later in
the same or another computer environment.
Design an algorithm to seri... |
"""
* Author: ZHAO Zinan
* Created: 01/25/2019
341. Flatten Nested List Iterator
"""
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
... |
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918,
237,
412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379,
843, 831, 445, 742, 717, 958,743, 527
]
for number in numbers:
if ... |
# Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
class Solution:
def toLowerCase(self, str):
res = []
for char in str:
if ord(char) >= 65 and ord(char) <= 90:
res += chr(ord(char) + 32)
# res +=... |
def foo():
if 1:
if 2:
pass
|
#!/usr/bin/python
# https://practice.geeksforgeeks.org/problems/relative-sorting/0
def sol(a, b, m, n):
"""
Store the counts of each element, traverse through the second array and
keep building a temp. array, finally insert the elements which are not in
the second array
complextiy = m+n
"""
... |
# Exercício Python 13: Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.
dist = float(input('Insira a distância da viagem em km: '))
if dist <= 200.00:
print(f'O preço da passagem s... |
SQL_INIT_TABLES_AND_TRIGGERS = '''
CREATE TABLE consumers
(
component TEXT NOT NULL,
subcomponent TEXT NOT NULL,
host TEXT NOT NULL,
itype TEXT NOT NULL,
iprimary TEXT NOT NULL,
isecondary TEXT NOT NULL,
itertiary TEXT NOT NULL,
optional BOOLEAN NO... |
"""Isotopic Abundances for each isotope"""
class Natural_Isotope(object):
def __init__(self, symbol, mass_number, mass, isotopic_abundance,
cross_section):
self.symbol = symbol
self.mass_number = mass_number
self.mass = mass
self.isotopic_abundance = .01 *... |
# Achar o maior número palíndromo resultado de uma multiplicação entre dois números com 3 digitos.
# Função para testar se é palíndromo
def is_palindrome(word):
word = str(word)
if len(str(word)) <= 1:
return True
if str(word)[0] == str(word)[-1]:
return is_palindrome(word[1:-1])
return... |
__project__ = 'OCRErrorCorrectpy3'
__author__ = 'jcavalie'
__email__ = "Jcavalieri8619@gmail.com"
__date__ = '10/25/14'
EpsilonTransition = None
TransitionWeight = None
outputsModel=None
NUM_PARTITIONS=None
EM_STEP=True
|
def test_get_page_hierarchy_as_xml():
given_pages('PageOne', 'PageOne.ChildOne', 'PageTwo')
when_request_is_issued('root', 'type:pages')
then_response_should_be_xml()
def test_get_page_hierarchy_has_right_tags():
given_pages('PageOne', 'PageOne.ChildOne', 'PageTwo')
when_request_is_issued('root'... |
def new_file(filename, content):
with open(filename, 'w+') as f:
f.write(content)
print('Created at', filename)
|
####################################################
# Block
########################
blocks_head = []
class Block:
name = "Block"
tag = "div"
content_seperator = ""
allows_nesting = True
def __init__(self, parent):
self.parent = parent
self.parent.add(self) if parent else None
... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=int(input())
a=[*map(int,input().split())]
r=a[1]-a[0]
print(a[-1]+r*all(y-x==r for x,y in zip(a,a[1:])))
|
'''
Function:
打印从1到最大的n位数
Author:
Charles
'''
class Solution:
def printNumbers(self, n: int) -> List[int]:
start, end = 1, 10 ** n
return list(range(start, end)) |
# -*- coding: utf-8 -*-
"""
List Data Examples and Operations
Intro to Python Workshop
"""
# List Data are NOT immutable, unlike string data
testlist = [10,11,13,7,8,3]
print (testlist)
testlist[2] = 14
print (testlist)
# Lists are collections of items - we can put many values in a single variable
dmb = ... |
test = { 'name': 'q4c',
'points': 1,
'suites': [ { 'cases': [ {'code': ">>> is_valid_november_2020_sweden('Sweden', '2020-11-04')\nTrue", 'hidden': False, 'locked': False},
{'code': ">>> not is_valid_november_2020_sweden('sweden', '2020-11-04')\nTrue", 'hidden': False,... |
class complex:
def __init__(self, real, img):
self.real = real
self.img = img
def add(self, b):
res = complex(0,0)
res.real = self.real + b.real
res.img = self.img + b.img
return res
def display(self):
if self.img>=0:
print("{} + i{}".format(self.real, self.img))
if self.img<0:
print("{} -... |
"""A macro for creating a webpack federation route module"""
load("@aspect_rules_swc//swc:swc.bzl", "swc")
# Defines this as an importable module area for shared macros and configs
def build_route(name, entry, srcs, data, webpack, federation_shared_config):
"""
Macro that allows easy composition of routes fr... |
"""
Author: Justin Cappos
Description:
It should be okay to put __ in a doc string...
"""
#pragma repy
def foo():
"""__ should also be allowed here__"""
pass
class bar:
"""__ and here__"""
pass
|
#1st method
sq1 = []
for x in range(10):
sq1.append(x**2)
print("sq1 = ", sq1)
# 2nd method
sq2 = [x**2 for x in range(10)]
print("sq2 = ", sq2)
sq3 = [(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y]
print("sq3 = ", sq3)
vec = [-4, -2, 0, 2, 4]
print("x*2", [x*2 for x in vec])
print("x if x>0", [x for x in ve... |
salario = float(input('Qual o salário do funcionário?: '))
porcentagem = float(input('Quantos % de aumento?: '))
aumento = salario + (salario * porcentagem /100)
print('O aumento vai ser de {:.2f}R$ para {:.2f}R$'.format(salario, aumento))
|
n = str(input('Digite o seu nome completo: ')).strip()
print('Muito prazer em te conhecer,',n,'!')
nome = n.split()
print(f'Seu primeiro nome é {nome[0]}')
print(f'Seu último nome é {nome[len(nome)-1]}')
|
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def solution(value: int) -> str:
"""
Complete the solution so that it
returns a formatted string.
The return value should equal "Value
is VALUE" where value is a 5 digit
padd... |
# module trackmod.namereg
class NameRegistry(object):
class AllRegistered(object):
terminal = True
def register(self, names):
return
def __contains__(self, name):
return True
all_registered = AllRegistered()
class AllFound(object):
def __init__(... |
"""
For a given string and dictionary, how many sentences can you make from the
string, such that all the words are contained in the dictionary.
eg: for given string -> "appletablet"
"apple", "tablet"
"applet", "able", "t"
"apple", "table", "t"
"app", "let", "able", "t"
"applet", {app, let, apple, t, applet} => 3
"th... |
BOP_CONFIG = dict()
BOP_CONFIG['hb'] = dict(
input_resize=(640, 480),
urdf_ds_name='hb',
obj_ds_name='hb',
train_pbr_ds_name=['hb.pbr'],
inference_ds_name=['hb.bop19'],
test_ds_name=[],
)
BOP_CONFIG['icbin'] = dict(
input_resize=(640, 480),
urdf_ds_name='icbin',
obj_ds_name='icbin',... |
class MixUp:
def __init__(self):
pass
class CutMix:
def __init__(self):
pass
|
s = help(list)
print(s)
L = [] # пустой список
L = [1, 3, "test", {}] # 4 элемента
L = [1, 3, 'test2', ['e1', 'e2']] # вложенные подсписки
print(L[3][0]) # e1
'''
Генерация списков из итерируемых объектов
'''
L = list('spam')
L = list(range(-10, 10))
print(len(L)) # 20
print(L) # [-10, -9, -8, -7, -6, -5, -4, -... |
# 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
class Solution:
def calc_diameter(self, diameter, node):
if node:
l_height = calc_diameter(node.left)
... |
class C:
def f(self, x):
pass
def g(self):
def f(x): #gets ignored by pytype but fixer sees it, generates warning (FIXME?)
return 1
return f
|
"""定义了服务器的错误.
包括:
* ListenerError 钩子注册错误
* MultipleProcessDone 通过抛出这个异常来中断多进程任务的主进程循环
"""
class ListenerError(Exception):
"""钩子注册错误."""
pass
class MultipleProcessDone(Exception):
"""通过抛出这个异常来中断多进程任务的主进程循环."""
pass
|
var1 = 10
var2 = 15
var3 = 12.6
print (var1, var2, var3)
A = 89
B = 56
Addition = A + B
print (Addition)
A = 89
B = 56
Substraction = A - B
print (Substraction)
#type function
#variable
#operands
#operator
f = 9/5*+32
print (float(f))
#type function
#variable
#operands
#operator
c = 5*32/9
print (float(c)) |
expected_output = {
"main": {
"chassis": {
"name": {
"descr": "A901-6CZ-FT-A Chassis",
"name": "A901-6CZ-FT-A Chassis",
"pid": "A901-6CZ-FT-A",
"sn": "CAT2342U1S6",
"vid": "V04 "
}
}
},
"s... |
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
prod = float(input('Digite o valor do produto: '))
print('O valor do prpduto com desconto é {:.2f}'.format(prod - (prod * 0.05)))
|
# -*- coding: utf-8 -*-
"""
@author: 2series
"""
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, src, dest):
... |
class Clock:
def __init__(self, hour, minute):
self.hour = (hour + (minute // 60)) % 24
self.minute = minute % 60
def __repr__(self):
return "{:02d}:{:02d}".format(self.hour, self.minute)
def __eq__(self, other):
return self.hour == other.hour and self.minute == other.minut... |
{'name': 'Library Management Application',
'description': 'Library books, members and book borrowing.',
'author': 'Daniel Reis',
'depends': ['base'],
'data': [
'security/library_security.xml',
'security/ir.model.access.csv',
'views/library_menu.xml',
'views/book_view.xml',
'views/book_list_templ... |
number = int(input('Enter a number: '))
times = int(input('Enter a times: '))
def multiplication(numbers, x):
z = 1
while z <= numbers:
b = '{} x {} = {}'.format(z, x, x * z)
print(b)
z += 1
multiplication(number, times)
|
"""The Sampling configuration file consists of the parameters which conducting adaptive sampling/active learning from the VRM system
:param sampling_config['sample_dim']: Initial set (number) of KCC values to be generated to be sent to VRM for deviation pattern simulation
:type samplin... |
#! python3
# isPhoneNumber.py - Program without regular expressions to find a phone number in text
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0,3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4... |
# -*- coding:utf-8 -*-
def payment(balance, paid):
if balance < paid:
return balance, 0
else:
return paid, balance - paid
if __name__ == '__main__':
balance = float(input("Enter opening balance: "))
paid = float(input("Enter monthly payment: "))
print(" Amount Remaining")
... |
# Title : Lambda example
# Author : Kiran raj R.
# Date : 31:10:2020
def higher_o_func(x, func): return x + func(x)
result1 = higher_o_func(2, lambda x: x * x)
# result1 x = 2, (2*2) + 2, x = 6
result2 = higher_o_func(2, lambda x: x + 3)
# result2 x=2, (2 + 3) + 2, x = 7
result3 = higher_o_func(4, lambda x: x*... |
class ListTransformer():
def __init__(self, _list):
self._list = _list
@property
def tuple(self):
return tuple(self._list)
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# condition = '(![(NSString *)[[NSThread callStackSymbols] description] containsString:@"test1"])&&(![(NSString *)[[NSThread callStackSymbols] description] containsString:@"test2"])'
condition = '1'
# 忽略 C++ 的异常
IGNORE_CXX_COUNT = 0
IGNORE_CXX_CONDITION = condition
# 忽略 OC ... |
class Solution:
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
# Time Complexity: O(N)
# Space Complexity: O(1)
longest = releaseTimes[0]
slowestKey = keysPressed[0]
for i in range(1, len(releaseTimes)):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.