content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Cat:
name = ''
age = 0
color = ''
def __init__(self, name, age=0, color ='White'):
self.name = name
self.age = age
self.color = color
def meow(self):
print(f'{self.name} meow')
def sleep(self):
print(f' {self.name} zzz')
def hungry(self):
... | class Cat:
name = ''
age = 0
color = ''
def __init__(self, name, age=0, color='White'):
self.name = name
self.age = age
self.color = color
def meow(self):
print(f'{self.name} meow')
def sleep(self):
print(f' {self.name} zzz')
def hungry(self):
... |
def ascending_order(arr):
if(len(arr) == 1):
return 0
else:
count = 0
for i in range(0, len(arr)-1):
if(arr[i+1]<arr[i]):
diff = arr[i] - arr[i+1]
arr[i+1]+=diff
count+=diff
return count
if __name__=="__main__":
... | def ascending_order(arr):
if len(arr) == 1:
return 0
else:
count = 0
for i in range(0, len(arr) - 1):
if arr[i + 1] < arr[i]:
diff = arr[i] - arr[i + 1]
arr[i + 1] += diff
count += diff
return count
if __name__ == '__mai... |
class Products:
# Surface Reflectance 8-day 500m
modisRefl = 'MODIS/006/MOD09A1' # => NDDI
# Surface Temperature 8-day 1000m */
modisTemp = 'MODIS/006/MOD11A2' # => T/NDVI
# fAPAR 8-day 500m
modisFpar = 'MODIS/006/MOD15A2H' # => fAPAR
#Evapotranspiration 8-day 500m
modisEt = 'MODIS/006/MOD16A2' # =... | class Products:
modis_refl = 'MODIS/006/MOD09A1'
modis_temp = 'MODIS/006/MOD11A2'
modis_fpar = 'MODIS/006/MOD15A2H'
modis_et = 'MODIS/006/MOD16A2'
modis_evi = 'MODIS/006/MOD13A1' |
# 3. Longest Substring Without Repeating Characters
# Runtime: 60 ms, faster than 74.37% of Python3 online submissions for Longest Substring Without Repeating Characters.
# Memory Usage: 14.4 MB, less than 53.07% of Python3 online submissions for Longest Substring Without Repeating Characters.
class Solution:
#... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
idx = {}
max_len = 0
left = 0
for right in range(len(s)):
char = s[right]
if char in idx:
left = max(left, idx[char])
max_len = max(max_len, right - left + 1)
... |
# Party member and chosen four names
CHOSEN_FOUR = (
'NESS',
'PAULA',
'JEFF',
'POO',
)
PARTY_MEMBERS = (
'NESS',
'PAULA',
'JEFF',
'POO',
'POKEY',
'PICKY',
'KING',
'TONY',
'BUBBLE_MONKEY',
'DUNGEON_MAN',
'FLYING_MAN_1',
'FLYING_MAN_2',
'FLYING_MAN_3',... | chosen_four = ('NESS', 'PAULA', 'JEFF', 'POO')
party_members = ('NESS', 'PAULA', 'JEFF', 'POO', 'POKEY', 'PICKY', 'KING', 'TONY', 'BUBBLE_MONKEY', 'DUNGEON_MAN', 'FLYING_MAN_1', 'FLYING_MAN_2', 'FLYING_MAN_3', 'FLYING_MAN_4', 'FLYING_MAN_5', 'TEDDY_BEAR', 'SUPER_PLUSH_BEAR') |
# -*- coding: utf-8 -*-
def test_receiving_events(vim):
vim.command('call rpcnotify(%d, "test-event", 1, 2, 3)' % vim.channel_id)
event = vim.next_message()
assert event[1] == 'test-event'
assert event[2] == [1, 2, 3]
vim.command('au FileType python call rpcnotify(%d, "py!", bufnr("$"))' %
... | def test_receiving_events(vim):
vim.command('call rpcnotify(%d, "test-event", 1, 2, 3)' % vim.channel_id)
event = vim.next_message()
assert event[1] == 'test-event'
assert event[2] == [1, 2, 3]
vim.command('au FileType python call rpcnotify(%d, "py!", bufnr("$"))' % vim.channel_id)
vim.command('... |
class TreeError:
TYPE_ERROR = 'ERROR'
TYPE_ANOMALY = 'ANOMALY'
ON_INDI = 'INDIVIDUAL'
ON_FAM = 'FAMILY'
def __init__(self, err_type, err_on, err_us, err_on_id, err_msg):
self.err_type = err_type
self.err_on = err_on
self.err_us = err_us
self.err_on_id = err_on_id
... | class Treeerror:
type_error = 'ERROR'
type_anomaly = 'ANOMALY'
on_indi = 'INDIVIDUAL'
on_fam = 'FAMILY'
def __init__(self, err_type, err_on, err_us, err_on_id, err_msg):
self.err_type = err_type
self.err_on = err_on
self.err_us = err_us
self.err_on_id = err_on_id
... |
budget_header = 'Budget'
forecast_total_header = 'Forecast outturn'
variance_header = 'Variance -overspend/underspend'
variance_percentage_header = 'Variance %'
year_to_date_header = 'Year to Date Actuals'
budget_spent_percentage_header = '% of budget spent to date'
variance_outturn_header = "Forecast movement"
| budget_header = 'Budget'
forecast_total_header = 'Forecast outturn'
variance_header = 'Variance -overspend/underspend'
variance_percentage_header = 'Variance %'
year_to_date_header = 'Year to Date Actuals'
budget_spent_percentage_header = '% of budget spent to date'
variance_outturn_header = 'Forecast movement' |
def get_distance_matrix(orig, edited):
# initialize the matrix
orig_len = len(orig) + 1
edit_len = len(edited) + 1
distance_matrix = [[0] * edit_len for _ in range(orig_len)]
for i in range(orig_len):
distance_matrix[i][0] = i
for j in range(edit_len):
distance_matrix[0][j] = j
... | def get_distance_matrix(orig, edited):
orig_len = len(orig) + 1
edit_len = len(edited) + 1
distance_matrix = [[0] * edit_len for _ in range(orig_len)]
for i in range(orig_len):
distance_matrix[i][0] = i
for j in range(edit_len):
distance_matrix[0][j] = j
for i in range(1, orig_le... |
plural_suffixes = {
'ches': 'ch',
'shes': 'sh',
'ies': 'y',
'ves': 'fe',
'oes': 'o',
'zes': 'z',
's': ''
}
plural_words = {
'pieces': 'piece',
'bunches': 'bunch',
'haunches': 'haunch',
'flasks': 'flask',
'veins': 'vein',
'bowls': 'bowl'
} | plural_suffixes = {'ches': 'ch', 'shes': 'sh', 'ies': 'y', 'ves': 'fe', 'oes': 'o', 'zes': 'z', 's': ''}
plural_words = {'pieces': 'piece', 'bunches': 'bunch', 'haunches': 'haunch', 'flasks': 'flask', 'veins': 'vein', 'bowls': 'bowl'} |
def insert_space(msg, idx):
msg = msg[:idx] + " " + msg[idx:]
print(msg)
return msg
def reverse(msg, substring):
if substring in msg:
msg = msg.replace(substring, "", 1)
msg += substring[::-1]
print(msg)
return msg
else:
print("error")
return msg
d... | def insert_space(msg, idx):
msg = msg[:idx] + ' ' + msg[idx:]
print(msg)
return msg
def reverse(msg, substring):
if substring in msg:
msg = msg.replace(substring, '', 1)
msg += substring[::-1]
print(msg)
return msg
else:
print('error')
return msg
def... |
class PokepayResponse(object):
def __init__(self, response, response_body):
self.body = response_body
self.elapsed = response.elapsed
self.status_code = response.status_code
self.ok = response.ok
self.headers = response.headers
self.url = response.url
def body(se... | class Pokepayresponse(object):
def __init__(self, response, response_body):
self.body = response_body
self.elapsed = response.elapsed
self.status_code = response.status_code
self.ok = response.ok
self.headers = response.headers
self.url = response.url
def body(s... |
str1=input("enter first string:")
str2=input("enter second string:")
new_a = str2[:2] + str1[2:]
new_b = str1[:2] + str2[2:]
print("the new string after swapping first two charaters of both string:",(new_a+' ' +new_b))
| str1 = input('enter first string:')
str2 = input('enter second string:')
new_a = str2[:2] + str1[2:]
new_b = str1[:2] + str2[2:]
print('the new string after swapping first two charaters of both string:', new_a + ' ' + new_b) |
a = int(input())
b = int(input())
if a > b:
print(1)
elif a == b:
print(0)
else:
print(2)
| a = int(input())
b = int(input())
if a > b:
print(1)
elif a == b:
print(0)
else:
print(2) |
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(list(zip(keys, values)))
# Lazily, Python 2.3+, not 3.x:
hash = dict(zip(keys, values))
| keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(list(zip(keys, values)))
hash = dict(zip(keys, values)) |
description = 'Refsans 4 analog 1 GPIO on Raspberry'
group = 'optional'
tango_base = 'tango://%s:10000/test/ads/' % setupname
lowlevel = ()
devices = {
'%s_ch1' % setupname : device('nicos.devices.entangle.Sensor',
description = 'ADin0',
tangodevice = tango_base + 'ch1',
unit = 'V',
... | description = 'Refsans 4 analog 1 GPIO on Raspberry'
group = 'optional'
tango_base = 'tango://%s:10000/test/ads/' % setupname
lowlevel = ()
devices = {'%s_ch1' % setupname: device('nicos.devices.entangle.Sensor', description='ADin0', tangodevice=tango_base + 'ch1', unit='V', fmtstr='%.4f', visibility=lowlevel), '%s_ch2... |
file = open('JacobiMatrix.java', 'w')
for i in range(10):
for j in range(10):
file.write('jacobiMatrix.setEntry(' + str(i) + ', ' + str(j) + ', Allfunc.cg' + str(i) + str(j) + '(currentApprox));\n')
file.close()
| file = open('JacobiMatrix.java', 'w')
for i in range(10):
for j in range(10):
file.write('jacobiMatrix.setEntry(' + str(i) + ', ' + str(j) + ', Allfunc.cg' + str(i) + str(j) + '(currentApprox));\n')
file.close() |
#!/usr/bin/python2
lst = []
with open('lst.txt', 'r') as f:
lst = f.read().split('\n')
i=1
for img in lst:
if 'resized' in img:
with open(img, 'r') as rd:
with open("combined/%05d.%s.png" % (i, img.split('.')[1]), 'w') as wr:
wr.write(rd.read())
i+=1
| lst = []
with open('lst.txt', 'r') as f:
lst = f.read().split('\n')
i = 1
for img in lst:
if 'resized' in img:
with open(img, 'r') as rd:
with open('combined/%05d.%s.png' % (i, img.split('.')[1]), 'w') as wr:
wr.write(rd.read())
i += 1 |
class Task:
def __init__(self):
self.name = "";
self.active = False;
def activate(self):
pass
def update(self, dt):
pass
def is_complete(self):
pass
def close(self):
pass
| class Task:
def __init__(self):
self.name = ''
self.active = False
def activate(self):
pass
def update(self, dt):
pass
def is_complete(self):
pass
def close(self):
pass |
'''
define some function to use.
'''
def bytes_to_int(bytes_string, order_type):
'''
the bind of the int.from_bytes function.
'''
return int.from_bytes(bytes_string, byteorder=order_type)
def bits_to_int(bit_string):
'''
the bind of int(string, 2) function.
'''
return int... | """
define some function to use.
"""
def bytes_to_int(bytes_string, order_type):
"""
the bind of the int.from_bytes function.
"""
return int.from_bytes(bytes_string, byteorder=order_type)
def bits_to_int(bit_string):
"""
the bind of int(string, 2) function.
"""
return int(bit_string, 2... |
def _calc_product(series, start_idx, end_idx):
product = 1
for digit in series[start_idx:end_idx + 1]:
product *= int(digit)
return product
def largest_product_in_series(num_digits, series):
largest_product = 0
for i in range(num_digits, len(series) + 1):
product = _calc_product(se... | def _calc_product(series, start_idx, end_idx):
product = 1
for digit in series[start_idx:end_idx + 1]:
product *= int(digit)
return product
def largest_product_in_series(num_digits, series):
largest_product = 0
for i in range(num_digits, len(series) + 1):
product = _calc_product(ser... |
class Solution:
def countOfAtoms(self, formula: str) -> str:
formula = "(" + formula + ")"
l = len(formula)
def mmerge(dst, src, xs):
for k, v in src.items():
t = dst.get(k, 0)
dst[k] = v * xs + t
def aux(st):
nonlocal formula... | class Solution:
def count_of_atoms(self, formula: str) -> str:
formula = '(' + formula + ')'
l = len(formula)
def mmerge(dst, src, xs):
for (k, v) in src.items():
t = dst.get(k, 0)
dst[k] = v * xs + t
def aux(st):
nonlocal fo... |
#Program to be tested
def boarding(seat_number):
if seat_number >= 1 and seat_number <= 25:
batch_no = 1
elif seat_number >= 26 and seat_number <= 100:
batch_no = 2
elif seat_number >= 101 and seat_number <= 200:
batch_no = 3
else:
batch_no = -1
return batch_no
| def boarding(seat_number):
if seat_number >= 1 and seat_number <= 25:
batch_no = 1
elif seat_number >= 26 and seat_number <= 100:
batch_no = 2
elif seat_number >= 101 and seat_number <= 200:
batch_no = 3
else:
batch_no = -1
return batch_no |
# PRE PROCESSING
def symmetric_NaN_replacement(dataset):
np_dataset = dataset.to_numpy()
for col in range(0,(np_dataset.shape[1])):
ss_idx = 0
for row in range(1,(dataset.shape[0]-1)):
if (np.isnan(np_dataset[row,col]) and (~np.isnan(np_dataset[row-1,col]))): # if a NaN is found, an... | def symmetric__na_n_replacement(dataset):
np_dataset = dataset.to_numpy()
for col in range(0, np_dataset.shape[1]):
ss_idx = 0
for row in range(1, dataset.shape[0] - 1):
if np.isnan(np_dataset[row, col]) and ~np.isnan(np_dataset[row - 1, col]):
ss_idx = row
... |
name0_0_1_0_0_2_0 = None
name0_0_1_0_0_2_1 = None
name0_0_1_0_0_2_2 = None
name0_0_1_0_0_2_3 = None
name0_0_1_0_0_2_4 = None | name0_0_1_0_0_2_0 = None
name0_0_1_0_0_2_1 = None
name0_0_1_0_0_2_2 = None
name0_0_1_0_0_2_3 = None
name0_0_1_0_0_2_4 = None |
# -*- coding: utf-8 -*-
__title__ = 'pyginx'
__version__ = '0.1.13.7.7'
__description__ = ''
__author__ = 'wrmsr'
__author_email__ = 'timwilloney@gmail.com'
__url__ = 'https://github.com/wrmsr/pyginx'
| __title__ = 'pyginx'
__version__ = '0.1.13.7.7'
__description__ = ''
__author__ = 'wrmsr'
__author_email__ = 'timwilloney@gmail.com'
__url__ = 'https://github.com/wrmsr/pyginx' |
path = r'c:\users\raibows\desktop\emma.txt'
file = open(path, 'r')
s = file.readlines()
file.close()
r = [i.swapcase() for i in s]
file = open(path, 'w')
file.writelines(r)
file.close()
| path = 'c:\\users\\raibows\\desktop\\emma.txt'
file = open(path, 'r')
s = file.readlines()
file.close()
r = [i.swapcase() for i in s]
file = open(path, 'w')
file.writelines(r)
file.close() |
class Config(object):
def __init__(self):
# directories
self.save_dir = ''
self.log_dir = ''
self.train_data_file = ''
self.val_data_file = ''
# input
self.patch_size = [42, 42, 1]
self.N = self.patch_size[0]*self.patch_size[1]
... | class Config(object):
def __init__(self):
self.save_dir = ''
self.log_dir = ''
self.train_data_file = ''
self.val_data_file = ''
self.patch_size = [42, 42, 1]
self.N = self.patch_size[0] * self.patch_size[1]
self.pre_n_layers = 3
self.pregconv_n_layer... |
CAS_HEADERS = ('Host', 'Port', 'ID', 'Operator',
'NMEA', 'Country', 'Latitude', 'Longitude',
'FallbackHost', 'FallbackPort', 'Site', 'Other Details', 'Distance')
NET_HEADERS = ('ID', 'Operator', 'Authentication',
'Fee', 'Web-Net', 'Web-Str', 'Web-Reg', 'Other Details', 'Dis... | cas_headers = ('Host', 'Port', 'ID', 'Operator', 'NMEA', 'Country', 'Latitude', 'Longitude', 'FallbackHost', 'FallbackPort', 'Site', 'Other Details', 'Distance')
net_headers = ('ID', 'Operator', 'Authentication', 'Fee', 'Web-Net', 'Web-Str', 'Web-Reg', 'Other Details', 'Distance')
str_headers = ('Mountpoint', 'ID', 'Fo... |
__version__ = '0.1'
supported_aln_types = ('blast', 'sam', 'xml')
supported_db_types = ('nt', 'nr','cds', 'genome', 'none')
consensus_aln_types = ('xml',)
| __version__ = '0.1'
supported_aln_types = ('blast', 'sam', 'xml')
supported_db_types = ('nt', 'nr', 'cds', 'genome', 'none')
consensus_aln_types = ('xml',) |
def for_G():
for row in range(7):
for col in range(5):
if (col==0 and (row!=0 and row!=6)) or ((row==0 or row==6) and (col>0)) or (row==3 and col>1) or (row>3 and col==4):
print("*",end=" ")
else:
print(end=" ")
print()
def while_G(... | def for_g():
for row in range(7):
for col in range(5):
if col == 0 and (row != 0 and row != 6) or ((row == 0 or row == 6) and col > 0) or (row == 3 and col > 1) or (row > 3 and col == 4):
print('*', end=' ')
else:
print(end=' ')
print()
def w... |
def solution(A, K):
# if length is equal to K nothing changes
if K == len(A):
return A
# if all elements are the same, nothing change
if all([item == A[0] for item in A]):
return A
N = len(A)
_A = [0] * N
for ind in range(N):
transf_ind = ind + K
_A[... | def solution(A, K):
if K == len(A):
return A
if all([item == A[0] for item in A]):
return A
n = len(A)
_a = [0] * N
for ind in range(N):
transf_ind = ind + K
_A[transf_ind - transf_ind // N * N] = A[ind]
return _A |
# *###################
# * SYMBOL TABLE
# *###################
class SymbolTable:
def __init__(self, parent=None):
self.symbols = {}
self.parent = parent
def get(self, name):
value = self.symbols.get(name, None)
if value is None and self.parent:
return self.parent.g... | class Symboltable:
def __init__(self, parent=None):
self.symbols = {}
self.parent = parent
def get(self, name):
value = self.symbols.get(name, None)
if value is None and self.parent:
return self.parent.get(name)
return value
def set(self, name, value):
... |
#!/usr/bin/env python3
try:
print('If you provide a legal file name, this program will output the last two lines of the song to that file...')
print('\nMary had a little lamb,')
answersnow = input('With fleece as white as (enter your file name): ')
answersnowobj = open(answersnow, 'w')
except:
print... | try:
print('If you provide a legal file name, this program will output the last two lines of the song to that file...')
print('\nMary had a little lamb,')
answersnow = input('With fleece as white as (enter your file name): ')
answersnowobj = open(answersnow, 'w')
except:
print('Error with that file ... |
def solve_knapsack(profits, weights, capacity):
# basic checks
n = len(profits)
if capacity <= 0 or n == 0 or len(weights) != n:
return 0
dp = [0 for x in range(capacity + 1)] # <<<<<<<<<<
# if we have only one weight, we will take it if it is not more than the capacity
for c in range... | def solve_knapsack(profits, weights, capacity):
n = len(profits)
if capacity <= 0 or n == 0 or len(weights) != n:
return 0
dp = [0 for x in range(capacity + 1)]
for c in range(0, capacity + 1):
if weights[0] <= c:
dp[c] = profits[0]
for i in range(1, n):
for c in ... |
input1 = input("Insira a palavra #1")
input2 = input("Insira a palavra #2")
input3 = input("Insira a palavra #3")
input3 = input3.upper().replace('A', '').replace('E', '').replace('I', '').replace('O', '').replace('U', '')
print(input1.upper())
print(input2.lower())
print(input3) | input1 = input('Insira a palavra #1')
input2 = input('Insira a palavra #2')
input3 = input('Insira a palavra #3')
input3 = input3.upper().replace('A', '').replace('E', '').replace('I', '').replace('O', '').replace('U', '')
print(input1.upper())
print(input2.lower())
print(input3) |
# Define a simple function that prints x
def f(x):
x += 1
print(x)
# Set y
y = 10
# Call the function
f(y)
# Print y to see if it changed
print(y) | def f(x):
x += 1
print(x)
y = 10
f(y)
print(y) |
#
# @lc app=leetcode id=922 lang=python3
#
# [922] Sort Array By Parity II
#
# @lc code=start
class Solution:
def sortArrayByParityII(self, a: List[int]) -> List[int]:
i = 0 # pointer for even misplaced
j = 1 # pointer for odd misplaced
sz = len(a)
# invariant: for every mi... | class Solution:
def sort_array_by_parity_ii(self, a: List[int]) -> List[int]:
i = 0
j = 1
sz = len(a)
while i < sz and j < sz:
if a[i] % 2 == 0:
i += 2
elif a[j] % 2 == 1:
j += 2
else:
(a[i], a[j]) =... |
class StringUtil:
@staticmethod
def is_empty(string):
if string is None or string.strip() == "":
return True
else:
return False
@staticmethod
def is_not_empty(string):
return not StringUtil.is_empty(string)
| class Stringutil:
@staticmethod
def is_empty(string):
if string is None or string.strip() == '':
return True
else:
return False
@staticmethod
def is_not_empty(string):
return not StringUtil.is_empty(string) |
#!python3
#encoding:utf-8
class Json2Sqlite(object):
def __init__(self):
pass
def BoolToInt(self, bool_value):
if True == bool_value:
return 1
else:
return 0
def IntToBool(self, int_value):
if 0 == int_value:
return False
else:
... | class Json2Sqlite(object):
def __init__(self):
pass
def bool_to_int(self, bool_value):
if True == bool_value:
return 1
else:
return 0
def int_to_bool(self, int_value):
if 0 == int_value:
return False
else:
return True... |
INPUT = {
"google": {
"id_token": ""
},
"github": {
"code": "",
"state": ""
}
}
| input = {'google': {'id_token': ''}, 'github': {'code': '', 'state': ''}} |
base=10
height=5
area=1/2*(base*height)
print("Area of our triangle is : ", area)
file = open("/Users/lipingzhang/Desktop/program/pycharm/seq2seq/MNIST_data/0622_train_features.csv","r")
lines = []
with file as myFile:
for line in file:
feat = []
line = line.split(',')
for i in range(0, len... | base = 10
height = 5
area = 1 / 2 * (base * height)
print('Area of our triangle is : ', area)
file = open('/Users/lipingzhang/Desktop/program/pycharm/seq2seq/MNIST_data/0622_train_features.csv', 'r')
lines = []
with file as my_file:
for line in file:
feat = []
line = line.split(',')
for i in... |
def main():
A=input("Enter the string")
A1=A[0:2:1]
A2=A[-2::1]
print(A1)
print(A2)
A3=(A1+A2)
print("The new string is " ,A3)
if(__name__== '__main__'):
main()
| def main():
a = input('Enter the string')
a1 = A[0:2:1]
a2 = A[-2::1]
print(A1)
print(A2)
a3 = A1 + A2
print('The new string is ', A3)
if __name__ == '__main__':
main() |
'''
Kattis - memorymatch
Consider the 2 different corner cases and the rest is not too hard.
Time: O(num_opens), Space: O(n)
'''
n = int(input())
num_opens = int(input())
cards = {}
turned_off = set()
for i in range(num_opens):
x, y, cx, cy = input().split()
x, y = int(x), int(y)
if not cx in cards:
... | """
Kattis - memorymatch
Consider the 2 different corner cases and the rest is not too hard.
Time: O(num_opens), Space: O(n)
"""
n = int(input())
num_opens = int(input())
cards = {}
turned_off = set()
for i in range(num_opens):
(x, y, cx, cy) = input().split()
(x, y) = (int(x), int(y))
if not cx in cards:
... |
# Copyright 2020 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | class Tensorforceconfig(object):
def __init__(self, *, buffer_observe=False, create_debug_assertions=False, create_tf_assertions=True, device='CPU', eager_mode=False, enable_int_action_masking=True, name='agent', seed=None, tf_log_level=40):
assert buffer_observe is False or buffer_observe == 'episode' or ... |
# John McDonough
# github - movinalot
# Advent of Code 2015
testing = 0
debug = 0
day = "03"
year = "2015"
part = "1"
answer = None
with open("puzzle_data_" + day + "_" + year + ".txt") as f:
puzzle_data = f.read()
if testing:
puzzle_data = ">"
#puzzle_data = "^>v<"
#puzzle_data ... | testing = 0
debug = 0
day = '03'
year = '2015'
part = '1'
answer = None
with open('puzzle_data_' + day + '_' + year + '.txt') as f:
puzzle_data = f.read()
if testing:
puzzle_data = '>'
if debug:
print(puzzle_data)
houses = {}
x = 0
y = 0
def update_present_count(x, y):
if (x, y) in houses:
hous... |
# string methods
course = 'Python for Beginners'
print('Original = ' + course)
print(course.upper())
print(course.lower())
print(course.find('P')) # finds the index of P which is 0
print(course.replace('Beginners', 'Absolute Beginners'))
print('Python' in course) # Boolean value
| course = 'Python for Beginners'
print('Original = ' + course)
print(course.upper())
print(course.lower())
print(course.find('P'))
print(course.replace('Beginners', 'Absolute Beginners'))
print('Python' in course) |
class Event:
def __init__(self):
self.listeners = set()
def __call__(self, *args, **kwargs):
for listener in self.listeners:
listener(*args, **kwargs)
def subscribe(self, listener):
self.listeners.add(listener)
| class Event:
def __init__(self):
self.listeners = set()
def __call__(self, *args, **kwargs):
for listener in self.listeners:
listener(*args, **kwargs)
def subscribe(self, listener):
self.listeners.add(listener) |
# currently unused; to be tested and further refined prior to final csv handover
byline_replacementlist = [
"Exclusive ",
" And ",
# jobs
"National",
"Correspondent",
"Political",
"Health " ,
"Political",
"Education" ,
"Commentator",
"Regional",
"Agencies",
"Defence",
"Fashion",
"Music",
"Social Iss... | byline_replacementlist = ['Exclusive ', ' And ', 'National', 'Correspondent', 'Political', 'Health ', 'Political', 'Education', 'Commentator', 'Regional', 'Agencies', 'Defence', 'Fashion', 'Music', 'Social Issues', 'Reporter', 'Chief', 'Business', 'Workplace', 'Editor', 'Indulge', 'Science', 'Sunday', 'Saturdays', 'Wri... |
# read input
file = open("day_two_input.txt", 'r')
# compile to list
raw_data = file.read().splitlines()
valid_count = 0
# iterate over all lines
for line in raw_data:
line_data = line.split()
# find min/max group from line
required_value_list = line_data[0].split('-')
# define min/max
min = int(... | file = open('day_two_input.txt', 'r')
raw_data = file.read().splitlines()
valid_count = 0
for line in raw_data:
line_data = line.split()
required_value_list = line_data[0].split('-')
min = int(required_value_list[0])
max = int(required_value_list[1])
character = line_data[1].split(':')[0]
passwo... |
__title__ = 'SQL Python for Deep Learning'
__version__ = '0.1'
__author__ = 'Miguel Gonzalez-Fierro'
__license__ = 'MIT license'
# Synonym
VERSION = __version__
LICENSE = __license__
| __title__ = 'SQL Python for Deep Learning'
__version__ = '0.1'
__author__ = 'Miguel Gonzalez-Fierro'
__license__ = 'MIT license'
version = __version__
license = __license__ |
#
# Complete the 'flippingMatrix' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY matrix as parameter.
#
def flippingMatrix(matrix):
n = len(matrix) - 1
max_sum = 0
for i in range(len(matrix) // 2):
for j in range(len(matrix) // 2):
... | def flipping_matrix(matrix):
n = len(matrix) - 1
max_sum = 0
for i in range(len(matrix) // 2):
for j in range(len(matrix) // 2):
top_left = matrix[i][j]
top_right = matrix[i][n - j]
bottom_left = matrix[n - i][j]
bottom_right = matrix[n - i][n - j]
... |
#
# PySNMP MIB module SIAE-UNITYPE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file://./sm_unitype.mib
# Produced by pysmi-0.3.2 at Fri Jul 19 08:22:05 2019
# On host 0e190c6811ee platform Linux version 4.9.125-linuxkit by user root
# Using Python version 3.7.3 (default, Apr 3 2019, 05:39:12)
#
OctetString, Object... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ... |
class hash_list():
def __init__(self):
self.hash_list = {}
def add(self, *args):
if args:
for item in args:
key = self._key(item)
if self.hash_list.get(key):
self.hash_list[key].append(item)
else:
... | class Hash_List:
def __init__(self):
self.hash_list = {}
def add(self, *args):
if args:
for item in args:
key = self._key(item)
if self.hash_list.get(key):
self.hash_list[key].append(item)
else:
... |
class Parent():
def __init__(self, last_name, eye_color):
print("Parent Constructor Called.")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last name - " + self.last_name)
print("Eye color - " + self.eye_color)
class Chi... | class Parent:
def __init__(self, last_name, eye_color):
print('Parent Constructor Called.')
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print('Last name - ' + self.last_name)
print('Eye color - ' + self.eye_color)
class Child(Parent):
... |
# Mumbling
def accum(s):
counter = 0
answer = ''
for char in s:
counter += 1
answer += char.upper()
for i in range(counter - 1):
answer += char.lower()
if counter < len(s):
answer += '-'
return answer
# Alternative solution
def... | def accum(s):
counter = 0
answer = ''
for char in s:
counter += 1
answer += char.upper()
for i in range(counter - 1):
answer += char.lower()
if counter < len(s):
answer += '-'
return answer
def accum2(s):
answer = ''
for i in range(len(s))... |
CALLING = 0
WAITING = 1
IN_VEHICLE = 2
ARRIVED = 3
DISAPPEARED = 4 | calling = 0
waiting = 1
in_vehicle = 2
arrived = 3
disappeared = 4 |
def print_progress(iteration, total, start_time, print_every=1e-2):
progress = (iteration + 1) / total
if iteration == total - 1:
print("Completed in {}s.\n".format(int(time() - start_time)))
elif (iteration + 1) % max(1, int(total * print_every / 100)) == 0:
print("{:.2f}% completed. Time ... | def print_progress(iteration, total, start_time, print_every=0.01):
progress = (iteration + 1) / total
if iteration == total - 1:
print('Completed in {}s.\n'.format(int(time() - start_time)))
elif (iteration + 1) % max(1, int(total * print_every / 100)) == 0:
print('{:.2f}% completed. Time -... |
def solve(heights):
temp = heights[0]
for height in heights[1:]:
if height > temp:
temp = height
else:
print(temp)
return
print(temp)
return
t = int(input())
heights = list(map(int, input().split()))
solve(heights)
| def solve(heights):
temp = heights[0]
for height in heights[1:]:
if height > temp:
temp = height
else:
print(temp)
return
print(temp)
return
t = int(input())
heights = list(map(int, input().split()))
solve(heights) |
commands = []
with open('./input', encoding='utf8') as file:
for line in file.readlines():
cmd, cube = line.strip().split(" ")
ranges = [
[int(val)+50 for val in dimension[2:].split('..')]
for dimension in cube.split(',')
]
commands.append({'cmd': cmd, 'range... | commands = []
with open('./input', encoding='utf8') as file:
for line in file.readlines():
(cmd, cube) = line.strip().split(' ')
ranges = [[int(val) + 50 for val in dimension[2:].split('..')] for dimension in cube.split(',')]
commands.append({'cmd': cmd, 'ranges': ranges})
reactor = [[[0 for... |
class MorphSerializable:
def __init__(self, properties_to_serialize, property_dict):
self.property_dict = property_dict
self.properties_to_serialize = properties_to_serialize
| class Morphserializable:
def __init__(self, properties_to_serialize, property_dict):
self.property_dict = property_dict
self.properties_to_serialize = properties_to_serialize |
#
# PySNMP MIB module F5-BIGIP-GLOBAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F5-BIGIP-GLOBAL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:11:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
'''
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
19. Remove Nth Node From End of List
Medium
7287
370
Add to List
Share
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:... | """
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
19. Remove Nth Node From End of List
Medium
7287
370
Add to List
Share
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:... |
# -*- coding: utf-8 -*-
table = [
{
'id': 500,
'posizione_lat': '45.467269',
'posizione_long': '9.214908',
},
{
'id': 501,
'posizione_lat': '45.481383',
'posizione_long': '9.169981',
}
]
| table = [{'id': 500, 'posizione_lat': '45.467269', 'posizione_long': '9.214908'}, {'id': 501, 'posizione_lat': '45.481383', 'posizione_long': '9.169981'}] |
A, B = input().split()
a = sum(map(int, A))
b = sum(map(int, B))
print(a if a > b else b)
| (a, b) = input().split()
a = sum(map(int, A))
b = sum(map(int, B))
print(a if a > b else b) |
'''
MBEANN settings for solving the OpenAI Gym problem.
'''
class SettingsEA:
# --- Evolutionary algorithm settings. --- #
popSize = 500
maxGeneration = 500 # 0 to (max_generation - 1)
isMaximizingFit = True
eliteSize = 0
tournamentSize = 20
tournamentBestN = 1 # Select best N individua... | """
MBEANN settings for solving the OpenAI Gym problem.
"""
class Settingsea:
pop_size = 500
max_generation = 500
is_maximizing_fit = True
elite_size = 0
tournament_size = 20
tournament_best_n = 1
class Settingsmbeann:
in_size = None
out_size = None
hid_size = 0
is_reccurent = ... |
TAB = " "
NEWLINE = "\n"
def generate_converter(bits_precision, colors_list_hex, entity_name="sprite_converter"):
l = []
# Entity declaration
l += ["library IEEE;"]
l += ["use IEEE.std_logic_1164.all;"]
l += ["use IEEE.numeric_std.all;"]
l += [""]
l += ["entity " + entity_name + " is"]... | tab = ' '
newline = '\n'
def generate_converter(bits_precision, colors_list_hex, entity_name='sprite_converter'):
l = []
l += ['library IEEE;']
l += ['use IEEE.std_logic_1164.all;']
l += ['use IEEE.numeric_std.all;']
l += ['']
l += ['entity ' + entity_name + ' is']
l += [TAB + 'port (']
... |
# Default logging settings for DeepRank.
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'brief': {
'format': '%(message)s',
},
'precise': {
'format': '%(levelname)s: %(message)s',
},
},
'filters': {
... | default_logging = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'brief': {'format': '%(message)s'}, 'precise': {'format': '%(levelname)s: %(message)s'}}, 'filters': {'require_debug': {'()': 'deeprank.utils.logger_helper.requireDebugFilter'}, 'use_only_info_level': {'()': 'deeprank.utils.logger_helper... |
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
longest_streak = 0
num_set = set(nums)
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
... | class Solution:
def longest_consecutive(self, nums: List[int]) -> int:
longest_streak = 0
num_set = set(nums)
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
... |
# Databricks notebook source
print("hello world")
# COMMAND ----------
print("hello world2")
| print('hello world')
print('hello world2') |
# Problem Statement
# The previous version of Quicksort was easy to understand, but it was not optimal. It required copying the numbers into other arrays, which takes up space and time. To make things faster, one can create an "in-place" version of Quicksort, where the numbers are all sorted within the array itself.
... | def quick(A, p, r):
if p < r:
q = partition(A, p, r)
quick(A, p, q - 1)
quick(A, q + 1, r)
def partition(A, p, r):
x = A[r]
i = p - 1
for j in range(p, r):
if A[j] <= x:
i += 1
(A[i], A[j]) = (A[j], A[i])
(A[i + 1], A[r]) = (A[r], A[i + 1])
... |
# WARNING: Changing line numbers of code in this file will break collection tests that use tracing to check paths and line numbers.
# Also, do not import division from __future__ as this will break detection of __future__ inheritance on Python 2.
def question():
return 3 / 2
| def question():
return 3 / 2 |
CYBERCRIME_RESPONSE_MOCK = {
'success': True,
'message': 'Malicious: Keitaro'
}
CYBERCRIME_ERROR_RESPONSE_MOCK = {
'error': 'Server unavailable'
}
EXPECTED_DELIBERATE_RESPONSE = {
'data': {
'verdicts': {
'count': 1,
'docs': [
{
'disp... | cybercrime_response_mock = {'success': True, 'message': 'Malicious: Keitaro'}
cybercrime_error_response_mock = {'error': 'Server unavailable'}
expected_deliberate_response = {'data': {'verdicts': {'count': 1, 'docs': [{'disposition': 2, 'observable': {'type': 'ip', 'value': '104.24.123.62'}, 'type': 'verdict'}]}}}
expe... |
num = input()
prime = 0
non_prime = 0
is_prime = True
while num != "stop":
num = int(num)
if num < 0:
print(f"Number is negative.")
num = input()
continue
for i in range(2, (num+1)//2):
if num % i == 0:
non_prime += num
is_prime = False
br... | num = input()
prime = 0
non_prime = 0
is_prime = True
while num != 'stop':
num = int(num)
if num < 0:
print(f'Number is negative.')
num = input()
continue
for i in range(2, (num + 1) // 2):
if num % i == 0:
non_prime += num
is_prime = False
... |
def mujoco():
return dict(
nsteps=2048,
nminibatches=32,
lam=0.95,
gamma=0.99,
noptepochs=10,
log_interval=1,
ent_coef=0.0,
lr=lambda f: 3e-4 * f,
cliprange=0.2,
value_network='copy'
)
# Daniel: more accurately matches the PPO pape... | def mujoco():
return dict(nsteps=2048, nminibatches=32, lam=0.95, gamma=0.99, noptepochs=10, log_interval=1, ent_coef=0.0, lr=lambda f: 0.0003 * f, cliprange=0.2, value_network='copy')
def atari():
return dict(nsteps=128, nminibatches=4, lam=0.95, gamma=0.99, noptepochs=4, log_interval=1, ent_coef=0.01, lr=lam... |
#Q6. Given a string "I love Python programming language", extract the word "programming" (use slicing)
string= "I love Python programming language"
print(string[14:25]) | string = 'I love Python programming language'
print(string[14:25]) |
# Copyright 2022 Google LLC
#
# 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 by applicable law or agreed to in writing, ... | def test_types(plan_runner):
_disks = '[{\n name = "data1"\n size = "10"\n source_type = "image"\n source = "image-1"\n options = null\n }, {\n name = "data2"\n size = "20"\n source_type = "snapshot"\n source = "snapshot-2"\n options = null\n }, {\n name = "data3"\n size = null... |
#
# PySNMP MIB module ASCEND-MIBT1NET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBT1NET-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:12:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration')
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_const... |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def vulkan_memory_allocator_repository():
maybe(
http_archive,
name = "vulkan-memory-allocator",
urls = [
"https://github.com/GPUOpen-LibrariesAndS... | load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def vulkan_memory_allocator_repository():
maybe(http_archive, name='vulkan-memory-allocator', urls=['https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator/archive/7c482850... |
x = ["Python", "Java", "Typescript", "Rust"]
# COmprobar si un valor pertenece a esa variable / objeto
a = "python" in x # False
a = "Python" in x # True
a = "Typescrip" in x # False
a = "Typescript" in x # True
a = "python" not in x # True
a = "Python" not in x # False
a = "Typescrip" not in x # True
a = "Typescr... | x = ['Python', 'Java', 'Typescript', 'Rust']
a = 'python' in x
a = 'Python' in x
a = 'Typescrip' in x
a = 'Typescript' in x
a = 'python' not in x
a = 'Python' not in x
a = 'Typescrip' not in x
a = 'Typescript' not in x
x = 'Anartz'
a = 'a' in x
a = 'nar' in x
a = 'anar' in x
a = 'Anar' in x
print('Final') |
#
# PySNMP MIB module MY-FILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MY-FILE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:06:31 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... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
'''
This is code that will help a game master/dungeon master get the initiative and health of the players,
put them all in correct initiative order, then help you go through the turns until combat is over.
'''
def validate_num_input(user_input):
while True:
try:
num_input = int(input(user_in... | """
This is code that will help a game master/dungeon master get the initiative and health of the players,
put them all in correct initiative order, then help you go through the turns until combat is over.
"""
def validate_num_input(user_input):
while True:
try:
num_input = int(input(user_in... |
expected_output = {
'ids': {
'100': {
'state': 'active',
'type': 'icmp-jitter',
'destination': '192.0.2.2',
'rtt_stats': '100',
'rtt_stats_msecs': 100,
'return_code': 'OK',
'last_run': '22:49:53 PST Tue May 3 2011'
}... | expected_output = {'ids': {'100': {'state': 'active', 'type': 'icmp-jitter', 'destination': '192.0.2.2', 'rtt_stats': '100', 'rtt_stats_msecs': 100, 'return_code': 'OK', 'last_run': '22:49:53 PST Tue May 3 2011'}, '101': {'state': 'active', 'type': 'udp-jitter', 'destination': '192.0.2.2', 'rtt_stats': '100', 'rtt_stat... |
def callvars_subcmd(analysis:str, args:list, outdir:str=None,env:str=None) -> None:
if 'help' in args or 'h' in args:
print("Help:")
print("bam --> gvcf")
print("==========================")
print("call-variants <sample-name> <input-files> [-r reference] ")
print("call-varia... | def callvars_subcmd(analysis: str, args: list, outdir: str=None, env: str=None) -> None:
if 'help' in args or 'h' in args:
print('Help:')
print('bam --> gvcf')
print('==========================')
print('call-variants <sample-name> <input-files> [-r reference] ')
print('call-v... |
sum = 0
num1, num2, temp = 1, 2, 1
while (num2 <= 4000000):
if(num2%2==0):
sum += num2
temp = num1
num1 = num2
num2 += temp
print(sum) | sum = 0
(num1, num2, temp) = (1, 2, 1)
while num2 <= 4000000:
if num2 % 2 == 0:
sum += num2
temp = num1
num1 = num2
num2 += temp
print(sum) |
def perm_check(checkSet, mainSet):
checkSet = set(checkSet)
mainSet = set(mainSet)
if checkSet.issubset(mainSet):
return True
else:
return False
def is_subset(checkSet, mainSet):
checkSet = set(checkSet)
mainSet = set(mainSet)
if checkSet.issubset(mainSet):
return ... | def perm_check(checkSet, mainSet):
check_set = set(checkSet)
main_set = set(mainSet)
if checkSet.issubset(mainSet):
return True
else:
return False
def is_subset(checkSet, mainSet):
check_set = set(checkSet)
main_set = set(mainSet)
if checkSet.issubset(mainSet):
retur... |
def addition(num):
b=num+1
return b
| def addition(num):
b = num + 1
return b |
RED = 0xFF0000
MAROON = 0x800000
ORANGE = 0xFF8000
YELLOW = 0xFFFF00
OLIVE = 0x808000
GREEN = 0x008000
AQUA = 0x00FFFF
TEAL = 0x008080
BLUE = 0x0000FF
NAVY = 0x000080
PURPLE = 0x800080
PINK = 0xFF0080
WHITE = 0xFFFFFF
BLACK = 0x000000
| red = 16711680
maroon = 8388608
orange = 16744448
yellow = 16776960
olive = 8421376
green = 32768
aqua = 65535
teal = 32896
blue = 255
navy = 128
purple = 8388736
pink = 16711808
white = 16777215
black = 0 |
# similar to partial application, but only with one level deeper
def curry_add(x):
def curry_add_inner(y):
def curry_add_inner_2(z):
return x + y + z
return curry_add_inner_2
return curry_add_inner
add_5 = curry_add(5)
add_5_and_6 = add_5(6)
print(add_5_and_6(7))
# or we can even... | def curry_add(x):
def curry_add_inner(y):
def curry_add_inner_2(z):
return x + y + z
return curry_add_inner_2
return curry_add_inner
add_5 = curry_add(5)
add_5_and_6 = add_5(6)
print(add_5_and_6(7))
print(curry_add(5)(6)(7)) |
def is_low_point(map: list[list[int]], x: int, y: int) -> bool:
m, n = len(map), len(map[0])
val = map[x][y]
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
x1, y1 = x + dx, y + dy
if x1 >= 0 and x1 < m and y1 >= 0 and y1 < n and val >= map[x1][y1]:
return False
return True
map = []
with open('... | def is_low_point(map: list[list[int]], x: int, y: int) -> bool:
(m, n) = (len(map), len(map[0]))
val = map[x][y]
for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
(x1, y1) = (x + dx, y + dy)
if x1 >= 0 and x1 < m and (y1 >= 0) and (y1 < n) and (val >= map[x1][y1]):
return False... |
#
# @lc app=leetcode id=207 lang=python3
#
# [207] Course Schedule
#
# @lc code=start
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = [[] for _ in range(numCourses)]
visit = [0]*numCourses
for x, y in prerequisites:
graph[x... | class Solution:
def can_finish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = [[] for _ in range(numCourses)]
visit = [0] * numCourses
for (x, y) in prerequisites:
graph[x].append(y)
def dfs(i):
if visit[i] == -1:
ret... |
# Sequential Digits
'''
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Inpu... | """
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Input: low = 1000, high =... |
class Callback():
callbacks = {}
def registerCallback(self, base, state):
print("registered %s for %s" % (state, base))
self.callbacks[state] = base
def runCallbacks(self):
for key,value in self.callbacks.items():
print("state=%s value=%s, type=%s" % (key, value, type(... | class Callback:
callbacks = {}
def register_callback(self, base, state):
print('registered %s for %s' % (state, base))
self.callbacks[state] = base
def run_callbacks(self):
for (key, value) in self.callbacks.items():
print('state=%s value=%s, type=%s' % (key, value, typ... |
a = 1; # Setting the variable a to 1
b = 2; # Setting the variable b to 2
print(a+b); # Using the arguments a and b added together using the print function.
| a = 1
b = 2
print(a + b) |
lista = [i for i in range(0,101)]
lista = [i for i in range(0,101) if i%2 == 0]
tupla = tuple( (i for i in range(0,101) if i%2 == 0))
diccionario = {i:valor for i, valor in enumerate(lista) if i<10}
print(lista)
print()
print(tupla)
print()
print(diccionario)
| lista = [i for i in range(0, 101)]
lista = [i for i in range(0, 101) if i % 2 == 0]
tupla = tuple((i for i in range(0, 101) if i % 2 == 0))
diccionario = {i: valor for (i, valor) in enumerate(lista) if i < 10}
print(lista)
print()
print(tupla)
print()
print(diccionario) |
# coding: utf-8
n = int(input())
d = {}
for i in range(n):
temp = input()
if temp in d.keys():
print(temp+str(d[temp]))
d[temp] += 1
else:
print('OK')
d[temp] = 1
| n = int(input())
d = {}
for i in range(n):
temp = input()
if temp in d.keys():
print(temp + str(d[temp]))
d[temp] += 1
else:
print('OK')
d[temp] = 1 |
def lis(a):
lis = [0] * len(a)
# lis[0] = a[0]
for i in range(0, len(a)):
max = -1
for j in range(0, i):
if a[i] > a[j]:
if max == -1 and max < lis[j] +1:
max = a[i]
if max == -1:
max = a[i]
lis[i] = max
return lis
if __name__ == '__main__':
A = [2, 3, 5, 4]
print(lis(A))
| def lis(a):
lis = [0] * len(a)
for i in range(0, len(a)):
max = -1
for j in range(0, i):
if a[i] > a[j]:
if max == -1 and max < lis[j] + 1:
max = a[i]
if max == -1:
max = a[i]
lis[i] = max
return lis
if __name__ == '... |
# Write an implementation of the Queue ADT using a Python list.
# Compare the performance of this implementation to the ImprovedQueue for a range of queue lengths.
class ListQueue:
def __init__(self):
self.list = []
def insert(self, cargo):
self.list.append(cargo)
def is_empty(self):
... | class Listqueue:
def __init__(self):
self.list = []
def insert(self, cargo):
self.list.append(cargo)
def is_empty(self):
return len(self.list) == 0
def remove(self):
if self.is_empty():
return None
listcargo = self.list[0]
self.list.remove(... |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
#print(new_class)
new_class.append('Peter Warden')
#print(new_class)
new_class.remove('Carla Gentry')
print(new_cla... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
new_class.append('Peter Warden')
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70... |
# add some debug printouts
debug = False
# dead code elimination
dce = False
# assume there will be no backwards
forward_only = True
# assume input tensors are dynamic
dynamic_shapes = True
# assume weight tensors are fixed size
static_weight_shapes = True
# enable some approximation algorithms
approximations = Fa... | debug = False
dce = False
forward_only = True
dynamic_shapes = True
static_weight_shapes = True
approximations = False
size_asserts = True
pick_loop_orders = True
inplace_buffers = False
class Cpp:
threads = -1
simdlen = None
min_chunk_size = 4096
cxx = ('g++-10', 'g++')
class Triton:
cudagraphs =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.