content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Problem : Find out the missing number
Author : Alok Tripathi
"""
def getMissingNo(arr):
n = len(arr)
# Sum of (N+1) * (N+2) natural number [n is length of arr]
total = (n + 1) * (n + 2) / 2
sum_of_arr = sum(arr)
return int(total - sum_of_arr) # sum of n... natural no. - sum of array
if __... | """
Problem : Find out the missing number
Author : Alok Tripathi
"""
def get_missing_no(arr):
n = len(arr)
total = (n + 1) * (n + 2) / 2
sum_of_arr = sum(arr)
return int(total - sum_of_arr)
if __name__ == '__main__':
arr = [1, 2, 3, 5]
miss = get_missing_no(arr)
print(miss) |
a = int(input())
v = 0
for x in range(1,10+1):
print(v+1,"x",a,"=",a*(v+1))
v = v+ 1
| a = int(input())
v = 0
for x in range(1, 10 + 1):
print(v + 1, 'x', a, '=', a * (v + 1))
v = v + 1 |
"""
A OISC emulation using the Subleq operation.
Tom Findlay (findlaytel@gmail.com)
Feb. 2021
"""
class whisk:
def __init__(self, memory=30000):
self.memory = [0]*memory
def subleq(self,addr):
if addr < 0:
return None
A = self.memory[addr]
B = se... | """
A OISC emulation using the Subleq operation.
Tom Findlay (findlaytel@gmail.com)
Feb. 2021
"""
class Whisk:
def __init__(self, memory=30000):
self.memory = [0] * memory
def subleq(self, addr):
if addr < 0:
return None
a = self.memory[addr]
b = self.memory[addr... |
# Implementation using list
# Initializing queue using a list
myQueue = []
# Adding elements to the queue
myQueue.append(1)
myQueue.append(2)
myQueue.append(3)
# Printing the queue
print("Initial queue:", myQueue)
# Size of the queue
print("Size: ", len(myQueue))
# Check if queue is empty
if not myQueue:
print(... | my_queue = []
myQueue.append(1)
myQueue.append(2)
myQueue.append(3)
print('Initial queue:', myQueue)
print('Size: ', len(myQueue))
if not myQueue:
print('Queue is empty')
else:
print('Queue is not empty')
print('First element in the queue: ', myQueue[0])
print('Dequeued element:', myQueue.pop(0))
print('Queue a... |
#!/usr/bin/env python3
def merge(A,l,m,r):
L,R = A[l:m+1],A[m+1:r+1] #copied
L.append(float("inf"))
R.append(float("inf"))
i,j = 0,0
for k in range(l,r+1):
A[k]= L[i] if L[i]<R[j] else R[j]
i,j =(1+i,j) if L[i]<R[j] else (i,j+1)
def merge_sort(A,l,r):
if l<r:
m = l+((... | def merge(A, l, m, r):
(l, r) = (A[l:m + 1], A[m + 1:r + 1])
L.append(float('inf'))
R.append(float('inf'))
(i, j) = (0, 0)
for k in range(l, r + 1):
A[k] = L[i] if L[i] < R[j] else R[j]
(i, j) = (1 + i, j) if L[i] < R[j] else (i, j + 1)
def merge_sort(A, l, r):
if l < r:
... |
# str(Color())
class Color:
color = 'orange'
def __str__(self):
return Color.color
print(str(Color()))
| class Color:
color = 'orange'
def __str__(self):
return Color.color
print(str(color())) |
# 1. Define a function that accepts 2 values and returns
# its sum, subtraction and multiplication.
# SOLUTION:
def result(a, b):
sum = a+b
sub = a-b
mul = a*b
print(f"Sum is {sum}, Sub is {sub}, & Multiply is {mul}")
a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
resul... | def result(a, b):
sum = a + b
sub = a - b
mul = a * b
print(f'Sum is {sum}, Sub is {sub}, & Multiply is {mul}')
a = int(input('Enter value of a: '))
b = int(input('Enter value of b: '))
result(a, b)
def max(a, b, c):
if a > b and a > c:
print(f'{a} is maximum among all')
elif b > a and ... |
################################################################
### User input parameters for C3S-LAA
################################################################
### Required dependencies and input files
# Path for the AMOS package that contains minimus assembler
amos_path = "/usr/local/amos/bin/"
... | amos_path = '/usr/local/amos/bin/'
primer_info_file = 'primer_pairs_info.txt'
barcode_info_file = 'barcode_pairs_info.txt'
fofn = '/mnt/data27/ffrancis/PacBio_sequence_files/EqPCR_raw/F03_1/Analysis_Results/m160901_060459_42157_c101086112550000001823264003091775_s1_p0.bas.h5'
ccs = '/mnt/data27/ffrancis/PacBio_sequence... |
# general
make_debug = False
make_task = ""
build_type = "Release"
app_name = "MyApp"
| make_debug = False
make_task = ''
build_type = 'Release'
app_name = 'MyApp' |
sum = 0
for num in range(1,1000):
if (num % 3 == 0 or num % 5 == 0):
sum += num
print(sum) | sum = 0
for num in range(1, 1000):
if num % 3 == 0 or num % 5 == 0:
sum += num
print(sum) |
def split_lines(el):
return el.split('\n')
split_lines('10\n is\n the\n perfect\n number')
| def split_lines(el):
return el.split('\n')
split_lines('10\n is\n the\n perfect\n number') |
class Solution:
# @param {integer[]} prices
# @return {integer}
def maxProfit(self, prices):
if len(prices) < 2:
return 0
minn = prices[:-1]
maxn = prices[1:]
mi = minn[0]
for i in range(1, len(minn)):
if minn[i] > mi:
minn[i]... | class Solution:
def max_profit(self, prices):
if len(prices) < 2:
return 0
minn = prices[:-1]
maxn = prices[1:]
mi = minn[0]
for i in range(1, len(minn)):
if minn[i] > mi:
minn[i] = mi
else:
mi = minn[i]
... |
class ManagedFile:
"""
Manager for open with context manager
"""
def __init__(self,name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type,exc_val, exc_tb):
if self.file:
self.file.clos... | class Managedfile:
"""
Manager for open with context manager
"""
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file... |
__all__ = ['UndefinedType', 'undefined']
class _SingletonMeta(type):
def __call__(self, *args, **kwargs):
if not hasattr(self, '__instance__'):
self.__instance__ = super().__call__(*args, **kwargs)
return self.__instance__
class UndefinedType(metaclass=_SingletonMeta):
... | __all__ = ['UndefinedType', 'undefined']
class _Singletonmeta(type):
def __call__(self, *args, **kwargs):
if not hasattr(self, '__instance__'):
self.__instance__ = super().__call__(*args, **kwargs)
return self.__instance__
class Undefinedtype(metaclass=_SingletonMeta):
"""A new si... |
def bubbleSort(alist):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
pr... | def bubble_sort(alist):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubble_sort(alist)
pr... |
def format_search_terms(search_terms):
s=''
q=[]
if search_terms != None:
for term in search_terms:
q.append(term)
q.append('%20')
s= ''.join(q)
return s
def format_from_user(from_user):
s=''
q=[]
if from_user != None:
q.append('from%3A')
... | def format_search_terms(search_terms):
s = ''
q = []
if search_terms != None:
for term in search_terms:
q.append(term)
q.append('%20')
s = ''.join(q)
return s
def format_from_user(from_user):
s = ''
q = []
if from_user != None:
q.append('from%... |
class EventBrokerError(Exception):
pass
class EventBrokerAuthError(EventBrokerError):
pass
| class Eventbrokererror(Exception):
pass
class Eventbrokerautherror(EventBrokerError):
pass |
# We'll use a greedy algorithm to check to see if we have a
# new max sum as we iterate along the along. If at any time
# our sum becomes negative, we reset the sum.
def largestContiguousSum(arr):
maxSum = 0
currentSum = 0
for i, _ in enumerate(arr):
currentSum += arr[i]
max... | def largest_contiguous_sum(arr):
max_sum = 0
current_sum = 0
for (i, _) in enumerate(arr):
current_sum += arr[i]
max_sum = max(currentSum, maxSum)
if currentSum < 0:
current_sum = 0
return maxSum
print(largest_contiguous_sum([5, -9, 6, -2, 3]))
print(largest_contiguou... |
def diagonalDifference(arr):
diagonal1 = 0
diagonal2 = 0
for pos, line in enumerate(arr):
diagonal1 += line[pos]
diagonal2 += line[len(arr)-1 - pos]
return abs(diagonal1 - diagonal2)
| def diagonal_difference(arr):
diagonal1 = 0
diagonal2 = 0
for (pos, line) in enumerate(arr):
diagonal1 += line[pos]
diagonal2 += line[len(arr) - 1 - pos]
return abs(diagonal1 - diagonal2) |
class MaterialSubsurfaceScattering:
back = None
color = None
color_factor = None
error_threshold = None
front = None
ior = None
radius = None
scale = None
texture_factor = None
use = None
| class Materialsubsurfacescattering:
back = None
color = None
color_factor = None
error_threshold = None
front = None
ior = None
radius = None
scale = None
texture_factor = None
use = None |
shiboken_library_soversion = str(6.1)
version = "6.1.1"
version_info = (6, 1, 1, "", "")
__build_date__ = '2021-06-03T07:46:50+00:00'
__setup_py_package_version__ = '6.1.1'
| shiboken_library_soversion = str(6.1)
version = '6.1.1'
version_info = (6, 1, 1, '', '')
__build_date__ = '2021-06-03T07:46:50+00:00'
__setup_py_package_version__ = '6.1.1' |
# S1
input_list = []
for i in range(int(6)):
input_list.append(input())
win_counter = 0
loss_counter = 0
for i in input_list:
if i == "W":
win_counter += 1
else:
loss_counter += 1
if win_counter == 1 or win_counter == 2:
print("3")
elif win_counter == 3 or win_counter == 4:
print("2"... | input_list = []
for i in range(int(6)):
input_list.append(input())
win_counter = 0
loss_counter = 0
for i in input_list:
if i == 'W':
win_counter += 1
else:
loss_counter += 1
if win_counter == 1 or win_counter == 2:
print('3')
elif win_counter == 3 or win_counter == 4:
print('2')
eli... |
"""
Given a list of possibly overlapping intervals, return a new list of
intervals where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should
return [(1, 3), (4, 10), (20, 25)].
Source: Daily Coding Prob... | """
Given a list of possibly overlapping intervals, return a new list of
intervals where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should
return [(1, 3), (4, 10), (20, 25)].
Source: Daily Coding Prob... |
class Evaluator:
@staticmethod
def zip_evaluate(coefs, words):
if (len(coefs) != len(words)):
return -1
return sum([coeff * len(word) for (coeff, word)
in zip(coefs, words)])
@staticmethod
def enumerate_evaluate(coefs, words):
if (len(coefs) != le... | class Evaluator:
@staticmethod
def zip_evaluate(coefs, words):
if len(coefs) != len(words):
return -1
return sum([coeff * len(word) for (coeff, word) in zip(coefs, words)])
@staticmethod
def enumerate_evaluate(coefs, words):
if len(coefs) != len(words):
... |
# You are given an array of desired filenames in the order of their creation.
# Since two files cannot have equal names, the one which comes later will have
# an addition to its name in a form of (k), where k is the smallest positive
# integer such that the obtained name is not used yet.
#
# Return an array of names th... | def file_naming(names):
new_names = []
for name in names:
if name in new_names:
name = add_suffix(name, new_names)
new_names.append(name)
return new_names
def add_suffix(name, new_names):
count = 1
new_name = name + '(' + str(count) + ')'
while new_name in new_names:... |
load("@dwtj_rules_markdown//markdown:defs.bzl", "markdown_library")
def index_md(name = "index_md"):
markdown_library(
name = name,
srcs = ["INDEX.md"],
)
| load('@dwtj_rules_markdown//markdown:defs.bzl', 'markdown_library')
def index_md(name='index_md'):
markdown_library(name=name, srcs=['INDEX.md']) |
length_check_fields=['reset_pc', 'physical_addr_size']
bsc_cmd = '''bsc -u -verilog -elab -vdir {0} -bdir {1} -info-dir {1} \
+RTS -K40000M -RTS -check-assert -keep-fires \
-opt-undetermined-vals -remove-false-rules -remove-empty-rules \
-remove-starved-rules -remove-dollar -unspecified-to X -show-schedule \
-show-m... | length_check_fields = ['reset_pc', 'physical_addr_size']
bsc_cmd = 'bsc -u -verilog -elab -vdir {0} -bdir {1} -info-dir {1} +RTS -K40000M -RTS -check-assert -keep-fires -opt-undetermined-vals -remove-false-rules -remove-empty-rules -remove-starved-rules -remove-dollar -unspecified-to X -show-schedule -show-module-use ... |
BOT_NAME = 'naver_movie'
SPIDER_MODULES = ['naver_movie.spiders']
NEWSPIDER_MODULE = 'naver_movie.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 2
COOKIES_ENABLED = True
DEFAULT_REQUEST_HEADERS = {
"Referer": "https://movie.naver.com/"
}
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.useragent.U... | bot_name = 'naver_movie'
spider_modules = ['naver_movie.spiders']
newspider_module = 'naver_movie.spiders'
robotstxt_obey = False
download_delay = 2
cookies_enabled = True
default_request_headers = {'Referer': 'https://movie.naver.com/'}
downloader_middlewares = {'scrapy.downloadermiddlewares.useragent.UserAgentMiddlew... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
# print(head)
slow, fast = head, head
... | class Solution:
def is_palindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
(slow, fast) = (head, head)
pre = None
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
def ... |
#
# @lc app=leetcode id=557 lang=python
#
# [557] Reverse Words in a String III
#
# https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
#
# algorithms
# Easy (63.15%)
# Likes: 624
# Dislikes: 67
# Total Accepted: 127.4K
# Total Submissions: 198.3K
# Testcase Example: `"Let's take LeetCode co... | class Solution(object):
def _reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
sl = s.split()
ls = []
for l in sl:
ls.append(''.join(list(l)[::-1]))
return ' '.join(ls)
def __reverse_words(self, s):
"""
:type s:... |
n = float(input())
whole = int(n)
fractional = int(round((n % 1), 2) * 100)
print(whole, fractional)
| n = float(input())
whole = int(n)
fractional = int(round(n % 1, 2) * 100)
print(whole, fractional) |
class Spam(object):
def __init__(self, key, value):
self.list_ = [value]
self.dict_ = {key : value}
self.list_.append(value)
self.dict_[key] = value
print(f'List: {self.list_}')
print(f'Dict: {self.dict_}')
Spam('Key 1', 'Value 1')
Spam('Key 2', 'Value 2')
| class Spam(object):
def __init__(self, key, value):
self.list_ = [value]
self.dict_ = {key: value}
self.list_.append(value)
self.dict_[key] = value
print(f'List: {self.list_}')
print(f'Dict: {self.dict_}')
spam('Key 1', 'Value 1')
spam('Key 2', 'Value 2') |
lista = [5,7,9,2,4,3,1,6,8]
comparaciones = 0
for i in range(len(lista) -1): #recorre la lista
for j in range(len(lista)-1): #sirve para comparar los elementos de la lista
#print('Comparando: ' , lista[j], "con ", lista[j+1])
if(lista[j] > lista[j+1]):
#lista[j], lista[j+1] = lista[j+1] ... | lista = [5, 7, 9, 2, 4, 3, 1, 6, 8]
comparaciones = 0
for i in range(len(lista) - 1):
for j in range(len(lista) - 1):
if lista[j] > lista[j + 1]:
comparaciones += 1
temporal = lista[j]
lista[j] = lista[j + 1]
lista[j + 1] = temporal
print(lista)
print(... |
#
# PySNMP MIB module SW-TRUNK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-TRUNK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:05:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, single_value_constraint, constraints_union, value_range_constraint) ... |
class Twitter():
Consumer_Key = ''
Consumer_Secret = ''
Access_Token = ''
Access_Token_Secret = ''
CONNECTION_STRING = "sqlite:///Twitter.db"
LANG = ["en"]
| class Twitter:
consumer__key = ''
consumer__secret = ''
access__token = ''
access__token__secret = ''
connection_string = 'sqlite:///Twitter.db'
lang = ['en'] |
feature_types = {
# features with continuous numeric values
"continuous": [
"number_diagnoses",
"time_in_hospital",
"number_inpatient",
"number_emergency",
"num_procedures",
"num_medications",
"num_lab_procedures"],
# features which describe buckets o... | feature_types = {'continuous': ['number_diagnoses', 'time_in_hospital', 'number_inpatient', 'number_emergency', 'num_procedures', 'num_medications', 'num_lab_procedures'], 'range': ['age', 'weight'], 'categorical': ['diabetesMed', 'chlorpropamide', 'repaglinide', 'medical_specialty', 'rosiglitazone', 'miglitol', 'glipi... |
def main() :
#Create a set
lstOrganizations = {"sharjeelswork", "Fiserv", "R Systems"}
print(lstOrganizations) # Sets are unordered, so the items will appear in a random order.
"""Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you ca... | def main():
lst_organizations = {'sharjeelswork', 'Fiserv', 'R Systems'}
print(lstOrganizations)
'Access Items\n\tYou cannot access items in a set by referring to an index, since sets are unordered the items has no index.\n\tBut you can loop through the set items using a for loop, or ask if a specified valu... |
while True:
try:
input()
alice = set(input().split())
beatriz = set(input().split())
repeticoes = [1 for carta in alice if carta in beatriz]
print(min([len(alice), len(beatriz)]) - len(repeticoes))
except EOFError:
break
| while True:
try:
input()
alice = set(input().split())
beatriz = set(input().split())
repeticoes = [1 for carta in alice if carta in beatriz]
print(min([len(alice), len(beatriz)]) - len(repeticoes))
except EOFError:
break |
def square(a):
return(a*a)
# a=int(input("enter the number"))
# square(a)
s=[2,3,4,5,6,7,8,9,10]
print(list(map(square,s)))
| def square(a):
return a * a
s = [2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(map(square, s))) |
"""
@file
@brief Exception for Mokadi.
"""
class MokadiException(Exception):
"""
Mokadi exception.
"""
pass # pylint: disable=W0107
class CognitiveException(Exception):
"""
Failure when calling the API.
"""
pass # pylint: disable=W0107
class WikipediaException(Exception):
"""... | """
@file
@brief Exception for Mokadi.
"""
class Mokadiexception(Exception):
"""
Mokadi exception.
"""
pass
class Cognitiveexception(Exception):
"""
Failure when calling the API.
"""
pass
class Wikipediaexception(Exception):
"""
Issue with :epkg:`wikipedia`.
"""
pass
... |
features = [
"mtarg1",
"mtarg2",
"mtarg3",
"roll",
"pitch",
"LACCX",
"LACCY",
"LACCZ",
"GYROX",
"GYROY",
"SC1I",
"SC2I",
"SC3I",
"BT1I",
"BT2I",
"vout",
"iout",
"cpuUsage",
]
fault_features = ["fault", "fault_type", "fault_value", "fault_duration"... | features = ['mtarg1', 'mtarg2', 'mtarg3', 'roll', 'pitch', 'LACCX', 'LACCY', 'LACCZ', 'GYROX', 'GYROY', 'SC1I', 'SC2I', 'SC3I', 'BT1I', 'BT2I', 'vout', 'iout', 'cpuUsage']
fault_features = ['fault', 'fault_type', 'fault_value', 'fault_duration'] |
READ_ME ="""
INDEXICAL is designed to assist in the creation of book indexes.
It offers the following functionality:
(1) Analyze a readable PDF, extracting capitalized phrases, italicized phrases,
phrases in double quotation marks, and phrases surrounding by parentheses.
(2) Filter through the results of (1)... | read_me = '\nINDEXICAL is designed to assist in the creation of book indexes.\n\nIt offers the following functionality:\n\n(1) Analyze a readable PDF, extracting capitalized phrases, italicized phrases,\nphrases in double quotation marks, and phrases surrounding by parentheses.\n\n(2) Filter through the results of (1) ... |
"""Implements a class for Latin Square puzzles.
A Latin Square is a square grid of numbers from 1..N, where a number may not
be repeated in the same row or column. Such squares form the basis of puzzles
like Sudoku, Kenken(tm), and their variants.
Classes:
LatinSquare: Implements a square puzzle constrained by no... | """Implements a class for Latin Square puzzles.
A Latin Square is a square grid of numbers from 1..N, where a number may not
be repeated in the same row or column. Such squares form the basis of puzzles
like Sudoku, Kenken(tm), and their variants.
Classes:
LatinSquare: Implements a square puzzle constrained by no... |
maxsimal = 0
while True:
a = int(input("Masukan bilangan = "))
if maxsimal < a:
maxsimal = a
if a == 0:
break
print("Bilangan Terbesarnya Adalah = ", maxsimal)
| maxsimal = 0
while True:
a = int(input('Masukan bilangan = '))
if maxsimal < a:
maxsimal = a
if a == 0:
break
print('Bilangan Terbesarnya Adalah = ', maxsimal) |
class Holding(object):
def __init__(self, name, symbol, sector, market_val_percent, market_value, number_of_shares):
self.name = name
self.symbol = symbol
self.sector = sector
self.market_val_percent = market_val_percent
self.market_value = market_value
self.number_... | class Holding(object):
def __init__(self, name, symbol, sector, market_val_percent, market_value, number_of_shares):
self.name = name
self.symbol = symbol
self.sector = sector
self.market_val_percent = market_val_percent
self.market_value = market_value
self.number_o... |
# rps data for the rock-paper-scissors portion of the red-green game
# to be imported by rg.cgi
# this file represents the "host throw" for each numbered round
rps_data = {
0: "rock",
1: "rock",
2: "scissors",
3: "paper",
4: "paper",
5: "scissors",
6: "rock",
7: "scissors",
8: "pape... | rps_data = {0: 'rock', 1: 'rock', 2: 'scissors', 3: 'paper', 4: 'paper', 5: 'scissors', 6: 'rock', 7: 'scissors', 8: 'paper', 9: 'paper', 10: 'scissors', 11: 'rock', 12: 'paper', 13: 'paper', 14: 'rock', 15: 'scissors', 16: 'scissors', 17: 'scissors', 18: 'rock', 19: 'scissors', 20: 'paper', 21: 'rock', 22: 'paper', 23... |
user_info = {}
while True:
print("\n\t\t\tUnits:metric")
name = str(input("Enter your name: "))
height = float(input("Input your height in meters(For instance:1.89): "))
weight = float(input("Input your weight in kilogram(For instance:69): "))
age = int(input("Input your age: "))
sex = str(input... | user_info = {}
while True:
print('\n\t\t\tUnits:metric')
name = str(input('Enter your name: '))
height = float(input('Input your height in meters(For instance:1.89): '))
weight = float(input('Input your weight in kilogram(For instance:69): '))
age = int(input('Input your age: '))
sex = str(input... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
def getHeaders(fileName):
headers = []
headerList = ['User-Agent','Cookie']
with open(fileName, 'r') as fp:
for line in fp.readlines():
name, value = line.split(':', 1)
if name in headerList:
headers.append((name.st... | def get_headers(fileName):
headers = []
header_list = ['User-Agent', 'Cookie']
with open(fileName, 'r') as fp:
for line in fp.readlines():
(name, value) = line.split(':', 1)
if name in headerList:
headers.append((name.strip(), value.strip()))
return header... |
class ComponentsAssembly:
def __init__(self, broker, strategy, datafeed, sizer, metrics_collection, *args):
self._components = [broker, strategy, datafeed, sizer, metrics_collection, *args]
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index ... | class Componentsassembly:
def __init__(self, broker, strategy, datafeed, sizer, metrics_collection, *args):
self._components = [broker, strategy, datafeed, sizer, metrics_collection, *args]
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < ... |
# Lecture 3.6, slide 2
# Defines the value to take the square root of, epsilon, and the number of guesses.
x = 9
epsilon = 0.01
numGuesses = 0
# Here, 0 < x < 1, then the low is x and the high is 1 - the sqrt(x) > x if 0 < x < 1.
# If x > 1, then the low is 0 and the high is x - the sqrt(x) < x if x > 1.
if (x >= 0 a... | x = 9
epsilon = 0.01
num_guesses = 0
if x >= 0 and x < 1:
low = x
high = 1.0
elif x >= 1:
low = 0.0
high = x
ans = (low + high) / 2.0
while abs(ans ** 2 - x) >= epsilon:
print('low = ' + str(low) + ' ; high = ' + str(high) + ' ; ans = ' + str(ans))
num_guesses += 1
if ans ** 2 < x:
l... |
# ctx.addClock("csi_rx_i.dphy_clk", 96)
# ctx.addClock("video_clk", 24)
# ctx.addClock("uart_i.sys_clk_i", 12)
ctx.addClock("EXTERNAL_CLK", 12)
# ctx.addClock("clk", 25)
| ctx.addClock('EXTERNAL_CLK', 12) |
class Solution:
def soupServings(self, N: int) -> float:
def dfs(a: int, b: int) -> float:
if a <= 0 and b <= 0:
return 0.5
if a <= 0:
return 1.0
if b <= 0:
return 0.0
if memo[a][b] > 0:
return memo[a][b]
memo[a][b] = 0.25 * (dfs(a - 4, b) +
... | class Solution:
def soup_servings(self, N: int) -> float:
def dfs(a: int, b: int) -> float:
if a <= 0 and b <= 0:
return 0.5
if a <= 0:
return 1.0
if b <= 0:
return 0.0
if memo[a][b] > 0:
return... |
# First we define a variable "to_find" which contains the alphabet to be checked for in the file
# fo is the file which is to be read.
to_find="e"
fo = open('E:/file1.txt' ,'r+')
count=0
for line in fo:
for word in line.split():
if word.find(to_find)!=-1:
count=count+1
print(... | to_find = 'e'
fo = open('E:/file1.txt', 'r+')
count = 0
for line in fo:
for word in line.split():
if word.find(to_find) != -1:
count = count + 1
print(count) |
DELIVERY_TYPES = (
(1, "Vaginal Birth"), # Execise care when changing...
(2, "Caesarian")
)
| delivery_types = ((1, 'Vaginal Birth'), (2, 'Caesarian')) |
class Solution:
def makeGood(self, s: str) -> str:
i = 0
string = list(s)
while i < len(string) - 1:
a = string[i]
b = string[i + 1]
if a.lower() == b.lower() and a != b:
string.pop(i)
string.pop(i)
i = 0
... | class Solution:
def make_good(self, s: str) -> str:
i = 0
string = list(s)
while i < len(string) - 1:
a = string[i]
b = string[i + 1]
if a.lower() == b.lower() and a != b:
string.pop(i)
string.pop(i)
i = 0
... |
l,j,k=[list(input()) for i in range(3)]
l.extend(j)
for i in l:
if i not in k :
k.append(i)
break
k.remove(i)
print('YES' if k==[] else 'NO')
| (l, j, k) = [list(input()) for i in range(3)]
l.extend(j)
for i in l:
if i not in k:
k.append(i)
break
k.remove(i)
print('YES' if k == [] else 'NO') |
#
# PySNMP MIB module CXQLLC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXQLLC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:33:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) ... |
class Solution:
"""
https://leetcode.com/problems/move-zeroes/
Given an array nums, write a function to move all 0's to the end of
it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your
function, nums should be [1, 3... | class Solution:
"""
https://leetcode.com/problems/move-zeroes/
Given an array nums, write a function to move all 0's to the end of
it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your
function, nums should be [1, 3... |
RGB2HEX = 1
RGB2HSV = 2
RGB2HSL = 3
HEX2RGB = 4
HSV2RGB = 5
OPCV_RGB2HSV = 100
OPCV_HSV2RGB = 101 | rgb2_hex = 1
rgb2_hsv = 2
rgb2_hsl = 3
hex2_rgb = 4
hsv2_rgb = 5
opcv_rgb2_hsv = 100
opcv_hsv2_rgb = 101 |
class ImageGroupsComponent:
def __init__(self, key=None, imageGroup=None):
self.key = 'imagegroups'
self.current = None
self.animationList = {}
self.alpha = 255
self.hue = None
self.playing = True
if key is not None and imageGroup is not None:
sel... | class Imagegroupscomponent:
def __init__(self, key=None, imageGroup=None):
self.key = 'imagegroups'
self.current = None
self.animationList = {}
self.alpha = 255
self.hue = None
self.playing = True
if key is not None and imageGroup is not None:
sel... |
class Tag(object):
def __init__(self, tag_name : str, type_ = None):
self.__tag_name = tag_name
self.__type : str = type_ if type_ is not None else ""
@property
def type(self) -> str:
return self.__type
@property
def name(self) -> str:
return self.__tag_name... | class Tag(object):
def __init__(self, tag_name: str, type_=None):
self.__tag_name = tag_name
self.__type: str = type_ if type_ is not None else ''
@property
def type(self) -> str:
return self.__type
@property
def name(self) -> str:
return self.__tag_name
def _... |
#First go
print("Hello, World!")
message = "Hello, World!"
print(message)
#-------> print "Hello World!" is Python 2 syntax, use print("Hello World!") for Python 3
| print('Hello, World!')
message = 'Hello, World!'
print(message) |
"""
This is a module defined in sub-package
It defines following importable objects
- two module top level functions
- one class
"""
def top_level_function1() -> None:
""" This is first top level function
"""
def top_level_function2() -> None:
""" This is second top level function
"""
class Clas... | """
This is a module defined in sub-package
It defines following importable objects
- two module top level functions
- one class
"""
def top_level_function1() -> None:
""" This is first top level function
"""
def top_level_function2() -> None:
""" This is second top level function
"""
class Class:
... |
# https://leetcode.com/problems/minimum-depth-of-binary-tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
if not root:
return 0
... | class Solution:
def min_depth(self, root):
if not root:
return 0
ans = set()
def helper(node, depth):
if not node.left and (not node.right):
ans.add(depth)
return
if node.right:
helper(node.right, depth + 1... |
EXCHANGE_CFFEX = 0
EXCHANGE_SHFE = 1
EXCHANGE_DCE = 2
EXCHANGE_SSEOPT = 3
EXCHANGE_CZCE = 4
EXCHANGE_SZSE = 5
EXCHANGE_SSE = 6
EXCHANGE_UNKNOWN = 7
| exchange_cffex = 0
exchange_shfe = 1
exchange_dce = 2
exchange_sseopt = 3
exchange_czce = 4
exchange_szse = 5
exchange_sse = 6
exchange_unknown = 7 |
numerator = int(input("Enter a numerator: "))
denominator = int(input("Enter denominator: "))
while denominator == 0:
print("Denominator cannot be 0")
denominator = int(input("Enter denominator: "))
if int(numerator / denominator) * denominator == numerator:
print("Divides evenly!")
else:
... | numerator = int(input('Enter a numerator: '))
denominator = int(input('Enter denominator: '))
while denominator == 0:
print('Denominator cannot be 0')
denominator = int(input('Enter denominator: '))
if int(numerator / denominator) * denominator == numerator:
print('Divides evenly!')
else:
print("Doesn't... |
class Solution:
#Function to find sum of weights of edges of the Minimum Spanning Tree.
def spanningTree(self, V, adj):
#code here
##findpar with rank compression
def findpar(x):
if parent[x]==x:
return x
else:
parent[x]=findpa... | class Solution:
def spanning_tree(self, V, adj):
def findpar(x):
if parent[x] == x:
return x
else:
parent[x] = findpar(parent[x])
return parent[x]
def union(x, y):
lp_x = findpar(x)
lp_y = findpar(y)
... |
class Pegawai:
def __init__(self, nama, email, gaji):
self.__namaPegawai = nama
self.__emailPegawai = email
self.__gajiPegawai = gaji
# decoration ini digunakan untuk mengakses property
# nama pegawai agar dapat diakses tanpa menggunakan
# intance.namaPegawai() melainkan instan... | class Pegawai:
def __init__(self, nama, email, gaji):
self.__namaPegawai = nama
self.__emailPegawai = email
self.__gajiPegawai = gaji
@property
def nama_pegawai(self):
return self.__namaPegawai
@namaPegawai.setter
def nama_pegawai(self, nama):
self.__namaPe... |
snippet_normalize (cr, width, height)
cr.set_line_width (0.12)
cr.set_line_cap (cairo.LINE_CAP_BUTT) #/* default */
cr.move_to (0.25, 0.2); cr.line_to (0.25, 0.8)
cr.stroke ()
cr.set_line_cap (cairo.LINE_CAP_ROUND)
cr.move_to (0.5, 0.2); cr.line_to (0.5, 0.8)
cr.stroke ()
cr.set_line_cap (cairo.LINE_CAP_SQUARE)
cr.m... | snippet_normalize(cr, width, height)
cr.set_line_width(0.12)
cr.set_line_cap(cairo.LINE_CAP_BUTT)
cr.move_to(0.25, 0.2)
cr.line_to(0.25, 0.8)
cr.stroke()
cr.set_line_cap(cairo.LINE_CAP_ROUND)
cr.move_to(0.5, 0.2)
cr.line_to(0.5, 0.8)
cr.stroke()
cr.set_line_cap(cairo.LINE_CAP_SQUARE)
cr.move_to(0.75, 0.2)
cr.line_to(0.... |
class DiscreteEnvWrapper:
def __init__(self, env):
self.__env = env
def reset(self):
return self.__env.reset()
def step(self, action):
next_state, reward, done, info = self.__env.step(action)
return next_state, reward, done, info
def render(self):
self.__env.re... | class Discreteenvwrapper:
def __init__(self, env):
self.__env = env
def reset(self):
return self.__env.reset()
def step(self, action):
(next_state, reward, done, info) = self.__env.step(action)
return (next_state, reward, done, info)
def render(self):
self.__e... |
def mse(x, target):
n = max(x.numel(), target.numel())
return (x - target).pow(2).sum() / n
def snr(x, target):
noise = (x - target).pow(2).sum()
signal = target.pow(2).sum()
SNR = 10 * (signal / noise).log10_()
return SNR
| def mse(x, target):
n = max(x.numel(), target.numel())
return (x - target).pow(2).sum() / n
def snr(x, target):
noise = (x - target).pow(2).sum()
signal = target.pow(2).sum()
snr = 10 * (signal / noise).log10_()
return SNR |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
size = len(preorder)
root = TreeNode(preorder[0])
s = ... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bst_from_preorder(self, preorder: List[int]) -> TreeNode:
size = len(preorder)
root = tree_node(preorder[0])
s = []
s.append(root)
i = 1
... |
def get_account(account_id: int):
return {
'account_id': 1,
'email': 'noreply@gerenciagram.com',
'first_name': 'Gerenciagram'
}
| def get_account(account_id: int):
return {'account_id': 1, 'email': 'noreply@gerenciagram.com', 'first_name': 'Gerenciagram'} |
__author__ = 'Michael Andrew michael@hazardmedia.co.nz'
class SoundModel(object):
sound = None
path = ""
delay = 0
delay_min = 0
delay_max = 0
def __init__(self, sound, path, delay=0, delay_min=0, delay_max=0):
self.sound = sound
self.path = path
self.delay = delay
... | __author__ = 'Michael Andrew michael@hazardmedia.co.nz'
class Soundmodel(object):
sound = None
path = ''
delay = 0
delay_min = 0
delay_max = 0
def __init__(self, sound, path, delay=0, delay_min=0, delay_max=0):
self.sound = sound
self.path = path
self.delay = delay
... |
max_strlen=[]
max_strindex=[]
for i in range(1,11):
file_name="sample."+str(i)
with open(file_name,"rb") as f:
offsets=[]
len_of_file=[]
for strand in f.readlines():
offsets.append(sum(len_of_file))
len_of_file.append(len(strand))
max_strlen.appe... | max_strlen = []
max_strindex = []
for i in range(1, 11):
file_name = 'sample.' + str(i)
with open(file_name, 'rb') as f:
offsets = []
len_of_file = []
for strand in f.readlines():
offsets.append(sum(len_of_file))
len_of_file.append(len(strand))
max_strlen.... |
tokens = ('IMPLY', 'LPAREN', 'RPAREN', 'PREDICATENAME', 'PREDICATEVAR')
precedence = (
('left', 'IMPLY'),
('left', '|', '&'),
('right', '~'),
)
t_ignore = ' \t'
t_IMPLY = r'=>'
t_RPAREN = r'\)'
t_LPAREN = r'\('
literals = ['|', ',', '&', '~']
def t_PREDICATENAME(t):
r'[A-Z][a-zA-Z0-9_]*'... | tokens = ('IMPLY', 'LPAREN', 'RPAREN', 'PREDICATENAME', 'PREDICATEVAR')
precedence = (('left', 'IMPLY'), ('left', '|', '&'), ('right', '~'))
t_ignore = ' \t'
t_imply = '=>'
t_rparen = '\\)'
t_lparen = '\\('
literals = ['|', ',', '&', '~']
def t_predicatename(t):
"""[A-Z][a-zA-Z0-9_]*"""
t.value = str(t.value)
... |
for i in range(int(input())):
n = int(input())
a = [0 for j in range(32)]
for j in range(n):
s = input()
p = 0
if('a' in s):
p|=1
if('e' in s):
p|=2
if('i' in s):
p|=4
if('o' in s):
p|=8
if('u' in s):
... | for i in range(int(input())):
n = int(input())
a = [0 for j in range(32)]
for j in range(n):
s = input()
p = 0
if 'a' in s:
p |= 1
if 'e' in s:
p |= 2
if 'i' in s:
p |= 4
if 'o' in s:
p |= 8
if 'u' in s:
... |
begin_unit
comment|'# Copyright 2013 OpenStack Foundation'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
... | begin_unit
comment | '# Copyright 2013 OpenStack Foundation'
nl | '\n'
comment | '#'
nl | '\n'
comment | '# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl | '\n'
comment | '# not use this file except in compliance with the License. You may obtain'
nl | '\n'
comment | '# a copy o... |
## https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/
## Restrictions with multiple metaclasses
# class Meta1(type):
# pass
# class Meta2(type):
# pass
# class Base1(metaclass=Meta1):
# pass
# class Base2(metaclass=Meta2):
# pass
# class Foobar(Base1, Base2):
# pass
# class Meta(type)... | class Base1(metaclass=Meta):
pass
class Base2(metaclass=SubMeta):
pass
class Foobar(Base1, Base2):
pass
type(Foobar) |
# 14. Longest Common Prefix
# Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
... | class Solution(object):
def longest_common_prefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = ''
if not strs:
return prefix
shortest = min(strs, key=len)
for i in range(len(shortest)):
if all([x.startswith(s... |
STRING_FILTER = 'string'
CHOICE_FILTER = 'choice'
BOOLEAN_FILTER = 'boolean'
RADIO_FILTER = 'radio'
HALF_WIDTH_FILTER = 'half_width'
FULL_WIDTH_FILTER = 'full_width'
VALID_FILTERS = (
STRING_FILTER,
CHOICE_FILTER,
BOOLEAN_FILTER,
RADIO_FILTER,
)
VALID_FILTER_WIDTHS = (
HALF_WIDTH_FILTER,
FULL... | string_filter = 'string'
choice_filter = 'choice'
boolean_filter = 'boolean'
radio_filter = 'radio'
half_width_filter = 'half_width'
full_width_filter = 'full_width'
valid_filters = (STRING_FILTER, CHOICE_FILTER, BOOLEAN_FILTER, RADIO_FILTER)
valid_filter_widths = (HALF_WIDTH_FILTER, FULL_WIDTH_FILTER)
sort_param = 'so... |
class Passenger():
def __init__(self, weight, floor, destination, time):
self.weight = weight
self.floor = floor
self.destination = destination
self.elevator = None
self.created_at = time
def enter(self, elevator):
'''
Input: the elevator that the passen... | class Passenger:
def __init__(self, weight, floor, destination, time):
self.weight = weight
self.floor = floor
self.destination = destination
self.elevator = None
self.created_at = time
def enter(self, elevator):
"""
Input: the elevator that the passenge... |
# ============================================================
# Title: Keep Talking and Nobody Explodes Solver: Who's on First?
# Author: Ryan J. Slater
# Date: 4/4/2019
# ============================================================
def solveSimonSays(textList, # List of strings [displayText, topLeft, topRight, m... | def solve_simon_says(textList, bombSpecs):
if textList[0] in ['ur']:
return get_responses_from_word(textList[1])
elif textList[0] in ['first', 'okay', 'c']:
return get_responses_from_word(textList[2])
elif textList[0] in ['yes', 'nothing', 'led', 'they are']:
return get_responses_fro... |
#coding:utf-8
#pulic
BASE_DIR = "/home/dengerqiang/Documents/WORK/"
VQA_BASE = BASE_DIR + 'VQA/'
DATA10 = VQA_BASE + "data1.0/"
DATA20 = VQA_BASE + "data2.0/"
IMAGE_DIR = VQA_BASE + "images/"
GLOVE_DIR = BASE_DIR + 'glove/'
NLTK_DIR = BASE_DIR + "nltk_data"
#private
WORK_DIR = BASE_DIR+ "VQA/DenseCoAttention/"
GLOVE_... | base_dir = '/home/dengerqiang/Documents/WORK/'
vqa_base = BASE_DIR + 'VQA/'
data10 = VQA_BASE + 'data1.0/'
data20 = VQA_BASE + 'data2.0/'
image_dir = VQA_BASE + 'images/'
glove_dir = BASE_DIR + 'glove/'
nltk_dir = BASE_DIR + 'nltk_data'
work_dir = BASE_DIR + 'VQA/DenseCoAttention/'
glove_file = 'glove.6B.100d.pt'
rnn_d... |
#!/usr/bin/python
class RedditUser:
def __init__(
self,
name: str,
can_submit_guess: bool = True,
is_potential_winner: bool = False,
num_guesses: int = 0,
):
"""
Parametrized constructor
"""
self.name = name
self.can_submit_guess =... | class Reddituser:
def __init__(self, name: str, can_submit_guess: bool=True, is_potential_winner: bool=False, num_guesses: int=0):
"""
Parametrized constructor
"""
self.name = name
self.can_submit_guess = can_submit_guess
self.is_potential_winner = is_potential_winne... |
def toMinutesArray(times: str):
res = [0, 0]
startEnd = times.split()
hourMin = startEnd[0].split(':')
res[0] = int(hourMin[0]) * 60 + int(hourMin[1])
hourMin = startEnd[1].split(':')
res[1] = int(hourMin[0]) * 60 + int(hourMin[1])
return res
MAX_MINS = 1500
N = int(input())
table = [0] *... | def to_minutes_array(times: str):
res = [0, 0]
start_end = times.split()
hour_min = startEnd[0].split(':')
res[0] = int(hourMin[0]) * 60 + int(hourMin[1])
hour_min = startEnd[1].split(':')
res[1] = int(hourMin[0]) * 60 + int(hourMin[1])
return res
max_mins = 1500
n = int(input())
table = [0]... |
# For the central discovery server
LOG_FILE = 'discovered.pkl'
DISCOVERY_PORT = 4444
MESSAGING_PORT = 8192
PROMPT_FILE = 'prompt'
SHARED_FOLDER = 'shared'
DOWNLOAD_FOLDER = 'download'
CHUNK_SIZE = 1000000 | log_file = 'discovered.pkl'
discovery_port = 4444
messaging_port = 8192
prompt_file = 'prompt'
shared_folder = 'shared'
download_folder = 'download'
chunk_size = 1000000 |
class FindImage:
def __init__(self, image_repo):
self.image_repo = image_repo
def by_ayah_id(self, ayah_id):
return self.image_repo.find_by_ayah_id(ayah_id) | class Findimage:
def __init__(self, image_repo):
self.image_repo = image_repo
def by_ayah_id(self, ayah_id):
return self.image_repo.find_by_ayah_id(ayah_id) |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | """
Rules for generating ruby code with protoc
including rules for ruby, grpc-ruby, and various flavors of gapic-generator-ruby
"""
load(':private/ruby_gapic_library_internal.bzl', _ruby_gapic_library_internal='ruby_gapic_library_internal')
load('@rules_gapic//:gapic.bzl', 'proto_custom_library')
def ruby_gapic_librar... |
# -*- coding: utf-8 -*-
"""
> 005 @ Jane Street
~~~~~~~~~~~~~~~~~~~
```cons(a, b)``` constructs a pair, and ```car(pair)``` and ```cdr(pair)``` returns
the first and last element of that pair. For example, ```car(cons(3, 4))``` returns
```3```, and ```cdr(cons(3, 4))``` returns ```4```.
Given ... | """
> 005 @ Jane Street
~~~~~~~~~~~~~~~~~~~
```cons(a, b)``` constructs a pair, and ```car(pair)``` and ```cdr(pair)``` returns
the first and last element of that pair. For example, ```car(cons(3, 4))``` returns
```3```, and ```cdr(cons(3, 4))``` returns ```4```.
Given this implementation of co... |
# To review... adding up the lengths of strings in a list
# e.g. totalLength(["UCSB","Apple","Pie"]) should be: 12
# because len("UCSB")=4, len("Apple")=5, and len("Pie")=3, and 4+5+3 = 12
def totalLength(listOfStrings):
" add up length of all the strings "
# for now, ignore errors.. assume they are all of ... | def total_length(listOfStrings):
""" add up length of all the strings """
count = 0
for string in listOfStrings:
count = count + len(string)
return count
def test_total_length_1():
assert total_length(['UCSB', 'Apple', 'Pie']) == 12
def test_total_length_2():
assert total_length([]) ==... |
T = int(input(''))
X = 0
Y = 0
for i in range(T):
B = int(input(''))
A1, D1, L1 = map(int, input().split())
A2, D2, L2 = map(int, input().split())
X = (A1 + D1) / 2
if L1 % 2 == 0:
X = X + L1
Y = (A2 + D2) / 2
if L2 % 2 == 0:
Y = Y + L1
if X == Y:
print('Empate')
... | t = int(input(''))
x = 0
y = 0
for i in range(T):
b = int(input(''))
(a1, d1, l1) = map(int, input().split())
(a2, d2, l2) = map(int, input().split())
x = (A1 + D1) / 2
if L1 % 2 == 0:
x = X + L1
y = (A2 + D2) / 2
if L2 % 2 == 0:
y = Y + L1
if X == Y:
print('Empat... |
class Solution:
def XXX(self, n: int) -> str:
ans = '1#'
for i in range(1, n):
t, cnt = '', 1
for j in range(1, len(ans)):
if ans[j] == ans[j - 1]:
cnt += 1
else:
t += (str(cnt) + ans[j - 1])
... | class Solution:
def xxx(self, n: int) -> str:
ans = '1#'
for i in range(1, n):
(t, cnt) = ('', 1)
for j in range(1, len(ans)):
if ans[j] == ans[j - 1]:
cnt += 1
else:
t += str(cnt) + ans[j - 1]
... |
# This kata was seen in programming competitions with a wide range of variations. A strict bouncy array of numbers, of
# length three or longer, is an array that each term (neither the first nor the last element) is strictly higher or lower
# than its neighbours.
# For example, the array:
# arr = [7,9,6,10,5,11,10,12,... | def longest_bouncy_list(arr):
bounce = ''
count = 0
value = []
depths = [[] for i in range(4)]
if arr[1:] == arr[:-1]:
return [arr[0]]
if arr[0] < arr[1]:
bounce = 'low'
elif arr[0] > arr[1]:
bounce = 'high'
for (x, y) in zip(arr[:], arr[1:]):
current_dept... |
DEFAULTS = {
'label': "{win[title]}",
'label_alt': "[class_name='{win[class_name]}' exe='{win[process][name]}' hwnd={win[hwnd]}]",
'label_no_window': None,
'max_length': None,
'max_length_ellipsis': '...',
'monitor_exclusive': True,
'ignore_windows': {
'classes': [],
'process... | defaults = {'label': '{win[title]}', 'label_alt': "[class_name='{win[class_name]}' exe='{win[process][name]}' hwnd={win[hwnd]}]", 'label_no_window': None, 'max_length': None, 'max_length_ellipsis': '...', 'monitor_exclusive': True, 'ignore_windows': {'classes': [], 'processes': [], 'titles': []}, 'callbacks': {'on_left... |
#!python3
class Error(Exception):
pass
class IncompatibleArgumentError(Error):
pass
class DataShapeError(Error):
pass | class Error(Exception):
pass
class Incompatibleargumenterror(Error):
pass
class Datashapeerror(Error):
pass |
x = 9
def f(x):
return x
| x = 9
def f(x):
return x |
# 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 findTilt(self, root: TreeNode) -> int:
tilt = [0]
def dfs(node):
if node is... | class Solution:
def find_tilt(self, root: TreeNode) -> int:
tilt = [0]
def dfs(node):
if node is None:
return 0
left = dfs(node.left)
right = dfs(node.right)
tilt[0] += abs(left - right)
return left + right + node.val
... |
def test_filtering_sequential_blocks_with_bounded_range(
w3,
emitter,
Emitter,
wait_for_transaction):
builder = emitter.events.LogNoArguments.build_filter()
builder.fromBlock = "latest"
initial_block_number = w3.eth.block_number
builder.toBlock = initial_block_number ... | def test_filtering_sequential_blocks_with_bounded_range(w3, emitter, Emitter, wait_for_transaction):
builder = emitter.events.LogNoArguments.build_filter()
builder.fromBlock = 'latest'
initial_block_number = w3.eth.block_number
builder.toBlock = initial_block_number + 100
filter_ = builder.deploy(w3... |
"""
reverse words
author oinegexruam@
"""
def reverse_word(word):
word_reverse = ''
for i in range(1, len(word) + 1):
index_reverse = len(word) - i
word_reverse += word[index_reverse]
return word_reverse
reverse_word(str(input('type a word: ')))
| """
reverse words
author oinegexruam@
"""
def reverse_word(word):
word_reverse = ''
for i in range(1, len(word) + 1):
index_reverse = len(word) - i
word_reverse += word[index_reverse]
return word_reverse
reverse_word(str(input('type a word: '))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.