content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def expectOne(vals):
assert len(vals) == 1
return vals[0]
| def expect_one(vals):
assert len(vals) == 1
return vals[0] |
class CSVDumper:
@classmethod
def dump(self, matrix, encoding='sjis'):
rows = []
for row in matrix:
fields = []
for field in row:
if field is None:
fields.append('')
elif str(field).isdigit():
fields... | class Csvdumper:
@classmethod
def dump(self, matrix, encoding='sjis'):
rows = []
for row in matrix:
fields = []
for field in row:
if field is None:
fields.append('')
elif str(field).isdigit():
fields... |
'''Hercy wants to save money for his first car. He puts money
in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday,
he will put in $1 more than the day before. On every subsequent Monday,
he will put in $1 more than the previous Monday.
Given n, return... | """Hercy wants to save money for his first car. He puts money
in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday,
he will put in $1 more than the day before. On every subsequent Monday,
he will put in $1 more than the previous Monday.
Given n, return... |
# Radix Sort is an improvement over Counting Sort
# Counting Sort is highly inefficient with large ranges
# Radix sort sorts digit by digit from least to most significant digit.
# It can be imagined as a bucket sort based on place values.
def radixSort(array, base=10):
# Get the maximum in the array to find the ma... | def radix_sort(array, base=10):
m = max(array)
place_value = 1
while m / placeValue > 0:
occurence = [0] * base
for element in array:
occurence[int(element / placeValue % base)] += 1
for i in range(1, base):
occurence[i] += occurence[i - 1]
temp = [0] ... |
'''
-- Make required Folder & open Integrated CMD in it !
In CMD type :
[To make exact copy of system base python but no modules included!]
-- pip install virtualenv
-- virtualenv [nameOfSubFolderInRequiredFolder] // Here I used VirtualEnvironment
--OR--
To make exact copy of system base p... | """
-- Make required Folder & open Integrated CMD in it !
In CMD type :
[To make exact copy of system base python but no modules included!]
-- pip install virtualenv
-- virtualenv [nameOfSubFolderInRequiredFolder] // Here I used VirtualEnvironment
--OR--
To make exact copy of system base p... |
ME = '''
query getMe {
me {
username
isStaff
isSuperuser
isAgreed
profile {
id
oauthType
name
nameKo
nameEn
bio
bioKo
bioEn
email
phone
organiz... | me = '\nquery getMe {\n me {\n username\n isStaff\n isSuperuser\n isAgreed\n profile { \n id\n oauthType\n name\n nameKo\n nameEn\n bio\n bioKo\n bioEn\n email\n phone\n ... |
# -*- coding: utf-8 -*-
args = input().split()
n1, n2, n3 = list(map (int, args))
average = (lambda a, b, c: (a + b + c)/3)(n1, n2, n3)
result = (lambda av: "Approved" if av >= 6 else "Disapproved")
print(result(average))
| args = input().split()
(n1, n2, n3) = list(map(int, args))
average = (lambda a, b, c: (a + b + c) / 3)(n1, n2, n3)
result = lambda av: 'Approved' if av >= 6 else 'Disapproved'
print(result(average)) |
# leetcode
class Solution:
def isPalindrome(self, s: str) -> bool:
s_cp = s.replace(" ", "").lower()
clean_s = ''
for l in s_cp:
# check if num
if ord(l) >= 48 and ord(l) <= 57:
clean_s += l
elif ord(l) >= 97 and ord(l) <... | class Solution:
def is_palindrome(self, s: str) -> bool:
s_cp = s.replace(' ', '').lower()
clean_s = ''
for l in s_cp:
if ord(l) >= 48 and ord(l) <= 57:
clean_s += l
elif ord(l) >= 97 and ord(l) <= 122:
clean_s += l
return clea... |
'''
Two intervals i1, i2overlap if the following requirements are satisfied:
requirement 1: i1.end >= i2.start
requirement 2: i1.start <= i2.end
We preprocess the list by sorting intervals by starts increasingly.
In this way, requirement 2 i1.start <= i2.start < i2.end is promised.
We only have to compare i1.end with ... | """
Two intervals i1, i2overlap if the following requirements are satisfied:
requirement 1: i1.end >= i2.start
requirement 2: i1.start <= i2.end
We preprocess the list by sorting intervals by starts increasingly.
In this way, requirement 2 i1.start <= i2.start < i2.end is promised.
We only have to compare i1.end with ... |
"""
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
... | """
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
... |
"""Utility to store int or float parameters with a label
The label is added merely for information: there is no
extra functionality associated with it.
The module has a factory class Parameter(value, label)
which returns either ParameterInt ot ParameterFloat
depending on type(value).
"""
class ParameterInt(int):
... | """Utility to store int or float parameters with a label
The label is added merely for information: there is no
extra functionality associated with it.
The module has a factory class Parameter(value, label)
which returns either ParameterInt ot ParameterFloat
depending on type(value).
"""
class Parameterint(int):
... |
#
# PySNMP MIB module Nortel-Magellan-Passport-DataCollectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-DataCollectionMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:26:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, value_size_constraint, constraints_intersection) ... |
numbers = [-1,0]
target = -1
hashMap = {}
for index, num in enumerate(numbers):
diff = target - num
if diff in hashMap:
print([hashMap[diff]+1, index+1])
hashMap[num] = index | numbers = [-1, 0]
target = -1
hash_map = {}
for (index, num) in enumerate(numbers):
diff = target - num
if diff in hashMap:
print([hashMap[diff] + 1, index + 1])
hashMap[num] = index |
#SCOPE USING NONLOCAL KEYWORD
x = 10#GLOBAL VARIABLE X
def outer():
x=20#LOCAL VARIABLE X
y=30#LOCAL VARIABLE Y
print("outer func x before inner call:", x)
print("outer func y before inner call:", y)
def inner():
nonlocal y#LOCAL VARIABLE Y REFERS TO ITS ABOVE LEVEL OUTER Y
global x#... | x = 10
def outer():
x = 20
y = 30
print('outer func x before inner call:', x)
print('outer func y before inner call:', y)
def inner():
nonlocal y
global x
x = 30
y = 40
print('inner func x :', x)
print('inner func y :', y)
inner()
print('oute... |
"""
1. Clarification
2. Possible solutions
- dp
3. Coding
4. Tests
"""
# T=O(n), S=O(n)
# dp[i][j], i: day, j:
# 0 - have a share of stock
# 1 - have no stock and cool down next day
# 2 - have no stock and no cool down next day
class Solution:
def maxProfit(self, prices: List[int]) -> ... | """
1. Clarification
2. Possible solutions
- dp
3. Coding
4. Tests
"""
class Solution:
def max_profit(self, prices: List[int]) -> int:
if not prices:
return 0
n = len(prices)
dp = [[0] * 3 for _ in range(n)]
(dp[0][0], dp[0][1], dp[0][2]) = (-prices[0], 0, 0)
... |
#========================================================================================================
# TOPIC: PYTHON - Modules
#========================================================================================================
# NOTES: * Any Python file is a module.
# * Module is a file with Python ... | country_1 = 'USA'
country_2 = 'China'
country_3 = 'India'
list_world_nations = ['USA', 'China', 'India']
tuple_world_nations = ('USA', 'China', 'India')
dictionary_world_nations = {'Country_1': 'USA', 'Country_1': 'China', 'Country_1': 'India'}
def module_function_add(in_number1, in_number2):
"""This function add ... |
# Define a sum_of_lengths function that accepts a list of strings.
# The function should return the sum of the string lengths.
#
# EXAMPLES
# sum_of_lengths(["Hello", "Bob"]) => 8
# sum_of_lengths(["Nonsense"]) => 8
# sum_of_lengths(["Nonsense", "or", "confidence"]) => 20
def sum... | def sum_of_lengths(array):
sum = 0
for element in array:
sum += len(element)
return sum
print(sum_of_lengths(['Hello', 'Bob']))
print(sum_of_lengths(['Nonsense']))
print(sum_of_lengths(['Nonsense', 'or', 'confidence'])) |
# Generates an infinite series of odd numbers
def odds():
n = 1
while True:
yield n
n += 2
def pi_series():
odd_nums = odds()
approximation = 0
while True:
approximation += (4 / next(odd_nums))
yield approximation
approxim... | def odds():
n = 1
while True:
yield n
n += 2
def pi_series():
odd_nums = odds()
approximation = 0
while True:
approximation += 4 / next(odd_nums)
yield approximation
approximation -= 4 / next(odd_nums)
yield approximation
approx_pi = pi_series()
for x... |
data = [
{'v': 'v0.1', 't': 1391},
{'v': 'v0.1', 't': 1394},
{'v': 'v0.1', 't': 1300},
{'v': 'v0.1', 't': 1321},
{'v': 'v0.1.3', 't': 1491},
{'v': 'v0.1.3', 't': 1494},
{'v': 'v0.1.3', 't': 1400},
{'v': 'v0.1.3', 't': 1421},
{'v': 'v0.1.2', 't': 1291},
{'v': 'v0.1.2', 't': 1294},... | data = [{'v': 'v0.1', 't': 1391}, {'v': 'v0.1', 't': 1394}, {'v': 'v0.1', 't': 1300}, {'v': 'v0.1', 't': 1321}, {'v': 'v0.1.3', 't': 1491}, {'v': 'v0.1.3', 't': 1494}, {'v': 'v0.1.3', 't': 1400}, {'v': 'v0.1.3', 't': 1421}, {'v': 'v0.1.2', 't': 1291}, {'v': 'v0.1.2', 't': 1294}, {'v': 'v0.1.2', 't': 1200}, {'v': 'v0.1.... |
def minimum(a):
b=list[0]
i=0
while i<len(list):
if list[i]<b:
b=list[i]
i=i+1
return(b)
list=[5,3,1,6,5,4,7,6]
print(minimum(list))
| def minimum(a):
b = list[0]
i = 0
while i < len(list):
if list[i] < b:
b = list[i]
i = i + 1
return b
list = [5, 3, 1, 6, 5, 4, 7, 6]
print(minimum(list)) |
__about__="Class method vs Static Method."
class MyClass:
def method(self):
print("Instance of method called", self)
@classmethod
def classmethod(cls):
print("Instance of classmethod called", cls)
@staticmethod
def staticmethod():
print("Instance of staticmethod called")
... | __about__ = 'Class method vs Static Method.'
class Myclass:
def method(self):
print('Instance of method called', self)
@classmethod
def classmethod(cls):
print('Instance of classmethod called', cls)
@staticmethod
def staticmethod():
print('Instance of staticmethod called'... |
'''
Class for adding the expreimental data for the cell model
'''
class Experimental:
def __init__(self):
self.experimental_data = dict()
def define_exp(self, **kwargs):
for exp_type, data in kwargs.items():
self.experimental_data.update({exp_type: data})
| """
Class for adding the expreimental data for the cell model
"""
class Experimental:
def __init__(self):
self.experimental_data = dict()
def define_exp(self, **kwargs):
for (exp_type, data) in kwargs.items():
self.experimental_data.update({exp_type: data}) |
def get_hard_coded_app_id_dict():
# Matches, manually added, from game names to Steam appIDs
hard_coded_dict = {
# Manually fix matches for which the automatic name matching (based on Levenshtein distance) is wrong:
"The Missing": "842910",
"Pillars of Eternity 2": "560130",
"Dr... | def get_hard_coded_app_id_dict():
hard_coded_dict = {'The Missing': '842910', 'Pillars of Eternity 2': '560130', 'Dragon Quest XI': '742120', 'DRAGON QUEST XI: Echoes of an Elusive Age': '742120', 'Dragon Quest XI: Echoes of an Elusive Age': '742120', 'Dragon Quest XI: Shadows of an Elusive Age': '742120', 'Atelier... |
rates = list() # Equals to: rates = []
genres = list()
ages = list()
another_one = True
while another_one:
genre = input('Please enter your genre (either M or F): ')
genres.append(genre)
age = int(input('Type your age: '))
ages.append(age)
rate = input('You rate the product as '
... | rates = list()
genres = list()
ages = list()
another_one = True
while another_one:
genre = input('Please enter your genre (either M or F): ')
genres.append(genre)
age = int(input('Type your age: '))
ages.append(age)
rate = input('You rate the product as 1-unsatisfactory 2-bad 3-regular 4-good 5-grea... |
def euclidean_distance(x1, y1, x2, y2):
"""Compute euclidean distance between two points."""
def which_start_and_pitstop(pitstop_num, pitstop_coords, start_coords):
"""Computes the relevant pitstop and startpoint info.
Extracts the pitstop coordinates, relevant startpoint number and
startpoint co... | def euclidean_distance(x1, y1, x2, y2):
"""Compute euclidean distance between two points."""
def which_start_and_pitstop(pitstop_num, pitstop_coords, start_coords):
"""Computes the relevant pitstop and startpoint info.
Extracts the pitstop coordinates, relevant startpoint number and
startpoint coo... |
greetings = ["hey", "howdy", "hi", "hello", "hi there"]
questions = ["how_are_you_feeling", "how_are_you", "what_is_your_name", "how_old_are_you", "where_are_you_from", "are_you_a_boy_or_a_girl", "what_up"]
insults = ["dumb", "stupid", "Ugly", "Retard", "Retarded", "suck"]
complements = ["great", "awesome"]
cuss_wo... | greetings = ['hey', 'howdy', 'hi', 'hello', 'hi there']
questions = ['how_are_you_feeling', 'how_are_you', 'what_is_your_name', 'how_old_are_you', 'where_are_you_from', 'are_you_a_boy_or_a_girl', 'what_up']
insults = ['dumb', 'stupid', 'Ugly', 'Retard', 'Retarded', 'suck']
complements = ['great', 'awesome']
cuss_words ... |
def extractEachKth(inputArray, k):
return [x for i, x in enumerate(inputArray) if (i + 1) % k != 0]
print(extractEachKth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)) | def extract_each_kth(inputArray, k):
return [x for (i, x) in enumerate(inputArray) if (i + 1) % k != 0]
print(extract_each_kth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)) |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.3.beta7'
date = '2021-02-07'
banner = 'SageMath version 9.3.beta7, Release Date: 2021-02-07'
| version = '9.3.beta7'
date = '2021-02-07'
banner = 'SageMath version 9.3.beta7, Release Date: 2021-02-07' |
_attrs = {
"base": attr.string(
mandatory = True
),
# See: https://github.com/opencontainers/image-spec/blob/main/config.md#properties
"entrypoint": attr.string_list(),
"cmd": attr.string_list(),
"labels": attr.string_list(),
"tag": attr.string_list(),
"layers": attr.label_list(... | _attrs = {'base': attr.string(mandatory=True), 'entrypoint': attr.string_list(), 'cmd': attr.string_list(), 'labels': attr.string_list(), 'tag': attr.string_list(), 'layers': attr.label_list()}
def _strip_external(path):
return path[len('external/'):] if path.startswith('external/') else path
def _impl(ctx):
... |
def numsum(n):
''' The recursive sum of all digits in a number
unit a single character is obtained'''
res = sum([int(i) for i in str(n)])
if res < 10: return res
else : return numsum(res)
for n in range(1,101):
response = 'Fizz'*(numsum(n) in [3,6,9]) + \
'Buzz'*(str(n)[-1] in ['5','0'... | def numsum(n):
""" The recursive sum of all digits in a number
unit a single character is obtained"""
res = sum([int(i) for i in str(n)])
if res < 10:
return res
else:
return numsum(res)
for n in range(1, 101):
response = 'Fizz' * (numsum(n) in [3, 6, 9]) + 'Buzz' * (str(n)[-... |
class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
if not A or not A[0]: return 0
n, m = len(A), len(A[0])
tot = n*2**(m-1)
for i in range(1, m):
zero = sum(A[j][0]^A[j][i] for j in range(n))
... | class Solution:
def matrix_score(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
if not A or not A[0]:
return 0
(n, m) = (len(A), len(A[0]))
tot = n * 2 ** (m - 1)
for i in range(1, m):
zero = sum((A[j][0] ^ A[j][i] for ... |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import plotly\n",
"import pandas as pd\n",
"\n",
"from nltk.stem import WordNetLemmatizer\n",
"from nltk.tokenize import word_tokenize\n",
"\n",
"fr... | {'cells': [{'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': ['import json\n', 'import plotly\n', 'import pandas as pd\n', '\n', 'from nltk.stem import WordNetLemmatizer\n', 'from nltk.tokenize import word_tokenize\n', '\n', 'from flask import Flask\n', 'from flask import render_te... |
# Solution 1
# O(n^2) time / O(1) space
# n - number of buildings
def largestRectangleUnderSkyline(buildings):
maxArea = 0
for pillarIdx in range(len(buildings)):
currentHeight = buildings[pillarIdx]
furthestLeft = pillarIdx
while furthestLeft > 0 and buildings[furthestLeft - 1] >= currentHeight:
... | def largest_rectangle_under_skyline(buildings):
max_area = 0
for pillar_idx in range(len(buildings)):
current_height = buildings[pillarIdx]
furthest_left = pillarIdx
while furthestLeft > 0 and buildings[furthestLeft - 1] >= currentHeight:
furthest_left -= 1
furthest_r... |
t=int(input())
while(t):
t=t-1
n=int(input())
c=0
a=list(map(int,input().split()))
b=[]
b.append(int(a[0]))
for i in range(1,len(a)):
b.append(min(int(a[i]),int(b[i-1])))
for i in range(0,len(a)):
if(int(a[i])==int(b[i])):
c+=1
print(c)
| t = int(input())
while t:
t = t - 1
n = int(input())
c = 0
a = list(map(int, input().split()))
b = []
b.append(int(a[0]))
for i in range(1, len(a)):
b.append(min(int(a[i]), int(b[i - 1])))
for i in range(0, len(a)):
if int(a[i]) == int(b[i]):
c += 1
print(... |
#!/usr/bin/env python3
__author__ = "Mert Erol"
# This signature is required for the automated grading to work.
# Do not rename the function or change its list of parameters!
def visualize(records):
pclass_1 = 0
pclass_1_alive = 0
pclass_2 = 0
pclass_2_alive = 0
pclass_3 = 0
pclass_3_alive = 0
... | __author__ = 'Mert Erol'
def visualize(records):
pclass_1 = 0
pclass_1_alive = 0
pclass_2 = 0
pclass_2_alive = 0
pclass_3 = 0
pclass_3_alive = 0
dataset = records[1]
for p in dataset:
pclass = p[1]
alive = p[0]
if pclass == 1:
pclass_1 += 1
... |
# Dummy class for packages that have no MPI
class MPIDummy(object):
def __init__(self):
pass
def Get_rank(self):
return 0
def Get_size(self):
return 1
def barrier(self):
pass
def send(self, lnlike0, dest=1, tag=55):
pass
def recv(self, source=1, tag=5... | class Mpidummy(object):
def __init__(self):
pass
def get_rank(self):
return 0
def get_size(self):
return 1
def barrier(self):
pass
def send(self, lnlike0, dest=1, tag=55):
pass
def recv(self, source=1, tag=55):
pass
def iprobe(self, sour... |
def gcd(a, b):
factors_a = []
for i in range(1, a+1):
if (a%i) == 0:
factors_a.append(i)
factors_b = []
for i in range(1, b+1):
if (b%i) == 0:
factors_b.append(i)
common_factors = []
for i in factors_a:
if i in factors_b:
common_facto... | def gcd(a, b):
factors_a = []
for i in range(1, a + 1):
if a % i == 0:
factors_a.append(i)
factors_b = []
for i in range(1, b + 1):
if b % i == 0:
factors_b.append(i)
common_factors = []
for i in factors_a:
if i in factors_b:
common_fac... |
"""Pygame Zero, a zero-boilerplate game framework for education.
You shouldn't need to import things from the 'pgzero' package directly; just
use 'pgzrun' to run the game file.
"""
__version__ = '1.2'
| """Pygame Zero, a zero-boilerplate game framework for education.
You shouldn't need to import things from the 'pgzero' package directly; just
use 'pgzrun' to run the game file.
"""
__version__ = '1.2' |
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 3 Module Part 1 - Practice Quiz
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Scripting examples encountered during the Module Part 1 Practice Quiz:
# 02. Fill in the blanks to make the print_prime_f... | def print_prime_factors(number):
factor = 2
while factor <= number:
if number % factor == 0:
print(factor)
number = number / factor
else:
factor += 1
return 'Done'
print_prime_factors(100)
def is_power_of_two(n):
while n % 2 == 0:
if n == 0:
... |
test = """2H2 + O2 -> 2H2O"""
def times_sep(s):
elem = []
times = []
checking_pro = False
last = 0
for i in range(len(s)):
if checking_pro:
if s[i].isalpha() and not s[i].islower() or s[i].isdigit():
elem.append(s[last])
checking_pro = False
... | test = '2H2 + O2 -> 2H2O'
def times_sep(s):
elem = []
times = []
checking_pro = False
last = 0
for i in range(len(s)):
if checking_pro:
if s[i].isalpha() and (not s[i].islower()) or s[i].isdigit():
elem.append(s[last])
checking_pro = False
if ... |
#4: Skriv alle primtal mellem 1 og 100
for primtal in range(2, 101):
for i in range(2, primtal):
if (primtal % i) == 0:
break
else:
print(primtal)
| for primtal in range(2, 101):
for i in range(2, primtal):
if primtal % i == 0:
break
else:
print(primtal) |
class Checkers:
def __init__(self):
pass
def is_operation(self, command):
operations = ['+', '-', 'x', '*', '/',
'plus', 'minus', 'times', 'divide']
for operation in operations:
if operation in command:
return True
| class Checkers:
def __init__(self):
pass
def is_operation(self, command):
operations = ['+', '-', 'x', '*', '/', 'plus', 'minus', 'times', 'divide']
for operation in operations:
if operation in command:
return True |
# noinspection PyUnusedLocal
# skus = unicode string
class InvalidOfferException(Exception):
def __init__(self, expression, message):
self.expression = expression
self.message = message
def checkout(skus):
products = {
'A': productA, 'B': productB, 'C': productC,'D': productD,'E': prod... | class Invalidofferexception(Exception):
def __init__(self, expression, message):
self.expression = expression
self.message = message
def checkout(skus):
products = {'A': productA, 'B': productB, 'C': productC, 'D': productD, 'E': productE, 'F': productF, 'G': productG, 'H': productH, 'I': prod... |
str = "RahulShettyAcademy.com"
str1 = "Consulting firm"
str3 = "RahulShetty"
print(str[1]) #a
print(str[0:5]) # if you want substring in python
print(str+str1) # concatenation
print(str3 in str) # substring check
var = str.split(".")
print(var)
print(var[0])
str4 = " great "
print(str4.strip())
print(str4.ls... | str = 'RahulShettyAcademy.com'
str1 = 'Consulting firm'
str3 = 'RahulShetty'
print(str[1])
print(str[0:5])
print(str + str1)
print(str3 in str)
var = str.split('.')
print(var)
print(var[0])
str4 = ' great '
print(str4.strip())
print(str4.lstrip())
print(str4.rstrip()) |
class Solution:
def secondHighest(self, s: str) -> int:
a = []
for i in s:
if i.isdigit():
a.append(int(i))
stack = [-1]
maxs = max(a)
for i in a:
if i < maxs:
while stack and stack[-1] < i:
stack.pop... | class Solution:
def second_highest(self, s: str) -> int:
a = []
for i in s:
if i.isdigit():
a.append(int(i))
stack = [-1]
maxs = max(a)
for i in a:
if i < maxs:
while stack and stack[-1] < i:
stack.p... |
'''
Fibonacci Sequence
'''
print("Enter a number for Fibonacci")
f = input()
| """
Fibonacci Sequence
"""
print('Enter a number for Fibonacci')
f = input() |
class Duration:
def __init__(self, hours: int = 0, minutes: int = 0, seconds: int = 0):
# setup the class instance and convert any provided times to seconds
self.total_duration: int = (hours * 60 * 60) + (minutes * 60) + seconds
def __add__(self, other):
new_total: int = self.total_dur... | class Duration:
def __init__(self, hours: int=0, minutes: int=0, seconds: int=0):
self.total_duration: int = hours * 60 * 60 + minutes * 60 + seconds
def __add__(self, other):
new_total: int = self.total_duration + other.total_duration
return duration(seconds=new_total)
def get_ho... |
# https://lospec.com/palette-list/pear36
COLORS = [
"#5e315b",
"#8c3f5d",
"#ba6156",
"#f2a65e",
"#ffe478",
"#cfff70",
"#8fde5d",
"#3ca370",
"#3d6e70",
"#323e4f",
"#322947",
"#473b78",
"#4b5bab",
"#4da6ff",
"#66ffe3",
"#ffffeb",
"#c2c2d1",
"#7e7e8... | colors = ['#5e315b', '#8c3f5d', '#ba6156', '#f2a65e', '#ffe478', '#cfff70', '#8fde5d', '#3ca370', '#3d6e70', '#323e4f', '#322947', '#473b78', '#4b5bab', '#4da6ff', '#66ffe3', '#ffffeb', '#c2c2d1', '#7e7e8f', '#606070', '#43434f', '#272736', '#3e2347', '#57294b', '#964253', '#e36956', '#ffb570', '#ff9166', '#eb564b', '#... |
fout = open('output.txt', 'w')
line1 = "This here's the wattle,\n"
fout.write(line1)
line2 = "the emblem of our land.\n"
fout.write(line2)
fout.close()
| fout = open('output.txt', 'w')
line1 = "This here's the wattle,\n"
fout.write(line1)
line2 = 'the emblem of our land.\n'
fout.write(line2)
fout.close() |
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
"""Prefix sum.
Running time: O(n) where n is the length of A.
"""
n = len(A)
pre = 0
res = 0
d = {0: 1}
for a in A:
pre = (pre + a) % K
res += d.get(pre, 0... | class Solution:
def subarrays_div_by_k(self, A: List[int], K: int) -> int:
"""Prefix sum.
Running time: O(n) where n is the length of A.
"""
n = len(A)
pre = 0
res = 0
d = {0: 1}
for a in A:
pre = (pre + a) % K
res += d.get(pr... |
def unique_markers(n_markers):
"""Returns a unique list of distinguishable markers. These are predominantly based
on the default seaborn markers.
Parameters
----------
n_markers
The number of markers to return (max=11).
"""
markers = [
"circle",
"x",
"diamon... | def unique_markers(n_markers):
"""Returns a unique list of distinguishable markers. These are predominantly based
on the default seaborn markers.
Parameters
----------
n_markers
The number of markers to return (max=11).
"""
markers = ['circle', 'x', 'diamond', 'cross', 'square', 'st... |
"""
This file contains the functional tests for the `devices` blueprint.
These tests use GETs and POSTs to different URLs to check for the
proper behavior of the `devices` blueprint.
"""
def test_inventory(client):
"""
GIVEN a Flask application configured for testing
WHEN the '/inventory/<category>' page... | """
This file contains the functional tests for the `devices` blueprint.
These tests use GETs and POSTs to different URLs to check for the
proper behavior of the `devices` blueprint.
"""
def test_inventory(client):
"""
GIVEN a Flask application configured for testing
WHEN the '/inventory/<category>' page ... |
def main(fn):
with open(fn, 'r') as f:
lines = [li.strip() for li in f.readlines()]
cmds = list()
for li in lines:
fields = li.split()
cmds.append([fields[0], int(fields[1])])
is_looping, acc = run(cmds)
print(acc)
for i in range(len(cmds)):
if not flip_cmd(cmds... | def main(fn):
with open(fn, 'r') as f:
lines = [li.strip() for li in f.readlines()]
cmds = list()
for li in lines:
fields = li.split()
cmds.append([fields[0], int(fields[1])])
(is_looping, acc) = run(cmds)
print(acc)
for i in range(len(cmds)):
if not flip_cmd(cmds... |
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def dfs(word, idx, r, c):
m, n = len(board), len(board[0])
if idx == len(word):
return True
if (... | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def dfs(word, idx, r, c):
(m, n) = (len(board), len(board[0]))
if idx == len(word):
return True
... |
print ('hello world')
print ('hello second time')
print ('Again and Again')
| print('hello world')
print('hello second time')
print('Again and Again') |
#!/usr/bin/env python3
disc_size = [17, 19, 7, 13, 5, 3]
disc_pos = [5, 8, 1, 7, 1, 0]
def solve():
shift_pos = [(disc_pos[i]+i+1)%disc_size[i] for i in range(len(disc_pos))]
t = 0
while max(shift_pos) != 0:
shift_pos = [(shift_pos[i]+1)%disc_size[i] for i in range(len(shift_pos))]
t += 1... | disc_size = [17, 19, 7, 13, 5, 3]
disc_pos = [5, 8, 1, 7, 1, 0]
def solve():
shift_pos = [(disc_pos[i] + i + 1) % disc_size[i] for i in range(len(disc_pos))]
t = 0
while max(shift_pos) != 0:
shift_pos = [(shift_pos[i] + 1) % disc_size[i] for i in range(len(shift_pos))]
t += 1
print(t)
s... |
'''
enable extension for this user
link :
https://bits.bitcoin.org.hk/extensions?usr=dd09c7b0fe33480ab28252c9c9b85c6b&enable=lnurlp
create a lnurlp pay link
needs an admin key
POST /lnurlp/api/v1/links
Headers
{"X-Api-Key": <admin_key>}
Body (application/json)
{"description": <string> "amount": <integer> "max": ... | """
enable extension for this user
link :
https://bits.bitcoin.org.hk/extensions?usr=dd09c7b0fe33480ab28252c9c9b85c6b&enable=lnurlp
create a lnurlp pay link
needs an admin key
POST /lnurlp/api/v1/links
Headers
{"X-Api-Key": <admin_key>}
Body (application/json)
{"description": <string> "amount": <integer> "max": <... |
"""
Person class
"""
# Create a Person class with the following properties
# 1. name
# 2. age
# 3. social security number
| """
Person class
""" |
class Config:
def __init__(self):
self.DARKNET_PATH = "lib/pyyolo/darknet"
self.DATACFG = "data/obj.data"
self.CFGFILE = "cfg/yolo-obj.cfg"
self.WEIGHTFILE_SKETCH = "models/yolo-obj_final_sketch.weights"
self.WEIGHTFILE_TEMPLATES = "models/yolo-obj_45000.weights"
self... | class Config:
def __init__(self):
self.DARKNET_PATH = 'lib/pyyolo/darknet'
self.DATACFG = 'data/obj.data'
self.CFGFILE = 'cfg/yolo-obj.cfg'
self.WEIGHTFILE_SKETCH = 'models/yolo-obj_final_sketch.weights'
self.WEIGHTFILE_TEMPLATES = 'models/yolo-obj_45000.weights'
sel... |
# coding = utf-8
# Create date: 2018-11-6
# Author :Bowen Lee
def test_kernel_headers(ros_kvm_init, cloud_config_url):
command = 'sleep 10; sudo system-docker inspect kernel-headers'
kwargs = dict(cloud_config='{url}test_kernel_headers.yml'.format(url=cloud_config_url),
is_install_to_hard_dr... | def test_kernel_headers(ros_kvm_init, cloud_config_url):
command = 'sleep 10; sudo system-docker inspect kernel-headers'
kwargs = dict(cloud_config='{url}test_kernel_headers.yml'.format(url=cloud_config_url), is_install_to_hard_drive=True)
tuple_return = ros_kvm_init(**kwargs)
client = tuple_return[0]
... |
NAME='router_xmldir'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['router_xmldir']
| name = 'router_xmldir'
cflags = []
ldflags = []
libs = []
gcc_list = ['router_xmldir'] |
class Solution:
def brokenCalc(self, X, Y):
res = 0
while X < Y:
res += Y % 2 + 1
Y = (Y + 1) // 2
return res + X - Y | class Solution:
def broken_calc(self, X, Y):
res = 0
while X < Y:
res += Y % 2 + 1
y = (Y + 1) // 2
return res + X - Y |
class RemoteDockerException(RuntimeError):
pass
class InstanceNotRunning(RemoteDockerException):
pass
| class Remotedockerexception(RuntimeError):
pass
class Instancenotrunning(RemoteDockerException):
pass |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
self.ix = 0
self.... | class Solution:
def flip_match_voyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
self.ix = 0
self.flipped = []
self.n = len(voyage)
def preorder(node):
if node:
if node.val == voyage[self.ix]:
self.ix += 1
... |
"""
@author: magician
@date: 2019/12/19
@file: key_word_demo.py
"""
def safe_division(number, divisor, ignore_overflow=False, ignore_zero_division=False):
"""
safe_division
:param number:
:param divisor:
:param ignore_overflow:
:param ignore_zero_division:
:return:
"""
... | """
@author: magician
@date: 2019/12/19
@file: key_word_demo.py
"""
def safe_division(number, divisor, ignore_overflow=False, ignore_zero_division=False):
"""
safe_division
:param number:
:param divisor:
:param ignore_overflow:
:param ignore_zero_division:
:return:
"""
t... |
def run_api_workflow_with_assertions(workflow_specification, current_request, test_context):
current_request_result = current_request(test_context)
if current_request_result is not None and current_request_result["continue_workflow"]:
run_api_workflow_with_assertions(
workflow_specification,... | def run_api_workflow_with_assertions(workflow_specification, current_request, test_context):
current_request_result = current_request(test_context)
if current_request_result is not None and current_request_result['continue_workflow']:
run_api_workflow_with_assertions(workflow_specification, workflow_spe... |
INPUT_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Deriva Demo Input",
"description": ("Input schema for the demo DERIVA ingest Action Provider. This Action "
"Provider can restore a DERIVA backup to a new or existing catalog, "
"or creat... | input_schema = {'$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'Deriva Demo Input', 'description': 'Input schema for the demo DERIVA ingest Action Provider. This Action Provider can restore a DERIVA backup to a new or existing catalog, or create a new DERIVA catalog from a BDBag containing TableSchema.'... |
h,m,s = map(int, input().split())
s += (m*60 + h*3600 + int(input()))
h = s//3600
m = (s%3600)//60
s = (s%3600)%60
if h>23:
h %= 24
print(h,m,s)
| (h, m, s) = map(int, input().split())
s += m * 60 + h * 3600 + int(input())
h = s // 3600
m = s % 3600 // 60
s = s % 3600 % 60
if h > 23:
h %= 24
print(h, m, s) |
#!/usr/bin/env python3
def main():
s = 0
for j in range(1, 1001):
s += j ** j
print(str(s)[-10:])
if __name__ == '__main__':
main()
| def main():
s = 0
for j in range(1, 1001):
s += j ** j
print(str(s)[-10:])
if __name__ == '__main__':
main() |
"""
Audio segment
"""
class Segment():
"""
Audio segment
"""
def __init__(self, waveform, boundaries, sample_rate, channel):
self._waveform = waveform
self._boundaries = boundaries
self._sample_rate = sample_rate
self._channel = channel
@property
def waveform(... | """
Audio segment
"""
class Segment:
"""
Audio segment
"""
def __init__(self, waveform, boundaries, sample_rate, channel):
self._waveform = waveform
self._boundaries = boundaries
self._sample_rate = sample_rate
self._channel = channel
@property
def waveform(sel... |
f = open("thirteen.txt", "r")
lines = [x.strip() for x in f.readlines()]
dots = []
for line in lines:
if line == "":
break
p = line.split(",")
dots.append((int(p[0]), int(p[1])))
folds = [line.split()[2] for line in lines if line.startswith("fold along ")]
fold = folds[0]
dir = fold[0]
line ... | f = open('thirteen.txt', 'r')
lines = [x.strip() for x in f.readlines()]
dots = []
for line in lines:
if line == '':
break
p = line.split(',')
dots.append((int(p[0]), int(p[1])))
folds = [line.split()[2] for line in lines if line.startswith('fold along ')]
fold = folds[0]
dir = fold[0]
line = int(fo... |
class FormattedTextRun(object, IDisposable):
""" A structure that defines a single run of a formatted text. """
def Dispose(self):
""" Dispose(self: FormattedTextRun) """
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: FormattedTextRun,d... | class Formattedtextrun(object, IDisposable):
""" A structure that defines a single run of a formatted text. """
def dispose(self):
""" Dispose(self: FormattedTextRun) """
pass
def release_unmanaged_resources(self, *args):
""" ReleaseUnmanagedResources(self: FormattedTextRun,disposi... |
def test_register_get(client, captured_templates):
"""
GIVEN a Flask application configured for testing (client)
WHEN the '/' route is requested (GET)
THEN there should be the correct `status_code`, `template.name`,
and the correct `page_title` in the context
"""
# mimic a browser: 'GE... | def test_register_get(client, captured_templates):
"""
GIVEN a Flask application configured for testing (client)
WHEN the '/' route is requested (GET)
THEN there should be the correct `status_code`, `template.name`,
and the correct `page_title` in the context
"""
response = client.get(... |
class Solution:
# @param A : integer
# @return a list of strings
def fizzBuzz(self, n):
result = []
for i in range(1, n+1):
s = ''
if i %3 == 0:
s += 'Fizz'
if i % 5 == 0:
s += 'Buzz'
if s == ''... | class Solution:
def fizz_buzz(self, n):
result = []
for i in range(1, n + 1):
s = ''
if i % 3 == 0:
s += 'Fizz'
if i % 5 == 0:
s += 'Buzz'
if s == '':
result.append(i)
else:
r... |
class Tag:
_major: str
_minor: str
_separator: str
_factors: dict
def __init__(self, major: str, minor="", separator="", **kwargs):
self._major = major
self._minor = minor
self._separator = separator
self._factors = kwargs
@property
def major(self) -> str:
... | class Tag:
_major: str
_minor: str
_separator: str
_factors: dict
def __init__(self, major: str, minor='', separator='', **kwargs):
self._major = major
self._minor = minor
self._separator = separator
self._factors = kwargs
@property
def major(self) -> str:
... |
def boyer_moore_bad_environment(A, p, m, k):
bad_table = {(i, a): True for i in range(1, m + 1) for a in A}
for i in range(1, m + 1):
for j in range(max(0, i - k), min(i + k, m) + 1):
bad_table[(j, p[i])] = False
return bad_table
def boyer_moore_multi_dim_shift(A, p, m, k):
ready = {a: m + 1 for a i... | def boyer_moore_bad_environment(A, p, m, k):
bad_table = {(i, a): True for i in range(1, m + 1) for a in A}
for i in range(1, m + 1):
for j in range(max(0, i - k), min(i + k, m) + 1):
bad_table[j, p[i]] = False
return bad_table
def boyer_moore_multi_dim_shift(A, p, m, k):
ready = {a... |
# dfir_ntfs: an NTFS parser for digital forensics & incident response
# (c) Maxim Suhanov
__version__ = '1.0.3'
__all__ = [ 'MFT', 'Attributes', 'WSL', 'USN', 'LogFile', 'BootSector', 'ShadowCopy', 'PartitionTable' ]
| __version__ = '1.0.3'
__all__ = ['MFT', 'Attributes', 'WSL', 'USN', 'LogFile', 'BootSector', 'ShadowCopy', 'PartitionTable'] |
# motorsports.vehicles
# description
#
# Author: Allen Leis <allen.leis@georgetown.edu>
# Created: Fri Sep 11 23:22:32 2015 -0400
#
# Copyright (C) 2015 georgetown.edu
# For license information, see LICENSE.txt
#
# ID: vehicles.py [] allen.leis@georgetown.edu $
"""
A module to supply building related classes
"""
#... | """
A module to supply building related classes
"""
class Basevehicle(object):
def __init__(self):
self._state = None
@property
def state(self):
"""
return a string describing the state of the vehicle
"""
return self._state or 'stopped'
@property
def descr... |
# obtain the comma-separated value from the user
csv = input("Enter string: ")
# split the string by the coma and save it in a list
csv = csv.split(',')
# displaying each of the variables
# csv[0] is the name
# csv[1] is the age
# csv[2] is the phone number
print('\n{0:=<30}\nName: {1:30}\nAge: {2:30}\nContact: {3:30... | csv = input('Enter string: ')
csv = csv.split(',')
print('\n{0:=<30}\nName: {1:30}\nAge: {2:30}\nContact: {3:30}\n{4:=<30}\n'.format('', csv[0], csv[1], csv[2], '')) |
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
arr = []
for i in nums:
sq = i*i
arr.append(sq)
return sorted(arr) | class Solution:
def sorted_squares(self, nums: List[int]) -> List[int]:
arr = []
for i in nums:
sq = i * i
arr.append(sq)
return sorted(arr) |
# Fibonacci numbers
def fibs(_to, _from=0):
'''
Returns a given range of fibonacci sequence. Both indexes are included.
fibonacci_sequence[_from:_to]
param _to: int [required] - upper index of requested range
param _from: int [optional] - lower index of requested range
returns: list... | def fibs(_to, _from=0):
"""
Returns a given range of fibonacci sequence. Both indexes are included.
fibonacci_sequence[_from:_to]
param _to: int [required] - upper index of requested range
param _from: int [optional] - lower index of requested range
returns: list - requested range of fibonac... |
def greedy_player_mgt(game_mgr):
game_mgr = game_mgr
def fn_get_action(pieces):
valid_moves = game_mgr.fn_get_valid_moves(pieces, 1)
if valid_moves is None:
return None
candidates = []
for a in range(game_mgr.fn_get_action_size()):
if valid_moves[a]==0:... | def greedy_player_mgt(game_mgr):
game_mgr = game_mgr
def fn_get_action(pieces):
valid_moves = game_mgr.fn_get_valid_moves(pieces, 1)
if valid_moves is None:
return None
candidates = []
for a in range(game_mgr.fn_get_action_size()):
if valid_moves[a] == 0:... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def maximumPopulation(self, logs):
"""
:type logs: List[List[int]]
:rtype: int
"""
MIN_YEAR, MAX_YEAR = 1950, 2050
years = [0]*(MAX_YEAR-MIN_YEAR+1)
for s, e in logs:
years[s-MIN_YEAR] += 1
... | class Solution(object):
def maximum_population(self, logs):
"""
:type logs: List[List[int]]
:rtype: int
"""
(min_year, max_year) = (1950, 2050)
years = [0] * (MAX_YEAR - MIN_YEAR + 1)
for (s, e) in logs:
years[s - MIN_YEAR] += 1
years[... |
# Time: O(1), per move.
# Space: O(n^2)
class TicTacToe(object):
def __init__(self, n):
"""
Initialize your data structure here.
:type n: int
"""
self.__rows = [[0, 0] for _ in xrange(n)]
self.__cols = [[0, 0] for _ in xrange(n)]
self.__diagonal = [0, 0]
... | class Tictactoe(object):
def __init__(self, n):
"""
Initialize your data structure here.
:type n: int
"""
self.__rows = [[0, 0] for _ in xrange(n)]
self.__cols = [[0, 0] for _ in xrange(n)]
self.__diagonal = [0, 0]
self.__anti_diagonal = [0, 0]
d... |
# Lists in Python are mutable objects that may contain
# any number of items of different types
my_list = [1, "Hello", True, 3.4]
# Python allows negative indexing
my_list = [1, 2, 3, 4, 5, 6]
print(my_list[-1])
# We can access a range of items within the list using slicing
# my_list[start:stop:step]
my_list = ['H', ... | my_list = [1, 'Hello', True, 3.4]
my_list = [1, 2, 3, 4, 5, 6]
print(my_list[-1])
my_list = ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
print(my_list[2:5])
print(my_list[5:])
print(my_list[:-2])
print(my_list[::-1])
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
my_list.insert(2, 7)
print(my_list)
print(my_list.pop... |
l = [2, 5, 6, 5, 11]
def isPal(x):
str_num = str(x)
if len(str_num) == 1:
return True
if len(str_num) % 2 != 0:
mid = int(len(str_num)/2)
front = str_num[:mid]
back = str_num[mid+1:]
else:
mid = int(len(str_num)/2)
front = str_num[:mid]
back =... | l = [2, 5, 6, 5, 11]
def is_pal(x):
str_num = str(x)
if len(str_num) == 1:
return True
if len(str_num) % 2 != 0:
mid = int(len(str_num) / 2)
front = str_num[:mid]
back = str_num[mid + 1:]
else:
mid = int(len(str_num) / 2)
front = str_num[:mid]
bac... |
# take two input numbers
number1 = input("Insert first number : ")
number2 = input("Insert second number : ")
operator = input("Insert operator (+ or - or * or /)")
if operator == '+':
total = number1 + number2
elif operator == '-':
total = number1 - number2
elif operator == '*':
total = number... | number1 = input('Insert first number : ')
number2 = input('Insert second number : ')
operator = input('Insert operator (+ or - or * or /)')
if operator == '+':
total = number1 + number2
elif operator == '-':
total = number1 - number2
elif operator == '*':
total = number2 * number1
elif operator == '/':
... |
"""
File containing all local variable necessary for the script to run
"""
#Enter your domain name. A value beginning with a period can be used as a subdomain wildcard.
DOMAIN = ".locktopus.fr"
#PATHS :
DEVELOPMENT_SETTINGS_FILE_PATH = "../locktopus/web_project/settings.py" | """
File containing all local variable necessary for the script to run
"""
domain = '.locktopus.fr'
development_settings_file_path = '../locktopus/web_project/settings.py' |
# https://leetcode.com/problems/gray-code/
#
# algorithms
# Easy (35.75%)
# Total Accepted: 365,649
# Total Submissions: 1,022,741
# beats 95.52% of python submissions
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums... | class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while m and n:
if nums1[m - 1]... |
# Geometry.py
# Tasks
# Write these functions to calculate following tasks
# 1. Areas ==> Circle, Triangle, Reactangle, Square,..
# 2. Volumes ==> Sphere, Pyramid, Prism, Cone,
def rectangle(width, length):
return width * length
def perimeter_rect(width, length):
return 2*width + 2*length
def triangle(base,... | def rectangle(width, length):
return width * length
def perimeter_rect(width, length):
return 2 * width + 2 * length
def triangle(base, height):
return 0.5 * base * height
def perimeter_triangle(a, b, c):
return a + b + c
if __name__ == '__main__':
print('Geometry.py')
area_rect = rectangle(1... |
def pascal(p):
result = []
for i in range(p):
if i == 0:
result.append([1])
else:
result.append([1] + [result[i - 1][j] + result[i - 1][j + 1] for j in range(len(result[i - 1]) - 1)] + [1])
return result | def pascal(p):
result = []
for i in range(p):
if i == 0:
result.append([1])
else:
result.append([1] + [result[i - 1][j] + result[i - 1][j + 1] for j in range(len(result[i - 1]) - 1)] + [1])
return result |
def encode(key: str, txt: str):
txt_c = ''
for index in range(0, len(txt)):
txt_int = ord(txt[index].lower()) + (ord(key[index % len(key)].upper()) - 65)
if txt_int > 122:
txt_int = txt_int - 26
if txt_int < 97 or txt_int > 122:
txt_c = txt_c + txt[index]
... | def encode(key: str, txt: str):
txt_c = ''
for index in range(0, len(txt)):
txt_int = ord(txt[index].lower()) + (ord(key[index % len(key)].upper()) - 65)
if txt_int > 122:
txt_int = txt_int - 26
if txt_int < 97 or txt_int > 122:
txt_c = txt_c + txt[index]
... |
# Class to store Trie(Patterns)
# It handles all cases particularly the case where a pattern Pi is a subtext of a pattern Pj for i != j
class Trie_Patterns:
def __init__(self, patterns, start, end):
self.build_trie(patterns, start, end)
# The trie will be a dictionary of dictionaries where:
# ... T... | class Trie_Patterns:
def __init__(self, patterns, start, end):
self.build_trie(patterns, start, end)
def build_trie(self, patterns, start, end):
self.trie = dict()
self.trie[0] = dict()
self.node_patterns_mapping = dict()
self.max_node_no = 0
for i in range(len(... |
def trikotniska_stevila(n):
vsota = 0
for i in range(1, n + 1):
vsota += i
return vsota
def najdi():
j = 0
n = 0
st_deliteljev = 0
while st_deliteljev <= 500:
st_deliteljev = 0
j += 1
n = trikotniska_stevila(j)
i = 1
while i <= n ** 0.5:
... | def trikotniska_stevila(n):
vsota = 0
for i in range(1, n + 1):
vsota += i
return vsota
def najdi():
j = 0
n = 0
st_deliteljev = 0
while st_deliteljev <= 500:
st_deliteljev = 0
j += 1
n = trikotniska_stevila(j)
i = 1
while i <= n ** 0.5:
... |
pid_yaw = rm_ctrl.PIDCtrl()
list_LineList = RmList()
variable_X = 0
def start():
global variable_X
global list_LineList
global pid_yaw
robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow)
# rotate gimbal downward so the line is more visible
gimbal_ctrl.pitch_ctrl(-20)
# enable line det... | pid_yaw = rm_ctrl.PIDCtrl()
list__line_list = rm_list()
variable_x = 0
def start():
global variable_X
global list_LineList
global pid_yaw
robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow)
gimbal_ctrl.pitch_ctrl(-20)
vision_ctrl.enable_detection(rm_define.vision_detection_line)
vision... |
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
def product(*x):
sum = 1
if len(x) > 0:
for item in x:
sum = item * sum
print(sum)
def tr... | def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
def product(*x):
sum = 1
if len(x) > 0:
for item in x:
sum = item * sum
print(sum)
def trim(... |
# def form_list():
# with open("words.txt",'r') as f:
# import pdb; pdb.set_trace()
# data=f.readlines()
# form_list()
data=['TEMPERATURE', 'PARTICULAR', 'INSTRUMENT', 'EXPERIMENT', 'EXPERIENCE', 'ESPECIALLY', 'DICTIONARY', 'SUBSTANCE', 'REPRESENT', 'PARAGRAPH', 'NECESSARY', 'DIFFICULT', '... | data = ['TEMPERATURE', 'PARTICULAR', 'INSTRUMENT', 'EXPERIMENT', 'EXPERIENCE', 'ESPECIALLY', 'DICTIONARY', 'SUBSTANCE', 'REPRESENT', 'PARAGRAPH', 'NECESSARY', 'DIFFICULT', 'DETERMINE', 'CONTINENT', 'CONSONANT', 'CONDITION', 'CHARACTER', 'TRIANGLE', 'TOGETHER', 'THOUSAND', 'SYLLABLE', 'SURPRISE', 'SUBTRACT', 'STRAIGHT',... |
# -*- coding: utf-8 -*-
"""
1534. Count Good Triplets
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b... | """
1534. Count Good Triplets
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
... |
#
# PySNMP MIB module HH3C-RADIUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-RADIUS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:29:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
#!/usr/bin/env python3
# python3 program of subtraction of
# two numbers using 2's complement .
# function to subtract two values
# using 2's complement method
def Subtract(a, b):
# ~b is the 1's Complement of b
# adding 1 to it make it 2's Complement
c = a + (~b + 1)
return c
# Driver code
if __na... | def subtract(a, b):
c = a + (~b + 1)
return c
if __name__ == '__main__':
(a, b) = (56, 22)
print(subtract(a, b)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.