content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#Task https://adventofcode.com/2020/day/2
inputExample = [['2-3','r','rrnr'],
['5-10','n','ltnnnknnvcnnn'],
['7-9','p','jtpptpllpj'],
['2-5','s','slssssszssssssss'],
['16-17','d','dddddddddddddddlp'],
['2-5','q','bbwqqbkmdhqmjhn'],
['7-10','m','qmpgmmsmmmmkmmkj'],
['1-3','a','abcde'],
['4-7','g','vczggdgbgxg... | input_example = [['2-3', 'r', 'rrnr'], ['5-10', 'n', 'ltnnnknnvcnnn'], ['7-9', 'p', 'jtpptpllpj'], ['2-5', 's', 'slssssszssssssss'], ['16-17', 'd', 'dddddddddddddddlp'], ['2-5', 'q', 'bbwqqbkmdhqmjhn'], ['7-10', 'm', 'qmpgmmsmmmmkmmkj'], ['1-3', 'a', 'abcde'], ['4-7', 'g', 'vczggdgbgxgg']]
def get_valid_passwords(inpu... |
#!/usr/bin/env python
# coding: utf-8
class tokenargs(object):
'''Wraps builtin list with checks for illegal characters in token arguments.'''
# Disallow these characters inside token arguments
illegal = '[]:'
# Replace simple inputs with illegal characters with their legal equivalents
re... | class Tokenargs(object):
"""Wraps builtin list with checks for illegal characters in token arguments."""
illegal = '[]:'
replace = {"':'": '58', "'['": '91', "']'": '93'}
def __init__(self, items=None):
"""Construct a new list of token arguments."""
self.list = list()
if items i... |
#
# PySNMP MIB module SAF-IPRADIO (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SAF-IPRADIO
# Produced by pysmi-0.3.4 at Wed May 1 14:59:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
gopen = open('namecheck.txt' , 'w')
for i in range(1,54):
fopen = open('%d' % i, 'r')
for z in range(100):
rline = fopen.readline()
if rline:
rlist = rline.split('$')
name = rlist[0].strip()
clg = rlist[1].strip()
nlist = name.split(' ')
if len(nlist)==1:
gopen.write('%s, %s \n' % (name,clg))
... | gopen = open('namecheck.txt', 'w')
for i in range(1, 54):
fopen = open('%d' % i, 'r')
for z in range(100):
rline = fopen.readline()
if rline:
rlist = rline.split('$')
name = rlist[0].strip()
clg = rlist[1].strip()
nlist = name.split(' ')
... |
class RectCoordinates:
def __init__(self, x, y, w, h):
self.startX = int(x)
self.startY = int(y)
self.w = int(w)
self.h = int(h)
self.endY = int(y + h)
self.endX = int(x + w)
def get_frame(self, frame):
return frame[self.startY:self.endY, self.startX:self... | class Rectcoordinates:
def __init__(self, x, y, w, h):
self.startX = int(x)
self.startY = int(y)
self.w = int(w)
self.h = int(h)
self.endY = int(y + h)
self.endX = int(x + w)
def get_frame(self, frame):
return frame[self.startY:self.endY, self.startX:sel... |
# Reading lines from file and putting from a list to a dict
dna = dict()
contents = []
for line in open('rosalind_gc.txt', 'r').readlines():
contents.append(line.strip('\n'))
if line[0] == '>':
header = line[1:].rstrip()
dna[header] = ''
else:
dna[header] = dna.get(header) + line.rst... | dna = dict()
contents = []
for line in open('rosalind_gc.txt', 'r').readlines():
contents.append(line.strip('\n'))
if line[0] == '>':
header = line[1:].rstrip()
dna[header] = ''
else:
dna[header] = dna.get(header) + line.rstrip()
greather = ['', 0, '']
for key in dna:
gc_qtd = 0
... |
#!/usr/bin/python
# Filename: func_default.py
def say(message='3',times=1):
print (message * times)
say();
say(times=11)
say('Hello')
say('World',5)
say(2,4)
| def say(message='3', times=1):
print(message * times)
say()
say(times=11)
say('Hello')
say('World', 5)
say(2, 4) |
def negate_condition(condition: callable):
def _f(context):
return not condition(context)
return _f
def dummy(context: dict) -> dict:
return context
class Transition:
def __init__(self, next_state: object, condition: callable, callback: callable = dummy):
self.next_state = next_stat... | def negate_condition(condition: callable):
def _f(context):
return not condition(context)
return _f
def dummy(context: dict) -> dict:
return context
class Transition:
def __init__(self, next_state: object, condition: callable, callback: callable=dummy):
self.next_state = next_state
... |
# python3
def compute_min_number_of_refills(d, m, stops):
assert 1 <= d <= 10 ** 5
assert 1 <= m <= 400
assert 1 <= len(stops) <= 300
assert 0 < stops[0] and all(stops[i] < stops[i + 1] for i in range(len(stops) - 1)) and stops[-1] < d
count = 0
curr = 0
stops.insert(0, 0)
stops.appen... | def compute_min_number_of_refills(d, m, stops):
assert 1 <= d <= 10 ** 5
assert 1 <= m <= 400
assert 1 <= len(stops) <= 300
assert 0 < stops[0] and all((stops[i] < stops[i + 1] for i in range(len(stops) - 1))) and (stops[-1] < d)
count = 0
curr = 0
stops.insert(0, 0)
stops.append(d)
... |
def applicant_selector(gpa,ps_score,ec_count):
message = "This applicant should be rejected."
if (gpa >= 3):
if (ps_score >= 90):
if (ec_count >= 3):
message = "This applicant should be accepted."
else:
message = "This applicant should be given an in-person interview."
return messag... | def applicant_selector(gpa, ps_score, ec_count):
message = 'This applicant should be rejected.'
if gpa >= 3:
if ps_score >= 90:
if ec_count >= 3:
message = 'This applicant should be accepted.'
else:
message = 'This applicant should be given an in-p... |
# lc551.py
# LeetCode 551. Student Attendance Record I `E`
# acc | 91% | 13'
# A~0f27
class Solution:
def checkRecord(self, s: str) -> bool:
a = 0
l = 0
for c in s:
if c == "L":
l += 1
if l > 2:
return False
else:... | class Solution:
def check_record(self, s: str) -> bool:
a = 0
l = 0
for c in s:
if c == 'L':
l += 1
if l > 2:
return False
else:
l = 0
if c == 'A':
a += 1
... |
inp = input()
def palin(inp):
if len(inp)==1: return True
elif len(inp)==2: return inp[0]==inp[1]
else: return inp[0]==inp[-1] and palin(inp[1:-1])
if palin(inp): print('PALINDROME')
else: print('NOT PALINDROME') | inp = input()
def palin(inp):
if len(inp) == 1:
return True
elif len(inp) == 2:
return inp[0] == inp[1]
else:
return inp[0] == inp[-1] and palin(inp[1:-1])
if palin(inp):
print('PALINDROME')
else:
print('NOT PALINDROME') |
def bazel_toolchains_repositories():
org_chromium_clang_mac()
org_chromium_clang_linux_x64()
org_chromium_sysroot_linux_x64()
org_chromium_binutils_linux_x64()
org_chromium_libcxx()
org_chromium_libcxxabi()
def org_chromium_clang_mac():
native.new_http_archive(
name = 'org_chromium_... | def bazel_toolchains_repositories():
org_chromium_clang_mac()
org_chromium_clang_linux_x64()
org_chromium_sysroot_linux_x64()
org_chromium_binutils_linux_x64()
org_chromium_libcxx()
org_chromium_libcxxabi()
def org_chromium_clang_mac():
native.new_http_archive(name='org_chromium_clang_mac',... |
# This file contains the set of rules of basic
# defining the constants
DIGITS = '0123456789'
# defining the token types
TOKEN_INT = 'INT'
TOKEN_FLOAT = 'FLOAT'
TOKEN_PLUS = 'PLUS'
TOKEN_MULTI = 'MUL'
TOKEN_MINUS = 'MINUS'
TOKEN_DIVIDE = 'DIV'
TOKEN_LPAREN = 'LPAREN' # left parenthesis
TOKEN_RPAREN = 'RP... | digits = '0123456789'
token_int = 'INT'
token_float = 'FLOAT'
token_plus = 'PLUS'
token_multi = 'MUL'
token_minus = 'MINUS'
token_divide = 'DIV'
token_lparen = 'LPAREN'
token_rparen = 'RPAREN'
class Position:
def __init__(self, indx, line, column, file_name, file_txt):
self.indx = indx
self.line =... |
{
"targets": [{
"target_name": "ui",
"include_dirs": ["<(module_root_dir)/src/includes", "<(module_root_dir)"],
"sources": [
'<!@(node tools/list-sources.js)'
],
"conditions": [
["OS=='win'", {
"libraries": [
"<(module_root_dir)/libui.lib"
]
}],
["OS=='linux'", {
"cflags": ["-fvi... | {'targets': [{'target_name': 'ui', 'include_dirs': ['<(module_root_dir)/src/includes', '<(module_root_dir)'], 'sources': ['<!@(node tools/list-sources.js)'], 'conditions': [["OS=='win'", {'libraries': ['<(module_root_dir)/libui.lib']}], ["OS=='linux'", {'cflags': ['-fvisibility=hidden', '-std=gnu11'], 'ldflags': ["-Wl,... |
class Solution:
# Sorting key function (Accepted), O(n log n) time, O(n) space
def sortByBits(self, arr: List[int]) -> List[int]:
def tup(n):
return (bin(n).count('1'), n)
return sorted(arr, key=tup)
# One Liner (Top Voted), O(n log n) time, O(n) space
def sortByBits(self, A... | class Solution:
def sort_by_bits(self, arr: List[int]) -> List[int]:
def tup(n):
return (bin(n).count('1'), n)
return sorted(arr, key=tup)
def sort_by_bits(self, A):
return sorted(A, key=lambda a: (bin(a).count('1'), a)) |
#
# PySNMP MIB module STN-CHASSIS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STN-CHASSIS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:03:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) ... |
# Python returning values
def withdraw_money(current_bal, amount):
if(current_bal >= amount):
current_bal -= amount
return current_bal
balance = withdraw_money(100, 20)
if (balance >= 50):
print(f"The balance is {balance}.")
else:
print("You need to make a deposit.")
| def withdraw_money(current_bal, amount):
if current_bal >= amount:
current_bal -= amount
return current_bal
balance = withdraw_money(100, 20)
if balance >= 50:
print(f'The balance is {balance}.')
else:
print('You need to make a deposit.') |
while True:
n = int(input("Height: "))
width = n
if n > 0 and n <= 8:
break
for num_of_hashes in range(1, n + 1):
num_of_spaces = n - num_of_hashes
print(" " * num_of_spaces, end="")
print("#" * num_of_hashes, end="")
print(" ", end="")
print("#" * num_of_hashes)
| while True:
n = int(input('Height: '))
width = n
if n > 0 and n <= 8:
break
for num_of_hashes in range(1, n + 1):
num_of_spaces = n - num_of_hashes
print(' ' * num_of_spaces, end='')
print('#' * num_of_hashes, end='')
print(' ', end='')
print('#' * num_of_hashes) |
class Events:
# REPL to USER EVENTS
INP = 'inp'
OUT = 'out'
ERR = 'err'
HTML = 'html'
EXC = 'exc'
PONG = 'pong'
PATH = 'path'
DONE = 'ended'
STARTED = 'started'
FORKED = 'forked'
# REPL <-> USER EVENTS
NOINT = 'noint'
# USER to REPL EVENTS
WRT = 'wrt'
RU... | class Events:
inp = 'inp'
out = 'out'
err = 'err'
html = 'html'
exc = 'exc'
pong = 'pong'
path = 'path'
done = 'ended'
started = 'started'
forked = 'forked'
noint = 'noint'
wrt = 'wrt'
run = 'run'
ping = 'ping'
fork = 'fork'
def encode(event, data=''):
re... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... | def test():
assert 'junk_drawer' in __solution__, "Make sure you are naming your object 'junk_drawer'"
assert 'drawer_length' in __solution__, "Make sure you are naming your object 'drawer_length'"
assert 'cleaned_junk_drawer' in __solution__, "Make sure you are naming your object 'cleaned_junk_drawer'"
... |
# Runtime Average-case: Theta(n^2)
# Runtime Best-case (already sorted): O(n)
# Runtime Worst-case (reserve sorted): Theta(n^2)
# In Place: Yes
# Stable: Yes
def insertion_sort(a):
for j in range(1, len(a)):
key = a[j]
# start with element before and keep going back
i = j - 1
whil... | def insertion_sort(a):
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0 and key < a[i]:
a[i + 1] = a[i]
i = i - 1
a[i + 1] = key
a = [4, 6, 8, 9, 3, 5, 1]
insertion_sort(a)
print(a) |
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if not node: return None
... | class Solution:
def clone_graph(self, node):
if not node:
return None
res = undirected_graph_node(node.label)
seen = {node.label: res}
self.helper(node, res, seen)
return res
def helper(self, node, answer, seen):
seen[answer.label] = answer
f... |
squares = [1, 4, 9, 16, 25]
print(squares)
print(squares[0]) #Get first value; remember index offset
print(squares[-1]) #Get last value in sequence
print(squares[2:4]) #Return slice of list
squares.append(54) #Add new value
print(squares)
squares[3] = 88 #Insert new value
print(squares)
| squares = [1, 4, 9, 16, 25]
print(squares)
print(squares[0])
print(squares[-1])
print(squares[2:4])
squares.append(54)
print(squares)
squares[3] = 88
print(squares) |
# ### Problem 3
# Given 2 lists of claim numbers, write the code to merge the 2 lists provided to produce a new list by alternating values between the 2 lists. Once the merge has been completed, print the new list of claim numbers (DO NOT just print the array variable!)
# ```
# # Start with these lists
# list_of_claim_... | nums1 = [2, 4, 6, 8, 10]
nums2 = [1, 3, 5, 7, 9]
numall = []
for x in range(0, len(nums1)):
numall.append(nums1[x])
numall.append(nums2[x])
print(numall) |
class OffsetMissingInIndex(Exception):
pass
class CouldNotFindOffset(Exception):
pass
class LogSizeExceeded(Exception):
pass
| class Offsetmissinginindex(Exception):
pass
class Couldnotfindoffset(Exception):
pass
class Logsizeexceeded(Exception):
pass |
print("Welcome to the F.A.T C.A.T program, this program encrypts messages using the reverse cipher method") #Prints whats in the parenteses
sentence = input("What do you want to encrypt? ") #Declares a varible and stores what the user inputs
final = ""
i = len(sentence) -1
while(i != -1):
final+= sentence[i];
i... | print('Welcome to the F.A.T C.A.T program, this program encrypts messages using the reverse cipher method')
sentence = input('What do you want to encrypt? ')
final = ''
i = len(sentence) - 1
while i != -1:
final += sentence[i]
i -= 1
print(final) |
def sum_series(generator, n):
return sum(generator(i) for i in range(n))
def series(generator, n):
return [generator(i) for i in range(n)]
def search_bordered_sum_series(generator_fabric, n, left_x, right_x, border, epsilon=0.01**5):
left_y = sum_series(generator_fabric(left_x), n)
right_y = sum_s... | def sum_series(generator, n):
return sum((generator(i) for i in range(n)))
def series(generator, n):
return [generator(i) for i in range(n)]
def search_bordered_sum_series(generator_fabric, n, left_x, right_x, border, epsilon=0.01 ** 5):
left_y = sum_series(generator_fabric(left_x), n)
right_y = sum_s... |
computation_config = {
'Variable': 'GV1',
'From': ['WB API'],
'files': ['GV1_WB.csv'],
'function': lambda df, var: df.groupby(['ISO']).transform(lambda x: x.rolling(5, 1).mean()),#.mean(axis=1),
'sub_variables': [
'Adjusted net savings, including particulate emission damage (% of GNI)',
... | computation_config = {'Variable': 'GV1', 'From': ['WB API'], 'files': ['GV1_WB.csv'], 'function': lambda df, var: df.groupby(['ISO']).transform(lambda x: x.rolling(5, 1).mean()), 'sub_variables': ['Adjusted net savings, including particulate emission damage (% of GNI)'], 'Description': lambda var: f'{var[0]} 5 years ro... |
# DomirScire
class Animal:
def __init__(self, color, number_of_legs):
self.species = self.__class__.__name__
self.color = color
self.number_of_legs = number_of_legs
def __repr__(self):
return f'{self.color} {self.species}, {self.number_of_legs} legs'
class Wolf(Animal):
de... | class Animal:
def __init__(self, color, number_of_legs):
self.species = self.__class__.__name__
self.color = color
self.number_of_legs = number_of_legs
def __repr__(self):
return f'{self.color} {self.species}, {self.number_of_legs} legs'
class Wolf(Animal):
def __init__(s... |
TRAIN = False
USERS = {
'yuncam':'aBc1to3'
}
| train = False
users = {'yuncam': 'aBc1to3'} |
##function 'return_list' goes here
def return_list(the_string):
new_list = []
the_string = the_string.replace(" ",",")
the_string = the_string.split(",")
if len(the_string) == 1:
return the_string[0]
else:
for x in range(len(the_string)):
new_list.append(the_string[x... | def return_list(the_string):
new_list = []
the_string = the_string.replace(' ', ',')
the_string = the_string.split(',')
if len(the_string) == 1:
return the_string[0]
else:
for x in range(len(the_string)):
new_list.append(the_string[x])
return new_list
def main():... |
class Option:
OPTION_ENABLE = 256
OPTION_TX_ABORT = 1024
OPTION_HIGH_PRIORITY = 2048
| class Option:
option_enable = 256
option_tx_abort = 1024
option_high_priority = 2048 |
#BFS or Breadth First Search is a traversal algorithm for a tree or graph, where we start from the root node(for a tree)
#And visit all the nodes level by level from left to right. It requires us to keep track of the chiildren of each node we visit
#In a queue, so that after traversal through a level is complete, our a... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Bst:
def __init__(self):
self.root = None
self.number_of_nodes = 0
def insert(self, data):
new_node = node(data)
if self.root == None:
self.... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
curr_level = [cloned]
while... | class Solution:
def get_target_copy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
curr_level = [cloned]
while curr_level:
next_level = []
for node in curr_level:
if node.val == target.val:
return node
... |
# Demo Python Tuples
'''
Create Tuple With One Item
To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.
'''
# One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(t... | """
Create Tuple With One Item
To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.
"""
thistuple = ('apple',)
print(type(thistuple))
thistuple = 'apple'
print(type(thistuple)) |
# Copyright 2017 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
DEPS = [
'properties',
'step',
'url',
]
def RunSteps(api):
api.url.validate_url(api.properties['url_to_validate'])
def GenTests(api):
... | deps = ['properties', 'step', 'url']
def run_steps(api):
api.url.validate_url(api.properties['url_to_validate'])
def gen_tests(api):
yield (api.test('basic') + api.properties(url_to_validate='https://example.com'))
yield (api.test('no_scheme') + api.properties(url_to_validate='example.com') + api.expect_e... |
#!/usr/bin/env python
def plain_merge(array_a: list, array_b: list) -> list:
pointer_a, pointer_b = 0, 0
length_a, length_b = len(array_a), len(array_b)
result = []
while pointer_a < length_a and pointer_b < length_b:
if array_a[pointer_a] <= array_b[pointer_b]:
result.append(arr... | def plain_merge(array_a: list, array_b: list) -> list:
(pointer_a, pointer_b) = (0, 0)
(length_a, length_b) = (len(array_a), len(array_b))
result = []
while pointer_a < length_a and pointer_b < length_b:
if array_a[pointer_a] <= array_b[pointer_b]:
result.append(array_a[pointer_a])
... |
x={"a","b","c"}
y=(1,2,3)
z=[4,5,2]
print(type(x));
print(type(y));
print(type(z));
x.add("d")
print(x)
z.append(5)
print(y)
print(z)
for i in x:
print (i)
if 5 in z:
print("yes")
x.remove("b")
print(x)
z.remove(4)
print(z)
z.insert(1,7)
print(z)
z.extend(y)
print(z)
print(z.count(2))
del... | x = {'a', 'b', 'c'}
y = (1, 2, 3)
z = [4, 5, 2]
print(type(x))
print(type(y))
print(type(z))
x.add('d')
print(x)
z.append(5)
print(y)
print(z)
for i in x:
print(i)
if 5 in z:
print('yes')
x.remove('b')
print(x)
z.remove(4)
print(z)
z.insert(1, 7)
print(z)
z.extend(y)
print(z)
print(z.count(2))
del y
print(y) |
first = ord('A')
last = ord('Z')
for i in range(first, last + 1):
for j in range(last, first - 1, -1):
if j <= i:
print(chr(i), end=' ')
else:
print('', end=' ')
print()
| first = ord('A')
last = ord('Z')
for i in range(first, last + 1):
for j in range(last, first - 1, -1):
if j <= i:
print(chr(i), end=' ')
else:
print('', end=' ')
print() |
coordinates_01EE00 = ((123, 116),
(123, 124), (123, 127), (123, 128), (123, 136), (123, 137), (124, 115), (124, 117), (124, 119), (124, 120), (124, 121), (124, 122), (124, 130), (124, 134), (124, 135), (124, 138), (125, 114), (125, 116), (125, 124), (125, 125), (125, 126), (125, 127), (125, 128), (125, 131), (125, 13... | coordinates_01_ee00 = ((123, 116), (123, 124), (123, 127), (123, 128), (123, 136), (123, 137), (124, 115), (124, 117), (124, 119), (124, 120), (124, 121), (124, 122), (124, 130), (124, 134), (124, 135), (124, 138), (125, 114), (125, 116), (125, 124), (125, 125), (125, 126), (125, 127), (125, 128), (125, 131), (125, 132... |
# -*- coding: utf-8 -*-
Consent_form_Out = { # From Operator_CR to UI
"source": {
"service_id": "String",
"rs_id": "String",
"dataset": [
{
"dataset_id": "String",
"title": "String",
"description": "String",
"keywor... | consent_form__out = {'source': {'service_id': 'String', 'rs_id': 'String', 'dataset': [{'dataset_id': 'String', 'title': 'String', 'description': 'String', 'keyword': [], 'publisher': 'String', 'distribution': {'distribution_id': 'String', 'access_url': 'String'}, 'component_specification_label': 'String', 'selected': ... |
class Adapter(object):
def __init__(self):
self.interfaces = []
| class Adapter(object):
def __init__(self):
self.interfaces = [] |
with open("10.in") as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
# Part 1
luc = {"(": ")", ")": "(", "[": "]", "]": "[",
"{": "}", "}": "{", "<": ">", ">": "<"}
lup = {")": 3, "]": 57, "}": 1197, ">": 25137}
score = 0
for line in lines:
stack = []
for i in range(0,... | with open('10.in') as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
luc = {'(': ')', ')': '(', '[': ']', ']': '[', '{': '}', '}': '{', '<': '>', '>': '<'}
lup = {')': 3, ']': 57, '}': 1197, '>': 25137}
score = 0
for line in lines:
stack = []
for i in range(0, len(line)):
... |
__all__ = [
'config_enums',
'feed_enums',
'file_enums'
]
| __all__ = ['config_enums', 'feed_enums', 'file_enums'] |
#Flag
#Use a flag that stores on the nodes to know if we visited or not.
#time: O(N).
#space: O(N), for each node we use O(1) and there are N nodes.
class Solution(object):
def detectCycle(self, head):
curr = head
while curr:
if hasattr(curr, 'visited') and curr.visited: return curr
... | class Solution(object):
def detect_cycle(self, head):
curr = head
while curr:
if hasattr(curr, 'visited') and curr.visited:
return curr
curr.visited = True
curr = curr.next
return None
class Solution(object):
def detect_cycle(self, h... |
class Solution:
def binarySearchableNumbers(self, nums: List[int]) -> int:
maximums = [nums[0]] # from the left
minimums = [0] * len(nums) # from the right
min_n = nums[-1]
result = 0
for n in nums[1::]:
maximums.append(max(maximums[-1], n))
... | class Solution:
def binary_searchable_numbers(self, nums: List[int]) -> int:
maximums = [nums[0]]
minimums = [0] * len(nums)
min_n = nums[-1]
result = 0
for n in nums[1:]:
maximums.append(max(maximums[-1], n))
for idx in range(len(nums) - 1, -1, -1):
... |
# def candies(s): # worst case = three passes of 's', len, max, sum
# length = len(s)
# if length <= 1:
# return -1
# return max(s) * length - sum(s)
def candies(seq):
length = 0
maximum = 0
total = 0
for i, a in enumerate(seq):
try:
current = int(a)
ex... | def candies(seq):
length = 0
maximum = 0
total = 0
for (i, a) in enumerate(seq):
try:
current = int(a)
except TypeError:
return -1
length += 1
total += current
if current > maximum:
maximum = current
return maximum * length ... |
def convert2meter(s, input_unit="in"):
'''
Function to convert inches, feet and cubic feet to meters and cubic meters
'''
if input_unit == "in":
return s*0.0254
elif input_unit == "ft":
return s*0.3048
elif input_unit == "cft":
return s*0.0283168
else:
print(... | def convert2meter(s, input_unit='in'):
"""
Function to convert inches, feet and cubic feet to meters and cubic meters
"""
if input_unit == 'in':
return s * 0.0254
elif input_unit == 'ft':
return s * 0.3048
elif input_unit == 'cft':
return s * 0.0283168
else:
... |
# [Stone Colusses] It Ain't Natural
CHIEF_TATOMO = 2081000
sm.setSpeakerID(CHIEF_TATOMO)
sm.sendNext("Well, you don't look like you just spoke to an ancient nature spirit, but I suppose we'll know soon enough. "
"Are you ready for a little adventure?\r\n\r\n"
"#bYou know it! How do I get to th... | chief_tatomo = 2081000
sm.setSpeakerID(CHIEF_TATOMO)
sm.sendNext("Well, you don't look like you just spoke to an ancient nature spirit, but I suppose we'll know soon enough. Are you ready for a little adventure?\r\n\r\n#bYou know it! How do I get to the Stone Colossus?")
sm.sendSay('Ah, humans. No patience, and not eno... |
# a = [1,2,2,3,4,5]
# # print(list(set(a)))
# def correct_list(a):
# return(list(set(a)))
# print(correct_list(a))
a = [1,2,2,3,4,5]
def correct_list(a):
s = []
for i in a:
if i not in s:
s.append(i)
return(s)
print(correct_list(a)) | a = [1, 2, 2, 3, 4, 5]
def correct_list(a):
s = []
for i in a:
if i not in s:
s.append(i)
return s
print(correct_list(a)) |
'''
Title: %s
Given: %s
Return %s
Sample Dataset: %s
Sample Output: %s
'''
def compute():
pass
if __name__ == "__main__":
pass
| """
Title: %s
Given: %s
Return %s
Sample Dataset: %s
Sample Output: %s
"""
def compute():
pass
if __name__ == '__main__':
pass |
# encoding: utf-8
##################################################
# This script shows an example of a header section. This sections is a group of commented lines (lines starting with
# the "#" character) that describes general features of the script such as the type of licence (defined by the
# developer), authors,... | print('tuples are very similar to lists')
print('the are defined by ()')
my_tuple = (1, 2, 3)
print(my_tuple)
data_type = type(my_tuple)
print(data_type, '\n')
print('tuples can have different data types as items')
my_tuple = ('One', 'Two', 3)
print(my_tuple, '\n')
print('you can use indexing and slicing for tuples')
p... |
def result(text):
count=0
for i in range(len(metin)):
if(ord(metin[i])>=65 and ord(metin[i])<=90):
count=count+1
return count
| def result(text):
count = 0
for i in range(len(metin)):
if ord(metin[i]) >= 65 and ord(metin[i]) <= 90:
count = count + 1
return count |
def genTest():
print('Block of code before first yield statement')
yield 1
print('Block of code after first yield statement and before second yield statement')
yield 2
print('Block of code after all yield statements')
# foo = genTest returns <function gen at 0x101faf400>
foo = genTest() # retu... | def gen_test():
print('Block of code before first yield statement')
yield 1
print('Block of code after first yield statement and before second yield statement')
yield 2
print('Block of code after all yield statements')
foo = gen_test()
print(foo.__next__())
print()
print(foo.__next__())
print('\n')
... |
class PropertyReference:
def __init__(self, var_name, property_name):
self.var_name = var_name
self.property_name = property_name
def __str__(self):
return f'{self.var_name}.{self.property_name}'
def code_gen_string(self):
return str(self)
class FunctionCallArgument:
... | class Propertyreference:
def __init__(self, var_name, property_name):
self.var_name = var_name
self.property_name = property_name
def __str__(self):
return f'{self.var_name}.{self.property_name}'
def code_gen_string(self):
return str(self)
class Functioncallargument:
... |
##Retrieve region of sequences delimited by a forward and reverse pattern
#v0.0.1
f = [ [x.split('\n')[0], ''.join(x.split('\n')[1:])] for x in open('gg-13-8-99.fasta', 'r').read().rstrip('\n').split('>') ][1:]
fw = ['AGAGTTTGATCMTGGCTCAG']
rv = ['GWATTACCGCGGCKGCTG']
mtol = 1
endstr = 3
w = open('ggmb.fa', 'w')
nl = ... | f = [[x.split('\n')[0], ''.join(x.split('\n')[1:])] for x in open('gg-13-8-99.fasta', 'r').read().rstrip('\n').split('>')][1:]
fw = ['AGAGTTTGATCMTGGCTCAG']
rv = ['GWATTACCGCGGCKGCTG']
mtol = 1
endstr = 3
w = open('ggmb.fa', 'w')
nl = []
print('Forward:' + fw[0])
print('Reverse:' + rv[0])
print('Mismatches tolerated:' ... |
def say(message, times = 1):
print(message * times)
say('Hello', 4)
say('World', 4)
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3)
func(3, c=13)
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
retur... | def say(message, times=1):
print(message * times)
say('Hello', 4)
say('World', 4)
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3)
func(3, c=13)
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
a ... |
# write program reading an integer from standard input - a
# printing sum of squares of natural numbers smaller than a
# for example, for a=4, result = 1*1 + 2*2 + 3*3 = 14
a = int(input("pass a - "))
element = 1
result = 0
while element < a:
result = result + element * element
element = element + 1
print("... | a = int(input('pass a - '))
element = 1
result = 0
while element < a:
result = result + element * element
element = element + 1
print('result = ' + str(result)) |
# implement strip() to remove the white spaces in the head and tail of a string.
def strip(s):
while len(s) != 0 and (s[0] == ' ' or s[-1] == ' '):
s = s[1:] if s[0] == ' ' else s
s = s[:-1] if s[-1] == ' ' else s
return s
if __name__ == "__main__":
if strip('hello ') != 'hello':
... | def strip(s):
while len(s) != 0 and (s[0] == ' ' or s[-1] == ' '):
s = s[1:] if s[0] == ' ' else s
s = s[:-1] if s[-1] == ' ' else s
return s
if __name__ == '__main__':
if strip('hello ') != 'hello':
print('fail!')
elif strip(' hello') != 'hello':
print('fail!')
eli... |
a = [1,2,3,4,5]
k =2
del a[0]
for i in range(0,len(a)):
print(a[i])
| a = [1, 2, 3, 4, 5]
k = 2
del a[0]
for i in range(0, len(a)):
print(a[i]) |
# Copyright (c) 2018 Lotus Load
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribu... | load('@io_bazel_rules_docker//go:image.bzl', 'go_image')
load('@io_bazel_rules_docker//container:container.bzl', 'container_bundle')
load('@io_bazel_rules_docker//contrib:push-all.bzl', 'docker_push')
def app_image(name, binary, repository, **kwargs):
go_image(name='image', binary=binary, **kwargs)
container_b... |
# working-with-Data-structure
#union
def union(set1,set2):
return set(set1)&(set2)
# driver code
Set1={0,2,3,4,5,6,8}
Set2={1,2,3,4,5}
Print(union(set1,set2))
#intersection
def intersection(set1,set2):
return set(set1)&(set2)
#driver code
Set1={0,2,4,6,8}
Set2={1,2,4,4,5}
Print(intersection(set1,set2))
#diffe... | def union(set1, set2):
return set(set1) & set2
set1 = {0, 2, 3, 4, 5, 6, 8}
set2 = {1, 2, 3, 4, 5}
print(union(set1, set2))
def intersection(set1, set2):
return set(set1) & set2
set1 = {0, 2, 4, 6, 8}
set2 = {1, 2, 4, 4, 5}
print(intersection(set1, set2))
set1 = {0, 2, 3, 4, 5, 6, 8}
set2 = {1, 2, 3, 4, 5}
set... |
class Qint(int):
def __init__(self, num):
self.qkey = None
self.parent = None
self.parental_id = None
self.name = None
self._qint = True
| class Qint(int):
def __init__(self, num):
self.qkey = None
self.parent = None
self.parental_id = None
self.name = None
self._qint = True |
#!/usr/bin/env python
# Analyse des accidents corporels de la circulation a partir des fichiers csv open data
# - telecharger les fichiers csv depuis :
# https://www.data.gouv.fr/en/datasets/bases-de-donnees-annuelles-des-accidents-corporels-de-la-circulation-routiere-annees-de-2005-a-2019/
# - changer la commune et l... | commune = '92012'
annee = 2019
id_acc = []
accidents = {}
gravite = {'1': 'indemne', '2': 'tue', '3': 'grave', '4': 'leger'}
def get_header(line):
h = line.rstrip().replace('"', '').split(';')
h = dict(zip(h, range(len(h))))
return h
with open('caracteristiques-' + str(annee) + '.csv') as f:
head = get... |
# n = int(input('Enter the number of time you want to display Hello World!'))
# i = 0
##While Loop
# while i < n :
# print('Hello World\n')
# x += 1
n = input('Enter a number: ')
#Check if the input is empty
if n == "":
print('Nothing to display')
else:
#For Loop
for i in range(int(n)):
print(... | n = input('Enter a number: ')
if n == '':
print('Nothing to display')
else:
for i in range(int(n)):
print('Hello World!') |
class MenuItem:
pass
# Buat instance untuk class MenuItem
menu_item1 = MenuItem()
| class Menuitem:
pass
menu_item1 = menu_item() |
class FederationClientServiceVariables:
def __init__(self):
self.FederationClientServiceStatus = ''
self.FederationClientServicePort = 9000
self.FederationClientServiceIP = None | class Federationclientservicevariables:
def __init__(self):
self.FederationClientServiceStatus = ''
self.FederationClientServicePort = 9000
self.FederationClientServiceIP = None |
class Format:
def skip(self, line):
False
def before(self, line):
return s, None
def after(self, line, data):
return s
class fastText(Format):
LABEL_PREFIX = '__label__'
def before(self, line):
labels = []
_ = []
for w in line.split(' '):
... | class Format:
def skip(self, line):
False
def before(self, line):
return (s, None)
def after(self, line, data):
return s
class Fasttext(Format):
label_prefix = '__label__'
def before(self, line):
labels = []
_ = []
for w in line.split(' '):
... |
# Time complexity: O(n)
# Approach: Backtracking. Similar to DP 2D array solution.
class Solution:
def findIp(self, s, index, i, tmp, ans):
if i==4:
if index >= len(s):
ans.append(tmp[1:])
return
if index >= len(s):
return
if s[index]=='0'... | class Solution:
def find_ip(self, s, index, i, tmp, ans):
if i == 4:
if index >= len(s):
ans.append(tmp[1:])
return
if index >= len(s):
return
if s[index] == '0':
self.findIp(s, index + 1, i + 1, tmp + '.' + s[index], ans)
... |
# Just to implement while loop
answer = 'no'
while answer != 'yes':
answer = input( 'Are you done?' )
print( 'Finally Exited.' );
| answer = 'no'
while answer != 'yes':
answer = input('Are you done?')
print('Finally Exited.') |
base_tree = [{
'url_delete': 'http://example.com/adminpages/delete/id/1',
'list_of_pk': ('["id", 1]', ),
'id': 1,
'label': u'Hello Traversal World!',
'url_update': 'http://example.com/adminpages/update/id/1',
'children': [{
'url_delete': 'http://example.com/adminpages/delete/id/2',
... | base_tree = [{'url_delete': 'http://example.com/adminpages/delete/id/1', 'list_of_pk': ('["id", 1]',), 'id': 1, 'label': u'Hello Traversal World!', 'url_update': 'http://example.com/adminpages/update/id/1', 'children': [{'url_delete': 'http://example.com/adminpages/delete/id/2', 'list_of_pk': ('["id", 2]',), 'id': 2, '... |
@metadata_reactor
def add_backup_key(metadata):
return {
'users': {
'root': {
'authorized_keys': {
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDM70gDI1cuIKu15VAEYnlWMFi3zGPf6shtQCzrHBv1nOOkfPdXlXACC4H5+MiTV5foAIA8PUaqOV9gow1w639TnWDL2DwPJ5RsT+P5g4eWszW5xQPo0zAKuvlT... | @metadata_reactor
def add_backup_key(metadata):
return {'users': {'root': {'authorized_keys': {'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDM70gDI1cuIKu15VAEYnlWMFi3zGPf6shtQCzrHBv1nOOkfPdXlXACC4H5+MiTV5foAIA8PUaqOV9gow1w639TnWDL2DwPJ5RsT+P5g4eWszW5xQPo0zAKuvlTMB9JkDXGx1OpOE4e9n3++71yuvF/wVlqYxJwxeWXCdHf2ayx6OrTMcSMUIi+... |
# This file mainly exists to allow python setup.py test to work.
# flake8: noqa
def runtests():
pass
if __name__ == '__main__':
runtests()
| def runtests():
pass
if __name__ == '__main__':
runtests() |
line = open("day10.txt", "r").readline()
def day10(iterate, sequence):
for i in range(iterate):
concat = ""
first = True
second = False
sameNumberCounter = 0
secondNum = 0
numCounter = 0
for num in sequence:
numCounter += 1
if second ... | line = open('day10.txt', 'r').readline()
def day10(iterate, sequence):
for i in range(iterate):
concat = ''
first = True
second = False
same_number_counter = 0
second_num = 0
num_counter = 0
for num in sequence:
num_counter += 1
if sec... |
#
# PySNMP MIB module ALCATEL-IND1-IPMS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-IPMS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:02:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (softent_ind1_ipms,) = mibBuilder.importSymbols('ALCATEL-IND1-BASE', 'softentIND1Ipms')
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, cons... |
num = int(input( "Digite um valor de 0 a 9999: "))
num1 = str(num)
num2 = num1.zfill(4)
print('Unidade: {}'.format(num2[3]))
print('Dezena: {}'.format(num2[2]))
print('Centena: {}'.format(num2[1]))
print('Milhar: {}'.format(num2[0]))
| num = int(input('Digite um valor de 0 a 9999: '))
num1 = str(num)
num2 = num1.zfill(4)
print('Unidade: {}'.format(num2[3]))
print('Dezena: {}'.format(num2[2]))
print('Centena: {}'.format(num2[1]))
print('Milhar: {}'.format(num2[0])) |
builder_layers = {
# P-CAD ASCII layer types:
# Signal, Plane, NonSignal
-1: "null", # LT_UNDEFINED
0: "Signal", # LT_SIGNAL
1: "Plane", # LT_POWER
2: "NonSignal", # LT_MIXED
3: "Plane" # LT_JUMPER
}
builder_padshapes = {
# P-CAD ASCII padshape types:
# padViaShapeT... | builder_layers = {-1: 'null', 0: 'Signal', 1: 'Plane', 2: 'NonSignal', 3: 'Plane'}
builder_padshapes = {0: 'Ellipse', 1: 'Rect', 2: 'Oval', 3: '', 4: 'RndRect', 5: '', 6: 'Polygon'}
builder_font_renderer__stroke = 0
builder_font_renderer__true_type = 2
builder_font_family__serif = 0
builder_font_family__sanserif = 1
bu... |
def calc_no(val):
temp = val
s = 0
while temp > 0:
s += temp%10
temp //= 10
return not(val%s)
row = int(input())
arr = [] # storing input values
for i in range(row):
arr.append(list(map(int,input().split())))
bool_tab = [] # storing their resp boolean value if it is divisible by t... | def calc_no(val):
temp = val
s = 0
while temp > 0:
s += temp % 10
temp //= 10
return not val % s
row = int(input())
arr = []
for i in range(row):
arr.append(list(map(int, input().split())))
bool_tab = []
for i in range(row):
x = []
for j in range(len(arr[0])):
x.appen... |
def weather_conditions(temp):
if temp > 7:
print("Warm")
else:
print("Cold")
x = int(input("Enter a temparature"))
weather_conditions(x)
| def weather_conditions(temp):
if temp > 7:
print('Warm')
else:
print('Cold')
x = int(input('Enter a temparature'))
weather_conditions(x) |
T = int(input())
for kase in range(1, T + 1):
n = int(input())
[input() for i in range(0, n + 1)]
if n & 1:
print(f'Case #{kase}: 1\n0.0')
else:
print(f'Case #{kase}: 0') | t = int(input())
for kase in range(1, T + 1):
n = int(input())
[input() for i in range(0, n + 1)]
if n & 1:
print(f'Case #{kase}: 1\n0.0')
else:
print(f'Case #{kase}: 0') |
school_class = {}
while True:
name = input("Enter the student's name: ")
if name == '':
break
score = int(input("Enter the student's score (0-10): "))
if score not in range(0, 11):
break
if name in school_class:
school_class[name] += (score,)
else:
school_... | school_class = {}
while True:
name = input("Enter the student's name: ")
if name == '':
break
score = int(input("Enter the student's score (0-10): "))
if score not in range(0, 11):
break
if name in school_class:
school_class[name] += (score,)
else:
school_class[na... |
with open("day6_input") as infile:
cycles = [[int(x) for x in infile.readline().split('\t') if x != '\n']]
steps = 0
while True:
current_cycle = cycles[-1]
max_ = max(current_cycle)
maxindex = current_cycle.index(max_)
new_cycle = current_cycle[:]
new_cycle[maxindex] = 0
for i in range(maxi... | with open('day6_input') as infile:
cycles = [[int(x) for x in infile.readline().split('\t') if x != '\n']]
steps = 0
while True:
current_cycle = cycles[-1]
max_ = max(current_cycle)
maxindex = current_cycle.index(max_)
new_cycle = current_cycle[:]
new_cycle[maxindex] = 0
for i in range(maxin... |
pattern = []
with open('day_3.txt') as f:
for line in f:
pattern.append([line.rstrip()])
def count_trees(pattern, right, down):
'''Use dictionary to redefine positions outside base pattern,
count all trees in pattern (#) which we meet, when we follow defined number of moves to right and down'''
... | pattern = []
with open('day_3.txt') as f:
for line in f:
pattern.append([line.rstrip()])
def count_trees(pattern, right, down):
"""Use dictionary to redefine positions outside base pattern,
count all trees in pattern (#) which we meet, when we follow defined number of moves to right and down"""
... |
'''
Dictionary that keeps the cost of individual parts of cars.
'''
car_body = {
'Honda' : 500,
'Nissan' : 1000,
'Suzuki' : 600,
'Toyota' : 500
}
car_tyres = {
'Honda' : 1400,
'Nissan' : 500,
'Suzuki' : 600,
'Toyota' : 1000
}
car_doors = {
'Honda' : 400,
'Nissan': 300,
'Su... | """
Dictionary that keeps the cost of individual parts of cars.
"""
car_body = {'Honda': 500, 'Nissan': 1000, 'Suzuki': 600, 'Toyota': 500}
car_tyres = {'Honda': 1400, 'Nissan': 500, 'Suzuki': 600, 'Toyota': 1000}
car_doors = {'Honda': 400, 'Nissan': 300, 'Suzuki': 600, 'Toyota': 800} |
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
missing = []
limit = arr[-1]
nums = set(arr)
for i in range(1,limit):
if i not in nums:
missing.append(i)
if len(missing) >= k:
return missing... | class Solution:
def find_kth_positive(self, arr: List[int], k: int) -> int:
missing = []
limit = arr[-1]
nums = set(arr)
for i in range(1, limit):
if i not in nums:
missing.append(i)
if len(missing) >= k:
return missing[k - 1]
... |
# mendapatkan tagihan bulanan
# selamat satu unit lagi dan anda sudah membuat sebuah program! ketika
# kita bilang anda bisa membuat apa saja dengan python, kita bersungguh-sungguh!
# batas dari apa yang anda bisa bangun adalah di imajinasi anda
# terus belajar ke bab berikutnya dan akhirnya anda akan bisa membuat prog... | """
instruksi
-oke sekarang kita buat variabel
total_tagihan
yang merupakan jumlah dari
sisa_cicilan
dan
jumlah_bunga
-setelahnya kita buat
tagihan_bulanan
yang merupakan
total_tagihan
dibagi
12
-jalankan codenya dan lihat tagihan bulananan anda
-ubah angkanya sesuasi yang anda mau dan bermain mainlah dengan apa yang t... |
def find(n, m, x, y, dx, dy):
if x < 0 or x == 20 or y < 0 or y == 20:
return -1
elif n == 0:
return 1
else:
return m[y][x] * find(n - 1, m, x + dx, y + dy, dx, dy)
directions = [None] * 8
for i in range(0, 8):
if i == 0:
directions[i] = [0, 1]
elif i == 1:
d... | def find(n, m, x, y, dx, dy):
if x < 0 or x == 20 or y < 0 or (y == 20):
return -1
elif n == 0:
return 1
else:
return m[y][x] * find(n - 1, m, x + dx, y + dy, dx, dy)
directions = [None] * 8
for i in range(0, 8):
if i == 0:
directions[i] = [0, 1]
elif i == 1:
... |
cue_words=["call it as",
"call this as",
"called as the",
"call it as",
"referred to as",
"is defined as",
"known as the",
"defined as",
"known as",
"mean by",
"concept of",
"talk about",
"called as",
"called the",
"called an",
"called a",
"call as",
"called"]
| cue_words = ['call it as', 'call this as', 'called as the', 'call it as', 'referred to as', 'is defined as', 'known as the', 'defined as', 'known as', 'mean by', 'concept of', 'talk about', 'called as', 'called the', 'called an', 'called a', 'call as', 'called'] |
def nonrep():
checklist=[]
my_string={"pythonprograming"}
for s in my_string:
if s in my_string:
my_string[s]+=1
else:
my_string=1
checklist.appened(my_string[s])
for s in checklist:
if s==1:
return True
else:
F... | def nonrep():
checklist = []
my_string = {'pythonprograming'}
for s in my_string:
if s in my_string:
my_string[s] += 1
else:
my_string = 1
checklist.appened(my_string[s])
for s in checklist:
if s == 1:
return True
else:
... |
'''
This file contains any primitives for Lyanna that aren't just
borrowed from the language. Basically this is Nothing and Undefined,
which are singletons. That is, their classes are stuck here and only
selected instances are exported through __all__
'''
class NothingType(object):
def __str__(self):
retur... | """
This file contains any primitives for Lyanna that aren't just
borrowed from the language. Basically this is Nothing and Undefined,
which are singletons. That is, their classes are stuck here and only
selected instances are exported through __all__
"""
class Nothingtype(object):
def __str__(self):
retu... |
def settingDecoder(data):
# data can be:
# raw string
# list of strings
data = data.strip()
if (len(data) > 1) and (data[0] == '[') and (data[-1] == ']'):
data = [x.strip() for x in data[1:-1].split(',')]
return data
def loadSetting(filename = "SETTINGS"):
res = dict()
with open... | def setting_decoder(data):
data = data.strip()
if len(data) > 1 and data[0] == '[' and (data[-1] == ']'):
data = [x.strip() for x in data[1:-1].split(',')]
return data
def load_setting(filename='SETTINGS'):
res = dict()
with open(filename, 'r') as f:
for line in f:
sline... |
messages = 'game.apps.core.signals.messages.%s' # user.id
planet = 'game.apps.core.signals.planet_details.%s' # planetID_requestID
account_data = 'game.apps.core.signals.account_data.%s'
building = 'game.apps.core.signals.building.%s' # buildingID
task_updated = 'game.apps.core.signals.task_updated.%s' # user.i... | messages = 'game.apps.core.signals.messages.%s'
planet = 'game.apps.core.signals.planet_details.%s'
account_data = 'game.apps.core.signals.account_data.%s'
building = 'game.apps.core.signals.building.%s'
task_updated = 'game.apps.core.signals.task_updated.%s' |
# 39. Combination Sum
# Time: O((len(candidates))^(target/avg(candidates))) Review
# Space: O(target/avg(candidates))) [depth of recursion tree?]Review
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
self.util(candidates, target, 0 , [], ... | class Solution:
def combination_sum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
self.util(candidates, target, 0, [], result)
return result
def util(self, candidates, target, start, cur_res, result):
if target < 0:
return
if targ... |
class audo:
def __init__(self, form, data = None):
self.form = form
self.values = []
if data:
self.load(data)
def load(self, data):
for i in range(data.readUInt32()):
while (data.offset & 3) != 0:
data.offset += 1
data.push... | class Audo:
def __init__(self, form, data=None):
self.form = form
self.values = []
if data:
self.load(data)
def load(self, data):
for i in range(data.readUInt32()):
while data.offset & 3 != 0:
data.offset += 1
data.push(data.r... |
# Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | ipproto_ip = 0
ipproto_hopopts = 0
ipproto_icmp = 1
ipproto_igmp = 2
ipproto_tcp = 6
ipproto_udp = 17
ipproto_routing = 43
ipproto_fragment = 44
ipproto_gre = 47
ipproto_ah = 51
ipproto_icmpv6 = 58
ipproto_none = 59
ipproto_dstopts = 60
ipproto_ospf = 89
ipproto_vrrp = 112
ipproto_sctp = 132 |
lst = [90, 180, 0]
empty = []
lst.append(empty)
def function_a():
for empty in lst:
if empty in lst:
print(lst)
function_b()
function_b()
print(lst)
def function_b():
for empty in lst:
if empty in lst:
... | lst = [90, 180, 0]
empty = []
lst.append(empty)
def function_a():
for empty in lst:
if empty in lst:
print(lst)
function_b()
function_b()
print(lst)
def function_b():
for empty in lst:
if empty in lst:
print(lst)
function_b()
function... |
def options_displ():
print(
'''
weather now: Displays the current weather
weather today: Displays the weather for this day
weather tenday: Displays weather for next ten days
detailed tenday: Displays ten day weather with extended info
weather -t: Disp... | def options_displ():
print('\n weather now: Displays the current weather\n weather today: Displays the weather for this day\n weather tenday: Displays weather for next ten days\n detailed tenday: Displays ten day weather with extended info\n \n weather -t: Displays current ... |
class TimelineService(object):
@classmethod
def get_timeline(cls, officer_allegations):
allegations_date = officer_allegations\
.values_list('allegation__incident_date_only', 'start_date')\
.order_by('allegation__incident_date')
items = []
for date in allegation... | class Timelineservice(object):
@classmethod
def get_timeline(cls, officer_allegations):
allegations_date = officer_allegations.values_list('allegation__incident_date_only', 'start_date').order_by('allegation__incident_date')
items = []
for date in allegations_date:
if not da... |
l = [int(e) for e in input().split()]
for i in range(1, len(l), 2):
l[i], l[i - 1] = l[i - 1], l[i]
[print(n) for n in l]
| l = [int(e) for e in input().split()]
for i in range(1, len(l), 2):
(l[i], l[i - 1]) = (l[i - 1], l[i])
[print(n) for n in l] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.