content
stringlengths
7
1.05M
r=s=t=1 #--- I1 print(r + s + t) r=s=t='1' #--- I2 print(r + s + t)
"""Genetic Programming in Python, with a scikit-learn inspired API ``gplearn`` is a set of algorithms for learning genetic programming models. """ __version__ = '0.4.dev0' __all__ = ['genetic', 'functions', 'fitness'] print("GPLEARN MOD")
n = int(input('Digite o número que deseja a tabuada: ')) for c in range(1, 11): print('{} X {} = {}'.format(n, c, n*c))
_base_ = '../../base.py' # model settings model = dict( type='Classification', pretrained=None, backbone=dict( type='ResNet', depth=50, out_indices=[4], # 4: stage-4 norm_cfg=dict(type='BN')), head=dict( type='ClsHead', with_avg_pool=True, in_channels=2048, num_c...
class BruteForceProtectionException(Exception): pass class BruteForceProtectionBanException(BruteForceProtectionException): pass class BruteForceProtectionCaptchaException(BruteForceProtectionException): pass
string = "John Doe lives at 221B Baker Street." pattern = re.compile(r""" ([a-zA-Z ]+) # Save as many letters and spaces as possible to group 1 \ lives\ at\ # Match " lives at " (?P<address>.*) # Save everything in between as a group named `address` \. # Match the period at th...
class LanguageModel: def infer(x): """Run language model on input x Args: x (str): Prompt to run inference on Returns: (str) Output of inference """ return prompt
# Copyright 2016 x620 <https://github.com/x620> # Copyright 2016,2020 Ivan Yelizariev <https://it-projects.info/team/yelizariev> # Copyright 2018 Ruslan Ronzhin # Copyright 2019 Artem Rafailov <https://it-projects.info/team/Ommo73/> # License LGPL-3.0 (https://www.gnu.org/licenses/lgpl.html). { "name": """Show mess...
"""Config file tools for edx_lint.""" def merge_configs(main, tweaks): """Merge tweaks into a main config file.""" for section in tweaks.sections(): for option in tweaks.options(section): value = tweaks.get(section, option) if option.endswith("+"): option = optio...
model = Model() i1 = Input("input", "TENSOR_FLOAT32", "{1, 2, 2, 1}") axis = Parameter("axis", "TENSOR_INT32", "{1}", [2]) keepDims = False output = Output("output", "TENSOR_FLOAT32", "{1, 2, 1}") model = model.Operation("REDUCE_MIN", i1, axis, keepDims).To(output) # Example 1. Input in operand 0, input0 = {i1: # inp...
# https://leetcode.com/problems/subrectangle-queries class SubrectangleQueries: def __init__(self, rectangle): self.rectangle = rectangle def updateSubrectangle(self, row1, col1, row2, col2, newValue): for row in range(row1, row2 + 1): for col in range(col1, col2 + 1): ...
entries = [ { "env-title": "atari-alien", "env-variant": "No-op start", "score": 6482.10, }, { "env-title": "atari-amidar", "env-variant": "No-op start", "score": 833, }, { "env-title": "atari-assault", "env-variant": "No-op start", ...
class BaseViewTemplate(): def get_template(self): if self.request.user.is_authenticated: template = "core/base.html" else: template = "core/base-nav.html" return template
class Parent(object): """A simple example class""" # 클래스 정의 시작부분에 """...""" 도큐먼트 스트링 def __init__(self): # 컨스트럭터 (생성자) self.name = "Kim" def override(self): # override() 메소드 print("PARENT override()") def implicit(self): ...
{ "roadMapId" : "2", "mapIds" : { "1" : { "parameter" : [ "-l" ], "code" : "import json\ndef eventHandler(event, context, callback):\n\tjsonString = json.dumps(event)\n\tprint(jsonString)\n\tif event[\"present\"] == \"person\":\n\t\tprint(\"OK\")...
# program to converte API text file to markdown for wiki. all_apis = [] with open("stepspy_api.txt","rt") as fid_api: api = [] line = fid_api.readline().strip() api.append(line) while True: line = fid_api.readline() if len(line)==0: if len(api) != 0: all_apis....
type_input = input() symbol = input() def int_type(num): number = int(num) result = number * 2 print(result) def real_type(num): number = float(num) result = number * 1.5 print(f"{result:.2f}") def string_type(text): string = "$" + text + "$" print(string) if type_input == "int":...
class Settings: '''存储设置的类''' def __init__(self): # 屏幕设置 self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) self.score_scale = 1.5 # 子弹设置 self.bullet_width = 300 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullets_allowed = 3 #...
class Wrapper: "Wrapper to disable commit in sqla" def __init__(self, obj): self.obj = obj def __getattr__(self, attr): if attr in ["commit", "rollback"]: return lambda *args, **kwargs: None obj = getattr(self.obj, attr) if attr not in ["cursor", "execute"]: ...
load("@bazel_skylib//lib:paths.bzl", "paths") load("@bazel_skylib//lib:shell.bzl", "shell") load("@fbcode_macros//build_defs/config:read_configs.bzl", "read_choice") load("@fbcode_macros//build_defs/lib:allocators.bzl", "allocators") load("@fbcode_macros//build_defs/lib:build_info.bzl", "build_info") load("@fbcode_macr...
''' Given a list of non negative integers, arrange them such that they form the largest number. Example 1: Input: [10,2] Output: "210" Example 2: Input: [3,30,34,5,9] Output: "9534330" Note: The result may be very large, so you need to return a string instead of an integer. ''' class Solution(object): def large...
class Pessoa: olhos = 2 # atributo de classe def __init__(self, *filhos, nome=None, idade=35): # atributos de instância self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá {id(self)}.' @staticmethod def metodo_estat...
class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: result = [] if not words or not pattern: return result for word in words: mapping = {} isMapped = True for i, c in enum...
CONSUMER_KEY = 'WVQrIJcorH11hQoP6mHKvXIZJ' CONSUMER_SECRET = 'Ui3V1dEsa5owJnhu3nLNyqdz2hFf6HmvICPObiShmkzBszKnah' ACCESS_TOKEN = '218405160-0iabe9XqpwAJ4z4BYsaXwH3ydKpFZhnzj5xpHxpI' ACCESS_SECRET = 'PdPNfcgkc5x7TO54cxVjGOjSrqY2jbcaayV46ys9IkLj3'
var.nexus_allowAllDigitNames = True # put it somewhere else var.doCheckForDuplicateSequences = False t = var.trees[0] a = var.alignments[0] t.data = Data() t.model.dump() print('\nAfter optimizing, the composition of the model for the non-root nodes is:') print(t.model.parts[0].comps[0].val) print('...and:') prin...
""" A very basic study on variables, their types and some operators """ # defining variables and values integer_value, floatValue, boolean_value = 36, 5.3, True adition = integer_value + floatValue division = integer_value / floatValue exponention1 = 3 ** 3 exponention2 = 27 ** (1 / 3) floor = integer_value // flo...
''' 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。 如果不存在最后一个单词,请返回 0 。 说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。   示例: 输入: "Hello World" 输出: 5 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/length-of-last-word ''' class Solution: def lengthOfLastWord(self, s: str) -> int: if ...
# # PySNMP MIB module HUAWEI-DATASYNC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-DATASYNC-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:43:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
def main(name="User", name2="Your Pal"): print(f"Hello, {name}! I am {name2}!") if __name__=="__main__": main()
# 変数宣言 name = 1234 # 整数型、文字列型、浮動小数点型 123 'hello' "world" "I can't drive." 1.23 # コメント # プログラムの意味を記述するもの # デバッグポイント・コードの実行に支障はありません # print()関数 # 関数はミニプログラム
def _dup(file,mode,checked=True): """Replacement for perl built-in open function when the mode contains '&'.""" global OS_ERROR, TRACEBACK, AUTODIE try: if isinstance(file, io.IOBase): # file handle file.flush() return os.fdopen(os.dup(file.fileno()), mode, encodi...
# -*- coding: utf-8 -*- """ @Time : 2020/12/27 23:45 @Auth : 高冷Aloof @File :__init__.py @IDE :PyCharm @Motto:ABC(Always Be Coding) """
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 16:15:05 2020 Logical condition: If statement @author: Ashish """ day_of_week = input("What day of the week is it today? ") if day_of_week == "Monday": print("Have a great start to your week!") elif day_of_week == "Friday": print("It's ok to finish a...
class PeekableIterator: def __init__(self, nums): self.nums = nums self.i = 0 def peek(self): return self.nums[self.i] def next(self): self.i += 1 return self.nums[self.i-1] def hasnext(self): return self.i < len(self.nums)
# DADSA - Assignment 1 # Reece Benson class Player(): _id = None _name = None _gender = None _score = None _points = None def __init__(self, _name, _gender, _id): self._id = _id self._name = _name self._gender = _gender self._score = { } self._points = 0...
_champernownes_constant = "" def _calculate_champernownes_nth_decimal(length): res = [] curr_length = 0 i = 1 while curr_length < length: res += [str(i)] curr_length += len(res[-1]) i += 1 return "".join(res) def champernownes_nth_decimal(n): global _champernownes_con...
class Solution: solution = [] def inorderTraversal(self, root: TreeNode) -> List[int]: if (root == None): return self.solution = [] self.inorderHelper(root) return self.solution def inorderHelper(self, root: TreeNode): if (root == None): ...
# -*- coding: utf-8 -*- """ """ #Function that checks whether a string can be converted into a float def isfloat(value): try: float(value) return True except ValueError: return False #Function that checks whether a string can be converted into an integer def isint(value): try: int...
winClass = window.get_active_class() if winClass not in ("code.Code", "emacs.Emacs"): # Regular window keyboard.send_keys('<home>') else: # VS Code keyboard.send_keys('<alt>+a')
""" Module to manage affiliate marketing links Purpose: allow managing affiliate marketing links in one place Author: Tom W. Hartung Date: Winter, 2019 Copyright: (c) 2019 Tom W. Hartung, Groja.com, and JooMoo Websites LLC. Reference: """ class AffiliateLinks: """ Use python dictionaries to make it easier ...
# GYP project file for TDesktop { 'targets': [ { 'target_name': 'libtgvoip', 'type': 'static_library', 'dependencies': [], 'defines': [ 'WEBRTC_APM_DEBUG_DUMP=0', 'TGVOIP_USE_DESKTOP_DSP', 'WEBRTC_NS_FLOAT', ], 'variables': { ...
#!/usr/bin/env python GLOBAL_ARGUMENTS = [ 'property-id', 'start-date', 'end-date', 'ndays', 'domain', 'prefix', ] def format_comma(d): """ Format a comma separated number. """ return '{:,d}'.format(int(d)) def format_duration(secs): """ Format a duration in seconds a...
# Time: O(n * l^2) # Space: O(n * l) # Given a list of words, please write a program that returns # all concatenated words in the given list of words. # # A concatenated word is defined as a string that is comprised entirely of # at least two shorter words in the given array. # # Example: # Input: ["cat","cats","cats...
def get_chunks(l, n, max_chunks=None): """ Returns a chunked version of list l with a maximum of n items in each chunk :param iterable[T] l: list of items of type T :param int n: max size of each chunk :param int max_chunks: maximum number of chunks that can be returned. Pass none (the default) fo...
print("####################################################") print("#FILENAME:\t\ta1p3.py\t\t\t #") print("#ASSIGNMENT:\t\tHomework Assignment 1 Pt. 3#") print("#COURSE/SECTION:\tCIS 3389.251\t\t #") print("#DUE DATE:\t\tWednesday, 12.February 2020#") print("####################################################\n\...
description = '' pages = ['header', 'checkout'] def setup(data): pass def test(data): navigate('http://store.demoqa.com/') click(header.go_to_checkout) verify_text_in_element(checkout.title, 'Checkout') capture('Checkout page is displayed') def teardown(data): pass
# ENUM definitions # Symbol type SYMBOL_TYPE_SPOT = 'SPOT' # Order status ORDER_STATUS_NEW = 'NEW' ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED' ORDER_STATUS_FILLED = 'FILLED' ORDER_STATUS_CANCELED = 'CANCELED' ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL' ORDER_STATUS_REJECTED = 'REJECTED' ORDER_STATUS_EXPIRED ...
# -*- coding: utf-8 -*- """ Created on Thu Nov 28 19:34:48 2019 @author: wenbin """ """ 实现一个队列的数据结构,使其具有入队列,出队列,查看队列首尾元素,查看队列大小等功能 数组实现队列. """ class MyQueue: def __init__(self): self.arr = [] self.front = 0 #队尾头 self.rear = 0 #队尾尾 # 判断队列是否为空 def isEmpty(self): ...
# cases where DictAchievement should unlock # >> CASE {'name': 'John Doe', 'age': 24} # >> CASE { 'name': 'John Doe', 'age': 24 } # >> CASE func({'name': 'John Doe', 'age': 24})
km = float(input('Quantidade de Km rodados: ')) dias = float(input('Quantidade de dias: ')) q = km * 0.15 d = dias * 60 print('Você pagará R${:.2f} pelo aluguel do veículo.'.format(q + d))
#!/usr/bin/env python3 # default arguments, assume a default value if one is not provided def display_info(name, age='42'): print('Name: ', name, 'Age', age) display_info(age='56', name='Marc Wilson') display_info(name='Marc Wilson')
# Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) # e mostre seu status, de acordo com a tabela abaixo: # # – IMC abaixo de 18,5: Abaixo do Peso # # – Entre 18,5 e 25: Peso Ideal # # – 25 até 30: Sobrepeso # # – 30 até 40: Obesidade peso = float(input('Qual é ...
#!/usr/bin/env python ''' Copyright (C) 2019, WAFW00F Developers. See the LICENSE file for copying permission. ''' NAME = 'Malcare (Inactiv)' def is_waf(self): schemes = [ self.matchContent(r'firewall.{0,15}?powered.by.{0,15}?malcare.{0,15}?pro'), self.matchContent('blocked because of malicious a...
n,k=map(int,input().split()) if k<n//2 or (n==1 and k!=0): print(-1) else: if n==1: print(1) else: x=r=k-(n-2)//2 while r<=x+n: r+=x ans=[r,x] for i in range(2,n): ans.append(ans[1]+i-1) print(*ans)
class news_source: ''' News Source Class to define News Source Objects ''' def __init__(self, id, name, homepage_url, description): self.id = id self.name = name self.homepage_url = homepage_url self.description = description # self.logo = logo class Articles: ...
# Time: O(n) # Space: O(1) class Solution(object): def numberOfLines(self, widths, S): """ :type widths: List[int] :type S: str :rtype: List[int] """ result = [1, 0] for c in S: w = widths[ord(c)-ord('a')] result[1] += w i...
class MarkerPosition: def __init__(self, markers_points, rotation_vector, translation_vector): self.markers_points = markers_points self.rotation_vector = rotation_vector self.translation_vector = translation_vector def set_markers_points(self, markers_points): self.markers_poi...
def _ghc_paths_module_impl(ctx): tools = ctx.toolchains["@rules_haskell//haskell:toolchain"].tools ghc = tools.ghc ctx.actions.run_shell( inputs = [ghc], outputs = [ctx.outputs.out], command = """ cat > {out} << EOM module GHC.Paths ( ghc, ghc_pkg, libdir, docdir ) wh...
#import formatter #import htmllib url="http://www.cnn.com" filehandle = urllib.urlopen(url) #w = formatter.DumbWriter() # plain text #f = formatter.AbstractFormatter(w) #p = htmllib.HTMLParser(f) #p.feed(filehandle.read()) #p.close() #filehandle.close() fromaddr = "ahouman2@hatswitch.crhc.illinois.edu" msg =...
def factI(n): """ Assumes that n is an int > 0 Returns n!""" result = 1 while n > 1: result = result * n n -= 1 return result def factR(n): """ Assumes that n is an int > 0 Returns n! """ if n == 1: return n else: return n*factR(n-1)
class WebPageCssSelect: def __init__(self, url, ua_type, selector_name, value): self.url = url self.ua_type = ua_type self.selector_name = selector_name self.value = value def output(self): return self.url + ',' + self.ua_type + ',' + self.selector_name + ',' + self.value
num = 10 num1 = 10 num2 = 20 num3 = 30
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
# Classes & Objects class Person: # __ means private __name = '' __email = '' def __init__(self, name, email): self.__name = name self.__email = email def set_name(self, name): self.__name = name def get_name(self): return self.__name def set_email(self, e...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyTensorflow(Package): """TensorFlow is an Open Source Software Library for Machine Intelligence This is a ...
''' https://leetcode.com/problems/longest-valid-parentheses/ ''' class Solution: def longestValidParentheses(self, s: str) -> int: stack=[-1] maxValid=0 for i in range(0,len(s)): if s[i]=="(": stack.append(i) else: stack.pop() if stack=...
class Response: def __init__(self, inst): self.instance = inst @property def id(self): return self.instance['status'] @property def status(self): return self.instance['status']
NUM_ROWS = 10 NUM_COLS = 10 with open('input.txt') as file: octopi = [] num_flashes = 0 for row in range(NUM_ROWS): line = file.readline() octopi.append([]) for col in range(NUM_COLS): octopi[row].append(int(line[col])) for step in range(100): flashes = [] ...
FILTERS_KEY = 'FILTERS' SAMPLE_RATE_METRIC_KEY = '_sample_rate' SAMPLING_PRIORITY_KEY = '_sampling_priority_v1' ANALYTICS_SAMPLE_RATE_KEY = '_dd1.sr.eausr' ORIGIN_KEY = '_dd.origin' HOSTNAME_KEY = '_dd.hostname' ENV_KEY = 'env' NUMERIC_TAGS = (ANALYTICS_SAMPLE_RATE_KEY, ) MANUAL_DROP_KEY = 'manual.drop' MANUAL_KEEP_K...
def init(bot, data): @bot.command() async def add(ctx): await ctx.send("Add Ludus to your server: <https://discordapp.com/api/oauth2/authorize?client_id=593828724001079297&permissions=124992&scope=bot>") @bot.command() async def github(ctx): await ctx.send("Ludus is open source! You...
"""User provided customizations. Here one changes the default arguments for compiling _gpaw.so (serial) and gpaw-python (parallel). Here are all the lists that can be modified: * libraries * library_dirs * include_dirs * extra_link_args * extra_compile_args * runtime_library_dirs * extra_objects * define_macros * mp...
# -*- coding:utf-8 -*- # @Time : 2019/12/31 16:59 # @Author : Dg # 几个高阶函数的简单复习 def big_than_10(x): if x > 10: return True else: return False result = map(big_than_10, (1, 2, 3, 18,)) # 返回列表 print(result, type(result)) def fn(x, y): return x * 10 + y r_ = reduce(fn, [1, 2, 3]) prin...
# -*- coding: utf-8 -*- """Top-level package for Spectrify.""" __author__ = """The Narrativ Company, Inc.""" __email__ = 'engineering@narrativ.com' __version__ = '1.0.1'
#! /usr/bin/env zxpy ~'echo Hello world!' def print_file_count(): file_count = ~'ls -1 | wc -l' ~"echo -n 'file count is: '" print(file_count) print_file_count()
class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type numsSize: int """ self.nums = nums def pick(self, target): """ :type target: int :rtype: int """ count = 0 ans = -1...
#!/usr/bin/env python # _*_coding:utf-8 _*_ #@Time    :2019/4/24 0024 下午 9:36 #@Author  :喜欢二福的沧月君(necydcy@gmail.com) #@FileName: YanghuiTriangle.py #@Software: PyCharm """ (九)、杨辉三角形 【题目描述】 输出n(0<n)行杨辉三角形,n由用户输入。 """ def YangHui (num = 10): LL = [[1]] for i in range(1,num): LL.append(...
def extractLasciviousImouto(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'].replace('-', '.')) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'The Beast of the 17th District' in item['tags'] or 'the beast of the 17th district' in item['title'].l...
## Capitalizes the first letter of a string. ## Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the lower_rest parameter to keep the rest of the string intact, or set it to true to convert to lowercase. def capitalize(string, lower_rest=False): return string[:1].upper() ...
# Topological sorting of a directed ascylic graph # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2014-2019, Lars Asplund lars.anders.asplund@gmail.c...
# Rock, paper, scissors game print("--------------------------------") print(" Rock, Paper, Scissors v1") print("--------------------------------") player1 = input("Player 1, enter your name: ") player2 = input("Player 2, enter your name: ") rolls = ["rock", "paper", "scissors"] roll1 = input(f"{player1}, enter y...
"""Constants for the Carson integration.""" DOMAIN = "carson" UNLOCKED_TIMESPAN_SEC = 5 ATTRIBUTION = "provided by Eagle Eye" CONF_LIST_FROM_EAGLE_EYE = "list_from_eagle_eye" DEFAULT_CONF_LIST_FROM_EAGLE_EYE = False
# Copyright 2016 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
class VkError(Exception): def __init__(self, code, message, request_params): super(VkError, self).__init__() self.code = code self.message = message self.request_params = request_params def __str__(self): return 'VkError {}: {} (request_params: {})'.format(self.code, sel...
#!/usr/bin/env python # -*- coding: utf-8 -*- print(''' .intel_syntax noprefix .extern isr_common ''') print('// Interrupt Service Routines') for i in range(255): print('''isr{0}: cli {1} push {0} jmp isr_common '''.format(i, 'push 0' if i not in [8, 10, 11, 12, 13, 14, 17] else 'nop'...
"""Find first and last position of elements in sorted arrays.""" """First and last position in sorted arrays.""" def searchRange(nums, target): """Find first and last position.""" def midpoint(x, y): """Find mid point.""" return x + (y - x) // 2 lo, hi = 0, len(nums)-1 _max = -1 ...
# This sample tests the logic that infers parameter types based on # default argument values or annotated base class methods. class Parent: def func1(self, a: int, b: str) -> float: ... class Child(Parent): def func1(self, a, b): reveal_type(self, expected_text="Self@Child") reveal_t...
#!/usr/bin/python3 class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False s = str(x) for i in range(int(len(s)/2)): last = len(s) - i - 1 if s[i] != s[last]: return False return True if __name__ == "__main_...
# *** DEFINE CONSTANTS *** # DO NOT ADD TO VERSION CONTROL AFTER ENTERING PERSONAL INFO # LOCATION WHERE BLOTTER FILE IS LOCATED (INPUT) SRCPATH = "D:/financial/" SRCFILE = "blotter.xlsx" # OUTPUT DATA DESTINATION (WINDOWS FORMAT) outpath = "D://financial//" outpath_linux = "/mnt/d/financial/" # OUTPUT FILE NAMES ou...
""" https://leetcode.com/problems/reverse-integer/ """ class Solution: def reverse(self, x: int) -> int: multiply = 1 upper_bound = 2**31-1 lower_bound = -2**31 if x < 0: multiply = -1 value = int(str(abs(x))[::-1]) print(f"mult={multiply}, value={value},...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/25 0025 上午 11:51 # @Author : Exchris Tsai # @Site : # @File : example55.py # @Software: PyCharm """ 题目:学习使用按位取反~。 程序分析:~0=1; ~1=0; (1)先使a右移4位。 (2)设置一个低4位全为1,其余全为0的数。可用~(~0<<4) (3)将上面二者进行&运算。 """ __author__ = 'Exchris Tsai' if __name__ == "__ma...
def get_num(capacity, p): cell = [] for i in range(len(p) + 1): cell.append([]) for j in range(capacity + 1): cell[i].append(0) for i in range(1, len(p) + 1): for j in range(1, capacity + 1): if p[i - 1] <= i: cell[i][j] = max(p[i -1], cell[i]...
#!/usr/bin/env python # examples of Church numerals zero = lambda f: lambda x: x one = lambda f: lambda x: f(x) two = lambda f: lambda x: f(f(x)) three = lambda f: lambda x: f(f(f(x))) four = lambda f: lambda x: f(f(f(f(x)))) five = lambda f: lambda x: f(f(f(f(f(x))))) def to_intp(f): print (f(lam...
#!/usr/bin/env python3 # https://arc098.contest.atcoder.jp/tasks/arc098_a n = int(input()) s = input() a = [0] * n if s[0] == 'W': a[0] = 1 for i in range(1, n): c = s[i] if c == 'E': a[i] = a[i - 1] else: a[i] = a[i - 1] + 1 b = [0] * n if s[n - 1] == 'E': b[n - 1] = 1 for i in range(n - 2,...
class SystemUnsupported(Exception): def __init__(self): message = "不支持您的系统" super().__init__(message) class SubClassInvaild(Exception): def __init__(self): message = "SubClass didn't provide needed function" super().__init__(message) class InvalidInputUrl(Exception): def...
# Copyright (c) Jeremías Casteglione <jrmsdev@gmail.com> # See LICENSE file. __all__ = ['configure'] def configure(env, cfg): env.settings.merge(cfg, 'os', ( 'hostname', 'hostname.file', 'users.home.dir', ))
# # Copyright (c) 2013,2014, Oracle and/or its affiliates. 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; version 2 of the License. # # This program is distributed in the...
def reverse_string(string): reverse = '' for char in range(len(string) - 1, -1, -1): reverse += string[char] print(reverse)
class RestException(Exception): pass class ResourceException(RestException): pass class RestServerException(RestException): pass
class CreateAuth: def __init__(self, repository): self.auth_repository = repository async def create(self): return await self.auth_repository.create()
length = int( input("Enter the length of rectagle: ") ) width = int( input("Enter the width of rectange: ") ) perimeter = 2 * (length + width) area = length * width print("Area: ", area, "square cm") print("Perimeter:", perimeter, "cm")