content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class DPANodeTypeSpecification:
def is_satisfied_by(self, dpa_node):
classname = dpa_node.__class__.__name__
return (classname == 'DPANode')
| class Dpanodetypespecification:
def is_satisfied_by(self, dpa_node):
classname = dpa_node.__class__.__name__
return classname == 'DPANode' |
def empty(x):
if x:
return False
else:
return True
| def empty(x):
if x:
return False
else:
return True |
# O(n^2)
def reverse_string(string):
if len(string) == 0:
return string
return reverse_string(string[1:]) + string[0]
if __name__ == '__main__':
print(reverse_string('Eashan'))
| def reverse_string(string):
if len(string) == 0:
return string
return reverse_string(string[1:]) + string[0]
if __name__ == '__main__':
print(reverse_string('Eashan')) |
__all__ = ('Validator',)
class Validator(object):
def validate(self, arg_list, starting_index):
raise NotImplementedError
| __all__ = ('Validator',)
class Validator(object):
def validate(self, arg_list, starting_index):
raise NotImplementedError |
# This code is linked with 'Challenge_16.py'.
def max_finder(a_list):
max_in_list = a_list[0]
for index in range(1, len(a_list)):
if a_list[index] > max_in_list:
max_in_list = a_list[index]
return max_in_list
| def max_finder(a_list):
max_in_list = a_list[0]
for index in range(1, len(a_list)):
if a_list[index] > max_in_list:
max_in_list = a_list[index]
return max_in_list |
##Variable Assignment and Printing
#Strings
#Quotes
'single quotes' #Generally used for regular expressions such as dict keys or SQL
"Double quotes" #Used for representing Strings
#Printing
x = "Hello World!" # Assigns statement/String "Hello World!" to var x
print(x) # Prints current value of instantiated var
#form... | """single quotes"""
'Double quotes'
x = 'Hello World!'
print(x)
x = 'Hello'
y = 'World!'
print('{} {}'.format(x, y))
x = 'Hello'
y = 'World!'
print('{one} {two}'.format(two=y, one=x)) |
N, M = map(int, input().split())
C = list(map(int,input().split()))
INF = 10**10
dp = [[INF]*(N+1) for _ in range(M+1)]
dp[0][0] = 0
for m in range(M):
for n in range(N+1):
if n-C[m]>=0:
dp[m+1][n] = min(dp[m+1][n-C[m]]+1, dp[m][n])
else:
dp[m+1][n] = dp[m][n]
print (dp[M][N]... | (n, m) = map(int, input().split())
c = list(map(int, input().split()))
inf = 10 ** 10
dp = [[INF] * (N + 1) for _ in range(M + 1)]
dp[0][0] = 0
for m in range(M):
for n in range(N + 1):
if n - C[m] >= 0:
dp[m + 1][n] = min(dp[m + 1][n - C[m]] + 1, dp[m][n])
else:
dp[m + 1][n]... |
#!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if my_list:
for i in range(len(my_list) - 1, -1, -1):
print("{:d}".format(my_list[i]))
| def print_reversed_list_integer(my_list=[]):
if my_list:
for i in range(len(my_list) - 1, -1, -1):
print('{:d}'.format(my_list[i])) |
class BinaryImage(object):
def __init__(self,b):
self.b=b
def _determineColorValue(self):
v = 255*self.b
return ("#%02x%02x%02x" % (v, v, v))
| class Binaryimage(object):
def __init__(self, b):
self.b = b
def _determine_color_value(self):
v = 255 * self.b
return '#%02x%02x%02x' % (v, v, v) |
x:int = 1
y:int = 2
a:bool = True
b:bool = False
c:str = ""
d:str = ""
b = a
printf("%d", x != y)
x = y
printf("%d", x == y)
x = 2
y = 2
printf("%d", x == y)
x = y = 0
printf("%d", x == 0)
printf("%d", y == 0)
printf("%d", a == b)
b = False
printf("%d", a != b)
printf("%s", c)
printf("%s", d)
d = c = "123"
printf("... | x: int = 1
y: int = 2
a: bool = True
b: bool = False
c: str = ''
d: str = ''
b = a
printf('%d', x != y)
x = y
printf('%d', x == y)
x = 2
y = 2
printf('%d', x == y)
x = y = 0
printf('%d', x == 0)
printf('%d', y == 0)
printf('%d', a == b)
b = False
printf('%d', a != b)
printf('%s', c)
printf('%s', d)
d = c = '123'
printf... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Echos A Input - Usage: Echo <text>"""
imports = ()
reqcoms = ()
def func(root, display, *args, **kwargs):
display.insert("end", "")
for arg in args:
if arg == "\\n":
display.insert("end", "")
else:
display.in... | """Echos A Input - Usage: Echo <text>"""
imports = ()
reqcoms = ()
def func(root, display, *args, **kwargs):
display.insert('end', '')
for arg in args:
if arg == '\\n':
display.insert('end', '')
else:
display.insert('end', arg, sep='') |
n,m,*a=map(int,open(0).read().split())
s=set(a)
dp=[0,1]+[0]*n
mod=1000000007
for i in range(2,n+2):
if (i-1) not in s:
dp[i]=(dp[i-1]+dp[i-2])%mod
print(dp[n+1])
| (n, m, *a) = map(int, open(0).read().split())
s = set(a)
dp = [0, 1] + [0] * n
mod = 1000000007
for i in range(2, n + 2):
if i - 1 not in s:
dp[i] = (dp[i - 1] + dp[i - 2]) % mod
print(dp[n + 1]) |
class TrieNode(object):
def __init__(self, char):
self.char = char
self.children = []
self.words_count = 0
self.is_word = False
def get_child(self, char):
for child in self.children:
if child.char == char:
return child
return None
cl... | class Trienode(object):
def __init__(self, char):
self.char = char
self.children = []
self.words_count = 0
self.is_word = False
def get_child(self, char):
for child in self.children:
if child.char == char:
return child
return None
cl... |
# -*- coding: utf-8 -*-
"""Document __init__.py here.
Copyright (C) 2020, Auto Trader UK
Created 15. Dec 2020 14:31
"""
| """Document __init__.py here.
Copyright (C) 2020, Auto Trader UK
Created 15. Dec 2020 14:31
""" |
# Expressing a percentage
points = 19
total = 22
print('Correct answers: {:.2%}'.format(points/total))
| points = 19
total = 22
print('Correct answers: {:.2%}'.format(points / total)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_dfs_n.py
# Create Date: 2015-03-03 14:53:53
# Usage: AC_dfs_n.py
# Descripton:
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_valid_bst(self, root):
def dfs(root, minval, maxval):
if root is None:
return True
return minval < root.val < maxval and dfs(r... |
# checking if condition
for i in range (1,101):
if(((i % 3) == 0) and ((i % 5) == 0)):
print('FuzzBuzz')
elif ((i % 3) == 0):
print('Fuzz')
elif ((i % 5) == 0):
print('Buzz')
else:
print(i) | for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print('FuzzBuzz')
elif i % 3 == 0:
print('Fuzz')
elif i % 5 == 0:
print('Buzz')
else:
print(i) |
{
"target_defaults": {
"default_configuration": "Release",
"configurations": {
"Debug" : { "defines": ["_DEBUG"] },
"Release": { "defines": ["NDEBUG"] }
},
"conditions": [
["OS=='linux' or OS=='mac'", {
"cflags": ["-fvisibility=hidden"]
}]
]
},
"targets": [{
... | {'target_defaults': {'default_configuration': 'Release', 'configurations': {'Debug': {'defines': ['_DEBUG']}, 'Release': {'defines': ['NDEBUG']}}, 'conditions': [["OS=='linux' or OS=='mac'", {'cflags': ['-fvisibility=hidden']}]]}, 'targets': [{'target_name': 'njs-test', 'sources': ['njs_test.cpp', 'njs_test_p.h']}]} |
REQUEST_STATUS_CHOICES = (
('Pending', 'Pending'),
('Accepted', 'Accepted'),
('Rejected', 'Rejected'),
('Blocked', 'Blocked'),
)
CAUSE_CATEGORY_CHOICES = (
('Animals', 'Animals'),
('Environment', 'Environment'),
('Humans', 'Humans'),
)
| request_status_choices = (('Pending', 'Pending'), ('Accepted', 'Accepted'), ('Rejected', 'Rejected'), ('Blocked', 'Blocked'))
cause_category_choices = (('Animals', 'Animals'), ('Environment', 'Environment'), ('Humans', 'Humans')) |
__all__ = (
'WumpyException', 'ExtensionFailure'
)
class WumpyException(Exception):
"""Base exception that all other exceptions from the library subclass."""
pass
class ConnectionClosed(WumpyException):
"""Exception raised when the WebSocket to the Discord gateway was closed."""
pass
class Com... | __all__ = ('WumpyException', 'ExtensionFailure')
class Wumpyexception(Exception):
"""Base exception that all other exceptions from the library subclass."""
pass
class Connectionclosed(WumpyException):
"""Exception raised when the WebSocket to the Discord gateway was closed."""
pass
class Commandexcep... |
class C:
def __init__(self, x):
self.x = x
def m1(self): return f"calling m1 from C, x = {self.x}"
def m2(self): return f"calling m2 from C, x = {self.x}"
class Proxy(object):
def __init__(self, prototype):
self.prototype = prototype
def m2(self):
self.x = 10
retur... | class C:
def __init__(self, x):
self.x = x
def m1(self):
return f'calling m1 from C, x = {self.x}'
def m2(self):
return f'calling m2 from C, x = {self.x}'
class Proxy(object):
def __init__(self, prototype):
self.prototype = prototype
def m2(self):
self.x... |
class Discount:
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
def calculate_for(self, quantity):
return quantity // self.quantity * self.price
class PricePolicy:
def __init__(self, original_price, discounts=None):
self.original_price = or... | class Discount:
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
def calculate_for(self, quantity):
return quantity // self.quantity * self.price
class Pricepolicy:
def __init__(self, original_price, discounts=None):
self.original_price = o... |
coordinates_E0E1E1 = ((125, 112),
(126, 112), (126, 115), (126, 129), (127, 112), (127, 116), (127, 129), (127, 130), (128, 113), (128, 115), (128, 117), (128, 129), (128, 130), (129, 114), (129, 117), (129, 129), (129, 130), (130, 115), (130, 117), (130, 120), (130, 129), (131, 105), (131, 107), (131, 116), (131, 11... | coordinates_e0_e1_e1 = ((125, 112), (126, 112), (126, 115), (126, 129), (127, 112), (127, 116), (127, 129), (127, 130), (128, 113), (128, 115), (128, 117), (128, 129), (128, 130), (129, 114), (129, 117), (129, 129), (129, 130), (130, 115), (130, 117), (130, 120), (130, 129), (131, 105), (131, 107), (131, 116), (131, 11... |
def solution(participant=None, completion=None):
answer = ''
if not isinstance(participant, list) or not isinstance(completion, list):
return answer
participant.sort()
completion.sort()
for i, j in zip(participant, completion):
if i != j:
return i
answer = participan... | def solution(participant=None, completion=None):
answer = ''
if not isinstance(participant, list) or not isinstance(completion, list):
return answer
participant.sort()
completion.sort()
for (i, j) in zip(participant, completion):
if i != j:
return i
answer = participa... |
# -*- coding: utf-8 -*-
"""
ontraportlib.models.sort_dir_enum
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ) on 11/14/2017
"""
class SortDirEnum(object):
"""Implementation of the 'SortDir' enum.
TODO: type enum description here.
Attributes:
... | """
ontraportlib.models.sort_dir_enum
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ) on 11/14/2017
"""
class Sortdirenum(object):
"""Implementation of the 'SortDir' enum.
TODO: type enum description here.
Attributes:
ASC: TODO: type description here.
... |
no_mutation = {
'soc_lower': 0,
'soc_upper': 0,
'charge_price_lower': 0,
'charge_price_upper': 0,
'discharge_price_lower': 0,
'discharge_price_upper': 0
}
aggressive_mutation = {
'charge_price_lower': -5,
'charge_price_upper': 0,
'discharge_price_lower': 0,
'discharge_price_uppe... | no_mutation = {'soc_lower': 0, 'soc_upper': 0, 'charge_price_lower': 0, 'charge_price_upper': 0, 'discharge_price_lower': 0, 'discharge_price_upper': 0}
aggressive_mutation = {'charge_price_lower': -5, 'charge_price_upper': 0, 'discharge_price_lower': 0, 'discharge_price_upper': 5}
small_mutation = {'soc_lower': -2, 's... |
# -*- coding: utf-8 -*-
class firstInFirstOut:
def processData(self, listOfNumbers):
#takes only the first element of each tuple
n = 0
arrivalTimeList = [x[n] for x in listOfNumbers]
#takes only the second element of each tuple
n = 1
burstTimeList = [x[n] for x in l... | class Firstinfirstout:
def process_data(self, listOfNumbers):
n = 0
arrival_time_list = [x[n] for x in listOfNumbers]
n = 1
burst_time_list = [x[n] for x in listOfNumbers]
process_data = []
for i in range(len(listOfNumbers)):
temporary = []
pr... |
#(C) Copyright [2022] American Megatrends International LLC
#
#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 ... | """
from config.config import CONFIG_DATA
import logging
import json
from utilities.client import Client
from config import constants
from http import HTTPStatus
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class EventSubscription():
def __init__(self):
self.client =... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
... | class Solution:
def recover_tree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
nums = []
inorder_travel(root, nums)
inorder_set(root, sorted(nums))
def inorder_travel(root: TreeNode, nums) -> None:
if not root:
... |
def string_format_s(arg1):
return 'this is %s' % arg1
def string_format(arg1):
return 'this is {}'.format(arg1)
def string_format_f(arg1):
return f'this is {arg1}'
def string_format_f_multiple(arg1, arg2, arg3):
return f'{arg2} this is {arg1}! {arg3}'
def string_format_multiple(arg1, arg2, arg3)... | def string_format_s(arg1):
return 'this is %s' % arg1
def string_format(arg1):
return 'this is {}'.format(arg1)
def string_format_f(arg1):
return f'this is {arg1}'
def string_format_f_multiple(arg1, arg2, arg3):
return f'{arg2} this is {arg1}! {arg3}'
def string_format_multiple(arg1, arg2, arg3):
... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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, merge, p... | """
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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, merge, p... |
"""
Copyright 2013 Rackspace
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 writing, software
dist... | """
Copyright 2013 Rackspace
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 writing, software
dist... |
'''
It's Magic
Sussutu is a world-renowned magician. And recently, he was blessed with the power to remove EXACTLY ONE element from an array.
Given, an array A (index starting from 0) with N elements. Now, Sussutu CAN remove only that element which makes the sum of ALL the remaining elements exactly divisible by 7.
Th... | """
It's Magic
Sussutu is a world-renowned magician. And recently, he was blessed with the power to remove EXACTLY ONE element from an array.
Given, an array A (index starting from 0) with N elements. Now, Sussutu CAN remove only that element which makes the sum of ALL the remaining elements exactly divisible by 7.
Th... |
class Duck:
def quack(self):
return 'quack!'
def swim(self):
return 'I can swim!'
def display(self):
return 'I am a duck!'
class MallardDuck(Duck):
def display(self):
return 'I am a mallard duck ^^'
class RedheadDuck(Duck):
def display(self):
return 'I am a redhead duck @_@'
class ... | class Duck:
def quack(self):
return 'quack!'
def swim(self):
return 'I can swim!'
def display(self):
return 'I am a duck!'
class Mallardduck(Duck):
def display(self):
return 'I am a mallard duck ^^'
class Redheadduck(Duck):
def display(self):
return 'I ... |
class Scene:
def __init__(self, display):
self._entities = []
self._display = display
def addEntity(self, entity):
self._entities.append(entity)
def update(self, events, delta):
for entity in self._entities:
entity.update(delta)
def draw(self, screen):
for entity in self._entities:
e... | class Scene:
def __init__(self, display):
self._entities = []
self._display = display
def add_entity(self, entity):
self._entities.append(entity)
def update(self, events, delta):
for entity in self._entities:
entity.update(delta)
def draw(self, screen):
... |
# https://leetcode.com/problems/two-sum/
# Given an array of integers, return indices of the two numbers such
# that they add up to a specific target.
# You may assume that each input would have exactly one solution, and
# you may not use the same element twice.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,... | class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
hash = {}
for (index, value) in enumerate(nums):
if target - value in hash:
return (hash[target - value], index)
hash[value] = index |
# House Robber III 337
# ttungl@gmail.com
# The thief has found himself a new place for his thievery again.
# There is only one entrance to this area, called the "root."
# Besides the root, each house has one and only one parent house.
# After a tour, the smart thief realized that
# "all houses in this place forms ... | class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def robsub(root):
if not root:
return (0, 0)
(leftrob, rightrob) = (robsub(root.left), robsub(root.right))
(first, second) = (root.val +... |
# uninhm
# https://atcoder.jp/contests/abc162/tasks/abc162_b
# simulation
ans = 0
for i in range(int(input())+1):
if not (i%3 == 0 or i%5 == 0):
ans += i
print(ans)
| ans = 0
for i in range(int(input()) + 1):
if not (i % 3 == 0 or i % 5 == 0):
ans += i
print(ans) |
BOARDING_TRANS = str.maketrans({"F": "0", "B": "1", "L": "0", "R": "1"})
def boarding_pass_to_seat_id(boarding_pass: str) -> int:
return int(boarding_pass.translate(BOARDING_TRANS), 2)
def find_hole_in_list(numbers: list) -> int:
expected_sum = 0.5 * (len(numbers) + 1) * (min(numbers) + max(numbers))
retu... | boarding_trans = str.maketrans({'F': '0', 'B': '1', 'L': '0', 'R': '1'})
def boarding_pass_to_seat_id(boarding_pass: str) -> int:
return int(boarding_pass.translate(BOARDING_TRANS), 2)
def find_hole_in_list(numbers: list) -> int:
expected_sum = 0.5 * (len(numbers) + 1) * (min(numbers) + max(numbers))
retu... |
# import math
# import os
# import random
# import re
# import sys
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def gradingStudents(grades):
aut_list = []
for grade in grades:
if... | def grading_students(grades):
aut_list = []
for grade in grades:
if grade >= 38 and grade % 5 != 0:
dif_next_multiple = 0
check_grade = grade
while check_grade % 5 != 0:
check_grade += 1
dif_next_multiple += 1
if dif_next_mu... |
def key_value_help():
print("Hello !")
print("Let's Dive Deep and see the Features of this App - \n\n")
print("--help or -h - For help")
print("set - For Setting Key Value Pair")
print("get - For Getting Key Value Pair")
print("Thanks\nArchit Kumar Dwevedi")
def key_value_invalid():
print... | def key_value_help():
print('Hello !')
print("Let's Dive Deep and see the Features of this App - \n\n")
print('--help or -h - For help')
print('set - For Setting Key Value Pair')
print('get - For Getting Key Value Pair')
print('Thanks\nArchit Kumar Dwevedi')
def key_value_invalid():
print('... |
"""
The function sum_positive_numbers should return the sum of all positive numbers between the number n received and 1.
For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. Let's make this work
"""
# Remeber to define Base case!
def sum_positive_numbers(n):
#The base ... | """
The function sum_positive_numbers should return the sum of all positive numbers between the number n received and 1.
For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. Let's make this work
"""
def sum_positive_numbers(n):
if n < 1:
return n
return n +... |
nome_do_arquivo = input('Digite o nome do arquivo de entrada: ')
# nome_do_arquivo = 'entrada.txt'
conjunto_palavras_caracteres_repetidos = set()
with open(nome_do_arquivo, 'r', encoding='utf8') as arquivo:
for linha in arquivo:
linha = linha.strip()
palavras = linha.split()
for palavra in p... | nome_do_arquivo = input('Digite o nome do arquivo de entrada: ')
conjunto_palavras_caracteres_repetidos = set()
with open(nome_do_arquivo, 'r', encoding='utf8') as arquivo:
for linha in arquivo:
linha = linha.strip()
palavras = linha.split()
for palavra in palavras:
palavra = pal... |
n, m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
| (n, m) = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input()))) |
#
# This is an example configuration.
# Add your own keys and rename it to `slackbot_settings.py`.
#
DEFAULT_REPLY = "Hi! :wave: If you want me to do something, you should tell me what to do."
ERRORS_TO = "your_slack_username_goes_here" # Don't put an @ sign.
PLUGINS = [
'slackbot.plugins'
]
API_AI_KEY = "api... | default_reply = 'Hi! :wave: If you want me to do something, you should tell me what to do.'
errors_to = 'your_slack_username_goes_here'
plugins = ['slackbot.plugins']
api_ai_key = 'api.ai client access token'
api_token = 'slack integration api key'
google_calendar_id = 'something@group.calendar.google'
send_at = '9:00'... |
"""
https://programmers.co.kr/learn/courses/30/lessons/42577
"""
def solution(phone_book):
phone_book.sort()
for i in range(len(phone_book)-1):
if phone_book[i] == phone_book[i+1][:len(phone_book[i])]:
return False
return True | """
https://programmers.co.kr/learn/courses/30/lessons/42577
"""
def solution(phone_book):
phone_book.sort()
for i in range(len(phone_book) - 1):
if phone_book[i] == phone_book[i + 1][:len(phone_book[i])]:
return False
return True |
def main():
myList = [i for i in range(1, 101) if i%4 == 0]
return print(myList)
if __name__=="__main__":
main() | def main():
my_list = [i for i in range(1, 101) if i % 4 == 0]
return print(myList)
if __name__ == '__main__':
main() |
10 (0, 0)
100 (7, 17)
1000 (70, 325)
10000 (703, 4858)
100000 (7026, 64741)
1000000 (70229, 808950)
10000000 (702309, 9706567)
| 10(0, 0)
100(7, 17)
1000(70, 325)
10000(703, 4858)
100000(7026, 64741)
1000000(70229, 808950)
10000000(702309, 9706567) |
a=4
b=5
c=a+b
print("the value of a+b is : ",c)
| a = 4
b = 5
c = a + b
print('the value of a+b is : ', c) |
"""PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter
print_big('a')
out: *
* *
*****
* *
* *
HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purpose... | """PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter
print_big('a')
out: *
* *
*****
* *
* *
HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purpose... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
if not head:
return None
p = head
while p.next:
... | class Solution(object):
def remove_elements(self, head, val):
if not head:
return None
p = head
while p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return head.next if head.val == val else head |
# 1) swapcase = Convert uppercase characters to lowercase and lowercase characters to uppercase
x="python"
print(x.swapcase())
# 2) casefold = Convert in lowercase
print(x.casefold())
# 3) capitalize = More specifically, make the first character have upper case and the rest lower case
print(x.capitalize())
# 4) t... | x = 'python'
print(x.swapcase())
print(x.casefold())
print(x.capitalize())
print(x.title()) |
class Solution:
def minMalwareSpread(self, matrix: List[List[int]], initial: List[int]) -> int:
graph = collections.defaultdict(list)
for i, row in enumerate(matrix):
for j, val in enumerate(row):
if val == 1:
graph[i].append(j)
inf_relations =... | class Solution:
def min_malware_spread(self, matrix: List[List[int]], initial: List[int]) -> int:
graph = collections.defaultdict(list)
for (i, row) in enumerate(matrix):
for (j, val) in enumerate(row):
if val == 1:
graph[i].append(j)
inf_rela... |
description = 'Dilatometer'
group = 'optional'
includes = ['alias_T']
tango_base = 'tango://stressictrl.stressi.frm2:10000/stressi/dilato/'
devices = {
'Ts_dil': device('nicos.devices.tango.Sensor',
description = 'The sample temperature',
tangodevice = tango_base + 'temp',
pollinterval =... | description = 'Dilatometer'
group = 'optional'
includes = ['alias_T']
tango_base = 'tango://stressictrl.stressi.frm2:10000/stressi/dilato/'
devices = {'Ts_dil': device('nicos.devices.tango.Sensor', description='The sample temperature', tangodevice=tango_base + 'temp', pollinterval=2.0), 'dil_time': device('nicos.device... |
class ApiConfig:
"""class that store Api configuration added in ApiConfig instance
Store Configs passed to ApiConfig and provide a search class
method to retrieve configs by 'name'
Exception:
NotImplementedError:
Call the '__init__' special method is not allowed
it r... | class Apiconfig:
"""class that store Api configuration added in ApiConfig instance
Store Configs passed to ApiConfig and provide a search class
method to retrieve configs by 'name'
Exception:
NotImplementedError:
Call the '__init__' special method is not allowed
it ra... |
def triangle_star(row):
for x in range(1,row+1):
for k in range(x):
print("*",end=" ")
print("")
x = input("How many rows : ")
try :
x = int(x)
triangle_star(x)
except ValueError:
print("Please enter number only")
| def triangle_star(row):
for x in range(1, row + 1):
for k in range(x):
print('*', end=' ')
print('')
x = input('How many rows : ')
try:
x = int(x)
triangle_star(x)
except ValueError:
print('Please enter number only') |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def min_diff_in_BST(self, root: TreeNode) -> int:
left = float('inf')
right = float('inf')
if root.left:
left = min(abs(root.val - self.max(root.le... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def min_diff_in_bst(self, root: TreeNode) -> int:
left = float('inf')
right = float('inf')
if root.left:
left = min(abs(root.val - self.max(root.l... |
def possible_player_pairs(array) :
lenArr = len(array)
if (lenArr <= 0):
return []
if (lenArr == 1):
return array
results = []
for i in range(0, lenArr - 1):
for j in range(i + 1, lenArr):
results.append(array[i] + array[j])
return results
def count_player_pairs(n) :
if (n <= 0):... | def possible_player_pairs(array):
len_arr = len(array)
if lenArr <= 0:
return []
if lenArr == 1:
return array
results = []
for i in range(0, lenArr - 1):
for j in range(i + 1, lenArr):
results.append(array[i] + array[j])
return results
def count_player_pairs(... |
class APIError(Exception):
error_code = 1000
log_message = "API Error"
send_to_sentry = False
request_id = None
def __init__(self, request_id=None, message=None):
if message is not None:
self.log_message = message
self.request_id = request_id
def __str__(self):
... | class Apierror(Exception):
error_code = 1000
log_message = 'API Error'
send_to_sentry = False
request_id = None
def __init__(self, request_id=None, message=None):
if message is not None:
self.log_message = message
self.request_id = request_id
def __str__(self):
... |
class InvalidRequestObject(object):
def __init__(self):
self.errors = list()
def __nonzero__(self):
return False
__bool__ = __nonzero__
def add_error(self, parameter, value):
self.errors.append({'parameter': parameter, 'message': value})
def has_errors(self):
retu... | class Invalidrequestobject(object):
def __init__(self):
self.errors = list()
def __nonzero__(self):
return False
__bool__ = __nonzero__
def add_error(self, parameter, value):
self.errors.append({'parameter': parameter, 'message': value})
def has_errors(self):
retu... |
def A():
return ValueError
try: raise ValueError() # breaks
except A(): pass
| def a():
return ValueError
try:
raise value_error()
except a():
pass |
entrada_1 = input().split()
entrada_2 = input().split()
x1, y1 = entrada_1
x2, y2 = entrada_2
distancia = (((float(x2) - float(x1)) ** 2) + ((float(y2) - float(y1)) ** 2))
saida = distancia ** (1/2)
print(f"{saida:.4f}")
| entrada_1 = input().split()
entrada_2 = input().split()
(x1, y1) = entrada_1
(x2, y2) = entrada_2
distancia = (float(x2) - float(x1)) ** 2 + (float(y2) - float(y1)) ** 2
saida = distancia ** (1 / 2)
print(f'{saida:.4f}') |
description = 'Multi tomo setup with four motors in Experimental Chamber 1, currently only 3 motors implemented'
group = 'optional'
tango_base = 'tango://antareshw.antares.frm2.tum.de:10000/antares/'
devices = dict(
sry_multi_1 = device('nicos.devices.entangle.Motor',
description = 'Multitomo sample rota... | description = 'Multi tomo setup with four motors in Experimental Chamber 1, currently only 3 motors implemented'
group = 'optional'
tango_base = 'tango://antareshw.antares.frm2.tum.de:10000/antares/'
devices = dict(sry_multi_1=device('nicos.devices.entangle.Motor', description='Multitomo sample rotation 1', tangodevice... |
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# dp[i] means fewest coins needed to reach amount i
# dp[i] = min(dp[i-coins[p1]] + 1,...dp[i-coins[pn]]+1)
dp = [None for _ in range(amount + 1)]
for coin in coins:
if coin < len(dp):
... | class Solution:
def coin_change(self, coins: List[int], amount: int) -> int:
dp = [None for _ in range(amount + 1)]
for coin in coins:
if coin < len(dp):
dp[coin] = 1
dp[0] = 0
def count_coins(i):
if dp[i] != None:
return dp[i... |
class Solution:
def jump(self, nums: List[int]) -> int:
if not nums or len(nums) == 0:
return 0
n = len(nums)
dp = [float('inf') for _ in range(n)]
dp[0] = 0
for i in range(1, n):
for j in range(i):
if nums[j]... | class Solution:
def jump(self, nums: List[int]) -> int:
if not nums or len(nums) == 0:
return 0
n = len(nums)
dp = [float('inf') for _ in range(n)]
dp[0] = 0
for i in range(1, n):
for j in range(i):
if nums[j] + j >= i:
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
p = dummy = ListNode(-1)
p.next = head
for _ in range(m - 1):
p = p... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverse_between(self, head: ListNode, m: int, n: int) -> ListNode:
p = dummy = list_node(-1)
p.next = head
for _ in range(m - 1):
p = p.next
curr = p.next
... |
# Eve IDs
EVE_CATEGORY_ID_SHIP = 6
EVE_CATEGORY_ID_STRUCTURE = 65
EVE_CATEGORY_ID_FIGHTER = 87
EVE_GROUP_MINING_DRONE = 101
EVE_GROUP_ORBITAL_INFRASTRUCTURE = 1025
| eve_category_id_ship = 6
eve_category_id_structure = 65
eve_category_id_fighter = 87
eve_group_mining_drone = 101
eve_group_orbital_infrastructure = 1025 |
img_width, img_height = 299, 299
num_channels = 3
train_data = 'data/train'
valid_data = 'data/valid'
num_classes = 80
num_train_samples = 53879
num_valid_samples = 7120
verbose = 1
batch_size = 32
num_epochs = 1000
patience = 50
best_model = 'model.11-0.6262.hdf5' | (img_width, img_height) = (299, 299)
num_channels = 3
train_data = 'data/train'
valid_data = 'data/valid'
num_classes = 80
num_train_samples = 53879
num_valid_samples = 7120
verbose = 1
batch_size = 32
num_epochs = 1000
patience = 50
best_model = 'model.11-0.6262.hdf5' |
#
# PySNMP MIB module TAILF-ALARM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TAILF-ALARM-MIB
# Produced by pysmi-0.3.4 at Wed Aug 7 20:00:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.7.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint) ... |
def triangleArea(side, height):
return side * height / 2
side = float(input())
height = float(input())
print(triangleArea(side, height)) | def triangle_area(side, height):
return side * height / 2
side = float(input())
height = float(input())
print(triangle_area(side, height)) |
# a. merge
full = pd.merge(pop, prices_long, on=['date','municipality'], how='left')
full.sort_values(['municipality','date'], inplace=True)
# b. take logs
full['log_population'] = np.log(full['population'])
full['log_price'] = np.log(full['price'])
# c. figur 1: log differences
ax = full.groupby('municipality').di... | full = pd.merge(pop, prices_long, on=['date', 'municipality'], how='left')
full.sort_values(['municipality', 'date'], inplace=True)
full['log_population'] = np.log(full['population'])
full['log_price'] = np.log(full['price'])
ax = full.groupby('municipality').diff(1).plot(x='log_population', y='log_price', kind='scatte... |
def _topic_str(topic_d):
type_ = topic_d.get("type") or topic_d.get("type_str", "topic")
type_str = f', {type_}' if type_ != 'topic' else ''
return f'{topic_d["name"]} ({topic_d["id"]}{type_str})'
def created_connection(plugin, parameters):
return (
f"Created fdbk DB connection of type '{plugi... | def _topic_str(topic_d):
type_ = topic_d.get('type') or topic_d.get('type_str', 'topic')
type_str = f', {type_}' if type_ != 'topic' else ''
return f"{topic_d['name']} ({topic_d['id']}{type_str})"
def created_connection(plugin, parameters):
return f"Created fdbk DB connection of type '{plugin}' with pa... |
class Dictionary:
def get_sub_dictionary(self):
return Dictionary
pass
| class Dictionary:
def get_sub_dictionary(self):
return Dictionary
pass |
"""
Implicit chaining
-> Occurs when an exception is raised incidentally during processing of another.
-> The original exception is stored on the __context__ attribute of the second.
"""
| """
Implicit chaining
-> Occurs when an exception is raised incidentally during processing of another.
-> The original exception is stored on the __context__ attribute of the second.
""" |
# -*- coding: utf-8 -*-
# simple set, constructed by a list, will auto remove duplicated values
s = {1, 1, 2, 3}
print(s)
# duplicated values will not be added
s.add(1)
s.add(4)
print(s)
# remove key
s.remove(4)
print(s)
# set operation
s2 = {2, 3, 4}
print(s2.intersection(s))
print(s2 & s) # shortcut
print(s2.dif... | s = {1, 1, 2, 3}
print(s)
s.add(1)
s.add(4)
print(s)
s.remove(4)
print(s)
s2 = {2, 3, 4}
print(s2.intersection(s))
print(s2 & s)
print(s2.difference(s))
print(s2 - s)
print(s2.union(s))
print(s2 | s) |
def collatz(num):
length = 1
while num != 1:
if num % 2 == 0:
num //= 2
else:
num = 3 * num + 1
length += 1
return length
def solution(num):
max_length = 1
value = 1
for i in range(1, num):
chain_length = collatz(i)
if chain_length... | def collatz(num):
length = 1
while num != 1:
if num % 2 == 0:
num //= 2
else:
num = 3 * num + 1
length += 1
return length
def solution(num):
max_length = 1
value = 1
for i in range(1, num):
chain_length = collatz(i)
if chain_length... |
# coding: utf8
def memory_reallocation_v1(s):
"""memory reallocation."""
cycles = 0
banks = s[:]
ll = len(banks)
seen = []
uk = ''.join(list(map(str, banks)))
while uk not in seen:
seen.append(uk)
key_chosen = banks.index(max(banks))
value_chosen = banks[key_chosen... | def memory_reallocation_v1(s):
"""memory reallocation."""
cycles = 0
banks = s[:]
ll = len(banks)
seen = []
uk = ''.join(list(map(str, banks)))
while uk not in seen:
seen.append(uk)
key_chosen = banks.index(max(banks))
value_chosen = banks[key_chosen]
banks[ke... |
class SignifyError(Exception):
"""Base class for all errors generated by Signify"""
pass
class ParseError(SignifyError):
pass
class SignedPEParseError(ParseError):
pass
class SignerInfoParseError(ParseError):
pass
class AuthenticodeParseError(ParseError):
"""Raised when any exception r... | class Signifyerror(Exception):
"""Base class for all errors generated by Signify"""
pass
class Parseerror(SignifyError):
pass
class Signedpeparseerror(ParseError):
pass
class Signerinfoparseerror(ParseError):
pass
class Authenticodeparseerror(ParseError):
"""Raised when any exception regardi... |
PIXIV_IOS_USER_AGENT = 'PixivIOSApp/4.13.3 (iOS 14.6; iPhone13,2)'
PIXIV_ANDROID_USER_AGENT = "PixivAndroidApp/5.0.234 (Android 11; Pixel 5)"
PIXIV_REQUEST_HEADERS = {
'APP-OS': 'ios',
'APP-OS-Version': '12.6',
'Accept-Language': 'zh-CH;zh;q=0.9;en;q=0.8',
}
| pixiv_ios_user_agent = 'PixivIOSApp/4.13.3 (iOS 14.6; iPhone13,2)'
pixiv_android_user_agent = 'PixivAndroidApp/5.0.234 (Android 11; Pixel 5)'
pixiv_request_headers = {'APP-OS': 'ios', 'APP-OS-Version': '12.6', 'Accept-Language': 'zh-CH;zh;q=0.9;en;q=0.8'} |
__all__ = ['make_site']
def make_site(rep):
if isinstance(rep, Site):
return rep
elif rep is None or isinstance(rep, tuple):
return GridSite(rep)
else:
return Site(rep)
class Site:
def __init__(self, location, placed=True):
self.location = location
self.place... | __all__ = ['make_site']
def make_site(rep):
if isinstance(rep, Site):
return rep
elif rep is None or isinstance(rep, tuple):
return grid_site(rep)
else:
return site(rep)
class Site:
def __init__(self, location, placed=True):
self.location = location
self.placed... |
# See bazel/README.md for details on how this system works.
EXTENSIONS = {
"envoy.filters.http.router": "//source/extensions/filters/http/router:config",
"envoy.filters.network.direct_response": "//source/extensions/filters/network/direct_response:config",
"envoy.filters.network.http_connection_manager": "/... | extensions = {'envoy.filters.http.router': '//source/extensions/filters/http/router:config', 'envoy.filters.network.direct_response': '//source/extensions/filters/network/direct_response:config', 'envoy.filters.network.http_connection_manager': '//source/extensions/filters/network/http_connection_manager:config', 'envo... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... | class Macroexecmode(object):
"""
Const Class
Specify whether a macro can be executed.
**since**
OOo 1.1.2
See Also:
`API MacroExecMode <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1document_1_1MacroExecMode.html>`_
"""
__ooo_ns__: str = ... |
class Solution(object):
def solve(self, board):
# Handle base case
if len(board) == 0 or len(board[0]) == 0:
return board
# Get Mark all Os on the edge and their connected Os
for i in range(len(board)):
for j in range(len(board[0])):
if i == ... | class Solution(object):
def solve(self, board):
if len(board) == 0 or len(board[0]) == 0:
return board
for i in range(len(board)):
for j in range(len(board[0])):
if i == 0 or j == 0 or i == len(board) - 1 or (j == len(board[0]) - 1):
self.... |
"""
The main entry point for player-wearable armor.
This module gives a main entry point for all armor. Currently, this is all
inside one file, but could be split into more. The class :class:`Armor` is the
main entry point of all armor, being the one to define generic stats.
While all armor classes can have more than... | """
The main entry point for player-wearable armor.
This module gives a main entry point for all armor. Currently, this is all
inside one file, but could be split into more. The class :class:`Armor` is the
main entry point of all armor, being the one to define generic stats.
While all armor classes can have more than... |
# bug collector
bugs_total = 0.0
for day in range(5):
print("Enter the collected bugs for day", day + 1, end='')
bugs = int(input(": "))
# add bugs to accumulator
bugs_total += bugs
print()
print("The total bugs collected: ", bugs_total)
| bugs_total = 0.0
for day in range(5):
print('Enter the collected bugs for day', day + 1, end='')
bugs = int(input(': '))
bugs_total += bugs
print()
print('The total bugs collected: ', bugs_total) |
mult_3_5 = lambda x: x%3==0 or x%5==0
print(mult_3_5(3))
print(mult_3_5(4))
print(mult_3_5(5))
def add1():
return lambda x: x + 1
f = add1()
print(f(2))
| mult_3_5 = lambda x: x % 3 == 0 or x % 5 == 0
print(mult_3_5(3))
print(mult_3_5(4))
print(mult_3_5(5))
def add1():
return lambda x: x + 1
f = add1()
print(f(2)) |
""" Root module for the fixtest tool.
Copyright (c) 2014 Kenn Takara
See LICENSE for details
"""
| """ Root module for the fixtest tool.
Copyright (c) 2014 Kenn Takara
See LICENSE for details
""" |
def pattern():
for i in range(len(name)):
# A
if name[i] == "A":
print_A = [[" " for i in range(6)] for j in range(7)]
for row in range(7):
for col in range(6):
if ((col == 0 or col == 3) and (row > 0)) or ((row == 0 or row == 3) and (col =... | def pattern():
for i in range(len(name)):
if name[i] == 'A':
print_a = [[' ' for i in range(6)] for j in range(7)]
for row in range(7):
for col in range(6):
if (col == 0 or col == 3) and row > 0 or ((row == 0 or row == 3) and (col == 1 or col == 2)... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
list1 = [5, 8, 10] #for loops
list2 = ["Ravi", "EMC", "IBM", "Sogeti"]
for i in list1:
print(i)
for j in list2:
print(j)
# In[5]:
print(range(0,10))
for k in range(0,5):
print(k)
# In[9]:
sum = 0
for n in range(1,11):
sum += n
print(sum)
prin... | list1 = [5, 8, 10]
list2 = ['Ravi', 'EMC', 'IBM', 'Sogeti']
for i in list1:
print(i)
for j in list2:
print(j)
print(range(0, 10))
for k in range(0, 5):
print(k)
sum = 0
for n in range(1, 11):
sum += n
print(sum)
print(sum)
counter = 0
while counter < 10:
print(counter)
counter = counter + 1
... |
# test waiting within async with enter/exit functions
# uPy allows normal generators to be awaitables.
# CircuitPython does not.
# In CircuitPython you need to have an __await__ method on an awaitable like in CPython;
# and like in CPython, generators do not have __await__.
class Awaitable:
def __init__(self, x)... | class Awaitable:
def __init__(self, x):
self.x = x
def __await__(self):
print('f start:', self.x)
yield (self.x + 1)
yield (self.x + 2)
return self.x + 3
class Acontext:
async def __aenter__(self):
print('enter')
print('f returned:', await awaitabl... |
class Constant(object):
"""
Constant Class
This class contains all variable constants.
All variables with a variable value will call this class.
"""
# Weight first patch
w_first_patch = 5
# Weight second patch
w_second_patch = 5
# Weight number of inputs
w_number_inputs = 1
... | class Constant(object):
"""
Constant Class
This class contains all variable constants.
All variables with a variable value will call this class.
"""
w_first_patch = 5
w_second_patch = 5
w_number_inputs = 1
first_label_neurons = 32
second_label_neurons = 16
third_label_neurons... |
func_count_dic = {}
userA = {}
userB = {}
def check_fn_docs():
'''
A function check_fn_docs is defined to check whether the input function
has doctring length should be 50 characters.
Input : function name
Output : return nested function.
'''
char_count = 50
def len_docs_... | func_count_dic = {}
user_a = {}
user_b = {}
def check_fn_docs():
"""
A function check_fn_docs is defined to check whether the input function
has doctring length should be 50 characters.
Input : function name
Output : return nested function.
"""
char_count = 50
def len_docs_check(func)... |
# Segments are comprised of 2 main components: Transport and DataProcessingGroup (DPG)
# The Transport represents an mechanism for input objects to be sent to the DPG. The DPG
# is a cluster of different DataProcessor objects each created with a work function. The transport
# does not need to be homogenous as the type ... | class Segment:
def __init__(self, transport, dpGroup, config):
self.transport = transport
self.dpGroup = dpGroup
self.config = config
self.procTypesAndCounts = self.dpGroup.getProcessorMapCounts()
def has_work(self):
queue_has_items = self.transport.size()
dpg_i... |
# print it like this
"""Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are"
"""
print("Twinkle, twinkle, little star,\n\tHow I wonder what you are!\n\t\t... | """Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are"
"""
print('Twinkle, twinkle, little star,\n\tHow I wonder what you are!\n\t\tUp above the world so... |
# DESCRIPTION
# Given a string, sort it in decreasing order based on the frequency of characters.
# Example 1:
# Input:
# "tree"
# Output:
# "eert"
# Explanation:
# 'e' appears twice while 'r' and 't' both appear once.
# So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
# Example ... | class Solution:
"""
Time: O(N LOG N), where N is the length of the string because must sort the dictionary
Space: O(N), space for hashtable of the chars in string
"""
def frequency_sort(self, s: str) -> str:
result = ''
if not s or len(s) == 0:
return result
cha... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def mpmcQueue():
http_archive(
name = "mpmc_queue",
build... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def mpmc_queue():
http_archive(name='mpmc_queue', build_file='//bazel/deps/mpmc_queue:build.BUILD', sha256='675004f332c74390c16efea98f30ebc636a2855434bdbfa24eaa703501a6ae0f', strip... |
sample_event = {
'level': 'error',
'exception': {
'values': [
{
'module': None, 'type': 'TypeError', 'value': 'Testing stuff', 'mechanism': None,
'stacktrace': {
'frames': [
{
'filename': ... | sample_event = {'level': 'error', 'exception': {'values': [{'module': None, 'type': 'TypeError', 'value': 'Testing stuff', 'mechanism': None, 'stacktrace': {'frames': [{'filename': 'microcosm_pubsub/result.py', 'abs_path': '/Users/rob/dev/microcosm-pubsub/microcosm_pubsub/result.py', 'function': 'invoke', 'module': 'mi... |
map_out = {
r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{1,6}(-|\+)\d{2}' : 'YYYY-MM-DD HH:MM:SS.FFFFFF-TZ'
, r'\d{2}:\d{2}:\d{2}.\d{1,6}' : 'HH:MM:SS.FFFFFF'
, r'\d{4}-\d{2}-\d{2}' : 'YYYY-MM-DD'}
test_cases = [
test_case(
cmd=('yb_chunk_dml_by_date_part.py @{argsdir}/yb_chunk_dml_by_date_part__ar... | map_out = {'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{1,6}(-|\\+)\\d{2}': 'YYYY-MM-DD HH:MM:SS.FFFFFF-TZ', '\\d{2}:\\d{2}:\\d{2}.\\d{1,6}': 'HH:MM:SS.FFFFFF', '\\d{4}-\\d{2}-\\d{2}': 'YYYY-MM-DD'}
test_cases = [test_case(cmd='yb_chunk_dml_by_date_part.py @{argsdir}/yb_chunk_dml_by_date_part__args1 --execute_chunk_d... |
'''
Created on 1.12.2016
@author: Darren
''''''
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
... | """
Created on 1.12.2016
@author: Darren
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if t... |
#!/bin/python3
"""
https://www.hackerrank.com/challenges/simple-text-editor/problem
"""
class SimpleTextEditor:
def __init__(self):
self.s = ''
# It works as a stack for storing full copies of previous s.
# However, it might take too much memory resource if s is huge.
self.s_histo... | """
https://www.hackerrank.com/challenges/simple-text-editor/problem
"""
class Simpletexteditor:
def __init__(self):
self.s = ''
self.s_history = []
def add_history(self):
self.s_history.append(self.s)
def append(self, w):
self.s += w
def delete(self, k):
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.