Reputation: 13
I'm trying to convert a Python script to PowerShell but I don't have any Python experience and it's getting long for a little piece of code.
def combinliste(seq, k):
p = []
i, imax = 0, 2**len(seq)-1
while i<=imax:
s = []
j, jmax = 0, len(seq)-1
while j<=jmax:
if (i>>j)&1==1:
s.append(seq[j])
j += 1
if len(s)==k:
p.append(s)
i += 1
return p
I have made something but I really don't know if it's correct.
What is +=
in PowerShell, is it same as Python?
function combinliste {
Param($seq, $k)
$p = @()
$i; $imax = 0, [Math]::Pow(2, $seq.Count) - 1
while ($i -le $jmax) {
$s = @()
$j, $jmax = 0, $seq.Count - 1
while ($j -le $jmax) {
if ($i -shr $j -band 1 -eq 1) {
$s + ($seq ???? #I don't know how to do it here
}
$j #humm.. 1
}
if ($s.Count -eq $k) {
$p + $s
}
$i #humm.. 1
return $p
}
}
I have tried few variations, but I'm lost.
Upvotes: 1
Views: 9306
Reputation: 2355
function combinliste { param($seq,$k)
$p = New-Object System.Collections.ArrayList
$i, $imax = 0, ([math]::Pow(2, $seq.Length) - 1)
while ($i -le $imax) {
$s = New-Object System.Collections.ArrayList
$j, $jmax = 0, ($seq.Length - 1)
while ($j -le $jmax) {
if((($i -shr $j) -band 1) -eq 1) {$s.Add($seq[$j]) | Out-Null}
$j+=1
}
if ($s.Count -eq $k) {$p.Add($s) | Out-Null }
$i+=1
}
return $p
}
$p = combinliste @('green', 'red', 'blue', 'white', 'yellow') 3
$p | foreach {$_ -join " | "}
Upvotes: 3
Reputation: 200373
The append()
method updates an array in-place. The +
operator in PowerShell doesn't do that. You need the +=
assignment operator for it.
$s += $seq[$j]
and
$p += $s
Alternatively you can use ArrayList
collections instead of plain arrays:
$s = New-Object 'Collections.ArrayList'
and use their Add()
method:
$s.Add($seq[$j]) | Out-Null
The trailing Out-Null
is to suppress the index of the appended item that Add()
outputs by default.
Side note: you probably need to put the return $p
after the outer while
loop, and $i; $imax = ...
must be $i, $imax = ...
for assigning two values to two variables in one statement.
Upvotes: 0