content
stringlengths
7
1.05M
# Insertion Sort # Time Complexity: O(n^2) # Space Complexity: O(1) # Assume first element is sorted at beginning # and then using it to compare with next element # if this element is less than next element # then swap them def insertion_Sort(lst): for i in range(1, len(lst)): # first read from 1 to n-1...
#Assume s is a string of lower case characters. #Write a program that prints the longest substring of s #in which the letters occur in alphabetical order. #For example, if s = 'azcbobobegghakl', then your program should print #Longest substring in alphabetical order is: beggh #In the case of ties, print the first sub...
# 384. Shuffle an Array # https://leetcode.com/problems/shuffle-an-array/ class Solution: def __init__(self, nums: List[int]): self.orig = nums[:] self.reset() def reset(self) -> List[int]: """ Resets the array to its original configuration and return it. """...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Yue-Wen FANG' __maintainer__ = "Yue-Wen FANG" __email__ = 'fyuewen@gmail.com' __license__ = 'Apache License 2.0' __creation_date__= 'Dec. 26, 2018' """ In a CLASS, we do not always need pass external arguments, we can also set the default in the class """ c...
def calc_fitness_value(x,y,z): fitnessvalues = [] x = generation_fitness_func(x) y = generation_fitness_func(y) z = generation_fitness_func(z) for p in range(len(x)): fitnessvalues += [(x[p]*x[p])+(y[p]*y[p])+(z[p]*z[p])] return fitnessvalues #fitness_value = x*x + y*...
content = b'BM\xbc\x03\x00\x00\x00\x00\x00\x006\x00\x00\x00(\x00\x00\x00\x1e\x00\x00\x00\x0f\x00\x00\x00\x01\x00\x10\x00\x00\x00\x00\x00\x86\x03\x00\x00\x12\x0b\x00\x00\x12\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x7f\xff\x7f\xff\x7f\xdf{\x7fo\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x...
class Baseagent(object): def __init__(self, args): self.args = args self.agent = list() # inference def choose_action_to_env(self, observation, train=True): observation_copy = observation.copy() obs = observation_copy["obs"] agent_id = observation_copy["controlled_p...
# Knutha Morrisa Pratt (KMP) for string matching # Complexity: O(n) # Reference used: http://code.activestate.com/recipes/117214/ def kmp(full_string, pattern): ''' It takes two arguments, the main string and the patterb which is to be searched and returns the position(s) or the starting indexes of the ...
def add(a, b): def o̵̶(o̶, o̵): return o̶̵(o̵, o̶) def o̶̵(o̵, o̶): # a b return o['o̵'](o̵ if o̵ > o̶ else o̶, o̶ if o̶ == o̶ else o̶) def o̶(o̵̶, o̶̵): return o̵(o̵̶, o̶̵) def o̵(o̶̵, o̵̶): o̶̵ -= -o̵̶ return o̶̵ if o̶̵ == o̶̵ else o̵̶ + o̶̵ o = { ...
lista = [] alunos = [] cont = 0 print('='*50) print(f'PROGRAMA DE NOTA ESCOLAR') print('='*50) while True: alunos.append(str(input('Nome: ')).strip().upper()) alunos.append(float(input('Nota 1: '))) alunos.append(float(input('Nota 2: '))) alunos.append((alunos[1] + alunos[2])/2) lista.append(alun...
class HouseInfo: "房源信息" def __init__(self, area, price, hasWindow, bathroom, kitchen, address, owner): self.__area = area self.__price = price self.__window = hasWindow self.__bathroom = bathroom self.__kitchen = kitchen self.__address = address ...
# Description # Keep improving your bot by developing new skills for it. # We suggest a simple guessing game that will predict the age of a user. # It's based on a simple math trick. First, take a look at this formula: # `age = (remainder3 * 70 + remainder5 * 21 + remainder7 * 15) % 105` # The `numbersremainder3`, `...
REQUEST_CACHE_LIMIT = 200*1024*1024 QUERY_CACHE_LIMIT = 200*1024*1024 class index: def __init__(self, name, request_cache, query_cache): self.name = name self.request_cache = request_cache self.query_cache = query_cache
PCLASS = ''' class Parser(object): class ScanError(Exception): pass class ParseError(Exception): pass def parsefail(self, expected, found, val=None): raise Parser.ParseError("Parse Error, line {}: Expected token {}, but found token {}:{}".format(self.line, expected, found, val)) ...
x = int(input()) y = int(input()) numeros = [x,y] numeros_ = sorted(numeros) soma = 0 for a in range(numeros_[0]+1,numeros_[1]): if a %2 != 0: soma += a print(soma)
class couponObject(object): def __init__( self, player_unique_id, code = None, start_at = None, ends_at = None, entitled_collection_ids = {}, entitled_product_ids = {}, once_per_customer = None, prerequisite_quantity_range = None, ...
def on_enter(event_data): """ """ pocs = event_data.model pocs.next_state = 'sleeping' pocs.say("Resetting the list of observations and doing some cleanup!") # Cleanup existing observations try: pocs.observatory.scheduler.reset_observed_list() except Exception as e: # pragma: no c...
{ 'targets': [ { 'target_name': 'vivaldi', 'type': 'none', 'dependencies': [ 'chromium/chrome/chrome.gyp:chrome', ], 'conditions': [ ['OS=="win"', { # Allow running and debugging vivaldi from the top directory of the MSVS solution view 'product_na...
# 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 pseudoPalindromicPaths (self, root: TreeNode) -> int: ''' T: O(n) and S: O(n) ''...
# # PySNMP MIB module RADLAN-RADIUSSRV (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-RADIUSSRV # Produced by pysmi-0.3.4 at Wed May 1 14:48:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
def rom(n): if n == 1000: return 'M' if n == 900: return 'CM' if n == 500: return 'D' if n == 400: return 'CD' if n == 100: return 'C' if n == 90: return 'XC' if n == 50: return 'L' if n == 40: return 'XL' if n == 10: return 'X' if n == 9: return 'IX' if n == ...
# Copyright 2013 10gen Inc. # # 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...
def resolve(): ''' code here ''' N = int(input()) mat = [[int(item) for item in input().split()] for _ in range(N)] dp = [[0 for _ in range(N+1)] for _ in range(N+1)] for i in reversed(range(N-2)): for j in range(i+2, N): dp[i][j] = min(dp[i][j-1] * mat[i][0]*mat[j][0]*...
""" Provides the ApiContext class """ __copyright__ = "Copyright 2017, Datera, Inc." class ApiContext(object): """ This object is created by the top level API object, and is passed in to all endpoints and entities. """ def __init__(self): self.connection = None self.hostname = No...
#public symbols __all__ = ["Factory"] class Factory(object): """Base class for objects that know how to create other objects based on a type argument and several optional arguments (version, server id, and resource description). """ def __init__(self): pass def create(s...
class Classe_1: def funcao_da_classe_1(self, string): dicionario = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} valor = 0 for i in range(len(string)): if i > 0 and dicionario[string[i]] > dicionario[string[i -1]]: valor += dicionario[string[i]...
def leiaInt(imput): while True: try: n = int(input(imput)) except: print(f'\033[1;31mErro! O valor digitado não é um número inteiro.\033[m') valido = False else: return n break def leiaFloat(imput): while True: try: ...
def partition(array, low, high): i = low - 1 pivot = array[high] for j in range(low, high): if array[j] < pivot: i += 1 array[i], array[j] = array[j], array[i] array[i + 1], array[high] = array[high], array[i + 1] return i + 1 def quick_sort(array...
# -*- coding: utf-8 -*- """ Created on Wed Mar 24 19:41:31 2021 @author: Abeg """ #Linear Search def LinearSearch(arr,k): global value for i in range(len(arr)): if(arr[i]==k): value=i return value n,k=map(int,input().split()) arr=list(map(int,input().strip().spli...
# -*- coding: utf-8 -*- # @Date : 2014-06-27 14:37:20 # @Author : xindervella@gamil.com SRTP_URL = 'http://10.1.30.98:8080/srtp2/USerPages/SRTP/Report3.aspx' TIME_OUT = 8
i=1 for i in range(0,5): if i==2: print('bye') break print("sadique")
class ArrayParam: def mfouri(self, oper="", coeff="", mode="", isym="", theta="", curve="", **kwargs): """Calculates the coefficients for, or evaluates, a Fourier series. APDL Command: ``*MFOURI`` Parameters ---------- oper Type of Fourier operation: ...
def _normalize_scratch_rotation(degree): while degree <= -180: degree += 360 while degree > 180: degree -= 360 return degree def _convert_scratch_to_pygame_rotation(degree): deg = _normalize_scratch_rotation(degree) if deg == 0: return 90 elif deg == 90: ...
# 2D Array is аn аrrаy оf аrrаys. # Pоsitiоn оf аn dаtа еlеmеnt is rеfеrrеd by twо indicеs # Sо it rеprеsеnts а tаblе with rоws аn dcоlumns оf dаtа # #======================================================================================== Temperatures = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6...
def frequencySort(self, s: str) -> str: m = {} for i in s: if i not in m: m[i] = 1 else: m[i] += 1 r = "" for i in sorted(m, key=m.get, reverse=True): r += i * m[i] return r
# String Format # As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: ''' age = 23 txt = "My name is Nayan, I am " + age + "Years old" print(txt) #Error ''' # But we can combine strings and numbers by using the format() method! # The format() method takes the passed arg...
# Джокер + Выигрышные номера тиража + предыдущий тираж к примеру 59587 def test_joker_winning_draw_numbers_for_previous_draw(app): app.ResultAndPrizes.open_page_results_and_prizes() app.ResultAndPrizes.click_game_joker() app.ResultAndPrizes.click_winning_draw_numbers() app.ResultAndPrizes.select_draw...
#Write a Python class to reverse a string word by word. class py_solution: def reverse_words(self, s): return reversed(s) print(py_solution().reverse_words('rewangi'))
""" 局部变量 """ def putchar(c): pass def main(): a = 0x61 putchar(a) b = 0x62 putchar(b) c = 0x63 putchar(c)
# Chapter 7 exercises from the book Python Crash Course: A Hands-On, Project-Based Introduction to Programming. # 7-1. Rental Car car = input('Which car do you want to rent?') print('Let me see if I can find you a '+ car + '.') # 7-2. Restaurant Seating number = input('How many people come to dinner?') number...
# 🚨 Don't change the code below 👇 age = input("What is your current age?") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 left_age = 90 - int(age) days = left_age * 365 weeks = left_age * 52 months = left_age * 12 print(f"You have {days} days, {weeks} weeks, and {months} months left.")
# Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. # # Note: You can only move either down or right at any point in time. # # Example: # # Input: # [ # [1,3,1], # [1,5,1], # [4,2,1] # ] # Output: 7 # Explanation: ...
# follow pep-386 # Examples: # * 0.3 - released version # * 0.3a1 - alpha version # * 0.3.dev - version in developmentv __version__ = '0.7.dev' __releasedate__ = ''
class RegistrationInfo(object): def __init__(self, hook_name, expect_exists, register_kwargs=None): assert isinstance(expect_exists, bool) self.hook_name = hook_name self.expect_exists = expect_exists self.register_kwargs = register_kwargs or {}
""" Write a Python function that takes a sequence of numbers and determine whether all numbers are different from each other """ def test_distinct(data): if len(data) == len(set(data)): return True else: return False print(test_distinct([1, 5, 7, 9])) print(test_distinct([2, 7, 5, 8, 8, 9, 0]))
def includeme(config): config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('api', '/api') config.add_route('download', '/download') config.add_route('docs', '/docs') config.add_route('create', '/create') config.add_route('demo', '/dem...
''' Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both inde...
metadata = Hash() data = Hash(default_value=0) sc_contract = Variable() unit_contract = Variable() terrain_contract = Variable() random.seed() @construct def seed(): metadata['operator'] = ctx.caller #prize calclulation Parameters metadata['winner_percent'] = decimal('0.09') metadata['h...
# -*- coding: utf-8 -*- """Top-level package for poker_project.""" __author__ = """Zack Raffo""" __email__ = 'raffo.z@husky.neu.edu' __version__ = '0.1.0'
def tic_tac_toe(): board = [1, 2, 3, 4, 5, 6, 7, 8, 9] end = False win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) def draw(): print(board[0], board[1], board[2]) print(board[3], board[4], board[5]) print(board...
# This is the library where we store the value of the different constants # In order to use this library do: # import units_library as UL # U = UL.units() # kpc = U.kpc_cm class units: def __init__(self): self.rho_crit = 2.77536627e11 #h^2 Msun/Mpc^3 self.c_kms = 3e5 #km/s ...
def get_transporter(configuration): transporter_module = configuration.get_module_transporter() transporter_configuration = configuration.get_configuration() return transporter_module.get_transporter(transporter_configuration)
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class HadoopDistributionEnum(object): """Implementation of the 'HadoopDistributionEnum' enum. Specifies the Hadoop Distribution. Hadoop distribution. 'CDH' indicates Hadoop distribution type Cloudera. 'HDP' indicates Hadoop dist...
def LCSlength(X, Y, lx, ly): # Parameters are the two strings and their lengths if lx == 0 or ly == 0: return 0 if X[lx - 1] == Y[ly - 1]: return LCSlength(X, Y, lx - 1, ly - 1) + 1 return max(LCSlength(X, Y, lx - 1, ly), LCSlength(X, Y, lx, ly - 1)) print("Enter the first string : \n") X...
def areRotations(someString, someSubstring): tempString = 2 * someString return tempString.find(someSubstring, 0, len(tempString)) print(areRotations("AACD", "ACDA")) print(areRotations("AACD", "AADC"))
m= ["qzbw", "qez", ],[ "xgedfibnyuhqsrazlwtpocj", "fxgpoqijdzybletckwaunsr", "pwnqsizrfcbyljexgouatd", "ljtperqsodghnufiycxwabz", ],[ "uk", "kupacjlriv", "dku", "qunk", ],[ "yjnprofmcuhdlawt", "frmhulyncvweatodzjp", "fhadtrcyjzwlnpumo", "hrcutablndyjpfmwo", ],[ "rdclv", "lrvdc", "crldv", "dvrcl", "vrlcd", ],[ "dqrwajpb...
#!/usr/bin/env python2 ARTICLE_QUERY = """ SELECT articles.title, count(*) AS num FROM log, articles WHERE log.path = '/article/' || articles.slug GROUP BY...
a, b = 1, 2 result = 0 while True: a, b = b, a + b if a >= 4_000_000: break if a % 2 == 0: result += a print(result)
def draw_1d(line, row): print(("*"*row + "\n")*line) def draw_2d(line, row, simbol): print((simbol*row + "\n")*line) def special_draw_2d(line, row, border, fill): print(border*row) row -= 2 line -= 2 i = line while i > 0: print(border + fill*row + border) i -= 1 print(...
def registrar(registry, name="entry"): """ Creates and returns a register function that can be used as a decorator for registering functions into the given registry dictionary. :param registry: Dictionary to add entry registrations to. :param name: Name to give to each entry. "entry" is used by de...
#!/usr/bin/env python # encoding: utf-8 # @author: Zhipeng Ye # @contact: Zhipeng.ye19@xjtlu.edu.cn # @file: implementstrstr.py # @time: 2020-02-22 16:27 # @desc: class Solution: def strStr(self, haystack, needle): if len(needle) == 0: return 0 haystack_length = len(haystack) ...
""" Helper script for writing a "input_collect_{run_name}.json" input file (see README.md). Below is an example of it for the 1D Heisenberg model ({run_name} = 1D_heisenberg1) which has a seed of 1 and 1600 samples. """ info = 'heisenberg1' run_name = 'run1D_{}_1_'.format(info) input_filename = 'input_collect...
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'shard', 'type': 'static_library', 'msvs_shard': 4, 'sources': [ 'hello1.cc', 'hello2....
#-*- coding: utf-8 -*- BASE = { # can be overriden by a configuration file 'SOA_MNAME': 'polaris.example.com.', 'SOA_RNAME': 'hostmaster.polaris.example.com.', 'SOA_SERIAL': 1, 'SOA_REFRESH': 3600, 'SOA_RETRY': 600, 'SOA_EXPIRE': 86400, 'SOA_MINIMUM': 1, 'SOA_TTL': 86400, 'SHAR...
# test_with_pytest.py def test_always_passes(): assert True def test_always_fails(): assert False
def main(): chars = input() stack = [] for char in chars: if char == '<': # pop from stack if len(stack) != 0: stack.pop() else: stack.append(char) print(''.join(stack)) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- model = { 'en ': 0, 'de ': 1, ' de': 2, 'et ': 3, 'an ': 4, ' he': 5, 'er ': 6, ' va': 7, 'n d': 8, 'van': 9, 'een': 10, 'het': 11, ' ge': 12, 'oor': 13, ' ee': 14, 'der': 15, ' en': 16, 'ij ': 17, 'aar': 18, 'gen': 19, 'te ': 20, 'ver': 21, ' in': 22, ' me': 23, 'aan': ...
# -*- coding: utf-8 -*- """Workspace/project-oriented tmux/git personal assistant. Working on multiple git repositories and juggling tmux sessions can be tedious. `mx` tries to help with that. """ __package__ = 'mx' __license__ = 'MIT' __version__ = '0.2.17' __author__ = __maintainer__ = 'Rafael Bodill' __email__ = 'j...
# 面试题3:二维数组中的查找 # 题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序, # 每一列都按照从上到下递增的顺序排序。请完成一个函数, # 输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 def findNum(matrix,num): if not matrix: return False row,col = 0,len(matrix[0])-1 while row < len(matrix) and col >= 0: if num == matrix[row][col]: print("有...
# @Title: 困于环中的机器人 (Robot Bounded In Circle) # @Author: KivenC # @Date: 2019-05-18 16:54:26 # @Runtime: 52 ms # @Memory: 12.9 MB class Solution: def isRobotBounded(self, instructions: str) -> bool: # 仅当循环一次后方向仍向北且有位移才不会困于环中,不然循环四次之后都会达到同一个状态(同方向,同坐标) x, y = 0, 0 # 位置 dx, dy = 0, 1 # 方向 ...
"""syphon.tests.build_.__init__.py Copyright (c) 2017-2018 Keithley Instruments, LLC. Licensed under MIT (https://github.com/ehall/syphon/blob/master/LICENSE) """
class BaseError(Exception): pass class CredentialRequired(BaseError): pass class UnexpectedError(BaseError): pass class Forbidden (BaseError): pass class Not_Found (BaseError): pass class Payment_Required (BaseError): pass class Internal_Server_Error (BaseError): pass class Service_Un...
''' Copyright (c) 2020 WEI.ZHOU. All rights reserved. The following code snippets are only used for circulation and cannot be used for business. If the code is used, no consent is required, but the author has nothing to do with any problems and consequences. In case of code problems, feedback can be made through the...
def formula(): a=int(input("Enter a ")) b=int(input("Enter b ")) print((for1(a,b))*(for1(a,b))) print(for1(a,b)) def for1(a,b): return(a+b) formula()
def say_hello(): print("Hello World!") def say_name(name): print(f"Hello {name}!") def calculate_something(some_value, other_value): return some_value + other_value def run_example(): hello_func = say_hello hello_func() hello_name = say_name hello_name("Mikołaj") # calculatio...
input = """turn off 660,55 through 986,197 turn off 341,304 through 638,850 turn off 199,133 through 461,193 toggle 322,558 through 977,958 toggle 537,781 through 687,941 turn on 226,196 through 599,390 turn on 240,129 through 703,297 turn on 317,329 through 451,798 turn on 957,736 through 977,890 turn on 263,530 throu...
""" util.py Utility functions for testing SONiC CLI """ def parse_colon_speparated_lines(lines): """ @summary: Helper function for parsing lines which consist of key-value pairs formatted like "<key>: <value>", where the colon can be surrounded by 0 or more whitespace characters ...
class Solution(object): def insert(self, intervals, working): r = [] s = working[0] e = working[1] for pair in intervals: print(r,s,e,pair) print() cs = pair[0] ce = pair[1] if ce < s: r.append(pair) ...
#!/bin/zsh def isphonenumber(text): if len(text) != 12: return False for i in range(0, 3): if not text[i].isdecimal(): return False if text[3] != '-': return False for i in range(4, 7): if not text[i].isdecimal(): return False if text[7] != '-...
class BiggestRectangleEasy: def findArea(self, N): m, n = 0, N/2 for i in xrange(n+1): m = max(m, i*(n-i)) return m
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: l = [] for i in range(1<<len(nums)): subset = [] for j in range(len(nums)): if i & (1<<j): subset.append(nums[j]) l.append(subset) return l
# VEX Variables class VEXVariable: __slots__ = tuple() def __hash__(self): raise NotImplementedError() def __eq__(self, other): raise NotImplementedError() class VEXMemVar: __slots__ = ('addr', 'size', ) def __init__(self, addr, size): self.addr = addr self.s...
n1 = int(input('Digite um numero inteiro: ')) if n1 % 2 == 0: print('O numero {} e PAR'.format(n1)) else: print('O numero {} é IMPAR'.format(n1))
''' A script that replaces commas with tabs in a file ''' in_filename = input("Please input the file name:") out_filename = "out_"+in_filename with open(in_filename,"r") as fin: with open(out_filename,"w+") as fout: for line in fin: fout.write(line.replace(',','\t')) print("Output File:",out_...
def member_format(m): return """ <tr> <td width="15%%"> <img src="../assets/%s"> </td> <td> <span id="bioname"> <b> %s </b> </span> <br> %s <p> %s </p> </td> </tr>"""%(m['image'],m['name'],m['position'],m['description']) members=[ {"name":"Lucas Wagner","position":"Group Leader","image":"lucas.png", "desc...
# Manipulation von Strings teststring='das ist EIN TEsTsTRInG' low='lower' upp='UPPER' print('Stirings wie dieser:['+teststring+'] Können auch manipuliert werden') print() input() print('Man kann z.b. mit upper() den kompletten Inhalt des Strings\nin Grossbuchstaben schreiben.') print('Beispiel:', teststring.upper())...
class Command: def __init__(self): self.id self.commandName self.commandEmbbeding self.event
""" src_dir: agent路径 sgw_dir: sgw下的src_dir, sgw_save_path + agent_id + src_dir == sgw_dir 目标: archive(src_dir), sgw_dir 将被归档,并进入刻录流程,并可以追踪到状态:未归档, """ class Agent(object): def __init__(self): self.filesystem = {} def get(self, path): self.filesystem.get(path)
def get_input() -> list: with open(f"{__file__.rstrip('code.py')}input.txt") as f: return [l[:-1] for l in f.readlines()] def parse_input(lines: list) -> list: instructions = [] for line in lines: split = line.split(" ") instructions.append([split[0], int(split[1])]) return ins...
# B2067-药房管理 m = float(input()) n = int(input()) num_list = list(map(float, input().split())) fail_num = 0 for i in range(0, n): # 每次循环前检查所需的药物是否够用,够用则交付 if(m - num_list[i] >= 0): m -= num_list[i] # 不够,给没取到药的人计数 else: fail_num += 1 continue print(fail_num)
###### # 第一题 # [a-zA-Z]+: 匹配任意个大或小写字母组成的单词 # [A-Z][a-z]*: 匹配大写字母开头的单词 # p[aeiou]{,2}t: 匹配p*t或p**t类型的单词,*是元音字母 # \d+(\.\d+)?: 匹配整数和小数 # ([^aeiou][aeiou][^aeiou])*:匹配babbabbabbab类型的字符串? a是小写元音字母,b是不是小写元音字母的东西?? # \w+|[^\w\s]+: 匹配连续的字母或者连续的非字母非空白字符 ###### # 第二题 # 假设单词不包含空格 content = open('a.in').readlines() result0 = [] ...
"""Lib macros.""" # the cell format intentionally uses a deprecated cell format # @lint-ignore SKYLINT load( "cell//:lib2.bzl", _foo = "foo", ) foo = _foo
# -*- coding: utf-8 -*- """Domain Driven Design framework - Event.""" class Event: pass
with open("files_question4.txt")as main_file: with open("Delhi.txt","w")as file1: with open("Shimla.txt","w") as file2: with open("other.txt","w") as file3: for i in main_file: if "delhi" in i: file1.write(i) elif "Shimla" in i: file2.write(i) else: file3.write(i) main_file.cl...
def create_new_employee_department(): employee_department = [] emp = ' ' while emp != ' ': emp_department_input = input('Enter employee last name \n') employee_department.append(emp_department_input) return employee_department
# TRANSCRIBE TO MRNA EDABIT SOLUTION: # creating a function to solve the problem. def dna_to_rna(dna): # returning the DNA strand with modifications to make it an RNA strand. return(dna.replace("A", "U") .replace("T", "A") .replace("G", "C") .replace("C", "G"))
class ConfigurationError(Exception): """ This exception should be thrown if configuration errors happen """ class SerializerError(Exception): """ This exception should be thrown if serializer errors happen """ class AuthenticationError(Exception): """ This exception should be thrown ...
class Calculator: def add(self, x, y): return x + y def subtract(self, x, y): return x - y def multiply(self, x, y): return x * y def divide(self, x, y): try: return x / y except ZeroDivisionError: print('Invalid operation. Division by 0...
# Merge Two Binary Trees class Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if not t1 and not t2: return None result = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"func": "MLE_01_serving.ipynb", "Class": "MLE_01_serving.ipynb"} modules = ["de__extract.py", "de__transform.py", "de__load.py", "ds__load.py", "ds__prepr...