np.array([0, 0, 0]) [ [1, 2, 2] ] += [4, 5, 6] does not accumulate - numpy

All arrays in the following are NumPy arrays.
I have an array of numbers, say a = [4, 5, 6].
I want to add them to an accumulation array, say s = [0, 0, 0]
but I want to control which number goes to where.
For instance, I want
s[1] += a[0],
s[2] += a[1], and then
s[2] += a[2].
So I set up an auxiliary array i = [1, 2, 2]
and hope that s[i] += a would work.
But it wouldn't;
s[2] end up only receiving a[2],
as if s[i] += a is implemented by
t = [0, 0, 0]; t[i] = a; s += t.
I would like to know if there is a way to achieve my version of "s[i] += a"
without having to do for-loops in pure python,
as I heard that the latter is much slower.

Related

Convert the value of a dictionary in a column into a particular number in pandas

I have a dataframe as shown below
Date Aspect
21-01-2020 {word1:'positive', word2:'negative', word3:'neutral'}
22-01-2020 {word1:'negative', word2:'negative', word3:'neutral', word4:'neutral'}
23-01-2020 {word1:'positive', word2:'positive', word3:'negative'}
I would like to replace positive to 1, negative to -1 and neutral to 0.
Expected Output:
Date Aspect
21-01-2020 {word1:1, word2:-1, word3:0}
22-01-2020 {word1:-1, word2:-1, word3:0, word4:0}
23-01-2020 {word1:1, word2:1, word3:-1}
If column Aspect is filled by dictionaries use dict comprehension with mapping by helper dict:
d = {'positive':1, 'negative':-1, 'neutral':0}
df['Aspect'] = df['Aspect'].apply(lambda x: {k: d[v] for k, v in x.items()})
#alternative
#df['Aspect'] = [{k: d[v] for k, v in x.items()} for x in df['Aspect']]
print (df)
Date Aspect
0 21-01-2020 {'word1': 1, ' word2': -1, 'word3': 0}
1 22-01-2020 {'word1': -1, 'word2': -1, 'word3': 0, 'word4'...
2 23-01-2020 {'word1': 1, 'word2': 1, 'word3': -1}

Unweave sequence, Kotlin functional/streaming idiom

I have a sequence of interleaved data (with fixed stride) and I'd like to reduce it to a single value for each "structure" (n*stride values to n values).
I could just use loop writing into the mutable list with selected step for reader index, but I'm looking for more functional and readable approach. Any thoughts?
For example:
Input sequence consists of RGB triplets (stride 3) and output is grayscale.
Imperative way is like:
fun greyscale(stream:List<Byte>):List<Byte>{
val out = ArrayList(stream.size / 3)
var i = 0; var o = 0
while(i < stream.size)
out[o++]=(stream[i++] + stream[i++] + stream[i++])/3
return out
}
How can I make something like that without explicitly implementing a function and mutable container, but purely on functional extensions like .map and so on?
Kotlin 1.2 (Milestone 1 was released yesterday) brings the chunked method on collections. It chunks up the collection into blocks of a given size. You can use this to implement your function:
fun greyscale(stream: List<Byte>): List<Byte> =
stream.chunked(3)
.map { (it.sum() / 3).toByte() }
A possible way would be grouping by the index of the elements (in this case /3) and mapping these groups to their sum.
stream.withIndex()
.groupBy { it.index / 3 }
.toSortedMap()
.values
.map { (it.sumBy { it.value } / 3).toByte() }
Also strictly functional, but using Rx, would be possible by using window(long)
Observable.from(stream)
.window(3)
.concatMap { it.reduce(Int::plus).toObservable() }
.map { (it / 3).toByte() }
Similar to #marstran's answer, in Kotlin 1.2 you can use chunked function, but providing the transform lambda to it:
fun greyscale(stream: List<Byte>): List<Byte> =
stream.chunked(3) { it.average().toByte() }
This variant has an advantage that it doesn't instantiate a new List for every triple, but rather creates a single List and reuses it during the entire operation.
Excludes remaining elements:
const val N = 3
fun greyscale(stream: List<Byte>) = (0 until stream.size / N)
.map { it * N }
.map { stream.subList(it, it + N).sum() / N }
.map(Int::toByte)
Output
[1, 2, 3, 4, 5, 6] => [2, 5]
[1, 2, 3, 4, 5] => [2]
Includes remaining elements:
const val N = 3
fun greyscale(stream: List<Byte>) = (0 until (stream.size + N - 1) / N)
.map { it * N }
.map { stream.subList(it, minOf(stream.size, it + N)).sum() / N }
.map(Int::toByte)
Output
[1, 2, 3, 4, 5, 6] => [2, 5]
[1, 2, 3, 4, 5] => [2, 3]
Best what I'm capable of is this:
fun grayscale(rgb:List<Byte>):List<Byte>
= rgb.foldIndexed(
IntArray(rgb.size / 3),
{ idx, acc, i ->
acc[idx / 3] = acc[idx / 3] + i; acc
}).map{ (it / 3).toByte() }
Output
in: [1, 2, 3, 4, 5, 6]
out: [2, 5]
And variations with ArrayList with add and last

Is there a way to fold with index in Rust?

In Ruby, if I had an array a = [1, 2, 3, 4, 5] and I wanted to get the sum of each element times its index I could do
a.each.with_index.inject(0) {|s,(i,j)| s + i*j}
Is there an idiomatic way to do the same thing in Rust? So far, I have
a.into_iter().fold(0, |x, i| x + i)
But that doesn't account for the index, and I can't really figure out a way to get it to account for the index. Is this possible and if so, how?
You can chain it with enumerate:
fn main() {
let a = [1, 2, 3, 4, 5];
let b = a.into_iter().enumerate().fold(0, |s, (i, j)| s + i * j);
println!("{:?}", b); // Prints 40
}

Groovy not returning a list of lists after for loop

I am learning Groovy and I am trying to return a list of lists but when I do my for loop in counter() function, it automatically returns just giving me the first iteration and doesn't continue with the rest of the words.
I found the issue is in the for loop of counter(), it looks like Groovy shares the i variable in the loops. Coming from Python each for loop holds its own variable i. Is there something like this in Groovy?
lista = ["apple","banana","orange","melon","watermelon"]
def copaa(a_list_of_things){
lista_to_return = []
for (i = 0; i < a_list_of_things.size(); i++) {
lis = counter(a_list_of_things[i])
lista_to_return.add(lis)
}
return lista_to_return
}
def counter(word){
list_of_times = []
//return "bla"
for (i = 0; i < word.length(); i++) {
list_of_times.add(i)
}
return list_of_times
}
ls = copaa(lista)
println(ls)
Avoid global scope:
prefix the i variable declarations with the implicit type def (actually Object) or an appropriate explicit type (e.g. int or Integer) to make the scope local to the loop. Otherwise these variables are placed (as a single one i) in the bindings of the script (practically it's treated as a global variable).
Modify the relevant lines of your code like this:
// with def...
for (def i = 0; i < a_list_of_things.size(); i++) {
// ...
for (def i = 0; i < word.length(); i++) {
// ...OR with an explicit type (e.g. int) the scope is limited
// to the for loop as expected
for (int i = 0; i < a_list_of_things.size(); i++) {
// ...
for (int i = 0; i < word.length(); i++) {
Output
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
The Groovy Way
To gives you some extra hints I reimplemented your algorithm using some of the cool features groovy provides (collect, closure, numeric ranges):
wordList = ["apple","watermelon"]
// collect process each word (the implicit variable it) and returns a new list
// each field of the new list is a range from 0 till it.size() (not included)
outList = wordList.collect { (0 ..< it.size()).toArray() }
assert outList == [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

How to create cartesian product [duplicate]

This question already has answers here:
Generate all possible n-character passwords
(4 answers)
Closed 1 year ago.
I have a list of integers, a = [0, ..., n]. I want to generate all possible combinations of k elements from a; i.e., the cartesian product of the a with itself k times. Note that n and k are both changeable at runtime, so this needs to be at least a somewhat adjustable function.
So if n was 3, and k was 2:
a = [0, 1, 2, 3]
k = 2
desired = [(0,0), (0, 1), (0, 2), ..., (2,3), (3,0), ..., (3,3)]
In python I would use the itertools.product() function:
for p in itertools.product(a, repeat=2):
print p
What's an idiomatic way to do this in Go?
Initial guess is a closure that returns a slice of integers, but it doesn't feel very clean.
For example,
package main
import "fmt"
func nextProduct(a []int, r int) func() []int {
p := make([]int, r)
x := make([]int, len(p))
return func() []int {
p := p[:len(x)]
for i, xi := range x {
p[i] = a[xi]
}
for i := len(x) - 1; i >= 0; i-- {
x[i]++
if x[i] < len(a) {
break
}
x[i] = 0
if i <= 0 {
x = x[0:0]
break
}
}
return p
}
}
func main() {
a := []int{0, 1, 2, 3}
k := 2
np := nextProduct(a, k)
for {
product := np()
if len(product) == 0 {
break
}
fmt.Println(product)
}
}
Output:
[0 0]
[0 1]
[0 2]
[0 3]
[1 0]
[1 1]
[1 2]
[1 3]
[2 0]
[2 1]
[2 2]
[2 3]
[3 0]
[3 1]
[3 2]
[3 3]
The code to find the next product in lexicographic order is simple: starting from the right, find the first value that won't roll over when you increment it, increment that and zero the values to the right.
package main
import "fmt"
func main() {
n, k := 5, 2
ix := make([]int, k)
for {
fmt.Println(ix)
j := k - 1
for ; j >= 0 && ix[j] == n-1; j-- {
ix[j] = 0
}
if j < 0 {
return
}
ix[j]++
}
}
I've changed "n" to mean the set is [0, 1, ..., n-1] rather than [0, 1, ..., n] as given in the question, since the latter is confusing since it has n+1 elements.
Just follow the answer Implement Ruby style Cartesian product in Go, play it on http://play.golang.org/p/NR1_3Fsq8F
package main
import "fmt"
// NextIndex sets ix to the lexicographically next value,
// such that for each i>0, 0 <= ix[i] < lens.
func NextIndex(ix []int, lens int) {
for j := len(ix) - 1; j >= 0; j-- {
ix[j]++
if j == 0 || ix[j] < lens {
return
}
ix[j] = 0
}
}
func main() {
a := []int{0, 1, 2, 3}
k := 2
lens := len(a)
r := make([]int, k)
for ix := make([]int, k); ix[0] < lens; NextIndex(ix, lens) {
for i, j := range ix {
r[i] = a[j]
}
fmt.Println(r)
}
}