Dart - First letter of each word in a List - list

List<String> pisah = ['saya','sedang','belajar','menjadi','programmer','yang','handal','dan','menyenangkan'];
How can I make that list so that I can print just every first letter of the word
example like :
baris 1 : S S B M P Y H D M

That's all in a day's work for the method map.
final letters = pisah.map((s) => s[0]).toList();
print(letters);
The .toList() call may or may not be needed depending on what exactly you want to do with the result. For example, it can be omitted if you want only to iterate over it, but it's required if you need to access individual letters using letter[i].

Related

How to call characters from first list with second list

I want to input two comma separated strings: the first a set of strings, the second a set of ranges and return substrings based on ranges, for example:
x=input("Input string to search: ")
search=x.split(',')
y=input("Input numbers to locate: ")
numbers=y.split(',')
I would then like to use the second list of ranges to print out specified characters from the first list.
An example:
Input string to search: abcdefffg,aabcdefghi,bbcccdefghi
Input numbers to locate: 1:2,2:3,5:9
I would like the output to look like this:
bc
bcd
defghi
Any suggestions? Thanks in advance!
split(':') splits a "range" into its two components. map(int, ...) converts them to integers. string[a:b] takes characters at indices a through b.
zip is an easy way to read from two different lists combined.
Let me know if you have any other questions:
x = "abcdefffg,aabcdefghi,bbcccdefghi"
search = x.split(',')
y = "1:2,2:3,5:9"
numbers = y.split(',')
results = []
for string, rng in zip(search, numbers):
start, how_many = map(int, rng.split(':'))
results.append(string[start:start+how_many])
print(" ".join(results))
# Output:
# bc bcd defghi

Extract substring based on regex to use in RDD.filter

I am trying to filter out rows of a text file whose second column value begins with words from a list.
I have the list such as:
val mylist = ["Inter", "Intra"]
If I have a row like:
Cricket Inter-house
Inter is in the list, so that row should get filtered out by the RDD.filter operation. I am using the following regex:
`[A-Za-z0-9]+`
I tried using """[A-Za-z0-9]+""".r to extract the substring but the result is in a non empty iterator.
My question is how to access the above result in the filter operation?
You need to construct regular expression like ".* Inter.*".r since """[A-Za-z0-9]+""" matches any word. Here is some working example, hope it helps:
val mylist = List("Inter", "Intra")
val textRdd = sc.parallelize(List("Cricket Inter-house", "Cricket Int-house",
"AAA BBB", "Cricket Intra-house"))
// map over my list to dynamically construct regular expressions and check if it is within
// the text and use reduce to make sure none of the pattern exists in the text, you have to
// call collect() to see the result or take(5) if you just want to see the first five results.
(textRdd.filter(text => mylist.map(word => !(".* " + word + ".*").r
.pattern.matcher(text).matches).reduce(_&&_)).collect())
// res1: Array[String] = Array(Cricket Int-house, AAA BBB)
filter will remove anything for which the function passed to the filter method returns true. Thus, Regex isn't exactly what you want. Instead, let's develop a function that takes a row and compares it against a candidate string and returns true if the second column in that row starts with the candidate:
val filterFunction: (String, String) => Boolean =
(row, candidate) => row.split(" ").tail.head.startsWith(candidate)
We can convince ourselves that this works pretty easily using a worksheet:
// Test data
val mylist = List("Inter", "Intra")
val file = List("Cricket Inter-house", "Boom Shakalaka")
filterFunction("Cricket Inter-house", "Inter") // true
filterFunction("Cricket Inter-house", "Intra") // false
filterFunction("Boom Shakalaka", "Inter") // false
filterFunction("Boom Shakalaka", "Intra") // false
Now all that remains is to utilize this function in the filter. Essentially, for every row, we want to test the filter against every line in our candidate list. That means taking the candidate list and 'folding left' to check every item on it against the function. If any candidate reports true, then we know that row should be filtered out of the final result:
val result = file.filter((row: String) => {
!mylist.foldLeft(false)((x: Boolean, candidate: String) => {
x || filterFunction(row, candidate)
})
})
// result: List[String] = List(Boom Shakalaka)
The above can be a little dense to unpack. We are passing to the filter method a function that takes in a row and produces a boolean value. We want that value to be true if and only if the row does not match our criteria. We've already embedded our criteria in the filterFunction: we just need to run it against every combination of item in mylist.
To do this we use foldLeft, which takes a starting value (in this case false) and iteratively moves through the list, updating that starting value and returning the final result.
To 'update' that value we write a function that logically-ORs the starting value with the result of running our filter function against the row and the current item in mylist.

Why is max number ignoring two-digit numbers?

At the moment I am saving a set of variables to a text file. I am doing following to check if my code works, but whenever I use a two-digit numbers such as 10 it would not print this number as the max number.
If my text file looked like this.
tom:5
tom:10
tom:1
It would output 5 as the max number.
name = input('name')
score = 4
if name == 'tom':
fo= open('tom.txt','a')
fo.write('Tom: ')
fo.write(str(score ))
fo.write("\n")
fo.close()
if name == 'wood':
fo= open('wood.txt','a')
fo.write('Wood: ')
fo.write(str(score ))
fo.write("\n")
fo.close()
tomL2 = []
woodL2 = []
fo = open('tom.txt','r')
tomL = fo.readlines()
tomLi = tomL2 + tomL
fo.close
tomLL=max(tomLi)
print(tomLL)
fo = open('wood.txt','r')
woodL = fo.readlines()
woodLi = woodL2 + woodL
fo.close
woodLL=max(woodLi)
print(woodLL)
You are comparing strings, not numbers. You need to convert them into numbers before using max. For example, you have:
tomL = fo.readlines()
This contains a list of strings:
['tom:5\n', 'tom:10\n', 'tom:1\n']
Strings are ordered lexicographically (much like how words would be ordered in an English dictionary). If you want to compare numbers, you need to turn them into numbers first:
tomL_scores = [int(s.split(':')[1]) for s in tomL]
The parsing is done in the following way:
….split(':') separates the string into parts using a colon as the delimiter:
'tom:5\n' becomes ['tom', '5\n']
…[1] chooses the second element from the list:
['tom', '5\n'] becomes '5\n'
int(…) converts a string into an integer:
'5\n' becomes 5
The list comprehension [… for s in tomL] applies this sequence of operations to every element of the list.
Note that int (or similarly float) are rather picky about what it accepts: it must be in the form of a valid numeric literal or it will be rejected with an error (although preceding and trailing whitespace is allowed). This is why you need ….split(':')[1] to massage the string into a form that it's willing to accept.
This will yield:
[5, 10, 1]
Now, you can apply max to obtain the largest score.
As a side-note, the statement
fo.close
will not close a file, since it doesn't actually call the function. To call the function you must enclose the arguments in parentheses, even if there are none:
fo.close()

Sort a set of variables based on frequency from a Perl RegEx

I am attempting to use a table or array to list and sort items
this following sequence of letters, or items, by what is 'eaten'
first (in the captured perl RegEx) These four lists are the exact same
items, just entered in a different order, in succession.
Input items: these letters represent an action or an input into the
client.
a b c d
b c d a
c d b a
d a b c
perl regex:
^(\w+) eats (a|an) (\w+)\.$
So matches[4] will be the item captured.
This will trigger RegEx will fire in the client with 'each' set of
letters (a, b, c, d) Entered, separately. So four sets of a, b, c, d that
will be input in succession but on a rotating order basis. The above
RegEx will in fire 16x (once for each letter.) I need to be able to
sort it so, if (a) is eaten first every time, then that will have
priority at the top going down. But it might not always be (a), it
could be any of the letters that hold priority.
I need this priority list to be displayed to a Geyser such as
PrioList= Geyser.MiniConsole:new({
name="PrioList",
x="70%", y="50%",
width="30%", height="50%",
})
I then need to be able to set each letter to a different priority list
or variable. Because each separate letter will indicate a different
action needed to be taken, so I will need to say
if (a == highestpriority) then
do action / function()
end
I am unsure of how to write the 'for' statement that will be able to
sort and list these items based off the 4 groups of letters. I figure
the list will have to be saved and reset, after each sequence then
somehow entered into a table or array, and compared to each other for
the highest priority. But this seriously beyond what I know how to
script, but I would definitely love to learn this.
If I'm correctly understanding you, one option is to use a 1) hash to tally the frequency of the first letter entered, and 2) dispatch table to associate each letter with a subroutine:
use strict;
use warnings;
use List::Util qw/shuffle/;
my %seen;
my %dispatchTable = (
a => \&a_priority,
b => \&b_priority,
c => \&c_priority,
d => \&d_priority
);
for my $i ( 1 .. 4 ) {
my #chars = shuffle qw/a b c d/;
print "Round $i: #chars\n";
$seen{ $chars[0] }++;
}
my $priority = ( sort { $seen{$b} <=> $seen{$a} } keys %seen )[0];
print "Priority: $priority\n";
$dispatchTable{$priority}->();
sub a_priority {
print "a priority sub called\n";
}
sub b_priority {
print "b priority sub called\n";
}
sub c_priority {
print "c priority sub called\n";
}
sub d_priority {
print "d priority sub called\n";
}
Sample run output:
Round 1: d c a b
Round 2: b a d c
Round 3: d b a c
Round 4: c d a b
Priority: d
d priority sub called
You said, "I need to be able to sort it so, if (a) is eaten first every time..." The above attempts to select the item with the highest frequency--not the item that was first all four times.
You'll need to decide what to do in cases where more than one letter shares the same frequency, but perhaps this will help provide some direction.

How do I account for all possible orders?

I have 7 items...
a b c d e f and g
The seven items can be in any order. How to I check with regex that they are there (or not) but no other items are...
^(a)?(b)?(c)?(d)?(e)?(f)?(g)?$
Thad would check for the seven items with any combination of items missing, but only in that order. How do I have the regex check for any possible order of the 7 items?
Both of these would pass:
abcdefg
aceg
I need these to pass as well
bc
fabcd
bgef
I'm using single letters to simplify things. For example (\stest)? would be an example of one of the items (\skey="([^"<>]+)?")? is another... I would like to prevent duplicates as well.
These should not pass
abca
aa
gfdef
Something like this would work:
^(?!(.*(a|b|c|d|e|f|g).*(\2)))((a|b|c|d|e|f|g)+)$
If you are using php use preg_split seven times with a, b, c, d, e, f, g as the spliter expresion.
Concatenate the result and perform the next.
If any split gives you more than 2 elements you have duplicates
if your resulting final string is different from '' you have invalid parts.
Here you have the code
// checks that any part present is valid but not repeated and not extra stuff
function checkAny($que) {
// atention to the escaping \
$toCheck = array('a','b','c','\\skey="([^"<>]+)?"','d','/slashtest','f','g');
foreach($toCheck as $one){
// $t = preg_split('/'.preg_quote($one,'/').'/', $que); // preg_cuote is not valid for your propouse
$t = preg_split('~'.$one.'~', $que); // so, select a proper sign insted of ~
if(count($t)>2) return 'fail: repeated component/part';
$que = implode('', $t); // can use trim() here if it is usefull for you
if($que=='') return 'pass!!!'; //do not waste time doing any more tests
}
return 'fail: unknown component/part';
}
//test
echo checkAny('abcc'); // fail
echo checkAny('ab/slashtestc'); // fail because the repated a, be careful in test order to avoid this problem
echo checkAny('abcg'); // pass
echo checkAny('ab key="xx"c'); // pass
if php is not the case, preg_replace can be easy substituded on any language supporting regex