content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Hashtable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] *self.size
def put(self, key, data):
hash_value = self.hash_function(key)
if self.slots[hash_value] == None:
self.slots[hash_value] = key
... | class Hashtable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hash_value = self.hash_function(key)
if self.slots[hash_value] == None:
self.slots[hash_value] = key
self... |
def setup():
size (300,300)
background (100)
smooth()
noLoop()
def draw ():
strokeWeight(15)
str(100)
line (100,200, 200,100)
line (200,200, 100,100)
| def setup():
size(300, 300)
background(100)
smooth()
no_loop()
def draw():
stroke_weight(15)
str(100)
line(100, 200, 200, 100)
line(200, 200, 100, 100) |
name = 'pyopengl'
version = '3.1.0'
authors = [
'Mike C. Fletcher <mcfletch@vrplumber.com>'
]
description = \
'''
Standard OpenGL bindings for Python.
'''
build_requires = [
'setuptools'
]
requires = [
'python'
]
variants = [
['platform-linux', 'arch-x86_64', 'os-CentOS-7']
]
uuid = '... | name = 'pyopengl'
version = '3.1.0'
authors = ['Mike C. Fletcher <mcfletch@vrplumber.com>']
description = '\n Standard OpenGL bindings for Python.\n '
build_requires = ['setuptools']
requires = ['python']
variants = [['platform-linux', 'arch-x86_64', 'os-CentOS-7']]
uuid = 'pyopengl'
def commands():
env.PYTH... |
n, m = map(int, input().split())
l = [*map(int, input().split())]
for _ in range(m):
l.sort()
l[0], l[1] = l[0]+l[1], l[0]+l[1]
print(sum(l))
| (n, m) = map(int, input().split())
l = [*map(int, input().split())]
for _ in range(m):
l.sort()
(l[0], l[1]) = (l[0] + l[1], l[0] + l[1])
print(sum(l)) |
def dictMerge(a, b):
for key, value in b.items():
if isinstance(value, dict):
if key in a:
dictMerge(a[key], value)
else:
a[key] = dict(value)
else:
a[key] = value
| def dict_merge(a, b):
for (key, value) in b.items():
if isinstance(value, dict):
if key in a:
dict_merge(a[key], value)
else:
a[key] = dict(value)
else:
a[key] = value |
class Calculator:
def __init__(self,num1):
self.num1 = num1
def __add__(self,num2):
return self.num1 + num2.num1
def __mul__(self,num2):
return self.num1 * num2.num1
def __len__(self,str):
return len(self.str)
def __str__(self):
return ... | class Calculator:
def __init__(self, num1):
self.num1 = num1
def __add__(self, num2):
return self.num1 + num2.num1
def __mul__(self, num2):
return self.num1 * num2.num1
def __len__(self, str):
return len(self.str)
def __str__(self):
return f'The Decimal N... |
# Copyright 2020 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | def pre_polygons(thresholds, dilation_factors):
"""Prepares polygon threshold and dilation parameters.
Args:
thresholds: list, thresholds to apply to images in range [0., 1.].
dilation_factors: list, factors to dilate polygons in range [0., inf).
Yields:
2-tuple of threshold and di... |
# Copyright 2020 Plezentek, Inc. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | sqlc_release = provider(doc='Contains information about the SQLC release used in the toolchain', fields={'goos': 'The host OS the release was built for.', 'goarch': 'The host architecture the release was built for.', 'root_file': 'The file at the base of the toolchain context', 'sqlc': 'The sqlc binary to execute', 've... |
input = """
% Reported by Axel Polleres to trigger a bug with -OR.
true.
%actiontime(T) :- T < #maxint, #int(T).
location(t) :- true.
location(B) :- block(B).
% blocksC2.dl without free variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Blocks world domain description in C
% Elementary Act... | input = "\n% Reported by Axel Polleres to trigger a bug with -OR.\n\ntrue.\n%actiontime(T) :- T < #maxint, #int(T).\nlocation(t) :- true.\nlocation(B) :- block(B).\n\n% blocksC2.dl without free variables\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Blocks world domain description in C\n% Eleme... |
SCRABBLE_LETTER_VALUES = {
"a": 1,
"b": 3,
"c": 3,
"d": 2,
"e": 1,
"f": 4,
"g": 2,
"h": 4,
"i": 1,
"j": 8,
"k": 5,
"l": 1,
"m": 3,
"n": 1,
"o": 1,
"p": 3,
"q": 10,
"r": 1,
"s": 1,
"t": 1,
"u": 1,
"v": 4,
"w": 4,
"x": 8,
... | scrabble_letter_values = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}
def get_word_score(word, n):
word_lower = word.lower()
word_len = len(wordL... |
"""
Created on Mon Jul 26 17:23:16 2021
@author: Andile Jaden Mbele
"""
"""
1. number of times around loop is n
2. number of operations inside loop is a constant
3. overall just O(n)
"""
def fact_iter(n):
prod = 1
for i in range(1, n + 1):
prod *= i
return prod
| """
Created on Mon Jul 26 17:23:16 2021
@author: Andile Jaden Mbele
"""
'\n1. number of times around loop is n\n2. number of operations inside loop is a constant\n3. overall just O(n)\n'
def fact_iter(n):
prod = 1
for i in range(1, n + 1):
prod *= i
return prod |
def trace(matrix):
try:
return sum(matrix[i][i] for i in range(max(len(matrix), len(matrix[0]))))
except:
return None | def trace(matrix):
try:
return sum((matrix[i][i] for i in range(max(len(matrix), len(matrix[0])))))
except:
return None |
"""Pushserver base configuration.
"""
class Config(object):
"""Base Configuration.
This should contain default values that will be used by all environments.
"""
DEBUG = False
TESTING = False
SERVER_NAME = None
SENTRY_DSN = None
BLUEPRINTS = (
('flask.ext.sse.sse', '/stream')... | """Pushserver base configuration.
"""
class Config(object):
"""Base Configuration.
This should contain default values that will be used by all environments.
"""
debug = False
testing = False
server_name = None
sentry_dsn = None
blueprints = (('flask.ext.sse.sse', '/stream'), ('pushser... |
"""
parition dp
f[k][i]: minimum time it will take for the first k copier to copy first i books
funciton:
f[k][i] = min for j=0..i(max(f[k - 1][j], A[j] + ... + A[i - 1]))
intial:
f[0][0] = 0
f[0][x] = sys.maxsize
f[k][0] = 0
answer:f[k][n - 1]
"""
# import sys
# class Solution:
# """
# @param pages: an array o... | """
parition dp
f[k][i]: minimum time it will take for the first k copier to copy first i books
funciton:
f[k][i] = min for j=0..i(max(f[k - 1][j], A[j] + ... + A[i - 1]))
intial:
f[0][0] = 0
f[0][x] = sys.maxsize
f[k][0] = 0
answer:f[k][n - 1]
""" |
oredict = [
"logWood",
"plankWood",
"slabWood",
"stairWood",
"stickWood",
"treeSapling",
"treeLeaves",
"vine",
"oreGold",
"oreIron",
"oreLapis",
"oreDiamond",
"oreRedstone",
"oreEmerald",
"oreQuartz",
"oreCoal",
"ingotIron",
"ingotGold",
"ingot... | oredict = ['logWood', 'plankWood', 'slabWood', 'stairWood', 'stickWood', 'treeSapling', 'treeLeaves', 'vine', 'oreGold', 'oreIron', 'oreLapis', 'oreDiamond', 'oreRedstone', 'oreEmerald', 'oreQuartz', 'oreCoal', 'ingotIron', 'ingotGold', 'ingotBrick', 'ingotBrickNether', 'nuggetGold', 'nuggetIron', 'gemDiamond', 'gemEme... |
class Embed:
def __init__(self, title=None, description=None, color=None, spoiler=False):
self.title = title
self.description = description
self.color = color
self.spoiler = spoiler
self.field_data = None
self.footer = None
def add_field(self, name, value, inline... | class Embed:
def __init__(self, title=None, description=None, color=None, spoiler=False):
self.title = title
self.description = description
self.color = color
self.spoiler = spoiler
self.field_data = None
self.footer = None
def add_field(self, name, value, inlin... |
"""External tests associated with doctest_private_tests.py.
>>> my_function(['A', 'B', 'C'], 2)
['A', 'B', 'C', 'A', 'B', 'C']
"""
| """External tests associated with doctest_private_tests.py.
>>> my_function(['A', 'B', 'C'], 2)
['A', 'B', 'C', 'A', 'B', 'C']
""" |
# -*- coding: utf-8 -*-
"""
***************************************************************************
qgsfeature.py
---------------------
Date : May 2018
Copyright : (C) 2018 by Denis Rouzaud
Email : denis@opengis.ch
**************************************... | """
***************************************************************************
qgsfeature.py
---------------------
Date : May 2018
Copyright : (C) 2018 by Denis Rouzaud
Email : denis@opengis.ch
***************************************************************... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 7 16:09:41 2017
@author: User
"""
def sameChrs():
commonS = []
s1 = str(input('Enter first string\n'))
s2 = str(input('Enter second string?\n'))
print('This is what you entered\n', s1,'\n', s2)
if len(s2) > len(s1):
raise Value... | """
Created on Thu Dec 7 16:09:41 2017
@author: User
"""
def same_chrs():
common_s = []
s1 = str(input('Enter first string\n'))
s2 = str(input('Enter second string?\n'))
print('This is what you entered\n', s1, '\n', s2)
if len(s2) > len(s1):
raise ValueError
else:
for i in ran... |
"""Singleton metaclass"""
# Copyright (C) 2019 F5 Networks, 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 applicabl... | """Singleton metaclass"""
class _Singleton(type):
""" A metaclass that creates a Singleton base class when called. """
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
return... |
#!/usr/bin/env python3
# create a list containing three items
my_list = ["192.168.0.5", 5060, "UP"]
# display first item
print("The first item in the list (IP): " + my_list[0] )
# Below needs to be cast from an int to a str for printing
print("The second item in the list (port): " + str(my_list[1]) )
# displaying the f... | my_list = ['192.168.0.5', 5060, 'UP']
print('The first item in the list (IP): ' + my_list[0])
print('The second item in the list (port): ' + str(my_list[1]))
print('The third item in the list (state): ' + my_list[2])
iplist = [5060, '80', 55, '10.0.0.1', '10.20.30.1', 'ssh']
print(iplist[3:5]) |
load("@bazel_gazelle//:deps.bzl", "go_repository")
def pprof_go_repositories():
go_repository(
name = "com_github_chzyer_logex",
importpath = "github.com/chzyer/logex",
sum = "h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=",
version = "v1.1.10",
)
go_repository(
nam... | load('@bazel_gazelle//:deps.bzl', 'go_repository')
def pprof_go_repositories():
go_repository(name='com_github_chzyer_logex', importpath='github.com/chzyer/logex', sum='h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=', version='v1.1.10')
go_repository(name='com_github_chzyer_readline', importpath='github.com/c... |
#SIMPLE CLASS TO SHOW HOW TO WORK WITH PACKAGES (look "11_test_my_package.py")
#Santiago Garcia Arango
#One of the modules to show how to create a simple package in python.
class hello:
def __init__(self, name):
self.name = name
def say_hi_to_someone(self):
sentence = "Hello, " + self.name... | class Hello:
def __init__(self, name):
self.name = name
def say_hi_to_someone(self):
sentence = 'Hello, ' + self.name + '!!!'
return sentence |
""" Python program to pass list to a function
and double the odd
values and half the even values of the list
and display the list elements after changing
"""
def operator_fn(a):
new=[]
for i in a:
if i%2==0:
i=i/2
new.append(i)
elif i%2!=0:
i=i*2... | """ Python program to pass list to a function
and double the odd
values and half the even values of the list
and display the list elements after changing
"""
def operator_fn(a):
new = []
for i in a:
if i % 2 == 0:
i = i / 2
new.append(i)
elif i % 2 != 0:
i = ... |
class TextCompressor:
def longestRepeat(self, sourceText):
l = len(sourceText)
for i in xrange(l / 2, 0, -1):
for j in xrange(0, l - i):
if sourceText[j : i + j] in sourceText[i + j :]:
return sourceText[j : i + j]
return ""
| class Textcompressor:
def longest_repeat(self, sourceText):
l = len(sourceText)
for i in xrange(l / 2, 0, -1):
for j in xrange(0, l - i):
if sourceText[j:i + j] in sourceText[i + j:]:
return sourceText[j:i + j]
return '' |
class Solution:
def canIwin(self, maxint: int, desiredtotal: int) -> bool:
if maxint * (maxint + 1) < desiredtotal:
return False
cache = dict()
def dp(running_total, used):
if used in cache:
return cache[used]
for k in range(maxint, 0, -1):... | class Solution:
def can_iwin(self, maxint: int, desiredtotal: int) -> bool:
if maxint * (maxint + 1) < desiredtotal:
return False
cache = dict()
def dp(running_total, used):
if used in cache:
return cache[used]
for k in range(maxint, 0, -... |
class TreasureHunt:
def __init__(self, table, user_clues=None):
try: # check user_clues
user_clues = [int(clue) for clue in user_clues]
except (TypeError, ValueError, IndexError):
print('Clue has wrong type, expect - <int>. Start default:')
user_clues = None
... | class Treasurehunt:
def __init__(self, table, user_clues=None):
try:
user_clues = [int(clue) for clue in user_clues]
except (TypeError, ValueError, IndexError):
print('Clue has wrong type, expect - <int>. Start default:')
user_clues = None
try:
... |
#!/usr/bin/env python
#
# (c) Copyright Rosetta Commons Member Institutions.
# (c) This file is part of the Rosetta software suite and is made available under license.
# (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
# (c) For more information, see http://www.rosettacommons.or... | current_directory = '' |
def func(a, b, n, m):
min_elem = max(a)
max_elem = min(b)
ans = []
for i in range(min_elem, max_elem+1):
j = 0
while j < n and i%a[j] == 0:
j += 1
if j == n:
if i%a[j-1] == 0:
k = 0
while k < m and b[k]%i == 0:
k += 1
if k == m:
if b[k-1]%i == 0:
ans.append(i)
retu... | def func(a, b, n, m):
min_elem = max(a)
max_elem = min(b)
ans = []
for i in range(min_elem, max_elem + 1):
j = 0
while j < n and i % a[j] == 0:
j += 1
if j == n:
if i % a[j - 1] == 0:
k = 0
while k < m and b[k] % i == 0:
... |
# -*- coding: utf-8 -*-
"""
exceptions.py
Exception class for pytineye.
Copyright (c) 2021 TinEye. All rights reserved worldwide.
"""
class TinEyeAPIError(Exception):
"""Base exception."""
def __init__(self, code, message):
self.code = code
self.message = message
def __repr__(self):
... | """
exceptions.py
Exception class for pytineye.
Copyright (c) 2021 TinEye. All rights reserved worldwide.
"""
class Tineyeapierror(Exception):
"""Base exception."""
def __init__(self, code, message):
self.code = code
self.message = message
def __repr__(self):
return "<pytineye.A... |
f = open('input.txt')
triangles = [map(int,l.split()) for l in f.readlines()]
possible = 0
for t in triangles:
t.sort()
if t[0] + t[1] > t[2]:
possible += 1
print(possible)
| f = open('input.txt')
triangles = [map(int, l.split()) for l in f.readlines()]
possible = 0
for t in triangles:
t.sort()
if t[0] + t[1] > t[2]:
possible += 1
print(possible) |
# -*- coding: utf-8 -*-
def import_object(name):
""" from tornado.utils.import_object """
if name.count('.') == 0:
return __import__(name, None, None)
parts = name.split('.')
obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
try:
return getattr(obj, parts[-1])
e... | def import_object(name):
""" from tornado.utils.import_object """
if name.count('.') == 0:
return __import__(name, None, None)
parts = name.split('.')
obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
try:
return getattr(obj, parts[-1])
except AttributeError:
... |
"""
One Away: There are three types of edits that can be performed on strings: insert a character,
remove a character, or replace a character. Given two strings, write a function to check if they are
one edit (or zero edits) away.
EXAMPLE
pale, ple -> true
pales. pale -> true
pale. bale -> true
pale. bake -> fal... | """
One Away: There are three types of edits that can be performed on strings: insert a character,
remove a character, or replace a character. Given two strings, write a function to check if they are
one edit (or zero edits) away.
EXAMPLE
pale, ple -> true
pales. pale -> true
pale. bale -> true
pale. bake -> fal... |
"""Majordomo Protocol definitions"""
# This is the version of MDP/Client we implement
C_CLIENT = "MDPC01"
# This is the version of MDP/Worker we implement
W_WORKER = "MDPW01"
# MDP/Server commands, as strings
W_READY = "\001"
W_REQUEST = "\002"
W_REPLY = "\003"
W_HEARTBEAT = "\004... | """Majordomo Protocol definitions"""
c_client = 'MDPC01'
w_worker = 'MDPW01'
w_ready = '\x01'
w_request = '\x02'
w_reply = '\x03'
w_heartbeat = '\x04'
w_disconnect = '\x05'
commands = [None, 'READY', 'REQUEST', 'REPLY', 'HEARTBEAT', 'DISCONNECT'] |
# ------------------------------
# 337. House Robber III
#
# Description:
# The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses... | class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res = self.robSub(root)
return max(res)
def rob_sub(self, root):
if not root:
return [0, 0]
left = self.robSub(root.left)
right = self.robSub(root.r... |
#!/usr/bin/python
dist = int(input())
v_r = int(input())
v_c = int(input())
time_r = dist / v_r
time_c = 50 / v_c
if time_c > time_r:
print("Meep Meep")
else:
print("Yum")
| dist = int(input())
v_r = int(input())
v_c = int(input())
time_r = dist / v_r
time_c = 50 / v_c
if time_c > time_r:
print('Meep Meep')
else:
print('Yum') |
# Problem: Remove x from string
def removeX(string):
if len(string)==0:
return string
if string[0]=="x":
return removeX(string[1:])
else:
return string[0]+removeX(string[1:])
# Main
string = input()
print(removeX(string))
| def remove_x(string):
if len(string) == 0:
return string
if string[0] == 'x':
return remove_x(string[1:])
else:
return string[0] + remove_x(string[1:])
string = input()
print(remove_x(string)) |
def add(num1,num2):
c=num1+num2
return c
a=int(input("ENTER num1 : "))
b=int(input("ENTER num1 : "))
print(add(a,b))
| def add(num1, num2):
c = num1 + num2
return c
a = int(input('ENTER num1 : '))
b = int(input('ENTER num1 : '))
print(add(a, b)) |
# set per your own configs
prefixs = [
'011XXXXX.',
]
prefixs_mid_process = []
prefixs_post_process = []
# process ASTERISK-like regex pattern for a prefix
# we are not expanding 'X' or '.'
# this is because we don't support length based prefix matching
# instead we utilize dr_rules longest-to-shortest prefix matching... | prefixs = ['011XXXXX.']
prefixs_mid_process = []
prefixs_post_process = []
def process_prefix(prefix):
for i in range(len(prefix)):
if prefix[i] == 'N':
tmp = list(prefix)
for j in range(2, 9 + 1):
tmp[i] = str(j)
prefixs_mid_process.append(''.join(tm... |
"""
Bicycle Object.
"""
#Class Header
class Bicycle :
"""
Initializer that creates three fields
"""
def __init__(self, gear_in, speed_in, color_in) :
self.gear = gear_in
self.speed = speed_in
self.color = color_in
#ACCESSORS
"""
Accessor function for the gear field
"""
def getgear(self)... | """
Bicycle Object.
"""
class Bicycle:
"""
Initializer that creates three fields
"""
def __init__(self, gear_in, speed_in, color_in):
self.gear = gear_in
self.speed = speed_in
self.color = color_in
'\n Accessor function for the gear field\n '
def getgear(self):
r... |
#~ def product(x,y):
#~ return x*y
#~ op = product(2,3)
#~ print(op)
#~ def product(x,y):
#~ print(x*y)
#~ op = product(2,3)
#~ print(op)
def product(x,y):
print("i am before return")
return x*y
print("i am after return")
product(2,3) | def product(x, y):
print('i am before return')
return x * y
print('i am after return')
product(2, 3) |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# Solution: 2 pointer solution -> O(n*n)
nums.sort()
res = []
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
left, right = i+1, len(nums)-1
... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
(left, right) = (i + 1, len(nums) - 1)
while left < right:
... |
l = int(input())
h = int(input())
t = str(input())
alphabet = [str(input()) for i in range(h)]
for i in range(h):
for char in t.lower():
if char >= 'a' and char <= 'z':
x = ord(char) - ord('a')
else:
x = ord('z') - ord('a') + 1
print(alphabet[i][x*l : x*l+l], end='... | l = int(input())
h = int(input())
t = str(input())
alphabet = [str(input()) for i in range(h)]
for i in range(h):
for char in t.lower():
if char >= 'a' and char <= 'z':
x = ord(char) - ord('a')
else:
x = ord('z') - ord('a') + 1
print(alphabet[i][x * l:x * l + l], end=... |
def fahrenheit_converter(C):
fahrenheit = C * 9 / 5 + 32
print(str(fahrenheit) + 'F')
c2f = fahrenheit_converter(35)
print(c2f)
| def fahrenheit_converter(C):
fahrenheit = C * 9 / 5 + 32
print(str(fahrenheit) + 'F')
c2f = fahrenheit_converter(35)
print(c2f) |
#!/usr/bin python
# -*- coding: utf-8 -*-
"""
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there
exists one unique longest palindromic substring.
https://oj.leetcode.com/problems/longest-palindromic-substring/
"""
class Solution:
# @return... | """
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there
exists one unique longest palindromic substring.
https://oj.leetcode.com/problems/longest-palindromic-substring/
"""
class Solution:
def longest_palindrome(self, s):
max_length... |
n = int(input())
tr = []
for _ in range(n):
tr.append(int(input()))
front = rear = 1
front_max = tr[0]
for i in range(1,len(tr)):
if front_max < tr[i]:
front += 1
front_max = tr[i]
tr.reverse()
rear_max = tr[0]
for i in range(1,len(tr)):
if rear_max < tr[i]:
rear += 1
re... | n = int(input())
tr = []
for _ in range(n):
tr.append(int(input()))
front = rear = 1
front_max = tr[0]
for i in range(1, len(tr)):
if front_max < tr[i]:
front += 1
front_max = tr[i]
tr.reverse()
rear_max = tr[0]
for i in range(1, len(tr)):
if rear_max < tr[i]:
rear += 1
rear_... |
f_name = '../results/result-1__rf_log.txt'
f = open(f_name,"r")
line_ext = list()
for line in f:
if 'Kappa : ' in line:
kappa = 'KAPPA\t'+line.strip().split(' : ')[1]
if 'Accuracy : ' in line and 'Balanced' not in line:
accu = 'ACCURACY\t'+line.strip().split(' : ')[1]
if 'Sensitivity : ' in... | f_name = '../results/result-1__rf_log.txt'
f = open(f_name, 'r')
line_ext = list()
for line in f:
if 'Kappa : ' in line:
kappa = 'KAPPA\t' + line.strip().split(' : ')[1]
if 'Accuracy : ' in line and 'Balanced' not in line:
accu = 'ACCURACY\t' + line.strip().split(' : ')[1]
if 'Sensitivity : ... |
### stuff I don't need to make the cards
def drawSquareGrid(dwg, widthInMillimeters):
hLineGroup = dwg.add(dwg.g(id='hlines', stroke='green'))
y = 0
while y < 100:
hLineGroup.add(dwg.add(dwg.line(
start = (0*mm, y*mm),
end = (150*mm, y*mm))))
y += widthInMillimeters... | def draw_square_grid(dwg, widthInMillimeters):
h_line_group = dwg.add(dwg.g(id='hlines', stroke='green'))
y = 0
while y < 100:
hLineGroup.add(dwg.add(dwg.line(start=(0 * mm, y * mm), end=(150 * mm, y * mm))))
y += widthInMillimeters
v_line_group = dwg.add(dwg.g(id='vlines', stroke='blue'... |
T = int(input())
for _ in range(T):
n, k = map(int, input().split())
print((n ** k - 1) % 9 + 1) | t = int(input())
for _ in range(T):
(n, k) = map(int, input().split())
print((n ** k - 1) % 9 + 1) |
class maxheap:
'''
implements max heap:
'''
def __init__(self, maxsize):
'''
initialize an empty max heap with a max size.
'''
self.size = 0
self.maxsize = maxsize
self.Heap = [0] * (self.maxsize + 1)
self.root = 1
def parent(self, pos):
... | class Maxheap:
"""
implements max heap:
"""
def __init__(self, maxsize):
"""
initialize an empty max heap with a max size.
"""
self.size = 0
self.maxsize = maxsize
self.Heap = [0] * (self.maxsize + 1)
self.root = 1
def parent(self, pos):... |
def closure(graph):
n = len(graph)
reachable = [[0 for _ in range(n)] for _ in range(n)]
for i, v in enumerate(graph):
for neighbor in v:
reachable[i][neighbor] = 1
for k in range(n):
for i in range(n):
for j in range(n):
reachable[i][... | def closure(graph):
n = len(graph)
reachable = [[0 for _ in range(n)] for _ in range(n)]
for (i, v) in enumerate(graph):
for neighbor in v:
reachable[i][neighbor] = 1
for k in range(n):
for i in range(n):
for j in range(n):
reachable[i][j] |= reach... |
quant = int(input())
for c in range(quant):
frase = input().split()
for x in range(len(frase) - 1, 0, -1):
for i in range(x):
if len(frase[i]) < len(frase[i+1]):
temp = frase[i]
frase[i] = frase[i+1]
frase[i+1] = temp
resultado = ' '.join(f... | quant = int(input())
for c in range(quant):
frase = input().split()
for x in range(len(frase) - 1, 0, -1):
for i in range(x):
if len(frase[i]) < len(frase[i + 1]):
temp = frase[i]
frase[i] = frase[i + 1]
frase[i + 1] = temp
resultado = ' '.... |
# $Id: local_dummy_lang.py 8452 2020-01-09 10:50:44Z milde $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
... | """
English-language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {'author': 'dummy Author', 'authors': 'dummy Authors', 'organization': 'dummy Organization', 'address': 'dummy Address', 'contact': 'dummy Contact', 'version': 'dummy Version', 'revision': 'dummy R... |
#!/usr/bin/env python3
"""This module contain a list subcommand for the docker-image resource."""
def configure_parser(docker_image_subparser):
"""Adds the parser for the list command to an argparse ArgumentParser"""
docker_image_subparser.add_parser(
"list", help="List docker images present on instan... | """This module contain a list subcommand for the docker-image resource."""
def configure_parser(docker_image_subparser):
"""Adds the parser for the list command to an argparse ArgumentParser"""
docker_image_subparser.add_parser('list', help='List docker images present on instance')
def subcommand(api):
""... |
class Solution:
def twoSum(self, arr: List[int], target: int) -> List[int]:
l = 0
r = len(arr) - 1
while l < r:
total = arr[l] + arr[r]
if total == target:
return l + 1, r + 1
elif total < target:
l += ... | class Solution:
def two_sum(self, arr: List[int], target: int) -> List[int]:
l = 0
r = len(arr) - 1
while l < r:
total = arr[l] + arr[r]
if total == target:
return (l + 1, r + 1)
elif total < target:
l += 1
else... |
'''
Created on 7 Feb 2015
@author: robrant
'''
MONGO_DBNAME = 'dfkm'
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
TESTING = True
"""
lat = 50.722
lon = -1.866
50m
""" | """
Created on 7 Feb 2015
@author: robrant
"""
mongo_dbname = 'dfkm'
mongo_host = 'localhost'
mongo_port = 27017
testing = True
'\n\nlat = 50.722\nlon = -1.866\n50m \n\n' |
'''' | cancer | Total
symptom |No | Yes |
no |99989 | 0 | 99989
yes |10 | 1 | 11
total |99999 | 1 | 100000
'''
def cal_bayes(prior_H, prob_E_given_H, prob_E):
return prior_H * prob_E_given_H / prob_E
if __name__ == '__main__':
prior_H = 1 / 100000 # probability ... | """' | cancer | Total
symptom |No | Yes |
no |99989 | 0 | 99989
yes |10 | 1 | 11
total |99999 | 1 | 100000
"""
def cal_bayes(prior_H, prob_E_given_H, prob_E):
return prior_H * prob_E_given_H / prob_E
if __name__ == '__main__':
prior_h = 1 / 100000
prob_not_h = 1... |
METRICS_AGGREGATE_KEYS = [
'sum',
'max',
'min'
]
BUCKETS_AGGREGATE_KEYS = [
'terms',
'date_histogram'
]
BUCKETS_AGGREGATE_OPTIONALS = [
'format',
'order',
'size',
'interval'
]
| metrics_aggregate_keys = ['sum', 'max', 'min']
buckets_aggregate_keys = ['terms', 'date_histogram']
buckets_aggregate_optionals = ['format', 'order', 'size', 'interval'] |
def book_dto(book):
try:
if not book:
return None
return {
'id': str(book.pk),
'book_name': book.name,
'summary': book.summary if book.summary else "",
'author': book.author,
'book_genre': book.genre,
'barcode': book... | def book_dto(book):
try:
if not book:
return None
return {'id': str(book.pk), 'book_name': book.name, 'summary': book.summary if book.summary else '', 'author': book.author, 'book_genre': book.genre, 'barcode': book.barcode, 'created_at': str(book.created_at), 'created_by': book.created_... |
count_dict, count, Last_item = {}, 0, None
binario = str(bin(int(input())))
binary_list = [n for n in binario]
for item in binary_list:
if Last_item != item:
Last_item = item
count = 1
else:
count += 1
if count > count_dict.get(item, 0):
count_dict[item] = count
print(coun... | (count_dict, count, last_item) = ({}, 0, None)
binario = str(bin(int(input())))
binary_list = [n for n in binario]
for item in binary_list:
if Last_item != item:
last_item = item
count = 1
else:
count += 1
if count > count_dict.get(item, 0):
count_dict[item] = count
print(cou... |
class Sample(object):
def func_0(self):
return '0'
def func_1(self, arg1):
return arg1
def func_2(self, arg1, arg2):
return arg1 + arg2
s = Sample()
result = s.func_0()
print(result)
result = s.func_1('test1')
print(result)
result = s.func_2('test1', 'test2')
print(result)
fu... | class Sample(object):
def func_0(self):
return '0'
def func_1(self, arg1):
return arg1
def func_2(self, arg1, arg2):
return arg1 + arg2
s = sample()
result = s.func_0()
print(result)
result = s.func_1('test1')
print(result)
result = s.func_2('test1', 'test2')
print(result)
func = ... |
# 647. Palindromic Substrings
# Runtime: 128 ms, faster than 79.15% of Python3 online submissions for Palindromic Substrings.
# Memory Usage: 14.1 MB, less than 85.33% of Python3 online submissions for Palindromic Substrings.
class Solution:
# Expand Around Possible Centers
def countSubstrings(self, s: str)... | class Solution:
def count_substrings(self, s: str) -> int:
count = 0
def expand_around_center(left: int, right: int) -> None:
nonlocal count
while left >= 0 and right < len(s):
if s[left] != s[right]:
break
else:
... |
def test_submit_retrieve(client) -> None:
headers = {
'Content-Type': 'text/plain'
}
urls = {
'https://www.wikipedia.org/': '48VIcsBN5UX',
'https://www.google.com/': '48VIcsBN5UY',
'https://www.stackoverflow.com/': '48VIcsBN5UZ',
'https://www.youtube.com/watch?v=dQw4... | def test_submit_retrieve(client) -> None:
headers = {'Content-Type': 'text/plain'}
urls = {'https://www.wikipedia.org/': '48VIcsBN5UX', 'https://www.google.com/': '48VIcsBN5UY', 'https://www.stackoverflow.com/': '48VIcsBN5UZ', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ': '48VIcsBN5Ua'}
for key in urls:
... |
list1 = [ 9, 2, 8, 4, 0, 1, 34 ]
# insert 45 at 5th index
list1.insert(4, 45)
print(list1)
list2 = ['q', 'b', 'u', 'h', 'p']
# insert z at the front of the list
list2.insert(0, 'z')
print(list2)
| list1 = [9, 2, 8, 4, 0, 1, 34]
list1.insert(4, 45)
print(list1)
list2 = ['q', 'b', 'u', 'h', 'p']
list2.insert(0, 'z')
print(list2) |
# Implement regular expression matching with the following special characters:
# . (period) which matches any single character
# * (asterisk) which matches zero or more of the preceding element
# That is, implement a function that takes in a string and a valid regular
# expression and returns whether or not the string... | def check_regex(re, string):
bool_mat = [[False] * (len(re) + 1) for i in range(len(string) + 1)]
boolMat[0][0] = True
for i in range(0, len(string) + 1):
for j in range(1, len(re) + 1):
if re[j - 1] == '*':
boolMat[i][j] = boolMat[i][j - 2] or (i > 0 and j > 1 and (re[j ... |
#
# PySNMP MIB module SCA-FREXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCA-FREXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:52:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint, constraints_union) ... |
# 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 allPossibleFBT(self, N: int) -> List[TreeNode]:
if N % 2 == 0: return []
dp = [[] for i ... | class Solution:
def all_possible_fbt(self, N: int) -> List[TreeNode]:
if N % 2 == 0:
return []
dp = [[] for i in range(N + 1)]
dp[1] = [tree_node(0)]
for i in range(3, N + 1, 2):
for j in range(1, i, 2):
k = i - j - 1
for l in ... |
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
t = int(input())
allResult = ''
for k in range(t):
input()
string = input()
result = 'a'
while string.find(result) != -1:
if result[len(result) - 1] != 'z':
result = result[:-1] + ALPHABET[ord(result[-1]) - 96]
else:
if result[0] == ALPHABET[25]:
temp = ''
f... | alphabet = 'abcdefghijklmnopqrstuvwxyz'
t = int(input())
all_result = ''
for k in range(t):
input()
string = input()
result = 'a'
while string.find(result) != -1:
if result[len(result) - 1] != 'z':
result = result[:-1] + ALPHABET[ord(result[-1]) - 96]
elif result[0] == ALPHAB... |
# Time: O(n), n is the number of the integers.
# Space: O(h), h is the depth of the nested lists.
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# ... | class Nestediterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.__depth = [[nestedList, 0]]
def next(self):
"""
:rtype: int
"""
(nested_list, i) = self.... |
# n = int(input())
# res = [[10 ** 9 for j in range(n)] for _ in range(n)]
# res[0][0] = 0
# scores = []
# for _ in range(n):
# scores.append(list(map(int, input().split())))
# direcs = [(0, 1), (0, -1), (-1, 0), (1, 0)]
# d4_scores = [[[] for _ in range(n)] for _ in range(n)]
# for i in range(n):
# for j in range(n)... | (n, m, k) = list(map(int, input().split()))
gifts = []
for _ in range(n):
gifts.append(list(map(int, input().split())))
gifts.sort(key=lambda x: [x[2], x[0], x[1]])
res = 0
i = 0
while i < n:
(p, w, _) = gifts[i]
i += 1
if k >= p and m >= w:
res += 1
k -= p
m -= w
print(res) |
for v in graph.getVertices():
print(v.value.rank) | for v in graph.getVertices():
print(v.value.rank) |
class Solution:
def coinChange(self, coins: 'List[int]', amount: int) -> int:
coins.sort(reverse=True)
impossible = (amount + 1) * 2
dp = [impossible] * (amount + 1)
dp[0] = 0
for current in range(amount + 1):
for coin in coins:
if curren... | class Solution:
def coin_change(self, coins: 'List[int]', amount: int) -> int:
coins.sort(reverse=True)
impossible = (amount + 1) * 2
dp = [impossible] * (amount + 1)
dp[0] = 0
for current in range(amount + 1):
for coin in coins:
if current + coin... |
EXAMPLES1 = (
('04-exemple1.txt', 4512),
)
EXAMPLES2 = (
('04-exemple1.txt', 1924),
)
INPUT = '04.txt'
def read_data(fn):
with open(fn) as f:
numbers = [int(s) for s in f.readline().strip().split(',')]
boards = list()
board = None
for line in f:
... | examples1 = (('04-exemple1.txt', 4512),)
examples2 = (('04-exemple1.txt', 1924),)
input = '04.txt'
def read_data(fn):
with open(fn) as f:
numbers = [int(s) for s in f.readline().strip().split(',')]
boards = list()
board = None
for line in f:
if not line.strip():
... |
"""
For this challenge, create the worlds simplest IM client. It should work like this: if Alice on computer A wants to talk
to Bob on computer B, she should start the IM program as a server listening to some port. Bob should then start the
program on his end, punch in computer A's IP address with the right port. The t... | """
For this challenge, create the worlds simplest IM client. It should work like this: if Alice on computer A wants to talk
to Bob on computer B, she should start the IM program as a server listening to some port. Bob should then start the
program on his end, punch in computer A's IP address with the right port. The t... |
#!/usr/bin/python
#
# AbstractPatching is the base patching class of all the linux distros
#
# Copyright 2014 Microsoft Corporation
#
# 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
#
# htt... | class Configoptions(object):
disabled = ['true', 'false']
stop = ['true', 'false']
reboot_after_patch = ['rebootifneed', 'auto', 'required', 'notrequired']
category = {'required': 'important', 'all': 'importantandrecommended'}
oneoff = ['true', 'false']
interval_of_weeks = [str(i) for i in range... |
# pylint: disable=missing-module-docstring
#
# Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >.
#
# This file is part of < https://github.com/UsergeTeam/Userge > project,
# and is released under the "GNU v3.0 License Agreement".
# Please see < https://github.com/uaudith/Userge/blob/master/LIC... | __all__ = ['send_msg', 'reply_last_msg', 'edit_last_msg', 'del_last_msg', 'end']
def _log(func):
def wrapper(text, log=None, tmp=None):
if log and callable(log):
if tmp:
log(tmp, text)
else:
log(text)
func(text)
return wrapper
def _send_... |
nuke.root().knob('onScriptSave').setValue('''
import re
for n in nuke.allNodes():
if n.Class() == 'Write':
code = """
import re
fileVersion = re.search( r'[vV]\d+', os.path.split(nuke.root().name())[1]).group()
print fileVersion
for node in nuke.allNodes():
if node.Class() == 'Write':
node.knob('file').setValue(... | nuke.root().knob('onScriptSave').setValue('\nimport re\nfor n in nuke.allNodes():\n\tif n.Class() == \'Write\':\n\t\tcode = """\nimport re\nfileVersion = re.search( r\'[vV]\\d+\', os.path.split(nuke.root().name())[1]).group()\nprint fileVersion\n\nfor node in nuke.allNodes():\n\tif node.Class() == \'Write\':\n\t\tnode.... |
"""
Because on the ReadTheDocs Server we cannot import the core extension, because a libpython*so which the core.so
is linked against is not found, this module fakes the core.so such that imports works
"""
__version__ = (1, 2, 3, 4)
__features__ = {}
ALL_SITES = -1
class SQSResult:
pass
class IterationSetting... | """
Because on the ReadTheDocs Server we cannot import the core extension, because a libpython*so which the core.so
is linked against is not found, this module fakes the core.so such that imports works
"""
__version__ = (1, 2, 3, 4)
__features__ = {}
all_sites = -1
class Sqsresult:
pass
class Iterationsettings:
... |
#
# PySNMP MIB module RBN-SMS1000-ENVMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-SMS1000-ENVMON-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:53:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, constraints_intersection, value_range_constraint) ... |
"""
Author : Drew Heasman
Date(last updated) : 05 June 2021
Description : Geochemical calculations
"""
elements = {}
elements["O"] = 15.9994
elements["Al"] = 26.981539
elements["Si"] = 28.0855
elements["K"] = 39.0983
elements["Cr"] = 51.9961
elements["Fe"] = 55.845
elements["Nd... | """
Author : Drew Heasman
Date(last updated) : 05 June 2021
Description : Geochemical calculations
"""
elements = {}
elements['O'] = 15.9994
elements['Al'] = 26.981539
elements['Si'] = 28.0855
elements['K'] = 39.0983
elements['Cr'] = 51.9961
elements['Fe'] = 55.845
elements['Nd'] = 144.24
... |
'''
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindro... | """
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
"""
class Solution:
def is_palindrome(self, head: ListNode) -> bool:
"""
Find the middle of the linked list and reverse the half of the
linked ... |
with open("sample.txt", 'a') as jabber:
for i in range(1,13):
for j in range(1,13):
print(f"{j:>2} times {i:2} is {i*j:<}", file=jabber)
print("-"*20, file=jabber) | with open('sample.txt', 'a') as jabber:
for i in range(1, 13):
for j in range(1, 13):
print(f'{j:>2} times {i:2} is {i * j:<}', file=jabber)
print('-' * 20, file=jabber) |
"""
In Python, a string can be split on a delimiter.
Example:
>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings.
>>> print a
['this', 'is', 'a', 'string']
Joining a string is simple:
>>> a = "-".join(a)
>>> print a
this-is-a-string
"""
def split_and_join(line):
# write you... | """
In Python, a string can be split on a delimiter.
Example:
>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings.
>>> print a
['this', 'is', 'a', 'string']
Joining a string is simple:
>>> a = "-".join(a)
>>> print a
this-is-a-string
"""
def split_and_join(line):
line = line.... |
class SocketManager(object):
def __init__(self):
self.ws = set()
def add_socket(self, ws):
self.ws.add(ws)
def remove_sockets(self, disconnected_ws):
if not isinstance(disconnected_ws, set):
disconnected_ws = {disconnected_ws, }
self.ws -= disconnected_ws
| class Socketmanager(object):
def __init__(self):
self.ws = set()
def add_socket(self, ws):
self.ws.add(ws)
def remove_sockets(self, disconnected_ws):
if not isinstance(disconnected_ws, set):
disconnected_ws = {disconnected_ws}
self.ws -= disconnected_ws |
# This class handles exceptions. All exceptions raised will be passed through the API to the client
class DebugException(Exception):
exception_dict = {
101: "Don't be naughty, type something with meaning >.<", # "Invalid input, please check your sentence",
301: "Keyword not found in Database",
... | class Debugexception(Exception):
exception_dict = {101: "Don't be naughty, type something with meaning >.<", 301: 'Keyword not found in Database', 302: 'Invalid Synonym Level. Level must be integer between 1 and 3', 303: 'No Synonym Link found', 304: 'Invalid base word', 305: 'Relationship already exists', 306: 'Re... |
class MockFeeEstOne():
@property
def status_code(self):
return 200
def json(self):
return {"fastestFee": 200, "halfHourFee": 200, "hourFee": 100}
class TestDataOne():
@property
def path(self):
return 'tests/test_files'
@property
def pub_key_file_name(self):
... | class Mockfeeestone:
@property
def status_code(self):
return 200
def json(self):
return {'fastestFee': 200, 'halfHourFee': 200, 'hourFee': 100}
class Testdataone:
@property
def path(self):
return 'tests/test_files'
@property
def pub_key_file_name(self):
r... |
# <auto-generated>
# This code was generated by the UnitCodeGenerator tool
#
# Changes to this file will be lost if the code is regenerated
# </auto-generated>
def to_milligrams(value):
return value * 28349.5231
def to_grams(value):
return value * 28.3495231
def to_kilograms(value):
return value / 35.274
def to_... | def to_milligrams(value):
return value * 28349.5231
def to_grams(value):
return value * 28.3495231
def to_kilograms(value):
return value / 35.274
def to_tonnes(value):
return value * 2.83495231e-05
def to_pounds(value):
return value * 0.0625
def to_stones(value):
return value / 224.0
def t... |
"""This module implements exceptions for this package."""
__all__ = ["Error", "InvalidRecordError", "InvalidHeaderError", "InvalidFooterError", "LogicError"]
class Error(Exception):
"""
Base class for exceptions in this module.
@see https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions
... | """This module implements exceptions for this package."""
__all__ = ['Error', 'InvalidRecordError', 'InvalidHeaderError', 'InvalidFooterError', 'LogicError']
class Error(Exception):
"""
Base class for exceptions in this module.
@see https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions
... |
S1 = "Hello World"
print("Length of the String is", len(S1)) # To find the length of a String
List1 = ["Emon", "Bakkar", "Ehassan", "Anik", "Ahad", "Sibbir"]
print("After join the list:", ", ".join(List1)) # To join the String
S2 = "Hey this is Emon"
List2 = S2.split()
print("After Split the String:{}".format(List2... | s1 = 'Hello World'
print('Length of the String is', len(S1))
list1 = ['Emon', 'Bakkar', 'Ehassan', 'Anik', 'Ahad', 'Sibbir']
print('After join the list:', ', '.join(List1))
s2 = 'Hey this is Emon'
list2 = S2.split()
print('After Split the String:{}'.format(List2))
s3 = 'Welcome to Python Programming'
print('After repla... |
list = ['iam vengeance']
list1 = []
for k in list:
list1.append(k.title())
print(list1) | list = ['iam vengeance']
list1 = []
for k in list:
list1.append(k.title())
print(list1) |
def func_kwargs(**kwargs):
print('kwargs: ', kwargs)
print('type: ', type(kwargs))
func_kwargs(key1=1, key2=2, key3=3)
# kwargs: {'key1': 1, 'key2': 2, 'key3': 3}
# type: <class 'dict'>
def func_kwargs_positional(arg1, arg2, **kwargs):
print('arg1: ', arg1)
print('arg2: ', arg2)
print('kwargs: '... | def func_kwargs(**kwargs):
print('kwargs: ', kwargs)
print('type: ', type(kwargs))
func_kwargs(key1=1, key2=2, key3=3)
def func_kwargs_positional(arg1, arg2, **kwargs):
print('arg1: ', arg1)
print('arg2: ', arg2)
print('kwargs: ', kwargs)
func_kwargs_positional(0, 1, key1=1)
d = {'key1': 1, 'key2':... |
class DestinyPyError(Exception):
...
class APIError(DestinyPyError):
...
class InvalidJSONResponse(APIError):
...
class APIResponseError(APIError):
def __init__(self, errorCode: int) -> None:
super().__init__(f'API returned an error code {errorCode}')
self.errorCode = errorCode
c... | class Destinypyerror(Exception):
...
class Apierror(DestinyPyError):
...
class Invalidjsonresponse(APIError):
...
class Apiresponseerror(APIError):
def __init__(self, errorCode: int) -> None:
super().__init__(f'API returned an error code {errorCode}')
self.errorCode = errorCode
clas... |
"""__init__.py."""
__title__ = 'hammingambuj'
__version__ = '0.0.3'
__author__ = 'Ambuj Dubey' | """__init__.py."""
__title__ = 'hammingambuj'
__version__ = '0.0.3'
__author__ = 'Ambuj Dubey' |
"""
@file
@brielf Shortcut to *sphinxext*.
"""
| """
@file
@brielf Shortcut to *sphinxext*.
""" |
# -*- coding: utf-8 -*-
def fibonacci(ene):
a = 0
b = 1
contador = 1
fibo = 0
while contador < ene:
fibo = b + a
a = b
b = fibo
contador += 1
return fibo
print('fibonacci(5) = ' + str(fibonacci(5)))
print('fibonacci(10) = ' + str(fibonacci(10)))
print('fibonac... | def fibonacci(ene):
a = 0
b = 1
contador = 1
fibo = 0
while contador < ene:
fibo = b + a
a = b
b = fibo
contador += 1
return fibo
print('fibonacci(5) = ' + str(fibonacci(5)))
print('fibonacci(10) = ' + str(fibonacci(10)))
print('fibonacci(20) = ' + str(fibonacci(2... |
# model settings
_base_ = "swin_tiny_my_MM_supervised.py"
model = dict(type="Recognizer3DJoint", backbone=dict(generative=True, discriminative=True),
cls_head=dict(type='JointHead'))
| _base_ = 'swin_tiny_my_MM_supervised.py'
model = dict(type='Recognizer3DJoint', backbone=dict(generative=True, discriminative=True), cls_head=dict(type='JointHead')) |
'''
Given three arrays sorted in increasing order. Find the elements that are common in all three arrays.
Input:
A = {1, 5, 10, 20, 40, 80}
B = {6, 7, 20, 80, 100}
C = {3, 4, 15, 20, 30, 70, 80, 120}
Output: [20, 80]
Explanation: 20 and 80 are the only
common elements in A, B and C.
'''
def common_elements(arr1,ar... | """
Given three arrays sorted in increasing order. Find the elements that are common in all three arrays.
Input:
A = {1, 5, 10, 20, 40, 80}
B = {6, 7, 20, 80, 100}
C = {3, 4, 15, 20, 30, 70, 80, 120}
Output: [20, 80]
Explanation: 20 and 80 are the only
common elements in A, B and C.
"""
def common_elements(arr1, a... |
'''
Author: He,Yifan
Date: 2022-02-16 21:46:19
LastEditors: He,Yifan
LastEditTime: 2022-02-16 21:52:34
'''
__version__ = "0.0.0" | """
Author: He,Yifan
Date: 2022-02-16 21:46:19
LastEditors: He,Yifan
LastEditTime: 2022-02-16 21:52:34
"""
__version__ = '0.0.0' |
def countSumOfTwoRepresentations2(n, l, r):
noWays = 0
for x in range(l, r + 1):
if (n - x >= x) and (n - x <= r):
noWays += 1
return noWays
| def count_sum_of_two_representations2(n, l, r):
no_ways = 0
for x in range(l, r + 1):
if n - x >= x and n - x <= r:
no_ways += 1
return noWays |
__author__ = 'jkm4ca'
def greeting(msg):
print(msg)
| __author__ = 'jkm4ca'
def greeting(msg):
print(msg) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.