How to print lists in a scific order in kotlin? - kotlin

im working on a project and i have a list in kotlin like:
val list = listOf("banana", "1","apple","3","banana","2")
and i want to print it like
Output:
banana = 1
banana = 2
apple = 3
so like every work with the number should be like one val, and i need to print in scific order (the order is toooo random for any sort command), so im panning on just coppying the whole xinhua dictionary here (since all chinese words have a scific unicode), and make the code it replace like:
val list = listOf("banana丨", "1","apple丩","3","banana丨","2")
but how to print them in the order?
ps. even me as a chinese dont know most of the words in xinhua dictionary lol so there is more then enofe

Assuming that you have the following input list, as shown in your question, where the order of occurrence is always one word followed by the scific order:
val list = listOf("banana", "1","apple","3","banana","2")
You could do the following:
1. Create a data class that defines one entry in your raw input list
data class WordEntry(val word: String, val order: Int)
2. Map over your raw input list by using the windowed and map methods
val dictionary = list.windowed(2, 2).map { WordEntry(it.first(), it.last().toInt()) }
Here, the windowed(2, 2) method creates a window of size 2 and step 2, meaning that we iterate over the raw input list and always work with two entries at every second step. Assuming that the order in the raw input list is always the word followed by the scific order, this should work. Otherwise, this would not work, so the order is very important here!
3. Sort the transformed dictionary by the order property
val sortedDictionary = dictionary.sortedBy { it.order }
Edit: You can also sort by any other property. Just pass another property to the lambda expression of sortedBy (e.g. sortedBy { it.word } if you want to sort it by the word property)
4. Finally, you can print out your sorted dictionary
val outputStr = sortedDictionary.joinToString("\n") { "${it.word} = ${it.order}" }
print(outputStr)
Output:
banana = 1
banana = 2
apple = 3

Related

Get array from 1 to number of columns of csv in nextflow

One of my process gives output of one csv file. I want to create an array channel from 1 to number of columns. For example:
My output
my_out_ch.view() -> test.csv
Assume, test.csv has 11 columns. Now I want to create a channel which gives me:
1,2,3,4,5,6,7,8,910,11
How could I get this? I have tried with splitText operator as below without luck:
my_out_ch.splitText(by:1,limit:1)
But it only gives me the columns names. There is a parameter elem, I am not sure if elem could give me the array and also not sure how to use it. Any help?
You could use the splitCsv operator to parse the CSV file. Then create an intRange using the map operator. Either call collect() to emit a java.util.ArrayList or call join() to emit a string. For example:
params.input_tsv = 'test.tsv'
Channel.fromPath( params.input_tsv )
| splitCsv( sep: '\t', limit: 1 )
| map { (1..it.size()).join(',') }
| view()
Results:
1,2,3,4,5,6,7,8,9,10,11

How to sum specific elements of a mixed Kotlin collection

If I had a mixed type Kotlin collection how would I be able to access and sum specific elements within that list. for example:
var mixedList = listOf("dog", "cat", 7, "Apple", "Orange", 10)
elements[2] and [5] are Ints. So how would I access and add them together for 17?
As already suggested this problem can be easily solved using filterIsInstance and sum functions defined for Iterable as well as Sequence in kotlin statndard library. but one small, yet very important detail is performance implication of Iterable vs Sequence
For small data set
val sum = yourList.filterIsInstance<Int>.sum()
// In first pass list is filtered, in second pass sum is calculated
For large data sets
val sum = yourList.asSequence().filterIsInstance<Int>().sum()
// Item is filtered and added to sum in single pass
fun main() {
val mixedList = listOf("dog", "cat", 7, "Apple", "Orange", 10)
val sum = mixedList.filterIsInstance<Int>().sum()
println(sum)
}
Output:
17

How do I reverse each value in a column bit wise for a hex number?

I have a dataframe which has a column called hexa which has hex values like this. They are of dtype object.
hexa
0 00802259AA8D6204
1 00802259AA7F4504
2 00802259AA8D5A04
I would like to remove the first and last bits and reverse the values bitwise as follows:
hexa-rev
0 628DAA592280
1 457FAA592280
2 5A8DAA592280
Please help
I'll show you the complete solution up here and then explain its parts below:
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
list_of_bits = [i+j for i, j in zip(trimmed_bits[::2], trimmed_bits[1::2])]
reversed_bits = [list_of_bits[-i] for i in range(1,len(list_of_bits)+1)]
return ''.join(reversed_bits)
df['hexa-rev'] = df['hexa'].apply(lambda x: reverse_bits(x))
There are possibly a couple ways of doing it, but this way should solve your problem. The general strategy will be defining a function and then using the apply() method to apply it to all values in the column. It should look something like this:
df['hexa-rev'] = df['hexa'].apply(lambda x: reverse_bits(x))
Now we need to define the function we're going to apply to it. Breaking it down into its parts, we strip the first and last bit by indexing. Because of how negative indexes work, this will eliminate the first and last bit, regardless of the size. Your result is a list of characters that we will join together after processing.
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
The second line iterates through the list of characters, matches the first and second character of each bit together, and then concatenates them into a single string representing the bit.
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
list_of_bits = [i+j for i, j in zip(trimmed_bits[::2], trimmed_bits[1::2])]
The second to last line returns the list you just made in reverse order. Lastly, the function returns a single string of bits.
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
list_of_bits = [i+j for i, j in zip(trimmed_bits[::2], trimmed_bits[1::2])]
reversed_bits = [list_of_bits[-i] for i in range(1,len(list_of_bits)+1)]
return ''.join(reversed_bits)
I explained it in reverse order, but you want to define this function that you want applied to your column, and then use the apply() function to make it happen.

Count items in Infopath field

I created a form in Infopath with a rich text box field. The field is used to keep a list of usernames (first and last). I want to be able to keep a of count each entry and keep a tally. I then want to use that total # of entries to add or subtract from other fields. Is there any way to do that?
Is the rich text box field just a large string? If so you could just use python's built in split function, and either split by ("\r\n"), or (",").
Example:
u = "Bob, Michael, Jean"
x = u.split(",")
X will be a list of usernames. If you are using line breaks for each new username, then replace (",") with ("\r\n").
Now to count the items in a list you just need to iterate on the list you created with a for loop.
Example:
b = 0
u = "Bob, Michael, Jean"
x = u.split(",")
for i in x:
b += 1 // b will be the number of usernames

How to chose options in a while loop

My program --> I Will ask the user to introduce a number and I want to make that if the number is not in a random sequence (I choose 1,2,3) of numbers, the user need to write again a number until the number they enter is in the sequence:
a = (1,2,3)
option = int(input(''))
while option != a:
print('Enter a number between 1 and 3 !!')
option = int(input(''))
So as you can see I use the variable as a tuple but I don't know how to do it.. =(
Assuming the use of a tuple is obligatory, you will need to get input as a string, because it is iterable type. It will alow you easily convert to int, sign by sign, thru list comprehension. Now you have a list of ints, which you simply convert to a tuple. The final option variable looks:
option = tuple([int(sign) for sign in str(input(''))])
But consider keeping your signature in int instead of tuple. Int number is also unequivocal if its about sequence. In python 123 == 132 returns False. That way, you need only to replace:
a = (1,2,3)
by a:
a = 123
And script will works.