content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def get_config():
conf = {
# Change it to necessary directory
'workdir': 'dataset/cr_data/',
'PAD': 0,
'BOS': 1,
'EOS': 2,
'UNK': 3,
'train_qt': 'sql.train.qt.pkl',
'train_code': 'sql.train.code.pkl',
# parameters
'qt_len': 20,
... | def get_config():
conf = {'workdir': 'dataset/cr_data/', 'PAD': 0, 'BOS': 1, 'EOS': 2, 'UNK': 3, 'train_qt': 'sql.train.qt.pkl', 'train_code': 'sql.train.code.pkl', 'qt_len': 20, 'code_len': 120, 'qt_n_words': 7775, 'code_n_words': 7726, 'vocab_qt': 'sql.qt.vocab.pkl', 'vocab_code': 'sql.code.vocab.pkl', 'checkpoin... |
def get_urls(*args, **kwargs):
return {
'http://docutils.sourceforge.net/RELEASE-NOTES.txt'
}, set()
| def get_urls(*args, **kwargs):
return ({'http://docutils.sourceforge.net/RELEASE-NOTES.txt'}, set()) |
#
# PySNMP MIB module G6-FACTORY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/G6-FACTORY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:04:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) ... |
#! /usr/bin/env python
def is_num_palindrome(num):
# Skip single-digit inputs
if num // 10 == 0:
return False
temp = num
reversed_num = 0
while temp != 0:
reversed_num = (reversed_num * 10) + (temp % 10)
print(f'Reverse number: {reversed_num}')
temp = temp // 10
... | def is_num_palindrome(num):
if num // 10 == 0:
return False
temp = num
reversed_num = 0
while temp != 0:
reversed_num = reversed_num * 10 + temp % 10
print(f'Reverse number: {reversed_num}')
temp = temp // 10
print(f'Temp number: {temp}')
if num == reversed_nu... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 5, 2015
# Question: 122-Best-Time-to-Buy-and-Sell-Stock-II
# Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
# ==============================... | class Solution:
def max_profit(self, prices):
if len(prices) <= 1:
return 0
total = 0
for i in range(len(prices) - 1):
total += prices[i + 1] - prices[i] if prices[i + 1] - prices[i] > 0 else 0
return total |
"""
IF the name is less than 3 characters then the name is
shorter than usual. If the name is of more than 50 characters
it is longer than usual.
"""
#Taking name from the user
name = str(input("Please enter your full name: "))
#Evaluating the name
if len(name) < 3:
print("The name that you have put is too sh... | """
IF the name is less than 3 characters then the name is
shorter than usual. If the name is of more than 50 characters
it is longer than usual.
"""
name = str(input('Please enter your full name: '))
if len(name) < 3:
print('The name that you have put is too short')
elif len(name) > 50:
print('The name that ... |
# Refer: https://codeforces.com/contest/1538/problem/B
def distribute_candies(arr, n):
s = sum(arr)
if s % n != 0:
return -1
avg = s // n
cnt = 0
for c in arr:
if c > avg:
cnt += 1
return cnt
if __name__ == "__main__":
t = int(input())
i = 0
while i < ... | def distribute_candies(arr, n):
s = sum(arr)
if s % n != 0:
return -1
avg = s // n
cnt = 0
for c in arr:
if c > avg:
cnt += 1
return cnt
if __name__ == '__main__':
t = int(input())
i = 0
while i < t:
n = int(input())
arr = list(map(int, inp... |
__all__ = ['RetryStrategy']
class RetryStrategy (object):
"""
Base class for retry strategies.
"""
def exhaust (self):
"""
Sets the retry strategy in such a state that it will always return a
value that indicates that no further sleep attempts should be made.
"""
... | __all__ = ['RetryStrategy']
class Retrystrategy(object):
"""
Base class for retry strategies.
"""
def exhaust(self):
"""
Sets the retry strategy in such a state that it will always return a
value that indicates that no further sleep attempts should be made.
"""
... |
# Copyright 2020 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | class Constants(object):
"""Static class contains all constant variables"""
class Enumbackport(object):
class __Metaclass__(type):
def __iter__(self):
for item in self.__dict__:
if item == self.__dict__[item]:
yield item
defa... |
# Scrapy settings for sephora project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware... | bot_name = 'sephora'
spider_modules = ['sephora.spiders']
newspider_module = 'sephora.spiders'
user_agent = ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.362... |
_base_ = './van_small_8xb128_fp16_ep300.py'
# model settings
model = dict(
backbone=dict(arch='large', drop_path_rate=0.2),
)
| _base_ = './van_small_8xb128_fp16_ep300.py'
model = dict(backbone=dict(arch='large', drop_path_rate=0.2)) |
#!/usr/bin/python
REGISTER_USER = "RegisterUser"
CURRENT_MEDS = "CurrentRx"
DOSAGE_REMINDER = "DosageReminder"
REFILL_REMINDER = "RefillReminder" | register_user = 'RegisterUser'
current_meds = 'CurrentRx'
dosage_reminder = 'DosageReminder'
refill_reminder = 'RefillReminder' |
if __name__ == "__main__":
s = 'Hello from Python!'
words = s.split(' ')
print(words)
for w in words:
print(w)
for ch in s:
print(ch) | if __name__ == '__main__':
s = 'Hello from Python!'
words = s.split(' ')
print(words)
for w in words:
print(w)
for ch in s:
print(ch) |
def sequentialSearch(n, array, x):
if x >= n: return None
location = 0
while (location < n and array[location] != x): location += 1
return location
| def sequential_search(n, array, x):
if x >= n:
return None
location = 0
while location < n and array[location] != x:
location += 1
return location |
MICROBIT = "micro:bit"
# string arguments for constructor
BLANK_5X5 = "00000:00000:00000:00000:00000:"
# pre-defined image patterns
IMAGE_PATTERNS = {
"HEART": "09090:99999:99999:09990:00900:",
"HEART_SMALL": "00000:09090:09990:00900:00000:",
"HAPPY": "00000:09090:00000:90009:09990:",
"SMILE": "00000:... | microbit = 'micro:bit'
blank_5_x5 = '00000:00000:00000:00000:00000:'
image_patterns = {'HEART': '09090:99999:99999:09990:00900:', 'HEART_SMALL': '00000:09090:09990:00900:00000:', 'HAPPY': '00000:09090:00000:90009:09990:', 'SMILE': '00000:00000:00000:90009:09990:', 'SAD': '00000:09090:00000:09990:90009:', 'CONFUSED': '0... |
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
result, currentSum, hashSet, start = 0, 0, set(), 0
for end in range(len(nums)):
while nums[end] in hashSet:
hashSet.remove(nums[start])
currentSum -= nums[start]
star... | class Solution:
def maximum_unique_subarray(self, nums: List[int]) -> int:
(result, current_sum, hash_set, start) = (0, 0, set(), 0)
for end in range(len(nums)):
while nums[end] in hashSet:
hashSet.remove(nums[start])
current_sum -= nums[start]
... |
"""
Instruction:
- write a proper docstring that includes any exception conditions
- add two more meaningful testcases to the doctests part of each function
- write the body of the function where a marker "YOUR CODE HERE" appear
To test these functions, use the following command:
python3 -m doctest week5_inclass_ex.p... | """
Instruction:
- write a proper docstring that includes any exception conditions
- add two more meaningful testcases to the doctests part of each function
- write the body of the function where a marker "YOUR CODE HERE" appear
To test these functions, use the following command:
python3 -m doctest week5_inclass_ex.p... |
"""
TCF CLI VERSION
"""
__version__ = '0.1.1'
| """
TCF CLI VERSION
"""
__version__ = '0.1.1' |
class Solution:
def specialArray(self, nums):
length = len(nums)
rng = range(length)
# Start from end. (todo, try starting from beginning)
for i in range(1, length+1):
# keep track of matches (>= i)
match = 0
for idx in rng:
n = num... | class Solution:
def special_array(self, nums):
length = len(nums)
rng = range(length)
for i in range(1, length + 1):
match = 0
for idx in rng:
n = nums[idx]
if n >= i:
match = match + 1
if match ... |
"""
Batch processing exceptions
"""
class SQSBatchProcessingError(Exception):
"""When at least one message within a batch could not be processed"""
| """
Batch processing exceptions
"""
class Sqsbatchprocessingerror(Exception):
"""When at least one message within a batch could not be processed""" |
numbers = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
result = [el for num, el in enumerate(numbers) if numbers[num - 1] < numbers[num]]
print(result) | numbers = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
result = [el for (num, el) in enumerate(numbers) if numbers[num - 1] < numbers[num]]
print(result) |
# Create a word-count method
# Function that returns number of words in a string
def count_words(string):
# Split the string into words
words = string.split()
# Return the number of words
return len(words)
# Create a new feature word_count
ted['word_count'] = ted['transcript'].apply(count_words)
# ... | def count_words(string):
words = string.split()
return len(words)
ted['word_count'] = ted['transcript'].apply(count_words)
print(ted['word_count'].mean()) |
class DiskError(RuntimeError):
pass
class SaveError(DiskError):
pass
class LoadError(DiskError):
pass
class RenameError(DiskError):
pass
class PathDoesNotExistError(DiskError):
pass
class PathExistsError(DiskError):
pass
class NotAFileError(FileNotFoundError):
pass
class DirectoryNotFoundError(NotA... | class Diskerror(RuntimeError):
pass
class Saveerror(DiskError):
pass
class Loaderror(DiskError):
pass
class Renameerror(DiskError):
pass
class Pathdoesnotexisterror(DiskError):
pass
class Pathexistserror(DiskError):
pass
class Notafileerror(FileNotFoundError):
pass
class Directorynotf... |
RECOGNIZE = {
" | | ": '1',
" _ _||_ ": '2',
" _ _| _| ": '3',
" |_| | ": '4',
" _ |_ _| ": '5',
" _ |_ |_| ": '6',
" _ | | ": '7',
" _ |_||_| ": '8',
" _ |_| _| ": '9',
" _ | ||_| ": '0',
}
def convert(input_grid):
if input_grid == [] or ... | recognize = {' | | ': '1', ' _ _||_ ': '2', ' _ _| _| ': '3', ' |_| | ': '4', ' _ |_ _| ': '5', ' _ |_ |_| ': '6', ' _ | | ': '7', ' _ |_||_| ': '8', ' _ |_| _| ': '9', ' _ | ||_| ': '0'}
def convert(input_grid):
if input_grid == [] or len(input_grid) % 4 != 0:
raise valu... |
class CianException(Exception):
"""Base class for exceptions"""
class CianStatusException(CianException):
"""Incorrect status in response from cian server"""
def __init__(self, status):
super().__init__(f"Status in response from cian is not 'ok'. Status: {status}")
| class Cianexception(Exception):
"""Base class for exceptions"""
class Cianstatusexception(CianException):
"""Incorrect status in response from cian server"""
def __init__(self, status):
super().__init__(f"Status in response from cian is not 'ok'. Status: {status}") |
def cap_text(text):
"""
Input a String
Output the capitalized String
"""
return text.title() | def cap_text(text):
"""
Input a String
Output the capitalized String
"""
return text.title() |
def foo(**args):
pass
a = {}
b = {}
foo(**a)
| def foo(**args):
pass
a = {}
b = {}
foo(**a) |
class Shield:
def __init__(self):
self.water_level = 0
self.switch_state = 0
def tick(self, water_level, switch_state, action):
return action
| class Shield:
def __init__(self):
self.water_level = 0
self.switch_state = 0
def tick(self, water_level, switch_state, action):
return action |
# 1046. Last Stone Weight - LeetCode Contest
# https://leetcode.com/contest/weekly-contest-137/problems/last-stone-weight/
class Solution:
def lastStoneWeight(self, stones) -> int:
stones = sorted(stones,reverse=True)
while len(stones) > 1:
first_stone = stones.pop(0)
second... | class Solution:
def last_stone_weight(self, stones) -> int:
stones = sorted(stones, reverse=True)
while len(stones) > 1:
first_stone = stones.pop(0)
second_stone = stones.pop(0)
if first_stone > second_stone:
remains = first_stone - second_stone
... |
class Node(object):
def __init__(self, key, data=None, result=None):
self.key = key
self.data = data
self.result = []
if result is not None:
self.result.append(result)
self.children = dict()
class Trie(object):
"""
Trie Data Structure
Data Structure... | class Node(object):
def __init__(self, key, data=None, result=None):
self.key = key
self.data = data
self.result = []
if result is not None:
self.result.append(result)
self.children = dict()
class Trie(object):
"""
Trie Data Structure
Data Structure... |
#!/usr/bin/python
# tuple_one.py
print ((3 + 7))
print ((3 + 7, ))
| print(3 + 7)
print((3 + 7,)) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 6 23:48:22 2019
gnomesort example from Python Algorithms by Magnus Lie Hetland
"""
def gnomesort(seq):
i =0
while i < len(seq):
if i == 0 or seq[i-1] <= seq[i]:
i += 1
else:
seq[i], seq[i-1] = seq[i-1], seq[i... | """
Created on Sun Jan 6 23:48:22 2019
gnomesort example from Python Algorithms by Magnus Lie Hetland
"""
def gnomesort(seq):
i = 0
while i < len(seq):
if i == 0 or seq[i - 1] <= seq[i]:
i += 1
else:
(seq[i], seq[i - 1]) = (seq[i - 1], seq[i])
i -= 1 |
"""
:testcase_name factorial
:author Sriteja Kummita
:script_type Class
:description Class, RecursiveFactorial contains a function that calculates factorial of a given number recursively
"""
class RecursiveFactorial:
def factorial(self, n):
if n <= 1:
return 1
return n * self.factorial... | """
:testcase_name factorial
:author Sriteja Kummita
:script_type Class
:description Class, RecursiveFactorial contains a function that calculates factorial of a given number recursively
"""
class Recursivefactorial:
def factorial(self, n):
if n <= 1:
return 1
return n * self.factorial... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | pretrained_models = {'panns_cnn6-32k': {'url': 'https://paddlespeech.bj.bcebos.com/cls/inference_model/panns_cnn6_static.tar.gz', 'md5': 'da087c31046d23281d8ec5188c1967da', 'cfg_path': 'panns.yaml', 'model_path': 'inference.pdmodel', 'params_path': 'inference.pdiparams', 'label_file': 'audioset_labels.txt'}, 'panns_cnn... |
"""
Enumerates the Resource Description Framework and XML namespaces in use in ISDE.
Each class variable is a `dict` with two keys:
- _ns_: The preferred namespace prefix for the vocabulary as a `str`
- _url_: The URL to the vocabulary as a `str`
"""
class RDFNamespaces:
"""
Resource Description Framework na... | """
Enumerates the Resource Description Framework and XML namespaces in use in ISDE.
Each class variable is a `dict` with two keys:
- _ns_: The preferred namespace prefix for the vocabulary as a `str`
- _url_: The URL to the vocabulary as a `str`
"""
class Rdfnamespaces:
"""
Resource Description Framework nam... |
class FuzzyOperatorSizeException(Exception):
"""
An Exception which indicates that the associated matrix of the operator has invalid shape.
"""
def __init__(self, message: str = "Only squared matrices are valid to represent a fuzzy operator."):
super().__init__(message)
| class Fuzzyoperatorsizeexception(Exception):
"""
An Exception which indicates that the associated matrix of the operator has invalid shape.
"""
def __init__(self, message: str='Only squared matrices are valid to represent a fuzzy operator.'):
super().__init__(message) |
"""Top-level package for ERD Generator."""
__author__ = """Datateer"""
__email__ = 'dev@datateer.com'
__version__ = '__version__ = 0.1.0'
| """Top-level package for ERD Generator."""
__author__ = 'Datateer'
__email__ = 'dev@datateer.com'
__version__ = '__version__ = 0.1.0' |
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
self.position = sorted(position)
low, high = 0, self.position[-1] - self.position[0]
while low <= high:
mid = (high+low) // 2
if self.check(self.position, m, mid):
low = mid + 1... | class Solution:
def max_distance(self, position: List[int], m: int) -> int:
self.position = sorted(position)
(low, high) = (0, self.position[-1] - self.position[0])
while low <= high:
mid = (high + low) // 2
if self.check(self.position, m, mid):
low =... |
l = int(input())
ar = input().split()
for size in range(l):
ar[size] = int(ar[size])
def shift(plist, index):
temp = plist[index]
if plist[index-1] > plist[index]:
plist[index] = plist[index-1]
plist[index-1] = temp
if index - 2 == -1:
pass
else:
... | l = int(input())
ar = input().split()
for size in range(l):
ar[size] = int(ar[size])
def shift(plist, index):
temp = plist[index]
if plist[index - 1] > plist[index]:
plist[index] = plist[index - 1]
plist[index - 1] = temp
if index - 2 == -1:
pass
else:
... |
SERPRO_API_GATEWAY = "https://apigateway.serpro.gov.br"
SERPRO_PUBLIC_JWKS = "https://d-biodata.estaleiro.serpro.gov.br/api/v1/jwks"
AUTHENTICATE_ENDPOINT = "/token"
# biodata endpoints
BIODATA_TOKEN_ENDPOINT = "/biodata/v1/token"
JWT_AUDIENCE = '35284162000183'
| serpro_api_gateway = 'https://apigateway.serpro.gov.br'
serpro_public_jwks = 'https://d-biodata.estaleiro.serpro.gov.br/api/v1/jwks'
authenticate_endpoint = '/token'
biodata_token_endpoint = '/biodata/v1/token'
jwt_audience = '35284162000183' |
def div(a, b):
if(b != 0):
return a/b
else:
print("cannot divide by 0")
return
def add(a,b):
return a+b | def div(a, b):
if b != 0:
return a / b
else:
print('cannot divide by 0')
return
def add(a, b):
return a + b |
class Graph(object):
def __init__(self, n):
self._n = n
| class Graph(object):
def __init__(self, n):
self._n = n |
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
def base64_to_base10(s):
return sum(ALPHABET.index(j)*64**i for i,j in enumerate(s[::-1]))
| alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
def base64_to_base10(s):
return sum((ALPHABET.index(j) * 64 ** i for (i, j) in enumerate(s[::-1]))) |
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
#create counter
visited = {}
counter = 0
#loop through nums
for i in nums:
if i in visited:
counter += visited[i]
visited[i] += 1
... | class Solution:
def num_identical_pairs(self, nums: List[int]) -> int:
visited = {}
counter = 0
for i in nums:
if i in visited:
counter += visited[i]
visited[i] += 1
else:
visited[i] = 1
return counter |
n= int(input())
line1 = sum([int(i) for i in input().split()])
line2 = sum([int(i) for i in input().split()])
line3 = sum([int(i) for i in input().split()])
first = line1-line2
second = line2-line3
print(first)
print(second)
| n = int(input())
line1 = sum([int(i) for i in input().split()])
line2 = sum([int(i) for i in input().split()])
line3 = sum([int(i) for i in input().split()])
first = line1 - line2
second = line2 - line3
print(first)
print(second) |
#!/usr/bin/env python3
#Create and print string
people = "sapiens, erectus, neanderthalensis"
print(people)
#Split the string into individual words
species = people.split(', ')
print(species)
#Sort alphabetically
print(sorted(species))
#Sort be length of string and print
print(sorted(species,key=len))
| people = 'sapiens, erectus, neanderthalensis'
print(people)
species = people.split(', ')
print(species)
print(sorted(species))
print(sorted(species, key=len)) |
y = int(input("Digite um numero: "))
x = int(input("Digite um numero: "))
linha = 1
coluna = 1
while linha <= x:
while coluna <= y:
print(linha * coluna, end="\t")
coluna += 1
linha += 1
print()
coluna = 1
| y = int(input('Digite um numero: '))
x = int(input('Digite um numero: '))
linha = 1
coluna = 1
while linha <= x:
while coluna <= y:
print(linha * coluna, end='\t')
coluna += 1
linha += 1
print()
coluna = 1 |
class DataGeneratorCfg:
n_samples = 300
centers = [[-1, 0.5], [1, 0], [1,1]]
cluster_std = 0.5
random_state = None
class APCfg:
n_iterations = 300
damping = 0.8
preference = -50 #'MEDIAN', 'MINIMUM' or a value
class MainCfg:
generate_new_data=True # Saves it to data folde... | class Datageneratorcfg:
n_samples = 300
centers = [[-1, 0.5], [1, 0], [1, 1]]
cluster_std = 0.5
random_state = None
class Apcfg:
n_iterations = 300
damping = 0.8
preference = -50
class Maincfg:
generate_new_data = True
show_iterations = False
outfilename = 'output/result.png'
... |
"Implementing stack using python lists"
class UnderFlowError(Exception):
pass
class OverFlowError(Exception):
pass
class Stack:
def __init__(self, max_size):
self.s = []
self.top = -1
self.max_size = max_size
@property
def stack_empty(self):
return self.top == ... | """Implementing stack using python lists"""
class Underflowerror(Exception):
pass
class Overflowerror(Exception):
pass
class Stack:
def __init__(self, max_size):
self.s = []
self.top = -1
self.max_size = max_size
@property
def stack_empty(self):
return self.top =... |
# #!/usr/bin/env python
# encoding: utf-8
# --------------------------------------------------------------------------------------------------------------------
#
# Name: merging_two_dictionaries.py
# Version: 1.0
#
# Summary: Merging two dictionaries.
#
# Author: Alexsander Lopes Camargos
# Author-email: alcamargos... | """
Merging Two Dictionaries
While in Python 2, we used the update() method to merge two dictionaries;
Python 3 made the process even simpler. In the script given below, two dictionaries are merged.
Values from the second dictionary are used in case of intersections.
"""
dict_1 = {'apple': 9, 'banana': 6, 'avocado': ... |
# output: ok
a, b, c, d, e, f = 1000, 1000, 1000, 1000, 1000, 1000
g, h, i, j, k, l = 2, 1000, 1000, 1000, 1000, 1000
a = a + 1
b = b - 2
c = c * 3
d = d / 4
e = e // 5
f = f % 6
g = g ** 7
h = h << 8
i = i >> 9
j = j & 10
k = k ^ 11
l = l | 12
assert a == 1001
assert b == 998
assert c == 3000
assert d == 250
assert... | (a, b, c, d, e, f) = (1000, 1000, 1000, 1000, 1000, 1000)
(g, h, i, j, k, l) = (2, 1000, 1000, 1000, 1000, 1000)
a = a + 1
b = b - 2
c = c * 3
d = d / 4
e = e // 5
f = f % 6
g = g ** 7
h = h << 8
i = i >> 9
j = j & 10
k = k ^ 11
l = l | 12
assert a == 1001
assert b == 998
assert c == 3000
assert d == 250
assert e == 20... |
"""
Given a linked list, remove the nth node from the end of list and return its
head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes
1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
"""
# ... | """
Given a linked list, remove the nth node from the end of list and return its
head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes
1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
"""
c... |
'''
Description : Data Structure Using String Method
Function Date : 07 Feb 2021
Function Author : Prasad Dangare
Input : str
Output : str
'''
# This is a string object
name = 'prasad'
if name.startswith('pra'):
print ('Yes, the string starts with "pra"')
if ... | """
Description : Data Structure Using String Method
Function Date : 07 Feb 2021
Function Author : Prasad Dangare
Input : str
Output : str
"""
name = 'prasad'
if name.startswith('pra'):
print('Yes, the string starts with "pra"')
if 'a' in name:
print('Yes, it contains the st... |
class Utilities:
@staticmethod
def get_longest(words):
longest = ""
for word in words:
if len(word) > len(longest):
longest = word
Utilities.log(longest)
return longest
@staticmethod
def log(word):
print("Logging: " + word)
| class Utilities:
@staticmethod
def get_longest(words):
longest = ''
for word in words:
if len(word) > len(longest):
longest = word
Utilities.log(longest)
return longest
@staticmethod
def log(word):
print('Logging: ' + word) |
"""
The binary search algorithm - search for an item inside a sorted list.
Also includes the bisect algorithm:
Return the insertion point for an item x in a list to maintain sorted order.
(again in logarithmic time)
Author:
Christos Nitsas
(nitsas)
(chrisnitsas)
Language:
Python 3(.4)
Date:
November, 20... | """
The binary search algorithm - search for an item inside a sorted list.
Also includes the bisect algorithm:
Return the insertion point for an item x in a list to maintain sorted order.
(again in logarithmic time)
Author:
Christos Nitsas
(nitsas)
(chrisnitsas)
Language:
Python 3(.4)
Date:
November, 20... |
data = {
4 : [2, 0, 3, 1],
5 : [3, 0, 2, 4, 1],
6 : [3, 0, 4, 1, 5, 2],
7 : [4, 0, 5, 3, 1, 6, 2],
8 : [2, 4, 1, 7, 0, 6, 3, 5],
9 : [3, 1, 4, 7, 0, 2, 5, 8, 6],
10 : [8, 4, 0, 7, 3, 1, 6, 9, 5, 2],
11 : [5, 7, 0, 3, 8, 2, 9, 6, 10, 1, 4],
12 : [7, 10, 0, 2, 8, 5, 3, 1, 9, 11, 6, 4],... | data = {4: [2, 0, 3, 1], 5: [3, 0, 2, 4, 1], 6: [3, 0, 4, 1, 5, 2], 7: [4, 0, 5, 3, 1, 6, 2], 8: [2, 4, 1, 7, 0, 6, 3, 5], 9: [3, 1, 4, 7, 0, 2, 5, 8, 6], 10: [8, 4, 0, 7, 3, 1, 6, 9, 5, 2], 11: [5, 7, 0, 3, 8, 2, 9, 6, 10, 1, 4], 12: [7, 10, 0, 2, 8, 5, 3, 1, 9, 11, 6, 4], 13: [7, 5, 2, 9, 12, 0, 4, 10, 1, 6, 11, 3, 8... |
{
"targets": [
{
"target_name": "clang_indexer",
"sources": [
"addon.cc"
],
"include_dirs": [
"<!(node -e \"require('nan')\")",
"/Users/vincentrouille/Dev/MicroStep/llvm/tools/clang/include"
],
"link_settings": {
"libraries": ["/Users/vincentroui... | {'targets': [{'target_name': 'clang_indexer', 'sources': ['addon.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")', '/Users/vincentrouille/Dev/MicroStep/llvm/tools/clang/include'], 'link_settings': {'libraries': ['/Users/vincentrouille/Dev/MicroStep/llvm/build-release/lib/libclang.dylib', '-Wl,-rpath ./']}, 'cfla... |
class FileHandler:
def get_data(self, path: str):
contents = []
try:
with open(path, 'r') as x:
content = x.read().strip()
contents = list(map(int, content.split(' ')))
except FileNotFoundError:
if path:
print(f"File at loca... | class Filehandler:
def get_data(self, path: str):
contents = []
try:
with open(path, 'r') as x:
content = x.read().strip()
contents = list(map(int, content.split(' ')))
except FileNotFoundError:
if path:
print(f"File at loc... |
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
desc = '1'
if n == 1:
return desc
for i in range(2, n+1):
last_ch = None
counter = 0
last_desc = desc
desc = ''
... | class Solution(object):
def count_and_say(self, n):
"""
:type n: int
:rtype: str
"""
desc = '1'
if n == 1:
return desc
for i in range(2, n + 1):
last_ch = None
counter = 0
last_desc = desc
desc = ''
... |
'''
import random
## random choice will choose 1 option from the list
randnum = random.choice(['True', 'False'])
print(randnum)
'''
class Enemy:
def __init__(self):
pass
self.health = health
self.attack = attack
def health(self):
pass
def attack(self):
pass
class Player(Enemy):
d... | """
import random
## random choice will choose 1 option from the list
randnum = random.choice(['True', 'False'])
print(randnum)
"""
class Enemy:
def __init__(self):
pass
self.health = health
self.attack = attack
def health(self):
pass
def attack(self):
pass
cl... |
ids = [
"elrond",
"gandalf",
"galadriel",
"celeborn",
"aragorn",
"arwen",
"glorfindel",
"legolas",
"thorin",
"balin",
"gloin",
"gimli",
"denethor",
"boromir",
"faramir",
"theoden",
"eomer",
"eowyn",
"bilbo",
"frodo",
"sam",
"pipin",... | ids = ['elrond', 'gandalf', 'galadriel', 'celeborn', 'aragorn', 'arwen', 'glorfindel', 'legolas', 'thorin', 'balin', 'gloin', 'gimli', 'denethor', 'boromir', 'faramir', 'theoden', 'eomer', 'eowyn', 'bilbo', 'frodo', 'sam', 'pipin', 'merry', 'sauron', 'mordu', 'witchking', 'nazgul', 'azog', 'ugluk', 'mauhur', 'shagrat',... |
# -*- coding: utf-8 -*-
"""
pepipost
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class DomainStruct(object):
"""Implementation of the 'DomainStruct' model.
Domain Modal
Attributes:
domain (string): The domain you wish to include ... | """
pepipost
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Domainstruct(object):
"""Implementation of the 'DomainStruct' model.
Domain Modal
Attributes:
domain (string): The domain you wish to include in the 'From' header
of your em... |
#Author: ahmelq - github.com/ahmedelq/
#License: MIT
#this is a solution of https://old.reddit.com/r/dailyprogrammer/comments/aphavc/20190211_challenge_375_easy_print_a_new_number_by/
# -- coding: utf-8 --
def exoticNum(n):
return ''.join([
str(int(num) + 1)
for num in list(str(n))])
i... | def exotic_num(n):
return ''.join([str(int(num) + 1) for num in list(str(n))])
if __name__ == '__main__':
print(exotic_num(998)) |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class BaseAnonymizor(object):
'''BaseType for anonymizers of the *data-migrator*.
Instantiate the anonymizer and definition and call the instantiation at
translation time.
Implement the :meth:`~.__call__` method to implement your specific anonymizor.
... | class Baseanonymizor(object):
"""BaseType for anonymizers of the *data-migrator*.
Instantiate the anonymizer and definition and call the instantiation at
translation time.
Implement the :meth:`~.__call__` method to implement your specific anonymizor.
"""
def __call__(self, v):
"""out... |
# -*- coding: utf-8 -*-
def test_chat_delete(slack_time):
assert slack_time.chat.delete
def test_chat_delete_scheduled_message(slack_time):
assert slack_time.chat.delete_scheduled_message
def test_chat_get_permalink(slack_time):
assert slack_time.chat.get_permalink
def test_chat_me_message(slack_tim... | def test_chat_delete(slack_time):
assert slack_time.chat.delete
def test_chat_delete_scheduled_message(slack_time):
assert slack_time.chat.delete_scheduled_message
def test_chat_get_permalink(slack_time):
assert slack_time.chat.get_permalink
def test_chat_me_message(slack_time):
assert slack_time.cha... |
for _ in range(int(input())):
n = int(input())
s = input()
count_prev = 0
count = 0
changes = 0
for i in s:
if i == "(":
count -= 1
else:
count += 1
if count>0 and count>count_prev:
#print(i, count)
changes += 1
... | for _ in range(int(input())):
n = int(input())
s = input()
count_prev = 0
count = 0
changes = 0
for i in s:
if i == '(':
count -= 1
else:
count += 1
if count > 0 and count > count_prev:
changes += 1
count_prev = count
pr... |
a='platzi'
a=list(a) #Convierto a lista, porque una lista si se puede modificar
a[0]='c' #Realizo el cambio que necesito
a=''.join(a) #Concateno para obtener nuevamente el string
print(a)
| a = 'platzi'
a = list(a)
a[0] = 'c'
a = ''.join(a)
print(a) |
# -*- coding: utf-8 -*-
""" Assessments Module - Controllers
@author: Fran Boon
@see: http://eden.sahanafoundation.org/wiki/Pakistan
@ToDo: Rename as 'assessment' (Deprioritised due to Data Migration issues being distracting for us currently)
"""
module = request.controller
if module not in deployment_... | """ Assessments Module - Controllers
@author: Fran Boon
@see: http://eden.sahanafoundation.org/wiki/Pakistan
@ToDo: Rename as 'assessment' (Deprioritised due to Data Migration issues being distracting for us currently)
"""
module = request.controller
if module not in deployment_settings.modules:
sessi... |
var1 = [0,1,2,3,4,5]
for x in var1:
var1[x] = x*x
for x in "123456":
print(x)
#While loop
someval = 1
while someval<1000:
someval *= 2 | var1 = [0, 1, 2, 3, 4, 5]
for x in var1:
var1[x] = x * x
for x in '123456':
print(x)
someval = 1
while someval < 1000:
someval *= 2 |
class Rod:
def __init__(self, length, boost_begin, boost_count, ang_acc):
self.length = length
self.boost_begin = boost_begin
self.boost_count = boost_count
self.ang_acc = ang_acc
self.ang_vel = 0
self.ang_pos = 0
| class Rod:
def __init__(self, length, boost_begin, boost_count, ang_acc):
self.length = length
self.boost_begin = boost_begin
self.boost_count = boost_count
self.ang_acc = ang_acc
self.ang_vel = 0
self.ang_pos = 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
QSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems
This module is developed by:
Yalin Li <zoe.yalin.li@gmail.com>
This module is under the University of Illinois/NCSA Open Source License.
Please refer to https://github.com/QSD-G... | """
QSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems
This module is developed by:
Yalin Li <zoe.yalin.li@gmail.com>
This module is under the University of Illinois/NCSA Open Source License.
Please refer to https://github.com/QSD-Group/QSDsan/blob/master/LICENSE.txt
for license ... |
class SingleNode:
def __init__(self, key, next=None):
self.key = key
self.next = None
def __repr__(self):
return f"Node: key={self.key}, next={self.next.key if self.next is not None else None}"
class SinglyLinkedList:
def __init__(self):
self.sentinel = SingleNode(None)
... | class Singlenode:
def __init__(self, key, next=None):
self.key = key
self.next = None
def __repr__(self):
return f'Node: key={self.key}, next={(self.next.key if self.next is not None else None)}'
class Singlylinkedlist:
def __init__(self):
self.sentinel = single_node(None... |
# Your code here
s=str(input())
n=len(s)
for i in range(n):
print(s[0],end="")
| s = str(input())
n = len(s)
for i in range(n):
print(s[0], end='') |
# from Attributes_and_Methods.movie_world_02E.project.customer import Customer
# from Attributes_and_Methods.movie_world_02E.project.dvd import DVD
class MovieWorld:
def __init__(self, name: str):
self.name = name
self.customers = []
self.dvds = []
@staticmethod
def dvd_capacity()... | class Movieworld:
def __init__(self, name: str):
self.name = name
self.customers = []
self.dvds = []
@staticmethod
def dvd_capacity():
return 15
@staticmethod
def customer_capacity():
return 10
def add_customer(self, customer):
if len(self.cust... |
print("Welcome to Python Prizza Deliveries!")
size = input("What size pirzza do you want? S, M, L \n")
add_pepperoni = input("Do you want pepperoni? Y or N \n")
extra_cheese = input("Do you want extra cheese? Y or N \n")
bill = 0
if size=="S" | "s":
bill += 15
if add_pepperoni == "Y":
bill +... | print('Welcome to Python Prizza Deliveries!')
size = input('What size pirzza do you want? S, M, L \n')
add_pepperoni = input('Do you want pepperoni? Y or N \n')
extra_cheese = input('Do you want extra cheese? Y or N \n')
bill = 0
if size == 'S' | 's':
bill += 15
if add_pepperoni == 'Y':
bill += 2
elif s... |
class Solution:
def nextGreaterElement(self, nums1, nums2):
# Write your code here
answer = {}
stack = []
for x in nums2:
while stack and stack[-1] < x:
answer[stack[-1]] = x
del stack[-1]
stack.append(x)
for x in stack... | class Solution:
def next_greater_element(self, nums1, nums2):
answer = {}
stack = []
for x in nums2:
while stack and stack[-1] < x:
answer[stack[-1]] = x
del stack[-1]
stack.append(x)
for x in stack:
answer[x] = -1
... |
"""
escopo
"""
variavel = 'valor'
def func():
print(variavel)
def func2():
global variavel
variavel = 'outro valor'
print(variavel)
def func3():
print(variavel)
func()
func2()
func3()
| """
escopo
"""
variavel = 'valor'
def func():
print(variavel)
def func2():
global variavel
variavel = 'outro valor'
print(variavel)
def func3():
print(variavel)
func()
func2()
func3() |
def move_disk(fp,tp):
print("moving disk from",fp,"to",tp)
def move_tower(heigth,from_pole,to_pole,with_pole):
if heigth>=1:
move_tower(heigth-1,from_pole, with_pole, to_pole)
move_disk(from_pole,to_pole)
move_tower(heigth-1,with_pole,to_pole,from_pole)
def move_disk(fp,tp):
print("m... | def move_disk(fp, tp):
print('moving disk from', fp, 'to', tp)
def move_tower(heigth, from_pole, to_pole, with_pole):
if heigth >= 1:
move_tower(heigth - 1, from_pole, with_pole, to_pole)
move_disk(from_pole, to_pole)
move_tower(heigth - 1, with_pole, to_pole, from_pole)
def move_disk(... |
## Beginner Series #3 Sum of Numbers
## 7 kyu
## https://www.codewars.com/kata/55f2b110f61eb01779000053
def get_sum(a,b):
if a == b:
return a
elif a < b:
return sum([i for i in range(a, b+1)])
elif b < a:
return sum([i for i in range(b, a+1)]) | def get_sum(a, b):
if a == b:
return a
elif a < b:
return sum([i for i in range(a, b + 1)])
elif b < a:
return sum([i for i in range(b, a + 1)]) |
load(":repositories.bzl", "csharp_repos")
# NOTE: THE RULES IN THIS FILE ARE KEPT FOR BACKWARDS COMPATIBILITY ONLY.
# Please use the rules in repositories.bzl
def csharp_proto_compile(**kwargs):
print("Import of rules in deps.bzl is deprecated, please use repositories.bzl")
csharp_repos(**kwargs)
def c... | load(':repositories.bzl', 'csharp_repos')
def csharp_proto_compile(**kwargs):
print('Import of rules in deps.bzl is deprecated, please use repositories.bzl')
csharp_repos(**kwargs)
def csharp_grpc_compile(**kwargs):
print('Import of rules in deps.bzl is deprecated, please use repositories.bzl')
csharp... |
def count():
x=1
while x<10000:
yield x
x+=1
for x in count():
print(x) | def count():
x = 1
while x < 10000:
yield x
x += 1
for x in count():
print(x) |
#sorted(iterable, key=key, reverse=reverse)
# List
x = ['q', 'w', 'r', 'e', 't', 'y']
print (sorted(x))
# Tuple
x = ('q', 'w', 'e', 'r', 't', 'y')
print (sorted(x))
# String-sorted based on ASCII translations
x = "python"
print (sorted(x))
# Dictionary
x = {'q':1, 'w':2, 'e':3, 'r':4,... | x = ['q', 'w', 'r', 'e', 't', 'y']
print(sorted(x))
x = ('q', 'w', 'e', 'r', 't', 'y')
print(sorted(x))
x = 'python'
print(sorted(x))
x = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}
print(sorted(x))
x = {'q', 'w', 'e', 'r', 't', 'y'}
print(sorted(x))
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print(sorted(x))
l... |
class Graph(object):
"""docstring for Graph"""
def __init__(self):
self.edges = {}
self.numVertices = 0
self.start = ""
self.end = ""
def neighbors(self, id):
return self.edges[id]
def cost(self, current, next):
for x in self.edges[current]:
if x[1] == next:
return x[0]
| class Graph(object):
"""docstring for Graph"""
def __init__(self):
self.edges = {}
self.numVertices = 0
self.start = ''
self.end = ''
def neighbors(self, id):
return self.edges[id]
def cost(self, current, next):
for x in self.edges[current]:
... |
# python 3
# (C) Simon Gawlik
# started 8/1/2015
n = 20 #232792560
primes = []
non_primes = []
# find prime numbers up to n
def primes_lt_n (n):
for num in range (2, n + 1):
is_prime = True
for i in range (2, num):
if num % i == 0:
is_prime = False
if i... | n = 20
primes = []
non_primes = []
def primes_lt_n(n):
for num in range(2, n + 1):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
if is_prime:
primes.append(num)
else:
non_primes.append(num)
primes_lt_n(n... |
ages = [34, 87, 35, 31, 19, 44, 16]
odds = [age for age in ages if age % 2 == 1]
print(odds)
friends = ['Rolf', 'james', 'Sam', 'alex', 'Louise']
guests = ['jose', 'benjamin', 'Mark', 'Alex', 'Sophie', 'michelle', 'rolf']
lower_case_friends = [friend.lower() for friend in friends]
lower_case_guests = [guest.lower()... | ages = [34, 87, 35, 31, 19, 44, 16]
odds = [age for age in ages if age % 2 == 1]
print(odds)
friends = ['Rolf', 'james', 'Sam', 'alex', 'Louise']
guests = ['jose', 'benjamin', 'Mark', 'Alex', 'Sophie', 'michelle', 'rolf']
lower_case_friends = [friend.lower() for friend in friends]
lower_case_guests = [guest.lower() for... |
# -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of web_readonly_bypass,
# an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# web_readonly_bypass is free software:
# you can redistribute it and/or m... | {'name': 'Read Only ByPass', 'version': '8.0.1.0.1', 'author': 'ACSONE SA/NV, Odoo Community Association (OCA)', 'maintainer': 'ACSONE SA/NV,Odoo Community Association (OCA)', 'website': 'http://www.acsone.eu', 'category': 'Technical Settings', 'depends': ['web'], 'summary': 'Allow to save onchange modifications to rea... |
#
# PySNMP MIB module POLICY-BASED-MANAGEMENT-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/POLICY-BASED-MANAGEMENT-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:23:59 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) ... |
"""
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
"""
class Solution:
def findComplement(self, num: int) -> int:
bin_num = bin(num)[2:]
return int(str(int(len(bin_num) * '1') - int(bin_num)), 2)
| """
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
"""
class Solution:
def find_complement(self, num: int) -> int:
bin_num = bin(num)[2:]
return int(str(int(len(bin_num) * '1') - int(bin_num)), 2) |
#!/usr/bin/env python3
def reverse(input: str) -> str:
if len(input) < 2:
return input
return input[-1] + reverse(input[1:-1]) + input[0]
def reverse_iter(input: str) -> str:
ret = ""
for i in range(len(input)):
ret += input[len(input)-1-i]
return ret
if __name__ == '__main__... | def reverse(input: str) -> str:
if len(input) < 2:
return input
return input[-1] + reverse(input[1:-1]) + input[0]
def reverse_iter(input: str) -> str:
ret = ''
for i in range(len(input)):
ret += input[len(input) - 1 - i]
return ret
if __name__ == '__main__':
string = input('Str... |
#cubes
list = []
for number in range(1,11):
list.append(number**3)
for number in list:
print(number)
| list = []
for number in range(1, 11):
list.append(number ** 3)
for number in list:
print(number) |
class decorate:
def __init__(self, arg1=None, arg2=None):
self.arg1 = arg1
self.arg2 = arg2
def __call__(self, method):
def wrapper():
print('ARG1 = %s, ARG2 = %s' % ( str(self.arg1), str(self.arg2)) )
method()
return wrapper
@decorate('the decoration... | class Decorate:
def __init__(self, arg1=None, arg2=None):
self.arg1 = arg1
self.arg2 = arg2
def __call__(self, method):
def wrapper():
print('ARG1 = %s, ARG2 = %s' % (str(self.arg1), str(self.arg2)))
method()
return wrapper
@decorate('the decoration', ... |
class Team:
""" A class for creating a team with an attacking, defending and overall attribute"""
def __init__(self, name, player1, player2, player3, player4, player5):
self.name = name
self.player1 = player1
self.player2 = player2
self.player3 = player3
... | class Team:
""" A class for creating a team with an attacking, defending and overall attribute"""
def __init__(self, name, player1, player2, player3, player4, player5):
self.name = name
self.player1 = player1
self.player2 = player2
self.player3 = player3
self.player4 = p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-10
Last_modify: 2016-03-10
******************************************
'''
'''
Say you have an array for which the ith el... | """
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-10
Last_modify: 2016-03-10
******************************************
"""
'\nSay you have an array for which the ith element is the price of\na given stock on day i.\n... |
def Typename(name):
class TypeN(type):
def __repr__(cls):
return name
return TypeN
| def typename(name):
class Typen(type):
def __repr__(cls):
return name
return TypeN |
# https://leetcode.com/problems/maximum-number-of-balls-in-a-box
def get_box(ball):
count = 0
while ball > 0:
count += ball % 10
ball //= 10
return count
def count_balls(low_limit, high_limit):
hash_counter = {}
for ball in range(low_limit, high_limit + 1):
... | def get_box(ball):
count = 0
while ball > 0:
count += ball % 10
ball //= 10
return count
def count_balls(low_limit, high_limit):
hash_counter = {}
for ball in range(low_limit, high_limit + 1):
box = get_box(ball)
if box in hash_counter:
hash_counter[box] ... |
"""
Problem #5
"""
# cons implementation
def cons(a,b):
return lambda f: f(a,b)
def car(func):
f1 = lambda a,b :a
return func(f1)
def cdr(func):
f2 = lambda a,b:b
return func(f2)
if __name__ == "__main__":
assert car(cons(3,4)) == 3
assert cdr(cons(3,4)) == 4
| """
Problem #5
"""
def cons(a, b):
return lambda f: f(a, b)
def car(func):
f1 = lambda a, b: a
return func(f1)
def cdr(func):
f2 = lambda a, b: b
return func(f2)
if __name__ == '__main__':
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4 |
def removeDuplicates(nums):
if not nums:
return 0
slow = 1
for fast in range(1, len(nums)):
if nums[fast] != nums[slow-1]:
nums[slow] = nums[fast]
slow += 1
return slow
if __name__ == '__main__':
print(removeDuplicates([0,0,1,1,1,2,2,3,3,4]))
print(rem... | def remove_duplicates(nums):
if not nums:
return 0
slow = 1
for fast in range(1, len(nums)):
if nums[fast] != nums[slow - 1]:
nums[slow] = nums[fast]
slow += 1
return slow
if __name__ == '__main__':
print(remove_duplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
... |
# Magnum IO Developer Environment container recipe
Stage0 += comment('GENERATED FILE, DO NOT EDIT')
Stage0 += baseimage(image='nvcr.io/nvidia/cuda:11.4.0-devel-ubuntu20.04')
# GDS 1.0 is part of the CUDA base image
Stage0 += nsight_systems(cli=True, version='2021.2.1')
Stage0 += mlnx_ofed(version='5.3-1.0.0.1')
Stag... | stage0 += comment('GENERATED FILE, DO NOT EDIT')
stage0 += baseimage(image='nvcr.io/nvidia/cuda:11.4.0-devel-ubuntu20.04')
stage0 += nsight_systems(cli=True, version='2021.2.1')
stage0 += mlnx_ofed(version='5.3-1.0.0.1')
stage0 += gdrcopy(ldconfig=True, version='2.2')
stage0 += ucx(version='1.10.1', cuda=True, gdrcopy=... |
class IterationTimeoutError(Exception):
pass
class AlreadyRunningError(Exception):
pass
class TimeoutError(Exception):
pass
class MissingCredentialsError(Exception):
pass
class IncompleteCredentialsError(Exception):
pass
class FileNotFoundError(Exception):
pass
| class Iterationtimeouterror(Exception):
pass
class Alreadyrunningerror(Exception):
pass
class Timeouterror(Exception):
pass
class Missingcredentialserror(Exception):
pass
class Incompletecredentialserror(Exception):
pass
class Filenotfounderror(Exception):
pass |
class Solution(object):
def isValid(self, s):
stack = []
for word in s:
#print word
if word == "{" or word == "[" or word == "(":
stack.append(word)
elif word == "}" or word == "]"or word == ")":
if len(stack)==0:
... | class Solution(object):
def is_valid(self, s):
stack = []
for word in s:
if word == '{' or word == '[' or word == '(':
stack.append(word)
elif word == '}' or word == ']' or word == ')':
if len(stack) == 0:
return False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.