content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
All that is open must be closed...
http://www.codewars.com/kata/55679d644c58e2df2a00009c/train/python
"""
def is_balanced(source, caps):
count = {}
stack = []
for c in source:
if c in caps:
i = caps.index(c)
if i % 2 == 0:
if caps[i] == caps[i + 1]:
... | """
All that is open must be closed...
http://www.codewars.com/kata/55679d644c58e2df2a00009c/train/python
"""
def is_balanced(source, caps):
count = {}
stack = []
for c in source:
if c in caps:
i = caps.index(c)
if i % 2 == 0:
if caps[i] == caps[i + 1]:
... |
#python program to display odd numbers
print("Odd numbers are as follows")
for i in range(1,100,2):
print(i)
print("End of the program")
| print('Odd numbers are as follows')
for i in range(1, 100, 2):
print(i)
print('End of the program') |
#!/usr/bin/python3
def img_splitter(img):
img_lines = img.splitlines()
longest = 0
for ind, line in enumerate(img_lines):
if line == "":
img_lines.pop(ind)
if len(line) > longest:
longest = len(line)
for line in img_lines:
if len(line) < longest:
... | def img_splitter(img):
img_lines = img.splitlines()
longest = 0
for (ind, line) in enumerate(img_lines):
if line == '':
img_lines.pop(ind)
if len(line) > longest:
longest = len(line)
for line in img_lines:
if len(line) < longest:
line.format(n=... |
class BinaryMatrix(object):
def __init__(self, mat):
self.mat = mat
def get(self, x: int, y: int) -> int:
return self.mat[x][y]
def dimensions(self):
n = len(self.mat)
m = len(self.mat[0])
return n, m
class Solution:
def leftMostColumnWithOne(self, binaryMatri... | class Binarymatrix(object):
def __init__(self, mat):
self.mat = mat
def get(self, x: int, y: int) -> int:
return self.mat[x][y]
def dimensions(self):
n = len(self.mat)
m = len(self.mat[0])
return (n, m)
class Solution:
def left_most_column_with_one(self, bina... |
USER_AGENTS = [
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/57.0.2987.110 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/61.0.3163.79 "
... | user_agents = ['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0', 'Mozilla... |
# Block No 99997
# Block Bits 453281356
# Difficulty 14,484.16
_bits = input("* block's BITS ? : ");
hexBits = hex(int(_bits));
_hexHead = hexBits[:4];
_hexTail = '0x'+hexBits[4:];
print("- BITS in hexadecimal : ", hexBits);
print(" ", _hexHead);
print(" ", _... | _bits = input("* block's BITS ? : ")
hex_bits = hex(int(_bits))
_hex_head = hexBits[:4]
_hex_tail = '0x' + hexBits[4:]
print('- BITS in hexadecimal : ', hexBits)
print(' ', _hexHead)
print(' ', _hexTail)
max_difficulty = hex(2695953529101130949315647634472399133... |
class BaseConfig:
SECRET_KEY = None
class DevelopmentConfig(BaseConfig):
FLASK_ENV="development"
class ProductionConfig(BaseConfig):
FLASK_ENV="production" | class Baseconfig:
secret_key = None
class Developmentconfig(BaseConfig):
flask_env = 'development'
class Productionconfig(BaseConfig):
flask_env = 'production' |
class Analyzer():
'''
Analyzer holds image data, hooks to pre-processed and intermediate data
and the methods to analyze and output visualizations
start: 2017-05-27, Nathan Ing
'''
def __init__(self):
pass | class Analyzer:
"""
Analyzer holds image data, hooks to pre-processed and intermediate data
and the methods to analyze and output visualizations
start: 2017-05-27, Nathan Ing
"""
def __init__(self):
pass |
"""
The Elves think their skill will improve after making a few recipes.
However, that could take ages; you can speed this up considerably by identifying
the scores of the ten recipes after that.
What are the scores of the ten recipes immediately after the number of recipes
in your puzzle input?
"""
class Scoreboar... | """
The Elves think their skill will improve after making a few recipes.
However, that could take ages; you can speed this up considerably by identifying
the scores of the ten recipes after that.
What are the scores of the ten recipes immediately after the number of recipes
in your puzzle input?
"""
class Scoreboard... |
# bubble sort function
def bubble_sort(arr):
n = len(arr)
# Repeat loop N times
# equivalent to: for(i = 0; i < n-1; i++)
for i in range(0, n-1):
# Repeat internal loop for (N-i)th largest element
for j in range(0, n-i-1):
# if jth value is greater than (j+1) value
... | def bubble_sort(arr):
n = len(arr)
for i in range(0, n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j])
arr = [64, 34, 25, 12, 22, 11, 90]
print('Before sorting:', arr)
bubble_sort(arr)
print('After sorting:', arr)
'\nOut... |
arr = []
for i in range(5):
dum = list(map(int, input().split()))
arr.append(dum)
def sol(arr):
for i in range(5):
for j in range(5):
if arr[i][j] == 1:
return abs(2-i) + abs(2-j)
print(sol(arr)) | arr = []
for i in range(5):
dum = list(map(int, input().split()))
arr.append(dum)
def sol(arr):
for i in range(5):
for j in range(5):
if arr[i][j] == 1:
return abs(2 - i) + abs(2 - j)
print(sol(arr)) |
"""
*args
A special operator we can pass to functions.
Gathers remaining arguments as a tuple.
"""
def sum_all_nums(num1, num2, num3):
return num1 + num2 + num3
print(sum_all_nums(4, 6, 9)) # 19
print(sum_all_nums(4, 6)) # Error: no value for argument num3
def sum_with_args(*args):
total = 0
f... | """
*args
A special operator we can pass to functions.
Gathers remaining arguments as a tuple.
"""
def sum_all_nums(num1, num2, num3):
return num1 + num2 + num3
print(sum_all_nums(4, 6, 9))
print(sum_all_nums(4, 6))
def sum_with_args(*args):
total = 0
for num in args:
total += num
return tot... |
# coding: utf-8
# This example is the python implementation of nowait.1.f from OpenMP 4.5 examples
n = 100
m = 100
a = zeros(n, double)
b = zeros(n, double)
y = zeros(m, double)
z = zeros(m, double)
#$ omp parallel
#$ omp do schedule(runtime)
for i in range(0, m):
z[i] = i*1.0
#$ omp end do nowait
#$ omp do
fo... | n = 100
m = 100
a = zeros(n, double)
b = zeros(n, double)
y = zeros(m, double)
z = zeros(m, double)
for i in range(0, m):
z[i] = i * 1.0
for i in range(1, n):
b[i] = (a[i] + a[i - 1]) / 2.0
for i in range(1, m):
y[i] = sqrt(z[i]) |
#!/usr/bin/env python3v
## create file object in "r"ead mode
filename = input("Name of file: ")
with open(f"{filename}", "r") as configfile:
## readlines() creates a list by reading target
## file line by line
configlist = configfile.readlines()
## file was just auto closed (no more indenting)
## each i... | filename = input('Name of file: ')
with open(f'{filename}', 'r') as configfile:
configlist = configfile.readlines()
print(configlist)
num_lines = len(configlist)
print(f'Using the len() function, we see there are: {num_lines} line') |
class Solution:
def preorderTraversal(self, root):
ret = []
s = [root]
while s:
cur = s.pop()
if not cur:
continue
ret.append(cur.val)
if cur.right:
s.append(cur.right)
if cur.left:
... | class Solution:
def preorder_traversal(self, root):
ret = []
s = [root]
while s:
cur = s.pop()
if not cur:
continue
ret.append(cur.val)
if cur.right:
s.append(cur.right)
if cur.left:
... |
execfile('ex-3.02.py')
assert dtype.size == MPI.DOUBLE.size + MPI.CHAR.size
assert dtype.extent >= dtype.size
dtype.Free()
| execfile('ex-3.02.py')
assert dtype.size == MPI.DOUBLE.size + MPI.CHAR.size
assert dtype.extent >= dtype.size
dtype.Free() |
"""
--- Day 6: Custom Customs ---
As your flight approaches the regional airport where you'll switch to a much larger plane,
customs declaration forms are distributed to the passengers.
The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is
identify the questions for which anyone... | """
--- Day 6: Custom Customs ---
As your flight approaches the regional airport where you'll switch to a much larger plane,
customs declaration forms are distributed to the passengers.
The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is
identify the questions for which anyone ... |
class Solution:
def largestBSTSubtree(self, root: TreeNode) -> int:
return self._post_order(root)[0]
def _post_order(self, root):
if not root:
return 0, True, None, None
if not root.left and not root.right:
return 1, True, root.val, root.val
ln, l... | class Solution:
def largest_bst_subtree(self, root: TreeNode) -> int:
return self._post_order(root)[0]
def _post_order(self, root):
if not root:
return (0, True, None, None)
if not root.left and (not root.right):
return (1, True, root.val, root.val)
(ln,... |
# print function range value
for value in range(1, 5):
print(value)
numbers = list(range(1, 6))
print(numbers)
even_numbers = list(range(2, 11))
print(even_numbers)
| for value in range(1, 5):
print(value)
numbers = list(range(1, 6))
print(numbers)
even_numbers = list(range(2, 11))
print(even_numbers) |
def is_odd(n):
return n % 2 == 1
def is_weird(n):
if is_odd(n):
return True
else:
# n is even
if 2 <= n <= 5:
return False
elif 6 <= n <= 20:
return True
elif 20 < n:
return False
n = int(input())
if (is_weird(n)):
print("W... | def is_odd(n):
return n % 2 == 1
def is_weird(n):
if is_odd(n):
return True
elif 2 <= n <= 5:
return False
elif 6 <= n <= 20:
return True
elif 20 < n:
return False
n = int(input())
if is_weird(n):
print('Weird')
else:
print('Not Weird') |
class calculos():
def __init__(self):
self.funcoes = {
"soma": self.soma,
"subtracao": self.subtracao,
"multiplicacao": self.multiplicacao,
"divisao": self.divisao,
"quadrado": self.quadrado,
"raiz_quadrada": self.raiz_quadrada,
... | class Calculos:
def __init__(self):
self.funcoes = {'soma': self.soma, 'subtracao': self.subtracao, 'multiplicacao': self.multiplicacao, 'divisao': self.divisao, 'quadrado': self.quadrado, 'raiz_quadrada': self.raiz_quadrada, 'porcentagem': self.porcentagem}
def soma(self, x, y):
return x + y
... |
# Print the list created by using list comprehension
names = ['George', 'Harry', 'Weasely', 'Ron', 'Potter', 'Hermione']
best_list = [name for name in names if len(name) >= 6]
print(best_list)
# Range Objects
# Create a range object that goes from 0 to 5
nums = range(6)
print(type(nums))
# Convert nums to a list
nums... | names = ['George', 'Harry', 'Weasely', 'Ron', 'Potter', 'Hermione']
best_list = [name for name in names if len(name) >= 6]
print(best_list)
nums = range(6)
print(type(nums))
nums_list = list(nums)
print(nums_list)
nums_list2 = [*range(1, 12, 2)]
print(nums_list2)
names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman'... |
# -*- coding:utf-8 -*-
def read_files(path):
file = open(path, 'r+')
str_ = file.read()
print(str_)
file.close()
| def read_files(path):
file = open(path, 'r+')
str_ = file.read()
print(str_)
file.close() |
#!/usr/bin/python3
""" 4-main """
MRUCache = __import__('4-mru_cache').MRUCache
my_cache = MRUCache()
my_cache.put("A", "Hello")
my_cache.put("B", "World")
my_cache.put("C", "Holberton")
my_cache.put("D", "School")
my_cache.print_cache()
print(my_cache.get("B"))
my_cache.put("E", "Battery")
my_cache.print_cache()
my_c... | """ 4-main """
mru_cache = __import__('4-mru_cache').MRUCache
my_cache = mru_cache()
my_cache.put('A', 'Hello')
my_cache.put('B', 'World')
my_cache.put('C', 'Holberton')
my_cache.put('D', 'School')
my_cache.print_cache()
print(my_cache.get('B'))
my_cache.put('E', 'Battery')
my_cache.print_cache()
my_cache.put('C', 'Str... |
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
def change(i):
if i == '0':
return '1'
return '0'
l = ''
print(bin(num)[2:])
for i in bin(num)[2:]:
l... | class Solution(object):
def find_complement(self, num):
"""
:type num: int
:rtype: int
"""
def change(i):
if i == '0':
return '1'
return '0'
l = ''
print(bin(num)[2:])
for i in bin(num)[2:]:
l += ch... |
for a in range (2,21):
if a > 1:
for i in range(2,a):
if (a % i) == 0:
break
else:
print(a) | for a in range(2, 21):
if a > 1:
for i in range(2, a):
if a % i == 0:
break
else:
print(a) |
#!/usr/bin/env python3
# Simple data processing, extraction of GPGGA and GPRMC entries
# Source filename
FILENAME = "../data/GNSS_34_2020-02-23_16-20-44.txt"
# Output filename
OUTFILE = "../output/track.nmea"
if __name__ == "__main__":
outfile = open(OUTFILE, 'w')
with open(FILENAME, 'r') as f:
for... | filename = '../data/GNSS_34_2020-02-23_16-20-44.txt'
outfile = '../output/track.nmea'
if __name__ == '__main__':
outfile = open(OUTFILE, 'w')
with open(FILENAME, 'r') as f:
for line in f.readlines():
try:
data = line.split(';')[1].strip()
if data.startswith('$... |
registry = {}
def unmarshal(typestr, x):
try:
unmarshaller = registry[typestr]
except KeyError:
raise TypeError("No unmarshaller registered for '{}'".format(typestr))
return unmarshaller(x)
def register(typestr, unmarshaller):
if typestr in registry:
raise NameError(
... | registry = {}
def unmarshal(typestr, x):
try:
unmarshaller = registry[typestr]
except KeyError:
raise type_error("No unmarshaller registered for '{}'".format(typestr))
return unmarshaller(x)
def register(typestr, unmarshaller):
if typestr in registry:
raise name_error("An unmar... |
def play(n=None):
if n is None:
while True:
try:
n = int(input('Input the grid size: '))
except ValueError:
print('Invalid input')
continue
if n <= 0:
print('Invalid input')
continue
... | def play(n=None):
if n is None:
while True:
try:
n = int(input('Input the grid size: '))
except ValueError:
print('Invalid input')
continue
if n <= 0:
print('Invalid input')
continue
... |
def get_rate(numbers,
is_o2):
nb_bits = len(numbers[0])
assert all([len(n) == nb_bits for n in numbers])
current_numbers = [n for n in numbers]
i = 0
while len(current_numbers) > 1:
nb_ones = sum([elem[i] == '1' for elem in current_numbers])
nb_zeros = sum([elem[i] ==... | def get_rate(numbers, is_o2):
nb_bits = len(numbers[0])
assert all([len(n) == nb_bits for n in numbers])
current_numbers = [n for n in numbers]
i = 0
while len(current_numbers) > 1:
nb_ones = sum([elem[i] == '1' for elem in current_numbers])
nb_zeros = sum([elem[i] == '0' for elem in... |
# Returns the sum of all multipliers of x for numbers from 1 to end.
def sumOfMultipliers(end, x):
n = end / x
return (n * (n + 1) / 2) * x
end = 999 # below 1000
x = 3
y = 5
# We have to subtract one sum of the multipliers of x * y because these multipliers take part in both of the sums of the multipliers of x an... | def sum_of_multipliers(end, x):
n = end / x
return n * (n + 1) / 2 * x
end = 999
x = 3
y = 5
sum = sum_of_multipliers(end, x) + sum_of_multipliers(end, y) - sum_of_multipliers(end, x * y)
print(sum) |
def cmdissue(toissue, activesession):
ssh_stdin, ssh_stdout, ssh_stderr = activesession.exec_command(toissue)
return ssh_stdout.read().decode('UTF-8')
def commands_list(sshsession, commands):
for x in commands:
## call our imported function and save the value returned
resp = cmdissue(x, ... | def cmdissue(toissue, activesession):
(ssh_stdin, ssh_stdout, ssh_stderr) = activesession.exec_command(toissue)
return ssh_stdout.read().decode('UTF-8')
def commands_list(sshsession, commands):
for x in commands:
resp = cmdissue(x, sshsession)
if resp != '':
print(resp) |
List1 = []
List2 = []
List3 = []
List4 = []
List5 = [13,31,2,19,96]
statusList1 = 0
while statusList1 < 13:
inputList1 = str(input("Masukkan hewan bersayap : "))
statusList1 += 1
List1.append(inputList1)
print()
statusList2 = 0
while statusList2 < 5:
inputList2 = str(input("Masukkan hewan berkaki 2 : ")... | list1 = []
list2 = []
list3 = []
list4 = []
list5 = [13, 31, 2, 19, 96]
status_list1 = 0
while statusList1 < 13:
input_list1 = str(input('Masukkan hewan bersayap : '))
status_list1 += 1
List1.append(inputList1)
print()
status_list2 = 0
while statusList2 < 5:
input_list2 = str(input('Masukkan hewan berka... |
class dataStore:
dataList=[]
symbolList=[]
optionList=[]
def __init__(self):
self.dataList=[]
self.symbolList=[]
self.optionList=[]
def reset(self):
self.dataList=[]
self.symbolList=[]
... | class Datastore:
data_list = []
symbol_list = []
option_list = []
def __init__(self):
self.dataList = []
self.symbolList = []
self.optionList = []
def reset(self):
self.dataList = []
self.symbolList = []
self.optionList = [] |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
class MessageType(object):
TYPE_GLOBAL_BEGIN = 1
TYPE_GLOBAL_BEGIN_RESULT = 2
TYPE_GLOBAL_COMMIT = 7
TYPE_GLOBAL_COMMIT_RESULT = 8
TYPE_GLOBAL_ROLLBACK = 9
TYPE_GLOBAL_ROLLBACK_RESULT = 10
TYPE_GLOBAL_STATUS... | class Messagetype(object):
type_global_begin = 1
type_global_begin_result = 2
type_global_commit = 7
type_global_commit_result = 8
type_global_rollback = 9
type_global_rollback_result = 10
type_global_status = 15
type_global_status_result = 16
type_global_report = 17
type_global_... |
def scoreOfParentheses(S):
total = 0
cur = 0
for i in range(len(S)):
if S[i] == "(":
cur += 1
elif S[i] == ")":
cur -= 1
if S[i-1] == "(":
total += 2**cur
return total
print(scoreOfParentheses("()")) # 1
print(scoreOfP... | def score_of_parentheses(S):
total = 0
cur = 0
for i in range(len(S)):
if S[i] == '(':
cur += 1
elif S[i] == ')':
cur -= 1
if S[i - 1] == '(':
total += 2 ** cur
return total
print(score_of_parentheses('()'))
print(score_of_parentheses('... |
c = input().split()
W, H, x, y, r = int(c[0]), int(c[1]), int(c[2]), int(c[3]), int(c[4])
if r <= x <= W - r and r <= y <= H - r:
print("Yes")
else:
print("No")
| c = input().split()
(w, h, x, y, r) = (int(c[0]), int(c[1]), int(c[2]), int(c[3]), int(c[4]))
if r <= x <= W - r and r <= y <= H - r:
print('Yes')
else:
print('No') |
# -*- coding: utf-8 -*-
numeros = []
for x in range(100):
numeros.append(int(input()))
print(max(numeros))
print(numeros.index(max(numeros))+1)
| numeros = []
for x in range(100):
numeros.append(int(input()))
print(max(numeros))
print(numeros.index(max(numeros)) + 1) |
# Python Program to Differentiate Between type() and isinstance()
class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = Polygon()
obj_triangle = Triangle()
print(type(obj_triangle) == Triangle) # true
print(type(obj_triangle) == Polygon) #... | class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = polygon()
obj_triangle = triangle()
print(type(obj_triangle) == Triangle)
print(type(obj_triangle) == Polygon)
print(isinstance(obj_polygon, Polygon))
print(isinstance(obj_triangle, Polygon)) |
s1 = (2, 1.3, 'love', 5.6, 9, 12, False)
s2 = [True, 5, 'smile']
print('s1=',s1)
print('s1[:5]=',s1[:5])
print('s1[2:]=',s1[2:])
print('s1[0:5:2]=',s1[0:5:2])
print('s1[2:0:-1]=',s1[2:0:-1])
print('s1[-1]=',s1[-1])
print('s1[-3]=',s1[-3])
| s1 = (2, 1.3, 'love', 5.6, 9, 12, False)
s2 = [True, 5, 'smile']
print('s1=', s1)
print('s1[:5]=', s1[:5])
print('s1[2:]=', s1[2:])
print('s1[0:5:2]=', s1[0:5:2])
print('s1[2:0:-1]=', s1[2:0:-1])
print('s1[-1]=', s1[-1])
print('s1[-3]=', s1[-3]) |
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code # -> 200
r.headers['content-type']
# -> 'application/json; charset=utf8'
r.encoding # -> 'utf-8'
r.text # -> u'{"type":"User"...'
r.json()
# -> {u'private_gists': 419, u'total_private_repos': 77, ...}
| r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
r.headers['content-type']
r.encoding
r.text
r.json() |
class AttachedFile:
def __init__(self, original_name: str, tmp_file_path: str, need_content_analysis: bool, uid: str) -> None:
"""
Holds information about attached files.
:param original_name: Name of the file from which the attachments are extracted
:param tmp_file_path: path to th... | class Attachedfile:
def __init__(self, original_name: str, tmp_file_path: str, need_content_analysis: bool, uid: str) -> None:
"""
Holds information about attached files.
:param original_name: Name of the file from which the attachments are extracted
:param tmp_file_path: path to th... |
class Joint:
def __init__(self, name, min_angle: float, max_angle: float):
self.name = name
self.min_angle = min_angle
self.max_angle = max_angle | class Joint:
def __init__(self, name, min_angle: float, max_angle: float):
self.name = name
self.min_angle = min_angle
self.max_angle = max_angle |
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordSet = set(wordDict) # Converted to set for O(1)
# table to map a string to its corresponding words break
# {string: [['word1', 'word2'...], ['word3', 'word4', ...]]}
mem = defaultdict(list)
... | class Solution:
def word_break(self, s: str, wordDict: List[str]) -> List[str]:
word_set = set(wordDict)
mem = defaultdict(list)
def _word_break_topdown(s):
""" return list of word lists """
if not s:
return [[]]
if s in mem:
... |
#
# PySNMP MIB module SONOMASYSTEMS-SONOMA-ATM-E3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-ATM-E3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:09:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
def shift(a):
last = a[-1]
a.insert(0, last)
a.pop()
return a
def f(a,b):
a = list(a)
b = list(b)
for i in range(len(a)):
a = shift(a)
if a == b:
return True
return False
f('abcde', 'abced')
| def shift(a):
last = a[-1]
a.insert(0, last)
a.pop()
return a
def f(a, b):
a = list(a)
b = list(b)
for i in range(len(a)):
a = shift(a)
if a == b:
return True
return False
f('abcde', 'abced') |
def extractBinggoCorp(item):
"""
# Binggo & Corp Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Jiang Ye' in item['title'] and 'Chapter' in item['title']:
return buildReleaseMessageWithType(... | def extract_binggo_corp(item):
"""
# Binggo & Corp Translations
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Jiang Ye' in item['title'] and 'Chapter' in item['title']:
ret... |
class BaloneyInterpreter(object):
def __init__(self, prog):
self.prog = prog
def run(self):
self.vars = {} # All variables
self.lists = {} # List variables
self.error = 0 # Indicates program error
self.stat = list(self.prog) # Ord... | class Baloneyinterpreter(object):
def __init__(self, prog):
self.prog = prog
def run(self):
self.vars = {}
self.lists = {}
self.error = 0
self.stat = list(self.prog)
self.stat.sort()
print(self.stat) |
#!/bin/python3
def plus_minus(array):
ratio_positive = round(sum(i > 0 for i in array) / len(array), 6)
ratio_negative = round(sum(i < 0 for i in array) / len(array), 6)
ratio_zero = round(sum(i == 0 for i in array) / len(array), 6)
return ratio_positive, ratio_negative, ratio_zero
def test_plus_min... | def plus_minus(array):
ratio_positive = round(sum((i > 0 for i in array)) / len(array), 6)
ratio_negative = round(sum((i < 0 for i in array)) / len(array), 6)
ratio_zero = round(sum((i == 0 for i in array)) / len(array), 6)
return (ratio_positive, ratio_negative, ratio_zero)
def test_plus_minus():
... |
"""
Dictionary examples.
The intention is that you would use the code in the functions rather
than the functions themselves.
"""
def create_dict():
"""
Create a new dictionary.
Example from: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': ... | """
Dictionary examples.
The intention is that you would use the code in the functions rather
than the functions themselves.
"""
def create_dict():
"""
Create a new dictionary.
Example from: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one'... |
# Heap
# CLRS Chapter 6 Page 152, 154, 157, 163, 164
# For CPython's implementation see:
# https://hg.python.org/cpython/file/2.7/Lib/heapq.py
def max_heapify(heap, node):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = le... | def max_heapify(heap, node):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = left
if right < size(heap) and heap[largest] < heap[right]:
largest = right
if largest != node:
_swap(heap, node, largest)
... |
def ascii(arg): pass
def filter(pred, iterable): pass
def hex(arg): pass
def map(func, *iterables): pass
def oct(arg): pass
| def ascii(arg):
pass
def filter(pred, iterable):
pass
def hex(arg):
pass
def map(func, *iterables):
pass
def oct(arg):
pass |
#!/usr/bin/python3
'''General Class which is used for all the class
'''
class GeneralSeller:
def __init__(self,mechant_i):
pass
def start_product(self):
pass
class WishSeller(GeneralSeller):
'''
'''
class AmazonSeller(GeneralSeller):
pass
class AlibabaSeller(GeneralSeller):
pa... | """General Class which is used for all the class
"""
class Generalseller:
def __init__(self, mechant_i):
pass
def start_product(self):
pass
class Wishseller(GeneralSeller):
"""
"""
class Amazonseller(GeneralSeller):
pass
class Alibabaseller(GeneralSeller):
pass
class Ebays... |
upTo = int(input())
res = 0
for i in range(upTo):
res += i
print(res)
| up_to = int(input())
res = 0
for i in range(upTo):
res += i
print(res) |
class Solution(object):
def intersect(self, nums1, nums2):
nums1_counter = collections.Counter(nums1)
nums2_counter = collections.Counter(nums2)
result = []
for k in nums1_counter.keys():
if k in nums2_counter:
result.extend([k] * min(nums... | class Solution(object):
def intersect(self, nums1, nums2):
nums1_counter = collections.Counter(nums1)
nums2_counter = collections.Counter(nums2)
result = []
for k in nums1_counter.keys():
if k in nums2_counter:
result.extend([k] * min(nums1_counter[k], nu... |
class CandidateViewer:
def __init__(self, df):
self.df = df
def show_candidates(self):
best_players_selections = ['2 players', '3 players', '4 players', '5 or more players']
weight_selections = [(1, 1.4), (1.5, 1.9), (1.9, 2.5), (2.5, 3.1), (3.1, 4)]
cols = ['title', 'year', 'w... | class Candidateviewer:
def __init__(self, df):
self.df = df
def show_candidates(self):
best_players_selections = ['2 players', '3 players', '4 players', '5 or more players']
weight_selections = [(1, 1.4), (1.5, 1.9), (1.9, 2.5), (2.5, 3.1), (3.1, 4)]
cols = ['title', 'year', 'w... |
def main():
q = int(input())
pre = [
3, 5, 13, 37, 61, 73, 157, 193, 277, 313, 397, 421, 457, 541, 613, 661, 673, 733, 757, 877, 997, 1093, 1153, 1201, 1213, 1237, 1321, 1381, 1453, 1621, 1657, 1753, 1873, 1933, 1993, 2017, 2137, 2341, 2473, 2557, 2593, 2797, 2857, 2917,
3061, 3217, 3253, 3313, ... | def main():
q = int(input())
pre = [3, 5, 13, 37, 61, 73, 157, 193, 277, 313, 397, 421, 457, 541, 613, 661, 673, 733, 757, 877, 997, 1093, 1153, 1201, 1213, 1237, 1321, 1381, 1453, 1621, 1657, 1753, 1873, 1933, 1993, 2017, 2137, 2341, 2473, 2557, 2593, 2797, 2857, 2917, 3061, 3217, 3253, 3313, 3517, 3733, 4021,... |
# pkg.mod
# descr
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: timestamp
#
# Copyright (C) 2013 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
"""
##########################################################################
## Imports
##... | """
""" |
class FileListing:
dictionary: dict
def __init__(self, dictionary: dict):
self.dictionary = dictionary
def __eq__(self, other):
return self.dictionary == other.dictionary
def __repr__(self):
return {'dictionary': self.dictionary}
@property
def tenant(self):
re... | class Filelisting:
dictionary: dict
def __init__(self, dictionary: dict):
self.dictionary = dictionary
def __eq__(self, other):
return self.dictionary == other.dictionary
def __repr__(self):
return {'dictionary': self.dictionary}
@property
def tenant(self):
re... |
# Builds
#T# Table of contents
#C# Compiling to bytecode
#C# Building a project to binary
#T# Beginning of content
#C# Compiling to bytecode
# |-------------------------------------------------------------
#T# Python code is compiled from .py source code files, to .pyc bytecode files
#T# in the operating syste... | print('Built') |
def get_profile(name, age: int, *sports, **awards):
if type(age) != int:
raise ValueError
if len(sports) > 5:
raise ValueError
if sports and not awards:
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports}
if not sports and award... | def get_profile(name, age: int, *sports, **awards):
if type(age) != int:
raise ValueError
if len(sports) > 5:
raise ValueError
if sports and (not awards):
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports}
if not sports and awards:
r... |
a = int(input("a= "))
b = int(input("b= "))
c = int(input("c= "))
if a == 0:
if b != 0:
print("La solution est", -c / b)
else:
if c == 0:
print("INF")
else:
print("Aucune solution")
else:
delta = (b ** 2) - 4 * a * c
if delta > 0:
print(
... | a = int(input('a= '))
b = int(input('b= '))
c = int(input('c= '))
if a == 0:
if b != 0:
print('La solution est', -c / b)
elif c == 0:
print('INF')
else:
print('Aucune solution')
else:
delta = b ** 2 - 4 * a * c
if delta > 0:
print('Les deux solutions sont ', (-b - del... |
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 6
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
N = 100
return sum(i for i in range(N+1))**2 - sum(i**2 for i in range(N+1))
if __name__ == "__main__":
print(run())
| """
Solution to Project Euler problem 6
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
n = 100
return sum((i for i in range(N + 1))) ** 2 - sum((i ** 2 for i in range(N + 1)))
if __name__ == '__main__':
print(run()) |
# --
# Copyright (c) 2008-2021 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --
class SessionError(LookupError):
def name(self):
return self.__class__.__name__
# ... | class Sessionerror(LookupError):
def name(self):
return self.__class__.__name__
class Criticalsessionerror(SessionError):
pass
class Lockerror(CriticalSessionError):
"""Raised when an exclusive lock on a session can't be acquired
"""
pass
class Stateerror(CriticalSessionError):
"""Ra... |
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
s = set()
for v in arr:
if v * 2 in s or (v % 2 == 0 and v / 2 in s): return True
s.add(v)
return False
| class Solution:
def check_if_exist(self, arr: List[int]) -> bool:
s = set()
for v in arr:
if v * 2 in s or (v % 2 == 0 and v / 2 in s):
return True
s.add(v)
return False |
n = int(input("Dame un numero entero: "))
def factorial( n ):
if n == 1:
return n
else:
#llamada recursiva
return n * factorial( n - 1 )
print("El factorial de: ",n,"es", factorial(n)) | n = int(input('Dame un numero entero: '))
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n - 1)
print('El factorial de: ', n, 'es', factorial(n)) |
#!/bin/python3
rd = open("06.input", "r")
fullSum = 0
validLetters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }
while True:
letters = {}
count = 0
while True:
line = rd.readline().strip()
if not li... | rd = open('06.input', 'r')
full_sum = 0
valid_letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
while True:
letters = {}
count = 0
while True:
line = rd.readline().strip()
if not line or line == '':
... |
'''
done
'''
ipAddress = '127.0.0.1'
port = 21
name = "Pustakalupi"
pi = 3.14 #tidak ada constant dalam Python 3
print("ipAddress bertipe :", type(ipAddress))
print("port bertipe :", type(port))
print("name bertipe :", type(name))
print("pi bertipe :", type(pi))
print(pi)
del pi
print(pi) | """
done
"""
ip_address = '127.0.0.1'
port = 21
name = 'Pustakalupi'
pi = 3.14
print('ipAddress bertipe :', type(ipAddress))
print('port bertipe :', type(port))
print('name bertipe :', type(name))
print('pi bertipe :', type(pi))
print(pi)
del pi
print(pi) |
class Originator:
_state = None
class Memento:
def __init__(self, state):
self._state = state
def setState(self, state):
self._state = state
def getState(self):
return self._state
def __init__(self, state = None):
self._state = state
... | class Originator:
_state = None
class Memento:
def __init__(self, state):
self._state = state
def set_state(self, state):
self._state = state
def get_state(self):
return self._state
def __init__(self, state=None):
self._state = state
... |
# please excuse me, I'm a C# and Rust developer with only minor Python experience :D
# let's give it a go though!
MAP = {
'a': "100000", 'n': "101110",
'b': "110000", 'o': "101010",
'c': "100100", 'p': "111100",
'd': "100110", 'q': "111110",
'e': "100010", 'r': "111010",
'f': "110100", 's': "01... | map = {'a': '100000', 'n': '101110', 'b': '110000', 'o': '101010', 'c': '100100', 'p': '111100', 'd': '100110', 'q': '111110', 'e': '100010', 'r': '111010', 'f': '110100', 's': '011100', 'g': '110110', 't': '011110', 'h': '110010', 'u': '101001', 'i': '010100', 'v': '111001', 'j': '010110', 'w': '010111', 'k': '101000'... |
"""
252. Meeting Rooms
Easy
Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: true
Constraints:
0 <= intervals.... | """
252. Meeting Rooms
Easy
Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: true
Constraints:
0 <= intervals.... |
# Desafio066: Desafio criar um programa que leia varios numeros de o valor total digitado e pare quando digitado 999.
nu = int (0)
controle = int(0)
print('Se precisar sair digite 999')
while True:
nu = int(input('Digite um numero '))
if nu == 999:
break
controle = controle + nu
print(controle)
| nu = int(0)
controle = int(0)
print('Se precisar sair digite 999')
while True:
nu = int(input('Digite um numero '))
if nu == 999:
break
controle = controle + nu
print(controle) |
__author__ = 'tony petrov'
DEFAULT_SOCIAL_MEDIA_CYCLE = 3600 # 1 hour since most social media websites have a 1 hour timeout
# tasks
TASK_EXPLORE = 0
TASK_BULK_RETRIEVE = 1
TASK_FETCH_LISTS = 2
TASK_FETCH_USER = 3
TASK_UPDATE_WALL = 4
TASK_FETCH_STREAM = 5
TASK_GET_DASHBOARD = 6
TASK_GET_TAGGED = 7
TASK_GET_BLOG_POST... | __author__ = 'tony petrov'
default_social_media_cycle = 3600
task_explore = 0
task_bulk_retrieve = 1
task_fetch_lists = 2
task_fetch_user = 3
task_update_wall = 4
task_fetch_stream = 5
task_get_dashboard = 6
task_get_tagged = 7
task_get_blog_posts = 8
task_get_facebook_wall = 9
task_fetch_facebook_users = 10
task_twitt... |
class Professor:
def __init__(self, nome):
self.__nome = nome #conceito de encapusulamento
self.__salaDeAula = None
def nome(self):
return self.__nome
def salaDeAula(self, sala):
self.__salaDeAula = sala
def EmAula(self):
return 'Em aula'
class Sala:
... | class Professor:
def __init__(self, nome):
self.__nome = nome
self.__salaDeAula = None
def nome(self):
return self.__nome
def sala_de_aula(self, sala):
self.__salaDeAula = sala
def em_aula(self):
return 'Em aula'
class Sala:
def __init__(self, numero):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def init():
pass
def servers():
return {}
| def init():
pass
def servers():
return {} |
def processArray(l2):
loss=[];mloss=0
for i in range(0,len(l2)):
loss.append(l2[i][0]-l2[i][len(l2[i])-1])
if(len(loss)>0):
mloss=loss.index(max(loss))
print(len(l2[mloss]))
l=[]
while True:
a=int(input())
if(a<0):
break
l.append(a)
ans=[]
i=0
while(i<len(l)):
k=l[i]
tmp=[... | def process_array(l2):
loss = []
mloss = 0
for i in range(0, len(l2)):
loss.append(l2[i][0] - l2[i][len(l2[i]) - 1])
if len(loss) > 0:
mloss = loss.index(max(loss))
print(len(l2[mloss]))
l = []
while True:
a = int(input())
if a < 0:
break
l.append(a)
ans = []
i = ... |
class Solution:
def hammingWeight(self, n: int) -> int:
n = bin(n)[2:]
str_n = str(n)
return str_n.count("1")
| class Solution:
def hamming_weight(self, n: int) -> int:
n = bin(n)[2:]
str_n = str(n)
return str_n.count('1') |
def coordinate_input():
x, y = input("X, Y Coordinates ==> ").strip().split(",")
return float(x), float(y)
def main():
coordinates = []
print("Type the coordinates in order; it means A,B,C...")
while True:
try:
point = coordinate_input()
coordinates.append(point)
... | def coordinate_input():
(x, y) = input('X, Y Coordinates ==> ').strip().split(',')
return (float(x), float(y))
def main():
coordinates = []
print('Type the coordinates in order; it means A,B,C...')
while True:
try:
point = coordinate_input()
coordinates.append(point)... |
''' Exemplo 1
c = 1
while c < 11:
print(c)
c += 1
print('Fim')
'''
'''eXEMPLO 2
n = 1
while n!= 0:
n = int(input('Digite um valor: '))
print('Fim') '''
''' Exemplo 3
r = 'S'
while r == 'S':
n = int(input('Digite um valor: '))
r = str(input('Quer continuar? [S/N] ')).upper()
print('Fim')'''
''' Exem... | """ Exemplo 1
c = 1
while c < 11:
print(c)
c += 1
print('Fim')
"""
"eXEMPLO 2 \nn = 1\nwhile n!= 0:\n n = int(input('Digite um valor: '))\nprint('Fim') "
" Exemplo 3\nr = 'S'\nwhile r == 'S':\n n = int(input('Digite um valor: '))\n r = str(input('Quer continuar? [S/N] ')).upper()\nprint('Fim')"
" Exemp... |
#!/home/user/code/Django-Sample/django_venv/bin/python2.7
# EASY-INSTALL-SCRIPT: 'Django==1.11.3','django-admin.py'
__requires__ = 'Django==1.11.3'
__import__('pkg_resources').run_script('Django==1.11.3', 'django-admin.py')
| __requires__ = 'Django==1.11.3'
__import__('pkg_resources').run_script('Django==1.11.3', 'django-admin.py') |
def LB2idx(lev, band, nlevs, nbands):
''' convert level and band to dictionary index '''
# reset band to match matlab version
band += (nbands-1)
if band > nbands-1:
band = band - nbands
if lev == 0:
idx = 0
elif lev == nlevs-1:
# (Nlevels - ends)*Nbands + ends -1 (becaus... | def lb2idx(lev, band, nlevs, nbands):
""" convert level and band to dictionary index """
band += nbands - 1
if band > nbands - 1:
band = band - nbands
if lev == 0:
idx = 0
elif lev == nlevs - 1:
idx = (nlevs - 2) * nbands + 2 - 1
else:
idx = nbands * lev - band - ... |
# https://www.hackerrank.com/challenges/s10-standard-deviation/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input().strip())
all1 = [int(i) for i in input().strip().split()]
u = sum(all1) / n
v = sum(((i - u) ** 2) for i in all1)/n
sd = v ** 0.5
print("{0:0.1f}".forma... | n = int(input().strip())
all1 = [int(i) for i in input().strip().split()]
u = sum(all1) / n
v = sum(((i - u) ** 2 for i in all1)) / n
sd = v ** 0.5
print('{0:0.1f}'.format(sd)) |
context_mapping = {
"schema": "http://www.w3.org/2001/XMLSchema#",
"brick": "http://brickschema.org/schema/1.0.3/Brick#",
"brickFrame": "http://brickschema.org/schema/1.0.3/BrickFrame#",
"BUDO-M": "https://git.rwth-aachen.de/EBC/Team_BA/misc/Machine-Learning/tree/MA_fst-bll/building_ml_p... | context_mapping = {'schema': 'http://www.w3.org/2001/XMLSchema#', 'brick': 'http://brickschema.org/schema/1.0.3/Brick#', 'brickFrame': 'http://brickschema.org/schema/1.0.3/BrickFrame#', 'BUDO-M': 'https://git.rwth-aachen.de/EBC/Team_BA/misc/Machine-Learning/tree/MA_fst-bll/building_ml_platform/BUDO-M/Platform_Applicati... |
"""Relaydomains app constants."""
PERMISSIONS = {
"Resellers": [
("relaydomains", "relaydomain", "add_relaydomain"),
("relaydomains", "relaydomain", "change_relaydomain"),
("relaydomains", "relaydomain", "delete_relaydomain"),
("relaydomains", "service", "add_service"),
("re... | """Relaydomains app constants."""
permissions = {'Resellers': [('relaydomains', 'relaydomain', 'add_relaydomain'), ('relaydomains', 'relaydomain', 'change_relaydomain'), ('relaydomains', 'relaydomain', 'delete_relaydomain'), ('relaydomains', 'service', 'add_service'), ('relaydomains', 'service', 'change_service'), ('re... |
"""Defines error messages and functions."""
_BAD_NAME = "Bad name '{name}'."
_BAD_LITERAL = "Bad literal '{literal}'."
_NOT_IMPLEMENTED = "Not implemented:"
class CheckError(Exception):
def __init__(self, message):
self.message = message
def bad_name(name):
_error(_BAD_NAME, name=name)
def bad_... | """Defines error messages and functions."""
_bad_name = "Bad name '{name}'."
_bad_literal = "Bad literal '{literal}'."
_not_implemented = 'Not implemented:'
class Checkerror(Exception):
def __init__(self, message):
self.message = message
def bad_name(name):
_error(_BAD_NAME, name=name)
def bad_liter... |
OBJECT( 'VALUE',
attributes = [
A( 'ANY', 'value' ),
]
)
| object('VALUE', attributes=[a('ANY', 'value')]) |
# Reading Error Messages
# Read the Python code and the resulting traceback below,
# and answer the following questions:
# How many levels does the traceback have?
# What is the function name where the error occurred?
# On which line number in this function did the error occur?
# What is the type of error?
# What is... | def print_message(day):
messages = {'monday': 'Hello, world!', 'tuesday': 'Today is Tuesday!', 'wednesday': 'It is the middle of the week.', 'thursday': 'Today is Donnerstag in German!', 'friday': 'Last day of the week!', 'saturday': 'Hooray for the weekend!', 'sunday': 'Aw, the weekend is almost over.'}
print(... |
"""
This is a config file that will be used to generate the .piwall file
"""
# Network information
master_ip = "0.0.0.0"
# Wall.py for PiWall
configs = {
'walls': {
'wall_name': {
'name': 'wall_name',
'height': '270',
'width': '1080',
'master_ip': '0.0.0.0'
... | """
This is a config file that will be used to generate the .piwall file
"""
master_ip = '0.0.0.0'
configs = {'walls': {'wall_name': {'name': 'wall_name', 'height': '270', 'width': '1080', 'master_ip': '0.0.0.0'}}, 'num_of_tiles': 4, 'tiles': [{'name': 'tile_name', 'wall': 'wall_name', 'width': '270', 'height': '270', ... |
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
return pair((lambda a, b: a))
def cdr(pair):
return pair((lambda a, b: a)) | def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
return pair(lambda a, b: a)
def cdr(pair):
return pair(lambda a, b: a) |
"""Sub-module of the package."""
def hello_world():
"""Print "Hello World"."""
print("Hello World")
| """Sub-module of the package."""
def hello_world():
"""Print "Hello World"."""
print('Hello World') |
# Testing site
base_url = 'http://localhost:80/demo'
# Login account
admin_auth_data = {'name': 'admin', 'password': 'admin'}
login_url = base_url + '/api/auth'
header = dict()
| base_url = 'http://localhost:80/demo'
admin_auth_data = {'name': 'admin', 'password': 'admin'}
login_url = base_url + '/api/auth'
header = dict() |
def add(x,y):
'''Add two nos'''
return x+y
def subtract(x,y):
'''Subtract two nos'''
return y-x
| def add(x, y):
"""Add two nos"""
return x + y
def subtract(x, y):
"""Subtract two nos"""
return y - x |
"""
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the
shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
__author__ = 'Daniel'
class Solutio... | """
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the
shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
__author__ = 'Daniel'
class Solution... |
def word2features(sent, i):
word = sent[i][0]
postag = sent[i][1]
features = [
'bias',
'word.lower=' + word.lower(),
'word[-3:]=' + word[-3:],
'word[-2:]=' + word[-2:],
'word.isupper=%s' % word.isupper(),
'word.istitle=%s' % word.istitle(),
'word.isdigit=%s' % word.isdigit(),
'postag=' + postag,
'p... | def word2features(sent, i):
word = sent[i][0]
postag = sent[i][1]
features = ['bias', 'word.lower=' + word.lower(), 'word[-3:]=' + word[-3:], 'word[-2:]=' + word[-2:], 'word.isupper=%s' % word.isupper(), 'word.istitle=%s' % word.istitle(), 'word.isdigit=%s' % word.isdigit(), 'postag=' + postag, 'postag[:2]=... |
words_single = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
words_teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
words_tens = ['','ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety... | words_single = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
words_teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
words_tens = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninet... |
#!/usr/bin/env python3
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10,001st prime number?
https://projecteuler.net/problem=7
"""
| """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10,001st prime number?
https://projecteuler.net/problem=7
""" |
def ping():
"""Always returns 'pong'."""
return 'pong'
def cowsay():
return r"""
___________________
< Hello Resource Hub! >
===================
\
\
^__^
(oo)\_______
... | def ping():
"""Always returns 'pong'."""
return 'pong'
def cowsay():
return '\n ___________________\n < Hello Resource Hub! >\n ===================\n \\\n \\\n ^__^\n (oo)\\______... |
def same_wind(history, **kwargs):
"""Set the tropopause wind at their previous values for the new state
:param history: Current history of state
:type history: :class:`History` object
"""
assert history.size > 1
previous_state = history.state_list[-2]
current_state = history.state_list[... | def same_wind(history, **kwargs):
"""Set the tropopause wind at their previous values for the new state
:param history: Current history of state
:type history: :class:`History` object
"""
assert history.size > 1
previous_state = history.state_list[-2]
current_state = history.state_list[... |
def test_Compare():
a: bool
a = 5 > 4
a = 5 <= 4
a = 5 < 4
a = 5.6 >= 5.59999
a = 3.3 == 3.3
a = 3.3 != 3.4
a = complex(3, 4) == complex(3., 4.)
| def test__compare():
a: bool
a = 5 > 4
a = 5 <= 4
a = 5 < 4
a = 5.6 >= 5.59999
a = 3.3 == 3.3
a = 3.3 != 3.4
a = complex(3, 4) == complex(3.0, 4.0) |
def spaces(n, i):
countSpace= n-i
spaces = " "*countSpace
return spaces
def staircase(n):
for i in range(1, n+1):
cadena = spaces(n,i)
steps = "#"*i
cadena = cadena+steps
print(cadena)
if __name__ == "__main__":
tamanio = int(input("Ingresa el numero de esc... | def spaces(n, i):
count_space = n - i
spaces = ' ' * countSpace
return spaces
def staircase(n):
for i in range(1, n + 1):
cadena = spaces(n, i)
steps = '#' * i
cadena = cadena + steps
print(cadena)
if __name__ == '__main__':
tamanio = int(input('Ingresa el numero de ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.