content stringlengths 42 6.51k |
|---|
def count_syllables_in_word(word):
"""
This function counts the number of syllables in a word
"""
count = 0
endings = '!,;.?:'
last_char = word[-1]
if last_char in endings:
processed_word = word[0:-1]
else:
processed_word = word
if len(processed_word) <= 3:
... |
def to_camel_case(text):
"""Converts to Camel-Case"""
init, *temp = text.split("_")
return "".join([init.lower(), *map(str.title, temp)]) |
def remove_top_words(text, remove_words):
"""
text: str of text to be filtered
remove_words: set of most common strings
"""
new_contents = [word for word in text.split() if word not in remove_words]
return ' '.join(new_contents) |
def readable_duration(seconds: float, pad: str = "") -> str:
"""Produce human-readable duration."""
if seconds < 10:
return f"{seconds:.2g}s"
seconds = int(round(seconds))
parts = []
time_minute = 60
time_hour = 3600
time_day = 86400
time_week = 604800
weeks, seconds = div... |
def bytes_to_num(buf):
"""
Convert multibyte buffer into an integer value. Bytes must be in
little-endian order. This function pays no attention to overflow,
etc.
:param buf: bytes to convert.
:returns: integer value.
"""
val = 0
for i in range(len(buf) - 1, -1, -1):
val ... |
def _policy_dict_at_state(callable_policy, state):
"""Turns a policy function into a dictionary at a specific state.
Args:
callable_policy: A function from `state` -> lis of (action, prob),
state: the specific state to extract the policy from.
Returns:
A dictionary of action -> prob at this state.
... |
def _best_lookup(node, do_lookup, lookup_value, _collected=None):
"""Looks up an x_address (the `lookup_value`) using the function `do_lookup`.
We return the longest matched prefix that we can find."""
if _collected is None:
_collected = []
if (lookup_value == []) or (not hasattr(node, 'childre... |
def label2nodename(label):
"""
convert label e.g. '(1,2)' to nodename e.g. 'n1c2'
"""
lsplit = label.split(',')
return 'n' + lsplit[0][1:] + 'c' + lsplit[1][:-1] |
def fileexists(filename):
"""Replacement method for os.stat."""
try:
f = open( filename, 'r' )
f.close()
return True
except:
pass
return False |
def expand(order, axiom, variables, rules):
""" axiom is string
variables and rules are list of strings
"""
expansion = ""
if order == 0:
return list(axiom)
for variable in list(axiom):
expansion += rules[variables.index(variable)]
return expand(order - 1, expansion, variable... |
def cake_decoration(orders):
"""
IMPORTANT: You should only use list comprehension for this question.
Follow the syntax guidelines in the writeup.
Take a list of orders and count the unique letters needed to
be decorated for orders of even length.
>>> cake_decoration(['Marina', 'Ruixuan','Geor... |
def tokenize_spec(spec):
"""Tokenize a GitHub-style spec into parts, error if spec invalid."""
spec_parts = spec.split('/', 2) # allow ref to contain "/"
if len(spec_parts) != 3:
msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=spec)
if len(spec_parts) == 2 ... |
def getYearfromDate(pythondate):
"""
Assuming the input is a python date... return just the year.
If not a python date, empty return.
"""
try:
return(pythondate.year)
except:
return(None) |
def port_bound(port):
"""
Returns true if the port is bound.
"""
return port['binding:vif_type'] != 'unbound' |
def parse_squares(input_squares):
"""Parse squares from the input_squares.
Returns dict with keys being id of square and value list of str with
square contents"""
squares = {}
for square in input_squares:
if square:
lines = [line.strip() for line in square.split('\n')]
... |
def _get_audio_info(media_data):
"""Parses audio URL, audio download URL, audio duration
If the audio does not allow download, we save the 'streaming'
URL as the `audio_url`
:return: Tuple with main audio file information:
- audio_url
- download_url
- duration (in milliseconds)
"""
a... |
def pprint2columns(llist, max_length=60):
"""
llist = a list of strings
max_length = if a word is longer than that, for single col display
> prints a list in two columns, taking care of alignment too
"""
if len(llist) == 0:
return None
col_width = max(len(word) for word in llist) +... |
def filename(snum, inum, enum):
"""Generate a filename to write an example to. Take the section
number from the table of contents, item number (subsection number),
and example number. Numbers start at 1. Return the filename."""
assert snum > 0, \
'%d.%d #%d: Section number should be greater tha... |
def check_greenlist_positions(curword: str, grn: list) -> bool:
"""
Checks the greenlist positions to ensure every word has a green letter in the correct positions
:param curword: The current word from the word pool
:param grn: Array representing the correct letters
:return: Bool -false if the word ... |
def get_motif(sequences):
"""
Computes the motif for a given collection of sequences.
A motif is a representative sequence for all sequences in a collection, with blank values (0) being those which are variable within the collection, and fixed values which are not.
Motifs are related to the measure of synchrony in ... |
def get_operator_name(operator_string):
"""
Get operator class
"""
# the actual name of the operator
return operator_string.split(".")[-1] |
def euler_criterion(a, p):
"""p is odd prime, a is positive integer. Euler's Criterion will check if
a is a quadratic residue mod p. If yes, returns True. If a is a non-residue
mod p, then False"""
return pow(a, (p - 1) // 2, p) == 1 |
def due_mins_to_words(mins:int) -> str:
"""Convert the parm number of minutes to a due time in words."""
if mins == 0:
return 'now'
elif mins == 1:
return 'in 1 minute'
else:
return 'in ' + str(mins) + ' minutes' |
def translate(phrase, rot):
"""Translates `phrase` by shifting each character `rot` positions forward"""
ord_a = ord("a")
diff_az = ord("z") + 1 - ord_a
translated = ""
for char in phrase:
if "a" <= char <= "z":
char = chr(((ord(char) - ord_a + rot) % diff_az) + ord_a)
tr... |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if not nums or len(nums) == 0:
return 0
global_max = float("-inf")
current_max = float("-... |
def flatten(lst):
"""
Flatten a list that contains nested lists
@param lst: The source list
@type lst: list
@return: flat list
"""
def flatten_helper(current, flat):
# flatten a list of nested lists
for item in current:
if isinstance(item, list):
... |
def check_uniqueness_in_rows(board: list):
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
>>> ch... |
def append_unique(the_list, new_item):
"""
append the newe_item to the_list, only if it does not exist
:param the_list:
:param new_item:
:return:
"""
exist = any(new_item == item for item in the_list)
if not exist:
the_list.append(new_item)
return the_list |
def add_one(t_number, last_time_timeout):
"""Function will add a number if provided condition is set to True."""
if last_time_timeout:
t_number += 1
return t_number
else:
return 0 |
def get_human_readable_time(seconds: float) -> str:
"""Convert seconds into a human-readable string."""
prefix = "-" if seconds < 0 else ""
seconds = abs(seconds)
int_seconds = int(seconds)
days, int_seconds = divmod(int_seconds, 86400)
hours, int_seconds = divmod(int_seconds, 3600)
minutes,... |
def getPrimitiveRoot(p: int, factors: list) -> int:
"""Generates smallest primitive root modulo prime number p
Parameters:
p: int
Modulo value
factors: list
List of prime divisors of value (p - 1)
"""
seed = 2
while True:
if pow(seed, p - 1, ... |
def getOptInteger(s):
"""XXX Return a single integer. This function was originally
written by Ingrid Ofte for pyana's XtcExplorer module. XXX What if
conversion fails?
"""
if (s is None or s == "" or s == "None"):
return None
return (int(s)) |
def command_add_record_to_file(rec, fname) :
"""Returns command to add record to file.
"""
return 'echo "%s" >> %s' % (rec, fname) |
def _mle_t(n_neut, exp_rel_neut, alpha, theta):
""" Maximum likelihood estimator for dNdS rate of neutral mutations
"""
tml = (n_neut + alpha - 1) / (exp_rel_neut + (1/theta))
if alpha <= 1:
tml = max(alpha * theta, tml)
return tml |
def remove_quotation(value):
"""Removes quotes from string value"""
result = value
if value.strip(' ') != "":
if value[0] == "\'" or value[0] == "\"":
result = result[1:]
if value[-1] == "\'" or value[-1] == "\"":
result = result[:-1]
return result |
def get_large_image_urls(api_data):
""" This is typically the image data we want to retrieve per product """
images = [x['largeUrl'] for x in api_data['imageAssets']]
return images |
def mass_gpemgh(GPE,gravity,height):
"""Usage: Find mass from gravitational potential energy, gravity and height"""
result=GPE/gravity*height
return result |
def is_select_permitted(user_id, table, dwsupport_model):
"""
Return true if User has been authorized to select from 'table'
Keyword Parameters:
user_id -- String, representing unique identifier for user that
initiated the authorized API session.
table -- DWSupport Data Transfer Object rep... |
def token_count_for_group(num_groups, total_tokens, group_number):
"""
Determine a number of tokens to retrieve for a particular group out of an
overall redemption attempt.
:param int num_groups: The total number of groups the tokens will be
divided into.
:param int total_tokens: The total... |
def coordinateToString(coordinate):
""" convert (9.0 ,4.0) to "J5" """
alphabateList = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]
return str(alphabateList[int(coordinate[0])]) + str(int(coordinate[1]) + 1) |
def ordinal(n):
"""
Convert an integer into its ordinal representation::
ordinal(0) => '0th'
ordinal(3) => '3rd'
ordinal(122) => '122nd'
ordinal(213) => '213th'
"""
n = int(n)
suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)]
if 11 <= (n % 100) <= 13:
... |
def is_number_tryexcept(s):
""" Returns True is string is a number. """
try:
float(s)
return True
except ValueError:
return False |
def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
For clarification see document or mail d3dileep@gmail.com
:param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
None if unit not one of m, h, d o... |
def notNone(arg,default=None):
""" Returns arg if not None, else returns default. """
return [arg,default][arg is None] |
def transpose(matrix):
"""Returns the transpose for the given matrix"""
if not matrix:
return []
elif matrix[0] and not isinstance(matrix[0], list):
return [[elem] for elem in matrix]
return list(map(list, zip(*matrix))) |
def is_leap_year(year: int) -> bool:
"""
Returns whether a year is a leap year
:param year: Year
:return: If the given year is a leap year
"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
def govukify(html):
"""
A method to add govuk classes to vanilla HTML
Params
------
html : str
a string of html
"""
html = html.replace("<p", '<p class="govuk-body"')
html = html.replace("<h1", '<h1 class="govuk-heading-xl"')
html = html.replace("<h2", '<h2 class="govuk-head... |
def random_string(string_length=3):
"""Generates a random string of fixed length.
Args:
string_length (int, optional): Fixed length. Defaults to 3.
Returns:
str: A random string
"""
import random
import string
# random.seed(1001)
letters = string.ascii_lowercase
r... |
def extract_vars(l):
"""
Extracts variables from lines, looking for lines
containing an equals, and splitting into key=value.
"""
data = {}
for s in l.splitlines():
if "=" in s:
name, value = s.split("=")
data[name] = value
return data |
def distribute_calib_tensors(calib_tensors, calib_cfg, tensor_to_node):
"""Distributes the tensors for calibration, depending on the
algorithm set in the configuration of their nodes.
Args:
calib_tensors: tensors to distribute.
calib_cfg (dict): calibration configuration.
tensor_... |
def combine_uval(ulist):
"""
Combine multiple measurements of the same event into one measurement.
Uses weighted average.
"""
combined = None
if ulist is not None:
combined = ulist[0]
for oth in ulist[1:]:
combined.update(oth)
return combined |
def merge_dicts(*dict_args):
"""Merge arg_params and aux_params to populate shared_buffer"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def _before(node):
"""
Returns the set of all nodes that are before the given node.
"""
try:
pos = node.treeposition()
tree = node.root()
except AttributeError:
return []
return [tree[x] for x in tree.treepositions() if x[: len(pos)] < pos[: len(x)]] |
def check_ar_training_strategy(ar_training_strategy):
"""Check AR training strategy validity."""
if not isinstance(ar_training_strategy, str):
raise TypeError("'ar_training_strategy' must be a string: 'RNN' or 'AR'.")
if ar_training_strategy not in ["RNN","AR"]:
raise ValueError("'ar_trainin... |
def fast_overlap(s, t):
"""Return the overlap between sorted S and sorted T.
>>> fast_overlap([2, 3, 5, 6, 7], [1, 4, 5, 6, 7, 8])
3
"""
count, i, j = 0, 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
count, i, j = count + 1, i + 1, j + 1
elif s[i] < t[j]:
... |
def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal places"""
places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""
count = 0
formatted = ... |
def parse_as_string(raw):
""" Parses the given value as string. Strips spaces, tabs, newlines, carriage
returns, single and double quotation marks of the ends."""
return raw.strip("\t\n\r \"'") |
def convert_text_to_bool(text):
"""
Converts a text to a boolean.
"""
true_values = ['True', 'true', 't', 'T', '1']
if text in true_values:
return True
return False |
def regenerate_response(db_entry):
"""Unique message generator.
Args:
db_entry (dict?): Stored response from the database that has already been created.
Returns:
JSON string which contains the message response
"""
# Init a blank json response
response_data = {'wallet_addr... |
def get_salary(x):
""" returns the int value for the ordinal value class
:param x: a value that is either 'crew', 'first', 'second', or 'third'
:return: returns 3 if 'crew', 2 if first, etc.
"""
if x == '>50K':
return '1'
else:
return '0' |
def deep_merge_dict(a, b, path=[], overwrite=True):
"""Deeply merges b into a"""
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
deep_merge_dict(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # ... |
def _is_image_file(filename):
"""
Is the given extension in the filename supported ?
"""
# FIXME: Need to add all available SimpleITK types!
IMG_EXTENSIONS = ['.nii.gz', '.nii', '.mha', '.mhd']
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) |
def manhattan(rating1, rating2):
"""Computes the Man hattan distance"""
distance = 0
commonRatings = False
for key in rating1:
if key in rating2:
distance += abs(rating1[key] - rating2[key])
commonRatings = True
if commonRatings:
return distance
else:
... |
def num_paths_to_top(height, possible_steps):
"""
Given the height of a staircase n, and a list of possible steps you
can take at a time, calculate the number of possible paths
you can take to reach the top of the staircase.
For example, given a height 3, and the possible steps [1, 2, 3],
there would be 4 possib... |
def overlaps(x1, x2, y1, y2):
"""
Returns true if array [x1, x2] overlaps with [y1, y2]
:param x1: int
:param x2: int, assume x1 <= x2
:param y1: int
:param y2: int, assume y1 <= y2
:return: boolean
"""
return x1 <= y2 and y1 <= x2 |
def sqrt_decimal_expansion(n: int, precision: int) -> str:
"""Finds the square root of a number to arbitrary decimal precision.
Args:
n: A positive integer value.
precision: The desired number of digits following the decimal point.
Returns:
A string representation of ``sqrt(n)`` in... |
def symb_seq_to_spans(symb_seq):
"""
Converts sequence of symbol labels (IOBES) format to spans
"""
chunks = []
current = None
for i, label in enumerate(symb_seq):
if label.startswith('B-'):
if current is not None:
chunks.append('@'.join(current))
... |
def apply_look_and_say(element):
"""
Apply look-and-say rule to an element
New element consist of number which represents length of string
and then one of the digits of the element
Args:
element (str): various number of digits of one type
Returns:
list: new string a... |
def topic_node(topic):
"""
In order to prevent topic/node name aliasing, we have to remap
topic node names. Currently we just prepend a space, which is
an illegal ROS name and thus not aliased.
@return str: topic mapped to a graph node name.
"""
return ' ' + topic |
def deltatime(time: int) -> str:
"""conversts the number of seconds into days, hours, minutes, and seconds.
Args:
time (int): the amount of time to be converted.
Returns:
str: the string version
"""
time_days = time // 86400
string = ""
if time_days > 0:
if time_day... |
def find_version_attribute(obj):
"""Depending on the object, modified, created or _date_added is used to store the
object version"""
if "modified" in obj:
return "modified"
elif "created" in obj:
return "created"
elif "_date_added" in obj:
return "_date_added" |
def length_wu(length, logprobs, alpha=0.):
"""
NMT length re-ranking score from
"Google's Neural Machine Translation System" :cite:`wu2016google`.
"""
modifier = (((5 + length) ** alpha) / ((5 + 1) ** alpha))
return logprobs / modifier |
def write_hemiellipsoid(sz, loc, mat, orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0):
"""
@brief Writes a hemiellipsoid.
@param sz [size u_vec 1, size uvec 2, size uvec 3]
@param loc location of center point
@param mat material keyw... |
def find_largest_digit_helper(n, max_num):
"""
:param n : the intager to search
: max_num: the largest digit
"""
if n/10 < 1:
if n % 10 > max_num:
max_num = n % 10
return max_num
else:
if n % 10 > max_num:
max_num = n % 10
return find_largest_digit_helper(n // 10, max_num) |
def get_longest_increasing_subsequence(X):
"""Returns the Longest Increasing Subsequence in the Given List/Array"""
N = len(X)
P = [0] * N
M = [0] * (N + 1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo + hi) // 2
if (X[M[mid]] <... |
def int_label_to_char(label):
"""
Converts a integer label to the corresponding character
:param label: the integer label
:return: The corresponding character for the label.
"""
# Is a label for a numer?
if label > 25:
# Cast number to string
return str(label - 26)
else:... |
def is_prime_opt(n):
"""
Method to determine whether an input number is Prime
:param n: input integer
:return: prints "Prime" in case a num is prime, and "Not prime" otherwise
"""
if n <= 1:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
... |
def determine_position(
beacon_from_scanner_with_unknown_position,
beacon_from_scanner_with_known_position,
known_position,
):
"""
:param beacon_from_scanner_with_known_position: beacon from Scanner with no position, rotated to be as if in XYZ
:param beacon_from_scanner_with_known_position: same... |
def get_bounding_straight_rectangle(points):
"""Given a list of points, determine the straight rectangle bounding all of them. Returns xywh."""
xs = [point[0] for point in points]
ys = [point[1] for point in points]
xmin, xmax = (min(xs), max(xs))
ymin, ymax = (min(ys), max(ys))
return xmin, ymin, xmax-xmin... |
def digit_nth_power(nth):
"""
Finds the sum of all numbers that can be written as the sum of nth power of their digits.
Uses Brute force to find the sum of all numbers. We first need to find the limit/upper bound. To do that we
The highest digit is 9 and 9^5=59049 , which has five digits. If we then lo... |
def obj_guess_arg_type2(full_name, arg_name, type_guess_engine="pytype"):
"""
guess typing pytypes de Google
:param full_name:
:param arg_name:
:param type_guess_engine:
:return:
"""
if type_guess_engine == "pytype":
"""
Use Google pytype, but doc is super poor....... |
def my_join(iters, string):
"""for loop on joining textstrings"""
out=""
for i in range(iters):
out+=string.join(", ")
return out |
def gt_dosage(gt):
"""Convert unphased genotype to dosage"""
x = gt.split(b'/')
return int(x[0])+int(x[1]) |
def _parse_response(message: bytes, reply: bytes) -> bytes:
"""Sometimes we receive many messages, so we need to split
them up and choose the right one."""
responses = [b"R" + i for i in reply.split(b"R") if i]
if message[0] == ord("G"):
which = message[1]
try:
return next(r... |
def validate_example(example):
"""
:param example: DESCRIPTION
:type example: TYPE
:return: DESCRIPTION
:rtype: TYPE
"""
if not isinstance(example, str):
example = "{0}".format(example)
return example |
def GetMainIsoUrl(pro):
"""Gets the main .iso URL.
If |pro| is False, downloads the Express edition.
"""
prefix = 'http://download.microsoft.com/download/'
if pro:
return (prefix +
'A/F/1/AF128362-A6A8-4DB3-A39A-C348086472CC/VS2013_RTM_PRO_ENU.iso')
else:
return (prefix +
'7/2/E/72E... |
def trim_name(player_name):
"""Remove player number if any."""
return player_name.split(" ")[-1] |
def get_fields_from_fieldsets(fieldsets):
"""
Get a list of all fields included in a fieldsets definition.
"""
fields = []
try:
for name, options in fieldsets:
fields.extend(options['fields'])
except (TypeError, KeyError):
raise ValueError('"fieldsets" must be an ite... |
def cloneDistribution(d):
#---+----|----+----|----+----|----+----|----+----|----+----|----+----|
"""
This function clones (deep copies) a ProbabilityDistribution object.
Cloning is needed because while separate chains in an MCMC analysis
need to begin with the same random number seed, it is not good... |
def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not ... |
def sigma_bins(pref):
"""
Some pre-defined density bin options. Add to here as appropriate
Inputs:
pref = a reference depth
Outputs:
bins = a dictionary with some entries
"""
if int(pref) == 0:
bins = {"pref" : int(pref),
"nbins" : 52,
"sigmin" : 23.0,
... |
def select_dict(coll, key, value):
"""
Given an iterable of dictionaries, return the dictionaries
where the values at a given key match the given value.
If the value is an iterable of objects, the function will
consider any to be a match.
This is especially useful when calling REST APIs which
... |
def power_num(base, expo):
""" recursively calculates power """
if expo == 0:
return 1
return base * power_num(base, expo - 1) |
def _validate_project(project, parent):
"""Ensure the project is set appropriately.
If ``parent`` is passed, skip the test (it will be checked / fixed up
later).
If ``project`` is unset, attempt to infer the project from the environment.
:type project: str
:param project: A project.
:typ... |
def merge_contiguous(index_bounds):
"""
Combines any contiguous index bounds.
Args:
index_bounds (list): a list of bounding index tuples for each
potentially non-maximal C-contiguous block of data selected.
Returns:
maximal_index_bounds (list): a list of bounds equivalent to
... |
def get_weight(position):
"""
Get the probability of scoring a goal given the position of the field where
the event is generated.
Parameters
----------
position: tuple
the x,y coordinates of the event
"""
x, y = position
# 0.01
if x >= 65 and x <= 75:
r... |
def listtogroups(filelist):
"""Seperates list into groups of header and body"""
i = 0
slidedata = [[]]
for line in filelist:
if line != "":
slidedata[i].append(line)
continue
i += 1
slidedata.append([])
return slidedata |
def getNodeState(node_name,local_state):
"""
:param local_state:
:param node_name:
:return:
@type local_state: Dict
@type node_name: str
@rtype: Dict
"""
if node_name in local_state:
my_state = local_state[node_name]
else:
my_state = {}
local_state[node_n... |
def selection_sort(array):
"""This solution uses two `for` and a index as reference vector."""
length = len(array)
for i in range(len(array)):
minimum = i
for j in range(i+1, len(array)):
if array[minimum] > array[j]:
minimum = j
array[i], array[minimum] ... |
def partitionp(n,k=-1):
""" partitionp(n) is the number of distinct unordered partitions of the integer n.
partitionp(n,k) is the number of distinct unordered partitions of the integer n whose largest component is k."""
if (k == -1): return sum([partitionp(n,i) for i in range(1,n+1)])
if (n < k): return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.