content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution(object):
mem={}
def canWin2(self, s):
"""
:type s: str
:rtype: bool
"""
# check mem first
if s in self.mem:
return self.mem[s]
# can I win? if no moves to go then return False since I cannot win.
nextMove=self.moves(s)
... | class Solution(object):
mem = {}
def can_win2(self, s):
"""
:type s: str
:rtype: bool
"""
if s in self.mem:
return self.mem[s]
next_move = self.moves(s)
if not nextMove:
self.mem[s] = False
return False
for move... |
"""
John McDonough
github - movinalot
Advent of Code 2020
"""
# pylint: disable=invalid-name
TESTING = 0
TESTFILE = 0
DEBUG = 0
DAY = "06"
YEAR = "2020"
PART = "2"
ANSWER = None
PUZZLE_DATA = None
def process_puzzle_input(ext=".txt"):
""" Process puzzle input """
with open("puzzle_data_" +... | """
John McDonough
github - movinalot
Advent of Code 2020
"""
testing = 0
testfile = 0
debug = 0
day = '06'
year = '2020'
part = '2'
answer = None
puzzle_data = None
def process_puzzle_input(ext='.txt'):
""" Process puzzle input """
with open('puzzle_data_' + DAY + '_' + YEAR + ext) as f:
puzzle_data... |
def lcm(a: int, b: int) -> int:
"""Return a LCM (Lowest Common Multiple) of given two integers
>>> lcm(3, 10)
30
>>> lcm(42, 63)
126
>>> lcm(40, 80)
80
>>> lcm(-20, 30)
60
"""
g = min(abs(a), abs(b))
while g >= 1:
if a % g == 0 and b % g == 0:
break
... | def lcm(a: int, b: int) -> int:
"""Return a LCM (Lowest Common Multiple) of given two integers
>>> lcm(3, 10)
30
>>> lcm(42, 63)
126
>>> lcm(40, 80)
80
>>> lcm(-20, 30)
60
"""
g = min(abs(a), abs(b))
while g >= 1:
if a % g == 0 and b % g == 0:
break
... |
username = 'billgates@microsoft.com'
password = 'i-love-cortana'
home_path = '~/chromedriver'
app_name = 'myapp_v01'
subscription = 'azure-subscription-dropdown'
authoring_resource = "your-authoring-resource"
| username = 'billgates@microsoft.com'
password = 'i-love-cortana'
home_path = '~/chromedriver'
app_name = 'myapp_v01'
subscription = 'azure-subscription-dropdown'
authoring_resource = 'your-authoring-resource' |
class OmnikassaException(Exception):
pass
class InvalidResponseCode(OmnikassaException):
def __init__(self, data):
self.data = data
def __str__(self):
return 'Got responseCode {}'.format(self.data['responseCode'])
class InvalidSeal(OmnikassaException):
def __init__(self, data):
... | class Omnikassaexception(Exception):
pass
class Invalidresponsecode(OmnikassaException):
def __init__(self, data):
self.data = data
def __str__(self):
return 'Got responseCode {}'.format(self.data['responseCode'])
class Invalidseal(OmnikassaException):
def __init__(self, data):
... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dct = {}
for i in range(len(nums)):
if (dct.get(target-nums[i], -1) == -1):
dct[nums[i]] = i
else:
return [dct.get(target-nums[i]), i] | class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
dct = {}
for i in range(len(nums)):
if dct.get(target - nums[i], -1) == -1:
dct[nums[i]] = i
else:
return [dct.get(target - nums[i]), i] |
class Solution:
# keep pre-computed fibs around.
fibs = [
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,
987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,
75025, 121393, 196418, 317811, 514229, 832040, 1346269,
2178309, 3524578, 5702887, 9227465, 14930352, 24157... | class Solution:
fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 7... |
with open("data/modelnet40_normal_resampled/modelnet40_test_orig.txt") as f:
lines = f.readlines()
lines = lines[::13]
with open("data/modelnet40_normal_resampled/modelnet40_test.txt", 'w') as f2:
for line in lines:
f2.write(line)
| with open('data/modelnet40_normal_resampled/modelnet40_test_orig.txt') as f:
lines = f.readlines()
lines = lines[::13]
with open('data/modelnet40_normal_resampled/modelnet40_test.txt', 'w') as f2:
for line in lines:
f2.write(line) |
#############################################################
# 2016-09-26: MessageIdType.py
# Author: Jeremy M. Gibson (State Archives of North Carolina)
#
# Description: Implementation of message-id-type
##############################################################
class MessageId:
""""""
def __init__(sel... | class Messageid:
""""""
def __init__(self):
"""Constructor for MessageId"""
pass |
class Keys:
"""Remap the keypresses from numbers to variables."""
UP = 259
DOWN = 258
LEFT = 260
RIGHT = 261
ENTER = 10
SPACE = 32
ESC = 27
W = 119
A = 97
S = 115
D = 100
# DEFAULT KEYS
Q = 113
TAB = 9
PG_... | class Keys:
"""Remap the keypresses from numbers to variables."""
up = 259
down = 258
left = 260
right = 261
enter = 10
space = 32
esc = 27
w = 119
a = 97
s = 115
d = 100
q = 113
tab = 9
pg_down = 338
pg_up = 339 |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
class BaseCrawler:
start_url = ''
browser = None
dir_path = ''
def __init__(self, browser, dir_path):
self.browser = browser
self.dir_path = dir_path
self.crawl(self.start_url)
def get_html(self, url):
self.browser.ge... | class Basecrawler:
start_url = ''
browser = None
dir_path = ''
def __init__(self, browser, dir_path):
self.browser = browser
self.dir_path = dir_path
self.crawl(self.start_url)
def get_html(self, url):
self.browser.get(url)
return self.browser.page_source
... |
# Given an array, sort it using mergesort
def merge(a, start, mid, end, aux):
for i in range(len(a)):
aux[i] = a[i]
left = start
right = mid+1
i = left
while left <= mid and right <= end:
if aux[left] < aux[right]:
a[i] = aux[left]
left += 1
i += 1
else:
a[i] = aux[right]
right += 1
i ... | def merge(a, start, mid, end, aux):
for i in range(len(a)):
aux[i] = a[i]
left = start
right = mid + 1
i = left
while left <= mid and right <= end:
if aux[left] < aux[right]:
a[i] = aux[left]
left += 1
i += 1
else:
a[i] = aux[ri... |
n = int(input())
s = [list(map(int, input().split())) for _ in [0] * n]
s = sorted(s, key=lambda x: x[0])
c = 0
for i in range(10):
i = 0
while (i != len(s)-1 and i < len(s)):
if s[i][1] >= abs(s[i][0] - s[i+1][0]):
c += 1
s.pop(i)
i += 1
print(n-c)
| n = int(input())
s = [list(map(int, input().split())) for _ in [0] * n]
s = sorted(s, key=lambda x: x[0])
c = 0
for i in range(10):
i = 0
while i != len(s) - 1 and i < len(s):
if s[i][1] >= abs(s[i][0] - s[i + 1][0]):
c += 1
s.pop(i)
i += 1
print(n - c) |
name = input('please input your name:')
sql = 'select * from dome where name="%s"' % name
print(sql)
name = 'zr;drop database demo'
sql = 'select * from dome where name="%s"' % name
print(sql)
name = 'zr;drop database demo'
initname = [name]
#csl = 'connect mysqldb successful:'.cursor()
#sql = csl.excu... | name = input('please input your name:')
sql = 'select * from dome where name="%s"' % name
print(sql)
name = 'zr;drop database demo'
sql = 'select * from dome where name="%s"' % name
print(sql)
name = 'zr;drop database demo'
initname = [name]
sql = 'select * from demo where name = %s' % initname
print(sql) |
class SecurePathProxy:
"""
This class is a good way to change directories without having to remember to go back later.
Use with 'with'!
There's also a very nice method to apply any callable entity in all children folders recursivilly
"""
def __init__(self, os_interfaced_object, path):
se... | class Securepathproxy:
"""
This class is a good way to change directories without having to remember to go back later.
Use with 'with'!
There's also a very nice method to apply any callable entity in all children folders recursivilly
"""
def __init__(self, os_interfaced_object, path):
s... |
_base_ = (
"./FlowNet512_1.5AugCosyAAEGray_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_Pbr_01_02MasterChefCan_bop_test.py"
)
OUTPUT_DIR = "output/deepim/ycbvPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_ycbvPbr_SO/02_03CrackerBox"
DATASETS = dict(TRAIN=("ycbv_003_cracker_b... | _base_ = './FlowNet512_1.5AugCosyAAEGray_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_Pbr_01_02MasterChefCan_bop_test.py'
output_dir = 'output/deepim/ycbvPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveR_ClipGrad_fxfy1_Dtw01_LogDz_PM10_Flat_ycbvPbr_SO/02_03CrackerBox'
datasets = dict(TRAIN=('ycbv_003_cracker_box_train... |
#!/usr/bin/env python3
# coding: utf-8
class RdboxNodeReport(object):
def __init__(self, rdbox_node_list, formatter):
self.rdbox_node_list = rdbox_node_list
self.formatter = formatter
def output_report(self):
return self.formatter.output_report(self.rdbox_node_list)
| class Rdboxnodereport(object):
def __init__(self, rdbox_node_list, formatter):
self.rdbox_node_list = rdbox_node_list
self.formatter = formatter
def output_report(self):
return self.formatter.output_report(self.rdbox_node_list) |
class CONFIG:
server_addr = '127.0.0.1'
server_port = 2333
buffersize = 1024
atp_size = 512
head_size = 8
cnt_frames = 1024 | class Config:
server_addr = '127.0.0.1'
server_port = 2333
buffersize = 1024
atp_size = 512
head_size = 8
cnt_frames = 1024 |
# @author Huaze Shen
# @date 2020-05-02
def hamming_weight(n: int) -> int:
num_ones = 0
while n != 0:
num_ones += (n & 1)
n = n >> 1
return num_ones
if __name__ == '__main__':
print(hamming_weight(5))
| def hamming_weight(n: int) -> int:
num_ones = 0
while n != 0:
num_ones += n & 1
n = n >> 1
return num_ones
if __name__ == '__main__':
print(hamming_weight(5)) |
def replace_domain(email, old_domain, new_domain):
if "@" + old_domain in email:
index = email.index("@" + old_domain)
new_email = email[:index] + "@" + new_domain
return new_email
return email
w = 1
while w == 1:
ask = input("Enter your email id, old domain, new domain :").split("... | def replace_domain(email, old_domain, new_domain):
if '@' + old_domain in email:
index = email.index('@' + old_domain)
new_email = email[:index] + '@' + new_domain
return new_email
return email
w = 1
while w == 1:
ask = input('Enter your email id, old domain, new domain :').split(','... |
def mergesort(arra):
'''
Uses the merge sort algorithm to sort a list
Inputs:
arra: a list
Returns
a sorted version of that list
'''
if len(arra)>1:
middle = len(arra)//2
LHS = mergesort(arra[:middle])
RHS = mergesort(arra[middle:])
l = 0
... | def mergesort(arra):
"""
Uses the merge sort algorithm to sort a list
Inputs:
arra: a list
Returns
a sorted version of that list
"""
if len(arra) > 1:
middle = len(arra) // 2
lhs = mergesort(arra[:middle])
rhs = mergesort(arra[middle:])
l = 0
... |
class Do:
"""Implementation of the do-operator.
Attributes
----------
causation : CausalGraph or CausalStructureModel
treatment : str
Methods
----------
"""
def __init__(self, causation):
"""
Parameters
----------
causation : CausalGraph or Causal... | class Do:
"""Implementation of the do-operator.
Attributes
----------
causation : CausalGraph or CausalStructureModel
treatment : str
Methods
----------
"""
def __init__(self, causation):
"""
Parameters
----------
causation : CausalGraph or CausalSt... |
class Server:
def __init__(self, host_name, port):
self.host_name = host_name
self.port = port
| class Server:
def __init__(self, host_name, port):
self.host_name = host_name
self.port = port |
# Enumerate, tuples (KO)
my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print(counter_list)
# Lamba (OK)
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
... | my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print(counter_list)
def multiply(x):
return x * x
def add(x):
return x + x
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
my_str = 'AiBohPhoBiA'
l = range(-1, 2)... |
# 270010300
if not sm.hasQuestCompleted(3503): # time lane quest
sm.chat("You have not completed the appropriate quest to enter here.")
else:
sm.warp(270010400, 5)
sm.dispose()
| if not sm.hasQuestCompleted(3503):
sm.chat('You have not completed the appropriate quest to enter here.')
else:
sm.warp(270010400, 5)
sm.dispose() |
"""
[2017-05-10] Challenge #314 [Intermediate] Comparing Rotated Words
https://www.reddit.com/r/dailyprogrammer/comments/6aefs1/20170510_challenge_314_intermediate_comparing/
# Description
We've explored the concept of string rotations before as [garland
words](https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj... | """
[2017-05-10] Challenge #314 [Intermediate] Comparing Rotated Words
https://www.reddit.com/r/dailyprogrammer/comments/6aefs1/20170510_challenge_314_intermediate_comparing/
# Description
We've explored the concept of string rotations before as [garland
words](https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj... |
nt=float(input())
np=float(input())
media=(nt+np)/2
if media>=6:
print(f'aprovado')
elif media<6 and nt>=2:
print(f'talvez com a sub')
else:
print(f'reprovado')
| nt = float(input())
np = float(input())
media = (nt + np) / 2
if media >= 6:
print(f'aprovado')
elif media < 6 and nt >= 2:
print(f'talvez com a sub')
else:
print(f'reprovado') |
def getReferenceParam(paramType, model, trial, latent, neuron, kernelParamIndex, indPointIndex, indPointIndex2):
if paramType=="kernel":
kernelsParams = model.getKernelsParams()
refParam = kernelsParams[latent][kernelParamIndex]
elif paramType=="embeddingC":
embeddingParams = model.getS... | def get_reference_param(paramType, model, trial, latent, neuron, kernelParamIndex, indPointIndex, indPointIndex2):
if paramType == 'kernel':
kernels_params = model.getKernelsParams()
ref_param = kernelsParams[latent][kernelParamIndex]
elif paramType == 'embeddingC':
embedding_params = mo... |
n=int(input())
lst=map(int,input().split())
lst2=lst.sort()
print(lst2)
print(min(lst2))
| n = int(input())
lst = map(int, input().split())
lst2 = lst.sort()
print(lst2)
print(min(lst2)) |
print ('Current value of var test is: ', test)
test.Value = 'New value set by Python'
print ('New value is:', test)
print ('-----------------------------------------------------')
class C:
def __init__(Self, Arg):
Self.Arg = Arg
def __str__(Self):
return '<C instance contains: ' + str(Self.Arg) + '>'
print ... | print('Current value of var test is: ', test)
test.Value = 'New value set by Python'
print('New value is:', test)
print('-----------------------------------------------------')
class C:
def __init__(Self, Arg):
Self.Arg = Arg
def __str__(Self):
return '<C instance contains: ' + str(Self.Arg) ... |
'''3. Write a Python program to get the largest number from a list.'''
def get_largest(lst):
return max(lst)
print(get_largest([1, 2, 5, 3, 60, 2, 5])) | """3. Write a Python program to get the largest number from a list."""
def get_largest(lst):
return max(lst)
print(get_largest([1, 2, 5, 3, 60, 2, 5])) |
hello_message = "Hi there :wave:"
welcome_attachment = [
{
"pretext": "I am here to take some *feedback* about your meeting room.",
"text": "*_How do you feel about your meeting room?_*",
"callback_id": "os",
"color": "#3AA3E3",
"attachment_type": "default",
"actions... | hello_message = 'Hi there :wave:'
welcome_attachment = [{'pretext': 'I am here to take some *feedback* about your meeting room.', 'text': '*_How do you feel about your meeting room?_*', 'callback_id': 'os', 'color': '#3AA3E3', 'attachment_type': 'default', 'actions': [{'name': 'bad', 'text': 'Bad', 'type': 'button', 's... |
class Solution:
# @return a boolean
def isScramble(self, s1, s2):
cnt = {}
for ch in s1:
if ch not in cnt:
cnt[ch] = 1
else:
cnt[ch] += 1
for ch in s2:
if ch not in cnt:
return False
else:
... | class Solution:
def is_scramble(self, s1, s2):
cnt = {}
for ch in s1:
if ch not in cnt:
cnt[ch] = 1
else:
cnt[ch] += 1
for ch in s2:
if ch not in cnt:
return False
else:
cnt[ch] -... |
# pylint: disable=missing-module-docstring
__all__ = [
'test_int__postgres_orm',
]
| __all__ = ['test_int__postgres_orm'] |
# scripts/pretty_printer.py
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
s... | class Bcolors:
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.EN... |
#given an array and a target number, the goal is to find the target number in ther array and then move those target numbers to the end of the array.
# O(n) time | O(n) space
def moveElementToEnd(array, toMove):
idx = 0
idj = len(array) - 1
# We've just made to pointers at the start and the end of the... | def move_element_to_end(array, toMove):
idx = 0
idj = len(array) - 1
while idx < idj:
while idx < idj and array[idj] == toMove:
idj -= 1
if array[idx] == toMove:
(array[idx], array[idj]) = (array[idj], array[idx])
idx += 1
return array
blah = move_element_... |
'''
Given head which is a reference node to a singly-linked list.
The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 ... | """
Given head which is a reference node to a singly-linked list.
The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 ... |
"""
Helper methods for binary package
Author: Ian Doarn
"""
def pad(value: str, return_type=str) -> """Pad binary value with zeros""":
if len(value) % 4 != 0:
pad_amount = 4 - (len(value) % 4)
return return_type(('0' * pad_amount) + value)
else:
return return_type(value)
def to_strin... | """
Helper methods for binary package
Author: Ian Doarn
"""
def pad(value: str, return_type=str) -> 'Pad binary value with zeros':
if len(value) % 4 != 0:
pad_amount = 4 - len(value) % 4
return return_type('0' * pad_amount + value)
else:
return return_type(value)
def to_string(binary_a... |
n=int(input())
s=input()
l,r=s.rfind('L')+1,s.find('R')+1
if r>0:
print(r,r+s.count('R'))
else:
print(l,l-s.count('L')) | n = int(input())
s = input()
(l, r) = (s.rfind('L') + 1, s.find('R') + 1)
if r > 0:
print(r, r + s.count('R'))
else:
print(l, l - s.count('L')) |
# Optimal Division
class Solution:
def optimalDivision(self, nums):
if len(nums) == 1:
return str(nums[0])
elif len(nums) == 2:
return f"{nums[0]}/{nums[1]}"
lhs = nums[0]
rhs = '/'.join(str(e) for e in nums[1:])
return f"{lhs}/({rhs})"
if __name__ =... | class Solution:
def optimal_division(self, nums):
if len(nums) == 1:
return str(nums[0])
elif len(nums) == 2:
return f'{nums[0]}/{nums[1]}'
lhs = nums[0]
rhs = '/'.join((str(e) for e in nums[1:]))
return f'{lhs}/({rhs})'
if __name__ == '__main__':
... |
class NotFoundException(Exception):
def __init__(self, name, regex_string):
self.name = name
self.regex_string = regex_string
def __str__(self):
return (
'No matches found about the following pattern.\n' +
'PATTERN_NAME: ' + repr(self.name) + '\n' +
... | class Notfoundexception(Exception):
def __init__(self, name, regex_string):
self.name = name
self.regex_string = regex_string
def __str__(self):
return 'No matches found about the following pattern.\n' + 'PATTERN_NAME: ' + repr(self.name) + '\n' + 'REGEX: ' + repr(self.regex_string)
... |
# Problem URL: https://leetcode.com/problems/sudoku-solver
class Solution:
def find_empty_loc(self, board, location_list):
for row in range(9):
for col in range(9):
if board[row][col] == '.':
location_list[0] = row
location_list[1]... | class Solution:
def find_empty_loc(self, board, location_list):
for row in range(9):
for col in range(9):
if board[row][col] == '.':
location_list[0] = row
location_list[1] = col
return True
return False
de... |
p1=input("Rock,Paper or Scissors: ")
p2=input("Rock,Paper or Scissors: ")
print("Player1 choosed ",p1)
print("Player2 choosed ",p2)
while p1=="Rock":
if p2=="Rock":
print("Game is equal")
elif p2=="Paper":
print("Winner is Player2")
elif p2=="Scissors":
print("Winner is player2")
... | p1 = input('Rock,Paper or Scissors: ')
p2 = input('Rock,Paper or Scissors: ')
print('Player1 choosed ', p1)
print('Player2 choosed ', p2)
while p1 == 'Rock':
if p2 == 'Rock':
print('Game is equal')
elif p2 == 'Paper':
print('Winner is Player2')
elif p2 == 'Scissors':
print('Winner is... |
input=__import__('sys').stdin.readline
n,m=map(int,input().split());d=[list(map(int,input().split())) for _ in range(n)]
for i in range(n):
for j in range(m):
if i==0 and j==0: continue
elif i==0: d[i][j]+=d[i][j-1]
elif j==0: d[i][j]+=d[i-1][j]
else: d[i][j]+=max(d[i-1][j-1],d[i][j-... | input = __import__('sys').stdin.readline
(n, m) = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(n)]
for i in range(n):
for j in range(m):
if i == 0 and j == 0:
continue
elif i == 0:
d[i][j] += d[i][j - 1]
elif j == 0:
d[i][j... |
# Part 1
def jump1(jumps):
j = jumps.split("\n")
l = []
for item in j:
l += [int(item)]
length = len(l)
loc = 0
counter = 0
while 0 <= loc and loc < length:
counter += 1
jump = l[loc]
l[loc] += 1
loc += jump
return(counter)
# Part 2
def jump2(jump... | def jump1(jumps):
j = jumps.split('\n')
l = []
for item in j:
l += [int(item)]
length = len(l)
loc = 0
counter = 0
while 0 <= loc and loc < length:
counter += 1
jump = l[loc]
l[loc] += 1
loc += jump
return counter
def jump2(jumps):
j = jumps.s... |
# list of random English nouns used for resource name utilities
words = [
'People',
'History',
'Way',
'Art',
'World',
'Information',
'Map',
'Two',
'Family',
'Government',
'Health',
'System',
'Computer',
'Meat',
'Year',
'Thanks',
'Music',
'Person',... | words = ['People', 'History', 'Way', 'Art', 'World', 'Information', 'Map', 'Two', 'Family', 'Government', 'Health', 'System', 'Computer', 'Meat', 'Year', 'Thanks', 'Music', 'Person', 'Reading', 'Method', 'Data', 'Food', 'Understanding', 'Theory', 'Law', 'Bird', 'Literature', 'Problem', 'Software', 'Control', 'Knowledge... |
"""
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is... | """
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is... |
#Problem URL: https://www.hackerrank.com/challenges/grading/problem
def gradingStudents(grades):
for x in range (0, len(grades)):
if(grades[x] >= 38):
difference = 5 - (grades[x] % 5)
if(difference < 3):
grades[x] += difference
return grades
| def grading_students(grades):
for x in range(0, len(grades)):
if grades[x] >= 38:
difference = 5 - grades[x] % 5
if difference < 3:
grades[x] += difference
return grades |
#!/usr/bin/env python
"""
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
def solve_fifteen():
return sum(int(x) for x in str(2 ** 1000))
def test_function():
assert solve_fifteen() == 1366
if __name__ == '__main__':
test_func... | """
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
def solve_fifteen():
return sum((int(x) for x in str(2 ** 1000)))
def test_function():
assert solve_fifteen() == 1366
if __name__ == '__main__':
test_function() |
def mul_by_2(num):
return num*2
def mul_by_3(num):
return num*3
| def mul_by_2(num):
return num * 2
def mul_by_3(num):
return num * 3 |
def severity2color(sev):
red = [0.674,0.322]
orange = [0.700,0.400]
yellow = [0.700, 0.500]
white = [0.350,0.350]
green = [0.408,0.517]
sevMap = {5:red, 4:orange, 3:yellow, 2:yellow, 1:white, 0:white, -1:white, -2:green}
return sevMap[sev]
| def severity2color(sev):
red = [0.674, 0.322]
orange = [0.7, 0.4]
yellow = [0.7, 0.5]
white = [0.35, 0.35]
green = [0.408, 0.517]
sev_map = {5: red, 4: orange, 3: yellow, 2: yellow, 1: white, 0: white, -1: white, -2: green}
return sevMap[sev] |
class Solution:
def minSteps(self, n):
ans = 0
while n >= 2:
facter = self.minFacter(n)
if facter is not None:
ans += facter
n /= facter
return int(ans)
def minFacter(self, n):
ans = None
for i in Primes.element... | class Solution:
def min_steps(self, n):
ans = 0
while n >= 2:
facter = self.minFacter(n)
if facter is not None:
ans += facter
n /= facter
return int(ans)
def min_facter(self, n):
ans = None
for i in Primes.elements... |
for _ in range(int(input())):
x, y , k = map(int, input().split(' '))
if x * y - 1 == k:
print("YES")
else:
print("NO")
| for _ in range(int(input())):
(x, y, k) = map(int, input().split(' '))
if x * y - 1 == k:
print('YES')
else:
print('NO') |
a = list()
for i in 'LastNightStudy':
if (i == 'i'):
pass
else:
a.append(i)
if a is not None:
print(a)
| a = list()
for i in 'LastNightStudy':
if i == 'i':
pass
else:
a.append(i)
if a is not None:
print(a) |
"""An iterative implementation for the sum of a list of numbers."""
def listsum1(nums):
accum = 0
for num in nums:
accum += num
return accum
def listsum2(nums):
accum = 0
i = 0
while i < len(nums):
accum += nums[i]
i += 1
return accum
def main():
print(lists... | """An iterative implementation for the sum of a list of numbers."""
def listsum1(nums):
accum = 0
for num in nums:
accum += num
return accum
def listsum2(nums):
accum = 0
i = 0
while i < len(nums):
accum += nums[i]
i += 1
return accum
def main():
print(listsum1... |
fin = open("input")
fout = open("output", "w")
n = int(fin.readline())
fout.write("#" * n)
fout.close()
| fin = open('input')
fout = open('output', 'w')
n = int(fin.readline())
fout.write('#' * n)
fout.close() |
"""
Demonstrates how numbers can be displayed with formatting.
The format function always returns a string-type, regardless
of if the value to be formatted is a float or int.
"""
#Example 1 - Formatting floats
amount_due = 15000.0
monthly_payment = amount_due / 12
print("The monthly payment is $", monthly_payment)
#F... | """
Demonstrates how numbers can be displayed with formatting.
The format function always returns a string-type, regardless
of if the value to be formatted is a float or int.
"""
amount_due = 15000.0
monthly_payment = amount_due / 12
print('The monthly payment is $', monthly_payment)
print('The monthly payment is $', ... |
# recursive
def pascal_triangle(n):
assert n >= 1
if n == 1:
return 1
elif n == 2:
return 1, 1
else:
x = pascal_helper(pascal_triangle(n-1))
x.insert(0, 1)
x.append(1)
return x
def pascal_helper(lst):
def helper():
for pair in zip(lst, lst[1:]... | def pascal_triangle(n):
assert n >= 1
if n == 1:
return 1
elif n == 2:
return (1, 1)
else:
x = pascal_helper(pascal_triangle(n - 1))
x.insert(0, 1)
x.append(1)
return x
def pascal_helper(lst):
def helper():
for pair in zip(lst, lst[1:]):
... |
class Pessoa:
def __init__(self,nome=None,idade=35,*filhos):
self.idade = idade
self.nome=nome
self.filhos=list(filhos)
def cumprimentar(self):
return 'ola'
@staticmethod
def estatico():
return 42
@classmethod
def nome_atributos_de_cl... | class Pessoa:
def __init__(self, nome=None, idade=35, *filhos):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return 'ola'
@staticmethod
def estatico():
return 42
@classmethod
def nome_atributos_de_classes(cls):... |
config = {
"DATA_DIR": "/data/temp_archive/",
"IRODS_ROOT": "/ZoneA/home/rods/",
"FDSNWS_ADDRESS": "http://rdsa-test.knmi.nl/fdsnws/station/1/query",
"MONGO": [
{
"NAME": "WFCatalog-daily",
"HOST": "wfcatalog_mongo",
"PORT": 27017,
"DATABASE": "wfr... | config = {'DATA_DIR': '/data/temp_archive/', 'IRODS_ROOT': '/ZoneA/home/rods/', 'FDSNWS_ADDRESS': 'http://rdsa-test.knmi.nl/fdsnws/station/1/query', 'MONGO': [{'NAME': 'WFCatalog-daily', 'HOST': 'wfcatalog_mongo', 'PORT': 27017, 'DATABASE': 'wfrepo', 'COLLECTION': 'daily_streams'}, {'NAME': 'WFCatalog-segments', 'HOST'... |
"""
3_problem.py
Rearrange Array Elements so as to form two numbers such that their sum
is maximum. Return these two numbers. You can assume that all array
elements are in the range [0, 9].
The number of digits in both the numbers cannot differ by more than 1.
You're not allowed to use any sorting function that Pytho... | """
3_problem.py
Rearrange Array Elements so as to form two numbers such that their sum
is maximum. Return these two numbers. You can assume that all array
elements are in the range [0, 9].
The number of digits in both the numbers cannot differ by more than 1.
You're not allowed to use any sorting function that Pytho... |
with open('day_10.txt') as f:
initial_sequence = f.read()
def parse_sequence(sequence):
"""
Take a sequence of numbers and parse them into a list, group the same
numbers into one element of the list
Args:
sequence (str): sequence of numbers
Returns:
list: parsed sequence, wh... | with open('day_10.txt') as f:
initial_sequence = f.read()
def parse_sequence(sequence):
"""
Take a sequence of numbers and parse them into a list, group the same
numbers into one element of the list
Args:
sequence (str): sequence of numbers
Returns:
list: parsed sequence, whe... |
def content():
topic_dict = {
"Basics": [["Introduction to Python", "/introduction-to-python-programming/"],
["Installing modules", "/installing-modules/"],
["Math basics", "/math-basics/"]],
"Web Dev": []
}
return topic_dict
| def content():
topic_dict = {'Basics': [['Introduction to Python', '/introduction-to-python-programming/'], ['Installing modules', '/installing-modules/'], ['Math basics', '/math-basics/']], 'Web Dev': []}
return topic_dict |
# Run in QGIS python console
settings = QSettings(QSettings.NativeFormat, QSettings.UserScope, 'QuantumGIS', 'QGis')
settings.setValue('/Projections/projectDefaultCrs', 'EPSG:2278')
settings.value('/Projections/projectDefaultCrs')
settings.sync()
| settings = q_settings(QSettings.NativeFormat, QSettings.UserScope, 'QuantumGIS', 'QGis')
settings.setValue('/Projections/projectDefaultCrs', 'EPSG:2278')
settings.value('/Projections/projectDefaultCrs')
settings.sync() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
SubConfKey = set(["dataset", "trainer", "model"])
class Config(object):
def __init__(self, d):
self.d = d
def __repr__(self):
return str(self.d)
def _get_main_conf(conf, d):
return {k: v for k, v in d.items() if k not in SubConfKey}
... | sub_conf_key = set(['dataset', 'trainer', 'model'])
class Config(object):
def __init__(self, d):
self.d = d
def __repr__(self):
return str(self.d)
def _get_main_conf(conf, d):
return {k: v for (k, v) in d.items() if k not in SubConfKey}
def __getattr__(self, name):
i... |
"""Python client for Arris DCX960."""
class ArrisDCX960ConnectionError(Exception):
pass
class ArrisDCX960AuthenticationError(Exception):
pass | """Python client for Arris DCX960."""
class Arrisdcx960Connectionerror(Exception):
pass
class Arrisdcx960Authenticationerror(Exception):
pass |
def _ceil_pow2(n: int) -> int:
x = 0
while (1 << x) < n:
x += 1
return x
def _bsf(n: int) -> int:
x = 0
while n % 2 == 0:
x += 1
n //= 2
return x
| def _ceil_pow2(n: int) -> int:
x = 0
while 1 << x < n:
x += 1
return x
def _bsf(n: int) -> int:
x = 0
while n % 2 == 0:
x += 1
n //= 2
return x |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = []
while root:
if not root.left:
... | class Solution:
def inorder_traversal(self, root: TreeNode) -> List[int]:
result = []
while root:
if not root.left:
result.append(root.val)
root = root.right
else:
predecessor = root.left
while predecessor.right... |
class LinkError(Exception):
"""
Base class for exceptions in linking module.
"""
NO_PROJECT = 'NO_PROJECT'
INVALID_TYPE = 'INVALID_TYPE'
TYPE_MISSING = 'TYPE_MISSING'
OUT_PATH_MISSING = 'OUT_PATH_MISSING'
NO_STEPS = 'NO_STEPS'
NAME_MISSING = 'NAME_MISSING'
DATASET_MISSING = '... | class Linkerror(Exception):
"""
Base class for exceptions in linking module.
"""
no_project = 'NO_PROJECT'
invalid_type = 'INVALID_TYPE'
type_missing = 'TYPE_MISSING'
out_path_missing = 'OUT_PATH_MISSING'
no_steps = 'NO_STEPS'
name_missing = 'NAME_MISSING'
dataset_missing = '... |
{
'targets' : [
#native
{
'target_name' : 'node_native',
'type' : 'static_library',
'nnative_use_openssl%': 'true',
'nnative_shared_openssl%': 'false',
'nnative_target_type%': 'static_library',
'variables': {
'nnativ... | {'targets': [{'target_name': 'node_native', 'type': 'static_library', 'nnative_use_openssl%': 'true', 'nnative_shared_openssl%': 'false', 'nnative_target_type%': 'static_library', 'variables': {'nnative_regex_name%': 're2'}, 'dependencies': ['../deps/libuv/uv.gyp:libuv', '../deps/http-parser/http_parser.gyp:http_parser... |
n = int(input())
mat = []
for i in range (n):
l = []
for j in range(n):
l.append(int(input()))
mat.append(l)
inver = []
for i in range (n):
inver.append(mat[i][i])
for i in range (n):
mat[i][i] = mat[i][n - 1 - i]
for j in range (len(mat)):
mat[j][n-1-j] = inver[j]
prin = []
for k in r... | n = int(input())
mat = []
for i in range(n):
l = []
for j in range(n):
l.append(int(input()))
mat.append(l)
inver = []
for i in range(n):
inver.append(mat[i][i])
for i in range(n):
mat[i][i] = mat[i][n - 1 - i]
for j in range(len(mat)):
mat[j][n - 1 - j] = inver[j]
prin = []
for k in ran... |
class JSONDecodeError(Exception):
pass
class APIErrorException(Exception):
error_code = 0
def get_error_code(self):
return self.error_code
def __init__(self, message, code, error_code, response_dict):
self.message = message
self.code = code
self.error_code = error_cod... | class Jsondecodeerror(Exception):
pass
class Apierrorexception(Exception):
error_code = 0
def get_error_code(self):
return self.error_code
def __init__(self, message, code, error_code, response_dict):
self.message = message
self.code = code
self.error_code = error_code... |
class Game:
def __init__(self,x=640,y=480):
self.x = x
self.y = y
pygame.init()
self.fps = pygame.time.Clock()
pygame.key.set_repeat(5,5)
self.window = pygame.display.set_mode((self.x,self.y))
pygame.display.set_caption('Russian game, Made in the UK, by an American.')
self.speed = 60
self.keys =... | class Game:
def __init__(self, x=640, y=480):
self.x = x
self.y = y
pygame.init()
self.fps = pygame.time.Clock()
pygame.key.set_repeat(5, 5)
self.window = pygame.display.set_mode((self.x, self.y))
pygame.display.set_caption('Russian game, Made in the UK, by a... |
class Calculadora(object):
"""docstring for Calculadora"""
memoria = 10
def suma(self,a, b):
return a + b
def resta(self,a, b):
return a - b
def multiplicacion(self,a, b):
return a * b
def division(self,a, b):
return a / b
@classmethod
def numerosPrimo... | class Calculadora(object):
"""docstring for Calculadora"""
memoria = 10
def suma(self, a, b):
return a + b
def resta(self, a, b):
return a - b
def multiplicacion(self, a, b):
return a * b
def division(self, a, b):
return a / b
@classmethod
def numeros... |
"""
Otrzymujesz dwa napisy. Sprawdz czy napisy sa swoimi rotacjami.
"""
# Wersja 1
def czy_rotacja_v1(slowo_a, slowo_b):
if len(slowo_a) != len(slowo_b):
return False
return (slowo_a + slowo_a).find(slowo_b) > -1
# Testy Poprawnosci
def test_1():
slowo_a = "malpka"
slowo_b = "kamapl"
a... | """
Otrzymujesz dwa napisy. Sprawdz czy napisy sa swoimi rotacjami.
"""
def czy_rotacja_v1(slowo_a, slowo_b):
if len(slowo_a) != len(slowo_b):
return False
return (slowo_a + slowo_a).find(slowo_b) > -1
def test_1():
slowo_a = 'malpka'
slowo_b = 'kamapl'
assert not czy_rotacja_v1(slowo_a, ... |
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i,len(arr)):
if arr[min_index] > arr[j]:
min_index = j
arr[i],arr[min_index] = arr[min_index],arr[i]
a = [25,12,7,10,8,23]
print(a)
selection_sort(a)
print(a) | def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i, len(arr)):
if arr[min_index] > arr[j]:
min_index = j
(arr[i], arr[min_index]) = (arr[min_index], arr[i])
a = [25, 12, 7, 10, 8, 23]
print(a)
selection_sort(a)
print(a) |
#
# PySNMP MIB module HH3C-TE-TUNNEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-TE-TUNNEL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
def maximo(x,y,z):
if x>=y:
if x>z:
return x
else:
return z
if y>=x:
if y>z:
return y
else:
return z
| def maximo(x, y, z):
if x >= y:
if x > z:
return x
else:
return z
if y >= x:
if y > z:
return y
else:
return z |
"""
Copyright (c) 2017 Wind River Systems, Inc.
SPDX-License-Identifier: Apache-2.0
"""
dev_certificate = b"""-----BEGIN CERTIFICATE-----
MIIDejCCAmKgAwIBAgICEAQwDQYJKoZIhvcNAQELBQAwQjELMAkGA1UEBhMCQ0Ex
EDAOBgNVBAgMB09udGFyaW8xITAfBgNVBAoMGFdpbmQgUml2ZXIgU3lzdGVtcywg
SW5jLjAeFw0xNzA4MTgxNDM3MjlaFw0yNzA4M... | """
Copyright (c) 2017 Wind River Systems, Inc.
SPDX-License-Identifier: Apache-2.0
"""
dev_certificate = b'-----BEGIN CERTIFICATE-----\n MIIDejCCAmKgAwIBAgICEAQwDQYJKoZIhvcNAQELBQAwQjELMAkGA1UEBhMCQ0Ex\n EDAOBgNVBAgMB09udGFyaW8xITAfBgNVBAoMGFdpbmQgUml2ZXIgU3lzdGVtcywg\n SW5jLjAeFw0xNzA4MTgxNDM3MjlaFw0yNzA4M... |
"""
class that represents a pool of votes
based on a dict(block_hash:vote)
"""
class VotePool():
pass
| """
class that represents a pool of votes
based on a dict(block_hash:vote)
"""
class Votepool:
pass |
text_file = open("test.txt", "r")
data = text_file.read()
print(data)
text_file.close()
| text_file = open('test.txt', 'r')
data = text_file.read()
print(data)
text_file.close() |
"""
Transformer to pre-process network input.
"""
class Transformer:
"""
A transformer transforms input data according to normalization and pre-processing best practices. The transformer
bundles several of these best practices.
"""
def __init__(self):
"""
Constructor, sets default ... | """
Transformer to pre-process network input.
"""
class Transformer:
"""
A transformer transforms input data according to normalization and pre-processing best practices. The transformer
bundles several of these best practices.
"""
def __init__(self):
"""
Constructor, sets default ... |
class ParameterStoreError(Exception):
"""
Raised when an interaction with Systems Manager Parameter Store fails.
"""
def __init__(self, name: str, reason: str, region: str) -> None:
msg = f"Failed to interact with parameter {name} in {region}: {reason}"
super().__init__(msg)
class Par... | class Parameterstoreerror(Exception):
"""
Raised when an interaction with Systems Manager Parameter Store fails.
"""
def __init__(self, name: str, reason: str, region: str) -> None:
msg = f'Failed to interact with parameter {name} in {region}: {reason}'
super().__init__(msg)
class Para... |
class PipHisto():
apps_list = []
def __init__(self, apps_list):
self.setApps(apps_list)
def print_pip_histo(self, apps_list=[], version=None, egg=None):
app_histo = self.pip_histo(apps_list, version, egg)
header_string = ''
if version:
header_string = ' | versi... | class Piphisto:
apps_list = []
def __init__(self, apps_list):
self.setApps(apps_list)
def print_pip_histo(self, apps_list=[], version=None, egg=None):
app_histo = self.pip_histo(apps_list, version, egg)
header_string = ''
if version:
header_string = ' | version'... |
# -*- coding: utf-8 -*-
"""
Make a two-player Rock-Paper-Scissors game.
(Hint: Ask for player plays (using input), compare them,
print out a message of congratulations to the winner,
and ask if the players want to start a new game)
"""
def StartGame():
A = "Player A wins!"
B = "Player B wins!"
while Tr... | """
Make a two-player Rock-Paper-Scissors game.
(Hint: Ask for player plays (using input), compare them,
print out a message of congratulations to the winner,
and ask if the players want to start a new game)
"""
def start_game():
a = 'Player A wins!'
b = 'Player B wins!'
while True:
choice_a = i... |
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
if len(nums) == 1: return nums[0]
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left)//2
if mid != 0 and mid < len(nums)-1:
i... | class Solution:
def single_non_duplicate(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
(left, right) = (0, len(nums) - 1)
while left <= right:
mid = left + (right - left) // 2
if mid != 0 and mid < len(nums) - 1:
if nums... |
class Client1CException(Exception):
""" Base exception for all exceptions in the client_1C_timesheet package
"""
pass
| class Client1Cexception(Exception):
""" Base exception for all exceptions in the client_1C_timesheet package
"""
pass |
'''The goal is to determine if two strings are anagrams of each other.
An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).
For example:
"rat" is an anagram of "art"
"alert" is an anagram of "alter"
"Slot machines" is an anagram of "Cash lost in me"
functio... | """The goal is to determine if two strings are anagrams of each other.
An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).
For example:
"rat" is an anagram of "art"
"alert" is an anagram of "alter"
"Slot machines" is an anagram of "Cash lost in me"
functio... |
def mx_cc_copts():
return ["-fdiagnostics-color=always", "-Werror"]
def mx_cuda_copts():
return ["-xcuda", "-std=c++11"]
def mx_cc_library(
name,
srcs = [],
deps = [],
copts = [],
**kwargs):
native.cc_library(
name = name,
copts = mx_cc_copts() + c... | def mx_cc_copts():
return ['-fdiagnostics-color=always', '-Werror']
def mx_cuda_copts():
return ['-xcuda', '-std=c++11']
def mx_cc_library(name, srcs=[], deps=[], copts=[], **kwargs):
native.cc_library(name=name, copts=mx_cc_copts() + copts, srcs=srcs, deps=deps, **kwargs)
def mx_cc_binary(name, srcs=[],... |
"""
0621. Task Scheduler
You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. Each task is done in one unit of time. For each unit of time, the CPU could complete eithe... | """
0621. Task Scheduler
You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. Each task is done in one unit of time. For each unit of time, the CPU could complete eithe... |
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
counts1 = self.calcCounts(nums1)
counts2 = self.calcCounts(nums2)
intersection = set(counts1.keys()) & set(counts2.keys(... | class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
counts1 = self.calcCounts(nums1)
counts2 = self.calcCounts(nums2)
intersection = set(counts1.keys()) & set(counts2.keys(... |
class UndergroundSystem:
def __init__(self):
# {id: (stationName, time)}
self.checkIns = {}
# {route: (numTrips, totalTime)}
self.checkOuts = defaultdict(lambda: [0, 0])
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.checkIns[id] = (stationName, t)
def checkOut(self, id: ... | class Undergroundsystem:
def __init__(self):
self.checkIns = {}
self.checkOuts = defaultdict(lambda : [0, 0])
def check_in(self, id: int, stationName: str, t: int) -> None:
self.checkIns[id] = (stationName, t)
def check_out(self, id: int, stationName: str, t: int) -> None:
... |
class INotifyDataErrorInfo:
# no doc
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return INotifyDataErrorInfo()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def GetErrors(self,propertyName):
""" GetErrors(self: INotifyDataErrorInfo,propertyName: str) -> IEnumerable """... | class Inotifydataerrorinfo:
def zzz(self):
"""hardcoded/mock instance of the class"""
return i_notify_data_error_info()
instance = zzz()
'hardcoded/returns an instance of the class'
def get_errors(self, propertyName):
""" GetErrors(self: INotifyDataErrorInfo,propertyName: str) ... |
# Coding Question: Given JSON object that have marks of students, create a json object that returns the average marks in each subject
class StudentRecords:
'Student records management'
def getAverageMarks(self, total_students_dict):
Total = {}
student_marks_list = []
total_students = len(total_st... | class Studentrecords:
"""Student records management"""
def get_average_marks(self, total_students_dict):
total = {}
student_marks_list = []
total_students = len(total_students_dict)
for (k, v) in total_students_dict.items():
marks__list = list(v.values())
... |
testing=False
interval=900
static=False
staticColor =(0, 0, 255)
nightmode=False
beginSleep=21
stopSleep=4
# LED Strip Config
# If you use the Waveshare LED HAT, recommended on GitHub, you should not need to change these
LED_COUNT = 32
LED_PIN = 18
LED_FREQ_HZ = 800000
LED_DMA = 5
LED_BRIGHTNESS = 100
LED_INVERT = Fa... | testing = False
interval = 900
static = False
static_color = (0, 0, 255)
nightmode = False
begin_sleep = 21
stop_sleep = 4
led_count = 32
led_pin = 18
led_freq_hz = 800000
led_dma = 5
led_brightness = 100
led_invert = False |
"""
CCC '17 J1 - Quadrant Selection
Find this problem at:
https://dmoj.ca/problem/ccc17j1
"""
x, y = int(input()), int(input())
if x > 0 and y > 0:
print(1)
elif x < 0 and y > 0:
print(2)
elif x < 0 and y < 0:
print(3)
elif x > 0 and y < 0:
print(4)
| """
CCC '17 J1 - Quadrant Selection
Find this problem at:
https://dmoj.ca/problem/ccc17j1
"""
(x, y) = (int(input()), int(input()))
if x > 0 and y > 0:
print(1)
elif x < 0 and y > 0:
print(2)
elif x < 0 and y < 0:
print(3)
elif x > 0 and y < 0:
print(4) |
"""
This holds the current game state. The board is in a grid shape with 0-based
row and column indices represented by (row, column) Cells:
(0, 0), (0, 1), (0, 2), ..., (0, COLUMNS - 1)
(1, 0), (1, 1), (1, 2), ..., (1, COLUMNS - 1)
...
(ROWS - 1, 0), (ROWS - 1, 1), ..., (ROWS - 1, COLUMNS - 1)
"""
ROWS = 10
COLUMNS =... | """
This holds the current game state. The board is in a grid shape with 0-based
row and column indices represented by (row, column) Cells:
(0, 0), (0, 1), (0, 2), ..., (0, COLUMNS - 1)
(1, 0), (1, 1), (1, 2), ..., (1, COLUMNS - 1)
...
(ROWS - 1, 0), (ROWS - 1, 1), ..., (ROWS - 1, COLUMNS - 1)
"""
rows = 10
columns = ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 11:46:15 2017
@author: johnkenny
Player class used to create player objects
"""
#used to create players
class Player(object):
#constructer to match the pl json api lib attritubes
def __init__(self, dbid, f_name, l_name, team, pos,... | """
Created on Fri Dec 29 11:46:15 2017
@author: johnkenny
Player class used to create player objects
"""
class Player(object):
def __init__(self, dbid, f_name, l_name, team, pos, goals, assits, saves, clean_sheets, number, goals_conceded, own_goals, penalties_saved, photo, penalties_missed, yellow_cards, red_... |
#!/usr/bin/env python3
if __name__ == "__main__":
a = [-1, 1, 66.25, 333, 333, 1234.5]
print(a)
del a[0]
print(a)
del a[2:4]
print(a)
del a[:]
print(a)
del a
# Below causes an error since 'a' is no more available
# print(a)
| if __name__ == '__main__':
a = [-1, 1, 66.25, 333, 333, 1234.5]
print(a)
del a[0]
print(a)
del a[2:4]
print(a)
del a[:]
print(a)
del a |
fp = open("./packet.csv", "r")
vals = fp.readlines()
count = 1
pre_val = 0
current = 0
val_bins = []
for i in range(len(vals)):
pre_val = current
current = int(vals[i])
if current == pre_val:
count = count + 1
else:
count = 1
if count == 31:
print(pre_val)
val_bi... | fp = open('./packet.csv', 'r')
vals = fp.readlines()
count = 1
pre_val = 0
current = 0
val_bins = []
for i in range(len(vals)):
pre_val = current
current = int(vals[i])
if current == pre_val:
count = count + 1
else:
count = 1
if count == 31:
print(pre_val)
val_bins.ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.