content
stringlengths
7
1.05M
class Solution: def restoreString(self, s: str, indices: List[int]) -> str: result = [None] * len(s) for i, j in enumerate(indices): result[j] = s[i] return "".join(result)
""" *Hue* The hue ring. """
class Nothing: """A basic Callable NoneType Use this object to write generic code pipelines Makes your life easier when using the railway paradigm Using Nothing lets you avoid errors like: AttributeError: "NoneType" object has no attribute ... TypeError: "NoneType" object is not callable...
class Dog: name=None legs=None age=None gender=None isCute=None
''' Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each let...
# this files contains basic metadata about the project. This data will be used # (by default) in the base.html and index.html PROJECT_METADATA = { 'title': 'HistoGIS', 'author': 'Peter Andorfer, Matthias Schlögl', 'subtitle': 'A Geographical Information System, workbench and repository to retrieve,\ co...
# from linked_list import LinkedList def ll_merge(arg2, arg1): if arg2._len <= 0 and arg1._len <= 0: return False if arg2.head is None: return arg1 if arg1.head is None: return arg2 if True: ptr_left, ptr_right = arg1.head, arg2.head while ptr_right is not Non...
upload_folder = './static/images/' static_folder = '/static/' testing_folder = './unit_tests/' test_data_folder = '/tests/test_data' class Config(object): DEBUG = False TESTING = False class ProductionConfig(Config): SECRET_KEY = 'Y\xbf\xb9\xb6\x9e\xca\xf0\tM\x08\x96\x17\xa1t\x90h\xaf\x92\xca1\xde\xcff...
#!/usr/bin/env python """This is a simple user input function.""" __author__ = "Otto Mättas" __copyright__ = "Copyright 2021, The Python Problems" __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Otto Mättas" __email__ = "otto.mattas@eesti.ee" __status__ = "Development" # DEFINE THE USER CHOICE INPUT FUNCTIO...
__author__ = 'Christie' # Write a function in any language that takes as input a list of lists of integers. # The function should return void, and print to standard output the number of times each integer appeared at each index # in an inner list. So for instance: # countem ([ [ 1,2,3], [1,3,4], [1,3] ]) would outpu...
while True: username = input("Type your username: ") if (username != "Diego"): continue password = input("Type your password: ") if (password == "pass21"): break print("Welcome! Access Allowed!")
prvni_cislo = int(input("cislo 1: ")) druhe_cislo = int(input("cislo 2: ")) operace = input("Jakou operaci chceš použít?\n +, -, * nebo / ") # 1. napsat podmínky pro operace # 2. Tisk výsledku
#Challenge 23 #Create an algorithm that will: # •Allow the user to input how much money they want to change to coins. # •Select which coin they want to convert the money into £1, 50p, 20p, 10p, 5p, 2p ,p # •Calculate how many of each coin will be given in. howToCoin = input("Please enter the amount you wh...
def square(number: int) -> int: if 1 < number > 64: raise ValueError(f"number should be between 1 and 64, was {number}") return 1 << (number - 1) # 1 * 2^(number-1) def total() -> int: return (1 << 64) - 1 # 2^64 -1 = 1.844674407371e+19
############################################## # This for AVX2 REGISTER_TYPE="__m256d" DATA_TYPE="double" REGISTER_WIDTH = 4 NUMBER_OF_REGISTERS = 16 MASK_IN_REGISTER = 0 # should be 1 ?? #TARGET_ITILE = 4 #TARGET_JTILE = 12 TARGET_ITILE = 3 TARGET_JTILE = 16 TARGET_KTILE = 48 CACHE_SIZE = 8192 MAX_JTILE = 20 MAX_I...
# SEQUÊNCIA DE FIBONACCI # 0 -> 1 -> 1 -> 2 -> 3 ... # t1 - t2 - t3 num = int(input("Aumentar a sequência: ")) t1 = 0 t2 = 1 cont = 3 print("{} -> {}".format(t1, t2), end=" ") while cont <= num: t3 = t1 + t2 print("-> {}".format(t3), end=" ") t1 = t2 t2 = t3 cont += 1 print("FIM")
# @author Huaze Shen # @date 2020-01-29 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def flatten(root): if root is None: return flatten(root.left) flatten(root.right) temp = root.right root.right = root.left root.l...
# Author - @Nathaniel Walker # Date - 9/23/20 # Description - This method will get the area of a square given one side length. # define method def area_of_square(side): return side * side
class ArtistMethods(object): """Artist methods of the public API.""" def artist(self, artist_id, text_format=None): """Gets data for a specific artist. Args: artist_id (:obj:`int`): Genius artist ID text_format (:obj:`str`, optional): Text format of the results ...
# There are few cases when recursion is useful # 1.When we need quick solution over efficient one # 2.While traversing trees # In this program we'll find factorial of a number # O(n!) def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1) print(factorial(5))
''' Purpose : In a trading system a product is bought in the morning and sold out on the same day. If a person can make only 2 transactions a day with a condition that second transaction is followed only after first then find the maximum profit the person could get. Input formate : Line1 : Number of test cases Line...
thistuple = ("apple", "banana", "cherry") print(thistuple) # ('apple', 'banana', 'cherry') thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) # ('apple', 'banana', 'cherry', 'apple', 'cherry') thistuple = ("apple", "banana", "cherry") print(len(thistuple)) # 3 thistuple = ("apple",) print(...
vulgarity_pl = ('chuj','chuja', 'chujek', 'chuju', 'chujem', 'chujnia', 'chujowy', 'chujowa', 'chujowe', 'cipa', 'cipę', 'cipe', 'cipą', 'cipie', 'dojebać','dojebac', 'dojebie', 'dojebał', 'dojebal', 'dojebała', 'dojebala', 'dojebałem', 'dojebalem', 'dojebałam', 'dojebalam', 'dojebię', 'dojebie', 'dopieprzać', 'dopiepr...
class Graph: def __init__(self, edges): self.edges = edges self.graph_dict = {} for start, end in edges: if start in self.graph_dict: self.graph_dict[start].append(end) else: self.graph_dict[start] = [end] print("Graph Dict:", s...
# the operator looks the same but behaves differently depending on the input. # Example: Addition (+ operator) # number + number = sum # string + string = concatenation # Overriding class Employee: def setNumberOfWorkingHours(self): self.numberOfWorkingHours = 40 def displayNumberOfWorkingHours(self)...
def get_nested(o, default, *args): if o is None: return default current = o for arg in args: if current is None or arg is None or current.get(arg, None) is None: return default current = current.get(arg, default) return current
class Solution: def newInteger(self, n): base9 = "" while n: base9 += str(n % 9) n //= 9 return int(base9[::-1])
#!/usr/bin/env python class Dog: def identify(self): return "jims dog"
# coding=utf-8 # # @lc app=leetcode id=989 lang=python # # [989] Add to Array-Form of Integer # # https://leetcode.com/problems/add-to-array-form-of-integer/description/ # # algorithms # Easy (44.95%) # Likes: 151 # Dislikes: 28 # Total Accepted: 20.3K # Total Submissions: 45.8K # Testcase Example: '[1,2,0,0]\n3...
# Time: O(n^2) # Space: O(n) class Solution(object): def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] nums.sort() dp = [1] * len(nums) prev = [-1] * len(nums) largest_...
# # https://rosettacode.org/wiki/Topological_sort#Python # ############### # # https://codeforces.com/blog/entry/16823 # ############### # https://www.python.org/doc/essays/graphs/ graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ ans = float('-inf') ...
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. https://stackoverflow.com/a/11326230 """ return "/".join(map(lambda x: str(x).strip('/').rstrip('/'), args))
"""Top-level package for bjorn.""" __author__ = """Juan Manuel Cristóbal Moreno""" __email__ = 'juanmcristobal@gmail.com' __version__ = '0.1.3'
a + b c - d e * f g / h i % j k // l m ** n o | p q & r s ^ t u << v w >> x
def _1(): for row in range(7): for col in range(7): if (col==3 or row==6) or (row<3 and row+col==2): print("*",end="") else: print(end=" ") print()
CACHEDOPS = "cachedoperations" SLICEBUILDERS = "slicebuilders" GENERIC = "slicebuilder" SUBPOPULATION = "subpopulation" ATTACK = "attack" AUGMENTATION = "augmentation" TRANSFORMATION = "transformation" CURATION = "curated"
BINANCE_SUPPORTED_QUOTE_ASSET = { 'BTC', 'ETH', 'USDT', 'BNB' } class SupportedQuoteAsset: @staticmethod def getQuoteAsset(symbol, supportedAssetMap): for val in supportedAssetMap: if symbol.endswith(val): return val return None
# # @lc app=leetcode id=876 lang=python3 # # [876] Middle of the Linked List # # https://leetcode.com/problems/middle-of-the-linked-list/description/ # # algorithms # Easy (68.04%) # Likes: 1170 # Dislikes: 56 # Total Accepted: 207.3K # Total Submissions: 304.7K # Testcase Example: '[1,2,3,4,5]' # # Given a non-...
names:{ "000000": "Black", "000080": "Navy Blue", "0000C8": "Dark Blue", "0000FF": "Blue", "000741": "Stratos", "001B1C": "Swamp", "002387": "Resolution Blue", "002900": "Deep Fir", "002E20": "Burnham", "002FA7": "International Klein Blue", "003153": "Prussian Blue", "003366": "Midnight Blue", "003399": "Smalt", "00353...
class RenderTargetType: """ This stores the possible types of targets beeing able to be attached to a RenderTarget. Python does not support enums (yet) so this is a class. """ Color = "color" Depth = "depth" Aux0 = "aux0" Aux1 = "aux1" Aux2 = "aux2" Aux3 = "aux3" All = ["dep...
""" Subarray Sum Equals K Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 Constraints: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000...
###### Config for test ###: Variables ggtrace_cpu = [ "data/formatted/", # pd.readfilepath [1], # usecols trong pd False, # multi_output None, # output_idx "cpu/", # path_save_result ] ggtrace_ram = [ "data/formatted/",...
# pylint: disable-msg=R0903 """check use of super""" __revision__ = None class Aaaa: """old style""" def hop(self): """hop""" super(Aaaa, self).hop() def __init__(self): super(Aaaa, self).__init__() class NewAaaa(object): """old style""" def hop(self): """hop""" ...
competitor1 = int(input()) competitor2 = int(input()) competitor3 = int(input()) sum_sec = competitor1 + competitor2 + competitor3 minutes = sum_sec // 60 sec = sum_sec % 60 if sec < 10: print(f"{minutes}:0{sec}") else: print(f"{minutes}:{sec}")
''' 0. 猜想一下 min() 这个BIF的实现过程 ''' def minx(*arg): xiuxiu = arg[-1] for each in arg: if each < xiuxiu: xiuxiu = each return xiuxiu print(minx(1 , 5 , 9 , 8 ,7))
def extractUntunedTranslation(item): """ """ title = item['title'].replace(' III(', ' vol 3 (').replace(' III:', ' vol 3:').replace(' II:', ' vol 2:').replace(' I:', ' vol 1:').replace(' IV:', ' vol 4:').replace( ' V:', ' vol 5:') vol, chp, frag, postfix = extractVolChapterFragmentPostfix(title) if not (chp ...
med1 = float(input('Primeira Nota')) med2 = float(input('Segunda Nota')) media = (med1 + med2)/2 print('Tirando {} e {}, A media do aluno è {} '.format(med1, med2, media)) if media < 5: print('Você foi REPROVADO') elif media == 5 or media > 5 and media < 6.9: print('Você esta de RECUPERAÇÂO') elif media == 7 or...
class Solution: def toLowerCase(self, string): return string.lower()
# Rouge Highlighter token test - Generic Traceback def test(): print(unknown_test_var) test()
# -*- coding: utf-8 -*- basic_table = dict(map(lambda s: s.split(u'\t'), u''' あ a い i う u え e お o か ka き ki く ku け ke こ ko さ sa し shi す su せ se そ so た ta ち chi つ tsu て te と to な na に ni ぬ nu ね ne の no は ha ひ hi ふ fu へ he ほ ho ま ma み mi む mu め me も mo や ya ゆ yu よ yo ら ra り ri る ru れ re ろ ro わ wa を o ん n ぁ a ぃ i ぅ u ぇ e...
# -*- coding: utf-8 -*- """ Created on Mon Dec 9 16:12:01 2019 @author: NOTEBOOK """ def main(): purchase = float(input("Enter the total amount of purchase: ")) tax(purchase) def tax(pur): sales_tax = pur * 0.04 county_tax = pur * 0.02 total_tax = sales_tax + county_tax total = pur +...
# -*- coding: utf-8 -*- """ 1466. Reorder Routes to Make All Paths Lead to the City Zero There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one dir...
# err_raise.py def foo(s): n = int(s) if n == 0: raise ValueError('invalid value: %s' % s) return 10 / n def bar(): try: foo('0') except ValueError as e: print('ValueError!') bar()
nome=str(input('digite seu nome')) if nome== 'daiane': print('que nome lindo !') else: print('seu nome é comun') print('boa noite {}'.format(nome))
# Search in Rotated Sorted Array II 81 # ttungl@gmail.com class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ # use binary search # tricky part is to increase the left until left=mid and nums[mid...
# -*- coding: utf-8 -*- # @Time: 2020/4/13 18:49 # @Author: GraceKoo # @File: 96_unique-binary-search-trees.py # @Desc: https://leetcode-cn.com/problems/unique-binary-search-trees/ class Solution: def numTrees(self, n: int) -> int: if n < 0: return 0 dp = [0 for _ in range(n + 1)] ...
class Load: elapsedTime = 0 powerUsage = 0.0 csvName = "" id = 0 isBackgroundLoad = None def __init__(self, elapsed_time, power_usage, csv_path): self.elapsedTime = int(elapsed_time) self.powerUsage = float(power_usage) self.csvName = csv_path.split("\\")[-1] # csvNa...
class News: def __init__(self, title, description, thumbnail, link): self.thumbnail = thumbnail.rstrip() self.title = title.rstrip() if description: self.description = description.rstrip() else: self.description = "Sem descrição!" self.link = link.rstr...
# -*- coding: utf-8 -*- # Copyright (c) 2014-2019 Dontnod Entertainment # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use,...
def fnc(func): def wrapper(): print('Функция-обёртка!') print('Оборачиваемая функция: {}'.format(func)) print('Выполняем обёрнутую функцию...') func() print('Выходим из обёртки') return wrapper @fnc def hello_world(): print('Hello world!') hello_world()
# Variable definition - Array or list (Değiken tanımlama - dizi veya liste) credits = ["creadit 1", "credit 2","credit 3"] #Loops - for (Döngüler - for döngüsü) for credit in credits: print(credit)
def count1(x): count = 0 for i in range(len(x)): if x[i:i + 2] == 'ba': count += 1 return count def main(): print(count1('baba')) print(count1('aba')) print(count1('baaabab')) print(count1('abc')) print(count1('goodbye')) print(count1('a')) print(count1('ba'...
def name_match(name, strict=True): """ Perform a GBIF name matching using the species and genus names Parameters ---------- species_name: str name of the species to request more information genus_name: str name of the genus of the species strict: boolean define i...
_SERVICES = ["xcube_gen", "xcube_serve", "xcube_geodb"] def get_services(): return _SERVICES
def min_fee(print_page_list): sum_ = 0 prev = 0 for i in sorted(print_page_list): sum_ += (prev + i) prev += i return sum_ if __name__ == "__main__": print(min_fee([6, 11, 4, 1])) print(min_fee([3, 2, 1])) print(min_fee([3, 1, 4, 3, 2])) print(min_fee([8, 4, 2, 3, 9, 23...
SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 NUMBER_OF_POINTS = 4 POINT_WIDTH = 4.0 CIRCLE_BORDER_WIDTH = 1 SWEEP_LINE_OFFSET = 0.001
""" Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). Example For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". """ def alphabeticShift(inputString): ...
''' The array-form of an integer num is an array representing its digits in left to right order. For example, for num = 1321, the array form is [1,3,2,1]. Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. Example 1: Input: num = [1,2,0,0], k = 34 Output: [1,2...
frase = 'Curso em video Python' print(frase.count('o')) print('oi') print("""Nessa aula, vamos aprender operações com String no Python. As principais operações que vamos aprender são o Fatiamento de String, Análise com len(), count(), find(), transformações com replace(), upper(), lower(), capitalize(), title(), s...
""" Put a list of postgres supported functions """ pgf = ( "round", "min", )
# -*- coding: utf-8 -*- ################################################################################ # LexaLink Copyright information - do not remove this copyright notice # Copyright (C) 2012 # # Lexalink - a free social network and dating platform for the Google App Engine. # # Original author: Alexander Marqu...
""" Simple DXF Export by Simon Greenwold. Press the 'R' key to export a DXF file. """ add_library('dxf') # import processing.dxf.* record = False def setup(): size(400, 400, P3D) noStroke() sphereDetail(12) def draw(): global record if record: beginRaw(DXF, "output.dxf") # Start record...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Author: AsherYang Email : ouyangfan1991@gmail.com Date : 2018/7/27 Desc : 厂商 brand 网络实体 """ class NetBrand: def __init__(self): self._brand_id = None self._brand_name = None self._brand_logo = None # 对应db advert_id @property de...
def convert_sample_to_shot_coQA(sample, with_knowledge=None): prefix = f"{sample['meta']}\n" for turn in sample["dialogue"]: prefix += f"Q: {turn[0]}" +"\n" if turn[1] == "": prefix += f"A:" return prefix else: prefix += f"A: {turn[1]}" +"\n" re...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ if...
def ensureUtf(s, encoding='utf8'): """Converts input to unicode if necessary. If `s` is bytes, it will be decoded using the `encoding` parameters. This function is used for preprocessing /source/ and /filename/ arguments to the builtin function `compile`. """ # In Python2, str == bytes. # In...
#!/usr/bin/python # encoding: utf-8 """ @author: liaozhicheng.cn@163.com @date: 2016/7/24 """
class File: def criar(nomeArquivo): nomeArquivo = input('NOME DO ARQUIVO= ') arquivo = open(nomeArquivo,'x') arquivo.close def escrever(texto): nomeArquivo = input('NOME DO ARQUIVO= ') arquivo = open(nomeArquivo,'w') file = File() file.criar() file.escrever(input())
#!/usr/bin/python # -*- coding: utf-8 -*- # Caution! I am not responsible for using these samples. Use at your own risk # Google, Inc. is the copyright holder of samples downloaded with this tool. # Generated automatically by imgw_podest.py. Feel free to modify it SLIGHTLY. LANGUAGE = 'pl' START_MARKER = 'ę. ' END_...
print('') print('') print('===== DESAFIO 4 =====') print('') n1 = input('Digite algo: ') print('Seu tipo é:',type(n1)) print('E alfanumérico:', n1.isalnum()) print('Ele e um número:', n1.isnumeric()) print('Ele e alfabético:', n1.isalpha()) print('Ele está em letras maiúsculas:', n1.isupper()) print('Ele está em letra...
# -*- coding: utf-8 -*- """ Created on Tue Apr 14 14:44:48 2020 @author: marcu """
#--------------------------------------------------------------- # QUEUE (V2) #--------------------------------------------------------------- # V0 class Queue(object): def __init__(self, limit = 10): self.queue = [] self.front = None self.rear = None self.limit = limit self...
def count_sevens(*args): return args.count(7) nums = [90,1,35,67,89,20,3,1,2,3,4,5,6,9,34,46,57,68,79,12,23,34,55,1,90,54,34,76,8,23,34,45,56,67,78,12,23,34,45,56,67,768,23,4,5,6,7,8,9,12,34,14,15,16,17,11,7,11,8,4,6,2,5,8,7,10,12,13,14,15,7,8,7,7,345,23,34,45,56,67,1,7,3,6,7,2,3,4,5,6,7,8,9,8,7,6,5,4,2,1,2,3,4,5,...
class WebSocketDefine: # Uri = "wss://dstream.binance.com/ws" # testnet Uri = "wss://dstream.binancefuture.com/ws" # testnet new spec # Uri = "wss://sdstream.binancefuture.com/ws" class RestApiDefine: # Url = "https://dapi.binance.com" # testnet Url = "https://testnet.binanc...
""" CLI tool to introspect flake8 plugins and their codes. """ __version__ = '0.1.1'
class NullLogger: level_name = None def remove(self, handler_id=None): # pragma: no cover pass def add(self, sink, **kwargs): # pragma: no cover pass def disable(self, name): # pragma: no cover pass def enable(self, name): # pragma: no cover pass def crit...
class MyHashSet: """ 不使用任何内建的哈希表库设计一个哈希集合 具体地说,你的设计应该包含以下的功能 add(value):向哈希集合中插入一个值。 contains(value) :返回哈希集合中是否存在这个值。 remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。 示例: MyHashSet hashSet = new MyHashSet(); hashSet.add(1);         hashSet.add(2);       ...
"""Custom exceptions.""" class MFilesException(Exception): """M-Files base exception."""
class SomeCls(): """ class SomeCls """ def __init__(self): pass def returns_true(self): """ returns_true """ return True
# ------------------------------------------------------------------------------ # CONFIG (Change propriately) # ------------------------------------------------------------------------------ # Required token = "please input" post_channel_id = "please input" target_days = 1 # The target range is ...
# Python Week4 Day-21 # المجموعات في لغة البايثون # Python Sets 2 print("\n-------------Length--------------------\n") # Get the Length of a Set thisset = {"apple", "banana", "cherry"} print("Number of Items in set : ", len(thisset)) print("\n----------Remove Item------------------\n") # Remove Item thisset1 = {"apple"...
def facto(a): fact=1 while(a>0): fact*=a a-=1 return fact
# -*- coding: utf-8 -*- '标识信息' '准备发送' SEND_FILE = '[SEND]' '准备接收' RECV_FILE = '[RECV]' '文件信息' FILE_INFO = '[INFO]' '数据分隔符' SPLIT = '[SPLT]' '开始传输' START_TRANSFER = '[STAR]' '传输数据' DATA = '[DATA]' '请求下一段数据' NEXT = '[NEXT]' '结束传输' STOP_TRANSFER = '[STOP]' '未知header' NONE = '[NONE]' def unpack_msg(msg): '解包消息' ...
def is_prime(n: int) -> bool: if n < 2: return False elif n == 2: return True for i in range(2, n): if n % i == 0: return False return True if __name__ == '__main__': m = int(input()) n = int(input()) prime_sum = 0 prime_min = None for i in rang...
""" @author: Alfons @contact: alfons_xh@163.com @file: 3. Longest Substring Without Repeating Characters.py @time: 19-1-9 下午9:34 @version: v1.0 """ class Solution: def lengthOfLongestSubstring(self, s): """ 大意是查找目标字符串中的无重复字符的最长子字符串。 问题的关键点在于,遇到重复字符时的处理。 从头开始遍历整个目标字符串,将无重复子串的开头索引...
# pyOCD debugger # Copyright (c) 2018-2020 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # 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...
"""TRUTH TABLE GENERATOR by ANTHONY CURTIS ADLER""" left_mark = '(' right_mark = ')' def contains (phrase,chars): """Returns TRUE if <phrase> contains ANY one of <chars>""" for x in chars: if x in phrase: return True return False def bracketed (phrase): ...
def get_cityscapes_palette(num_cls=19): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ palette = [0] * (num_cls * 3) palette[0:3] = (128, 64, 128) # 0: 'road' palette[3:6] = (244, 35,232) ...
# Define variables a and b. Read values a and b from console and calculate: # a + b # a - b # a * b # a / b # a**b. # Output obtained results. a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) print(a + b) print(a - b) print(a * b) print(a / b) print(a**b) print(a%b) print(a...