content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Welcome to the new format of the course! From now on, I'll be writing within
these Python files instead of in seperate .md files. This will let me write
code in this files and comment on them directly, because this is a .py file
that you can actually run!
To start, we're going to talk about how a computer st... | """
Welcome to the new format of the course! From now on, I'll be writing within
these Python files instead of in seperate .md files. This will let me write
code in this files and comment on them directly, because this is a .py file
that you can actually run!
To start, we're going to talk about how a computer stores d... |
#
# Copyright (c) 2010-2016, Fabric Software Inc. All rights reserved.
#
Direct = 0
Reference = 1
Pointer = 2
| direct = 0
reference = 1
pointer = 2 |
class GtExampleDependency:
def __init__(self,gt_example):
self.gt_example = gt_example
self.parent_dependencies = []
self.child_dependencies = []
def add_parent(self, parent_dependency):
self.parents().append(parent_dependency)
def add_child(self, child_dependency):
... | class Gtexampledependency:
def __init__(self, gt_example):
self.gt_example = gt_example
self.parent_dependencies = []
self.child_dependencies = []
def add_parent(self, parent_dependency):
self.parents().append(parent_dependency)
def add_child(self, child_dependency):
... |
n=int(input())
t=[[0]*n for i in range (n)]
i,j=0,0
for k in range(1, n*n+1):
t[i][j]=k
if k==n*n: break
if i<=j+1 and i+j<n-1: j+=1
elif i<j and i+j>=n-1: i+=1
elif i>=j and i+j>n-1: j-=1
elif i>j+1 and i+j<=n-1: i-=1
for i in range(n):
print(*t[i]) | n = int(input())
t = [[0] * n for i in range(n)]
(i, j) = (0, 0)
for k in range(1, n * n + 1):
t[i][j] = k
if k == n * n:
break
if i <= j + 1 and i + j < n - 1:
j += 1
elif i < j and i + j >= n - 1:
i += 1
elif i >= j and i + j > n - 1:
j -= 1
elif i > j + 1 and i... |
#use of the while loop to determine the number of digits of an integer n:
n = int(input())
length = 0
while n > 0:
n = n//10
length = length + 1
print("number of digits in the given number n =" , length)
#On each iteration we cut the last digit of the number using
# integer division by 10 (n //= 10). In the... | n = int(input())
length = 0
while n > 0:
n = n // 10
length = length + 1
print('number of digits in the given number n =', length) |
class ShapeConfig():
def __init__(
self,
shape=[74, 74, 125, 125],
verbose=False
):
self.shape = shape
self._number_of_substrip = len(self.shape)
self._number_of_pixels = 0
for pixel_number in self.shape:
self._number_of_pixels += pixel_numbe... | class Shapeconfig:
def __init__(self, shape=[74, 74, 125, 125], verbose=False):
self.shape = shape
self._number_of_substrip = len(self.shape)
self._number_of_pixels = 0
for pixel_number in self.shape:
self._number_of_pixels += pixel_number
self._offsets = []
... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minn = float("inf")
profit = 0
for price in prices:
if minn > price : minn = price
if price - minn > profit : profit = price - minn
return profit | class Solution:
def max_profit(self, prices: List[int]) -> int:
minn = float('inf')
profit = 0
for price in prices:
if minn > price:
minn = price
if price - minn > profit:
profit = price - minn
return profit |
coordinates_E0E1E1 = ((125, 117),
(125, 120), (126, 96), (126, 117), (126, 119), (126, 127), (127, 94), (127, 97), (127, 109), (127, 118), (127, 119), (127, 127), (128, 93), (128, 98), (128, 108), (128, 109), (128, 118), (128, 119), (129, 92), (129, 94), (129, 96), (129, 100), (129, 101), (129, 103), (129, 107), (129... | coordinates_e0_e1_e1 = ((125, 117), (125, 120), (126, 96), (126, 117), (126, 119), (126, 127), (127, 94), (127, 97), (127, 109), (127, 118), (127, 119), (127, 127), (128, 93), (128, 98), (128, 108), (128, 109), (128, 118), (128, 119), (129, 92), (129, 94), (129, 96), (129, 100), (129, 101), (129, 103), (129, 107), (129... |
class EMA:
def __init__(self):
self.EMA_12 = []
self.EMA_20 = []
self.EMA_26 = []
self.EMA_50 = []
self.EMA_80 = []
self.EMA_85 = []
self.EMA_90 = []
self.EMA_95 = []
self.EMA_100 = []
self.EMA_160 = []
@staticmethod
def EMA(da... | class Ema:
def __init__(self):
self.EMA_12 = []
self.EMA_20 = []
self.EMA_26 = []
self.EMA_50 = []
self.EMA_80 = []
self.EMA_85 = []
self.EMA_90 = []
self.EMA_95 = []
self.EMA_100 = []
self.EMA_160 = []
@staticmethod
def ema(d... |
def solution(x):
s = 0
for i in range(x):
if i%3 == 0 or i%5 == 0:
s += i
return s | def solution(x):
s = 0
for i in range(x):
if i % 3 == 0 or i % 5 == 0:
s += i
return s |
class Iris:
def __init__(self, features, label):
self.features = features
self.label = label
def sum(self):
return sum(self.features)
for *features, label in DATA:
iris = Iris(features, label)
result[iris.label] = iris.sum()
| class Iris:
def __init__(self, features, label):
self.features = features
self.label = label
def sum(self):
return sum(self.features)
for (*features, label) in DATA:
iris = iris(features, label)
result[iris.label] = iris.sum() |
# -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive licens... | """Hashing algorithms
Hash functions take arbitrary binary strings as input, and produce a random-like output
of fixed size that is dependent on the input; it should be practically infeasible
to derive the original input data given only the hash function's
output. In other words, the hash function is *one-way*.
It s... |
class CameraInterface:
def get_image(self):
raise NotImplementedError()
def get_depth(self):
raise NotImplementedError() | class Camerainterface:
def get_image(self):
raise not_implemented_error()
def get_depth(self):
raise not_implemented_error() |
class HTTPCache(ValueError):
pass
__all__ = ("HTTPCache",)
| class Httpcache(ValueError):
pass
__all__ = ('HTTPCache',) |
class AuthError(Exception):
pass
class BadExtentError(Exception):
pass
class InvalidEndpoint(Exception):
pass
class InvalidDatestring(Exception):
pass
class RequiredArgumentError(Exception):
pass
class Request429Error(Exception):
pass
class RequestsPerSecondLimitExceeded(Request429E... | class Autherror(Exception):
pass
class Badextenterror(Exception):
pass
class Invalidendpoint(Exception):
pass
class Invaliddatestring(Exception):
pass
class Requiredargumenterror(Exception):
pass
class Request429Error(Exception):
pass
class Requestspersecondlimitexceeded(Request429Error):
... |
class Warning(StandardError):
pass
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError... | class Warning(StandardError):
pass
class Error(StandardError):
pass
class Interfaceerror(Error):
pass
class Databaseerror(Error):
pass
class Dataerror(DatabaseError):
pass
class Operationalerror(DatabaseError):
pass
class Integrityerror(DatabaseError):
pass
class Internalerror(Databas... |
# This makes this folder a package and can be left empty if you like.
# the __all__ special variable indicates what modules to load then the * star
# is used for importing.
__all__ = ['aCoolModule']
| __all__ = ['aCoolModule'] |
main_colors = ['red', 'yellow', 'blue']
secondary_colors = {
'orange': ('red', 'yellow'),
'purple': ('red', 'blue'),
'green': ('yellow', 'blue')
}
base_strings = input().split()
made_colors_all = []
made_colors_final = []
while base_strings:
first_string = base_strings.pop(0)
second_string = base_s... | main_colors = ['red', 'yellow', 'blue']
secondary_colors = {'orange': ('red', 'yellow'), 'purple': ('red', 'blue'), 'green': ('yellow', 'blue')}
base_strings = input().split()
made_colors_all = []
made_colors_final = []
while base_strings:
first_string = base_strings.pop(0)
second_string = base_strings.pop() if... |
def inc(c, d):
return chr(ord(c) + d)
def dec(c, d):
return chr(ord(c) - d)
arg1 = ["+"] * 29
arg1[0x13] = '6'
arg1[0x10] = 'n'
arg1[0xd] = 'r'
arg1[0x14] = dec('%', -8)
arg1[0xf] = 'n'
arg1[10] = 'p'
arg1[0x10] = dec('u', 7)
arg1[3] = '{'
arg1[0x13] = '6'
arg1[0x15] = 'q'
arg1[2] = 'n'
arg1[0] = 's'
arg1[7]... | def inc(c, d):
return chr(ord(c) + d)
def dec(c, d):
return chr(ord(c) - d)
arg1 = ['+'] * 29
arg1[19] = '6'
arg1[16] = 'n'
arg1[13] = 'r'
arg1[20] = dec('%', -8)
arg1[15] = 'n'
arg1[10] = 'p'
arg1[16] = dec('u', 7)
arg1[3] = '{'
arg1[19] = '6'
arg1[21] = 'q'
arg1[2] = 'n'
arg1[0] = 's'
arg1[7] = 'l'
arg1[14] ... |
class SequentialProcessor(object):
def process(self, vertice, executor):
results = []
for vertex in vertice:
result = executor.execute(executor.param(vertex))
results.append((vertex, result))
return results
| class Sequentialprocessor(object):
def process(self, vertice, executor):
results = []
for vertex in vertice:
result = executor.execute(executor.param(vertex))
results.append((vertex, result))
return results |
#!/bin/env python
"""A file which contains only what is strictly necessary for completion of the is_even function"""
# Y combinator, used for recursion
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda a: y(y)(a)))
# Church arithmetic
succ = lambda n: lambda f: lambda x: f(n(f)(x))
pred = lambda n: lambda f: lambda x... | """A file which contains only what is strictly necessary for completion of the is_even function"""
y = lambda f: (lambda x: x(x))(lambda y: f(lambda a: y(y)(a)))
succ = lambda n: lambda f: lambda x: f(n(f)(x))
pred = lambda n: lambda f: lambda x: n(lambda g: lambda h: h(g(f)))(lambda _: x)(lambda u: u)
minus = lambda m... |
n = input().split()
K=int(n[0])
N=int(n[1])
M=int(n[2])
need= K*N
if need>M:
print(need-M)
else:
print('0')
| n = input().split()
k = int(n[0])
n = int(n[1])
m = int(n[2])
need = K * N
if need > M:
print(need - M)
else:
print('0') |
def aoc(data):
jolts = 0
ones = 0
threes = 1
for psu in sorted([int(i) for i in data.split()]):
if psu == jolts + 1:
ones += 1
if psu == jolts + 3:
threes += 1
jolts = psu
return ones * threes
| def aoc(data):
jolts = 0
ones = 0
threes = 1
for psu in sorted([int(i) for i in data.split()]):
if psu == jolts + 1:
ones += 1
if psu == jolts + 3:
threes += 1
jolts = psu
return ones * threes |
async def m001_initial(db):
await db.execute(
f"""
CREATE TABLE IF NOT EXISTS tipjar.TipJars (
id {db.serial_primary_key},
name TEXT NOT NULL,
wallet TEXT NOT NULL,
onchain TEXT,
webhook TEXT
);
"""
)
await db.exec... | async def m001_initial(db):
await db.execute(f'\n CREATE TABLE IF NOT EXISTS tipjar.TipJars (\n id {db.serial_primary_key},\n name TEXT NOT NULL,\n wallet TEXT NOT NULL,\n onchain TEXT,\n webhook TEXT\n );\n ')
await db.execute(f'\n ... |
# -*- coding: utf8 -*-
# Copyright 2017-2019 NLCI (http://www.nlci.in/fonts/)
# Apache License v2.0
class Charset:
common_name = 'NLCI: Tamil script'
native_name = 'Tamil script'
abbreviation = 'Taml'
key = 0x0B95
glyphs = [
0x0B82, # TAMIL SIGN ANUSVARA
0x0B83, # TAMIL SIGN VISA... | class Charset:
common_name = 'NLCI: Tamil script'
native_name = 'Tamil script'
abbreviation = 'Taml'
key = 2965
glyphs = [2946, 2947, 2949, 2950, 2951, 2952, 2953, 2954, 2958, 2959, 2960, 2962, 2963, 2964, 2965, 2969, 2970, 2972, 2974, 2975, 2979, 2980, 2984, 2985, 2986, 2990, 2991, 2992, 2993, 2994... |
def run_length_encoding(string: str) -> str:
counter = 0
current_character = None
output = []
for character in string:
if current_character == character:
counter += 1
else:
if current_character:
output.append(current_character + str(counter if c... | def run_length_encoding(string: str) -> str:
counter = 0
current_character = None
output = []
for character in string:
if current_character == character:
counter += 1
else:
if current_character:
output.append(current_character + str(counter if coun... |
###***********************************###
'''
Grade Notifier
File: refresh_result.py
Author: Ehud Adler
Core Maintainers: Ehud Adler, Akiva Sherman,
Yehuda Moskovits
Copyright: Copyright 2019, Ehud Adler
License: MIT
'''
###***********************************###
class RefreshResult():
def __init__(self, classes, g... | """
Grade Notifier
File: refresh_result.py
Author: Ehud Adler
Core Maintainers: Ehud Adler, Akiva Sherman,
Yehuda Moskovits
Copyright: Copyright 2019, Ehud Adler
License: MIT
"""
class Refreshresult:
def __init__(self, classes, gpa):
self.classes = classes
self.gpa = gpa |
'''
key -> value store
any types -> any type
'''
english = {
'apple': 'fruit blah blah',
'apetite': 'desire for something, usually food',
'pluto': 'a gray planet'
}
print(english['apple'])
#print(english['banana']) fails with KeyError
print(english.get('banana')) #handles KeyError and return Non... | """
key -> value store
any types -> any type
"""
english = {'apple': 'fruit blah blah', 'apetite': 'desire for something, usually food', 'pluto': 'a gray planet'}
print(english['apple'])
print(english.get('banana'))
print(english.get('banana', 'unknown word'))
english['banana'] = 'yellow fleshy fruit'
print(eng... |
def __is_integer(some_string):
try:
int(some_string)
return True
except:
return False
def compute(expression: str = None) -> int:
stack = []
for element in expression.split():
if __is_integer(element):
stack.append(int(element))
continue
... | def __is_integer(some_string):
try:
int(some_string)
return True
except:
return False
def compute(expression: str=None) -> int:
stack = []
for element in expression.split():
if __is_integer(element):
stack.append(int(element))
continue
sec... |
# encoding=utf-8
class Player(object):
'''A basic player with a name and a Bot.
bot may be a subclass of LightCycleBaseBot or a string with its Python
source code.
'''
def __init__(self, name, bot, **kwargs):
for attr, value in kwargs.items():
if not hasattr(self, attr):
... | class Player(object):
"""A basic player with a name and a Bot.
bot may be a subclass of LightCycleBaseBot or a string with its Python
source code.
"""
def __init__(self, name, bot, **kwargs):
for (attr, value) in kwargs.items():
if not hasattr(self, attr):
setatt... |
RATE_1MBIT = 0
RATE_250KBIT = 2
RATE_2MBIT = 1
def config():
pass
def off():
pass
def on():
pass
def receive():
pass
def receive_bytes():
pass
def receive_bytes_into():
pass
def receive_full():
pass
def reset():
pass
def send():
pass
def send_bytes():
pass
| rate_1_mbit = 0
rate_250_kbit = 2
rate_2_mbit = 1
def config():
pass
def off():
pass
def on():
pass
def receive():
pass
def receive_bytes():
pass
def receive_bytes_into():
pass
def receive_full():
pass
def reset():
pass
def send():
pass
def send_bytes():
pass |
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
txt = "The price is {:.2f} dollars"
print(txt.format(price))
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49
... | price = 49
txt = 'The price is {} dollars'
print(txt.format(price))
txt = 'The price is {:.2f} dollars'
print(txt.format(price))
quantity = 3
itemno = 567
price = 49
myorder = 'I want {} pieces of item number {} for {:.2f} dollars.'
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49
myo... |
# 8 kyu
def reverse_words(s):
return " ".join(reversed(s.split()))
| def reverse_words(s):
return ' '.join(reversed(s.split())) |
def tower_builder(n_floors):
tower = []
d = '*'
for i in range(1, 2 * n_floors + 1 , 2):
tower.append((d * i).center(2 * i - 1))
return tower
print(tower_builder(3))
| def tower_builder(n_floors):
tower = []
d = '*'
for i in range(1, 2 * n_floors + 1, 2):
tower.append((d * i).center(2 * i - 1))
return tower
print(tower_builder(3)) |
#
# PySNMP MIB module Netrake-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Netrake-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:16: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 2019, 0... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
numbers = [1,2,3,4,5]
numbers_again = [n for n in numbers]
even_numbers = [n for n in numbers if n%2 == 0]
odd_squares = [n**2 for n in numbers if n%2 == 1]
matrix = [[1,2,3], [4,5,6], [7,8,9]]
flattened_matrix = [n for row in x for n in row]
| numbers = [1, 2, 3, 4, 5]
numbers_again = [n for n in numbers]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_squares = [n ** 2 for n in numbers if n % 2 == 1]
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_matrix = [n for row in x for n in row] |
'''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
'''
class Solution(object):
def minPathSum(self, grid):
"""
:type gr... | """
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
"""
class Solution(object):
def min_path_sum(self, grid):
"""
:type grid: Li... |
# -*- coding: utf-8 -*-
class BaseProcessor(object):
def __init__(self, exporter, generator_info):
super(BaseProcessor, self).__init__()
self.exporter = exporter
self.generator_info = generator_info
def run(self):
pass
| class Baseprocessor(object):
def __init__(self, exporter, generator_info):
super(BaseProcessor, self).__init__()
self.exporter = exporter
self.generator_info = generator_info
def run(self):
pass |
n = int(input())
dic = {}
for i in range(n):
c = input()
if c == "Q":
n = input()
if n in dic.keys():
print(dic[n])
else:
print("NONE")
elif c == "A":
n, p = input().split(" ")
dic[n] = p
| n = int(input())
dic = {}
for i in range(n):
c = input()
if c == 'Q':
n = input()
if n in dic.keys():
print(dic[n])
else:
print('NONE')
elif c == 'A':
(n, p) = input().split(' ')
dic[n] = p |
class Solution:
def nextBeautifulNumber(self, n: int) -> int:
def isBalance(num: int) -> bool:
count = [0] * 10
while num:
if num % 10 == 0:
return False
count[num % 10] += 1
num //= 10
return all(c == i for i, c in enumerate(count) if c)
n += 1
while n... | class Solution:
def next_beautiful_number(self, n: int) -> int:
def is_balance(num: int) -> bool:
count = [0] * 10
while num:
if num % 10 == 0:
return False
count[num % 10] += 1
num //= 10
return all((c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim :set ft=py:
# blosc args
DEFAULT_TYPESIZE = 8
DEFAULT_CLEVEL = 7
DEFAULT_SHUFFLE = True
DEFAULT_CNAME = 'blosclz'
# bloscpack args
DEFAULT_OFFSETS = True
DEFAULT_CHECKSUM = 'adler32'
DEFAULT_MAX_APP_CHUNKS = lambda x: 10 * x
DEFAULT_CHUNK_SIZE = '1M'
# metadata ar... | default_typesize = 8
default_clevel = 7
default_shuffle = True
default_cname = 'blosclz'
default_offsets = True
default_checksum = 'adler32'
default_max_app_chunks = lambda x: 10 * x
default_chunk_size = '1M'
default_magic_format = b'JSON'
default_meta_checksum = 'adler32'
default_meta_codec = 'zlib'
default_meta_level... |
class Heroes:
ana = 1
bastion = 2
dva = 3
genji = 4
hanzo = 5
junkrat = 6
lucio = 7
mccree = 8
mei = 9
mercy = 10
pharah = 11
reaper = 12
reinhardt = 13
roadhog = 14
soldier76 = 15
symmetra = 16
torbjorn = 17
tracer = 18
widowmaker = 19
win... | class Heroes:
ana = 1
bastion = 2
dva = 3
genji = 4
hanzo = 5
junkrat = 6
lucio = 7
mccree = 8
mei = 9
mercy = 10
pharah = 11
reaper = 12
reinhardt = 13
roadhog = 14
soldier76 = 15
symmetra = 16
torbjorn = 17
tracer = 18
widowmaker = 19
win... |
#-------------------#
# Measures
#-------------------#
json_save = False
measures = {
"z":"[i * pF.dz for i in range(pN.n_z)]",
"phi":"getDryProfile('phiPart')",
"vx":"getVxPartProfile()",
"dirs":"getOrientationHist(5.0, 0.0)",
"mdirs":"getVectorMeanOrientation()",
"ori":"getOrientationProfiles(pM.z_ground,... | json_save = False
measures = {'z': '[i * pF.dz for i in range(pN.n_z)]', 'phi': "getDryProfile('phiPart')", 'vx': 'getVxPartProfile()', 'dirs': 'getOrientationHist(5.0, 0.0)', 'mdirs': 'getVectorMeanOrientation()', 'ori': 'getOrientationProfiles(pM.z_ground, pF.dz*20, int(pN.n_z/20))'} |
# encoding: utf-8
##################################################
# This script shows an example of a header section. This sections is a group of commented lines (lines starting with
# the "#" character) that describes general features of the script such as the type of licence (defined by the
# developer), authors,... | city_name = 'Calgary'
city_area = 200000
city_population = 3000
city_density = city_population / city_area
print('The most awesome city is ' + city_name)
print('Population Density is')
print(city_density)
print('Population Density ' + str(city_density) + ' inhabitants per hectare') |
def consecutive_pairalign(reversed_part, identical_part):
count = 0
lrev = len(reversed_part)
no_iter = min(len(reversed_part), len(identical_part))
i = 0
for i in range(0, no_iter):
if (reversed_part[lrev - i - 1] + identical_part[i]) in [
"au",
"ua",
"gc... | def consecutive_pairalign(reversed_part, identical_part):
count = 0
lrev = len(reversed_part)
no_iter = min(len(reversed_part), len(identical_part))
i = 0
for i in range(0, no_iter):
if reversed_part[lrev - i - 1] + identical_part[i] in ['au', 'ua', 'gc', 'cg', 'ug', 'gu']:
count... |
myconfig = {
"name": "Your Name",
"email": None,
"password": None,
"categories": ["physics:cond-mat"]
}
| myconfig = {'name': 'Your Name', 'email': None, 'password': None, 'categories': ['physics:cond-mat']} |
fin = open('sum.in', 'r')
fout = open('sum.out', 'w')
while True:
True
result = sum(map(int, fin.readline().strip().split()))
fout.write(str(result)+'\n')
| fin = open('sum.in', 'r')
fout = open('sum.out', 'w')
while True:
True
result = sum(map(int, fin.readline().strip().split()))
fout.write(str(result) + '\n') |
# -*- coding: utf-8 -*-
__author__ = 'Hugo Martiniano'
__email__ = 'hugomartiniano@gmail.com'
__version__ = '0.1.7'
__url__ = 'https://github.com/hmartiniano/faz'
| __author__ = 'Hugo Martiniano'
__email__ = 'hugomartiniano@gmail.com'
__version__ = '0.1.7'
__url__ = 'https://github.com/hmartiniano/faz' |
word = input()
length = len(word)
def firstLine():
for i in range(0, length):
if (i == 0):
print(".", end='')
if (i % 3 == 2):
print(".*..", end='')
else:
print(".#..", end='')
print()
def secondLine():
for i in range(0, length):
if (i... | word = input()
length = len(word)
def first_line():
for i in range(0, length):
if i == 0:
print('.', end='')
if i % 3 == 2:
print('.*..', end='')
else:
print('.#..', end='')
print()
def second_line():
for i in range(0, length):
if i == 0:... |
# Here will be implemented the runtime stats calculators
class statsCalculator:
# Average of file sizes that were opened, written or read. (Before write operation)
avgFileSizes_open = 0
open_counter = 0
avgFileSizes_read = 0
read_counter = 0
avgFileSizes_write = 0
write_counter = 0
def... | class Statscalculator:
avg_file_sizes_open = 0
open_counter = 0
avg_file_sizes_read = 0
read_counter = 0
avg_file_sizes_write = 0
write_counter = 0
def avg_file_sizes_update(self, filesMap, fileName, type):
if filesMap.get(fileName):
if type == 'open':
se... |
class Point(object):
__slots__ = ('x', 'y')
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __getitem__(self, index):
if isinstance(index, slice):
if index.start is None an... | class Point(object):
__slots__ = ('x', 'y')
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return point(self.x + other.x, self.y + other.y)
def __getitem__(self, index):
if isinstance(index, slice):
if index.start is None and ... |
def power(x, y):
if(y == 0):
return 1
if(y < 0):
n = (1/x) * power(x, (y+1)/2)
return n*n
if(y%2 == 0):
m = power(x, y/2)
return m*m
else:
return x * power(x, y-1)
def main():
print("To calculate x^y ...\n")
x = float(input("Please e... | def power(x, y):
if y == 0:
return 1
if y < 0:
n = 1 / x * power(x, (y + 1) / 2)
return n * n
if y % 2 == 0:
m = power(x, y / 2)
return m * m
else:
return x * power(x, y - 1)
def main():
print('To calculate x^y ...\n')
x = float(input('Please ente... |
"""
https://leetcode.com/problems/wiggle-subsequence/
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is tri... | """
https://leetcode.com/problems/wiggle-subsequence/
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is tri... |
# -*- coding: UTF8 -*-
"""
NAME
visualize
DESCRIPTION
Module that implements methods to plot ground_truth trajectories
and estimated for 6D poses.
METHODS
get_xy(pose)
Function that extracts (x,y) positions from
a list of 6D poses.
get_seq_star... | """
NAME
visualize
DESCRIPTION
Module that implements methods to plot ground_truth trajectories
and estimated for 6D poses.
METHODS
get_xy(pose)
Function that extracts (x,y) positions from
a list of 6D poses.
get_seq_start(pose)
Fun... |
print('Accumulated value of a scheduled savings account')
p = float(input('Type the value of the monthly application constant: '))
i = float(input('The tax: '))
n = int(input('How many months: '))
accumulated_value = p*((1 + i)**n - 1) / i
print(f'The accumulated value is $${accumulated_value}.')
| print('Accumulated value of a scheduled savings account')
p = float(input('Type the value of the monthly application constant: '))
i = float(input('The tax: '))
n = int(input('How many months: '))
accumulated_value = p * ((1 + i) ** n - 1) / i
print(f'The accumulated value is $${accumulated_value}.') |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'dracarysX'
class APIError(Exception):
"""
"""
def __init__(self, code, message):
self.code = code
self.message = message
class APIError404(APIError):
"""
"""
def __init__(self, message='Not Found'):
super... | __author__ = 'dracarysX'
class Apierror(Exception):
"""
"""
def __init__(self, code, message):
self.code = code
self.message = message
class Apierror404(APIError):
"""
"""
def __init__(self, message='Not Found'):
super(APIError404, self).__init__(code=404, message=m... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class SharedMemoryException(Exception):
"""
Exception raised when using shared memory.
"""
def __init__(self, msg: str) -> None:
super().__init__(msg)
| class Sharedmemoryexception(Exception):
"""
Exception raised when using shared memory.
"""
def __init__(self, msg: str) -> None:
super().__init__(msg) |
def ngram(s, num):
res = []
slen = len(s) - num + 1
for i in range(slen):
ss = s[i:i + num]
res.append(ss)
return res
def diff_ngram(sa, sb, num):
a = ngram(sa, num)
b = ngram(sb, num)
r = []
cnt = 0
for i in a:
for j in b:
if i == j:
cnt += 1
r.append(i)
return cn... | def ngram(s, num):
res = []
slen = len(s) - num + 1
for i in range(slen):
ss = s[i:i + num]
res.append(ss)
return res
def diff_ngram(sa, sb, num):
a = ngram(sa, num)
b = ngram(sb, num)
r = []
cnt = 0
for i in a:
for j in b:
if i == j:
... |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
"""Hash table.
"""
st = {}
ts = {}
for i in range(len(s)):
if s[i] not in st:
st[s[i]] = t[i]
elif st[s[i]] != t[i]:
return False
if t[i] not in... | class Solution:
def is_isomorphic(self, s: str, t: str) -> bool:
"""Hash table.
"""
st = {}
ts = {}
for i in range(len(s)):
if s[i] not in st:
st[s[i]] = t[i]
elif st[s[i]] != t[i]:
return False
if t[i] not ... |
def some_function():
for i in range(4):
yield i
for i in some_function():
print(i) | def some_function():
for i in range(4):
yield i
for i in some_function():
print(i) |
def spiralCopy(inputMatrix):
numRows = len(inputMatrix)
numCols = len(inputMatrix[0])
# keep track of where we are along each
# of the four sides of the matrix
topRow = 0
bottomRow = numRows - 1
leftCol = 0
rightCol = numCols - 1
result = []
# iterate throughout the entire matr... | def spiral_copy(inputMatrix):
num_rows = len(inputMatrix)
num_cols = len(inputMatrix[0])
top_row = 0
bottom_row = numRows - 1
left_col = 0
right_col = numCols - 1
result = []
while topRow <= bottomRow and leftCol <= rightCol:
for i in range(leftCol, rightCol + 1):
res... |
class Config(object):
JOOX_API_DOMAIN = "https://api-jooxtt.sanook.com/web-fcgi-bin"
JOOX_AUTH_PATH = "/web_wmauth"
JOOX_GETFAV_PATH = "/web_getfav"
JOOX_ADD_DIR_PATH = "/web_fav_add_dir"
JOOX_DEL_DIR_PATH = "/web_fav_del_dir"
JOOX_ADD_SONG_PATH = "/web_fav_add_song"
JOOX_DEL_SONG_PATH = "/... | class Config(object):
joox_api_domain = 'https://api-jooxtt.sanook.com/web-fcgi-bin'
joox_auth_path = '/web_wmauth'
joox_getfav_path = '/web_getfav'
joox_add_dir_path = '/web_fav_add_dir'
joox_del_dir_path = '/web_fav_del_dir'
joox_add_song_path = '/web_fav_add_song'
joox_del_song_path = '/w... |
n=int(input())
squareMatrix=[]
k=0; i=0
while k<n:
row=input()
squareMatrix.append([])
for j in range(0,len(row)):
squareMatrix[i].append(row[j])
k+=1; i+=1
symbolToFind=input()
rowFound=0; colFound=0; symbolFound=False
for k in range(0,len(squareMatrix)):
if symbolFound=... | n = int(input())
square_matrix = []
k = 0
i = 0
while k < n:
row = input()
squareMatrix.append([])
for j in range(0, len(row)):
squareMatrix[i].append(row[j])
k += 1
i += 1
symbol_to_find = input()
row_found = 0
col_found = 0
symbol_found = False
for k in range(0, len(squareMatrix)):
if ... |
# Given an array nums, write a function to move all 0's to the end of it
# while maintaining the relative order of the non-zero elements.
# EXAMPLE
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
'''
Time: O(N), worst case no 0s have to i... | class Solution:
def move_zeroes(self, nums: List[int]) -> None:
"""
Time: O(N), worst case no 0s have to iterate over the entire array
Space: O(1)
"""
'\n Do not return anything, modify nums in-place instead.\n '
n = 0
a = 0
'\n M... |
def czy_pal(tekst):
for x in range(len(tekst)):
if tekst[x] != tekst[len(tekst)-1-x]:
return False
return True
def nowy_pal(tekst):
odp = tekst
for x in range(len(tekst)):
odp += tekst[len(tekst)-1-x]
return odp
tekst = input()
results = czy_pal(tekst)
if result... | def czy_pal(tekst):
for x in range(len(tekst)):
if tekst[x] != tekst[len(tekst) - 1 - x]:
return False
return True
def nowy_pal(tekst):
odp = tekst
for x in range(len(tekst)):
odp += tekst[len(tekst) - 1 - x]
return odp
tekst = input()
results = czy_pal(tekst)
if results... |
class Ts2xlException(Exception):
'''
Used for expected errors, where the command-line tool
shouldn't show a full stack trace.
'''
pass
| class Ts2Xlexception(Exception):
"""
Used for expected errors, where the command-line tool
shouldn't show a full stack trace.
"""
pass |
#!/usr/bin/python
# Word and some similarity (float).
class WordSim:
"""Word and some similarity"""
# name of the dictionary article
word = ''
# size of synset kernel |IntS|, i.e. number of synonyms, which always make subsets more nearer
sim = 0.0;
#def f(self):
# ret... | class Wordsim:
"""Word and some similarity"""
word = ''
sim = 0.0 |
class DataGridViewColumn(DataGridViewBand, ICloneable, IDisposable, IComponent):
"""
Represents a column in a System.Windows.Forms.DataGridView control.
DataGridViewColumn()
DataGridViewColumn(cellTemplate: DataGridViewCell)
"""
def Clone(self):
"""
Clone(self: DataGridViewColum... | class Datagridviewcolumn(DataGridViewBand, ICloneable, IDisposable, IComponent):
"""
Represents a column in a System.Windows.Forms.DataGridView control.
DataGridViewColumn()
DataGridViewColumn(cellTemplate: DataGridViewCell)
"""
def clone(self):
"""
Clone(self: DataGridViewColumn) -> object
... |
class Example1:
def __init__(self):
self.field1 = 1
class Example2(Example1):
def __init__(self): # Some valuable comment here
Example1.__init__(self) | class Example1:
def __init__(self):
self.field1 = 1
class Example2(Example1):
def __init__(self):
Example1.__init__(self) |
A, B, C = map(int, input().split())
K = int(input())
for _ in range(K):
if A >= B:
B *= 2
elif B >= C:
C *= 2
if A < B < C:
print('Yes')
else:
print('No')
| (a, b, c) = map(int, input().split())
k = int(input())
for _ in range(K):
if A >= B:
b *= 2
elif B >= C:
c *= 2
if A < B < C:
print('Yes')
else:
print('No') |
"""This module defines custom exceptions
"""
class InvalidItemException(Exception):
"""Exception for when the pipeline tries to process an non-supported item."""
pass
| """This module defines custom exceptions
"""
class Invaliditemexception(Exception):
"""Exception for when the pipeline tries to process an non-supported item."""
pass |
class TestResult:
def __init__(self):
self.runCount = 0
self.errorCount = 0
def testStarted(self):
self.runCount = self.runCount + 1
def testFailed(self):
self.errorCount = self.errorCount + 1
def summary(self):
return "%d run, %d failed" % (self.runCount, self.er... | class Testresult:
def __init__(self):
self.runCount = 0
self.errorCount = 0
def test_started(self):
self.runCount = self.runCount + 1
def test_failed(self):
self.errorCount = self.errorCount + 1
def summary(self):
return '%d run, %d failed' % (self.runCount, s... |
"""
a set of very basic queries - simply ensure the counts of label
"""
EXPECTED_COUNTS = {
'Case': 35577,
'Sample': 76883,
'Project': 172,
'Aliquot': 849801,
'DrugResponse': 641610,
'G2PAssociation': 50099,
'Gene': 63677,
'GenomicFeature': 5941,
'Allele': 4023292,
'Phenotype'... | """
a set of very basic queries - simply ensure the counts of label
"""
expected_counts = {'Case': 35577, 'Sample': 76883, 'Project': 172, 'Aliquot': 849801, 'DrugResponse': 641610, 'G2PAssociation': 50099, 'Gene': 63677, 'GenomicFeature': 5941, 'Allele': 4023292, 'Phenotype': 3234, 'Exon': 737019, 'Protein': 94575, 'P... |
"""terrainbento **UniformPrecipitator**."""
class UniformPrecipitator(object):
"""Generate uniform precipitation.
UniformPrecipitator populates the at-node field "rainfall__flux" with a
value provided by the keyword argument ``rainfall_flux``.
To make discharge proprortional to drainage area, use th... | """terrainbento **UniformPrecipitator**."""
class Uniformprecipitator(object):
"""Generate uniform precipitation.
UniformPrecipitator populates the at-node field "rainfall__flux" with a
value provided by the keyword argument ``rainfall_flux``.
To make discharge proprortional to drainage area, use the... |
#Topic Class for handling msg from device
#Jon Durrant
#17-Sep-2021
#Topic handler superclass. Respond to a message on a particular topic channel
class Topic:
# handle a topic message
# @param topicName - string name of the topic
# @param data - string data
# @param twin - twin interface... | class Topic:
def handle(self, topicName: str, data: object, twin):
return |
# capitlize certain letters in plain text
# how to decide which letters to capitalize ?
# => Idea1: bool array with same length as plain_text
# -> set the required letters (positions) to True
# specify letters -> use range (start, end) position
class FormattedText:
def __init__(self, plain_text):
... | class Formattedtext:
def __init__(self, plain_text):
self.plain_text = plain_text
self.caps = [False] * len(plain_text)
def capitalize(self, start, end):
for i in range(start, end):
self.caps[i] = True
def __str__(self):
result = []
for i in range(len(s... |
class Solution:
"""
@param S: a string
@return: return a list of strings
"""
def letterCasePermutation(self, S):
return self.dfs(S, 0, {})
def dfs(self, S, idx, records):
if idx == len(S):
return [""]
if idx in records:
return records[idx]
... | class Solution:
"""
@param S: a string
@return: return a list of strings
"""
def letter_case_permutation(self, S):
return self.dfs(S, 0, {})
def dfs(self, S, idx, records):
if idx == len(S):
return ['']
if idx in records:
return records[idx]
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
_multi_phase = False
def enable_multi_phase():
global _multi_phase
_multi_phase = True
def multi_phase_enabled():
return _multi_phase
| _multi_phase = False
def enable_multi_phase():
global _multi_phase
_multi_phase = True
def multi_phase_enabled():
return _multi_phase |
def numbers_divisible_by_5_and_7_between_values(start_value, end_value):
result = []
for e in range(start_value, end_value + 1, 5):
if e % 7 == 0:
result.append(e)
return result
def numbers_divisible_by_5_and_13_between_values(start_value, end_value):
result = []
for e in range... | def numbers_divisible_by_5_and_7_between_values(start_value, end_value):
result = []
for e in range(start_value, end_value + 1, 5):
if e % 7 == 0:
result.append(e)
return result
def numbers_divisible_by_5_and_13_between_values(start_value, end_value):
result = []
for e in range(... |
class Constants:
def __init__(self):
self.version = "0.1a"
self.paste_url = "https://pastebin.com/api/api_post.php"
self.user_url = "https://pastebin.com/api/api_login.php"
self.raw_paste_url = "https://pastebin.com/api/api_raw.php"
self.headers = {
"X-Li... | class Constants:
def __init__(self):
self.version = '0.1a'
self.paste_url = 'https://pastebin.com/api/api_post.php'
self.user_url = 'https://pastebin.com/api/api_login.php'
self.raw_paste_url = 'https://pastebin.com/api/api_raw.php'
self.headers = {'X-Library': 'PasteBunny %... |
#!/usr/bin/python
# -*- coding: iso8859-1 -*-
# This should be not uploaded to repo, but since we're using test credentials is ok
# Should use env variables, local_settings not uploaded to repo or pass protect this
BASE_URL = 'http://22566bf6.ngrok.io/' # This might change with ngrok everytime...need to set it each tim... | base_url = 'http://22566bf6.ngrok.io/'
secretkeyprod = ''
secretkeytest = '0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF'
pbx_site = '1999888'
pbx_identifiant = '107904482'
pbx_rang = '32' |
"""A macro that wraps a script to generate an object that maps routes to their entry data"""
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary", "npm_package_bin")
def generate_route_manifest(name, routes):
"""Generates a json file that is a representation of all routes.
Args:
name: name o... | """A macro that wraps a script to generate an object that maps routes to their entry data"""
load('@build_bazel_rules_nodejs//:index.bzl', 'nodejs_binary', 'npm_package_bin')
def generate_route_manifest(name, routes):
"""Generates a json file that is a representation of all routes.
Args:
name: name of... |
# avax-python : Python tools for the exploration of the Avalanche AVAX network.
#
# Find tutorials and use cases at https://crypto.bi
"""
Copyright (C) 2021 - crypto.bi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), t... | """
Copyright (C) 2021 - crypto.bi
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s... |
class Superman:
def __init__(self):
self.superpowers = ['flight']
def print_superpowers(self):
print(f"Superpowers {self.superpowers}")
sm = Superman()
sm.print_superpowers()
class Megaman(Superman):
def __init__(self, megaman_powers=[]):
super().__init__()
self.superpowe... | class Superman:
def __init__(self):
self.superpowers = ['flight']
def print_superpowers(self):
print(f'Superpowers {self.superpowers}')
sm = superman()
sm.print_superpowers()
class Megaman(Superman):
def __init__(self, megaman_powers=[]):
super().__init__()
self.superpowe... |
# List Comprehension is sort of like Map + Filter
numbers_list = range(10)
# Basic list comprehension (map)
doubled = [x * 2 for x in numbers_list]
print(doubled)
# Basic list comprehension (filter)
evens = [x for x in numbers_list if x % 2 == 0]
print(evens)
# list comprehension (map + filter)
doubled_evens = [x *... | numbers_list = range(10)
doubled = [x * 2 for x in numbers_list]
print(doubled)
evens = [x for x in numbers_list if x % 2 == 0]
print(evens)
doubled_evens = [x * 2 for x in numbers_list if x % 2 == 0]
print(doubled_evens)
processed_data = [x * 2 if x % 2 == 0 else x * 10 for x in numbers_list]
print(processed_data) |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# Version 1: Inorder traverse, Time: O(n)
class Solution:
"""
@param root: the given BST
@param p: the given node
@return: the in-order predecessor of the give... | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the given BST
@param p: the given node
@return: the in-order predecessor of the given node in the BST
"""
def inorder_... |
#looping in Tuples
#tuple with one element
#tuple unpacking
#list inside tuple
#some function that you can use with tuple
Mixed = (1,2,3,4.0)
#for loop and tuple
for i in Mixed:
print(i)
#you can use while loop too
#tuple with one element
num1 = (1) #that is the class of integer
num2 = (1,) #that is the class of ... | mixed = (1, 2, 3, 4.0)
for i in Mixed:
print(i)
num1 = 1
num2 = (1,)
words = ('word1',)
print(type(num1))
print(type(num2))
print(type(Mixed))
print(type(words))
furit = ('Apple', 'Grapes', 'Mango')
print(type(furit))
furits = ('Apple', 'Mango', 'Peach', 'Orange')
(furit1, furit2, furit3, furit4) = furits
print(fur... |
class classonlymethod(classmethod):
'''
Descriptor for making class only methods.
A `classonly` method is a class method, which can be called only from the
class itself and not from instances. If called from an instance will
raise ``AttributeError``.
'''
def __get__(self, instance, owner):... | class Classonlymethod(classmethod):
"""
Descriptor for making class only methods.
A `classonly` method is a class method, which can be called only from the
class itself and not from instances. If called from an instance will
raise ``AttributeError``.
"""
def __get__(self, instance, owner):... |
ACTIVATED_MSG = (200, "Successfully_activated")
DEACTIVATED_MSG = (200, "Successfully_deactivated")
DELETE_IMG = (204, "image_deleted")
SENT_SMS_MSG = (403, 'Message_Didnt_send')
NOT_SENT_SMS_MSG = (200, 'Message_sent')
NOT_VALID_CODE = (422, 'Code_is_not_valid')
STILL_HAS_VALID_CODE = (403, 'Phone_already_has_valid_co... | activated_msg = (200, 'Successfully_activated')
deactivated_msg = (200, 'Successfully_deactivated')
delete_img = (204, 'image_deleted')
sent_sms_msg = (403, 'Message_Didnt_send')
not_sent_sms_msg = (200, 'Message_sent')
not_valid_code = (422, 'Code_is_not_valid')
still_has_valid_code = (403, 'Phone_already_has_valid_co... |
"""Classes to organize the ouput of GLSL shader parsing"""
class Identifier:
def __init__(self, name, index, swizzle):
self.name = name
self.index = None
self.swizzle = None
def __repr__(self):
r = ["Ident(name=", self.name]
if self.index != None:
r.append(", index={}".format(self.index))
if self.swi... | """Classes to organize the ouput of GLSL shader parsing"""
class Identifier:
def __init__(self, name, index, swizzle):
self.name = name
self.index = None
self.swizzle = None
def __repr__(self):
r = ['Ident(name=', self.name]
if self.index != None:
r.append(... |
inutil = input()
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
temp = True
temp2 = True
for index,i in enumerate(b):
if i not in a:
temp = False
for n in b[0:index]:
for m in b[0:index]:
if m+n == i:
temp = True
if not temp:
print(i)
temp2 = False
break
if temp2:
p... | inutil = input()
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
temp = True
temp2 = True
for (index, i) in enumerate(b):
if i not in a:
temp = False
for n in b[0:index]:
for m in b[0:index]:
if m + n == i:
temp = True
i... |
class RenderMethod:
def __init__(self, image):
self.image = image
def to_string(self):
raise NotImplementedError('Renderer::to_string() should be implemented!')
| class Rendermethod:
def __init__(self, image):
self.image = image
def to_string(self):
raise not_implemented_error('Renderer::to_string() should be implemented!') |
"""
Given an array of distinct integers,
find length of the longest subarray which contains numbers that can be arranged in a continuous sequence.
Examples:
Input: arr[] = {10, 12, 11};
Output: Length of the longest contiguous subarray is 3
Input: arr[] = {14, 12, 11, 20};
Output: Length of the longest contiguou... | """
Given an array of distinct integers,
find length of the longest subarray which contains numbers that can be arranged in a continuous sequence.
Examples:
Input: arr[] = {10, 12, 11};
Output: Length of the longest contiguous subarray is 3
Input: arr[] = {14, 12, 11, 20};
Output: Length of the longest contiguou... |
#Imprima o valor da soma dos quadrados de 3 numeros inteiras
a = int(input('Digite o valor de a: '))
b = int(input('Digite o valor de b: '))
c = int(input('Digite o valor de c: '))
d = (a**2) + (b**2) + (c**2)
print(f'Resultado: {d}') | a = int(input('Digite o valor de a: '))
b = int(input('Digite o valor de b: '))
c = int(input('Digite o valor de c: '))
d = a ** 2 + b ** 2 + c ** 2
print(f'Resultado: {d}') |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( S , n ) :
found = False
S.sort ( )
for i in range ( n - 1 , - 1 , - 1 ) :
for j in range ( 0 , ... | def f_gold(S, n):
found = False
S.sort()
for i in range(n - 1, -1, -1):
for j in range(0, n):
if i == j:
continue
for k in range(j + 1, n):
if i == k:
continue
for l in range(k + 1, n):
if... |
"""Module initialization."""
__version__ = "0.29.0"
__name__ = "gt4sd"
| """Module initialization."""
__version__ = '0.29.0'
__name__ = 'gt4sd' |
# -*- coding: utf-8 -*-
class NumMatrix(object):
''' https://leetcode.com/problems/range-sum-query-2d-immutable/
'''
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
self.matrix_sum = []
if not matrix:
... | class Nummatrix(object):
""" https://leetcode.com/problems/range-sum-query-2d-immutable/
"""
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
self.matrix_sum = []
if not matrix:
return
... |
# Super Spooky Damage Skin
success = sm.addDamageSkin(2433183)
if success:
sm.chat("The Super Spooky Damage Skin has been added to your account's damage skin collection.")
| success = sm.addDamageSkin(2433183)
if success:
sm.chat("The Super Spooky Damage Skin has been added to your account's damage skin collection.") |
# 2 - Dimmensional array
# Is implemented as array of array or list of list in python
# initialize an 2D array
array_2D = [[1, 2, 3, 4],
["a", "b", "c", "d"]]
# or
array_2d = [[5,6,7,8],
[3,5,2,9]]
# print the second item in the first row
print(array_2d[0][1])
print(array_2D[0][1])
# print ... | array_2_d = [[1, 2, 3, 4], ['a', 'b', 'c', 'd']]
array_2d = [[5, 6, 7, 8], [3, 5, 2, 9]]
print(array_2d[0][1])
print(array_2D[0][1])
print(array_2D[1][2])
print(array_2d[1][2])
for row in array_2D:
for item in row:
print(item)
for i in range(len(array_2d)):
for j in range(len(array_2d[i])):
prin... |
# MIN HEIGHT BST
# O(NlogN) time and O(N) space
def minHeightBst(array):
return minHeightHelper(array, None, 0, len(array) - 1)
def minHeightHelper(array, nodeBST, start, end):
if start > end:
return
mid = (start + end) // 2
if not nodeBST:
nodeBST = BST(array[mid])
else:
nodeBST.insert(array[mid])
m... | def min_height_bst(array):
return min_height_helper(array, None, 0, len(array) - 1)
def min_height_helper(array, nodeBST, start, end):
if start > end:
return
mid = (start + end) // 2
if not nodeBST:
node_bst = bst(array[mid])
else:
nodeBST.insert(array[mid])
min_height_h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.