content
stringlengths
7
1.05M
def consolidate(sets): setlist = [s for s in sets if s] for i, s1 in enumerate(setlist): if s1: for s2 in setlist[i+1:]: intersection = s1.intersection(s2) if intersection: s2.update(s1) s1.clear() s1...
class InterpreterException(Exception): def __init__(self, message): self.message = message def __str__(self): return self.message class SymbolNotFound(InterpreterException): pass class UnexpectedCharacter(InterpreterException): pass class ParserSyntaxError(InterpreterException): ...
#! /usr/bin/env python # # parameters/standard.py # # Nick Barnes, Ravenbrook Limited, 2010-02-15 # Avi Persin, Revision 2016-01-06 """Parameters controlling the standard GISTEMP algorithm. Various parameters controlling each phase of the algorithm are collected and documented here. They appear here in approximately...
#Copyright (c) 2009-11, Walter Bender, Tony Forster # This procedure is invoked when the user-definable block on the # "extras" palette is selected. # Usage: Import this code into a Python (user-definable) block; when # this code is run, the current mouse status will be pushed to the # FILO heap. If a mouse button ev...
#Constants POSITION_MAP = { # Remaining: F, IR, Util 0 : '0' # IR? , 1 : 'Center' , 2 : 'Left Wing' , 3 : 'Right Wing' , 4 : 'Defense' , 5 : 'Goalie' , 6 : '6' # Forward ? , 7 : '7' # Goalie, F (Goalie Bench?) , 8 : '8' # Goalie, F , 'Center': 1 , 'Left Wing'...
can_juggle = True # The code below has problems. See if # you can fix them! #if can_juggle print("I can juggle!") #else print("I can't juggle.")
# decompiled-by-hand & optimized # definitely not gonna refactor this one # 0.18s on pypy3 ip_reg = 4 reg = [0, 0, 0, 0, 0, 0] i = 0 seen = set() lst = [] while True: i += 1 break_true = False while True: if break_true: if i == 1: print("1)", reg[1]) if reg[1...
"""Write a program that allow user enter a file name (path) then content, allow user to save it""" filename = input("Please input filename") f= open(filename,"w+") content = input("Please input content") f.write(content)
class DxlNmapOptions: """ Constants that are used to execute Nmap tool +-------------+---------+----------------------------------------------------------+ | Option | Command | Description | +=============+=========+=============================...
# See # The configuration file should be a valid Python source file with a python extension (e.g. gunicorn.conf.py). # https://docs.gunicorn.org/en/stable/configure.html bind='127.0.0.1:8962' timeout=75 daemon=True user='user' accesslog='/var/local/log/user/blockchain_backup.gunicorn.access.log' errorlog='/var/l...
size = 5 m = (2 * size)-2 for i in range(0, size): for j in range(0, m): print(end=" ") m = m - 1 for j in range(0, i + 1): if(m%2!=0): print("*", end=" ") print("")
__version__ = '2.0.0' __description__ = 'Sample for calculations with data from the ctrlX Data Layer' __author__ = 'Fantastic Python Developers' __licence__ = 'MIT License' __copyright__ = 'Copyright (c) 2021 Bosch Rexroth AG'
__all__ = ( 'readonly_admin', 'singleton' )
def somar(x, y): if x and y >= 0: x = x + y return(x) def subtrair(x, y): if x and y >= 0: x = x - y return(x) def multiplicar(x, y): if x and y >= 0: x = x * y return(x) def dividirInteiro(x, y): if x and y >= 0: x = x / y return(x) def dividir(x, y):...
integer = [ ['lld', 'long long', 9223372036854775807, -9223372036854775808], ['ld', 'long', 9223372036854775807, -9223372036854775808], ['lu', 'unsigned long', 18446744073709551615, 0], ['d', 'signed', 2147483647, -2147483648], ['u', 'unsigned', 4294967295, 0], ['hd', 'short', 32767, -32768], ...
#!/usr/bin/env python # # Create filter taps to use for interpolation filter in # clock recovery algorithm. These taps are copied from # GNU Radio at gnuradio/filter/interpolator_taps.h. # # This file includes them in natural order and I want # them stored in reversed order such that they can be # used directly. # fil...
class Node: def __init__(self, val: int): self.val = val self.prev = None self.next = None class DoublyLinkedList: def takeinput(self) -> Node: inputlist = [int(x) for x in input().split()] head = None temp = None for curr in inputlist: if c...
class Combo(): def combine(self,n, k): A = list(range(1,n + 1)) res = self.comb(A, k) return res def comb(self, A, n): if n == 0: return [[]] l = [] for i in range(0, len(A)): m = A[i] remLst = A[i + 1:] for p in se...
f = open('./day4.py') for chunk in iter(lambda :f.read(10),''): print(chunk)
class WebsiteBaseError(Exception): pass class TreeTraversal(WebsiteBaseError): def __init__(self, tree, request, segment, req=None): super().__init__() self.tree, self.request, self.segment, self.req = tree, request, segment, req def __str__(self) -> str: return f"{self.tree} > {s...
linelist = [line for line in open('Day 02.input').readlines()] hor = 0 dep = 0 for line in linelist: mov, amount = line.split(' ') if mov == 'forward': hor += int(amount) else: dep += int(amount) * (-1 if mov == 'up' else 1) print(hor * dep)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple color picker program.""" BANNER = """ .::::::::::::::::::::::::::::::::::::::::::::::::. .. .... .. .. ...... ... .. ...
def convert_sample_to_shot_wow(sample, with_knowledge=True): prefix = "Dialogue:\n" assert len(sample["dialogue"]) == len(sample["meta"]) for turn, meta in zip(sample["dialogue"],sample["meta"]): prefix += f"User: {turn[0]}" +"\n" if with_knowledge: if len(meta)>0: ...
# Test cases that are expected to fail, e.g. unimplemented features or bug-fixes. # Remove from list when fixed. xfail = { "namespace_keywords", # 70 "googletypes_struct", # 9 "googletypes_value", # 9 "import_capitalized_package", "example", # This is the example in the readme. Not a test. } se...
class Settings: BOT_KEY = "" HOST_NAME = "127.0.0.1" USER_NAME = "root" USER_PASS = "Andrey171200" SQL_NAME = "moneysaver"
{ "targets": [ { "target_name": "binding", "sources": [ "native\\winhttpBindings.cpp" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")" ], "libraries": [ "WinHTTP.lib", "-DelayLoad:node.exe" ], "msbuild_settings": { "ClCompile"...
def open_file(): while True: file_name = input("Enter input file: ") try: measles = open(file_name, "r") break except: print("File unable to open. Invalid name or file doesn't exist!") continue # name it re-prompts for a write name return ...
def get_obj1(): obj = \ { "sha": "d25341478381063d1c76e81b3a52e0592a7c997f", "commit": { "author": { "name": "Stephen Dolan", "email": "mu@netsoc.tcd.ie", "date": "2013-06-22T16:30:59Z" }, "committer": { "name": "Stephen Dolan", ...
description = 'system setup' group = 'lowlevel' sysconfig = dict( cache = 'localhost', instrument = 'ErWIN', experiment = 'Exp', datasinks = ['conssink', 'dmnsink'], notifiers = [], ) modules = ['nicos.commands.standard'] devices = dict( ErWIN = device('nicos.devices.instrument.Instrument', ...
valor = input("Digite algo: ") print("É do tipo", type(valor)) print("Valor numérico:", valor.isnumeric()) print("Valor Alfa:", valor.isalpha()) print("Valor Alfanumérico:", valor.isalnum()) print("Valor ASCII:", valor.isascii()) print("Valor Decimal", valor.isdecimal()) print("Valor Printavel", valor.isprintable())
# -*- coding: utf-8 -*- """ 1265. Print Immutable Linked List in Reverse You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface: ImmutableListNode: An interface of immutable linked list, you are given the head of the list. You need to use the foll...
num1 = input() num2 = input() num3 = input() print(int(num1) + int(num2) + int(num3))
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head linked_list = '' while temp: linked_list += str(temp.data) + " -> " ...
def bubblesort(L): keepgoing = True while keepgoing: keepgoing = False for i in range(len(L)-1): if L[i]>L[i+1]: L[i], L[i+1] = L[i+1], L[i] keepgoing = True
# Hydro settings TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' APPLICATION_NAME = 'HYDRO' SECRET_KEY = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&amp;022shmi1jcgihb*' # SESSION_TIMEOUT is used in validate_session_active decorator to see if the # session is active. SECOND = 1 MINUTE = SECOND * 60 SECONDS_IN_DAY = SECOND*86400 ...
def load_external_repo(): native.local_repository( name = "ext_repo", path = "test/external_repo/repo", )
''' Created on May 26, 2012 @author: Charlie ''' class MainModule01(object): def __init__(self): pass
# # PySNMP MIB module GENERIC-3COM-VLAN-MIB-1-0-7 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERIC-3COM-VLAN-MIB-1-0-7 # Produced by pysmi-0.3.4 at Wed May 1 11:09:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python versio...
""" User configuration file for the client. """ SERVER_ADDRESS = "127.0.0.1" SERVER_PORT = 50000
# PROBLEM # # 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 case of ti...
mandatory = \ { 'article' : ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'], 'book' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'], 'booklet' : ['ENTRYTYPE', 'ID', 'title', 'year'], 'conference' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'], 'inbook' : ['...
class ParkingLot: def __init__(self, username, latitude, longitude, totalSpace, costHour): self.username = username self.latitude = latitude self.longitude = longitude self.totalSpace = totalSpace self.availableSpace = totalSpace self.costHour = costHour def getS...
class AnalyticalModelStick(AnalyticalModel,IDisposable): """ An element that represents a stick in the structural analytical model. Could be one of beam,brace or column type. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def GetAlignmentMethod(self,selector): """ GetA...
"""" Crie uma Fazenda de Bichinhos instanciando vários objetos bichinho e mantendo o controle deles através de uma lista. Imite o funcionamento do programa básico, mas ao invés de exigis que o usuário tome conta de um único bichinho, exija que ele tome conta da fazenda inteira. Cada opção do menu deveria permitir que o...
lst1=list() lst1.append('K') lst1.append('A') lst2=['U', 'S', 'H', 'I', 'K'] print(lst1+lst2) print(lst2[0] +lst2[1]+lst1[1]) for i in lst1+lst2: print(i)
class Photo(object): def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set): self.id = photo_id self.orientation = orientation self.number_of_tags = number_of_tags self.tags = tags self.is_vertical = orientation == 'V' self.is_horizontal =...
# addition will takes place after multiplication and addition num1 = 1 + 4 * 3 / 2; # same as 5 * 3 /2 num2 = (1 + 4) * 3 / 2; # same as 1+12/2 num3 = 1 + (4 * 3) / 2; print("python follow precedence rules"); # this should produce 7.5 print(num1); print(num2); print(num3);
class Fruit: def __init__(self,name,parents): self.name = name self.parents = parents self.children = [] self.family = [] self.siblings = [] self.node = None ## Link to node object in graph def find_children(self,basket): # basket is a list of Fruit objects for fruit in basket: if ...
file = open("text.txt", "r") file2 = open("text2.txt", "w") for data in file: file2.write(data) file.close() file2.close()
animals = ['cat', 'dog', 'pig'] for animal in animals : print (animal + 'would make a great pet.') print ('All of those animals would makea great pet')
"""Exceptions of the library""" class PyConnectError(Exception): """Base class for all exceptions in py_connect.""" class InvalidPowerCombination(PyConnectError): """Connection of different power pins.""" class MaxConnectionsError(PyConnectError): """Interface has exceeded it's max connections limit."...
#! /bin/bash/python3 '''Ejemplo de un script que puede ser importado como módulo.''' titulo = "Espacio muestral" datos = (76, 81, 75, 77, 80, 75, 76, 79, 75) def promedio(encabezado, muestra): '''Despliega el contenido de encabezado,así como el cálculo del promedio de muestra, ingresado en una lista o tu...
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock'] num_files = 100 with open(f'INPUT_FULL', 'w') as f: for genre in genres: for i in range(num_files): for j in range(6): f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav /...
# Copyright 2020 University of Adelaide # # 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 ...
d = {'key1': 1, 'key2': 2, 'key3': 3} for k in d: print(k) # key1 # key2 # key3 for k in d.keys(): print(k) # key1 # key2 # key3 keys = d.keys() print(keys) print(type(keys)) # dict_keys(['key1', 'key2', 'key3']) # <class 'dict_keys'> k_list = list(d.keys()) print(k_list) print(type(k_list)) # ['key1', 'key...
# Testing out some stuff with async and await async def hello(name): print ("hello" + name) return "hello" + name # We can use the await statement in coroutines to call # coroutines as normal functions; i.e. what it implies is that # if we runt return await func(*args) in a courtoune # is like running r...
number = int(input()) raiz = number/2 for i in range(1,20): raiz = ((raiz ** 2) + number) / (2 * raiz) print(raiz)
class Item: def __init__(self,weight,value) -> None: self.weight=weight self.value=value self.ratio=value/weight def knapsackMethod(items,capacity): items.sort(key=lambda x: x.ratio,reverse=True) usedCapacity=0 totalValue=0 for i in items: if usedCapacity+i.weight<=c...
class Node: """ A node class used in A* Pathfinding. parent: it is parent of current node position: it is current position of node in the maze. g: cost from start to current Node h: heuristic based estimated cost for current Node to end Node f: total cost of present n...
#LeetCode problem 54: Spiral Matrix class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if(len(matrix)==0 or len(matrix[0])==0): return [] res=[] rb=0 re=len(matrix) cb=0 ce=len(matrix[0]) while(re>rb and ce>cb): ...
""" Non-orthogonal Reflection by Ira Greenberg. Based on the equation (R = 2N(N * L) - L) where R is the reflection vector, N is the normal, and L is the incident vector. """ # Position of left hand side of floor. base1 = None # Position of right hand side of floor. base2 = None # A list of subpoints along the floo...
def isPower(n): ''' Determine if the given number is a power of some non-negative integer. ''' if n == 1: return True sqrt = math.sqrt(n) for a in range(int(sqrt)+1): for b in range(2, int(sqrt)+1): if a ** b == n: return True return False
# Add your own choices here! fruit = ["apples", "oranges", "pears", "grapes", "blueberries"] lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"] situations = {"fruit":fruit, "lunch":lunch}
__author__ = 'Brian Nguyen' def greeting(msg): print("We would like to say: " + msg)
""" This module contains the general settings used across modules. """ FPS = 60 WINDOW_WIDTH = 1100 WINDOW_HEIGHT = 600 TIME_MULTIPLIER = 1.0
class Solution: def longestSubarray(self, nums: List[int]) -> int: k = 1 max_len, i = 0, 0 for j in range(len(nums)): if nums[j] == 0: k -= 1 if k < 0: if nums[i] == 0: k += 1 i += 1 max_...
ROOT_WK_API_URL = "https://api.wanikani.com/v2/" RESOURCES_WITHOUT_IDS = ["user", "collection", "report"] SUBJECT_ENDPOINT = "subjects" SINGLE_SUBJECT_ENPOINT = r"subjects/\d+" ASSIGNMENT_ENDPOINT = "assignments" REVIEW_STATS_ENDPOINT = "review_statistics" STUDY_MATERIALS_ENDPOINT = "study_materials" REVIEWS_ENDPOINT ...
""" Script testing 14.4.2 control from OWASP ASVS 4.0: 'Verify that all API responses contain a Content-Disposition: attachment; filename="api.json" header (or other appropriate filename for the content type).' The script will raise an alert if 'Content-Disposition' header is present but not follow the format - Cont...
MAX_N = 10000 + 1 isprime = [True] * (MAX_N) isprime[0] = False isprime[1] = False for i in range(2, MAX_N): if not isprime[i]: continue for j in range(i+i, MAX_N, i): isprime[j] = False T = int(input()) for _ in range(T): n = int(input()) for i in range(n//2, 1, -1): if isprim...
# # PySNMP MIB module DOCS-LOADBALANCING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-LOADBALANCING-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:53:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
""" Linear State Space Element Class """ class Element(object): """ State space member """ def __init__(self): self.sys_id = str() # A string with the name of the element self.sys = None # The actual object self.ss = None # The state space object self.settings = ...
"""Constants.""" # A ``None``-ish constant for use where ``None`` may be a valid value. NOT_SET = type('NOT_SET', (), { '__bool__': (lambda self: False), '__str__': (lambda self: 'NOT_SET'), '__repr__': (lambda self: 'NOT_SET'), '__copy__': (lambda self: self), })() # An alias for NOT_SET that may be...
class Solution: def minCut(self, s: str) -> int: dp=self.isPal(s) return self.bfs(s,dp) def isPal(self,s): dp=[[False for i in s] for i in s] for i in range(len(s)): dp[i][i]=True if i+1<len(s): dp[i][i+1]=True if s[i]==s[i+1] else False ...
def main(j, args, params, tags, tasklet): params.merge(args) doc = params.doc tags = params.tags out = "" cmdstr = params.macrostr.split(":", 1)[1].replace("}}", "").strip() md5 = j.base.byteprocessor.hashMd5(cmdstr) j.system.fs.createDir(j.system.fs.joinPaths(j.core.portal.active.filesro...
""" TakeDown v0.0.1 =============== author: Zesheng Xing email: zsxing@ucdavis.edu This Python project is to help people search on some client hosting contents that potential violate the their copyright. """ VERSION = "0.1.0" DESCRIPTION = "A python script that allows users to search potential copyright violated info...
""" Exceptions module """ class CuckooHashMapFullException(Exception): """ Exception raised when filter is full. """ pass
print('Interrogando um suspeito: ') pg1 = str(input("Telefonou para a vítma?(S/N)\n").upper().strip()) pg2 = str(input('Esteve no local do crime?(S/N)\n').upper().strip()) pg3 = str(input('Mora perto da vítma?(S/N)\n').upper().strip()) pg4 = str(input('Devia para a vítma?(S/N)\n').upper().strip()) pg5 = str(input('Já t...
class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle == "": return 0 for i in range(0, len(haystack) - len(needle) + 1): print(haystack[i : i + len(needle)], needle) if haystack[i : i + len(needle)] == needle: return i ...
""" 499. Word Count (Map Reduce) https://www.lintcode.com/problem/word-count-map-reduce/description """ class WordCount: # @param {str} line a text, for example "Bye Bye see you next" def mapper(self, _, line): # Write your code here # Please use 'yield key, value' word_lists = line.spl...
class Solution: def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ # This method changes the existing tree instead of returning a new one if t1 and t2: t1.val += t2.val t1.left = self.mergeTrees...
n = int(input()) m = int(input()) r = m for i in range(n): a, b = map(int, input().split()) m += a m -= b if m < 0: print(0) exit() r = max(r, m) print(r)
name = " alberT" one = name.rsplit() print("one:", one) two = name.index('al', 0) print("two:", two) three = name.index('T', -1) print("three:", three) four = name.replace('l', 'p') print("four:", four) five = name.split('l') print("five:", five) six = name.upper() print("six:", six) seven = name.lower() print("...
n = int(input()) s = [[0] * 10 for _ in range(n + 1)] s[1] = [0] + [1] * 9 mod = 1000 ** 3 for i in range(2, n + 1): for j in range(0, 9 + 1): if j >= 1: s[i][j] += s[i - 1][j - 1] if j <= 8: s[i][j] += s[i - 1][j + 1] print(sum(s[n]) % mod)
class RpnCalcError(Exception): """Calculator Generic Exception""" pass class StackDepletedError(RpnCalcError): """ Stack is out of items """ pass
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Definition of all Rainman2 exceptions """ __author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)' __date__ = 'Wednesday, February 14th 2018, 11:38:08 am' class FileOpenError(IOError): """ Exception raised when a file couldn't be opene...
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. print('-' * 100) print('{: ^100}'.format('EXERCÍCIO 014 - CONVERSOR DE TEMPERATURAS')) print('-' * 100) c = float(input('Informe a temperatura em ºC: ')) f = ((9 * c) / 5) + 32 print(f'A temperatura de {c:...
__title__ = "FisherExactTest" __version__ = "1.0.1" __author__ = "Ae-Mc" __author_email__ = "ae_mc@mail.ru" __description__ = "Two tailed Fisher's exact test wrote in pure Python" __url__ = "https://github.com/Ae-Mc/Fisher" __classifiers__ = [ "Programming Language :: Python :: 3 :: Only", "Programming Language...
# Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. # Example: # Given nums = [-2, 0, 3, -5, 2, -1] # sumRange(0, 2) -> 1 # sumRange(2, 5) -> -1 # sumRange(0, 5) -> -3 class NumArray: def __init__(self, nums): """ :type nums: List[int] ...
# -*- coding: utf-8 -*- class Solution: def sortSentence(self, s: str) -> str: tokens = s.split() result = [None] * len(tokens) for token in tokens: word, index = token[:-1], int(token[-1]) result[index - 1] = word return ' '.join(result) if __name__ == '...
#!/usr/bin/python3 ##python3 闭包 与 nonlocal #如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用, #那么内部函数就被认为是闭包(closure) def A_(): var = 0 def clo_B(): var_b = 1 # 闭包的局部变量 var = 100 print(var) # 引用外部的var , 但是不会改变var 的值 return clo_B #clo_B是一个闭包 #nonlocal 关键字 def A_(): var = 0 def clo_B(): nonlocal var # nonlocal关...
"""Specifies the supported Bazel versions.""" CURRENT_BAZEL_VERSION = "5.0.0" OTHER_BAZEL_VERSIONS = [ "6.0.0-pre.20220223.1", ] SUPPORTED_BAZEL_VERSIONS = [ CURRENT_BAZEL_VERSION, ] + OTHER_BAZEL_VERSIONS
def _compile(words): if not len(words): return None, '' num = None if words[0].isdigit(): num = int(words[0]) words = words[1:] return num, ' '.join(words) def _split_out_colons(terms): newterms = [] for term in terms: if ':' in term: subterms = term...
class BankAccount: def __init__(self, checking = None, savings = None): self._checking = checking self._savings = savings def get_checking(self): return self._checking def set_checking(self, new_checking): self._checking = new_checking def get_savings(self): return self._savings def s...
""" LeetCode Problem: 344. Reverse String Link: https://leetcode.com/problems/reverse-string/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(n) Space Complexity: O(1) """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-pla...
# 670. 最大交换 # # 20200905 # huao class Solution: def maximumSwap(self, num: int) -> int: return int(self.maximumSwapStr(str(num))) def maximumSwapStr(self, num: str) -> str: s = list(num) if len(s) == 1: return num maxNum = '0' maxLoc = 0 for i in ran...
# abba # foo bar bar foo text1 = list(input()) text2 = input().split() # text1 = set(text1) print(text1) print(text2) for i in range(len(text1)): if text1[i] == "a": text1[i] = 1 else: text1[i] = 0 for i in range(len(text2)): if text2[i] == "foo": text2[i] = 1 else: te...
#!/usr/bin/env python3 ''' The MIT License (MIT) Copyright (c) 2014 Mark Haines 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...
class Solution: def isIdealPermutation(self, A: List[int]) -> bool: n = len(A) g = local = 0 for i in range(1, n): if A[i] < A[i-1]: local += 1 if A[i] < i: diff = i - A[i] ...
xval = 0 xvalue1 = 1 xvalue2 = 2 print(xvalue1 + xvalue2)
class Order(): def __init__(self, exchCode, sym_, _sym, orderType, price, side, qty, stopPrice=''): self.odid = None self.status = None self.tempOdid = None self.sym_ = sym_ self._sym = _sym self.symbol = sym_ + _sym self.exchCode = exchCode.upper() se...