content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
print("Enter the name of the file along with it's extension:-") a=str(input()) if('.py' in a): print("The extension of the file is : python") else: print("The extension of the file is not python")
print("Enter the name of the file along with it's extension:-") a = str(input()) if '.py' in a: print('The extension of the file is : python') else: print('The extension of the file is not python')
# -*- coding: utf-8 -*- # (C) Wu Dong, 2018 # All rights reserved __author__ = 'Wu Dong <wudong@eastwu.cn>' __time__ = '2018/9/6 11:07'
__author__ = 'Wu Dong <wudong@eastwu.cn>' __time__ = '2018/9/6 11:07'
# ABC167B - Easy Linear Programming def main(): # input A, B, C, K = map(int, input().split()) # compute kotae = A+(K-A)*0-(K-A-B) # output print(kotae) if __name__ == '__main__': main()
def main(): (a, b, c, k) = map(int, input().split()) kotae = A + (K - A) * 0 - (K - A - B) print(kotae) if __name__ == '__main__': main()
def lin(): print('-'*20) lin() def msg(m): lin() print(m) lin() msg('SISTEMA') def s(a,b): print(a+b) s(2,3) def cont(*num): for v in num: print(v,end=' ') print('\nfim') cont(2,3,7) def dobra(lst): pos = 0 while pos < len(lst): lst[pos] *= 2 pos += 1 valo...
def lin(): print('-' * 20) lin() def msg(m): lin() print(m) lin() msg('SISTEMA') def s(a, b): print(a + b) s(2, 3) def cont(*num): for v in num: print(v, end=' ') print('\nfim') cont(2, 3, 7) def dobra(lst): pos = 0 while pos < len(lst): lst[pos] *= 2 pos ...
inst = set() with open('tools/write_bytecode.py') as file: for line in file: if line.strip().startswith('#'): continue if '$' in line: instruction = line.split('$')[1].strip() print(instruction) inst.add(instruction.split()[0].strip().replace('32',...
inst = set() with open('tools/write_bytecode.py') as file: for line in file: if line.strip().startswith('#'): continue if '$' in line: instruction = line.split('$')[1].strip() print(instruction) inst.add(instruction.split()[0].strip().replace('32', '')...
################################################################ # compareTools.py # # Defines how nodes and edges are compared. # Usable by other packages such as smallGraph # # Author: H. Mouchere, Oct. 2013 # Copyright (c) 2013-2014 Richard Zanibbi and Harold Mouchere ################################################...
def generate_list_err(ab, ba): list_err = [] if len(ab) == 0: ab = ['_'] if len(ba) == 0: ba = ['_'] for c1 in ab: for c2 in ba: listErr.append((c1, c2)) return listErr def default_metric(labelList1, labelList2): diff = set(labelList1) ^ set(labelList2) i...
# -*- coding: utf-8 -*- def main(): n = int(input()) s = list() t = list() for i in range(n): si, ti = map(str, input().split()) s.append(si) t.append(int(ti)) x = input() index = s.index(x) print(sum(t[index + 1:])) if __name__ == '__main__': ...
def main(): n = int(input()) s = list() t = list() for i in range(n): (si, ti) = map(str, input().split()) s.append(si) t.append(int(ti)) x = input() index = s.index(x) print(sum(t[index + 1:])) if __name__ == '__main__': main()
### Alternating Characters - Solution def alternatingCharacters(): q = int(input()) while q: s = input() del_count = 0 for i in range(len(s)-1): if s[i] == s[i+1]: del_count += 1 print(del_count) q -= 1 alternatingCharacters()
def alternating_characters(): q = int(input()) while q: s = input() del_count = 0 for i in range(len(s) - 1): if s[i] == s[i + 1]: del_count += 1 print(del_count) q -= 1 alternating_characters()
class FileWarning(Exception): def __init__(self, file, message, *args, **kwargs): file.warn(message, *args, **kwargs) super().__init__(message % args) class FileError(Exception): def __init__(self, file, message, *args, **kwargs): file.error(message, *args, **kwargs) super()....
class Filewarning(Exception): def __init__(self, file, message, *args, **kwargs): file.warn(message, *args, **kwargs) super().__init__(message % args) class Fileerror(Exception): def __init__(self, file, message, *args, **kwargs): file.error(message, *args, **kwargs) super()._...
class RenderedView(object): def __init__(self, view_file: str, data): self.view_file = view_file self.data = data
class Renderedview(object): def __init__(self, view_file: str, data): self.view_file = view_file self.data = data
# PART 1 def game_of_cups(starting_sequence,num_of_moves,min_cup=None,max_cup=None): # create a "linked list" dict cups = { starting_sequence[i] : starting_sequence[i+1] for i in range(len(starting_sequence)-1) } cups[starting_sequence[-1]] = starting_sequence[0] # current_cup = ...
def game_of_cups(starting_sequence, num_of_moves, min_cup=None, max_cup=None): cups = {starting_sequence[i]: starting_sequence[i + 1] for i in range(len(starting_sequence) - 1)} cups[starting_sequence[-1]] = starting_sequence[0] current_cup = starting_sequence[0] max_cup = max_cup or max(starting_sequen...
txt = 'asdf;lkajsdf,as;lfkja' for i in txt: txt = txt[1:] if i == ",": break print(txt)
txt = 'asdf;lkajsdf,as;lfkja' for i in txt: txt = txt[1:] if i == ',': break print(txt)
class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key ...
class Hashtable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key ...
description = 'Email and SMS notifiers' group = 'lowlevel' devices = dict( email = device('nicos.devices.notifiers.Mailer', mailserver = 'mailhost.frm2.tum.de', sender = 'kws1@frm2.tum.de', copies = [ ('g.brandl@fz-juelich.de', 'all'), ('a.feoktystov@fz-juelich.de',...
description = 'Email and SMS notifiers' group = 'lowlevel' devices = dict(email=device('nicos.devices.notifiers.Mailer', mailserver='mailhost.frm2.tum.de', sender='kws1@frm2.tum.de', copies=[('g.brandl@fz-juelich.de', 'all'), ('a.feoktystov@fz-juelich.de', 'all'), ('h.frielinghaus@fz-juelich.de', 'all'), ('z.mahhouti@f...
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) if height > 120: print("you can ride the rollercoaster!") age = int(input("What is your age? ")) if age <= 18: print("$7") else: print("$12") else: print("no")
print('Welcome to the rollercoaster!') height = int(input('What is your height in cm? ')) if height > 120: print('you can ride the rollercoaster!') age = int(input('What is your age? ')) if age <= 18: print('$7') else: print('$12') else: print('no')
# "Config.py" # - config file for ConfigGUI.py # This is Python, therefore this is a comment # NOTE: variable names cannot start with '__' ECGColumn = True HRColumn = False PeakColumn = True RRColumn = True SeparateECGFile = True TCP_Host = "localhost" TCP_Port = 1000 TCPtimeout = 3 TimeColumn = True UDPConnectTimeo...
ecg_column = True hr_column = False peak_column = True rr_column = True separate_ecg_file = True tcp__host = 'localhost' tcp__port = 1000 tc_ptimeout = 3 time_column = True udp_connect_timeout = 1 udp_receive_timeout = 5 udp__client_ip = 'localhost' udp__client_port = 1001 udp__server_ip = 'localhost' udp__server_port ...
hidden_dim = 128 dilation = [1,2,4,8,16,32,64,128,256,512] sample_rate = 16000 timestep = 6080 is_training = True use_mulaw = True batch_size = 1 num_epochs = 10000 save_dir = './logdir' test_data = 'test.wav'
hidden_dim = 128 dilation = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] sample_rate = 16000 timestep = 6080 is_training = True use_mulaw = True batch_size = 1 num_epochs = 10000 save_dir = './logdir' test_data = 'test.wav'
# This file provides an object for version numbers. class Version: def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=""): self.major = major self.minor = minor self.patch = patch self.tag = tag def __repr__(self): return "Version(" + str(self.major...
class Version: def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=''): self.major = major self.minor = minor self.patch = patch self.tag = tag def __repr__(self): return 'Version(' + str(self.major) + ', ' + str(self.minor) + ', ' + str(self.patch) + ',...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: self.result = [] self.wft([root]) return self.resu...
class Solution: def level_order_bottom(self, root: TreeNode) -> List[List[int]]: self.result = [] self.wft([root]) return self.result def wft(self, nodes): new_nodes = [] values = [] for n in nodes: if n is not None: values.append(n.v...
class airQuality: def __init__(self, bus): self.iaq = 0 self.bus = bus self.address = 0x5A self.datablock = 9 self.data = 0 def read(self): data = self.bus.read_i2c_block_data(self.address, 0x00, self.datablock) #WIP # Convert the data #if...
class Airquality: def __init__(self, bus): self.iaq = 0 self.bus = bus self.address = 90 self.datablock = 9 self.data = 0 def read(self): data = self.bus.read_i2c_block_data(self.address, 0, self.datablock)
#You are given a list of n-1 integers and these integers are in the range of 1 to n. #There are no duplicates in the list. #One of the integers is missing in the list. Write an efficient code to find the missing integer ar=[ 1, 2, 4, 5, 6 ] def missing_(a): print("l",l) for i in range(1,l+2): if(i not in a): ...
ar = [1, 2, 4, 5, 6] def missing_(a): print('l', l) for i in range(1, l + 2): if i not in a: return i print(missing_(ar))
print('Enter a text and when finished press Enter twice: ') text = '' while True: line = input() if line: text += line + '\n ' else: break def wc(text): n_words = len(text.split(' ')) - 1 n_lines = len(text.split('\n')) - 1 n_characters = len(text) - 2*n_lines ...
print('Enter a text and when finished press Enter twice: ') text = '' while True: line = input() if line: text += line + '\n ' else: break def wc(text): n_words = len(text.split(' ')) - 1 n_lines = len(text.split('\n')) - 1 n_characters = len(text) - 2 * n_lines print(f'Char...
def sample_anchors_pre(df, n_samples= 256, neg_ratio= 0.5): ''' Sample total of n samples across both BG and FG classes. If one of the classes have less samples than n/2, we will sample from majority class to make up for short. Args: df with column named labels_anchors, containing 1 for f...
def sample_anchors_pre(df, n_samples=256, neg_ratio=0.5): """ Sample total of n samples across both BG and FG classes. If one of the classes have less samples than n/2, we will sample from majority class to make up for short. Args: df with column named labels_anchors, containing 1 for foregrou...
ansOut = [] coin = [10, 50, 100, 500] while True: price = int(input()) if price == 0: break cash = list(map(int, input().split())) sumCash = sum(c * n for c, n in zip(coin, cash)) change = sumCash - price changeCoins = [(change % 50) // 10, (change % 100) // 50, (change % 500) // 100, ch...
ans_out = [] coin = [10, 50, 100, 500] while True: price = int(input()) if price == 0: break cash = list(map(int, input().split())) sum_cash = sum((c * n for (c, n) in zip(coin, cash))) change = sumCash - price change_coins = [change % 50 // 10, change % 100 // 50, change % 500 // 100, c...
def isBalanced(expr): if len(expr)%2!=0: return False opening=set('([{') match=set([ ('(',')'), ('[',']'), ('{','}') ]) stack=[] for char in expr: if char in opening: stack.append(char) else: if len(stack)==0: return False ...
def is_balanced(expr): if len(expr) % 2 != 0: return False opening = set('([{') match = set([('(', ')'), ('[', ']'), ('{', '}')]) stack = [] for char in expr: if char in opening: stack.append(char) else: if len(stack) == 0: return False...
class Solution: def mySqrt(self, x: int) -> int: left, right = 0, x while left <= right: mid = left + (right - left) // 2 square = mid ** 2 if square <= x: left = mid + 1 elif squ...
class Solution: def my_sqrt(self, x: int) -> int: (left, right) = (0, x) while left <= right: mid = left + (right - left) // 2 square = mid ** 2 if square <= x: left = mid + 1 elif square > x: right = mid - 1 re...
In [18]: my_list = [27, "11-13-2017", 84.98, 5] In [19]: store27 = salesReceipt._make(my_list) In [20]: print(store27) salesReceipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
In[18]: my_list = [27, '11-13-2017', 84.98, 5] In[19]: store27 = salesReceipt._make(my_list) In[20]: print(store27) sales_receipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []} def dfs_topsort(graph): # recursive dfs with L = [] # additional list for order of nodes color = { u : "white" for u in graph } found_cycle = [False] for u in graph: if color[u] == "white": dfs_visit(graph,...
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []} def dfs_topsort(graph): l = [] color = {u: 'white' for u in graph} found_cycle = [False] for u in graph: if color[u] == 'white': dfs_visit(graph, u, color, L, found_cycle) if found_cycle[0]: break if found_cycle[...
#!/usr/bin/env python3 flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacb...
flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacbd3f2}', 'QCTF{8e4225e08e6...
#!/usr/bin/python3.5 def fib(n: int): fibs = [1, 1] for _ in range(max(n-2, 0)): fibs.append(fibs[-1] + fibs[-2]) return fibs[n-1] print("%s" % fib(38))
def fib(n: int): fibs = [1, 1] for _ in range(max(n - 2, 0)): fibs.append(fibs[-1] + fibs[-2]) return fibs[n - 1] print('%s' % fib(38))
# coding=utf8 class Error(Exception): pass class TitleRequiredError(Error): pass class TextRequiredError(Error): pass class APITokenRequiredError(Error): pass class GetImageRequestError(Error): pass class ImageUploadHTTPError(Error): pass class FileTypeNotSupported(Error): pass...
class Error(Exception): pass class Titlerequirederror(Error): pass class Textrequirederror(Error): pass class Apitokenrequirederror(Error): pass class Getimagerequesterror(Error): pass class Imageuploadhttperror(Error): pass class Filetypenotsupported(Error): pass class Telegraphunkno...
class Tree(object): def __init__(self): self.children = [] self.metadata = [] def add_child(self, leaf): self.children.append(leaf) def add_metadata(self, metadata): self.metadata.append(metadata) def sum_metadata(self): metasum = sum(self.metadata) for...
class Tree(object): def __init__(self): self.children = [] self.metadata = [] def add_child(self, leaf): self.children.append(leaf) def add_metadata(self, metadata): self.metadata.append(metadata) def sum_metadata(self): metasum = sum(self.metadata) fo...
print("RENTAL MOBIL ABCD") print("-------------------------------") #Input nama = input("Masukkan Nama Anda : ") umur = int(input("Masukkan Umur Anda : ")) if umur < 18: print("Maaf", nama, "anda belum bisa meminjam kendaraan") else: ktp = int(input("Masukkan Nomor KTP Anda : ")) k_mobil = in...
print('RENTAL MOBIL ABCD') print('-------------------------------') nama = input('Masukkan Nama Anda : ') umur = int(input('Masukkan Umur Anda : ')) if umur < 18: print('Maaf', nama, 'anda belum bisa meminjam kendaraan') else: ktp = int(input('Masukkan Nomor KTP Anda : ')) k_mobil = input('Kategori Mobil [4...
def func_that_raises(): raise ValueError('Error message') def func_no_catch(): func_that_raises()
def func_that_raises(): raise value_error('Error message') def func_no_catch(): func_that_raises()
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016-2017 JiNong Inc. All right reserved. # __title__ = 'python-pyjns' __version__ = '0.40' __author__ = 'Kim, JoonYong' __email__ = 'joonyong.jinong@gmail.com' __copyright__ = 'Copyright 2016-2017 JiNong Inc.'
__title__ = 'python-pyjns' __version__ = '0.40' __author__ = 'Kim, JoonYong' __email__ = 'joonyong.jinong@gmail.com' __copyright__ = 'Copyright 2016-2017 JiNong Inc.'
extensions = [ "cogs.help", "cogs.game_punishments.ban", "cogs.game_punishments.kick", "cogs.game_punishments.unban", "cogs.game_punishments.warn", "cogs.settings.setchannel", "cogs.verification.verify" ]
extensions = ['cogs.help', 'cogs.game_punishments.ban', 'cogs.game_punishments.kick', 'cogs.game_punishments.unban', 'cogs.game_punishments.warn', 'cogs.settings.setchannel', 'cogs.verification.verify']
def __getitem__(self,idx): if idx < self.lastIndex: return self.myArray[idx] else: raise LookupError('index out of bounds') def __setitem__(self,idx,val): if idx < self.lastIndex: self.myArray[idx] = val else: raise LookupError('index out of bounds')
def __getitem__(self, idx): if idx < self.lastIndex: return self.myArray[idx] else: raise lookup_error('index out of bounds') def __setitem__(self, idx, val): if idx < self.lastIndex: self.myArray[idx] = val else: raise lookup_error('index out of bounds')
__author__ = "Amane Katagiri" __contact__ = "amane@ama.ne.jp" __copyright__ = "Copyright (C) 2016 Amane Katagiri" __credits__ = "" __date__ = "2016-12-07" __license__ = "MIT License" __version__ = "0.1.0"
__author__ = 'Amane Katagiri' __contact__ = 'amane@ama.ne.jp' __copyright__ = 'Copyright (C) 2016 Amane Katagiri' __credits__ = '' __date__ = '2016-12-07' __license__ = 'MIT License' __version__ = '0.1.0'
example_dict = {} for idx in range(0, 10): example_dict[idx] = idx for key, value in example_dict.items(): formmating = f'key is {key}, value is {value}' print(formmating)
example_dict = {} for idx in range(0, 10): example_dict[idx] = idx for (key, value) in example_dict.items(): formmating = f'key is {key}, value is {value}' print(formmating)
def minimumSwaps(arr): a = dict(enumerate(arr,1)) b = {v:k for k,v in a.items()} count = 0 for i in a: x = a[i] if x!=i: y = b[i] a[y] = x b[x] = y count+=1 return count n = int(input()) arr = list(map(int,input(...
def minimum_swaps(arr): a = dict(enumerate(arr, 1)) b = {v: k for (k, v) in a.items()} count = 0 for i in a: x = a[i] if x != i: y = b[i] a[y] = x b[x] = y count += 1 return count n = int(input()) arr = list(map(int, input().split())) p...
def extract_characters(*file): with open("file3.txt") as f: while True: c = f.read(1) if not c: break print(c) extract_characters('file3.txt')
def extract_characters(*file): with open('file3.txt') as f: while True: c = f.read(1) if not c: break print(c) extract_characters('file3.txt')
class MTUError(Exception): pass class MACError(Exception): pass class IPv4AddressError(Exception): pass
class Mtuerror(Exception): pass class Macerror(Exception): pass class Ipv4Addresserror(Exception): pass
def cyclesort(lst): for i in range(len(lst)): if i != lst[i]: n = i while 1: tmp = lst[int(n)] if n != i: lst[int(n)] = last_value lst.log() else: lst[int(n)] = None ...
def cyclesort(lst): for i in range(len(lst)): if i != lst[i]: n = i while 1: tmp = lst[int(n)] if n != i: lst[int(n)] = last_value lst.log() else: lst[int(n)] = None ...
# game model # - holds global game properties class Game(): def __init__(self, config): self.config = config self.pygame = config.pygame self.screen = self.pygame.display.set_mode( ( self.config.SCREEN_PX_WIDTH, self.config.SCREEN_PX_HEIGHT ) ) self.clock = self.pygame.time.Clock() self....
class Game: def __init__(self, config): self.config = config self.pygame = config.pygame self.screen = self.pygame.display.set_mode((self.config.SCREEN_PX_WIDTH, self.config.SCREEN_PX_HEIGHT)) self.clock = self.pygame.time.Clock() self.running = True self.restart = T...
lexicon_dataset = { 'direction': 'north south east west down up left right back', 'verb': 'go stop kill eat', 'stop': 'the in of from at it', 'noun': 'door bear princess cabinet' } def scan(sentence): result = [] words = sentence.split(' ') for word in words: if word.isnumeric(): ...
lexicon_dataset = {'direction': 'north south east west down up left right back', 'verb': 'go stop kill eat', 'stop': 'the in of from at it', 'noun': 'door bear princess cabinet'} def scan(sentence): result = [] words = sentence.split(' ') for word in words: if word.isnumeric(): word = i...
# # PHASE: unused deps checker # # DOCUMENT THIS # load( "@io_bazel_rules_scala//scala/private:rule_impls.bzl", "get_unused_dependency_checker_mode", ) def phase_unused_deps_checker(ctx, p): return get_unused_dependency_checker_mode(ctx)
load('@io_bazel_rules_scala//scala/private:rule_impls.bzl', 'get_unused_dependency_checker_mode') def phase_unused_deps_checker(ctx, p): return get_unused_dependency_checker_mode(ctx)
def merge_sorted_arr(left, right): i = 0 j = 0 new_arr = [] while j < len(right) and i < len(left): if left[i] < right[j]: new_arr.append(left[i]) i += 1 elif right[j] <= left[i]: new_arr.append(right[j]) j += 1 while i < len(left): ...
def merge_sorted_arr(left, right): i = 0 j = 0 new_arr = [] while j < len(right) and i < len(left): if left[i] < right[j]: new_arr.append(left[i]) i += 1 elif right[j] <= left[i]: new_arr.append(right[j]) j += 1 while i < len(left): ...
{ "targets": [ { "target_name" : "libtracer", "type" : "static_library", "sources" : [ "./libtracer/basic.observer.cpp", "./libtracer/simple.tracer/simple.tracer.cpp", "./libtracer/annotated.tracer/TrackingExecutor.cpp", "./libtracer/annotated.tracer/BitMap.cpp", "./libtracer...
{'targets': [{'target_name': 'libtracer', 'type': 'static_library', 'sources': ['./libtracer/basic.observer.cpp', './libtracer/simple.tracer/simple.tracer.cpp', './libtracer/annotated.tracer/TrackingExecutor.cpp', './libtracer/annotated.tracer/BitMap.cpp', './libtracer/annotated.tracer/annotated.tracer.cpp'], 'include_...
pet1 = {'name': 'mr.bubbles', "type":'dog', "owner" : 'joe'} pet2 = {'name': 'spot', "type":'cat', "owner" : 'bob'} pet3 = {'name': 'chester', "type":'horse', "owner" : 'chloe'} pets = [pet1, pet2, pet3] for pet in pets: print(pet['name'], pet['type'], pet['owner'])
pet1 = {'name': 'mr.bubbles', 'type': 'dog', 'owner': 'joe'} pet2 = {'name': 'spot', 'type': 'cat', 'owner': 'bob'} pet3 = {'name': 'chester', 'type': 'horse', 'owner': 'chloe'} pets = [pet1, pet2, pet3] for pet in pets: print(pet['name'], pet['type'], pet['owner'])
''' Author: ZHAO Zinan Created: 10. March 2019 1005. Maximize Sum Of Array After K Negations ''' class Solution: def largestSumAfterKNegations(self, A: List[int], K: int) -> int: A.sort() for index, a in enumerate(A): if a <= 0: if K > 0: ...
""" Author: ZHAO Zinan Created: 10. March 2019 1005. Maximize Sum Of Array After K Negations """ class Solution: def largest_sum_after_k_negations(self, A: List[int], K: int) -> int: A.sort() for (index, a) in enumerate(A): if a <= 0: if K > 0: A[in...
def main(): N, M = map(int, input().split()) a = list(map(int, input().split())) A = a[-1] def is_ok(mid): last = a[0] count = 1 for i in range(1,N): if a[i] - last >= mid: count += 1 last = a[i] if count >= M...
def main(): (n, m) = map(int, input().split()) a = list(map(int, input().split())) a = a[-1] def is_ok(mid): last = a[0] count = 1 for i in range(1, N): if a[i] - last >= mid: count += 1 last = a[i] if count >= M: r...
class AddOperation: def soma(self, number1, number2): return number1 + number2
class Addoperation: def soma(self, number1, number2): return number1 + number2
GOOGLE_SHEET_URL = ( "https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/{table_name}" ) LOGGING_DICT = { "version": 1, "disable_existing_loggers": False, "formatters": {"standard": {"format": "%(message)s"}}, "handlers": { "file": { "level": "INFO", "cl...
google_sheet_url = 'https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/{table_name}' logging_dict = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'standard': {'format': '%(message)s'}}, 'handlers': {'file': {'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'a...
N = int(input()) A = [int(x) for x in input().split()] for i in range(N): for j in range(i, N): A[i], A[j] = A[j], A[i] if sorted(A) == A: print("YES") quit() A[i], A[j] = A[j], A[i] print("NO")
n = int(input()) a = [int(x) for x in input().split()] for i in range(N): for j in range(i, N): (A[i], A[j]) = (A[j], A[i]) if sorted(A) == A: print('YES') quit() (A[i], A[j]) = (A[j], A[i]) print('NO')
def add_time(start, duration, start_day = ""): new_time = "" #24h_hours = 0 # If a user added a starting day, correct the input to be lower if start_day: start_day = start_day.lower() if start_day == 'monday': start_day_num = 0 elif start_day == 'tuesday': start_day_num = 1 elif start_day...
def add_time(start, duration, start_day=''): new_time = '' if start_day: start_day = start_day.lower() if start_day == 'monday': start_day_num = 0 elif start_day == 'tuesday': start_day_num = 1 elif start_day == 'wednesday': start_day_num = 2 elif start_day == 'th...
n1 = 36 n2 = 14 m = max(n1, n2) lcm = n1 * n2 rng = range(m, n1*n2+1) for i in rng: if i % n1 == 0 and i % n2 == 0: print("The lcm is " + str(i)) break
n1 = 36 n2 = 14 m = max(n1, n2) lcm = n1 * n2 rng = range(m, n1 * n2 + 1) for i in rng: if i % n1 == 0 and i % n2 == 0: print('The lcm is ' + str(i)) break
# take linear julia list of lists and convert to julia array format execfile('../pyprgs/in_out_line.py') execfile('../pyprgs/in_out_csv.py') dat1 = lin.reader("../poets/results_poets/cross_validation/EC1.dat") dat2 = lin.reader("../poets/results_poets/cross_validation/EC2.dat") dat3 = lin.reader("../poets/results_poe...
execfile('../pyprgs/in_out_line.py') execfile('../pyprgs/in_out_csv.py') dat1 = lin.reader('../poets/results_poets/cross_validation/EC1.dat') dat2 = lin.reader('../poets/results_poets/cross_validation/EC2.dat') dat3 = lin.reader('../poets/results_poets/cross_validation/EC3.dat') dat4 = lin.reader('../poets/results_poet...
# Quick Sort # Randomize Pivot to avoid worst case, currently pivot is last element def quickSort(A, si, ei): if si < ei: pi = partition(A, si, ei) quickSort(A, si, pi-1) quickSort(A, pi+1, ei) # Partition # Utility function for partitioning the array(used in quick sort) def partition(A, s...
def quick_sort(A, si, ei): if si < ei: pi = partition(A, si, ei) quick_sort(A, si, pi - 1) quick_sort(A, pi + 1, ei) def partition(A, si, ei): x = A[ei] i = si - 1 for j in range(si, ei): if A[j] <= x: i += 1 (A[i], A[j]) = (A[j], A[i]) (A[i +...
class Proxy(): proxies = [] # Will contain proxies [ip, port] #### adding proxy information so as not to get blocked so fast def getProxyList(self): # Retrieve latest proxies url = 'https://www.sslproxies.org/' header = {'User-Agent': str(ua.random)} response = requests.get(ur...
class Proxy: proxies = [] def get_proxy_list(self): url = 'https://www.sslproxies.org/' header = {'User-Agent': str(ua.random)} response = requests.get(url, headers=header) soup = beautiful_soup(response.text, 'lxml') proxies_table = soup.find(id='proxylisttable') ...
file = open("nomes.txt", "r") lines = file.readlines() title = lines[0] names = title.strip().split(",") print(names) for i in lines[1:]: aux = i.strip().split(",") print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2]))
file = open('nomes.txt', 'r') lines = file.readlines() title = lines[0] names = title.strip().split(',') print(names) for i in lines[1:]: aux = i.strip().split(',') print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2]))
x = 50 def funk(): global x print("x je ", x) x = 2 print("Promjena globalne vrijednost promjeljive x na ", x) funk() print("Vrijednost promjeljive x sada je ", x)
x = 50 def funk(): global x print('x je ', x) x = 2 print('Promjena globalne vrijednost promjeljive x na ', x) funk() print('Vrijednost promjeljive x sada je ', x)
# Each new term in the Fibonacci sequence is generated by adding # the previous two terms. By starting with 1 and 2, the first 10 # terms will be: # # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # # By considering the terms in the Fibonacci sequence whose values # do not exceed four million, find the sum of the even-valu...
def fib_sum(limit): return fib_calc(limit, 0, 1, 0) def fib_calc(limit, a, b, accum): if b > limit: return accum else: if b % 2 == 0: accum += b return fib_calc(limit, b, a + b, accum) if __name__ == '__main__': print(fib_sum(4000000))
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Gregorian'}, {'abbr': 1, 'code': 1, 'title': '360-day'}, {'abbr': 2, 'code': 2, 'title': '365-day'}, {'abbr': 3, 'code': 3, 'title': 'Proleptic Gregorian'}, {'abbr': None, 'code': 255, 'title': 'Missing'})
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Gregorian'}, {'abbr': 1, 'code': 1, 'title': '360-day'}, {'abbr': 2, 'code': 2, 'title': '365-day'}, {'abbr': 3, 'code': 3, 'title': 'Proleptic Gregorian'}, {'abbr': None, 'code': 255, 'title': 'Missing'})
# # PySNMP MIB module ZXR10-VSWITCH-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXR10-VSWITCH-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:42:32 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) ...
del_items(0x80122A40) SetType(0x80122A40, "struct Creds CreditsTitle[6]") del_items(0x80122BE8) SetType(0x80122BE8, "struct Creds CreditsSubTitle[28]") del_items(0x80123084) SetType(0x80123084, "struct Creds CreditsText[35]") del_items(0x8012319C) SetType(0x8012319C, "int CreditsTable[224]") del_items(0x801243BC) SetTy...
del_items(2148674112) set_type(2148674112, 'struct Creds CreditsTitle[6]') del_items(2148674536) set_type(2148674536, 'struct Creds CreditsSubTitle[28]') del_items(2148675716) set_type(2148675716, 'struct Creds CreditsText[35]') del_items(2148675996) set_type(2148675996, 'int CreditsTable[224]') del_items(2148680636) s...
has_high_income = True has_good_credit = True has_criminal_record = False if has_high_income and has_good_credit: print("Eligible for loan") if has_high_income or has_good_credit: print("Eligible for consultation") if has_good_credit and not has_criminal_record: print("Eligible for credit card")
has_high_income = True has_good_credit = True has_criminal_record = False if has_high_income and has_good_credit: print('Eligible for loan') if has_high_income or has_good_credit: print('Eligible for consultation') if has_good_credit and (not has_criminal_record): print('Eligible for credit card')
#1 def print_factors(n): #2 for i in range(1, n+1): #3 if n % i == 0: print(i) #4 number = int(input("Enter a number : ")) #5 print("The factors for {} are : ".format(number)) print_factors(number)
def print_factors(n): for i in range(1, n + 1): if n % i == 0: print(i) number = int(input('Enter a number : ')) print('The factors for {} are : '.format(number)) print_factors(number)
# Min Heap implementation def swap(h, i, j): h[i], h[j] = h[j], h[i] def _min_heap_sift_up(h, k): while k//2 >= 0: if h[k] < h[k//2]: swap(h, k, k//2) k = k//2 else: break def _min_heap_sift_down(h, k): last = len(h)-1 while (2*k+1) < last: ...
def swap(h, i, j): (h[i], h[j]) = (h[j], h[i]) def _min_heap_sift_up(h, k): while k // 2 >= 0: if h[k] < h[k // 2]: swap(h, k, k // 2) k = k // 2 else: break def _min_heap_sift_down(h, k): last = len(h) - 1 while 2 * k + 1 < last: child = 2 *...
{ "targets": [ { "target_name": "node-cursor", "sources": [ "node-cursor.cc" ] } ] }
{'targets': [{'target_name': 'node-cursor', 'sources': ['node-cursor.cc']}]}
def solution(coins, amount): coins = sorted(coins) minCoins = [0] * (amount + 1) for k in range(1, amount+1): minCoins[k] = amount + 1 i = 0 while i < len(coins) and coins[i] <= k: minCoins[k] = min(minCoins[k], minCoins[k - coins[i]] + 1) i += 1 ...
def solution(coins, amount): coins = sorted(coins) min_coins = [0] * (amount + 1) for k in range(1, amount + 1): minCoins[k] = amount + 1 i = 0 while i < len(coins) and coins[i] <= k: minCoins[k] = min(minCoins[k], minCoins[k - coins[i]] + 1) i += 1 if min...
class Node: def __init__(self, value, _next=None): self._value = value self._next = _next def __str__(self): return f'{self._value}' def __repr__(self): return f'<Node | Val: {self._value} | Next: {self._next}>'
class Node: def __init__(self, value, _next=None): self._value = value self._next = _next def __str__(self): return f'{self._value}' def __repr__(self): return f'<Node | Val: {self._value} | Next: {self._next}>'
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. # click to show follow up. # Follow up: # Did you use extra space? # A straight forward solution using O(mn) space is probably a bad idea. # A simple improvement uses O(m + n) space, but still not the best solution. # Coul...
class Solution: def set_zeroes(self, matrix): fr = fc = False for i in xrange(len(matrix)): for j in xrange(len(matrix[0])): if matrix[i][j] == 0: matrix[i][0] = matrix[0][j] = 0 if i == 0: fr = True ...
x=input('enter str1') y=input('enter str2') a=[] b=[];c=[];max=-1 for i in range(len(x)+1): for j in range(i+1,len(x)+1): a.append(x[i:j]) for i in range(len(y)+1): for j in range(i+1,len(y)+1): b.append(y[i:j]) for i in range(len(a)): for j in range(len(b)): if a[i]==b[j...
x = input('enter str1') y = input('enter str2') a = [] b = [] c = [] max = -1 for i in range(len(x) + 1): for j in range(i + 1, len(x) + 1): a.append(x[i:j]) for i in range(len(y) + 1): for j in range(i + 1, len(y) + 1): b.append(y[i:j]) for i in range(len(a)): for j in range(len(b)): ...
altitude = int(input("CURRENT ALTITUDE:")) if altitude <=1000: print("You can land the plan") elif altitude > 1000 and altitude < 5000: print("Come down to 1000") else: print("Turn around")
altitude = int(input('CURRENT ALTITUDE:')) if altitude <= 1000: print('You can land the plan') elif altitude > 1000 and altitude < 5000: print('Come down to 1000') else: print('Turn around')
class Solution: def myPow(self, x: float, n: int) -> float: ''' x^n = x^2 ^ (n//2) if n is even x^n = x * x^2 ^ (n//2) is n is odd ''' if n == 0: return 1 result = self.myPow(x*x, abs(n) //2) if n % 2: result *= x ...
class Solution: def my_pow(self, x: float, n: int) -> float: """ x^n = x^2 ^ (n//2) if n is even x^n = x * x^2 ^ (n//2) is n is odd """ if n == 0: return 1 result = self.myPow(x * x, abs(n) // 2) if n % 2: result *= x if n < 0:...
# -*- coding: utf-8 -*- class Solution: def reversePrefix(self, word: str, ch: str) -> str: return ''.join(reversed(word[:word.find(ch) + 1])) + word[word.find(ch) + 1:] if __name__ == '__main__': solution = Solution() assert 'dcbaefd' == solution.reversePrefix('abcdefd', 'd') assert 'zxyxxe...
class Solution: def reverse_prefix(self, word: str, ch: str) -> str: return ''.join(reversed(word[:word.find(ch) + 1])) + word[word.find(ch) + 1:] if __name__ == '__main__': solution = solution() assert 'dcbaefd' == solution.reversePrefix('abcdefd', 'd') assert 'zxyxxe' == solution.reversePrefi...
#!/usr/bin/env python3 def mysteryAlgorithm(lst): for i in range(1,len(lst)): while i > 0 and lst[i-1] > lst[i]: lst[i], lst[i-1] = lst[i-1], lst[i] i -= 1 return lst print(mysteryAlgorithm([6, 4, 3, 8, 5]))
def mystery_algorithm(lst): for i in range(1, len(lst)): while i > 0 and lst[i - 1] > lst[i]: (lst[i], lst[i - 1]) = (lst[i - 1], lst[i]) i -= 1 return lst print(mystery_algorithm([6, 4, 3, 8, 5]))
''' practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses by Aashik J Krishnan/Aash Gates ''' x = 10 y ="ten" #step 1 temp = x #temp variable now holds the value of x #step 2 x = y #the variable x now holds the value of y #step 3 y = temp # y now holds the value of temp which is the orginal value...
""" practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses by Aashik J Krishnan/Aash Gates """ x = 10 y = 'ten' temp = x x = y y = temp print(x) print(y) print(temp)
# # @lc app=leetcode id=541 lang=python3 # # [541] Reverse String II # # https://leetcode.com/problems/reverse-string-ii/description/ # # algorithms # Easy (49.66%) # Total Accepted: 117.1K # Total Submissions: 235.8K # Testcase Example: '"abcdefg"\n2' # # Given a string s and an integer k, reverse the first k char...
class Solution: def reverse_str(self, s: str, k: int) -> str: if len(s) < k: return self.reverseAllStr(s) elif len(s) >= k and len(s) < 2 * k: return self.reverseAllStr(s[:k]) + s[k:] else: return self.reverseAllStr(s[:k]) + s[k:2 * k] + self.reverseStr(s...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
def load_command_table(self, _): with self.command_group('approle', is_preview=True) as g: g.custom_command('list', 'list_app_roles') g.custom_command('assignment list', 'list_role_assignments') g.custom_command('assignment add', 'add_role_assignment') g.custom_command('assignment re...
''' Url: https://www.hackerrank.com/challenges/write-a-function/problem Name: Write a function ''' def is_leap(year): ''' For this reason, not every four years is a leap year. The rule is that if the year is divisible by 100 and not divisible by 400, leap year is skipped. The year 2000 was a leap year, for ex...
""" Url: https://www.hackerrank.com/challenges/write-a-function/problem Name: Write a function """ def is_leap(year): """ For this reason, not every four years is a leap year. The rule is that if the year is divisible by 100 and not divisible by 400, leap year is skipped. The year 2000 was a leap year, for exa...
class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: E = len(trust) if E < N - 1: return -1 trustScore = [0] * N for a, b in trust: trustScore[a - 1] -= 1 trustScore[b - 1] += 1 for index, t in enumerate(trustScore, 1...
class Solution: def find_judge(self, N: int, trust: List[List[int]]) -> int: e = len(trust) if E < N - 1: return -1 trust_score = [0] * N for (a, b) in trust: trustScore[a - 1] -= 1 trustScore[b - 1] += 1 for (index, t) in enumerate(trustS...
line = '-'*39 bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|' blankNum1 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*4 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|' blankNum2 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*3 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}...
line = '-' * 39 bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|' blank_num1 = '|' + ' ' * 6 + '{0}' + ' ' * 4 + '|' + ' ' * 4 + '{1}' + ' ' * 4 + '|' + ' ' * 7 + '{2}' + ' ' * 7 + '|' blank_num2 = '|' + ' ' * 6 + '{0}' + ' ' * 4 + '|' + ' ' * 3 + '{1}' + ' ' ...
def dfs(u, graph, visited): visited.add(u) for v in graph[u]: if v not in visited: dfs(v, graph, visited) def count_dfs(u, graph, visited=None, depth=0): if visited is None: visited = set() visited.add(u) res = 1 for v, count in graph[u]: if v not in visite...
def dfs(u, graph, visited): visited.add(u) for v in graph[u]: if v not in visited: dfs(v, graph, visited) def count_dfs(u, graph, visited=None, depth=0): if visited is None: visited = set() visited.add(u) res = 1 for (v, count) in graph[u]: if v not in visite...
def selection_sort(arr): for num in range(0, len(arr)): min_position = num for i in range(num, len(arr)): if arr[i] < arr[min_position]: min_position = i temp = arr[num] arr[num] = arr[min_position] arr[min_position] = temp arr = [6, 3, 8, 5, 2, 7, 4, 1] print(f'Unordered: {arr}') selection_sort(a...
def selection_sort(arr): for num in range(0, len(arr)): min_position = num for i in range(num, len(arr)): if arr[i] < arr[min_position]: min_position = i temp = arr[num] arr[num] = arr[min_position] arr[min_position] = temp arr = [6, 3, 8, 5, 2, 7,...
print('<AMO FAZER EXERCICIO NO URI>') print('< AMO FAZER EXERCICIO NO URI>') print('<AMO FAZER EXERCICIO >') print('<AMO FAZER EXERCICIO NO URI>') print('<AMO FAZER EXERCICIO NO URI >') print('<AMO FAZER EXERCICIO NO URI>') print('< AMO FAZER EXERCICIO >') print('<AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO NO URI>') print('< AMO FAZER EXERCICIO NO URI>') print('<AMO FAZER EXERCICIO >') print('<AMO FAZER EXERCICIO NO URI>') print('<AMO FAZER EXERCICIO NO URI >') print('<AMO FAZER EXERCICIO NO URI>') print('< AMO FAZER EXERCICIO >') print('<AMO FAZER EXERCICIO >')
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: for idx in range(len(image)): image[idx] = list(reversed(image[idx])) image[idx] = [1 if b == 0 else 0 for b in image[idx]] return image
class Solution: def flip_and_invert_image(self, image: List[List[int]]) -> List[List[int]]: for idx in range(len(image)): image[idx] = list(reversed(image[idx])) image[idx] = [1 if b == 0 else 0 for b in image[idx]] return image
WINSTRIDE = (8, 8) PADDING = (8, 8) SCALE = 1.15 MIN_NEIGHBORS = 5 OVERLAP_NMS = 0.9
winstride = (8, 8) padding = (8, 8) scale = 1.15 min_neighbors = 5 overlap_nms = 0.9
index_definition = { "name": "id", "field_type": "int", "index_type": "hash", "is_pk": True, "is_array": False, "is_dense": False, "is_sparse": False, "collate_mode": "none", "sort_order_letters": "", "expire_after": 0, "config": { }, "json_paths": [ "id" ] } updated_in...
index_definition = {'name': 'id', 'field_type': 'int', 'index_type': 'hash', 'is_pk': True, 'is_array': False, 'is_dense': False, 'is_sparse': False, 'collate_mode': 'none', 'sort_order_letters': '', 'expire_after': 0, 'config': {}, 'json_paths': ['id']} updated_index_definition = {'name': 'id', 'field_type': 'int64', ...
def fac(n): if n==1 or n==0: return 1 else: return n*fac(n-1) print(fac(10))
def fac(n): if n == 1 or n == 0: return 1 else: return n * fac(n - 1) print(fac(10))
#-------------------------------------------------------------------# # Returns the value of the given card #-------------------------------------------------------------------# def get_value(card): value = card[0:len(card)-1] return int(value) #-----------------------------------------------------------------...
def get_value(card): value = card[0:len(card) - 1] return int(value) def get_suit(card): suit = card[len(card) - 1:] return suit def get_cards_of_same_suit(suit, dealerCards): cards_of_same_suit = tuple() for c in dealerCards: if get_suit(c) == suit: if cardsOfSameSuit == t...
# we prompt the user for the code. # enters beginning meter reading # Enters ending meter reading. # we compute the gallons of water as a 10th of the gotten gallons. # we print out the bill meant to be paid the user def bill_calculator(code, gallons): if code == "r": bill = 5.00 + (gallons * 0.0005) ...
def bill_calculator(code, gallons): if code == 'r': bill = 5.0 + gallons * 0.0005 return round(bill, 2) elif code == 'c': if gallons <= 4000000: bill = 1000.0 return round(bill, 2) else: first_half = 1000.0 sec_half = (gallons - 400...
''' exceptions.py: exceptions defined by textform Authors ------- Michael Hucka <mhucka@caltech.edu> -- Caltech Library Copyright --------- Copyright (c) 2020 by the California Institute of Technology. This code is open-source software released under a 3-clause BSD license. Please see the file "LICENSE" for more ...
""" exceptions.py: exceptions defined by textform Authors ------- Michael Hucka <mhucka@caltech.edu> -- Caltech Library Copyright --------- Copyright (c) 2020 by the California Institute of Technology. This code is open-source software released under a 3-clause BSD license. Please see the file "LICENSE" for more ...
#Written for Python 3.4.2 data = [line.rstrip('\n') for line in open("input.txt")] blacklist = ["ab", "cd", "pq", "xy"] vowels = ['a', 'e', 'i', 'o', 'u'] def contains(string, samples): for sample in samples: if string.find(sample) > -1: return True return False def isNicePart1(string): ...
data = [line.rstrip('\n') for line in open('input.txt')] blacklist = ['ab', 'cd', 'pq', 'xy'] vowels = ['a', 'e', 'i', 'o', 'u'] def contains(string, samples): for sample in samples: if string.find(sample) > -1: return True return False def is_nice_part1(string): if contains(string, bl...
class MyStr(str): def __format__(self, *args, **kwargs): print("my format") return str.__format__(self, *args, **kwargs) def __mod__(self, *args, **kwargs): print("mod") return str.__mod__(self, *args, **kwargs) if __name__ == "__main__": ms = MyStr("- %s - {} -") prin...
class Mystr(str): def __format__(self, *args, **kwargs): print('my format') return str.__format__(self, *args, **kwargs) def __mod__(self, *args, **kwargs): print('mod') return str.__mod__(self, *args, **kwargs) if __name__ == '__main__': ms = my_str('- %s - {} -') prin...
# # AGENT # Sanjin # # STRATEGY # This agent always defects, if the opponent defected too often. Otherwise it cooperates. # def getGameLength(history): return history.shape[1] def getChoice(snitch): return "tell truth" if snitch else "stay silent" def strategy(history, memory): if getGameLength(history...
def get_game_length(history): return history.shape[1] def get_choice(snitch): return 'tell truth' if snitch else 'stay silent' def strategy(history, memory): if get_game_length(history) == 0: return (get_choice(False), None) average = sum(history[1]) / history.shape[1] snitch = average <= ...
VERSION = (0, 1) YFANTASY_MAIN = 'yfantasy' def get_package_version(): return '%s.%s' % (VERSION[0], VERSION[1])
version = (0, 1) yfantasy_main = 'yfantasy' def get_package_version(): return '%s.%s' % (VERSION[0], VERSION[1])
nums = [] with open("day1_input", "r") as f: for line in f: nums.append(int(line)) # part 1 # for numA in nums: # for numB in nums: # # find two entries that sum to 2020: # if (numA + numB == 2020): # print(numA, numB) # # their product is: # print(...
nums = [] with open('day1_input', 'r') as f: for line in f: nums.append(int(line)) for num_a in nums: for num_b in nums: for num_c in nums: if numA + numB + numC == 2020: print(numA, numB, numC) print(numA * numB * numC)
text = input("Enter A sentence: ") bad_words = [BADWORDSHERE] for words in bad_words: if words in text: text_length = len(words) hide_word = "*" * text_length text = text.replace(words, hide_word) print(text)
text = input('Enter A sentence: ') bad_words = [BADWORDSHERE] for words in bad_words: if words in text: text_length = len(words) hide_word = '*' * text_length text = text.replace(words, hide_word) print(text)
Clock.clear() # controll ####################################################### Clock.bpm = 120 Scale.default = Scale.chromatic Root.default = 0 p1 >> keys( [4,6,11,13,16,18,23,25] ,dur=[0.25] ,oct=4 ,vibdepth=0.3 ,vib=0.01 ) p2 >> blip( [4,6,11,13,15,16,18,23,25] ,dur=[0.25] ,oct=...
Clock.clear() Clock.bpm = 120 Scale.default = Scale.chromatic Root.default = 0 p1 >> keys([4, 6, 11, 13, 16, 18, 23, 25], dur=[0.25], oct=4, vibdepth=0.3, vib=0.01) p2 >> blip([4, 6, 11, 13, 15, 16, 18, 23, 25], dur=[0.25], oct=3, sus=2, vibdepth=0.3, vib=0.01, amp=0.35) p3 >> bass([(11, 16), [(11, 16, 18), (11, 16, 23...