content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
n = int(input())
total = 1
while n != 0:
total *= n
n -= 1
print(n)
print(total) | n = int(input())
total = 1
while n != 0:
total *= n
n -= 1
print(n)
print(total) |
# https://leetcode.com/problems/matrix-diagonal-sum/
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
res = 0
i, j = 0, 0
while (j < len(mat)):
#print(i,j)
res += mat[i][j]
i += 1
j += 1
i, j = 0, len(m... | class Solution:
def diagonal_sum(self, mat: List[List[int]]) -> int:
res = 0
(i, j) = (0, 0)
while j < len(mat):
res += mat[i][j]
i += 1
j += 1
(i, j) = (0, len(mat) - 1)
while j >= 0:
if i != j:
res += mat[i][j... |
def test():
print('\nNON-NESTED BLOCK COMMENT EXAMPLE:')
sample = ''' /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function s... | def test():
print('\nNON-NESTED BLOCK COMMENT EXAMPLE:')
sample = ' /**\n * Some comments\n * longer comments here that we can parse.\n *\n * Rahoo\n */\n function subroutine() {\n a = /* inline comment */ b + c ;\n }\n /*/ <-- tricky comments */\n\n /**\n * Another comment.\n */\n ... |
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
window = collections.deque()
ans = []
for i, num in enumerate(nums):
while window and num >= window[-1][0]:
window.pop()
window.append((num, i))
if i - window... | class Solution:
def max_sliding_window(self, nums: List[int], k: int) -> List[int]:
window = collections.deque()
ans = []
for (i, num) in enumerate(nums):
while window and num >= window[-1][0]:
window.pop()
window.append((num, i))
if i - w... |
#Tuples - faster Lists you can't change
friends = ['John','Michael','Terry','Eric','Graham']
friends_tuple = ('John','Michael','Terry','Eric','Graham')
print(friends)
print(friends_tuple)
print(friends[2:4])
print(friends_tuple[2:4]) | friends = ['John', 'Michael', 'Terry', 'Eric', 'Graham']
friends_tuple = ('John', 'Michael', 'Terry', 'Eric', 'Graham')
print(friends)
print(friends_tuple)
print(friends[2:4])
print(friends_tuple[2:4]) |
t1 = 0
t2 = 1
print(f'{t1} -> {t2} -> ', end='')
for c in range(1, 21):
t3 = t1 + t2
print(f'{t3} -> ', end='')
t1 = t2
t2 = t3
print('FIM', end='') | t1 = 0
t2 = 1
print(f'{t1} -> {t2} -> ', end='')
for c in range(1, 21):
t3 = t1 + t2
print(f'{t3} -> ', end='')
t1 = t2
t2 = t3
print('FIM', end='') |
# COLORS = ['V', 'I', 'B', 'G', 'Y', 'O', 'R']
EMPTY = "-"
# DIRS = np.array([(1, 0), (0, -1), (-1, 0), (0, 1)])
RIGHTMOST = -1
def is_color(board, x, y, color):
if min(x, y) < 0:
return False
if x >= len(board):
return False
if y >= len(board[0]):
return False
if board[x][y] !... | empty = '-'
rightmost = -1
def is_color(board, x, y, color):
if min(x, y) < 0:
return False
if x >= len(board):
return False
if y >= len(board[0]):
return False
if board[x][y] != color:
return False
return True
def get_group(board, x, y):
color = board[x][y]
... |
def solveQuestion(inputPath, minValComp, maxValComp):
fileP = open(inputPath, 'r')
fileLines = fileP.readlines()
fileP.close()
botMoves = {}
botValues = {}
for line in fileLines:
line = line.strip('\n')
isLowOutput = False
isHighOutput = False
if line[:... | def solve_question(inputPath, minValComp, maxValComp):
file_p = open(inputPath, 'r')
file_lines = fileP.readlines()
fileP.close()
bot_moves = {}
bot_values = {}
for line in fileLines:
line = line.strip('\n')
is_low_output = False
is_high_output = False
if line[:5]... |
def Mergesort(arr):
n= len(arr)
if n > 1:
mid = int(n/2)
left = arr[0:mid]
right = arr[mid:n]
Mergesort(left)
Mergesort(right)
Merge(left, right, arr)
def Merge(left, right, arr):
i = 0
j = 0
k = 0
while i < len(left) an... | def mergesort(arr):
n = len(arr)
if n > 1:
mid = int(n / 2)
left = arr[0:mid]
right = arr[mid:n]
mergesort(left)
mergesort(right)
merge(left, right, arr)
def merge(left, right, arr):
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
... |
a = [5, 4, 8, 3, 4, 14, 90, 45, 9, 3, 2, 4]
for i in range(len(a), 0, -1):
for j in range(0, i - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
print(a) | a = [5, 4, 8, 3, 4, 14, 90, 45, 9, 3, 2, 4]
for i in range(len(a), 0, -1):
for j in range(0, i - 1):
if a[j] > a[j + 1]:
(a[j], a[j + 1]) = (a[j + 1], a[j])
print(a) |
# MEDIUM
# find smallest x, largest x, draw a line to split those two value
# store all points in to a set([])
# check if every point in set can be matched by mirroring the y axis
class Solution:
def isReflected(self, points: List[List[int]]) -> bool:
print(max(points),min(points))
check = set([(... | class Solution:
def is_reflected(self, points: List[List[int]]) -> bool:
print(max(points), min(points))
check = set([(x, y) for (x, y) in points])
count = 0
(minx, maxx) = (float('inf'), -float('inf'))
for (x, y) in points:
minx = min(minx, x)
maxx =... |
def is_prime(num):
if num <= 1:
return False
d = 2
while d * d <= num and num % d != 0:
d += 1
return d * d > num | def is_prime(num):
if num <= 1:
return False
d = 2
while d * d <= num and num % d != 0:
d += 1
return d * d > num |
c = 0
arr = [8,7,3,2,1,8,18,9,7,3,4]
for i in range(len(arr)):
if arr.count(i) == 1:
c += 1
print(c)
| c = 0
arr = [8, 7, 3, 2, 1, 8, 18, 9, 7, 3, 4]
for i in range(len(arr)):
if arr.count(i) == 1:
c += 1
print(c) |
# coding=UTF8
# Processamento
for num in range(100, 201):
if num % 2 > 0:
print(num) | for num in range(100, 201):
if num % 2 > 0:
print(num) |
## https://leetcode.com/submissions/detail/230651834/
## problem is to find the numbers between 1 and length of the
## array that aren't in the array. simple way to do that is to
## do the set difference between range(1, len(ar)+1) and the
## input numbers
## hits 98th percentile in terms of runtime, though only
... | class Solution:
def find_disappeared_numbers(self, nums: List[int]) -> List[int]:
return list(set(range(1, len(nums) + 1)) - set(nums)) |
player_1_score = 0
player_2_score = 0
LOOP_UNTIL_USER_CHOOSES_TO_EXIT_AFTER_A_ROUND = True
while LOOP_UNTIL_USER_CHOOSES_TO_EXIT_AFTER_A_ROUND:
player_1_shape = input('[PLAYER 1]: Choose "rock", "paper", or "scissors": ')
player_2_shape = input('[PLAYER 2]: Choose "rock", "paper", or "scissors": ')
ROCK_S... | player_1_score = 0
player_2_score = 0
loop_until_user_chooses_to_exit_after_a_round = True
while LOOP_UNTIL_USER_CHOOSES_TO_EXIT_AFTER_A_ROUND:
player_1_shape = input('[PLAYER 1]: Choose "rock", "paper", or "scissors": ')
player_2_shape = input('[PLAYER 2]: Choose "rock", "paper", or "scissors": ')
rock_sha... |
#isdecimal
n1 = "947"
print(n1.isdecimal()) # -- D1
n2 = "947 2"
print(n2.isdecimal()) # -- D2
n3 = "abx123"
print(n3.isdecimal()) # -- D3
n4 = "\u0034"
print(n4.isdecimal()) # -- D4
n5 = "\u0038"
print(n5.isdecimal()) # -- D5
n6 = "\u0041"
print(n6.isdecimal()) # -- D6
n7 = "3.4"
print(n7.isdecimal()) # -- D7
n8 = "#$... | n1 = '947'
print(n1.isdecimal())
n2 = '947 2'
print(n2.isdecimal())
n3 = 'abx123'
print(n3.isdecimal())
n4 = '4'
print(n4.isdecimal())
n5 = '8'
print(n5.isdecimal())
n6 = 'A'
print(n6.isdecimal())
n7 = '3.4'
print(n7.isdecimal())
n8 = '#$!@'
print(n8.isdecimal()) |
def memoize(f):
storage = {}
def wrapper(*args):
key = tuple(args)
if storage.has_key(key):
return storage[key]
else:
result = f(*args)
storage[key] = result
return result
return wrapper
def test_memoize():
@memoize
def sil... | def memoize(f):
storage = {}
def wrapper(*args):
key = tuple(args)
if storage.has_key(key):
return storage[key]
else:
result = f(*args)
storage[key] = result
return result
return wrapper
def test_memoize():
@memoize
def silly... |
# Fitur .append()
print(">>> Fitur .append()")
list_makanan = ['Gado-gado', 'Ayam Goreng', 'Rendang']
list_makanan.append('Ketoprak')
print(list_makanan)
# Fitur .clear()
print(">>> Fitur .clear()")
list_makanan = ['Gado-gado', 'Ayam Goreng', 'Rendang']
list_makanan.clear()
print(list_makanan)
# Fitur .copy()
print(">>... | print('>>> Fitur .append()')
list_makanan = ['Gado-gado', 'Ayam Goreng', 'Rendang']
list_makanan.append('Ketoprak')
print(list_makanan)
print('>>> Fitur .clear()')
list_makanan = ['Gado-gado', 'Ayam Goreng', 'Rendang']
list_makanan.clear()
print(list_makanan)
print('>>> Fitur .copy()')
list_makanan1 = ['Gado-gado', 'Ay... |
#!/usr/bin/python
# coding=utf-8
class BasicGenerater(object):
def __init__(self):
self.first_name = 'Jack'
self.last_name = 'Freeman'
def my_name(self):
print('.'.join((self.first_name, self.last_name)))
def __del__(self):
print("call del")
class AdvaceGenerator(BasicGe... | class Basicgenerater(object):
def __init__(self):
self.first_name = 'Jack'
self.last_name = 'Freeman'
def my_name(self):
print('.'.join((self.first_name, self.last_name)))
def __del__(self):
print('call del')
class Advacegenerator(BasicGenerater):
def __init__(self):... |
class Solution:
def change(self, amount, coins):
dp = [0 for i in range(amount + 1)]
# for amount 0, you can have 1 combination, do not include any coin
dp[0] = 1
for coin in coins:
for i in range(coin, amount + 1):
# add i - coin dp value, the number of c... | class Solution:
def change(self, amount, coins):
dp = [0 for i in range(amount + 1)]
dp[0] = 1
for coin in coins:
for i in range(coin, amount + 1):
dp[i] += dp[i - coin]
return dp[amount]
def main():
my_sol = solution()
print('For the coins 1, 2,... |
class UI:
def __init__(self):
'''
'''
print('Welcome to calculator v1')
def start(self, controller):
'''
We ask the user for 2 numbers and add them.
'''
print('Please enter number1')
number1 = input()
print('Please enter number2')
number2 = input()
result = control... | class Ui:
def __init__(self):
"""
"""
print('Welcome to calculator v1')
def start(self, controller):
"""
We ask the user for 2 numbers and add them.
"""
print('Please enter number1')
number1 = input()
print('Please enter number2')
number2 = i... |
DEBUG = True
TESTING = False
MONGODB_SETTINGS = [{
'host':'localhost',
'port':27017,
'db':'REALTIME_APP'
}] | debug = True
testing = False
mongodb_settings = [{'host': 'localhost', 'port': 27017, 'db': 'REALTIME_APP'}] |
# Week-11 Challenge 1 And Extra Challenge
x = open("Week-11/Week-11-Challenge.txt", "r")
print(x.read())
x.close()
print("\n-*-*-*-*-*-*")
print("-*-*-*-*-*-*")
print("-*-*-*-*-*-*\n")
y = open("Week-11/Week-11-Challenge.txt", "a")
y.write("\nThe best way we learn anything is by practice and exercise questions ")
y =... | x = open('Week-11/Week-11-Challenge.txt', 'r')
print(x.read())
x.close()
print('\n-*-*-*-*-*-*')
print('-*-*-*-*-*-*')
print('-*-*-*-*-*-*\n')
y = open('Week-11/Week-11-Challenge.txt', 'a')
y.write('\nThe best way we learn anything is by practice and exercise questions ')
y = open('Week-11/Week-11-Challenge.txt', 'r')
... |
'''
Note: This kata is inspired by Convert a Number to a String!. Try that one too.
Description
We need a function that can transform a string into a number. What ways of achieving this do you know?
Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral numb... | """
Note: This kata is inspired by Convert a Number to a String!. Try that one too.
Description
We need a function that can transform a string into a number. What ways of achieving this do you know?
Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral numb... |
print(-1)
print(-0)
print(-(6))
print(-(12*2))
print(- -10)
| print(-1)
print(-0)
print(-6)
print(-(12 * 2))
print(--10) |
# Problem Statement: https://leetcode.com/problems/valid-anagram/
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
else:
letter_cnt = {}
for letter in s:
if not letter in letter_cnt:
... | class Solution:
def is_anagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
else:
letter_cnt = {}
for letter in s:
if not letter in letter_cnt:
letter_cnt[letter] = 1
else:
... |
# -*- coding: utf-8 -*-
description = 'detectors'
group = 'lowlevel' # is included by panda.py
display_order = 70
excludes = ['qmesydaq']
tango_base = 'tango://phys.panda.frm2:10000/panda/'
devices = dict(
timer = device('nicos.devices.entangle.TimerChannel',
tangodevice = tango_base + 'frmctr2/timer... | description = 'detectors'
group = 'lowlevel'
display_order = 70
excludes = ['qmesydaq']
tango_base = 'tango://phys.panda.frm2:10000/panda/'
devices = dict(timer=device('nicos.devices.entangle.TimerChannel', tangodevice=tango_base + 'frmctr2/timer', visibility=()), mon1=device('nicos.devices.entangle.CounterChannel', ta... |
expected_output = {
"key_chains": {
"bla": {
"keys": {
1: {
"accept_lifetime": {
"end": "always valid",
"is_valid": True,
"start": "always valid",
},
... | expected_output = {'key_chains': {'bla': {'keys': {1: {'accept_lifetime': {'end': 'always valid', 'is_valid': True, 'start': 'always valid'}, 'key_string': 'cisco123', 'send_lifetime': {'end': 'always valid', 'is_valid': True, 'start': 'always valid'}}, 2: {'accept_lifetime': {'end': '06:01:00 UTC Jan 1 2010', 'is_vali... |
# Challenge 3 : Write a function called delete_starting_evens() that has a parameter named lst.
# The function should remove elements from the front of lst until the front of the list is not even.
# The function should then return lst.
# Date : Sun 07 Jun 2020 07:21:17 AM IST
def de... | def delete_starting_evens(lst):
while len(lst) != 0 and lst[0] % 2 == 0:
del lst[0]
return lst
print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
print(delete_starting_evens([4, 8, 10])) |
def test(n):
i = 0
res = 0
while i < n:
i = i + 1
print(res)
test(100)
| def test(n):
i = 0
res = 0
while i < n:
i = i + 1
print(res)
test(100) |
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
vegetables = ["rucula", "tomate", "lechuga", "acelga"];
print(vegetables);
print(len(vegetables));
print(str(type(vegetables)));
print('-'*10);
print(vegetables[0]); # Elemento 0
print(vegetables[1:]... | vegetables = ['rucula', 'tomate', 'lechuga', 'acelga']
print(vegetables)
print(len(vegetables))
print(str(type(vegetables)))
print('-' * 10)
print(vegetables[0])
print(vegetables[1:])
print(vegetables[2:])
print(vegetables[0:10000])
print(vegetables[:])
print(vegetables[1:3][::-1])
print('-' * 10)
vegetables.append('be... |
class DashboardMixin(object):
def getTitle(self):
raise NotImplementedError("You must override this method in a child class.")
def getContent(self):
raise NotImplementedError("You must override this method in a child class.")
| class Dashboardmixin(object):
def get_title(self):
raise not_implemented_error('You must override this method in a child class.')
def get_content(self):
raise not_implemented_error('You must override this method in a child class.') |
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
def toChar(n):
return chr(97 + n - 1)
ans = [''] * n
i = 0
while i < n:
# how many spaces left to fill?
left = n - i
if k < left:
# you got `left` spac... | class Solution:
def get_smallest_string(self, n: int, k: int) -> str:
def to_char(n):
return chr(97 + n - 1)
ans = [''] * n
i = 0
while i < n:
left = n - i
if k < left:
pass
if k - 26 < left - 1:
ans[i]... |
def version():
if __grains__['os'] == 'eos':
res = __salt__['napalm.pyeapi_run_commands']('show version')
return res[0]['version']
else:
return 'Not supported on this platform'
def model():
if __grains__['os'] == 'eos':
res = __salt__['napalm.pyeapi_run_commands']('show vers... | def version():
if __grains__['os'] == 'eos':
res = __salt__['napalm.pyeapi_run_commands']('show version')
return res[0]['version']
else:
return 'Not supported on this platform'
def model():
if __grains__['os'] == 'eos':
res = __salt__['napalm.pyeapi_run_commands']('show vers... |
class digested_sequence:
def __init__(ds, sticky0, sticky1, sequence):
# Both sticky ends (left and right, respectively) encoded based on sticky stranded alphabet with respect to top sequence.
ds.sticky0 = sticky0
ds.sticky1 = sticky1
# Top sequence between two sticky ends
ds.sequence = sequence
| class Digested_Sequence:
def __init__(ds, sticky0, sticky1, sequence):
ds.sticky0 = sticky0
ds.sticky1 = sticky1
ds.sequence = sequence |
class Publication:
def __init__(self, title, price):
self.title = title
self.price = price
class Periodical(Publication):
def __init__(self, title, publisher, price, period):
Publication.__init__(self, title, price)
self.period = period
self.publisher = publisher
clas... | class Publication:
def __init__(self, title, price):
self.title = title
self.price = price
class Periodical(Publication):
def __init__(self, title, publisher, price, period):
Publication.__init__(self, title, price)
self.period = period
self.publisher = publisher
clas... |
def configurations():
return {
"components": {
"kvstore": False,
"web": True,
"indexing": False,
"dmc": True
}
} | def configurations():
return {'components': {'kvstore': False, 'web': True, 'indexing': False, 'dmc': True}} |
#!/bin/python3
if __name__ == '__main__':
n = int(input())
english = list(map(int, input().split(' ')))
b = int(input())
french = list(map(int, input().split(' ')))
students = set(english).difference(french)
print(len(students))
| if __name__ == '__main__':
n = int(input())
english = list(map(int, input().split(' ')))
b = int(input())
french = list(map(int, input().split(' ')))
students = set(english).difference(french)
print(len(students)) |
class Ssh:
def __init__(self,user,server,port,mode):
self.user=user
self.server=server
self.port=port
self.mode=mode
@classmethod
def fromconfig(cls, config):
propbag={}
for key, item in config:
if key.strip()[0] == ";":
continue
... | class Ssh:
def __init__(self, user, server, port, mode):
self.user = user
self.server = server
self.port = port
self.mode = mode
@classmethod
def fromconfig(cls, config):
propbag = {}
for (key, item) in config:
if key.strip()[0] == ';':
... |
def extractLizonkanovelsWordpressCom(item):
'''
Parser for 'lizonkanovels.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('bestial blade by priest', ... | def extract_lizonkanovels_wordpress_com(item):
"""
Parser for 'lizonkanovels.wordpress.com'
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [('bestial blade by priest', 'bestial ... |
def debug( content ):
print( "[*] " + str(content) , flush=True)
def bad( content ):
print( "[-] " + str(content) , flush=True)
def good( content ):
print( "[+] " + str(content) , flush=True)
# sample output:
# [*] Gimme yo money
# [-] Money taken by chad.
# [+] Chad receives the money.
| def debug(content):
print('[*] ' + str(content), flush=True)
def bad(content):
print('[-] ' + str(content), flush=True)
def good(content):
print('[+] ' + str(content), flush=True) |
# API Error Codes
AUTHORIZATION_FAILED = 5 # Invalid access token
PERMISSION_IS_DENIED = 7
CAPTCHA_IS_NEEDED = 14
ACCESS_DENIED = 15 # No access to call this method
INVALID_USER_ID = 113 # User deactivated
class VkException(Exception):
pass
class VkAuthError(VkException):
pass
class VkA... | authorization_failed = 5
permission_is_denied = 7
captcha_is_needed = 14
access_denied = 15
invalid_user_id = 113
class Vkexception(Exception):
pass
class Vkautherror(VkException):
pass
class Vkapierror(VkException):
__slots__ = ['error', 'code', 'message', 'request_params', 'redirect_uri']
captcha_n... |
def read_ims_legacy(name):
data = {}
dls = []
#should read in .tex file
infile = open(name + ".tex")
instring = infile.read()
##instring = instring.replace(':description',' :citation') ## to be deprecated soon
instring = unicode(instring,'utf-8')
meta = {}
metatxt = instri... | def read_ims_legacy(name):
data = {}
dls = []
infile = open(name + '.tex')
instring = infile.read()
instring = unicode(instring, 'utf-8')
meta = {}
metatxt = instring.split('::')[1]
meta['record_txt'] = '::' + metatxt.strip() + '\n\n'
(meta['bibtype'], rest) = metatxt.split(None, 1)
... |
first_line = input().split()
second_line = input().split()
third_line = input().split()
board_list = [
first_line,
second_line,
third_line
]
first = '1'
second = '2'
empty = '0'
first_win = [first] * 3
second_win = [second] * 3
is_first_player = False
is_second_player = False
diagonal... | first_line = input().split()
second_line = input().split()
third_line = input().split()
board_list = [first_line, second_line, third_line]
first = '1'
second = '2'
empty = '0'
first_win = [first] * 3
second_win = [second] * 3
is_first_player = False
is_second_player = False
diagonals = [board_list[0][0], board_list[1][... |
try:
count = int(input("Give me a number: "))
except ValueError:
print("That's not a number!")
else:
print("Hi " * count) | try:
count = int(input('Give me a number: '))
except ValueError:
print("That's not a number!")
else:
print('Hi ' * count) |
x = int(input())
dentro = fora = 0
for y in range(0, x, 1):
num = int(input())
if num >= 10 and num <= 20:
dentro += 1
else:
fora += 1;
print('{} in'.format(dentro))
print('{} out'.format(fora)) | x = int(input())
dentro = fora = 0
for y in range(0, x, 1):
num = int(input())
if num >= 10 and num <= 20:
dentro += 1
else:
fora += 1
print('{} in'.format(dentro))
print('{} out'.format(fora)) |
#
# PySNMP MIB module NNCFRINTSTATISTICS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NNCFRINTSTATISTICS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:23:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
def betterSurround(st):
st = list(st)
if st[0]!= '+' and st[len(st)-1]!= '=':
return False
else:
for i in range(0,len(st)):
if st[i].isalpha():
if not (st[i-1]=='+' or st[i-1]=='=') and (st[i+1] == '+' or st[i+1] == '='):
return false
... | def better_surround(st):
st = list(st)
if st[0] != '+' and st[len(st) - 1] != '=':
return False
else:
for i in range(0, len(st)):
if st[i].isalpha():
if not (st[i - 1] == '+' or st[i - 1] == '=') and (st[i + 1] == '+' or st[i + 1] == '='):
retu... |
for i in range(4):
outfile = 'paramslist.txt'
params = [0, 1, 2]
with open(outfile, 'a+') as f:
for param in params:
f.write(str(param))
f.write(' ')
f.write('\n')
| for i in range(4):
outfile = 'paramslist.txt'
params = [0, 1, 2]
with open(outfile, 'a+') as f:
for param in params:
f.write(str(param))
f.write(' ')
f.write('\n') |
# ParPy: A python natural language
# parser based on the one used
# by Zork, for use in Python games
# Copyright (c) Finn Lancaster 2021
# This file contains the BASE action words
# accepted by the users program. For example
# , take, move, etc.
# ParPy handles similar entries and conversion
# to program-accepted one... | recognized_terms = [('', ''), ('', '')] |
config = {
'matrikkel_zip_files': [{
'zip_name': 'Y:/kartdata/Matrikkeldata/SOSIuttrekk/07_Vestfold/0709_Larvik/UTM32_Euref89/Shape/32_Matrikkeldata_0709.zip',
'target_shape_prefix': '32_0709adresse_punkt'
},{
'zip_name': 'Y:/kartdata/Matrikkeldata/SOSIuttrekk/07_Vestfold/0706_Sandefjord/UTM32_Euref89/Shape/32_... | config = {'matrikkel_zip_files': [{'zip_name': 'Y:/kartdata/Matrikkeldata/SOSIuttrekk/07_Vestfold/0709_Larvik/UTM32_Euref89/Shape/32_Matrikkeldata_0709.zip', 'target_shape_prefix': '32_0709adresse_punkt'}, {'zip_name': 'Y:/kartdata/Matrikkeldata/SOSIuttrekk/07_Vestfold/0706_Sandefjord/UTM32_Euref89/Shape/32_Matrikkelda... |
'''
Gets memory usage of Linux python process
Tyson Jones, Nov 2017
tyson.jones@materials.ox.ac.uk
'''
_FIELDS = ['VmRSS', 'VmHWM', 'VmSize', 'VmPeak']
def get_memory():
'''
returns the current and peak, real and virtual memories
used by the calling linux python process, in Bytes
'''
# read i... | """
Gets memory usage of Linux python process
Tyson Jones, Nov 2017
tyson.jones@materials.ox.ac.uk
"""
_fields = ['VmRSS', 'VmHWM', 'VmSize', 'VmPeak']
def get_memory():
"""
returns the current and peak, real and virtual memories
used by the calling linux python process, in Bytes
"""
with open('/p... |
class Time():
current_world = None
current_time_step = None
@staticmethod
def get_current_world():
return Time.current_world
@staticmethod
def get_current_time_step():
return Time.current_time_step
@staticmethod
def reset():
Time.current_world = None
Ti... | class Time:
current_world = None
current_time_step = None
@staticmethod
def get_current_world():
return Time.current_world
@staticmethod
def get_current_time_step():
return Time.current_time_step
@staticmethod
def reset():
Time.current_world = None
Time... |
class InvalidPasswordException(Exception):
pass
class InvalidValueException(Exception):
pass
| class Invalidpasswordexception(Exception):
pass
class Invalidvalueexception(Exception):
pass |
class Carta():
CARTAS_VALORES = {
"3": 10,
"2": 9,
"1": 8,
"13": 7,
"12": 6,
"11": 5,
"7": 4,
"6": 3,
"5": 2,
"4": 1
}
NAIPES_VALORES = {
"Paus": 4,
"Copas": 3,
"Espadas": 2,
... | class Carta:
cartas_valores = {'3': 10, '2': 9, '1': 8, '13': 7, '12': 6, '11': 5, '7': 4, '6': 3, '5': 2, '4': 1}
naipes_valores = {'Paus': 4, 'Copas': 3, 'Espadas': 2, 'Moles': 1}
def __init__(self, numero, naipe):
self.numero = numero
self.naipe = naipe
def verificar_carta(self, car... |
def subUnsort(A):
n = len(A)
for i in range(0, n - 1):
if A[i] > A[i + 1]:
break
if i == n - 1:
return -1
start = i
for i in range(n - 1, start, -1):
if A[i] < A[start] or A[i] < A[i - 1]:
break
end = i
min = A[start]
max = A[start]
fo... | def sub_unsort(A):
n = len(A)
for i in range(0, n - 1):
if A[i] > A[i + 1]:
break
if i == n - 1:
return -1
start = i
for i in range(n - 1, start, -1):
if A[i] < A[start] or A[i] < A[i - 1]:
break
end = i
min = A[start]
max = A[start]
fo... |
#!/usr/bin/env python3
#pylint: disable=missing-docstring
class DeviceNotFoundException(Exception):
status_code = 404
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class UpstreamApiException(Except... | class Devicenotfoundexception(Exception):
status_code = 404
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class Upstreamapiexception(Exception):
status_code = 502
def __init__(self, message... |
Node11 = {"ip":"10.1.3.11",
"user":"marian",
"password":"descartes"}
Node17 = {"ip":"10.1.3.17",
"user":"marian",
"password":"descartes"} | node11 = {'ip': '10.1.3.11', 'user': 'marian', 'password': 'descartes'}
node17 = {'ip': '10.1.3.17', 'user': 'marian', 'password': 'descartes'} |
user_name,age = input("Enter the name and age to watch the movie : ").split()
age = int(age)
conduction = user_name[0].lower()
if conduction == 'a' and age >= 10 :
print(f"Hello {user_name}!! \n You can watch the coco movie ")
else :
if age < 10:
print("Your age is smaller then limit to watch... | (user_name, age) = input('Enter the name and age to watch the movie : ').split()
age = int(age)
conduction = user_name[0].lower()
if conduction == 'a' and age >= 10:
print(f'Hello {user_name}!! \n You can watch the coco movie ')
elif age < 10:
print('Your age is smaller then limit to watch the movie ')
else:
... |
def test_can_withdraw_as_alice(nft_funded, alice, bob, accounts, beneficiary):
nft_funded.withdraw({"from": alice})
init_balance = beneficiary.balance()
accounts[1].transfer(nft_funded, 10 ** 18)
nft_funded.mint({"from": bob})
nft_funded.withdraw({"from": alice})
final_balance = beneficiary.bala... | def test_can_withdraw_as_alice(nft_funded, alice, bob, accounts, beneficiary):
nft_funded.withdraw({'from': alice})
init_balance = beneficiary.balance()
accounts[1].transfer(nft_funded, 10 ** 18)
nft_funded.mint({'from': bob})
nft_funded.withdraw({'from': alice})
final_balance = beneficiary.bala... |
class Solution:
def solve(self, nums):
numsDict = {}
for i in nums:
if i in numsDict:
numsDict[i] += 1
else:
numsDict[i] = 1
for num in numsDict:
if num == numsDict[num]:
return True
... | class Solution:
def solve(self, nums):
nums_dict = {}
for i in nums:
if i in numsDict:
numsDict[i] += 1
else:
numsDict[i] = 1
for num in numsDict:
if num == numsDict[num]:
return True
return False |
# Author: veelion
db_host = 'localhost'
db_db = 'crawler'
db_user = 'your-user'
db_password = 'your-password'
| db_host = 'localhost'
db_db = 'crawler'
db_user = 'your-user'
db_password = 'your-password' |
BCT_ADDRESS = '0x2f800db0fdb5223b3c3f354886d907a671414a7f'
NCT_ADDRESS = '0xd838290e877e0188a4a44700463419ed96c16107'
UBO_ADDRESS = '0x2b3ecb0991af0498ece9135bcd04013d7993110c'
NBO_ADDRESS = '0x6bca3b77c1909ce1a4ba1a20d1103bde8d222e48'
GRAY = '#232B2B'
DARK_GRAY = '#343a40'
FIGURE_BG_COLOR = '#202020'
MCO2_ADDRESS = '0... | bct_address = '0x2f800db0fdb5223b3c3f354886d907a671414a7f'
nct_address = '0xd838290e877e0188a4a44700463419ed96c16107'
ubo_address = '0x2b3ecb0991af0498ece9135bcd04013d7993110c'
nbo_address = '0x6bca3b77c1909ce1a4ba1a20d1103bde8d222e48'
gray = '#232B2B'
dark_gray = '#343a40'
figure_bg_color = '#202020'
mco2_address = '0... |
CrfSegMoodPath = 'E:\python_code\Djangotest2\cmdb\model\msr.crfsuite'
HmmDIC = 'E:\python_code\Djangotest2\cmdb\model\HMMDic.pkl'
HmmDISTRIBUTION = 'E:\python_code\Djangotest2\cmdb\model\HMMDistribution.pkl'
CrfNERMoodPath = 'E:\python_code\Djangotest2\cmdb\model\PKU.crfsuite'
BiLSTMCXPath = 'E:\python_code\Djangotest2... | crf_seg_mood_path = 'E:\\python_code\\Djangotest2\\cmdb\\model\\msr.crfsuite'
hmm_dic = 'E:\\python_code\\Djangotest2\\cmdb\\model\\HMMDic.pkl'
hmm_distribution = 'E:\\python_code\\Djangotest2\\cmdb\\model\\HMMDistribution.pkl'
crf_ner_mood_path = 'E:\\python_code\\Djangotest2\\cmdb\\model\\PKU.crfsuite'
bi_lstmcx_path... |
#
# @lc app=leetcode.cn id=50 lang=python3
#
# [50] Pow(x, n)
#
n = 5
x = 6
x & 1
# @lc code=start
class Solution:
def myPow(self, x: float, n: int) -> float:
ans = 0
pow_n = x
if n > 0:
while x > 0:
if x & 1 == 1:
ans += pow_n
... | n = 5
x = 6
x & 1
class Solution:
def my_pow(self, x: float, n: int) -> float:
ans = 0
pow_n = x
if n > 0:
while x > 0:
if x & 1 == 1:
ans += pow_n
x = x >> 1
pow_n *= pow_n |
class UnknownList(Exception):
pass
class InsufficientPermissions(Exception):
pass
class AlreadySubscribed(Exception):
pass
class NotSubscribed(Exception):
pass
class ClosedSubscription(Exception):
pass
class ClosedUnsubscription(Exception):
pass
class UnknownFlag(Exception):
pass
clas... | class Unknownlist(Exception):
pass
class Insufficientpermissions(Exception):
pass
class Alreadysubscribed(Exception):
pass
class Notsubscribed(Exception):
pass
class Closedsubscription(Exception):
pass
class Closedunsubscription(Exception):
pass
class Unknownflag(Exception):
pass
clas... |
heroes_number = int(input())
heroes_list = dict()
for heroes in range(heroes_number):
hero = input().split(' ')
hero_name = hero[0]
hero_hit_points = int(hero[1])
hero_mana_points = int(hero[2])
heroes_list[hero_name] = {'HP': hero_hit_points, 'MP': hero_mana_points}
command = input()
while comm... | heroes_number = int(input())
heroes_list = dict()
for heroes in range(heroes_number):
hero = input().split(' ')
hero_name = hero[0]
hero_hit_points = int(hero[1])
hero_mana_points = int(hero[2])
heroes_list[hero_name] = {'HP': hero_hit_points, 'MP': hero_mana_points}
command = input()
while command ... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 1, 2015
# Question: 083-Remove-Duplicates-from-Sorted-List
# Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list/
# ==============================... | class Solution:
def delete_duplicates(self, head):
ptr = head
while ptr:
ptr.next = self.findNext(ptr)
ptr = ptr.next
return head
def find_next(self, head):
if not head or not head.next:
return None
elif head.val != head.next.val:
... |
#Check if NOT
txt = "Hello buddie unu!"
print("owo" not in txt)
txt = "The best things in life are free!"
if "expensive" not in txt:
print("Yes, 'expensive' is NOT present.")
'''
Terminal:
True
Yes, 'expensive' is NOT present.
'''
#https://www.w3schools.com/python/python_strings.asp | txt = 'Hello buddie unu!'
print('owo' not in txt)
txt = 'The best things in life are free!'
if 'expensive' not in txt:
print("Yes, 'expensive' is NOT present.")
"\nTerminal:\nTrue\nYes, 'expensive' is NOT present.\n" |
class InternalError(Exception):
pass
class InvalidAccessError(Exception):
pass
class InvalidStateError(Exception):
pass
| class Internalerror(Exception):
pass
class Invalidaccesserror(Exception):
pass
class Invalidstateerror(Exception):
pass |
{
'targets': [
{
'target_name': 'profiler',
'sources': [
'cpu_profiler.cc',
'graph_edge.cc',
'graph_node.cc',
'heap_profiler.cc',
'profile.cc',
'profile_node.cc',
'profiler.cc',
'snapshot.cc',
],
}
]
}
| {'targets': [{'target_name': 'profiler', 'sources': ['cpu_profiler.cc', 'graph_edge.cc', 'graph_node.cc', 'heap_profiler.cc', 'profile.cc', 'profile_node.cc', 'profiler.cc', 'snapshot.cc']}]} |
def Insertionsort(A):
for i in range(1, len(A)):
tmp = A[i]
k = i
while k > 0 and tmp < A[k - 1]:
A[k] = A[k - 1]
k -= 1
A[k] = tmp
A = [54, 26, 93, 17, 77, 31, 44, 55, 20]
Insertionsort(A)
print(A) | def insertionsort(A):
for i in range(1, len(A)):
tmp = A[i]
k = i
while k > 0 and tmp < A[k - 1]:
A[k] = A[k - 1]
k -= 1
A[k] = tmp
a = [54, 26, 93, 17, 77, 31, 44, 55, 20]
insertionsort(A)
print(A) |
class policy_name_protection():
def __init__(self,name_protection):
self.np=name_protection
def __call__(self,target):
try:
if target.policy.has_key('name_protection')==True:
if target.policy.get('name_protection')==False and self.np==True:
... | class Policy_Name_Protection:
def __init__(self, name_protection):
self.np = name_protection
def __call__(self, target):
try:
if target.policy.has_key('name_protection') == True:
if target.policy.get('name_protection') == False and self.np == True:
... |
#!/usr/bin/env python3
# Problem Set 4A
# Name: John L. Jones
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for ... | def get_permutations(sequence):
"""
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutatio... |
def function(param, param1):
pass
def result():
pass
function(result<arg1>(), result())
| def function(param, param1):
pass
def result():
pass
function(result < arg1 > (), result()) |
# https://open.kattis.com/problems/stockbroker
# init values
cash = 100
shares = 0
prices = []
#first input: num days (1-365)
num_days = int(input())
#next inputs: values on each day (1-500)
for _ in range(num_days):
prices.append(int(input()))
for i in range(len(prices)-1):
if prices[i] ... | cash = 100
shares = 0
prices = []
num_days = int(input())
for _ in range(num_days):
prices.append(int(input()))
for i in range(len(prices) - 1):
if prices[i] < prices[i + 1]:
if shares + cash // prices[i] > 100000:
cash = cash - (100000 - shares) * prices[i]
shares = 100000
... |
class RequestInfo:
def __init__(self,
human_string, # human-readable string (will be printed for Human object)
action_requested, # action requested ('card' + index of card / 'opponent' / 'guess')
current_hand = [], ... | class Requestinfo:
def __init__(self, human_string, action_requested, current_hand=[], discard_pile=[], move_history=[], players_active_status=[], players_protection_status=[], invalid_moves=[], valid_moves=[], players_active=[], players_protected=[]):
self.human_string = human_string
self.action_r... |
class RawMemory(object):
'''Represents raw memory.'''
def __init__(self):
self._pointer_to_object = {}
self._object_to_pointer = {}
# address 0 won't be used
self._current_pointer = 0
def get_pointer(self, obj):
assert obj in self._object_to_pointer
return se... | class Rawmemory(object):
"""Represents raw memory."""
def __init__(self):
self._pointer_to_object = {}
self._object_to_pointer = {}
self._current_pointer = 0
def get_pointer(self, obj):
assert obj in self._object_to_pointer
return self._object_to_pointer[obj]
d... |
class Paginator:
def __init__(self, configuration, request):
self.configuration = configuration
self.page = request.args.get('page', 1, type=int)
self.page_size = request.args.get('page_size', configuration.per_page, type=int)
if self.page_size > configuration.max_page_size:
... | class Paginator:
def __init__(self, configuration, request):
self.configuration = configuration
self.page = request.args.get('page', 1, type=int)
self.page_size = request.args.get('page_size', configuration.per_page, type=int)
if self.page_size > configuration.max_page_size:
... |
'''
Python To-Do
A simple to-do list program using text files to hold tasks
Authored by: Bryce Buchanan
'''
# TO DO 1. Convert to class
# TO DO 2. Allow editing of tasks
# TO DO 3. Detemine and implement best data structure
# TO DO 4. File I/O
# TO DO 5. GUI
#class ToDoItem:
# def __init__(self, task):
# self.task ... | """
Python To-Do
A simple to-do list program using text files to hold tasks
Authored by: Bryce Buchanan
"""
class Todomodule:
def __init__(self, toDoList, completedTasks, head=None):
self.toDoList = toDoList
self.completedTasks = completedTasks
self.head = head
def add(self):
... |
EXECUTE_MODE_AUTO = "auto"
EXECUTE_MODE_ASYNC = "async"
EXECUTE_MODE_SYNC = "sync"
EXECUTE_MODE_OPTIONS = frozenset([
EXECUTE_MODE_AUTO,
EXECUTE_MODE_ASYNC,
EXECUTE_MODE_SYNC,
])
EXECUTE_CONTROL_OPTION_ASYNC = "async-execute"
EXECUTE_CONTROL_OPTION_SYNC = "sync-execute"
EXECUTE_CONTROL_OPTIONS = frozense... | execute_mode_auto = 'auto'
execute_mode_async = 'async'
execute_mode_sync = 'sync'
execute_mode_options = frozenset([EXECUTE_MODE_AUTO, EXECUTE_MODE_ASYNC, EXECUTE_MODE_SYNC])
execute_control_option_async = 'async-execute'
execute_control_option_sync = 'sync-execute'
execute_control_options = frozenset([EXECUTE_CONTROL... |
# Euler problem 90: Cube digit pairs
def solve():
# Find all possible dies with 6 digits on faces out of 10 combinations
options = []
find_options(options, [])
count = 0
# Figure out which combinations of two dies make a square
for die1 in options:
for die2 in options:
... | def solve():
options = []
find_options(options, [])
count = 0
for die1 in options:
for die2 in options:
if is_solution(die1, die2):
count += 1
print(count // 2)
def find_options(options, die):
if len(die) == 6:
options.append(die)
return
i... |
class SimHash:
def __init__(self, bit=64, limit=3):
self.bit = bit
self.limit = limit
self.docs = []
def compute_bits(self, text):
word_hash = []
for word in text:
word_hash.append(hash(word))
hash_bits = []
while len(hash_bits) <... | class Simhash:
def __init__(self, bit=64, limit=3):
self.bit = bit
self.limit = limit
self.docs = []
def compute_bits(self, text):
word_hash = []
for word in text:
word_hash.append(hash(word))
hash_bits = []
while len(hash_bits) < self.bit:
... |
# Write a function that takes a string as input and returns the string reversed.
class Solution(object):
def reverseString(self, s):
return s[::-1] | class Solution(object):
def reverse_string(self, s):
return s[::-1] |
# Copyright 2018, Michael DeHaan LLC
# License: Apache License Version 2.0 + Commons Clause
# ---------------------------------------------------------------------------
# workers.py - configuration related to worker setup. This file *CAN* be
# different per worker.
# ------------------------------------------------... | build_root = '/tmp/vespene/buildroot/'
fileserving_enabled = True
fileserving_port = 8000
fileserving_hostname = ''
fileserving_url = '/srv'
buildroot_web_link = '' |
#1016
#ENTRADA DE DADOS
entrada = int(input())
#SE O CARRO Y CONSEGUE SE DISTANCIAR EM CADA MINUTO 500metros = 0.5km
tempo = entrada/0.5
print(int(tempo), 'minutos')
| entrada = int(input())
tempo = entrada / 0.5
print(int(tempo), 'minutos') |
class InsertQueryComposer(object):
_insert_part = None
_values_part_template = None
_values_part = None
values_count = None
def __init__(self, table_name, columns):
columns_clause = ""
values_clause = ""
for column in columns:
columns_clause += "`{column_name}`, ... | class Insertquerycomposer(object):
_insert_part = None
_values_part_template = None
_values_part = None
values_count = None
def __init__(self, table_name, columns):
columns_clause = ''
values_clause = ''
for column in columns:
columns_clause += '`{column_name}`, ... |
# parsetable.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'AND ARRAY ASSIGNMENT BINDIGSEQ CASE CHAR COLON COMMA COMMENT CONST DIGSEQ DIV DO DOT DOTDOT DOWNTO ELSE END EQUAL FOR FORWARD FUNCTION GE GOTO GT HEXDIGSEQ IDENTIFIER IF IN LABEL LBRAC LE LP... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'AND ARRAY ASSIGNMENT BINDIGSEQ CASE CHAR COLON COMMA COMMENT CONST DIGSEQ DIV DO DOT DOTDOT DOWNTO ELSE END EQUAL FOR FORWARD FUNCTION GE GOTO GT HEXDIGSEQ IDENTIFIER IF IN LABEL LBRAC LE LPAREN LT MINUS MOD NIL NOT NOTEQUAL OCTDIGSEQ OF OR OTHERWISE PACKED PBEG... |
# program to display student's marks from record
student_n = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_n:
print(marks[student])
break
else:
print('No entry with that name found.') | student_n = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_n:
print(marks[student])
break
else:
print('No entry with that name found.') |
def shouldAttack(target):
return target and target.type != "burl"
while True:
enemy = hero.findNearestEnemy()
if shouldAttack(enemy):
hero.attack(enemy)
| def should_attack(target):
return target and target.type != 'burl'
while True:
enemy = hero.findNearestEnemy()
if should_attack(enemy):
hero.attack(enemy) |
class Animal:
cat = "cat"
dog = "dog"
panda = "panda"
koala = "koala"
fox = "fox"
bird = "bird"
racoon = "racoon"
kangaroo = "kangaroo"
elephant = "elephant"
giraffe = "giraffe"
whale = "whale"
birb = "birb"
raccoon = "raccoon"
class Gif:
wink = "wink"
pat = ... | class Animal:
cat = 'cat'
dog = 'dog'
panda = 'panda'
koala = 'koala'
fox = 'fox'
bird = 'bird'
racoon = 'racoon'
kangaroo = 'kangaroo'
elephant = 'elephant'
giraffe = 'giraffe'
whale = 'whale'
birb = 'birb'
raccoon = 'raccoon'
class Gif:
wink = 'wink'
pat = ... |
##### Functions ################################################################
def lgis3( seq, count ):
'''
Returns reversed version of (a) longest increasing subsequence.
seq: the sequence for which (a) longest increasing subsequence is desired.
count: number of items in seq
Notes:
Uses "P... | def lgis3(seq, count):
"""
Returns reversed version of (a) longest increasing subsequence.
seq: the sequence for which (a) longest increasing subsequence is desired.
count: number of items in seq
Notes:
Uses "Patience Sorting"
Each 'pile' is a subsequence with the opposite polarity {decrea... |
class Customer(object):
def __init__(self, match, customer, **kwargs):
self.id = kwargs.get('id', None)
self.match = match
self.customer = customer
def __repr__(self):
return 'Customer(id=%r, match=%r, customer=%r)' % (
self.id, self.match, self.customer)
@cla... | class Customer(object):
def __init__(self, match, customer, **kwargs):
self.id = kwargs.get('id', None)
self.match = match
self.customer = customer
def __repr__(self):
return 'Customer(id=%r, match=%r, customer=%r)' % (self.id, self.match, self.customer)
@classmethod
d... |
{
'variables': {
'zmq_shared%': 'false',
'zmq_draft%': 'false',
'zmq_no_sync_resolve%': 'false',
},
'targets': [
{
'target_name': 'libzmq',
'type': 'none',
'conditions': [
["zmq_shared == 'false'", {
'actions': [{
'action_name': 'build_libzmq',
... | {'variables': {'zmq_shared%': 'false', 'zmq_draft%': 'false', 'zmq_no_sync_resolve%': 'false'}, 'targets': [{'target_name': 'libzmq', 'type': 'none', 'conditions': [["zmq_shared == 'false'", {'actions': [{'action_name': 'build_libzmq', 'inputs': ['package.json'], 'outputs': ['libzmq/lib'], 'action': ['sh', '<(PRODUCT_D... |
#n! = 1 * 2 * 3 * 4 ..... * n
#n! = [1 * 2 * 3 * 4 ..... n-1]* n
#n! = n * (n-1)!
# n = 7
# product = 1
# for i in range(n):
# product = product * (i+1)
# print(product)
def factorial_iter(n):
product = 1
for i in range(n):
product = product * (i+1)
return product
def factorial_recursive(n):... | def factorial_iter(n):
product = 1
for i in range(n):
product = product * (i + 1)
return product
def factorial_recursive(n):
if n == 1 or n == 0:
return 1
return n * factorial_recursive(n - 1)
f = factorial_recursive(3)
print(f) |
#!/usr/bin/env python2
# The MIT License (MIT)
#
# Copyright (c) 2015 Shane O'Connor
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | rgb_colors = dict(neon_green='#39FF14', brown='#774400', purple='#440077', cornflower_blue='#6495ED', firebrick='#B22222') |
class Cell:
def __init__(self, c=' '):
self.c = c
self.highlight = {}
def __mul__(self, n):
return [Cell(self.c) for i in range(n)]
def __str__(self):
return self.c
class Highlight:
def __init__(self, line, highlight):
self.line = line
self.highlight = ... | class Cell:
def __init__(self, c=' '):
self.c = c
self.highlight = {}
def __mul__(self, n):
return [cell(self.c) for i in range(n)]
def __str__(self):
return self.c
class Highlight:
def __init__(self, line, highlight):
self.line = line
self.highlight ... |
def parse_args(r_args):
columns = r_args.get('columns')
args = {key:value for (key,value) in r_args.items() if key not in ('columns', 'api_key')}
return columns, args | def parse_args(r_args):
columns = r_args.get('columns')
args = {key: value for (key, value) in r_args.items() if key not in ('columns', 'api_key')}
return (columns, args) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Config(object):
config = None
def __init__(self, config):
self.config = config
def __str__(self):
return str(self.config)
def __getitem__(self, item):
return self.config[item]
def interactive(self):
return sel... | class Config(object):
config = None
def __init__(self, config):
self.config = config
def __str__(self):
return str(self.config)
def __getitem__(self, item):
return self.config[item]
def interactive(self):
return self.config['app']['interactive']
def dry(self)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.