content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" https://leetcode.com/problems/largest-number-at-least-twice-of-others/ In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwis...
""" https://leetcode.com/problems/largest-number-at-least-twice-of-others/ In a given integer array nums, there is always exactly one largest element. Find whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwis...
def metric(grams): """ Converts grams to kilograms if grams are greater than 1,000. """ grams = int(grams) if grams >= 1000: kilograms = 0 kilograms = grams / 1000.0 # If there is no remainder, convert the float to an integer # so that the '.0' is removed. if not (gra...
def metric(grams): """ Converts grams to kilograms if grams are greater than 1,000. """ grams = int(grams) if grams >= 1000: kilograms = 0 kilograms = grams / 1000.0 if not grams % 1000: kilograms = int(kilograms) return u'%s %s' % (str(kilograms), 'kg') else:...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: Register class RegisterStatus(object): Success = 0 FailUnknown = 1 FailUserNameConflicted = 2
class Registerstatus(object): success = 0 fail_unknown = 1 fail_user_name_conflicted = 2
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ # longest substring without repeating char seen = {} left, ans = 0, 0 for idx, ch in enumerate(s): if ch in seen: left = max(left, seen[...
class Solution: def length_of_longest_substring(self, s): """ :type s: str :rtype: int """ seen = {} (left, ans) = (0, 0) for (idx, ch) in enumerate(s): if ch in seen: left = max(left, seen[ch]) seen[ch] = idx + 1 ...
word1 = input() word2 = txt = input()[::-1] if(word1 == word2): print("YES") else: print("NO")
word1 = input() word2 = txt = input()[::-1] if word1 == word2: print('YES') else: print('NO')
# MIT License # Copyright (C) Michael Tao-Yi Lee (taoyil AT UCI EDU) # A descriptor class class PositiveAttr(object): def __init__(self, name): self.name = name self.parent = None def __get__(self, instance, cls): print("get called", instance, cls) return instance.__dict__[sel...
class Positiveattr(object): def __init__(self, name): self.name = name self.parent = None def __get__(self, instance, cls): print('get called', instance, cls) return instance.__dict__[self.name] def __set__(self, instance, value): print('set called', instance, valu...
class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: s = s.replace('-', '').upper()[::-1] return '-'.join(s[i:i + k] for i in range(0, len(s), k))[::-1]
class Solution: def license_key_formatting(self, s: str, k: int) -> str: s = s.replace('-', '').upper()[::-1] return '-'.join((s[i:i + k] for i in range(0, len(s), k)))[::-1]
""" request_interceptor.py ~~~~~~ Created By : Pankaj Suthar """ def intercept_request(request): """ intercept_request :param request: Flask Request Object :return: updated request """ pass
""" request_interceptor.py ~~~~~~ Created By : Pankaj Suthar """ def intercept_request(request): """ intercept_request :param request: Flask Request Object :return: updated request """ pass
class Solution: def rotate(self, nums: List[int], k: int) -> None: if not nums: return step = k % len(nums) self.swap(nums, 0, len(nums) - step - 1) self.swap(nums, len(nums)-step, len(nums) - 1) self.swap(nums, 0, len(nums) - 1) def swap(self, nums, left, ri...
class Solution: def rotate(self, nums: List[int], k: int) -> None: if not nums: return step = k % len(nums) self.swap(nums, 0, len(nums) - step - 1) self.swap(nums, len(nums) - step, len(nums) - 1) self.swap(nums, 0, len(nums) - 1) def swap(self, nums, left,...
""" List / Array Iterable """ numbers = [] print(type(numbers)) # adding elements # append adds at the last index (value) numbers.append(10) numbers.append(45) print(numbers) # insert (index, value) numbers.insert(0, 45) print(numbers) # remoing an element # pop (no arg) --> removes from last index # remove(value) ...
""" List / Array Iterable """ numbers = [] print(type(numbers)) numbers.append(10) numbers.append(45) print(numbers) numbers.insert(0, 45) print(numbers)
""" Given a sorted list of integers, find all the unique triplets which sum up to the given target. Note: Each triplet must be a tuple having elements (input[i], input[j], input[k]), such that i < j < k. The ordering of unique triplets within the output list does not matter. Example: Input : [1,2,3,4,5,6,7] Target: 1...
""" Given a sorted list of integers, find all the unique triplets which sum up to the given target. Note: Each triplet must be a tuple having elements (input[i], input[j], input[k]), such that i < j < k. The ordering of unique triplets within the output list does not matter. Example: Input : [1,2,3,4,5,6,7] Target: 1...
#!/usr/bin/env python #------------------------------------------------------------------------------- # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: #--------------------------------...
class Solution: def min_depth(self, root): if root == None: return 0 if root.left == None or root.right == None: return self.minDepth(root.left) + self.minDepth(root.right) + 1 return min(self.minDepth(root.right), self.minDepth(root.left)) + 1 def min_depth2(se...
# reads from the console two numbers a and b, calculates and prints the face of a rectangle with sides a and b a = int(input()) b = int(input()) print(a * b)
a = int(input()) b = int(input()) print(a * b)
a = [] a.append(2) for i in range(1,36): sum,dem,cnt = 0,0,9; for j in range(i): cnt = 9*(10**(j//2)) sum += cnt a.append(a[i-1]+sum) t = int(input()) for i in range(t): n = int(input()) print(a[n])
a = [] a.append(2) for i in range(1, 36): (sum, dem, cnt) = (0, 0, 9) for j in range(i): cnt = 9 * 10 ** (j // 2) sum += cnt a.append(a[i - 1] + sum) t = int(input()) for i in range(t): n = int(input()) print(a[n])
""" The main entrypoint to our CLI """ def main(): """ The main entrypoint to our CLI """ print("sumgraph!")
""" The main entrypoint to our CLI """ def main(): """ The main entrypoint to our CLI """ print('sumgraph!')
class ResponseBuilder(object): def __init__(self, status_code: int, result = None): """Builder for the response""" self.status_code = status_code self.result = result def get_response(self): return { 'result': self.result, 'status_code': self.status_code ...
class Responsebuilder(object): def __init__(self, status_code: int, result=None): """Builder for the response""" self.status_code = status_code self.result = result def get_response(self): return {'result': self.result, 'status_code': self.status_code}
c_num = int(input()) a_num = 1 b_num = 1 # O(n**2) while a_num < c_num: while b_num < c_num: if (a_num**2 + b_num**2) == c_num**2: print(a_num, b_num) b_num += 1 b_num = 1 a_num += 1 # Bisa pakai yang atas atau yang bawah # O(n**2) # for a in range(1, c_num): # for b in ra...
c_num = int(input()) a_num = 1 b_num = 1 while a_num < c_num: while b_num < c_num: if a_num ** 2 + b_num ** 2 == c_num ** 2: print(a_num, b_num) b_num += 1 b_num = 1 a_num += 1
num = int(input("Enter a number: \t")) pow = int(input("Enter Power: \t")) sum = 1 i = 1 while(i<=pow): sum=sum*num i+=1 print(num,"to the power",pow,"is",sum)
num = int(input('Enter a number: \t')) pow = int(input('Enter Power: \t')) sum = 1 i = 1 while i <= pow: sum = sum * num i += 1 print(num, 'to the power', pow, 'is', sum)
items = [] def enqueue(item): items.append(item) def dequeue(): if len(items) > 0: items.pop(0) enqueue(5) enqueue(11) enqueue('Jones') enqueue(45) print(items) dequeue() print(items) dequeue() print(items)
items = [] def enqueue(item): items.append(item) def dequeue(): if len(items) > 0: items.pop(0) enqueue(5) enqueue(11) enqueue('Jones') enqueue(45) print(items) dequeue() print(items) dequeue() print(items)
class Sampling_InfinteLoopWrapper: def __init__(self, sampling_algo): self.sampling_algo = sampling_algo def get(self): return self.sampling_algo.current() def move_next(self): if not self.sampling_algo.move_next(): self.sampling_algo.reset() assert self.sam...
class Sampling_Infinteloopwrapper: def __init__(self, sampling_algo): self.sampling_algo = sampling_algo def get(self): return self.sampling_algo.current() def move_next(self): if not self.sampling_algo.move_next(): self.sampling_algo.reset() assert self.sa...
##################################### # Installation module for autorecon ##################################### # XXX: Expects seclists to be in /usr/share/seclists # AUTHOR OF MODULE NAME AUTHOR="ypcrts" # DESCRIPTION OF THE MODULE DESCRIPTION="This module will install/update autorecon - a multi-threaded network re...
author = 'ypcrts' description = 'This module will install/update autorecon - a multi-threaded network reconnaissance tool' install_type = 'GIT' repository_location = 'https://github.com/Tib3rius/AutoRecon.git' install_location = 'autorecon' debian = 'python3,python3-pip' fedora = 'git' after_commands = 'cd {INSTALL_LOC...
# -*- coding: UTF-8 -*- lan = 15 for a in range(5): lan *= 10 print(lan)
lan = 15 for a in range(5): lan *= 10 print(lan)
def almost_equal(obj1, obj2, exclude_paths=[]): def almost_equal_helper(x, y, path): if isinstance(x, dict): if not isinstance(y, dict): print(f"At path {path}, obj1 was of type dict while obj2 was not") return False if not set(x.keys()) == set(y.key...
def almost_equal(obj1, obj2, exclude_paths=[]): def almost_equal_helper(x, y, path): if isinstance(x, dict): if not isinstance(y, dict): print(f'At path {path}, obj1 was of type dict while obj2 was not') return False if not set(x.keys()) == set(y.keys...
table = [] n, m = map(int, input().split()) for i in range(n): row = list(map(int, input().split())) table.append(row) k = int(input()) table.sort(key=lambda x: x[k]) for row in table: print(*row)
table = [] (n, m) = map(int, input().split()) for i in range(n): row = list(map(int, input().split())) table.append(row) k = int(input()) table.sort(key=lambda x: x[k]) for row in table: print(*row)
class Company: def __init__(self): self.ticker = '' self.name = '' self.rating = '' self.rating_date = '' self.piotroski_f_score = '0.0' self.base_link = '' self.p_e = '0.0' self.p_bv = '0.0' self.p_bv_g = '0.0' self.p_s = '0.0' ...
class Company: def __init__(self): self.ticker = '' self.name = '' self.rating = '' self.rating_date = '' self.piotroski_f_score = '0.0' self.base_link = '' self.p_e = '0.0' self.p_bv = '0.0' self.p_bv_g = '0.0' self.p_s = '0.0' ...
"""All the key sequences""" # If you add a binding, add something about your setup # if you can figure out why it's different # Special names are for multi-character keys, or key names # that would be hard to write in a config file # TODO add PAD keys hack as in bpython.cli # fmt: off CURTSIES_NAMES = { b' ': ...
"""All the key sequences""" curtsies_names = {b' ': '<SPACE>', b'\x1b ': '<Esc+SPACE>', b'\t': '<TAB>', b'\x1b[Z': '<Shift-TAB>', b'\x1b[A': '<UP>', b'\x1b[B': '<DOWN>', b'\x1b[C': '<RIGHT>', b'\x1b[D': '<LEFT>', b'\x1bOA': '<UP>', b'\x1bOB': '<DOWN>', b'\x1bOC': '<RIGHT>', b'\x1bOD': '<LEFT>', b'\x1b[1;5A': '<Ctrl-UP>...
__version__ = '0.3.0' __author__ = 'Ian Dennis Miller' __email__ = 'iandennismiller@gmail.com' __url__ = 'http://diamond-methods.org/puppet-diamond.html'
__version__ = '0.3.0' __author__ = 'Ian Dennis Miller' __email__ = 'iandennismiller@gmail.com' __url__ = 'http://diamond-methods.org/puppet-diamond.html'
__author__ = 'Pat and Tony' #abstract class for the Observer interface class Observer(object): #must be implemented in all subclasses def notify(self, msg): pass
__author__ = 'Pat and Tony' class Observer(object): def notify(self, msg): pass
def solution(N, A): result = [0] * N max_num, max_counter = 0, 0 for num in A: if num == N + 1: max_counter = max_num else: result[num-1] = max(result[num-1], max_counter) result[num-1] += 1 max_num = max(max_num, result[num-1]) for ...
def solution(N, A): result = [0] * N (max_num, max_counter) = (0, 0) for num in A: if num == N + 1: max_counter = max_num else: result[num - 1] = max(result[num - 1], max_counter) result[num - 1] += 1 max_num = max(max_num, result[num - 1]) ...
def can_build(env, platform): return env["tools"] and env["module_raycast_enabled"] def configure(env): pass
def can_build(env, platform): return env['tools'] and env['module_raycast_enabled'] def configure(env): pass
''' A test suite of unit tests for the plantpredict-python package. It is assumed that the plantpredict package is in the python path, and `mock` is installed. Note: mock could not be installed through conda, used pip instead. To run all tests, from the `tests` directory, do: ``` python -m unittest discover -v ``` ...
""" A test suite of unit tests for the plantpredict-python package. It is assumed that the plantpredict package is in the python path, and `mock` is installed. Note: mock could not be installed through conda, used pip instead. To run all tests, from the `tests` directory, do: ``` python -m unittest discover -v ``` ...
class Animal: fur_color = "Orange" def speak(self): raise NotImplementedError def eat(self): pass def chase(self): pass class HouseCat(Animal): def speak(self): print("Meeeeowwww") cat = HouseCat() cat.speak()
class Animal: fur_color = 'Orange' def speak(self): raise NotImplementedError def eat(self): pass def chase(self): pass class Housecat(Animal): def speak(self): print('Meeeeowwww') cat = house_cat() cat.speak()
class Solution: def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels=[] for c in s: if c=='a' or c=='e' or c=='i' or c=='o' or c=='u' or c=='A' or c=='E' or c=='I' or c=='O' or c=='U': vowels.append(c) st='' ...
class Solution: def reverse_vowels(self, s): """ :type s: str :rtype: str """ vowels = [] for c in s: if c == 'a' or c == 'e' or c == 'i' or (c == 'o') or (c == 'u') or (c == 'A') or (c == 'E') or (c == 'I') or (c == 'O') or (c == 'U'): vo...
class ModelExecutionContext: """ This class represents the execution context of a model. It will contain information like correlation id, etc... that the model might need to use during execution. """ def __init__(self, correlation_id, process, online=False): """ Initial...
class Modelexecutioncontext: """ This class represents the execution context of a model. It will contain information like correlation id, etc... that the model might need to use during execution. """ def __init__(self, correlation_id, process, online=False): """ Initializes t...
"""Constants for the Hassio Info integration.""" DOMAIN = "hassio_info" TITLE = "Supervisor+"
"""Constants for the Hassio Info integration.""" domain = 'hassio_info' title = 'Supervisor+'
#// 26 bits block id, 8 bits shift distance, 4 bits last key byte, 5 bits storage, 21 bits value print( " DELME sz 1751672936 keysz 26728 b 9816750e idx 422567") def prt(b): print( " block id ", b >> 38 ) print( " shift ", (b >> 30) & 0xFF ) print( " key ", (b >> 26) & 0xF ) print( " storage ", (b >...
print(' DELME sz 1751672936 keysz 26728 b 9816750e idx 422567') def prt(b): print(' block id ', b >> 38) print(' shift ', b >> 30 & 255) print(' key ', b >> 26 & 15) print(' storage ', b >> 21 & 31) print(' value ', b >> 0 & 2097151) prt(2551602861) prt(3625344685)
#Websites to crawling For the News Paper, with white list and black list WhiteListURLS = { 'Hoy': 'http://hoy.com.do/encuestas/', 'Listin Diario': 'https://www.listindiario.com/encuestas', 'La Informacion': 'http://www.lainformacion.com.do/modulos/encuestas/encuestas_anteriores.php?idEnc=744', 'La Bazuc...
white_list_urls = {'Hoy': 'http://hoy.com.do/encuestas/', 'Listin Diario': 'https://www.listindiario.com/encuestas', 'La Informacion': 'http://www.lainformacion.com.do/modulos/encuestas/encuestas_anteriores.php?idEnc=744', 'La Bazuca': 'http://www.labazuca.com/encuestas/', 'El Nacional': 'http://elnacional.com.do/encue...
class headless_download(object): ROBOT_LIBRARY_VERSION = 1.0 def __init__(self): pass def enable_download_in_headless_chrome(self, driver, download_dir): """ there is currently a "feature" in chrome where headless does not allow file download: https://bugs.chromium.org/p/c...
class Headless_Download(object): robot_library_version = 1.0 def __init__(self): pass def enable_download_in_headless_chrome(self, driver, download_dir): """ there is currently a "feature" in chrome where headless does not allow file download: https://bugs.chromium.org/p/ch...
def mod_brightness(colour, modifier): red = min(int(((colour & 0xff0000) >> 16) * modifier), 0xff) green = min(int(((colour & 0x00ff00) >> 8) * modifier), 0xff) blue = min(int((colour & 0x0000ff) * modifier), 0xff) return red << 16 | green << 8 | blue def int_scale_flag(flag_name, max_size)...
def mod_brightness(colour, modifier): red = min(int(((colour & 16711680) >> 16) * modifier), 255) green = min(int(((colour & 65280) >> 8) * modifier), 255) blue = min(int((colour & 255) * modifier), 255) return red << 16 | green << 8 | blue def int_scale_flag(flag_name, max_size): flag = bmp_data(f...
def Musical_era_question_1(): score_number = 0 what_key_str = "minor" #print ("Can you identify this key?") a=input("Can you identify this key? \n Question 1: What is the key of this song?") #import audio file of We're Going Wrong here if "minor" in a: score_number = 1 return sco...
def musical_era_question_1(): score_number = 0 what_key_str = 'minor' a = input('Can you identify this key? \n Question 1: What is the key of this song?') if 'minor' in a: score_number = 1 return (score_number, what_key_str, 'Correct!') else: score_number = 0 return (...
#!/usr/bin/env python # # Copyright 2014 - 2016 The BCE Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the license.txt file. # _MAJOR = 1 _MINOR = 5 _REVISION = 1097 def get_version(): """Get BCE version. :rtype : (int, int, int) :ret...
_major = 1 _minor = 5 _revision = 1097 def get_version(): """Get BCE version. :rtype : (int, int, int) :return: A tuple (Major, Minor, Revision). """ return (_MAJOR, _MINOR, _REVISION)
class ParserException(Exception): """ParserException Generic exception for parser errors Extends: Exception """ pass class NoRouteException(Exception): """NoRouteException Generic exception for route not found errors Extends: Exception """ pass
class Parserexception(Exception): """ParserException Generic exception for parser errors Extends: Exception """ pass class Norouteexception(Exception): """NoRouteException Generic exception for route not found errors Extends: Exception """ pass
ten_things = "Apples Oranges Crows Telephone Light Sugar" print ("Wait there are not 10 things in that list. Let's fix that.") stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len (stuff) != 10: next_one = more_stuff.pop() pri...
ten_things = 'Apples Oranges Crows Telephone Light Sugar' print("Wait there are not 10 things in that list. Let's fix that.") stuff = ten_things.split(' ') more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy'] while len(stuff) != 10: next_one = more_stuff.pop() print('Adding ', next_...
def _generate_variables(repository_ctx, build_info): repository_ctx.template( "generate_variables.py", repository_ctx.path(Label("//support/bazel:generate_variables.py")), {}, ) python_interpreter = repository_ctx.attr.python_interpreter if repository_ctx.attr.python_interpreter...
def _generate_variables(repository_ctx, build_info): repository_ctx.template('generate_variables.py', repository_ctx.path(label('//support/bazel:generate_variables.py')), {}) python_interpreter = repository_ctx.attr.python_interpreter if repository_ctx.attr.python_interpreter_target != None: python_...
class dictRules: """ A special class for getting and setting multiple dictionaries simultaneously. This class is not meant to be instantiated on its own, but rather in response to a slice operation on UniformDictList. """ def __init__(parent, slice): self.parent = parent self.ra...
class Dictrules: """ A special class for getting and setting multiple dictionaries simultaneously. This class is not meant to be instantiated on its own, but rather in response to a slice operation on UniformDictList. """ def __init__(parent, slice): self.parent = parent self.ra...
""" A minimal UF implementation. """ class UnionFind: """ Typical DSU implementation with path-compression and union by rank. Requires members to be able to be used as indexes. """ def __init__(self, iterable=None): self.parent = list(iterable or []) self.rank = [0] * len(self...
""" A minimal UF implementation. """ class Unionfind: """ Typical DSU implementation with path-compression and union by rank. Requires members to be able to be used as indexes. """ def __init__(self, iterable=None): self.parent = list(iterable or []) self.rank = [0] * len(self...
def check_bc(self, p=None): # check that boundary conditions are satisfied if self.nconstraints == 0: # no boundary conditions return True if p is None: # use random parameter vector p = np.random.randn(self.dof) coeff = self.get_block_coeff(p) lhs = np.polyval(...
def check_bc(self, p=None): if self.nconstraints == 0: return True if p is None: p = np.random.randn(self.dof) coeff = self.get_block_coeff(p) lhs = np.polyval(coeff, 0)[1:] rhs = list(map(np.polyval, coeff.T, np.diff(self.breakpoints[:-1]))) assert np.allclose(lhs, rhs)
_exports = [ "all_resources", "carbon_per_mmbtu", "carbon_per_mwh", "carbon_resources", "clean_resources", "label2type", "nox_per_mwh", "renewable_resources", "so2_per_mwh", "type2color", "type2hatchcolor", "type2label", ] type2color = { "wind": "xkcd:green", "so...
_exports = ['all_resources', 'carbon_per_mmbtu', 'carbon_per_mwh', 'carbon_resources', 'clean_resources', 'label2type', 'nox_per_mwh', 'renewable_resources', 'so2_per_mwh', 'type2color', 'type2hatchcolor', 'type2label'] type2color = {'wind': 'xkcd:green', 'solar': 'xkcd:amber', 'hydro': 'xkcd:light blue', 'ng': 'xkcd:o...
""" PPO algorithm implementation """ class Model(object): """ PPO algorithm """
""" PPO algorithm implementation """ class Model(object): """ PPO algorithm """
def extractWolfieTranslation(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'The amber sword' in item['tags']: return buildReleaseMessageWithType(item, 'The Amber Sword', vol, chp, frag=frag, po...
def extract_wolfie_translation(item): """ """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'The amber sword' in item['tags']: return build_release_message_with_type(item, 'The A...
def is_divisible(num, divs): return all([num % div == 0 for div in divs]) # MAIN start = int(input('Start of range: ')) end = int(input('End of range: ')) divs = list( map( lambda i: int(i), input('Type in the divisors, separated by commas: ').split(',') ) ) divisibles = [n for n in range(start, end) if is_div...
def is_divisible(num, divs): return all([num % div == 0 for div in divs]) start = int(input('Start of range: ')) end = int(input('End of range: ')) divs = list(map(lambda i: int(i), input('Type in the divisors, separated by commas: ').split(','))) divisibles = [n for n in range(start, end) if is_divisible(n, divs)]...
#!/usr/bin/env python # vim: set ts=4 sw=4 et: class Controller(object): """ Encapsulates the control logic for each stage of flight within its own controller class. """ def __init__(self, commander, vehicle): self.commander = commander self.vehicle = vehicle def enter(self): ...
class Controller(object): """ Encapsulates the control logic for each stage of flight within its own controller class. """ def __init__(self, commander, vehicle): self.commander = commander self.vehicle = vehicle def enter(self): """ Called by the commander when...
# -*- coding: utf-8 -*- """ 2027. Minimum Moves to Convert String https://leetcode.com/problems/minimum-moves-to-convert-string/ Example 1: Input: s = "XXX" Output: 1 Explanation: XXX -> OOO We select all the 3 characters and convert them in one move. Example 2: Input: s = "XXOX" Output: 2 Explanation: XXOX -> OOO...
""" 2027. Minimum Moves to Convert String https://leetcode.com/problems/minimum-moves-to-convert-string/ Example 1: Input: s = "XXX" Output: 1 Explanation: XXX -> OOO We select all the 3 characters and convert them in one move. Example 2: Input: s = "XXOX" Output: 2 Explanation: XXOX -> OOOX -> OOOO We select the f...
coordinates_E0E1E1 = ((126, 114), (126, 116), (126, 117), (126, 118), (127, 114), (127, 120), (128, 114), (128, 115), (128, 119), (128, 121), (129, 105), (129, 108), (129, 115), (129, 120), (129, 121), (130, 101), (130, 103), (130, 104), (130, 109), (130, 120), (130, 121), (131, 101), (131, 105), (131, 106), (131, 10...
coordinates_e0_e1_e1 = ((126, 114), (126, 116), (126, 117), (126, 118), (127, 114), (127, 120), (128, 114), (128, 115), (128, 119), (128, 121), (129, 105), (129, 108), (129, 115), (129, 120), (129, 121), (130, 101), (130, 103), (130, 104), (130, 109), (130, 120), (130, 121), (131, 101), (131, 105), (131, 106), (131, 10...
"""08_arithmetic_operations.py.""" a = 15 b = 2 sum = a + b difference = a - b product = a * b division = a / b remainder = a % b print(f'{a} + {b} = {sum}') # 15 + 2 = 17 print(f'{a} - {b} = {difference}') # 15 - 2 = 13 print(f'{a} * {b} = {product}') # 15 * 2 = 30 print(f'{a} / {b} = {division}') # 15 / 2 = 7.5...
"""08_arithmetic_operations.py.""" a = 15 b = 2 sum = a + b difference = a - b product = a * b division = a / b remainder = a % b print(f'{a} + {b} = {sum}') print(f'{a} - {b} = {difference}') print(f'{a} * {b} = {product}') print(f'{a} / {b} = {division}') print(f'{a} % {b} = {remainder}')
with open('input.txt', 'r') as file: start, stop = file.read().split('-') start = int(start) stop = int(stop) result_1 = 0 result_2 = 0 for pword in range(start, stop): isdouble = False num = [int(i) for i in str(pword)] if num == sorted(num): counts = {str(pword).count(x) for x in str(pword)}...
with open('input.txt', 'r') as file: (start, stop) = file.read().split('-') start = int(start) stop = int(stop) result_1 = 0 result_2 = 0 for pword in range(start, stop): isdouble = False num = [int(i) for i in str(pword)] if num == sorted(num): counts = {str(pword).count(x) for x in str(pword)}...
#print("Hello World") #temperature = int(input("What is the temperature outside?")) #if temperature > 80: #print("Turn on the AC.") #else: #print("Open the Windows.") score = int(input("What is your test score?")) if score >= 90: print('Your grade is an A.') elif score>= 80: print('Your grade is a B'...
score = int(input('What is your test score?')) if score >= 90: print('Your grade is an A.') elif score >= 80: print('Your grade is a B') elif score >= 70: print('Your grade is a C') elif score >= 60: print('Your grade is a D') else: print('You Suck,, Drop Out of School')
class ZenviaTokenNotFound(Exception): pass class ZenviaUrlNotFound(Exception): pass class InvalidArgument(Exception): pass
class Zenviatokennotfound(Exception): pass class Zenviaurlnotfound(Exception): pass class Invalidargument(Exception): pass
def _check_box_size(size): if int(size) <= 0: raise ValueError(f"Invalid box size. Must be larger than 0") def _check_border(size): if int(size) <= 0: raise ValueError(f"Invalid border value. Must be larger than 0") class QRCode: def __init__(self, box_size=10, border=2): _check_...
def _check_box_size(size): if int(size) <= 0: raise value_error(f'Invalid box size. Must be larger than 0') def _check_border(size): if int(size) <= 0: raise value_error(f'Invalid border value. Must be larger than 0') class Qrcode: def __init__(self, box_size=10, border=2): _check...
n = int(input()) cnt = 0 for i in range(2,11): n2 = n L = [] while(n2 > 0): L.append(n2%i) n2//=i if L == L[::-1]: print(i,end=" ") for k in L: print(k, end = "") print() cnt+=1 if cnt == 0: print("NIE")
n = int(input()) cnt = 0 for i in range(2, 11): n2 = n l = [] while n2 > 0: L.append(n2 % i) n2 //= i if L == L[::-1]: print(i, end=' ') for k in L: print(k, end='') print() cnt += 1 if cnt == 0: print('NIE')
# # PySNMP MIB module TIMETRA-BSX-NG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-BSX-NG-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:17:06 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) ...
'''Finding the Square Root of an Integer Find the square root of the integer without using any Python library. You have to find the floor value of the square root. For example if the given number is 16, then the answer would be 4. If the given number is 27, the answer would be 5 because sqrt(5) = 5.196 whose floor va...
"""Finding the Square Root of an Integer Find the square root of the integer without using any Python library. You have to find the floor value of the square root. For example if the given number is 16, then the answer would be 4. If the given number is 27, the answer would be 5 because sqrt(5) = 5.196 whose floor va...
class Solution: def scoreOfParentheses(self, S: str) -> int: sLen = len(S) if sLen == 0: return 0 elif sLen == 1: # throw out error message pass return 0 else: sList = [] bgnIdx = 0 num = 0 ...
class Solution: def score_of_parentheses(self, S: str) -> int: s_len = len(S) if sLen == 0: return 0 elif sLen == 1: pass return 0 else: s_list = [] bgn_idx = 0 num = 0 while True: if...
class Solution: def firstUniqChar(self, s: str) -> int: dicti = {} for char in s: if char not in dicti: dicti[char] = 0 dicti[char] += 1 for index, char in enumerate(s): if dicti[char] == 1: return index return -...
class Solution: def first_uniq_char(self, s: str) -> int: dicti = {} for char in s: if char not in dicti: dicti[char] = 0 dicti[char] += 1 for (index, char) in enumerate(s): if dicti[char] == 1: return index return ...
# noinspection PyUnusedLocal # friend_name = unicode string def hello(friend_name): if not isinstance(friend_name, str): raise ValueError("Invalid input") return f"Hello, {friend_name}!"
def hello(friend_name): if not isinstance(friend_name, str): raise value_error('Invalid input') return f'Hello, {friend_name}!'
# person = dict(first_name="Bob", last_name="Smith") person = { "first_name": "Bob", "last_name": "Smith", "age": 34, "jobs": { "programmer": "Sr. Developer", "crochet": "Magazine Editor for Crocheting" } } # person["jobs"]["programmer"] # person = dict([ # ("first_name", "B...
person = {'first_name': 'Bob', 'last_name': 'Smith', 'age': 34, 'jobs': {'programmer': 'Sr. Developer', 'crochet': 'Magazine Editor for Crocheting'}} for key in person: print(key + ': ' + str(person[key]))
k, q = map(int, input().split()) dp = [[0.0 for i in range(k + 1)] for j in range(10000)] dp[0][0] = 1.0 for i in range(1, 10000): for j in range(1, k + 1): dp[i][j] = dp[i - 1][j] * j / k + dp[i - 1][j - 1] * (k - j + 1) / k for t in range(q): p = int(input()) for i in range(10000): ...
(k, q) = map(int, input().split()) dp = [[0.0 for i in range(k + 1)] for j in range(10000)] dp[0][0] = 1.0 for i in range(1, 10000): for j in range(1, k + 1): dp[i][j] = dp[i - 1][j] * j / k + dp[i - 1][j - 1] * (k - j + 1) / k for t in range(q): p = int(input()) for i in range(10000): if p ...
def readlist(file="day_05/input.txt"): with open(file, "r") as f: return [int(char) for char in f.readline().split(",")] def parse_instruction(instruction): sint = str(instruction).zfill(5) parm3 = bool(int(sint[0])) parm2 = bool(int(sint[1])) parm1 = bool(int(sint[2])) op = int(sint[-...
def readlist(file='day_05/input.txt'): with open(file, 'r') as f: return [int(char) for char in f.readline().split(',')] def parse_instruction(instruction): sint = str(instruction).zfill(5) parm3 = bool(int(sint[0])) parm2 = bool(int(sint[1])) parm1 = bool(int(sint[2])) op = int(sint[-2...
# https://projecteuler.net/problem=63 """ The reason i have choosen 25 is because any number which when is raised to the power of 25 gradually increases from 8 digits of 2^25 linearly(at first with a diffrence of 4(that is num_of_digit in 2^25 is 8 and 3^25 id 12) which starts halfening) ,hence all the sollution must ...
""" The reason i have choosen 25 is because any number which when is raised to the power of 25 gradually increases from 8 digits of 2^25 linearly(at first with a diffrence of 4(that is num_of_digit in 2^25 is 8 and 3^25 id 12) which starts halfening) ,hence all the sollution must lie for numbers below 25 only, since a...
def cantApariciones(letra, cadena): cant=0 for i in range(len(cadena)): if (letra==cadena[i]): cant+=1 return (cant) def imprimeCantApariciones(cadena): listaAparecidos=[] for i in range(len(cadena)): letra=cadena[i] if (cantApariciones(letra,listaAp...
def cant_apariciones(letra, cadena): cant = 0 for i in range(len(cadena)): if letra == cadena[i]: cant += 1 return cant def imprime_cant_apariciones(cadena): lista_aparecidos = [] for i in range(len(cadena)): letra = cadena[i] if cant_apariciones(letra, listaApar...
# ***************************************************************** # Copyright 2015 MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description: IBM TA2 batch class # # Modifications: # Date Name Modification # ---- ---- ------------...
class Ibmbatch(list): """ This class represents a batched input. """ def __str__(self): return ''.join([str(int(inp_bit)) for inp_bit in self]) def get_num_values(self, value): """returns the number of instances of value in the batch""" num_values = 0 for elt in sel...
# _*_ coding: utf-8 _*_ # # Package: bookstore.src.core.repository.databases __all__ = ["book_repository", "db_repository", "mysql_repository"]
__all__ = ['book_repository', 'db_repository', 'mysql_repository']
mock_history_data = { "coord": [50.0, 50.0], "list": [ { "main": {"aqi": 2}, "components": { "co": 270.367, "no": 5.867, "no2": 43.184, "o3": 4.783, "so2": 14.544, "pm2_5": 13.448, ...
mock_history_data = {'coord': [50.0, 50.0], 'list': [{'main': {'aqi': 2}, 'components': {'co': 270.367, 'no': 5.867, 'no2': 43.184, 'o3': 4.783, 'so2': 14.544, 'pm2_5': 13.448, 'pm10': 15.524, 'nh3': 0.289}, 'dt': 1606482000}, {'main': {'aqi': 2}, 'components': {'co': 280.38, 'no': 8.605, 'no2': 42.155, 'o3': 2.459, 's...
class Matrix: """ Square matrix """ def __init__(self, matrix): assert len(matrix) == len(matrix[0]), "expected a square matrix" self.container = matrix def __mul__(self, other): if not isinstance(other, Matrix): return TypeError assert len(self.container) == len(oth...
class Matrix: """ Square matrix """ def __init__(self, matrix): assert len(matrix) == len(matrix[0]), 'expected a square matrix' self.container = matrix def __mul__(self, other): if not isinstance(other, Matrix): return TypeError assert len(self.containe...
#! /usr/bin/env python """Module with a dictionary and variables for storing constant parameters. Usage ----- from param import VLT_NACO VLT_NACO['diam'] """ VLT_SPHERE = { 'latitude' : -24.627, 'longitude' : -70.404, 'plsc' : 0.01225, # plate scale [arcsec]/px 'diam': 8.2, ...
"""Module with a dictionary and variables for storing constant parameters. Usage ----- from param import VLT_NACO VLT_NACO['diam'] """ vlt_sphere = {'latitude': -24.627, 'longitude': -70.404, 'plsc': 0.01225, 'diam': 8.2} vlt_naco = {'latitude': -24.627, 'longitude': -70.404, 'plsc': 0.02719, 'diam': 8.2, 'lambdal': ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename: ClimbingStairs.py # @Author: olenji - lionhe0119@hotmail.com # @Description: # @Create: 2019-07-23 11:58 # @Last Modified: 2019-07-23 11:58 class Solution: def climbStairs(self, n: int) -> int: if n == 1: return 1 a = 1 ...
class Solution: def climb_stairs(self, n: int) -> int: if n == 1: return 1 a = 1 b = 2 for i in range(n): (b, a) = (a + b, b) return b if __name__ == '__main__': s = solution() print(s.climbStairs(10))
word = 'banana' count = 0 for letter in word: if letter == 'n': count = count + 1 print(count)
word = 'banana' count = 0 for letter in word: if letter == 'n': count = count + 1 print(count)
""" 1704. Determine if String Halves Are Alike Easy 151 10 Add to List Share You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A',...
""" 1704. Determine if String Halves Are Alike Easy 151 10 Add to List Share You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A',...
class Solution(object): def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ lookup = {} for i, s in enumerate(list1): lookup[s] = i result = [] min_sum = float("inf") ...
class Solution(object): def find_restaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ lookup = {} for (i, s) in enumerate(list1): lookup[s] = i result = [] min_sum = float('inf') ...
n = int(input()) left_dp = [1] * (n + 1) right_dp = [1] * (n + 1) arr = list(map(int, input().split())) for i in range(1, n): for j in range(i): if arr[j] < arr[i]: left_dp[i] = max(left_dp[i], left_dp[j] + 1) for i in range(n - 2, -1, -1): for j in range(n - 1, i, -1): if arr[j]...
n = int(input()) left_dp = [1] * (n + 1) right_dp = [1] * (n + 1) arr = list(map(int, input().split())) for i in range(1, n): for j in range(i): if arr[j] < arr[i]: left_dp[i] = max(left_dp[i], left_dp[j] + 1) for i in range(n - 2, -1, -1): for j in range(n - 1, i, -1): if arr[j] < a...
#encoding:utf-8 subreddit = 'ani_bm' t_channel = '@cahaf_avir' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'ani_bm' t_channel = '@cahaf_avir' def send_post(submission, r2t): return r2t.send_simple(submission)
class Computer: def __init__(self,name,size): self.brand = name self.size = size class Laptop(Computer): def __init__(self,name,size,model): super().__init__(name,size) self.model = model if __name__ == "__main__": abc = Laptop('MSI','15.6','GL Series') print("...
class Computer: def __init__(self, name, size): self.brand = name self.size = size class Laptop(Computer): def __init__(self, name, size, model): super().__init__(name, size) self.model = model if __name__ == '__main__': abc = laptop('MSI', '15.6', 'GL Series') print('...
def div_elem_list(list, divider): try: return [i /divider for i in list] except ZeroDivisionError as e: print(e, '- this is the error.') return list list = list(range(10)) divider = 0 print(div_elem_list(list, divider)) # que permiten que tu no vas a tener errores dentro # ...
def div_elem_list(list, divider): try: return [i / divider for i in list] except ZeroDivisionError as e: print(e, '- this is the error.') return list list = list(range(10)) divider = 0 print(div_elem_list(list, divider))
# Object change log actions OBJECT_CHANGE_ACTION_CREATE = 1 OBJECT_CHANGE_ACTION_UPDATE = 2 OBJECT_CHANGE_ACTION_DELETE = 3 OBJECT_CHANGE_ACTION_CHOICES = ( (OBJECT_CHANGE_ACTION_CREATE, "Created"), (OBJECT_CHANGE_ACTION_UPDATE, "Updated"), (OBJECT_CHANGE_ACTION_DELETE, "Deleted"), ) # User Actions Constan...
object_change_action_create = 1 object_change_action_update = 2 object_change_action_delete = 3 object_change_action_choices = ((OBJECT_CHANGE_ACTION_CREATE, 'Created'), (OBJECT_CHANGE_ACTION_UPDATE, 'Updated'), (OBJECT_CHANGE_ACTION_DELETE, 'Deleted')) user_action_create = 1 user_action_edit = 2 user_action_delete = 3...
class FileStructureHelper: def __init__(self, run_settings): self.run_settings = run_settings def get_project_directory(self): return self.run_settings.app_directory + '/projects/' + self.run_settings.project def get_config_file_path(self): return self.get_project_directory() + "/...
class Filestructurehelper: def __init__(self, run_settings): self.run_settings = run_settings def get_project_directory(self): return self.run_settings.app_directory + '/projects/' + self.run_settings.project def get_config_file_path(self): return self.get_project_directory() + '/...
""" Copyright (c) 2019-2020, the Decred developers See LICENSE for details """ class DecredError(Exception): pass
""" Copyright (c) 2019-2020, the Decred developers See LICENSE for details """ class Decrederror(Exception): pass
# The usual way numbers = [1, 2, 3, 4, 5, 6] new_numbers = [] for f in numbers: new_num = f + 1 new_numbers.append(new_num) print(new_numbers) # 6 lines!! # With list comperhension numbers = [1, 2, 3, 4, 5, 6] new_numbers = [n + 1 for n in numbers] print(new_numbers) # 3 lines!! # Using list comperhension wit...
numbers = [1, 2, 3, 4, 5, 6] new_numbers = [] for f in numbers: new_num = f + 1 new_numbers.append(new_num) print(new_numbers) numbers = [1, 2, 3, 4, 5, 6] new_numbers = [n + 1 for n in numbers] print(new_numbers) range_list = [item * 2 for item in range(1, 5)] names = ['Alex', 'Beth', 'Dave', 'Carolinnie', 'da...
""" Given a list, rotate the list to the right by k places, where k is non-negative. Example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class So...
""" Given a list, rotate the list to the right by k places, where k is non-negative. Example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. """ class Solution(object): def rotate_right(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode ...
def sum_numbers(num1, num2): return num1 + num2 def multiply_numbers(num1, num2): return num1 * num2 def func_executor(*args): results = [] for arg in args: func, nums = arg results.append(func(*nums)) return results print(func_executor((sum_numbers, (1, 2)), (multiply_number...
def sum_numbers(num1, num2): return num1 + num2 def multiply_numbers(num1, num2): return num1 * num2 def func_executor(*args): results = [] for arg in args: (func, nums) = arg results.append(func(*nums)) return results print(func_executor((sum_numbers, (1, 2)), (multiply_numbers, (...
# -*- coding: utf-8 -*- ############################################################################# # Copyright Vlad Popovici <popovici@bioxlab.org> # # Licensed under the MIT License. See LICENSE file in root folder. ############################################################################# __author__ = "Vlad P...
__author__ = 'Vlad Popovici <popovici@bioxlab.org>' __version__ = 0.1 class Error(Exception): """Basic error exception for QPATH. Args: msg (str): Human-readable string describing the exception. code (:obj:`int`, optional): Error code. Attributes: msg (str): Human-readable string ...
class Solution: def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]: if not mat: return [] m = len(mat) n = len(mat[0]) get = lambda i, j: mat[i][j] if 0 <= i < m and 0 <= j < n else 0 row = lambda i, j: sum([get(i, y) for y in range(j - K, j + K + 1)]...
class Solution: def matrix_block_sum(self, mat: List[List[int]], K: int) -> List[List[int]]: if not mat: return [] m = len(mat) n = len(mat[0]) get = lambda i, j: mat[i][j] if 0 <= i < m and 0 <= j < n else 0 row = lambda i, j: sum([get(i, y) for y in range(j - K...
'''Starlark rule for packaging Python 3 Google Cloud Functions.''' SRC_ZIP_EXTENSION = 'zip' SRC_PY_EXTENSION = 'py' MEMORY_VALUES = [ 128, 256, 512, 1024, 2048, 4096, ] MAX_TIMEOUT = 540 DEPLOY_SCRIPT_TEMPLATE = '''#!/usr/bin/env fish set gcf_archive (status --current-filename | sed 's/\.fish$/\.zip/' | xargs real...
"""Starlark rule for packaging Python 3 Google Cloud Functions.""" src_zip_extension = 'zip' src_py_extension = 'py' memory_values = [128, 256, 512, 1024, 2048, 4096] max_timeout = 540 deploy_script_template = "#!/usr/bin/env fish\nset gcf_archive (status --current-filename | sed 's/\\.fish$/\\.zip/' | xargs realpath)\...
#!/usr/bin/python3 #Every instance of this class, represents a single word found in a message. class Word: def __init__(self, word): #The word itself. self.word = word #The number of times the word was found in a collection of ham messages. self.inHam = 0 #The number of ...
class Word: def __init__(self, word): self.word = word self.inHam = 0 self.inSpam = 0 self.hamProbability = 0 self.spamProbability = 0 def compute_ham_probability(self, number_of_keywords, my_sum): self.hamProbability = float(1 + self.inHam) / float(number_of_ke...
URL_LIST_ARTICLES = "../../../data/nytimes_news_articles.txt" URL_BASE_ARTICLE = "../../../data/articles/nytimes" URL_SPLIT_WORDS = "../../../data/split_words.json" URL_SORT = "../../../data/sort.json" URL_LIST_DICT = "../../../data/list_dict.json" URL_LIST_DOCID = "../../../data/list_doc_id.json" N_ARTICLE = 1000
url_list_articles = '../../../data/nytimes_news_articles.txt' url_base_article = '../../../data/articles/nytimes' url_split_words = '../../../data/split_words.json' url_sort = '../../../data/sort.json' url_list_dict = '../../../data/list_dict.json' url_list_docid = '../../../data/list_doc_id.json' n_article = 1000
# 914000220 if not "cmd=o" in sm.getQRValue(21002): sm.showFieldEffect("aran/tutorialGuide3") sm.systemMessage("You can use a Command Attack by pressing both the arrow key and the attack key after a Consecutive Attack.") sm.addQRValue(21002, "cmd=o")
if not 'cmd=o' in sm.getQRValue(21002): sm.showFieldEffect('aran/tutorialGuide3') sm.systemMessage('You can use a Command Attack by pressing both the arrow key and the attack key after a Consecutive Attack.') sm.addQRValue(21002, 'cmd=o')
class Curry: def __init__(self, f, params=[], length=None): self.f = f self.len = f.__code__.co_argcount if length is None else length self.params = params def __call__(self, *a): p = [*self.params, *a] return self.f(*p) if len(p) >= self.len else Curry(self.f, p, self....
class Curry: def __init__(self, f, params=[], length=None): self.f = f self.len = f.__code__.co_argcount if length is None else length self.params = params def __call__(self, *a): p = [*self.params, *a] return self.f(*p) if len(p) >= self.len else curry(self.f, p, self....
''' #basic data types a = int(input()) b = float(input()) c = "I'm a boy" print(c) #casting------converting one datatype to another type a = 1.22222 print(int(a)) #flowchartXXXX----conditionals----if/else x = 'Ronaldo is better than Messi' try: print('Ronaldo' in s) except: print('sorry--not execute') ''...
""" #basic data types a = int(input()) b = float(input()) c = "I'm a boy" print(c) #casting------converting one datatype to another type a = 1.22222 print(int(a)) #flowchartXXXX----conditionals----if/else x = 'Ronaldo is better than Messi' try: print('Ronaldo' in s) except: print('sorry--not execute') ""...
class SubsystemA(object): def operation_a1(self): print("Operation a1") def operation_a2(self): print("Operation a2") class SubsystemB(object): def operation_b1(self): print("Operation b1") def operation_b2(self): print("Operation b2") class SubsystemC(object): de...
class Subsystema(object): def operation_a1(self): print('Operation a1') def operation_a2(self): print('Operation a2') class Subsystemb(object): def operation_b1(self): print('Operation b1') def operation_b2(self): print('Operation b2') class Subsystemc(object): ...
# Copyright 2004-2009 Joe Wreschnig, Michael Urman, Steven Robertson # 2011,2013 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation def decode(s, charset="utf-8...
def decode(s, charset='utf-8'): """Decode a string; if an error occurs, replace characters and append a note to the string.""" try: return s.decode(charset) except UnicodeError: return s.decode(charset, 'replace') + ' ' + _('[Invalid Encoding]') def encode(s, charset='utf-8'): """En...
class Cashier: def __init__(self, n, discount, products, prices): self.n = n self.now = n self.dc = discount self.pds = products self.pcs = prices def getBill(self, product, amount): money = 0 for i in range(len(product)): money += self.pcs[s...
class Cashier: def __init__(self, n, discount, products, prices): self.n = n self.now = n self.dc = discount self.pds = products self.pcs = prices def get_bill(self, product, amount): money = 0 for i in range(len(product)): money += self.pcs[...