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.TestEnvironment(test_env), }, ) return struct()
# 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[i] is the ith item of the list and L[j] the jth one. In a given list of size N there could be up to O(N**2) inversions. To do the counting efficiently (i.e. in O(N*log(N)) time) we use a divide and conquer approach. More specifically, we piggyback on the mergesort algorithm. Author: Christos Nitsas (nitsas) (chrisnitsas) Language: Python 3(.4) Date: October, 2014 """ __all__ = ['count_inversions', 'count', 'mergesort_and_count'] def count_inversions(sequence): """ Count the number of inversions in the sequence and return an integer. sequence -- a sequence of items that can be compared using <= we assume the sequence is sliceable We count inversions from the ascending order. This will piggyback on the mergesort divide and conquer algorithm. """ _, num_inversions = mergesort_and_count(sequence) return num_inversions count = count_inversions def mergesort_and_count(sequence): """ Sort the sequence into a list (call this "merged"), count the number "N" of inversions, and return a tuple with "merged" and "N". """ if len(sequence) <= 1: return (list(sequence), 0) left = sequence[:len(sequence)//2] right = sequence[len(sequence)//2:] return merge_and_count_inversions(mergesort_and_count(left), mergesort_and_count(right)) def merge_and_count_inversions(left_tuple, right_tuple): """ Count the number of split inversions while merging the given results of the left and right subproblems and return a tuple containing the resulting merged sorted list and the total number of inversions. left_tuple -- a tuple containing the sorted sublist and the count of inversions from the left subproblem right_tuple -- a tuple containing the sorted sublist and the count of inversions from the right subproblem We call split inversions the pairs of items where the larger item is in the left subsequence and the smaller item is in the right. The total number of inversions "count_total" is: count_total = count_left + count_right + count_split, where "count_left", "count_right" are the number of inversions in the left and right subsequence respectively and "count_split" is the number of split inversions. """ left, count_left = left_tuple right, count_right = right_tuple merged, count_split = list(), 0 # Careful! # If we use list slicing in the following loop we might end up with # worse than O(L*log(L)) complexity. We will use indices instead. index_l, index_r = 0, 0 while len(left) - index_l > 0 and len(right) - index_r > 0: if left[index_l] <= right[index_r]: merged.append(left[index_l]) index_l += 1 # no inversions discovered here else: # the item right[index_r] is smaller than every item in # left[index_l:] merged.append(right[index_r]) index_r += 1 # all the items of left[index_l:] formed inversions with the # item we just appended to "merged" count_split += len(left) - index_l if len(left) - index_l > 0: merged.extend(left[index_l:]) # no more inversions elif len(right) - index_r > 0: merged.extend(right[index_r:]) # no more inversions count_total = count_left + count_right + count_split return (merged, count_total)
# 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: solution += data[0] count_use_max_value += 1 print(solution)
# 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', -10, +10), ('roll', -10, +10)], '-x': [('pitch', +160, +172), ('roll', -10, +10)], '+y': [('pitch', +70, +90), ('yaw', -80, -100)], '-y': [('pitch', -90, -110), ('roll', -10, +10)], '+z': [('pitch', -90, -110), ('roll', -10, +10)], '-z': [('pitch', +70, +90), ('yaw', -10, +10)], } # map axis letter to ESP axis (stage) number ESP_AX = {'roll': 1, 'pitch': 2, 'yaw': 3} # move sequence for safe trajectories -- minimal moves for rough home to rough home transitions ORIG_SAFE_TRAJ_MOVES = [ # rough_home ax1 pos1, ax2 pos2, etc. ('+x', [(2, 0)]), ('-z', [(2, 80)]), ('+y', [(3, -90)]), ('-x', [(2, 170)]), ('-y', [(2, -100), (3, -90)]), ('+z', [(3, 0)]), ] NEXT_SAFE_TRAJ_MOVES = [ # rough_home ax1 pos1, ax2 pos2, etc. ('+y', [(3, -90)]), ('-x', [(2, 170)]), ('-y', [(2, -100), (3, -90)]), ('+z', [(3, 0)]), ] SAFE_TRAJ_MOVES = [ # rough_home ax1 pos1, ax2 pos2, etc. ('+z', [(3, 0)]), ] # time to allow stage to settle (e.g. after a move, wait a short bit before querying actual position) ESP_SETTLE = 3 # seconds
# 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 [] else: curList = [ root ] while True: nextList = [] expanded = False for curRoot in curList: curRootLeft = curRoot.left curRootRight = curRoot.right curRoot.left = None curRoot.right = None nextList.append( curRoot ) if curRootLeft != None: nextList.append( curRootLeft ) expanded = True if curRootRight != None: nextList.append( curRootRight ) expanded = True if expanded: curList = nextList else: break outList = [ x.val for x in curList ] return outList
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_password (string): Specifies the new linux password. linux_username (string): Specifies the linux username for which the password will be updated. verify_password (bool): True if request is only to verify if current password matches with set password. """ # Create a mapping from Model property names to API property names _names = { "linux_password":'linuxPassword', "linux_username":'linuxUsername', "linux_current_password":'linuxCurrentPassword', "verify_password":'verifyPassword' } def __init__(self, linux_password=None, linux_username=None, linux_current_password=None, verify_password=None): """Constructor for the UpdateLinuxPasswordReqParams class""" # Initialize members of the class self.linux_current_password = linux_current_password self.linux_password = linux_password self.linux_username = linux_username self.verify_password = verify_password @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary linux_password = dictionary.get('linuxPassword') linux_username = dictionary.get('linuxUsername') linux_current_password = dictionary.get('linuxCurrentPassword') verify_password = dictionary.get('verifyPassword') # Return an object of this model return cls(linux_password, linux_username, linux_current_password, verify_password)
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) for pattern in ctx.attr.exclude_patterns] exclude_patterns_str = " ".join(exclude_patterns) substitutions = { "@@ADDLICENSE_SHORT_PATH@@": shell.quote(ctx.executable._addlicense.short_path), "@@MODE@@": shell.quote(ctx.attr.mode), "@@EXCLUDE_PATTERNS@@": exclude_patterns_str, } ctx.actions.expand_template( template = ctx.file._runner, output = out_file, substitutions = substitutions, is_executable = True, ) runfiles = ctx.runfiles(files = [ctx.executable._addlicense]) return [DefaultInfo( runfiles = runfiles, executable = out_file, )] addlicense = rule( implementation = _addlicense_impl, attrs = { "mode": attr.string( values = [ "format", "check", ], default = "format", ), "exclude_patterns": attr.string_list( allow_empty = True, doc = "A list of glob patterns passed to the find command. E.g. './vendor/*' to exclude the Go vendor directory", default = [ ".*.git/*", ".*.project/*", ".*idea/*", ], ), "_addlicense": attr.label( default = Label("@com_github_google_addlicense//:addlicense"), executable = True, cfg = "host", ), "_runner": attr.label( default = Label("//bazel/rules_addlicense:runner.bash.template"), allow_single_file = True, ), }, executable = True, )
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 <= num: i = i << 1 return (i - 1) ^ num class Solution: def findComplement(self, num: int) -> int: copy = num; i = 0; while copy != 0 : copy >>= 1; num ^= (1<<i); i += 1; return num; class Solution: def findComplement(self, num: int) -> int: mask = 1 while( mask < num): mask = (mask << 1) | 1 return ~num & mask class Solution: def findComplement(self, num: int) -> int: n = 0; while (n < num): n = (n << 1) | 1; return n - num;
''' 给你一个整数 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: revertedNumber = revertedNumber * 10 + x % 10 x //= 10 return x == revertedNumber or x == revertedNumber // 10 s = Solution() print(s.isPalindrome(2)) print(s.isPalindrome(22)) print(s.isPalindrome(232)) print(s.isPalindrome(2332)) print(s.isPalindrome(-232)) print(s.isPalindrome(-22))
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 foo
# 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, total / count))
# # 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 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint") mib2ext, = mibBuilder.importSymbols("INTEL-GEN-MIB", "mib2ext") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibIdentifier, NotificationType, TimeTicks, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, IpAddress, Integer32, Bits, ObjectIdentity, Gauge32, Counter64, iso = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "NotificationType", "TimeTicks", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "IpAddress", "Integer32", "Bits", "ObjectIdentity", "Gauge32", "Counter64", "iso") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") rsvp = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 6, 33)) conf = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 6, 33, 1)) confIfTable = MibTable((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1), ) if mibBuilder.loadTexts: confIfTable.setStatus('mandatory') confIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1), ).setIndexNames((0, "INTEL-RSVP-MIB", "confIfIndex")) if mibBuilder.loadTexts: confIfEntry.setStatus('mandatory') confIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: confIfIndex.setStatus('mandatory') confIfCreateObj = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(5, 5)).setFixedLength(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: confIfCreateObj.setStatus('mandatory') confIfDeleteObj = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("delete", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: confIfDeleteObj.setStatus('mandatory') confIfUdpEncap = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: confIfUdpEncap.setStatus('mandatory') confIfRsvpTotalBw = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: confIfRsvpTotalBw.setStatus('mandatory') confIfMaxBwPerFlow = MibTableColumn((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 1, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: confIfMaxBwPerFlow.setStatus('mandatory') confRsvpEnabled = MibScalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: confRsvpEnabled.setStatus('mandatory') confRefreshTimer = MibScalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: confRefreshTimer.setStatus('mandatory') confCleanupFactor = MibScalar((1, 3, 6, 1, 4, 1, 343, 6, 33, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: confCleanupFactor.setStatus('mandatory') mibBuilder.exportSymbols("INTEL-RSVP-MIB", rsvp=rsvp, confIfTable=confIfTable, conf=conf, confIfIndex=confIfIndex, confIfDeleteObj=confIfDeleteObj, confIfRsvpTotalBw=confIfRsvpTotalBw, confCleanupFactor=confCleanupFactor, confIfUdpEncap=confIfUdpEncap, confIfMaxBwPerFlow=confIfMaxBwPerFlow, confIfEntry=confIfEntry, confRefreshTimer=confRefreshTimer, confRsvpEnabled=confRsvpEnabled, confIfCreateObj=confIfCreateObj)
""" 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. """ class Solution(object): def letterCasePermutation(self, S): def dfs(path, i): if i>=len(S): opt.append(path) return if S[i] not in num_char: dfs(path+S[i].upper(), i+1) dfs(path+S[i].lower(), i+1) else: dfs(path+S[i], i+1) num_char = set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) opt = [] dfs('', 0) return opt
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": { "license_version": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "view_count": { "type": "long" }, "provider": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "source": { "fields": { "keyword": { "ignore_above": 256, "type": "keyword" } }, "type": "text" }, "license": { "fields": { "keyword": { "ignore_above": 256, "type": "keyword" } }, "type": "text" }, "url": { "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }, "type": "text" }, "tags": { "properties": { "accuracy": { "type": "float" }, "name": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }, "analyzer": "english" } } }, "foreign_landing_url": { "fields": { "keyword": { "ignore_above": 256, "type": "keyword" } }, "type": "text" }, "id": { "type": "long" }, "identifier": { "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }, "type": "text" }, "title": { "type": "text", "similarity": "boolean", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }, "analyzer": "english" }, "creator": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "created_on": { "type": "date" }, "description": { "fields": { "keyword": { "type": "keyword" } }, "type": "text", "analyzer": "english" }, "height": { "type": "integer" }, "width": { "type": "integer" }, "extension": { "fields": { "keyword": { "ignore_above": 8, "type": "keyword" } }, "type": "text" }, } } } } } return mapping[table_name]
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: print('os numeros sao iguais')
""" 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],n) for i in pow2: if n == i: n = n // 2 if n != 1: player = 1 - player break elif n & i == i: n = n - i if n != 1: player = 1 - player break return ["Louise", "Richard"][player] if __name__ == "__main__": t = int(input().strip()) for a0 in range(t): n = int(input().strip()) result = counterGame(n) print(result)
#!/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_MSEC_PER_SAMPLE_LINE_NUM = 2 BIOPAC_ECG_CHANNEL = 1 BIOPAC_SKIN_CONDUCTANCE_CHANNEL = 3 ECG_R_PEAK_DETECTION_THRESHOLD = 2.0 ECG_MF_HRV_CUTOFF = [0.07, 0.15] ECG_HF_HRV_CUTOFF = [0.15, 0.5] TRAINING_DATA_RATIO = 0.75
# 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 -= 1 _ = int(input()) given_stack = list(map(int, input().split())) top_stacks = [] for i in given_stack: to_push = binary_search(top_stacks, i) if to_push == len(top_stacks): top_stacks.append(i) else: top_stacks[to_push] = i print(len(top_stacks), end=" ") print(" ".join([str(i) for i in top_stacks])) if __name__ == "__main__": main()
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_UNREALISTIC = True CANCEL_ALL_ON_STARTUP = True GET_INFO_BEFORE_SLEEP = True
# # 에라스토테네스의 채를 이용한 소수 구하는 함수 # 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(i + i, max_num, i): # i의 배수부터 주어진 숫자까지 i만큼 반복한다. # primes[j] = False # return [i for i in range(min_num, max_num) if primes[i] == True] # # # num1, num2 = map(int, input().split()) # for prime in get_prime(num1, num2+1): # if prime > 0: # print(prime) m, n = map(int, input().split()) exp = set() primes = [] for i in range(2, n+1): if i in exp: continue if i >= m: primes.append(i) j = 1 while i * j <= n: exp.add(i*j) j+=1 print("\n".join(map(str, primes)))
''' 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: [email protected] ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head, tail = [None, None] carry = 0 while (l1 or l2): n1 = l1.val if l1 else 0 n2 = l2.val if l2 else 0 sum_ = n1 + n2 + carry carry = sum_ // 10 if not head: head = tail = ListNode(sum_ % 10) else: tail.next = ListNode(sum_ % 10) tail = tail.next if l1: l1 = l1.next if l2: l2 = l2.next if (carry > 0): tail.next = ListNode(carry) return head
""" 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 check them kids till there are no more kids or all kids are visited. - when you get to a leaf or node with all visited kids, pop it off the top of the stack - pick the previous node and check it's kids for unvisited ones - rinse and repeat till you find the destination node you were looking for """ graph = {'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C']} def dfs_recursive(graph, start, visited=[]): # put the starting element into our stack visited += [start] # for all the neighbors of our current node, perform dfs for neighbor in graph[start]: if neighbor not in visited: # current neigbor becomes new start visited = dfs_recursive(graph, neighbor, visited) return visited def depth_first_search(graph, start): """ Without recursion """ visited = [] stack = [start] while stack: # get the element at the top of the stack node = stack.pop() if node not in visited: # add it to the list of visited nodes visited.append(node) # get its neighbors neighbors = graph[node] # for all it's unvisited neighbors, add them to the stack # each of them will be visited later for neighbor in neighbors: if neighbor not in visited: stack.append(neighbor) return visited print(dfs_recursive(graph, 'A')) # ['A', 'B', 'D', 'E', 'C', 'F', 'G'] print(depth_first_search(graph, 'A')) # ['A', 'E', 'D', 'B', 'C', 'G', 'F']
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 in nums: v = max(curr, prev + num) prev = curr curr = v return curr
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, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] O(n^2) """ for x in range(len(nums)): for y in range(len(nums)): if x != y and nums[x] + nums[y] == target: return [x, y] def twoSumBest(self, nums, target): """ O(n) """ if len(nums) <= 1: return False # hashmap : key = target - array_value, value = array_index # 解题思路相当于顺序寻找另一半 buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i if __name__ == '__main__': nums = [2, 7, 11, 15] target = 9 result = Solution().twoSum(nums, target)
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 == 2: print('O número {} foi convertido para {}'.format(num,oct(num))) elif opcao == 3: print('O número {} foi convertido para {}'.format(num,oct(num))) else: print('Opção invalida')
# -*- 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 for x in dataset['exchanges'] if x['type'] == 'reference product'] if len(exchanges) != 1: return default else: try: return exchanges[0]['production volume']['amount'] except KeyError: return default def original_production_volume(dataset, default=None): """Get original (i.e. before activity link subtractions) 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 for x in dataset['exchanges'] if x['type'] == 'reference product'] if len(exchanges) != 1: return default try: pv = exchanges[0]['production volume'] except KeyError: return default if 'original amount' in pv: return pv['original amount'] elif 'amount' in pv: return pv['amount'] else: return default def reference_products_as_string(dataset): """Get all reference products as a string separated by ``'|'``. Return ``'None found'`` if no reference products were found.""" exchanges = sorted([exc['name'] for exc in dataset['exchanges'] if exc['type'] == 'reference product']) if not exchanges: return "None found" else: return "|".join(exchanges)
# 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 'trade' or 'issue' or leave blank (compendium and omnibus are trades)" type_filtered_holder = [] number_filtered_holder = []# Will hold the new entries after filtering step # FIRST GET EITHER ISSUE OR PAPERBACK ADD TYPE paperback_signs = ["vol", "vol.", "volume", "tpb", 'pb',"tp", "paperback" ,"omnibus", "compendium", "hc", "hardcover", "graphic novel", "softcover"] issue_signs = ["#"] for book in results: if any(x in book["title"].lower() for x in issue_signs): book["type"] = "issue" elif any(x in book["title"].lower() for x in paperback_signs): book["type"] = "trade" else: book["type"] = "unknown (assume trade)" if book_type: # NOT NONE for book in results: if book["type"] == book_type or book["type"] == "unknown (assume trade)": type_filtered_holder.append(book) else: type_filtered_holder = results if number: for book in type_filtered_holder: if "{}".format(number) in book["title"] or "0{}".format(number) in book["title"]: number_filtered_holder.append(book) else: number_filtered_holder = type_filtered_holder # PUT CHEAPER FIRST number_filtered_holder = sorted(number_filtered_holder, key=lambda k: k['price']) return number_filtered_holder
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 :parameters: db_ref : iterable an iterable object (i.e. list, set etc) that would serve as the reference db of the instance. Changes in that object will affect the output of ToggleFilter instance. show_by_default: bool decide if by default all the items are "on", i.e. these items will be presented if no other toggling occurred. default value : **True** """ self._data = db_ref self._toggle_db = set() self._filter_method = filter self.__set_initial_state(show_by_default) def reset (self): """ Toggles off all the items """ self._toggle_db = set() def toggle_item(self, item_key): """ Toggle a single item in/out. :parameters: item_key : an item the by its value the filter can decide to toggle or not. Example: int, str and so on. :return: + **True** if item toggled **into** the filtered items + **False** if item toggled **out from** the filtered items :raises: + KeyError, in case if item key is not part of the toggled list and not part of the referenced db. """ if item_key in self._toggle_db: self._toggle_db.remove(item_key) return False elif item_key in self._data: self._toggle_db.add(item_key) return True else: raise KeyError("Provided item key isn't a key of the referenced data structure.") def toggle_items(self, *args): """ Toggle multiple items in/out with a single call. Each item will be ha. :parameters: args : iterable an iterable object containing all item keys to be toggled in/out :return: + **True** if all toggled items were toggled **into** the filtered items + **False** if at least one of the items was toggled **out from** the filtered items :raises: + KeyError, in case if ont of the item keys was not part of the toggled list and not part of the referenced db. """ # in python 3, 'map' returns an iterator, so wrapping with 'list' call creates same effect for both python 2 and 3 return all(list(map(self.toggle_item, args))) def filter_items(self): """ Filters the pointed database by showing only the items mapped at toggle_db set. :returns: Filtered data of the original object. """ return self._filter_method(self.__toggle_filter, self._data) # private methods def __set_initial_state(self, show_by_default): try: _ = (x for x in self._data) if isinstance(self._data, dict): self._filter_method = ToggleFilter.dict_filter if show_by_default: self._toggle_db = set(self._data.keys()) return elif isinstance(self._data, list): self._filter_method = ToggleFilter.list_filter elif isinstance(self._data, set): self._filter_method = ToggleFilter.set_filter elif isinstance(self._data, tuple): self._filter_method = ToggleFilter.tuple_filter if show_by_default: self._toggle_db = set(shallow_copy(self._data)) # assuming all relevant data with unique identifier return except TypeError: raise TypeError("provided data object is not iterable") def __toggle_filter(self, x): return (x in self._toggle_db) # static utility methods @staticmethod def dict_filter(function, iterable): assert isinstance(iterable, dict) return {k: v for k,v in iterable.items() if function(k)} @staticmethod def list_filter(function, iterable): # in python 3, filter returns an iterator, so wrapping with list creates same effect for both python 2 and 3 return list(filter(function, iterable)) @staticmethod def set_filter(function, iterable): return {x for x in iterable if function(x)} @staticmethod def tuple_filter(function, iterable): return tuple(filter(function, iterable)) if __name__ == "__main__": pass
""" 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_defs/lib:src_and_dep_helpers.bzl", "src_and_dep_helpers") load("@fbcode_macros//build_defs/lib:visibility.bzl", "get_visibility") load("@fbcode_macros//build_defs:cpp_python_extension.bzl", "cpp_python_extension") load( "@fbsource//tools/build_defs:fb_native_wrapper.bzl", "fb_native", ) def _get_lang(): return "py" def _get_lang_opt(): return "-python" def _get_lang_flags(java_package = None, **kwargs): _ignore = java_package _ignore = kwargs return [ "-threads", "-safecstrings", "-classic", ] def _get_generated_sources(module): src = module + ".py" return {src: src} def _get_language_rule( base_path, name, module, hdr, src, gen_srcs, cpp_deps, deps, py_base_module = None, visibility = None, **kwargs): _ignore = base_path _ignore = hdr _ignore = kwargs # Build the C/C++ python extension from the generated C/C++ sources. cpp_python_extension( name = name + "-ext", srcs = [src], base_module = py_base_module, module_name = "_" + module, # Generated code uses a lot of shadowing, so disable GCC warnings # related to this. compiler_specific_flags = { "gcc": [ "-Wno-shadow", "-Wno-shadow-local", "-Wno-shadow-compatible-local", ], }, # This is pretty gross. We format the deps just to get # re-parsed by the C/C++ converter. Long-term, it'd be # be nice to support a better API in the converters to # handle higher-leverl objects, but for now we're stuck # doing this to re-use other converters. deps = src_and_dep_helpers.format_deps([d for d in cpp_deps if d.repo == None]), external_deps = [ (d.repo, d.base_path, None, d.name) for d in cpp_deps if d.repo != None ], ) # Generate the wrapping python library. out_deps = [] out_deps.extend(deps) out_deps.append(":" + name + "-ext") attrs = {} attrs["name"] = name attrs["visibility"] = get_visibility(visibility, name) attrs["srcs"] = gen_srcs attrs["deps"] = out_deps if py_base_module != None: attrs["base_module"] = py_base_module # At some point swig targets should also include typing Options # For now we just need an empty directory. if get_typing_config_target(): gen_typing_config(name) fb_native.python_library(**attrs) return [] python_converter = LangConverterInfo( get_lang = _get_lang, get_lang_opt = _get_lang_opt, get_lang_flags = _get_lang_flags, get_generated_sources = _get_generated_sources, get_language_rule = _get_language_rule, )
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): mStr = code[lbi-count] else: mStr = code[lbi-count] + mStr count += 1 multiplier = int(mStr) code_inside = code[lbi + 1:rbi] code = code[0:lbi - len(mStr)] + expand(code_inside,multiplier) + code[rbi+1:] if("[" not in code): return code else: return expandString(code) coded = input() a = (expandString(coded)) print(a) main()
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,)) return '{' + '; '.join(ret) + '}' __repr__ = __str__ class MyListSubclass(list): def __init__(self): list.__init__(self) self.var1 = 11 self.append('a') self.append('b') def __str__(self): ret = [] for obj in self: ret.append(repr(obj)) ret.append('self.var1: %s' % (self.var1,)) return '[' + ', '.join(ret) + ']' __repr__ = __str__ class MySetSubclass(set): def __init__(self): set.__init__(self) self.var1 = 12 self.add('a') def __str__(self): ret = [] for obj in sorted(self): ret.append(repr(obj)) ret.append('self.var1: %s' % (self.var1,)) return 'set([' + ', '.join(ret) + '])' __repr__ = __str__ class MyTupleSubclass(tuple): def __new__ (cls): return super(MyTupleSubclass, cls).__new__(cls, tuple(['a', 1])) def __init__(self): self.var1 = 13 def __str__(self): ret = [] for obj in self: ret.append(repr(obj)) ret.append('self.var1: %s' % (self.var1,)) return 'tuple(' + ', '.join(ret) + ')' __repr__ = __str__ def Call(): variable_for_test_1 = MyListSubclass() variable_for_test_2 = MySetSubclass() variable_for_test_3 = MyDictSubclass() variable_for_test_4 = MyTupleSubclass() all_vars_set = True # Break here if __name__ == '__main__': Call() print('TEST SUCEEDED!')
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 InvalidWriterStream(Exception): """Error while writing to the stream buffer.""" class DecodingError(Exception): """Error while decoding the avro binary.""" class EncodingError(Exception): """Error while encoding data in to avro binary."""
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 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class ToscaGraph(object): '''Graph of Tosca Node Templates.''' def __init__(self, nodetemplates): self.nodetemplates = nodetemplates self.vertices = {} self._create() def _create_vertex(self, node): if node not in self.vertices: self.vertices[node.name] = node def _create_edge(self, node1, node2, relationship): if node1 not in self.vertices: self._create_vertex(node1) self.vertices[node1.name].related[node2] = relationship def vertex(self, node): if node in self.vertices: return self.vertices[node] def __iter__(self): return iter(self.vertices.values()) def _create(self): for node in self.nodetemplates: for relTpl, req, reqDef in node.relationships: for tpl in self.nodetemplates: if tpl.name == relTpl.target.name: self._create_edge(node, tpl, relTpl.type_definition) self._create_vertex(node)
""" 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('No seu ambiente está {:.2f}º Celsius ou {:.2f}º Fahrenheit'.format(temp_c, temp_f))
""" 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((elapsed % 3600) / 60) # minutes seconds = int(elapsed) % 60 # seconds milliseconds = int((elapsed - int(elapsed)) * 1000) # milliseconds print('time:', elapsed, 's ~', hours, 'hour,', minutes, 'min,', seconds, 's,', milliseconds, 'ms')
# 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)) # def n(a) : # if a==0 : # return 0 # # print(a) # n(a-1) # print((a*5)) # print(n(10)) # print(100*("string\n\n")) # print() d="" # for i in (a.split(",") # for i in a : # if i.isalpha() : # d=d+i # print(d) # for i in (a.split(",")) : # d=d+i # print(type(d)) a=['saikira','bhopland','petland','bhatland'] f=[] for i in a[::-1] : f.append(i[::-1]) print(f)
class NetworkException(Exception): pass class SecretException(Exception): pass
# -*- coding: utf-8 -*- """ A sample of kay settings. :Copyright: (c) 2009 Accense Technology, Inc. Takashi Matsuo <[email protected]>, All rights reserved. :license: BSD, see LICENSE for more details. """ DEBUG = False ROOT_URL_MODULE = 'kay.tests.globalurls' INSTALLED_APPS = ( 'kay.tests', ) APP_MOUNT_POINTS = { 'kay.tests': '/', } # You can remove following settings if unnecessary. CONTEXT_PROCESSORS = ( 'kay.context_processors.request', 'kay.context_processors.url_functions', 'kay.context_processors.media_url', ) MIDDLEWARE_CLASSES = ( 'kay.ext.appstats.middleware.AppStatsMiddleware', )
# -*- coding: utf-8 -*- """ @author:XuMing([email protected]) @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 words @staticmethod def bigrams(words, join_string, skip=0): """ Input: a list of words, e.g., ["I", "am", "Denny"] Output: a list of bigram, e.g., ["I_am", "am_Denny"] """ assert type(words) == list L = len(words) if L > 1: lst = [] for i in range(L - 1): for k in range(1, skip + 2): if i + k < L: lst.append(join_string.join([words[i], words[i + k]])) else: # set it as unigram lst = NgramUtil.unigrams(words) return lst @staticmethod def trigrams(words, join_string, skip=0): """ Input: a list of words, e.g., ["I", "am", "Denny"] Output: a list of trigram, e.g., ["I_am_Denny"] """ assert type(words) == list L = len(words) if L > 2: lst = [] for i in range(L - 2): for k1 in range(1, skip + 2): for k2 in range(1, skip + 2): if i + k1 < L and i + k1 + k2 < L: lst.append(join_string.join([words[i], words[i + k1], words[i + k1 + k2]])) else: # set it as bigram lst = NgramUtil.bigrams(words, join_string, skip) return lst @staticmethod def fourgrams(words, join_string): """ Input: a list of words, e.g., ["I", "am", "Denny", "boy"] Output: a list of trigram, e.g., ["I_am_Denny_boy"] """ assert type(words) == list L = len(words) if L > 3: lst = [] for i in range(L - 3): lst.append(join_string.join([words[i], words[i + 1], words[i + 2], words[i + 3]])) else: # set it as trigram lst = NgramUtil.trigrams(words, join_string) return lst @staticmethod def uniterms(words): return NgramUtil.unigrams(words) @staticmethod def biterms(words, join_string): """ Input: a list of words, e.g., ["I", "am", "Denny", "boy"] Output: a list of biterm, e.g., ["I_am", "I_Denny", "I_boy", "am_Denny", "am_boy", "Denny_boy"] """ assert type(words) == list L = len(words) if L > 1: lst = [] for i in range(L - 1): for j in range(i + 1, L): lst.append(join_string.join([words[i], words[j]])) else: # set it as uniterm lst = NgramUtil.uniterms(words) return lst @staticmethod def triterms(words, join_string): """ Input: a list of words, e.g., ["I", "am", "Denny", "boy"] Output: a list of triterm, e.g., ["I_am_Denny", "I_am_boy", "I_Denny_boy", "am_Denny_boy"] """ assert type(words) == list L = len(words) if L > 2: lst = [] for i in range(L - 2): for j in range(i + 1, L - 1): for k in range(j + 1, L): lst.append(join_string.join([words[i], words[j], words[k]])) else: # set it as biterm lst = NgramUtil.biterms(words, join_string) return lst @staticmethod def fourterms(words, join_string): """ Input: a list of words, e.g., ["I", "am", "Denny", "boy", "ha"] Output: a list of fourterm, e.g., ["I_am_Denny_boy", "I_am_Denny_ha", "I_am_boy_ha", "I_Denny_boy_ha", "am_Denny_boy_ha"] """ assert type(words) == list L = len(words) if L > 3: lst = [] for i in range(L - 3): for j in range(i + 1, L - 2): for k in range(j + 1, L - 1): for l in range(k + 1, L): lst.append(join_string.join([words[i], words[j], words[k], words[l]])) else: # set it as triterm lst = NgramUtil.triterms(words, join_string) return lst @staticmethod def ngrams(words, ngram, join_string=" "): """ wrapper for ngram """ ngram = int(ngram) if ngram == 1: return NgramUtil.unigrams(words) elif ngram == 2: return NgramUtil.bigrams(words, join_string) elif ngram == 3: return NgramUtil.trigrams(words, join_string) elif ngram == 4: return NgramUtil.fourgrams(words, join_string) elif ngram == 12: unigram = NgramUtil.unigrams(words) bigram = [x for x in NgramUtil.bigrams(words, join_string) if len(x.split(join_string)) == 2] return unigram + bigram elif ngram == 123: unigram = NgramUtil.unigrams(words) bigram = [x for x in NgramUtil.bigrams(words, join_string) if len(x.split(join_string)) == 2] trigram = [x for x in NgramUtil.trigrams(words, join_string) if len(x.split(join_string)) == 3] return unigram + bigram + trigram elif ngram == 1234: unigram = NgramUtil.unigrams(words) bigram = [x for x in NgramUtil.bigrams(words, join_string) if len(x.split(join_string)) == 2] trigram = [x for x in NgramUtil.trigrams(words, join_string) if len(x.split(join_string)) == 3] fourgram = [x for x in NgramUtil.fourgrams(words, join_string) if len(x.split(join_string)) == 4] return unigram + bigram + trigram + fourgram @staticmethod def nterms(words, nterm, join_string=" "): """wrapper for nterm""" if nterm == 1: return NgramUtil.uniterms(words) elif nterm == 2: return NgramUtil.biterms(words, join_string) elif nterm == 3: return NgramUtil.triterms(words, join_string) elif nterm == 4: return NgramUtil.fourterms(words, join_string)
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(self): if not len(self.two): while self.one: self.two.append(self.one.pop()) queue = MyQueue() t = int(input()) for line in range(t): values = map(int, input().split()) values = list(values) queue.check() if values[0] == 1: queue.put(values[1]) elif values[0] == 2: queue.pop() else: print(queue.peek())
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("%") : portion_saved = portion_saved.replace("%", "") if float(portion_saved) >= 1 : portion_saved = float(portion_saved) portion_saved /= 100 portion_down_payment = 0.25 r = 0.04 current_savings = 0.0 down_payment = total_cost * portion_down_payment monthly_salary = annual_salary/12 months = 0 while current_savings < down_payment : current_savings += current_savings*(r/12) current_savings += monthly_salary*portion_saved months += 1 print("It will take", months, "months to save enough money for the down payment.")
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/skylark/drake_cc.bzl # Modificiation: # - Modify comment: linux -> elsewhere def dsym_command(name): """Returns the command to produce .dSYM on macOS, or a no-op on elsewhere.""" return select({ "@com_chokobole_bazel_utils//:apple_debug": ( "dsymutil -f $(location :" + name + ") -o $@ 2> /dev/null" ), "//conditions:default": ( "touch $@" ), }) def dsym( name, tags = ["dsym"], visibility = ["//visibility:private"], **kwargs): native.genrule( name = name + "_dsym", srcs = [":" + name], outs = [name + ".dSYM"], output_to_bindir = 1, tags = tags, visibility = visibility, cmd = dsym_command(name), **kwargs )
""" 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 = [] while index < size: if text[index] == "(": stack.append("(") elif text[index] == ")": if stack and stack[-1] == "(": stack.pop() else: return False index += 1 return not stack def balanced_parentheses(text: str, index: int = 0) -> bool: """ each * can be one of "", ")", "(" """ if not text: return True if index < len(text): if text[index] == "*": before = text[:index] after = text[index + 1 :] return ( balanced_parentheses(before + after, index) or balanced_parentheses(before + ")" + after, index + 1) or balanced_parentheses(before + "(" + after, index + 1) ) else: return balanced_parentheses(text, index + 1) else: return is_balanced(text) if __name__ == "__main__": assert balanced_parentheses("(()*") is True assert balanced_parentheses("(()*))") is True assert balanced_parentheses("(()*)") is True assert balanced_parentheses("(*)") is True assert balanced_parentheses(")*(") is False
# 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 Python doesn't allow subclassing `bool`. ''' def __init__(self, value, reason=None): ''' Construct the `ReasonedBool`. `reason` is the reason *why* it has a value of `True` or `False`. It is usually a string, but is allowed to be of any type. ''' self.value = bool(value) self.reason = reason def __repr__(self): if self.reason is not None: return f'<{self.value} because {repr(self.reason)}>' else: # self.reason is None return f'<{self.value} with no reason>' def __eq__(self, other): return bool(self) == other def __hash__(self): return hash(bool(self)) def __neq__(self, other): return not self.__eq__(other) def __bool__(self): return self.value
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 done!今あるパイプラインについて調べたくなったときは、nlp.pipe_namesやnlp.pipelineを使ってプリントしましょう。" )
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 and needs to be # repeated until the input really gets the value set while not browser.value(form_password): browser.fill(form_password, password) browser.submit(form) def verify_phone(browser, phone=None): if browser.is_visible(form_phone): if phone: browser.fill(form_phone, phone) browser.submit(form_phone) else: raise Exception('TweetDeck login prompted for phone ' 'number, but none was provided')
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 Madrugada!!') except EOFError: break
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", "collect_multiple_files": "00_downloading_pdfs.ipynb", "get_ix": "01_parsing_roll_call_votes.ipynb", "useful_string": "01_parsing_roll_call_votes.ipynb", "SummaryParser": "01_parsing_roll_call_votes.ipynb", "VotesParser": "01_parsing_roll_call_votes.ipynb", "get_all_issues": "01_parsing_roll_call_votes.ipynb"} modules = ["download.py", "parse.py"] doc_url = "https://eschmidt42.github.io/eu_parliament/" git_url = "https://github.com/eschmidt42/eu_parliament/tree/master/" def custom_doc_links(name): return None
# 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 here as code instead of using https://github.com/jimbobbennett/CircuitPython_HMAC.git as we only need sha256, so just having the code we need saves 19k of RAM """ # pylint: disable=C0103, W0108, R0915, C0116, C0115 def __translate(key, translation): return bytes(translation[x] for x in key) TRANS_5C = bytes((x ^ 0x5C) for x in range(256)) TRANS_36 = bytes((x ^ 0x36) for x in range(256)) SHA_BLOCKSIZE = 64 SHA_DIGESTSIZE = 32 def new_shaobject(): """Struct. for storing SHA information.""" return { "digest": [0] * 8, "count_lo": 0, "count_hi": 0, "data": [0] * SHA_BLOCKSIZE, "local": 0, "digestsize": 0, } def sha_init(): """Initialize the SHA digest.""" sha_info = new_shaobject() sha_info["digest"] = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, ] sha_info["count_lo"] = 0 sha_info["count_hi"] = 0 sha_info["local"] = 0 sha_info["digestsize"] = 32 return sha_info ROR = ( lambda x, y: (((x & 0xFFFFFFFF) >> (y & 31)) | (x << (32 - (y & 31)))) & 0xFFFFFFFF ) Ch = lambda x, y, z: (z ^ (x & (y ^ z))) Maj = lambda x, y, z: (((x | y) & z) | (x & y)) S = lambda x, n: ROR(x, n) R = lambda x, n: (x & 0xFFFFFFFF) >> n Sigma0 = lambda x: (S(x, 2) ^ S(x, 13) ^ S(x, 22)) Sigma1 = lambda x: (S(x, 6) ^ S(x, 11) ^ S(x, 25)) Gamma0 = lambda x: (S(x, 7) ^ S(x, 18) ^ R(x, 3)) Gamma1 = lambda x: (S(x, 17) ^ S(x, 19) ^ R(x, 10)) def sha_transform(sha_info): W = [] d = sha_info["data"] for i in range(0, 16): W.append( (d[4 * i] << 24) + (d[4 * i + 1] << 16) + (d[4 * i + 2] << 8) + d[4 * i + 3] ) for i in range(16, 64): W.append( (Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]) & 0xFFFFFFFF ) ss = sha_info["digest"][:] # pylint: disable=too-many-arguments, line-too-long def RND(a, b, c, d, e, f, g, h, i, ki): """Compress""" t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i] t1 = Sigma0(a) + Maj(a, b, c) d += t0 h = t0 + t1 return d & 0xFFFFFFFF, h & 0xFFFFFFFF ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 0, 0x428A2F98 ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 1, 0x71374491 ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 2, 0xB5C0FBCF ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 3, 0xE9B5DBA5 ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 4, 0x3956C25B ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 5, 0x59F111F1 ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 6, 0x923F82A4 ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 7, 0xAB1C5ED5 ) ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 8, 0xD807AA98 ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 9, 0x12835B01 ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 10, 0x243185BE ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 11, 0x550C7DC3 ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 12, 0x72BE5D74 ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 13, 0x80DEB1FE ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 14, 0x9BDC06A7 ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 15, 0xC19BF174 ) ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 16, 0xE49B69C1 ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 17, 0xEFBE4786 ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 18, 0x0FC19DC6 ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 19, 0x240CA1CC ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 20, 0x2DE92C6F ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 21, 0x4A7484AA ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 22, 0x5CB0A9DC ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 23, 0x76F988DA ) ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 24, 0x983E5152 ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 25, 0xA831C66D ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 26, 0xB00327C8 ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 27, 0xBF597FC7 ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 28, 0xC6E00BF3 ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 29, 0xD5A79147 ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 30, 0x06CA6351 ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 31, 0x14292967 ) ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 32, 0x27B70A85 ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 33, 0x2E1B2138 ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 34, 0x4D2C6DFC ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 35, 0x53380D13 ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 36, 0x650A7354 ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 37, 0x766A0ABB ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 38, 0x81C2C92E ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 39, 0x92722C85 ) ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 40, 0xA2BFE8A1 ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 41, 0xA81A664B ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 42, 0xC24B8B70 ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 43, 0xC76C51A3 ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 44, 0xD192E819 ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 45, 0xD6990624 ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 46, 0xF40E3585 ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 47, 0x106AA070 ) ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 48, 0x19A4C116 ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 49, 0x1E376C08 ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 50, 0x2748774C ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 51, 0x34B0BCB5 ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 52, 0x391C0CB3 ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 53, 0x4ED8AA4A ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 54, 0x5B9CCA4F ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 55, 0x682E6FF3 ) ss[3], ss[7] = RND( ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], 56, 0x748F82EE ) ss[2], ss[6] = RND( ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], 57, 0x78A5636F ) ss[1], ss[5] = RND( ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], ss[5], 58, 0x84C87814 ) ss[0], ss[4] = RND( ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], ss[4], 59, 0x8CC70208 ) ss[7], ss[3] = RND( ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], ss[3], 60, 0x90BEFFFA ) ss[6], ss[2] = RND( ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], ss[2], 61, 0xA4506CEB ) ss[5], ss[1] = RND( ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], ss[1], 62, 0xBEF9A3F7 ) ss[4], ss[0] = RND( ss[1], ss[2], ss[3], ss[4], ss[5], ss[6], ss[7], ss[0], 63, 0xC67178F2 ) # Feedback dig = [] for i, x in enumerate(sha_info["digest"]): dig.append((x + ss[i]) & 0xFFFFFFFF) sha_info["digest"] = dig def sha_update(sha_info, buffer): """Update the SHA digest. :param dict sha_info: SHA Digest. :param str buffer: SHA buffer size. """ if isinstance(buffer, str): raise TypeError("Unicode strings must be encoded before hashing") count = len(buffer) buffer_idx = 0 clo = (sha_info["count_lo"] + (count << 3)) & 0xFFFFFFFF if clo < sha_info["count_lo"]: sha_info["count_hi"] += 1 sha_info["count_lo"] = clo sha_info["count_hi"] += count >> 29 if sha_info["local"]: i = SHA_BLOCKSIZE - sha_info["local"] if i > count: i = count # copy buffer for x in enumerate(buffer[buffer_idx : buffer_idx + i]): sha_info["data"][sha_info["local"] + x[0]] = x[1] count -= i buffer_idx += i sha_info["local"] += i if sha_info["local"] == SHA_BLOCKSIZE: sha_transform(sha_info) sha_info["local"] = 0 else: return while count >= SHA_BLOCKSIZE: # copy buffer sha_info["data"] = list(buffer[buffer_idx : buffer_idx + SHA_BLOCKSIZE]) count -= SHA_BLOCKSIZE buffer_idx += SHA_BLOCKSIZE sha_transform(sha_info) # copy buffer pos = sha_info["local"] sha_info["data"][pos : pos + count] = list(buffer[buffer_idx : buffer_idx + count]) sha_info["local"] = count def getbuf(s): if isinstance(s, str): return s.encode("ascii") return bytes(s) def sha_final(sha_info): """Finish computing the SHA Digest.""" lo_bit_count = sha_info["count_lo"] hi_bit_count = sha_info["count_hi"] count = (lo_bit_count >> 3) & 0x3F sha_info["data"][count] = 0x80 count += 1 if count > SHA_BLOCKSIZE - 8: # zero the bytes in data after the count sha_info["data"] = sha_info["data"][:count] + ([0] * (SHA_BLOCKSIZE - count)) sha_transform(sha_info) # zero bytes in data sha_info["data"] = [0] * SHA_BLOCKSIZE else: sha_info["data"] = sha_info["data"][:count] + ([0] * (SHA_BLOCKSIZE - count)) sha_info["data"][56] = (hi_bit_count >> 24) & 0xFF sha_info["data"][57] = (hi_bit_count >> 16) & 0xFF sha_info["data"][58] = (hi_bit_count >> 8) & 0xFF sha_info["data"][59] = (hi_bit_count >> 0) & 0xFF sha_info["data"][60] = (lo_bit_count >> 24) & 0xFF sha_info["data"][61] = (lo_bit_count >> 16) & 0xFF sha_info["data"][62] = (lo_bit_count >> 8) & 0xFF sha_info["data"][63] = (lo_bit_count >> 0) & 0xFF sha_transform(sha_info) dig = [] for i in sha_info["digest"]: dig.extend( [((i >> 24) & 0xFF), ((i >> 16) & 0xFF), ((i >> 8) & 0xFF), (i & 0xFF)] ) return bytes(dig) # pylint: disable=protected-access class sha256: digest_size = digestsize = SHA_DIGESTSIZE block_size = SHA_BLOCKSIZE name = "sha256" def __init__(self, s=None): """Constructs a SHA256 hash object.""" self._sha = sha_init() if s: sha_update(self._sha, getbuf(s)) def update(self, s): """Updates the hash object with a bytes-like object, s.""" sha_update(self._sha, getbuf(s)) def digest(self): """Returns the digest of the data passed to the update() method so far.""" return sha_final(self._sha.copy())[: self._sha["digestsize"]] def hexdigest(self): """Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits. """ return "".join(["%.2x" % i for i in self.digest()]) def copy(self): """Return a copy (“clone”) of the hash object.""" new = sha256() new._sha = self._sha.copy() return new class HMAC: """RFC 2104 HMAC class. Also complies with RFC 4231. This supports the API for Cryptographic Hash Functions (PEP 247). """ blocksize = 64 # 512-bit HMAC; can be changed in subclasses. def __init__(self, key, msg=None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. *OR* A hashlib constructor returning a new hash object. *OR* A hash name suitable for hashlib.new(). Defaults to hashlib.md5. Implicit default to hashlib.md5 is deprecated and will be removed in Python 3.6. Note: key and msg must be a bytes or bytearray objects. """ if not isinstance(key, (bytes, bytearray)): raise TypeError( "key: expected bytes or bytearray, but got %r" % type(key).__name__ ) digestmod = sha256 self.digest_cons = digestmod self.outer = self.digest_cons() self.inner = self.digest_cons() self.digest_size = self.inner.digest_size if hasattr(self.inner, "block_size"): blocksize = self.inner.block_size if blocksize < 16: blocksize = self.blocksize else: blocksize = self.blocksize # self.blocksize is the default blocksize. self.block_size is # effective block size as well as the public API attribute. self.block_size = blocksize if len(key) > blocksize: key = self.digest_cons(key).digest() key = key + bytes(blocksize - len(key)) self.outer.update(__translate(key, TRANS_5C)) self.inner.update(__translate(key, TRANS_36)) if msg is not None: self.update(msg) @property def name(self): """Return the name of this object""" return "hmac-" + self.inner.name def update(self, msg): """Update this hashing object with the string msg.""" self.inner.update(msg) def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ # Call __new__ directly to avoid the expensive __init__. other = self.__class__.__new__(self.__class__) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other def _current(self): """Return a hash object for the current state. To be used only internally with digest() and hexdigest(). """ hmac = self.outer.copy() hmac.update(self.inner.digest()) return hmac def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ hmac = self._current() return hmac.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead.""" hmac = self._current() return hmac.hexdigest() def new_hmac(key, msg=None): """Create a new hashing object and return it. key: The starting key for the hash. msg: if available, will immediately be hashed into the object's starting state. You can now feed arbitrary strings into the object using its update() method, and can ask for the hash value at any time by calling its digest() method. """ return HMAC(key, msg)
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` directory dest='nbtemplate', # directory in `nbextension/` namespace require='nbtemplate/main' # _also_ in `nbextension/` namespace ), dict( section='notebook', src='static', dest='nbtemplate', require='nbtemplate/templateSelector' ), dict( section='notebook', src='static', dest='nbtemplate', require='nbtemplate/blockSelector' ) ]; def load_jupyter_server_extension(nbapp): nbapp.log.info('Loaded nbtemplate!');
""" 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 = "ioctl", hdrs = ["ioctl.h"], visibility = ["//visibility:public"], ) cc_library( name = "types", hdrs = ["types.h"], visibility = ["//visibility:public"], ) cc_library( name = "fcntl", hdrs = ["fcntl.h"], visibility = ["//visibility:public"], )""" )
""" 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 "Hoheneichen", # 10 "Wellingsbuettel", # 11 "Poppenbuettel*", # 12 ) numStops = 26 stops_position = ( (0, 0), # Stop 0 (2, 0), # Stop 1 (3, 0), # Stop 2 (4, 0), # Stop 3 (5, 0), # Stop 4 (6, 0), # Stop 5 (7, 0), # Stop 6 (8, 0), # Stop 7 (9, 0), # Stop 8 (11, 0), # Stop 9 (13, 0), # Stop 10 (14, 0), # Stop 11 (15, 0), # Stop 12 (15, 1), # Stop 13 (15, 1), # Stop 14 (13, 1), # Stop 15 (12, 1), # Stop 16 (11, 1), # Stop 17 (10, 1), # Stop 18 (9, 1), # Stop 19 (8, 1), # Stop 20 (7, 1), # Stop 21 (6, 1), # Stop 22 (4, 1), # Stop 23 (2, 1), # Stop 24 (1, 1), # Stop 25 ) stops_distance = ( (0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 0 (0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 1 (0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 2 (0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 3 (0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 4 (0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 5 (0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 6 (0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 7 (0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 8 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 9 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 10 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 11 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 12 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 13 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 14 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 15 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 16 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0), # Stop 17 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), # Stop 18 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0), # Stop 19 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0), # Stop 20 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), # Stop 21 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), # Stop 22 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0), # Stop 23 (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2), # Stop 24 (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 25 ) station_start = 0 """ TRAMS """ numTrams = 18 tram_capacity = 514 tram_capacity_cargo = 304 tram_capacity_min_passenger = 208 tram_capacity_min_cargo = 0 tram_speed = 1 tram_headway = 1 tram_min_service = 1 tram_max_service = 10 min_time_next_tram = 0.333 tram_travel_deviation = 0.167 """ PASSENGERS """ passenger_set = "pas-20210422-1717-int1" passenger_service_time_board = 0.0145 passenger_service_time_alight = 0.0145 """ CARGO """ numCargo = 70 cargo_size = 4 cargo_station_destination = ( 8, # 0 4, # 1 8, # 2 5, # 3 8, # 4 3, # 5 4, # 6 5, # 7 3, # 8 12, # 9 12, # 10 5, # 11 5, # 12 3, # 13 4, # 14 5, # 15 5, # 16 8, # 17 5, # 18 5, # 19 8, # 20 5, # 21 12, # 22 8, # 23 4, # 24 5, # 25 8, # 26 5, # 27 12, # 28 3, # 29 4, # 30 12, # 31 12, # 32 4, # 33 3, # 34 4, # 35 12, # 36 12, # 37 5, # 38 12, # 39 3, # 40 5, # 41 5, # 42 4, # 43 4, # 44 3, # 45 12, # 46 5, # 47 8, # 48 3, # 49 5, # 50 3, # 51 8, # 52 12, # 53 4, # 54 8, # 55 8, # 56 3, # 57 3, # 58 12, # 59 8, # 60 3, # 61 3, # 62 8, # 63 4, # 64 12, # 65 12, # 66 5, # 67 3, # 68 4, # 69 ) cargo_release = ( 2, # 0 3, # 1 3, # 2 5, # 3 6, # 4 6, # 5 7, # 6 8, # 7 8, # 8 9, # 9 9, # 10 10, # 11 12, # 12 13, # 13 14, # 14 15, # 15 16, # 16 17, # 17 18, # 18 21, # 19 22, # 20 24, # 21 25, # 22 26, # 23 27, # 24 28, # 25 28, # 26 30, # 27 32, # 28 33, # 29 33, # 30 34, # 31 35, # 32 37, # 33 37, # 34 37, # 35 37, # 36 38, # 37 39, # 38 41, # 39 41, # 40 43, # 41 44, # 42 45, # 43 46, # 44 46, # 45 47, # 46 48, # 47 49, # 48 49, # 49 51, # 50 55, # 51 56, # 52 57, # 53 61, # 54 61, # 55 61, # 56 62, # 57 64, # 58 64, # 59 65, # 60 65, # 61 66, # 62 66, # 63 67, # 64 70, # 65 70, # 66 71, # 67 71, # 68 72, # 69 ) cargo_station_deadline = ( 33, # 0 119, # 1 119, # 2 176, # 3 123, # 4 59, # 5 72, # 6 171, # 7 18, # 8 90, # 9 175, # 10 142, # 11 88, # 12 84, # 13 105, # 14 170, # 15 155, # 16 156, # 17 140, # 18 173, # 19 123, # 20 126, # 21 91, # 22 36, # 23 87, # 24 127, # 25 144, # 26 134, # 27 141, # 28 163, # 29 101, # 30 108, # 31 144, # 32 47, # 33 162, # 34 76, # 35 175, # 36 97, # 37 87, # 38 164, # 39 114, # 40 143, # 41 142, # 42 55, # 43 56, # 44 56, # 45 57, # 46 118, # 47 160, # 48 59, # 49 112, # 50 168, # 51 170, # 52 139, # 53 71, # 54 71, # 55 71, # 56 82, # 57 135, # 58 90, # 59 109, # 60 161, # 61 151, # 62 128, # 63 77, # 64 80, # 65 169, # 66 97, # 67 129, # 68 99, # 69 ) cargo_max_delay = 3 cargo_service_time_load = 0.3333333333333333 cargo_service_time_unload = 0.25 """ parameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.html """ #initial entropy entropy = 8991598675325360468762009371570610170 #index for seed sequence child child_seed_index = ( 0, # 0 ) """ Results from timetabling """ scheme = "SI" method = "timetabling_closed" passengerData = "0-rep" downstream_cargo = False delivery_optional = False assignment_method = "timetabling_closed" operating = ( False, # 0 False, # 1 False, # 2 False, # 3 True, # 4 True, # 5 True, # 6 True, # 7 True, # 8 True, # 9 True, # 10 True, # 11 True, # 12 True, # 13 True, # 14 True, # 15 True, # 16 True, # 17 ) tram_tour = ( (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 1 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 2 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 3 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 4 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 5 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 6 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 7 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 8 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 9 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 10 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 11 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 12 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 13 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 14 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 15 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 16 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 17 ) tram_time_arrival = ( (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 0 (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 1 (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 2 (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 3 (0.0, 3.0, 5.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 21.0, 24.0, 26.0, 28.0, 30.0, 32.0, 40.0, 43.0, 46.0, 50.0, 52.0, 54.0, 58.0, 60.0, 64.0, 70.0, 80.0), # 4 (2.0, 11.0, 13.0, 15.0, 17.0, 19.0, 22.0, 24.0, 27.0, 30.0, 33.0, 35.0, 37.0, 39.0, 41.0, 48.0, 60.0, 66.0, 71.0, 82.0, 84.0, 86.0, 88.0, 90.0, 92.0, 95.0), # 5 (17.0, 29.0, 31.0, 33.0, 35.0, 37.0, 39.0, 41.0, 43.0, 46.0, 52.0, 54.0, 61.0, 64.0, 72.0, 74.0, 77.0, 80.0, 82.0, 84.0, 86.0, 88.0, 90.0, 92.0, 94.0, 97.0), # 6 (33.0, 40.0, 42.0, 44.0, 46.0, 48.0, 50.0, 52.0, 56.0, 59.0, 64.0, 67.0, 69.0, 72.0, 74.0, 76.0, 79.0, 82.0, 84.0, 86.0, 88.0, 90.0, 92.0, 94.0, 96.0, 99.0), # 7 (39.0, 48.0, 50.0, 52.0, 54.0, 56.0, 58.0, 60.0, 62.0, 65.0, 68.0, 70.0, 72.0, 74.0, 77.0, 79.0, 82.0, 85.0, 87.0, 89.0, 91.0, 93.0, 95.0, 97.0, 99.0, 102.0), # 8 (47.0, 50.0, 52.0, 54.0, 56.0, 58.0, 60.0, 62.0, 64.0, 67.0, 70.0, 72.0, 74.0, 77.0, 79.0, 81.0, 84.0, 87.0, 89.0, 91.0, 93.0, 95.0, 97.0, 99.0, 101.0, 104.0), # 9 (49.0, 52.0, 56.0, 59.0, 64.0, 66.0, 68.0, 70.0, 72.0, 75.0, 78.0, 80.0, 82.0, 84.0, 86.0, 88.0, 91.0, 94.0, 96.0, 98.0, 100.0, 102.0, 105.0, 107.0, 109.0, 112.0), # 10 (53.0, 64.0, 66.0, 68.0, 70.0, 72.0, 74.0, 76.0, 78.0, 81.0, 84.0, 86.0, 88.0, 90.0, 92.0, 94.0, 97.0, 103.0, 105.0, 107.0, 109.0, 120.0, 131.0, 142.0, 145.0, 157.0), # 11 (63.0, 67.0, 69.0, 71.0, 73.0, 75.0, 77.0, 79.0, 81.0, 84.0, 87.0, 89.0, 91.0, 94.0, 96.0, 107.0, 113.0, 123.0, 127.0, 133.0, 138.0, 144.0, 151.0, 162.0, 164.0, 168.0), # 12 (66.0, 70.0, 72.0, 74.0, 76.0, 78.0, 80.0, 82.0, 84.0, 87.0, 90.0, 92.0, 95.0, 97.0, 108.0, 113.0, 122.0, 133.0, 136.0, 138.0, 149.0, 153.0, 162.0, 164.0, 167.0, 170.0), # 13 (69.0, 73.0, 75.0, 77.0, 79.0, 81.0, 83.0, 85.0, 87.0, 90.0, 93.0, 95.0, 97.0, 108.0, 113.0, 122.0, 132.0, 137.0, 142.0, 153.0, 155.0, 163.0, 165.0, 167.0, 169.0, 172.0), # 14 (72.0, 75.0, 77.0, 79.0, 81.0, 83.0, 85.0, 87.0, 89.0, 94.0, 97.0, 99.0, 109.0, 115.0, 126.0, 135.0, 145.0, 157.0, 159.0, 161.0, 163.0, 165.0, 167.0, 169.0, 171.0, 174.0), # 15 (74.0, 77.0, 79.0, 81.0, 83.0, 91.0, 95.0, 97.0, 99.0, 102.0, 114.0, 125.0, 136.0, 138.0, 147.0, 152.0, 156.0, 159.0, 161.0, 163.0, 165.0, 167.0, 169.0, 171.0, 173.0, 176.0), # 16 (76.0, 85.0, 87.0, 89.0, 91.0, 97.0, 100.0, 102.0, 113.0, 125.0, 133.0, 138.0, 148.0, 150.0, 152.0, 155.0, 158.0, 161.0, 163.0, 165.0, 167.0, 169.0, 171.0, 173.0, 175.0, 178.0), # 17 ) tram_time_departure = ( (-0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0), # 0 (-0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0), # 1 (-0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0), # 2 (-0.0, -0.0, -0.0, -0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0), # 3 (1.0, 4.0, 7.0, 9.0, 11.0, 13.0, 15.0, 17.0, 19.0, 22.0, 25.0, 27.0, 29.0, 31.0, 39.0, 41.0, 44.0, 49.0, 51.0, 53.0, 57.0, 59.0, 63.0, 69.0, 78.0, 81.0), # 4 (9.0, 12.0, 14.0, 16.0, 18.0, 21.0, 23.0, 26.0, 28.0, 31.0, 34.0, 36.0, 38.0, 40.0, 47.0, 58.0, 64.0, 70.0, 81.0, 83.0, 85.0, 87.0, 89.0, 91.0, 93.0, 96.0), # 5 (27.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0, 42.0, 44.0, 50.0, 53.0, 60.0, 63.0, 71.0, 73.0, 75.0, 78.0, 81.0, 83.0, 85.0, 87.0, 89.0, 91.0, 93.0, 95.0, 98.0), # 6 (38.0, 41.0, 43.0, 45.0, 47.0, 49.0, 51.0, 55.0, 57.0, 62.0, 66.0, 68.0, 71.0, 73.0, 75.0, 77.0, 80.0, 83.0, 85.0, 87.0, 89.0, 91.0, 93.0, 95.0, 97.0, 101.0), # 7 (46.0, 49.0, 51.0, 53.0, 55.0, 57.0, 59.0, 61.0, 63.0, 66.0, 69.0, 71.0, 73.0, 76.0, 78.0, 80.0, 83.0, 86.0, 88.0, 90.0, 92.0, 94.0, 96.0, 98.0, 100.0, 103.0), # 8 (48.0, 51.0, 53.0, 55.0, 57.0, 59.0, 61.0, 63.0, 65.0, 68.0, 71.0, 73.0, 76.0, 78.0, 80.0, 82.0, 85.0, 88.0, 90.0, 92.0, 94.0, 96.0, 98.0, 100.0, 102.0, 105.0), # 9 (50.0, 55.0, 58.0, 63.0, 65.0, 67.0, 69.0, 71.0, 73.0, 76.0, 79.0, 81.0, 83.0, 85.0, 87.0, 89.0, 92.0, 95.0, 97.0, 99.0, 101.0, 104.0, 106.0, 108.0, 110.0, 113.0), # 10 (62.0, 65.0, 67.0, 69.0, 71.0, 73.0, 75.0, 77.0, 79.0, 82.0, 85.0, 87.0, 89.0, 91.0, 93.0, 95.0, 101.0, 104.0, 106.0, 108.0, 119.0, 130.0, 141.0, 144.0, 155.0, 162.0), # 11 (65.0, 68.0, 70.0, 72.0, 74.0, 76.0, 78.0, 80.0, 82.0, 85.0, 88.0, 90.0, 93.0, 95.0, 106.0, 111.0, 121.0, 126.0, 132.0, 137.0, 143.0, 150.0, 161.0, 163.0, 166.0, 169.0), # 12 (68.0, 71.0, 73.0, 75.0, 77.0, 79.0, 81.0, 83.0, 85.0, 88.0, 91.0, 94.0, 96.0, 107.0, 112.0, 120.0, 131.0, 135.0, 137.0, 148.0, 152.0, 161.0, 163.0, 166.0, 168.0, 171.0), # 13 (71.0, 74.0, 76.0, 78.0, 80.0, 82.0, 84.0, 86.0, 88.0, 91.0, 94.0, 96.0, 107.0, 112.0, 121.0, 130.0, 135.0, 141.0, 152.0, 154.0, 162.0, 164.0, 166.0, 168.0, 170.0, 173.0), # 14 (73.0, 76.0, 78.0, 80.0, 82.0, 84.0, 86.0, 88.0, 92.0, 95.0, 98.0, 108.0, 114.0, 125.0, 134.0, 143.0, 155.0, 158.0, 160.0, 162.0, 164.0, 166.0, 168.0, 170.0, 172.0, 175.0), # 15 (75.0, 78.0, 80.0, 82.0, 90.0, 94.0, 96.0, 98.0, 100.0, 112.0, 124.0, 135.0, 137.0, 146.0, 151.0, 154.0, 157.0, 160.0, 162.0, 164.0, 166.0, 168.0, 170.0, 172.0, 174.0, 177.0), # 16 (83.0, 86.0, 88.0, 90.0, 96.0, 99.0, 101.0, 112.0, 123.0, 131.0, 137.0, 147.0, 149.0, 151.0, 154.0, 156.0, 159.0, 162.0, 164.0, 166.0, 168.0, 170.0, 172.0, 174.0, 176.0, 179.0), # 17 ) cargo_tram_assignment = ( 5, # 0 5, # 1 7, # 2 5, # 3 7, # 4 5, # 5 7, # 6 5, # 7 5, # 8 7, # 9 7, # 10 7, # 11 7, # 12 6, # 13 8, # 14 8, # 15 6, # 16 6, # 17 6, # 18 6, # 19 7, # 20 6, # 21 6, # 22 6, # 23 11, # 24 7, # 25 8, # 26 8, # 27 7, # 28 8, # 29 7, # 30 14, # 31 11, # 32 7, # 33 8, # 34 7, # 35 7, # 36 10, # 37 11, # 38 17, # 39 8, # 40 11, # 41 8, # 42 8, # 43 9, # 44 9, # 45 9, # 46 11, # 47 11, # 48 10, # 49 12, # 50 12, # 51 11, # 52 11, # 53 11, # 54 11, # 55 11, # 56 12, # 57 12, # 58 12, # 59 13, # 60 13, # 61 13, # 62 13, # 63 13, # 64 14, # 65 16, # 66 17, # 67 17, # 68 17, # 69 )
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': -0.0, 'z_val': -0.2588196396827698}, 'position': { 'x_val': 1.5999999046325684, 'y_val': 10.800000190734863, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.8660249710083008, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.5000007152557373}, 'position': { 'x_val': 8.887084007263184, 'y_val': 18.478761672973633, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.7071061134338379, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.7071074843406677}, 'position': { 'x_val': 18.74375343322754, 'y_val': 22.20650863647461, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.7071061134338379, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.7071074843406677}, 'position': { 'x_val': 30.04375457763672, 'y_val': 22.20648956298828, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.4999988079071045, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.8660261034965515}, 'position': { 'x_val': 39.04375457763672, 'y_val': 19.206478118896484, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.17364656925201416, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.9848079681396484}, 'position': { 'x_val': 45.74375534057617, 'y_val': 11.706478118896484, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 1.8477439880371094e-06, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 1.0}, 'position': { 'x_val': 45.74375534057617, 'y_val': 2.2064781188964844, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.5000025629997253, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.8660238981246948}, 'position': { 'x_val': 40.343753814697266, 'y_val': -4.793521404266357, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.7071094512939453, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.7071040272712708}, 'position': { 'x_val': 30.74375343322754, 'y_val': -7.893521785736084, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.7071094512939453, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.7071040272712708}, 'position': { 'x_val': 18.54375457763672, 'y_val': -7.893521785736084, 'z_val': 2.0199999809265137}}, { 'orientation': { 'w_val': 0.8191542029380798, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.5735733509063721}, 'position': { 'x_val': 9.543754577636719, 'y_val': -5.093521595001221, 'z_val': 2.0199999809265137}}] soccer_medium_gate_pose_dicts = [ { 'orientation': { 'w_val': 0.5735755562782288, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.8191526532173157}, 'position': { 'x_val': 10.388415336608887, 'y_val': 80.77406311035156, 'z_val': -43.57999801635742}}, { 'orientation': { 'w_val': 0.34201890230178833, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.939693033695221}, 'position': { 'x_val': 18.11046600341797, 'y_val': 76.26078033447266, 'z_val': -43.57999801635742}}, { 'orientation': { 'w_val': 0.1736472249031067, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.9848079085350037}, 'position': { 'x_val': 25.433794021606445, 'y_val': 66.28687286376953, 'z_val': -43.57999801635742}}, { 'orientation': { 'w_val': 0.17364656925201416, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.9848079681396484}, 'position': { 'x_val': 30.065513610839844, 'y_val': 56.549530029296875, 'z_val': -43.57999801635742}}, { 'orientation': { 'w_val': 2.562999725341797e-06, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 1.0}, 'position': { 'x_val': 32.30064392089844, 'y_val': 45.6310920715332, 'z_val': -43.87999725341797}}, { 'orientation': { 'w_val': 0.7071093916893005, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.7071041464805603}, 'position': { 'x_val': 26.503353118896484, 'y_val': 38.19984436035156, 'z_val': -43.37999725341797}}, { 'orientation': { 'w_val': 0.7660470008850098, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.642784595489502}, 'position': { 'x_val': 3.264113664627075, 'y_val': 37.569061279296875, 'z_val': -43.57999801635742}}, { 'orientation': { 'w_val': 0.9848085641860962, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.17364364862442017}, 'position': { 'x_val': -16.862957000732422, 'y_val': 45.41843795776367, 'z_val': -46.57999801635742}}, { 'orientation': { 'w_val': 0.9848069548606873, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.17365287244319916}, 'position': { 'x_val': -15.493884086608887, 'y_val': 63.18687438964844, 'z_val': -52.07999801635742}}, { 'orientation': { 'w_val': 0.8191484212875366, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.5735815763473511}, 'position': { 'x_val': -6.320737361907959, 'y_val': 78.21236419677734, 'z_val': -55.779998779296875}}, { 'orientation': { 'w_val': 0.8191484212875366, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.5735815763473511}, 'position': { 'x_val': 5.143640041351318, 'y_val': 82.38504791259766, 'z_val': -55.779998779296875}}, { 'orientation': { 'w_val': 0.7071030139923096, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.7071105241775513}, 'position': { 'x_val': 14.558510780334473, 'y_val': 84.4320297241211, 'z_val': -55.18000030517578}}, { 'orientation': { 'w_val': 0.7071030139923096, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.7071105241775513}, 'position': { 'x_val': 23.858510971069336, 'y_val': 82.83203125, 'z_val': -32.07999801635742}}, { 'orientation': { 'w_val': 0.3420146107673645, 'x_val': 0.0, 'y_val': -0.0, 'z_val': -0.9396945834159851}, 'position': { 'x_val': 38.25851058959961, 'y_val': 78.13202667236328, 'z_val': -31.3799991607666}}, { 'orientation': { 'w_val': 6.258487701416016e-06, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 1.0}, 'position': { 'x_val': 51.058509826660156, 'y_val': 52.13203048706055, 'z_val': -25.8799991607666}}, { 'orientation': { 'w_val': 0.3420267701148987, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.9396902322769165}, 'position': { 'x_val': 44.95851135253906, 'y_val': 38.932029724121094, 'z_val': -25.8799991607666}}, { 'orientation': { 'w_val': 0.7071123123168945, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.7071012258529663}, 'position': { 'x_val': 25.958515167236328, 'y_val': 26.33203125, 'z_val': -19.8799991607666}}, { 'orientation': { 'w_val': 0.7071123123168945, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.7071012258529663}, 'position': { 'x_val': 11.658514976501465, 'y_val': 26.33203125, 'z_val': -12.779999732971191}}, { 'orientation': { 'w_val': 0.5735827684402466, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.8191476464271545}, 'position': { 'x_val': -10.141484260559082, 'y_val': 22.632030487060547, 'z_val': -6.37999963760376}}, { 'orientation': { 'w_val': 0.5000063180923462, 'x_val': -0.0, 'y_val': 0.0, 'z_val': 0.8660216927528381}, 'position': { 'x_val': -24.641483306884766, 'y_val': 9.132031440734863, 'z_val': 2.119999885559082}}]
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) collatz(numberToSequence) collatzCalled = True except: print ('Error: Value input must be an INTEGER') numberToSequence = input() def collatz(numberToSequence): while numberToSequence != 1: if numberToSequence % 2 == 0: numberToSequence = numberToSequence // 2 print (numberToSequence) elif numberToSequence % 2 == 1: numberToSequence = 3 * numberToSequence + 1 print (numberToSequence) tryCollatz(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), ('mul',), ('add',), ] m = Machine()
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(0) if (a != 0): break res.append(a) # 뽑은 인형의 총 개수 org_len = len(res) # 터트릴수 있는건 최소 2개이상이 존재 해야 하기 때문 while (len(res) >= 2): temp = len(res) # 2개가 연속으로 있는 경우 제거 for i in range(temp-1): if (res[i] == res[i+1]): res.pop(i + 1) res.pop(i) break # 끝까지 다 갔는데 터지지 않은경우 종료 if (i == temp-2): break # 터트려진 인형 = 전체 인형 - 남아 있는 인형 answer = org_len - len(res) return answer if __name__ == "__main__": # execute only if run as a script solution([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]], [1,5,3,5,1,2,1,4])
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.append(mat1) xDeg -= derece mat2 = [] for i in range(derece + 1): gecici = 0 for j in range(len(liste)): gecici += liste[j] * (j + 1) ** i mat2.append(gecici) for i in range(derece + 1): gecici1 = mat[i][i] for j in range(i + 1, derece + 1): ort = gecici1 / mat[j][i] mat2[j] = mat2[j] * ort - mat2[i] for k in range(derece + 1): mat[j][k] = mat[j][k] * ort - mat[i][k] for i in range(derece, -1, -1): gecici1 = mat[i][i] for j in range(i - 1, -1, -1): ort = gecici1 / mat[j][i] mat2[j] = mat2[j] * ort - mat2[i] for k in range(derece + 1): mat[j][k] = mat[j][k] * ort - mat[i][k] for i in range(derece + 1): mat2[i] = mat2[i] / mat[i][i] yDeg = 0 for i in range(len(liste)): yDeg += liste[i] yDeg = yDeg / len(liste) stn = 0 str = 0 for i in range(len(liste)): xDeg = liste[i] stn += (liste[i] - yDeg) ** 2 for j in range(len(mat2)): xDeg -= mat2[j] * (i + 1) ** j xDeg = xDeg ** 2 str += xDeg a = ((stn - str) / stn) ** (1 / 2) return mat2, a def katsayi(r1, r2, r3, r4, r5, r6, dosya2): dosya2.write("<----------------------------------------->\n") dosya2.write("r1 = " + str(r1) + " r2 = " + str(r2) + " r 3 = " + str(r3) + "r4 = " + str(r4) + " r5 = " + str( r5) + " r6 = " + str(r6) + "\n") dizi = [r1, r2, r3, r4, r5, r6] for i in range(len(dizi)): if dizi[i] == max(dizi): dosya2.write("r=" + str(dizi[i]) + " " + str(i + 1) + ".\n") def katsayiHes(pol1, pol2, pol3, pol4, pol5, pol6, dosya2, a1, a2): dosya2.write(" \n" + " \n" + " \n" + "polinomlarin katsayilari " + str(a1) + " ---- " + str(a2) + " \n") a1 = a1 + 10 a2 = a2 + 10 dosya2.write("1.dereceden katsayilar \nk1 = " + str(pol1[0]) + " k1 = " + str(pol1[1]) + "\n") dosya2.write( "2.dereceden katsayilar \nk0 = " + str(pol2[0]) + " k1 = " + str(pol2[1]) + " k2 =" + str(pol2[2]) + "\n") dosya2.write("3.dereceden katsayilar \nk0 = " + str(pol3[0]) + " k1 = " + str(pol3[1]) + " k2 =" + str( pol3[2]) + " k3 = " + str(pol3[3]) + "\n") dosya2.write("4.dereceden katsayilar \nk0 = " + str(pol4[0]) + " k1 = " + str(pol4[1]) + " k2 =" + str( pol4[2]) + " k3 = " + str(pol4[3]) + " k4 = " + str(pol4[4]) + "\n") dosya2.write("5.dereceden katsayilar \nk0 = " + str(pol5[0]) + " k1 = " + str(pol5[1]) + " k2 =" + str( pol5[2]) + " k3 = " + str(pol5[3]) + " k4 = " + str(pol5[4]) + " k5 = " + str(pol5[5]) + "\n") dosya2.write("6.dereceden katsayilar \nk0 = " + str(pol6[0]) + " k1 = " + str(pol6[1]) + " k2 =" + str( pol6[2]) + " k3 = " + str(pol6[3]) + " k4 = " + str(pol6[4]) + " k5 = " + str(pol6[5]) + " k6 = " + str( pol6[6]) + "\n") return a1,a2 a1=1 a2=10 dosya = open("veriler.txt", "r") liste = dosya.readlines() for i in range(len(liste)): liste[i] = int(liste[i]) pol_1, r1 = formulUygula(1, liste) pol_2, r2 = formulUygula(2, liste) pol_3, r3 = formulUygula(3, liste) pol_4, r4 = formulUygula(4, liste) pol_5, r5 = formulUygula(5, liste) pol_6, r6 = formulUygula(6, liste) dosya.close() dosya2 = open("sonuc.txt", "w") a1,a2=katsayiHes(pol_1, pol_2, pol_3, pol_4, pol_5, pol_6, dosya2, a1, a2) katsayi(r1, r2, r3, r4, r5, r6, dosya2) for i in range(len(liste) // 10): onlu = [] for j in range(10): onlu.append(liste[10 * i + j]) pol_1, r1 = formulUygula(1, onlu) pol_2, r2 = formulUygula(2, onlu) pol_3, r3 = formulUygula(3, onlu) pol_4, r4 = formulUygula(4, onlu) pol_5, r5 = formulUygula(5, onlu) pol_6, r6 = formulUygula(6, onlu) a1,a2=katsayiHes(pol_1, pol_2, pol_3, pol_4, pol_5, pol_6, dosya2, a1, a2) katsayi(r1, r2, r3, r4, r5, r6, dosya2) dosya2.close()
# 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 manager dict. :param app: The core Sphinx app object. Mostly used for config. """ super(LineManager, self).__init__() self.app = app @property def config(self): """ Return Sphinx config object. """ return self.app.config def add_family(self, major_number): """ Expand to a new release line with given ``major_number``. This will flesh out mandatory buckets like ``unreleased_bugfix`` and do other necessary bookkeeping. """ # Normally, we have separate buckets for bugfixes vs features keys = ["unreleased_bugfix", "unreleased_feature"] # But unstable prehistorical releases roll all up into just # 'unreleased' if major_number == 0 and self.config.releases_unstable_prehistory: keys = ["unreleased"] # Either way, the buckets default to an empty list self[major_number] = {key: [] for key in keys} @property def unstable_prehistory(self): """ Returns True if 'unstable prehistory' behavior should be applied. Specifically, checks config & whether any non-0.x releases exist. """ return self.config.releases_unstable_prehistory and not self.has_stable_releases @property def stable_families(self): """ Returns release family numbers which aren't 0 (i.e. prehistory). """ return [x for x in self if x != 0] @property def has_stable_releases(self): """ Returns whether stable (post-0.x) releases seem to exist. """ nonzeroes = self.stable_families # Nothing but 0.x releases -> yup we're prehistory if not nonzeroes: return False # Presumably, if there's >1 major family besides 0.x, we're at least # one release into the 1.0 (or w/e) line. if len(nonzeroes) > 1: return True # If there's only one, we may still be in the space before its N.0.0 as # well; we can check by testing for existence of bugfix buckets return any(x for x in self[nonzeroes[0]] if not x.startswith("unreleased"))
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 lines intersect """ # Set up the input with open('input-05.txt', 'r') as file: vents = file.readlines() # Solution to part 1 def solve_1(vent_map, dimension): # Assume the ocean_floor is a dimension x dimension grid ocean_floor = [[0 for i in range(dimension)] for j in range(dimension)] for vent in vent_map: coords = vent.split('->') start = coords[0].split(',') end = coords[1].split(',') if int(start[0]) != int(end[0]) and int(start[1]) != int(end[1]): continue if int(start[0]) == int(end[0]): # Same x coordinate => row changes, column remains the same start_row, end_row = int(start[1]), int(end[1]) if start_row > end_row: start_row, end_row = end_row, start_row for i in range(start_row, end_row + 1): ocean_floor[i][int(start[0])] += 1 elif int(start[1]) == int(end[1]): # Same y coordinate => column changes, row remains the same start_column, end_column = int(start[0]), int(end[0]) if start_column > end_column: start_column, end_column = end_column, start_column for i in range(start_column, end_column + 1): ocean_floor[int(start[1])][i] += 1 dangerous_vents = 0 for row in ocean_floor: for cell in row: if cell >= 2: dangerous_vents += 1 return dangerous_vents, ocean_floor ans, _ = solve_1(vents, 10) print(ans) # Answer was 7414 # Define helper functions def get_diagonal_points(start_x, start_y, end_x, end_y): """ Returns a list of tuples that contains diagonal points from one point to another :param start_x: :param start_y: :param end_x: :param end_y: :return: """ points = [] y_inc = 1 if int(start_x) > int(end_x): start_x, start_y, end_x, end_y = end_x, end_y, start_x, start_y if start_y > end_y: y_inc = -1 while start_x <= end_x: points.append((start_x, start_y)) start_x += 1 start_y += y_inc return points def get_points_from_line(line): """ Returns a list of points on a vertical or horizontal line. Returns an empty list otherwise :param line: :return: """ coords = line.split('->') start = list(map(lambda x: int(x), coords[0].split(','))) end = list(map(lambda x: int(x), coords[1].split(','))) points = [] if start[0] == end[0]: if start[1] > end[1]: start, end = end, start row = start[1] while row <= end[1]: points.append((start[0], row)) row += 1 elif start[1] == end[1]: if start[0] > end[0]: start, end = end, start col = start[0] while col <= end[0]: points.append((col, start[1])) col += 1 elif start[0] != end[0]: slope = (int(start[1]) - int(end[1])) / (int(start[0]) - int(end[0])) if abs(slope) == 1: points = get_diagonal_points(start[0], start[1], end[0], end[1]) return points def update_ocean_floor(points, ocean_floor): """ Updates all the given points on the ocean floor and increments their value by 1 :param points: :param ocean_floor: :return: """ for point in points: ocean_floor[point[0]][point[1]] += 1 return ocean_floor # Solution to part 2 def solve_2(vent_map, dimension): ocean_floor = [[0 for i in range(dimension)] for j in range(dimension)] # Also consider lines at 45 degrees for vent in vent_map: points = get_points_from_line(vent) update_ocean_floor(points, ocean_floor) dangerous_vents = 0 for row in ocean_floor: for cell in row: if cell >= 2: dangerous_vents += 1 return dangerous_vents ans = solve_2(vents, 1000) print(ans) # Answer was 19676
# # 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:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint") DisplayStringUnsized, modules = mibBuilder.importSymbols("AT-SMI-MIB", "DisplayStringUnsized", "modules") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, ModuleIdentity, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, MibIdentifier, NotificationType, Counter64, iso, ObjectIdentity, Integer32, Unsigned32, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ModuleIdentity", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "MibIdentifier", "NotificationType", "Counter64", "iso", "ObjectIdentity", "Integer32", "Unsigned32", "Bits", "Gauge32") TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "DisplayString", "TextualConvention") ds3 = ModuleIdentity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109)) ds3.setRevisions(('2006-06-28 12:22',)) if mibBuilder.loadTexts: ds3.setLastUpdated('200606281222Z') if mibBuilder.loadTexts: ds3.setOrganization('Allied Telesis, Inc') ds3TrapTable = MibTable((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 1), ) if mibBuilder.loadTexts: ds3TrapTable.setStatus('current') ds3TrapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: ds3TrapEntry.setStatus('current') ds3TcaTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: ds3TcaTrapEnable.setStatus('current') ds3TrapError = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=NamedValues(("ds3NoError", 1), ("ds3PES", 2), ("ds3PSES", 3), ("ds3SEFs", 4), ("ds3UAS", 5), ("ds3LCVs", 6), ("ds3PCVs", 7), ("ds3LESs", 8), ("ds3CCVs", 9), ("ds3CESs", 10), ("ds3CSESs", 11))).clone('ds3NoError')).setMaxAccess("readonly") if mibBuilder.loadTexts: ds3TrapError.setStatus('current') ds3TrapLoc = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("ds3NoLoc", 1), ("ds3Near", 2), ("ds3Far", 3))).clone('ds3NoLoc')).setMaxAccess("readonly") if mibBuilder.loadTexts: ds3TrapLoc.setStatus('current') ds3TrapInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("ds3NoInt", 1), ("ds3Fifteen", 2), ("ds3Twentyfour", 3))).clone('ds3NoInt')).setMaxAccess("readonly") if mibBuilder.loadTexts: ds3TrapInterval.setStatus('current') ds3Traps = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 0)) tcaTrap = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 109, 0, 1)).setObjects(("AT-DS3-MIB", "ds3TrapError"), ("AT-DS3-MIB", "ds3TrapLoc"), ("AT-DS3-MIB", "ds3TrapInterval")) if mibBuilder.loadTexts: tcaTrap.setStatus('current') mibBuilder.exportSymbols("AT-DS3-MIB", ds3TrapTable=ds3TrapTable, PYSNMP_MODULE_ID=ds3, tcaTrap=tcaTrap, ds3Traps=ds3Traps, ds3=ds3, ds3TrapInterval=ds3TrapInterval, ds3TrapLoc=ds3TrapLoc, ds3TrapEntry=ds3TrapEntry, ds3TrapError=ds3TrapError, ds3TcaTrapEnable=ds3TcaTrapEnable)
# 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) # ('new_value', 'total') print(av.__code__.co_freevars) # ('series',) # print(type(av.__code__)) print(av.__closure__, type(av.__closure__)) print(av.__closure__[0].cell_contents, type(av.__closure__)) # The nonlocal Declaration count = 1000 total = 10000 def make_Averager(): count = 0 total = 0 def averager(new_value): # count = count + 1 which is local scope and undefined hence add non local # global count, total nonlocal count, total count += 1 print(total) print(count) total += new_value return total / count return averager # UnboundLocalError: local variable 'count' referenced before assignment # av1 = make_Averager() print(av1(100))
# Public Key PK = "fubotong" # Push request actively PUSH = 0 # Secret Key SK = "(*^%]@XUNLEI`12f&amp;^" # 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_SERVER CREATE_BT_SERVER = "%s/create_bt" % TASK_SERVER CREATE_ED2K_SERVER = "%s/create_ed2k" % TASK_SERVER QUERY_SERVER = "%s/query" % TASK_SERVER UPLOAD_BT_SERVER = "%s/upload_torrent" % TASK_SERVER QUERY_BT_SERVER = "%s/torrent_info" % TASK_SERVER #NEW_URL_SERVER = "http://180.97.151.98:80" NEW_URL_SERVER = "http://gdl.lixian.vip.xunlei.com" # using gen new url MID = 666 AK = "9:0:999:0" THRESHOLD = 150 SRCID = 6 VERNO = 1 UI = 'hzfubotong' FID_LEN = 64 FID_DECODED_LEN = FID_LEN / 4 * 3 # define error code OFFLINE_TIMEOUT = -1 OFFLINE_HTTP_ERROR = -2 OFFLINE_STATUS_ERROR = -3 OFFLINE_DOWNLOAD_ERROR = -4 OFFLINE_GENURL_ERROR = -5 OFFLINE_UNKNOWN_ERROR = -6 #pk fubotong #appkey hzfubotong #sk (*^%]@XUNLEI`12f&amp;^ #ak 9:0:999:0
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、如果顾空间,需要保存每行/每列的边界 测试: 1、用了顾空间的方案,用时击败86%,内存消耗击败5%,看来有问题 2、看答案后修改,用时击败86%,内存消耗击败84%,成功 答案: 1、方法一:遍历,然后建立一个同等大小的矩阵,True and False 2、方法二:按层遍历 我的方案: 1、依然是模拟的方案 2、但是不要那么多空间了,我们只保存每行/每列的边界就好了 3、最终优化,我们只保存横向边界和纵向边界就好了 """ result = [] rowMax = len(matrix) colMax = len(matrix[0]) # rowBound = [[-1,colMax] for _ in range(rowMax)] # colBound = [[-1,rowMax] for _ in range(colMax)] rowBound = [-1,colMax] colBound = [-1,rowMax] direction = [0,1] cnt = 0 i = 0 j = 0 # rowBound[0] = [0,colMax] # colBound[0] = [0,rowMax] while cnt < rowMax * colMax: # 向前一步走,判断是否越界 print(i,j,direction,rowBound,colBound) result.append(matrix[i][j]) # 移动 directionCnt = 4 moveFlag = 0 while directionCnt>0 and not moveFlag: # print(directionCnt,moveFlag,direction) if direction[1]: if j + direction[1] < rowBound[1] and j + direction[1] > rowBound[0]: j += direction[1] moveFlag = 1 else: direction = [direction[1],0] else: if i + direction[0] < colBound[1] and i + direction[0] > colBound[0]: i += direction[0] moveFlag = 1 else: direction = [0,-direction[0]] directionCnt -= 1 # 更新边界 if direction[1]: if direction[1] > 0: colBound[0] = max(colBound[0],i) else: colBound[1] = min(colBound[1],i) else: if direction[0] > 0: rowBound[1] = min(rowBound[1],j) else: rowBound[0] = max(rowBound[0],j) # print(i,j,direction,rowBound,colBound) cnt +=1 return result if __name__ == '__main__': solu = Solution() input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # input_List = [[1,2,3],[4,5,6],[7,8,9]] # input_List = 1 # numerator = -50 # strs = ["eat", "tea", "tan", "ate", "nat", "bat"] result = solu.spiralOrder(input_List) output_Str = ' result = ' + str(result) print(output_Str)
""" 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]) if num < low: continue if num > high: break result.append(num) return result
""" 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 def is_added(self): """ Returns true if the wme is currently in soar's working memory """ return self.added def add_to_wm(self, parent_id): """ Creates a structure in working memory rooted at the given parent_id """ if self.added: self._remove_from_wm_impl() self._add_to_wm_impl(parent_id) self.added = True def update_wm(self, parent_id = None): """ Updates the structure in Soar's working memory It will also add it to wm if parent_id is not None """ if self.added: self._update_wm_impl() elif parent_id: self._add_to_wm_impl(parent_id) self.added = True def remove_from_wm(self): """ Removes the structure from Soar's working memory """ if not self.added: return self._remove_from_wm_impl() self.added = False ### Internal Methods - To be implemented by derived classes def _add_to_wm_impl(self, parent_id): """ Method to implement in derived class - add to working memory """ pass def _update_wm_impl(self): """ Method to implement in derived class - update working memory """ pass def _remove_from_wm_impl(self): """ Method to implement in derived class - remove from working memory """ pass
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.send(text)
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]): board[row][col]+=2 def gameOfLife(self, board): for row in range(len(board)): for col in range(len(board[row])): self.update(board, row, col) for row in range(len(board)): for col in range(len(board[row])): board[row][col] >>= 1 a = Solution() b = [ [0,1,0], [0,0,1], [1,1,1], [0,0,0] ] a.gameOfLife(b) print(b)
__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()