content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
s: str = ""
se: str = ""
l: [int] = None
le: int = 0
k: bool = False
def f():
1+"2"
for k in l:
1+"2"
for g in l:
1+"2"
for f in l:
1+"2"
for se in l:
1+"2"
for l in s:
1+"2"
for f in k:
1+"2"
| s: str = ''
se: str = ''
l: [int] = None
le: int = 0
k: bool = False
def f():
1 + '2'
for k in l:
1 + '2'
for g in l:
1 + '2'
for f in l:
1 + '2'
for se in l:
1 + '2'
for l in s:
1 + '2'
for f in k:
1 + '2' |
# coding=utf8
SthWrong = (-1, 'Something Wrong')
ArgMis = (-1000, 'Args Missing')
ArgFormatInvalid = (-1001, 'Args Format Invalid')
DataNotExists = (-2000, 'Data Not Exists') | sth_wrong = (-1, 'Something Wrong')
arg_mis = (-1000, 'Args Missing')
arg_format_invalid = (-1001, 'Args Format Invalid')
data_not_exists = (-2000, 'Data Not Exists') |
# Directory and File locations
DATASETDIR = "driving_dataset/"
MODELDIR = "save"
MODELFILE = MODELDIR + "/model.ckpt"
LOGDIR = "logs"
| datasetdir = 'driving_dataset/'
modeldir = 'save'
modelfile = MODELDIR + '/model.ckpt'
logdir = 'logs' |
"""!
@brief Cloud Tool for Yandex Disk service.
@details The tool has been implemented to support CI infrastructure of pyclustering library.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
| """!
@brief Cloud Tool for Yandex Disk service.
@details The tool has been implemented to support CI infrastructure of pyclustering library.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
""" |
side1 = 12
side2 = 14
side3 = 124
if side1 == side2 and side2 == side3:
print(1)
elif side1 == side2 or side2 == side3 or side1 == side3:
print(2)
else:
print(3)
| side1 = 12
side2 = 14
side3 = 124
if side1 == side2 and side2 == side3:
print(1)
elif side1 == side2 or side2 == side3 or side1 == side3:
print(2)
else:
print(3) |
class RPCError(Exception):
pass
class ConsistencyError(Exception):
pass
class TermConsistencyError(ConsistencyError):
def __init__(self, term: int):
self.term = term
class LeaderConsistencyError(ConsistencyError):
def __init__(self, leader_id: bytes):
self.leader_id = leader_id
c... | class Rpcerror(Exception):
pass
class Consistencyerror(Exception):
pass
class Termconsistencyerror(ConsistencyError):
def __init__(self, term: int):
self.term = term
class Leaderconsistencyerror(ConsistencyError):
def __init__(self, leader_id: bytes):
self.leader_id = leader_id
cla... |
#Card class to be imported by every program in repository
#Ace value initialized to 11, can be changed to 1 in-game
class Card:
def __init__(self, suit_id, rank_id):
self.suit_id = suit_id
self.rank_id = rank_id
if self.rank_id == 1:
self.rank = "Ace"
self.value = 1... | class Card:
def __init__(self, suit_id, rank_id):
self.suit_id = suit_id
self.rank_id = rank_id
if self.rank_id == 1:
self.rank = 'Ace'
self.value = 11
elif self.rank_id == 11:
self.rank = 'Jack'
self.value = 10
elif self.rank_... |
# find the maximum path sum. The path may start and end at any node in the tree.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def max_sum_path(root):
max_sum_path_util.res = -float('inf')
max_sum_path_util(root)
return max_sum_pat... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def max_sum_path(root):
max_sum_path_util.res = -float('inf')
max_sum_path_util(root)
return max_sum_path_util.res
def max_sum_path_util(root):
if root is None:
return 0
l... |
def buildGraphFromInput():
n = int(input())
graph = []
for i in range(n):
x, y = [int(j) for j in input().split()]
graph.append((x,y))
return graph
def computeNumberOfNeighbors(graph):
numberOfNeighbors = {}
for x,y in graph:
if not x in numberOfNeighbors:
... | def build_graph_from_input():
n = int(input())
graph = []
for i in range(n):
(x, y) = [int(j) for j in input().split()]
graph.append((x, y))
return graph
def compute_number_of_neighbors(graph):
number_of_neighbors = {}
for (x, y) in graph:
if not x in numberOfNeighbors:
... |
MES_LEVEL_INFO = 0
MES_LEVEL_WARN = 1
MES_LEVEL_ERROR = 2
_level = 0
_message = ""
def set_mes(level, message):
global _level
global _message
if message != "":
_level = level
_message = message
def get_mes():
... | mes_level_info = 0
mes_level_warn = 1
mes_level_error = 2
_level = 0
_message = ''
def set_mes(level, message):
global _level
global _message
if message != '':
_level = level
_message = message
def get_mes():
return (_level, _message) |
#
# PySNMP MIB module IBM-INTERFACE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IBM-INTERFACE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:51:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection, constraints_union) ... |
name = "btclib"
__version__ = "2020.12"
__author__ = "The btclib developers"
__author_email__ = "devs@btclib.org"
__copyright__ = "Copyright (C) 2017-2020 The btclib developers"
__license__ = "MIT License"
| name = 'btclib'
__version__ = '2020.12'
__author__ = 'The btclib developers'
__author_email__ = 'devs@btclib.org'
__copyright__ = 'Copyright (C) 2017-2020 The btclib developers'
__license__ = 'MIT License' |
class Sentinel(object):
"""Unique placeholders for signals"""
def __init__(self, name=None):
self.name = name
def __eq__(self, other):
return other is self
def __hash__(self):
return id(self)
def __str__(self):
if self.name is not None:
return str(self.... | class Sentinel(object):
"""Unique placeholders for signals"""
def __init__(self, name=None):
self.name = name
def __eq__(self, other):
return other is self
def __hash__(self):
return id(self)
def __str__(self):
if self.name is not None:
return str(self... |
#
# PySNMP MIB module RARITANCCv2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RARITANCCv2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:43:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
age=input("How old are you? 38")
height=input("How tall are you? `120")
weight=input("How much do you weight? 129")
print(f"So, you're {age} old, {height} tall, and {weight} heavy.")
| age = input('How old are you? 38')
height = input('How tall are you? `120')
weight = input('How much do you weight? 129')
print(f"So, you're {age} old, {height} tall, and {weight} heavy.") |
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Copyright: [CUP] - See LICENSE for details.
# Authors: liushuxian(liushuxian)
"""
This module provides utils of jenkins.
"""
STATUS_FAIL = "FAIL"
STATUS_ERROR = "ERROR"
STATUS_ABORTED = "ABORTED"
STATUS_REGRESSION = "REGRESSION"
STATUS_SUCCESS = "SUCCESS"
STATUS_FIXED = ... | """
This module provides utils of jenkins.
"""
status_fail = 'FAIL'
status_error = 'ERROR'
status_aborted = 'ABORTED'
status_regression = 'REGRESSION'
status_success = 'SUCCESS'
status_fixed = 'FIXED'
status_passed = 'PASSED'
result_failure = 'FAILURE'
result_failed = 'FAILED'
result_skipped = 'SKIPPED' |
# Homeserver address
homeserver = "https://phuks.co"
# Homeserver credentials. Not required if using a .token file
username = "jenny"
password = "nice&secure"
# Display name
nick = "Jenny"
# Prefix for commands
prefix = '.'
# List of admins using full matrix usernames
admins = ['@polsaker:phuks.co']
# If this lis... | homeserver = 'https://phuks.co'
username = 'jenny'
password = 'nice&secure'
nick = 'Jenny'
prefix = '.'
admins = ['@polsaker:phuks.co']
whitelistonly_modules = []
disabled_modules = ['steam', 'phuks']
wolframalpha_apikey = '123456-7894561234'
google_apikey = 'PutItInHere'
darksky_apikey = 'GibMeTheWeather'
cleverbot_ap... |
# table definition
table = {
'table_name' : 'db_view_cols',
'module_id' : 'db',
'short_descr' : 'Db view columns',
'long_descr' : 'Database view column definitions',
'sub_types' : None,
'sub_trans' : None,
'sequence' : ['seq', ['view_id', 'col_type'], None],
'tre... | table = {'table_name': 'db_view_cols', 'module_id': 'db', 'short_descr': 'Db view columns', 'long_descr': 'Database view column definitions', 'sub_types': None, 'sub_trans': None, 'sequence': ['seq', ['view_id', 'col_type'], None], 'tree_params': None, 'roll_params': None, 'indexes': None, 'ledger_col': None, 'defn_com... |
f = open('input.txt', 'r')
values = []
for line in f:
values.append(int(line))
counter = 0
# Part 1:
for x in range(len(values)-1):
if values[x+1] > values[x]:
counter += 1
print(f"part 1: {counter}")
# Part 2:
counter = 0
for x in range(2, len(values)-1):
lsum = sum([values[i] for i in range... | f = open('input.txt', 'r')
values = []
for line in f:
values.append(int(line))
counter = 0
for x in range(len(values) - 1):
if values[x + 1] > values[x]:
counter += 1
print(f'part 1: {counter}')
counter = 0
for x in range(2, len(values) - 1):
lsum = sum([values[i] for i in range(x - 2, x + 1)])
... |
#
# PySNMP MIB module ENTERASYS-MGMT-AUTH-NOTIFICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-MGMT-AUTH-NOTIFICATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:49:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# U... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
"""
This module contains the result sentences and intents for the English version
of the Supervisor app.
"""
# Result sentences
RESULT_BACK = "Hi, I'm back!"
RESULT_CONFIRM_REBOOT = "Do you really want to reboot the system?"
RESULT_CONFIRM_SHUTDOWN = "Do you really want to shutdown the system?"
RESULT_DISABLE_APP = "O... | """
This module contains the result sentences and intents for the English version
of the Supervisor app.
"""
result_back = "Hi, I'm back!"
result_confirm_reboot = 'Do you really want to reboot the system?'
result_confirm_shutdown = 'Do you really want to shutdown the system?'
result_disable_app = "OK, I'll disable the ... |
class Solution(object):
def fizzBuzz(self, n):
# Scaleable hash
dict = {3:"Fizz", 5:"Buzz"}
res = []
# Iterate through 1-n+1
for i in range(1, n+1):
# app represents what to append of not the number
app = ""
# iterate throug... | class Solution(object):
def fizz_buzz(self, n):
dict = {3: 'Fizz', 5: 'Buzz'}
res = []
for i in range(1, n + 1):
app = ''
for j in [3, 5]:
if not i % j:
app += dict[j]
if app != '':
res.append(app)
... |
# MAJOR_VER = 20
# MINOR_VER = 11
# REVISION_VER = 0
# CONTROL_VER = 6
# OFFICIAL = False
# MAJOR_VER = 20
# MINOR_VER = 12
# REVISION_VER = 5
# CONTROL_VER = 6
# OFFICIAL = True
MAJOR_VER = 21
MINOR_VER = 6
REVISION_VER = 0
CONTROL_VER = 6
OFFICIAL = False
| major_ver = 21
minor_ver = 6
revision_ver = 0
control_ver = 6
official = False |
#https://www.hackerrank.com/challenges/array-left-rotation
length, rotations = map(int, input().strip().split())
array = list(map(int, input().strip().split()))
displacement = rotations % length
lower = []
for i in range(displacement, length):
lower.append(array[i])
upper = []
for i in range(displacement):
... | (length, rotations) = map(int, input().strip().split())
array = list(map(int, input().strip().split()))
displacement = rotations % length
lower = []
for i in range(displacement, length):
lower.append(array[i])
upper = []
for i in range(displacement):
upper.append(array[i])
array = lower + upper
print(' '.join(m... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
curr = head
stack = []
while curr:
... | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
curr = head
stack = []
while curr:
... |
DWI_ENTITIES = dict(suffix="dwi", extension=".nii.gz")
TENSOR_DERIVED_ENTITIES = dict(suffix="dwiref", resolution="dwi")
TENSOR_DERIVED_METRICS = dict(
diffusion_tensor=[
"fa",
"ga",
"rgb",
"md",
"ad",
"rd",
"mode",
"evec",
"eval",
"t... | dwi_entities = dict(suffix='dwi', extension='.nii.gz')
tensor_derived_entities = dict(suffix='dwiref', resolution='dwi')
tensor_derived_metrics = dict(diffusion_tensor=['fa', 'ga', 'rgb', 'md', 'ad', 'rd', 'mode', 'evec', 'eval', 'tensor'], restore_tensor=['fa', 'ga', 'rgb', 'md', 'ad', 'rd', 'mode', 'evec', 'eval', 't... |
#!/usr/bin/env python3
t = sorted([float(x) for x in input().split()])
o = float(input())
best = (t[0] + t[1] + t[2])/3
worst = (t[1] + t[2] + t[3])/3
if o < best: print('impossible')
elif o >= worst: print('infinite')
else: print(f'{3*o-t[1]-t[2]:.2f}')
| t = sorted([float(x) for x in input().split()])
o = float(input())
best = (t[0] + t[1] + t[2]) / 3
worst = (t[1] + t[2] + t[3]) / 3
if o < best:
print('impossible')
elif o >= worst:
print('infinite')
else:
print(f'{3 * o - t[1] - t[2]:.2f}') |
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_test")
def gen_tests(srcs):
for src in srcs:
name = src.replace("s/","_").replace(".ts","")
nodejs_test(name=name, entry_point = src, data=[":tsc","@npm//big-integer"]) | load('@build_bazel_rules_nodejs//:index.bzl', 'nodejs_test')
def gen_tests(srcs):
for src in srcs:
name = src.replace('s/', '_').replace('.ts', '')
nodejs_test(name=name, entry_point=src, data=[':tsc', '@npm//big-integer']) |
# https://www.codementor.io/moyosore/a-dive-into-python-closures-and-decorators-part-2-ab2enoyjg
def hello(f):
print(f"{f} in @hello")
def f_wrapper(name):
print("in wrapper of @hello")
print(f"name:{name}, f(name):{f(name)}")
return f"Hello {f(name)}"
return f_wrapper
def uppe... | def hello(f):
print(f'{f} in @hello')
def f_wrapper(name):
print('in wrapper of @hello')
print(f'name:{name}, f(name):{f(name)}')
return f'Hello {f(name)}'
return f_wrapper
def uppercase(f):
print(f'{f} in @uppercase')
def f_wrapper(name):
print('in wrapper of @upp... |
'''
Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic function of the form f(x) = ax2 + bx + c to each element x in the array.
The returned array must be in sorted order.
Expected time complexity: O(n)
Example:
nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5,
Result: [3, 9, 15, 33]... | """
Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic function of the form f(x) = ax2 + bx + c to each element x in the array.
The returned array must be in sorted order.
Expected time complexity: O(n)
Example:
nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5,
Result: [3, 9, 15, 33]... |
class Generator(object):
def __init__(self, number, factor):
self.number = number
self.factor = factor
def next(self):
self.number = (self.number * self.factor) % 2147483647
return self.number
class Judge(object):
def __init__(self):
self.A = Generator(512, 16807)
... | class Generator(object):
def __init__(self, number, factor):
self.number = number
self.factor = factor
def next(self):
self.number = self.number * self.factor % 2147483647
return self.number
class Judge(object):
def __init__(self):
self.A = generator(512, 16807)
... |
class primary_key(object):
"""A decorator to assign the primary key to a Model class"""
def __init__(self, partition_key, sort_key=None):
"""constructor for the primary_key decorator
Arguments:
partition_key -- a string of the tables partition_key
sort_key -- optional string of... | class Primary_Key(object):
"""A decorator to assign the primary key to a Model class"""
def __init__(self, partition_key, sort_key=None):
"""constructor for the primary_key decorator
Arguments:
partition_key -- a string of the tables partition_key
sort_key -- optional string of... |
fig, ax = plt.subplots()
im = ax.pcolor(grouped_pivot, cmap='RdBu')
#label names
row_labels = grouped_pivot.columns.levels[1]
col_labels = grouped_pivot.index
#move ticks and labels to the center
ax.set_xticks(np.arange(grouped_pivot.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(grouped_pivot.shape[0]) + 0.5,... | (fig, ax) = plt.subplots()
im = ax.pcolor(grouped_pivot, cmap='RdBu')
row_labels = grouped_pivot.columns.levels[1]
col_labels = grouped_pivot.index
ax.set_xticks(np.arange(grouped_pivot.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(grouped_pivot.shape[0]) + 0.5, minor=False)
ax.set_xticklabels(row_labels, minor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : ZhaoYY
#pylint: disable=invalid-name
'''
problems about int.
'''
class IntProblem:
'''
int problems
'''
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x > 0 and x % 10 == 0:
... | """
problems about int.
"""
class Intproblem:
"""
int problems
"""
def is_palindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x > 0 and x % 10 == 0:
return False
t = 0
z = x
while x > 0:
t = t * 10 + x % 10
... |
#!/usr/bin/env python3
"""
Learn Python 3 the hard way exercise 1
"""
| """
Learn Python 3 the hard way exercise 1
""" |
def sayhello(name):
return "Hello, " + name + ", nice to meet you!"
if __name__ == "__main__":
print(sayhello(input("What is your name? ")))
| def sayhello(name):
return 'Hello, ' + name + ', nice to meet you!'
if __name__ == '__main__':
print(sayhello(input('What is your name? '))) |
# using cube coordinates: https://www.redblobgames.com/grids/hexagons/
def update(tile, command):
x, y, z = tile
if command == 'w':
x -= 1
y += 1
elif command == 'e':
x += 1
y -= 1
elif command == 'nw':
y += 1
z -= 1
elif command == 'se':
y -= ... | def update(tile, command):
(x, y, z) = tile
if command == 'w':
x -= 1
y += 1
elif command == 'e':
x += 1
y -= 1
elif command == 'nw':
y += 1
z -= 1
elif command == 'se':
y -= 1
z += 1
elif command == 'ne':
x += 1
z -... |
# Demo Python For Loops - The range() Function
'''
The range() Function - Part 2
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
'''
# Using the start parameter:
for ... | """
The range() Function - Part 2
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
"""
for x in range(2, 7):
print(x) |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | def create__thrift_unicode_decode_error_from__unicode_decode_error(error, field_name):
if isinstance(error, ThriftUnicodeDecodeError):
error.field_names.append(field_name)
return error
return thrift_unicode_decode_error(error.encoding, error.object, error.start, error.end, error.reason, field_na... |
class Enactor:
def __init__(self, dev_info, sftp_location, sftp_port, sftp_username, sftp_password, sftp_key_location,
sftp_directory):
pass
def stop(self):
pass
def enact_light_plan(self, dev, BL_Quota, NL_Quota):
return True
def enact_socket_plan(self, dev... | class Enactor:
def __init__(self, dev_info, sftp_location, sftp_port, sftp_username, sftp_password, sftp_key_location, sftp_directory):
pass
def stop(self):
pass
def enact_light_plan(self, dev, BL_Quota, NL_Quota):
return True
def enact_socket_plan(self, dev, AC_total):
... |
# noinspection PyUnusedLocal
# skus = unicode string
def getItems():
items = {
'A': 50,
'B': 30,
'C': 20,
'D': 15,
'E': 40,
'F': 10,
'G': 20,
'H': 10,
'I': 35,
'J': 60,
'K': 70,
'L': 90,
'M': 15,
'N': 40... | def get_items():
items = {'A': 50, 'B': 30, 'C': 20, 'D': 15, 'E': 40, 'F': 10, 'G': 20, 'H': 10, 'I': 35, 'J': 60, 'K': 70, 'L': 90, 'M': 15, 'N': 40, 'O': 10, 'P': 50, 'Q': 30, 'R': 50, 'S': 20, 'T': 20, 'U': 40, 'V': 50, 'W': 20, 'X': 17, 'Y': 20, 'Z': 21}
return items
def get_multi_items():
multi_items... |
class Solution:
def reverse(self, x: int):
flag = 0
minus = "-"
if x < 0:
flag = 1
x = x * -1
result= str(x)
result = ''.join(reversed(result))
x = int(result)
if flag == 1:
x = x * -1
if x > 2147... | class Solution:
def reverse(self, x: int):
flag = 0
minus = '-'
if x < 0:
flag = 1
x = x * -1
result = str(x)
result = ''.join(reversed(result))
x = int(result)
if flag == 1:
x = x * -1
if x > 2147483647 or x < -214... |
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
v1 = [int(x) for x in version1.split('.')]
v2 = [int(x) for x in version2.split('.')]
while v1 and v1[-1] == 0:
v1.pop()
while v2 and v2[-1] == 0:
v2.pop()
if v1 < v2:
... | class Solution:
def compare_version(self, version1: str, version2: str) -> int:
v1 = [int(x) for x in version1.split('.')]
v2 = [int(x) for x in version2.split('.')]
while v1 and v1[-1] == 0:
v1.pop()
while v2 and v2[-1] == 0:
v2.pop()
if v1 < v2:
... |
def star(N):
for i in range(0,N):
for j in range(0,i+1):
print("*",end = "")
print("\r")
if __name__ == '__main__':
N = int(input())
star(N)
| def star(N):
for i in range(0, N):
for j in range(0, i + 1):
print('*', end='')
print('\r')
if __name__ == '__main__':
n = int(input())
star(N) |
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return self.height(root) != -1
def height(self, root):
if not root:
return 0
lh = self.height(root.right)
if lh == -1:
return -1
rh = self.height(root.left)
if rh == -1:
... | class Solution:
def is_balanced(self, root: TreeNode) -> bool:
return self.height(root) != -1
def height(self, root):
if not root:
return 0
lh = self.height(root.right)
if lh == -1:
return -1
rh = self.height(root.left)
if rh == -1:
... |
"""Path sum: two ways
"""
matrix_height = 80
matrix_width = 80
def traverse(matrix, v, h, cur_score=0, max_path=[[False] * matrix_width for x in range(matrix_height)]):
max_path[matrix_height-1][matrix_width-1] = matrix[matrix_height-1][matrix_width-1]
min_score = float("inf")
if max_path[v][h]:
... | """Path sum: two ways
"""
matrix_height = 80
matrix_width = 80
def traverse(matrix, v, h, cur_score=0, max_path=[[False] * matrix_width for x in range(matrix_height)]):
max_path[matrix_height - 1][matrix_width - 1] = matrix[matrix_height - 1][matrix_width - 1]
min_score = float('inf')
if max_path[v][h]:
... |
class Metrics:
listMetric = {}
def addMetric(self, metric):
self.listMetric[metric.getName()] = metric.getData()
def getMetrics(self):
return self.listMetric | class Metrics:
list_metric = {}
def add_metric(self, metric):
self.listMetric[metric.getName()] = metric.getData()
def get_metrics(self):
return self.listMetric |
# coding: utf-8
class Maxipago(object):
def __init__(self, maxid, api_key, api_version='3.1.1.15', sandbox=False):
self.maxid = maxid
self.api_key = api_key
self.api_version = api_version
self.sandbox = sandbox
def __getattr__(self, name):
try:
class_name ... | class Maxipago(object):
def __init__(self, maxid, api_key, api_version='3.1.1.15', sandbox=False):
self.maxid = maxid
self.api_key = api_key
self.api_version = api_version
self.sandbox = sandbox
def __getattr__(self, name):
try:
class_name = ''.join([n.title... |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Defines different rounding options for binary search.'''
# todo: Confirm that `*_IF_BOTH` options are used are used in all places that
# currently ~use them.
class Rounding:
'''Base class for rounding options for binary sea... | """Defines different rounding options for binary search."""
class Rounding:
"""Base class for rounding options for binary search."""
class Both(Rounding):
"""
Get a tuple `(low, high)` of the 2 items that surround the specified value.
If there's an exact match, gives it twice in the tuple, i.e. `... |
expected_output = {
"interfaces": {
"GigabitEthernet1/0/1": {
"name": "foo bar",
"down_time": "00:00:00",
"up_time": "4d5h",
},
}
} | expected_output = {'interfaces': {'GigabitEthernet1/0/1': {'name': 'foo bar', 'down_time': '00:00:00', 'up_time': '4d5h'}}} |
data = [
[0, 'Does your animal fly?', 1, 2],
[1, 'Is your flying animal a bird?', 3, 4],
[2, 'Does your animal live underwater?', 7, 8],
[3, 'Is your bird native to Australia?', 5, 6],
[4, 'Is it a fruit bat?'],
[5, 'Is it a kookaburra?'],
[6, 'Is it a blue jay?'],
[7, 'Is your animal a ... | data = [[0, 'Does your animal fly?', 1, 2], [1, 'Is your flying animal a bird?', 3, 4], [2, 'Does your animal live underwater?', 7, 8], [3, 'Is your bird native to Australia?', 5, 6], [4, 'Is it a fruit bat?'], [5, 'Is it a kookaburra?'], [6, 'Is it a blue jay?'], [7, 'Is your animal a mammal?', 9, 10], [8, 'Is it a wo... |
def riverSizes(matrix):
# Write your code here.
if not matrix:
return []
sizes=[]
visited=[[False for values in row] for row in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if visited[i][j]:
continue
getSize(i,j,visited,matrix,sizes)
return sizes
def getSi... | def river_sizes(matrix):
if not matrix:
return []
sizes = []
visited = [[False for values in row] for row in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if visited[i][j]:
continue
get_size(i, j, visited, matrix, sizes)
... |
# G00364712 Robert Higgins - Exercise 2
# Collatz Conjecture https://en.wikipedia.org/wiki/Collatz_conjecture
nStr = input("Enter a positive integer:")
n = int(nStr)
while n > 1:
if n % 2 == 0:
n = n/2
print(int(n))
else:
n = (3*n) + 1
print(int(n))
# Output below for user inp... | n_str = input('Enter a positive integer:')
n = int(nStr)
while n > 1:
if n % 2 == 0:
n = n / 2
print(int(n))
else:
n = 3 * n + 1
print(int(n)) |
collatz_lengths = {}
def collatz_length(number: int) -> int:
"""Calculate the collatz sequence length for a number
All values that are visited while generating the sequence
will have their sequence length cached. This allows
for greatly improved performance with multiple use.
"""
length_if_kn... | collatz_lengths = {}
def collatz_length(number: int) -> int:
"""Calculate the collatz sequence length for a number
All values that are visited while generating the sequence
will have their sequence length cached. This allows
for greatly improved performance with multiple use.
"""
length_if_kno... |
def functie(l,n):
for a in range(1,n+1):
l.append(a**n)
list=[]
n = int(input("n = "))
functie(list,n)
print(list)
| def functie(l, n):
for a in range(1, n + 1):
l.append(a ** n)
list = []
n = int(input('n = '))
functie(list, n)
print(list) |
# 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 ( A , arr_size , sum ) :
for i in range ( 0 , arr_size - 1 ) :
s = set ( )
curr_sum = sum - A [ i... | def f_gold(A, arr_size, sum):
for i in range(0, arr_size - 1):
s = set()
curr_sum = sum - A[i]
for j in range(i + 1, arr_size):
if curr_sum - A[j] in s:
print('Triplet is', A[i], ', ', A[j], ', ', curr_sum - A[j])
return True
s.add(A[j]... |
# ------- MAIN SETTINGS ----------- #
SQLITE_DB_PATH = u'/Users/sidhshar/Downloads/dbstore/pp.sqlite'
JSON_DATA_FILENAME = 'pp.json'
MASTER_JSON_FILENAME = 'master.json'
STOP_COUNT = 2
# ------- STORAGE SETTINGS ----------- #
INPUT_STORE_DIRECTORY = u'/Users/sidhshar/Downloads/photodirip'
OUTPUT_STORE_DIRECTORY ... | sqlite_db_path = u'/Users/sidhshar/Downloads/dbstore/pp.sqlite'
json_data_filename = 'pp.json'
master_json_filename = 'master.json'
stop_count = 2
input_store_directory = u'/Users/sidhshar/Downloads/photodirip'
output_store_directory = u'/Users/sidhshar/Downloads/photodirop'
type_jpg_family = ('jpg', 'jpeg')
type_video... |
def make_key(*args):
return "ti:" + ":".join(args)
def make_refset_key(pmid):
return make_key("article", pmid, "refset") | def make_key(*args):
return 'ti:' + ':'.join(args)
def make_refset_key(pmid):
return make_key('article', pmid, 'refset') |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Find an element in a sorted array that has been rotated a num... | class Array(object):
def search_sorted_array(self, array, val):
if array is None or val is None:
raise type_error('array or val cannot be None')
if not array:
return None
return self._search_sorted_array(array, val, start=0, end=len(array) - 1)
def _search_sorte... |
def strip_ptms(sequence):
"""
Removes all post-translation modifications (i.e. phosphorylation,
glycosylation, etc) from a sequence.
Parameters
----------
sequence : str
Returns
-------
str
"""
return sequence.upper()
| def strip_ptms(sequence):
"""
Removes all post-translation modifications (i.e. phosphorylation,
glycosylation, etc) from a sequence.
Parameters
----------
sequence : str
Returns
-------
str
"""
return sequence.upper() |
def iterable(source):
def callbag(start, sink):
if (start != 0):
return
for i in source:
sink(1, i)
return callbag | def iterable(source):
def callbag(start, sink):
if start != 0:
return
for i in source:
sink(1, i)
return callbag |
'''1. Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations.
Sample data:
/*
X = [10, 20, 20, 20]
Y = [10, 20, 30, 40]
Z = [10, 30, 40, 20]
target = 70
*/ '''
X = [10, 20, 20, 20]
Y = [... | """1. Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations.
Sample data:
/*
X = [10, 20, 20, 20]
Y = [10, 20, 30, 40]
Z = [10, 30, 40, 20]
target = 70
*/ """
x = [10, 20, 20, 20]
y = [... |
"""
You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employe... | """
You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employe... |
def request_numbers():
numbers = []
for n in range(3):
number = float(input("Number: "))
numbers.append(number)
return numbers
def main():
numbers = request_numbers()
ordered = list(sorted(numbers))
if numbers == ordered:
print("Aumentando")
elif numbers == ordered[... | def request_numbers():
numbers = []
for n in range(3):
number = float(input('Number: '))
numbers.append(number)
return numbers
def main():
numbers = request_numbers()
ordered = list(sorted(numbers))
if numbers == ordered:
print('Aumentando')
elif numbers == ordered[:... |
"""
stringjumble.py
Author: Carlton
Credit: You
Assignment:
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With words in reverse order, ... | """
stringjumble.py
Author: Carlton
Credit: You
Assignment:
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With words in reverse order, ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 21:38:08 2018
@author: Dell
"""
__all__=['dxf','s2k'] | """
Created on Wed Mar 28 21:38:08 2018
@author: Dell
"""
__all__ = ['dxf', 's2k'] |
##
## Karkinos - b0bb
##
## https://twitter.com/0xb0bb
## https://github.com/0xb0bb/karkinos
##
MAJOR_VERSION = 0
MINOR_VERSION = 2
KARKINOS_VERSION = 'Karkinos v%d.%d' % (MAJOR_VERSION, MINOR_VERSION)
| major_version = 0
minor_version = 2
karkinos_version = 'Karkinos v%d.%d' % (MAJOR_VERSION, MINOR_VERSION) |
# Tuenti Challenge Edition 8 Level 6
PROBLEM_SIZE = "test"
# -- jam input/output ------------------------------------------------------- #
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
res = []
i = 0
while i < len(lines):
N = int(lines[i])
notes = [tuple... | problem_size = 'test'
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
res = []
i = 0
while i < len(lines):
n = int(lines[i])
notes = [tuple(map(int, l.split(' '))) for l in lines[i + 1:i + N + 1]]
res.append((N, notes))
... |
class StorageServiceName(basestring):
"""
The Storage Service Name
"""
@staticmethod
def get_api_name():
return "storage-service-name"
| class Storageservicename(basestring):
"""
The Storage Service Name
"""
@staticmethod
def get_api_name():
return 'storage-service-name' |
# -*- coding: utf-8 -*-
class BasePlugin(object):
NAME = 'base_plugin'
DESCRIPTION = ''
@property
def plugin_name(self):
"""Return the name of the plugin."""
return self.NAME
def Process(self, **kwargs):
"""Evaluates if this is the correct plugin and processes data accord... | class Baseplugin(object):
name = 'base_plugin'
description = ''
@property
def plugin_name(self):
"""Return the name of the plugin."""
return self.NAME
def process(self, **kwargs):
"""Evaluates if this is the correct plugin and processes data accordingly.
""" |
#!/usr/bin/env python3
if __name__ == '__main__':
numbers = [[6, 1, 6], [6], [5, 6, 6], [5], [4], [7, 5, 7, 2], [5, 8], [9], [7], [5, 6], [3, 4], [8], [4, 9, 3, 6], [8, 2, 4], [9, 7], [6, 8], [2, 5], [2, 4], [8, 3, 4], [5, 2], [4], [4, 4, 5, 5], [5, 1], [1, 4, 8], [6, 5], [5, 7, 8, 9], [1], [6], [3], [6], [7, 3, 8... | if __name__ == '__main__':
numbers = [[6, 1, 6], [6], [5, 6, 6], [5], [4], [7, 5, 7, 2], [5, 8], [9], [7], [5, 6], [3, 4], [8], [4, 9, 3, 6], [8, 2, 4], [9, 7], [6, 8], [2, 5], [2, 4], [8, 3, 4], [5, 2], [4], [4, 4, 5, 5], [5, 1], [1, 4, 8], [6, 5], [5, 7, 8, 9], [1], [6], [3], [6], [7, 3, 8, 8], [6], [2, 5, 4], [7... |
SEPN = f"\n{'=' * 40}"
SEP = f"{SEPN}\n"
QUERY_SPLIT_SIZE = 5000
SEQUENCE = 'sequence'
TABLE = 'table'
PRIMARY = 'primary'
UNIQUE = 'unique'
FOREIGN = 'foreign'
| sepn = f"\n{'=' * 40}"
sep = f'{SEPN}\n'
query_split_size = 5000
sequence = 'sequence'
table = 'table'
primary = 'primary'
unique = 'unique'
foreign = 'foreign' |
"""Top-level package for Genetic Algorithm."""
__author__ = """Puneetha Pai B P"""
__email__ = 'puneethapai29@gmail.com'
__version__ = '0.0.1'
| """Top-level package for Genetic Algorithm."""
__author__ = 'Puneetha Pai B P'
__email__ = 'puneethapai29@gmail.com'
__version__ = '0.0.1' |
def code_function():
#function begin############################################
global code
code="""
`include "{0}_seq_item.sv"
`include "{0}_sequencer.sv"
`include "{0}_sequence.sv"
`include "{0}_driver.sv"
`include "{0}_monitor.sv"
class {0}_agent extends uvm_agent;
//--------------------... | def code_function():
global code
code = '\n`include "{0}_seq_item.sv"\n`include "{0}_sequencer.sv"\n`include "{0}_sequence.sv"\n`include "{0}_driver.sv"\n`include "{0}_monitor.sv"\n\nclass {0}_agent extends uvm_agent;\n\n //---------------------------------------\n // component instances\n //----------------... |
# Numbers in Python can be of two types: Integers and Floats
# They're very important as many ML algorithms can only deal
# with numbers and will ignore/crash on any other kind of input
# because they're based complex math algorithms
# Integers have unbound size in Python 3!
lucky_number = 13
universe_number = 42
# ... | lucky_number = 13
universe_number = 42
pi = 3.14
a_third = 0.333
times_two = lucky_number * 2
square = universe_number ** 2
mod = 3 % 2
radius = 50
area_of_circle = pi * radius ** 2
print(area_of_circle) |
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Ole Krause-Sparmann
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... | class Vectorfilter(object):
"""
Interface for vector-list filters. They get either (vector, data, distance)
tupes or (vector, data) tuples and return subsets of them.
Some filters work on lists of (vector, data, distance) tuples, others work
on lists of (vector, data) tuples and others work on both... |
# Runs all 1d datasets.
Experiment(description='Run all 1D datasets',
data_dir='../data/1d_data/',
max_depth=8,
random_order=False,
k=2,
debug=False,
local_computation=True,
n_rand=3,
sd=4,
max_jobs=500,
... | experiment(description='Run all 1D datasets', data_dir='../data/1d_data/', max_depth=8, random_order=False, k=2, debug=False, local_computation=True, n_rand=3, sd=4, max_jobs=500, verbose=True, make_predictions=False, skip_complete=True, results_dir='../results/Feb 10 1D results/', iters=200) |
# 1.2 Palindrome Tester
def is_palindrome(input_string):
length = len(input_string)
palindrome = True
for i in range(0, length // 2):
if input_string[i] != input_string[length - i - 1]:
palindrome = False
return palindrome
| def is_palindrome(input_string):
length = len(input_string)
palindrome = True
for i in range(0, length // 2):
if input_string[i] != input_string[length - i - 1]:
palindrome = False
return palindrome |
class Gurney:
def greeting(self):
print('welcome to Simple Calculator Alpha 0.1')
def main(self):
firstNumber = float(input('Enter your first number: '))
operator = float(input('enter your operator: '))
secondNumber = float(input('Enter your third number:'))
if (ope... | class Gurney:
def greeting(self):
print('welcome to Simple Calculator Alpha 0.1')
def main(self):
first_number = float(input('Enter your first number: '))
operator = float(input('enter your operator: '))
second_number = float(input('Enter your third number:'))
if operat... |
symbology = 'code93'
cases = [
('001.png', 'CODE93', dict(includetext=True)),
('002.png', 'CODE93^SFT/A', dict(parsefnc=True, includecheck=True)),
]
| symbology = 'code93'
cases = [('001.png', 'CODE93', dict(includetext=True)), ('002.png', 'CODE93^SFT/A', dict(parsefnc=True, includecheck=True))] |
class Solution:
def minimumDeletions(self, s: str) -> int:
n = len(s)
a = 0
res = 0
for i in range(n - 1, -1, -1):
if s[i] == 'a':
a += 1
elif s[i] == 'b':
if a > 0:
a -= 1
res += 1
... | class Solution:
def minimum_deletions(self, s: str) -> int:
n = len(s)
a = 0
res = 0
for i in range(n - 1, -1, -1):
if s[i] == 'a':
a += 1
elif s[i] == 'b':
if a > 0:
a -= 1
res += 1
... |
num1=100
num2=200
num3=300
a
b
c
1
2
3
ttttt
e
f
g
9
8
7
| num1 = 100
num2 = 200
num3 = 300
a
b
c
1
2
3
ttttt
e
f
g
9
8
7 |
#Find the Runner-Up Score!
if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
arr=sorted(arr)
a=arr[0]
b=arr[0]
for i in range(1,n):
if(arr[i]==a):
pass
elif(arr[i]>a):
a=arr[i]
b=arr[i-1]
print(b) | if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
arr = sorted(arr)
a = arr[0]
b = arr[0]
for i in range(1, n):
if arr[i] == a:
pass
elif arr[i] > a:
a = arr[i]
b = arr[i - 1]
print(b) |
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
| access_token = ''
access_token_secret = ''
consumer_key = ''
consumer_secret = '' |
SECRET_KEY = '\xa6\xbaG\x80\xc9-$s\xd5~\x031N\x8f\xd9/\x88\xd0\xba#B\x9c\xcd_'
DEBUG = False
DB_HOST = 'localhost'
DB_USER = 'grupo35'
DB_PASS = 'OTRiYWJhYjU3YWMy'
DB_NAME = 'grupo35'
SQLALCHEMY_DATABASE_URI = 'mysql://grupo35:OTRiYWJhYjU3YWMy@localhost/grupo35'
SQLALCHEMY_TRACK_MODIFICATIONS = False | secret_key = '¦ºG\x80É-$sÕ~\x031N\x8fÙ/\x88к#B\x9cÍ_'
debug = False
db_host = 'localhost'
db_user = 'grupo35'
db_pass = 'OTRiYWJhYjU3YWMy'
db_name = 'grupo35'
sqlalchemy_database_uri = 'mysql://grupo35:OTRiYWJhYjU3YWMy@localhost/grupo35'
sqlalchemy_track_modifications = False |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: 'TreeNode') -> 'List[int]':
out = []
self.traverse(root, out)
return out
... | class Solution:
def inorder_traversal(self, root: 'TreeNode') -> 'List[int]':
out = []
self.traverse(root, out)
return out
def traverse(self, root, out):
if root:
self.traverse(root.left, out)
out.append(root.val)
self.traverse(root.right, ou... |
# Created by MechAviv
# Quest ID :: 17620
# [Commerci Republic] Eye for an Eye
sm.setSpeakerID(9390217)
sm.sendNext("Now, what dream can I make come true for you? Remember, anything in the entire world is yours for the asking.")
sm.setSpeakerID(9390217)
sm.setPlayerAsSpeaker()
sm.sendSay("Can you introduce me to Gil... | sm.setSpeakerID(9390217)
sm.sendNext('Now, what dream can I make come true for you? Remember, anything in the entire world is yours for the asking.')
sm.setSpeakerID(9390217)
sm.setPlayerAsSpeaker()
sm.sendSay('Can you introduce me to Gilberto Daniella?')
sm.setSpeakerID(9390217)
sm.sendSay('I offer to make your wildes... |
#!/usr/bin/env python3
f = "day10.input.txt"
# f = "day10.ex.txt"
ns = open(f).read().strip().split("\n")
ns = [int(x) for x in ns]
ns.sort()
ns.insert(0, 0)
ns.append(max(ns) + 3)
def part1():
count1 = 0
count3 = 0
for i in range(len(ns) - 1):
diff = ns[i + 1] - ns[i]
if diff == 1:
count1 += 1... | f = 'day10.input.txt'
ns = open(f).read().strip().split('\n')
ns = [int(x) for x in ns]
ns.sort()
ns.insert(0, 0)
ns.append(max(ns) + 3)
def part1():
count1 = 0
count3 = 0
for i in range(len(ns) - 1):
diff = ns[i + 1] - ns[i]
if diff == 1:
count1 += 1
if diff == 3:
... |
def sub_dict(dic, *keys, **renames):
d1 = {k: v for k, v in dic.items() if k in keys}
d2 = {renames[k]: v for k, v in dic.items() if k in renames.keys()}
return d1 | d2
| def sub_dict(dic, *keys, **renames):
d1 = {k: v for (k, v) in dic.items() if k in keys}
d2 = {renames[k]: v for (k, v) in dic.items() if k in renames.keys()}
return d1 | d2 |
# TODO: Figure out if this is even being used...
class logging(object):
def __init__(self, arg):
super(logging, self).__init__()
self.arg = arg
| class Logging(object):
def __init__(self, arg):
super(logging, self).__init__()
self.arg = arg |
# https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/train/python
def solution(args):
print(args)
i = j = 0
result = []
section = []
while i < len(args):
section.append(str(args[j]))
while j + 1 < len(args) and args[j] + 1 == args[j + 1]:
section.append(str(args... | def solution(args):
print(args)
i = j = 0
result = []
section = []
while i < len(args):
section.append(str(args[j]))
while j + 1 < len(args) and args[j] + 1 == args[j + 1]:
section.append(str(args[j + 1]))
j += 1
if len(section) > 2:
result... |
'''
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's n... | """
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's n... |
def is_a_leap_year(year):
if (year % 400 == 0):
return True
elif (year % 100 == 0):
return False
elif (year % 4 == 0):
return True
return False
def get_number_of_days(month, is_a_leap_year):
if (month == 4 or month == 6 or month == 9 or month == 11):
return 30
if... | def is_a_leap_year(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
return False
def get_number_of_days(month, is_a_leap_year):
if month == 4 or month == 6 or month == 9 or (month == 11):
return 30
if month... |
""" This module holds custom exceptions """
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class ItemNotInInventoryError(Error):
""" This exception is raised whenever the item we want to remove from our inventory is not there. """
def __init__(self, message, inventory: ... | """ This module holds custom exceptions """
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class Itemnotininventoryerror(Error):
""" This exception is raised whenever the item we want to remove from our inventory is not there. """
def __init__(self, message, inventory: d... |
"""
pgdumpreport
============
Generate a report from the contents of a pg_dump created archive.
"""
version = '1.0.0'
| """
pgdumpreport
============
Generate a report from the contents of a pg_dump created archive.
"""
version = '1.0.0' |
class WordCount:
# @param {str} line a text, for example "Bye Bye see you next"
def mapper(self, _, line):
# Write your code here
# Please use 'yield key, value'
for word in line.split():
yield word, 1
# @param key is from mapper
# @param values is a set of value w... | class Wordcount:
def mapper(self, _, line):
for word in line.split():
yield (word, 1)
def reducer(self, key, values):
yield (key, sum(values)) |
CLIENT_ID = "affordability-c31256e5-39c4-4b20-905a-7500c583c591"
CLIENT_SECRET = "eea983ac6dde3d1db86efe5793c7f6ec64b3d9c3ca6c81f4b71380109a723050"
API_BASE = "https://api.nordicapigateway.com/"
# If Python 2.x is used, only ASCII characters can be used in the values below.
SECRET_KEY = "0401" # for local session sto... | client_id = 'affordability-c31256e5-39c4-4b20-905a-7500c583c591'
client_secret = 'eea983ac6dde3d1db86efe5793c7f6ec64b3d9c3ca6c81f4b71380109a723050'
api_base = 'https://api.nordicapigateway.com/'
secret_key = '0401'
userhash = 'test-user-id'
include_transaction_details = False |
MEDIA_INTENT = 'media'
FEELING_INTENTS = ['smalltalk.appraisal.good', 'smalltalk.user.can_not_sleep',
'smalltalk.appraisal.thank_you', 'smalltalk.user.good',
'smalltalk.user.happy', 'smalltalk.user.sad',
'smalltalk.appraisal.bad', 'smalltalk.agent.happy',
... | media_intent = 'media'
feeling_intents = ['smalltalk.appraisal.good', 'smalltalk.user.can_not_sleep', 'smalltalk.appraisal.thank_you', 'smalltalk.user.good', 'smalltalk.user.happy', 'smalltalk.user.sad', 'smalltalk.appraisal.bad', 'smalltalk.agent.happy', 'smalltalk.user.sick']
affirmation_intents = ['yes', 'correct', ... |
x1, v1, x2, v2 = map(int, input().strip().split(' '))
if v1 == v2:
print("NO")
else:
j = (x1 - x2) // (v2 - v1)
print("YES" if j > 0 and (x1+v1*j == x2+v2*j) else "NO")
| (x1, v1, x2, v2) = map(int, input().strip().split(' '))
if v1 == v2:
print('NO')
else:
j = (x1 - x2) // (v2 - v1)
print('YES' if j > 0 and x1 + v1 * j == x2 + v2 * j else 'NO') |
with open("meeting.in", "r") as inputFile:
numberOfFields, numberOfPaths = map(int, list(inputFile.readline().strip().split()))
paths = [list(map(int, line.strip().split())) for line in inputFile.readlines()]
bessiepassable, elsiepassable = {str(i[0])+str(i[1]):i[2] for i in paths}, {str(i[0])+str(i[1]):i[3] f... | with open('meeting.in', 'r') as input_file:
(number_of_fields, number_of_paths) = map(int, list(inputFile.readline().strip().split()))
paths = [list(map(int, line.strip().split())) for line in inputFile.readlines()]
(bessiepassable, elsiepassable) = ({str(i[0]) + str(i[1]): i[2] for i in paths}, {str(i[0]) + st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.