## python – Capitalizing the first letter of every word in a string (with arbitrary spacing)

• remove the unused `import`s

Your code logic is OK but the execution is not good. Try not to overcomplicate it. Take a piece of paper and write the procedure of how a human like YOU would do it, just with a pencil and paper.

``````read the names individually... make first character capital if it isn't a digit
``````

Now that you have basic design, become more specific, or in Python terms

• read the names individually `for word in string.split()`
• make the first character capital: `string.title()`
• if it isn’t a digit : `if not string(0).isdigit()`

The primary problem which I faced is handling arbitrary spaces

`string.split()` will return the same thing, let it be 1 space or 1000 spaces. It does not matter

Now you have exactly what you need, it is just a matter of putting it together.

``````for every word in words, capitalize if the first character isn't a digit else do nothing
``````
``````    return " ".join(word.title() if not word(0).isdigit() else word for word in words.split())
``````

Furthermore, using `capitalize()` will avoid the extra check

``````    return " ".join(word.capitalize() for word in words.split(' '))
``````

EDIT:

You have to use `.split(' ')` and NOT `.split()` since `.split()` removes all the whitespaces.

As you mentioned, `title()` and `capitalize()` fail for scenarios where you pass something like

``````ALLISON heck
``````

Output

``````Allison Heck
``````

In that case, you need to have extra checks. The best thing to do here is to create another function that specifically capitalizes the first letter

Here is what I thought of

``````def cap_first(word):
return word(:1).upper() + word(1:)
``````

the `solve` function remains the same

``````def solve(words):
return ' '.join(cap_first(word) for word in words.split(' ')
``````

## Benchmarks

the latter code is surely more readable and compact, but what is its performance compared to the previous solution?

I will measure the execution time in the following manner using the `time` module

``````for iterations in (10 ** 5,11 ** 5, 10 ** 6, 11 ** 6):
print(f"n{iterations} iteartionsn")

start = time.time()
for _ in range(iterations): solvenew(names)
print(f"Time taken for new function: {time.time() - start:.3f} s")

start = time.time()
for _ in range(iterations): solveoriginal(names)
print(f"Time taken for original function: {time.time() - start:.3f} s")
``````

Here are the results

``````#                      Time taken
#
#     iterations  |  original    |   new
#   --------------------------------------
#       10 ** 6   |   2.553 s    |  2.106 s
#   --------------------------------------
#       11 ** 6   |   6.203 s    |  5.542 s
#   --------------------------------------
#       10 ** 7   |   32.412 s   |  24.774 s
``````

Feel free to try it yourself

## recursion – std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++

This is a follow-up question for the previous questions about recursive functions, including A Summation Function For Arbitrary Nested Vector Implementation In C++, A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++, A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++, A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++. In order to test these functions for arbitrary nested iterables, I am trying to implement some arbitrary nested iterable generators to construct nested `std::vector`s and nested `std::array`s with the given parameters. The generator for `std::array` case is named `n_dim_array_generator` and another generator for `std::vector` is named `n_dim_vector_generator`. After trying to use `if constexpr` syntax in the previous question, I found that it is possible to use the similar technique in `n_dim_array_generator` function and `n_dim_vector_generator` function.

The usage description

For example, `auto test_vector = n_dim_vector_generator<2, int>(1, 3);` is expected to create a “test_vector” object which type is `std::vector<std::vector<int>>`. The content of this `test_vector` should as same as the following code.

``````std::vector<int> vector1;
vector1.push_back(1);
vector1.push_back(1);
vector1.push_back(1);
std::vector<std::vector<int>> test_vector;
test_vector.push_back(vector1);
test_vector.push_back(vector1);
test_vector.push_back(vector1);
``````

There are four key part in the usage `n_dim_vector_generator<2, int>(1, 3)`. The first number `2` represents the nested layers, the second parameter `int` represents the type of base elements, the third parameter `1` represents the input element which would be filled in, and the fourth parameter `3` represents the element count in each layer.

In the `n_dim_array_generator` function, the first parameter also represents the nested layers, but the parameter which represents the element count in each layer has been moved into the second one. Then, the third parameter represents the type of base elements and the fourth parameter represents the input element which would be filled in.

The experimental implementation

The experimental implementation of `n_dim_vector_generator` function and `n_dim_array_generator` function:

``````template<std::size_t dim, class T>
auto n_dim_vector_generator(T input, std::size_t times)
{
if (dim < 0)
{
throw std::logic_error("Dimension can not be set less than 0");
}
if constexpr (dim == 0)
{
return input;
}
else
{
std::vector<decltype(n_dim_vector_generator<dim - 1>(input, times))> output;
for (size_t i = 0; i < times; i++)
{
output.push_back(n_dim_vector_generator<dim - 1>(input, times));
}
return output;
}
}

template<std::size_t dim, std::size_t times, class T>
auto n_dim_array_generator(T input)
{
if (dim < 0)
{
throw std::logic_error("Dimension can not be set less than 0");
}
if constexpr (dim == 0)
{
return input;
}
else
{
std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;
for (size_t i = 0; i < times; i++)
{
output(i) = n_dim_array_generator<dim - 1, times>(input);
}
return output;
}
}
``````

Test cases

The test cases of `n_dim_vector_generator` function and `n_dim_array_generator` function are as below.

``````//  n_dim_vector_generator function usage with recursive_reduce function and recursive_count_if function
auto test_vector1 = n_dim_vector_generator<3, int>(3, 2);
std::cout << "recursive_reduce output: " << recursive_reduce(test_vector1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<3>(test_vector1, ()(auto& i) {return i == 3; }) << std::endl;

//  n_dim_array_generator function usage with recursive_reduce function and recursive_count_if function
auto test_array1 = n_dim_array_generator<3, 2, int>(3);
std::cout << "recursive_reduce output: " << recursive_reduce(test_array1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<3>(test_array1, ()(auto& i) {return i == 3; }) << std::endl;
``````

The output of this test is as follows.

``````recursive_reduce output: 24
recursive_count_if output: 8
recursive_reduce output: 24
recursive_count_if output: 8
``````

All suggestions are welcome.

The summary information:

## recursion – A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++

This is a follow-up question for A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++, A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++. As G. Sliepen’s answer `Don't try to deduce the predicate's parameter type` and Quuxplusone’s answer mentioned `I think the user of this API should have to tell the function explicitly how many "levels" to unwrap downward`, I am trying to implement another version `recursive_count_if` template function with unwrap level parameter. Thanks to Quuxplusone for providing the hint of using `if constexpr` to achieve this.

``````template<std::size_t unwrap_level, class T1, class T2> requires (is_iterable<T1>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
if constexpr (unwrap_level > 1)
{
return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus<std::size_t>(), (predicate)(auto& element) {
return recursive_count_if<unwrap_level - 1>(element, predicate);
});
}
else
{
return std::count_if(input.begin(), input.end(), predicate);
}
}
``````

The used `is_iterable` concept is as below. I keep it in order to get nicer error messages if user accidentily try to apply this `recursive_count_if()` on something that can not be iterated over.

``````template<typename T>
concept is_iterable = requires(T x)
{
*std::begin(x);
std::end(x);
};
``````

Some test cases are as below. With this version `recursive_count_if`, you can always use `auto` keyword in the input lambda parameter.

``````//  std::vector<std::vector<int>> case
std::vector<int> test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };
std::vector<decltype(test_vector)> test_vector2;
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);

// use a lambda expression to count elements divisible by 3.
int num_items1 = recursive_count_if<2>(test_vector2, ()(auto& i) {return i % 3 == 0; });
std::cout << "#number divisible by three: " << num_items1 << 'n';

// std::deque<std::deque<int>> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);

std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);

// use a lambda expression to count elements divisible by 3.
int num_items2 = recursive_count_if<2>(test_deque2, ()(auto& i) {return i % 3 == 0; });
std::cout << "#number divisible by three: " << num_items2 << 'n';

std::vector<std::vector<std::string>> v = { {"hello"}, {"world"} };
auto size5 = ()(auto& s) { return s.size() == 5; };
auto n = recursive_count_if<2>(v, size5);
std::cout << "n:" << n << std::endl;

//  std::vector<std::vector<std::vector<int>>> case
std::vector<decltype(test_vector2)> test_vector3;
test_vector3.push_back(test_vector2);
test_vector3.push_back(test_vector2);
test_vector3.push_back(test_vector2);
std::cout << recursive_count_if<1>(test_vector3,
(test_vector2)(auto& element)
{
return std::equal(element.begin(), element.end(), test_vector2.begin());
}) << std::endl;
``````

All suggestions are welcome.

The summary information:

## algorithms – How to convert a string (number representation) to an arbitrary base using custom alphabet?

I’m trying to figure out an efficient way (without recursion) to convert a string (number representation) from one arbitrary base to another using custom alphabet. But I cannot think of a very fast efficient method (byte shift?) to do it:

``````def convert_base(target, base_from, base_to):
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
base_to_alphabet_slice = alphabet(:base_to)
base_from_alphabet_slice = alphabet(:base_from)
result = ''
for char in target:
result += ...
return result

print(convert_base('E', 16, 2))
# Output: '1110'

print(convert_base('1110', 2, 16))
# Output: 'E'

print(convert_base('E', 16, 10))
# Output: '14'
``````

Can someone suggest a good method for this?

## recursion – A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++

This is a follow-up question for A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++. After digging into the thing that detecting the argument type of a function, I found that it is possible to simplify the `T1` parameter in last implementation with `boost::callable_traits::args_t` syntax in `Boost.CallableTraits` library. As the result, `recursive_count_if` template function can be used exactly as the following code.

``````std::vector<std::vector<std::string>> v = {{"hello"}, {"world"}};
auto size5 = ()(std::string s) { return s.size() == 5; };
auto n = recursive_count_if(v, size5);
``````

The implementation of `recursive_count_if` function with automatic type deducing:

``````#include <boost/callable_traits.hpp>
//  recursive_count_if implementation
template<class T1, class T2> requires (is_iterable<T1> && std::same_as<std::tuple<std::iter_value_t<T1>>, boost::callable_traits::args_t<T2>>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
return std::count_if(input.begin(), input.end(), predicate);
}

//  transform_reduce version
template<class T1, class T2> requires (is_iterable<T1> && !std::same_as<std::tuple<std::iter_value_t<T1>>, boost::callable_traits::args_t<T2>>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), (predicate)(auto& element) {
return recursive_count_if(element, predicate);
});
}
``````

The used `is_iterable` concept:

``````template<typename T>
concept is_iterable = requires(T x)
{
*std::begin(x);
std::end(x);
};
``````

The constraints of usage

Because the type in the input lambda function plays the role of termination condition, you can not use `auto` keyword as generic lambdas here. If the lambda function like `()(auto element) { }` is passed in, compiling errors will pop up. If you want to use generic lambdas, maybe you can choose the previous version `recursive_count_if` function due to the termination condition is separated.

All suggestions are welcome.

The summary information:

## numerics – 3D Inclusion with structured mesh and coarse and arbitrary matrix

I am wondering if there is a simple way to define a structured 3D mesh (inclusion) like e.g. that

and surround it with a corse and unstructured Matrix. It should be possible to refine both more or less independently (of course when the inclusion is refined the outer matrix will also get finer at the direct inclusin-matrix-boundary).

My attempts so fare always results in an unstructured mesh for the inclusion as well as for the matrix like this:

I have used the following code to generate the last mesh…

``````xI = 200; yI = 200; zI = 20;
InclusionRegion =
Region(Hexahedron({{-xI/2, -yI/2, -zI/2}, {xI/2, -yI/2, -zI/2}, {xI/
2, yI/2, -zI/2}, {-xI/2, yI/2, -zI/2}
, {-xI/2, -yI/2, zI/2}, {xI/2, -yI/2, zI/2}, {xI/2, yI/2,
zI/2}, {-xI/2, yI/2, zI/2}}), Axes -> True);

xM = xI*2; yM = yI*2; zM = zI*2;
MatrixRegion =
Region(Hexahedron({{-xM/2, -yM/2, -zM/2}, {xM/2, -yM/2, -zM/2}, {xM/
2, yM/2, -zM/2}, {-xM/2, yM/2, -zM/2}
, {-xM/2, -yM/2, zM/2}, {xM/2, -yM/2, zM/2}, {xM/2, yM/2,
zM/2}, {-xM/2, yM/2, zM/2}}), Axes -> True);

mesh = ToElementMesh(
DiscretizeGraphics(
RegionDifference(MatrixRegion, InclusionRegion))
, "RegionMarker" -> {{{0., 0., 0.}, 1, 10000}, {{xM/2, yM/2, zM/2},
2, 1000}}
, MaxCellMeasure -> {"Volume" -> 10000}
, "MeshOrder" -> 1);
``````

I am grateful for any help or suggestions.

Max

## recursion – A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++

This is a follow-up question for A Summation Function For Arbitrary Nested Vector Implementation In C++ and A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++. Besides the summation result, I am trying to get the element count in arbitrary nested iterable things. For example, there are three elements in `std::vector<int> test_vector = { 1, 2, 3 };`, so the element count of `test_vector` is `3`. The experimental implementation of `recursive_count` is as below.

``````size_t recursive_count()
{
return 0;
}

template<class T> requires (!is_elements_iterable<T> && !is_iterable<T>)
size_t recursive_count(const T& input)
{
return 1;
}

template<class T> requires (!is_elements_iterable<T> && is_iterable<T>)
size_t recursive_count(const T& input)
{
return input.size();
}

template<class T> requires (is_elements_iterable<T> && is_iterable<T>)
size_t recursive_count(const T& input)
{
size_t output{};
for (auto &element : input)
{
output += recursive_count(element);
}
return output;
}
``````

Some test cases of this `recursive_count` template function.

``````//  std::vector<int> case
std::vector<int> test_vector = {
1, 2, 3
};
auto recursive_count_result1 = recursive_count(test_vector);
std::cout << recursive_count_result1 << std::endl;

//  std::vector<std::vector<int>> case
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
auto recursive_count_result2 = recursive_count(test_vector2);
std::cout << recursive_count_result2 << std::endl;

// std::deque<int> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_count_result3 = recursive_count(test_deque);
std::cout << recursive_count_result3 << std::endl;

// std::deque<std::deque<int>> case
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_count_result4 = recursive_count(test_deque2);
std::cout << recursive_count_result4 << std::endl;
``````

All suggestions are welcome.

The summary information:

## pathfinder 1e – Is there a way to cause an arbitrary magical beast to gain character levels in a chosen class?

I was looking at this answer from our fine cheese collection, and it occurred to me that it would be quite a lot more practical if we could arrange for the assistance of a gorilla and war mammoth with barbarian levels (especially as that would allow the gorilla to take levels in Ride). Awakening them is easily enough done, at which point they’re in the same intelligence range as anyone else (and if they’re too dumb, you can awaken another one) but I’ve not found a way to actually apply class levels to them once that was done. The Leadership feat offers a mechanic for hanging on to them, but doesn’t seem to do anything for their further development. The Monstrous Companion feat actually does offer a way to inject class levels into an existing magical beast, but only of a specific list of magical beasts on offer.

So… is there something that I’m missing? Is there a way to turn a War Mammoth (awakened or otherwise) into a barbarian? I suppose I’d also accept a method for indefinitely turning a barbarian into a war mammoth, as long as the barbarian continued to enjoy the benefits of his class features. That one seems somewhat less likely, however.

The objective here is that the stack could be fielded by an appropriately designed party of characters, after enough levels had passed to gain appropriate resources, without having to pause to transform before battle every time. Whether the mammoth starts out as a PC or not is considered unimportant for the purposes of the question. likewise, if you can manage to cause a war mammoth (and gorilla) with appropriate class levels to come into being, it is assumed that you can come up with a way to convince them to hang around and rage-stack with you.

## Graph with arbitrary chromatic number

There is a graph $$G$$ with $$omega(G) = 2$$ and $$chi(G) = 100$$.

There is a graph $$G$$ with $$omega(G) = 3$$ and $$chi(G) = 100$$.

where $$omega(G)$$ the maximum clique size of
Graph $$G$$, is the largest integer $$k$$ for which $$G$$
contains a clique (complete subgraph) of size $$k$$

$$chi(G)$$ is the chromatic number

Do not really know how to give an example of these two problems. Could you help me out? Thanks!

## Prove a function, where f is arbitrary scalar function and V is arbitrary vector function

Prove
∇(f^2 V)=f^2(∇ V)-2fV ∇ f,
where f is an arbitrary scalar function and V is a arbitrary vector function of (x,y,z).