content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# ------------------------------
# 155. Min Stack
#
# Description:
# Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
# push(x) -- Push element x onto stack.
# pop() -- Removes the element on top of the stack.
# top() -- Get the top element.
# getMin() -- Retrieve the m... | class Minstack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minimum = sys.maxsize
def push(self, x: int) -> None:
if x <= self.minimum:
self.stack.append(self.minimum)
self.minimum = x
sel... |
"""
Project Euler - Problem Solution 023
Copyright (c) Justin McGettigan. All rights reserved.
https://github.com/jwmcgettigan/project-euler-solutions
"""
def sum_of_divisors(n):
# reused from problem 021
if n == 0: return 0
total = 1 # start at one since 1 is also a divisor
for i in range(2, int(n**0.5)+1):
... | """
Project Euler - Problem Solution 023
Copyright (c) Justin McGettigan. All rights reserved.
https://github.com/jwmcgettigan/project-euler-solutions
"""
def sum_of_divisors(n):
if n == 0:
return 0
total = 1
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
if n / i == i:
... |
# Insertion Sort
# Time Complexity: O(n^2)
# Space Complexity: O(1)
# Assume first element is sorted at beginning
# and then using it to compare with next element
# if this element is less than next element
# then swap them
def insertion_Sort(lst):
for i in range(1, len(lst)): # first read from 1 to n-1... | def insertion__sort(lst):
for i in range(1, len(lst)):
print(lst)
cur = lst[i]
j = i - 1
while j >= 0 and cur < lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = cur
return lst |
#Assume s is a string of lower case characters.
#Write a program that prints the longest substring of s
#in which the letters occur in alphabetical order.
#For example, if s = 'azcbobobegghakl', then your program should print
#Longest substring in alphabetical order is: beggh
#In the case of ties, print the first sub... | def f(x, y):
if ord(x) <= ord(y):
return True
else:
return False
s = 'rmfsntggmsuqemcvy'
a = 0
s1 = str()
w = bool()
while a < len(s) - 1:
w = f(s[a], s[a + 1])
if w == True:
s1 = s1 + s[a]
if a == len(s) - 2:
s1 = s1 + s[a + 1]
a += 1
elif w == Fa... |
# 384. Shuffle an Array
# https://leetcode.com/problems/shuffle-an-array/
class Solution:
def __init__(self, nums: List[int]):
self.orig = nums[:]
self.reset()
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""... | class Solution:
def __init__(self, nums: List[int]):
self.orig = nums[:]
self.reset()
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
self.data = self.orig[:]
return self.data
def shuffle(self) -> ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yue-Wen FANG'
__maintainer__ = "Yue-Wen FANG"
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__= 'Dec. 26, 2018'
"""
In a CLASS, we do not always need pass external arguments,
we can also set the default in the class
"""
c... | __author__ = 'Yue-Wen FANG'
__maintainer__ = 'Yue-Wen FANG'
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__ = 'Dec. 26, 2018'
'\nIn a CLASS, we do not always need pass external arguments,\nwe can also set the default in the class\n'
class Person:
def __init__(self, name, heigh... |
def calc_fitness_value(x,y,z):
fitnessvalues = []
x = generation_fitness_func(x)
y = generation_fitness_func(y)
z = generation_fitness_func(z)
for p in range(len(x)):
fitnessvalues += [(x[p]*x[p])+(y[p]*y[p])+(z[p]*z[p])]
return fitnessvalues
#fitness_value = x*x + y*... | def calc_fitness_value(x, y, z):
fitnessvalues = []
x = generation_fitness_func(x)
y = generation_fitness_func(y)
z = generation_fitness_func(z)
for p in range(len(x)):
fitnessvalues += [x[p] * x[p] + y[p] * y[p] + z[p] * z[p]]
return fitnessvalues
def generation_fitness_func(generation... |
content = b'BM\xbc\x03\x00\x00\x00\x00\x00\x006\x00\x00\x00(\x00\x00\x00\x1e\x00\x00\x00\x0f\x00\x00\x00\x01\x00\x10\x00\x00\x00\x00\x00\x86\x03\x00\x00\x12\x0b\x00\x00\x12\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x7f\xff\x7f\xff\x7f\xdf{\x7fo\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x... | content = b'BM\xbc\x03\x00\x00\x00\x00\x00\x006\x00\x00\x00(\x00\x00\x00\x1e\x00\x00\x00\x0f\x00\x00\x00\x01\x00\x10\x00\x00\x00\x00\x00\x86\x03\x00\x00\x12\x0b\x00\x00\x12\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x7f\xff\x7f\xff\x7f\xdf{\x7fo\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x7f\xff\x... |
class Baseagent(object):
def __init__(self, args):
self.args = args
self.agent = list()
# inference
def choose_action_to_env(self, observation, train=True):
observation_copy = observation.copy()
obs = observation_copy["obs"]
agent_id = observation_copy["controlled_p... | class Baseagent(object):
def __init__(self, args):
self.args = args
self.agent = list()
def choose_action_to_env(self, observation, train=True):
observation_copy = observation.copy()
obs = observation_copy['obs']
agent_id = observation_copy['controlled_player_index']
... |
# Knutha Morrisa Pratt (KMP) for string matching
# Complexity: O(n)
# Reference used: http://code.activestate.com/recipes/117214/
def kmp(full_string, pattern):
'''
It takes two arguments, the main string and the patterb which is to be
searched and returns the position(s) or the starting indexes of the
... | def kmp(full_string, pattern):
"""
It takes two arguments, the main string and the patterb which is to be
searched and returns the position(s) or the starting indexes of the
pattern in the main string (if exists)
agrs 'full-string' is the text from where pappern has to be searched
'pattern'... |
# Description
# Keep improving your bot by developing new skills for it.
# We suggest a simple guessing game that will predict the age of a user.
# It's based on a simple math trick. First, take a look at this formula:
# `age = (remainder3 * 70 + remainder5 * 21 + remainder7 * 15) % 105`
# The `numbersremainder3`, `... | print('Hello! My name is Aid.')
print('I was created in 2020.')
print('Please, remind me your name.')
name = input()
print(f'What a great name you have, {name}!')
print('Let me guess your age.')
print('Enter remainders of dividing your age by 3, 5 and 7.')
remainder3 = int(input())
remainder5 = int(input())
remainder7 ... |
REQUEST_CACHE_LIMIT = 200*1024*1024
QUERY_CACHE_LIMIT = 200*1024*1024
class index:
def __init__(self, name, request_cache, query_cache):
self.name = name
self.request_cache = request_cache
self.query_cache = query_cache
| request_cache_limit = 200 * 1024 * 1024
query_cache_limit = 200 * 1024 * 1024
class Index:
def __init__(self, name, request_cache, query_cache):
self.name = name
self.request_cache = request_cache
self.query_cache = query_cache |
PCLASS = '''
class Parser(object):
class ScanError(Exception):
pass
class ParseError(Exception):
pass
def parsefail(self, expected, found, val=None):
raise Parser.ParseError("Parse Error, line {}: Expected token {}, but found token {}:{}".format(self.line, expected, found, val))
... | pclass = '\nclass Parser(object):\n\n class ScanError(Exception):\n pass\n class ParseError(Exception):\n pass\n def parsefail(self, expected, found, val=None):\n raise Parser.ParseError("Parse Error, line {}: Expected token {}, but found token {}:{}".format(self.line, expected, found, val... |
x = int(input())
y = int(input())
numeros = [x,y]
numeros_ = sorted(numeros)
soma = 0
for a in range(numeros_[0]+1,numeros_[1]):
if a %2 != 0:
soma += a
print(soma)
| x = int(input())
y = int(input())
numeros = [x, y]
numeros_ = sorted(numeros)
soma = 0
for a in range(numeros_[0] + 1, numeros_[1]):
if a % 2 != 0:
soma += a
print(soma) |
class couponObject(object):
def __init__(
self,
player_unique_id,
code = None,
start_at = None,
ends_at = None,
entitled_collection_ids = {},
entitled_product_ids = {},
once_per_customer = None,
prerequisite_quantity_range = None,
... | class Couponobject(object):
def __init__(self, player_unique_id, code=None, start_at=None, ends_at=None, entitled_collection_ids={}, entitled_product_ids={}, once_per_customer=None, prerequisite_quantity_range=None, prerequisite_shipping_price_range=None, prerequisite_subtotal_range=None, prerequisite_collection_i... |
def on_enter(event_data):
""" """
pocs = event_data.model
pocs.next_state = 'sleeping'
pocs.say("Resetting the list of observations and doing some cleanup!")
# Cleanup existing observations
try:
pocs.observatory.scheduler.reset_observed_list()
except Exception as e: # pragma: no c... | def on_enter(event_data):
""" """
pocs = event_data.model
pocs.next_state = 'sleeping'
pocs.say('Resetting the list of observations and doing some cleanup!')
try:
pocs.observatory.scheduler.reset_observed_list()
except Exception as e:
pocs.logger.warning(f'Problem with cleanup: {... |
{
'targets': [
{
'target_name': 'vivaldi',
'type': 'none',
'dependencies': [
'chromium/chrome/chrome.gyp:chrome',
],
'conditions': [
['OS=="win"', {
# Allow running and debugging vivaldi from the top directory of the MSVS solution view
'product_na... | {'targets': [{'target_name': 'vivaldi', 'type': 'none', 'dependencies': ['chromium/chrome/chrome.gyp:chrome'], 'conditions': [['OS=="win"', {'product_name': 'vivaldi.exe', 'dependencies': ['chromium/third_party/crashpad/crashpad/handler/handler.gyp:crashpad_handler']}]]}]} |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: TreeNode) -> int:
'''
T: O(n) and S: O(n)
''... | class Solution:
def pseudo_palindromic_paths(self, root: TreeNode) -> int:
"""
T: O(n) and S: O(n)
"""
def is_palindrome(path):
d = {}
for digit in path:
d[digit] = d.get(digit, 0) + 1
even_count = 0
for digit in d:
... |
#
# PySNMP MIB module RADLAN-RADIUSSRV (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-RADIUSSRV
# Produced by pysmi-0.3.4 at Wed May 1 14:48:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) ... |
def rom(n):
if n == 1000: return 'M'
if n == 900: return 'CM'
if n == 500: return 'D'
if n == 400: return 'CD'
if n == 100: return 'C'
if n == 90: return 'XC'
if n == 50: return 'L'
if n == 40: return 'XL'
if n == 10: return 'X'
if n == 9: return 'IX'
if n == ... | def rom(n):
if n == 1000:
return 'M'
if n == 900:
return 'CM'
if n == 500:
return 'D'
if n == 400:
return 'CD'
if n == 100:
return 'C'
if n == 90:
return 'XC'
if n == 50:
return 'L'
if n == 40:
return 'XL'
if n == 10:
... |
# Copyright 2013 10gen Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | """
This module defines constants that are intended to be imported into the Flask
app configuration by default.
"""
debug = False
secret_key = 'A0gjhsd3678HK'
db_host = 'localhost'
db_port = 27017
db_name = 'mongows'
host = '0.0.0.0'
logging_conf = 'webapps/configs/logging.yaml'
no_frontend = False
no_validation = Fal... |
def resolve():
'''
code here
'''
N = int(input())
mat = [[int(item) for item in input().split()] for _ in range(N)]
dp = [[0 for _ in range(N+1)] for _ in range(N+1)]
for i in reversed(range(N-2)):
for j in range(i+2, N):
dp[i][j] = min(dp[i][j-1] * mat[i][0]*mat[j][0]*... | def resolve():
"""
code here
"""
n = int(input())
mat = [[int(item) for item in input().split()] for _ in range(N)]
dp = [[0 for _ in range(N + 1)] for _ in range(N + 1)]
for i in reversed(range(N - 2)):
for j in range(i + 2, N):
dp[i][j] = min(dp[i][j - 1] * mat[i][0] * ... |
"""
Provides the ApiContext class
"""
__copyright__ = "Copyright 2017, Datera, Inc."
class ApiContext(object):
"""
This object is created by the top level API object, and is passed in
to all endpoints and entities.
"""
def __init__(self):
self.connection = None
self.hostname = No... | """
Provides the ApiContext class
"""
__copyright__ = 'Copyright 2017, Datera, Inc.'
class Apicontext(object):
"""
This object is created by the top level API object, and is passed in
to all endpoints and entities.
"""
def __init__(self):
self.connection = None
self.hostname = None... |
#public symbols
__all__ = ["Factory"]
class Factory(object):
"""Base class for objects that know how to create other objects
based on a type argument and several optional arguments (version,
server id, and resource description).
"""
def __init__(self):
pass
def create(s... | __all__ = ['Factory']
class Factory(object):
"""Base class for objects that know how to create other objects
based on a type argument and several optional arguments (version,
server id, and resource description).
"""
def __init__(self):
pass
def create(self, typname, version=None, ser... |
class Classe_1:
def funcao_da_classe_1(self, string):
dicionario = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
valor = 0
for i in range(len(string)):
if i > 0 and dicionario[string[i]] > dicionario[string[i -1]]:
valor += dicionario[string[i]... | class Classe_1:
def funcao_da_classe_1(self, string):
dicionario = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
valor = 0
for i in range(len(string)):
if i > 0 and dicionario[string[i]] > dicionario[string[i - 1]]:
valor += dicionario[string[... |
def partition(array, low, high):
i = low - 1
pivot = array[high]
for j in range(low, high):
if array[j] < pivot:
i += 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[high] = array[high], array[i + 1]
return i + 1
def quick_sort(array... | def partition(array, low, high):
i = low - 1
pivot = array[high]
for j in range(low, high):
if array[j] < pivot:
i += 1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quick_sort(array, low, high)... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 19:41:31 2021
@author: Abeg
"""
#Linear Search
def LinearSearch(arr,k):
global value
for i in range(len(arr)):
if(arr[i]==k):
value=i
return value
n,k=map(int,input().split())
arr=list(map(int,input().strip().spli... | """
Created on Wed Mar 24 19:41:31 2021
@author: Abeg
"""
def linear_search(arr, k):
global value
for i in range(len(arr)):
if arr[i] == k:
value = i
return value
(n, k) = map(int, input().split())
arr = list(map(int, input().strip().split()))
print(linear_search(arr, k)) |
# -*- coding: utf-8 -*-
# @Date : 2014-06-27 14:37:20
# @Author : xindervella@gamil.com
SRTP_URL = 'http://10.1.30.98:8080/srtp2/USerPages/SRTP/Report3.aspx'
TIME_OUT = 8
| srtp_url = 'http://10.1.30.98:8080/srtp2/USerPages/SRTP/Report3.aspx'
time_out = 8 |
i=1
for i in range(0,5):
if i==2:
print('bye')
break
print("sadique")
| i = 1
for i in range(0, 5):
if i == 2:
print('bye')
break
print('sadique') |
def _normalize_scratch_rotation(degree):
while degree <= -180:
degree += 360
while degree > 180:
degree -= 360
return degree
def _convert_scratch_to_pygame_rotation(degree):
deg = _normalize_scratch_rotation(degree)
if deg == 0:
return 90
elif deg == 90:
... | def _normalize_scratch_rotation(degree):
while degree <= -180:
degree += 360
while degree > 180:
degree -= 360
return degree
def _convert_scratch_to_pygame_rotation(degree):
deg = _normalize_scratch_rotation(degree)
if deg == 0:
return 90
elif deg == 90:
return 0... |
def frequencySort(self, s: str) -> str:
m = {}
for i in s:
if i not in m:
m[i] = 1
else:
m[i] += 1
r = ""
for i in sorted(m, key=m.get, reverse=True):
r += i * m[i]
return r | def frequency_sort(self, s: str) -> str:
m = {}
for i in s:
if i not in m:
m[i] = 1
else:
m[i] += 1
r = ''
for i in sorted(m, key=m.get, reverse=True):
r += i * m[i]
return r |
# String Format
# As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
'''
age = 23
txt = "My name is Nayan, I am " + age + "Years old"
print(txt) #Error
'''
# But we can combine strings and numbers by using the format() method!
# The format() method takes the passed arg... | """
age = 23
txt = "My name is Nayan, I am " + age + "Years old"
print(txt) #Error
"""
age = 23
txt = "My name is Nayan, and I'm {} Years old"
print(txt.format(age))
quantity = 5
itemno = 1001
price = 101.05
myorder = 'I want {} pieces of item {} for {} Rupees'
print(myorder.format(quantity, itemno, price))
quantity... |
#Write a Python class to reverse a string word by word.
class py_solution:
def reverse_words(self, s):
return reversed(s)
print(py_solution().reverse_words('rewangi'))
| class Py_Solution:
def reverse_words(self, s):
return reversed(s)
print(py_solution().reverse_words('rewangi')) |
# Chapter 7 exercises from the book Python Crash Course: A Hands-On, Project-Based Introduction to Programming.
# 7-1. Rental Car
car = input('Which car do you want to rent?')
print('Let me see if I can find you a '+ car + '.')
# 7-2. Restaurant Seating
number = input('How many people come to dinner?')
number... | car = input('Which car do you want to rent?')
print('Let me see if I can find you a ' + car + '.')
number = input('How many people come to dinner?')
number = int(number)
if number > 8:
print('Sorry, but there is none table available for your group right now, can you wait for a little?')
else:
print('Your table ... |
# follow pep-386
# Examples:
# * 0.3 - released version
# * 0.3a1 - alpha version
# * 0.3.dev - version in developmentv
__version__ = '0.7.dev'
__releasedate__ = ''
| __version__ = '0.7.dev'
__releasedate__ = '' |
class RegistrationInfo(object):
def __init__(self, hook_name, expect_exists, register_kwargs=None):
assert isinstance(expect_exists, bool)
self.hook_name = hook_name
self.expect_exists = expect_exists
self.register_kwargs = register_kwargs or {}
| class Registrationinfo(object):
def __init__(self, hook_name, expect_exists, register_kwargs=None):
assert isinstance(expect_exists, bool)
self.hook_name = hook_name
self.expect_exists = expect_exists
self.register_kwargs = register_kwargs or {} |
"""
Write a Python function that takes a sequence of numbers and determine whether all numbers are different from each other
"""
def test_distinct(data):
if len(data) == len(set(data)):
return True
else:
return False
print(test_distinct([1, 5, 7, 9]))
print(test_distinct([2, 7, 5, 8, 8, 9, 0])) | """
Write a Python function that takes a sequence of numbers and determine whether all numbers are different from each other
"""
def test_distinct(data):
if len(data) == len(set(data)):
return True
else:
return False
print(test_distinct([1, 5, 7, 9]))
print(test_distinct([2, 7, 5, 8, 8, 9, 0])) |
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('api', '/api')
config.add_route('download', '/download')
config.add_route('docs', '/docs')
config.add_route('create', '/create')
config.add_route('demo', '/dem... | def includeme(config):
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('api', '/api')
config.add_route('download', '/download')
config.add_route('docs', '/docs')
config.add_route('create', '/create')
config.add_route('demo', '/dem... |
'''
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both inde... | """
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both inde... |
metadata = Hash()
data = Hash(default_value=0)
sc_contract = Variable()
unit_contract = Variable()
terrain_contract = Variable()
random.seed()
@construct
def seed():
metadata['operator'] = ctx.caller
#prize calclulation Parameters
metadata['winner_percent'] = decimal('0.09')
metadata['h... | metadata = hash()
data = hash(default_value=0)
sc_contract = variable()
unit_contract = variable()
terrain_contract = variable()
random.seed()
@construct
def seed():
metadata['operator'] = ctx.caller
metadata['winner_percent'] = decimal('0.09')
metadata['house_percent'] = decimal('0.01')
sc_contract.se... |
# -*- coding: utf-8 -*-
"""Top-level package for poker_project."""
__author__ = """Zack Raffo"""
__email__ = 'raffo.z@husky.neu.edu'
__version__ = '0.1.0'
| """Top-level package for poker_project."""
__author__ = 'Zack Raffo'
__email__ = 'raffo.z@husky.neu.edu'
__version__ = '0.1.0' |
def tic_tac_toe():
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end = False
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def draw():
print(board[0], board[1], board[2])
print(board[3], board[4], board[5])
print(board... | def tic_tac_toe():
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end = False
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def draw():
print(board[0], board[1], board[2])
print(board[3], board[4], board[5])
print(board[6], boa... |
# This is the library where we store the value of the different constants
# In order to use this library do:
# import units_library as UL
# U = UL.units()
# kpc = U.kpc_cm
class units:
def __init__(self):
self.rho_crit = 2.77536627e11 #h^2 Msun/Mpc^3
self.c_kms = 3e5 #km/s
... | class Units:
def __init__(self):
self.rho_crit = 277536627000.0
self.c_kms = 300000.0
self.Mpc_cm = 3.0856e+24
self.kpc_cm = 3.0856e+21
self.Msun_g = 1.989e+33
self.Ymass = 0.24
self.mH_g = 1.6726e-24
self.yr_s = 31557600.0
self.km_cm = 100000... |
def get_transporter(configuration):
transporter_module = configuration.get_module_transporter()
transporter_configuration = configuration.get_configuration()
return transporter_module.get_transporter(transporter_configuration)
| def get_transporter(configuration):
transporter_module = configuration.get_module_transporter()
transporter_configuration = configuration.get_configuration()
return transporter_module.get_transporter(transporter_configuration) |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class HadoopDistributionEnum(object):
"""Implementation of the 'HadoopDistributionEnum' enum.
Specifies the Hadoop Distribution.
Hadoop distribution.
'CDH' indicates Hadoop distribution type Cloudera.
'HDP' indicates Hadoop dist... | class Hadoopdistributionenum(object):
"""Implementation of the 'HadoopDistributionEnum' enum.
Specifies the Hadoop Distribution.
Hadoop distribution.
'CDH' indicates Hadoop distribution type Cloudera.
'HDP' indicates Hadoop distribution type Hortonworks.
"""
cdh = 'CDH'
hd... |
def LCSlength(X, Y, lx, ly): # Parameters are the two strings and their lengths
if lx == 0 or ly == 0:
return 0
if X[lx - 1] == Y[ly - 1]:
return LCSlength(X, Y, lx - 1, ly - 1) + 1
return max(LCSlength(X, Y, lx - 1, ly), LCSlength(X, Y, lx, ly - 1))
print("Enter the first string : \n")
X... | def lc_slength(X, Y, lx, ly):
if lx == 0 or ly == 0:
return 0
if X[lx - 1] == Y[ly - 1]:
return lc_slength(X, Y, lx - 1, ly - 1) + 1
return max(lc_slength(X, Y, lx - 1, ly), lc_slength(X, Y, lx, ly - 1))
print('Enter the first string : \n')
x = input()
print('Enter the second string: \n')
y ... |
def areRotations(someString, someSubstring):
tempString = 2 * someString
return tempString.find(someSubstring, 0, len(tempString))
print(areRotations("AACD", "ACDA"))
print(areRotations("AACD", "AADC"))
| def are_rotations(someString, someSubstring):
temp_string = 2 * someString
return tempString.find(someSubstring, 0, len(tempString))
print(are_rotations('AACD', 'ACDA'))
print(are_rotations('AACD', 'AADC')) |
m= ["qzbw",
"qez",
],[
"xgedfibnyuhqsrazlwtpocj",
"fxgpoqijdzybletckwaunsr",
"pwnqsizrfcbyljexgouatd",
"ljtperqsodghnufiycxwabz",
],[
"uk",
"kupacjlriv",
"dku",
"qunk",
],[
"yjnprofmcuhdlawt",
"frmhulyncvweatodzjp",
"fhadtrcyjzwlnpumo",
"hrcutablndyjpfmwo",
],[
"rdclv",
"lrvdc",
"crldv",
"dvrcl",
"vrlcd",
],[
"dqrwajpb... | m = (['qzbw', 'qez'], ['xgedfibnyuhqsrazlwtpocj', 'fxgpoqijdzybletckwaunsr', 'pwnqsizrfcbyljexgouatd', 'ljtperqsodghnufiycxwabz'], ['uk', 'kupacjlriv', 'dku', 'qunk'], ['yjnprofmcuhdlawt', 'frmhulyncvweatodzjp', 'fhadtrcyjzwlnpumo', 'hrcutablndyjpfmwo'], ['rdclv', 'lrvdc', 'crldv', 'dvrcl', 'vrlcd'], ['dqrwajpb', 'asrf... |
#!/usr/bin/env python2
ARTICLE_QUERY = """
SELECT
articles.title,
count(*) AS num
FROM
log,
articles
WHERE
log.path = '/article/' || articles.slug
GROUP BY... | article_query = "\n SELECT\n articles.title,\n count(*) AS num\n FROM\n log,\n articles\n WHERE\n log.path = '/article/' || articles.slug\n GROUP BY\n ... |
a, b = 1, 2
result = 0
while True:
a, b = b, a + b
if a >= 4_000_000:
break
if a % 2 == 0:
result += a
print(result)
| (a, b) = (1, 2)
result = 0
while True:
(a, b) = (b, a + b)
if a >= 4000000:
break
if a % 2 == 0:
result += a
print(result) |
def draw_1d(line, row):
print(("*"*row + "\n")*line)
def draw_2d(line, row, simbol):
print((simbol*row + "\n")*line)
def special_draw_2d(line, row, border, fill):
print(border*row)
row -= 2
line -= 2
i = line
while i > 0:
print(border + fill*row + border)
i -= 1
print(... | def draw_1d(line, row):
print(('*' * row + '\n') * line)
def draw_2d(line, row, simbol):
print((simbol * row + '\n') * line)
def special_draw_2d(line, row, border, fill):
print(border * row)
row -= 2
line -= 2
i = line
while i > 0:
print(border + fill * row + border)
i -= 1... |
def registrar(registry, name="entry"):
"""
Creates and returns a register function that can be used as a decorator
for registering functions into the given registry dictionary.
:param registry: Dictionary to add entry registrations to.
:param name: Name to give to each entry. "entry" is used by de... | def registrar(registry, name='entry'):
"""
Creates and returns a register function that can be used as a decorator
for registering functions into the given registry dictionary.
:param registry: Dictionary to add entry registrations to.
:param name: Name to give to each entry. "entry" is used by def... |
#!/usr/bin/env python
# encoding: utf-8
# @author: Zhipeng Ye
# @contact: Zhipeng.ye19@xjtlu.edu.cn
# @file: implementstrstr.py
# @time: 2020-02-22 16:27
# @desc:
class Solution:
def strStr(self, haystack, needle):
if len(needle) == 0:
return 0
haystack_length = len(haystack)
... | class Solution:
def str_str(self, haystack, needle):
if len(needle) == 0:
return 0
haystack_length = len(haystack)
needle_length = len(needle)
if needle_length > haystack_length:
return -1
index = -1
for i in range(haystack_length):
... |
"""
Helper script for writing a "input_collect_{run_name}.json" input file (see README.md).
Below is an example of it for the 1D Heisenberg model ({run_name} = 1D_heisenberg1)
which has a seed of 1 and 1600 samples.
"""
info = 'heisenberg1'
run_name = 'run1D_{}_1_'.format(info)
input_filename = 'input_collect... | """
Helper script for writing a "input_collect_{run_name}.json" input file (see README.md).
Below is an example of it for the 1D Heisenberg model ({run_name} = 1D_heisenberg1)
which has a seed of 1 and 1600 samples.
"""
info = 'heisenberg1'
run_name = 'run1D_{}_1_'.format(info)
input_filename = 'input_collect_run1D_{}.... |
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'shard',
'type': 'static_library',
'msvs_shard': 4,
'sources': [
'hello1.cc',
'hello2.... | {'targets': [{'target_name': 'shard', 'type': 'static_library', 'msvs_shard': 4, 'sources': ['hello1.cc', 'hello2.cc', 'hello3.cc', 'hello4.cc'], 'product_dir': '<(PRODUCT_DIR)'}, {'target_name': 'refs_to_shard', 'type': 'executable', 'dependencies': ['shard'], 'sources': ['hello.cc']}]} |
#-*- coding: utf-8 -*-
BASE = {
# can be overriden by a configuration file
'SOA_MNAME': 'polaris.example.com.',
'SOA_RNAME': 'hostmaster.polaris.example.com.',
'SOA_SERIAL': 1,
'SOA_REFRESH': 3600,
'SOA_RETRY': 600,
'SOA_EXPIRE': 86400,
'SOA_MINIMUM': 1,
'SOA_TTL': 86400,
'SHAR... | base = {'SOA_MNAME': 'polaris.example.com.', 'SOA_RNAME': 'hostmaster.polaris.example.com.', 'SOA_SERIAL': 1, 'SOA_REFRESH': 3600, 'SOA_RETRY': 600, 'SOA_EXPIRE': 86400, 'SOA_MINIMUM': 1, 'SOA_TTL': 86400, 'SHARED_MEM_HOSTNAME': '127.0.0.1', 'SHARED_MEM_STATE_TIMESTAMP_KEY': 'polaris_health:state_timestamp', 'SHARED_ME... |
# test_with_pytest.py
def test_always_passes():
assert True
def test_always_fails():
assert False | def test_always_passes():
assert True
def test_always_fails():
assert False |
def main():
chars = input()
stack = []
for char in chars:
if char == '<':
# pop from stack
if len(stack) != 0:
stack.pop()
else:
stack.append(char)
print(''.join(stack))
if __name__ == "__main__":
main()
| def main():
chars = input()
stack = []
for char in chars:
if char == '<':
if len(stack) != 0:
stack.pop()
else:
stack.append(char)
print(''.join(stack))
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
model = {
'en ': 0,
'de ': 1,
' de': 2,
'et ': 3,
'an ': 4,
' he': 5,
'er ': 6,
' va': 7,
'n d': 8,
'van': 9,
'een': 10,
'het': 11,
' ge': 12,
'oor': 13,
' ee': 14,
'der': 15,
' en': 16,
'ij ': 17,
'aar': 18,
'gen': 19,
'te ': 20,
'ver': 21,
' in': 22,
' me': 23,
'aan': ... | model = {'en ': 0, 'de ': 1, ' de': 2, 'et ': 3, 'an ': 4, ' he': 5, 'er ': 6, ' va': 7, 'n d': 8, 'van': 9, 'een': 10, 'het': 11, ' ge': 12, 'oor': 13, ' ee': 14, 'der': 15, ' en': 16, 'ij ': 17, 'aar': 18, 'gen': 19, 'te ': 20, 'ver': 21, ' in': 22, ' me': 23, 'aan': 24, 'den': 25, ' we': 26, 'at ': 27, 'in ': 28, ' ... |
# -*- coding: utf-8 -*-
"""Workspace/project-oriented tmux/git personal assistant.
Working on multiple git repositories and juggling tmux sessions can be tedious.
`mx` tries to help with that.
"""
__package__ = 'mx'
__license__ = 'MIT'
__version__ = '0.2.17'
__author__ = __maintainer__ = 'Rafael Bodill'
__email__ = 'j... | """Workspace/project-oriented tmux/git personal assistant.
Working on multiple git repositories and juggling tmux sessions can be tedious.
`mx` tries to help with that.
"""
__package__ = 'mx'
__license__ = 'MIT'
__version__ = '0.2.17'
__author__ = __maintainer__ = 'Rafael Bodill'
__email__ = 'justrafi@gmail' |
"""syphon.tests.build_.__init__.py
Copyright (c) 2017-2018 Keithley Instruments, LLC.
Licensed under MIT (https://github.com/ehall/syphon/blob/master/LICENSE)
"""
| """syphon.tests.build_.__init__.py
Copyright (c) 2017-2018 Keithley Instruments, LLC.
Licensed under MIT (https://github.com/ehall/syphon/blob/master/LICENSE)
""" |
class BaseError(Exception):
pass
class CredentialRequired(BaseError):
pass
class UnexpectedError(BaseError):
pass
class Forbidden (BaseError):
pass
class Not_Found (BaseError):
pass
class Payment_Required (BaseError):
pass
class Internal_Server_Error (BaseError):
pass
class Service_Un... | class Baseerror(Exception):
pass
class Credentialrequired(BaseError):
pass
class Unexpectederror(BaseError):
pass
class Forbidden(BaseError):
pass
class Not_Found(BaseError):
pass
class Payment_Required(BaseError):
pass
class Internal_Server_Error(BaseError):
pass
class Service_Unavai... |
def formula():
a=int(input("Enter a "))
b=int(input("Enter b "))
print((for1(a,b))*(for1(a,b)))
print(for1(a,b))
def for1(a,b):
return(a+b)
formula()
| def formula():
a = int(input('Enter a '))
b = int(input('Enter b '))
print(for1(a, b) * for1(a, b))
print(for1(a, b))
def for1(a, b):
return a + b
formula() |
input = """turn off 660,55 through 986,197
turn off 341,304 through 638,850
turn off 199,133 through 461,193
toggle 322,558 through 977,958
toggle 537,781 through 687,941
turn on 226,196 through 599,390
turn on 240,129 through 703,297
turn on 317,329 through 451,798
turn on 957,736 through 977,890
turn on 263,530 throu... | input = 'turn off 660,55 through 986,197\nturn off 341,304 through 638,850\nturn off 199,133 through 461,193\ntoggle 322,558 through 977,958\ntoggle 537,781 through 687,941\nturn on 226,196 through 599,390\nturn on 240,129 through 703,297\nturn on 317,329 through 451,798\nturn on 957,736 through 977,890\nturn on 263,53... |
"""
util.py
Utility functions for testing SONiC CLI
"""
def parse_colon_speparated_lines(lines):
"""
@summary: Helper function for parsing lines which consist of key-value pairs
formatted like "<key>: <value>", where the colon can be surrounded
by 0 or more whitespace characters
... | """
util.py
Utility functions for testing SONiC CLI
"""
def parse_colon_speparated_lines(lines):
"""
@summary: Helper function for parsing lines which consist of key-value pairs
formatted like "<key>: <value>", where the colon can be surrounded
by 0 or more whitespace characters
... |
class Solution(object):
def insert(self, intervals, working):
r = []
s = working[0]
e = working[1]
for pair in intervals:
print(r,s,e,pair)
print()
cs = pair[0]
ce = pair[1]
if ce < s:
r.append(pair)
... | class Solution(object):
def insert(self, intervals, working):
r = []
s = working[0]
e = working[1]
for pair in intervals:
print(r, s, e, pair)
print()
cs = pair[0]
ce = pair[1]
if ce < s:
r.append(pair)
... |
#!/bin/zsh
def isphonenumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-... | def isphonenumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
r... |
class BiggestRectangleEasy:
def findArea(self, N):
m, n = 0, N/2
for i in xrange(n+1):
m = max(m, i*(n-i))
return m
| class Biggestrectangleeasy:
def find_area(self, N):
(m, n) = (0, N / 2)
for i in xrange(n + 1):
m = max(m, i * (n - i))
return m |
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
l = []
for i in range(1<<len(nums)):
subset = []
for j in range(len(nums)):
if i & (1<<j):
subset.append(nums[j])
l.append(subset)
return l | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
l = []
for i in range(1 << len(nums)):
subset = []
for j in range(len(nums)):
if i & 1 << j:
subset.append(nums[j])
l.append(subset)
return l |
# VEX Variables
class VEXVariable:
__slots__ = tuple()
def __hash__(self):
raise NotImplementedError()
def __eq__(self, other):
raise NotImplementedError()
class VEXMemVar:
__slots__ = ('addr', 'size', )
def __init__(self, addr, size):
self.addr = addr
self.s... | class Vexvariable:
__slots__ = tuple()
def __hash__(self):
raise not_implemented_error()
def __eq__(self, other):
raise not_implemented_error()
class Vexmemvar:
__slots__ = ('addr', 'size')
def __init__(self, addr, size):
self.addr = addr
self.size = size
def... |
'''
A script that replaces commas with tabs in a file
'''
in_filename = input("Please input the file name:")
out_filename = "out_"+in_filename
with open(in_filename,"r") as fin:
with open(out_filename,"w+") as fout:
for line in fin:
fout.write(line.replace(',','\t'))
print("Output File:",out_... | """
A script that replaces commas with tabs in a file
"""
in_filename = input('Please input the file name:')
out_filename = 'out_' + in_filename
with open(in_filename, 'r') as fin:
with open(out_filename, 'w+') as fout:
for line in fin:
fout.write(line.replace(',', '\t'))
print('Output File:', o... |
def member_format(m):
return """ <tr> <td width="15%%"> <img src="../assets/%s"> </td>
<td> <span id="bioname"> <b> %s </b> </span> <br>
%s
<p> %s </p>
</td>
</tr>"""%(m['image'],m['name'],m['position'],m['description'])
members=[ {"name":"Lucas Wagner","position":"Group Leader","image":"lucas.png",
"desc... | def member_format(m):
return ' <tr> <td width="15%%"> <img src="../assets/%s"> </td>\n<td> <span id="bioname"> <b> %s </b> </span> <br>\n%s\n<p> %s </p>\n</td>\n</tr>' % (m['image'], m['name'], m['position'], m['description'])
members = [{'name': 'Lucas Wagner', 'position': 'Group Leader', 'image': 'lucas.png', 'd... |
class Command:
def __init__(self):
self.id
self.commandName
self.commandEmbbeding
self.event
| class Command:
def __init__(self):
self.id
self.commandName
self.commandEmbbeding
self.event |
def get_input() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt") as f:
return [l[:-1] for l in f.readlines()]
def parse_input(lines: list) -> list:
instructions = []
for line in lines:
split = line.split(" ")
instructions.append([split[0], int(split[1])])
return ins... | def get_input() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt") as f:
return [l[:-1] for l in f.readlines()]
def parse_input(lines: list) -> list:
instructions = []
for line in lines:
split = line.split(' ')
instructions.append([split[0], int(split[1])])
return inst... |
"""Lib macros."""
# the cell format intentionally uses a deprecated cell format
# @lint-ignore SKYLINT
load(
"cell//:lib2.bzl",
_foo = "foo",
)
foo = _foo
| """Lib macros."""
load('cell//:lib2.bzl', _foo='foo')
foo = _foo |
# -*- coding: utf-8 -*-
"""Domain Driven Design framework - Event."""
class Event:
pass
| """Domain Driven Design framework - Event."""
class Event:
pass |
with open("files_question4.txt")as main_file:
with open("Delhi.txt","w")as file1:
with open("Shimla.txt","w") as file2:
with open("other.txt","w") as file3:
for i in main_file:
if "delhi" in i:
file1.write(i)
elif "Shimla" in i:
file2.write(i)
else:
file3.write(i)
main_file.cl... | with open('files_question4.txt') as main_file:
with open('Delhi.txt', 'w') as file1:
with open('Shimla.txt', 'w') as file2:
with open('other.txt', 'w') as file3:
for i in main_file:
if 'delhi' in i:
file1.write(i)
el... |
def create_new_employee_department():
employee_department = []
emp = ' '
while emp != ' ':
emp_department_input = input('Enter employee last name \n')
employee_department.append(emp_department_input)
return employee_department
| def create_new_employee_department():
employee_department = []
emp = ' '
while emp != ' ':
emp_department_input = input('Enter employee last name \n')
employee_department.append(emp_department_input)
return employee_department |
# TRANSCRIBE TO MRNA EDABIT SOLUTION:
# creating a function to solve the problem.
def dna_to_rna(dna):
# returning the DNA strand with modifications to make it an RNA strand.
return(dna.replace("A", "U")
.replace("T", "A")
.replace("G", "C")
.replace("C", "G")) | def dna_to_rna(dna):
return dna.replace('A', 'U').replace('T', 'A').replace('G', 'C').replace('C', 'G') |
class ConfigurationError(Exception):
"""
This exception should be thrown if configuration errors happen
"""
class SerializerError(Exception):
"""
This exception should be thrown if serializer errors happen
"""
class AuthenticationError(Exception):
"""
This exception should be thrown ... | class Configurationerror(Exception):
"""
This exception should be thrown if configuration errors happen
"""
class Serializererror(Exception):
"""
This exception should be thrown if serializer errors happen
"""
class Authenticationerror(Exception):
"""
This exception should be thrown if... |
class Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
try:
return x / y
except ZeroDivisionError:
print('Invalid operation. Division by 0... | class Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
try:
return x / y
except ZeroDivisionError:
print('Invalid operation. Division by ... |
# Merge Two Binary Trees
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1 and not t2:
return None
result = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)... | class Solution(object):
def merge_trees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1 and (not t2):
return None
result = tree_node((t1.val if t1 else 0) + (t2.val if t2 else 0))
result.left = self.... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"func": "MLE_01_serving.ipynb",
"Class": "MLE_01_serving.ipynb"}
modules = ["de__extract.py",
"de__transform.py",
"de__load.py",
"ds__load.py",
"ds__prepr... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'func': 'MLE_01_serving.ipynb', 'Class': 'MLE_01_serving.ipynb'}
modules = ['de__extract.py', 'de__transform.py', 'de__load.py', 'ds__load.py', 'ds__preprocess.py', 'ds__build_features.py', 'ds__modelling.py', 'ds__validate.py', 'ds__postprocess.py'... |
def bisection(f, x0, x1, error=1e-15):
if f(x0) * f(x1) > 0:
print("No root found.")
else:
while True:
mid = 0.5 * (x0 + x1)
if abs(f(mid)) < error:
return mid
elif f(x0) * f(mid) > 0:
x0 = mid
else:
... | def bisection(f, x0, x1, error=1e-15):
if f(x0) * f(x1) > 0:
print('No root found.')
else:
while True:
mid = 0.5 * (x0 + x1)
if abs(f(mid)) < error:
return mid
elif f(x0) * f(mid) > 0:
x0 = mid
else:
... |
# Longest Substring Without Repeating Characters
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
window = set()
# pointer of sliding window, if find the char in window, then need to move pointer to right to remove all chars until remove this char
left =... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
window = set()
left = 0
max_len = 0
cur_len = 0
for ch in s:
while ch in window:
window.remove(s[left])
left += 1
cur_len -= 1
window... |
"""Constants."""
MAX_CONCURRENCY = 30
MAX_RETRY_ATTEMPTS = 5
DEFAULT_URL = "https://api.redbrickai.com"
ORG_API_HAS_CHANGED = (
"this api has changed recently, try running help(redbrick.get_org)"
+ " or visiting https://redbrick-sdk.readthedocs.io/en/stable/#redbrick.get_org"
)
PROJECT_API_HAS_CHANGED = (
... | """Constants."""
max_concurrency = 30
max_retry_attempts = 5
default_url = 'https://api.redbrickai.com'
org_api_has_changed = 'this api has changed recently, try running help(redbrick.get_org)' + ' or visiting https://redbrick-sdk.readthedocs.io/en/stable/#redbrick.get_org'
project_api_has_changed = 'this api has chang... |
{
"targets": [
{
# OpenSSL has a lot of config options, with some default options
# enabling known insecure algorithms. What's a good combinations
# of openssl config options?
# ./config no-asm no-shared no-ssl2 no-ssl3 no-hw no-zlib no-threads
#... | {'targets': [{'target_name': 'openssl', 'type': 'static_library', 'sources': ['1.0.1m/openssl-1.0.1m/crypto/aes/aes_cbc.c', '1.0.1m/openssl-1.0.1m/crypto/aes/aes_cfb.c', '1.0.1m/openssl-1.0.1m/crypto/aes/aes_core.c', '1.0.1m/openssl-1.0.1m/crypto/aes/aes_ctr.c', '1.0.1m/openssl-1.0.1m/crypto/aes/aes_ecb.c', '1.0.1m/ope... |
class PGSSException(Exception):
"""Base exception class"""
class PGSSInvalidOperation(PGSSException):
"""Invalid operation"""
class PGSSLookupError(PGSSException):
"""Invalid GoGraph lookup (ex. missing node or edge)"""
| class Pgssexception(Exception):
"""Base exception class"""
class Pgssinvalidoperation(PGSSException):
"""Invalid operation"""
class Pgsslookuperror(PGSSException):
"""Invalid GoGraph lookup (ex. missing node or edge)""" |
# Copyright 2018 Inria Damien.Saucez@inria.fr
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUT... | k = 4
login = 'login'
password = 'password'
subnet = '10.0.0.0/8'
location = 'nancy'
walltime = '1:00'
images = {'ovs': 'file:///home/dsaucez/distem-fs-jessie-ovs.tar.gz', 'hadoop-slave': 'file:///home/dsaucez/slave.tgz', 'hadoop-master': 'file:///home/dsaucez/master.tgz'}
masters = list()
slaves = list()
k2 = int(k / ... |
class FixedWidthRecord(object):
fields = ()
LEFT = 'ljust'
RIGHT = 'rjust'
encoding = 'utf-8'
lineterminator = '\r\n'
def __init__(self):
self.data = {}
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, key):
return self.data[key... | class Fixedwidthrecord(object):
fields = ()
left = 'ljust'
right = 'rjust'
encoding = 'utf-8'
lineterminator = '\r\n'
def __init__(self):
self.data = {}
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, key):
return self.data[key]
... |
month = input()
nights = int(input())
total_price_apartment = 0
total_price_studio = 0
discount_studio = 0
discount_apartment = 0
if month == 'May' or month == 'October':
total_price_studio = nights * 50
total_price_apartment = nights * 65
if nights > 14:
discount_studio = 0.30
... | month = input()
nights = int(input())
total_price_apartment = 0
total_price_studio = 0
discount_studio = 0
discount_apartment = 0
if month == 'May' or month == 'October':
total_price_studio = nights * 50
total_price_apartment = nights * 65
if nights > 14:
discount_studio = 0.3
elif nights > 7:
... |
price_history_2015="$413,268 $371,473 $336,311 $239,010 $227,809 $398,996 $403,729 $353,405 $220,980 $203,186 $459,297 $461,085 $1,078,036 $551,382 $503,344 $364,826 $399,342 $430,636 $644,972 $554,170 $275,601 $849,539 $396,181 $410,221 $381,013 $272,015 $457,796 $472,744 $229,586 $217,508 $287,573 $284,288 $266,932 $... | price_history_2015 = '$413,268 $371,473 $336,311 $239,010 $227,809 $398,996 $403,729 $353,405 $220,980 $203,186 $459,297 $461,085 $1,078,036 $551,382 $503,344 $364,826 $399,342 $430,636 $644,972 $554,170 $275,601 $849,539 $396,181 $410,221 $381,013 $272,015 $457,796 $472,744 $229,586 $217,508 $287,573 $284,288 $266,932... |
def main():
n = int(input())
a = list(map(int, input().split()))
minValue = 10 ** 9
maxValue = - (10 ** 9)
for i in range(n):
if a[i] > maxValue:
maxValue = a[i]
if a[i] < minValue:
minValue = a[i]
print(maxValue - minValue)
if __name__=="__mai... | def main():
n = int(input())
a = list(map(int, input().split()))
min_value = 10 ** 9
max_value = -10 ** 9
for i in range(n):
if a[i] > maxValue:
max_value = a[i]
if a[i] < minValue:
min_value = a[i]
print(maxValue - minValue)
if __name__ == '__main__':
... |
"""
URL: https://codeforces.com/problemset/problem/136/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
n = int(input())
inp = list(map(int, input().split()))
outp = [0] * n
for i in range(n):
outp[inp[i] - 1] = i + 1
print(' '.join(map(str, outp)))
| """
URL: https://codeforces.com/problemset/problem/136/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
n = int(input())
inp = list(map(int, input().split()))
outp = [0] * n
for i in range(n):
outp[inp[i] - 1] = i + 1
print(' '.join(map(str, outp))) |
# WEIGHING THE STONES
for _ in range(int(input())):
N = int(input())
DictR = {}
DictA = {}
Rupam = [int(a) for a in input().split()]
Ankit = [int(a) for a in input().split()]
for i in range(N):
DictR[Rupam[i]] = Rupam.count(Rupam[i])
DictA[Ankit[i]] = Ankit.count(Ankit[i])
#... | for _ in range(int(input())):
n = int(input())
dict_r = {}
dict_a = {}
rupam = [int(a) for a in input().split()]
ankit = [int(a) for a in input().split()]
for i in range(N):
DictR[Rupam[i]] = Rupam.count(Rupam[i])
DictA[Ankit[i]] = Ankit.count(Ankit[i])
maxr = r = 0
maxa ... |
def formatacao_real(numero: float) -> str:
return f"R${numero:,.2f}"
| def formatacao_real(numero: float) -> str:
return f'R${numero:,.2f}' |
class NullMailerErrorPool(Exception):
pass
class NullMailerErrorPipe(Exception):
pass
class NullMailerErrorQueue(Exception):
pass
class RabbitMQError(Exception):
pass
| class Nullmailererrorpool(Exception):
pass
class Nullmailererrorpipe(Exception):
pass
class Nullmailererrorqueue(Exception):
pass
class Rabbitmqerror(Exception):
pass |
class State:
def __init__(self, charge, time_of_day, day_of_year, rounds_remaining, cost):
self.battery = Battery(charge)
self.time_of_day = time_of_day
self.day_of_year = day_of_year
self.rounds_remaining = rounds_remaining
self.cost = cost
class Battery:
def __init__(s... | class State:
def __init__(self, charge, time_of_day, day_of_year, rounds_remaining, cost):
self.battery = battery(charge)
self.time_of_day = time_of_day
self.day_of_year = day_of_year
self.rounds_remaining = rounds_remaining
self.cost = cost
class Battery:
def __init__... |
def encontra_impares(lista):
x = []
if len(lista) > 0:
n = lista.pop(0)
if n % 2 != 0:
x.append(n)
x = x + encontra_impares(lista)
return x
if __name__=='__main__':
print (encontra_impares([1,2,3,4,5,5]))
| def encontra_impares(lista):
x = []
if len(lista) > 0:
n = lista.pop(0)
if n % 2 != 0:
x.append(n)
x = x + encontra_impares(lista)
return x
if __name__ == '__main__':
print(encontra_impares([1, 2, 3, 4, 5, 5])) |
"""1. Two Sum
Given an array of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
re... | """1. Two Sum
Given an array of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.