content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Question Link : https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/572/week-4-december-22nd-december-28th/3581/
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
dp = [0] * n
if s[0] != '0'... | class Solution(object):
def num_decodings(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
dp = [0] * n
if s[0] != '0':
dp[0] = 1
for i in range(1, n):
if s[i] != '0':
dp[i] += dp[i - 1]
... |
input = open('input', 'r').read().strip()
input = [list(map(int, r)) for r in input.splitlines()]
h, w = len(input), len(input[0])
def neighbours(x, y):
return [(p, q) for u in range(-1, 2) for v in range(-1, 2)
if 0 <= (p := x+u) < h and 0 <= (q := y+v) < w]
def step(m):
m = [[n+1 for n in r] ... | input = open('input', 'r').read().strip()
input = [list(map(int, r)) for r in input.splitlines()]
(h, w) = (len(input), len(input[0]))
def neighbours(x, y):
return [(p, q) for u in range(-1, 2) for v in range(-1, 2) if 0 <= (p := (x + u)) < h and 0 <= (q := (y + v)) < w]
def step(m):
m = [[n + 1 for n in r] f... |
''' Automatically set `current_app` into context based on URL namespace. '''
def namespaced(request):
''' Set `current_app` to url namespace '''
request.current_app = request.resolver_match.namespace
return {}
| """ Automatically set `current_app` into context based on URL namespace. """
def namespaced(request):
""" Set `current_app` to url namespace """
request.current_app = request.resolver_match.namespace
return {} |
# *-* coding:utf-8 *-*
"""Module states Amapa"""
def start(st_reg_number):
"""Checks the number valiaty for the Alagoas state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
if st_reg_number[0:2] != "03":
return False
... | """Module states Amapa"""
def start(st_reg_number):
"""Checks the number valiaty for the Alagoas state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
if st_reg_number[0:2] != '03':
return False
aux = int(st_reg_number[0:le... |
#!/usr/bin/env python
class AssembleError(Exception):
def __init__(self, line_no, reason):
message = '%d: %s' % (line_no, reason)
super(AssembleError, self).__init__(message)
| class Assembleerror(Exception):
def __init__(self, line_no, reason):
message = '%d: %s' % (line_no, reason)
super(AssembleError, self).__init__(message) |
#Boolean is a Data Type in Python which has 2 values - True and False
print (bool(0)) #Python will return False
print (bool(1)) #Python will return True
print (bool(1.5)) #Pyton will return True
print (bool(None)) #Python will return False
print (bool('')) #Python will return False | print(bool(0))
print(bool(1))
print(bool(1.5))
print(bool(None))
print(bool('')) |
n = int(input())
count = 0
for i in range(1, n + 1):
if i < 100:
count += 1
else:
s = str(i)
if int(s[1]) - int(s[0]) == int(s[2]) - int(s[1]):
count += 1
print(count)
| n = int(input())
count = 0
for i in range(1, n + 1):
if i < 100:
count += 1
else:
s = str(i)
if int(s[1]) - int(s[0]) == int(s[2]) - int(s[1]):
count += 1
print(count) |
l1 = list(range(10))
new_list = [x*x + 2*x + 1 for x in l1]
print(l1)
print(new_list)
| l1 = list(range(10))
new_list = [x * x + 2 * x + 1 for x in l1]
print(l1)
print(new_list) |
class Solution:
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n < 2:
return n
dp_ = [1] * n
for idx, num in enumerate(nums):
for i in range(idx-1, -1, -1):
if nums[i] < n... | class Solution:
def length_of_lis(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n < 2:
return n
dp_ = [1] * n
for (idx, num) in enumerate(nums):
for i in range(idx - 1, -1, -1):
if nums... |
# md5 : 2cdb8e874f0950ea17a7135427b4f07d
# sha1 : 73b16f132eb0247ea124b6243ca4109f179e564c
# sha256 : 099b17422e1df0235e024ff5128a60571e72af451e1c59f4d61d3cf32c1539ed
ord_names = {
3: b'mciExecute',
4: b'CloseDriver',
5: b'DefDriverProc',
6: b'DriverCallback',
7: b'DrvGetModuleHandle',
8: b'Get... | ord_names = {3: b'mciExecute', 4: b'CloseDriver', 5: b'DefDriverProc', 6: b'DriverCallback', 7: b'DrvGetModuleHandle', 8: b'GetDriverModuleHandle', 9: b'NotifyCallbackData', 10: b'OpenDriver', 11: b'PlaySound', 12: b'PlaySoundA', 13: b'PlaySoundW', 14: b'SendDriverMessage', 15: b'WOW32DriverCallback', 16: b'WOW32Resolv... |
"""
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
"""
# Definition f... | """
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
"""
class Solution(... |
dados = int(input())
pontos = input()
pontos = pontos.split(' ')
luisa = 0
antonio = 0
pessoa = 0
for vez in pontos:
pessoa += 1
if pessoa == 3:
pessoa = 1
if pessoa == 1:
luisa += int(vez)
elif pessoa == 2:
antonio += int(vez)
if int(vez) == 6 and pessoa == 1:
pe... | dados = int(input())
pontos = input()
pontos = pontos.split(' ')
luisa = 0
antonio = 0
pessoa = 0
for vez in pontos:
pessoa += 1
if pessoa == 3:
pessoa = 1
if pessoa == 1:
luisa += int(vez)
elif pessoa == 2:
antonio += int(vez)
if int(vez) == 6 and pessoa == 1:
pessoa... |
def getCountLetterString(input):
# get range
space_index = input.find(" ")
range = input[0:space_index]
hyphen_index = input.find("-")
start = range[0:hyphen_index]
end = range[hyphen_index + 1:]
# get letter
colon_index = input.find(":")
letter = input[space_index + 1:colon_index]
... | def get_count_letter_string(input):
space_index = input.find(' ')
range = input[0:space_index]
hyphen_index = input.find('-')
start = range[0:hyphen_index]
end = range[hyphen_index + 1:]
colon_index = input.find(':')
letter = input[space_index + 1:colon_index]
password = input[colon_inde... |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/own_data.py',
'../_base_/schedules/schedule_1x_own_data.py', '../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
load_from = 'https://download.openmmlab.com/mmdetection/... | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/own_data.py', '../_base_/schedules/schedule_1x_own_data.py', '../_base_/default_runtime.py']
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
load_from = 'https://download.openmmlab.com/mmdetection/v2.0/retinanet/retinanet_r5... |
# https://leetcode.com/problems/number-of-digit-one/
class Solution:
def countDigitOne(self, n: int) -> int:
result = threshold = 0
divisor = limit = 10
while n // limit > 0:
limit *= 10
while divisor <= limit:
div, mod = divmod(n, divisor)
result... | class Solution:
def count_digit_one(self, n: int) -> int:
result = threshold = 0
divisor = limit = 10
while n // limit > 0:
limit *= 10
while divisor <= limit:
(div, mod) = divmod(n, divisor)
result += div * (divisor // 10)
if mod > th... |
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
bmi = weight/(height**2)
if bmi <= 18.5 :
print(f"you bmi is {bmi}, you are underweight")
elif bmi <=25 :
print(f"you bmi is {bmi}you have a normal weight")
elif bmi <= 30 :
print(f"you bmi is {bmi... | height = float(input('enter your height in m: '))
weight = float(input('enter your weight in kg: '))
bmi = weight / height ** 2
if bmi <= 18.5:
print(f'you bmi is {bmi}, you are underweight')
elif bmi <= 25:
print(f'you bmi is {bmi}you have a normal weight')
elif bmi <= 30:
print(f'you bmi is {bmi}you are s... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 17 09:27:36 2016
@author: tih
"""
def Accounts(Type=None):
User_Pass = {
'NASA': ['', ''],
'GLEAM': ['', ''],
'FTP_WA': ['', ''],
'MSWEP': ['', ''],
'VITO': ['', '']}
Selected_Path = User_Pass[Type]
return(Selected_Path)
| """
Created on Thu Mar 17 09:27:36 2016
@author: tih
"""
def accounts(Type=None):
user__pass = {'NASA': ['', ''], 'GLEAM': ['', ''], 'FTP_WA': ['', ''], 'MSWEP': ['', ''], 'VITO': ['', '']}
selected__path = User_Pass[Type]
return Selected_Path |
script_create_table_tipos = lambda dados = {} : """
DROP TABLE IF EXISTS Tipos;
CREATE TABLE Tipos (
id int NOT NULL PRIMARY KEY,
nome text NOT NULL DEFAULT 'pokemon'
);
"""
script_insert_table_tipos = lambda dados = {} : """INSERT INTO Tipos (id, nome) VALUES (?, ?);"""
dados_padrao_tabel... | script_create_table_tipos = lambda dados={}: "\n DROP TABLE IF EXISTS Tipos;\n\n CREATE TABLE Tipos (\n id int NOT NULL PRIMARY KEY,\n nome text NOT NULL DEFAULT 'pokemon'\n );\n"
script_insert_table_tipos = lambda dados={}: 'INSERT INTO Tipos (id, nome) VALUES (?, ?);'
dados_padrao_tabela_tipos ... |
n, k = map(int,input().split())
cnt = 0
prime = [True]*(n+1)
for i in range(2,n+1,1):
if prime[i] == False: continue
for j in range(i,n+1,i):
if prime[j] == True: prime[j] = False;cnt+=1
if cnt == k: print(j);break | (n, k) = map(int, input().split())
cnt = 0
prime = [True] * (n + 1)
for i in range(2, n + 1, 1):
if prime[i] == False:
continue
for j in range(i, n + 1, i):
if prime[j] == True:
prime[j] = False
cnt += 1
if cnt == k:
print(j)
break |
class TrackData():
def __init__(self):
self.trail_data = None # common dictionary, which is mutable
self.camera_id = None
self.trail_num = 0
self.file_name = None
self.feat_list = []
self.mean_feat = None
self.height = None
self.map_time_stamp = []... | class Trackdata:
def __init__(self):
self.trail_data = None
self.camera_id = None
self.trail_num = 0
self.file_name = None
self.feat_list = []
self.mean_feat = None
self.height = None
self.map_time_stamp = []
self.target_image_path = None
... |
def sum_iter(numbers):
total = 0
for n in numbers:
total = total + n
return total
def sum_rec(numbers):
if len(numbers) == 0:
return 0
return numbers[0] + sum_rec(numbers[1:])
| def sum_iter(numbers):
total = 0
for n in numbers:
total = total + n
return total
def sum_rec(numbers):
if len(numbers) == 0:
return 0
return numbers[0] + sum_rec(numbers[1:]) |
with open('data.txt') as f:
data = f.readlines()
data = [int(i.rstrip()) for i in data]
incr = 0
for idx, val in enumerate(data):
if idx == 0:
print(data[0])
continue
if data[idx-1] < data[idx]:
incr += 1
print(f"{data[idx]} increase")
else:
print(f"{data[idx]}"... | with open('data.txt') as f:
data = f.readlines()
data = [int(i.rstrip()) for i in data]
incr = 0
for (idx, val) in enumerate(data):
if idx == 0:
print(data[0])
continue
if data[idx - 1] < data[idx]:
incr += 1
print(f'{data[idx]} increase')
else:
print(f'{data[idx]... |
#!/usr/bin/python3
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error: ', err) | def this_fails():
x = 1 / 0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error: ', err) |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def mergeTrees(self, t1, t2):
def recurse(a1, a2):
if a1 == None:
return a2
if a2 == None:
return a1
... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def merge_trees(self, t1, t2):
def recurse(a1, a2):
if a1 == None:
return a2
if a2 == None:
return a1
... |
# -*- coding: utf-8 -*-
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = ('postgresql+psycopg2://'
'taxo:taxo@localhost:5432/taxonwiki')
ASSETS_DEBUG = False
ASSETS_CACHE = True
ASSETS_MANIFEST = 'json'
UGLIFYJS_EXTRA_ARGS = ['--compress', '--mangle']
... | class Config(object):
debug = False
testing = False
database_uri = 'postgresql+psycopg2://taxo:taxo@localhost:5432/taxonwiki'
assets_debug = False
assets_cache = True
assets_manifest = 'json'
uglifyjs_extra_args = ['--compress', '--mangle']
compass_config = {'output_style': ':compressed'... |
buttons_dict = {1: [r"$|a|$", "abs"], 2: [r"$\sqrt{a}$", "sqrt"], 3: [r"$\log$", "log"],
4: [r"$\ln$", "ln"], 5: [r"$a^b$", "power"], 6: [r"$()$", "brackets"],
7: [r"%", "percent"], 8: [r"$=$", "equals"], 9: [r"$\lfloor{a}\rfloor$", "floor"],
10: [r"$f(x)$", "... | buttons_dict = {1: ['$|a|$', 'abs'], 2: ['$\\sqrt{a}$', 'sqrt'], 3: ['$\\log$', 'log'], 4: ['$\\ln$', 'ln'], 5: ['$a^b$', 'power'], 6: ['$()$', 'brackets'], 7: ['%', 'percent'], 8: ['$=$', 'equals'], 9: ['$\\lfloor{a}\\rfloor$', 'floor'], 10: ['$f(x)$', 'func'], 11: ['$\\cot$', 'cot'], 12: ['$\\tan$', 'tan'], 13: ['$7$... |
default_ingredient_list = ['lentils', 'kale', 'shallots', 'swiss cheese', 'anchovies', 'Quiche', 'cashew nut',
'Waffles', 'chicken liver', 'parsley', 'babaganoosh', 'Toast', 'bouillon', 'hamburger',
'hoisin sauce', 'chaurice sausage', 'fennel', 'curry', 'clams', '... | default_ingredient_list = ['lentils', 'kale', 'shallots', 'swiss cheese', 'anchovies', 'Quiche', 'cashew nut', 'Waffles', 'chicken liver', 'parsley', 'babaganoosh', 'Toast', 'bouillon', 'hamburger', 'hoisin sauce', 'chaurice sausage', 'fennel', 'curry', 'clams', 'spaghetti squash', 'haiku roll', 'ancho chili peppers', ... |
"""type_traits.py
We need to assess if a string can be converted to int or float.
This module provides simple tests is_<type>.
"""
def is_float(val):
try:
return float(val) - val == 0
except:
return False
return False
def is_int(val):
try:
return int(val) - val == 0
except... | """type_traits.py
We need to assess if a string can be converted to int or float.
This module provides simple tests is_<type>.
"""
def is_float(val):
try:
return float(val) - val == 0
except:
return False
return False
def is_int(val):
try:
return int(val) - val == 0
except... |
# coding:utf-8
# example 04: double_linked_list.py
class Node(object):
def __init__(self, val=None):
self.val = val
self.prev = None
self.next = None
class DoubleLinkedList(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = Node()
sel... | class Node(object):
def __init__(self, val=None):
self.val = val
self.prev = None
self.next = None
class Doublelinkedlist(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = node()
self.tailnode = None
self.length = 0
def ... |
def trinomial(cfg,i,j,k) : #function t=trinomial(i,j,k)
#% Computes the trinomial of
#% the three input arguments
... | def trinomial(cfg, i, j, k):
aux_1 = cfg.factorial(i + j + k)
aux_2 = cfg.factorial(i) * cfg.factorial(j) * cfg.factorial(k)
t = aux_1 / aux_2
return t |
for x in range(65,70):
for y in range(65,x+1):
print(chr(x),end='')
print()
"""
# p[attern
A
BB
CCC
DDDD
EEEEE
""" | for x in range(65, 70):
for y in range(65, x + 1):
print(chr(x), end='')
print()
'\n# p[attern \n\nA\nBB\nCCC\nDDDD\nEEEEE\n\n' |
# -*- coding: utf-8 -*-
name = 'tbb'
version = '2017.0'
def commands():
appendenv('LD_LIBRARY_PATH', '{root}/lib/intel64/gcc4.7')
env.TBBROOT.set('{root}')
env.TBB_LIBRARIES.set('{root}/lib/intel64/gcc4.7')
env.TBB_INCLUDE_DIR.set('{root}/include')
| name = 'tbb'
version = '2017.0'
def commands():
appendenv('LD_LIBRARY_PATH', '{root}/lib/intel64/gcc4.7')
env.TBBROOT.set('{root}')
env.TBB_LIBRARIES.set('{root}/lib/intel64/gcc4.7')
env.TBB_INCLUDE_DIR.set('{root}/include') |
budget = float(input())
season = input()
if budget <= 100:
destination = 'Bulgaria'
money_spent = budget * 0.7
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.3
info = f'Camp - {money_spent:.2f}'
elif budget <= 1000:
destination = 'Balkans'
mon... | budget = float(input())
season = input()
if budget <= 100:
destination = 'Bulgaria'
money_spent = budget * 0.7
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.3
info = f'Camp - {money_spent:.2f}'
elif budget <= 1000:
destination = 'Balkans'
mon... |
"""W3C Document Object Model implementation for Python.
The Python mapping of the Document Object Model is documented in <...>.
This package contains the following modules:
minidom -- A simple implementation of the Level 1 DOM with namespace
support added (based on the Level 2 specification).
"""
| """W3C Document Object Model implementation for Python.
The Python mapping of the Document Object Model is documented in <...>.
This package contains the following modules:
minidom -- A simple implementation of the Level 1 DOM with namespace
support added (based on the Level 2 specification).
""" |
FiboList , Flag = [0,1] , True
"""
This Function,
at first we create a array of -1's
to check fibonacci data's and store them in it.
Then each time we call the fibonacci function (Recursion).
Flag is for understanding that we need to create a new
arr or we call the function recursively.
"""
def fibonacci_1(n... | (fibo_list, flag) = ([0, 1], True)
"\nThis Function,\nat first we create a array of -1's \nto check fibonacci data's and store them in it.\nThen each time we call the fibonacci function (Recursion).\nFlag is for understanding that we need to create a new \narr or we call the function recursively.\n"
def fibonacci_1(n)... |
def solution(movements):
horizontal, vertical = 0, 0
for move in movements:
direction, magnitude = move.split(' ')
if direction == "forward":
horizontal += int(magnitude)
elif direction == "down":
vertical += int(magnitude)
elif direction == "up":
... | def solution(movements):
(horizontal, vertical) = (0, 0)
for move in movements:
(direction, magnitude) = move.split(' ')
if direction == 'forward':
horizontal += int(magnitude)
elif direction == 'down':
vertical += int(magnitude)
elif direction == 'up':
... |
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k <= 0 or n < k:
return []
res_lst = []
def dfs(i, curr_lst):
if len(curr_lst) == k:
res_lst.append(curr_lst)
for value in range(i, n+1):
dfs(value+1,... | class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k <= 0 or n < k:
return []
res_lst = []
def dfs(i, curr_lst):
if len(curr_lst) == k:
res_lst.append(curr_lst)
for value in range(i, n + 1):
dfs(value... |
# -*- coding: utf-8 -*-
__version__ = "0.2.4"
__title__ = "pygcgen"
__summary__ = "Automatic changelog generation"
__uri__ = "https://github.com/topic2k/pygcgen"
__author__ = "topic2k"
__email__ = "topic2k+pypi@gmail.com"
__license__ = "MIT"
__copyright__ = "2016-2018 %s" % __author__
| __version__ = '0.2.4'
__title__ = 'pygcgen'
__summary__ = 'Automatic changelog generation'
__uri__ = 'https://github.com/topic2k/pygcgen'
__author__ = 'topic2k'
__email__ = 'topic2k+pypi@gmail.com'
__license__ = 'MIT'
__copyright__ = '2016-2018 %s' % __author__ |
"""
Default status.html resource
"""
class StatusResource:
def on_get(self, req, resp):
pass | """
Default status.html resource
"""
class Statusresource:
def on_get(self, req, resp):
pass |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 13:02:55 2015
@author: magusverma
"""
def reached_limit(current, limit):
for i in range(len(current)):
if current[i] != limit[i]-1:
return False
return True
def increment(current, limit):
for i in range(len(current)-1,-1,-1):
i... | """
Created on Fri Nov 13 13:02:55 2015
@author: magusverma
"""
def reached_limit(current, limit):
for i in range(len(current)):
if current[i] != limit[i] - 1:
return False
return True
def increment(current, limit):
for i in range(len(current) - 1, -1, -1):
if current[i] < lim... |
class GraphEdgesMapping:
def __init__(self, first_dual_edges_mapping, second_dual_edges_mapping):
self._first = first_dual_edges_mapping
self._second = second_dual_edges_mapping
@property
def size(self):
return self._first.shape[0]
@property
def first(self):
ret... | class Graphedgesmapping:
def __init__(self, first_dual_edges_mapping, second_dual_edges_mapping):
self._first = first_dual_edges_mapping
self._second = second_dual_edges_mapping
@property
def size(self):
return self._first.shape[0]
@property
def first(self):
return... |
class Solution:
def binary_find_last(self, nums, target):
"""
this is find the last data
"""
low = 0
hight = len(nums)-1
first = True
while low <= hight:
mid = (hight-low)//2+low
if nums[mid] == target:
return mid
... | class Solution:
def binary_find_last(self, nums, target):
"""
this is find the last data
"""
low = 0
hight = len(nums) - 1
first = True
while low <= hight:
mid = (hight - low) // 2 + low
if nums[mid] == target:
return m... |
#!/usr/bin/env python3
data = open("in").read().split("\n\n")
data = list(map(lambda x: x.split("\n"), data))
for i in range(len(data)): # todo this is stupid
data[i] = list(filter(lambda x: x != '', data[i]))
tot = 0
tot2 = 0
for d in data:
a = set("".join(d))
tot += len(a)
tota = 0
for q in a:
... | data = open('in').read().split('\n\n')
data = list(map(lambda x: x.split('\n'), data))
for i in range(len(data)):
data[i] = list(filter(lambda x: x != '', data[i]))
tot = 0
tot2 = 0
for d in data:
a = set(''.join(d))
tot += len(a)
tota = 0
for q in a:
if len(d) == len(list(filter(lambda x: x... |
#operate with params
OP_PARAMS_PATH = "/data/params/"
def save_bool_param(param_name,param_value):
try:
real_param_value = 1 if param_value else 0
with open(OP_PARAMS_PATH+"/"+param_name, "w") as outfile:
outfile.write(f'{real_param_value}')
except IOError:
print("Failed t... | op_params_path = '/data/params/'
def save_bool_param(param_name, param_value):
try:
real_param_value = 1 if param_value else 0
with open(OP_PARAMS_PATH + '/' + param_name, 'w') as outfile:
outfile.write(f'{real_param_value}')
except IOError:
print('Failed to save ' + param_n... |
# Hello! World!
print("Hello, World!")
# Learning Strings
my_string = "This is a string"
## Make string uppercase
my_string_upper = my_string.upper()
print(my_string_upper)
# Determine data type of string
print(type(my_string))
# Slicing strings [python is zero-based and starts at 0 and not 1]
print(my_string[0:4])
pri... | print('Hello, World!')
my_string = 'This is a string'
my_string_upper = my_string.upper()
print(my_string_upper)
print(type(my_string))
print(my_string[0:4])
print(my_string[:1])
print(my_string[0:14]) |
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
self.ret = []
self.counts = collections.Counter(candidates)
nums = [k for k in set(sorted(candidates))]
self.Backtrack(nums, target, [], 0)
return self.ret
def Backtrack(sel... | class Solution:
def combination_sum2(self, candidates: List[int], target: int) -> List[List[int]]:
self.ret = []
self.counts = collections.Counter(candidates)
nums = [k for k in set(sorted(candidates))]
self.Backtrack(nums, target, [], 0)
return self.ret
def backtrack(s... |
"""
Instructions:
1. Create a class named ReversedString that inherits from StringOperations class
2. Implement the function reverse
3. reverse function should be a one liner function that returns the reverse string to_be_reversed
4. Instantiate the class ReversedString
5. Print to show your function implementation res... | """
Instructions:
1. Create a class named ReversedString that inherits from StringOperations class
2. Implement the function reverse
3. reverse function should be a one liner function that returns the reverse string to_be_reversed
4. Instantiate the class ReversedString
5. Print to show your function implementation res... |
# Function that detects cycle in a directed graph
def cycleCheck(vertices, adj):
visited = set()
ancestor = set()
for vertex in range(vertices):
if vertex not in visited:
if dfs(vertex, adj, visited, ancestor)==True:
return True
return False
# Recursive dfs funct... | def cycle_check(vertices, adj):
visited = set()
ancestor = set()
for vertex in range(vertices):
if vertex not in visited:
if dfs(vertex, adj, visited, ancestor) == True:
return True
return False
def dfs(vertex, adj, visited, ancestor):
visited.add(vertex)
anc... |
# DROP TABLES
USERS_TABLE = "users"
SONGS_TABLE = "songs"
ARTISTS_TABLE = "artists"
TIME_TABLE = "time"
SONGS_PLAY_TABLE = "songplays"
songplay_table_drop = f"DROP TABLE IF EXISTS {SONGS_PLAY_TABLE};"
user_table_drop = f"DROP TABLE IF EXISTS {USERS_TABLE};"
song_table_drop = f"DROP TABLE IF EXISTS {SONGS_TABLE};"
art... | users_table = 'users'
songs_table = 'songs'
artists_table = 'artists'
time_table = 'time'
songs_play_table = 'songplays'
songplay_table_drop = f'DROP TABLE IF EXISTS {SONGS_PLAY_TABLE};'
user_table_drop = f'DROP TABLE IF EXISTS {USERS_TABLE};'
song_table_drop = f'DROP TABLE IF EXISTS {SONGS_TABLE};'
artist_table_drop =... |
class Config(object):
SECRET_KEY = "CantStopAddictedToTheShinDigChopTopHeSaysImGonnaWinBig"
HOST = "0a398d5f.ngrok.io"
SHOPIFY_CONFIG = {
'API_KEY': '<API KEY HERE>',
'API_SECRET': '<API SECRET HERE>',
'APP_HOME': 'http://' + HOST,
'CALLBACK_URL': 'http://' + HOST + '/insta... | class Config(object):
secret_key = 'CantStopAddictedToTheShinDigChopTopHeSaysImGonnaWinBig'
host = '0a398d5f.ngrok.io'
shopify_config = {'API_KEY': '<API KEY HERE>', 'API_SECRET': '<API SECRET HERE>', 'APP_HOME': 'http://' + HOST, 'CALLBACK_URL': 'http://' + HOST + '/install', 'REDIRECT_URI': 'http://' + HO... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__version__ = "3.0.0"
__author__ = "Amir Zeldes"
__copyright__ = "Copyright 2015-2019, Amir Zeldes"
__license__ = "Apache 2.0 License"
| __version__ = '3.0.0'
__author__ = 'Amir Zeldes'
__copyright__ = 'Copyright 2015-2019, Amir Zeldes'
__license__ = 'Apache 2.0 License' |
DEV = {
"SERVER_NAME": "dev-api.materialsdatafacility.org",
"API_LOG_FILE": "deva.log",
"PROCESS_LOG_FILE": "devp.log",
"LOG_LEVEL": "DEBUG",
"FORM_URL": "https://connect.materialsdatafacility.org/",
"TRANSFER_DEADLINE": 3 * 60 * 60, # 3 hours, in seconds
"INGEST_URL": "https://dev-api.... | dev = {'SERVER_NAME': 'dev-api.materialsdatafacility.org', 'API_LOG_FILE': 'deva.log', 'PROCESS_LOG_FILE': 'devp.log', 'LOG_LEVEL': 'DEBUG', 'FORM_URL': 'https://connect.materialsdatafacility.org/', 'TRANSFER_DEADLINE': 3 * 60 * 60, 'INGEST_URL': 'https://dev-api.materialsdatafacility.org/ingest', 'INGEST_INDEX': 'mdf-... |
inputDoc = open("input.txt")
docLines = inputDoc.readlines()
inputDoc.close()
# PART 1
# Find two numbers that add up to 2020 and multiply them
correct1 = []
for line in docLines:
line = int(line.replace("\n", ""))
for lineTwo in docLines:
lineTwo = int(lineTwo.replace("\n", ""))
if line + line... | input_doc = open('input.txt')
doc_lines = inputDoc.readlines()
inputDoc.close()
correct1 = []
for line in docLines:
line = int(line.replace('\n', ''))
for line_two in docLines:
line_two = int(lineTwo.replace('\n', ''))
if line + lineTwo == 2020:
correct1 = [line, lineTwo]
... |
"""Contains the class for a problem instance."""
class AgglutinatingRolls():
"""Define a class for a problem instance."""
def __init__(self, instance: dict):
"""Initialize an object."""
self.rolls_a = instance.get('rolls_a', [])
self.rolls_b = instance.get('rolls_a', [])
# co... | """Contains the class for a problem instance."""
class Agglutinatingrolls:
"""Define a class for a problem instance."""
def __init__(self, instance: dict):
"""Initialize an object."""
self.rolls_a = instance.get('rolls_a', [])
self.rolls_b = instance.get('rolls_a', [])
self.cos... |
class InvalidApiKeyError(Exception):
def __init__(self):
self.message = "The API key you inserted isn't valid"
class InvalidCityNameError(Exception):
def __init__(self):
self.message = "Couldn't find any city with this name or code. Please check again."
| class Invalidapikeyerror(Exception):
def __init__(self):
self.message = "The API key you inserted isn't valid"
class Invalidcitynameerror(Exception):
def __init__(self):
self.message = "Couldn't find any city with this name or code. Please check again." |
#
# PySNMP MIB module GWPAGERMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GWPAGERMIB
# Produced by pysmi-0.3.4 at Wed May 1 13:20:45 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, 09:... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
a = input()
b = input()
c = input()
print(a[0] + b[1] + c[2])
| a = input()
b = input()
c = input()
print(a[0] + b[1] + c[2]) |
def evalRPN(tokens: List[str]) -> int:
stack = [] #make a stack to hold the numberes and result calculation
for char in tokens: #iterate through the tokens
if char not in "+*-/": #if token is not an operator then it is a number so we add to stack
stack.append(int(cha... | def eval_rpn(tokens: List[str]) -> int:
stack = []
for char in tokens:
if char not in '+*-/':
stack.append(int(char))
else:
(r, l) = (stack.pop(), stack.pop())
if char == '*':
stack.append(l * r)
elif char == '/':
st... |
# Lv-677.PythonCore
name_que = input("Hello. \nWhat is your name? \n")
print ("Hello, ", name_que)
age_que = input("How old are you? \n")
print ("Your age is: ", age_que)
live_que = input(f"Where do u live {name_que}? \n")
print("You live in ", live_que) | name_que = input('Hello. \nWhat is your name? \n')
print('Hello, ', name_que)
age_que = input('How old are you? \n')
print('Your age is: ', age_que)
live_que = input(f'Where do u live {name_que}? \n')
print('You live in ', live_que) |
# Royals and suits
jack = 11
queen = 12
king = 13
ace = 14
spades = 's'
clubs = 'c'
hearts = 'h'
diamonds = 'd'
ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace]
suits = [spades, clubs, hearts, diamonds]
# Hands
straight_flush = 'Straight flush'
quads = 'Four of a kind'
full_house = 'Full house'
flush = '... | jack = 11
queen = 12
king = 13
ace = 14
spades = 's'
clubs = 'c'
hearts = 'h'
diamonds = 'd'
ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace]
suits = [spades, clubs, hearts, diamonds]
straight_flush = 'Straight flush'
quads = 'Four of a kind'
full_house = 'Full house'
flush = 'Flush'
straight = 'Straight'
t... |
s = ''
while True:
try:
s+= input()
except:
break
r = ['a', s.count('a')]
for i in range(98, 123):
n = s.count(chr(i))
if n > r[1]:
r[0] = chr(i)
r[1] = n
elif n == r[1]:
r[0] += chr(i)
print(r[0])
| s = ''
while True:
try:
s += input()
except:
break
r = ['a', s.count('a')]
for i in range(98, 123):
n = s.count(chr(i))
if n > r[1]:
r[0] = chr(i)
r[1] = n
elif n == r[1]:
r[0] += chr(i)
print(r[0]) |
def Run(filepath):
with open(filepath) as input:
measurements = list(map(int, input.read().split('\n')))
print('Day 1')
Part1(measurements)
Part2(measurements)
def Part1(measurements):
increases = 0
previousDepth = None
for depth in measurements:
#Increment if this isn't t... | def run(filepath):
with open(filepath) as input:
measurements = list(map(int, input.read().split('\n')))
print('Day 1')
part1(measurements)
part2(measurements)
def part1(measurements):
increases = 0
previous_depth = None
for depth in measurements:
if previousDepth != None an... |
"""
O(n^min(k, n-k))
"""
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
self.dfs(list(range(1, n + 1)), k, [], result)
return result
def dfs(self, arr, k, path, result):
if k < 0:
return
if k == 0:
result.appen... | """
O(n^min(k, n-k))
"""
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
self.dfs(list(range(1, n + 1)), k, [], result)
return result
def dfs(self, arr, k, path, result):
if k < 0:
return
if k == 0:
result.appen... |
my_email = 'twitterlehigh2@gmail.com'
my_password = 'kB5-LXX-T7w-TLG'
# my_email = 'twitterlehigh@gmail.com'
# my_password = 'Lehigh131016'
| my_email = 'twitterlehigh2@gmail.com'
my_password = 'kB5-LXX-T7w-TLG' |
'''
Given an integer, write a function that reverses
the bits (in binary) and returns the integer result.
Understand:
417 --> 267
167 --> 417
0 --> 0
Plan:
Use bin() to convert the binary into a string.
Use bracket indexing to reverse the order.
Use int() to convert it into a decimal number.
'''
def csReverseInte... | """
Given an integer, write a function that reverses
the bits (in binary) and returns the integer result.
Understand:
417 --> 267
167 --> 417
0 --> 0
Plan:
Use bin() to convert the binary into a string.
Use bracket indexing to reverse the order.
Use int() to convert it into a decimal number.
"""
def cs_reverse_in... |
class Solution:
def solve(self, board: List[List[str]]) -> None:
m, n = len(board), len(board and board[0])
def explore(i, j):
board[i][j] = "S"
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n and board[x][y] == "O":... | class Solution:
def solve(self, board: List[List[str]]) -> None:
(m, n) = (len(board), len(board and board[0]))
def explore(i, j):
board[i][j] = 'S'
for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n and (board[x][y]... |
# -*- coding: utf-8 -*-
"""
To-Do application
"""
def add(todos):
"""
Add a task
"""
pass
def delete(todos, index=None):
"""
Delete one or all tasks
"""
pass
def get_printable_todos(todos):
"""
Get formatted tasks
"""
pass
def toggle_done(todos, index):
"""
... | """
To-Do application
"""
def add(todos):
"""
Add a task
"""
pass
def delete(todos, index=None):
"""
Delete one or all tasks
"""
pass
def get_printable_todos(todos):
"""
Get formatted tasks
"""
pass
def toggle_done(todos, index):
"""
Toggle a task
"""
... |
class SerVivo:
def __init__(self):
self._vivo = True
def is_vivo(self):
return self._vivo
def morir(self):
self._vivo= False
#Se pone _ porque es una clase abstracta y solo se puede usar en esta clase
#Se pone __ porque es una clase privada solo la usa cada clase
| class Servivo:
def __init__(self):
self._vivo = True
def is_vivo(self):
return self._vivo
def morir(self):
self._vivo = False |
#!/usr/bin/env python3
with open("main.go", encoding="utf-8") as file:
# FIXME
usage = "\n".join(file.read().split("\n")[13:-1])
with open("tools/_README.md", mode="r", encoding="utf-8") as file:
readme = file.read()
readme = readme.replace("<<<<USAGE>>>>", usage)
with open("README.md", mode="w", enco... | with open('main.go', encoding='utf-8') as file:
usage = '\n'.join(file.read().split('\n')[13:-1])
with open('tools/_README.md', mode='r', encoding='utf-8') as file:
readme = file.read()
readme = readme.replace('<<<<USAGE>>>>', usage)
with open('README.md', mode='w', encoding='utf-8') as file:
file.write... |
def binary_search(the_list, target):
lower_bound = 0
upper_bound = len(the_list) - 1
while lower_bound <= upper_bound:
pivot = (lower_bound + upper_bound) // 2
pivot_value = the_list[pivot]
if pivot_value == target:
return pivot
if pivot_value > target... | def binary_search(the_list, target):
lower_bound = 0
upper_bound = len(the_list) - 1
while lower_bound <= upper_bound:
pivot = (lower_bound + upper_bound) // 2
pivot_value = the_list[pivot]
if pivot_value == target:
return pivot
if pivot_value > target:
... |
"""
User ACL
========
"""
_schema = {
# Medlemsnummer
'id': {'type': 'integer',
'readonly': True
},
'acl': {'type': 'dict',
'readonly': False,
'schema': {'groups': {'type': 'list',... | """
User ACL
========
"""
_schema = {'id': {'type': 'integer', 'readonly': True}, 'acl': {'type': 'dict', 'readonly': False, 'schema': {'groups': {'type': 'list', 'default': [], 'schema': {'type': 'objectid'}}, 'roles': {'type': 'list', 'default': [], 'schema': {'type': 'objectid'}}}}}
definition = {'item... |
"""
The cost of stock on each day is given in an array A[] of size N.
Find all the days on which you buy and sell the stock
so that in between those days your profit is maximum.
"""
def sellandbuy(a, n):
result = []
start = 0
end = 1
while end < n:
if a[start] < a[end] and a[end] > a[end-... | """
The cost of stock on each day is given in an array A[] of size N.
Find all the days on which you buy and sell the stock
so that in between those days your profit is maximum.
"""
def sellandbuy(a, n):
result = []
start = 0
end = 1
while end < n:
if a[start] < a[end] and a[end] > a[end - ... |
def solution(n):
sum = 0
print(list(str(n)))
for i, j in enumerate(list(str(n))):
sum+=int(j)
return sum
print(solution(11)) | def solution(n):
sum = 0
print(list(str(n)))
for (i, j) in enumerate(list(str(n))):
sum += int(j)
return sum
print(solution(11)) |
"""
LeetCode Problem: 108. Convert Sorted Array to Binary Search Tree
Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(N)
Space Complexity: O(N)
"""
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Tre... | """
LeetCode Problem: 108. Convert Sorted Array to Binary Search Tree
Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(N)
Space Complexity: O(N)
"""
class Solution:
def sorted_array_to_bst(self, nums: List[int]) ->... |
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
x = [i == '1' for i in a[::-1]]
y = [i == '1' for i in b[::-1]]
r = []
carry = False
if len(x) > len(y):
y += [False] * (len(x) - len(... | class Solution:
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
x = [i == '1' for i in a[::-1]]
y = [i == '1' for i in b[::-1]]
r = []
carry = False
if len(x) > len(y):
y += [False] * (len(x) - len... |
#
# PySNMP MIB module HP-ICF-LINKTEST (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-LINKTEST
# Produced by pysmi-0.3.4 at Wed May 1 13:34:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
"""Configs for VisDA17 experiments."""
def get_weighting_config_class_pareto(alpha, reverse, seed):
return {
'name': 'class_pareto',
'kwargs': {
'alpha': alpha,
'reverse': reverse,
'seed': seed
},
}
def get_dataset_config_visda17_pareto_target_imba... | """Configs for VisDA17 experiments."""
def get_weighting_config_class_pareto(alpha, reverse, seed):
return {'name': 'class_pareto', 'kwargs': {'alpha': alpha, 'reverse': reverse, 'seed': seed}}
def get_dataset_config_visda17_pareto_target_imbalance(alpha, seed=None):
return {'name': 'VisDA17', 'val_fraction':... |
"""
This file contains the implementation of a mixin that contains a
method that solves the collision between a rectangular shape with
the ball.
Collision solve algorithm taken from:
https://github.com/noooway/love2d_arkanoid_tutorial/wiki/Resolving-Collisions
Author: Alejandro Mujica
Date: 15/07/2020
"""
class Bal... | """
This file contains the implementation of a mixin that contains a
method that solves the collision between a rectangular shape with
the ball.
Collision solve algorithm taken from:
https://github.com/noooway/love2d_arkanoid_tutorial/wiki/Resolving-Collisions
Author: Alejandro Mujica
Date: 15/07/2020
"""
class Ball... |
for x in range(16):
with open(f'..\\data\\cpu\\functions\\opcode_switch\\opcode_7xxx\\opcode_7xxx_{x}.mcfunction', 'w') as f:
f.write(f'scoreboard players operation Global V{hex(x)[2:].upper()} += Global PC_nibble_4\n')
f.write(f'execute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreb... | for x in range(16):
with open(f'..\\data\\cpu\\functions\\opcode_switch\\opcode_7xxx\\opcode_7xxx_{x}.mcfunction', 'w') as f:
f.write(f'scoreboard players operation Global V{hex(x)[2:].upper()} += Global PC_nibble_4\n')
f.write(f'execute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreb... |
class MoveGenerator:
"""
state=(BK,WK,WR)--> state=((x,y),(x,y,R),(x,y,K)) check for K and R for whose values most likely order you get is bk,w
where wk , wr and bk are positions for the pieces
"""
def __init__(self,state):
self.state=state #represennts initial state of the game p.s s... | class Movegenerator:
"""
state=(BK,WK,WR)--> state=((x,y),(x,y,R),(x,y,K)) check for K and R for whose values most likely order you get is bk,w
where wk , wr and bk are positions for the pieces
"""
def __init__(self, state):
self.state = state
self.bk = state[0]
... |
travel_route = input().split('||')
amount_of_fuel = int(input())
amount_of_ammunition = int(input())
travelled_distance = 0
for x in travel_route:
current_command = x.split(' ')
command = current_command[0]
if command == 'Travel':
value = int(current_command[1])
if amount_of_fuel >= value:
... | travel_route = input().split('||')
amount_of_fuel = int(input())
amount_of_ammunition = int(input())
travelled_distance = 0
for x in travel_route:
current_command = x.split(' ')
command = current_command[0]
if command == 'Travel':
value = int(current_command[1])
if amount_of_fuel >= value:
... |
'''
Author : MiKueen
Level : Medium
Problem Statement : Subarray Sum Equals K
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Constraints:
The length of the array is in range [1, 20,000].
T... | """
Author : MiKueen
Level : Medium
Problem Statement : Subarray Sum Equals K
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Constraints:
The length of the array is in range [1, 20,000].
T... |
class Node:
@property
def label(self):
return self.__label
@property
def left_child(self):
return self.__left_child
@left_child.setter
def left_child(self, n):
self.__left_child = n
self.__left_child.parent = self
@property
def right_sibling(self):
... | class Node:
@property
def label(self):
return self.__label
@property
def left_child(self):
return self.__left_child
@left_child.setter
def left_child(self, n):
self.__left_child = n
self.__left_child.parent = self
@property
def right_sibling(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
function
'''
def area(width, height=10):
'''
area
'''
print('width=%s, height=%s' % (width, height))
return width*height
print(area(10, 20))
print(area(height=10, width=20))
print(area(10))
def sum(a, b, *c):
'''
sum
'''
d = a+b
... | """
function
"""
def area(width, height=10):
"""
area
"""
print('width=%s, height=%s' % (width, height))
return width * height
print(area(10, 20))
print(area(height=10, width=20))
print(area(10))
def sum(a, b, *c):
"""
sum
"""
d = a + b
for i in c:
d = d + i
return ... |
# DEFEAT
# https://www.codechef.com/UNCO2021/problems/DEFEAT
NMK = [int(i) for i in input().split()]
matrix = []
for column in range(NMK[1]):
matrix.append([0]* NMK[0])
enemyLoc = []
for enemy in range(NMK[2]):
enemyLoc.append([i for i in input().split()])
for enemy in range(NMK[2]):
for enemyRow in enemyLoc[en... | nmk = [int(i) for i in input().split()]
matrix = []
for column in range(NMK[1]):
matrix.append([0] * NMK[0])
enemy_loc = []
for enemy in range(NMK[2]):
enemyLoc.append([i for i in input().split()])
for enemy in range(NMK[2]):
for enemy_row in enemyLoc[enemy][0]:
for enemy_col in enemyLoc[enemy][1]:
... |
class UvMap(object):
def __init__(self, coords=[], texture_file_name='', name=''):
self.coords = tuple(coords)
self.texture_file_name = texture_file_name
self.name = name
| class Uvmap(object):
def __init__(self, coords=[], texture_file_name='', name=''):
self.coords = tuple(coords)
self.texture_file_name = texture_file_name
self.name = name |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'cc_source_files': [
'animation.cc',
'animation.h',
'animation_curve.cc',
'animation_curve.h',
'anim... | {'variables': {'cc_source_files': ['animation.cc', 'animation.h', 'animation_curve.cc', 'animation_curve.h', 'animation_events.h', 'animation_id_provider.cc', 'animation_id_provider.h', 'animation_registrar.cc', 'animation_registrar.h', 'append_quads_data.h', 'bitmap_content_layer_updater.cc', 'bitmap_content_layer_upd... |
class FileLock:
def __init__(self, filename):
self.filename = filename
with open(self.filename, 'w') as f:
f.write('done')
def lock(self):
with open(self.filename, 'w') as f:
f.write('working')
def unlock(self):
with open(self.filename, 'w') as f:
... | class Filelock:
def __init__(self, filename):
self.filename = filename
with open(self.filename, 'w') as f:
f.write('done')
def lock(self):
with open(self.filename, 'w') as f:
f.write('working')
def unlock(self):
with open(self.filename, 'w') as f:
... |
# Approach 1
def reverseList(A, start, end):
while start < end:
A[start], A[end] = A[end], A[start]
start += 1
end -= 1
# reverseList([1, 2, 3, 4, 5, 6], 0, 5) = [6 5 4 3 2 1]
# Approach 2
def reverseList(A, start, end):
if start >= end:
return
A[start], A[end] = A[end],... | def reverse_list(A, start, end):
while start < end:
(A[start], A[end]) = (A[end], A[start])
start += 1
end -= 1
def reverse_list(A, start, end):
if start >= end:
return
(A[start], A[end]) = (A[end], A[start])
reverse_list(A, start + 1, end - 1) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 12:37:10 2020
@author: Arthur Donizeti Rodrigues Dias
"""
def arithmetic_arranger(problems, resultado = False):
lista =[]
listaNumero = []
listaOperador = []
listaSoma = []
listaFormatada = []
listaFormatada2 = []
listaForm... | """
Created on Wed Jul 22 12:37:10 2020
@author: Arthur Donizeti Rodrigues Dias
"""
def arithmetic_arranger(problems, resultado=False):
lista = []
lista_numero = []
lista_operador = []
lista_soma = []
lista_formatada = []
lista_formatada2 = []
lista_formatada3 = []
lista_formatada4 = ... |
#!/usr/bin/python3
# --- 001 > U5W2P1_Task1_w1
def solution(s):
return int(s)
if __name__ == "__main__":
print('----------start------------')
s = "12"
print(solution( s ))
print('------------end------------') | def solution(s):
return int(s)
if __name__ == '__main__':
print('----------start------------')
s = '12'
print(solution(s))
print('------------end------------') |
def sort(num) :
for i in range(len(num) - 1) :
for j in range(i, len(num)) :
if num[i] > num[j] :
temp = num[i]
num[i] = num[j]
num[j] = temp
num = [2, 6, 4, 8, 7]
sort(num)
print(num)
'''
Output :
[2, 4, 6, 7, 8]
''' | def sort(num):
for i in range(len(num) - 1):
for j in range(i, len(num)):
if num[i] > num[j]:
temp = num[i]
num[i] = num[j]
num[j] = temp
num = [2, 6, 4, 8, 7]
sort(num)
print(num)
'\nOutput :\n[2, 4, 6, 7, 8]\n' |
#! /usr/bin/env python3
def f(x):
def g(y):
# NEED THIS
nonlocal x
x = x - y
return x
return g
g0 = f(100)
ans0 = g0(42)
print(ans0)
g1 = f(200)
ans1 = g1(42)
print(ans1)
| def f(x):
def g(y):
nonlocal x
x = x - y
return x
return g
g0 = f(100)
ans0 = g0(42)
print(ans0)
g1 = f(200)
ans1 = g1(42)
print(ans1) |
"""
This file is part of pynadc
https://github.com/rmvanhees/pynadc
GOSAT-2 package
Copyright (c) 2019 SRON - Netherlands Institute for Space Research
All Rights Reserved
License: BSD-3-Clause
"""
__all__ = ['db']
| """
This file is part of pynadc
https://github.com/rmvanhees/pynadc
GOSAT-2 package
Copyright (c) 2019 SRON - Netherlands Institute for Space Research
All Rights Reserved
License: BSD-3-Clause
"""
__all__ = ['db'] |
# input
N = int(input())
S = []
for i in range(N):
S.append(input())
# process & output
length_T = 0
left = 0
right = N-1
while length_T < N:
if S[left] < S[right]:
print(S[left], end='')
left += 1
elif S[left] > S[right]:
print(S[right], end='')
right -= 1
else:
temp_l = left
temp_r = right
while ... | n = int(input())
s = []
for i in range(N):
S.append(input())
length_t = 0
left = 0
right = N - 1
while length_T < N:
if S[left] < S[right]:
print(S[left], end='')
left += 1
elif S[left] > S[right]:
print(S[right], end='')
right -= 1
else:
temp_l = left
tem... |
template = """
{
"packagingVersion": "4.0",
"upgradesFrom": ["%%(upgrades-from)s"],
"downgradesTo": ["%%(downgrades-to)s"],
"minDcosReleaseVersion": "1.9",
"name": "%(package-name)s",
"version": "%%(package-version)s",
"maintainer": "%%(maintainer)s",
"description": "%(package-name)s on DC/OS",
"selec... | template = '\n{\n "packagingVersion": "4.0",\n "upgradesFrom": ["%%(upgrades-from)s"],\n "downgradesTo": ["%%(downgrades-to)s"],\n "minDcosReleaseVersion": "1.9",\n "name": "%(package-name)s",\n "version": "%%(package-version)s",\n "maintainer": "%%(maintainer)s",\n "description": "%(package-name)s on DC/OS",\n... |
spin = input()
electric_charge = input()
if spin == '1' and electric_charge == '0':
print('Photon Boson')
else:
if electric_charge == '-1/3':
print('Strange Quark')
elif electric_charge == '2/3':
print('Charm Quark')
elif electric_charge == '-1':
print('Electron Lepton')
els... | spin = input()
electric_charge = input()
if spin == '1' and electric_charge == '0':
print('Photon Boson')
elif electric_charge == '-1/3':
print('Strange Quark')
elif electric_charge == '2/3':
print('Charm Quark')
elif electric_charge == '-1':
print('Electron Lepton')
else:
print('Muon Lepton') |
#! /usr/bin/python
@onRun
def run(args):
print("run")
return {"msg":"fsd"}
@onPause
def pause(args):
print("pause")
@onStart
def start(args):
print("start")
@onFinish
def finish(args):
print("finish") | @onRun
def run(args):
print('run')
return {'msg': 'fsd'}
@onPause
def pause(args):
print('pause')
@onStart
def start(args):
print('start')
@onFinish
def finish(args):
print('finish') |
"""
@file
@brief shortcuts to exams
"""
| """
@file
@brief shortcuts to exams
""" |
#encoding:utf-8
subreddit = 'tf2+tf2memes+tf2shitposterclub'
t_channel = '@r_TF2'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'tf2+tf2memes+tf2shitposterclub'
t_channel = '@r_TF2'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.