content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Author: Eda AYDIN
"""
T = int(input())
answer = []
for i in range(T):
size = int(input())
blocks = list(map(int, input().split()))
for j in range(size - 1):
if blocks[0] >= blocks[len(blocks) - 1]:
a = blocks[0]
blocks.pop(0)
elif blocks[0] < blo... | """
Author: Eda AYDIN
"""
t = int(input())
answer = []
for i in range(T):
size = int(input())
blocks = list(map(int, input().split()))
for j in range(size - 1):
if blocks[0] >= blocks[len(blocks) - 1]:
a = blocks[0]
blocks.pop(0)
elif blocks[0] < blocks[len(blocks) - ... |
# THIS FILE IS AUTO-GENERATED. PLEASE DO NOT MODIFY# version file for ldap3
# generated on 2018-08-01 17:55:24.174707
# on system uname_result(system='Windows', node='ELITE10GC', release='10', version='10.0.17134', machine='AMD64', processor='Intel64 Family 6 Model 58 Stepping 9, GenuineIntel')
# with Python 3.7.0 -... | __version__ = '2.5.1'
__author__ = 'Giovanni Cannata'
__email__ = 'cannatag@gmail.com'
__url__ = 'https://github.com/cannatag/ldap3'
__description__ = 'A strictly RFC 4510 conforming LDAP V3 pure Python client library'
__status__ = '5 - Production/Stable'
__license__ = 'LGPL v3' |
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
print(min(even))
print(max(even))
print(min(odd))
print(max(odd))
print()
print(len(even))
print(len(odd))
print()
# to count how many times s is repeated in the word
print("mississippi".count("s")) #4
print("mississippi".count("issi")) #1
even.extend(odd)
print(even)
... | even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
print(min(even))
print(max(even))
print(min(odd))
print(max(odd))
print()
print(len(even))
print(len(odd))
print()
print('mississippi'.count('s'))
print('mississippi'.count('issi'))
even.extend(odd)
print(even)
another_even = even
print(another_even)
even.sort()
print(even)
eve... |
class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
val = 0
res = [None] * len(A)
for i, v in enumerate(A):
val = ((val << 1) + v) % 5
res[i] = (val == 0)
return res
| class Solution:
def prefixes_div_by5(self, A: List[int]) -> List[bool]:
val = 0
res = [None] * len(A)
for (i, v) in enumerate(A):
val = ((val << 1) + v) % 5
res[i] = val == 0
return res |
t=int(input())
for i in range(t):
s=input()
if s[:int(len(s)/2)]==s[int(len(s)/2):]:
print("YES")
else:
print("NO")
| t = int(input())
for i in range(t):
s = input()
if s[:int(len(s) / 2)] == s[int(len(s) / 2):]:
print('YES')
else:
print('NO') |
__all__ = [
'feature_audio_opus', \
'feature_audio_opus_conf'
]
| __all__ = ['feature_audio_opus', 'feature_audio_opus_conf'] |
class ExecutionStep(object):
def run(self, db):
raise NotImplementedError('Method run(self, db) is not implemented.')
def explain(self):
raise NotImplementedError('Method explain(self) is not implemented.') | class Executionstep(object):
def run(self, db):
raise not_implemented_error('Method run(self, db) is not implemented.')
def explain(self):
raise not_implemented_error('Method explain(self) is not implemented.') |
class A(object):
def __init__(self):
print("init")
def __call__(self):
print("call ")
a = A() #imprime init
A() #imprime call
#https://pt.stackoverflow.com/q/109813/101
| class A(object):
def __init__(self):
print('init')
def __call__(self):
print('call ')
a = a()
a() |
""" stub test, remove this when there's actual testing """
def test_nothing():
""" do nothing """
| """ stub test, remove this when there's actual testing """
def test_nothing():
""" do nothing """ |
def check_for_subfolders(folder_id, service):
new_sub_patterns = {}
folders = service.files().list(q="mimeType='application/vnd.google-apps.folder' and parents in '"+folder_id+"' and trashed = false",fields="nextPageToken, files(id, name)",pageSize=400).execute()
all_folders = folders.get('files', [])
a... | def check_for_subfolders(folder_id, service):
new_sub_patterns = {}
folders = service.files().list(q="mimeType='application/vnd.google-apps.folder' and parents in '" + folder_id + "' and trashed = false", fields='nextPageToken, files(id, name)', pageSize=400).execute()
all_folders = folders.get('files', [])... |
'''
Double Ended Queue or deque is the extended version of Queue
because in deque you can add and remove form both first and last position
of the Queue.
'''
def Deque():
def __init__(self):
self._deque = []
def add_first(self,e):
'Add the item in first position.'
self._deque.insert(0,e... | """
Double Ended Queue or deque is the extended version of Queue
because in deque you can add and remove form both first and last position
of the Queue.
"""
def deque():
def __init__(self):
self._deque = []
def add_first(self, e):
"""Add the item in first position."""
self._deque.inse... |
class Error :
def __init__(self,name,details,position):
self.name = name
self.details = details
self.position = position
def __str__(self):
return f'Error : {self.name} -> {self.details} | line :{self.position.line} col : {self.position.col}'
class IllegalCharError(Erro... | class Error:
def __init__(self, name, details, position):
self.name = name
self.details = details
self.position = position
def __str__(self):
return f'Error : {self.name} -> {self.details} | line :{self.position.line} col : {self.position.col}'
class Illegalcharerror(Error):
... |
#!/usr/bin/env python
# Copyright 2016 Zara Zaimeche
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | white = (255, 255, 255)
cyan = (0, 255, 255)
magenta = (255, 0, 255)
black = (0, 0, 0)
orange = (255, 175, 0)
brightred = (255, 0, 0)
red = (155, 0, 0)
palegreen = (150, 255, 150)
brightgreen = (0, 255, 0)
green = (0, 155, 0)
brightblue = (0, 0, 255)
blue = (0, 0, 155)
paleyellow = (255, 255, 150)
brightyellow = (255, ... |
"""Constants and membership tests for ASCII characters"""
NUL = 0
SOH = 1
STX = 2
ETX = 3
EOT = 4
ENQ = 5
ACK = 6
BEL = 7
BS = 8
TAB = 9
HT = 9
LF = 10
NL = 10
VT = 11
FF = 12
CR = 13
SO = 14
SI = 15
DLE = 16
DC1 = 17
DC2 = 18
DC3 = 19
DC4 = 20
NAK = 21
SYN = 22
ETB = 23
CAN = 24
EM = 25
SUB = 26
ESC = 27
FS = 28
GS = ... | """Constants and membership tests for ASCII characters"""
nul = 0
soh = 1
stx = 2
etx = 3
eot = 4
enq = 5
ack = 6
bel = 7
bs = 8
tab = 9
ht = 9
lf = 10
nl = 10
vt = 11
ff = 12
cr = 13
so = 14
si = 15
dle = 16
dc1 = 17
dc2 = 18
dc3 = 19
dc4 = 20
nak = 21
syn = 22
etb = 23
can = 24
em = 25
sub = 26
esc = 27
fs = 28
gs = ... |
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Drive... | graph = {'5': ['3', '7'], '3': ['2', '4'], '7': ['8'], '2': [], '4': ['8'], '8': []}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print('Depth-First Search:-')
df... |
"""
Constants for the Shopcart Service
"""
NOT_FOUND = "Not Found"
| """
Constants for the Shopcart Service
"""
not_found = 'Not Found' |
#!/usr/bin/env python3
def part1(filename):
with open(filename) as f:
line = f.readline()
floor = 0
for c in line:
if c == '(':
floor += 1
elif c == ')':
floor -= 1
print(floor)
def part2(filename):
with open(filename) as f:
line = f.read... | def part1(filename):
with open(filename) as f:
line = f.readline()
floor = 0
for c in line:
if c == '(':
floor += 1
elif c == ')':
floor -= 1
print(floor)
def part2(filename):
with open(filename) as f:
line = f.readline()
floor = 0
i =... |
alist = ['bob', 'alice', 'tom', 'jerry']
# for i in range(len(alist)):
# print(i, alist[i])
print(list(enumerate(alist)))
for data in enumerate(alist):
print(data)
for i, name in enumerate(alist):
print(i, name)
| alist = ['bob', 'alice', 'tom', 'jerry']
print(list(enumerate(alist)))
for data in enumerate(alist):
print(data)
for (i, name) in enumerate(alist):
print(i, name) |
test = { 'name': 'q2',
'points': 6,
'suites': [ { 'cases': [ {'code': ">>> model.get_layer(index=0).output_shape[1] \n"
'300',
'hidden': False,
'locked': False},
{'code': ">>> model.get_layer(inde... | test = {'name': 'q2', 'points': 6, 'suites': [{'cases': [{'code': '>>> model.get_layer(index=0).output_shape[1] \n300', 'hidden': False, 'locked': False}, {'code': '>>> model.get_layer(index=1).output_shape[1] \n200', 'hidden': False, 'locked': False}, {'code': '>>> model.get_layer(index=2).output_shape[1] \n100', 'hid... |
def linear_search_with_sentinel(arr, key):
i = 0
arr.append(key)
while arr[i] != key:
i += 1
if i == len(arr) - 1:
return -1
return i
| def linear_search_with_sentinel(arr, key):
i = 0
arr.append(key)
while arr[i] != key:
i += 1
if i == len(arr) - 1:
return -1
return i |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014-2016 bromix (plugin.video.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
class RegisterProviderPath(object):
def __init__(self, re_path):
self._... | """
Copyright (C) 2014-2016 bromix (plugin.video.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
class Registerproviderpath(object):
def __init__(self, re_path):
self._kodion_re_path = re_path... |
# No.1/2019-06-10/68 ms/13.3 MB
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
l=['()']
if n==0: return []
for i in range(1,n):
newl=[]
for string in l:
for index in range(len(string)//2+1):
temp=string[:index]... | class Solution:
def generate_parenthesis(self, n: int) -> List[str]:
l = ['()']
if n == 0:
return []
for i in range(1, n):
newl = []
for string in l:
for index in range(len(string) // 2 + 1):
temp = string[:index] + '()... |
#function start
def sumtriangle(n):
if n == 1:
return 1
else:
return n+(sumtriangle(n-1)) #recursive function
#function end
n = int(input("Enter number :"))
while (n!= -1): #loop start
print(sumtriangle(n))
n = int(input("Enter number :"))
print("Finished")
| def sumtriangle(n):
if n == 1:
return 1
else:
return n + sumtriangle(n - 1)
n = int(input('Enter number :'))
while n != -1:
print(sumtriangle(n))
n = int(input('Enter number :'))
print('Finished') |
def generator(num):
if num < 0:
yield 'negativo'
else:
yield 'positivo' | def generator(num):
if num < 0:
yield 'negativo'
else:
yield 'positivo' |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"color2num": "00_utils.ipynb",
"colorize": "00_utils.ipynb",
"calc_logstd_anneal": "00_utils.ipynb",
"save_frames_as_gif": "00_utils.ipynb",
"conv2d_output_size": "00_utils... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'color2num': '00_utils.ipynb', 'colorize': '00_utils.ipynb', 'calc_logstd_anneal': '00_utils.ipynb', 'save_frames_as_gif': '00_utils.ipynb', 'conv2d_output_size': '00_utils.ipynb', 'num2tuple': '00_utils.ipynb', 'conv2d_output_shape': '00_utils.ipyn... |
def sumofdigits(number):
sum = 0
modulus = 0
while number!=0 :
modulus = number%10
sum+=modulus
number/=10
return sum
print(sumofdigits(123)) | def sumofdigits(number):
sum = 0
modulus = 0
while number != 0:
modulus = number % 10
sum += modulus
number /= 10
return sum
print(sumofdigits(123)) |
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
ans = []
for i in range(1, numRows+1):
level = [1] * i
if ans:
for j in range(1, i-1):
level[j] = ans[-1][j-1] + ans[-1][j]
... | class Solution:
def generate(self, numRows: int) -> List[List[int]]:
ans = []
for i in range(1, numRows + 1):
level = [1] * i
if ans:
for j in range(1, i - 1):
level[j] = ans[-1][j - 1] + ans[-1][j]
ans.append(level)
re... |
def module_fuel(mass, full_mass=True):
'''Calculate the amount of fuel for each part.
With full mass also calculate the amount of fuel for the fuel.
'''
fuel_mass = (mass // 3) - 2
total = 0
if fuel_mass <= 0:
return total
elif full_mass:
total = fuel_mass + module_fuel(fuel_... | def module_fuel(mass, full_mass=True):
"""Calculate the amount of fuel for each part.
With full mass also calculate the amount of fuel for the fuel.
"""
fuel_mass = mass // 3 - 2
total = 0
if fuel_mass <= 0:
return total
elif full_mass:
total = fuel_mass + module_fuel(fuel_ma... |
"""
@Author : dilless
@Time : 2018/6/23 0:59
@File : __init__.py.py
""" | """
@Author : dilless
@Time : 2018/6/23 0:59
@File : __init__.py.py
""" |
def recursive_power(x, y):
if y == 0:
return 1
if y >= 1:
return x * recursive_power(x, y - 1)
print(recursive_power(2, 10))
print(recursive_power(10, 100))
| def recursive_power(x, y):
if y == 0:
return 1
if y >= 1:
return x * recursive_power(x, y - 1)
print(recursive_power(2, 10))
print(recursive_power(10, 100)) |
primary_duties=[
'agree',
'agrees',
'duty',
'you will',
'must',
'has to',
'is required',
'requires',
'warrant',
'warrants',
'you shall',
'obligated',
'is liable',
'is responsible for',
'responsibility',
'obligation',
'obligations',
'may not',
'... | primary_duties = ['agree', 'agrees', 'duty', 'you will', 'must', 'has to', 'is required', 'requires', 'warrant', 'warrants', 'you shall', 'obligated', 'is liable', 'is responsible for', 'responsibility', 'obligation', 'obligations', 'may not', 'must not', 'not permitted', 'shall not', 'shall NOT', 'will not', 'not elig... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains modules and packages for identifying sources in
an astronomical image and estimating their morphological parameters
(e.g. centroid and shape parameters).
"""
| """
This subpackage contains modules and packages for identifying sources in
an astronomical image and estimating their morphological parameters
(e.g. centroid and shape parameters).
""" |
# Databricks notebook source
# MAGIC %run ./Student-Environment
# COMMAND ----------
# MAGIC %run ./Utilities-Datasets
# COMMAND ----------
def path_exists(path):
try:
return len(dbutils.fs.ls(path)) >= 0
except Exception:
return False
def install_datasets(reinstall=False):
working_dir ... | def path_exists(path):
try:
return len(dbutils.fs.ls(path)) >= 0
except Exception:
return False
def install_datasets(reinstall=False):
working_dir = working_dir_root
course_name = 'apache-spark-programming-with-databricks'
version = 'v02'
min_time = '2 minute'
max_time = '5 ... |
class DungeonTile:
def __init__(self, canvas_tile, is_obstacle):
self.canvas_tile = canvas_tile
self.is_obstacle = is_obstacle
| class Dungeontile:
def __init__(self, canvas_tile, is_obstacle):
self.canvas_tile = canvas_tile
self.is_obstacle = is_obstacle |
#!/usr/bin/env python3
"""Write a function which takes a float n as
argument and returns the floor of the float"""
def floor(n: float) -> int:
"""return int part of n
Args:
n (float): arg
Returns:
int: value int of np
"""
return int(n)
| """Write a function which takes a float n as
argument and returns the floor of the float"""
def floor(n: float) -> int:
"""return int part of n
Args:
n (float): arg
Returns:
int: value int of np
"""
return int(n) |
########
# Copyright (c) 2018 Cloudify Platform Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | class Deploymentmodificationstate(object):
started = 'started'
finished = 'finished'
rolledback = 'rolledback'
states = [STARTED, FINISHED, ROLLEDBACK]
end_states = [FINISHED, ROLLEDBACK]
class Snapshotstate(object):
created = 'created'
failed = 'failed'
creating = 'creating'
upload... |
class loss(object):
def __init__(self):
self.last_input = None
self.grads = {}
self.grads_cuda = {}
def loss(self, x, labels):
raise NotImplementedError
def grad(self, x, labels):
raise NotImplementedError
def loss_cuda(self, x, labels):
raise NotImplem... | class Loss(object):
def __init__(self):
self.last_input = None
self.grads = {}
self.grads_cuda = {}
def loss(self, x, labels):
raise NotImplementedError
def grad(self, x, labels):
raise NotImplementedError
def loss_cuda(self, x, labels):
raise NotImple... |
def example_function(arg1: int, arg2: int =1) -> bool:
"""
This is an example of a docstring that conforms to the Google style guide.
The indentation uses four spaces (no tabs). Note that each section starts
with a header such as `Arguments` or `Returns` and its contents is indented.
Arguments:
... | def example_function(arg1: int, arg2: int=1) -> bool:
"""
This is an example of a docstring that conforms to the Google style guide.
The indentation uses four spaces (no tabs). Note that each section starts
with a header such as `Arguments` or `Returns` and its contents is indented.
Arguments:
... |
'''
Visualizing USA Medal Counts by Edition: Line Plot
Your job in this exercise is to visualize the medal counts by 'Edition' for the USA. The DataFrame has been pre-loaded for you as medals.
INSTRUCTIONS
100XP
Create a DataFrame usa with data only for the USA.
Group usa such that ['Edition', 'Medal'] is the index. ... | """
Visualizing USA Medal Counts by Edition: Line Plot
Your job in this exercise is to visualize the medal counts by 'Edition' for the USA. The DataFrame has been pre-loaded for you as medals.
INSTRUCTIONS
100XP
Create a DataFrame usa with data only for the USA.
Group usa such that ['Edition', 'Medal'] is the index. ... |
class ArrayList:
DEFAULT_CAPACITY = 64
def __init__(self, physicalSize: int = 0):
self.data = None
self.logicalSize = 0
self.physicalSize = self.DEFAULT_CAPACITY
if physicalSize > 1:
self.physicalSize = physicalSize
self.data = [0] * self.physicalSize
d... | class Arraylist:
default_capacity = 64
def __init__(self, physicalSize: int=0):
self.data = None
self.logicalSize = 0
self.physicalSize = self.DEFAULT_CAPACITY
if physicalSize > 1:
self.physicalSize = physicalSize
self.data = [0] * self.physicalSize
def ... |
#!/usr/bin/env python3
class Style:
"""Shortcuts to terminal styling escape sequences"""
BOLD = "\033[1m"
END = "\033[0m"
FG_Black = "\033[30m"
FG_Red = "\033[31m"
FG_Green = "\033[32m"
FG_Yellow = "\033[33m"
FG_Blue = "\033[34m"
FG_Magenta = "\033[35m"
FG_Cyan = "\033[36m"
... | class Style:
"""Shortcuts to terminal styling escape sequences"""
bold = '\x1b[1m'
end = '\x1b[0m'
fg__black = '\x1b[30m'
fg__red = '\x1b[31m'
fg__green = '\x1b[32m'
fg__yellow = '\x1b[33m'
fg__blue = '\x1b[34m'
fg__magenta = '\x1b[35m'
fg__cyan = '\x1b[36m'
fg__white = '\x1b... |
# Function for nth Fibonacci number
def Fibonacci(n):
# First Fibonacci number is 0
if n == 0:
return 0
# Second Fibonacci number is 1
elif n == 1:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
k = input("Enter a Number. Do not enter any string or symbol")
tr... | def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
k = input('Enter a Number. Do not enter any string or symbol')
try:
if int(k) >= 0:
for i in range(int(k)):
print(fibonacci(i))
else:
print... |
"""
Conversion functions
"""
# Depth and length conversions
def ft_to_m(inputvalue):
"""
Converts feet to metres.
Parameters
----------
inputvalue : float
Input value in feet.
Returns
-------
float
Returns value in metres.
"""
return inputvalue * 0.3048
def m_... | """
Conversion functions
"""
def ft_to_m(inputvalue):
"""
Converts feet to metres.
Parameters
----------
inputvalue : float
Input value in feet.
Returns
-------
float
Returns value in metres.
"""
return inputvalue * 0.3048
def m_to_ft(inputvalue):
"""
... |
"""
https://leetcode.com/problems/insert-interval/
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Outpu... | """
https://leetcode.com/problems/insert-interval/
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Outpu... |
def checkpalindromic(num):
i = 1
newNum = num
while i <= 50:
newNum = newNum + int(str(newNum)[::-1])
i = i + 1
if str(newNum) == str(newNum)[::-1]:
return True
return False
ans = 0
for i in range(1,10000):
if not checkpalindromic(i):
ans += 1
pr... | def checkpalindromic(num):
i = 1
new_num = num
while i <= 50:
new_num = newNum + int(str(newNum)[::-1])
i = i + 1
if str(newNum) == str(newNum)[::-1]:
return True
return False
ans = 0
for i in range(1, 10000):
if not checkpalindromic(i):
ans += 1
print(ans... |
with open('mar27') as f:
content = f.readlines()
for line in content:
split = line.split(' ')
if split[0] == 'Episode:':
print("("+str(int(split[1])) + "," + split[3].split("\n")[0] + ")")
| with open('mar27') as f:
content = f.readlines()
for line in content:
split = line.split(' ')
if split[0] == 'Episode:':
print('(' + str(int(split[1])) + ',' + split[3].split('\n')[0] + ')') |
mystring="hello world"
#Print Complete string
print(mystring)
print(mystring[::])
#indexing of string
print(mystring[0])
print(mystring[4])
#slicing
print(mystring[1:7])
print(mystring[0:10:2])
# Methods
print(mystring.upper())
print(mystring.split())
#formatting
print("hello world {},".format("Loki"))
print("hello... | mystring = 'hello world'
print(mystring)
print(mystring[:])
print(mystring[0])
print(mystring[4])
print(mystring[1:7])
print(mystring[0:10:2])
print(mystring.upper())
print(mystring.split())
print('hello world {},'.format('Loki'))
print('hello world {}, {}, {}'.format('Loki', 'INSERTING', 'NEWFORMATTING'))
print('hello... |
## Advent of Code 2018: Day 8
## https://adventofcode.com/2018/day/8
## Jesse Williams
## Answers: [Part 1]: 36566, [Part 2]: 30548
class Node(object):
def __init__(self, chs, mds):
self.header = (chs, mds) # number of child nodes and metadata entries as specified in the node header
self.childNode... | class Node(object):
def __init__(self, chs, mds):
self.header = (chs, mds)
self.childNodes = []
self.metadataList = []
def get_metadata_sum(self):
sum = 0
for node in self.childNodes:
sum += node.getMetadataSum()
sum += sum(self.metadataList)
... |
'A somewhat inefficient (because of string.index) cypher'
plaintext = 'meet me at the usual place'
fromLetters = 'abcdefghijklmnopqrstuv0123456789 '
toLetters = '6n4pde3fs 2c1ivjr05lq8utbgam7hk9o'
for plaintext_char in plaintext:
from_letters_index: int = fromLetters.index(plaintext_char)
encrypted_letter... | """A somewhat inefficient (because of string.index) cypher"""
plaintext = 'meet me at the usual place'
from_letters = 'abcdefghijklmnopqrstuv0123456789 '
to_letters = '6n4pde3fs 2c1ivjr05lq8utbgam7hk9o'
for plaintext_char in plaintext:
from_letters_index: int = fromLetters.index(plaintext_char)
encrypted_letter... |
def common_ground(s1,s2):
words = s2.split()
return ' '.join(sorted((a for a in set(s1.split()) if a in words),
key=lambda b: words.index(b))) or 'death'
| def common_ground(s1, s2):
words = s2.split()
return ' '.join(sorted((a for a in set(s1.split()) if a in words), key=lambda b: words.index(b))) or 'death' |
#contador = 0
#print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador))
contador = 1
print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador)) | contador = 1
print('2 elevado a la' + str(contador) + ' es igual a: ' + str(2 ** contador)) |
# Building a stack using python list
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty() == True:
return None
else:
... | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty() == True:
return None
else:
return self.items.pop()
def top... |
# coding=utf-8
"""Score problem dynamic programming solution Python implementation."""
def sp(n):
dp = [0] * (n + 1)
dp[0] = 1
for i in range(3, n + 1):
dp[i] += dp[i - 3]
for i in range(5, n + 1):
dp[i] += dp[i - 5]
for i in range(10, n + 1):
dp[i] += dp[i - 10]
return... | """Score problem dynamic programming solution Python implementation."""
def sp(n):
dp = [0] * (n + 1)
dp[0] = 1
for i in range(3, n + 1):
dp[i] += dp[i - 3]
for i in range(5, n + 1):
dp[i] += dp[i - 5]
for i in range(10, n + 1):
dp[i] += dp[i - 10]
return dp[n]
if __name... |
def maxArea(height) -> int:
res=0
length=len(height)
for x in range(length):
if height[x]==0:
continue
prev_y=0
for y in range(length-1,x,-1):
if (height[y]<=prev_y):
continue
... | def max_area(height) -> int:
res = 0
length = len(height)
for x in range(length):
if height[x] == 0:
continue
prev_y = 0
for y in range(length - 1, x, -1):
if height[y] <= prev_y:
continue
prev_y = height[y]
area = min(h... |
# --- Day 8: Seven Segment Search ---
# Each digit of a seven-segment display is rendered by turning on or off any of seven segments named a through g:
# So, to render a 1, only segments c and f would be turned on; the rest would be off.
# To render a 7, only segments a, c, and f would be turned on.
#
# For each displa... | test_input = [[num.strip().split(' ') for num in line.split('|')] for line in open('resources/test_input', 'r').readlines()]
test_input_2 = [[num.strip().split(' ') for num in line.split('|')] for line in open('resources/test_input_2', 'r').readlines()]
val_input = [[num.strip().split(' ') for num in line.split('|')] f... |
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
m = {}
for n in arr:
if n in m:
m[n] += 1
else:
m[n] = 1
for n in arr:
if n * 2 in m and n is not 0:
return True
e... | class Solution:
def check_if_exist(self, arr: List[int]) -> bool:
m = {}
for n in arr:
if n in m:
m[n] += 1
else:
m[n] = 1
for n in arr:
if n * 2 in m and n is not 0:
return True
elif n is 0 and ... |
class Parent:
def __init__(self, last_name, eye_color):
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last name - "+self.last_name)
print("Eye color - "+self.eye_color)
class Child(Parent):
def __init__(self, last_name, eye_color, number... | class Parent:
def __init__(self, last_name, eye_color):
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print('Last name - ' + self.last_name)
print('Eye color - ' + self.eye_color)
class Child(Parent):
def __init__(self, last_name, eye_color, n... |
"""
WxAPI Exceptions
"""
class WxAPIException(Exception):
"""Base class for exceptions in this module"""
def __init__(self, message):
self.message = message
class InvalidFormat(WxAPIException):
"""The format provided is invalid"""
class FormatNotAllowed(WxAPIException):
"""The format provided... | """
WxAPI Exceptions
"""
class Wxapiexception(Exception):
"""Base class for exceptions in this module"""
def __init__(self, message):
self.message = message
class Invalidformat(WxAPIException):
"""The format provided is invalid"""
class Formatnotallowed(WxAPIException):
"""The format provide... |
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
J = set(J)
return sum(1 for stone in S if stone in J)
| class Solution:
def num_jewels_in_stones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
j = set(J)
return sum((1 for stone in S if stone in J)) |
#
# PySNMP MIB module HUAWEI-PWE3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-PWE3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:34:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
def median(nums):
"""
Find median of a list of numbers.
>>> median([0])
0
>>> median([4,1,3,2])
2.5
Args:
nums: List of nums
Returns:
Median.
"""
sorted_list = sorted(nums)
med = None
if len(sorted_list) % 2 == 0:
mid_index_1 = len(sorted_list) ... | def median(nums):
"""
Find median of a list of numbers.
>>> median([0])
0
>>> median([4,1,3,2])
2.5
Args:
nums: List of nums
Returns:
Median.
"""
sorted_list = sorted(nums)
med = None
if len(sorted_list) % 2 == 0:
mid_index_1 = len(sorted_list) ... |
# Autogenerated config.py
#
# NOTE: config.py is intended for advanced users who are comfortable
# with manually migrating the config file on qutebrowser upgrades. If
# you prefer, you can also configure qutebrowser using the
# :set/:bind/:config-* commands without having to write a config.py
# file.
#
# Documentation:... | config.load_autoconfig(False)
c.auto_save.session = True
config.set('content.cookies.accept', 'all', 'chrome-devtools://*')
config.set('content.cookies.accept', 'all', 'devtools://*')
config.set('content.geolocation', False, 'https://www.google.com.ar')
config.set('content.headers.accept_language', '', 'https://matchma... |
'''from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def main():
return print("Your bot is alive!")
def run():
app.run(host="0.0.0.0", port=8080) 4692
def keep_alive():
server = Thread(target=run)
server.start()'''
'''from flask import Flask
from threading import Th... | """from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def main():
return print("Your bot is alive!")
def run():
app.run(host="0.0.0.0", port=8080) 4692
def keep_alive():
server = Thread(target=run)
server.start()"""
'from flask import Flask\nfrom threading import Threa... |
#
# PySNMP MIB module CYCLADES-ACS-ADM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CYCLADES-ACS-ADM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:18:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_size_constraint, value_range_constraint) ... |
US_CENSUS = {'age': {'18-24': 0.1304,
'25-44': 0.3505,
'45-64': 0.3478,
'65+': 0.1713}, # Age from 2010 US Census https://www.census.gov/prod/cen2010/briefs/c2010br-03.pdf
'education': {'Completed graduate school': 0.1204,
... | us_census = {'age': {'18-24': 0.1304, '25-44': 0.3505, '45-64': 0.3478, '65+': 0.1713}, 'education': {'Completed graduate school': 0.1204, 'Graduated from college': 0.2128, 'Some college, no degree': 0.2777, 'Graduated from high school': 0.2832, 'Less than high school': 0.106}, 'gender': {'Female': 0.507, 'Male': 0.487... |
"""Convert units for human readable values"""
conv_factor = {
'K': 1/1024,
'M': 1,
'G': 1024,
'T': 1024*1024
}
def convert_to_base(string):
"""Convert the string to an integer number of base units.
Example: 3G = 3*1024
"""
stripped = string.strip()
try:
return int(stripped)... | """Convert units for human readable values"""
conv_factor = {'K': 1 / 1024, 'M': 1, 'G': 1024, 'T': 1024 * 1024}
def convert_to_base(string):
"""Convert the string to an integer number of base units.
Example: 3G = 3*1024
"""
stripped = string.strip()
try:
return int(stripped)
except Val... |
def get_range (string):
return_set = set()
for x in string.split(','):
x = x.strip()
if '-' not in x and x.isnumeric():
return_set.add(int(x))
elif x.count('-')==1:
from_here, to_here = x.split('-')[0].strip(), x.split('-')[1].strip()
... | def get_range(string):
return_set = set()
for x in string.split(','):
x = x.strip()
if '-' not in x and x.isnumeric():
return_set.add(int(x))
elif x.count('-') == 1:
(from_here, to_here) = (x.split('-')[0].strip(), x.split('-')[1].strip())
if from_here... |
# Implementation of SequentialSearch in python
# Python3 code to sequentially search key in arr[].
# If key is present then return its position,
# otherwise return -1
# If return value -1 then print "Not Found!"
# else print position at which element found
def Sequential_Search(dlist, item):
pos = 0
found = ... | def sequential__search(dlist, item):
pos = 0
found = False
while pos < len(dlist) and (not found):
if dlist[pos] == item:
found = True
else:
pos += 1
if found:
return pos
else:
return -1
list = input('Enter list elements (space seperated): ').s... |
user_name = "user"
password = "pass"
url= "ip address"
project_scope_name = "username"
domain_id = "defa"
| user_name = 'user'
password = 'pass'
url = 'ip address'
project_scope_name = 'username'
domain_id = 'defa' |
CURRENCY_LIST_ACRONYM = [
('AUD','Australia Dollar'),
('GBP','Great Britain Pound'),
('EUR','Euro'),
('JPY','Japan Yen'),
('CHF','Switzerland Franc'),
('USD','USA Dollar'),
('AFN','Afghanistan Afghani'),
('ALL','Albania Lek'),
('DZD','... | currency_list_acronym = [('AUD', 'Australia Dollar'), ('GBP', 'Great Britain Pound'), ('EUR', 'Euro'), ('JPY', 'Japan Yen'), ('CHF', 'Switzerland Franc'), ('USD', 'USA Dollar'), ('AFN', 'Afghanistan Afghani'), ('ALL', 'Albania Lek'), ('DZD', 'Algeria Dinar'), ('AOA', 'Angola Kwanza'), ('ARS', 'Argentina Peso'), ('AMD',... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
if __name__=='__main__':
print("Hello every body, I am Thomas.Li. I will be study hard for algorithms excercise") | if __name__ == '__main__':
print('Hello every body, I am Thomas.Li. I will be study hard for algorithms excercise') |
class CIDR(object):
def __init__(self, base, size=None):
try:
base, _size = base.split('/')
except ValueError:
pass
else:
if size is None:
size = _size
self.size = 2 ** (32 - int(size))
self._mask = ~(self.size - ... | class Cidr(object):
def __init__(self, base, size=None):
try:
(base, _size) = base.split('/')
except ValueError:
pass
else:
if size is None:
size = _size
self.size = 2 ** (32 - int(size))
self._mask = ~(self.size - 1)
... |
'''
URL: https://leetcode.com/problems/minimum-falling-path-sum
Time complexity: O(nm)
Space complexity: O(nm)
'''
class Solution:
def minFallingPathSum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
memo = [[None for i in range(len(A[0]))] for j in range(len(A))]
... | """
URL: https://leetcode.com/problems/minimum-falling-path-sum
Time complexity: O(nm)
Space complexity: O(nm)
"""
class Solution:
def min_falling_path_sum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
memo = [[None for i in range(len(A[0]))] for j in range(len(A))... |
USERS = "users"
COMMUNITIES = 'communities'
TEAMS = 'teams'
METRICS = 'metrics'
ACTIONS = 'actions' | users = 'users'
communities = 'communities'
teams = 'teams'
metrics = 'metrics'
actions = 'actions' |
'''
Created on 28-mei-2016
@author: vincent
Static configuration, updated and generated by autoconf
'''
VERSION = "0.1.0"
| """
Created on 28-mei-2016
@author: vincent
Static configuration, updated and generated by autoconf
"""
version = '0.1.0' |
# -*- coding: utf-8 -*-
# SiteProfileNotAvailable compatibility
class SiteProfileNotAvailable(Exception):
pass
| class Siteprofilenotavailable(Exception):
pass |
# 817. Linked List Components
# ttungl@gmail.com
# We are given head, the head node of a linked list containing unique integer values.
# We are also given the list G, a subset of the values in the linked list.
# Return the number of connected components in G, where two values are connected if they appear consecutive... | class Solution(object):
def num_components(self, head, G):
"""
:type head: ListNode
:type G: List[int]
:rtype: int
"""
(res, set_g) = (0, set(G))
while head:
if head.val in setG and (not head.next or head.next.val not in setG):
res... |
class Queen:
def __init__(self, row: int, column: int):
if row not in range(0, 8) or column not in range(0, 8):
raise ValueError("Must be between 0 and 7")
self.i = row
self.j = column
def can_attack(self, another_queen: 'Queen') -> bool:
if self.i == another_queen.... | class Queen:
def __init__(self, row: int, column: int):
if row not in range(0, 8) or column not in range(0, 8):
raise value_error('Must be between 0 and 7')
self.i = row
self.j = column
def can_attack(self, another_queen: 'Queen') -> bool:
if self.i == another_queen... |
def append_suppliers_list():
suppliers = []
counter = 1
supply = ""
while supply != "stop":
supply = input(f'Enter first name and last name of suppliers {counter} \n')
suppliers.append(supply)
counter += 1
suppliers.pop()
return suppliers
append_supplier... | def append_suppliers_list():
suppliers = []
counter = 1
supply = ''
while supply != 'stop':
supply = input(f'Enter first name and last name of suppliers {counter} \n')
suppliers.append(supply)
counter += 1
suppliers.pop()
return suppliers
append_suppliers_list() |
def test(a,b,c):
a =1
b =2
c =3
return [1,2,3]
a = test(1,2,3)
print(a,test) | def test(a, b, c):
a = 1
b = 2
c = 3
return [1, 2, 3]
a = test(1, 2, 3)
print(a, test) |
class BaseData:
def __init__(self):
self.root_dir = None
self.gray = None
self.div_Lint = None
self.filenames = None
self.L = None
self.Lint = None
self.mask = None
self.M = None
self.N = None
def _load_mask(self):
raise NotImpleme... | class Basedata:
def __init__(self):
self.root_dir = None
self.gray = None
self.div_Lint = None
self.filenames = None
self.L = None
self.Lint = None
self.mask = None
self.M = None
self.N = None
def _load_mask(self):
raise NotImplem... |
def decimal_to_binary(decimal_integer):
return bin(decimal_integer).replace("0b", "")
def solution(binary_integer):
count = 0
max_count = 0
for element in binary_integer:
if element == "1":
count += 1
if max_count < count:
max_count = count
else:... | def decimal_to_binary(decimal_integer):
return bin(decimal_integer).replace('0b', '')
def solution(binary_integer):
count = 0
max_count = 0
for element in binary_integer:
if element == '1':
count += 1
if max_count < count:
max_count = count
else:
... |
rows= int(input("Enter the number of rows: "))
cols= int(input("Enter the number of columns: "))
matrixA=[]
print("Enter the entries rowwise for matrix A: ")
for i in range(rows):
a=[]
for j in range(cols):
a.append(int(input()))
matrixA.append(a)
matrixB=[]
print("Enter the entries rowwise for m... | rows = int(input('Enter the number of rows: '))
cols = int(input('Enter the number of columns: '))
matrix_a = []
print('Enter the entries rowwise for matrix A: ')
for i in range(rows):
a = []
for j in range(cols):
a.append(int(input()))
matrixA.append(a)
matrix_b = []
print('Enter the entries rowwis... |
class Solution(object):
def rob(self, nums):
def helper(nums, i):
le = len(nums)
if i == le - 1:
return nums[le-1]
if i == le - 2:
return max(nums[le-1], nums[le-2])
if i == le - 3:
return max(nums[le-3] + nums[... | class Solution(object):
def rob(self, nums):
def helper(nums, i):
le = len(nums)
if i == le - 1:
return nums[le - 1]
if i == le - 2:
return max(nums[le - 1], nums[le - 2])
if i == le - 3:
return max(nums[le - 3... |
k = int(input())
for z in range(k):
l = int(input())
n = list(map(int,input().split()))
c = 0
for i in range(l-1):
for j in range(i+1,l):
if n[i]>n[j]:
c += 1
if c%2==0:
print('YES')
else:
print('NO')
| k = int(input())
for z in range(k):
l = int(input())
n = list(map(int, input().split()))
c = 0
for i in range(l - 1):
for j in range(i + 1, l):
if n[i] > n[j]:
c += 1
if c % 2 == 0:
print('YES')
else:
print('NO') |
test = {
'name': 'q3_1_1',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> len(my_20_features)
20
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> np.all([f in test_movies.labels f... | test = {'name': 'q3_1_1', 'points': 1, 'suites': [{'cases': [{'code': '\n >>> len(my_20_features)\n 20\n ', 'hidden': False, 'locked': False}, {'code': '\n >>> np.all([f in test_movies.labels for f in my_20_features])\n True\n ', 'hidden': False, 'locked': False}, {... |
line = input().split()
H = int(line[0])
W = int(line[1])
array = []
def get_ij(index):
i = index // W
if (i % 2 == 0):
j = index % W
else:
j = W - index % W - 1
return i+1, j+1
for i in range(H):
if i % 2 == 0:
array.extend([int(a) for a in input().split()])
else:
... | line = input().split()
h = int(line[0])
w = int(line[1])
array = []
def get_ij(index):
i = index // W
if i % 2 == 0:
j = index % W
else:
j = W - index % W - 1
return (i + 1, j + 1)
for i in range(H):
if i % 2 == 0:
array.extend([int(a) for a in input().split()])
else:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
VERSION
Control de versiones.
Autor: PABLO PIZARRO @ github.com/ppizarror
Fecha: SEPTIEMBRE 2016
Licencia: MiT licence
"""
__version__ = '1.0.0'
| """
VERSION
Control de versiones.
Autor: PABLO PIZARRO @ github.com/ppizarror
Fecha: SEPTIEMBRE 2016
Licencia: MiT licence
"""
__version__ = '1.0.0' |
# -*- coding: utf-8 -*-
"""
Created on Sun May 20 21:01:53 2018
@author: DrLC
"""
class VarDecl(object):
def __init__(self, line=""):
line = line.strip().strip(';,').strip().split()
self.__type = line[0]
assert self.__type in ["int", "float"], "Invalid type \""+self.__type+"\... | """
Created on Sun May 20 21:01:53 2018
@author: DrLC
"""
class Vardecl(object):
def __init__(self, line=''):
line = line.strip().strip(';,').strip().split()
self.__type = line[0]
assert self.__type in ['int', 'float'], 'Invalid type "' + self.__type + '"'
self.__name = line[-1]
... |
"""
read by line
"""
def get_path():
raise NotImplementedError
def get_absolute_path():
raise NotImplementedError
def get_canonical_path():
raise NotImplementedError
def get_cwd_path():
raise NotImplementedError
def is_absolute_path():
raise NotImplementedError
| """
read by line
"""
def get_path():
raise NotImplementedError
def get_absolute_path():
raise NotImplementedError
def get_canonical_path():
raise NotImplementedError
def get_cwd_path():
raise NotImplementedError
def is_absolute_path():
raise NotImplementedError |
class Player:
def __init__(self, player_name, examined_step_list):
self.user_name = player_name
self.player_score = {}
self.step_list = examined_step_list
self.generate_score_dict()
def generate_score_dict(self):
for key in self.step_list:
self.player_score[k... | class Player:
def __init__(self, player_name, examined_step_list):
self.user_name = player_name
self.player_score = {}
self.step_list = examined_step_list
self.generate_score_dict()
def generate_score_dict(self):
for key in self.step_list:
self.player_score[... |
class InwardMeta(type):
@classmethod
def __prepare__(meta, name, bases, **kwargs):
cls = super().__new__(meta, name, bases, {})
return {"__newclass__": cls}
def __new__(meta, name, bases, namespace):
cls = namespace["__newclass__"]
del namespace["__newclass__"]
for na... | class Inwardmeta(type):
@classmethod
def __prepare__(meta, name, bases, **kwargs):
cls = super().__new__(meta, name, bases, {})
return {'__newclass__': cls}
def __new__(meta, name, bases, namespace):
cls = namespace['__newclass__']
del namespace['__newclass__']
for ... |
class InvalidateEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.Control.Invalidated event.
InvalidateEventArgs(invalidRect: Rectangle)
"""
def Instance(self):
""" This function has been arbitrarily put into the stubs"""
return InvalidateEventArgs()
@staticmethod
def __new... | class Invalidateeventargs(EventArgs):
"""
Provides data for the System.Windows.Forms.Control.Invalidated event.
InvalidateEventArgs(invalidRect: Rectangle)
"""
def instance(self):
""" This function has been arbitrarily put into the stubs"""
return invalidate_event_args()
@staticmeth... |
nome=input('Qual o seu nome?')
print('Seja Bem-Vindo,',nome)
| nome = input('Qual o seu nome?')
print('Seja Bem-Vindo,', nome) |
# 337. House Robber III
# Leetcode solution(approach 1)
# 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 rob(self, root: TreeNode) -> int:
def h... | class Solution:
def rob(self, root: TreeNode) -> int:
def helper(node):
if not node:
return (0, 0)
left = helper(node.left)
right = helper(node.right)
rob = node.val + left[1] + right[1]
not_rob = max(left) + max(right)
... |
def main():
puzzleInput = open("python/day01.txt", "r").read()
# Part 1
assert(part1("") == 0)
print(part1(puzzleInput))
# Part 2
assert(part2("") == 0)
print(part2(puzzleInput))
def part1(puzzleInput):
return 0
def part2(puzzleInput):
return 0
if __name__ == "__main__":
... | def main():
puzzle_input = open('python/day01.txt', 'r').read()
assert part1('') == 0
print(part1(puzzleInput))
assert part2('') == 0
print(part2(puzzleInput))
def part1(puzzleInput):
return 0
def part2(puzzleInput):
return 0
if __name__ == '__main__':
main() |
# coding=utf-8
# Author: Jianghan LI
# Question: 230.Kth_Smallest_Element_in_a_BST
# Complexity: O(N)
# Date: 2017-10-03
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
... | class Solution(object):
def kth_smallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
inorder = []
cur = root
while k:
while cur:
inorder.append(cur)
cur = cur.left
cur =... |
def sentencemaker(pharase):
cap = pharase.capitalize()
interogatives = ("how" , "what" , "why")
if pharase.startswith(interogatives):
return "{}?".format(cap)
else:
return "{}".format(cap)
results = []
while True:
user_input = input("Say Something :-) ")
if user_inp... | def sentencemaker(pharase):
cap = pharase.capitalize()
interogatives = ('how', 'what', 'why')
if pharase.startswith(interogatives):
return '{}?'.format(cap)
else:
return '{}'.format(cap)
results = []
while True:
user_input = input('Say Something :-) ')
if user_input == '\\end':
... |
"""
https://github.com/alexhagiopol/cracking-the-coding-interview
http://jelices.blogspot.com/
https://www.youtube.com/watch?v=bum_19loj9A&list=PLBZBJbE_rGRV8D7XZ08LK6z-4zPoWzu5H
https://www.youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww/videos
https://github.com/TheAlgorithms/Python
https://codesays.com/
https://github.... | """
https://github.com/alexhagiopol/cracking-the-coding-interview
http://jelices.blogspot.com/
https://www.youtube.com/watch?v=bum_19loj9A&list=PLBZBJbE_rGRV8D7XZ08LK6z-4zPoWzu5H
https://www.youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww/videos
https://github.com/TheAlgorithms/Python
https://codesays.com/
https://github.... |
{
'targets': [
{
'target_name': 'node_stringprep',
'cflags_cc!': [ '-fno-exceptions', '-fmax-errors=0' ],
'include_dirs': [
'<!(node -e "require(\'nan\')")'
],
'conditions': [
['OS=="win"', {
'conditions': [
['"<!@(cmd /C where /Q icu-config || e... | {'targets': [{'target_name': 'node_stringprep', 'cflags_cc!': ['-fno-exceptions', '-fmax-errors=0'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'conditions': [['OS=="win"', {'conditions': [['"<!@(cmd /C where /Q icu-config || echo n)"!="n"', {'sources': ['node-stringprep.cc'], 'cflags!': ['-fno-exceptions', '`... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.