content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
fruit = {"orange": "a sweet, orange, citrus fruit",
"apple": "good for making cider",
"lemon": "a sour, yellow, citrus fruit",
"pear": "change me"}
# "apple": "The second one"} # reassigns the value of first 'apple' instead of printing a second 'apple' value
# # print(fruit)
... | fruit = {'orange': 'a sweet, orange, citrus fruit', 'apple': 'good for making cider', 'lemon': 'a sour, yellow, citrus fruit', 'pear': 'change me'}
print(fruit)
print(fruit.items())
print(tuple(fruit.items())) |
__version__ = '0.0.0'
API_ROOT = 'https://www.pythonanywhere.com/api/v0'
| __version__ = '0.0.0'
api_root = 'https://www.pythonanywhere.com/api/v0' |
def closeH5(h5File):
try:
h5File.close()
except:
pass
def closeAllH5Files(h5Files):
for h5File in h5Files:
closeH5(h5File)
def loadLabelsBlock(h5Dset, begin, end):
return h5Dset[begin[0]:end[0], begin[1]:end[1], begin[2]:end[2], 0]
def loadData(h5Dset, begin, end):
i... | def close_h5(h5File):
try:
h5File.close()
except:
pass
def close_all_h5_files(h5Files):
for h5_file in h5Files:
close_h5(h5File)
def load_labels_block(h5Dset, begin, end):
return h5Dset[begin[0]:end[0], begin[1]:end[1], begin[2]:end[2], 0]
def load_data(h5Dset, begin, end):
... |
original = 'Mary had a %s lamb.'
extra = 'little'
original % extra
'Mary had a little lamb.'
| original = 'Mary had a %s lamb.'
extra = 'little'
original % extra
'Mary had a little lamb.' |
# https://adventofcode.com/2021/day/5
test = "2021-05_sample.txt"
run = "2021-05_input.txt"
def part1(fname):
count = 0
points = {}
for line in open(fname):
a, _, b = line.rstrip().split(' ')
p1 = [int(x) for x in a.split(',')]
p2 = [int(x) for x in b.split(',')]
#print(f'\... | test = '2021-05_sample.txt'
run = '2021-05_input.txt'
def part1(fname):
count = 0
points = {}
for line in open(fname):
(a, _, b) = line.rstrip().split(' ')
p1 = [int(x) for x in a.split(',')]
p2 = [int(x) for x in b.split(',')]
if p1[0] == p2[0] or p1[1] == p2[1]:
... |
c=0;a=[];n=int(input())
for _ in range(n):
v,p=map(int,input().split())
a.append(v)
a.sort(reverse=True);k=a[4]
for i in range(5,n):
if k==a[i]: c+=1
else: break
print(c)
| c = 0
a = []
n = int(input())
for _ in range(n):
(v, p) = map(int, input().split())
a.append(v)
a.sort(reverse=True)
k = a[4]
for i in range(5, n):
if k == a[i]:
c += 1
else:
break
print(c) |
x=1
pos=0
while x<=6:
a=float(input())
if a>0:
pos=1+pos
x=x+1
print("%d valores positivos" % pos)
| x = 1
pos = 0
while x <= 6:
a = float(input())
if a > 0:
pos = 1 + pos
x = x + 1
print('%d valores positivos' % pos) |
class Node(object):
def __init__(self, item):
self.item = item
def __str__(self):
return str(self.item)
def __repr__(self):
return str(self)
def __getattr__(self, attr):
return getattr(self.item, attr)
| class Node(object):
def __init__(self, item):
self.item = item
def __str__(self):
return str(self.item)
def __repr__(self):
return str(self)
def __getattr__(self, attr):
return getattr(self.item, attr) |
class CountdownObject():
def __init__(self, list_nums, target):
self._list_nums = list_nums # e.g. [1,2,3,4]
self._target = target
self._permutations = [list_nums.copy()] # list of lists, all possible permutations of original list, e.g. [[1,5,7],[2,4,3]...], starts as original list of nums
self._solutions = [[... | class Countdownobject:
def __init__(self, list_nums, target):
self._list_nums = list_nums
self._target = target
self._permutations = [list_nums.copy()]
self._solutions = [[''] * len(list_nums)]
def get_permutations(self):
return self._permutations
def get_solutions... |
description = 'virtual POLI lifting counter'
group = 'lowlevel'
devices = dict(
liftingctr = device('nicos.devices.generic.VirtualMotor',
description = 'lifting counter axis',
pollinterval = 15,
maxage = 61,
fmtstr = '%.2f',
abslimits = (-4.2, 30),
precision = 0.01,... | description = 'virtual POLI lifting counter'
group = 'lowlevel'
devices = dict(liftingctr=device('nicos.devices.generic.VirtualMotor', description='lifting counter axis', pollinterval=15, maxage=61, fmtstr='%.2f', abslimits=(-4.2, 30), precision=0.01, unit='deg')) |
#
# PySNMP MIB module COLUBRIS-CONNECTION-LIMITING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COLUBRIS-CONNECTION-LIMITING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
def is_even(x):
result=x//2
if((x-result*2)==0):
return True
else:
return False | def is_even(x):
result = x // 2
if x - result * 2 == 0:
return True
else:
return False |
#!/usr/bin/python3
complex_delete = __import__('102-complex_delete').complex_delete
print_sorted_dictionary = \
__import__('6-print_sorted_dictionary').print_sorted_dictionary
a_dictionary = {'lang': "C", 'track': "Low", 'pref': "C", 'ids': [1, 2, 3]}
new_dict = complex_delete(a_dictionary, 'C')
print_sorted_dicti... | complex_delete = __import__('102-complex_delete').complex_delete
print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary
a_dictionary = {'lang': 'C', 'track': 'Low', 'pref': 'C', 'ids': [1, 2, 3]}
new_dict = complex_delete(a_dictionary, 'C')
print_sorted_dictionary(a_dictionary)
print(... |
def changeValueA(actualDataFrame, changeValue):
predictedData = actualDataFrame.copy()
predictedData["y"] = [item*changeValue for item in actualDataFrame["x"]]
return predictedData
def changeValueB(actualDataFrame, changeValue):
predictedData = actualDataFrame.copy()
predictedData["y"] = [item+cha... | def change_value_a(actualDataFrame, changeValue):
predicted_data = actualDataFrame.copy()
predictedData['y'] = [item * changeValue for item in actualDataFrame['x']]
return predictedData
def change_value_b(actualDataFrame, changeValue):
predicted_data = actualDataFrame.copy()
predictedData['y'] = [i... |
# # # # # # # # Python Tuples (a,b)
# # # # # # # # Immutable - size is fixed
# # # # # # # # Use - passing data that does not need changing
# # # # # # # # Faster than list - less bookkeeping no worries about size change
# # # # # # # # "safer" than list
# # # # # # # # Can be key in dict unlike list
# # # # # # # # F... | my_tuple = ('Valdis', 'programmer', 45, 200.8, [10, 20, 30], True, None, ('also_tuple', 5, True), {'food': 'potatoes', 'drink': 'kefir'})
print(my_tuple)
simple_tuple = (10, 20, 30)
print(simple_tuple)
another_tuple = tuple([1, 'Valdis', True])
print(another_tuple)
print(type(my_tuple))
numbers_tuple = tuple(range(100,... |
# v = dict.fromkeys(["k1","123","323"],123)
# print(v)
# dic = {'k1': 123, 456: 123, '999': 123}
# v = dic.pop()
# print(v,dic)
# del dic["999"]
# print(dic)
# dic = {'k1': 123, 123: 123, '999': 123}
# v = dic.setdefault("k2","123")
# print(v,dic)
# dic.update({"k3":"v3"})
# dic.update(k4="v4")
# for i in dic.keys():
... | dic = {'k1': 123, 123: 123, '999': 123}
for (i, v) in enumerate(dic.items(), 1):
print(i, v[0], v[1])
for (i, v) in enumerate(dic, 1):
print(i, v, dic[v]) |
crime_codes = {
'740': 'VANDALISM - FELONY ($400 & OVERALL CHURCH VANDALISMS) 0114',
'888': 'TRESPASSING',
'330': 'BURGLARY FROM VEHICLE',
'745': 'VANDALISM - MISDEAMEANOR ($399 OR UNDER)',
'510': 'VEHICLE - STOLEN',
'210': 'ROBBERY',
'901': 'VIOLATION OF RESTRAINING ORDER',
'626': 'INTI... | crime_codes = {'740': 'VANDALISM - FELONY ($400 & OVERALL CHURCH VANDALISMS) 0114', '888': 'TRESPASSING', '330': 'BURGLARY FROM VEHICLE', '745': 'VANDALISM - MISDEAMEANOR ($399 OR UNDER)', '510': 'VEHICLE - STOLEN', '210': 'ROBBERY', '901': 'VIOLATION OF RESTRAINING ORDER', '626': 'INTIMATE PARTNER - SIMPLE ASSAULT', '... |
def in_range(minim, maxim, num):
if minim > maxim:
aux = minim
minim = maxim
maxim = aux
return num in range(minim, maxim)
x = in_range(10, 14, 11)
print(x)
| def in_range(minim, maxim, num):
if minim > maxim:
aux = minim
minim = maxim
maxim = aux
return num in range(minim, maxim)
x = in_range(10, 14, 11)
print(x) |
# 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 __init__(self):
self.has_found = False
self.res = []
self.path = []
def DFS(self, n... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.has_found = False
self.res = []
self.path = []
def dfs(self, node, tar):
if node is None:
... |
info = {0: {'bad_channels': [3],
'color': 'red',
'polygon': [(0.396535162031, -0.628663752105),
(0.396444292843, -0.631425958949),
(0.396352852158, -0.634185981605),
(0.396260837973, -0.63694380631),
(0.3961682483, -0.639699419259),
... | info = {0: {'bad_channels': [3], 'color': 'red', 'polygon': [(0.396535162031, -0.628663752105), (0.396444292843, -0.631425958949), (0.396352852158, -0.634185981605), (0.396260837973, -0.63694380631), (0.3961682483, -0.639699419259), (0.396075081167, -0.642452806602), (0.395981334623, -0.645203954444), (0.395887006733, ... |
n = int(input())
salary = int(input())
penalty = 0
for i in range(n):
browser_tab = input()
if browser_tab == 'Facebook':
penalty += 150
elif browser_tab == 'Instagram':
penalty += 100
elif browser_tab == 'Reddit':
penalty += 50
if salary - penalty <= 0:
print('You have los... | n = int(input())
salary = int(input())
penalty = 0
for i in range(n):
browser_tab = input()
if browser_tab == 'Facebook':
penalty += 150
elif browser_tab == 'Instagram':
penalty += 100
elif browser_tab == 'Reddit':
penalty += 50
if salary - penalty <= 0:
print('You have lost ... |
# Tabela verdade do operador not
x = True
y = False
print(not x)
print(not y)
# Tabela verdade do operador and (e)(apenas true e true da true)
x = True
y = False
print(x and y)
# Tabela verdade do operador or (ou) (apenas false ou false da false)(o resto da true)
x = True
y = False
print(x or y)
# exemplo 1 not
x = ... | x = True
y = False
print(not x)
print(not y)
x = True
y = False
print(x and y)
x = True
y = False
print(x or y)
x = 10
y = 1
res = not x > y
print(res)
x = 10
y = 1
z = 5.5
res = x > y and z == y
print(res)
x = 10
y = 1
z = 5.5
res = x > y or z == y
print(res)
x = 10
y = 1
z = 5.5
res = x > y or (not z == y and y != y ... |
def encrypt(y):
y = y ^ y >> 11
y = y ^ y << 7 & 2636928640
y = y ^ y << 15 & 4022730752
y = y ^ y >> 18
return y
flag = open("flag", 'rb').read().strip()
encrypted = list(map(encrypt, flag))
print(encrypted)
# 151130148, 189142078, 184947887, 184947887, 155324581, 4194515, 16908820, 16908806, 172234346, 1... | def encrypt(y):
y = y ^ y >> 11
y = y ^ y << 7 & 2636928640
y = y ^ y << 15 & 4022730752
y = y ^ y >> 18
return y
flag = open('flag', 'rb').read().strip()
encrypted = list(map(encrypt, flag))
print(encrypted) |
def parity_brute_force(x):
res = 0
while x > 0:
res ^= x & 0x1
x = x >> 1
return res
def parity_bit_shifting(x):
four_bit_parity_lookup_table = 0x6996 #= 0b0110100110010110
x ^= x >> 32
x ^= x >> 16
x ^= x >> 8
x ^= x >> 4
x &= 0xF
return (four_bit_parity_loo... | def parity_brute_force(x):
res = 0
while x > 0:
res ^= x & 1
x = x >> 1
return res
def parity_bit_shifting(x):
four_bit_parity_lookup_table = 27030
x ^= x >> 32
x ^= x >> 16
x ^= x >> 8
x ^= x >> 4
x &= 15
return four_bit_parity_lookup_table >> x & 1
if __name__ ... |
t=int(input())
while(t):
n,v1,v2=map(int,input().split())
if(2**0.5)/v1<2/v2:
print("Stairs")
else:
print("Elevator")
t=t-1
| t = int(input())
while t:
(n, v1, v2) = map(int, input().split())
if 2 ** 0.5 / v1 < 2 / v2:
print('Stairs')
else:
print('Elevator')
t = t - 1 |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CON... | class Sensor:
def __init__(self, black_level, saturation, ccm, camera_name):
self.black_level = black_level
self.saturation = saturation
self.ccm = ccm
self.camera_name = camera_name
def to_dict(self):
return {'camera_name': self.camera_name, 'black_level': self.black_l... |
#def init():
#Global Variables
#global sim_start_time
sim_start_time = '2014-02-01 00:00:00'
#global DatumLong
#original coloseum DatumLong = 12.492373 #Eastwards
DatumLong = 12.4420
#global DatumLat
#original coloseum DatumLat = 41.890251 #Northwards
DatumLat = 41.9280
#map bounds in paper
#(41.856, 12.442),(41.928... | sim_start_time = '2014-02-01 00:00:00'
datum_long = 12.442
datum_lat = 41.928 |
class Color(DefaultColor):
HOSTNAME_FG = 231
HOSTNAME_BG = 23
HOME_SPECIAL_DISPLAY = False
JOBS_FG = 15
JOBS_BG = 31
| class Color(DefaultColor):
hostname_fg = 231
hostname_bg = 23
home_special_display = False
jobs_fg = 15
jobs_bg = 31 |
def tabcompare(source, target):
s_last_deal = 0
n = 0
with open('result.txt', 'w') as f:
for s in source:
for t in target:
print('compare {} and {}'.format(s, t))
s_last_deal = s
if s < t:
f.write(str(s))
... | def tabcompare(source, target):
s_last_deal = 0
n = 0
with open('result.txt', 'w') as f:
for s in source:
for t in target:
print('compare {} and {}'.format(s, t))
s_last_deal = s
if s < t:
f.write(str(s))
... |
# Time: O(n)
# Space: O(1)
def findThreeLargestNumbers(array):
threeLargestNumbers = [None, None, None]
for num in array:
updateLargest(threeLargestNumbers, num)
return threeLargestNumbers
def updateLargest(threeLargest, num):
if threeLargest[2] is None or num > threeLargest[2]:
shift... | def find_three_largest_numbers(array):
three_largest_numbers = [None, None, None]
for num in array:
update_largest(threeLargestNumbers, num)
return threeLargestNumbers
def update_largest(threeLargest, num):
if threeLargest[2] is None or num > threeLargest[2]:
shift_and_update(threeLarge... |
INF = 999999
def print_distances(graph, from_vertex=0):
num_vertices = len(graph)
dists = [ INF ] * num_vertices
visited = [ False ] * num_vertices
dists[from_vertex] = 0
for k in range(num_vertices - 1):
min_dist, vertex = INF, -1
for v in range(num_vertices):
if... | inf = 999999
def print_distances(graph, from_vertex=0):
num_vertices = len(graph)
dists = [INF] * num_vertices
visited = [False] * num_vertices
dists[from_vertex] = 0
for k in range(num_vertices - 1):
(min_dist, vertex) = (INF, -1)
for v in range(num_vertices):
if not vi... |
# Created by MechAviv
# Sheep Damage Skin | (2436721)
if sm.addDamageSkin(2436721):
sm.chat("'Sheep Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() | if sm.addDamageSkin(2436721):
sm.chat("'Sheep Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
# Space: O(1)
# Time: O(n)
class NumMatrix:
def __init__(self, matrix):
self.board = matrix
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
res = 0
for y in range(row1, row2 + 1):
for x in range(col1, col2 + 1):
res += self.board[y]... | class Nummatrix:
def __init__(self, matrix):
self.board = matrix
def sum_region(self, row1: int, col1: int, row2: int, col2: int) -> int:
res = 0
for y in range(row1, row2 + 1):
for x in range(col1, col2 + 1):
res += self.board[y][x]
return res |
name = "Sophie"
number = 24811
print (number)
number -= 20
name += "!!!"
print (name)
print (number)
age = 20016
age -= 20005
print ("Sophie is %s" % name) | name = 'Sophie'
number = 24811
print(number)
number -= 20
name += '!!!'
print(name)
print(number)
age = 20016
age -= 20005
print('Sophie is %s' % name) |
class CrudSerializer:
get_list_response_model = None
get_item_response_model = None
update_item_request_model = None
update_item_response_model = None
create_item_request_model = None
create_item_response_model = None
remove_item_response_model = None
| class Crudserializer:
get_list_response_model = None
get_item_response_model = None
update_item_request_model = None
update_item_response_model = None
create_item_request_model = None
create_item_response_model = None
remove_item_response_model = None |
name = "Jan Maximilan Schaffranek"
result = name.find("an")
if result == -1:
print("Not found")
else:
print("Found at index: ", result)
name2 = name.replace("Jan", "Yann")
print(name)
print(name2)
name3 = name.upper()
print(name3)
name4 = name.lower()
print(name4)
name5 = name.split(" ")
print(name5)... | name = 'Jan Maximilan Schaffranek'
result = name.find('an')
if result == -1:
print('Not found')
else:
print('Found at index: ', result)
name2 = name.replace('Jan', 'Yann')
print(name)
print(name2)
name3 = name.upper()
print(name3)
name4 = name.lower()
print(name4)
name5 = name.split(' ')
print(name5)
count = na... |
class CommandSyntaxException(Exception):
CONTEXT_AMOUNT = 50
def __init__(self, exc_type, message, str_input=None, cursor=-1):
super().__init__(message)
self.type = exc_type
self.message = message
self.input = str_input
self.cursor = cursor
def get_message(self)... | class Commandsyntaxexception(Exception):
context_amount = 50
def __init__(self, exc_type, message, str_input=None, cursor=-1):
super().__init__(message)
self.type = exc_type
self.message = message
self.input = str_input
self.cursor = cursor
def get_message(self):
... |
x = True
y = False
print(x and y)
# False
print(x or y)
# True
print(not x)
# False
print(bool(10))
# True
print(bool(0))
# False
print(bool(''))
# False
print(bool('0'))
# True
print(bool('False'))
# True
print(bool([]))
# False
print(bool([False]))
# True
x = 10 # True
y = 0 # False
print(x and y)
# 0
... | x = True
y = False
print(x and y)
print(x or y)
print(not x)
print(bool(10))
print(bool(0))
print(bool(''))
print(bool('0'))
print(bool('False'))
print(bool([]))
print(bool([False]))
x = 10
y = 0
print(x and y)
print(x or y)
print(not x)
x = 10
y = 100
print(x and y)
print(y and x)
print(x or y)
print(y or x)
x = 0
y =... |
"Mirror of release info"
TOOL_VERSIONS = {
"v1.2.185": {
"android-arm-eabi": "sha384-a9NRmV90j+tXV7xT3+LK+UBcUgKMVRp9k4yz29hKi7VRqwIQxuL3aKAcyP1mXCly",
"android-arm64": "sha384-rdQq6yIfkTZtuhYiIz2eo0/Y1MuPDAGqf4See2ZPYRnzF6owWSAkU1MzUnKlwvas",
"darwin-arm64": "sha384-hMId2tsrNKrkOUH5MLGmNfR... | """Mirror of release info"""
tool_versions = {'v1.2.185': {'android-arm-eabi': 'sha384-a9NRmV90j+tXV7xT3+LK+UBcUgKMVRp9k4yz29hKi7VRqwIQxuL3aKAcyP1mXCly', 'android-arm64': 'sha384-rdQq6yIfkTZtuhYiIz2eo0/Y1MuPDAGqf4See2ZPYRnzF6owWSAkU1MzUnKlwvas', 'darwin-arm64': 'sha384-hMId2tsrNKrkOUH5MLGmNfRo/MplSwiRGjdTYg2OuFJEHa3fy4... |
a, b = input().split()
a = int(a)
b = int(b)
if a < b:
c = b % a
if(c == 0):
print('Sao Multiplos')
else:
print('Nao sao Multiplos')
else:
c = a % b
if (c == 0):
print('Sao Multiplos')
else:
print('Nao sao Multiplos') | (a, b) = input().split()
a = int(a)
b = int(b)
if a < b:
c = b % a
if c == 0:
print('Sao Multiplos')
else:
print('Nao sao Multiplos')
else:
c = a % b
if c == 0:
print('Sao Multiplos')
else:
print('Nao sao Multiplos') |
def MFnComponent_elementCount(*args, **kwargs):
pass
def MFloatMatrix_isEquivalent(*args, **kwargs):
pass
def MTrimBoundaryArray_insert(*args, **kwargs):
pass
def boolPtr_value(*args, **kwargs):
pass
def MQuaternion_setToZAxis(*args, **kwargs):
pass
def MDataBlock_inputArrayValue(*args, **... | def m_fn_component_element_count(*args, **kwargs):
pass
def m_float_matrix_is_equivalent(*args, **kwargs):
pass
def m_trim_boundary_array_insert(*args, **kwargs):
pass
def bool_ptr_value(*args, **kwargs):
pass
def m_quaternion_set_to_z_axis(*args, **kwargs):
pass
def m_data_block_input_array_va... |
expected_output = {
'prefixes':{
'/misc/config':{
'size':'48648003584',
'free':'42960707584',
'type':'flash',
'flags':'rw'
},
'tftp:':{
'size':'0',
'free':'0',
'type':'network',
'flags':'rw'
},
'disk2:':{
... | expected_output = {'prefixes': {'/misc/config': {'size': '48648003584', 'free': '42960707584', 'type': 'flash', 'flags': 'rw'}, 'tftp:': {'size': '0', 'free': '0', 'type': 'network', 'flags': 'rw'}, 'disk2:': {'size': '4008443904', 'free': '3018457088', 'type': 'flash-disk', 'flags': 'rw'}, 'ftp:': {'size': '0', 'free'... |
class QuickUnion:
def __init__(self, N):
self._id = list(range(N))
self._count = N
self._rank = [0] * N
def find(self, p):
id = self._id
while p != id[p]:
p = id[p] = id[id[p]] # Path compression using halving.
return p
def union(self, p, q):
... | class Quickunion:
def __init__(self, N):
self._id = list(range(N))
self._count = N
self._rank = [0] * N
def find(self, p):
id = self._id
while p != id[p]:
p = id[p] = id[id[p]]
return p
def union(self, p, q):
id = self._id
rank =... |
class Solution:
def intToRoman(self, num: int) -> str:
roman_dict = {
"I": 1,
"IV": 4,
"V": 5,
"IX": 9,
"X": 10,
"XL": 40,
"L": 50,
"XC":90,
"C": 100,
"CD": 400,
"D": 500,
... | class Solution:
def int_to_roman(self, num: int) -> str:
roman_dict = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'MD': 900, 'M': 1000}
roman_list = []
for (k, v) in reversed(roman_dict.items()):
while num > 0:
... |
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
class Solution:
def levelOrder(self, root: 'Node') -> list:
q, ans = [root], []
while any(q):
ans.append([item.val for item in q])
q = [child for item in q for child i... | class Node:
def __init__(self, val, children):
self.val = val
self.children = children
class Solution:
def level_order(self, root: 'Node') -> list:
(q, ans) = ([root], [])
while any(q):
ans.append([item.val for item in q])
q = [child for item in q for c... |
avancer()
droite()
avancer()
gauche()
avancer()
droite()
for _ in range(16):
avancer()
ouvrir()
| avancer()
droite()
avancer()
gauche()
avancer()
droite()
for _ in range(16):
avancer()
ouvrir() |
class Solution:
def intToRoman(self, num):
s = "M" * (num // 1000)
s += "CM" if num % 1000 >= 900 else "D" *((num % 1000) // 500)
s += "CD" if num % 500 >= 400 and s[-2:] != "CM" else "C" * ((num % 500) // 100) if num % 500 < 400 else ""
s += "XC" if num % 100 >= 90 else "L" * ((num... | class Solution:
def int_to_roman(self, num):
s = 'M' * (num // 1000)
s += 'CM' if num % 1000 >= 900 else 'D' * (num % 1000 // 500)
s += 'CD' if num % 500 >= 400 and s[-2:] != 'CM' else 'C' * (num % 500 // 100) if num % 500 < 400 else ''
s += 'XC' if num % 100 >= 90 else 'L' * (num %... |
class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
memo = {}
def dp(i, j):
if (i, j) not in memo:
memo[i, j] = min([dp(i, k) + dp(k, j) + A[i] * A[j] * A[k] for k in range(i + 1, j)] or [0])
return memo[i, j]
return dp(0, len(A) - 1) | class Solution:
def min_score_triangulation(self, A: List[int]) -> int:
memo = {}
def dp(i, j):
if (i, j) not in memo:
memo[i, j] = min([dp(i, k) + dp(k, j) + A[i] * A[j] * A[k] for k in range(i + 1, j)] or [0])
return memo[i, j]
return dp(0, len(A) ... |
S = input()
check = [-1] * 26
for i in range(len(S)):
if check[ord(S[i]) - 97] != -1:
continue
else:
check[ord(S[i]) - 97] = i
for i in range(26):
print(check[i], end=' ') | s = input()
check = [-1] * 26
for i in range(len(S)):
if check[ord(S[i]) - 97] != -1:
continue
else:
check[ord(S[i]) - 97] = i
for i in range(26):
print(check[i], end=' ') |
l=range(1,50)
#l=[1,2,6,99,455,21111111,5]
print(type(l))
max=0
for i in l:
if i>max :
max=i
print(f"max is {max}") | l = range(1, 50)
print(type(l))
max = 0
for i in l:
if i > max:
max = i
print(f'max is {max}') |
class StorageInteractions:
def __init__(self, **repositories):
self._storage_repository = repositories["storage_repository"]
def load(self, name):
return self._storage_repository.load_file(name)
def store(self, file):
name = self._storage_repository.store_file(file)
return... | class Storageinteractions:
def __init__(self, **repositories):
self._storage_repository = repositories['storage_repository']
def load(self, name):
return self._storage_repository.load_file(name)
def store(self, file):
name = self._storage_repository.store_file(file)
return... |
##########################################################
# Author: Raghav Sikaria
# LinkedIn: https://www.linkedin.com/in/raghavsikaria/
# Github: https://github.com/raghavsikaria
# Last Update: 16-5-2020
# Project: LeetCode May 31 Day 2020 Challenge - Day 16
##########################################################... | class Solution:
def odd_even_list(self, head: ListNode) -> ListNode:
if head == None:
return None
odd_node = head
even_node = head.next
even_head = even_node
while even_node is not None:
if odd_node is None or even_node.next is None:
b... |
n=int(input("Tabuada de: "))
x=1
while x<=10:
print(n*x)
x=x+1 | n = int(input('Tabuada de: '))
x = 1
while x <= 10:
print(n * x)
x = x + 1 |
class BasePOI:
def __init__(self, lat, lng,value):
self.lat = lat
self.lng = lng
self.value = value
def __repr__(self):
return ','.join(list(map(str, (self.lat, self.lng, self.value))))
# models realted to the db tables
class Anemity(BasePOI):
def __i... | class Basepoi:
def __init__(self, lat, lng, value):
self.lat = lat
self.lng = lng
self.value = value
def __repr__(self):
return ','.join(list(map(str, (self.lat, self.lng, self.value))))
class Anemity(BasePOI):
def __init__(self, lat, lng, anemity_type, name):
Bas... |
# exception classes
class Error(Exception):
pass
class ParameterError(Error):
pass
| class Error(Exception):
pass
class Parametererror(Error):
pass |
input_file = "/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/output.root"
input_file = "/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501_minisample.root"
input_file = "/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501.root"
... | input_file = '/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/output.root'
input_file = '/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501_minisample.root'
input_file = '/Users/jrawling/Documents/Physics/DeadConeAnalysis/ATLASWork/samples/ttj/410501.root'
detector_... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def middleNode(self, head):
currNode = head
count = 0
while currNode:
currNode = currNode.next
count += 1
middle = count // 2 + 1
... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def middle_node(self, head):
curr_node = head
count = 0
while currNode:
curr_node = currNode.next
count += 1
middle = count // 2 + 1
... |
async def test_make_coro(make_coro):
coro = make_coro(1)
assert 1 == await coro()
| async def test_make_coro(make_coro):
coro = make_coro(1)
assert 1 == await coro() |
# https://i.gyazo.com/38682c2adf56d01422a7266f62c4794f.png
instruments = [
'Acoustic Grand Piano',
'Bright Acoustic Piano',
'Electric Grand Piano',
'Honky tonk Piano',
'Electric Piano 1',
'Electric Piano 2',
'Harpsichord',
'Clavi',
'Celesta',
'Glockenspiel',
'Music Box',
... | instruments = ['Acoustic Grand Piano', 'Bright Acoustic Piano', 'Electric Grand Piano', 'Honky tonk Piano', 'Electric Piano 1', 'Electric Piano 2', 'Harpsichord', 'Clavi', 'Celesta', 'Glockenspiel', 'Music Box', 'Vibraphone', 'Marimba', 'Xylophone', 'Tubular Bells', 'Dulcimer', 'Drawbar Organ', 'Percussive Organ', 'Roc... |
trick.real_time_enable()
trick.exec_set_software_frame(0.1)
# Instantiate the keyboard. Make sure you change the arguments to match your keyboard's
# vendor and product IDs
keyboard = trick.UsbKeyboard(0x413C, 0x2101)
example.add(keyboard)
# SingleFlightController's construtor takes the six Inputs we want to use for ... | trick.real_time_enable()
trick.exec_set_software_frame(0.1)
keyboard = trick.UsbKeyboard(16700, 8449)
example.add(keyboard)
roll = trick.CompositeInput()
roll.addInput(keyboard.keypad9)
roll.addInput(keyboard.keypad7, -1)
pitch = trick.CompositeInput()
pitch.addInput(keyboard.keypad8)
pitch.addInput(keyboard.keypad2, -... |
#pragma error
#pragma repy
global foo
foo = 2
| global foo
foo = 2 |
def input_natural():
num = int(input("Digite o valor de n: "))
return num
num = input_natural()
fatorial = 1
if num < 0:
input_natural()
else:
for i in range(1, num+1):
fatorial += fatorial * (num - i)
print(fatorial)
| def input_natural():
num = int(input('Digite o valor de n: '))
return num
num = input_natural()
fatorial = 1
if num < 0:
input_natural()
else:
for i in range(1, num + 1):
fatorial += fatorial * (num - i)
print(fatorial) |
"import rules"
load("@io_bazel_rules_dotnet//dotnet/private:context.bzl", "dotnet_context")
load("@io_bazel_rules_dotnet//dotnet/private:common.bzl", "as_iterable")
load("@io_bazel_rules_dotnet//dotnet/private:providers.bzl", "DotnetLibraryInfo")
load("@io_bazel_rules_dotnet//dotnet/private:rules/common.bzl", "collect... | """import rules"""
load('@io_bazel_rules_dotnet//dotnet/private:context.bzl', 'dotnet_context')
load('@io_bazel_rules_dotnet//dotnet/private:common.bzl', 'as_iterable')
load('@io_bazel_rules_dotnet//dotnet/private:providers.bzl', 'DotnetLibraryInfo')
load('@io_bazel_rules_dotnet//dotnet/private:rules/common.bzl', 'coll... |
def authenticate_as(client, username, password):
token = client.post(
"/auth/authenticate/", {"username": username, "password": password}
).data["token"]
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
| def authenticate_as(client, username, password):
token = client.post('/auth/authenticate/', {'username': username, 'password': password}).data['token']
client.credentials(HTTP_AUTHORIZATION=f'Bearer {token}') |
# Huu Hung Nguyen
# 10/07/2021
# Nguyen_HuuHung_donuts.py
# Constants for price dozen and single of plain donuts,
# and price dozen and single of fancy donuts.
# The program prompts the user for the number of plain and fancy donuts.
# It then calculates and displays the number of dozens and single donuts
# for e... | price_dozen_plain = 7.0
price_single_plain = 0.6
price_dozen_fancy = 9.0
price_single_fancy = 0.8
dozen = 12
plain = int(input('Enter number of plain donuts you want to buy: '))
fancy = int(input('Enter number of fancy donuts you want to buy: '))
dozen_plain = plain // DOZEN
single_plain = plain % DOZEN
dozen_fancy = f... |
file = open("input.txt", 'r')
out_string = ''
for segment in file.read().split('.'):
out_string += segment.split(':')[0] + '@@'
out = open('hello.html', 'w')
out.write('<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<link rel=\"stylesheet\" href=\"https://www... | file = open('input.txt', 'r')
out_string = ''
for segment in file.read().split('.'):
out_string += segment.split(':')[0] + '@@'
out = open('hello.html', 'w')
out.write('<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<link rel="stylesheet" href="https://www.w3schools.co... |
class SingletonMeta(type):
_instance = None
def __call__(self):
if self._instance is None:
self._instance = super().__call__()
return self._instance
| class Singletonmeta(type):
_instance = None
def __call__(self):
if self._instance is None:
self._instance = super().__call__()
return self._instance |
def func1():
pass
def func2(arg):
print(arg)
| def func1():
pass
def func2(arg):
print(arg) |
def prefix_suffix(w, m):
B, t = [-1] + [0] * m, -1
for i in range(1, m + 1):
while t >= 0 and w[t + 1] != w[i]:
t = B[t] # prefikso-sufiks to relacja przechodnia
t = t + 1
B[i] = t
return B | def prefix_suffix(w, m):
(b, t) = ([-1] + [0] * m, -1)
for i in range(1, m + 1):
while t >= 0 and w[t + 1] != w[i]:
t = B[t]
t = t + 1
B[i] = t
return B |
# data_list = [(x, y), ...]
b = np.matrix(map(lambda pair:
[pair[1]], data_list))
a = np.matrix(map(lambda pair:
[e**(d * pair[0]),
e**(-d * pair[0]),
1], data_list))
| b = np.matrix(map(lambda pair: [pair[1]], data_list))
a = np.matrix(map(lambda pair: [e ** (d * pair[0]), e ** (-d * pair[0]), 1], data_list)) |
#!/usr/bin/env python3
# _*_ coding:utf-8 _*
# Parent class has to inherit from "object" class
class Parent(object):
def __init__(self):
print("parent constructor called!")
| class Parent(object):
def __init__(self):
print('parent constructor called!') |
def sieve(number):
prime = [True for i in range(number+1)]
p = 2
while (p * p <= number):
if (prime[p] == True):
for i in range(p * p, number+1, p):
prime[i] = False
p += 1
primes = []
for p in range(2, number+1):
if prime[p]:
primes.ap... | def sieve(number):
prime = [True for i in range(number + 1)]
p = 2
while p * p <= number:
if prime[p] == True:
for i in range(p * p, number + 1, p):
prime[i] = False
p += 1
primes = []
for p in range(2, number + 1):
if prime[p]:
primes.... |
def main():
with open('input.txt', 'r') as f:
lines = f.readlines()
d = dict()
for li in lines:
s1, s2 = li.strip().split(')')
d[s2] = s1
total_links = 0
for s2,s1 in d.items():
while s1:
total_links += 1
s1 = d.get(s1, None)
print(tota... | def main():
with open('input.txt', 'r') as f:
lines = f.readlines()
d = dict()
for li in lines:
(s1, s2) = li.strip().split(')')
d[s2] = s1
total_links = 0
for (s2, s1) in d.items():
while s1:
total_links += 1
s1 = d.get(s1, None)
print(tot... |
def reversible_count(d):
if d % 4 == 1:
return 0
# 2 digits: no carry over, and sum of two digits is odd
# 2 digits => 20
# 4 digits: outer pair is the same as 2 digits
# inner pair has 30 possibilities because 0 is allowed
if d % 4 == 0 or d % 4 == 2:
return 20 * 30 **... | def reversible_count(d):
if d % 4 == 1:
return 0
if d % 4 == 0 or d % 4 == 2:
return 20 * 30 ** (d // 2 - 1)
if d % 4 == 3:
return 100 * 500 ** ((d - 3) // 4)
print(sum([reversible_count(d) for d in range(1, 10)])) |
class Locators():
base_url = "https://www.amazon.com.tr/"
search_box_locator_id = "twotabsearchtextbox"
search_box_text = "samsung galaxy m12"
search_summit_button_id = "nav-search-submit-button"
close_cookie_name = "accept"
product_title = "productTitle"
product = "span[class='a-size-base-p... | class Locators:
base_url = 'https://www.amazon.com.tr/'
search_box_locator_id = 'twotabsearchtextbox'
search_box_text = 'samsung galaxy m12'
search_summit_button_id = 'nav-search-submit-button'
close_cookie_name = 'accept'
product_title = 'productTitle'
product = "span[class='a-size-base-plu... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
lenA = 0
lenB = 0
tempA = h... | class Solution:
def get_intersection_node(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
len_a = 0
len_b = 0
temp_a = headA
temp_b = headB
while tempA:
len_a += 1
temp_a = tempA.next
while tempB:
len_b += 1
... |
SEARCH_WORD_LIST = ['woman', 'wear', 'skirt']#['cat', 'and', 'dog']
SECRET_FILE = "./engine/data/refer/azure_secret_sample.json"# be careful not to expose!
SAVE_DIR = "./engine/data/tmp"
SAVE_PAR_DIR = "./engine/data/tmp/bingimgs"
OBJINFO_PATH = "./engine/data/tmp/obj.json"
AZURE_DICT = "./engine/data/tmp/azure_rel_di... | search_word_list = ['woman', 'wear', 'skirt']
secret_file = './engine/data/refer/azure_secret_sample.json'
save_dir = './engine/data/tmp'
save_par_dir = './engine/data/tmp/bingimgs'
objinfo_path = './engine/data/tmp/obj.json'
azure_dict = './engine/data/tmp/azure_rel_dict/search_word.pkl' |
class DottedDict(dict):
__slots__ = ()
def __getattr__(self, item):
return self[item]
def __setattr__(self, name, value):
self[name] = value
| class Dotteddict(dict):
__slots__ = ()
def __getattr__(self, item):
return self[item]
def __setattr__(self, name, value):
self[name] = value |
class xsort():
# to find the max number in list we can
# use max() function in python
def findMax(_list):
mout = _list[0]
for i in _list:
if i >= mout:
mout = i
return mout
def run(_list):
list_ = []
for i in range(len(_list... | class Xsort:
def find_max(_list):
mout = _list[0]
for i in _list:
if i >= mout:
mout = i
return mout
def run(_list):
list_ = []
for i in range(len(_list)):
big = xsort.findMax(_list)
list_.insert(0, big)
_l... |
class Currying(object):
def __init__(self, fun):
self.fun = fun
self.argc = fun.__code__.co_argcount
self.argl = ()
def __call__(self, *args):
tmp = self.argl + args
if len(tmp) >= self.argc:
return self.fun(*tmp)
curr = Currying(self.fun)
cur... | class Currying(object):
def __init__(self, fun):
self.fun = fun
self.argc = fun.__code__.co_argcount
self.argl = ()
def __call__(self, *args):
tmp = self.argl + args
if len(tmp) >= self.argc:
return self.fun(*tmp)
curr = currying(self.fun)
cu... |
class Entity(object):
def __init__(self, entity_input_config):
if type(entity_input_config) is not dict:
#self._ha_api.log("Config error, not a dict check your entity configs")
self.entityId = "error"
self.nameOverride = None
self.iconOverride = None
e... | class Entity(object):
def __init__(self, entity_input_config):
if type(entity_input_config) is not dict:
self.entityId = 'error'
self.nameOverride = None
self.iconOverride = None
else:
self.entityId = entity_input_config.get('entity', 'unknown')
... |
imgurr = {
1: "https://i.imgur.com/ZF6TzS4.jpg",
2: "https://i.imgur.com/eaSvBJR.jpg",
3: "https://i.imgur.com/bDoDm2W.jpg",
4: "https://i.imgur.com/5mCbYFU.jpg",
5: "https://i.imgur.com/zfnmieg.jpg",
6: "https://i.imgur.com/lLCL9qv.jpg",
7: "https://i.imgu... | imgurr = {1: 'https://i.imgur.com/ZF6TzS4.jpg', 2: 'https://i.imgur.com/eaSvBJR.jpg', 3: 'https://i.imgur.com/bDoDm2W.jpg', 4: 'https://i.imgur.com/5mCbYFU.jpg', 5: 'https://i.imgur.com/zfnmieg.jpg', 6: 'https://i.imgur.com/lLCL9qv.jpg', 7: 'https://i.imgur.com/F0i1BLU.jpg', 8: 'https://i.imgur.com/7OIXQLG.jpg', 9: 'ht... |
SEED_PORT = 12345
SEED_ADDR = ('192.168.1.100', 5000)
UPDATE_INTERVAL = 20
BUFFER_SIZE = 102400
ALIVE_TIMEOUT = 20
| seed_port = 12345
seed_addr = ('192.168.1.100', 5000)
update_interval = 20
buffer_size = 102400
alive_timeout = 20 |
class Scanner(object):
def __init__(self, regex, code):
self.regex_list = regex
self.code = code
self.tokens = self.scan(code)
def match_regex(self, i, line):
start = line[i:]
for regex, token in self.regex_list:
tok = regex.match(start)
if to... | class Scanner(object):
def __init__(self, regex, code):
self.regex_list = regex
self.code = code
self.tokens = self.scan(code)
def match_regex(self, i, line):
start = line[i:]
for (regex, token) in self.regex_list:
tok = regex.match(start)
if tok... |
def test_get_test(mocked_response, testrail_client, test_data, test):
mocked_response(data_json=test_data)
api_test = testrail_client.tests.get_test(test_id=1)
assert api_test == test
def test_get_tests(mocked_response, testrail_client, test_data, test):
mocked_response(data_json=[test_data])
a... | def test_get_test(mocked_response, testrail_client, test_data, test):
mocked_response(data_json=test_data)
api_test = testrail_client.tests.get_test(test_id=1)
assert api_test == test
def test_get_tests(mocked_response, testrail_client, test_data, test):
mocked_response(data_json=[test_data])
api_t... |
# script that contains some path definitions
path = '../'
input_path = path + 'input_files/'
output_path = path + 'output_files/'
plot_path = path + 'plots/'
rand_path = path + 'QBCHL_random_graphs/'
rand_prefix = 'HQBCL_rand_network_'
| path = '../'
input_path = path + 'input_files/'
output_path = path + 'output_files/'
plot_path = path + 'plots/'
rand_path = path + 'QBCHL_random_graphs/'
rand_prefix = 'HQBCL_rand_network_' |
#!/usr/bin/python
# list_comprehension2.py
lang = "Python"
a = []
for e in lang:
a.append(ord(e))
b = [ord(e) for e in lang]
print (a)
print (b)
| lang = 'Python'
a = []
for e in lang:
a.append(ord(e))
b = [ord(e) for e in lang]
print(a)
print(b) |
'''
Created on Sep 2, 2010
@author: Wilder Rodrigues (wilder.rodrigues@ekholabs.nl)
'''
| """
Created on Sep 2, 2010
@author: Wilder Rodrigues (wilder.rodrigues@ekholabs.nl)
""" |
COINS = [25, 21, 10, 5, 1]
def min_coins_dp(coin_values, change, min_coins):
for cents in range(change + 1):
coin_count = cents
potential_coins_to_use = [coin for coin in coin_values if coin <= cents]
for potential_coin in potential_coins_to_use:
balance = cents - potential_c... | coins = [25, 21, 10, 5, 1]
def min_coins_dp(coin_values, change, min_coins):
for cents in range(change + 1):
coin_count = cents
potential_coins_to_use = [coin for coin in coin_values if coin <= cents]
for potential_coin in potential_coins_to_use:
balance = cents - potential_coin... |
miTupla = ("Pablo", 35, "Jole", 33)
print(miTupla[:])
print("Cambio la tupla a lista")
miLista = list(miTupla)
print(miLista[:])
print("Lo vuelvo a pasar a tupla")
miTupla2 = tuple(miLista)
print(miTupla2[:])
print("Cuento los elementos en la tupla")
print(miTupla2.count("Jole"))
print("Pido el tota... | mi_tupla = ('Pablo', 35, 'Jole', 33)
print(miTupla[:])
print('Cambio la tupla a lista')
mi_lista = list(miTupla)
print(miLista[:])
print('Lo vuelvo a pasar a tupla')
mi_tupla2 = tuple(miLista)
print(miTupla2[:])
print('Cuento los elementos en la tupla')
print(miTupla2.count('Jole'))
print('Pido el total de elementos en... |
def isPerfect( n ):
# To store sum of divisors
sum = 1
# Find all divisors and add them
i = 2
while i * i <= n:
if n % i == 0:
sum = sum + i + n/i
i += 1
# If sum of divisors is equal to
# n, then n is a perfect number
return (True if s... | def is_perfect(n):
sum = 1
i = 2
while i * i <= n:
if n % i == 0:
sum = sum + i + n / i
i += 1
return True if sum == n and n != 1 else False
n = int(input())
for i in range(n):
if is_perfect(i):
print(i, end=' ') |
class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans=cmin=cmax=nums[0]
for i in nums[1:]:
cmin,cmax = min(i,cmin*i,cmax*i),max(i,cmin*i,cmax*i)
if cmax>ans:
ans = cmax
return ans... | class Solution:
def max_product(self, nums: List[int]) -> int:
ans = cmin = cmax = nums[0]
for i in nums[1:]:
(cmin, cmax) = (min(i, cmin * i, cmax * i), max(i, cmin * i, cmax * i))
if cmax > ans:
ans = cmax
return ans |
#
# PySNMP MIB module TY1250I-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TY1250I-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:20:47 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, 0... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection, constraints_union) ... |
# 1417. Reformat The String - LeetCode
# https://leetcode.com/problems/reformat-the-string/
class Solution:
def reformat(self, s: str) -> str:
ret = ""
alphabets = []
numbers = []
for c in s:
if c.isdigit():
numbers.append(c)
if c.isa... | class Solution:
def reformat(self, s: str) -> str:
ret = ''
alphabets = []
numbers = []
for c in s:
if c.isdigit():
numbers.append(c)
if c.isalpha():
alphabets.append(c)
if abs(len(alphabets) - len(numbers)) > 1:
... |
print("INFORMACION: ","si es Ejecutivo:0","Jefe:1","Externo:2")
cargo=int(input("ingrese el cargo del trabajador"))
if cargo==0:
sueldo=90
elif cargo==1:
sueldo=100
else:
sueldo=50
print("Su sueldo es: ",sueldo)
| print('INFORMACION: ', 'si es Ejecutivo:0', 'Jefe:1', 'Externo:2')
cargo = int(input('ingrese el cargo del trabajador'))
if cargo == 0:
sueldo = 90
elif cargo == 1:
sueldo = 100
else:
sueldo = 50
print('Su sueldo es: ', sueldo) |
#String Ex1
#----------
### Work in your pynet_test repository ###
#a. Create a python script with three strings representing three names
#b. Print these three names out in a column 30 wide, right aligned
#c. Execute the script verify the output
#d. Add a prompt for a fourth name, print this out as well
#e. check yo... | name1 = 'Rudy'
name2 = 'Tom'
name3 = 'Greg'
print('{:>30} {:>30} {:>30}'.format(name1, name2, name3)) |
class Solution:
# One Pass (Accepted), O(n) time, O(1) space
def maxScore(self, s: str) -> int:
_max = cur = ones = 0
for i in range(1, len(s)-1):
if s[i] == '0':
cur += 1
_max = max(cur, _max)
else:
cur -= 1
... | class Solution:
def max_score(self, s: str) -> int:
_max = cur = ones = 0
for i in range(1, len(s) - 1):
if s[i] == '0':
cur += 1
_max = max(cur, _max)
else:
cur -= 1
ones += 1
return int(s[0] == '0') + ... |
K = 132
nominaly = [1, 2, 5, 10, 20, 50]
def change_making_greedy(K, nominaly):
nominaly.sort(reverse = True)
coins = []
for i in nominaly:
while K >= i:
coins.append(i)
K -= i
return coins
print(change_making_greedy(K,nominaly)) | k = 132
nominaly = [1, 2, 5, 10, 20, 50]
def change_making_greedy(K, nominaly):
nominaly.sort(reverse=True)
coins = []
for i in nominaly:
while K >= i:
coins.append(i)
k -= i
return coins
print(change_making_greedy(K, nominaly)) |
[
{
'date': '2016-01-01',
'description': "New Year's Day",
'locale': 'en-CA',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2016-02-15',
'description': 'Family Day',
'locale': 'en-CA',
'notes': '',
'region': 'AB'... | [{'date': '2016-01-01', 'description': "New Year's Day", 'locale': 'en-CA', 'notes': '', 'region': '', 'type': 'NF'}, {'date': '2016-02-15', 'description': 'Family Day', 'locale': 'en-CA', 'notes': '', 'region': 'AB', 'type': 'V'}, {'date': '2016-02-15', 'description': 'Family Day', 'locale': 'en-CA', 'notes': '', 'reg... |
#!/usr/bin/env python
#coding: utf-8
# VirusTotal
vt_key = ''
# MISP
misp_url = ''
misp_key = ''
misp_verifycert = False
# Twitter
consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''
# Slack
slack_channel = ''
slack_username = ''
slack_url = ''
| vt_key = ''
misp_url = ''
misp_key = ''
misp_verifycert = False
consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''
slack_channel = ''
slack_username = ''
slack_url = '' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.