content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: def longestDecomposition(self, text: str) -> int: ans = 0 l,r = 0,len(text)-1 while l <= r: i = 0 while text[l:l+i+1] != text[r-i:r+1]: i += 1 ans += 1 if i == r-l else 2 l,...
class Solution: def longest_decomposition(self, text: str) -> int: ans = 0 (l, r) = (0, len(text) - 1) while l <= r: i = 0 while text[l:l + i + 1] != text[r - i:r + 1]: i += 1 ans += 1 if i == r - l else 2 (l, r) = (l + i + 1, ...
class Node: def __init__(self,data): self.left = None self.data = data self.right = None # Search Node present or not in Node def search(self,target_data): if self.data == target_data: print(f"{target_data} is found") return self ...
class Node: def __init__(self, data): self.left = None self.data = data self.right = None def search(self, target_data): if self.data == target_data: print(f'{target_data} is found') return self elif self.left != None and self.data > target_data:...
class Logger: def __init__(self, fname): self.fname = fname if self.fname is None: print('Will not log') else: with open(self.fname, 'w') as f: f.write('Starting ====\n') def __call__(self, s): if self.fname is not None: with o...
class Logger: def __init__(self, fname): self.fname = fname if self.fname is None: print('Will not log') else: with open(self.fname, 'w') as f: f.write('Starting ====\n') def __call__(self, s): if self.fname is not None: with ...
# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project au...
{'includes': ['webrtc/build/common.gypi'], 'variables': {'webrtc_all_dependencies': ['webrtc/common_audio/common_audio.gyp:*', 'webrtc/common_video/common_video.gyp:*', 'webrtc/modules/modules.gyp:*', 'webrtc/system_wrappers/source/system_wrappers.gyp:*', 'webrtc/video_engine/video_engine.gyp:*', 'webrtc/voice_engine/v...
class SMS: endpoint = "http://center.fibosms.com/service.asmx" clientNo = "" clientPass = "" def __init__(self, clientNo, clientPass): self.clientNo = clientNo self.clientPass = clientPass def send_sms(self, message): return False
class Sms: endpoint = 'http://center.fibosms.com/service.asmx' client_no = '' client_pass = '' def __init__(self, clientNo, clientPass): self.clientNo = clientNo self.clientPass = clientPass def send_sms(self, message): return False
# reverse a given linkedlist class Node: # Constructor to initialize the node object def __init__(self, data=0, next=None): self.data = data self.next = next class LinkedList: # Constructor to initialize head def __init__(self) -> None: self.head = None # Function to inser...
class Node: def __init__(self, data=0, next=None): self.data = data self.next = next class Linkedlist: def __init__(self) -> None: self.head = None def push(self, data): node = node(data) node.next = self.head self.head = node def print_list(self): ...
#Functions and scope #Lexical scoping (sometimes known as static scoping ) #is a convention used with many programming languages that sets the scope #(range of functionality) of a variable so that it may only be called #from within the block of code in which it is defined. #Scopes can be nested inside another. #Thi...
name = 'Bryan Cairns' def test1(): print(f'My name is {name}') test1() x = 10 def test2(): x = 50 print(f'Function scope {x}') test2() print(f'Global scope {x}') x = 15 print(f'Global x: {x}') def test3(): x = 0 print(f'Function x: {x}') for i in range(3): x += 1 y = x * i ...
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
class Application: def __init__(self, name=None, date_created=None, date_updated=None, description=None, versions=[], templates=[]): self.name = name self.date_created = date_created self.date_updated = date_updated self.description = description self.versions = versions ...
def file_gen(): filename = "run_all_cifar.sh" f = open(filename,'w') f.write("mkdir Cifar_log\n") f.write("mkdir Cifar_log/intbit\n") f.write("mkdir Cifar_log/fracbit\n") for i in range(2,17): fracbits = i; intbits = 64 - i; f.write("cp ./include/minsoo/fracbit/fixed" + ...
def file_gen(): filename = 'run_all_cifar.sh' f = open(filename, 'w') f.write('mkdir Cifar_log\n') f.write('mkdir Cifar_log/intbit\n') f.write('mkdir Cifar_log/fracbit\n') for i in range(2, 17): fracbits = i intbits = 64 - i f.write('cp ./include/minsoo/fracbit/fixed' + s...
# Scrapy settings for doonia project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/topics/settings.html # BOT_NAME = 'doonia' SPIDER_MODULES = ['doonia.spiders'] NEWSPIDER_MODULE = 'doonia.spiders' # Cra...
bot_name = 'doonia' spider_modules = ['doonia.spiders'] newspider_module = 'doonia.spiders' log_file = 'log/scrapy.log' log_level = 'ERROR' item_pipelines = ['doonia.pipelines.MongoDBPipeline'] mongodb_server = 'localhost' mongodb_port = 27017 mongodb_db = 'doonia' mongodb_collect_production = 'production' mongodb_coll...
def make_exe(): dist = default_python_distribution() policy = dist.make_python_packaging_policy() policy.resources_location_fallback = "filesystem-relative:pyxel_lib" python_config = dist.make_python_interpreter_config() python_config.module_search_paths = ["$ORIGIN/pyxel_lib"] python_config.r...
def make_exe(): dist = default_python_distribution() policy = dist.make_python_packaging_policy() policy.resources_location_fallback = 'filesystem-relative:pyxel_lib' python_config = dist.make_python_interpreter_config() python_config.module_search_paths = ['$ORIGIN/pyxel_lib'] python_config.run...
class Contact: def __init__(self, firstname, middlename, lastname, nickname, homephone, mobilephone ): self.firstname = firstname self.middlename = middlename self.lastname = lastname self.nickname = nickname self.homephone = homephone self.mobilephone = mobilephone ...
class Contact: def __init__(self, firstname, middlename, lastname, nickname, homephone, mobilephone): self.firstname = firstname self.middlename = middlename self.lastname = lastname self.nickname = nickname self.homephone = homephone self.mobilephone = mobilephone
class Solution: def isHappy(self, n: int) -> bool: testSet = set() while n not in testSet: testSet.add(n) n = self.squreSum(n) return n == 1 def squreSum(self, num: int) -> int: result = 0 while num: remainder...
class Solution: def is_happy(self, n: int) -> bool: test_set = set() while n not in testSet: testSet.add(n) n = self.squreSum(n) return n == 1 def squre_sum(self, num: int) -> int: result = 0 while num: remainder = num % 10 ...
# The root configuration of energy internet # default_operation_mode=\ { "Operation_serve_mode" : 1, # The EMS is a server or a client, 1=the ems is a server,0=the ems is a client "Grid_connnected" : 1,#The system is connected to the main grid ? "Micro_grid_connected": 0, #The MG is conncte...
default_operation_mode = {'Operation_serve_mode': 1, 'Grid_connnected': 1, 'Micro_grid_connected': 0}
#encoding:utf-8 subreddit = 'subgenius' t_channel = '@subgeniuschurch' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'subgenius' t_channel = '@subgeniuschurch' def send_post(submission, r2t): return r2t.send_simple(submission)
height = int(input()) for i in range(1,height): for j in range(height-i,1,-1): print(end=" ") for j in range(height-i-1,height-1): print(j,end=" ") print() for i in range(1,height): for j in range(1,i+1): print(end=" ") for j in range(height-i,1,-1): print(he...
height = int(input()) for i in range(1, height): for j in range(height - i, 1, -1): print(end=' ') for j in range(height - i - 1, height - 1): print(j, end=' ') print() for i in range(1, height): for j in range(1, i + 1): print(end=' ') for j in range(height - i, 1, -1): ...
class ConfigValue: __value: object def __init__(self, value: object): self.__value = value def isNull(self) -> bool: return self.__value is None def getValue(self) -> object: return self.__value def getValueAsStr(self) -> str: return str(self.__valu...
class Configvalue: __value: object def __init__(self, value: object): self.__value = value def is_null(self) -> bool: return self.__value is None def get_value(self) -> object: return self.__value def get_value_as_str(self) -> str: return str(self.__value) de...
# -*- coding: utf-8 -*- class RPCProtocolError(Exception): pass class MethodNotFoundError(Exception): pass class RPCError(Exception): remote_exception_module = None remote_exception_type = None
class Rpcprotocolerror(Exception): pass class Methodnotfounderror(Exception): pass class Rpcerror(Exception): remote_exception_module = None remote_exception_type = None
def test(): print("hello, new file!") if __name__ == '__main__': test()
def test(): print('hello, new file!') if __name__ == '__main__': test()
def dump_raw_pcode(func, file): func_body = func.getBody() listing = currentProgram.getListing() opiter = listing.getInstructions(func_body, True) while opiter.hasNext(): op = opiter.next() raw_pcode = op.getPcode() file.write("{}\n".format(op)) for entry in raw_pcode: ...
def dump_raw_pcode(func, file): func_body = func.getBody() listing = currentProgram.getListing() opiter = listing.getInstructions(func_body, True) while opiter.hasNext(): op = opiter.next() raw_pcode = op.getPcode() file.write('{}\n'.format(op)) for entry in raw_pcode: ...
class Localisation: en_US = "en_US" ro_RO = "ro_RO" default = en_US
class Localisation: en_us = 'en_US' ro_ro = 'ro_RO' default = en_US
class Solution: def solve(self, nums): n = len(nums) if not n: return n max_left = [-float('inf')]*n max_right = [-float('inf')]*n max_left[0] = nums[0] max_right[-1] = nums[-1] for i in range(1,n): max_left[i] = max(nums[i],...
class Solution: def solve(self, nums): n = len(nums) if not n: return n max_left = [-float('inf')] * n max_right = [-float('inf')] * n max_left[0] = nums[0] max_right[-1] = nums[-1] for i in range(1, n): max_left[i] = max(nums[i], max_...
''' abcdefg1234567 -> a1b2c3d4e5f6g7 KEY: even odd manipulation ''' def shuffle(lst, left, right): if right - left <= 1: return length = right - left + 1 mid = left + length // 2 # cal mid for left and right left_mid = left + length // 4 right_mid = left + length * 3 // 4 revers...
""" abcdefg1234567 -> a1b2c3d4e5f6g7 KEY: even odd manipulation """ def shuffle(lst, left, right): if right - left <= 1: return length = right - left + 1 mid = left + length // 2 left_mid = left + length // 4 right_mid = left + length * 3 // 4 reverse(lst, left_mid, mid - 1) rever...
class Student: def __init__(self,name,ID): self.name = name self.ID = ID def Details(self): return "Name: "+self.name+"\n"+"ID: "+self.ID+"\n" #Write your code here class CSEStudent(Student): def __init__(self, name, ID,sem): super().__init__(name, ID) self.sem = s...
class Student: def __init__(self, name, ID): self.name = name self.ID = ID def details(self): return 'Name: ' + self.name + '\n' + 'ID: ' + self.ID + '\n' class Csestudent(Student): def __init__(self, name, ID, sem): super().__init__(name, ID) self.sem = sem ...
res = mySession.sql('SELECT name, age FROM users').execute() row = res.fetch_one() while row: print('Name: %s\n' % row[0]) print(' Age: %s\n' % row.age) row = res.fetch_one()
res = mySession.sql('SELECT name, age FROM users').execute() row = res.fetch_one() while row: print('Name: %s\n' % row[0]) print(' Age: %s\n' % row.age) row = res.fetch_one()
def get_valid_month(): ''' () -> int Return a valid month number input by user after (possibly repeated) prompting. A valid month number is an int between 1 and 12 inclusive. ''' prompt = 'Enter a valid month number: ' error_message = 'Invalid input! Read the instructions and try again!' ...
def get_valid_month(): """ () -> int Return a valid month number input by user after (possibly repeated) prompting. A valid month number is an int between 1 and 12 inclusive. """ prompt = 'Enter a valid month number: ' error_message = 'Invalid input! Read the instructions and try again!' mo...
# -*- coding: utf-8 -*- # https://www.linkedin.com/pulse/afternoon-debugging-e-commerce-image-processing-nikhil-rasiwasia def read_transparent_png(filename): image_4channel = cv2.imread(filename, cv2.IMREAD_UNCHANGED) alpha_channel = image_4channel[:,:,3] rgb_channels = image_4channel[:,:,:3] # Whi...
def read_transparent_png(filename): image_4channel = cv2.imread(filename, cv2.IMREAD_UNCHANGED) alpha_channel = image_4channel[:, :, 3] rgb_channels = image_4channel[:, :, :3] white_background_image = np.ones_like(rgb_channels, dtype=np.uint8) * 255 alpha_factor = alpha_channel[:, :, np.newaxis].ast...
#!/usr/bin/env python f_path = "./" f_name_topics = "record_topics.txt" # Read topic_list file #------------------------# topic_list_original = [] with open( (f_path+f_name_topics),'r') as _f: for _s in _f: # Remove the space and '\n' _s1 = _s.rstrip().lstrip() # Deal with coments ...
f_path = './' f_name_topics = 'record_topics.txt' topic_list_original = [] with open(f_path + f_name_topics, 'r') as _f: for _s in _f: _s1 = _s.rstrip().lstrip() _idx_comment = _s1.find('#') if _idx_comment >= 0: _s1 = _s1[:_idx_comment].rstrip() if len(_s1) > 0: ...
def ion_mq_stats(ion_name): ''' Define dictionary of ion names and mass, charge values List of ions taken from Gruesbeck thesis 2013 Inputs: ion_name - string name of ion ''' ion_q={ 'H+':1,'H+_D':1, 'He+':1, 'He2+':2, 'C4+':4, 'C5+':5, 'C6+':6, 'O+...
def ion_mq_stats(ion_name): """ Define dictionary of ion names and mass, charge values List of ions taken from Gruesbeck thesis 2013 Inputs: ion_name - string name of ion """ ion_q = {'H+': 1, 'H+_D': 1, 'He+': 1, 'He2+': 2, 'C4+': 4, 'C5+': 5, 'C6+': 6, 'O+': 1, 'O6+': 6, 'O7+...
# Order of corners and edges URF, UFL, ULB, UBR, DFR, DLF, DBL, DRB = range(8) UR, UF, UL, UB, DR, DF, DL, DB, FR, FL, BL, BR = range(12) FACE_MOVE = ('U', 'R', 'F', 'D', 'L', 'B') MOVES = ('U1', 'U2', 'U3', 'R1', 'R2', 'R3', 'F1', 'F2', 'F3', 'D1', 'D2', 'D3', 'L1', 'L2', 'L3', 'B1', 'B2', 'B3') G1 = ('U1', 'U2',...
(urf, ufl, ulb, ubr, dfr, dlf, dbl, drb) = range(8) (ur, uf, ul, ub, dr, df, dl, db, fr, fl, bl, br) = range(12) face_move = ('U', 'R', 'F', 'D', 'L', 'B') moves = ('U1', 'U2', 'U3', 'R1', 'R2', 'R3', 'F1', 'F2', 'F3', 'D1', 'D2', 'D3', 'L1', 'L2', 'L3', 'B1', 'B2', 'B3') g1 = ('U1', 'U2', 'U3', 'D1', 'D2', 'D3', 'R2',...
class Solution: def winnerSquareGame(self, n: int) -> bool: dp = [0] * (n+1) for i in range(1, n+1): j = 1 while j * j <= i and not dp[i]: dp[i] = dp[i-j*j]^1 j += 1 return dp[n]
class Solution: def winner_square_game(self, n: int) -> bool: dp = [0] * (n + 1) for i in range(1, n + 1): j = 1 while j * j <= i and (not dp[i]): dp[i] = dp[i - j * j] ^ 1 j += 1 return dp[n]
''' Question: Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output sh...
""" Question: Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output sh...
def tocall(arg1, arg2): print(str(arg1)) print(str(arg2)) return "VALUE TO RETURN"
def tocall(arg1, arg2): print(str(arg1)) print(str(arg2)) return 'VALUE TO RETURN'
''' Copyright (c) 2011-2014, Agora Games, LLC All rights reserved. https://github.com/agoragames/haigha/blob/master/LICENSE.txt ''' __version__ = "0.7.1"
""" Copyright (c) 2011-2014, Agora Games, LLC All rights reserved. https://github.com/agoragames/haigha/blob/master/LICENSE.txt """ __version__ = '0.7.1'
''' Exercise 8 from http://www.practicepython.org/ Make a two-player Rock-Paper-Scissors game. ''' class Player: def __init__(self, player_number): self.player_number = player_number self.player_won = False def get_player_input(self): allowed_inputs = ['rock', 'paper', 'scissors'] ...
""" Exercise 8 from http://www.practicepython.org/ Make a two-player Rock-Paper-Scissors game. """ class Player: def __init__(self, player_number): self.player_number = player_number self.player_won = False def get_player_input(self): allowed_inputs = ['rock', 'paper', 'scissors'] ...
TUNABLE_WEIGHT_TITLE = 3 TUNABLE_WEIGHT_CONTENT = 1 TUNABLE_WEIGHT_ABSTRACT = 2 TUNABLE_WEIGHT_DATE = 0.7 TUNABLE_WEIGHT_PAGE = 0.9 ADDITIVE_CONSTANT_DATE_BOOST = .5
tunable_weight_title = 3 tunable_weight_content = 1 tunable_weight_abstract = 2 tunable_weight_date = 0.7 tunable_weight_page = 0.9 additive_constant_date_boost = 0.5
def check(id): id = id.strip() if (id.isdigit() is False): return False if (len(id) != 10): return False type = id[0:1] if (type != '2' and type != '1'): return False sum = 0 for i in range(0, 10): if (i % 2 == 0): ZFOdd = str(int(id[i]) * 2).zfill...
def check(id): id = id.strip() if id.isdigit() is False: return False if len(id) != 10: return False type = id[0:1] if type != '2' and type != '1': return False sum = 0 for i in range(0, 10): if i % 2 == 0: zf_odd = str(int(id[i]) * 2).zfill(2) ...
def process(filename, move_fn): location = { 'position': 0, 'depth': 0, 'aim': 0 } with open(filename) as file: for line in file: location = move_fn(*parse(line), location) return location['position'] * location['depth'] def parse(command): return comma...
def process(filename, move_fn): location = {'position': 0, 'depth': 0, 'aim': 0} with open(filename) as file: for line in file: location = move_fn(*parse(line), location) return location['position'] * location['depth'] def parse(command): return (command.strip().split()[0], int(comm...
#!/usr/bin/env python # Helper functions and constants for patterns.py delimiters = '[\.\s\-\+_\/(),]' langs = [('rus(?:sian)?', 'Russian'), ('(?:True)?fre?(?:nch)?', 'French'), ('(?:nu)?ita(?:liano?)?', 'Italian'), ('castellano|spa(?:nish)?|esp?', 'Spanish'), ('swedish', 'Swedish...
delimiters = '[\\.\\s\\-\\+_\\/(),]' langs = [('rus(?:sian)?', 'Russian'), ('(?:True)?fre?(?:nch)?', 'French'), ('(?:nu)?ita(?:liano?)?', 'Italian'), ('castellano|spa(?:nish)?|esp?', 'Spanish'), ('swedish', 'Swedish'), ('dk|dan(?:ish)?', 'Danish'), ('ger(?:man)?|deu(?:tsch)?', 'German'), ('nordic', 'Nordic'), ('exyu', ...
phone_book = dict() data = input() while not data.isnumeric(): name, phone_number = data.split("-") phone_book[name] = phone_number data = input() for i in range(int(data)): name = input() if name in phone_book.keys(): print(f"{name} -> {phone_book[name]}") else: print(f"Conta...
phone_book = dict() data = input() while not data.isnumeric(): (name, phone_number) = data.split('-') phone_book[name] = phone_number data = input() for i in range(int(data)): name = input() if name in phone_book.keys(): print(f'{name} -> {phone_book[name]}') else: print(f'Contac...
a=input("chi nazarete?:") b = a//50 print (b,"is the number of 50s") c = a%50 d= c//20 print(d,"is the number of 20s") e=c%20 f = e//10 print (f,"is the number of 10s") f =e//5 print (f,"is the number of 5s") g = e%5 h =g//2 print(h,"is the number of 2s") i=g%2 j=i//1 print(j,"is the number of 1s") input("press <enter...
a = input('chi nazarete?:') b = a // 50 print(b, 'is the number of 50s') c = a % 50 d = c // 20 print(d, 'is the number of 20s') e = c % 20 f = e // 10 print(f, 'is the number of 10s') f = e // 5 print(f, 'is the number of 5s') g = e % 5 h = g // 2 print(h, 'is the number of 2s') i = g % 2 j = i // 1 print(j, 'is the n...
print('-=-=-=-= DESAFIO 77 -=-=-=-=') print() palavras = ('computador', 'apple', 'smartphone', 'starbucks', 'nubank', 'dobra', 'lenovo', 'capinha', 'iphone', 'python', 'programar', 'universidade', 'quadro') for item in palavras: print(f'Na palavra {item.upper()} temos', end=' ') for le...
print('-=-=-=-= DESAFIO 77 -=-=-=-=') print() palavras = ('computador', 'apple', 'smartphone', 'starbucks', 'nubank', 'dobra', 'lenovo', 'capinha', 'iphone', 'python', 'programar', 'universidade', 'quadro') for item in palavras: print(f'Na palavra {item.upper()} temos', end=' ') for letra in item: if le...
# AST only tests pass break continue raise raise NameError('String') raise RuntimeError from exc assert len(marks) != 0,"List is empty." assert x == "String" x = 1 x, y = x() x = y = 1 x, y = 1, 2 x[i] = (1, 2) x, y, z = t (x, y, z) = t x, = t (x,) = t x += 1 x: i64 y: i32 = 1 del x del () del (x, y) del (x, y,)...
pass break continue raise raise name_error('String') raise RuntimeError from exc assert len(marks) != 0, 'List is empty.' assert x == 'String' x = 1 (x, y) = x() x = y = 1 (x, y) = (1, 2) x[i] = (1, 2) (x, y, z) = t (x, y, z) = t (x,) = t (x,) = t x += 1 x: i64 y: i32 = 1 del x del () del (x, y) del (x, y) del x, y del...
{ "targets": [ { "target_name": "vertcoinhash", "sources": ["Lyra2RE.c", "Lyra2.c", "Sponge.c", "sha3/blake.c", "sha3/bmw.c", "sha3/cubehash.c", "sha3/groestl.c", "sha3/keccak.c", "sha3/skein.c", "scryptn.c", ...
{'targets': [{'target_name': 'vertcoinhash', 'sources': ['Lyra2RE.c', 'Lyra2.c', 'Sponge.c', 'sha3/blake.c', 'sha3/bmw.c', 'sha3/cubehash.c', 'sha3/groestl.c', 'sha3/keccak.c', 'sha3/skein.c', 'scryptn.c', 'vertcoin-hash.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]}
def atbash(message): alfabeto = "abcdefghijklmnopqrstuvwxyz" cifrado = alfabeto.upper()[::-1] message = message.lower() result = "" for letra in message: if letra in alfabeto: result += cifrado[alfabeto.index(letra)] else: result += letra return result d...
def atbash(message): alfabeto = 'abcdefghijklmnopqrstuvwxyz' cifrado = alfabeto.upper()[::-1] message = message.lower() result = '' for letra in message: if letra in alfabeto: result += cifrado[alfabeto.index(letra)] else: result += letra return result de...
oldstr = input("Enter string ") if oldstr[-3:] == "ing": newstr = oldstr + "ly" print(newstr) elif oldstr[-2:] == "ly": print(oldstr) elif oldstr[-3:] != "ing": if oldstr[-1:] == "e": newstr = oldstr[:-1] + "ing" print(newstr) else: newstr = oldstr + "ing" print(newstr)
oldstr = input('Enter string ') if oldstr[-3:] == 'ing': newstr = oldstr + 'ly' print(newstr) elif oldstr[-2:] == 'ly': print(oldstr) elif oldstr[-3:] != 'ing': if oldstr[-1:] == 'e': newstr = oldstr[:-1] + 'ing' print(newstr) else: newstr = oldstr + 'ing' print(newst...
''' cpress - python bindings ------------------------------------------------------------------------------- Installation: python2 setup.py install Usage: Import module with: from cpress import * See self-explanatory file `examples/example.py` for more informations. -------------------------------------...
""" cpress - python bindings ------------------------------------------------------------------------------- Installation: python2 setup.py install Usage: Import module with: from cpress import * See self-explanatory file `examples/example.py` for more informations. -------------------------------------...
def rotate_list(head, n): if n == 0: return head # get list length and store the pointer to last element list_len = 0 cur = head while cur: list_len+=1 last = cur cur = cur.next n = n % list_len if n < 0: n = list_len + n print ("list is {} items long, last item is {} shift {}".form...
def rotate_list(head, n): if n == 0: return head list_len = 0 cur = head while cur: list_len += 1 last = cur cur = cur.next n = n % list_len if n < 0: n = list_len + n print('list is {} items long, last item is {} shift {}'.format(list_len, last.data, ...
def test_ok(): assert 1 == 1 def test_fail(): assert 1 != 1
def test_ok(): assert 1 == 1 def test_fail(): assert 1 != 1
tab = False name= True if tab!=name: print ('choclate') print('tabs')
tab = False name = True if tab != name: print('choclate') print('tabs')
input_lines = open('input.txt') good = 0 col1, col2, col3 = [], [], [] for line in input_lines: s1, s2, s3 = map(int, line.split()) col1.append(s1) col2.append(s2) col3.append(s3) if len(col1) == 3: for col in (col1, col2, col3): a, b, c = col[:3] del col[:3] ...
input_lines = open('input.txt') good = 0 (col1, col2, col3) = ([], [], []) for line in input_lines: (s1, s2, s3) = map(int, line.split()) col1.append(s1) col2.append(s2) col3.append(s3) if len(col1) == 3: for col in (col1, col2, col3): (a, b, c) = col[:3] del col[:3] ...
# -*- coding: utf-8 -*- def setup(spec): spec.plugins['tests.plugins.dummy_plugin']['foo'] = 42
def setup(spec): spec.plugins['tests.plugins.dummy_plugin']['foo'] = 42
phone = input("phone: ") digit_mapping = { "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", } output = "" for x in phone: output += digit_mapping.get(x, "!") print(output)
phone = input('phone: ') digit_mapping = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five'} output = '' for x in phone: output += digit_mapping.get(x, '!') print(output)
# # PySNMP MIB module HUAWEI-BRAS-VSM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-BRAS-VSM-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:43:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) ...
class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) count = [0] * (1 + n) for c in citations: count[min(c, n)] += 1 h = n num = count[n] while num < h: h -= 1 num += count[h] return h
class Solution: def h_index(self, citations: List[int]) -> int: n = len(citations) count = [0] * (1 + n) for c in citations: count[min(c, n)] += 1 h = n num = count[n] while num < h: h -= 1 num += count[h] return h
while(True): a,b = map(int,input().split()) if a == 0 and b == 0: break if a%b == 0: print("multiple") elif b%a == 0: print("factor") else: print("neither")
while True: (a, b) = map(int, input().split()) if a == 0 and b == 0: break if a % b == 0: print('multiple') elif b % a == 0: print('factor') else: print('neither')
def commandPeasant(peasant, coins): coin = peasant.findNearest(coins) if coin: hero.command(peasant, "move", coin.pos) friends = hero.findFriends() peasants = { "Aurum": friends[0], "Argentum":friends[1], "Cuprum":friends[2] } while True: items = hero.findItems() go...
def command_peasant(peasant, coins): coin = peasant.findNearest(coins) if coin: hero.command(peasant, 'move', coin.pos) friends = hero.findFriends() peasants = {'Aurum': friends[0], 'Argentum': friends[1], 'Cuprum': friends[2]} while True: items = hero.findItems() gold_coins = [] silver_coin...
soma = 0 cont = 0 for c in range(1, 500, 2): if c % 3 == 0: soma += c cont += 1 print(soma) print(cont)
soma = 0 cont = 0 for c in range(1, 500, 2): if c % 3 == 0: soma += c cont += 1 print(soma) print(cont)
def is_float(string: str): try: float(string) return True except (ValueError, TypeError): return False
def is_float(string: str): try: float(string) return True except (ValueError, TypeError): return False
# Function to demonstrate printing pattern triangle def triangle(n): # number of spaces k = n - 1 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=" ") # decrementing k after each loo...
def triangle(n): k = n - 1 for i in range(0, n): for j in range(0, k): print(end=' ') k = k - 1 for j in range(0, i + 1): print('* ', end='') print('\r') n = 5 triangle(n)
"Public API for docs helpers" load( "//lib/private:docs.bzl", _stardoc_with_diff_test = "stardoc_with_diff_test", _update_docs = "update_docs", ) stardoc_with_diff_test = _stardoc_with_diff_test update_docs = _update_docs
"""Public API for docs helpers""" load('//lib/private:docs.bzl', _stardoc_with_diff_test='stardoc_with_diff_test', _update_docs='update_docs') stardoc_with_diff_test = _stardoc_with_diff_test update_docs = _update_docs
class Solution: def check(self, nums: List[int]) -> bool: # Let's just do the simple method of getting the first min index and then checking compare = sorted(nums) for i in range(len(nums)): compareL = compare[i:] + compare[:i] compareR = compare[-i:] + compare[:-1] ...
class Solution: def check(self, nums: List[int]) -> bool: compare = sorted(nums) for i in range(len(nums)): compare_l = compare[i:] + compare[:i] compare_r = compare[-i:] + compare[:-1] if compareR == nums or compareL == nums: return True ...
msg = 'hello world' print(msg) def firstfunc(x, y): return x*y
msg = 'hello world' print(msg) def firstfunc(x, y): return x * y
class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g = sorted(g) s = sorted(s) content = 0 while s and g: if s[-1] >= g[-1]: s.pop() content += 1 g.pop() return content
class Solution: def find_content_children(self, g: List[int], s: List[int]) -> int: g = sorted(g) s = sorted(s) content = 0 while s and g: if s[-1] >= g[-1]: s.pop() content += 1 g.pop() return content
class Solution: def sumEvenAfterQueries(self, A: 'List[int]', queries: 'List[List[int]]') -> 'List[int]': evens = sum(num for num in A if num % 2 == 0) ans = [] for val, idx in queries: if A[idx] % 2 == 0: A[idx] += val if val % 2 == 0: ...
class Solution: def sum_even_after_queries(self, A: 'List[int]', queries: 'List[List[int]]') -> 'List[int]': evens = sum((num for num in A if num % 2 == 0)) ans = [] for (val, idx) in queries: if A[idx] % 2 == 0: A[idx] += val if val % 2 == 0: ...
def speak(name): return ''
def speak(name): return ''
def collide(obj1, obj2): # obj1 and obj2 coordinates refer to the middle point of the mask, so we have to compute # the coordinates of the upper-left corner of the sprite x_offset = (obj2.x - obj2.get_width()/2) - (obj1.x - obj1.get_width()/2) y_offset = (obj2.y - obj2.get_height()/2) - (obj1.y - obj1.g...
def collide(obj1, obj2): x_offset = obj2.x - obj2.get_width() / 2 - (obj1.x - obj1.get_width() / 2) y_offset = obj2.y - obj2.get_height() / 2 - (obj1.y - obj1.get_height() / 2) return obj1.mask.overlap(obj2.mask, (x_offset, y_offset)) != None
class ListNode: def __init__(self, x): self.val = x self.next = None def trasver(root): while root is not None: print(root.val) root = root.next class Palindrome: def isPalindrome(self, pHead): if pHead is None or pHead.next is None: return True ...
class Listnode: def __init__(self, x): self.val = x self.next = None def trasver(root): while root is not None: print(root.val) root = root.next class Palindrome: def is_palindrome(self, pHead): if pHead is None or pHead.next is None: return True ...
te=raw_input() i=0 while te[0]!='x': i=i+1 if i<=10: print('"g%02d": ["%s","huiku"],' % (i,te)) else: if te[0]=='p': start=te[1:].split(':')[0] end=te[1:].split(':')[1] print('"c%02d": ["%s","prec","%s"],' %(i,start,end)) else: print('"c%02d": ["%s","sdf"],' %(i,te)) te=raw_input()
te = raw_input() i = 0 while te[0] != 'x': i = i + 1 if i <= 10: print('"g%02d": ["%s","huiku"],' % (i, te)) elif te[0] == 'p': start = te[1:].split(':')[0] end = te[1:].split(':')[1] print('"c%02d": ["%s","prec","%s"],' % (i, start, end)) else: print('"c%02d": ["...
description = 'Guide field Helmholtz coils around sample position' group = 'optional' tango_base = 'tango://miractrl.mira.frm2:10000/mira/' devices = dict( dct5 = device('nicos.devices.entangle.PowerSupply', description = 'current in first channel of supply', tangodevice = tango_base + 'tticoil/ou...
description = 'Guide field Helmholtz coils around sample position' group = 'optional' tango_base = 'tango://miractrl.mira.frm2:10000/mira/' devices = dict(dct5=device('nicos.devices.entangle.PowerSupply', description='current in first channel of supply', tangodevice=tango_base + 'tticoil/out1', timeout=2.5, precision=0...
# decorator def greetings(name): print('Hello,', name) def morning(func): def wrapper(arg): func(arg) print('Good morning,', arg) return wrapper @morning def greetings(name): print('Hello,', name) greetings('Susie')
def greetings(name): print('Hello,', name) def morning(func): def wrapper(arg): func(arg) print('Good morning,', arg) return wrapper @morning def greetings(name): print('Hello,', name) greetings('Susie')
class InterpreterError(Exception): pass class ScannerError(Exception): pass
class Interpretererror(Exception): pass class Scannererror(Exception): pass
class Solution: # @param matrix, a list of lists of integers # @return a list of lists of integers def rotate(self, matrix): n = len(matrix) # Layers for i in range(n / 2): # Each layer's index range start = i end = n - 1 - i for j in r...
class Solution: def rotate(self, matrix): n = len(matrix) for i in range(n / 2): start = i end = n - 1 - i for j in range(start, end): offset = j - start top = matrix[start][j] matrix[start][j] = matrix[end - offset...
# # PySNMP MIB module RADLAN-CLI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-CLI-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:45:49 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, constraints_intersection, value_size_constraint, single_value_constraint) ...
# https://leetcode.com/problems/find-the-shortest-superstring class Solution(object): def shortestSuperstring(self, A): N = len(A) # Populate graph graph = [[0 for _ in range(N)] for __ in range(N)] for i, x in enumerate(A): for j, y in enumerate(A): if...
class Solution(object): def shortest_superstring(self, A): n = len(A) graph = [[0 for _ in range(N)] for __ in range(N)] for (i, x) in enumerate(A): for (j, y) in enumerate(A): if i == j: continue for val in range(min(len(x), l...
GITHUB_ACTIONS_USERNAME = 'github_actions' LAMBDA_PROXY_AUTH_USERNAME = 'schedule' EMAIL_AUTOMATION_SENDER = 'andrey@seamlesscloud.io' DEFAULT_ENTRYPOINT = 'function.py' DEFAULT_REQUIREMENTS = 'requirements.txt' DEFAULT_CRON_SCHEDULE = "0 0 * * *" ARCHIVE_EXTENSION = "tar.gz"
github_actions_username = 'github_actions' lambda_proxy_auth_username = 'schedule' email_automation_sender = 'andrey@seamlesscloud.io' default_entrypoint = 'function.py' default_requirements = 'requirements.txt' default_cron_schedule = '0 0 * * *' archive_extension = 'tar.gz'
# variable spam = 1 text = "# This is not a comment because it's inside quotes." # number num = 8 / 5 # division always return a floating point number num1 = 8 // 5 # floor divison discards the fractional part num2 = 5 ** 2 # 5 squared # string word = 'does\'t' word1 = "does't" s = 'First line.\nSecond line.' # \n ...
spam = 1 text = "# This is not a comment because it's inside quotes." num = 8 / 5 num1 = 8 // 5 num2 = 5 ** 2 word = "does't" word1 = "does't" s = 'First line.\nSecond line.' print(s) s1 = 3 * 'un' + 'ium' text = 'Put several strings within parentheses to have them joined together.' print(text) s = 'supercalifragilisti...
class AuthError(Exception): def __init__( self, message=None): super(AuthError, self).__init__(message) self._message = message def __str__(self): return self._message class KeyError(AuthError): pass
class Autherror(Exception): def __init__(self, message=None): super(AuthError, self).__init__(message) self._message = message def __str__(self): return self._message class Keyerror(AuthError): pass
def func(idx: int) -> int: return "aa" print("starting") print(func(1)) print(func("x")) aaa = 4 if 2==1 else 3 print (aaa)
def func(idx: int) -> int: return 'aa' print('starting') print(func(1)) print(func('x')) aaa = 4 if 2 == 1 else 3 print(aaa)
# This problem was recently asked by Microsoft: # Given a node in a connected directional graph, create a copy of it. class Node: def __init__(self, value, adj=None): self.value = value self.adj = adj # Variable to help print graph self._print_visited = set() if self.adj ...
class Node: def __init__(self, value, adj=None): self.value = value self.adj = adj self._print_visited = set() if self.adj is None: self.adj = [] def __repr__(self): if self in self._print_visited: return '' else: self._print_...
n= int(input("Enter the integer number: ")) sum= 0 while (n>0): r= n%10 sum= (sum * 10) +r n=n// 10 print("The reverse number is : {}".format(sum))
n = int(input('Enter the integer number: ')) sum = 0 while n > 0: r = n % 10 sum = sum * 10 + r n = n // 10 print('The reverse number is : {}'.format(sum))
def prime_numbers(max): start = 2 end = max + 1 n = [True for i in range(start, end)] for a in range(start, end): if n[a - start]: for b in range(a + 1, end): # print(a, b, n[b - start], b % a) if b % a == 0: n[b - start]...
def prime_numbers(max): start = 2 end = max + 1 n = [True for i in range(start, end)] for a in range(start, end): if n[a - start]: for b in range(a + 1, end): if b % a == 0: n[b - start] = False nn = [] for i in range(start, end): i...
#In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. # Two nodes of a binary tree are cousins if they have the same depth, but have different parents. # We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. ...
class Solution: def is_cousins(self, root: TreeNode, x: int, y: int) -> bool: def dfs(node, parent, depth, mod): if node: if node.val == mod: return (depth, parent) return dfs(node.left, node, depth + 1, mod) or dfs(node.right, node, depth + ...
class ExtractionFailedError(Exception): def __init__(self): Exception.__init__(self, "Couldn't extract transactions from the given statement") class EntityNotFoundError(Exception): def __init__(self): Exception.__init__(self, "Couldn't find the entity with given entity_id") class ServiceTimeOu...
class Extractionfailederror(Exception): def __init__(self): Exception.__init__(self, "Couldn't extract transactions from the given statement") class Entitynotfounderror(Exception): def __init__(self): Exception.__init__(self, "Couldn't find the entity with given entity_id") class Servicetime...
n=int(input()) arr=list(map(int,input().split())) pos=[] neg=[] zero=[] for i in arr: if i>0: pos.append(i) elif i<0: neg.append(i) elif i==0: zero.append(i) print("%.6f"%(len(pos)/len(arr))) print("%.6f"%(len(neg)/len(arr))) print("%.6f"%(len(zero)/len(arr)))
n = int(input()) arr = list(map(int, input().split())) pos = [] neg = [] zero = [] for i in arr: if i > 0: pos.append(i) elif i < 0: neg.append(i) elif i == 0: zero.append(i) print('%.6f' % (len(pos) / len(arr))) print('%.6f' % (len(neg) / len(arr))) print('%.6f' % (len(zero) / len(a...
left = True right = False enable_flash = True distance = 400 (left << 7) + (right << 6) + (enable_flash << 5) + ((distance & 7936) >> 8) send_bytes = [ ord('$'), (left << 7) + (right << 6) + (enable_flash << 5) + ((distance & 7936) >> 8), distance & 255, ord('\n') ] print(bytearray(send_bytes))
left = True right = False enable_flash = True distance = 400 (left << 7) + (right << 6) + (enable_flash << 5) + ((distance & 7936) >> 8) send_bytes = [ord('$'), (left << 7) + (right << 6) + (enable_flash << 5) + ((distance & 7936) >> 8), distance & 255, ord('\n')] print(bytearray(send_bytes))
file1=open('data/ChipTop.pna',encoding='utf-8') layer_list=[] layer_count={} layer_tyep_list={} for line in file1: if(line[0]=='#'):# 'line' here is a string = # 1 3 3.57e+01 ....., need to convert it to list, strip by ' '. line_list=line.split( ) # 'line_list' is a list of small strings=['#', '1', '3.57e+01...
file1 = open('data/ChipTop.pna', encoding='utf-8') layer_list = [] layer_count = {} layer_tyep_list = {} for line in file1: if line[0] == '#': line_list = line.split() x1 = line_list[10] x2 = line_list[12] y1 = line_list[11] y2 = line_list[13] layer = line_list[8] ...
# Problem 169: Majority Element # You may assume that the array is non-empty and the majority element always exist in the array. # Example 1: # Input: # [3, 2, 3] # Output: # 3 # Example 2: # Input: # [2, 2, 1, 1, 1, 2, 2] # Output: # 2 def find_candidate(nums): if len(nums) == 1: return nums[0] ...
def find_candidate(nums): if len(nums) == 1: return nums[0] majority_c = nums[0] vote = 1 for index in range(len(nums)): if nums[index] == majority_c: vote += 1 else: vote -= 1 if vote == 0: majority_c = nums[index] vote = 1...
def average_temps(temps): sum_of_temps = 0 for temp in temps: sum_of_temps += float(temp) return sum_of_temps / len(temps) if __name__ == '__main__': temps = [23,21,34,32,16,33] result = average_temps(temps) print(result)
def average_temps(temps): sum_of_temps = 0 for temp in temps: sum_of_temps += float(temp) return sum_of_temps / len(temps) if __name__ == '__main__': temps = [23, 21, 34, 32, 16, 33] result = average_temps(temps) print(result)
# -*- coding: utf-8 -*- __author__ = 'Vauxoo OpenSource Specialists.' __email__ = 'mexico@vauxoo.com' __version__ = '0.7.4'
__author__ = 'Vauxoo OpenSource Specialists.' __email__ = 'mexico@vauxoo.com' __version__ = '0.7.4'
def prob_dist(counts, shots): output_distr = [v / shots for v in counts.values()] if len(output_distr) == 1: output_distr.append(1 - output_distr[0]) return output_distr
def prob_dist(counts, shots): output_distr = [v / shots for v in counts.values()] if len(output_distr) == 1: output_distr.append(1 - output_distr[0]) return output_distr
class Person: '''Base Class for person''' def __init__(self, x, y, symbol): '''Initialises The person at a location with the symbol''' self.x = x self.y = y self.symbol = symbol '''The below functions are for moving. No checking is done to see if the move is permitted...
class Person: """Base Class for person""" def __init__(self, x, y, symbol): """Initialises The person at a location with the symbol""" self.x = x self.y = y self.symbol = symbol 'The below functions are for moving. \n No checking is done to see if the move is permitted.' ...
# # PySNMP MIB module ASCEND-MIBTACL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBTACL-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:28:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration') (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_const...
def main(): counter = 0 print('im printing!') while True: print(counter) counter += 1 if counter >= 69: break if __name__ == '__main__': main()
def main(): counter = 0 print('im printing!') while True: print(counter) counter += 1 if counter >= 69: break if __name__ == '__main__': main()
word = "banana" check = "a" print(word.count(check))
word = 'banana' check = 'a' print(word.count(check))
# # PySNMP MIB module DPS-MIB-NGD-V10 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DPS-MIB-NGD-V10 # Produced by pysmi-0.3.4 at Wed May 1 12:54:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def convert(image): return image.reshape(1, image.shape[0], image.shape[1], 1)
def convert(image): return image.reshape(1, image.shape[0], image.shape[1], 1)
''' https://leetcode.com/problems/unique-binary-search-trees/ Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. ''' ''' Key Ideas: - The possible number of subtrees rooted at a node is the cartesian prod...
""" https://leetcode.com/problems/unique-binary-search-trees/ Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. """ '\n Key Ideas:\n - The possible number of subtrees rooted at a node is the cartesian produ...
print(1,2,3, sep='%') print (1) x = (1, 2, 3, 4, 5) print('well done')
print(1, 2, 3, sep='%') print(1) x = (1, 2, 3, 4, 5) print('well done')
#!/usr/bin/env python NAME = 'AnYu (AnYu Technologies)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return _, page = r if any(i in page for i in (b'Sorry! your access has been intercepted by AnYu', b'...
name = 'AnYu (AnYu Technologies)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return (_, page) = r if any((i in page for i in (b'Sorry! your access has been intercepted by AnYu', b'AnYu- the green channel'))): return True ...