content stringlengths 7 1.05M |
|---|
# Messages issued by the bot to the user
REMOVAL_MESSAGE = """
The message by {username} was deleted as it violated the channel's moral guidelines.
Multiple such violations may lead to a temporary or even a permanent ban
"""
PERSONAL_MESSAGE_AFTER_REMOVAL = """
We deleted your message because it was found to be toxic... |
def _get_ratio(ratio):
if isinstance(ratio, str):
if ':' in ratio:
r_w, r_h = ratio.split(':')
try:
ratio = float(r_w) / float(r_h)
except:
raise
if not isinstance(ratio, float):
ratio = float(ratio)
return ratio
def center... |
# @Title: 千位分隔数 (Thousand Separator)
# @Author: KivenC
# @Date: 2020-08-23 01:03:42
# @Runtime: 36 ms
# @Memory: 13.6 MB
class Solution:
def thousandSeparator(self, n: int) -> str:
# return format(n, ',').replace(',', '.')
s = str(n)
count = len(s)
res = ''
for c in s:
... |
# Copyright (c) 2015, Sofiat Olaosebikan. All Rights Reserved
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This ... |
class DefaultAlias(object):
''' unless explicitly assigned, this attribute aliases to another. '''
def __init__(self, name):
self.name = name
def __get__(self, inst, cls):
if inst is None:
# attribute accessed on class, return `self' descriptor
return self
ret... |
#使用BFS, 单词和length一块记录, dict中每个单词只能用一次, 所以用过即删。dict给的是set类型, 检查一个单词在不在其中(word in dict)为O(1)时间。设单词长度为L, dict里有N个单词, 每次扫一遍dict判断每个单词是否与当前单词只差一个字母的时间复杂度是O(N*L), 而每次变换当前单词的一个字母, 看变换出的词是否在dict中的时间复杂度是O(26*L), 所以要选择后者。Python真是慢啊, 同样的代码C++ 668ms过, Python 1416ms过。看到双向BFS的做法, 应该能更快, 再研究研究。
class Solution:
# @param start, a... |
f1 = open("unprocessed/Cit-HepTh-dates.csv", "w")
f2 = open("unprocessed/Cit-HepTh.csv", "w")
with open("unprocessed/Cit-HepTh-dates.txt", "r") as file:
c = 0
for line in file:
if not c == 0:
l = line.split()
nl = l[0] + "," + l[1] + '\n'
f1.write(nl)
... |
def color_analysis(img):
# obtain the color palatte of the image
palatte = defaultdict(int)
for pixel in img.getdata():
palatte[pixel] += 1
# sort the colors present in the image
sorted_x = sorted(palatte.items(), key=operator.itemgetter(1), reverse = True)
light_shade, dark_shade, shad... |
#Write a program using while loops that asks the user for a positive integer 'n' and prints
#a triangle using numbers from 1 to 'n'.
number = int(input("Give me a number: "))
count = 0
for x in range(1, number+1):
count += 1
dibujar = str(x)
print (dibujar*count)
|
"""
factorial() is function factorial(number),
take the number parameter been passed and
return the factorial of it
"""
def factorial(number):
if number == 0:
return 1
else:
ans = number * factorial(number - 1)
return ans
|
class Solution:
def getFactors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = []
self.helper(n, [], n, ans)
return ans
def helper(self, n, factors, left, ans):
if left == 1:
if factors:
ans.append(fact... |
class Board(object):
def __init__(self, boards):
if len(boards) != 25:
raise Exception(f"Invalid board : {len(boards)}")
self.boards = boards
self.marked = [False] * 25
@staticmethod
def parse(lines):
boards = []
for line in lines:
boards.ext... |
{
"format_version": "1.16.0",
"minecraft:entity": {
"description": {
"identifier": f"{namespace}:pig_{color}",
"is_spawnable": true,
"is_summonable": true,
"is_experimental": false
},
"components": {
"minecraft:type_family": {
"family": [
f"pig_{color}",
"pig",
"mob"
]
}... |
"""
The :mod:`stan.proc_functions.merge` module is the proc merge function
"""
def merge(dt_left, dt_right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True):
return dt_left.merge(dt_right, how='inner', on=None, left_on=None, right... |
"""
Constants
Author: Brady Volkmann
Date: 6/21/2019
Constants file for the Tektroniks TTR506 VNA
"""
# INITIALIZE CONSTANTS ======================================================
# configure acquisition parameters
startFreqSweep = '50 MHz'
stopFreqSweep = '6 GHz'
sweepDelay = '1s'
snpFilename = 'test.s1... |
description = 'The outside temperature on the campus'
group = 'lowlevel'
devices = dict(
OutsideTemp = device('nicos.devices.entangle.Sensor',
description = 'Outdoor air temperature',
tangodevice = 'tango://ictrlfs.ictrl.frm2:10000/frm2/meteo/temp',
),
)
|
#This is just a demo server file to demonstrate the working of Telopy Backend
#This program consist the last line of Telopy
#import time
#import sys
#cursor = ['|','/','-','\\']
print('Telopy Server is Live ',end="")
#while True:
# for i in cursor:
# print(i+"\x08",end="")
# sys.stdout.flush()
# ... |
class VersioningError(Exception):
pass
class ClassNotVersioned(VersioningError):
pass
class ImproperlyConfigured(VersioningError):
pass
|
def create_groups(items, n):
"""Splits items into n groups of equal size, although the last one may be shorter."""
# determine the size each group should be
try:
# this line could cause a ZeroDivisionError exception
size = len(items) // n
except ZeroDivisionError:
print('WARNING:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 22.01.20
@author: felix
"""
NORMALIZE = False
class EasyDict(dict):
def __init__(self, *args, **kwargs):
global NORMALIZE
NORMALIZE = kwargs.pop('normalize', False)
super(EasyDict, self).__init__(*args, **kwargs)
def __get... |
fig, axs = plt.subplots(1, 2, figsize=(20,5))
p1=boroughs4.plot(column='Controlled drugs',ax=axs[0],cmap='Blues',legend=True);
p2=boroughs4.plot(column='Stolen goods',ax=axs[1], cmap='Reds',legend=True);
axs[0].set_title('Controlled drugs', fontdict={'fontsize': '12', 'fontweight' : '5'});
axs[1].set_title('Stolen go... |
#Höfundur Einar Karl
#Dagsetning 24/09/2018
val=""
#While loop
while (val !="6"):
#Valmynd
print("------------------------------------------------") #Lína til að láta forritið líta betur út
print("1. Liður 1 (Tölu innsláttur) ")
print("2. Liður 2 (Ferhyrnings Reikningur) ")
print("3. Liður... |
class Reaction:
def __init__(self):
pass
def from_json(json):
reaction = Reaction()
reaction.reaction = json["reaction"].encode("unicode-escape")
reaction.actor = json["actor"]
return reaction
def list_from_json(json):
reactions = []
for child in json:
reactions.append(Reaction.from_json(child)... |
class Triangulo():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def semelhantes(self, triangulo):
a, b, c = triangulo.a, triangulo.b, triangulo.c
if ((a % self.a) == 0 ) and ((b % self.b) == 0) and ((c % self.c) == 0):
ret... |
age = input("Please enter your age: ")
if age.isdigit():
print(age)
age = int(input("Please enter your age: "))
while(True):
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
break
raise Except... |
def fasttsq(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fasttsq3d(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fasttsqp(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fastq(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fastq3d(M,psi,Y... |
## A - O somatorio de 2 com 2 e menor do que 4?
print(2+2 < 4)
##-------------------------
## B - O valor 7//3 e igual a 1+1?
print(7 // 3 == 1+1)
##--------------------------
## C - A soma de 3 elevado ao quadrado com 4 elevado ao quadrado e igual a 25?
print(3 ** 2 + 4 ** 2 == 25)
##--------------------------
## D -... |
# Heap
class Solution:
def shortestPathLength(self, graph):
memo, final, q = set(), (1 << len(graph)) - 1, [(0, i, 1 << i) for i in range(len(graph))]
while q:
steps, node, state = heapq.heappop(q)
if state == final: return steps
for v in graph[node]:
... |
"""
Conf file for base_url
"""
base_url = "http://qxf2trainer.pythonanywhere.com/accounts/login/"
|
"""
link: https://leetcode-cn.com/problems/target-sum
problem: 对数组每个元素补上正负号,问共有多少种方法使得数组元素和为 S,数组长度小于20,初始数组元素和不大于1000
solution: DP。直接搜时间复杂度O(2^20) 会 TLE,性能真烂。转变成有两个选择的 01 背包问题,扫一遍记录每轮的可能的结果有哪些。
注意两个选择的结果会互相干扰,不能用 01 背包的倒序法遍历,需要另起临时数组存储每轮新的结果再换回来。
"""
class Solution:
def findTargetSumWays(self, nums: ... |
def test_besthit():
assert False
def test_get_term():
assert False
def test_get_ancestors():
assert False
def test_search():
assert False
def test_suggest():
assert False
def test_select():
assert False
|
#
# PySNMP MIB module VISM-SESSION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VISM-SESSION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:27:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
"""
This module contains a function that loads previous trained classifier into the nlp unit.
"""
def loadClassif(nlp, app_path):
"""
This function loads the already trained classifier into the nlp unit.
If the classifier does not yet exist, it will be trained as part of this function.
Input:
... |
#---------------------------------
# PIPELINE RUN
#---------------------------------
# The configuration settings to run the pipeline. These options are overwritten
# if a new setting is specified as an argument when running the pipeline.
# These settings include:
# - logDir: The directory where the batch queue scripts... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
def num_glowing(n, prime... |
class DesignOpt:
def __init__(mesh, dofManager, quadRule):
self.mesh = mesh
self.dofManager = dofManager
self.quadRule = quadRule
|
__author__ = 'rhoerbe' #2013-09-05
# Entity Categories specifying the PVP eGov Token as of "PVP2-Allgemein V2.1.0", http://www.ref.gv.at/
EGOVTOKEN = ["PVP-VERSION",
"PVP-PRINCIPAL-NAME",
"PVP-GIVENNAME",
"PVP-BIRTHDATE",
"PVP-USERID",
"PVP-GID",
... |
# Даны два момента времени в пределах одних и тех же суток. Для каждого момента указан час,
# минута и секунда. Известно, что второй момент времени наступил не раньше первого.
# Определите сколько секунд прошло между двумя моментами времени.
h1 = int(input())
m1 = int(input())
s1 = int(input())
h2 = int(input())
m2 = i... |
# classes for inline and reply keyboards
class InlineButton:
def __init__(self, text_, callback_data_ = "", url_=""):
self.text = text_
self.callback_data = callback_data_
self.url = url_
if not self.callback_data and not self.url:
raise TypeError("Either callback_data ... |
def rank4_simple(a, b):
assert a.shape == b.shape
da, db, dc, dd = a.shape
s = 0
for iia in range(da):
for iib in range(db):
for iic in range(dc):
for iid in range(dd):
s += a[iia, iib, iic, iid] * b[iia, iib, iic, iid]
return s
|
#
# PySNMP MIB module CNTEXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNTEXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:29 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:... |
def get_dict_pos(lst, key, value):
return next((index for (index, d) in enumerate(lst) if d[key] == value), None)
def search_engine(search_term, data_key, data):
a = filter(lambda search_found: search_term in search_found[data_key], data)
return list(a)
|
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
n = len(word1)
m = len(word2)
# 有一个字符串为空串
if n * m == 0:
return n + m
# DP 数组
D = [ [0] * (m + 1) for _ in range(n + 1)]
# 边界状态初始化
for i in ran... |
"""
This module contains submodules used to mine Interaction data from `Kegg`,
`Hprd`, `InnateDB`, `BioPlex` and `Pina2` along with other data processing
modules.
The `features` module contains a function to compute the features based on
two `:class:`.database.models.Protein`s. The `uniprot` module contains s... |
#
# PySNMP MIB module F10-BPSTATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F10-BPSTATS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:11:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#3.1.1 => updates from 2016 to 2018
#3.1.2 => fix to pip distribution
__version__ = '3.1.2'
|
if __name__ == '__main__':
print("{file} is main".format(file=__file__))
else:
print("{file} is loaded".format(file=__file__)) |
class Config:
"""Discriminator configurations.
"""
def __init__(self, steps: int):
"""Initializer.
Args:
steps: diffusion steps.
"""
self.steps = steps
# embedding
self.pe = 128
self.embeddings = 512
self.mappers = 2
# blo... |
with open('.\\DARKCPU\\DARKCPU.bin', 'rb') as inputFile:
with open('image.bin', 'wb') as outputFile:
while True:
bufA = inputFile.read(1)
bufB = inputFile.read(1)
if bufA == "" or bufB == "":
break;
outputFile.write(bufB)
... |
class DefaultBindingPropertyAttribute:
"""
Specifies the default binding property for a component. This class cannot be inherited.
DefaultBindingPropertyAttribute()
DefaultBindingPropertyAttribute(name: str)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DefaultBindingPrope... |
# problem description can be added if required
n = int(input())
hou = [int(i) for i in input().split()]
p = int(input())
for i in range(p):
a, b = [int(i) for i in input().split()]
print(sum(hou[a - 1:b])) # sum was to be including both the 'a'th and 'b'th index
|
class ModelAdmin:
"""
The class provides the possibility of declarative describe of information
about the table and describe all things related to viewing this table on
the administrator's page.
class Users(models.ModelAdmin):
class Meta:
resource_type = PGResource
... |
''' Base Class method Proxy'''
#method 1, not recommand!
class A:
def spam(self, x):
pass
def foo(self):
pass
class B:
def __init__(self):
self._a = A()
def spam(self, x):
# Delegate to the internal self._a instance
return self._a.spam(x)
def foo(self):
... |
def aléa(a, b):
return (a + b) // 2
if __name__ == '__main__':
print('Import this module in order to use it!') |
class PacketSummary(object):
"""
A simple object containing a psml summary.
Can contain various summary information about a packet.
"""
def __init__(self, structure, values):
self._fields = {}
self._field_order = []
for key, val in zip(structure, values):
key, v... |
# "Matrix Decomposition"
# Alec Dewulf
# April Cook Off 2020
# Difficulty: Simple
# Concepts: Fast exponentiation, implementation
"""
This problem required the solver to caculate exponentials very quickly.
I did that by computing everything mod so the numbers remained small.
A more efficient exponent function could h... |
class Customer:
def __init__(self, customer_id, first, last, email, address, city, state, zip_code, phone):
self.id = customer_id
self.first = first
self.last = last
self.email = email
self.address = address
self.city = city
self.state = state
self.zip... |
def solution(x):
answer = True
temp = 0
copy = x
while copy != 0:
r = copy % 10
copy //= 10
temp += r
if x % temp != 0:
answer = False
return answer
print(solution(13)) |
# ------------------------------
# 138. Copy List with Random Pointer
#
# Description:
# A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
# Return a deep copy of the list.
#
# Version: 1.0
# 08/21/18 by Jianfa
# -----------------------... |
#!/usr/bin/python
# Tutaj _used i independent_set jest typu set.
class UnorderedSequentialIndependentSet1:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError("the graph is directed")
... |
input = '''10 3 15 10 5 15 5 15 9 2 5 8 5 2 3 6'''
memory = [int(x) for x in input.split('\t')]
memory_status = []
def update_memoery(memory):
highest_bank = max(memory)
highest_index = memory.index(highest_bank)
memory[highest_index] = 0
i = 0
while i < highest_bank:
memory[(highest_inde... |
for _ in range(int(input())):
n,x = [int(x) for x in input().split()]
dp = {}
s = input()
dp[x] = 1
for i in s:
if(i == "R"): x += 1
else:x -= 1
if(not dp.get(x)):dp[x] = 1
print(len(dp)) |
class FontStyleConverter(TypeConverter):
"""
Converts instances of System.Windows.FontStyle to and from other data types.
FontStyleConverter()
"""
def CanConvertFrom(self,*__args):
"""
CanConvertFrom(self: FontStyleConverter,td: ITypeDescriptorContext,t: Type) -> bool
Returns a value that... |
def median(array):
array = sorted(array)
if len(array) % 2 == 0:
return (array[(len(array) - 1) // 2] + array[len(array) // 2]) / 2
else:
return array[len(array) // 2]
|
# Copyright 2019 VMware, Inc.
# SPDX-License-Identifier: BSD-2-Clause
class PrePostProcessor(object):
def pre_process(self, data):
type(self)
return data
def post_process(self, data):
type(self)
return data
|
def find_digits(digits1, digits2, digit_quantity_to_find):
print('Inputs:')
print('\tdigits1 = %s' % (digits1))
print('\tdigits2 = %s' % (digits2))
print('\tdigit_quantity_to_find = %d' % (digit_quantity_to_find))
digit_count_by_input = [len(digits1), len(digits2)]
positions_by_digit_input = [... |
class Animal:
hungry = 100
def __init__(self, name, weight):
self.name = name
self.weight = weight
def eat(self, value):
self.hungry += int(value)
class FruitOfEggs:
amount_eggs = 5
def get_eggs(self):
if self.amount_eggs >= 0:
self.am... |
class Args:
"""
This module helps in preventing args being sent through multiple of classes to reach
any analysis/laser module
"""
def __init__(self):
self.solver_timeout = 10000
self.sparse_pruning = True
self.unconstrained_storage = False
args = Args()
|
# (c) 2012 Urban Airship and Contributors
__version__ = (0, 2, 0)
class RequestIPStorage(object):
def __init__(self):
self.ip = None
def set(self, ip):
self.ip = ip
def get(self):
return self.ip
_request_ip_storage = RequestIPStorage()
get_current_ip = _request_ip_storage.get
s... |
def sum_of_squares(value):
sum = 0
for _ in range(value + 1):
sum = sum + _ ** 2
return sum
def summed_squares(value):
sum = 0
for _ in range(value + 1):
sum += _
return sum ** 2
print(summed_squares(100) - sum_of_squares(100)) |
# Part 1
data = data.split("\r\n\r\n")
nums = list(map(int, data[0].split(",")))
boards = []
for k in data[1:]:
boards.append([])
for j in k.splitlines():
boards[-1].append(list(map(int, j.split())))
for num in nums:
for board in boards:
for row in board:
for i in range(len(row... |
def test_000_a_test_can_pass():
print("This test should always pass!")
assert True
def test_001_can_see_the_internet(selenium):
selenium.get('http://www.example.com')
|
f = open("shaam.txt")
# tell() tell the position of our f pointer
# print(f.readline())
# print(f.tell())
# print(f.readline())
# print(f.tell())
# seek() point the pointer to given index
f.seek(5)
print(f.readline())
f.close() |
"""
Stores all global variables
"""
global d, aSub1, aSubN, aSubX, aSubY, x, y, sSubN, n, operations, selection, r # declares all variables global
r = None # common rate
d = None # common difference
aSub1 = None # first number in sequence
aSubN = None # number in sequence given index n
aSubX = None # nu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" __init__.py : __init__ """
__author__ = "Abhay Arora ( @dumbstark )"
|
#!/usr/bin/env python3
# 给定一个正整数n, 求解出所有和为n的整数组合, 要求组合按照递增的方式展示,而且唯一,例如: 4=1+1+1+1,4=1+1+2
def get_all_combination(sums, result, count):
if sums < 0:
return
if sums == 0:
print("满足条件的组合...")
i = 0
while i < count:
print(result[i])
i += 1
i = (1... |
dp=[[0]*5 for i in range(101)]
dp[0][0]=1
dp[1][0]=1
dp[2][0]=1
dp[2][1]=1
dp[2][2]=1
dp[2][3]=1
dp[2][4]=1
for i in range(3,101):
dp[i][0]=sum(dp[i-1])
dp[i][4]=sum(dp[i-2])
j=i-2
while j>=0:
dp[i][1]+=sum(dp[j])
j-=2
j=i-2
while j>=0:
dp[i][2]+=sum(dp[j])
dp[i][3]+=sum(dp[j])
j-=1
for... |
# leapyear
y=input("enter any year")
if y%4==0:
print("{} is:leap year".format(y))
else:
print("{} is not a leap year".format(y))
|
t = int(input())
for i in range(t):
n, m = list(map(int, input().split()))
if(n%m == 0):
print("YES")
else:
print("NO")
|
a, b, c = (int(input()) for i in range(3))
if a <= b <= c:
print("True")
else:
print("False")
|
# 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 ( arr , n , x ) :
for i in range ( n ) :
if arr [ i ] > arr [ i + 1 ] :
break
l = ( i + 1... |
class Queue:
def __init__(self) -> None:
self._queue = []
def insert(self, val: int) -> None:
self._queue.append(val)
def pop(self) -> None:
self._queue.pop(0)
def __str__(self):
return "{}".format(self._queue)
def __len__(self):
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minimalExecTime(self, root: TreeN... |
class DeployResult(object):
def __init__(self, vm_name, vm_uuid, cloud_provider_resource_name, autoload,
inbound_ports, deployed_app_attributes, deployed_app_address,
public_ip, resource_group, extension_time_out, vm_details_data):
"""
:param str vm_name: The name o... |
# -*- coding: utf-8 -*-
# -------------------------------------
# basic unit
# -------------------------------------
PT = 1.0 # basic unit
ITP = 72.0 # inch to point
MAJOR_DIST = 5.0 * PT # significant distance exists between two block lines
MINOR_DIST = 1.0 * PT # small distance
TINY_DIST = 0.5 * PT # very... |
"""
readtransaction.py
Description:
This class keeps track of keys for which a write
operation is still pending when a client wants
to perform a read operation.
It also contains helper functions to easily store
(pending) writes and return the values corresponding
to those keys once no more keys... |
class PreRequisites:
def __init__(self, course_list=None):
self.course_list = course_list
|
#!/usr/local/bin/python3
def soma_1(x, y):
return x + y
def soma_2(x, y, z):
return x + y + z
def soma(*numeros):
return sum(numeros)
if __name__ == '__main__':
print(soma_1(10, 10))
print(soma_2(10, 10, 10))
# packing
print(soma(10, 10, 10, 10))
# unpacking
list_nums = [10, ... |
class ElementMulticlassFilter(ElementQuickFilter, IDisposable):
"""
A filter used to match elements by their class,where more than one class of element may be passed.
ElementMulticlassFilter(typeList: IList[Type],inverted: bool)
ElementMulticlassFilter(typeList: IList[Type])
"""
def Dispose... |
'''Escreva um programa que lê um número não determinados de valores a, todos inteiros e positivos, um de cada vez, e
calcule e escreva a média aritmética dos valores lidos, a quantidade de valores pares, a quantidade de valores ímpares, a
percentagem de valores pares e a percentagem de valores ímpares.'''
num = int(in... |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
m = {}
for i, n in enumerate(nums):
if (target-n) in m:
return [m[target-n], i]
m[n] = i
|
class CPU:
VECTOR_RESET = 0xFFFC # Reset Vector address.
def __init__(self, system):
self._system = system
self._debug_log = open("debug.log", "w")
def reset(self):
# Program Counter 16-bit, default to value located at the reset vector address.
self._pc = self._syste... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 04:22:02 2021
@author: Septhiono
"""
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n").lower()
name2 = input("What is their name? \n").lower()
name3=name1+name2
true=name3.count('t')+name3.count('r')+name3.count('u')+name3.coun... |
def greet_customer(grocery_store, special_item):
print("Welcome to "+ grocery_store + ".")
print("Our special is " + special_item + ".")
print("Have fun shopping!")
greet_customer("Stu's Staples", "papayas")
def mult_x_add_y(number, x, y):
print("Total: ", number * x + y)
mult_x_add_y(5, 2, 3)
mult_x_add_y... |
class TransitionId(object):
ClearReadout=0
Reset =1
Configure =2
Unconfigure =3
BeginRun =4
EndRun =5
BeginStep =6
EndStep =7
Enable =8
Disable =9
SlowUpdate =10
Unused_11 =11
L1Accept =12
NumberOf =13
|
MIN_MATCH = 4
STRING = 0x0
BYTE_ARR = 0x01
NUMERIC_INT = 0x02
NUMERIC_FLOAT = 0x03
NUMERIC_LONG = 0x04
NUMERIC_DOUBLE = 0x05
SECOND = 1000
HOUR = 60 * 60 * SECOND
DAY = 24 * HOUR
SECOND_ENCODING = 0x40
HOUR_ENCODING = 0x80
DAY_ENCODING = 0xC0
BLOCK_SIZE = 128
INDEX_OPTION_NONE = 0
INDEX_OPTION_DOCS = 1
INDEX_OPTION_... |
# -*- coding: utf-8 -*-
"""
@date: 2020/9/10 上午11:21
@file: __init__.py
@author: zj
@description:
"""
|
def ficha(jogador='<Desconhecido>', gol = 0):
print(f'O Jogador {jogador} fez {gol} gols.')
name = str(input('Digite o Nome do Jogador: '))
#leitura de variável como string para realizar teste isnumeric() e validar
gols = str(input('Digite a quantidade de Gols no Campeonato: '))
if gols.isnumeric():
gols = in... |
"""
Hao Ren
11 October, 2020
344. Reverse String
Python: One line solution. Just a joke.
"""
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
s.reverse()
|
#encoding:utf-8
subreddit = 'ProsePorn'
t_channel = '@r_proseporn'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.