How can I get the amount of consecutive sub strings of an object in a list?
You could use itertools.takewhile,
from itertools import takewhile
s = "0000101 001 001 11001"
result = [''.join(takewhile(lambda x: x == "0", chunk)) for chunk in s.split()]
print(result)
Output
['0000', '00', '00', '']
How to find a sub-list of two consecutive items in a list using Linq
You could rewrite your approach as follows:
bool hasSublist = list
.SkipWhile(x => x != "D")
.Take(2)
.SequenceEquals(new[] {"D", "E"});
If you need the starting index of {"D", "E"}
, you could add a select that pairs up letters and their indexes.
However, the problem with your approach is that it would miss the subsequence if there's another "D"
not followed by an "E"
, for example
"D" "A" "D" "B" "D" "C" "D" "D" "D" "E"
There is a "D" "E"
at the end, but your approach stops after finding the first "D"
.
If you are looking for sublists of length 2, you could use Zip
, like this:
bool hasSublist = list
.Zip(list.Skip(1), (a, b) => new {a, b})
.Any(p => p.a == "D" && p.b == "E");
However, this does not scale for longer sub-lists.
Using a plain for
loop would work much better:
for (var i = 0 ; i < list.Count-1 ; i++) {
if (list[i] == "D" && list[i+1] == "E") {
...
}
}
The if
inside could be replaced with SequenceEquals
, accommodating sub-lists of any length:
var desiredSublist = new[] {"D", "E", "F"};
for (var i = 0 ; i < list.Count-desiredSublist+1 ; i++) {
if (list.Skip(i).SequenceEquals(desiredSublist)) {
...
}
}
Read all possible sequential substrings in Python
Try this recursive algorithm:
def segment(word):
def sub(w):
if len(w) == 0:
yield []
for i in xrange(1, min(4, len(w) + 1)):
for s in sub(w[i:]):
yield [''.join(w[:i])] + s
return list(sub(word))
# And if you want a list of strings:
def str_segment(word):
return [' '.join(w) for w in segment(word)]
Output:
>>> segment(word)
[['W', 'I', 'N', 'E'], ['W', 'I', 'NE'], ['W', 'IN', 'E'], ['W', 'INE'], ['WI', 'N', 'E'], ['WI', 'NE'], ['WIN', 'E']]
>>> str_segment(word)
['W I N E', 'W I NE', 'W IN E', 'W INE', 'WI N E', 'WI NE', 'WIN E']
Sublists of consecutive elements that fit a condition in a list c# linq
You can always write your own helper function to do things like this. For example
public static IEnumerable<List<T>> GroupSequential<T, TKey>(
this IEnumerable<T> self,
Func<T, bool> condition)
{
var list = new List<T>();
using var enumerator = self.GetEnumerator();
if (enumerator.MoveNext())
{
var current = enumerator.Current;
var oldValue = condition(current);
if (oldValue)
{
list.Add(current);
}
while (enumerator.MoveNext())
{
current = enumerator.Current;
var newValue = condition(current);
if (newValue)
{
list.Add(current);
}
else if (oldValue)
{
yield return list;
list = new List<T>();
}
oldValue = newValue;
}
if (list.Count > 0)
{
yield return list;
}
}
}
This will put all the items with a true-value in a list. When a true->false transition is encountered the list is returned and recreated. I would expect that there are more compact ways to write functions like this, but it should do the job.
Python: How do I group recurring consecutive digits of only one type?
You can use itertools.groupby
for grouping consecutive items of the same key. Since you really only want to group 0s while leaving 1s separate items in this case, a trick I'd use is to use a key function that returns False
for 0s and an incremental number for 1s so that 1s would not be grouped together as their keys are always unique. You can use itertools.count
to generate such incremental numbers:
from itertools import groupby, count
item = '00011101110100010111010001110000'
c = count(1)
print([
'n' if k else sum(1 for _ in g)
for k, g in groupby(item, lambda i: i == '1' and next(c))
])
This outputs:
[3, 'n', 'n', 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 'n', 'n', 4]
Generate consecutive substring from the string using recursion
With recursion, you might do:
void print_seq(std::string_view s)
{
if (s.size() > 1) print_seq(s.substr(0, s.size() - 1));
std::cout << s << std::endl;
}
void print_all(std::string_view s)
{
print_seq(s);
if (s.size() > 1) print_all(s.substr(1));
}
int main()
{
print_all("ABCD");
}
Demo
Related Topics
Calculate Monthly Returns from Daily Returns in Pandas(Cumpound)
Swapping Columns in a Numpy Array
How to Block Comment Code in the Ipython Notebook
How to Print Superscript in Python
Python Pandas Count the Number of Occurances Inside Lists in a Column
How to Delete a Column That Contains Only Zeros in Pandas
How to Convert List into String With Quotes in Python
Type Conversion in Python Attributeerror: 'Str' Object Has No Attribute 'Astype'
Printing Even Characters With Strings in Python
Pip Install Pandas: Installing Dependencies Error
Running a Powershell Cmdlet in a Python Script
How to Execute a Script Remotely in Python Using Ssh
Creating Random Pairs from Lists
Python MySQL Connector: Caching_Sha2_Password Plugin
Index All *Except* One Item in Python
Plotly Graph Does Not Show When Jupyter Notebook Is Converted to Slides