content stringlengths 7 1.05M |
|---|
# Adds testing.TestEnvironment provider if "env" attr is specified
# https://bazel.build/rules/lib/testing#TestEnvironment
def phase_test_environment(ctx, p):
test_env = ctx.attr.env
if test_env:
return struct(
external_providers = {
"TestingEnvironment": testing.TestEnviro... |
# coding: utf-8
"""
.. _available-parsers:
Available Parsers
=================
This package contains a collection of parsers which you can use in conjonction
with builders to convert tables from one format to another.
You can pick a builder in the :ref:`Available Builders <available-builders>`.
"""
|
def keyquery():
return( set([]) )
def getval(prob):
return( prob.file )
|
#!/usr/bin/env python3
print('1a')
print('1b')
print('2a\n')
print('2b\n')
print('3a\r\n')
print('3b\r\n')
print('4a\r')
print('4b\r')
print('5a\n\r')
print('5b\n\r')
|
# You are given a string and your task is to swap cases.
# In other words, convert all lowercase letters to uppercase letters and vice versa.
def swap_case(s):
return s.swapcase()
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) |
# uncompyle6 version 3.7.2
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
# Embedded file name: extract__one_file_exe__pyinstaller\_test_file.py
__author__ = 'ipetrash'
def say():
print('Hello World!')
if __name__ == '__main__':
say() |
input = """
d(1).
d(2).
d(3).
d(4) :- #min{V : d(V)} = 1.
"""
output = """
d(1).
d(2).
d(3).
d(4) :- #min{V : d(V)} = 1.
"""
|
"""
Count the number of inversions in a sequence of orderable items.
Description:
Informally, when we say inversion we mean inversion from the (ascending)
sorted order.
For a more formal definition, let's call the list of items L. We call
inversion a pair of indices i, j with i < j and L[i] > L[j], where L... |
# Law of large number
# How to get first line input
n, m, k = map(int, input().split())
data = list(map(int, input().split()))
solution = 0
count_use_max_value = 0
data.sort(reverse=True)
for i in range(0, m):
if count_use_max_value >= k:
solution += data[1]
count_use_max_value = 0
else:
... |
# FIXME need to fix TWO_RIG_AX_TO_MOVE here; empirically-derived, like we did with safe trajectories
# define rig_ax to be moved to achieve either min or max given that we are at designated rough home position
TWO_RIG_AX_TO_MOVE = {
# rough_home ax1 min max ax2 min max
'+x': [('pitch', ... |
# 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 preorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
... |
def lambda_handler(event, context):
n = int(event['number'])
n = n * -1 if n < 0 else n
subject = event.get('__TRIGGERFLOW_SUBJECT', None)
return {'number': n, '__TRIGGERFLOW_SUBJECT': subject}
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class UpdateLinuxPasswordReqParams(object):
"""Implementation of the 'UpdateLinuxPasswordReqParams' model.
Specifies the user input parameters.
Attributes:
linux_current_password (string): Specifies the current password.
linux_passw... |
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:shell.bzl", "shell")
def _addlicense_impl(ctx):
out_file = ctx.actions.declare_file(ctx.label.name + ".bash")
exclude_patterns_str = ""
if ctx.attr.exclude_patterns:
exclude_patterns = ["-not -path %s" % shell.quote(pattern) fo... |
class Solution:
def findComplement(self, num: int) -> int:
res =i = 0
while num:
if not num & 1:
res |= 1 << i
num = num >> 1
i += 1
return res
class Solution:
def findComplement(self, num: int) -> int:
i = 1
while i <=... |
'''
给你一个整数 x ,如果 x 是一个回文整数,返回 ture ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x % 10 == 0 and x != 0):
return False
revertedNumber = 0
while x > revertedNumber:
reverte... |
class C:
def foo(self):
pass
class D:
def bar(self):
pass
class E:
def baz(self):
pass
def f():
return 0
def g():
return
x = (C(), D(), E())
a, b, c = x
x[0].bar() # NO bar
x[1].baz() # NO baz
x[2].foo() # baz
a.bar() # NO bar
b.baz() # NO baz
c.foo() # NO ... |
# 2019-01-15
# csv file reading
f = open('score.csv', 'r')
lines = f.readlines()
f.close()
for line in lines:
total = 0
count = 0
scores = line[:-1].split(',')
# print(scores)
for score in scores:
total += int(score)
count += 1
print("Total = %3d, Avg = %.2f" % (total, t... |
#
# PySNMP MIB module INTEL-RSVP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTEL-RSVP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:43:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
"""
For each character in the `S` (if it is not a number), it has 2 possibilities, upper or lower.
So starting from an empty string
We explore all the possibilities for the character at index i is upper or lower.
The time complexity is `O(2^N)`.
The space took `O(2^N), too. And the recursion level has N level.
"""
cla... |
def create_mapping(table_name):
"""
Return the Elasticsearch mapping for a given table in the database.
:param table_name: The name of the table in the upstream database.
:return:
"""
mapping = {
'image': {
"mappings": {
"doc": {
"properties"... |
aluguel = float(input('Quantidade de km rodados: '))
dias = int(input('Números de dias em que o carro foi alugado: '))
pago = (dias * 60) + (aluguel *0.15)
print('O total a pagar é R${:.2f}'.format(pago))
""" ALUGUEL DE CARROS """ |
print('*---*'*10)
print ('programa que le dois numeros e diz qual é o maior')
print('-----'*10)
num1=int(input('digite um numero'))
num2=int(input('digite um numero'))
if num1 > num2:
print(' {} é maior que {}'.format(num1,num2))
elif num2 > num1:
print(' {} é maior que {}'.format(num2, num1))
else:
pri... |
"""
Clear separation of the near universal extensions API from the default
implementations.
"""
|
# Algorithms > Bit Manipulation > Counter game
# Louise and Richard play a game, find the winner of the game.
#
# https://www.hackerrank.com/challenges/counter-game/problem
#
pow2 = [1 << i for i in range(63, -1, -1)]
def counterGame(n):
player = 0
while n != 1:
# print( ["Louise", "Richard"][player]... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
def sub_report():
print("Hey, I'm a function inside my subscript.") |
# -*- coding: utf-8 -*-
TOTAL_SESSION_NUM = 2
REST_DURATION = 5 * 60
BLOCK_DURATION = 2 * 60
MINIMUM_PULSE_CYCLE = 0.5
MAXIMUM_PULSE_CYCLE = 1.2
PPG_SAMPLE_RATE = 200
PPG_FIR_FILTER_TAP_NUM = 200
PPG_FILTER_CUTOFF = [0.5, 5.0]
PPG_SYSTOLIC_PEAK_DETECTION_THRESHOLD_COEFFICIENT = 0.5
BIOPAC_HEADER_LINES = 11
BIOPAC_... |
# Link to the problem: https://www.codechef.com/problems/STACKS
def binary_search(arr, x):
l = 0
r = len(arr)
while l < r:
mid = (r + l) // 2
if x < arr[mid]:
r = mid
else:
l = mid + 1
return l
def main():
T = int(input())
while T:
T ... |
class CorruptedStateSpaceModelStructureException(Exception):
pass
class CorruptedStochasticModelStructureException(Exception):
pass
|
API_ACCESS = 'YOUR_API_ACCESS'
API_SECRET = 'YOUR_API_SECRET'
BTC_UNIT = 0.001
BTC_AMOUNT = BTC_UNIT
CNY_UNIT = 0.01
CNY_STEP = CNY_UNIT
DIFFERENCE_STEP = 2.0
MIN_SURPLUS = 0.5
NO_GOOD_SLEEP = 15
MAX_TRIAL = 3
MAX_OPEN_ORDERS = 3
TOO_MANY_OPEN_SLEEP = 10
DEBUG_MODE = True
REMOVE_THRESHOLD = 20.0
REMOVE_UNREA... |
# # 에라스토테네스의 채를 이용한 소수 구하는 함수
# def get_prime(min_num, max_num):
# primes = [True] * max_num # 주어진 개수만큼 배열 생성 (임의로 전부다 프라임으로 취급한다.)
# m = int(max_num ** 0.5) # 제곱글응 이용하여 작은 수로 만든다.
# for i in range(2, m + 1): # 1과 2는 소수이니 그 다음 숫자부터 주어진 숫자까지 반복문을 돈다.
# if primes[i]:
# for j in range... |
'''
Description: python solution of AddTwoNumbers (https://leetcode-cn.com/problems/add-two-numbers/)
Author: Kotori Y
Date: 2021-04-20 16:49:38
LastEditors: Kotori Y
LastEditTime: 2021-04-20 16:51:04
FilePath: \LeetCode-Code\codes\LinkedList\AddTwoNumbers\AddTwoNumbers.py
AuthorMail: kotori@cbdd.me
'''
# Definition f... |
"""
DFS Steps:
- create and empty stack and and list of explored elements
- take the starting element and push it into the stack and add it to the visited list
- check if it has any children that are unvisited.
- if it has unvisited kids, pick one and add it to the top of the stack and the visited list
- recursively ch... |
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) < 3: return max(nums)
n = len(nums)
ans1 = self.robHouse(nums[:n-1])
ans2 = self.robHouse(nums[1:])
return max(ans1, ans2)
def robHouse(self, nums):
prev, curr = 0, 0
for num... |
class Source:
'''
this is a class that defines the source objects
'''
def __init__(self,id,name,url,description):
self.id = id
self.name = name
self.url = url
self.description = description |
""" Summary
"""
class Solution(object):
"""
Problem:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
... |
num = int(input('Digite o numero para ser convertido: '))
print('-='*10)
print('''Qual base de conversão?
[ 1 ] Binário
[ 2 ] Octal
[ 3 ] hexadecimal
''')
print('-='*10)
opcao = int(input('Digite sua opcao: '))
if opcao == 1:
print('O número {} foi convertido para {}'.format(num,bin(num)))
elif opcao == ... |
# -*- coding: utf-8 -*-
def production_volume(dataset, default=None):
"""Get production volume of reference product exchange.
Returns ``default`` (default value is ``None``) if no or multiple
reference products, or if reference product doesn't have a production
volume amount."""
exchanges = [x fo... |
# Warning : Keep this file private
# replace the values of the variables with yours
ckey = 'SaMpLe-C0nSuMeR-Key'
csecret = 'Y0uR-C0nSuMeR-SecRet'
atoken = 'Y0Ur-@cCeSs-T0Ken'
asecret = 'Y0uR-@cCesS-SeCrEt'
|
def filtering_results(results, book_type, number):
"""
results = list of dictionnary
Filter the results to getspecific type trade / issue
include omnibus and compendium in trades
and number
Based on comic title
"""
assert book_type in ["trade", "issue", None] , "Choose between ... |
def shallow_copy(x):
return type(x)(x)
class ToggleFilter(object):
"""
This class provides a "sticky" filter, that works by "toggling" items of the original database on and off.
"""
def __init__(self, db_ref, show_by_default=True):
"""
Instantiate a ToggleFilter object
:p... |
"""
Specializer to support generating Python libraries from swig sources.
"""
load("@fbcode_macros//build_defs/lib/swig:lang_converter_info.bzl", "LangConverterInfo")
load(
"@fbcode_macros//build_defs/lib:python_typing.bzl",
"gen_typing_config",
"get_typing_config_target",
)
load("@fbcode_macros//build_def... |
def main():
def expand(code,times):
return times * code
def expandString(code):
lbi = 0
rbi = 0
for i in range(len(code)):
if(code[i] == "["):
lbi = i
if(code[i] == "]"):
rbi = i
break
count = 1
while code[lbi-count].isdigit():
if(count == 1):
... |
class MyDictSubclass(dict):
def __init__(self):
dict.__init__(self)
self.var1 = 10
self['in_dct'] = 20
def __str__(self):
ret = []
for key, val in sorted(self.items()):
ret.append('%s: %s' % (key, val))
ret.append('self.var1: %s' % (self.var1,))
... |
class MessageParsingError(Exception):
"""Message format is not compliant with the wire format"""
def __init__(self, message: str, error: Exception = None):
self.error = error
self.message = message
class SchemaParsingError(Exception):
"""Error while parsing a JSON schema descriptor."""
... |
class QueryFileHandler:
@staticmethod
def load_queries(file_name: str):
file = open(file_name, 'r')
query = file.read()
file.close()
query_list = [s and s.strip() for s in query.split(';')]
return list(filter(None, query_list))
|
K = int(input())
result = 0
for A in range(1, K + 1):
for B in range(1, K + 1):
if A * B > K:
break
result += K // (A * B)
print(result)
|
# 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 agreed to in writing, software
# d... |
"""
curso Python 3 - Exercício Python #014
crie um programa que converta a temperatura em graus ºC para ºF
25.10.2020 - Felipe Ferreira de Aguiar
"""
#! a formula pode ser também (temp_c * 1.8) + 32
temp_c = float(input('Digite a temperatura em graus Celsius '))
temp_f = (( temp_c * 9 ) / 5) + 32
print('... |
"""
Simple module for calculating and displaying the time an algorithm for
a given Euler problem took to run
Author: Miguel Rentes
"""
def elapsed_time(elapsed):
"""
Computes the amount of time spent by the algorithm and outputs the time
"""
hours = int(elapsed / 3600) # hours
minutes = int((elap... |
# import requests
# from bs4 import BeautifulSoup
# with open('file:///home/shubham/fridaybeautifulsoup.html','r')
# def table(a,b):
# if a==1 :
# return 1
# return b*table(a-1,b)
# print(table(10,5))
# def pow(n) :
# if n==1 :
# return 2**n
# return 2*pow(n-1)
# # print(pow(3))
# d... |
class NetworkException(Exception):
pass
class SecretException(Exception):
pass
|
# -*- coding: utf-8 -*-
"""
A sample of kay settings.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
DEBUG = False
ROOT_URL_MODULE = 'kay.tests.globalurls'
INSTALLED_AP... |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
"""
class NgramUtil(object):
@staticmethod
def unigrams(words):
"""
Input: a list of words, e.g., ["I", "am", "Denny"]
Output: a list of unigram
"""
assert type(words) == list
return wor... |
st=input("Enter the binary string\n")
l=len(st)
a=[]
for i in range(l-1,-1,-1):
if a==[]:
a.append(st[i])
else:
p=a.pop()
if st[i] != p:
a.append(p)
a.append(st[i])
if len(a)==0:
print(-1)
else:
for i in range(len(a)):
print(a.pop(),end="")
|
# Project Euler #6: Sum square difference
n = 1
s = 0
s2 = 0
while n <= 100:
s += n
s2 += n * n
n += 1
print(s * s - s2)
|
# https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks/problem
class MyQueue(object):
def __init__(self):
self.one = []
self.two = []
def peek(self): return self.two[-1]
def pop(self): return self.two.pop()
def put(self, value): self.one.append(value)
def check(sel... |
line = input()
while not line == "Stop":
print(line)
line = input()
|
# coding=utf-8
class App:
DEBUG = False
TESTING = False
|
total_cost = input("Enter the cost of your dream house: ")
total_cost = float(total_cost)
annual_salary = input("Enter your annual income: ")
annual_salary = float(annual_salary)
portion_saved = input("Enter the percent of your income you will save: ")
if portion_saved.find("%") or portion_saved.startswith("%") :
... |
def metade(p):
r = p / 2
return r
def dobro(p):
r = p * 2
return r
def aumentar(p, taxa):
r = p + ((p * taxa) / 100)
return r
def diminuir(p, taxa):
r = p - ((p * taxa) / 100)
return r
|
#!/usr/bin/python3
__author__ = "yang.dd"
"""
example 088
"""
if __name__ == "__main__":
n = 0
while n < 7:
a = int(input("请输入一个数字:"))
while a < 1 or a > 50:
a = int(input("请输入一个数字:"))
print(a * "*")
n += 1
|
# Copyright (c) 2019 The Bazel Utils Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This function is taken from
# LICENSE: BSD
# URL: https://github.com/RobotLocomotion/drake/blob/47987499486349ba47ece6f30519aaf8f868bbe9/tools/skyla... |
"""
You're given a string consisting solely of (, ), and *. * can represent either a (, ),
or an empty string. Determine whether the parentheses are balanced.
For example, (()* and (*) are balanced. )*( is not balanced.
"""
def is_balanced(text: str) -> bool:
size = len(text)
index = 0
stack = []
whi... |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
class ReasonedBool:
'''
A variation on `bool` that also gives a `.reason`.
This is useful when you want to say "This is False because... (reason.)"
Unfortunately this class is not a subclass of `bool`, since Pytho... |
def test():
assert nlp.meta["name"] == "core_news_sm", "正しいパイプラインをロードしましたか?"
assert nlp.meta["lang"] == "ja", "正しいパイプラインをロードしましたか?"
assert "print(nlp.pipe_names)" in __solution__, "パイプラインの名前をプリントしましたか?"
assert "print(nlp.pipeline)" in __solution__, "パイプラインをプリントしましたか?"
__msg__.good(
"Well do... |
form = 'form.signin'
form_username = 'form.signin [name="session[username_or_email]"]'
form_password = 'form.signin [name="session[password]"]'
form_phone = '#challenge_response'
def login(browser, username, password):
browser.fill(form_username, username)
# For some reason filling of the password is flaky a... |
while True:
try:
n = int(input())
if ((n >= 0 and n < 90) or n == 360):
print('Bom Dia!!')
elif (n >=90 and n < 180):
print('Boa Tarde!!')
elif (n >= 180 and n < 270):
print('Boa Noite!!')
elif (n >= 270 and n < 360):
print('De ... |
class PytraitError(RuntimeError):
pass
class DisallowedInitError(PytraitError):
pass
class NonMethodAttrError(PytraitError):
pass
class MultipleImplementationError(PytraitError):
pass
class InheritanceError(PytraitError):
pass
class NamingConventionError(PytraitError):
pass
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"URL": "00_downloading_pdfs.ipynb",
"PDF_PATH": "00_downloading_pdfs.ipynb",
"identify_links_for_pdfs": "00_downloading_pdfs.ipynb",
"download_file": "00_downloading_pdfs.ipynb",
... |
# SPDX-FileCopyrightText: 2020 Jim Bennet for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`HMAC`
================================================================================
HMAC (Keyed-Hashing for Message Authentication) Python module.
Implements the HMAC algorithm as described by RFC 2104.
This is... |
SD_COMMENT="This is for local development"
SHELTERLUV_SECRET_TOKEN=""
APP_SECRET_KEY="ASKASK"
JWT_SECRET="JWTSECRET"
POSTGRES_PASSWORD="thispasswordisverysecure"
BASEUSER_PW="basepw"
BASEEDITOR_PW="editorpw"
BASEADMIN_PW="basepw"
DROPBOX_APP="DBAPPPW"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
'''
def _jupyter_server_extension_paths():
return [{
'module':'nbtemplate'
}];
def _jupyter_nbextension_paths():
return [
dict(
section='notebook',
src='static', # path is relative to `nbtemplate` directo... |
"""
58.翻转单词顺序.py
时间复杂度:O(n)
空间复杂度:O(n)
"""
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
return " ".join(s.split(" ")[::-1])
if __name__ == "__main__":
string = "I am a student."
s = Solution()
ret = s.ReverseSentence(string)
print(ret) |
def loadLinux_X86_64bit(visibility=None):
native.new_local_repository(
name = "system_include_x86_64_linux",
path = "/usr/include",
build_file_content = """
cc_library(
name = "soundcard",
hdrs = ["soundcard.h"],
visibility = ["//visibility:public"],
)
cc_library(
name = "ioc... |
"""
PERIODS
"""
numPeriods = 180
"""
STOPS
"""
numStations = 13
station_names = (
"Hamburg Hbf", # 0
"Landwehr", # 1
"Hasselbrook", # 2
"Wansbeker Chaussee*", # 3
"Friedrichsberg*", # 4
"Barmbek*", # 5
"Alte Woehr (Stadtpark)", # 6
"Ruebenkamp (City Nord)", # 7
"Ohlsdorf*", # 8
"Kornweg", # 9
... |
S = input()
T = input()
i = 0
for s, t in zip(S, T):
if s!=t:
i += 1
print(i)
|
# Soccer field easy
soccer_easy_gate_pose_dicts = [ { 'orientation': { 'w_val': 1.0,
'x_val': -0.0,
'y_val': 0.0,
'z_val': 0.0},
'position': { 'x_val': 0.0,
'y_val': 2.0,
'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.9659256935119629,
'x_val': 0.0,
'y_val': -... |
print ('WELCOME TO THE COLLATZ SEQUENCER: ALWAYS NUMBER 1')
print ('ENTER YOUR NUMBER AND PREPARE TO GET SEQUENCED')
numberToSequence = input()
def tryCollatz(numberToSequence):
collatzCalled = False
while(collatzCalled == False):
try:
numberToSequence = int(numberToSequence)
... |
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def example():
# Computer 2 + 3 * 0.1
code = [
('const', 2),
('const', 3),
('const', 0.1),
... |
def solution(board, moves):
answer = 0
# transpose
board = [list(x)for x in zip(*board)]
# 뽑은 인형 리스트
res = []
for lane in moves:
# 칸에서 인형을 다 뽑아서 없는 경우
if (board[lane-1] == []):
continue
# 0이 아닐때까지 계속 뽑기
while True:
a = board[lane-1].pop... |
def formulUygula(derece, liste):
mat = []
xDeg = 0
for i in range(derece + 1):
mat1 = []
for j in range(derece + 1):
gecici = 0
for k in range(1, len(liste) + 1):
gecici += k ** xDeg
mat1.append(gecici)
xDeg += 1
mat.app... |
# TODO: un-subclass dict in favor of something more explicit, once all regular
# dict-like access has been factored out into methods
class LineManager(dict):
"""
Manages multiple release lines/families as well as related config state.
"""
def __init__(self, app):
"""
Initialize new line... |
def LeiaDinheiro(msg):
valido = False
while not valido:
mens = str(input(msg)).replace(',', '.')
if mens.isalpha() or mens.strip() == '':
print("\033[31mERRO! tente algo valido\033[m")
else:
valido = True
return float(mens) |
"""
Problem 5 - https://adventofcode.com/2021/day/5
Part 1 -
Given a list of lines on a 2D graph, find the number of integral points where at least 2 horizontal or vertical
lines intersect
Part 2 -
Given the same set up, find the number of integral points where at least 2 horizontal, vertical, or diagonal... |
#
# PySNMP MIB module AT-DS3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-DS3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:13:43 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:... |
# closures
def make_averagr():
series = []
def averager(new_value):
series.append(new_value) # free variable
total = sum(series) / len(series)
return total
return averager
# print(locals())
av = make_averagr()
print(av(10))
print(av(11))
print(av.__code__.co_varnames)
# ('n... |
# Public Key
PK = "fubotong"
# Push request actively
PUSH = 0
# Secret Key
SK = "(*^%]@XUNLEI`12f&^"
# procotol type
HTTP = 1
ED2K = 2
BT = 3
TASK_SERVER = "http://open.lixian.vip.xunlei.com/download_to_clouds"
#TASK_SERVER = "http://t33093.sandai.net:8028/download_to_clouds"
CREATE_SERVER = "%s/create" % TASK_SE... |
def kth_common_divisor(a, b, k):
min_ = min(a, b)
divisors = []
for i in range(1, min_+1):
if a % i == 0 and b % i == 0:
divisors.append(i)
return divisors[-k]
if __name__ == "__main__":
a, b, k = map(int, input().split())
print(kth_common_divisor(a, b, k))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 16:11:15 2021
@author: qizhe
"""
class Solution:
def spiralOrder(self, matrix):
"""
读题:
1、这题一看就有思路啊,就是一个循环加换向的感觉,能不能有更简单的思路
2、螺旋之后,边界变了,不是很简单,要想办法处理边界
思路:
1、如果不顾空间,就开一个一模一样的数组,用来存储True or False
2、如果顾空间,需要保存每行... |
"""
SYSTEM_PARAMETERS
"""
EPSILON = 1E-12
#DEFAULT_STREAM_SIZE = 2**24
DEFAULT_STREAM_SIZE = 2**12
DEFAULT_BUFFER_SIZE_FOR_STREAM = DEFAULT_STREAM_SIZE / 4
|
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
class Foo:
def __init__(self, arg1: str, arg2: int) -> None:
self.arg1 = arg1
self.arg2 = arg2
|
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
nlow, nhigh = len(str(low)), len(str(high))
s = '123456789'
result = []
for n in range(nlow, nhigh+1):
for i in range(9-n+1):
num = int(s[i:i+n])
... |
"""
This module defines a utility interface called WMInterface
which defines a standard interface for adding and removing things from working memory
"""
class WMInterface(object):
""" An interface standardizing how to add/remove items from working memory """
def __init__(self):
self.added = False
... |
no = int(input('How many Natural Numbers do You Want?? '))
output = 0
i = 0
while i <= no:
output = output + i*i
i += 1
print(output)
|
class Log():
def log(self,text):
pass
def force_p(self,text):
print(text)
class Print(Log):
def log(self,text):
print(text)
class NoLog(Log) :
def log(self,text):
pass
class MessageLog(Log):
def set_channel(self,channel):
self.channel = channel
async def log(self,text):
await self.channel.sen... |
class Solution(object):
def update(self, board, row, col):
living = 0
for i in range(max(row-1, 0), min(row+2, len(board))):
for j in range(max(col-1, 0), min(col+2, len(board[0]))):
living += board[i][j] & 1
if living == 3 or (living == 4 and board[row][col]):
... |
__all__ = ["State"]
class State:
def __init__(self, value: str):
self.value = value
def __eq__(self, other):
if not isinstance(other, State):
return False
else:
return self.value == other.value
def __hash__(self):
return hash(self.value)
|
counts = {
"FAMILY|ID": 3,
"PARTICIPANT|ID": 3,
"BIOSPECIMEN|ID": 3,
"GENOMIC_FILE|URL_LIST": 3,
}
validation = {}
|
# Create a global variable.
my_value = 10
# The show_value function prints
# the value of the global variable.
def show_value():
print(my_value)
# Call the show_value function
show_value()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.