content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Program to find whether given input string has balanced brackets or not
def isBalanced(s):
a=[]
for i in range(len(s)):
if s[i]=='{' or s[i]=='[' or s[i]=='(':
a.append(s[i])
if s[i]=='}':
if len(a)==0:
return "NO"
else:
... | def is_balanced(s):
a = []
for i in range(len(s)):
if s[i] == '{' or s[i] == '[' or s[i] == '(':
a.append(s[i])
if s[i] == '}':
if len(a) == 0:
return 'NO'
elif a[-1] == '{':
a.pop()
else:
break
... |
#Requests stress Pod resources for a given period of time to simulate load
#deploymentLabel is the Deployment that the request is beings sent to
#cpuCost is the number of threads that the request will use on a pod
#execTime is how long the request will use those resource for before completing
class Request:
def __ini... | class Request:
def __init__(self, INFOLIST):
self.label = INFOLIST[0]
self.deploymentLabel = INFOLIST[1]
self.execTime = int(INFOLIST[2]) |
"""
datos de entrada
sueldo--->s--->int
ventas realizadas departamento 1--->vrd1--->int
ventas realizadas departamento 2--->vrd2--->int
ventas realizadas departamento 3--->vrd3--->int
"""
#entradas
s=int(input("ingrese el sueldo base: "))
vrd1=int(input("ingrese el numero de ventas realizadas por departamento 1: "))
vr... | """
datos de entrada
sueldo--->s--->int
ventas realizadas departamento 1--->vrd1--->int
ventas realizadas departamento 2--->vrd2--->int
ventas realizadas departamento 3--->vrd3--->int
"""
s = int(input('ingrese el sueldo base: '))
vrd1 = int(input('ingrese el numero de ventas realizadas por departamento 1: '))
vrd2 = i... |
dc_shell_setup_tcl = {
############
# default
############
'default': """
set BRICK_RESULTS [getenv "BRICK_RESULTS"];
set TSMC_DIR [getenv "TSMC_DIR"];
set DESIGN_NAME "%s"; # The name of the top-level design.
#############################################################
... | dc_shell_setup_tcl = {'default': '\nset BRICK_RESULTS\t\t\t\t[getenv "BRICK_RESULTS"]; \nset TSMC_DIR [getenv "TSMC_DIR"]; \n\nset DESIGN_NAME "%s"; # The name of the top-level design.\n\n#############################################################\n# The following variables wil... |
# Constants and functions for Marsaglia bits ingestion
# constants
FILE_BASE = '/media/alxfed/toca/bits.'
FILE_NUMBER_MIN = 1
FILE_NUMBER_MAX = 60
# pseudo-constants
FILE_EXTENSION = [str(i).zfill(2) for i in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX + 1)]
# starts with 0 element and ends with 59, that's why the dance i... | file_base = '/media/alxfed/toca/bits.'
file_number_min = 1
file_number_max = 60
file_extension = [str(i).zfill(2) for i in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX + 1)]
def file_name(n=1):
if n in range(FILE_NUMBER_MIN, FILE_NUMBER_MAX + 1):
return FILE_BASE + FILE_EXTENSION[n - 1]
else:
raise v... |
ENV_PARAMS = ("temperature", "salinity", "pressure", "sound_speed", "sound_absorption")
CAL_PARAMS = {
"EK": ("sa_correction", "gain_correction", "equivalent_beam_angle"),
"AZFP": ("EL", "DS", "TVR", "VTX", "equivalent_beam_angle", "Sv_offset"),
}
class CalibrateBase:
"""Class to handle calibration for a... | env_params = ('temperature', 'salinity', 'pressure', 'sound_speed', 'sound_absorption')
cal_params = {'EK': ('sa_correction', 'gain_correction', 'equivalent_beam_angle'), 'AZFP': ('EL', 'DS', 'TVR', 'VTX', 'equivalent_beam_angle', 'Sv_offset')}
class Calibratebase:
"""Class to handle calibration for all sonar mode... |
# Leetcode 138. Copy List with Random Pointer
#
# Link: https://leetcode.com/problems/copy-list-with-random-pointer/
# Difficulty: Medium
# Complexity:
# O(N) time | where N represent the number of elements in the linked list
# O(1) space
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next... | """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copy_random_list(self, head: 'Optional[Node]') -> 'Optional[Node]':
node = head
... |
def organise(records):
# { user: {shop -> {day -> counter}}}
res = {}
for person, shop, day in records:
if person and shop and (0 < day < 8):
if person not in res:
res[person] = {}
if shop not in res[person]:
res[person][shop] = {}
... | def organise(records):
res = {}
for (person, shop, day) in records:
if person and shop and (0 < day < 8):
if person not in res:
res[person] = {}
if shop not in res[person]:
res[person][shop] = {}
if day not in res[person][shop]:
... |
"""
70.49%
"""
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0 or n == 1:
return True
x = [n]
curr = n
ishappy = False
while True:
digits = list(str(curr))
curr = 0
... | """
70.49%
"""
class Solution(object):
def is_happy(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0 or n == 1:
return True
x = [n]
curr = n
ishappy = False
while True:
digits = list(str(curr))
curr = ... |
"""
.. Copyright (c) 2016 Marshall Farrier
license http://opensource.org/licenses/MIT
Constants for working with an options database
"""
LOG = {
'format': "%(asctime)s %(levelname)s %(module)s.%(funcName)s : %(message)s",
'path': 'mfstockmkt/options/db'
}
DB = {
'dev': {
... | """
.. Copyright (c) 2016 Marshall Farrier
license http://opensource.org/licenses/MIT
Constants for working with an options database
"""
log = {'format': '%(asctime)s %(levelname)s %(module)s.%(funcName)s : %(message)s', 'path': 'mfstockmkt/options/db'}
db = {'dev': {'name': 'test'}, 'prod': {'name': 'optMkt'}}
int... |
"""
File for global constants used in the program.
"""
# a constant
nsensors_taska = 5
nsensors_luke = 19
nsensors = nsensors_luke
nencoded = nsensors_luke
nfeat = 1
nelectrodes = 300
| """
File for global constants used in the program.
"""
nsensors_taska = 5
nsensors_luke = 19
nsensors = nsensors_luke
nencoded = nsensors_luke
nfeat = 1
nelectrodes = 300 |
'''
Convenience wrappers to make using the conf system as easy and seamless as possible
'''
def integrate(hub, imports, override=None, cli=None, roots=None, home_root=None, loader='json'):
'''
Load the conf sub and run the integrate sequence.
'''
hub.pop.sub.add('pop.mods.conf')
hub.conf.integrate... | """
Convenience wrappers to make using the conf system as easy and seamless as possible
"""
def integrate(hub, imports, override=None, cli=None, roots=None, home_root=None, loader='json'):
"""
Load the conf sub and run the integrate sequence.
"""
hub.pop.sub.add('pop.mods.conf')
hub.conf.integrate.... |
#!/usr/bin/env python
# create pipeline
#
reader = vtk.vtkDataSetReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/RectGrid2.vtk")
reader.Update()
# here to force exact extent
elev = vtk.vtkElevationFilter()
elev.SetInputConnection(reader.GetOutputPort())
elev.Update()
outline = vtk.vtkRectilinea... | reader = vtk.vtkDataSetReader()
reader.SetFileName('' + str(VTK_DATA_ROOT) + '/Data/RectGrid2.vtk')
reader.Update()
elev = vtk.vtkElevationFilter()
elev.SetInputConnection(reader.GetOutputPort())
elev.Update()
outline = vtk.vtkRectilinearGridOutlineFilter()
outline.SetInputData(elev.GetRectilinearGridOutput())
outline_... |
# Find the 10001st prime using the Sieve of Eratosthenes
def sieve(n):
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, (n + 1)):
if sieve[i]:
for j in range(i*i, (n + 1), i):
sieve[j] = False
return sieve
prime_sieve = sieve(400000);
primes =... | def sieve(n):
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, n + 1):
if sieve[i]:
for j in range(i * i, n + 1, i):
sieve[j] = False
return sieve
prime_sieve = sieve(400000)
primes = []
for (idx, val) in enumerate(prime_sieve):
if val:
... |
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
de... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = node(new_data)
new_node.next = self.head
self.head = new_node
def print_list(self):
... |
def bubble(alist):
for first in range(len(alist)-1,0,-1):
for sec in range(first):
if alist[sec] > alist[sec+1]:
tmp = alist[sec+1]
alist[sec+1] = alist[sec]
alist[sec] = tmp
def test_bubble():
alist = [1,7,2,5,9,12,5]
bubble(alist)
as... | def bubble(alist):
for first in range(len(alist) - 1, 0, -1):
for sec in range(first):
if alist[sec] > alist[sec + 1]:
tmp = alist[sec + 1]
alist[sec + 1] = alist[sec]
alist[sec] = tmp
def test_bubble():
alist = [1, 7, 2, 5, 9, 12, 5]
bubb... |
"""
>>> from datetime import datetime, timedelta
>>> from django.utils.timesince import timesince
>>> t = datetime(2007, 8, 14, 13, 46, 0)
>>> onemicrosecond = timedelta(microseconds=1)
>>> onesecond = timedelta(seconds=1)
>>> oneminute = timedelta(minutes=1)
>>> onehour = timedelta(hours=1)
>>> oneday = timedelta(da... | """
>>> from datetime import datetime, timedelta
>>> from django.utils.timesince import timesince
>>> t = datetime(2007, 8, 14, 13, 46, 0)
>>> onemicrosecond = timedelta(microseconds=1)
>>> onesecond = timedelta(seconds=1)
>>> oneminute = timedelta(minutes=1)
>>> onehour = timedelta(hours=1)
>>> oneday = timedelta(da... |
#
# PySNMP MIB module TPLINK-ETHERNETOAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-ETHERNETOAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:17:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) ... |
class ParticleInstanceModifier:
axis = None
object = None
particle_system_index = None
position = None
random_position = None
show_alive = None
show_dead = None
show_unborn = None
use_children = None
use_normal = None
use_path = None
use_preserve_shape = None
use_size... | class Particleinstancemodifier:
axis = None
object = None
particle_system_index = None
position = None
random_position = None
show_alive = None
show_dead = None
show_unborn = None
use_children = None
use_normal = None
use_path = None
use_preserve_shape = None
use_size... |
def FlagsForFile(filename, **kwargs):
return {
'flags': ['-x', 'c++', '-std=c++14', '-Wall', '-Wextra', '-Werror'
,'-I','C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/include'
,'-I','C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.2612... | def flags_for_file(filename, **kwargs):
return {'flags': ['-x', 'c++', '-std=c++14', '-Wall', '-Wextra', '-Werror', '-I', 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/include', '-I', 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.13.26128/... |
n = int(input('Digite um valor para calcular seu fatorial: '))
f = 1
print(f'Calculando {n}! = ', end =' ')
for i in range(1, n+1):
print(f'{n}', end = ' ')
print(' x ' if n > 1 else ' = ', end = ' ')
f *= i
n -= 1
print(f) | n = int(input('Digite um valor para calcular seu fatorial: '))
f = 1
print(f'Calculando {n}! = ', end=' ')
for i in range(1, n + 1):
print(f'{n}', end=' ')
print(' x ' if n > 1 else ' = ', end=' ')
f *= i
n -= 1
print(f) |
class TestTable:
def __init__(self):
self.id = None
self.code = None
DDLCOMMAND = """
CREATE TABLE TestTable (
id INTEGER CONSTRAINT pk_role PRIMARY KEY,
code INTEGER
);
"""
| class Testtable:
def __init__(self):
self.id = None
self.code = None
ddlcommand = '\n CREATE TABLE TestTable (\n id INTEGER CONSTRAINT pk_role PRIMARY KEY,\n code INTEGER\n );\n ' |
def most_common(lst):
return max(lst, key=lst.count)
| def most_common(lst):
return max(lst, key=lst.count) |
# https://leetcode.com/problems/defanging-an-ip-address
class Solution:
def defangIPaddr(self, address):
if not address:
return ""
ls = address.split(".")
return "[.]".join(ls)
| class Solution:
def defang_i_paddr(self, address):
if not address:
return ''
ls = address.split('.')
return '[.]'.join(ls) |
BOT = "b"
EMPTY = "-"
DIRT = "d"
def dist(pos1, pos2):
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def is_dirt(pos, board):
if min(pos) < 0:
return False
if pos[0] >= len(board):
return False
if pos[1] >= len(board[0]):
return False
if board[pos[0]][pos[1]] != ... | bot = 'b'
empty = '-'
dirt = 'd'
def dist(pos1, pos2):
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def is_dirt(pos, board):
if min(pos) < 0:
return False
if pos[0] >= len(board):
return False
if pos[1] >= len(board[0]):
return False
if board[pos[0]][pos[1]] != DI... |
SMALL = 1
MEDIUM = 2
LARGE = 3
ORDER_SIZE = (
(SMALL, u'Small'),
(MEDIUM, u'Medium'),
(LARGE, u'Large')
)
MARGARITA = 1
MARINARA = 2
SALAMI = 3
ORDER_TITLE = (
(1, u'margarita'),
(2, u'marinara'),
(3, u'salami')
)
RECEIVED = 1
IN_PROCESS = 2
OUT_FOR_DELIVERY = 3
DELIVERED = 4
RETURNED = 5
ORD... | small = 1
medium = 2
large = 3
order_size = ((SMALL, u'Small'), (MEDIUM, u'Medium'), (LARGE, u'Large'))
margarita = 1
marinara = 2
salami = 3
order_title = ((1, u'margarita'), (2, u'marinara'), (3, u'salami'))
received = 1
in_process = 2
out_for_delivery = 3
delivered = 4
returned = 5
order_status = ((RECEIVED, u'Recei... |
# I decided to write a code that generates data filtering object from a list of keyword parameters:
class Filter:
"""
Helper filter class. Accepts a list of single-argument
functions that return True if object in list conforms to some criteria
"""
def __init__(self, functions):
self... | class Filter:
"""
Helper filter class. Accepts a list of single-argument
functions that return True if object in list conforms to some criteria
"""
def __init__(self, functions):
self.functions = functions
def apply(self, data):
return [item for item in data if all((i(i... |
def fatorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
digit = int(input('numero para mostra o fatorial '))
print(fatorial(digit)) | def fatorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
digit = int(input('numero para mostra o fatorial '))
print(fatorial(digit)) |
# Time: O(n^2)
# Space: O(n)
class Solution(object):
def minSkips(self, dist, speed, hoursBefore):
"""
:type dist: List[int]
:type speed: int
:type hoursBefore: int
:rtype: int
"""
def ceil(a, b):
return (a+b-1)//b
dp = [0]*((len(dist)-1... | class Solution(object):
def min_skips(self, dist, speed, hoursBefore):
"""
:type dist: List[int]
:type speed: int
:type hoursBefore: int
:rtype: int
"""
def ceil(a, b):
return (a + b - 1) // b
dp = [0] * (len(dist) - 1 + 1)
for (i... |
#!/usr/bin/python3
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the sorted list(reverse=True):")
print(sorted(cars, reverse = True))
print("\nHere is the original list:")
print(cars)
pri... | cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)
print('\nHere is the sorted list:')
print(sorted(cars))
print('\nHere is the sorted list(reverse=True):')
print(sorted(cars, reverse=True))
print('\nHere is the original list:')
print(cars)
print(len(cars)) |
#
# PySNMP MIB module CISCO-CBP-TARGET-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CBP-TARGET-TC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:52:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
o = c50 = c20 = c10 = r = 0
while True:
o = int(input('Quanto voce deseja sacar? '))
r = o
while r >= 50:
c50 += 1
r = r - 50
while r >= 20:
c20 += 1
r = r - 20
while r > 10:
c10 += 1
r = r - 10
if r < 10:
break
print(f'Para o valor de R$ {... | o = c50 = c20 = c10 = r = 0
while True:
o = int(input('Quanto voce deseja sacar? '))
r = o
while r >= 50:
c50 += 1
r = r - 50
while r >= 20:
c20 += 1
r = r - 20
while r > 10:
c10 += 1
r = r - 10
if r < 10:
break
print(f'Para o valor de R$ {... |
__version__ = "3.12.1"
CTX_PROFILE = "PROFILE"
CTX_DEFAULT_PROFILE = "default"
| __version__ = '3.12.1'
ctx_profile = 'PROFILE'
ctx_default_profile = 'default' |
"""Mark this test directory as a package.
See https://github.com/python/mypy/issues/4008 for more info.
"""
| """Mark this test directory as a package.
See https://github.com/python/mypy/issues/4008 for more info.
""" |
"""
{{package}} module.
---------------
{{description}}
Author: {{author}}
Email: {{email}}
"""
| """
{{package}} module.
---------------
{{description}}
Author: {{author}}
Email: {{email}}
""" |
class Query:
def __init__(self, data, res={}):
self.res = res
self.data = data
def clear(self):
self.res = {}
def get(self):
return self.res
def documentAtTime(self, query, model):
self.data.clearScore()
# pLists = {}
query = query.split()
... | class Query:
def __init__(self, data, res={}):
self.res = res
self.data = data
def clear(self):
self.res = {}
def get(self):
return self.res
def document_at_time(self, query, model):
self.data.clearScore()
query = query.split()
query_term_count... |
'''
__init__.py
ColorPy is a Python package to convert physical descriptions of light:
spectra of light intensity vs. wavelength - into RGB colors that can
be drawn on a computer screen.
It provides a nice set of attractive plots that you can make of such
spectra, and some other color related functions... | """
__init__.py
ColorPy is a Python package to convert physical descriptions of light:
spectra of light intensity vs. wavelength - into RGB colors that can
be drawn on a computer screen.
It provides a nice set of attractive plots that you can make of such
spectra, and some other color related functions... |
"""Module `true`
Declares four functions:
* `isTrue`: return True if b is equal to True, return False otherwise
* `isFalse`: return True if b is equal to False, return False otherwise
* `isNotTrue`: return True if b is not equal to True, return False otherwise
* `isNotFalse`: return True if b is not equal to Fals... | """Module `true`
Declares four functions:
* `isTrue`: return True if b is equal to True, return False otherwise
* `isFalse`: return True if b is equal to False, return False otherwise
* `isNotTrue`: return True if b is not equal to True, return False otherwise
* `isNotFalse`: return True if b is not equal to Fals... |
# run python from an operating system command prmpt
# type the following:
msg = "Hello World"
print(msg)
# write it into a file called hello.py
# open a command prompt and type "python hello.py"
# this should run the script and print "Hello World"
# vscode alternative; Run the following in a terminal
# by selecting ... | msg = 'Hello World'
print(msg) |
# Backtracking
# def totalNQueens(self, n: int) -> int:
# diag1 = set()
# diag2 = set()
# used_cols = set()
#
# return self.helper(n, diag1, diag2, used_cols, 0)
#
#
# def helper(self, n, diag1, diag2, used_cols, row):
# if row == n:
# return 1
#
# solutions = 0
#
# for col in range(... | def total_n_queens(self, n):
self.res = 0
self.dfs([-1] * n, 0)
return self.res
def dfs(self, nums, index):
if index == len(nums):
self.res += 1
return
for i in range(len(nums)):
nums[index] = i
if self.valid(nums, index):
self.dfs(nums, index + 1)
def v... |
#########################
# EECS1015: Lab 9
# Name: Mahfuz Rahman
# Student ID: 217847518
# Email: mafu@my.yorku.ca
#########################
class MinMaxList:
def __init__(self, initializeList):
self.listData = initializeList
self.listData.sort()
def insertItem(self, item, printResult=False/... | class Minmaxlist:
def __init__(self, initializeList):
self.listData = initializeList
self.listData.sort()
def insert_item(self, item, printResult=False / True):
if len(self.listData) == 0:
self.listData.append(item)
print(f'Item ({item}) inserted at location 0')... |
'''
1560. Most Visited Sector in a Circular Track
Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i... | """
1560. Most Visited Sector in a Circular Track
Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i... |
while True:
X, Y = map(int, input().split())
if X == 0 or Y == 0:
break
else:
if X > 0 and Y > 0:
print('primeiro')
elif X > 0 and Y < 0:
print('quarto')
elif X < 0 and Y < 0:
print('terceiro')
else:
print('segundo')
| while True:
(x, y) = map(int, input().split())
if X == 0 or Y == 0:
break
elif X > 0 and Y > 0:
print('primeiro')
elif X > 0 and Y < 0:
print('quarto')
elif X < 0 and Y < 0:
print('terceiro')
else:
print('segundo') |
# A Caesar cypher is a weak form on encryption:
# It involves "rotating" each letter by a number (shift it through the alphabet)
#
# Example:
# A rotated by 3 is D; Z rotated by 1 is A
# In a SF movie the computer is called HAL, which is IBM rotated by -1
#
# Our function rotate_word() uses:
# ord (char to code_numbe... | def encrypt(word, no):
rotated = ''
for i in range(len(word)):
j = ord(word[i]) + no
rotated = rotated + chr(j)
return rotated
def decrypt(word, no):
return encrypt(word, -no)
assert encrypt('abc', 3) == 'def'
assert encrypt('IBM', -1) == 'HAL'
assert decrypt('def', 3) == 'abc'
assert d... |
expected_output = {
"chassis_mac_address": "4ce1.7592.a700",
"mac_wait_time": "Indefinite",
"redun_port_type": "FIBRE",
"chassis_index": {
1: {
"role": "Active",
"mac_address": "4ce1.7592.a700",
"priority": 2,
"hw_version": "V02",
"curr... | expected_output = {'chassis_mac_address': '4ce1.7592.a700', 'mac_wait_time': 'Indefinite', 'redun_port_type': 'FIBRE', 'chassis_index': {1: {'role': 'Active', 'mac_address': '4ce1.7592.a700', 'priority': 2, 'hw_version': 'V02', 'current_state': 'Ready', 'ip_address': '169.254.138.6', 'rmi_ip': '10.8.138.6'}, 2: {'role'... |
def read_instance(f):
print(f)
file = open(f)
width = int(file.readline())
n_circuits = int(file.readline())
DX = []
DY = []
for i in range(n_circuits):
piece = file.readline()
split_piece = piece.strip().split(" ")
DX.append(int(split_piece[0]))
DY.append(int... | def read_instance(f):
print(f)
file = open(f)
width = int(file.readline())
n_circuits = int(file.readline())
dx = []
dy = []
for i in range(n_circuits):
piece = file.readline()
split_piece = piece.strip().split(' ')
DX.append(int(split_piece[0]))
DY.append(int... |
n = 1024
while n > 0:
print(n)
n //= 2
| n = 1024
while n > 0:
print(n)
n //= 2 |
#!/usr/bin/env python3
title: str = 'Lady'
name: str = 'Gaga'
# Lady Gaga is an American actress, singer and songwriter.
# String concatination at its worst
print(title + ' ' + name + ' is an American actress, singer and songwriter.')
# Legacy example
print('%s %s is an American actress, singer and songwriter.' % (... | title: str = 'Lady'
name: str = 'Gaga'
print(title + ' ' + name + ' is an American actress, singer and songwriter.')
print('%s %s is an American actress, singer and songwriter.' % (title, name))
print('{} {} is an American actress, singer and songwriter.'.format(title, name))
print('{0} {1} is an American actress, sing... |
"""
Client Error HTTP Status Callables
"""
def HTTP404(environ, start_response):
"""
HTTP 404 Response
"""
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return ['']
def HTTP405(environ, start_response):
"""
HTTP 405 Response
"""
start_response('405 METHOD NOT ... | """
Client Error HTTP Status Callables
"""
def http404(environ, start_response):
"""
HTTP 404 Response
"""
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return ['']
def http405(environ, start_response):
"""
HTTP 405 Response
"""
start_response('405 METHOD NOT AL... |
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:
return 0
ans: float = x
tolerance = 0.00000001
while abs(ans - x/ans) > tolerance:
ans = (ans + x/ans) / 2
return int(ans)
tests = [
(
(4,),
2,
),
(
(8,... | class Solution:
def my_sqrt(self, x: int) -> int:
if x == 0:
return 0
ans: float = x
tolerance = 1e-08
while abs(ans - x / ans) > tolerance:
ans = (ans + x / ans) / 2
return int(ans)
tests = [((4,), 2), ((8,), 2)] |
if traffic_light == 'green':
pass # to implement
else:
stop()
| if traffic_light == 'green':
pass
else:
stop() |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class TypeVmDirEntryEnum(object):
"""Implementation of the 'Type_VmDirEntry' enum.
DirEntryType is the type of entry i.e. file/folder.
Specifies the type of directory entry.
'kFile' indicates that current entry is of file type.
'kDirectory' i... | class Typevmdirentryenum(object):
"""Implementation of the 'Type_VmDirEntry' enum.
DirEntryType is the type of entry i.e. file/folder.
Specifies the type of directory entry.
'kFile' indicates that current entry is of file type.
'kDirectory' indicates that current entry is of directory type.
'kS... |
if window.get_active_title() == "Terminal":
keyboard.send_keys("<super>+z")
else:
keyboard.send_keys("<ctrl>+z")
| if window.get_active_title() == 'Terminal':
keyboard.send_keys('<super>+z')
else:
keyboard.send_keys('<ctrl>+z') |
def naive_4() :
it = 0
def get_w() :
fan_in = 1
fan_out = 1
limit = np.sqrt(6 / (fan_in + fan_out))
return np.random.uniform(low =-limit , high = limit , size = (784 , 10))
w_init = get_w()
b_init = np,zeros(shape(10,))
last_score = 0.0
learnin_rate = 0.1
while True :
w = w_init + learning... | def naive_4():
it = 0
def get_w():
fan_in = 1
fan_out = 1
limit = np.sqrt(6 / (fan_in + fan_out))
return np.random.uniform(low=-limit, high=limit, size=(784, 10))
w_init = get_w()
b_init = (np, zeros(shape(10)))
last_score = 0.0
learnin_rate = 0.1
while True:... |
n = int(input())
for _ in range(n):
recording = input()
sounds = []
s = input()
while s != "what does the fox say?":
sounds.append(s.split(' ')[-1])
s = input()
fox_says = ""
for sound in recording.split(' '):
if sound not in sounds:
fox_says += " " + sou... | n = int(input())
for _ in range(n):
recording = input()
sounds = []
s = input()
while s != 'what does the fox say?':
sounds.append(s.split(' ')[-1])
s = input()
fox_says = ''
for sound in recording.split(' '):
if sound not in sounds:
fox_says += ' ' + sound
... |
count = 0
while count != 5:
count += 1
print(count)
print('--------')
counter = 0
while counter <= 20:
counter = counter + 3
print(counter)
print('--------')
countersito = 20
while countersito >= 0:
countersito -= 3
print(countersito) | count = 0
while count != 5:
count += 1
print(count)
print('--------')
counter = 0
while counter <= 20:
counter = counter + 3
print(counter)
print('--------')
countersito = 20
while countersito >= 0:
countersito -= 3
print(countersito) |
def netmiko_command(device, command=None, ckwargs={}, **kwargs):
if command:
output = device['nc'].send_command(command, **ckwargs)
else:
output = 'No command to run.'
return output | def netmiko_command(device, command=None, ckwargs={}, **kwargs):
if command:
output = device['nc'].send_command(command, **ckwargs)
else:
output = 'No command to run.'
return output |
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2017 University of California, Davis
#
# See COPYING for license... | __all__ = ['CoordSys', 'CSCart', 'CSGeo', 'Converter'] |
########
# PART 1
def read(filename):
with open("event2021/day25/" + filename, "r") as file:
rows = [line.strip() for line in file.readlines()]
return [ch for row in rows for ch in row], len(rows[0]), len(rows)
def draw(region_data):
region, width, height = region_data
for y in range(hei... | def read(filename):
with open('event2021/day25/' + filename, 'r') as file:
rows = [line.strip() for line in file.readlines()]
return ([ch for row in rows for ch in row], len(rows[0]), len(rows))
def draw(region_data):
(region, width, height) = region_data
for y in range(height):
for... |
# This sample tests the "reportPrivateUsage" feature.
class _TestClass(object):
pass
class TestClass(object):
def __init__(self):
self._priv1 = 1
| class _Testclass(object):
pass
class Testclass(object):
def __init__(self):
self._priv1 = 1 |
# Copyright (c) 2014 OpenStack Foundation.
#
# 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... | def ok():
res = '<?xml version="1.0" encoding="ISO-8859-1"?>\n<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"\n xmlns:if="http://www.cisco.com/nxos:1.0:if_manager"\n xmlns:nxos="http://www.cisco.com/nxos:1.0"\n message-id="urn:uuid:e7ef8254-10a6-11e4-b86d-becafe000bed">\n <... |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
'''
min_list = []
for i in range(len(nums)):
count = 0
for j in range(len(nums)):
if nums[j] < nums[i]:
count = count + 1
min_list.append... | class Solution:
def smaller_numbers_than_current(self, nums: List[int]) -> List[int]:
"""
min_list = []
for i in range(len(nums)):
count = 0
for j in range(len(nums)):
if nums[j] < nums[i]:
count = count + 1
min_list.ap... |
# def parse_ranges(input_string):
#
# output = []
# ranges = [item.strip() for item in input_string.split(',')]
#
# for item in ranges:
# start, end = [int(i) for i in item.split('-')]
# output.extend(range(start, end + 1))
#
# return output
# def parse_ranges(input_string):
#
# ran... | def parse_ranges(input_string):
ranges = [range_.strip() for range_ in input_string.split(',')]
for item in ranges:
if '->' in item:
yield int(item.split('-')[0])
elif '-' in item:
(start, end) = [int(i) for i in item.split('-')]
yield from range(start, end + ... |
"""
The question is incorrect as it says you can only travserse an open path once but
uses the same path repeatedly, violating its own rules
"""
def uniquePathsIII(grid: list[list[int]]) -> int:
if not grid or not grid[0]:
return 0
index = dict()
for r in range(rows := len(grid)):
for c in... | """
The question is incorrect as it says you can only travserse an open path once but
uses the same path repeatedly, violating its own rules
"""
def unique_paths_iii(grid: list[list[int]]) -> int:
if not grid or not grid[0]:
return 0
index = dict()
for r in range((rows := len(grid))):
for c... |
for row in range(4):
for col in range(4):
if col%3==0 and row<3 or row==3 and col>0:
print('*', end = ' ')
else:
print(' ', end = ' ')
print()
| for row in range(4):
for col in range(4):
if col % 3 == 0 and row < 3 or (row == 3 and col > 0):
print('*', end=' ')
else:
print(' ', end=' ')
print() |
def power(integer1, integer2=3):
result = 1
for i in range(integer2):
result = result * integer1
return result
print(power(3))
print(power(3,2)) | def power(integer1, integer2=3):
result = 1
for i in range(integer2):
result = result * integer1
return result
print(power(3))
print(power(3, 2)) |
#The values G,m1,m2,f and d stands for Gravitational constant, initial mass,final mass,force and distance respectively
G = 6.67 * 10 ** -11
m1 = float(input("The value of the initial mass: "))
m2 = float(input("The value of the final mass: "))
d = float(input("The distance between the bodies: "))
F = (G * m1 * m2)/(d *... | g = 6.67 * 10 ** (-11)
m1 = float(input('The value of the initial mass: '))
m2 = float(input('The value of the final mass: '))
d = float(input('The distance between the bodies: '))
f = G * m1 * m2 / d ** 2
print('The magnitude of the attractive force: ', F) |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
s = [ ]
j = 0
ans = 0
for i in range ( n ) :
while ( j < n and ( arr [ j ] not ... | def f_gold(arr, n):
s = []
j = 0
ans = 0
for i in range(n):
while j < n and arr[j] not in s:
s.append(arr[j])
j += 1
ans += (j - i) * (j - i + 1) // 2
s.remove(arr[i])
return ans
if __name__ == '__main__':
param = [([3, 4, 5, 6, 12, 15, 16, 17, 20,... |
var1 = 6
var2 = 3
if var1 >= 10:
print("Bigger than 10") #mind about the indent here (can be created by pressing tab button)
else:
print("Smaller or equal to 10") # all the codes written under a section wth tab belongs to that section
if var1 == var2:
print("var1 and 2 are equal")
else:
print("not eq... | var1 = 6
var2 = 3
if var1 >= 10:
print('Bigger than 10')
else:
print('Smaller or equal to 10')
if var1 == var2:
print('var1 and 2 are equal')
else:
print('not equal')
if var1 > 5 and var1 < 7:
print('Between')
elif var1 <= 5:
print('Smaller than 5')
else:
print('Bigger than or equal to 7')
i... |
class KNN():
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def predict(self, X_test, k=3):
predictions = np.zeros(X_test.shape[0])
for i, point in enumerate(X_test):
distances = self._get_distances(point... | class Knn:
def fit(self, X_train, y_train):
self.X_train = X_train
self.y_train = y_train
def predict(self, X_test, k=3):
predictions = np.zeros(X_test.shape[0])
for (i, point) in enumerate(X_test):
distances = self._get_distances(point)
k_nearest = self... |
__author__ = [
"Alexander Dunn <ardunn@lbl.gov>",
"Alireza Faghaninia <alireza.faghaninia@gmail.com>",
]
class BaseDataRetrieval:
"""
Abstract class to retrieve data from various material APIs while adhering to
a quasi-standard format for querying.
## Implementing a new DataRetrieval class
... | __author__ = ['Alexander Dunn <ardunn@lbl.gov>', 'Alireza Faghaninia <alireza.faghaninia@gmail.com>']
class Basedataretrieval:
"""
Abstract class to retrieve data from various material APIs while adhering to
a quasi-standard format for querying.
## Implementing a new DataRetrieval class
If you h... |
# -*- coding: utf-8 -*-
class Empty(object):
"""
Empty object represents emptyness state in `grappa`.
"""
def __repr__(self):
return 'Empty'
def __len__(self):
return 0
# Object reference representing emptpyness
empty = Empty()
| class Empty(object):
"""
Empty object represents emptyness state in `grappa`.
"""
def __repr__(self):
return 'Empty'
def __len__(self):
return 0
empty = empty() |
__title__ = 'alpha-vantage-py'
__description__ = 'Alpha Vantage Python package.'
__url__ = 'https://github.com/wstolk/alpha-vantage'
__version__ = '0.0.4'
__build__ = 0x022501
__author__ = 'Wouter Stolk'
__author_email__ = 'stolk.wouter@gmail.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2021 Wouter Stolk'... | __title__ = 'alpha-vantage-py'
__description__ = 'Alpha Vantage Python package.'
__url__ = 'https://github.com/wstolk/alpha-vantage'
__version__ = '0.0.4'
__build__ = 140545
__author__ = 'Wouter Stolk'
__author_email__ = 'stolk.wouter@gmail.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2021 Wouter Stolk'
_... |
LANGUAGES = [
{"English": "English", "alpha2": "en"},
{"English": "Italian", "alpha2": "it"},
]
| languages = [{'English': 'English', 'alpha2': 'en'}, {'English': 'Italian', 'alpha2': 'it'}] |
def max_profit(prices) -> int:
if not prices:
return 0
minPrice = prices[0]
maxPrice = 0
for i in range(1, len(prices)):
minPrice = min(prices[i], minPrice)
maxPrice = max(prices[i],maxPrice)
return maxPrice
arr = [100, 180, 260, 310, 40, 535, 695]
print(max_profit(arr)) | def max_profit(prices) -> int:
if not prices:
return 0
min_price = prices[0]
max_price = 0
for i in range(1, len(prices)):
min_price = min(prices[i], minPrice)
max_price = max(prices[i], maxPrice)
return maxPrice
arr = [100, 180, 260, 310, 40, 535, 695]
print(max_profit(arr)) |
# Paula Daly Solution to Problem 4 March 2019
# Collatz - particular sequence always reaches 1
# Defining the function
def collatz(number):
# looping through and if number found is even divide it by 2
if number % 2 == 0:
print(number // 2)
return number // 2
# looping through and if the nu... | def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 != 0:
result = 3 * number + 1
print(result)
return result
try:
n = input('Enter number: ')
while n != 1:
n = collatz(int(n))
except ValueError:
print('Please... |
"""
Reports: module definition
"""
PROPERTIES = {
'title': 'Reports',
'details': 'Create Reports',
'url': '/reports/',
'system': False,
'type': 'minor',
}
URL_PATTERNS = [
'^/reports/',
]
| """
Reports: module definition
"""
properties = {'title': 'Reports', 'details': 'Create Reports', 'url': '/reports/', 'system': False, 'type': 'minor'}
url_patterns = ['^/reports/'] |
"""
Datos de entrada
Presupuesto-->p-->float
Datos de Salida
Presupuesto ginecologia-->g-->float
Presupuesto traumatologiaa-->t-->float
Presupuesto pediatria-->e-->float
"""
#entrada
p=float(input("Digite el presupuesto Total: "))
#caja negra
g=p*0.4
t=p*0.3
e=p*0.3
#salida
print("El presupuesto dedicado a ginecologia:... | """
Datos de entrada
Presupuesto-->p-->float
Datos de Salida
Presupuesto ginecologia-->g-->float
Presupuesto traumatologiaa-->t-->float
Presupuesto pediatria-->e-->float
"""
p = float(input('Digite el presupuesto Total: '))
g = p * 0.4
t = p * 0.3
e = p * 0.3
print('El presupuesto dedicado a ginecologia: ', g)
print('E... |
class ConfigBase:
def __init__(self):
self.zookeeper = ""
self.brokers = ""
self.topic = ""
def __str__(self):
return str(self.zookeeper + ";" + self.brokers + ";" + self.topic)
def set_zookeeper(self, conf):
self.zookeeper = conf
def set_brokers(self, conf):
... | class Configbase:
def __init__(self):
self.zookeeper = ''
self.brokers = ''
self.topic = ''
def __str__(self):
return str(self.zookeeper + ';' + self.brokers + ';' + self.topic)
def set_zookeeper(self, conf):
self.zookeeper = conf
def set_brokers(self, conf):
... |
'''
Created on May 13, 2016
@author: david
'''
if __name__ == '__main__':
pass
| """
Created on May 13, 2016
@author: david
"""
if __name__ == '__main__':
pass |
# numbers_list = [int(x) for x in input().split(", ")]
def find_sum(numbers_list):
result = 1
for i in range(len(numbers_list)):
number = numbers_list[i]
if number <= 5:
result *= number
elif number <= 10:
result /= number
return result
print(find_sum([1,... | def find_sum(numbers_list):
result = 1
for i in range(len(numbers_list)):
number = numbers_list[i]
if number <= 5:
result *= number
elif number <= 10:
result /= number
return result
print(find_sum([1, 4, 5]), 20)
print(find_sum([4, 5, 6, 1, 3]), 20)
print(find... |
# post to the array-connections/connection-key endpoint to get a connection key
res = client.post_array_connections_connection_key()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
| res = client.post_array_connections_connection_key()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items)) |
BOT_CONFIG = 'default'
CONFIGS_DIR_NAME = 'configs'
BOTS_LOG_ROOT = 'bots'
LOG_FILE = 'bots.log'
LOOP_INTERVAL = 60
SETTINGS = 'settings.yml,secrets.yml'
VERBOSITY = 1
| bot_config = 'default'
configs_dir_name = 'configs'
bots_log_root = 'bots'
log_file = 'bots.log'
loop_interval = 60
settings = 'settings.yml,secrets.yml'
verbosity = 1 |
class BotLogic:
def BotExit(Nachricht):
print("Say Goodbye to the Bot")
# Beim Bot abmelden
def BotStart(Nachricht):
print("Say Hello to the Bot")
# Beim Bot anmelden | class Botlogic:
def bot_exit(Nachricht):
print('Say Goodbye to the Bot')
def bot_start(Nachricht):
print('Say Hello to the Bot') |
"""
1. Clarification
2. Possible solutions
- Python built-in
- Hand-crafted
- Deque
3. Coding
4. Tests
"""
# # T=O(n), S=O(n)
# class Solution:
# def reverseWords(self, s: str) -> str:
# if not s: return ''
# return ' '.join(reversed(s.split()))
# T=O(n), S=O(n) in python or O(1) in ... | """
1. Clarification
2. Possible solutions
- Python built-in
- Hand-crafted
- Deque
3. Coding
4. Tests
"""
class Solution:
def reverse_words(self, s: str) -> str:
if not s:
return ''
l = self.trim_spaces(s)
self.reverse(l, 0, len(l) - 1)
self.reverse_each_wo... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 10:22:45 2019
@author: Lee
"""
__version_info__ = (0, 3, 10)
__version__ = '.',join(map(str,__version_info__[:3]))
if len(__version_info__) == 4:
__version__+=__version_info[-1]
| """
Created on Tue May 14 10:22:45 2019
@author: Lee
"""
__version_info__ = (0, 3, 10)
__version__ = ('.', join(map(str, __version_info__[:3])))
if len(__version_info__) == 4:
__version__ += __version_info[-1] |
# class => module
MODULE_MAP = {
'ShuffleRerankPlugin': 'plugins.rerank.shuffle',
'PtTransformersRerankPlugin': 'plugins.rerank.transformers',
'PtDistilBertQAModelPlugin': 'plugins.qa.distilbert'
}
# image => directory
IMAGE_MAP = {
'alpine': '../Dockerfiles/alpine',
'pt': '../Dockerfiles/pt'
}
I... | module_map = {'ShuffleRerankPlugin': 'plugins.rerank.shuffle', 'PtTransformersRerankPlugin': 'plugins.rerank.transformers', 'PtDistilBertQAModelPlugin': 'plugins.qa.distilbert'}
image_map = {'alpine': '../Dockerfiles/alpine', 'pt': '../Dockerfiles/pt'}
indexer_map = {'ESIndexer': 'indexers.es'} |
'''
This file was used in an earlier version; geodata does not currently use
SQLAlchemy.
---
This file ensures all other files use the same SQLAlchemy session and Base.
Other files should import engine, session, and Base when needed. Use:
from initialize_sqlalchemy import Base, session, engine
'''
# # The engi... | """
This file was used in an earlier version; geodata does not currently use
SQLAlchemy.
---
This file ensures all other files use the same SQLAlchemy session and Base.
Other files should import engine, session, and Base when needed. Use:
from initialize_sqlalchemy import Base, session, engine
""" |
# Copyright 2021 IBM All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | """Constants for unstructured text
The ACD and QuickUMLS NLP services' output for these text strings must
be included in resources/acd/TestReportResponses.json and
resources/quickUmls/TestReportResponses.json
"""
text_for_multiple_conditions = 'Patient reports that they recently had pneumonia ' + 'and is now... |
# The authors of this work have released all rights to it and placed it
# in the public domain under the Creative Commons CC0 1.0 waiver
# (http://creativecommons.org/publicdomain/zero/1.0/).
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRA... | """Code for creating mappings that are used to place symbols in the matrix."""
def _distance(p):
return p[0] ** 2 + p[1] ** 2
def _may_use(vu, shape):
"""Returns true if the entry v, u may be used in a conjugate symmetric matrix.
In other words, the function returns false for v, u pairs that must be
... |
class EntityForm(django.forms.ModelForm):
class Meta:
model = Entity
exclude = (u'homepage', u'image')
| class Entityform(django.forms.ModelForm):
class Meta:
model = Entity
exclude = (u'homepage', u'image') |
'''
Simpler to just do the math than iterating. Break each number from 1 to 20 into its prime components.
The find the maximum times each unique prime occurs in any of the numbers.
Include the prime that number of times.
For instance, 9 is ( 3 * 3 ) and 18 is ( 3 * 3 * 2 ), both of which are the most
number of times ... | """
Simpler to just do the math than iterating. Break each number from 1 to 20 into its prime components.
The find the maximum times each unique prime occurs in any of the numbers.
Include the prime that number of times.
For instance, 9 is ( 3 * 3 ) and 18 is ( 3 * 3 * 2 ), both of which are the most
number of times ... |
"""
Mixin for returning the intersected frames.
"""
class IntersectedFramesMixin:
"""
Mixin for returning the intersected frames.
"""
def __init__(self):
self.intersected_frames = []
| """
Mixin for returning the intersected frames.
"""
class Intersectedframesmixin:
"""
Mixin for returning the intersected frames.
"""
def __init__(self):
self.intersected_frames = [] |
n, k = map(int, input().split())
arr = list(map(int, input().split()))
arr_find = list(map(int, input().split()))
def bin_search(arr, el):
left = -1
right = len(arr)
while right - left > 1:
mid = (right + left) // 2
if arr[mid] >= el:
right = mid
else:
lef... | (n, k) = map(int, input().split())
arr = list(map(int, input().split()))
arr_find = list(map(int, input().split()))
def bin_search(arr, el):
left = -1
right = len(arr)
while right - left > 1:
mid = (right + left) // 2
if arr[mid] >= el:
right = mid
else:
left... |
def default_getter(attribute=None):
"""a default method for missing renderer method
for example, the support to write data in a specific file type
is missing but the support to read data exists
"""
def none_presenter(_, **__):
"""docstring is assigned a few lines down the line"""
r... | def default_getter(attribute=None):
"""a default method for missing renderer method
for example, the support to write data in a specific file type
is missing but the support to read data exists
"""
def none_presenter(_, **__):
"""docstring is assigned a few lines down the line"""
r... |
"""Calculate Net:Gross estimates"""
def calculate_deep_net_gross_model(model, composition):
"""Calculate a net gross estimate based on the given deep composition"""
net_gross = model.assign(
bb_pct=lambda df: df.apply(
lambda row: composition["building_block_type"][row.building_block_type]... | """Calculate Net:Gross estimates"""
def calculate_deep_net_gross_model(model, composition):
"""Calculate a net gross estimate based on the given deep composition"""
net_gross = model.assign(bb_pct=lambda df: df.apply(lambda row: composition['building_block_type'][row.building_block_type], axis='columns'), cls_... |
n = int(input())
current = 1
bigger = False
for i in range(1, n + 1):
for j in range(1, i + 1):
if current > n:
bigger = True
break
print(str(current) + " ", end="")
current += 1
if bigger:
break
print()
| n = int(input())
current = 1
bigger = False
for i in range(1, n + 1):
for j in range(1, i + 1):
if current > n:
bigger = True
break
print(str(current) + ' ', end='')
current += 1
if bigger:
break
print() |
n = int(input())
d = list()
for i in range(2):
k=list(map(int,input().split()))
d.append(k)
c = list(zip(*d))
p = []
for i in range(len(c)):
p.append(c[i][0] * c[i][1])
number=sum(p)/sum(d[1])
print("{:.1f}".format(number)) | n = int(input())
d = list()
for i in range(2):
k = list(map(int, input().split()))
d.append(k)
c = list(zip(*d))
p = []
for i in range(len(c)):
p.append(c[i][0] * c[i][1])
number = sum(p) / sum(d[1])
print('{:.1f}'.format(number)) |
queries = {
"column": {
"head": "select top %d %s from %s;",
"all": "select %s from %s;",
"unique": "select distinct %s from %s;",
"sample": "select top %d %s from %s order by rand();"
},
"table": {
"select": "select %s from %s;",
"head": "select top %d * from... | queries = {'column': {'head': 'select top %d %s from %s;', 'all': 'select %s from %s;', 'unique': 'select distinct %s from %s;', 'sample': 'select top %d %s from %s order by rand();'}, 'table': {'select': 'select %s from %s;', 'head': 'select top %d * from %s;', 'all': 'select * from %s;', 'unique': 'select distinct %s... |
def reader():
with open('day3/puzzle_input.txt', 'r') as f:
return f.read().splitlines()
def tree(right, down):
count = 0
index = 0
lines = reader()
for i in range(0, len(lines), down):
line = lines[i]
if line[index] == '#':
count += 1
remainder = len(li... | def reader():
with open('day3/puzzle_input.txt', 'r') as f:
return f.read().splitlines()
def tree(right, down):
count = 0
index = 0
lines = reader()
for i in range(0, len(lines), down):
line = lines[i]
if line[index] == '#':
count += 1
remainder = len(lin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.