content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
## Find peak element in an array
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
## Iterative Binary Search
l, r = 0, len(nums)-1
while l<r:
mid = (l+r)//2
if nums[mid] > nums[mid+1]:
r = mid
... | class Solution:
def find_peak_element(self, nums: List[int]) -> int:
(l, r) = (0, len(nums) - 1)
while l < r:
mid = (l + r) // 2
if nums[mid] > nums[mid + 1]:
r = mid
else:
l = mid + 1
return l |
class Solution:
def numberOfWeeks(self, milestones: List[int]) -> int:
k = sorted(milestones,reverse = True)
t = sum(k) - k[0]
if k[0] <= t+1:
return sum(k)
else:
return 2*t+ 1 | class Solution:
def number_of_weeks(self, milestones: List[int]) -> int:
k = sorted(milestones, reverse=True)
t = sum(k) - k[0]
if k[0] <= t + 1:
return sum(k)
else:
return 2 * t + 1 |
class FilterModule(object):
''' Ansible core jinja2 filters '''
def filters(self):
return {
'infer_address' : self.infer_address
}
def infer_address(self, hostname, hostvars):
for t in ('ansible_ssh_host', 'ansible_host', 'inventory_hostname'):
if t in hos... | class Filtermodule(object):
""" Ansible core jinja2 filters """
def filters(self):
return {'infer_address': self.infer_address}
def infer_address(self, hostname, hostvars):
for t in ('ansible_ssh_host', 'ansible_host', 'inventory_hostname'):
if t in hostvars[hostname]:
... |
def check_log(recognition_log):
pair = recognition_log.split(",")
filename_tested = pair[0].split("/")[-1]
filename_result = pair[1].split("/")[-1]
no_extension_tested = filename_tested.split(".")[0]
no_extension_result = filename_result.split(".")[0]
check = no_extension_tested == no_extensio... | def check_log(recognition_log):
pair = recognition_log.split(',')
filename_tested = pair[0].split('/')[-1]
filename_result = pair[1].split('/')[-1]
no_extension_tested = filename_tested.split('.')[0]
no_extension_result = filename_result.split('.')[0]
check = no_extension_tested == no_extension_... |
#!/usr/bin/env python3
def mod_sum(n):
return sum([x for x in range(n) if (x % 3 == 0) or (x % 5 == 0)])
| def mod_sum(n):
return sum([x for x in range(n) if x % 3 == 0 or x % 5 == 0]) |
def display(summary, *args):
args = list(args)
usage = ""
example = ""
details = ""
delimiter = "="
try:
usage = args.pop(0)
example = args.pop(0)
details = args.pop(0)
except IndexError:
# End of arg list
pass
for x in range(1, len(summary)):
... | def display(summary, *args):
args = list(args)
usage = ''
example = ''
details = ''
delimiter = '='
try:
usage = args.pop(0)
example = args.pop(0)
details = args.pop(0)
except IndexError:
pass
for x in range(1, len(summary)):
delimiter = delimiter ... |
# -*- coding: utf-8 -*-
'''
Created on Mar 12, 2012
@author: hathcox
Copyright 2012 Root the Box
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/lice... | """
Created on Mar 12, 2012
@author: hathcox
Copyright 2012 Root the Box
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
Un... |
print(" _________ _____ ______ _________ ____ ______ ___________ ________ _________ ")
print(" | | | | / \ | | | | | ")
print(" | | | | /______\ | |... | print(' _________ _____ ______ _________ ____ ______ ___________ ________ _________ ')
print(' | | | | / \\ | | | | | ')
print(' | | | | /______\\ | |... |
# Write your code here
n,k = [int(x) for x in input().split()]
l = []
while n > 0 :
a = int(input())
l.append(a)
n -= 1
while(l[0] <= k) :
l.pop(0)
l = l[::-1]
while (l[0] <= k) :
l.pop(0)
#print(l)
print(len(l))
| (n, k) = [int(x) for x in input().split()]
l = []
while n > 0:
a = int(input())
l.append(a)
n -= 1
while l[0] <= k:
l.pop(0)
l = l[::-1]
while l[0] <= k:
l.pop(0)
print(len(l)) |
def find_2020th_number_spoken(starting_numbers):
num_list = []
starting_numbers = [ int(num) for num in starting_numbers.split(',') ]
for i in range(0, 2020):
#print(f'i:{i}, num_list: {num_list}')
if i < len(starting_numbers):
#print(f'Still in starting numbers')
num... | def find_2020th_number_spoken(starting_numbers):
num_list = []
starting_numbers = [int(num) for num in starting_numbers.split(',')]
for i in range(0, 2020):
if i < len(starting_numbers):
num_list.append(starting_numbers[i])
else:
last_num = num_list[i - 1]
... |
# used for template multi_assignment_list_modal
class MultiVideoAssignmentData:
def __init__(self, name, count, video_id, set_id):
self.name = name
self.count = count
self.video_id = video_id
self.set_id = set_id
| class Multivideoassignmentdata:
def __init__(self, name, count, video_id, set_id):
self.name = name
self.count = count
self.video_id = video_id
self.set_id = set_id |
first_number= 1
sec_number= 2
sum= 0
while (first_number < 4000000):
new= first_number + sec_number
first_number= sec_number
sec_number= new
if(first_number % 2== 0):
sum= sum+first_number
print(sum)
| first_number = 1
sec_number = 2
sum = 0
while first_number < 4000000:
new = first_number + sec_number
first_number = sec_number
sec_number = new
if first_number % 2 == 0:
sum = sum + first_number
print(sum) |
start_position = {
(1, 2): "y", (1, 3): "", (1, 5): "y'", (1, 6): "y2",
(2, 1): "z' y'", (2, 3): "z'", (2, 4): "z' y", (2, 6): "z' y2",
(3, 1): "x y2", (3, 2): "x y", (3, 4): "x", (3, 5): "x y'",
(4, 2): "z2 y'", (4, 3): "z2", (4, 5): "z2 y", (4, 6): "x2",
(5, 1): "z y", (5, 3): "z", (5, 4): "z y'",... | start_position = {(1, 2): 'y', (1, 3): '', (1, 5): "y'", (1, 6): 'y2', (2, 1): "z' y'", (2, 3): "z'", (2, 4): "z' y", (2, 6): "z' y2", (3, 1): 'x y2', (3, 2): 'x y', (3, 4): 'x', (3, 5): "x y'", (4, 2): "z2 y'", (4, 3): 'z2', (4, 5): 'z2 y', (4, 6): 'x2', (5, 1): 'z y', (5, 3): 'z', (5, 4): "z y'", (5, 6): 'z y2', (6, ... |
sink_db = 'gedcom'
sink_tbl = {
"person": "person",
"family": "family"
}
| sink_db = 'gedcom'
sink_tbl = {'person': 'person', 'family': 'family'} |
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
@gem('Sapphire.Combine')
def gem():
require_gem('Sapphire.Parse')
require_gem('Sapphire.SymbolTable')
variables = [
0, # 0 = copyright
]
query = variables.__getitem__
write = ... | @gem('Sapphire.Combine')
def gem():
require_gem('Sapphire.Parse')
require_gem('Sapphire.SymbolTable')
variables = [0]
query = variables.__getitem__
write = variables.__setitem__
qc = method(query, 0)
wc = method(write, 0)
wc0 = method(wc, 0)
empty_indentation__function = conjure_inde... |
def diag(kp):
nk = []
for x in xrange(len(kp)):
l = []
for y in xrange(len(kp)):
l.append(kp[y][x])
nk.append("".join(l))
return tuple(nk)
def parse_line(line):
left, right = line.strip().split(" => ")
a = tuple(left.split("/"))
b = right.split("/")
return a, b
def parse_input(puzzle_input... | def diag(kp):
nk = []
for x in xrange(len(kp)):
l = []
for y in xrange(len(kp)):
l.append(kp[y][x])
nk.append(''.join(l))
return tuple(nk)
def parse_line(line):
(left, right) = line.strip().split(' => ')
a = tuple(left.split('/'))
b = right.split('/')
ret... |
#
# Modify `remove_html_markup` so that it actually works!
#
def remove_html_markup(s):
tag = False
quote = False
quoteSign = '"'
out = ""
for c in s:
# print c, tag, quote
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = ... | def remove_html_markup(s):
tag = False
quote = False
quote_sign = '"'
out = ''
for c in s:
if c == '<' and (not quote):
tag = True
elif c == '>' and (not quote):
tag = False
elif (c == '"' or c == "'") and tag:
if quote == False or quoteSig... |
features_dict = {
"Name":{
"Description":"String",
"Pre_Action":'''
''',
"Post_Action":'''
''',
"Equip":'''
''',
"Unequip":'''
'''
},
"Dual Wielding":{
"Description":"You can use this weapon in your Off Hand (if availab... | features_dict = {'Name': {'Description': 'String', 'Pre_Action': '\n\n ', 'Post_Action': '\n\n ', 'Equip': '\n\n ', 'Unequip': '\n\n '}, 'Dual Wielding': {'Description': 'You can use this weapon in your Off Hand (if available) and attack for -1 AP but with no Techinques. ', 'Pre_Action':... |
tiles = [
# track example in Marin Headlands, a member of Bay Area Ridge Trail, a regional network
# https://www.openstreetmap.org/way/12188550
# https://www.openstreetmap.org/relation/2684235
[12, 654, 1582]
]
for z, x, y in tiles:
assert_has_feature(
z, x, y, 'roads',
{'highway': ... | tiles = [[12, 654, 1582]]
for (z, x, y) in tiles:
assert_has_feature(z, x, y, 'roads', {'highway': 'track'}) |
class Readfile():
def process(self, utils, logger):
filenames = utils.check_input()
words = []
for filename in filenames:
with open(utils.indir + filename, 'r') as f:
for line in f:
words.append(line.strip())
return words
| class Readfile:
def process(self, utils, logger):
filenames = utils.check_input()
words = []
for filename in filenames:
with open(utils.indir + filename, 'r') as f:
for line in f:
words.append(line.strip())
return words |
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2010, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
# Software Distributed under the MIT License
'''
Value types: An hierarchy of value types.
Hierarchy:
vtype
|- numeric
| |-ordinal
| | |- ordinalrange
| | ... | """
Value types: An hierarchy of value types.
Hierarchy:
vtype
|- numeric
| |-ordinal
| | |- ordinalrange
| | - boolean
| | - integer
| -continuous
- categorical
- boolean
"""
class Vtype(object):
def __init__(self, name):
self.name = name
class Numer... |
def letter_to_number(letter):
if letter == 'A':
return 10
if letter == 'B':
return 11
if letter == 'C':
return 12
if letter == 'D':
return 13
if letter == 'E':
return 14
if letter == 'F':
return 15
else:
return int(letter)
def int_to_... | def letter_to_number(letter):
if letter == 'A':
return 10
if letter == 'B':
return 11
if letter == 'C':
return 12
if letter == 'D':
return 13
if letter == 'E':
return 14
if letter == 'F':
return 15
else:
return int(letter)
def int_to_c... |
p = int(input())
total = 0
numbers = []
for i in range(p):
cod, quant = input().split(' ')
cod = int(cod)
quant = int(quant)
if(cod == 1001):
total = quant*1.50
elif(cod==1002):
total = quant*2.50
elif(cod==1003):
total = quant*3.50
elif(cod==1004):
total = q... | p = int(input())
total = 0
numbers = []
for i in range(p):
(cod, quant) = input().split(' ')
cod = int(cod)
quant = int(quant)
if cod == 1001:
total = quant * 1.5
elif cod == 1002:
total = quant * 2.5
elif cod == 1003:
total = quant * 3.5
elif cod == 1004:
tot... |
ENV_NAMES = [
"coinrun",
"starpilot",
"caveflyer",
"dodgeball",
"fruitbot",
"chaser",
"miner",
"jumper",
"leaper",
"maze",
"bigfish",
"heist",
"climber",
"plunder",
"ninja",
"bossfight",
]
HARD_GAME_RANGES = {
'coinrun': [5, 10],
'starpilot': [1.5... | env_names = ['coinrun', 'starpilot', 'caveflyer', 'dodgeball', 'fruitbot', 'chaser', 'miner', 'jumper', 'leaper', 'maze', 'bigfish', 'heist', 'climber', 'plunder', 'ninja', 'bossfight']
hard_game_ranges = {'coinrun': [5, 10], 'starpilot': [1.5, 35], 'caveflyer': [2, 13.4], 'dodgeball': [1.5, 19], 'fruitbot': [-0.5, 27.... |
# Use binary search to find the key in the list
def binarySearch(lst, key):
low = 0
high = len(lst) - 1
while high >= low:
mid = (high + low) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1
... | def binary_search(lst, key):
low = 0
high = len(lst) - 1
while high >= low:
mid = (high + low) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1
return -low - 1
def main():
lst = [2, 4, 7, ... |
#Alian Colors #2
alian_color = 'green'
if alian_color == 'green' or alian_color == 'yellow' or alian_color == 'red':
print("You just earned 5 points.")
else:
print("You just earned 10 points.") | alian_color = 'green'
if alian_color == 'green' or alian_color == 'yellow' or alian_color == 'red':
print('You just earned 5 points.')
else:
print('You just earned 10 points.') |
class Solution:
# @param {integer[]} nums
# @return {integer}
def removeDuplicates(self, nums):
n = len(nums)
if n <=1:
return n
i= 0
j = 0
while(j < n):
if nums[j]!=nums[i]:
nums[i+1] = nums[j]
i += 1
... | class Solution:
def remove_duplicates(self, nums):
n = len(nums)
if n <= 1:
return n
i = 0
j = 0
while j < n:
if nums[j] != nums[i]:
nums[i + 1] = nums[j]
i += 1
j += 1
return i + 1 |
canMega = [3,6,9,15,18,65,80,94,127,130,142,150,181,208,212,214,229,248,254,257,260,282,302,303,306,308,310,319,323,334,354,359,373,376,380,381,384,428,445,448,460,475,531,719]
megaForms = [6,150]
def findMega(dex):
if dex in canMega:
if dex in megaForms:
return "This Pokemon has multiple Mega Evolutions."
els... | can_mega = [3, 6, 9, 15, 18, 65, 80, 94, 127, 130, 142, 150, 181, 208, 212, 214, 229, 248, 254, 257, 260, 282, 302, 303, 306, 308, 310, 319, 323, 334, 354, 359, 373, 376, 380, 381, 384, 428, 445, 448, 460, 475, 531, 719]
mega_forms = [6, 150]
def find_mega(dex):
if dex in canMega:
if dex in megaForms:
... |
alien_color = 'green'
print("alien_color = " + alien_color)
if alien_color == 'green':
print("You earned 5 points!")
elif alien_color == 'yellow':
print("You earned 10 points!")
else:
print("You earned 15 points!")
alien_color = 'yellow'
print("\nalien_color = " + alien_color)
if alien_color == 'green':
... | alien_color = 'green'
print('alien_color = ' + alien_color)
if alien_color == 'green':
print('You earned 5 points!')
elif alien_color == 'yellow':
print('You earned 10 points!')
else:
print('You earned 15 points!')
alien_color = 'yellow'
print('\nalien_color = ' + alien_color)
if alien_color == 'green':
... |
COL_TIME = 0
COL_OPEN = 1
COL_HIGH = 2
COL_LOW = 3
COL_CLOSE = 4
def max_close(candles):
c = [x[COL_CLOSE] for x in candles]
return max(c) | col_time = 0
col_open = 1
col_high = 2
col_low = 3
col_close = 4
def max_close(candles):
c = [x[COL_CLOSE] for x in candles]
return max(c) |
# Author : Nekyz
# Date : 29/06/2015
# Project Euler Challenge 1
def sum_of_multiple_of_3_and_5(number: int) -> int:
result = 0
for num in range(0, number):
if num % 3 == 0:
result += num
elif num % 5 == 0:
result += num
return result
print("#################... | def sum_of_multiple_of_3_and_5(number: int) -> int:
result = 0
for num in range(0, number):
if num % 3 == 0:
result += num
elif num % 5 == 0:
result += num
return result
print('###################################')
print('Project Euler, multiple of 3 and 5.')
print('#... |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"VoxelBuffer",
"VoxelMap",
"Voxel",
"VoxelLibrary",
"VoxelTerrain",
"VoxelLodTerrain",
"VoxelStream",
"VoxelStreamFile",
"VoxelStreamBlockFiles",
"VoxelStreamRegionFile... | def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return ['VoxelBuffer', 'VoxelMap', 'Voxel', 'VoxelLibrary', 'VoxelTerrain', 'VoxelLodTerrain', 'VoxelStream', 'VoxelStreamFile', 'VoxelStreamBlockFiles', 'VoxelStreamRegionFiles', 'VoxelGenerator', 'VoxelGeneratorHei... |
fields = [
["#bEasy#k", 211042402],
["Normal", 211042400],
["#rChaos#k", 211042401]
]
# Zakum door portal
s = "Which difficulty of Zakum do you wish to fight? \r\n"
i = 0
for entry in fields:
s += "#L" + str(i) + "#" + entry[0] + "#l\r\n"
i += 1
answer = sm.sendSay(s)
sm.warp(fields[answer][1])
sm.dispose()
| fields = [['#bEasy#k', 211042402], ['Normal', 211042400], ['#rChaos#k', 211042401]]
s = 'Which difficulty of Zakum do you wish to fight? \r\n'
i = 0
for entry in fields:
s += '#L' + str(i) + '#' + entry[0] + '#l\r\n'
i += 1
answer = sm.sendSay(s)
sm.warp(fields[answer][1])
sm.dispose() |
class MEAPIUrls:
COLLECTION_STATS = 'https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/'
COLLECTION_INFO = 'https://api-mainnet.magiceden.io/collections/'
COLLECTION_LIST = 'https://api-mainnet.magiceden.io/all_collections'
COLLECTION_LIST_STATS = 'https://api-mainnet.magiceden.io/rpc/getAgg... | class Meapiurls:
collection_stats = 'https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/'
collection_info = 'https://api-mainnet.magiceden.io/collections/'
collection_list = 'https://api-mainnet.magiceden.io/all_collections'
collection_list_stats = 'https://api-mainnet.magiceden.io/rpc/getAgg... |
# http://codeforces.com/problemset/problem/318/A
n, k = map(int, input().split())
if k <= (n + 1) / 2:
print(k * 2 - 1)
else:
print(int(k - n / 2) * 2)
| (n, k) = map(int, input().split())
if k <= (n + 1) / 2:
print(k * 2 - 1)
else:
print(int(k - n / 2) * 2) |
class Solution:
def isPerfectSquare(self, num: int) -> bool:
i = 1
while i * i < num:
i += 1
return i * i == num
| class Solution:
def is_perfect_square(self, num: int) -> bool:
i = 1
while i * i < num:
i += 1
return i * i == num |
'''
import math
r=input(">>")
s=2*r*math.sin(math.pi/5)
Area=5*s*s/(4*math.tan(math.pi/5))
print(Area)
'''
'''
import math
x1,y1,x2,y2=input(">>")
x3,y3,x4,y4=math.radians(x1),math.radians(y1),math.radians(x2),math.radians(y2)
d=6371.01*math.acos(math.sin(x3)*math.sin(x4)+math.cos(x3)*math.cos(x4)*math.cos(y3-y4))
prin... | """
import math
r=input(">>")
s=2*r*math.sin(math.pi/5)
Area=5*s*s/(4*math.tan(math.pi/5))
print(Area)
"""
'\nimport math\nx1,y1,x2,y2=input(">>")\nx3,y3,x4,y4=math.radians(x1),math.radians(y1),math.radians(x2),math.radians(y2)\nd=6371.01*math.acos(math.sin(x3)*math.sin(x4)+math.cos(x3)*math.cos(x4)*math.cos(y3-y4))\np... |
# --------------
# Code starts here
# creating lists
class_1 = [ 'Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio' ]
class_2 = [ 'Hilary Mason', 'Carla Gentry', 'Corinna Cortes' ]
# concatinating lists
new_class = class_1 + class_2
# looking at the resultant list
print(new_class)
# appending 'Pet... | 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_class)
courses = {'Math': 65, 'English... |
class OslotsFeature(object):
def __init__(self, api, metaData, data):
self.api = api
self.meta = metaData
self.data = data[0]
self.maxSlot = data[1]
self.maxNode = data[2]
def items(self):
maxSlot = self.maxSlot
data = self.data
maxNode = self... | class Oslotsfeature(object):
def __init__(self, api, metaData, data):
self.api = api
self.meta = metaData
self.data = data[0]
self.maxSlot = data[1]
self.maxNode = data[2]
def items(self):
max_slot = self.maxSlot
data = self.data
max_node = self.... |
class Solution:
# Function to remove 2 chars by given index of the first char
def del_substr(i, s):
return s[:i] + s[i+2:]
def romanToInt(self, s: str) -> int:
# Roman numeral mapping
roman = {'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000}
# S... | class Solution:
def del_substr(i, s):
return s[:i] + s[i + 2:]
def roman_to_int(self, s: str) -> int:
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
special = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
output = 0
for i in ran... |
# Configuration file for jupyter-notebook.
## Whether to allow the user to run the notebook as root.
c.NotebookApp.allow_root = True
## The IP address the notebook server will listen on.
c.NotebookApp.ip = '*'
## Whether to open in a browser after starting. The specific browser used is
# platform dependent and dete... | c.NotebookApp.allow_root = True
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.password = ''
c.NotebookApp.port = 8888
c.NotebookApp.token = '' |
{
"targets": [
{
"target_name": "node-xed",
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"sources": [
"cpp/node-xed.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api')... | {'targets': [{'target_name': 'node-xed', 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'sources': ['cpp/node-xed.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', 'cpp/include'], 'conditions': [['OS in "linux"', {'libraries': ['../cpp/lib/linux/libxed.a']}], ['OS in "win... |
# Program to Add Two Integers
def isNumber(num):
if(type(num) == type(1)):
return True
else:
return False
def add(num1, num2):
if(isNumber(num1) & isNumber(num2)):
return num1 + num2
else:
return "we only accept numbers."
# Test cases
print(add(1, 2))
print(add("hola",... | def is_number(num):
if type(num) == type(1):
return True
else:
return False
def add(num1, num2):
if is_number(num1) & is_number(num2):
return num1 + num2
else:
return 'we only accept numbers.'
print(add(1, 2))
print(add('hola', 1)) |
def is_valid(r: int, c: int):
global n
return (-1 < r < n) and (-1 < c < n)
n = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(n)]
tokens = input()
while tokens != "END":
tokens = tokens.split()
cmd = tokens[0]
row = int(tokens[1])
col = int(tokens[2])
val = int(... | def is_valid(r: int, c: int):
global n
return -1 < r < n and -1 < c < n
n = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(n)]
tokens = input()
while tokens != 'END':
tokens = tokens.split()
cmd = tokens[0]
row = int(tokens[1])
col = int(tokens[2])
val = int(tokens[3... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/9/20 10:02
# @Author : Peter
# @Des :
# @File : Callback
# @Software: PyCharm
def msg(msg, *arg, **kw):
print("---" * 60)
print("callback -------> {}".format(msg))
print("---" * 60)
if __name__ == "__main__":
pass
| def msg(msg, *arg, **kw):
print('---' * 60)
print('callback -------> {}'.format(msg))
print('---' * 60)
if __name__ == '__main__':
pass |
class CounterStat:
new = int
@staticmethod
def apply_diff(x, y):
return x + y
class SetStat:
new = set
class Diff:
def __init__(self, added=set(), removed=set()):
self.added = added
self.removed = removed
def invert(self):
self.added, ... | class Counterstat:
new = int
@staticmethod
def apply_diff(x, y):
return x + y
class Setstat:
new = set
class Diff:
def __init__(self, added=set(), removed=set()):
self.added = added
self.removed = removed
def invert(self):
(self.added,... |
class Solution:
def heightChecker(self, heights: List[int]) -> int:
new_heights = sorted(heights)
count = 0
for i in range(len(heights)):
if heights[i] != new_heights[i]:
count += 1
return count
| class Solution:
def height_checker(self, heights: List[int]) -> int:
new_heights = sorted(heights)
count = 0
for i in range(len(heights)):
if heights[i] != new_heights[i]:
count += 1
return count |
# -*- coding: utf-8 -*-
A_INDEX = 0
B_INDEX = 1
C_INDEX = 2
D_INDEX = 3
def main():
values = input().split()
a = int(values[A_INDEX])
b = int(values[B_INDEX])
c = int(values[C_INDEX])
d = int(values[D_INDEX])
if b > c and d > a and c + d > a + b and c > 0 and d > 0 and a % 2 == 0:
pri... | a_index = 0
b_index = 1
c_index = 2
d_index = 3
def main():
values = input().split()
a = int(values[A_INDEX])
b = int(values[B_INDEX])
c = int(values[C_INDEX])
d = int(values[D_INDEX])
if b > c and d > a and (c + d > a + b) and (c > 0) and (d > 0) and (a % 2 == 0):
print('Valores aceito... |
# The realm, where users are allowed to login as administrators
SUPERUSER_REALM = ['super', 'administrators']
# Your database mysql://u:p@host/db
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:Pa55w0rd@localhost:5432/privacy_idea'
# This is used to encrypt the auth_token
SECRET_KEY = 't0p s3cr3t'
# This is used to en... | superuser_realm = ['super', 'administrators']
sqlalchemy_database_uri = 'postgresql://postgres:Pa55w0rd@localhost:5432/privacy_idea'
secret_key = 't0p s3cr3t'
pi_pepper = 'Never know...'
pi_encfile = '/opt/conda/envs/privacyidea/lib/python3.7/site-packages/enckey'
pi_audit_key_private = '/opt/conda/envs/privacyidea/lib... |
# program to split email to username and domain name
# made by itsmeevil
print("***Email Splitter***")
email = input("\nEnter an email: ")
sliced = email.split("@") # split string at "@" which will put it in an array- ["username", "domain name"]
print(f"\nUsername: {sliced[0]}\nDomain name: {sliced[1]}")
| print('***Email Splitter***')
email = input('\nEnter an email: ')
sliced = email.split('@')
print(f'\nUsername: {sliced[0]}\nDomain name: {sliced[1]}') |
class SocialMedia:
def __init__(self):
pass
def GetSocialMediaSites_NiceNames(self):
return {
'add.this':'AddThis',
'blogger':'Blogger',
'buffer':'Buffer',
'diaspora':'Diaspora',
'douban':'Douban',
'email':'EMail',
... | class Socialmedia:
def __init__(self):
pass
def get_social_media_sites__nice_names(self):
return {'add.this': 'AddThis', 'blogger': 'Blogger', 'buffer': 'Buffer', 'diaspora': 'Diaspora', 'douban': 'Douban', 'email': 'EMail', 'evernote': 'EverNote', 'getpocket': 'Pocket', 'facebook': 'FaceBook'... |
class ResistanceValue:
RESISTANCE_VALUES = [
(10, ["brown", "black"]),
(12, ["brown", "red"]),
(15, ["brown", "green"]),
(18, ["brown", "grey"]),
(22, ["red", "red"]),
(27, ["red", "purple"]),
(33, ["orange", "orange"]),
(39, ["orange", "white"]),
... | class Resistancevalue:
resistance_values = [(10, ['brown', 'black']), (12, ['brown', 'red']), (15, ['brown', 'green']), (18, ['brown', 'grey']), (22, ['red', 'red']), (27, ['red', 'purple']), (33, ['orange', 'orange']), (39, ['orange', 'white']), (47, ['yellow', 'purple']), (56, ['green', 'blue']), (68, ['green', '... |
def url(your_url):
root = 'https://sandboxapi.fsi.ng'
if your_url:
root = your_url
return root
| def url(your_url):
root = 'https://sandboxapi.fsi.ng'
if your_url:
root = your_url
return root |
N = int(input())
print("*"*N)
for i in range(N//2-1):
print("*"*((N//2-i)) + " "*(N-2*(N//2-i)) + "*"*((N//2-i)))
print("*" + " "*(N-2) + "*")
for i in range(N//2-2, -1, -1):
print("*"*((N//2-i)) + " "*(N-2*(N//2-i)) + "*"*((N//2-i)))
print("*"*N)
| n = int(input())
print('*' * N)
for i in range(N // 2 - 1):
print('*' * (N // 2 - i) + ' ' * (N - 2 * (N // 2 - i)) + '*' * (N // 2 - i))
print('*' + ' ' * (N - 2) + '*')
for i in range(N // 2 - 2, -1, -1):
print('*' * (N // 2 - i) + ' ' * (N - 2 * (N // 2 - i)) + '*' * (N // 2 - i))
print('*' * N) |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
dp = [[False for _ in range(len(s) + 1)] for _ in range(len(p) + 1)]
dp[0][0] = True
for i in range(1,len(p)+1):
if p[i-1] == '*':
dp[i][0] = dp[i-1][0]
else:
break
... | class Solution:
def is_match(self, s: str, p: str) -> bool:
dp = [[False for _ in range(len(s) + 1)] for _ in range(len(p) + 1)]
dp[0][0] = True
for i in range(1, len(p) + 1):
if p[i - 1] == '*':
dp[i][0] = dp[i - 1][0]
else:
break
... |
# Leo colorizer control file for md mode.
# This file is in the public domain.
# Properties for md mode.
# Important: most of this file is actually an html colorizer.
properties = {
"commentEnd": "-->",
"commentStart": "<!--",
"indentSize": "4",
"maxLineLen": "120",
"tabSize": "4",
}
... | properties = {'commentEnd': '-->', 'commentStart': '<!--', 'indentSize': '4', 'maxLineLen': '120', 'tabSize': '4'}
md_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '', 'highlight_digits': 'true', 'ignore_case': 'true', 'no_word_sep': ''}
md_inline_markup_attributes_dict = {'default': 'MARKUP', 'd... |
lista = ('APRENDER', 'PROGRAMA', 'LINGUAGES', 'PYTHON', 'CURSO',
'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCAADO',
'PROGRAMADOR', 'FUTURO')
for palavras in lista:
print(f'\nNa palavra {palavras} temos: ', end='')
for vogais in palavras:
if vogais in 'AEIOU':
pri... | lista = ('APRENDER', 'PROGRAMA', 'LINGUAGES', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCAADO', 'PROGRAMADOR', 'FUTURO')
for palavras in lista:
print(f'\nNa palavra {palavras} temos: ', end='')
for vogais in palavras:
if vogais in 'AEIOU':
print(vogais, end=' ') |
# -*- coding: utf-8 -*-
# package information.
INFO = dict(
name='coil',
description='Scheme interpreter written in Python',
author='coilo',
author_email='coilo.dev@gmail.com',
license='MIT License',
url='https://github.com/coilo/coil',
classifiers=[
'Programming Language :: Python... | info = dict(name='coil', description='Scheme interpreter written in Python', author='coilo', author_email='coilo.dev@gmail.com', license='MIT License', url='https://github.com/coilo/coil', classifiers=['Programming Language :: Python :: 3.4', 'License :: OSI Approved :: MIT License']) |
def foo(x):
def bar(x, y):
return lambda y: y(x)
return lambda y: bar(x, y)
print(foo(lambda x: x**3)(lambda x: x**2)(lambda x: x)(4)) | def foo(x):
def bar(x, y):
return lambda y: y(x)
return lambda y: bar(x, y)
print(foo(lambda x: x ** 3)(lambda x: x ** 2)(lambda x: x)(4)) |
# 190. Reverse Bits
# ttungl@gmail.com
# Reverse bits of a given 32 bits unsigned integer.
# For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
# return 964176192 (represented in binary as 00111001011110000010100101000000).
# Follow up:
# If this function is called many ti... | class Solution:
def reverse_bits(self, n):
res = 0
for i in range(32):
res <<= 1
res |= n & 1
n >>= 1
return res
res = str(bin(n))
pad = int(32 - len(res) + 2) * '0'
return int(res[0:2] + res[2:][::-1] + pad, 2) |
class Movie:
def __init__(self,title,year,imdb_score,have_seen):
self.title = title
self.year = year
self.imdb_score = imdb_score
self.have_seen = have_seen
def nice_print(self):
print("Title: ", self.title)
print("Year of production: ", self.year)
pr... | class Movie:
def __init__(self, title, year, imdb_score, have_seen):
self.title = title
self.year = year
self.imdb_score = imdb_score
self.have_seen = have_seen
def nice_print(self):
print('Title: ', self.title)
print('Year of production: ', self.year)
p... |
#!/usr/bin/env python3
class AppException(Exception):
status_code = 400
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class DeviceNotFoundException(AppException):
status_code = 404
class Ups... | class Appexception(Exception):
status_code = 400
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class Devicenotfoundexception(AppException):
status_code = 404
class Upstreamapiexception(AppExcep... |
saludo = "buenos dias"
for i in range(20):
print(saludo)
| saludo = 'buenos dias'
for i in range(20):
print(saludo) |
class ModuleBase():
# Invalid slot for modular chassis
MODULE_INVALID_SLOT = -1
# Possible card types for modular chassis
MODULE_TYPE_SUPERVISOR = "SUPERVISOR"
MODULE_TYPE_LINE = "LINE-CARD"
MODULE_TYPE_FABRIC = "FABRIC-CARD"
# Possible card status for modular chassis
# Module stat... | class Modulebase:
module_invalid_slot = -1
module_type_supervisor = 'SUPERVISOR'
module_type_line = 'LINE-CARD'
module_type_fabric = 'FABRIC-CARD'
module_status_empty = 'Empty'
module_status_offline = 'Offline'
module_status_present = 'Present'
module_status_fault = 'Fault'
module_st... |
#!/usr/bin/env python3
class Furnishings:
def __init__(self,room):
self.room = room
class Sofa(Furnishings):
pass
class Bookshelf(Furnishings):
pass
class Bed(Furnishings):
pass
class Table(Furnishings):
pass
def map_the_home(home):
home_map = {}
for fu... | class Furnishings:
def __init__(self, room):
self.room = room
class Sofa(Furnishings):
pass
class Bookshelf(Furnishings):
pass
class Bed(Furnishings):
pass
class Table(Furnishings):
pass
def map_the_home(home):
home_map = {}
for furniture in home:
if furniture.__dict__[... |
inputstart = int(input('Enter the beginning of the interval: '))
inputend = int(input('Enter the end of the interval: '))
for i in range(inputstart, inputend): # Iterating over numbers from a given interval
firstnum = 0 # The sum of the divisors of the second number = The first number of the pair
... | inputstart = int(input('Enter the beginning of the interval: '))
inputend = int(input('Enter the end of the interval: '))
for i in range(inputstart, inputend):
firstnum = 0
secnum = 0
for x in range(1, i):
if i % x == 0:
secnum += x
for y in range(1, secnum):
if secnum % y ==... |
class QvaPayException(Exception):
def __init__(self, status_code: int, *args: object) -> None:
super().__init__(*args)
self.status_code = status_code
| class Qvapayexception(Exception):
def __init__(self, status_code: int, *args: object) -> None:
super().__init__(*args)
self.status_code = status_code |
def mutable_or_immutable(para):
para += '1'
a = 'a'
b = ['b']
mutable_or_immutable(a)
print(a)
mutable_or_immutable(b)
print(b) | def mutable_or_immutable(para):
para += '1'
a = 'a'
b = ['b']
mutable_or_immutable(a)
print(a)
mutable_or_immutable(b)
print(b) |
#
# PySNMP MIB module HPR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:42:27 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)... | (sna_control_point_name,) = mibBuilder.importSymbols('APPN-MIB', 'SnaControlPointName')
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, val... |
RESULT = "result"
SUCCESS = "success"
ERROR = "error"
MESSAGE = "message"
CODE = "code"
PROPERTIES = 'properties'
MISSED_KEYS = {
"format": {
"type": "string"
}, "$ref": {
"type": "string",
"format": "uri"
}
}
| result = 'result'
success = 'success'
error = 'error'
message = 'message'
code = 'code'
properties = 'properties'
missed_keys = {'format': {'type': 'string'}, '$ref': {'type': 'string', 'format': 'uri'}} |
# We just put it here to get the checks to shut up
MIDDLEWARE_CLASSES = []
INSTALLED_APPS = (
'django.contrib.sites',
'absoluteuri',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
SITE_ID = 1
ROOT_URLCONF = 'absoluteuri.tests'
TEMPLATES = [
{
'BACKEND':... | middleware_classes = []
installed_apps = ('django.contrib.sites', 'absoluteuri')
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
site_id = 1
root_urlconf = 'absoluteuri.tests'
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True}] |
underworld_graph = {
992: {
"title": "Darkness",
"description": "You are standing on grass and surrounded by darkness.",
"terrain": "NORMAL",
"coordinates": "(75,61)",
"elevation": 0,
"w": 966
},
966: {
"title": "Darkness",
"description": "You ... | underworld_graph = {992: {'title': 'Darkness', 'description': 'You are standing on grass and surrounded by darkness.', 'terrain': 'NORMAL', 'coordinates': '(75,61)', 'elevation': 0, 'w': 966}, 966: {'title': 'Darkness', 'description': 'You are standing on grass and surrounded by darkness.', 'terrain': 'NORMAL', 'coordi... |
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
'''
T: O(n!) and S: O(n!)
'''
def permute(nums):
n = len(nums)
if n <= 1: return [nums]
out = []
for i in range(n):
first = [nums[... | class Solution:
def permute_unique(self, nums: List[int]) -> List[List[int]]:
"""
T: O(n!) and S: O(n!)
"""
def permute(nums):
n = len(nums)
if n <= 1:
return [nums]
out = []
for i in range(n):
first = ... |
__HEXCODE = "0123456789abcdef"
def byteToHex(someValue:int) -> str:
assert isinstance(someValue, int)
someValue = someValue & 255
return __HEXCODE[int(someValue / 16)] + __HEXCODE[someValue % 16]
def byteArrayToHexStr(someByteArray) -> str:
assert isinstance(someByteArray, (bytes, bytearray))
ret = ""
for... | __hexcode = '0123456789abcdef'
def byte_to_hex(someValue: int) -> str:
assert isinstance(someValue, int)
some_value = someValue & 255
return __HEXCODE[int(someValue / 16)] + __HEXCODE[someValue % 16]
def byte_array_to_hex_str(someByteArray) -> str:
assert isinstance(someByteArray, (bytes, bytearray))
... |
def trap(height):
'''Algo:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Output: Number of units of water trapped
Input: List of the brick walls position
Steps:
Observations:
find all subsequences s... | def trap(height):
"""Algo:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Output: Number of units of water trapped
Input: List of the brick walls position
Steps:
Observations:
find all subsequences s... |
def combination(n, r):
if n < r:
return 0
if r == 0:
return 1
tmp_n = 1
for i in range(r):
tmp_n *= n - i
tmp_r = 1
for i in range(r):
tmp_r *= r - i
return tmp_n // tmp_r
n, r = map(int, input().split())
print(combination(n, r))
def cmb(n, r):
if n - r ... | def combination(n, r):
if n < r:
return 0
if r == 0:
return 1
tmp_n = 1
for i in range(r):
tmp_n *= n - i
tmp_r = 1
for i in range(r):
tmp_r *= r - i
return tmp_n // tmp_r
(n, r) = map(int, input().split())
print(combination(n, r))
def cmb(n, r):
if n - r... |
'''
Created on Apr 20, 2017
@author: simulant
'''
| """
Created on Apr 20, 2017
@author: simulant
""" |
def iSort(lst,newl = [],n=1):
if len(lst)>0:
# print(newl,lst)
compInsert(newl,lst.pop(0),len(newl)-1)
if len(newl)>1:
print(newl,end=" ")
if len(lst)>0:
print(lst)
else:
print('\n',"sorted\n",newl,sep="")
iSort(lst,... | def i_sort(lst, newl=[], n=1):
if len(lst) > 0:
comp_insert(newl, lst.pop(0), len(newl) - 1)
if len(newl) > 1:
print(newl, end=' ')
if len(lst) > 0:
print(lst)
else:
print('\n', 'sorted\n', newl, sep='')
i_sort(lst, newl, n ... |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12930.py
# Description: UVa Online Judge - 12930
# =============================================================================
nt = 0
whil... | nt = 0
while True:
try:
line = input()
except EOFError:
break
nt += 1
line = line.split()
n_frac1 = len(line[0]) - line[0].find('.') - 1
n_frac2 = len(line[1]) - line[1].find('.') - 1
if n_frac1 < max(n_frac1, n_frac2):
line[0] += '0' * (max(n_frac1, n_frac2) - n_frac... |
consumer_key = '123456'
consumer_secret = '123456'
flickr_key = '123456'
flickr_secret = '123456'
| consumer_key = '123456'
consumer_secret = '123456'
flickr_key = '123456'
flickr_secret = '123456' |
'''69-crie um programa que leia a idade e o sexo de varias pessoas.a cada pessoa cadastrada, o programa devera perguntar se o usuario quer ou nao continuar.no final mostre:
A- quantas pessoas tem mais de 18 anos.
B- quantos homensforam cadastrados.
C- quantas mulheres tem menos de 20 anos. '''
tot18=toth=totm20=0
c... | """69-crie um programa que leia a idade e o sexo de varias pessoas.a cada pessoa cadastrada, o programa devera perguntar se o usuario quer ou nao continuar.no final mostre:
A- quantas pessoas tem mais de 18 anos.
B- quantos homensforam cadastrados.
C- quantas mulheres tem menos de 20 anos. """
tot18 = toth = totm20 ... |
# define variables
a = 10
b = 20
# swap numbers
a,b = b,a
# print result
print(a, b) | a = 10
b = 20
(a, b) = (b, a)
print(a, b) |
''' ATRIBUTOS DE UM ARQUIVO'''
arquivo = open('dados1.txt', 'r')
conteudo = arquivo.readlines()
print('tipo de conteudo, ', type (conteudo))
print('conteudo retornado pelo realines: ')
print(repr(conteudo))
arquivo.close()
| """ ATRIBUTOS DE UM ARQUIVO"""
arquivo = open('dados1.txt', 'r')
conteudo = arquivo.readlines()
print('tipo de conteudo, ', type(conteudo))
print('conteudo retornado pelo realines: ')
print(repr(conteudo))
arquivo.close() |
# Convert algebraic infix notation to revese polish notation (postfix)
def infixToPostfix(expr):
rpn = ""
stack = []
oper = "(+-*/^"
for e in expr:
if e.lower() >= "a" and e <= "z":
rpn += e
elif e == ")":
while len(stack) > 0:
op = stack.pop()
... | def infix_to_postfix(expr):
rpn = ''
stack = []
oper = '(+-*/^'
for e in expr:
if e.lower() >= 'a' and e <= 'z':
rpn += e
elif e == ')':
while len(stack) > 0:
op = stack.pop()
if op == '(':
break
... |
class Action_Keys():
def __init__(self, game_name):
self.game_name = game_name
def action_keys_Convert(self, key):
if self.game_name == 'Enduro':
return action_keys_Convert_Enduro(key)
elif self.game_name == 'SpaceInvaders':
return action_keys_C... | class Action_Keys:
def __init__(self, game_name):
self.game_name = game_name
def action_keys__convert(self, key):
if self.game_name == 'Enduro':
return action_keys__convert__enduro(key)
elif self.game_name == 'SpaceInvaders':
return action_keys__convert__space_i... |
def hex_to_rgb(hex_color, base=256):
return tuple(int(hex_color[i:i + 2], 16) for i in (1, 3, 5))
def rgb_to_hex(rgb, with_sharp=False, upper=True):
hex_code = ''.join([hex(one_channel)[2:] for one_channel in rgb])
if with_sharp:
hex_code = '#' + hex_code
if upper:
hex_code = hex_code... | def hex_to_rgb(hex_color, base=256):
return tuple((int(hex_color[i:i + 2], 16) for i in (1, 3, 5)))
def rgb_to_hex(rgb, with_sharp=False, upper=True):
hex_code = ''.join([hex(one_channel)[2:] for one_channel in rgb])
if with_sharp:
hex_code = '#' + hex_code
if upper:
hex_code = hex_code... |
# add two numbers using function without return
'''def add(x,y):
print("addition is : ",(x+y))
x = int(input("Enter a first number for addition : "))
y = int(input("Enter a second number for addition : "))
add(x,y)'''
# add two numbers using function with return
'''def add(x,y):
return (x+y)
x = int(input("Ent... | """def add(x,y):
print("addition is : ",(x+y))
x = int(input("Enter a first number for addition : "))
y = int(input("Enter a second number for addition : "))
add(x,y)"""
'def add(x,y):\n return (x+y)\nx = int(input("Enter a first number for addition : "))\ny = int(input("Enter a second number for addition : "))\... |
string = input("Ingrese la palabra a enmarcar: ")
num = int(input("Ingrese la cantidad de espacios entre el marco y la palabra"))
arribaAbajo = "*" * (len(string) + (num*2)+2)+ "\n"
laterales = "*" + " " * (len(string) + num*2) + "*\n"
resultado = arribaAbajo
for i in range(num):
resultado += laterales
resultado +=... | string = input('Ingrese la palabra a enmarcar: ')
num = int(input('Ingrese la cantidad de espacios entre el marco y la palabra'))
arriba_abajo = '*' * (len(string) + num * 2 + 2) + '\n'
laterales = '*' + ' ' * (len(string) + num * 2) + '*\n'
resultado = arribaAbajo
for i in range(num):
resultado += laterales
result... |
# At each point 3 choice possible
# 1. ith element.
# 2. max -ve before ith * ith element
# 3. max +ve before ith * ith element
# TC: O(n) | SC: O(1)
def solution_1(arr):
max_product = arr[0]
min_product = arr[0]
answer = arr[0]
for i in range(1, len(arr)):
choice1 = min_product*... | def solution_1(arr):
max_product = arr[0]
min_product = arr[0]
answer = arr[0]
for i in range(1, len(arr)):
choice1 = min_product * arr[i]
choice2 = max_product * arr[i]
min_product = min(arr[i], choice1, choice2)
max_product = max(arr[i], choice1, choice2)
answer... |
# set of rules that are expected to work for all supported frameworks
# Supported Frameworks: Mxnet, Pytorch, Tensorflow, Xgboost
UNIVERSAL_RULES = {
"AllZero",
"ClassImbalance",
"Confusion",
"LossNotDecreasing",
"Overfit",
"Overtraining",
"SimilarAcrossRuns",
"StalledTrainingRule",
... | universal_rules = {'AllZero', 'ClassImbalance', 'Confusion', 'LossNotDecreasing', 'Overfit', 'Overtraining', 'SimilarAcrossRuns', 'StalledTrainingRule', 'UnchangedTensor'}
deep_learning_rules = {'DeadRelu', 'ExplodingTensor', 'PoorWeightInitialization', 'SaturatedActivation', 'TensorVariance', 'VanishingGradient', 'Wei... |
__author__ = 'surya'
prey="This will give the list of prey protein used in the experiment"
bait="This will give all information of the Bait protein used in the experiment"
molecule="This will give all information store in the database about small molecule, if used in the experiment"
SdFound="This will give the list o... | __author__ = 'surya'
prey = 'This will give the list of prey protein used in the experiment'
bait = 'This will give all information of the Bait protein used in the experiment'
molecule = 'This will give all information store in the database about small molecule, if used in the experiment'
sd_found = 'This will give the... |
#
# PySNMP MIB module CISCO-TCPOFFLOAD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TCPOFFLOAD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:14:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ... |
'''given an array of integers, return indices of the two numbers such that they add up to a specific problem
given nums = [2, 7, 11, 15], target = 9
because nums[0] + nums[1] = 2 + 7 = 9
return [0, 1]
'''
#this is a great time to use a hash table
#class Solution(object):
def twoSum(nums, target):
index_mapping... | """given an array of integers, return indices of the two numbers such that they add up to a specific problem
given nums = [2, 7, 11, 15], target = 9
because nums[0] + nums[1] = 2 + 7 = 9
return [0, 1]
"""
def two_sum(nums, target):
index_mapping = {}
for i in range(len(nums)):
current = nums[i]
... |
def arrayMaximalAdjacentDifference(inputArray):
return max([abs(inputArray[x] - inputArray[x + 1]) for x in range(len(inputArray) - 1)])
# [2. 4, 1, 0] => 3
# [1, 1, 1, 1] => 1
# [-1, 4, 10, 3, -2] => 7
# [10, 11, 13] => 2
print(arrayMaximalAdjacentDifference([1, 1, 1, 1])) | def array_maximal_adjacent_difference(inputArray):
return max([abs(inputArray[x] - inputArray[x + 1]) for x in range(len(inputArray) - 1)])
print(array_maximal_adjacent_difference([1, 1, 1, 1])) |
[
{'base_name': 'PanSTARRS',
'service_type': 'xcone',
'adql': '',
'access_url': 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/'
'mean.votable?flatten_response=false&raw=false&sort_by=distance'
'&ra={}&dec={}&radius={}'
}
]
| [{'base_name': 'PanSTARRS', 'service_type': 'xcone', 'adql': '', 'access_url': 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/mean.votable?flatten_response=false&raw=false&sort_by=distance&ra={}&dec={}&radius={}'}] |
# https://www.codewars.com/kata/5174a4c0f2769dd8b1000003
# Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
# For example:
# solution([1,2,3,10,5]) # should return [1,2,3,5,10]
# solution(None) # should ... | def solution(nums):
return sorted(nums) if nums != None else []
print(solution([1, 2, 3, 10, 5]), [1, 2, 3, 5, 10])
print(solution(None), [])
print(solution([]), [])
print(solution([20, 2, 10]), [2, 10, 20])
print(solution([2, 20, 10]), [2, 10, 20]) |
# File for describing the Cab entity.
class Cab:
def __init__(self, city:str, brand: str, hourly_price: int, is_available: bool = True, id=None) -> None:
self.city = city
self.brand = brand
self.hourly_price = hourly_price
self.is_available = is_available
self.id = id | class Cab:
def __init__(self, city: str, brand: str, hourly_price: int, is_available: bool=True, id=None) -> None:
self.city = city
self.brand = brand
self.hourly_price = hourly_price
self.is_available = is_available
self.id = id |
print_('Voltages')
for a in ['CH1','CH2','CH3','AN8','CAP','SEN']:
button('Voltage : %s'%a,"get_voltage('%s')"%a,"display_number")
print('') #Just to get a newline
print('')
print_('Passive Elements')
button('Capacitance_:',"get_capacitance()","display_number")
print('')
button('Resistance__:',"get_resistance()","d... | print_('Voltages')
for a in ['CH1', 'CH2', 'CH3', 'AN8', 'CAP', 'SEN']:
button('Voltage : %s' % a, "get_voltage('%s')" % a, 'display_number')
print('')
print('')
print_('Passive Elements')
button('Capacitance_:', 'get_capacitance()', 'display_number')
print('')
button('Resistance__:', 'get_resistance()', 'displ... |
def main():
total = None
serie = input("What's your favorite serie?: ")
seasons = int(input("How much seasons have?: "))
number_chap = int(input("How much chapter have?: "))
duration_chap = int(input("How much minuts chapters have?: "))
total = seasons * number_chap * duration_chap / 60
p... | def main():
total = None
serie = input("What's your favorite serie?: ")
seasons = int(input('How much seasons have?: '))
number_chap = int(input('How much chapter have?: '))
duration_chap = int(input('How much minuts chapters have?: '))
total = seasons * number_chap * duration_chap / 60
prin... |
BASE_LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"format": "{module}: {message}",
"datefmt": "%d/%b/%Y %H:%M:%S",
"style": "{",
},
},
"handlers": {
"console": {
"level": "DEBUG",
... | base_logging = {'version': 1, 'disable_existing_loggers': False, 'formatters': {'console': {'format': '{module}: {message}', 'datefmt': '%d/%b/%Y %H:%M:%S', 'style': '{'}}, 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'console'}}, 'loggers': {'': {'handlers': ['console'], 'l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.