Is there a way to get 4 instead of 2 as a result?
List<String> test = [
'first',
'second',
if (false) 'third',
if (false) 'fourth',
];
print('length: ' + test.length.toString());
The length property on lists returns the number of elements in the list. In you example you are only inserting two values (because of the condition) so a length of 4 would not make sense and would give problems when you e.g. want to iterate over the list.
You can however add null elements if the condition are false like this:
void main() {
List<String> list = [
'first',
'second',
(false) ? 'third' : null,
(false) ? 'fourth' : null,
];
final listLengthIncludingConditions = list.length;
list.removeWhere((x) => x != null);
print('Number of possible elements in list: $listLengthIncludingConditions'); // 4
print('Number of elements in list: ${list.length}'); // 2
}
You can then save the length and remove the null elements.
Related
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 do I take a specific number of input in python. Say, if I only want to insert 5 elements in a list then how can I do that?
I tried to do it but couldn't figure out how.
In the first line I want to take an integer which will be the size of the list.
Second line will consist 5 elements separated by a space like this:
5
1 2 3 4 5
Thanks in advance.
count = int(raw_input("Number of elements:"))
data = raw_input("Data: ")
result = data.split(sep=" ", maxsplit=count)
if len(result) < count:
print("Too few elements")
You can also wrap int(input("Number of elements:")) in try/except to ensure that first input is actually int.
p.s. here is helpful q/a how to loop until correct input.
Input :-
5
1 2 3 4 5
then, use the below code :
n = int(input()) # Number of elements
List = list ( map ( int, input().split(" ") ) )
Takes the space separated input as list of integers. Number of elements count is not necessary here.
You can get the size of the List by len(List) .
Here list is a keyword for generating a List.
Or you may use an alternative :
n = int(input()) # Number of elements
List = [ int(elem) for elem in input().split(" ") ]
If you want it as List of strings, then use :
List = list( input().split(" ") )
or
s = input() # default input is string by using input() function in python 2.7+
List = list( s.split(" ") )
Or
List = [ elem for elem in input().split(" ") ]
Number of elements count is necessary while using a loop for receiving input in a new line ,then
Let the Input be like :
5
1
2
3
4
5
The modified code will be:-
n = int(input())
List = [ ] #declare an Empty list
for i in range(n):
elem = int(input())
List.append ( elem )
For Earlier version of python , use raw_input ( ) instead of input ( ), which receives default input as String.
I am trying to script a dynamic way way to only take the first two elements in a list and I am having some trouble. Below is a breakdown of what I have in my List
Declaration:
Set List = CreateObject("Scripting.Dictionary")
List Contents:
List(0) = 0-0-0-0
List(1) = 0-1-0-0
List(2) = 0-2-0-0
Code so far:
for count = 0 To UBound(List) -1 step 1
//not sure how to return
next
What I currently have does not work.
Desired Return List:
0-0-0-0
0-1-0-0
You need to use the Items method of the Dictionary. For more info see here
For example:
Dim a, i
a = List.Items
For i = 0 To List.Count - 1
MsgBox(a(i))
Next i
or if you just want the first 2:
For i = 0 To 1
MsgBox(a(i))
Next i
UBound() is for arrays, not dictionaries. You need to use the Count property of the Dictionary object.
' Show all dictionary items...
For i = 0 To List.Count - 1
MsgBox List(i)
Next
' Show the first two dictionary items...
For i = 0 To 1
MsgBox List(i)
Next
Does Groovy have a smart way to check if a list is sorted? Precondition is that Groovy actually knows how to sort the objects, e.g. a list of strings.
The way I do right now (with just some test values for this example) is to copy the list to a new list, then sort it and check that they are equal. Something like:
def possiblySorted = ["1", "2", "3"]
def sortedCopy = new ArrayList<>(possiblySorted)
sortedCopy.sort()
I use this in unit tests in several places so it would be nice with something like:
def possiblySorted = ["1", "2", "3"]
possiblySorted.isSorted()
Is there a good way like this to check if a list is sorted in Groovy, or which is the preffered way? I would almost expect Groovy to have something like this, since it is so smart with collections and iteration.
If you want to avoid doing an O(n*log(n)) operation to check if a list is sorted, you can iterate it just once and check if every item is less or equals than the next one:
def isSorted(list) {
list.size() < 2 || (1..<list.size()).every { list[it - 1] <= list[it] }
}
assert isSorted([])
assert isSorted([1])
assert isSorted([1, 2, 2, 3])
assert !isSorted([1, 2, 3, 2])
Why not just compare it to a sorted instance of the same list?
def possiblySorted = [ 4, 2, 1 ]
// Should fail
assert possiblySorted == possiblySorted.sort( false )
We pass false to the sort method, so it returns a new list rather than modifying the existing one
You could add a method like so:
List.metaClass.isSorted = { -> delegate == delegate.sort( false ) }
Then, you can do:
assert [ 1, 2, 3 ].isSorted()
assert ![ 1, 3, 2 ].isSorted()
I use this question in interviews and I wonder what the best solution is.
Write a Perl sub that takes n lists, and then returns 2^n-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that n is reasonably small (less than 20).
For example:
list_compare([1, 3], [2, 3]);
=> ([1], [2], [3]);
Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.
list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7])
=> ([1], [2], [3], [4], [5], [6], [7])
Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.
I usually give this problem as a follow up to the subset of this problem for n=2.
What is the solution?
Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does.
Your given solution can be simplified quite a bit still.
In the first loop, you can use plain addition since you are only ever ORing with single bits, and you can narrow the scope of $bit by iterating over indices. In the second loop, you can subtract 1 from the index instead of producing an unnecessary 0th output list element that needs to be shifted off, and where you unnecessarily iterate m*n times (where m is the number of output lists and n is the number of unique elements), iterating over the unique elements would reduce the iterations to just n (which is a significant win in typical use cases where m is much larger than n), and would simplify the code.
sub list_compare {
my ( #list ) = #_;
my %dest;
for my $i ( 0 .. $#list ) {
my $bit = 2**$i;
$dest{$_} += $bit for #{ $list[ $i ] };
}
my #output_list;
for my $val ( keys %dest ) {
push #{ $output_list[ $dest{ $val } - 1 ] }, $val;
}
return \#output_list;
}
Note also that once thought of in this way, the result gathering process can be written very concisely with the aid of the List::Part module:
use List::Part;
sub list_compare {
my ( #list ) = #_;
my %dest;
for my $i ( 0 .. $#list ) {
my $bit = 2**$i;
$dest{$_} += $bit for #{ $list[ $i ] };
}
return [ part { $dest{ $_ } - 1 } keys %dest ];
}
But note that list_compare is a terrible name. Something like part_elems_by_membership would be much better. Also, the imprecisions in your question Ben Tilly pointed out need to be rectified.
First of all I would like to note that nohat's answer simply does not work. Try running it, and look at the output in Data::Dumper to verify that.
That said, your question is not well-posed. It looks like you are using sets as arrays. How do you wish to handle duplicates? How do you want to handle complex data structures? What order do you want elements in? For ease I'll assume that the answers are squash duplicates, it is OK to stringify complex data structures, and order does not matter. In that case the following is a perfectly adequate answer:
sub list_compare {
my #lists = #_;
my #answers;
for my $list (#lists) {
my %in_list = map {$_=>1} #$list;
# We have this list.
my #more_answers = [keys %in_list];
for my $answer (#answers) {
push #more_answers, [grep $in_list{$_}, #$answer];
}
push #answers, #more_answers;
}
return #answers;
}
If you want to adjust those assumptions, you'll need to adjust the code. For example not squashing complex data structures and not squashing duplicates can be done with:
sub list_compare {
my #lists = #_;
my #answers;
for my $list (#lists) {
my %in_list = map {$_=>1} #$list;
# We have this list.
my #more_answers = [#$list];
for my $answer (#answers) {
push #more_answers, [grep $in_list{$_}, #$answer];
}
push #answers, #more_answers;
}
return #answers;
}
This is, however, using the stringification of the data structure to check whether things that exist in one exist in another. Relaxing that condition would require somewhat more work.
Here is my solution:
Construct a hash whose keys are the union of all the elements in the input lists, and the values are bit strings, where bit i is set if the element is present in list i. The bit strings are constructed using bitwise or. Then, construct the output lists by iterating over the keys of the hash, adding keys to the associated output list.
sub list_compare {
my (#lists) = #_;
my %compare;
my $bit = 1;
foreach my $list (#lists) {
$compare{$_} |= $bit foreach #$list;
$bit *= 2; # shift over one bit
}
my #output_lists;
foreach my $item (keys %compare) {
push #{ $output_lists[ $compare{$item} - 1 ] }, $item;
}
return \#output_lists;
}
Updated to include the inverted output list generation suggested by Aristotle