content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def minion_game(string):
# your code goes here
#string = string.lower()
vowel = ['A','E','I','O','U']
kev = 0
stu = 0
n = len(string)
x = n
for i in range(n) :
if string[i] in vowel :
kev += x
else :
stu += x
x -= 1
if kev > stu ... | def minion_game(string):
vowel = ['A', 'E', 'I', 'O', 'U']
kev = 0
stu = 0
n = len(string)
x = n
for i in range(n):
if string[i] in vowel:
kev += x
else:
stu += x
x -= 1
if kev > stu:
print('Kevin', str(kev))
elif kev < stu:
... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incor... | def maintenance_public_configuration_list(client):
return client.list()
def maintenance_public_configuration_show(client, resource_name):
return client.get(resource_name=resource_name)
def maintenance_applyupdate_list(client):
return client.list()
def maintenance_applyupdate_show(client, resource_group_n... |
def day5(fileName, part):
niceCount = 0
with open(fileName) as infile:
for line in infile:
vowels = sum(line.count(vowel) for vowel in "aeiou")
if vowels < 3:
continue
foundDouble = any(line[i] == line[i+1] for i in range(len(line) - 1))
if not foundDouble:
continue
foundBadString = any(badSt... | def day5(fileName, part):
nice_count = 0
with open(fileName) as infile:
for line in infile:
vowels = sum((line.count(vowel) for vowel in 'aeiou'))
if vowels < 3:
continue
found_double = any((line[i] == line[i + 1] for i in range(len(line) - 1)))
... |
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
self.bt(nums, 0, [], res)
return res
def bt(self, nums, idx, tempList, res):
res.append(tempList)
for i in range(idx, len(nums)):
self.bt(nums, i+1, tempList+[n... | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
self.bt(nums, 0, [], res)
return res
def bt(self, nums, idx, tempList, res):
res.append(tempList)
for i in range(idx, len(nums)):
self.bt(nums, i + 1, tempLis... |
''' Exception module '''
class CallGitServerException(Exception):
''' Base Exception for filtering Call Git Server Exceptions '''
STATUS_CODE = 127
class DuplicateRemote(CallGitServerException):
''' Exception throwed when there arent any match with the username '''
STATUS_CODE = 128
def __init_... | """ Exception module """
class Callgitserverexception(Exception):
""" Base Exception for filtering Call Git Server Exceptions """
status_code = 127
class Duplicateremote(CallGitServerException):
""" Exception throwed when there arent any match with the username """
status_code = 128
def __init__(... |
def test(tested_mod, Assert):
test_cases = [
# (expected, input)
([4], [4]),
([9,6], [6,9]),
([4,3,2,1], [4,3,2,1]),
([4,3,2,1], [1,2,3,4]),
([9,5,2,1], [1,5,2,9])
]
return Assert.all(tested_mod.sortierte_zettel, test_cases)
| def test(tested_mod, Assert):
test_cases = [([4], [4]), ([9, 6], [6, 9]), ([4, 3, 2, 1], [4, 3, 2, 1]), ([4, 3, 2, 1], [1, 2, 3, 4]), ([9, 5, 2, 1], [1, 5, 2, 9])]
return Assert.all(tested_mod.sortierte_zettel, test_cases) |
P, Q = map(float, input().split())
p, q = P / 100, Q / 100
a = p * q
b = (1 - p) * (1 - q)
print(a / (a + b) * 100)
| (p, q) = map(float, input().split())
(p, q) = (P / 100, Q / 100)
a = p * q
b = (1 - p) * (1 - q)
print(a / (a + b) * 100) |
##Patterns: E0116
while True:
try:
pass
finally:
##Err: E0116
continue
while True:
try:
pass
finally:
break
while True:
try:
pass
except Exception:
pass
else:
continue
| while True:
try:
pass
finally:
continue
while True:
try:
pass
finally:
break
while True:
try:
pass
except Exception:
pass
else:
continue |
class ESError(Exception):
pass
class ESRegistryError(ESError):
pass
| class Eserror(Exception):
pass
class Esregistryerror(ESError):
pass |
movies = ['The Matrix', 'Fast & Furious',
'Frozen',
'The life of Pi']
for movie in movies: print(movie)
print('We\'re done here!')
| movies = ['The Matrix', 'Fast & Furious', 'Frozen', 'The life of Pi']
for movie in movies:
print(movie)
print("We're done here!") |
# this code is not correct
class Node:
def __init__(self, data, next=None):
self.data=data
self.next = next
def printList(head):
print(head.data)
if head.next == None:
return
return printList(head.next)
def reverseList(head):
if head.next == None:
return head
ne... | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def print_list(head):
print(head.data)
if head.next == None:
return
return print_list(head.next)
def reverse_list(head):
if head.next == None:
return head
nextnext = head.next.ne... |
def rule(event):
return event.get("action") == "Blocked"
def title(event):
return "Access denied to domain " + event.get("domain", "<UNKNOWN_DOMAIN>")
| def rule(event):
return event.get('action') == 'Blocked'
def title(event):
return 'Access denied to domain ' + event.get('domain', '<UNKNOWN_DOMAIN>') |
# Config for OpenMX_viewer
# For Gui
fontFamilies=["Segoe UI", "Yu Gothic UI"]
# font sizes are in unit of pixel
fontSize_normal=16
fontSize_large=24
ContentsMargins=[5,5,5,5]
tickLength=-30
sigma_max=5
Eh=27.2114 # (eV)
# Pen for vLine and hLine
pen1=(0, 255, 0)
pen2=(255, 0, 0)
pen3=(255, 255, 0)
gridAlpha=50 # ... | font_families = ['Segoe UI', 'Yu Gothic UI']
font_size_normal = 16
font_size_large = 24
contents_margins = [5, 5, 5, 5]
tick_length = -30
sigma_max = 5
eh = 27.2114
pen1 = (0, 255, 0)
pen2 = (255, 0, 0)
pen3 = (255, 255, 0)
grid_alpha = 50
plot3_d_min_width = 400
plot3_d_min_height = 400 |
destinations = input()
while True:
input_command = input()
if input_command == "Travel":
break
arg = input_command.split(":")
command = arg[0]
if command == "Add Stop":
index = int(arg[1])
string = arg[2]
if 0 <= index < len(destinations):
destination... | destinations = input()
while True:
input_command = input()
if input_command == 'Travel':
break
arg = input_command.split(':')
command = arg[0]
if command == 'Add Stop':
index = int(arg[1])
string = arg[2]
if 0 <= index < len(destinations):
destinations = d... |
def html_tag():
# write body of decorator
pass
@html_tag('p')
def foobar():
return 'foobar'
if __name__ == "__main__":
assert foobar() == '<p>foobar</p>'
| def html_tag():
pass
@html_tag('p')
def foobar():
return 'foobar'
if __name__ == '__main__':
assert foobar() == '<p>foobar</p>' |
def max_power(s: str) -> int:
max_ = 1
curr = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
curr += 1
else:
if curr > max_:
max_ = curr
curr = 1
return max(max_, curr)
if __name__ == '__main__':
max_power("ccbccbb") | def max_power(s: str) -> int:
max_ = 1
curr = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
curr += 1
else:
if curr > max_:
max_ = curr
curr = 1
return max(max_, curr)
if __name__ == '__main__':
max_power('ccbccbb') |
class TestThruster:
def test_get(self, log_in, test_client):
response = test_client.get('/thruster')
data = response.get_json()[0]
assert response.status_code == 200
assert 1 == data['id']
assert 'T10' == data['name']
assert 10 == data['thrust_power']
| class Testthruster:
def test_get(self, log_in, test_client):
response = test_client.get('/thruster')
data = response.get_json()[0]
assert response.status_code == 200
assert 1 == data['id']
assert 'T10' == data['name']
assert 10 == data['thrust_power'] |
data = {
"last-modified-date": {
"value": 1523547463983
},
"name": {
"created-date": {
"value": 1523547463758
},
"last-modified-date": {
"value": 1523547463983
},
"given-names": {
"value": "Cecilia"
},
"famil... | data = {'last-modified-date': {'value': 1523547463983}, 'name': {'created-date': {'value': 1523547463758}, 'last-modified-date': {'value': 1523547463983}, 'given-names': {'value': 'Cecilia'}, 'family-name': {'value': 'Payne'}, 'credit-name': None, 'source': None, 'visibility': 'PUBLIC', 'path': '0000-0001-8868-9743'}, ... |
a = int(input())
t = input()
b = int(input())
if t == '*':
print(a*b)
elif t == '+':
print(a+b)
| a = int(input())
t = input()
b = int(input())
if t == '*':
print(a * b)
elif t == '+':
print(a + b) |
meta_file = '/mnt/fs4/chengxuz/Dataset/yfcc/meta.txt'
meta_file_dst = '/mnt/fs4/chengxuz/Dataset/yfcc/meta_short.txt'
with open(meta_file, 'r') as fin:
all_jpgs = fin.readlines()
all_jpgs = [_jpg[len('/mnt/fs4/Dataset/YFCC/images/'):] for _jpg in all_jpgs]
with open(meta_file_dst, 'w') as fout:
fout.writelines... | meta_file = '/mnt/fs4/chengxuz/Dataset/yfcc/meta.txt'
meta_file_dst = '/mnt/fs4/chengxuz/Dataset/yfcc/meta_short.txt'
with open(meta_file, 'r') as fin:
all_jpgs = fin.readlines()
all_jpgs = [_jpg[len('/mnt/fs4/Dataset/YFCC/images/'):] for _jpg in all_jpgs]
with open(meta_file_dst, 'w') as fout:
fout.writelines(... |
def longToSizeString(longVal):
if longVal >= 1073741824 :
return str(round(longVal/1073741824,2))+"GB"
elif longVal >= 1048576:
return str(round(longVal/1048576,2)) + "MB"
elif longVal >= 1024:
return str(round(longVal/1024,2))+"KB"
else:
return str(longVal)+"B" | def long_to_size_string(longVal):
if longVal >= 1073741824:
return str(round(longVal / 1073741824, 2)) + 'GB'
elif longVal >= 1048576:
return str(round(longVal / 1048576, 2)) + 'MB'
elif longVal >= 1024:
return str(round(longVal / 1024, 2)) + 'KB'
else:
return str(longVal... |
input = '361527'
input = int(input)
def walk():
number = 1
sign = 1
while True:
for _ in range(number):
yield sign, 0
for _ in range(number):
yield 0, sign
number += 1
sign = -sign
def calc_position(index):
pos = (0, 0)
for i, (dx, dy) in e... | input = '361527'
input = int(input)
def walk():
number = 1
sign = 1
while True:
for _ in range(number):
yield (sign, 0)
for _ in range(number):
yield (0, sign)
number += 1
sign = -sign
def calc_position(index):
pos = (0, 0)
for (i, (dx, dy)) ... |
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
length = sqrt(random.uniform(0, 1)) * self.radius
degree = random.uniform(0, 1) * 2 * math.pi
x = s... | class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def rand_point(self) -> List[float]:
length = sqrt(random.uniform(0, 1)) * self.radius
degree = random.uniform(0, ... |
class BasisFunctionLike(object):
@classmethod
def derivatives_factory(cls, coef, *args, **kwargs):
raise NotImplementedError
@classmethod
def functions_factory(cls, coef, *args, **kwargs):
raise NotImplementedError
| class Basisfunctionlike(object):
@classmethod
def derivatives_factory(cls, coef, *args, **kwargs):
raise NotImplementedError
@classmethod
def functions_factory(cls, coef, *args, **kwargs):
raise NotImplementedError |
def crop(image, height, width):
'''
Function to crop images
Parameters:
image, a 3d array of the image (can be obtained using plt.imread(image))
height, integer, the desired height of the cropped image
width, integer, the desired width of the cropped image
Returns:
cropped_image, a 3d... | def crop(image, height, width):
"""
Function to crop images
Parameters:
image, a 3d array of the image (can be obtained using plt.imread(image))
height, integer, the desired height of the cropped image
width, integer, the desired width of the cropped image
Returns:
cropped_image, a 3d ... |
entries = [
{
'env-title': 'atari-alien',
'env-variant': 'Human start',
'score': 128.30,
},
{
'env-title': 'atari-amidar',
'env-variant': 'Human start',
'score': 11.80,
},
{
'env-title': 'atari-assault',
'env-variant': 'Human start',
... | entries = [{'env-title': 'atari-alien', 'env-variant': 'Human start', 'score': 128.3}, {'env-title': 'atari-amidar', 'env-variant': 'Human start', 'score': 11.8}, {'env-title': 'atari-assault', 'env-variant': 'Human start', 'score': 166.9}, {'env-title': 'atari-asterix', 'env-variant': 'Human start', 'score': 164.5}, {... |
class BoxField:
BOXES = 'bbox'
KEYPOINTS = 'keypoints'
LABELS = 'label'
MASKS = 'masks'
NUM_BOXES = 'num_boxes'
SCORES = 'scores'
WEIGHTS = 'weights'
class DatasetField:
IMAGES = 'images'
IMAGES_INFO = 'images_information'
IMAGES_PMASK = 'images_padding_mask'
| class Boxfield:
boxes = 'bbox'
keypoints = 'keypoints'
labels = 'label'
masks = 'masks'
num_boxes = 'num_boxes'
scores = 'scores'
weights = 'weights'
class Datasetfield:
images = 'images'
images_info = 'images_information'
images_pmask = 'images_padding_mask' |
#
# PySNMP MIB module HH3C-WAPI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-WAPI-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) ... |
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [[0 for _ in range(n+1) ] for _ in range(n+1)]
for i in range(1,n+1):
for j in range(1,n+1):
if( s[i-1] == s[n-j]):
dp[i][j] = 1+dp[i-1][j-1]
else... | class Solution:
def longest_palindrome_subseq(self, s: str) -> int:
n = len(s)
dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
if s[i - 1] == s[n - j]:
dp[i][j] = 1 + dp[i - 1][j - 1]
... |
class JsutCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
# print(counter.__secretCount)
print(counter._JustCounter.__secretCount)
#public:normal variables
#private:__
#protected:_
| class Jsutcounter:
__secret_count = 0
def count(self):
self.__secretCount += 1
print(self.__secretCount)
counter = just_counter()
counter.count()
counter.count()
print(counter._JustCounter.__secretCount) |
class Solution:
def max_dp(self, nums2: List[int]) -> int:
dp=[0,0,nums2[0]]
for num in nums2[1:]:
dp.append(num+max(dp[-2], dp[-3]))
return max(dp[-1], dp[-2])
def rob(self, nums: List[int]) -> int:
if len(nums)<=3:
return max(nums)
e... | class Solution:
def max_dp(self, nums2: List[int]) -> int:
dp = [0, 0, nums2[0]]
for num in nums2[1:]:
dp.append(num + max(dp[-2], dp[-3]))
return max(dp[-1], dp[-2])
def rob(self, nums: List[int]) -> int:
if len(nums) <= 3:
return max(nums)
elif... |
#-*- coding:utf-8 -*-
def display(name,age):
print (name,age)
| def display(name, age):
print(name, age) |
n = int(input("Digite o valor de n: "))
i=0
count = 0
while count<n:
if (i % 2) != 0:
print (i)
count = count + 1
i = i + 1 | n = int(input('Digite o valor de n: '))
i = 0
count = 0
while count < n:
if i % 2 != 0:
print(i)
count = count + 1
i = i + 1 |
#
# PySNMP MIB module WWP-LEOS-BENCHMARK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-BENCHMARK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:30:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection, constraints_union) ... |
#
# PySNMP MIB module CISCOSB-CDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-CDP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:22:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection) ... |
unique_symbols= { 1:'I', 5:'V', 10:'X', 50:'L', 100:'C', 500:'D', 1000:'M' }
def calculateRoman(algarism, place):
if algarism==0: return ''
elif place>=4: return algarism * unique_symbols[1000]
elif algarism>5:
if algarism==9: return unique_symbols[10**(place-1)]+unique_symbols[10**place]
e... | unique_symbols = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M'}
def calculate_roman(algarism, place):
if algarism == 0:
return ''
elif place >= 4:
return algarism * unique_symbols[1000]
elif algarism > 5:
if algarism == 9:
return unique_symbols[10 ** (... |
class MapAsObject:
def __init__(self, wrapped):
self.wrapped = wrapped
def __getattr__(self, key):
try:
return self.wrapped[key]
except KeyError:
raise AttributeError("%r object has no attribute %r" %
(self.__class__.__name__, ke... | class Mapasobject:
def __init__(self, wrapped):
self.wrapped = wrapped
def __getattr__(self, key):
try:
return self.wrapped[key]
except KeyError:
raise attribute_error('%r object has no attribute %r' % (self.__class__.__name__, key))
def get(self, *args, **... |
fhand = open(input('Enter file name: '))
d = dict()
for ln in fhand:
if not ln.startswith('From '): continue
words = ln.split()
time = words[5]
d[time[:2]] = d.get(time[:2],0) + 1
l = list()
for key,val in d.items():
l.append((val,key))
l.sort()
for val,key in l:
print(key,val)
| fhand = open(input('Enter file name: '))
d = dict()
for ln in fhand:
if not ln.startswith('From '):
continue
words = ln.split()
time = words[5]
d[time[:2]] = d.get(time[:2], 0) + 1
l = list()
for (key, val) in d.items():
l.append((val, key))
l.sort()
for (val, key) in l:
print(key, val) |
dbname='postgres'
user='postgres'
password='q1w2e3r4'
host='127.0.0.1'
| dbname = 'postgres'
user = 'postgres'
password = 'q1w2e3r4'
host = '127.0.0.1' |
Blue = 0
Red = 0
Yellow = 0
Green = 0
Gold = 1
Health = 100
Experience = 0
if Gold == 1:
print("The chest opens")
Health += 50
Experience += 100
elif Blue == 1:
print("DEATH Appears")
Health -= 100
elif Red == 1:
print("The chest burns you")
Health -= 50
elif Y... | blue = 0
red = 0
yellow = 0
green = 0
gold = 1
health = 100
experience = 0
if Gold == 1:
print('The chest opens')
health += 50
experience += 100
elif Blue == 1:
print('DEATH Appears')
health -= 100
elif Red == 1:
print('The chest burns you')
health -= 50
elif Yellow == 1:
print('A monste... |
numList = [3, 4, 5, 6, 7]
length = len(numList)
for i in range(length):
print(2 * numList[i])
| num_list = [3, 4, 5, 6, 7]
length = len(numList)
for i in range(length):
print(2 * numList[i]) |
#
# @lc app=leetcode id=273 lang=python3
#
# [273] Integer to English Words
#
# @lc code=start
class Solution:
def numberToWords(self, num: int) -> str:
v0 = ["Thousand", "Million", "Billion"]
v1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve... | class Solution:
def number_to_words(self, num: int) -> str:
v0 = ['Thousand', 'Million', 'Billion']
v1 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
... |
'''
IQ test
'''
n = int(input())
numbers = list(map(int, input().split(' ')))
even = 0
odd = 0
first_eve = -1
first_odd = -1
for i in range(n):
if numbers[i] % 2 == 0:
even += 1
if first_eve == -1:
first_eve = i
else:
odd += 1
if first_odd == -1:
first_odd... | """
IQ test
"""
n = int(input())
numbers = list(map(int, input().split(' ')))
even = 0
odd = 0
first_eve = -1
first_odd = -1
for i in range(n):
if numbers[i] % 2 == 0:
even += 1
if first_eve == -1:
first_eve = i
else:
odd += 1
if first_odd == -1:
first_odd... |
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
opened = set()
N = len(rooms)
opened.add(0)
toOpen = rooms[0]
while toOpen:
nextRound = set()
for room in toOpen:
for newKey in rooms[room]:
... | class Solution:
def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool:
opened = set()
n = len(rooms)
opened.add(0)
to_open = rooms[0]
while toOpen:
next_round = set()
for room in toOpen:
for new_key in rooms[room]:
... |
'''
Python program to compute the sum of the negative
and positive numbers of an array of integers and display the
largest sum.
Original array elements: {0, 15, 16, 17, -14, -13, -12, -11, -10, 18,
19, 20}
Largest sum - Positive/Negative numbers of the said array: 105
Original array elements: {0, 3, 4, 5, 9, -22, -44,... | """
Python program to compute the sum of the negative
and positive numbers of an array of integers and display the
largest sum.
Original array elements: {0, 15, 16, 17, -14, -13, -12, -11, -10, 18,
19, 20}
Largest sum - Positive/Negative numbers of the said array: 105
Original array elements: {0, 3, 4, 5, 9, -22, -44,... |
'''input
549
817
715
603
1152
600
300
220
420
520
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem A
if __name__ == '__main__':
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print(min(a, b) + min(c, d))
| """input
549
817
715
603
1152
600
300
220
420
520
"""
if __name__ == '__main__':
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print(min(a, b) + min(c, d)) |
list_1 = [2,3,1,4,2,3,5,6,8,5,8,9,10,9,6]
s = set(list_1)
list_2 = list(s)
#print(list_2)
n = 3
l = len(list_1)
#print(l)
b = int((len(list_2)/n))
s1 = list_2.__getslice__(0, b)
s2 = list_2.__getslice__(len(s1), len(s1)+b)
#l1 = list(enumerate(s1, 1))
#l2 = list(enumerate(s2, 1))
print(s1,s2)
#print(l1, l2)
| list_1 = [2, 3, 1, 4, 2, 3, 5, 6, 8, 5, 8, 9, 10, 9, 6]
s = set(list_1)
list_2 = list(s)
n = 3
l = len(list_1)
b = int(len(list_2) / n)
s1 = list_2.__getslice__(0, b)
s2 = list_2.__getslice__(len(s1), len(s1) + b)
print(s1, s2) |
def get_token_files(parser, logic, logging, args=0):
if args:
if "hid" not in args.keys():
parser.print("missing honeypotid")
return
hid = args["hid"]
for h in hid:
r = logic.get_token_files(h)
if r != "":
parser.print("Tokens l... | def get_token_files(parser, logic, logging, args=0):
if args:
if 'hid' not in args.keys():
parser.print('missing honeypotid')
return
hid = args['hid']
for h in hid:
r = logic.get_token_files(h)
if r != '':
parser.print('Tokens l... |
class Queue:
def __init__(self, initial_size=10):
self.arr = [0 for _ in range(initial_size)]
self.next_index = 0
self.front_index = -1
self.queue_size = 0 | class Queue:
def __init__(self, initial_size=10):
self.arr = [0 for _ in range(initial_size)]
self.next_index = 0
self.front_index = -1
self.queue_size = 0 |
def divisores(n):
div=[]
for i in range(1,n-1):
if n % i ==0:
div.append(i)
return div
def amigos(a,b):
div_a = divisores(a)
div_b = divisores(b)
sigma_a = sum(div_a)
sigma_b = sum(div_b)
if sigma_a == b or sigma_b == a:
return True
else:
... | def divisores(n):
div = []
for i in range(1, n - 1):
if n % i == 0:
div.append(i)
return div
def amigos(a, b):
div_a = divisores(a)
div_b = divisores(b)
sigma_a = sum(div_a)
sigma_b = sum(div_b)
if sigma_a == b or sigma_b == a:
return True
else:
r... |
def print_formatted(number):
width = len(str(bin(number))) # Since the last column is always filled
for i in range(1, number+1):
print(str(i).rjust(width-2, '.') +
oct(i).lstrip("0o").rjust(width-1, '.') +
hex(i).lstrip("0x").upper().rjust(width-1, '.') +
... | def print_formatted(number):
width = len(str(bin(number)))
for i in range(1, number + 1):
print(str(i).rjust(width - 2, '.') + oct(i).lstrip('0o').rjust(width - 1, '.') + hex(i).lstrip('0x').upper().rjust(width - 1, '.') + bin(i).lstrip('0b').rjust(width - 1, '.'))
if __name__ == '__main__':
n = int... |
# Copyright 2014 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | min_tmos_major_version = 11
min_tmos_minor_version = 5
min_extra_mb = 500
default_hostname = 'bigip1'
max_hostname_length = 128
default_folder = 'Common'
folder_cache_timeout = 120
connection_timeout = 30
fdb_populate_static_arp = True
device_lock_prefix = 'lock_'
wsdl_cache_dir = ''
ha_vlan_name = 'HA'
ha_selfip_name ... |
# File: crowdstrike_consts.py
#
# Copyright (c) 2016-2020 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | crowdstrike_json_url = 'url'
crowdstrike_filter_request_str = '{0}rest/container?page_size=0&_filter_asset={1}&_filter_name__contains="{2}"&_filter_start_time__gte="{3}"'
crowdstrike_succ_connectivity_test = 'Connectivity test passed'
crowdstrike_err_connectivity_test = 'Connectivity test failed'
crowdstrike_err_connec... |
HANDSHAKING = 0
STATUS = 1
LOGIN = 2
PLAY = 3
| handshaking = 0
status = 1
login = 2
play = 3 |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.last = None
self.l = []
def isEmpty(self):
return self.head == None
# Method to add an item to the queue
def Enqueue(se... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.last = None
self.l = []
def is_empty(self):
return self.head == None
def enqueue(self, item):
temp = node(item)
... |
datasets = {
"cv-corpus-7.0-2021-07-21": {
"directories": ["speakers"],
"audio_extensions": [".wav", ".flac"],
"transcript_extension": ".txt"
},
"LibriTTS": {
"directories": ["train-clean-100", "train-clean-360", "train-other-500"],
"audio_extensions": [".wav", ".flac... | datasets = {'cv-corpus-7.0-2021-07-21': {'directories': ['speakers'], 'audio_extensions': ['.wav', '.flac'], 'transcript_extension': '.txt'}, 'LibriTTS': {'directories': ['train-clean-100', 'train-clean-360', 'train-other-500'], 'audio_extensions': ['.wav', '.flac'], 'transcript_extension': '.original.txt'}, 'TEDLIUM_r... |
# Copyright 2019 DIVERSIS Software. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law o... | def network_config(netType):
if netType == 1:
layer_out_dim_size = [16, 32, 64, 128, 256, 64, 10]
kernel_size = [[3, 3], [3, 3], [3, 3], [3, 3], [3, 3], [1], [1]]
stride_size = [2, 2, 2, 2, 2, 1, 1]
pool_kernel_size = [[3, 3], [3, 3], [3, 3], [3, 3], [3, 3], [3, 3], [3, 3]]
p... |
# https://app.codility.com/demo/results/trainingPURU8U-DP4/
def solution(array):
set_array = set()
for val in array:
if val not in set_array :
set_array.add(val)
return len(set_array)
if __name__ == '__main__':
print(solution([0])) | def solution(array):
set_array = set()
for val in array:
if val not in set_array:
set_array.add(val)
return len(set_array)
if __name__ == '__main__':
print(solution([0])) |
# The key 'ICE' is repeated to match the length of the string and later they are xored taking eacg character at a time
def xor(string,key):
length = divmod(len(string),len(key))
key = key*length[0]+key[0:length[1]]
return ''.join([chr(ord(a)^ord(b)) for a,b in zip(string,key)])
if __name__ == "__main__":
... | def xor(string, key):
length = divmod(len(string), len(key))
key = key * length[0] + key[0:length[1]]
return ''.join([chr(ord(a) ^ ord(b)) for (a, b) in zip(string, key)])
if __name__ == '__main__':
print(xor('\n'.join([line.strip() for line in open('5.txt')]), 'ICE')).encode('hex') |
Root.default = 'C'
Scale.scale = 'major'
Clock.bpm = 120
notas = [0, 3, 5, 4]
frequencia = var(notas, 4)
d0 >> play(
'<x |o2| ><---{[----]-*}>',
sample=4,
dur=1/2
)
s0 >> space(
notas,
dur=1/4,
apm=3,
pan=[-1, 0, 1]
)
s1 >> bass(
frequencia,
dur=1/4,
oct=4,
)
s2 >> spark(
... | Root.default = 'C'
Scale.scale = 'major'
Clock.bpm = 120
notas = [0, 3, 5, 4]
frequencia = var(notas, 4)
d0 >> play('<x |o2| ><---{[----]-*}>', sample=4, dur=1 / 2)
s0 >> space(notas, dur=1 / 4, apm=3, pan=[-1, 0, 1])
s1 >> bass(frequencia, dur=1 / 4, oct=4)
s2 >> spark(frequencia, dur=[1 / 2, 1 / 4]) + (0, 2, 4)
s3 >>... |
class Cue:
def __init__(self):
pass
def power_to_speed(self, power, ball=None):
# Translate a power (0-100) to the ball's velocity.
# Ball object passed in in case this depends on ball weight.
return power*10
def on_hit(self, ball):
# Apply some effect to ball on hi... | class Cue:
def __init__(self):
pass
def power_to_speed(self, power, ball=None):
return power * 10
def on_hit(self, ball):
pass
class Basiccue(Cue):
pass |
#
# PySNMP MIB module UAS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UAS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:28:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, constraints_union, value_size_constraint) ... |
def maior_primo(num):
if num < 2:
return False
else:
for n in range(2, num):
while num % n == 0:
return num - 1
return num
| def maior_primo(num):
if num < 2:
return False
else:
for n in range(2, num):
while num % n == 0:
return num - 1
return num |
# Demo Python If ... Else - And
'''
And
The 'and' keyword is a logical operator, and is used to combine conditional statements.
'''
# Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True") | """
And
The 'and' keyword is a logical operator, and is used to combine conditional statements.
"""
a = 200
b = 33
c = 500
if a > b and c > a:
print('Both conditions are True') |
def timesize(t):
if t<60:
return f"{t:.2f}s"
elif t<3600:
return f"{t/60:.2f}m"
elif t<86400:
return f"{t/3600:.2f}h"
else:
return f"{t/86400:.2f}d"
| def timesize(t):
if t < 60:
return f'{t:.2f}s'
elif t < 3600:
return f'{t / 60:.2f}m'
elif t < 86400:
return f'{t / 3600:.2f}h'
else:
return f'{t / 86400:.2f}d' |
# .txt mesh converter
def txt_mesh_converter(mesh_filename):
# txt mesh converter, returns mesh variables
with open(mesh_filename, 'r') as mesh_file:
lines = mesh_file.readlines()
# remove blank lines
lines_list = []
for line in lines:
if line.strip():
... | def txt_mesh_converter(mesh_filename):
with open(mesh_filename, 'r') as mesh_file:
lines = mesh_file.readlines()
lines_list = []
for line in lines:
if line.strip():
lines_list.append(line)
surfaces_start = lines_list.index('$Surfaces\n')
surfaces_end = lines_list.index('$... |
getAllObjects = [
{
"id": 1,
"keyName": "SPREAD",
"name": "SPREAD"
}
]
| get_all_objects = [{'id': 1, 'keyName': 'SPREAD', 'name': 'SPREAD'}] |
#
# PySNMP MIB module CISCO-OPTICAL-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OPTICAL-MONITOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:51:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
class MetaDato:
def __init__(self, nombreTabla, campos):
pass
def calcularRegistros(self):
pass
def getRegistro(self):
pass
| class Metadato:
def __init__(self, nombreTabla, campos):
pass
def calcular_registros(self):
pass
def get_registro(self):
pass |
nama = str(input("Masukkan Nama "))
nim = int(input("Masukkan NIM "))
uts = int(input("Masukkan Nilai UTS : "))
uas = int(input("Masukkan Nilai UAS : "))
hitungRataRata = (uts+uas)/2
if int(hitungRataRata) <= 40:
nilai = 'E'
elif int(hitungRataRata) <= 60:
nilai = 'D'
elif int(hitungRataRata) <= 70:
ni... | nama = str(input('Masukkan Nama '))
nim = int(input('Masukkan NIM '))
uts = int(input('Masukkan Nilai UTS : '))
uas = int(input('Masukkan Nilai UAS : '))
hitung_rata_rata = (uts + uas) / 2
if int(hitungRataRata) <= 40:
nilai = 'E'
elif int(hitungRataRata) <= 60:
nilai = 'D'
elif int(hitungRataRata) <= 70:
n... |
'''
Pattern
Plus star pattern:
Enter number of rows: 5
+
+
+
+
+++++++++
+
+
+
+
'''
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,number_rows+1):
if number_rows%2!=0:
if row==((number_rows//2)+1) or colu... | """
Pattern
Plus star pattern:
Enter number of rows: 5
+
+
+
+
+++++++++
+
+
+
+
"""
number_rows = int(input('Enter number of rows: '))
for row in range(1, number_rows + 1):
for column in range(1, number_rows + 1):
if number_rows % 2 != 0:
if row == number_rows //... |
class Solution:
def maxRotateFunction(self, A: List[int]) -> int:
n = len(A)
if n <= 1: return 0
if n == 2: return max(A)
result = -inf
for i in range(n):
result = max(result, sum([((j + i) % n) * v for j, v in enumerate(A)]))
return result
| class Solution:
def max_rotate_function(self, A: List[int]) -> int:
n = len(A)
if n <= 1:
return 0
if n == 2:
return max(A)
result = -inf
for i in range(n):
result = max(result, sum([(j + i) % n * v for (j, v) in enumerate(A)]))
re... |
def demo_map():
num_list = list( range(1, 6) )
## Example_#1:
# compute x^2 for each element
result = list( map( lambda x:x**2, num_list) )
# [1, 4, 9, 16, 25]
print( result )
## Example_#2:
# compute 3x + 1 for each element
result = list( map( lambda x:3*x+1, num_list) )
... | def demo_map():
num_list = list(range(1, 6))
result = list(map(lambda x: x ** 2, num_list))
print(result)
result = list(map(lambda x: 3 * x + 1, num_list))
print(result)
result = list(map(lambda x: x ** 0.5, num_list))
print(result)
str_list = ['apple', 'banana', 'cat', 'dog', 'elephant'... |
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
ans = numBottles // (numExchange - 1) + numBottles
return ans if numBottles % (numExchange - 1) else ans - 1
| class Solution:
def num_water_bottles(self, numBottles: int, numExchange: int) -> int:
ans = numBottles // (numExchange - 1) + numBottles
return ans if numBottles % (numExchange - 1) else ans - 1 |
self.description = "Sysupgrade with a set of sync packages replacing a set of local ones"
sp1 = pmpkg("pkg2")
sp1.replaces = ["pkg1"]
sp2 = pmpkg("pkg3")
sp2.replaces = ["pkg1"]
sp3 = pmpkg("pkg4")
sp3.replaces = ["pkg1", "pkg0"]
sp4 = pmpkg("pkg5")
sp4.replaces = ["pkg0"]
for p in sp1, sp2, sp3, sp4:
self.addpkg... | self.description = 'Sysupgrade with a set of sync packages replacing a set of local ones'
sp1 = pmpkg('pkg2')
sp1.replaces = ['pkg1']
sp2 = pmpkg('pkg3')
sp2.replaces = ['pkg1']
sp3 = pmpkg('pkg4')
sp3.replaces = ['pkg1', 'pkg0']
sp4 = pmpkg('pkg5')
sp4.replaces = ['pkg0']
for p in (sp1, sp2, sp3, sp4):
self.addpkg... |
class NullDisplay:
def __init__(self, board=None):
pass
def show_results(self):
pass
def draw(self):
pass | class Nulldisplay:
def __init__(self, board=None):
pass
def show_results(self):
pass
def draw(self):
pass |
n=int(input("How Many Time you Chack the Condition: "))
for i in range(1,n+1):
num=int(input("Enter The Number To be Chack Even or Odd: "))
if(num%2==0):
print("The Enterd Number is Even")
else:
print("The Enterd Number is odd")
| n = int(input('How Many Time you Chack the Condition: '))
for i in range(1, n + 1):
num = int(input('Enter The Number To be Chack Even or Odd: '))
if num % 2 == 0:
print('The Enterd Number is Even')
else:
print('The Enterd Number is odd') |
class ShareInstance():
__session = None
@classmethod
def share(cls, **kwargs):
if not cls.__session:
cls.__session = cls(**kwargs)
return cls.__session
# Expand dict
class Dict(dict):
def get(self, key, default=None, sep='.'):
keys = key.split(sep)
for i, ke... | class Shareinstance:
__session = None
@classmethod
def share(cls, **kwargs):
if not cls.__session:
cls.__session = cls(**kwargs)
return cls.__session
class Dict(dict):
def get(self, key, default=None, sep='.'):
keys = key.split(sep)
for (i, key) in enumerat... |
emoji_dict = {
"anger": ["\U0001F92C", "data/emoji/emoji_u1f92c.png"],
"disgust": ["\U0001F616", "data/emoji/emoji_u1f616.png"],
"fear": ["\U0001F633", "data/emoji/emoji_u1f633.png"],
"happy": ["\U0001F604", "data/emoji/emoji_u1f604.png"],
"neutral": ["\U0001F612", "data/emoji/emoji_u1f612.png"],
... | emoji_dict = {'anger': ['π€¬', 'data/emoji/emoji_u1f92c.png'], 'disgust': ['π', 'data/emoji/emoji_u1f616.png'], 'fear': ['π³', 'data/emoji/emoji_u1f633.png'], 'happy': ['π', 'data/emoji/emoji_u1f604.png'], 'neutral': ['π', 'data/emoji/emoji_u1f612.png'], 'sadness': ['π', 'data/emoji/emoji_u1f61e.png'], 'surprise': [... |
# Section 5.16 snippets
# Creating a Two-Dimensional List
a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]]
# Illustrating a Two-Dimensional List
# Identifying the Elements in a Two-Dimensional List
for row in a:
for item in row:
print(item, end=' ')
print()
# How the Nested Loops Execute
f... | a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]]
for row in a:
for item in row:
print(item, end=' ')
print()
for (i, row) in enumerate(a):
for (j, item) in enumerate(row):
print(f'a[{i}][{j}]={item} ', end=' ')
print() |
package_name = 'cms_search'
name = 'django-cms-search'
author = 'Benjamin Wohlwend'
author_email = 'piquadrat@gmail.com'
description = "An extension to django CMS to provide multilingual Haystack indexes"
version = __import__(package_name).__version__
project_url = 'http://github.com/piquadrat/%s' % name
license = 'BSD... | package_name = 'cms_search'
name = 'django-cms-search'
author = 'Benjamin Wohlwend'
author_email = 'piquadrat@gmail.com'
description = 'An extension to django CMS to provide multilingual Haystack indexes'
version = __import__(package_name).__version__
project_url = 'http://github.com/piquadrat/%s' % name
license = 'BSD... |
# Space: O(1)
# Time: O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def addOneRow(self, root, v, d):
if d==1:
new_node = Tree... | class Solution:
def add_one_row(self, root, v, d):
if d == 1:
new_node = tree_node(v)
new_node.left = root
return new_node
def helper(root, cur_level, required_level, required_val, direction):
if root is None and cur_level == required_level:
... |
'''
Selection sort is an O(n^2) sorting algorithm. The logic is to find the smallest element in
the unsorted portion of the array and swapping it in the right position. In the worst-case
it takes n(n+1)/2 accesses. '''
def selsort(A,l,r):
''' Convention is that array elements are indexed from l to r-1.'''
... | """
Selection sort is an O(n^2) sorting algorithm. The logic is to find the smallest element in
the unsorted portion of the array and swapping it in the right position. In the worst-case
it takes n(n+1)/2 accesses. """
def selsort(A, l, r):
""" Convention is that array elements are indexed from l to r-1."""
... |
def dominator(arr):
res = 0
if len(arr) == 0:
return -1
for x in arr:
if arr.count(x) > len(arr) / 2:
res = x
break
else:
res = -1
return res
| def dominator(arr):
res = 0
if len(arr) == 0:
return -1
for x in arr:
if arr.count(x) > len(arr) / 2:
res = x
break
else:
res = -1
return res |
def move(instruction, x, y, w_x, w_y):
if instruction[0] == 'N':
w_y += instruction[1]
if instruction[0] == 'S':
w_y -= instruction[1]
if instruction[0] == 'E':
w_x += instruction[1]
if instruction[0] == 'W':
w_x -= instruction[1]
if instruction[0] in ['L', 'R']:
... | def move(instruction, x, y, w_x, w_y):
if instruction[0] == 'N':
w_y += instruction[1]
if instruction[0] == 'S':
w_y -= instruction[1]
if instruction[0] == 'E':
w_x += instruction[1]
if instruction[0] == 'W':
w_x -= instruction[1]
if instruction[0] in ['L', 'R']:
... |
DEBUG = True
TEMPLATE_DEBUG = True
# THIS MUST BE HTTPS
DOMAIN_NAME="https://52.34.71.182:8000"
#CSRF_COOKIE_SECURE = False
#SESSION_COOKIE_SECURE = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'expfactory.db',
}
}
#DATABASES = {
# 'default': {
# ... | debug = True
template_debug = True
domain_name = 'https://52.34.71.182:8000'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'expfactory.db'}}
static_root = 'assets/'
static_url = '/assets/'
media_root = 'static/'
media_url = '/static/' |
# Writes down all combinations of plates
COMBINATIONS = [1.25, 2.5, 5, 10, 25]
# 1 kg is 2.20... pounds
KILOS_POUNDS_CONVERSION_RATE = 2.20462
# Function that asks for str input
def get_input_in_kilos():
return input("Enter weight in kilos: ")
# function that converts punds to kilos
def convert_kilos_to_pounds(k... | combinations = [1.25, 2.5, 5, 10, 25]
kilos_pounds_conversion_rate = 2.20462
def get_input_in_kilos():
return input('Enter weight in kilos: ')
def convert_kilos_to_pounds(kilos):
return kilos * KILOS_POUNDS_CONVERSION_RATE
def break_down_into_combinations(weight, options):
combination = []
difference... |
class Fila:
def __init__(self, maxx):
self.limit = maxx
self.elementos = [0] * maxx
self.ini = -1
self.end = -1
self._size = 0
self.offset = -1
def __len__(self):
return self._size
def insert(self, elem):
if ((self._size) >= self.limi... | class Fila:
def __init__(self, maxx):
self.limit = maxx
self.elementos = [0] * maxx
self.ini = -1
self.end = -1
self._size = 0
self.offset = -1
def __len__(self):
return self._size
def insert(self, elem):
if self._size >= self.limit or self.... |
# O(N^2)
def can_make_target1(arr, target):
for i in range(len(arr)):
for j in range(i, len(arr)):
if arr[i] + arr[j] == target:
return True
return False
# O(N)
def can_make_target2(arr, target):
looking_for = set()
for a in arr:
if a in looking_for:
... | def can_make_target1(arr, target):
for i in range(len(arr)):
for j in range(i, len(arr)):
if arr[i] + arr[j] == target:
return True
return False
def can_make_target2(arr, target):
looking_for = set()
for a in arr:
if a in looking_for:
return True
... |
# A somewhat special node as it is designed for use in skip list, in addition to having two pointers \
# it has three (next, previous and down).
# This class is used by SortedLinkList, but is somewhat different to a regular link list node.
class Node:
def __init__(self, value, next=None, down=None, prev=None)... | class Node:
def __init__(self, value, next=None, down=None, prev=None):
self.value = value
self.next = next
self.down = down
self.prev = prev |
expected_output = {
'rib_table': {
'ipv4': {
'num_multicast_tables': 1,
'num_unicast_tables': 3,
'total_multicast_prefixes': 0,
... | expected_output = {'rib_table': {'ipv4': {'num_multicast_tables': 1, 'num_unicast_tables': 3, 'total_multicast_prefixes': 0, 'total_unicast_prefixes': 14}}} |
#
# @lc app=leetcode id=993 lang=python3
#
# [993] Cousins in Binary Tree
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isCousins(self, root... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_cousins(self, root: TreeNode, x: int, y: int):
pre = 0
curval = 0
self.x = x
self.y = y
self.xdetail = []... |
class StringParser:
def __init__(self):
self.parse_trees = []
def register(self,tree):
self.parse_trees.append(tree)
def parse(self, string):
for tree in self.parse_trees:
return tree.parse(string) | class Stringparser:
def __init__(self):
self.parse_trees = []
def register(self, tree):
self.parse_trees.append(tree)
def parse(self, string):
for tree in self.parse_trees:
return tree.parse(string) |
def merge(pairs):
pairs = sorted(pairs)
j,tmp = 0, []
while j < len(pairs):
a = pairs[j]
if j < len(pairs) - 1:
b = pairs[j+1]
if a[1] == b[0]:
a = (a[0], b[1])
j += 1
tmp += [a]
j += 1
return tmp
print(merge(sorted(set([(1,2),(2,3),(4,5),(5... | def merge(pairs):
pairs = sorted(pairs)
(j, tmp) = (0, [])
while j < len(pairs):
a = pairs[j]
if j < len(pairs) - 1:
b = pairs[j + 1]
if a[1] == b[0]:
a = (a[0], b[1])
j += 1
tmp += [a]
j += 1
return tmp
print(merge(... |
def corner_move(game):
return list(set(game.possible_moves()) & {1, 3, 7, 9})
def center_move(game):
return list(set(game.possible_moves()) & {5})
def side_move(game):
return list(set(game.possible_moves()) & {2, 4, 6, 8})
def test_if_win_is_possible(game, to_check=None):
if to_check is None:
... | def corner_move(game):
return list(set(game.possible_moves()) & {1, 3, 7, 9})
def center_move(game):
return list(set(game.possible_moves()) & {5})
def side_move(game):
return list(set(game.possible_moves()) & {2, 4, 6, 8})
def test_if_win_is_possible(game, to_check=None):
if to_check is None:
... |
class Solution:
def maxProfit(self, prices) -> int:
'''
Notice that we can complete as many transactions as we like.
Therefore, a greedy rule are easily came out, that we buy it
on the low price day which compares with the next day and
sell it on the high price day which co... | class Solution:
def max_profit(self, prices) -> int:
"""
Notice that we can complete as many transactions as we like.
Therefore, a greedy rule are easily came out, that we buy it
on the low price day which compares with the next day and
sell it on the high price day which ... |
def part1():
values = [i.split(" ") for i in open("input.txt").read().split("\n")]
lights = [[False]*50 ,[False]*50,[False]*50,[False]*50,[False]*50,[False]*50]
for command in values:
if command[0] == "rect":
length, height = (int(i) for i in command[1].split("x"))
for i in ... | def part1():
values = [i.split(' ') for i in open('input.txt').read().split('\n')]
lights = [[False] * 50, [False] * 50, [False] * 50, [False] * 50, [False] * 50, [False] * 50]
for command in values:
if command[0] == 'rect':
(length, height) = (int(i) for i in command[1].split('x'))
... |
# https://blog.csdn.net/Violet_ljp/article/details/80556460
# https://www.youtube.com/watch?v=pcKY4hjDrxk
# https://github.com/minsuk-heo/problemsolving/tree/master/graph
def bfs(graph, start):
vertexList, edgeList = graph
visitedList = []
queue = [start]
adjacencyList = [[] for vertex in vertexList]
... | def bfs(graph, start):
(vertex_list, edge_list) = graph
visited_list = []
queue = [start]
adjacency_list = [[] for vertex in vertexList]
for edge in edgeList:
adjacencyList[edge[0]].append(edge[1])
while queue:
current = queue.pop()
for neighbor in adjacencyList[current]:... |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights R... | gb2312_typical_distribution_ratio = 0.9
gb2312_table_size = 3760
gb2312_char_to_freq_order = (1671, 749, 1443, 2364, 3924, 3807, 2330, 3921, 1704, 3463, 2691, 1511, 1515, 572, 3191, 2205, 2361, 224, 2558, 479, 1711, 963, 3162, 440, 4060, 1905, 2966, 2947, 3580, 2647, 3961, 3842, 2204, 869, 4207, 970, 2678, 5626, 2944, ... |
# from collections import Counter, defaultdict
# class Solution:
# def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# count = Counter(nums)
# # print('count: {}'.format(count))
# tmp = nums.copy() #list(set(nums.copy()))
# tmp.sort()
# # print('tmp... | class Solution:
def smaller_numbers_than_current(self, nums: List[int]) -> List[int]:
tmp = [0] * (max(nums) + 1)
for num in nums:
tmp[num] += 1
ans = []
for num in nums:
ans.append(sum(tmp[:num]))
return ans |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.