I'm working on such project, and got question for code compression.
There are many ways for list concatenation a+b, a.extend(b), and so on.
but my question is, there are any way for shallow concatenation of the lists; for example,
a = [1,2,3]
b = [4,5]
c = a+b
c
>> [1,2,3,4,5]
b[0] = 10
c
>> [1,2,3,4,5]
but, my desired result is [1,2,3,10,5], then how to define c for this?
If you create a nested list from a and b you can kinda achieve what you are looking for:
>>> a = [1, 2, 3]
>>> b = [4, 5]
>>> c = [a, b]
>>> b[0] = 10
>>> c
[[1, 2, 3], [10, 5]]
>>> c = [val for sub_list in c for val in sub_list]
>>> c
[1, 2, 3, 10, 5]
a = [1,2,3]
b = [4,5]
b[0] = 10
c = a+b
print(c)
or
import copy
a = [1,2,3]
b = [4,5]
c=[a,b]
bb = copy.copy(c)
c[1][0]=10
print([val for l in c for val in l])
# refer this link for shallow-deep-copy reference
# https://www.programiz.com/python-programming/shallow-deep-copy
Related
Can anyone explain, why the following happens with ES6 array destructuring?
let a, b, c
[a, b] = ['A', 'B']
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)
// expected: a=A b=BB c=C
// actual: a=BB b=C c=undefined
http://codepen.io/ronkot/pen/WxRqXg?editors=0011
As others have said, you're missing semicolons. But…
Can anyone explain?
There are no semicolons automatically inserted between your lines to separate the "two" statements, because it is valid as a single statement. It is parsed (and evaluated) as
let a = undefined, b = undefined, c = undefined;
[a, b] = (['A', 'B']
[(b, c)] = ['BB', 'C']);
console.log(`a=${a} b=${b} c=${c}`);
wherein
[a, b] = …; is a destructuring assignment as expected
(… = ['BB', 'C']) is an assignment expression assigning the array to the left hand side, and evaluating to the array
['A', 'B'][…] is a property reference on an array literal
(b, c) is using the comma operator, evaluating to c (which is undefined)
If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the start of every line that begins with (, [, /, +, - or `.
You've fallen into a trap of line wrapping and automatic semicolon insertion rules in JavaScript.
Take this example:
let x = [1, 2]
[2, 1]
It's the interpreted as:
let x = [1, 2][2, 1] // === [1, 2][(2, 1)] === [1, 2][1] === 2
That weird [(2, 1)] thing above is related to how Comma Operator works.
Thus, your example:
let a, b, c
[a, b] = ['A', 'B']
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)
Is interpreted as:
let a, b, c
[a, b] = ['A', 'B'][b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)
Now, if you insert a semicolon, it will work as you intended:
let a, b, c
[a, b] = ['A', 'B']; // note a semicolon here
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)
Also, it's a good idea to check your code by pasting it into Babel repl to see the generated output:
'use strict';
var a = void 0,
b = void 0,
c = void 0;
var _ref = ['A', 'B'][(b, c)] = ['BB', 'C'];
a = _ref[0];
b = _ref[1];
console.log('a=' + a + ' b=' + b + ' c=' + c);
I believe you have forgotten the line breaks ';'. Below is the corrected code. Please try:
let a,b,c
[a, b] = ['A', 'B'];
[b, c] = ['BB', 'C'];
console.log(`a=${a} b=${b} c=${c}`)
let a, b, c
[a, b] = ['A', 'B']***;***
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)
console: a=A b=BB c=C
NOTE: I'm not allowed to use any built-in functions
Given positive ints r and c indicating the number of rows and columns, create a 2D list that represents the "augmented identity matrix" with that dimension: It's the k x k identity matrix (where k = min(r,c)), and augmented rightwards or downwards as needed with zeroes in order to be of size r x c. Stated another way, it's an r x c matrix filled with zeroes that has ones along its main diagonal. I have to write this in both python and Haskell. I wrote the python solution but I'm kinda stuck on Haskell. The Haskell function has to be the following form:
augdentity :: Int -> Int -> [[Int]]
*Homework4> augdentity 3 3
[[1,0,0],[0,1,0],[0,0,1]]
*Homework4> augdentity 3 5
[[1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0]]
*Homework4> augdentity 5 3
[[1,0,0],[0,1,0],[0,0,1],[0,0,0],[0,0,0]]
*Homework4> augdentity 2 2
[[1,0],[0,1]]
def augdentity(r,c):
answer = []
for row in range(0, r):
newRow = [0] * c
for col in range(0, c):
if row == col:
newRow[col] = 1
answer.append(newRow)
return answer
So I got this for my haskell function. Put zeros in list when x != y but I don't know how to put 1 when x == y
augdentity :: Int -> Int -> [[Int]]
augdentity x y = [[0 | y <- [1 .. y], x /= y] | x <- [1 .. x]]
How about using if ... then ... else:
augdentity :: Int -> Int -> [[Int]]
augdentity r c = [[ if i == j then 1 else 0 | j <- [1..c] ] | i <- [1..r] ]
main = mapM_ (print . uncurry augdentity) [(3,3),(3,5),(5,3),(2,2)]
-- [[1,0,0],[0,1,0],[0,0,1]]
-- [[1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0]]
-- [[1,0,0],[0,1,0],[0,0,1],[0,0,0],[0,0,0]]
-- [[1,0],[0,1]]
Similarly, the python code could be simplified:
def augdentity(rows, cols):
return [[int(i == j) for j in range(cols)] for i in range(rows)]
for dim in [(3,3),(3,5),(5,3),(2,2)]:
print(augdentity(*dim))
# [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
# [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0]]
# [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0], [0, 0, 0]]
# [[1, 0], [0, 1]]
This question already has an answer here:
Haskell get all the numbers whose sum is X
(1 answer)
Closed last year.
I'm Trying to create a program that finds every paritions of a number.
For example the ways to decompose 4 are:
[1, 1, 1, 1]
[1, 1, 2]
[1, 3]
[2, 2]
[4]
I've done it in Python with:
n = 4
x = [0 for i in range(n+1)]
t = [0 for i in range(n+1)]
x[0] = 1
def partition(i):
for j in range(x[i-1], (n - t[i-1])//2 + 1):
x[i] = j
t[i] = t[i-1] + j
partition(i+1)
x[i] = n - t[i-1]
print(x[1:i+1])
partition(1)
But i need to write it in Haskell. Is there any way?
Here's a hint:
It will be valuable to reverse the order while thinking about this, so you are trying to generate:
[1, 1, 1, 1]
[2, 1, 1]
[2, 2]
[3, 1]
[4]
So, first choose every possible first element, here 1, 2, 3, or 4. Say we've chosen 1, then there are 3 remaining. We can recursively compute all the partitions of 3, and then prepend 1 to each of them.
(Oh, that's not quite right! Still a good place to start. But you will have e.g. [1,2,1] generated, so you will need to add a parameter, I think, saying "don't generate any numbers greater than m")
And we have to make sure to get the base case right. How many partitions are there of 0? There is one, the empty partition!
You can also translate it very literally using mutable vectors. The main difference is that you need to separate reads and writes very explicitly in Haskell, so it becomes a bit more messy.
This is what I came up with without understanding your algorithm:
import Data.Foldable ( for_ )
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as M
main :: IO ()
main = do
let n = 4
x <- M.replicate (n + 1) 0
t <- M.replicate (n + 1) 0
M.write x 0 1
let partition i = do
x' <- M.read x (i - 1)
t' <- M.read t (i - 1)
for_ [x' .. (n - t') `quot` 2] $ \j -> do
M.write x i j
t' <- M.read t (i - 1)
M.write t i (t' + j)
partition (i + 1)
t' <- M.read t (i - 1)
M.write x i (n - t')
x' <- V.freeze (M.slice 1 i x)
print (V.toList x')
partition 1
I am trying to do extended unpacking of tuple with * syntax. I'm trying to format string with f'' string syntax. None of those work in visual-studio-code python3.7.3 linuxmint64 system.
l = [1, 2, 3, 4, 5, 6]
a, *b = l
print(a, b)
Here is the error :
line 3
a, *b = l
^
SyntaxError: invalid syntax
Your Code:
l = [1, 2, 3, 4, 5, 6]
a, *b = l
print(a, b)
The above code won't as the correct syntax is b=[*l]. The * is used to unpack a list.
So if you want to have some values in both a and b so the code below...
l = [1, 2, 3, 4, 5, 6]
d = [3,2,1]
a , b = [*l] , [*d] # Here [*l] unpacks l in a list and assign it to a and
# and [*d] unpacks d in a list and assign it to b
print(a , b)
Hope this helps...
Is it possible to declare two lists in the same one-liner? Following code contains two one-liners so you have to loop over c twice:
c = [1,2,3,4]
a = [ d for d in c if (d % 2 == 0)]
b = [ d for d in c if (d % 2 != 0)]
Is this what you want ??
c = [1, 2, 3, 4]
a, b = [d for d in c if (d % 2 == 0)], [d for d in c if (d % 2 != 0)]
or how about
a, b = [], []
for i in c:
b.append(i) if i % 2 else a.append(i)