Dart, get all n number letter values from a list - list

Let's say I have a list
List test = ['hello', 'two', 'mountain', 'day', 'tomorrow', 'bye', 'sad', 'yesterday'];
ExpectedResult = ['two', 'day', 'bye', 'sad'];
I want to extract all values from a list that are of certain number of characters long, in this case all result words that I'm looking have three characters, is there a simple way of doing this?

List<String> nLetters(List<String> list, int n) {
return list.where((word) => word.length == n).toList();
}
Calling nLetters(['hello', 'two', 'mountain', 'day', 'tomorrow', 'bye', 'sad', 'yesterday'], 3) will produce [two, day, bye, sad]

Related

How to split a list in Dart/Flutter [duplicate]

This question already has answers here:
How do I split or chunk a list into equal parts, with Dart?
(21 answers)
Closed 10 months ago.
I have a list of Strings and an integer.
int number = 3;
var items = ['foo', 'hey','yo','bar', 'baz', 'qux'];
How can I split this list by the number(number of Lists to output).
Output :
List 1 = ['foo', 'hey']
List 2 = ['yo', 'bar']
List 3 = ['baz', 'qux']
void main(List<String> args) {
var n = 3;
var items = ['foo', 'hey','yo','bar', 'baz', 'qux'];
var m = (items.length / n).round();
var lists = List.generate(n, (i) => items.sublist(m*i, (i+1)*m <= items.length ? (i+1)*m : null));
print(lists);
}
Result:
[[foo, hey], [yo, bar], [baz, qux]]
Returns a new list containing the elements between start and end.
The new list is a List<E> containing the elements of this list at positions greater than or equal to start and less than end in the same order as they occur in this list.
var colors = ["red", "green", "blue", "orange", "pink"];
print(colors.sublist(1, 3)); // [green, blue]
If end is omitted, it defaults to the length of this list.
print(colors.sublist(1)); // [green, blue, orange, pink]
The start and end positions must satisfy the relations 0 ≤ start ≤ end ≤ this.length If end is equal to start, then the returned list is empty.
Implementation
List<E> sublist(int start, [int? end]);

How to return all elements of a list before and including regex match?

I want to split a list into various sub-lists. The list contains two types of elements: "colors" and a "color-IDs". The number of color-elements between the color-IDs varies:
colors = ['red', 'blue' ,'green', 'DocJ20031212doc1223', 'pink', 'yellow', 'DocNY20021212doc1212']
I want each sublist to contain all colors before the color-ID and the color-ID. I have tried to append the elements to a new list based on a regex, trying different indexes and if/if not combinations. After extensive research, this is the best I came up with:
colors_sorted = []
for i in colors:
if re.search("Doc[a-zA-Z 0-9]{16}",i) or len(colors_sorted) == 0:
colors_sorted.append([i])
else:
colors_sorted[-1].append(i)
print (colors_sorted)
However, this generates a new list that starts with the color-ID, while I want the color-ID to be the last element of each sub-list.
My output is:
[['red', 'blue', 'green'], ['DocJ20031212doc1223', 'pink', 'yellow'], ['DocNY20021212doc1212']]
We can rearrange your approach a little with a helper variable to store the sub-list:
colors_sorted = []
group = []
for i in colors:
group.append(i)
if i.startswith("Doc"):
colors_sorted.append(group)
group = []

How to count the number of words ending with the same suffix(word ending)?

I am trying to 1st divide up four-letter words based upon the last two letters of the word (suffix) and 2nd count up how many words I have for each of these endings.
I have a list containing 3,164 words called filtered and I have sorted them by their suffixes, which doesn't seem much of a help.
(I want to create a dictionary that takes the suffix as a key and the words as a list but I don't know where to begin!) It would be something like:
OUTPUT:
dic = {'ab': ['Ahab', 'Arab', 'Saab, ...]; 'al': ['Aral', 'Baal', ...]}
and so on. Would that be possible?
filtered.sort(key= lambda x : x[-2:])
print(filtered)
['HSBC', 'UCLA', 'FNMA', 'SARS', 'OHSA', 'Ahab', 'Arab', 'Saab', 'blab', 'crab', 'drab', 'flab', 'grab', 'scab', 'slab', 'stab', 'swab', 'Brad', 'Chad', 'Head', 'Mead', 'Thad', 'Vlad', 'bead', 'brad', 'clad', 'dead', 'glad', 'goad', 'grad', 'head', 'iPad', 'lead', 'load', 'mead', 'quad', 'read', 'road', 'scad', 'shad', 'toad', 'Olaf', 'Piaf', 'deaf', 'leaf', 'loaf', 'brag', 'crag', 'drag', 'flag', 'shag', 'slag', 'snag', 'stag', 'swag', 'Leah', 'Noah', 'Ptah', 'Utah', 'blah', 'shah', 'yeah', 'Thai', 'beak', 'flak', 'leak', 'peak', 'soak', 'teak', 'weak', 'Aral', 'Baal', 'Dial', 'Neal', 'Opal', 'Ural', 'anal', 'coal', 'deal', 'dial', 'dual', 'foal', 'goal', 'heal', 'meal', 'opal', 'oral', 'oval', 'peal', 'real', 'seal', 'teal', 'veal', 'vial', 'weal', 'zeal', 'Adam', 'Edam', 'Elam', 'Guam', 'Siam', 'Spam', 'beam', 'clam', 'cram', 'dram', 'exam', 'foam', 'gram', 'imam', 'loam', 'pram', 'ream', 'roam', 'scam', 'seam', 'sham', 'slam', 'swam', 'team', 'tram', 'wham', 'Adan', 'Alan', 'Bean', 'Bran', 'Chan', 'Dean', 'Evan', 'Fran', 'Iran', 'Ivan', 'Jean', 'Joan', 'Juan', 'Khan', 'Klan', 'Kwan', 'Lean', 'Oman', 'Oran', 'Ryan', 'Sean', 'Sian', 'Stan', 'Tran', 'Yuan', 'bean', 'bran', 'clan', 'dean', 'flan', 'khan', 'lean', 'loan', 'mean', 'moan', 'plan', 'roan', 'scan', 'span', 'swan', 'than', 'wean', 'chap', 'clap', 'crap', 'flap', 'heap', 'leap', 'reap', 'slap', 'snap', 'soap', 'swap', 'trap', 'wrap', 'Iraq', 'Adar', 'Alar', 'Iyar', 'Lear', 'Omar', 'Paar', 'Saar', 'Thar', 'afar', 'agar', 'ajar', 'bear', 'boar', 'char', 'czar', 'dear', 'fear', 'gear', 'hear', 'liar', 'near', 'pear', 'rear', 'roar', 'scar', 'sear', 'soar', 'spar', 'star', 'tear', 'tsar', 'tzar', 'wear', 'year', 'Boas', 'Haas', 'Xmas', 'alas', 'baas', 'bias', 'boas', 'bras', 'eras', 'leas', 'peas', 'seas', 'spas', 'teas', 'yeas', 'Fiat', 'beat', 'boat', 'brat', 'chat', 'coat', 'feat', 'fiat', 'flat', 'frat', 'gnat', 'goat', 'heat', 'meat', 'moat', 'neat', 'peat', 'scat', 'seat'...]
Assuming that suffixes are always two letters long and are case-sensitive, you can iterate through the word list and append each word to the dict of lists with the last two letters of the word as the key:
dic = {}
for word in filtered:
dic.setdefault(word[-2:], []).append(word)
dic becomes:
{'BC': ['HSBC'], 'LA': ['UCLA'], 'MA': ['FNMA'], 'RS': ['SARS'], 'SA': ['OHSA'], 'ab': ['Ahab', 'Arab', 'Saab', 'blab', 'crab', 'drab', 'flab', 'grab', 'scab', 'slab', 'stab', 'swab'], 'ad': ['Brad', 'Chad', 'Head', 'Mead', 'Thad', 'Vlad', 'bead', 'brad', 'clad', 'dead', 'glad', 'goad', 'grad', 'head', 'iPad', 'lead', 'load', 'mead', 'quad', 'read', 'road', 'scad', 'shad', 'toad'], 'af': ['Olaf', 'Piaf', 'deaf', 'leaf', 'loaf'], 'ag': ['brag', 'crag', 'drag', 'flag', 'shag', 'slag', 'snag', 'stag', 'swag'], 'ah': ['Leah', 'Noah', 'Ptah', 'Utah', 'blah', 'shah', 'yeah'], 'ai': ['Thai'], 'ak': ['beak', 'flak', 'leak', 'peak', 'soak', 'teak', 'weak'], 'al': ['Aral', 'Baal', 'Dial', 'Neal', 'Opal', 'Ural', 'anal', 'coal', 'deal', 'dial', 'dual', 'foal', 'goal', 'heal', 'meal', 'opal', 'oral', 'oval', 'peal', 'real', 'seal', 'teal', 'veal', 'vial', 'weal', 'zeal'], 'am': ['Adam', 'Edam', 'Elam', 'Guam', 'Siam', 'Spam', 'beam', 'clam', 'cram', 'dram', 'exam', 'foam', 'gram', 'imam', 'loam', 'pram', 'ream', 'roam', 'scam', 'seam', 'sham', 'slam', 'swam', 'team', 'tram', 'wham'], 'an': ['Adan', 'Alan', 'Bean', 'Bran', 'Chan', 'Dean', 'Evan', 'Fran', 'Iran', 'Ivan', 'Jean', 'Joan', 'Juan', 'Khan', 'Klan', 'Kwan', 'Lean', 'Oman', 'Oran', 'Ryan', 'Sean', 'Sian', 'Stan', 'Tran', 'Yuan', 'bean', 'bran', 'clan', 'dean', 'flan', 'khan', 'lean', 'loan', 'mean', 'moan', 'plan', 'roan', 'scan', 'span', 'swan', 'than', 'wean'], 'ap': ['chap', 'clap', 'crap', 'flap', 'heap', 'leap', 'reap', 'slap', 'snap', 'soap', 'swap', 'trap', 'wrap'], 'aq': ['Iraq'], 'ar': ['Adar', 'Alar', 'Iyar', 'Lear', 'Omar', 'Paar', 'Saar', 'Thar', 'afar', 'agar', 'ajar', 'bear', 'boar', 'char', 'czar', 'dear', 'fear', 'gear', 'hear', 'liar', 'near', 'pear', 'rear', 'roar', 'scar', 'sear', 'soar', 'spar', 'star', 'tear', 'tsar', 'tzar', 'wear', 'year'], 'as': ['Boas', 'Haas', 'Xmas', 'alas', 'baas', 'bias', 'boas', 'bras', 'eras', 'leas', 'peas', 'seas', 'spas', 'teas', 'yeas'], 'at': ['Fiat', 'beat', 'boat', 'brat', 'chat', 'coat', 'feat', 'fiat', 'flat', 'frat', 'gnat', 'goat', 'heat', 'meat', 'moat', 'neat', 'peat', 'scat', 'seat']}
I have two solutions for you.
Solution 1:
>>> from itertools import groupby
>>> key_func = lambda s: s[-2:]
>>> suffix_dict = dict([(suffix, list(words)) for suffix, words in groupby(sorted(filtered, key=key_func), key_func)])
Solution 2:
>>> from collections import defaultdict
>>> suffix_dict = defaultdict(list)
>>> for word in filtered:
... suffix_dict[word[-2:]].append(word)
Solution 2 would be relatively faster compared to Solution 1. Defaultdict will never raise a KeyError. Defaultdict works exactly like a dict in python, and it provides a default value for a non-existent key. More importantly, defaultdict is generally considered faster and optimized than dict, when there are lot of update operations involved. Several performance results have shown that defaultdict is often better than a normal dict, 1 and 2.
Benefits of Solution 1 over the other solution: Grouby needs two arguments - the data which it needs to group, and a function to group with. The data it iterates over needs to be sorted which is generally the same key function.
So when you get the final result 'suffix_dict', each list of words would be already sorted. Whereas, in Solution 1, the ordering of words from the original list 'filtered' would be retained.
Also, the performance between the two solution is marginal, especially if your original list is small.
So you can choose whichever suits your need more.
The counting part is easy:
>>> { k: len(v) for k, v in suffix_dict.items()}
References:
https://medium.com/#jaturongkongmanee/better-using-defaultdict-instead-of-just-only-dictionaries-in-python-5f66393363cd
https://www.reddit.com/r/learnpython/comments/2n2dgn/performance_difference_defaultdict_versus/

how to create a dictionary nested in python which will denote the number of occurences of a word associated with a particular work?

I have a list like :-
new_list=[['happy', 'people', 'need', 'rest'], ['rest', 'apple', 'good', 'happy'],['kepler', 'people', 'happy', 'apple'],['need', 'good', 'happy', 'good']]
and another list like
a=['good', 'apple', 'people', 'rest', 'kepler', 'need', 'happy']
which contains the number of distinct words of the new_list given.
Now i want to iterate through each element in list 'a' and find the sublists in new_list that contain that element and then in those sublists I want to calculate the occurance of words in it. For example for word "good" in list "a" the sublists in new_list containing "good" are
[['rest', 'apple', 'good', 'happy'],['need', 'good', 'happy', 'good']]
now calculating the occurance of earch word in this list
{"good":{"rest":1,"apple":1,"happy":2,"need":1}}
similarly I want the overall output for all the elements in 'a' list. How to do tht ?
You can use nested fors and ifs.
new_list=[['happy', 'people', 'need', 'rest'], ['rest', 'apple', 'good', 'happy'],['kepler', 'people', 'happy', 'apple'],['need', 'good', 'happy', 'good']]
a=['good', 'apple', 'people', 'rest', 'kepler', 'need', 'happy']
dct = {}
for item in a:
mid_dct = {}
for lst in new_list:
if item in lst: #checks if distinct item is in list
for word in lst: #iterates over that list to store words and their number of occurences
if word != item:
if word in mid_dct: #if that word in dct, adds one, if not adds that to list
mid_dct[word] += 1
else:
mid_dct[word] = 1
dct[item] = mid_dct
print dct

Extract consecutive numbers to form ranges in scala list

i have a scala list of tuples,
val stdLis:List[(String,Int)]=null
I need to combine the consecutive integers in the list to form ranges. The final result only needs ranges of integers from the list. The following approach leaves the non-consecutive numbers. But i need to form ranges for the consecutive numbers and also retain non consecutive numbers in the final list.
def mergeConsecutiveNum(lis:List[(String,Int)])={
var lisBuf = new ListBuffer[(String,Int)]
val newRanges = new ListBuffer[(Int,Int)]()
if(lis.size>1)
lis.sliding(2).foreach{i=>
if(i(0)._2+1 == i(1)._2)
lisBuf.appendAll(i)
else{
//println(lisBuf)
if(lisBuf.size>1) {
newRanges.append((lisBuf.head._2, lisBuf.last._2))
newRanges.append((i(0)._2,i(1)._2))
}
lisBuf.clear()
}
}else
newRanges.append((lis.head._2,0))
newRanges
}
for example:
val lis = List(("a",1),("b",2),("c",3),("d",4),("e",6),("f",7),("g",9))
it should give
lis((1,4),(6,7),(9,0))
Don't exactly know what you are asking.
Your code does not return anything.
Anyways, assuming that you need to merge two consecutive numbers in the list and create a range of list based on those numbers, here is something you can try
List(("", 5),("", 10),("", 6),("", 10)).map(_._2).grouped(2).map(ele => ele(0) to ele(1)).toList
List(Range(5, 6, 7, 8, 9, 10), Range(6, 7, 8, 9, 10))