content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Reminder Application
A bare-bones task management application
TODAY
0. Talk about our schema
1. set up an sqlite3 database
2. get user's task information
3. convert the user's date and time information into a datetime object
4. commit our formatted user input to t... | """
Reminder Application
A bare-bones task management application
TODAY
0. Talk about our schema
1. set up an sqlite3 database
2. get user's task information
3. convert the user's date and time information into a datetime object
4. commit our formatted user input to the database
5. get the <N> most recent tasks
... |
#
# PySNMP MIB module EQLIPSEC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQLIPSEC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:05:24 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,... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) ... |
insts=set()
fi=open('rcpsp-features.csv')
for i,l in enumerate(fi):
if i:
insts.add(l.split(',')[0])
fi.close()
print(insts)
params=set()
fp=open('incparams-rcpsp.csv')
for l in fp:
params.add(l.strip())
fp.close()
print(params)
fr=open('/home/haroldo/inst/algsel/rcpsp/results.csv')
fro=open('rcpsp... | insts = set()
fi = open('rcpsp-features.csv')
for (i, l) in enumerate(fi):
if i:
insts.add(l.split(',')[0])
fi.close()
print(insts)
params = set()
fp = open('incparams-rcpsp.csv')
for l in fp:
params.add(l.strip())
fp.close()
print(params)
fr = open('/home/haroldo/inst/algsel/rcpsp/results.csv')
fro = o... |
#!/usr/bin/env python3
def binarray2int(binarray) -> int:
y: int = 0
for i, j in enumerate(binarray[::-1]):
y += j << i # Bitwise equivalent to j*(2**i)
return y
def no_op() -> None:
# The no-op function; it should obviously be empty!
pass
if __name__ == "__main__":
no_op()
| def binarray2int(binarray) -> int:
y: int = 0
for (i, j) in enumerate(binarray[::-1]):
y += j << i
return y
def no_op() -> None:
pass
if __name__ == '__main__':
no_op() |
# Time: O(N), n=nodes in tree
# Space: O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
self.df... | class Solution:
def distance_k(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
self.dfs(root, None)
output = []
q = [(target, 0)]
seen = set()
while q:
(cur_node, cur_dist) = q.pop(0)
if cur_node in seen:
continue
... |
arr = [128,63,242,87,151,147,50,369,239,248,205,346,299,73,335,189,105,293,37,214,333,137]
converted_arr = list(map(lambda x: x % 37, arr))
def convert_char(char_code):
if(char_code == 36): return '_'
if(char_code >= 26): return chr(48 - 26 + char_code)
return chr(65 + char_code)
def convert_arr(arr):
... | arr = [128, 63, 242, 87, 151, 147, 50, 369, 239, 248, 205, 346, 299, 73, 335, 189, 105, 293, 37, 214, 333, 137]
converted_arr = list(map(lambda x: x % 37, arr))
def convert_char(char_code):
if char_code == 36:
return '_'
if char_code >= 26:
return chr(48 - 26 + char_code)
return chr(65 + ch... |
def funcPenjumlahan(arr):
jumlah = 0
for num in arr:
jumlah += num
return jumlah
def funcPanjangArray(arr):
panjang = 0
for angg in arr:
panjang += 1
return panjang
def funcMedian(arr):
# cari panjang array
panjang = funcPanjangArray(arr)
if panjang % 2 == 1: ... | def func_penjumlahan(arr):
jumlah = 0
for num in arr:
jumlah += num
return jumlah
def func_panjang_array(arr):
panjang = 0
for angg in arr:
panjang += 1
return panjang
def func_median(arr):
panjang = func_panjang_array(arr)
if panjang % 2 == 1:
index = panjang /... |
c.NotebookApp.base_url = '/jupyter'
c.NotebookApp.iopub_data_rate_limit = 1000000000
c.NotebookApp.iopub_msg_rate_limit = 1000000000
c.NotebookApp.token = ''
c.NotebookApp.password = ''
| c.NotebookApp.base_url = '/jupyter'
c.NotebookApp.iopub_data_rate_limit = 1000000000
c.NotebookApp.iopub_msg_rate_limit = 1000000000
c.NotebookApp.token = ''
c.NotebookApp.password = '' |
class Solution(object):
def findPeakElement(self, nums):
if len(nums) == 1:
return 0
else:
return self.fpe(0, len(nums) - 1, nums)
def fpe(self, start, end, nums):
middle = (start + end) // 2
if (middle == 0 and nums[middle] > nums[middle + 1]) or (
... | class Solution(object):
def find_peak_element(self, nums):
if len(nums) == 1:
return 0
else:
return self.fpe(0, len(nums) - 1, nums)
def fpe(self, start, end, nums):
middle = (start + end) // 2
if middle == 0 and nums[middle] > nums[middle + 1] or (middl... |
flags = {
'ebee8289545fc134ed28828cec99407e': 'QCTF{c0ngra7ulat10ns_y0u_c4n_hacK_eld3r_traN5m1tt3rs_PFaLd0UgjS}',
'a1782fb2a091f0dd78444e5054ba6ca7': 'QCTF{c0ngra7ulat10ns_y0u_c4n_hacK_eld3r_traN5m1tt3rs_Iy0qYo1SXM}',
'e22e6f3353b938b4320e681fee71fad3': 'QCTF{c0ngra7ulat10ns_y0u_c4n_hacK_eld3r_traN5m1tt3rs_... | flags = {'ebee8289545fc134ed28828cec99407e': 'QCTF{c0ngra7ulat10ns_y0u_c4n_hacK_eld3r_traN5m1tt3rs_PFaLd0UgjS}', 'a1782fb2a091f0dd78444e5054ba6ca7': 'QCTF{c0ngra7ulat10ns_y0u_c4n_hacK_eld3r_traN5m1tt3rs_Iy0qYo1SXM}', 'e22e6f3353b938b4320e681fee71fad3': 'QCTF{c0ngra7ulat10ns_y0u_c4n_hacK_eld3r_traN5m1tt3rs_388u7GO0rC}',... |
'''
Author: jianzhnie
Date: 2022-01-05 17:00:43
LastEditTime: 2022-01-05 17:00:44
LastEditors: jianzhnie
Description:
'''
| """
Author: jianzhnie
Date: 2022-01-05 17:00:43
LastEditTime: 2022-01-05 17:00:44
LastEditors: jianzhnie
Description:
""" |
__all__ = ["network_common",
"network_tests"
]
| __all__ = ['network_common', 'network_tests'] |
def get_env_parameters(env):
obs = env.reset()
action_space = env.action_space.shape[0]
obs_size = obs['observation'].shape[0]
goal_size = obs['desired_goal'].shape[0]
env_params = {'action': action_space,
'observation': obs_size,
'goal': goal_size,
... | def get_env_parameters(env):
obs = env.reset()
action_space = env.action_space.shape[0]
obs_size = obs['observation'].shape[0]
goal_size = obs['desired_goal'].shape[0]
env_params = {'action': action_space, 'observation': obs_size, 'goal': goal_size, 'action_max': env.action_space.high[0], 'max_episo... |
__all__ = ['RedPanda']
class RedPanda(object):
def __init__(self, name, cuteness):
if not isinstance(cuteness, int):
raise TypeError("Cuteness is not of type int")
if cuteness < 2:
raise ValueError("Red panda is not cute enough")
self.name = name
self.cut... | __all__ = ['RedPanda']
class Redpanda(object):
def __init__(self, name, cuteness):
if not isinstance(cuteness, int):
raise type_error('Cuteness is not of type int')
if cuteness < 2:
raise value_error('Red panda is not cute enough')
self.name = name
self.cute... |
'''
We will assume that fertility is a linear function of the female illiteracy rate. That is, f=ai+b, where a is the slope and b
is the intercept. We can think of the intercept as the minimal fertility rate, probably somewhere between one and two. The slope tells us how the fertility rate varies with illiteracy. We c... | """
We will assume that fertility is a linear function of the female illiteracy rate. That is, f=ai+b, where a is the slope and b
is the intercept. We can think of the intercept as the minimal fertility rate, probably somewhere between one and two. The slope tells us how the fertility rate varies with illiteracy. We c... |
# problem A
'''
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split(' ')))
cnt = 0
for i in range(len(a)-1):
max_a = max(a[i],a[i+1])
min_a = min(a[i],a[i+1])
next_a = min_a * 2
while True:
if next_a < max_a:
next_a *... | """
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split(' ')))
cnt = 0
for i in range(len(a)-1):
max_a = max(a[i],a[i+1])
min_a = min(a[i],a[i+1])
next_a = min_a * 2
while True:
if next_a < max_a:
next_a *= 2
... |
def sum7(numbers):
sum = 0
i = 0
double = False
n = len(numbers)
if n == 0: return -1
while i < n:
sum += numbers[i]
if double:
sum += numbers[i]
double = False
if numbers[i] == 7: double = True
i += 1
return sum
print(sum7([1, 2]))
pr... | def sum7(numbers):
sum = 0
i = 0
double = False
n = len(numbers)
if n == 0:
return -1
while i < n:
sum += numbers[i]
if double:
sum += numbers[i]
double = False
if numbers[i] == 7:
double = True
i += 1
return sum
pri... |
class DummySolverWrapper(object):
'''dummy object used for testing to emulate the behavior of the SolverWrapper'''
def __init__(self, interface_data_dict):
self.interface_data_dict = interface_data_dict
def GetInterfaceData(self, data_name):
return self.interface_data_dict[data_name] | class Dummysolverwrapper(object):
"""dummy object used for testing to emulate the behavior of the SolverWrapper"""
def __init__(self, interface_data_dict):
self.interface_data_dict = interface_data_dict
def get_interface_data(self, data_name):
return self.interface_data_dict[data_name] |
grid = []
with open('input.txt', 'r') as f:
for line in f:
line = line.strip()
grid.append(line)
NROWS = len(grid)
NCOLS = len(grid[0])
trees_encountered = 0
row, col = 0, 0
drow, dcol = 1, 3
while row < NROWS:
location = grid[row][col]
if location == '#':
trees_encountered += 1
row += drow
... | grid = []
with open('input.txt', 'r') as f:
for line in f:
line = line.strip()
grid.append(line)
nrows = len(grid)
ncols = len(grid[0])
trees_encountered = 0
(row, col) = (0, 0)
(drow, dcol) = (1, 3)
while row < NROWS:
location = grid[row][col]
if location == '#':
trees_encountered +... |
full_name = "Mayuri B Upadhaya"
print(f"Hello {full_name}, would you like to learn some python today ?")
#name cases
another_name = "guess who's back"
print(another_name.lower())
print(another_name.upper())
print(another_name.title())
#Famous quote
quote = "You must go into the unknown, kill the part of y... | full_name = 'Mayuri B Upadhaya'
print(f'Hello {full_name}, would you like to learn some python today ?')
another_name = "guess who's back"
print(another_name.lower())
print(another_name.upper())
print(another_name.title())
quote = "You must go into the unknown, kill the part of yourself that doesn't help you.\n Rescue ... |
PACKAGES = {
"alcotest": ["1.1.0"],
"base": ["v0.12.0"],
"base_bigstring": ["v0.12.0"],
"ocaml-migrate-parsetree": ["1.7.3"],
"ppx_tools_versioned": ["5.4.0", ["ppx_tools_versioned.metaquot_402"]],
"ppxlib": ["0.8.1", ["ppxlib.metaquot"]],
"result": ["1.3"],
"unix": [],
"yojson": ["1... | packages = {'alcotest': ['1.1.0'], 'base': ['v0.12.0'], 'base_bigstring': ['v0.12.0'], 'ocaml-migrate-parsetree': ['1.7.3'], 'ppx_tools_versioned': ['5.4.0', ['ppx_tools_versioned.metaquot_402']], 'ppxlib': ['0.8.1', ['ppxlib.metaquot']], 'result': ['1.3'], 'unix': [], 'yojson': ['1.7.0']}
opam = struct(version='2.0', ... |
my_list = [7,8,2,4,3,2,1]
print("list =",my_list)
my_list.sort()
print("list.sort() =",my_list)
my_list = [7,8,2,4,3,2,1]
print("list =",my_list)
my_list.sort(reverse=True)
print("list.sort(reverse=True) =",my_list)
| my_list = [7, 8, 2, 4, 3, 2, 1]
print('list =', my_list)
my_list.sort()
print('list.sort() =', my_list)
my_list = [7, 8, 2, 4, 3, 2, 1]
print('list =', my_list)
my_list.sort(reverse=True)
print('list.sort(reverse=True) =', my_list) |
docker_build_with_requirements = '''
FROM docker.io/jupyter/minimal-notebook:latest
COPY requirements.txt requirements.txt
RUN python3 -m pip install -r requirements.txt
$user
'''
docker_build_without_requirements = '''
FROM docker.io/jupyter/minimal-notebook:latest
$user
'''
docker_yaml = '''
version: "3"
services:
... | docker_build_with_requirements = '\nFROM docker.io/jupyter/minimal-notebook:latest\nCOPY requirements.txt requirements.txt\nRUN python3 -m pip install -r requirements.txt\n$user\n'
docker_build_without_requirements = '\nFROM docker.io/jupyter/minimal-notebook:latest\n$user\n'
docker_yaml = '\nversion: "3"\nservices:\n ... |
projeto = input("Nome do projeto : ")
app = input("Nome do app: ")
local = input("Local: ")
arquivo = open('package.txt', 'w')
arquivo.write('Django start package\n\n')
arquivo.write('Este arquivo cria todo o ambiente do Django com o ambiente virtual venv, para iniciar, copie todos os comando a baixo e colar no cmd, n... | projeto = input('Nome do projeto : ')
app = input('Nome do app: ')
local = input('Local: ')
arquivo = open('package.txt', 'w')
arquivo.write('Django start package\n\n')
arquivo.write('Este arquivo cria todo o ambiente do Django com o ambiente virtual venv, para iniciar, copie todos os comando a baixo e colar no cmd, n ... |
#
# PySNMP MIB module STMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STMIB
# Produced by pysmi-0.3.4 at Wed May 1 15:11:10 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:23:15)
#
... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, single_value_constraint, constraints_union, value_size_constraint) ... |
DISCOVERY_TIMEOUT = 1
BIND_IP = ''
BIND_PORT = 2525
# Messaging Defaults
MSG_SIZE_BYTES = 4
MSG_TYPE_HB = 'hb'
MSG_TYPE_DISCOVER = 'discover'
MSG_TYPE_JOIN = 'join'
MSG_TYPE_PEER = 'peers'
MSG_TYPE_LEDGER = 'ledger'
MSG_TYPE_SUCCESS = '200'
MSG_TYPE_FAILURE = '404'
MSG_HB_FREQ = 5 # Minimum time in seconds between HB ... | discovery_timeout = 1
bind_ip = ''
bind_port = 2525
msg_size_bytes = 4
msg_type_hb = 'hb'
msg_type_discover = 'discover'
msg_type_join = 'join'
msg_type_peer = 'peers'
msg_type_ledger = 'ledger'
msg_type_success = '200'
msg_type_failure = '404'
msg_hb_freq = 5
msg_hb_ttl = 10 * MSG_HB_FREQ
msg_hb_timeout = 3
def init(... |
model = dict(
type='Classification',
backbone=dict(
type='MIMVisionTransformer',
arch='b',
patch_size=16,
final_norm=True,
finetune=False),
head=dict(type='MAELinprobeHead', num_classes=1000, embed_dim=768))
| model = dict(type='Classification', backbone=dict(type='MIMVisionTransformer', arch='b', patch_size=16, final_norm=True, finetune=False), head=dict(type='MAELinprobeHead', num_classes=1000, embed_dim=768)) |
# Read input as specified in the question.
# Print output as specified in the question.
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a = str(input())
if(is_palindrome(a) == True):
p... | def is_palindrome(s):
if len(s) < 1:
return True
elif s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a = str(input())
if is_palindrome(a) == True:
print('true')
else:
print('false') |
# An ATM contains Indian currency notes of 100, 500 and 2000. To withdraw cash from this ATM, the user has to enter the amount. The ATM then calculates the number of
# notes of each currency, i.e. of 100, 500 and 2000. Write a function findDenom(amount) that returns dictionary containing mapping of currency and its num... | def find_denom(amount):
dict1 = {}
a = 0
b = 0
c = 0
if amount >= 2000:
a = int(amount / 2000)
amount = amount - a * 2000
if amount >= 500:
b = int(amount / 500)
amount = amount - b * 500
if amount >= 100:
c = int(amount / 100)
amount = amount ... |
class Solution:
def countTexts(self, pressedKeys: str) -> int:
dp = [0] * (len(pressedKeys) + 1)
dp[0] = 1
for i in range(1, len(pressedKeys) + 1):
maxSearchLength = 4 if pressedKeys[i - 1] in ('7', '9') else 3
for j in range(1, maxSearchLength + 1):
... | class Solution:
def count_texts(self, pressedKeys: str) -> int:
dp = [0] * (len(pressedKeys) + 1)
dp[0] = 1
for i in range(1, len(pressedKeys) + 1):
max_search_length = 4 if pressedKeys[i - 1] in ('7', '9') else 3
for j in range(1, maxSearchLength + 1):
... |
# This function will take a name and return the
# Create a function to return the first initial of a name
# Parameters:
# name: name of person
# Return value
# first letter of name passed in
def get_initial(name):
initial = name[0:1].upper()
return initial
# Ask for someone's name and return the initials
... | def get_initial(name):
initial = name[0:1].upper()
return initial
first_name = input('Enter your first name: ')
first_name_initial = get_initial(first_name)
print('Your initial is: ' + first_name_initial) |
S = input()
T = input()
S += S
if S.find(T) != -1:
print('Yes')
else:
print('No')
| s = input()
t = input()
s += S
if S.find(T) != -1:
print('Yes')
else:
print('No') |
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
hashset = set()
for i, num in enumerate(nums):
if num in hashset:
return True
hashset.add(num)
if len(hashset) > k:
hashset.remove(nums[i - k])
... | class Solution:
def contains_nearby_duplicate(self, nums: List[int], k: int) -> bool:
hashset = set()
for (i, num) in enumerate(nums):
if num in hashset:
return True
hashset.add(num)
if len(hashset) > k:
hashset.remove(nums[i - k])... |
class Solution:
def largestOddNumber(self, num: str) -> str:
x="97531"
for i in range(len(num)-1,-1,-1):
if num[i] in x:
return num[:i+1]
return ""
| class Solution:
def largest_odd_number(self, num: str) -> str:
x = '97531'
for i in range(len(num) - 1, -1, -1):
if num[i] in x:
return num[:i + 1]
return '' |
'''
PROBLEM 5: Staircase:
--------------------
Consider a staircase of size n = 4:
#
##
###
####
Observe that its base and height are both equal to n, and the image is drawn
using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size n.
INPUT FORMAT... | """
PROBLEM 5: Staircase:
--------------------
Consider a staircase of size n = 4:
#
##
###
####
Observe that its base and height are both equal to n, and the image is drawn
using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size n.
INPUT FORMAT... |
#!/usr/bin/env python3
array1 = [0, 3, 4, 31]
array2 = [4, 6, 30]
# print(sorted(array1 + array2)
def mergeSortedArray(array1, array2):
merged_array = []
if len(array1) == 0:
return array2
if len(array2) == 0:
return array1
i = 0
j = 0
while i < len(array1):
arra1Item ... | array1 = [0, 3, 4, 31]
array2 = [4, 6, 30]
def merge_sorted_array(array1, array2):
merged_array = []
if len(array1) == 0:
return array2
if len(array2) == 0:
return array1
i = 0
j = 0
while i < len(array1):
arra1_item = array1[i]
array2_item = array2[j]
pr... |
item1_list = [["Jash", 1], ["Samanta", 6], ["Chanda", 5], ["Majumdar", 3]]
for name, roll in item1_list:
print(name, "Roll no.", roll)
list_item = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in list_item:
if num > 6:
print(num, "is grater than 6")
elif num == 6:
print("The number is 6")
... | item1_list = [['Jash', 1], ['Samanta', 6], ['Chanda', 5], ['Majumdar', 3]]
for (name, roll) in item1_list:
print(name, 'Roll no.', roll)
list_item = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in list_item:
if num > 6:
print(num, 'is grater than 6')
elif num == 6:
print('The number is 6')
... |
# Assignment 5 -- Stepback Blackjack -- Alex Staley
# Resolving final score, counting wins/losses:
def finalScore(total, totalDealer, blackjack, blackjackDealer, bust):
win = False
tie = False
if bust:
print("\n...BUSTED!\n:( ")
if blackjack:
if blackjackDealer:
tie = True... | def final_score(total, totalDealer, blackjack, blackjackDealer, bust):
win = False
tie = False
if bust:
print('\n...BUSTED!\n:( ')
if blackjack:
if blackjackDealer:
tie = True
print("\nbut hey,\tIT'S LIKE BLACKJACK CITY OVER HERE!\n\tTable's hot! Please provide cr... |
def euler(f_dot, f_prev, t_prev, t, dt):
if t_prev + dt > t:
return f_prev
else:
return euler(f_dot, f_prev + f_dot(t_prev)*dt, t_prev+dt, t, dt) | def euler(f_dot, f_prev, t_prev, t, dt):
if t_prev + dt > t:
return f_prev
else:
return euler(f_dot, f_prev + f_dot(t_prev) * dt, t_prev + dt, t, dt) |
LEAGUES_TO_PATH = {
'nba': 'http://www.basketball-reference.com/leagues/NBA_{0}_games.html',
'acb': 'http://www.basketball-reference.com/euro/spain-liga-acb/{0}-schedule.html',
'lnb': 'http://www.basketball-reference.com/euro/france-lnb-pro-a/{0}-schedule.html',
'seriea': 'http://www.basketball-referenc... | leagues_to_path = {'nba': 'http://www.basketball-reference.com/leagues/NBA_{0}_games.html', 'acb': 'http://www.basketball-reference.com/euro/spain-liga-acb/{0}-schedule.html', 'lnb': 'http://www.basketball-reference.com/euro/france-lnb-pro-a/{0}-schedule.html', 'seriea': 'http://www.basketball-reference.com/euro/italy-... |
class Solution:
def partition(self, s):
if not s:
return []
curr = list()
ans = list()
dp = set()
self.divide(s, curr, ans, dp)
return ans
def divide(self, s, current, ans, dp):
if len(s) == 0:
ans.append(current.copy())
... | class Solution:
def partition(self, s):
if not s:
return []
curr = list()
ans = list()
dp = set()
self.divide(s, curr, ans, dp)
return ans
def divide(self, s, current, ans, dp):
if len(s) == 0:
ans.append(current.copy())
f... |
'''
https://www.codingame.com/training/easy/chuck-norris
'''
def convert_to_bytes(message: str) -> str:
res = []
for ch in message:
converted = bin(int.from_bytes(ch.encode(), 'big'))[2:].zfill(7)
res.append(converted)
return ''.join(res)
binary = convert_to_bytes(input(... | """
https://www.codingame.com/training/easy/chuck-norris
"""
def convert_to_bytes(message: str) -> str:
res = []
for ch in message:
converted = bin(int.from_bytes(ch.encode(), 'big'))[2:].zfill(7)
res.append(converted)
return ''.join(res)
binary = convert_to_bytes(input())
out = []
dig_co... |
FLASK_DEBUG=1
DEBUG=True
WTF_CSRF_ENABLED=False
SECRET_KEY="testing"
TESTING=True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = False
# https://github.com/jarus/flask-testing/issues/21#issuecomment-54517959
PRESERVE_CONTEXT_ON_EXCEPTION = False
| flask_debug = 1
debug = True
wtf_csrf_enabled = False
secret_key = 'testing'
testing = True
sqlalchemy_track_modifications = False
sqlalchemy_echo = False
preserve_context_on_exception = False |
t = int(input(""))
while t>0:
n = int(input())
for i in range(n):
if i==0:
print("3",end = ' ')
elif i%2==0:
print(2*i,end = ' ')
elif i%2==1:
print(i*i,end = ' ')
print('')
t=t-1 | t = int(input(''))
while t > 0:
n = int(input())
for i in range(n):
if i == 0:
print('3', end=' ')
elif i % 2 == 0:
print(2 * i, end=' ')
elif i % 2 == 1:
print(i * i, end=' ')
print('')
t = t - 1 |
# python3
def max_pairwise_product(numbers):
n = len(numbers)
assert n > 1
numbers.sort()
return numbers[n-1]*numbers[n-2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
| def max_pairwise_product(numbers):
n = len(numbers)
assert n > 1
numbers.sort()
return numbers[n - 1] * numbers[n - 2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers)) |
# Complete the solve function below.
s = input()
res = []
sl = s.split(' ')
for sle in sl:
if len(sle) == 0:
res.append('')
else:
res.append(sle[0].upper() + sle[1:])
print(' '.join(res))
| s = input()
res = []
sl = s.split(' ')
for sle in sl:
if len(sle) == 0:
res.append('')
else:
res.append(sle[0].upper() + sle[1:])
print(' '.join(res)) |
{
'variables': {
'loop_lib': 'uv',
'headless_lib': 'glx',
'coverage': '<!(echo $ENABLE_COVERAGE)>',
},
'conditions': [
['OS == "mac"', {
'variables': {
'headless_lib': 'cgl',
}
}],
],
'includes': [
'../../mbgl.gypi',
'../../test/test.gypi',
'../../benchmark/... | {'variables': {'loop_lib': 'uv', 'headless_lib': 'glx', 'coverage': '<!(echo $ENABLE_COVERAGE)>'}, 'conditions': [['OS == "mac"', {'variables': {'headless_lib': 'cgl'}}]], 'includes': ['../../mbgl.gypi', '../../test/test.gypi', '../../benchmark/benchmark.gypi', '../../bin/glfw.gypi', '../../bin/render.gypi', '../../bin... |
# problem name: Unusual Competitions
# problem link: https://codeforces.com/contest/1323/problem/C
# contest link: https://codeforces.com/contest/1323
# author: reyad
# time: (?)
# other_tags: constructive algorithms
n, b, a, r = int(input()), input(), 0, 0
for c in b:
a += -1 if (c == ")") else 1
if(a < 0 or (a ==... | (n, b, a, r) = (int(input()), input(), 0, 0)
for c in b:
a += -1 if c == ')' else 1
if a < 0 or (a == 0 and c == '('):
r += 1
print(r if a == 0 else -1) |
# grid traveller using tabulation; I may need to use numpy...nah I'll use for loops ;)
def createGridTable(m, n):
tab = []
for i in range(m+1):
tab.append([])
for j in range(n+1):
tab[i].append(0)
return tab
def gridTraveler(m, n):
tab = createGridTable(m, n)
# pprint(tab, width = m+6)
# seed
tab[1]... | def create_grid_table(m, n):
tab = []
for i in range(m + 1):
tab.append([])
for j in range(n + 1):
tab[i].append(0)
return tab
def grid_traveler(m, n):
tab = create_grid_table(m, n)
tab[1][1] = 1
for i in range(m + 1):
for j in range(n + 1):
if j ... |
TRANSACTION_COMMIT = 0x1701
TRANSACTION_CREATE = 0x1702
TRANSACTION_ROLLBACK = 0x1703
| transaction_commit = 5889
transaction_create = 5890
transaction_rollback = 5891 |
a = 1
while a in range (100): # Remember to change to 100 in range
a = a + 1
print("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
for i in range(100,2,... | a = 1
while a in range(100):
a = a + 1
print('* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *')
for i in range(100, 2, -1):
for j in range(i, 2, -1):
pr... |
# This function help calculate the space that will be added to the first operants in order to know wher we need to put it in the rendering
def checkspaces(first, second):
first_size = len(first)
second_size = len(second)
diff = first_size - second_size
space = 0
if diff < 0:
space = second_... | def checkspaces(first, second):
first_size = len(first)
second_size = len(second)
diff = first_size - second_size
space = 0
if diff < 0:
space = second_size - first_size
space = space + 2
if diff >= 0:
space = 2
count = 0
nb_space = ''
while count < space:
... |
def main():
print("Username: Hello\nPassword: World")
username = input("Username: ")
password = input("Password: ")
if username == "Hello":
if password == "World":
message = "\nWelcome, " + username + "!"
else:
message = "\nYour password is incorrect."
else:... | def main():
print('Username: Hello\nPassword: World')
username = input('Username: ')
password = input('Password: ')
if username == 'Hello':
if password == 'World':
message = '\nWelcome, ' + username + '!'
else:
message = '\nYour password is incorrect.'
else:
... |
n = int(input())
al = list(map(int, input().split()))
al.sort()
print(al[-1]-al[0])
| n = int(input())
al = list(map(int, input().split()))
al.sort()
print(al[-1] - al[0]) |
divisor_dict = {}
for number in range(1, 10001):
list_divs = []
for potential in range(1, number):
if number % potential == 0:
list_divs.append(potential)
divisor_dict[number] = list_divs
pairs_sum = set()
for key in divisor_dict:
for key2 in divisor_dict:
if sum(divisor_d... | divisor_dict = {}
for number in range(1, 10001):
list_divs = []
for potential in range(1, number):
if number % potential == 0:
list_divs.append(potential)
divisor_dict[number] = list_divs
pairs_sum = set()
for key in divisor_dict:
for key2 in divisor_dict:
if sum(divisor_dict... |
# --------------------------------------------------------------------------
# Copyright IBM Corp. 2015, 2015 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.... | def get_dict_path(d, path):
l = d
name = path
for i in path.split('.'):
l = l[i]
name = i
return (name, l)
def set_dict_path(d, path, v):
l = d
lst = path.split('.')
spath = lst[:-1]
entry = lst[-1]
for i in spath:
if i not in l:
l[i] = {}
... |
# pizza_topping = ['Olive', 'Mushroom', 'Tomato', 'Cheese', 'Pineapple']
# if 'Olive' in pizza_topping:
# print('Adding Olive')
# if 'Mushroom' in pizza_topping:
# print('Adding Mushroom')
# if 'Tomato' in pizza_topping:
# print('Adding Tomato')
# if 'Cheese' in pizza_topping:
# print('Adding Cheese')
#... | pizza_topping = ['Pepperoni', 'Chicken', 'Pork', 'Cheese', 'Beef']
if 'Pepperoni' in pizza_topping:
print('Put on the Pepperoni ')
if 'Chicken' in pizza_topping:
print('Put on the Chicken')
if 'Pork' in pizza_topping:
print('Put on the Pork')
if 'Cheese' in pizza_topping:
print('Put on the Cheese')
if '... |
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x*2 for x in a]
c = [x*2 for x in a if x%2==0]
with open("in.txt", "r") as f:
lines = f.readlines()
print(lines)
lines = [int(l) for l in lines]
print(lines)
def my_func(x):
x = x**2
x = x +2
x = x/3
return x
b = [my_func(x) for x in a] | a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x * 2 for x in a]
c = [x * 2 for x in a if x % 2 == 0]
with open('in.txt', 'r') as f:
lines = f.readlines()
print(lines)
lines = [int(l) for l in lines]
print(lines)
def my_func(x):
x = x ** 2
x = x + 2
x = x / 3
return x
b = [my_func(x) for x in... |
#!/usr/bin/env python3
def main():
p = 0
p2 = 0
try:
with open('../input.txt', 'r') as fin:
data = fin.read()
d = [int(i) for i in data.split()]
for j in d:
for k in d:
if(j + k == 2020):
p = j * k
... | def main():
p = 0
p2 = 0
try:
with open('../input.txt', 'r') as fin:
data = fin.read()
d = [int(i) for i in data.split()]
for j in d:
for k in d:
if j + k == 2020:
p = j * k
break
... |
# coding: utf-8
# file generated by setuptools_scm
# don't change, don't track in version control
version = '0.0.2.dev26+g5485901.d20211026'
version_tuple = (0, 0, 2, 'dev26', 'g5485901.d20211026')
| version = '0.0.2.dev26+g5485901.d20211026'
version_tuple = (0, 0, 2, 'dev26', 'g5485901.d20211026') |
class UnitError(Exception):
'''Unit Error'''
pass
class UnitExecutionError(UnitError):
'''Unit Execution Error'''
pass
class UnitOutputError(UnitError):
'''Unit Output Error'''
pass
| class Uniterror(Exception):
"""Unit Error"""
pass
class Unitexecutionerror(UnitError):
"""Unit Execution Error"""
pass
class Unitoutputerror(UnitError):
"""Unit Output Error"""
pass |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Pangram:
def is_pangram(self, input_string):
alphabet_letter_count = 26
letters_used = {}
input_string_letters = [letter.lower() for letter in "".join(input_string)]
for letter in input_string_letters:
if letter == " ... | class Pangram:
def is_pangram(self, input_string):
alphabet_letter_count = 26
letters_used = {}
input_string_letters = [letter.lower() for letter in ''.join(input_string)]
for letter in input_string_letters:
if letter == ' ' or letter == '.':
continue
... |
'''
We are going to use integers (numbers) as strings (text)
We'll define s as a string containing numbers, and we'll pull out each
number through indexes
Python stores the string as an array of characters
'''
s = '0123456789'
'''
We can use rounded brackets [] to pull out a character through their index
'''
print(s[4... | """
We are going to use integers (numbers) as strings (text)
We'll define s as a string containing numbers, and we'll pull out each
number through indexes
Python stores the string as an array of characters
"""
s = '0123456789'
'\nWe can use rounded brackets [] to pull out a character through their index\n'
print(s[4])
... |
#!/usr/bin/python3
def magic_string():
setattr(magic_string, "c", getattr(magic_string, "c", -1) + 1)
return ("Holberton" + ", Holberton" * magic_string.c)
| def magic_string():
setattr(magic_string, 'c', getattr(magic_string, 'c', -1) + 1)
return 'Holberton' + ', Holberton' * magic_string.c |
pairs = {
')': '(',
'}': '{',
']': '[',
'>': '<',
}
test_cases = 10
for t in range(1, test_cases + 1):
N = int(input().strip())
brackets = input().strip()
stack = []
result = 1
for bracket in brackets:
if bracket in ')]}>':
if stack[-1] == pairs[bracket]:
... | pairs = {')': '(', '}': '{', ']': '[', '>': '<'}
test_cases = 10
for t in range(1, test_cases + 1):
n = int(input().strip())
brackets = input().strip()
stack = []
result = 1
for bracket in brackets:
if bracket in ')]}>':
if stack[-1] == pairs[bracket]:
stack.pop()... |
def insertion_sort(lst):
for i in range(1, len(lst)):
j = i - 1
temp = lst[i]
while j >= 0 and temp < lst[j]:
lst[j + 1] = lst[j]
j = j - 1
lst[j+1] = temp | def insertion_sort(lst):
for i in range(1, len(lst)):
j = i - 1
temp = lst[i]
while j >= 0 and temp < lst[j]:
lst[j + 1] = lst[j]
j = j - 1
lst[j + 1] = temp |
## Script (Python) "publishItems"
##parameters=items=None, comment=''
##title=
##
wf_tool = context.portal_workflow
if items is None:
items = []
for obj in context.contentValues():
if ( wf_tool.getInfoFor( obj, 'review_state', '' )
in ( 'private', 'pending' ) ):
items.appen... | wf_tool = context.portal_workflow
if items is None:
items = []
for obj in context.contentValues():
if wf_tool.getInfoFor(obj, 'review_state', '') in ('private', 'pending'):
items.append(obj.getId())
for path in items:
object = context.restrictedTraverse(path)
wf_tool.doActionFor(obje... |
n=int(input());a=[int(i) for i in input().split()];x=int(input());cnt=0
for i in a:
if x==i: cnt+=1
print(cnt)
| n = int(input())
a = [int(i) for i in input().split()]
x = int(input())
cnt = 0
for i in a:
if x == i:
cnt += 1
print(cnt) |
def nextIDGenerator(cls, session):
try:
ids = [ int(row.id.split('.')[2]) for row in session.query(cls) ]
return max(ids) + 1
except:
return 0
| def next_id_generator(cls, session):
try:
ids = [int(row.id.split('.')[2]) for row in session.query(cls)]
return max(ids) + 1
except:
return 0 |
class Solution:
def findRelativeRanks(self, nums):
a = sorted(nums, reverse=True)
b = {}
for i, n in enumerate(a):
if i == 0:
b[n] = "Gold Medal"
elif i == 1:
b[n] = "Silver Medal"
elif i == 2:
b[n] = "Bronz... | class Solution:
def find_relative_ranks(self, nums):
a = sorted(nums, reverse=True)
b = {}
for (i, n) in enumerate(a):
if i == 0:
b[n] = 'Gold Medal'
elif i == 1:
b[n] = 'Silver Medal'
elif i == 2:
b[n] = 'B... |
class Solution:
def addDigits(self, num: int) -> int:
number_str = str(num)
if len(number_str) == 1:
return num
return self.addDigits(sum(int(digit) for digit in number_str))
| class Solution:
def add_digits(self, num: int) -> int:
number_str = str(num)
if len(number_str) == 1:
return num
return self.addDigits(sum((int(digit) for digit in number_str))) |
class Pipe:
def __init__(self, funcs, remove_null=False):
self.funcs = funcs
self.remove_null = remove_null
self.wrap()
def wrap(self):
for i in range(len(self.funcs)):
if (self.funcs[i].__defaults__ == None
or self.funcs[i].__defaults__.count("__... | class Pipe:
def __init__(self, funcs, remove_null=False):
self.funcs = funcs
self.remove_null = remove_null
self.wrap()
def wrap(self):
for i in range(len(self.funcs)):
if self.funcs[i].__defaults__ == None or self.funcs[i].__defaults__.count('__no_wrap__') == 0:
... |
f = open('input.txt','r')
lines = f.readlines()
cmds = [l.split(' ') for l in lines]
h = 0
v = 0
aim = 0
for (c,str) in cmds:
n = int(str)
match c:
case 'forward':
h += n
v += aim * n
case 'down':
aim += n
case 'up':
aim += - n
print('part2', h * v)
h = 0
v = 0
for (c,s... | f = open('input.txt', 'r')
lines = f.readlines()
cmds = [l.split(' ') for l in lines]
h = 0
v = 0
aim = 0
for (c, str) in cmds:
n = int(str)
match c:
case 'forward':
h += n
v += aim * n
case 'down':
aim += n
case 'up':
aim += -n
print('part... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'opps_demo',
'USER': '',
'PASSWORD': '',
'HOST': '127.0.0.1'
}
}
| databases = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'opps_demo', 'USER': '', 'PASSWORD': '', 'HOST': '127.0.0.1'}} |
def grep(pattern):
print("start grep")
while True:
line = yield
if pattern in line:
print(line)
def grep_python_coroutine():
g = grep("python")
yield from g
g = grep_python_coroutine()
print(type(g))
next(g)
g.send('python wow!')
| def grep(pattern):
print('start grep')
while True:
line = (yield)
if pattern in line:
print(line)
def grep_python_coroutine():
g = grep('python')
yield from g
g = grep_python_coroutine()
print(type(g))
next(g)
g.send('python wow!') |
nums = [1, 2, 3, 4]
def exchange(array):
even = [i for i in array if i % 2 == 0]
odd = [i for i in array if i % 2 != 0]
return odd + even
print(f"Original Array: {nums},\n Now swapping")
print(f"After swapping: {exchange(nums)}")
# two pointer solution
# Time: O(N), Space: O(1)
def twoPointerExchange(... | nums = [1, 2, 3, 4]
def exchange(array):
even = [i for i in array if i % 2 == 0]
odd = [i for i in array if i % 2 != 0]
return odd + even
print(f'Original Array: {nums},\n Now swapping')
print(f'After swapping: {exchange(nums)}')
def two_pointer_exchange(array):
i = 0
j = len(array) - 1
while ... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#=================================================================================
# author: Chancerel Codjovi (aka codrelphi)
# date: 2019-09-18
# source: https://www.hackerrank.com/challenges/nested-list/problem
#=============================================================... | if __name__ == '__main__':
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name, score])
new_students = [i for i in students if i[1] != min((i[1] for i in students))]
result_names = [i[0] for i in new_students if i[1] == min((i[1... |
ORANGE, WHITE = '\033[93m', '\033[0m'
def warning(message):
print("\n " + ORANGE + "Warning: " + WHITE + message + "\n")
class _Options:
def __init__(self):
self.values = tuple() # options with non-Boolean values (strings or numbers)
self.flags = tuple() # Boolean options
self.par... | (orange, white) = ('\x1b[93m', '\x1b[0m')
def warning(message):
print('\n ' + ORANGE + 'Warning: ' + WHITE + message + '\n')
class _Options:
def __init__(self):
self.values = tuple()
self.flags = tuple()
self.parameters = []
self.parameters_cursor = 0
def set_values(self... |
# Script to extract .com website names from large text file
with open('websites.txt', 'r') as f:
lines = f.readlines()
sites = []
for line in lines:
words = line.split()
for word in words:
if word[-4:] == '.com':
sites.append(word.lower())
with open('test_data.txt', 'w') as f:
for... | with open('websites.txt', 'r') as f:
lines = f.readlines()
sites = []
for line in lines:
words = line.split()
for word in words:
if word[-4:] == '.com':
sites.append(word.lower())
with open('test_data.txt', 'w') as f:
for site in sites:
f.write(site + '\n') |
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n1 = len(nums1)
n2 = len(nums2)
nums = []
i = 0
j = 0
while i < n1 or j < n2:
if i < n1 and j <n2:
if nums1[i] < nums2[j]:
nums.append(nums1[i])
i +=1
elif nums1[i] > nums2[j]:
nums.app... | def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
n1 = len(nums1)
n2 = len(nums2)
nums = []
i = 0
j = 0
while i < n1 or j < n2:
if i < n1 and j < n2:
if nums1[i] < nums2[j]:
nums.append(nums1[i])
i += 1
... |
# -*- coding: utf-8 -*-
ACTIVE_THRESHOLD = 200
CAPTURE_REGION = 100
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
BG_ADAPT = 0.5
GLOW_FADE = 15
SPRITE_SIZE = 64
SQRT_2 = 1.414
| active_threshold = 200
capture_region = 100
screen_width = 640
screen_height = 480
bg_adapt = 0.5
glow_fade = 15
sprite_size = 64
sqrt_2 = 1.414 |
#!/usr/bin/env python
def greatest_common_divisor(m,n):
'''
Euclid's algorithm for finding the
greatest common divisor of m,n
'''
r = m % n
if r == 0: return n
else: return greatest_common_divisor(n, r)
| def greatest_common_divisor(m, n):
"""
Euclid's algorithm for finding the
greatest common divisor of m,n
"""
r = m % n
if r == 0:
return n
else:
return greatest_common_divisor(n, r) |
class RCCException(Exception):
pass
class HTTPException(RCCException):
pass
class UNMSHTTPException(HTTPException):
pass
class BreakLoop(RCCException):
pass
| class Rccexception(Exception):
pass
class Httpexception(RCCException):
pass
class Unmshttpexception(HTTPException):
pass
class Breakloop(RCCException):
pass |
s = input()
n = int(float(s[1:]) * 100.0)
coins = [100, 25, 10, 5, 1]
change = [0, 0, 0, 0, 0]
for i in range(0, len(coins)):
while n - coins[i] >= 0:
change[i] += 1
n -= coins[i]
print(' '.join(map(str, change)))
| s = input()
n = int(float(s[1:]) * 100.0)
coins = [100, 25, 10, 5, 1]
change = [0, 0, 0, 0, 0]
for i in range(0, len(coins)):
while n - coins[i] >= 0:
change[i] += 1
n -= coins[i]
print(' '.join(map(str, change))) |
def inorder_tree_walk(x):
if x is not None:
inorder_tree_walk(x.left)
print(x.key)
inorder_tree_walk(x.right)
def tree_search(x, k):
if x is None or k == x.key:
return x
if k < x.key:
return tree_search(x.left, k)
return tree_search(x.right, k)
def iterative_t... | def inorder_tree_walk(x):
if x is not None:
inorder_tree_walk(x.left)
print(x.key)
inorder_tree_walk(x.right)
def tree_search(x, k):
if x is None or k == x.key:
return x
if k < x.key:
return tree_search(x.left, k)
return tree_search(x.right, k)
def iterative_tre... |
t = int(input())
for _ in range(t):
n = int(input())
prices = list(map(int, input().split()))[::-1]
m = prices[0]
c = 0
for p in prices[1:]:
c += p > m
m = min(m, p)
print(c)
| t = int(input())
for _ in range(t):
n = int(input())
prices = list(map(int, input().split()))[::-1]
m = prices[0]
c = 0
for p in prices[1:]:
c += p > m
m = min(m, p)
print(c) |
# Copyright (C) 2020 Google Inc.
#
# 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 writ... | def _img2h_impl(ctx):
outs = []
for img in ctx.files.srcs:
n = img.basename
out = ctx.actions.declare_file(n[0:len(n) - len(img.extension)] + 'h')
ctx.actions.run(inputs=[img], outputs=[out], arguments=['-out', out.path, img.path], executable=ctx.executable._img2h, use_default_shell_env=... |
a=int(input())
f=list(map(int,input().split()))
mi=-2147483648
ma=f[0]
for j in f:
if j>ma:
mi=ma
ma=j
print(mi)
| a = int(input())
f = list(map(int, input().split()))
mi = -2147483648
ma = f[0]
for j in f:
if j > ma:
mi = ma
ma = j
print(mi) |
# units for intervals
SECONDS = 1
MINUTES = 60 * SECONDS
HOURS = 60 * MINUTES
DAYS = 24 * HOURS
WEEKS = 7 * DAYS | seconds = 1
minutes = 60 * SECONDS
hours = 60 * MINUTES
days = 24 * HOURS
weeks = 7 * DAYS |
class ConfigError(Exception):
''' Exception type for errors in configuration file '''
pass
def _return_single_config(list_tuples_configs, attribute):
''' Returns the value for a single configuration from a list of config tuple values
Args:
list_tuples_configs: A list with config tuples [(config_paramete... | class Configerror(Exception):
""" Exception type for errors in configuration file """
pass
def _return_single_config(list_tuples_configs, attribute):
""" Returns the value for a single configuration from a list of config tuple values
Args:
list_tuples_configs: A list with config tuples [(config_pa... |
# Fast Inverse Square Root
def invSqrt(x):
print(x**-0.5)
# Spelling out words
word = input()
print(list(word))
# Cheap uwu talk
x = input()
x = x.replace('r', 'w')
x = x.replace('l', 'w')
print(x.replace('u', 'w'))
# Potato counter
i = 0
x = True
while(x == True):
word = str.lower(input())
if(word ... | def inv_sqrt(x):
print(x ** (-0.5))
word = input()
print(list(word))
x = input()
x = x.replace('r', 'w')
x = x.replace('l', 'w')
print(x.replace('u', 'w'))
i = 0
x = True
while x == True:
word = str.lower(input())
if word == 'potato':
i = i + 1
elif word == 'exit':
x = False
else:
... |
def func1(s):
if len(s) < 2:
return ''
else:
return s[:2] + s[-2:]
if __name__=="__main__":
print(func1("python"))
print(func1("py"))
print(func1("p")) | def func1(s):
if len(s) < 2:
return ''
else:
return s[:2] + s[-2:]
if __name__ == '__main__':
print(func1('python'))
print(func1('py'))
print(func1('p')) |
#
# PySNMP MIB module JUNIPER-BFD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-BFD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:47:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection) ... |
# shifted top-level comment
if some_condition:
# shifted right
# just right
# shifted left
repssn_ind = ssn_data[index].repssn_index
repssn_ni = ssn_data[index].ni
| if some_condition:
repssn_ind = ssn_data[index].repssn_index
repssn_ni = ssn_data[index].ni |
class HashMap:
def __init__(self):
self.size = 100
self.L = [None] * self.size
def hash(self, val):
return sum(map(ord, val)) % self.size
def insert(self, key, val):
i = self.hash(key)
while self.L[i] and i < self.size:
i += 1
if i == self.size:
raise RuntimeError('runtime er... | class Hashmap:
def __init__(self):
self.size = 100
self.L = [None] * self.size
def hash(self, val):
return sum(map(ord, val)) % self.size
def insert(self, key, val):
i = self.hash(key)
while self.L[i] and i < self.size:
i += 1
if i == self.size:... |
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if not node:
ret... | class Solution:
def clone_graph(self, node):
if not node:
return None
visited = {}
visited[node.label] = undirected_graph_node(node.label)
root = visited[node.label]
stack = [node]
while stack:
vertex = stack.pop()
for nei in verte... |
txt = sorted(tuple(x for x in input().lstrip()))
txt_set = set()
for i in txt:
if i not in txt_set:
print(f"{i}: {txt.count(i)} time/s")
txt_set.add(i)
| txt = sorted(tuple((x for x in input().lstrip())))
txt_set = set()
for i in txt:
if i not in txt_set:
print(f'{i}: {txt.count(i)} time/s')
txt_set.add(i) |
n,s=map(int,input().split())
a=list(map(int,input().split()))
light=[False]*(n+1)
prev=None
for i in a:
if prev==None:
prev=max(i,n-i)
else:
prev=max(i,prev)
print(max())
| (n, s) = map(int, input().split())
a = list(map(int, input().split()))
light = [False] * (n + 1)
prev = None
for i in a:
if prev == None:
prev = max(i, n - i)
else:
prev = max(i, prev)
print(max()) |
# Solution with recursion O(2^r+c)
def get_path(maze):
if not maze:
return None
path = []
if is_path(maze, len(maze) - 1, len(maze[0]) - 1, path):
return path
return None
def is_path(maze, row, col, path):
# if out of bounds or not available, return
if col < 0 or row < 0 or not... | def get_path(maze):
if not maze:
return None
path = []
if is_path(maze, len(maze) - 1, len(maze[0]) - 1, path):
return path
return None
def is_path(maze, row, col, path):
if col < 0 or row < 0 or (not maze[row][col]):
return False
is_at_origin = row == 0 and col == 0
... |
SCENARIO_START_TIME = 457
PHASE_2_DURATION = 3 * 30
PHASE_3_DURATION = 24 * 30 # can be adjusted but please keep this >= 9 * 30
SEVERITY_EFFICACY = 0.
INFECTION_EFFICACY = 0.7
TOTAL_DAILY_DOSES = {
'malaysia': 30000,
'philippines': 60000
}
VACC_AGE_GROUPS = [[0, 9], [10, 19], [20, 29], [30, 39], [40, 49], [50,... | scenario_start_time = 457
phase_2_duration = 3 * 30
phase_3_duration = 24 * 30
severity_efficacy = 0.0
infection_efficacy = 0.7
total_daily_doses = {'malaysia': 30000, 'philippines': 60000}
vacc_age_groups = [[0, 9], [10, 19], [20, 29], [30, 39], [40, 49], [50, 59], [60, 69], [70, None]] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.