content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Function to square every digit of a number.
# Eg. 9119 will become 811181, because 9^2 is 81 and 1^2 is 1.
def square_each_number(num):
result= ''
list = [int(d) for d in str(num)]
square_list = [i ** 2 for i in list]
for i in square_list:
result += str(i)
return float(result)
test.assert... | def square_each_number(num):
result = ''
list = [int(d) for d in str(num)]
square_list = [i ** 2 for i in list]
for i in square_list:
result += str(i)
return float(result)
test.assert_equals(square_digits(9119), 811181) |
# QUESTION:
#
# This problem was asked by Google.
#
# Given the root to a binary tree, implement serialize(root), which serializes
# the tree into a string, and deserialize(s), which deserializes the string
# back into the tree.
#
# For example, given the following Node class
#
# class Node:
# def __init__(self, va... | class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def solution(L):
if not L:
return None
if len(L) < 3:
return L
for i in range(0, len(L)):
if L[i] == 0:
return None
pro... |
def reverseBits(n):
head = 15
tail = 0
while head > tail:
headBit = (n >> head) & 1
tailBit = (n >> tail) & 1
if headBit != tailBit:
bitMask = (1 << head) | (1 << tail)
n ^= bitMask
head -= 1
tail += 1
return n
| def reverse_bits(n):
head = 15
tail = 0
while head > tail:
head_bit = n >> head & 1
tail_bit = n >> tail & 1
if headBit != tailBit:
bit_mask = 1 << head | 1 << tail
n ^= bitMask
head -= 1
tail += 1
return n |
def get(s, register):
if s in 'abcdefghijklmnopqrstuvwxyz':
return register[s]
return int(s)
def solveQuestion(inputPath):
fileP = open(inputPath, 'r')
instVals = [line.split() for line in fileP.read().strip().split("\n")]
fileP.close()
registers = {}
registers[0] = {}
... | def get(s, register):
if s in 'abcdefghijklmnopqrstuvwxyz':
return register[s]
return int(s)
def solve_question(inputPath):
file_p = open(inputPath, 'r')
inst_vals = [line.split() for line in fileP.read().strip().split('\n')]
fileP.close()
registers = {}
registers[0] = {}
regist... |
PRECISION = 100
class PiCalculator(object):
def __init__(self, precision):
self.precision = precision
def divide_one_by(self, b):
divider = 1
result = ""
for x in range(self.precision):
if divider // b == 0:
divider *= 10
result += ... | precision = 100
class Picalculator(object):
def __init__(self, precision):
self.precision = precision
def divide_one_by(self, b):
divider = 1
result = ''
for x in range(self.precision):
if divider // b == 0:
divider *= 10
result += '... |
def area(a, b):
return (a * b) / 2
print(area(6, 9))
print(area(5, 8))
| def area(a, b):
return a * b / 2
print(area(6, 9))
print(area(5, 8)) |
# returns the classification or None if no classification could be determined
def calcClass(arr):
sel0 = arr[0] > 0.0
sel1 = arr[1] > 0.0
if sel0 and sel1: # is selection valid? if not then we just ignore the result!
n = 2
maxSelVal = float("-inf")
maxSelIdx = None
for iIdx i... | def calc_class(arr):
sel0 = arr[0] > 0.0
sel1 = arr[1] > 0.0
if sel0 and sel1:
n = 2
max_sel_val = float('-inf')
max_sel_idx = None
for i_idx in range(n):
if arr[iIdx] > maxSelVal:
max_sel_idx = iIdx
max_sel_val = arr[iIdx]
... |
_base_ = './faster_rcnn_obb_r50_fpn_1x_dota2.0.py'
# fp16 settings
fp16 = dict(loss_scale=512.)
| _base_ = './faster_rcnn_obb_r50_fpn_1x_dota2.0.py'
fp16 = dict(loss_scale=512.0) |
class Digraph:
def __init__(self, v):
self.v = v
self.e = 0
self.adj = [[] for _ in range(v)]
def init_from(self, file_name):
with open(file_name) as f:
self.v = int(f.readline())
self.e = int(f.readline())
self.adj = [[] for _ in range(self... | class Digraph:
def __init__(self, v):
self.v = v
self.e = 0
self.adj = [[] for _ in range(v)]
def init_from(self, file_name):
with open(file_name) as f:
self.v = int(f.readline())
self.e = int(f.readline())
self.adj = [[] for _ in range(self.... |
# -*- coding: utf-8 -*-
try:
print('enter a number')
num = int (input())
print('enter a denom')
denom = int (input())
print(str(num/denom))
#you can raise the exceptions as follows
#raise ZeroDivisionError
except ZeroDivisionError:
#except IOError:
print('Canno... | try:
print('enter a number')
num = int(input())
print('enter a denom')
denom = int(input())
print(str(num / denom))
except ZeroDivisionError:
print('Cannot divide by zero')
print('enter a number')
num = int(input())
print('enter a denom')
denom = int(input())
print(str(num / ... |
class Journal:
def __init__(self, article_title, journal_title, year_published, page_start,
page_end, volume, issue, doi_or_website):
self.article_title = article_title
self.journal_title = journal_title
self.year_published = year_published
self.page_start = page_sta... | class Journal:
def __init__(self, article_title, journal_title, year_published, page_start, page_end, volume, issue, doi_or_website):
self.article_title = article_title
self.journal_title = journal_title
self.year_published = year_published
self.page_start = page_start
self.... |
vogais = ('Aprender', 'Programar', 'Linguagem', 'Python', 'Curso', 'Gratis', 'Estudar',
'Praticar', 'Trabalhar', 'Mercado', 'Programador')
for c in range(0, len(vogais)):
print(f'\nNa palavra {vogais[c].upper()} temos: ', end=' ')
for letra in vogais[c]:
if letra.lower() in 'aeiou':
print(l... | vogais = ('Aprender', 'Programar', 'Linguagem', 'Python', 'Curso', 'Gratis', 'Estudar', 'Praticar', 'Trabalhar', 'Mercado', 'Programador')
for c in range(0, len(vogais)):
print(f'\nNa palavra {vogais[c].upper()} temos: ', end=' ')
for letra in vogais[c]:
if letra.lower() in 'aeiou':
print(le... |
#!/usr/bin/env python3
def responses(input_text):
user_message = str(input_text).lower()
if user_message in ("yes","sure","ok"):
return "Great! Let's start. First I need to know where you were born."
if user_message in ("no","naw","no thanks"):
return "That's alright, maybe another t... | def responses(input_text):
user_message = str(input_text).lower()
if user_message in ('yes', 'sure', 'ok'):
return "Great! Let's start. First I need to know where you were born."
if user_message in ('no', 'naw', 'no thanks'):
return "That's alright, maybe another time."
return "I'm Crypt... |
'''
Este snipet es para crear un generador que me permita contar hasta 100.
'''
# Retorna la lsita con todos los valores
def count_to():
yield [n for n in range(0,101) if n%2 ==0]
if __name__ == '__main__':
i = count_to()
print(next(i)) # Lista
print(next(i)) # Error StopIteration
| """
Este snipet es para crear un generador que me permita contar hasta 100.
"""
def count_to():
yield [n for n in range(0, 101) if n % 2 == 0]
if __name__ == '__main__':
i = count_to()
print(next(i))
print(next(i)) |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
low = 0
high = len(numbers)-1
while low < high:
s = numbers[low] + numbers[high]
if s == target:
return [low+1, high+1]
if s > target:
high -= ... | class Solution:
def two_sum(self, numbers: List[int], target: int) -> List[int]:
low = 0
high = len(numbers) - 1
while low < high:
s = numbers[low] + numbers[high]
if s == target:
return [low + 1, high + 1]
if s > target:
h... |
#==============================================================================
# exceptions.py
# exception handler for Exosite HTTP JSON RPC API library (man, alphabet soup)
#==============================================================================
##
## Tested with python 2.6
##
## Copyright (c) 2010, Exosite LL... | class Oneexception(Exception):
pass
class Oneplatformexception(OneException):
pass
class Jsonrpcrequestexception(OneException):
pass
class Jsonrpcresponseexception(OneException):
pass
class Jsonstringexception(OneException):
pass
class Provisionexception(OneException):
def __init__(self, p... |
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
print('Difference of ',num1 ,'and' ,num2 ,'is :',... | num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print('Sum of ', num1, 'and', num2, 'is :', add)
print('Difference of ', num1, 'and', num2, 'is ... |
#!/usr/bin/env python3
c = 100
k = int(input())
i = 0
while c<k:
c = int(c*1.01)
i += 1
print(i) | c = 100
k = int(input())
i = 0
while c < k:
c = int(c * 1.01)
i += 1
print(i) |
def parse(data):
kernel, img = data.split("\n\n")
i = set()
for y, r in enumerate(img.split()):
for x, c in enumerate(r):
if c == "#":
i.add((x, y))
return [c == "#" for c in kernel], i
def enhance(kernel, i, inverted):
inverting = kernel[0] and not inverted
... | def parse(data):
(kernel, img) = data.split('\n\n')
i = set()
for (y, r) in enumerate(img.split()):
for (x, c) in enumerate(r):
if c == '#':
i.add((x, y))
return ([c == '#' for c in kernel], i)
def enhance(kernel, i, inverted):
inverting = kernel[0] and (not inve... |
print(a)
print(b)
c = a + b
print(c)
| print(a)
print(b)
c = a + b
print(c) |
class Solution(object):
def countSubstrings(self, s):
def manacher(s):
s = '^#' + '#'.join(s) + '#$'
P = [0] * len(s)
C, R = 0, 0
for i in xrange(1, len(s) - 1):
i_mirror = 2 * C - i
if R > i:
P[i] = min(R-i,... | class Solution(object):
def count_substrings(self, s):
def manacher(s):
s = '^#' + '#'.join(s) + '#$'
p = [0] * len(s)
(c, r) = (0, 0)
for i in xrange(1, len(s) - 1):
i_mirror = 2 * C - i
if R > i:
P[i] = m... |
FG = "\033[38;5;{}m"
BG = "\033[48;5;{}m"
RST = "\033[0m"
def print_256_color_lookup_table_for(x):
if x == "foreground" or x == "fg":
x = FG
elif x == "background" or x == "bg":
x = BG
else:
raise ValueError("Unrecognized value for argument.")
for n in range(16):
# Sta... | fg = '\x1b[38;5;{}m'
bg = '\x1b[48;5;{}m'
rst = '\x1b[0m'
def print_256_color_lookup_table_for(x):
if x == 'foreground' or x == 'fg':
x = FG
elif x == 'background' or x == 'bg':
x = BG
else:
raise value_error('Unrecognized value for argument.')
for n in range(16):
print(... |
demo_list = [1, 'hello', 1.34, True, [1, 2, 3]]
colors = ['red', 'green', 'blue']
numbers_list = list((1, 2, 3, 4))
print(numbers_list)
r = list(range(1, 100))
print(r)
print(len(colors))
print(colors[1])
print('green' in colors)
print(colors)
colors[1] = 'yellow'
print(colors)
colors.append('violet')... | demo_list = [1, 'hello', 1.34, True, [1, 2, 3]]
colors = ['red', 'green', 'blue']
numbers_list = list((1, 2, 3, 4))
print(numbers_list)
r = list(range(1, 100))
print(r)
print(len(colors))
print(colors[1])
print('green' in colors)
print(colors)
colors[1] = 'yellow'
print(colors)
colors.append('violet')
colors.extend(['v... |
# Leetcode Problem Link:
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: '... | class Solution:
def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if... |
'''
I=1 J=7
I=1 J=6
I=1 J=5
'''
i = 1
j = 7
while i < 10:
print("I={} J={}".format(i, j))
if j == 5:
i = i + 2
j = 7
else:
j = j - 1 | """
I=1 J=7
I=1 J=6
I=1 J=5
"""
i = 1
j = 7
while i < 10:
print('I={} J={}'.format(i, j))
if j == 5:
i = i + 2
j = 7
else:
j = j - 1 |
# MIT License
#
# Copyright (c) 2020-2021 Markus Prasser
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | class Biblebookstable:
bible_books = ('Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua', 'Judges', 'Ruth', '1 Samuel', '2 Samuel', '1 Kings', '2 Kings', '1 Chronicles', '2 Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job', 'Psalms', 'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', 'Jeremia... |
def max_heapify(A,k):
l = left(k)
m = middle(k)
r = right(k)
largest = k
if l < len(A) and A[l] > A[k]:
largest = l
else:
largest = k
if r < len(A) and A[r] > A[largest]:
largest = r
if m < len(A) and A[m] > A[largest]:
largest = m
if largest != k:
... | def max_heapify(A, k):
l = left(k)
m = middle(k)
r = right(k)
largest = k
if l < len(A) and A[l] > A[k]:
largest = l
else:
largest = k
if r < len(A) and A[r] > A[largest]:
largest = r
if m < len(A) and A[m] > A[largest]:
largest = m
if largest != k:
... |
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def remove_from_list(value, listHead):
curr = listHead
prev = None
while curr:
if curr.value > value:
if prev:
prev.next = curr.next
else:
... | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def remove_from_list(value, listHead):
curr = listHead
prev = None
while curr:
if curr.value > value:
if prev:
prev.next = curr.next
else:
... |
# recursive approach to find the number of set
# bits in binary representation of positive integer n
def count_set_bits(n):
if (n == 0):
return 0
else:
return (n & 1) + count_set_bits(n >> 1)
# Get value from user
n = 41
# Function calling
print(count_set_bits(n... | def count_set_bits(n):
if n == 0:
return 0
else:
return (n & 1) + count_set_bits(n >> 1)
n = 41
print(count_set_bits(n)) |
APPLICATION_GOOD_BODY = {
'information': {
'first_name': 'Andrew James',
'last_name': 'McLeod',
'date_of_birth': '1987-03-04',
'addresses': [
{
'address': '3023 BODEGA ROAD',
'city': 'VICTORIA',
'province_state': 'BC',
... | application_good_body = {'information': {'first_name': 'Andrew James', 'last_name': 'McLeod', 'date_of_birth': '1987-03-04', 'addresses': [{'address': '3023 BODEGA ROAD', 'city': 'VICTORIA', 'province_state': 'BC', 'country': 'CA'}]}}
auth_response = {'token': 'e5e4c777acb3c2a4e4234a282a8ac507c0be24708e6dfe121de563dda3... |
ENCRYPTION_FILE_CHUNK_SIZE = 64 * 1024 # 64K
ENCRYPTION_KEY_DERIVATION_ITERATIONS = 100000
ENCRYPTION_KEY_SIZE = 32
ZIP_CHUNK_SIZE = 64 * 1024 # 64K
ZIP_MEMBER_FILENAME = 'mayan_file'
| encryption_file_chunk_size = 64 * 1024
encryption_key_derivation_iterations = 100000
encryption_key_size = 32
zip_chunk_size = 64 * 1024
zip_member_filename = 'mayan_file' |
'''lst=[x for x in range(2,21,2)]
print(lst)'''
lst=[x for x in range(1,21) if x%2==0]
print(lst) | """lst=[x for x in range(2,21,2)]
print(lst)"""
lst = [x for x in range(1, 21) if x % 2 == 0]
print(lst) |
#multiple if statements (IBM Digital Nation Africa)
num = 72.5
if num > 0 :
print ("The Number is positive")
if num > 20 :
print("The Number is greater than 20")
| num = 72.5
if num > 0:
print('The Number is positive')
if num > 20:
print('The Number is greater than 20') |
# The Project
# Master Ticket
TICKET_PRICE = 10
tickets_remaining = 100
# Notify the user that the tickets are sold out if the tickets remaining is 0
if tickets_remaining == 0:
print("I'm sorry we are sold out!")
# Run this code continuously until we run out of tickets
while tickets_remaining >= 1:
# Output how... | ticket_price = 10
tickets_remaining = 100
if tickets_remaining == 0:
print("I'm sorry we are sold out!")
while tickets_remaining >= 1:
print('There are {} tickets remaining.'.format(tickets_remaining))
user_name = input('What is your name? ')
tickets_requested = input('How many tickets would you like... |
del_items(0x80116458)
SetType(0x80116458, "int NumOfMonsterListLevels")
del_items(0x800A375C)
SetType(0x800A375C, "struct MonstLevel AllLevels[16]")
del_items(0x80116174)
SetType(0x80116174, "unsigned char NumsLEV1M1A[4]")
del_items(0x80116178)
SetType(0x80116178, "unsigned char NumsLEV1M1B[4]")
del_items(0x8011617C)
S... | del_items(2148623448)
set_type(2148623448, 'int NumOfMonsterListLevels')
del_items(2148153180)
set_type(2148153180, 'struct MonstLevel AllLevels[16]')
del_items(2148622708)
set_type(2148622708, 'unsigned char NumsLEV1M1A[4]')
del_items(2148622712)
set_type(2148622712, 'unsigned char NumsLEV1M1B[4]')
del_items(214862271... |
# ------------------------------------
# CODE BOOLA 2015 PYTHON WORKSHOP
# Mike Wu, Jonathan Chang, Kevin Tan
# Puzzle Challenges Number 4
# ------------------------------------
# Wow! You are doing this way faster
# than I thought you would. Slooooow
# doooowwwwwnnn...
# ------------------------------------
# IN... | def reverse(s):
pass |
# import pytest
class TestTranslator:
def test___call__(self): # synced
assert True
def test_translate(self): # synced
assert True
def test_translate_recursively(self): # synced
assert True
def test_translate_json(self): # synced
assert True
class TestTranslata... | class Testtranslator:
def test___call__(self):
assert True
def test_translate(self):
assert True
def test_translate_recursively(self):
assert True
def test_translate_json(self):
assert True
class Testtranslatablemeta:
pass
class Testdonottranslatemeta:
pass |
class RBTreeNode:
def __init__(self, val, parent=None):
self.val = val
self.black = True
self.left = None
self.right = None
self.parent = parent
class RBTree:
def __init__(self):
self.root = None
def get_root(self):
return self.root
def insert(... | class Rbtreenode:
def __init__(self, val, parent=None):
self.val = val
self.black = True
self.left = None
self.right = None
self.parent = parent
class Rbtree:
def __init__(self):
self.root = None
def get_root(self):
return self.root
def insert... |
__all__ = ['gmrt_raw_toguppi']
class GUPPIINJ:
def __init__(self, guppifile) -> None:
self.header = self.header_dict()
self.guppifile = guppifile
# def bbinj(self,d):# samples_per_frame=960, pktsize=1024,npol=2, nchan=4):
# hdr = {k: self.header[k] for k in self.header if self.h... | __all__ = ['gmrt_raw_toguppi']
class Guppiinj:
def __init__(self, guppifile) -> None:
self.header = self.header_dict()
self.guppifile = guppifile
@classmethod
def header_dict(cls, par=None):
cls._header = header()
_dict = cls._header.__dict__
att = attr_dict()
... |
#ticTacToe.py
#Written by Jesse Gallarzo
gameGrid = [[' ' for i in range(3)] for j in range(3)]
gameOver = False
answer = str()
def gameRules():
print('Whoever matches three of a kind in a row or column wins! Place either an X or an O within the grid')
def printGrid():
print('|'+gameGrid[0][0]+'|'+gameGrid[0... | game_grid = [[' ' for i in range(3)] for j in range(3)]
game_over = False
answer = str()
def game_rules():
print('Whoever matches three of a kind in a row or column wins! Place either an X or an O within the grid')
def print_grid():
print('|' + gameGrid[0][0] + '|' + gameGrid[0][1] + '|' + gameGrid[0][2] + '|... |
# terrascript/data/bgpat/dnsimple.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:15:28 UTC)
__all__ = []
| __all__ = [] |
INFO = {
"name": "hi",
"description": "Membalas dengan hello",
"visibility": "public",
"authority": "all"
}
async def execute(client, message):
message_chat = message.chat
await client.send_message(
message_chat.id,
"Hello"
) | info = {'name': 'hi', 'description': 'Membalas dengan hello', 'visibility': 'public', 'authority': 'all'}
async def execute(client, message):
message_chat = message.chat
await client.send_message(message_chat.id, 'Hello') |
class Connection(object):
def open(self):
pass
def close(self):
pass
| class Connection(object):
def open(self):
pass
def close(self):
pass |
#
# PySNMP MIB module XEDIA-DVMRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-DVMRP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:42:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, constraints_intersection, value_range_constraint) ... |
# https://www.codewars.com/kata/52597aa56021e91c93000cb0/train/python
def move_zeros(array: list) -> list:
return [x for x in array if x != 0] + [0] * array.count(0)
# -----------------------------------------------------------------------------
tests = [
{
'assertion': move_zeros([1, 2, 0, 1, 0, 1, ... | def move_zeros(array: list) -> list:
return [x for x in array if x != 0] + [0] * array.count(0)
tests = [{'assertion': move_zeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1]), 'expected': [1, 2, 1, 1, 3, 1, 0, 0, 0, 0]}, {'assertion': move_zeros([9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]), 'expected': [9, 9, 1... |
__author__ = 'slaviann'
TEMPLATES = (
"ddos.list",
"domains.list",
"domains_ssl.list",
"suspend.list"
)
| __author__ = 'slaviann'
templates = ('ddos.list', 'domains.list', 'domains_ssl.list', 'suspend.list') |
NEEDLESS_ATTRS = ['op', 'desc', 'id', 'swap', 'trainable', 'ctx', 'event',
'inplace', 'lazy_execution', 'on_cpu', 'on_gpu', 'compute', 'middle_result', 'gpu_buffer',
]
ONNX_DOMAIN = ""
AI_ONNX_ML_DOMAIN = "ai.onnx.ml"
| needless_attrs = ['op', 'desc', 'id', 'swap', 'trainable', 'ctx', 'event', 'inplace', 'lazy_execution', 'on_cpu', 'on_gpu', 'compute', 'middle_result', 'gpu_buffer']
onnx_domain = ''
ai_onnx_ml_domain = 'ai.onnx.ml' |
class InvalidAPIKey(Exception):
pass
class GatewayError(Exception):
pass
class TooManyRequests(Exception):
pass
| class Invalidapikey(Exception):
pass
class Gatewayerror(Exception):
pass
class Toomanyrequests(Exception):
pass |
def db_field(**options):
def _exec(client, *args, **kwargs):
pass
return _exec
| def db_field(**options):
def _exec(client, *args, **kwargs):
pass
return _exec |
'''
Given n friends, each one can remain single or can be paired up with some other friend.
Each friend can be paired only once.
Find out the total number of ways in which friends can remain single or can be paired up.
Input : n = 3
Output : 4
Explanation
{1}, {2}, {3} : all single
{1}, {2, 3} : 2 and 3 paired but 1 ... | """
Given n friends, each one can remain single or can be paired up with some other friend.
Each friend can be paired only once.
Find out the total number of ways in which friends can remain single or can be paired up.
Input : n = 3
Output : 4
Explanation
{1}, {2}, {3} : all single
{1}, {2, 3} : 2 and 3 paired but 1 ... |
def insert_shift_array(l,b):
middle = len(l) // 2
if len(l) % 2 == 0:
return l[:middle] + [b] + l[middle:]
else:
return l[:middle + 1] + [b] + l[middle +1:]
| def insert_shift_array(l, b):
middle = len(l) // 2
if len(l) % 2 == 0:
return l[:middle] + [b] + l[middle:]
else:
return l[:middle + 1] + [b] + l[middle + 1:] |
boxes = [ ]
c = 0
for line in open( 'input.txt', 'r' ):
line = line.strip( )
if c == 0:
boxes.append( line )
c += 1
continue
for old_line in boxes:
diffs = 0
for i in range( len( old_line ) ):
if old_line[ i ] != line[ i ]:
diffs += 1
same_char = old_line[ i ]
#print( ---\n{0}\n{1}\n{2... | boxes = []
c = 0
for line in open('input.txt', 'r'):
line = line.strip()
if c == 0:
boxes.append(line)
c += 1
continue
for old_line in boxes:
diffs = 0
for i in range(len(old_line)):
if old_line[i] != line[i]:
diffs += 1
sam... |
# https://www.youtube.com/watch?v=-VpH54mhSu4&list=PL5TJqBvpXQv6TtedyS_a_pJK2uVrksh7D&index=3
def solve(A):
# [-2, 1, 2, 3, 5, -4]
min, max = 0, 0
# min, max = A[0], A[0] Other way to start beginning from the first position
for value in A:
if value <= min:
min = value
if v... | def solve(A):
(min, max) = (0, 0)
for value in A:
if value <= min:
min = value
if value >= max:
max = value
return min + max
a = [-2, 1, 2, 3, 5, -4]
b = [-4, -2, 1, 5, 10, 20, -15]
print(solve(A))
print(solve(B)) |
__version__ = "0.2.0"
__description__ = "Download data from Refinitiv Tick History and compute some market microstructure measures."
__author__ = "Mingze Gao"
__author_email__ = "mingze.gao@sydney.edu.au"
# __github_url__ = "https://github.com/mgao6767/mktstructure"
| __version__ = '0.2.0'
__description__ = 'Download data from Refinitiv Tick History and compute some market microstructure measures.'
__author__ = 'Mingze Gao'
__author_email__ = 'mingze.gao@sydney.edu.au' |
class Graph:
def __init__(self, v):
self.v = v
self.e = 0
self.adj = [[] for _ in range(v)]
def add_edge(self, v, w):
self.adj[v].append(w)
self.adj[w].append(v)
self.e += 1
def get_v(self):
return self.v
def det_e(self):
return self.e
... | class Graph:
def __init__(self, v):
self.v = v
self.e = 0
self.adj = [[] for _ in range(v)]
def add_edge(self, v, w):
self.adj[v].append(w)
self.adj[w].append(v)
self.e += 1
def get_v(self):
return self.v
def det_e(self):
return self.e
... |
# ------------------------------------------------------------
# MC911 - Compiler construction laboratory.
# IC - UNICAMP
#
# RA094139 - Marcelo Mingatos de Toledo
# RA093175 - Victor Fernando Pompeo Barbosa
#
# ------------------------------------------------------------
class LyaColor:
HEADER = '\033[95m'
O... | class Lyacolor:
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m' |
def print_tasks():
print("The available tasks are:")
for t in list_of_tasks:
print(display_full_task(t))
'''
for x in range(0, num_tasks):
n = input("\ninput name: \n") #Customize Questions
t = input("input time: \n")
c = input("input category: \n")
task=task_list(n,t,c)
... | def print_tasks():
print('The available tasks are:')
for t in list_of_tasks:
print(display_full_task(t))
'\nfor x in range(0, num_tasks):\n n = input("\ninput name: \n") #Customize Questions\n t = input("input time: \n")\n c = input("input category: \n")\n\n task=task_list(n,t,c)\n\n list... |
# Given a singly linked list and an integer k, remove the kth last element from
# the list. k is guaranteed to be smaller than the length of the list.
# The list is very long, so making more than one pass is prohibitively expensive.
class Node:
def __init__(self, value):
self.value = value
... | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Linklist:
def __init__(self, values):
self.length = 0
self.head = None
if values:
current = self.head = node(values[0])
self.length += 1
for v in values... |
def test_Dataset(mocker):
pass
| def test__dataset(mocker):
pass |
# Fibonacci series
# 0,1,1,2,3,5,8,13,21...
try:
term_number = int(input('Enter Term Number : '))
except:
print('Please Enter A Valid Integer')
quit()
n1, n2 = 0, 1
count = 0
if term_number <= 0:
print('Please enter a positive integer')
elif term_number == 1:
print('Fibonacci Series')
print(n1... | try:
term_number = int(input('Enter Term Number : '))
except:
print('Please Enter A Valid Integer')
quit()
(n1, n2) = (0, 1)
count = 0
if term_number <= 0:
print('Please enter a positive integer')
elif term_number == 1:
print('Fibonacci Series')
print(n1)
else:
print('Fibonacci Series')
... |
def floyd(num_vertice, graph):
distance = graph #to keep the distances of the graph
for target in range(num_vertice): #going thro all vertices
for i in range(num_vertice): #go thro row
for j in range(num_vertice):#go thro column
distance[i][j] = min(distance[i][j], distance[i... | def floyd(num_vertice, graph):
distance = graph
for target in range(num_vertice):
for i in range(num_vertice):
for j in range(num_vertice):
distance[i][j] = min(distance[i][j], distance[i][target] + distance[target][i]) |
class NoSuchListenerError(Exception):
pass
class NoSuchEventError(Exception):
pass
class InvalidHandlerError(Exception):
pass
| class Nosuchlistenererror(Exception):
pass
class Nosucheventerror(Exception):
pass
class Invalidhandlererror(Exception):
pass |
def packbits(myarray, axis=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def unpackbits(myarray, axis=None):
# TODO(beam2d): Implement it
raise NotImplementedError
| def packbits(myarray, axis=None):
raise NotImplementedError
def unpackbits(myarray, axis=None):
raise NotImplementedError |
upper_code = ''
lower_code = ''
currentBlock = True
f = open('code.slice','r')
p = f.read().splitlines()
for i in p:
if i == '[upper]':
currentBlock = True
continue
if i == '[end]':
continue
if i == '[lower]':
currentBlock = False
continue
if i == '[endFile]':... | upper_code = ''
lower_code = ''
current_block = True
f = open('code.slice', 'r')
p = f.read().splitlines()
for i in p:
if i == '[upper]':
current_block = True
continue
if i == '[end]':
continue
if i == '[lower]':
current_block = False
continue
if i == '[endFile]':... |
def listify(obj):
if obj is None:
return []
if isinstance(obj, (list, tuple)):
return obj
return [obj]
| def listify(obj):
if obj is None:
return []
if isinstance(obj, (list, tuple)):
return obj
return [obj] |
renterData = {
'Topshop': {
'totalSqm': 2400,
'term': 120, # month
'isGuaranteed': False,
'initialRent': 2000000, # in euro
'initialRentPerSqm': 833,
'annualIncrease': 0.025,
'abatement': 0, # in month
'TI': 200, # TI per sqm
'equityMultiple': ... | renter_data = {'Topshop': {'totalSqm': 2400, 'term': 120, 'isGuaranteed': False, 'initialRent': 2000000, 'initialRentPerSqm': 833, 'annualIncrease': 0.025, 'abatement': 0, 'TI': 200, 'equityMultiple': {'unleveraged': 2.92, 'lenderA': 2.11, 'lenderB': 2.52}, 'IRR': {'unleveraged': 0.51, 'lenderA': 0.66, 'lenderB': 0.49}... |
'''
This module is home to the IOManager class, which manages the various input
and output formats (specifically, FASTA, FASTQ, CLUSTAL alignments, and GFF
files, currently).
'''
class IOManager(object):
'''
A class used by the `IOBase` class to manage the various input and output
methods for the differen... | """
This module is home to the IOManager class, which manages the various input
and output formats (specifically, FASTA, FASTQ, CLUSTAL alignments, and GFF
files, currently).
"""
class Iomanager(object):
"""
A class used by the `IOBase` class to manage the various input and output
methods for the different... |
class URLOpener(object):
def __init__(self, x):
self.x = x
def urlopen(self):
return file(self.x) | class Urlopener(object):
def __init__(self, x):
self.x = x
def urlopen(self):
return file(self.x) |
class Repository:
def __init__(self, RepositoryAffiliation, user, data):
self.__userLogin = user.loginUser
self.__userId = user.id
self.__repositoryAffiliation = RepositoryAffiliation
self.__url = data['url']
self.__isFork = data['isFork']
self.__pushedAt = data['push... | class Repository:
def __init__(self, RepositoryAffiliation, user, data):
self.__userLogin = user.loginUser
self.__userId = user.id
self.__repositoryAffiliation = RepositoryAffiliation
self.__url = data['url']
self.__isFork = data['isFork']
self.__pushedAt = data['pus... |
def minesweeper(matrix):
x_axis, y_axis = len(matrix[0]), len(matrix)
new_matrix = []
for y in range(y_axis):
line = []
for x in range(x_axis):
neighbour = []
if x > 0:
neighbour.append(matrix[y][x-1])
if y > 0:
neig... | def minesweeper(matrix):
(x_axis, y_axis) = (len(matrix[0]), len(matrix))
new_matrix = []
for y in range(y_axis):
line = []
for x in range(x_axis):
neighbour = []
if x > 0:
neighbour.append(matrix[y][x - 1])
if y > 0:
... |
# get user email
email = input("What is your email address?:").strip()
# slice out user name
user = email[:email.index("@")]
# slice out domain name
domain = email[email.index("@")+1:]
# format message
output = "Your username is {} and you domain name is {}".format(user,domain)
# display output message
print(o... | email = input('What is your email address?:').strip()
user = email[:email.index('@')]
domain = email[email.index('@') + 1:]
output = 'Your username is {} and you domain name is {}'.format(user, domain)
print(output) |
class Computer:
def __init__(self):
self.name = "Shihab"
self.age = 18
def compare(self, other):
return self.age == other.age
c1 = Computer()
c1.age = 30
c2 = Computer()
c1.name = "Rashi"
if c1.compare(c2):
print("They are same")
else:
print("They are not same")
| class Computer:
def __init__(self):
self.name = 'Shihab'
self.age = 18
def compare(self, other):
return self.age == other.age
c1 = computer()
c1.age = 30
c2 = computer()
c1.name = 'Rashi'
if c1.compare(c2):
print('They are same')
else:
print('They are not same') |
class points:
user = []
points = []
def addUser(self, user, points):
try:
index = self.getIndex(user)
except:
index = -1
if index < 0:
self.user.append(user)
self.points.append(points)
return 'User ' + user + ... | class Points:
user = []
points = []
def add_user(self, user, points):
try:
index = self.getIndex(user)
except:
index = -1
if index < 0:
self.user.append(user)
self.points.append(points)
return 'User ' + user + ' added with ... |
#!/usr/bin/python
# splitting.py
nums = "1,5,6,8,2,3,1,9"
k = nums.split(",")
print (k)
l = nums.split(",", 5)
print (l)
m = nums.rsplit(",", 3)
print (m)
| nums = '1,5,6,8,2,3,1,9'
k = nums.split(',')
print(k)
l = nums.split(',', 5)
print(l)
m = nums.rsplit(',', 3)
print(m) |
# Name, Variables, Functions
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
print(f"Type1: {type(arg1)}. Type2: {type(arg2)}")
def print_take_2(one, two):
print(f"Value1: {one}, Value2: {two}")
def print_take_1(one):
print(f"Value: {one}")
def print_none():
... | def print_two(*args):
(arg1, arg2) = args
print(f'arg1: {arg1}, arg2: {arg2}')
print(f'Type1: {type(arg1)}. Type2: {type(arg2)}')
def print_take_2(one, two):
print(f'Value1: {one}, Value2: {two}')
def print_take_1(one):
print(f'Value: {one}')
def print_none():
print('I got nothing')
print_two... |
COL_WITH_NAN_SIGNIFICATION = ["BsmtQual", "BsmtCond", "BsmtExposure",
"BsmtFinType1", "BsmtFinType2", "GarageType",
"GarageFinish", "GarageQual", "GarageCond",
"PoolQC", "Fence", "MiscFeature", "Alley"]
CONTINUOUS_COL = ["LotFron... | col_with_nan_signification = ['BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond', 'PoolQC', 'Fence', 'MiscFeature', 'Alley']
continuous_col = ['LotFrontage', 'LotArea', 'MasVnrArea', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', '1s... |
def dec2bin(x):
cache = []
res = ''
while x:
num = x % 2
x = x // 2
cache.append(num)
while cache:
res += str(cache.pop())
return res
print(dec2bin(10),bin(10))
| def dec2bin(x):
cache = []
res = ''
while x:
num = x % 2
x = x // 2
cache.append(num)
while cache:
res += str(cache.pop())
return res
print(dec2bin(10), bin(10)) |
_config = {}
def Get(key):
global _config
return _config[key]
def Set(key, value):
global _config
_config[key] = value
| _config = {}
def get(key):
global _config
return _config[key]
def set(key, value):
global _config
_config[key] = value |
class Case:
def __init__(self, number: str, status: str, title: str, body: str):
self.number = number
self.status = status
self.title = title
self.body = body
| class Case:
def __init__(self, number: str, status: str, title: str, body: str):
self.number = number
self.status = status
self.title = title
self.body = body |
def update_transition_matrix(self, opponent_move):
global POSSIBLE_MOVES
if len(self.moves) <= len(LAST_POSSIBLE_MOVES[0]):
return None
for i in range(len(self.transition_sum_matrix[self.last_moves])):
self.transition_sum_matrix[self.last_moves][i] *= self.decay
self.transition_sum_matri... | def update_transition_matrix(self, opponent_move):
global POSSIBLE_MOVES
if len(self.moves) <= len(LAST_POSSIBLE_MOVES[0]):
return None
for i in range(len(self.transition_sum_matrix[self.last_moves])):
self.transition_sum_matrix[self.last_moves][i] *= self.decay
self.transition_sum_matri... |
class Vertex:
def __init__(self, name):
self.name = name
class Graph:
vertices = {}
edges = []
edge_indices = {}
def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
for row ... | class Vertex:
def __init__(self, name):
self.name = name
class Graph:
vertices = {}
edges = []
edge_indices = {}
def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
for row in... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head:
return
if head.next == None:
return head
def find_mid(h... | class Solution:
def sort_list(self, head: ListNode) -> ListNode:
if not head:
return
if head.next == None:
return head
def find_mid(head):
if not head:
return None
(slow, fast) = (head, head)
while fast.next and fa... |
def parse(input_file):
with open(input_file, 'r') as f:
return f.read().split('\n\n')
def clean_input(answers):
return [a.replace('\n', '') for a in answers]
def get_uniques(answers):
return [set(a) for a in answers]
def get_unique_count(answers):
return [len(a) for a in answers]
def get_agr... | def parse(input_file):
with open(input_file, 'r') as f:
return f.read().split('\n\n')
def clean_input(answers):
return [a.replace('\n', '') for a in answers]
def get_uniques(answers):
return [set(a) for a in answers]
def get_unique_count(answers):
return [len(a) for a in answers]
def get_agr... |
fib_num= lambda n:fib_num(n-1)+fib_num(n-2) if n>2 else 1
print(fib_num(6))
def test1_fib_num():
assert (fib_num(6)==8)
def test2_fib_num():
assert (fib_num(5)==5)
def test3_fib_num():
n = 10
assert (fib_num(2*n)==fib_num(n+1)**2 - fib_num(n-1)**2)
| fib_num = lambda n: fib_num(n - 1) + fib_num(n - 2) if n > 2 else 1
print(fib_num(6))
def test1_fib_num():
assert fib_num(6) == 8
def test2_fib_num():
assert fib_num(5) == 5
def test3_fib_num():
n = 10
assert fib_num(2 * n) == fib_num(n + 1) ** 2 - fib_num(n - 1) ** 2 |
people = ['Jonas', 'Julio', 'Mike', 'Mez']
ages = [25, 30, 31, 39]
for person, age in zip(people, ages):
print(person, age)
| people = ['Jonas', 'Julio', 'Mike', 'Mez']
ages = [25, 30, 31, 39]
for (person, age) in zip(people, ages):
print(person, age) |
def main() -> None:
n = int(input())
s = [list(map(lambda x: int(x) - 1, input())) for _ in range(n)]
time = [[-1] * 10 for _ in range(n)]
for i in range(n):
for j in range(10):
time[i][s[i][j]] = j
mn = 1 << 60
for d in range(10):
count = [0] * 10
... | def main() -> None:
n = int(input())
s = [list(map(lambda x: int(x) - 1, input())) for _ in range(n)]
time = [[-1] * 10 for _ in range(n)]
for i in range(n):
for j in range(10):
time[i][s[i][j]] = j
mn = 1 << 60
for d in range(10):
count = [0] * 10
mx = 0
... |
# encoding: utf-8
print("I will now count my chickens:")
print("Hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3 + 2 < 5 - 7?")
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", ... | print('I will now count my chickens:')
print('Hens', 25 + 30 / 6)
print('Roosters', 100 - 25 * 3 % 4)
print('Now I will count the eggs:')
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print('Is it true that 3 + 2 < 5 - 7?')
print(3 + 2 < 5 - 7)
print('What is 3 + 2?', 3 + 2)
print('What is 5 - 7?', 5 - 7)
print("Oh, that's ... |
'''
1) Create a Clusterfile
2) Add metadata to created Clusterfile
3) Create a bunch of Datasets
- Add them to created Clusterfile
'''
| """
1) Create a Clusterfile
2) Add metadata to created Clusterfile
3) Create a bunch of Datasets
- Add them to created Clusterfile
""" |
class EurecomDataset(Dataset):
def __init__(self,domain,variation,training_dir=None,transform=None):
self.transform = transform
self.training_dir = training_dir
# For each variant keep a list
self.thermal_illu = []
self.thermal_exp = []
self.thermal_pose = []
... | class Eurecomdataset(Dataset):
def __init__(self, domain, variation, training_dir=None, transform=None):
self.transform = transform
self.training_dir = training_dir
self.thermal_illu = []
self.thermal_exp = []
self.thermal_pose = []
self.thermal_occ = []
self... |
#!/usr/bin/env python3
# ex31: Making Decisions
print("You enter a dark room with two doors. Do you go through door #1 or door #2?")
door = input("> ")
if door == "1":
print("There's a giant bear here eating a cheese cake. What do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
... | print('You enter a dark room with two doors. Do you go through door #1 or door #2?')
door = input('> ')
if door == '1':
print("There's a giant bear here eating a cheese cake. What do you do?")
print('1. Take the cake.')
print('2. Scream at the bear.')
bear = input('> ')
if bear == '1':
print... |
class item:
def __init__(self, name, cap, dur, flav, text, cal):
self.name = name
self.cap = cap
self.dur = dur
self.fla = flav
self.tex = text
self.cal = cal
return
it = [item('Frosting', 4, -2, 0, 0, 5),
item('Candy', 0, 5, -1, 0, 8),
item('Butterscotch', -1, 0, 5, 0, 6),
... | class Item:
def __init__(self, name, cap, dur, flav, text, cal):
self.name = name
self.cap = cap
self.dur = dur
self.fla = flav
self.tex = text
self.cal = cal
return
it = [item('Frosting', 4, -2, 0, 0, 5), item('Candy', 0, 5, -1, 0, 8), item('Butterscotch', -... |
t = int(input())
for _ in range(t):
n = int(input())
s = input()
s = list(s)
index = 0
while index < n - 1:
s[index], s[index + 1] = s[index + 1], s[index]
index += 2
for i in range(n):
s[i] = chr(ord('z') - (ord(s[i]) - ord('a')))
print("".join(s))
| t = int(input())
for _ in range(t):
n = int(input())
s = input()
s = list(s)
index = 0
while index < n - 1:
(s[index], s[index + 1]) = (s[index + 1], s[index])
index += 2
for i in range(n):
s[i] = chr(ord('z') - (ord(s[i]) - ord('a')))
print(''.join(s)) |
# -*- coding: utf-8 -*-
# Author: Jiajun Ren <jiajunren0522@gmail.com>
electron = "e"
electrons = "es"
phonon = "ph"
class EphTable(tuple):
@classmethod
def all_phonon(cls, site_num):
return cls([phonon] * site_num)
@classmethod
def from_mol_list(cls, mol_list, scheme):
eph_list = ... | electron = 'e'
electrons = 'es'
phonon = 'ph'
class Ephtable(tuple):
@classmethod
def all_phonon(cls, site_num):
return cls([phonon] * site_num)
@classmethod
def from_mol_list(cls, mol_list, scheme):
eph_list = []
if scheme < 4:
for mol in mol_list:
... |
sentence = 'This awesome spaghetti is awesome'
better_sentence = sentence.replace('awesome', 'fabulous')
print(better_sentence)
date = '12/01/2035'
print(date.replace('/', '-'))
| sentence = 'This awesome spaghetti is awesome'
better_sentence = sentence.replace('awesome', 'fabulous')
print(better_sentence)
date = '12/01/2035'
print(date.replace('/', '-')) |
# if you have a list = [], or a string = '', it will evaluate as a False value
our_list = []
our_string = ''
if our_list:
print('This list has something in it.')
if our_string:
print('This string is not empty.')
teams = ['knicks', 'kings', 'heat', 'pacers', 'celtics', 'pelicans']
for team in teams:
if team.star... | our_list = []
our_string = ''
if our_list:
print('This list has something in it.')
if our_string:
print('This string is not empty.')
teams = ['knicks', 'kings', 'heat', 'pacers', 'celtics', 'pelicans']
for team in teams:
if team.startswith('k'):
print('The ' + team.title() + ' could win the NBA cham... |
class Node:
def __init__(self, key, value):
self.key = key
self.val = value
self.next = self.pre = None
self.pre = None
class LRUCache:
def remove(self, node):
node.pre.next, node.next.pre = node.next, node.pre
self.dic.pop(node.key)
def add(self, nod... | class Node:
def __init__(self, key, value):
self.key = key
self.val = value
self.next = self.pre = None
self.pre = None
class Lrucache:
def remove(self, node):
(node.pre.next, node.next.pre) = (node.next, node.pre)
self.dic.pop(node.key)
def add(self, node... |
TOKENIZE_TEXT_INPUT_SCHEMA = {
"type": "object",
"properties": {
"text": {"type": "string"},
},
"required": ["text"],
"additionalProperties": False
}
TOKENIZE_TEXT_OUTPUT_SCHEMA = {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "array",
... | tokenize_text_input_schema = {'type': 'object', 'properties': {'text': {'type': 'string'}}, 'required': ['text'], 'additionalProperties': False}
tokenize_text_output_schema = {'type': 'array', 'items': {'type': 'array', 'items': {'type': 'array', 'items': {'type': 'string'}}}} |
class Solution:
def convertToTitle(self, n: int) -> str:
return self.solution1(n)
def solution1(self, n: int) -> str:
ans = []
while n > 0:
n, r = divmod(n-1, 26)
ans.append(chr(r + ord('A')))
return ''.join(ans[::-1])
# time limit exceeded
def s... | class Solution:
def convert_to_title(self, n: int) -> str:
return self.solution1(n)
def solution1(self, n: int) -> str:
ans = []
while n > 0:
(n, r) = divmod(n - 1, 26)
ans.append(chr(r + ord('A')))
return ''.join(ans[::-1])
def solution2(self, n: i... |
def print_separator():
#print('--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------')
print('')
def print_components_menu(generate, download, convert, c... | def print_separator():
print('')
def print_components_menu(generate, download, convert, clean, windows):
print_separator()
print_separator()
print(' * Active components')
print(' -> Generator: ', generate)
print(' -> Downloader: ', download)
print(' -> Converter: ', convert)
... |
def validate_morph(morph):
if not "key" in morph:
print(" - key is missing")
return False
if not "type" in morph:
print(" - type is missing")
return False
if not "origin" in morph:
print(" - origin is missing")
return False
morph_type = morph["type"]
... | def validate_morph(morph):
if not 'key' in morph:
print(' - key is missing')
return False
if not 'type' in morph:
print(' - type is missing')
return False
if not 'origin' in morph:
print(' - origin is missing')
return False
morph_type = morph['type']
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.