content stringlengths 7 1.05M |
|---|
def sod(n):
ans = 0
while n:
rem = n%10
ans += rem
n = n // 10
return ans
t = int(input())
while t:
n = int(input())
a_score = 0
b_score = 0
while n:
a,b = map(int, input().split())
a_sum = sod(a)
b_sum = sod(b)
# print(a_sum... |
class MeterInfo(object):
def __init__(self, address: int
, dbid: int, devStr: str
, mBrand: str, mModel: str):
# - - - - - - - - - -
self.modbusAddress: int = address
self.meterDBID: int = dbid
self.deviceSystemString: str = devStr
self.meterBrand: str... |
class Solution:
def chalkReplacer(self, chalk: List[int], k: int) -> int:
gg = sum(chalk)
k = k%gg
for i,n in enumerate(chalk):
if n>k:
return i
k-=n
return len(chalk)-1 |
'''
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a ... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: mo-mo-
#
# Created: 23/09/2018
# Copyright: (c) mo-mo- 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
... |
# Write simple .camelCase method (camel_case function in PHP, CamelCase in C# or camelCase in Java) for strings. All
# words must have their first letter capitalized without spaces.
#
# For instance:
#
# camelcase("hello case") => HelloCase
# camelcase("camel case word") => CamelCaseWord
# Don't forget to rate this kat... |
"""
None
"""
class Solution:
def countElements(self, arr: List[int]) -> int:
res = 0
ss = set(arr)
for a in arr:
if a + 1 in ss:
res += 1
return res |
load("@io_bazel_rules_dotnet//dotnet/private:rules/nuget.bzl", "nuget_package")
def dotnet_repositories_xunit():
### Generated by the tool
nuget_package(
name = "xunit.runner.console",
package = "xunit.runner.console",
version = "2.4.1",
sha256 = "23f0b49edbfe5be8f8554e7f4317a39... |
def test(tested_mod, Assert):
test_cases = [
# (expected, inputs)
([], []),
([1, 3, 5, 6], [1, 3, 5, 6]),
([1], [1, 1, 1]),
([3, 1, 5, 2], [3, 1, 1, 5, 2, 2, 2])
]
return Assert.all(tested_mod.loesche_doppelte, test_cases)
|
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
trans_list=[]
if root==None:
return []
else:
trans_list+=self.inorderTraversal(root.left)
trans_list.append(root.val)
trans_list+=self.inorderTraversal(root.right)
... |
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
# Difficulty: Easy
# Max Score: 10
# Language: Python
# ========================
# Solution
# ========================
N = int(input())
A... |
# Copyright (c) Vera Galstyan Feb 2018
restaurant = input("How many people are in your group: ")
if int(restaurant)>=8:
print("You have to wait for a table, because you are " + restaurant)
else:
print("Your table is ready, because you are " + restaurant) |
if exists("1580195068422.png"):
click("1580195068422.png")
if exists("1580196282023.png"):
click("1580196282023.png")
click("1580193456450.png")
sleep(1)
click("1580193473300.png")
sleep(1)
click("1580193506111.png")
sleep(1)
click("1580193456450.png")
click("1580193641655.png")
click("158019... |
lines = []
with open("input.txt") as f:
lines = f.readlines()
width = 31
def calc_hits(right_steps, down_steps, lines):
right_pos = right_steps
down_pos = down_steps
trees_hit = 0
while down_pos < len(lines):
if lines[down_pos][right_pos] == '#':
trees_hit += 1
down_po... |
#----
# Ингредиенты (разделка туш):
metadict_detail['Туша баранья (килограмм)'] = {
# Субпродукты: ноги по запястный/скакательный сустав,
# кровь, внутренние органы, шкура, хвост (курдюк) и голова.
# Убойный выход 50%:
# https://lektsii.org/4-22560.html
# https://sel... |
#import urllib
#from lxml import html
#url = "https://material-ui.com/customization/color/"
#page = html.fromstring(urllib.urlopen(url).read())
#colors={}
#for color in page.xpath("//*[@class='jss260']"):
# colorName = color.xpath(".//*[@class='jss257']/text()")[0]
# value = {}
# for val in color.xpath(".//... |
class PyVistaImportError(ImportError):
message = """Trouble importing PyVista."""
def __init__(self):
"""Empty init."""
ImportError.__init__(self, self.message)
|
#
# PySNMP MIB module CISCO-DYNAMIC-ARP-INSPECTION-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DYNAMIC-ARP-INSPECTION-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 11:56:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... |
#!/usr/bin/env python3
digits = input()
skip = len(digits) // 2
print(sum(int(a) for a, b in zip(digits, digits[skip:]+digits[:skip]) if a == b))
|
with open('input.txt', 'r') as file:
input = file.readlines()
input = [ line.strip() for line in input ]
def part1():
return
def part2():
return
print(part1())
print(part2()) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# default settings for database schema router
DATABASE_ROUTERS = [ 'navigator.pgschema.routers.schemaRouter' ]
DATABASE_STATEMENT_TIMEOUT = 60000 # on milliseconds
DATABASE_COLLATION = 'UTF8'
DEBUG_SQL = True
DATABASE_TZ = 'UTC'
|
"""
A package allowing cleanup of import changes after migrating to Django 2.
This package is structured such that
form corehq.util.django2_shim.x.x import y
will work in both Django 1 and Django 2, and that once we are on django 2
we can replace `from corehq.util.django2_shim.` with `from django.` throughout
an... |
n = int(input())
value = n * (n - 1) // 2
if n % 2 == 0:
print('Even' if value % 2 == 0 else 'Odd')
else:
print('Either')
|
p = float(input('Digite o seu peso: (Kg) '))
a = float(input('Digite a sua altura: (m) '))
imc = p / (a * a)
print('O IMC desta pessoa é : {:.2f}'.format(imc))
if imc < 18.5:
print('ABAIXO do peso')
elif imc >= 18.5 and imc < 25:
print('PESO IDEAL')
elif imc >= 25 and imc < 30:
print('SOBREPESO')
elif imc >... |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
SECOND = 1
MILLISECOND = 1000
MICROSECOND = 1000000
NANOSECOND = 1000000000
TIME_UNITS = {'microsecond': MICROSECOND, 'millisecond': MILLISECOND, 'nanosecond': NANOSECOND, 'second': SECOND}
|
expected_output={
"interface":{
"GigabitEthernet3":{
"crypto_map_tag":"vpn-crypto-map",
"ident":{
1:{
"acl":"origin_is_acl,",
"action":"PERMIT",
"current_outbound_spi":"0x397C36EE(964441838)",
"dh_group":"none",
... |
class kycInfo:
def __init__(self, registerNumber, name, gender, dob=None, address=None):
self.registerNumber = registerNumber
self.name = name
self.gender = gender
self.dob = dob
self.address = address
|
GOOGLE_CLOUD_SPEECH_CREDENTIALS = "Insert Google Cloud Speech API Key"
mongourl = "Insert MongoDB URL"
stdlib = "Insert stdlib API Key"
|
# These are the common special chars occured with numbers
Num_Special_Chars = [',', '-', '+', ' ']
# get_type_lst will sample at most x entries from a given query
MAX_SAMPLE_SIZE = 500
|
# Fitur .add()
print(">>> Fitur .add()")
set_buah = {'Jeruk','Apel','Anggur'}
set_buah.add('Melon')
print(set_buah)
# Fitur .clear()
print(">>> Fitur .clear()")
set_buah = {'Jeruk','Apel','Anggur'}
set_buah.clear()
print(set_buah)
# Fitur .copy()
print(">>> Fitur .copy()")
set_buah1 = {'Jeruk','Apel','Anggur'}
set_buah... |
# docstyle-ignore
INSTALL_CONTENT = """
# Transformers installation
! pip install transformers datasets
# To install from source instead of the last release, comment the command above and uncomment the following one.
# ! pip install git+https://github.com/huggingface/transformers.git
"""
notebook_first_cells = [{"type... |
"""
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/
Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1s present whe... |
#
# @lc app=leetcode.cn id=160 lang=python
#
# [160] 相交链表
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# ... |
class Config:
MASTER_GEOMETRY_FIELDNAME = "wkb_geometry"
SCHEMA = "public"
SQL_FILE_EXTENSION = ".sql"
DATABASE_NAME = "gensmd"
PQSL_TEMPLATE = '"c:/Program Files/PostgreSQL/9.5/bin/psql.exe" -U postgres -q -d %s -f %s\n' % DATABASE_NAME
ID_FIELD_NAME = "zdroj_id"
PG_CONNECTOR = "dbname=%s u... |
palindrome = input("What word or phrase would you like to check?")
palindromeNoSpace = palindrome.replace(" ","")
lengthCheck = False
wordLength = 0
while lengthCheck == False:
if len(palindrome) == 0:
print("Please enter a word or phrase")
palindrome = input("What word or phrase would you like to ... |
# Copyright (c) 2013 Qubell Inc., http://qubell.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
s="Paraschiv Alexandru-Andrei"
crt=0
nume=0
poz=0
i=0
lg=len(s)
for i in range (lg):
if (i==0 or s[i-1]==" " or s[i-1]=="-"):
if s[i].islower():
print("Nume gresit")
break
if s[i]=="-":
crt+=1
if crt>1:
print("Nume gresit")
b... |
#
# PySNMP MIB module HPN-ICF-FC-TRACE-ROUTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-FC-TRACE-ROUTE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:38:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stacks = []
self.temp = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stacks += [x]
def pop(self) -> int:
... |
#!/usr/bin/python
"""
Powerful digit sum
https://projecteuler.net/problem=56
"""
def digitalsum(n):
n = list(str(n))
total = 0
for i in range(len(n)):
total = total + int(n[i])
return total
def main():
hold = 0
for i in range(1, 100):
for j in range(1, 100):
temp ... |
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if not root: return # 如果root为空,则说明root的上一节没有子节点
dfs(root.right) # 如果有子节点,先进入右边,即中序遍历的逆序
if self.k == 0: return # 先从右边找,如果右边就满足条件:有第K大节点,那就return
self.k -= 1 # 减一,说明离第k大子节点更... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 11 09:23:21 2022
@author: ACER
"""
def calcularArea():
print("calcular Area")
def calcularDist(x,y):
print(f"la distancia es {x-y}")
|
class StartupError(Exception):
def __init__(self, message):
self.message = message
class DeviceRegistrationError(Exception):
def __init__(self, message):
self.message = message
class OverlayRegistrationError(Exception):
def __init__(self, message):
self.message = message
class ... |
# 362. Design Hit Counter
# Medium
# 377
# 37
# Favorite
# Share
# Design a hit counter which counts the number of hits received in the past 5 minutes.
# Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the t... |
"""1614.
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
"""
def max_depth(s: str) -> int:
ans = 0
stack = []
for ch in s:
if ch == '(':
stack.append(ch)
elif ch == ')':
ans = max(ans, len(stack))
stack.pop()
return ans
|
s = 0
last = 1
for i in range(int(input())):
if int(input()) in [2,3]:
s+=1
print(s) |
def melhorCaso(lista,d,n):
casos00= []
aux = 0
for i in range(n-1,-1,-1):
if(i == n-1):
incremento = 1
while(aux <= d):
casos00.append(aux) # Ordem do menor para o maior
aux = lista[i]* incremento
incremento = incremento + 1
... |
class PageSections(object):
def __init__(self, driver):
super().__init__()
self.driver = driver
def click_menu(self):
return
|
def test_nodenet_statuslogger(app, runtime, test_nodenet):
net = runtime.get_nodenet(test_nodenet)
sl = net.netapi.statuslogger
sl.info("Learning.Foo", sl.ACTIVE, progress=(5, 23))
logs = runtime.get_logger_messages(sl.name)
assert "Learning.Foo" in logs['logs'][1]['msg']
result = app.get_json... |
# rotate 180 degrees
# need to call show after rotating as rotating only sets the remapping bits on the remap and offset registers
# show repopulates the gddram in the new correct order
display.rotate(True)
display.show()
# rotate 0 degrees
display.write_cmd(ssd1327.SET_DISP_OFFSET) # 0xA2
display.write_cmd(128 - disp... |
# Created by MechAviv
# Custom Puppy Damage Skin | (2439442)
if sm.addDamageSkin(2439442):
sm.chat("'Custom Puppy Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
"""
1464. Maximum Product of Two Elements in an Array
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/
Given the array of integers nums,
you will choose two different indices i and j of that array.
Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example:
Input: nums = [3,4,5,2]
Output: ... |
#
# PySNMP MIB module CISCO-WAN-NCDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-NCDP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:20:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
"""Utilities for handling unlabelled objects when translating workflow formats."""
class Labels(object):
"""Track labels assigned and generate anonymous ones."""
def __init__(self):
"""Initialize labels that have been encountered or generated."""
self.seen_labels = set()
self.anonymou... |
substvars = {
'SCRIPTS_DIR' : 'scripts',
}
tasks = {
'util' : {
'features' : 'cshlib',
'source' : 'shlib/**/*.c',
#'includes' : '.',
#'toolchain' : 'auto-c',
# 'install-files' testing
'install-files' : [
{
# copy whole directory... |
# @Author : Eric_Lee!!
# @Time : 2018/11/9 上午11:25
# @FileName: FirstDemo.py
# @Software: PyCharm
def predict(x):
print('听说班长今晚请吃饭')
|
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if(len(nums)-len(list(set(nums)))>0):
return True
elif len(nums)==1:
return False
else:
return False
|
#
# PySNMP MIB module CISCO-ST-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ST-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
# gunicorn demo_gunicorn
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return [b'Hello World\n']
# 下記はクラス構文例
# class Application:
# def __call__(self, environ, start_response):
# start_response('200 OK', [('Content-Type', 'text/plain')])
# ... |
#!/usr/bin/env python3
#ccpc20wh
'''
1 差分思想
2 结束的时候要清算! 维护哪些人还在组里?? ....
3 自己发的言不算消息!
'''
n,m,s = map(int,input().split()) # n=#groups; m=#students; s=#events..
gpmsgs = [0]*(n+1)
gpmber = [set() for i in range(n+2)]
person = [0]*(m+1)
for i in range(s):
t,x,y = map(int,input().split())
if t==1: #join
... |
# acm thailand 2011
def refill(lf_c, lf_h, lf_v, path=''):
'''recursive fill the walk path, if filled check if the walk are valid'''
global answer
if answer:
return
if lf_c == 0 and lf_h == 0 and lf_v == 0:
if chk(path):
## on valid path, ignore furthermore path ##
... |
'''
Write a function that takes in an array of positive integers and returns an integer representing the maximum sum of non-adjacent elements
in the array.
If a sum cannot be generated, the function should return 0.
[7,10,12,7,9,14] 7+12+14=33
'''
# O(n) time | O(n) space
# def maxSubsetSumNoAdjacent(array):
# #... |
#number of lines you want in the new file
lines_per_file = 100000
smallfile = None
with open('/home/cantos/Downloads/index.jsonl') as bigfile: #give the file name and extension
for lineno, line in enumerate(bigfile):
if lineno % lines_per_file == 0:
if smallfile:
smallfile.close(... |
'''
stuff = 'X\nY'
print("stuff[:] 'X\\nY'", stuff[:])
print("stuff", stuff)
print("len(stuff)", len(stuff))
#fhand = open('mboxnoexists.txt')
# print(fhand)
fhand = open('mbox.txt')
print(fhand)
count = 0
for line in fhand:
count = count + 1
print('mbox.txt line count: %d' % count)
# read all data to memory
# fh... |
class Solution:
"""
@param flights: the airline status from the city i to the city j
@param days: days[i][j] represents the maximum days you could take vacation in the city i in the week j
@return: the maximum vacation days you could take during K weeks
"""
def maxVacationDays(self, flights, day... |
# sumOfSquaresReadFromFile.py
# A program computes the sum of the squares of numbers read from a file.
"""Use the functions from the previous three problems to implement a program
that computes the sum of the squares of numbers read from a file. Your program
should prompt for a file name and print out the sum of the s... |
nkpop_list = ["https://www.youtube.com/watch?v=VCrdiTA0RqI",
"https://www.youtube.com/watch?v=S1KIh0MBBX4",
"https://www.youtube.com/watch?v=qhXrye7zkwY",
"https://www.youtube.com/watch?v=lNES9HTJ27U",
"https://www.youtube.com/watch?v=NKIiglf4bfA",
"... |
print('===== DESAFIO 009 =====')
x = int(input('Digite um numero para ser Multiplicado : '))
x1 = 1 * x
x2 = 2 * x
x3 = 3 * x
x4 = 4 * x
x5 = 5 * x
x6 = 6 * x
x7 = 7 * x
x8 = 8 * x
x9 = 9 * x
x10 = 10 * x
print('-' * 12)
print(f'Tabuada \n '
f'{x} x 1 = {x1} \n '
f'{x} x 2 = {x2} \n '
f'{x} x 3 =... |
def solution(numbers, hand):
answer = ''
left = (3,0)
right = (3,2)
_dict = {
1:(0,0),
2:(0,1),
3:(0,2),
4:(1,0),
5:(1,1),
6:(1,2),
7:(2,0),
8:(2,1),
9:(2,2),
0:(3,1)
}
... |
# Copyright (c) 2016 Google Inc. (under http://www.apache.org/licenses/LICENSE-2.0)
"""TypeVar test."""
class UserDict(object):
def __init__(self, initialdata = None):
pass
|
class FactorConf(object):
FACTOR_INIT_VERSION = "INIT_VERSION"
GROUP_FACTOR_PREFIX = "FACTOR_KEEPER_GROUP_FACTOR_"
FACTOR_LENGTH = 4740
@staticmethod
def get_group_factor_name(factors):
factors = sorted(factors)
return FactorConf.GROUP_FACTOR_PREFIX + "#".join(factors)
|
"""
WAP to compute sin(x) for given x. The user should supply x and a positive integer n. We compute the sine of x using
the taylor series and the computation should use all terms in the series up through the term involving
x^n sin(x) = x - x^3/3! + x^5/5! - x^7/7! + x^9/9! ...
3! = 1 * 2 * 3 * (4 * 5) = 5! * (6 * 7) =... |
def map_fn(obj, objs, apply_fn):
if isinstance(obj, dict):
return dict(map(lambda kv: (kv[0], map_fn(kv[1], list(map(lambda x: x[kv[0]], objs)), apply_fn)), obj.items()))
elif isinstance(obj, list):
return list(map(lambda e: map_fn(e[0], e[1:], apply_fn), zip(obj, *objs)))
elif isinstance(obj, tuple):
... |
"""Test vairables"""
debug_string_test = [
"item(1)\n",
"item(1)\n",
"item(1)\n",
"item(1)\n",
"item(1)\n",
"item(1)\n",
"row\n",
"\tcolumn\n",
"\t\titem(1)\n",
"\tcolumn\n",
"\t\titem(1)\n",
"row\n",
"\tcolumn\n",
"\t\titem(1)\n",
"\tcolumn\n",
"\t\titem(... |
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
l = []
for i in range(1,n+1):
if i%15==0 :
l.append("FizzBuzz")
elif i%3 == 0:
l.append("Fizz")
elif i%5 == 0:
l.append("Buzz")
else:
... |
class Solution:
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
length = len(heights)
if length == 0:
return 0
if length == 1:
return heights[0]
if length == 2:
return max(min(he... |
# Não é permitido divisões por 0
a = 2
b = 0
# try = tentar
try:
print(a/b)
# except = exceção
except:
print("Não é pertimitida divisão por 0")
print(a/a)
|
__all__ = ['NamecheapError', 'ApiError']
class NamecheapError(Exception):
pass
# https://www.namecheap.com/support/api/error-codes.aspx
class ApiError(NamecheapError):
def __init__(self, number, text):
Exception.__init__(self, '%s - %s' % (number, text))
self.number = number
self.te... |
def tribo(N):
if N == 0 or N == 1:
return 0
elif N == 2:
return 1
return tribo(N-1) + tribo(N-2)
def main():
N = int(input())
output = tribo(N)
print(output)
if __name__=='__main__':
main() |
"""Integrator functions used when no closed forms are available.
These are designed for second order ODE written as a first order ODE of two
variables (x,v):
dx/dt = v
dv/dt = force(x, v)
"""
def _symplectic_euler_step(state, force, dt):
"""Compute one step of the symplect... |
class dataScientist():
employees = []
def __init__(self):
self.languages = []
self.department = ''
def add_language(self, new_language):
self.languages.append(new_language)
dilara = dataScientist()
pitircik = dataScientist()
pitircik.add_language("R")
print(pitircik.languag... |
# encoding: utf-8
# module array
# from (built-in)
# by generator 1.147
"""
This module defines an object type which can efficiently represent
an array of basic values: characters, integers, floating point
numbers. Arrays are sequence types and behave very much like lists,
except that the type of objects stored in the... |
'''
签到系统配置文件
'''
LUCKY_MIN = 1
'''每日运势最小值'''
LUCKY_MAX = 5
'''每日运势最大值'''
FRIENDLY_ADD = 1
'''每次签到获得的好感度'''
GOLD_BASE = 10
'''每次签到金币底薪'''
LUCKY_GOLD = 1
'''幸运值影响金币因子'''
|
class html:
def __init__(self, line) -> None: #("# oi # <teddy>oi</teddy> # oi # <teddy>5</teddy> %")
self.line = line
self.tm = []
self.tl = []
self.start(self.line + ' ')
def start(self, line):
before = line[:line.find('<teddy>')]
# "# oi... |
n = int(input())
ans = 0
if n >= 1000:
ans += n - 999
if n >= 1000000:
ans += n - 999999
if n >= 1000000000:
ans += n - 999999999
if n >= 1000000000000:
ans += n - 999999999999
if n >= 1000000000000000:
ans += n - 999999999999999
print(ans)
|
#3. 利用map()函数将用户输入的不规范的英文名字,变为首字母大写,其他字符小写的形式
# 1) 假定用户输入的是["lambDA", “LILY”, “aliCe”]
def myf(a):
for i in a:
return a[:1].upper()+a[1:].lower()
l = ["lambDA","LILY","aliCe"]
l1 =list(map(myf,["lambDA","LILY","aliCe"]))
print(l1)
|
"""
:synopsis: Supported metric calculations to use on validation data with NPU API for training.
.. moduleauthor:: Naval Bhandari <naval@neuro-ai.co.uk>
"""
Accuracy = "Accuracy"
# Binary_accuracy = "Binary_accuracy"
# Binary_cross_entropy = "Binary_cross_entropy"
# Categorical_accuracy = "Categorical_accuracy"
Categ... |
def pluralize(word,num):
if num > 1:
if word [-3:]== "ife" :
return( word[:-3] + "ives")
elif word[-2:] == "sh" or word[-2:] == "ch" :
return( word + "es")
elif word[-2:] == "us":
return(word[:-2] + "i")
elif word[-2:] == "ay" or word[-2:] == "oy"... |
for col in numerical_feats:
print('{:15}'.format(col),
'Skewness: {:05.2f}'.format(df_train[col].skew()),
' ',
'Kurtosis: {:06.2f}'.format(df_train[col].kurt())
)
# 수치형 변수의 Skewness(비대칭도), Kurtosis(첨도)를 확인합니다.
# 이는 분포가 얼마나 비대칭을 띄는가 알려주는 척도입니다. (비대칭도: a=0이면 정규분포, a<0 이면 오른쪽... |
class Token(object):
def __init__(self, symbol, spec, line):
self.symbol = symbol
self.spec = spec
self.line = line
if spec == 'error':
self.value = symbol
elif spec == 'const':
self.value = int(symbol)
elif spec == 'OCT':
self.valu... |
template = {
'dns': {},
'inbounds':
[
{
'listen': '0.0.0.0',
'port': 1080,
'protocol': 'socks',
'settings': {
'auth': 'noauth',
'udp': True
}
},
{
... |
def exibe(v, n):
for i in range(n):
print(v[i], end=' ')
print('')
def troca(v, i, j):
v[i],v[j] = v[j],v[i]
def empurra(v, n):
for i in range(n - 1):
if v[i] > v[i+1]:
troca(v, i, i+1)
def bubble_sort(v, n):
exibe(v, n)
tam = n
while tam > 1:
empurr... |
"""
A decorator that allows you to specify a set of keyword arguments that
are required by the function. If any are missing, an exception is
raised which lists the missing arguments.
::
@required_arguments(bar='bar', baz='qux')
def my_function(x, y, bar=None, baz=None):
...something...
Invoking the ... |
""" This submodule implements a class that can manipulate numbers """
class NumManip:
"""This class implements a few different types of methods to manipulate numbers
Variables:
class_variable (int): A simple integer
Attributes:
num1 (int, float): The first number
num2 (int, float)... |
n=input()
for i in n:
a=int(i)
if(a%2!=0):
print(i,end="")
|
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
# The smallest happy number after 1 is 7
while n > 6:
# Split n into a list of squared digits
squared_digits = [int(x) ** 2 for x in str(n)]
# Recurse ... |
class Bunch(dict):
"""
Dictionary-like object returned when fetching data sets.
Some common options:
Option | Type | Description | Default
------ | ---- | ----------- | -------
data | List[Any] | An array of data for a set of instances | List[]
instance | Optional[Any] | Data for a specifi... |
class Node:
def __init__(self, code, id, name, definition, version, revision, superclass, dictionary_code):
self.code = code
self.id = id
self.name = name
self.definition = definition
self.version = version
self.revision = revision
self.superclass = superclas... |
with open("subreddits_list.txt", "r") as f:
subreddits = f.read().splitlines()
with open("script.sql", "w") as f:
for i in subreddits:
f.write(
f"CREATE TABLE IF NOT EXISTS '{i}' (Name text, Date text, Subscribers int, Live_Users int);\n"
f"INSERT INTO '{i}' SELECT * FROM measur... |
def parse(raw):
depth = 0
start = 0
pairs = []
for idx, ch in enumerate(raw):
if ch == '<':
depth += 1
if depth == 1:
pairs.append([start, idx])
elif ch == '>':
depth -= 1
if depth <= 0 and start == -1:
start = idx
res = []
for pair in pairs:
if pair[1] - pair[0] >= 10:
res.append(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.