I have a list of integers that looks like this when performing the print command:
0
1
0
1
1
I want to create a list out of it: [0, 1, 0, 1, 1]
How to do it?
I cannot find such information anywhere :(
s = """0
1
0
1
1"""
integers = map(int, s.splitlines())
idea taken from https://stackoverflow.com/a/27171335/1644901
Related
I am trying to draw the flowchart for this question and stuck.
Given a list A of n numbers, count the number of times 0 occurs in the list.It might be an easy question but I am a beginner and don't have much idea about most questions. Please help me draw that!
You need to iterate through the list A and for each value, check if the value is equal to zero. If it is, add 1 to a running total.
In pseudo code:
total = 0
listA = [1, 5, 0, 2, 0, ...]
for i = 0 to len(listA):
if listA[i] == 0:
total = total + 1
next i
So for my application I would need to create a tri diagonal matrix. This is easy to do with any language, you loop through all rows and columns, then set the main diagonal values, the sub diagonal values and the super diagonal values. Usually, this is performed on a 2d array.
For my application, I need to create a 1d array of "tridiagonal". Otherway to say this is: take the 2d tridiagonal matrix then turn it into 1d. I can just start with 2d then write some functions that convert 2d array to 1d array. This, I can do. I would like to know if we ca go directly to a 1D "tridiagonal"? For example, say the 2D array is 10*10, then my 1D array would be 100 elements long, then I would need to figure out which index is the main, super and sub diagonal.
Is it possible to do this? Please let me know and thank you
The elements on the main diagonal are at indexes (i, i) and there are n of them; the supra- and infra- diagonals at (i, i-1) and (i, i+1) and there are n-1 of them (i starts at 2 and ends at n-1 respectively).
An option is to use three vectors and store the elements at the respective indexes i in those three vectors.
You can also pack all values in a single vector of length 3n (or 3n-2 if you want to spare space). Add n or 2n to the index, depending on the diagonal you want to address. For an element (i, j), the index of the diagonal is given by j-i+2.
You can just look at your 1D array using a 2D array pointer. Fortran:
integer, target :: A(100)
integer, pointer :: B(:,:)
B(1:10,1:10) => A
B = 0
do i = 1, 10
B(i,i) = 1
end do
print '(*(1x,g0))', A
end
> gfortran diag1d.f90
> ./a.out
1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1
In C++ the casting is easy as well.
Please consider also:
#YvesDaoust's answer, because proposes a better storage strategy: instead of storing all the elements of the tridiagonal matrix, store just the non-zero. You could write a derived-type to encapsulate behavior, if it worths.
#VladmirF's answer, because a pointer association maybe a better approach (depending on your use case), than copying over all the array through reshape, if all you want is a temporarily indexing change for convenience while working on data.
Said that, let's go to my answer.
Populating a tridiagonal matrix is not a different problem than constructing any matrix. I don't think it really matters here. Just bear in mind that Fortran stores arrays in Column Major order, 1 based index.
Changing the shape of your data is easy and obvious, if storage is contiuous. You can make a pointer association or transferring it to a new variable with reshape.
Extracting the main, super and sub diagonal is also a trivial problem, and can be done with simple manipulation of the array index triplet. Look:
program tridiagonal
implicit none
integer, parameter :: n = 4
integer :: A(n, n), B(n**2), main(n), sub(n-1), sup(n-1)
A(1,:) = [1, 4, 0, 0]
A(2,:) = [3, 4, 1, 0]
A(3,:) = [0, 2, 3, 4]
A(4,:) = [0, 0, 1, 3]
! Remember, colum major
B = reshape(A, shape(B)) ! 1, 3, 0, 0, 4, 4, 2, 0, 0, 1, 3, 1, 0, 0, 4, 3
main = B( 1:n**2:n+1) ! 1, 4, 3, 3
sub = B( 2:n**2:n+1) ! 3, 2, 1
sup = B(n+1:n**2:n+1) ! 4, 1, 4
end
I took part in a coding contest wherein I encountered the following question:
On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.)
While solving the question, I solved it like a level-order traversal of a tree, trying to form the new string at each level. Unfortunately, it timed-out. I then tried to think along the terms of caching the results, etc. with no luck.
One of the highly upvoted solutions is like this:
class Solution {
public:
int kthGrammar(int N, int K) {
if (N == 1) return 0;
if (K % 2 == 0) return (kthGrammar(N - 1, K / 2) == 0) ? 1 : 0;
else return (kthGrammar(N - 1, (K + 1) / 2) == 0) ? 0 : 1;
}
};
My question is simple - what is the intuition behind working with the value of K (especially, the parities of K)? (I hope to be able to identify such questions when I encounter them in future).
Thanks.
Look at the sequence recursively. In generating a new row, the first half is identical to the process you used to get the previous row, so that part of the expansion is already done. The second half is merely the same sequence inverted (0 for 1, 1 for 0). This is one classic way to generate a parity map: flip all the bits and append, representing adding a 1 to the start of each binary number. Thinking of expanding the sequence 0-3 to 0-7, we start with
00 => 0
01 => 1
10 => 1
11 => 0
We now replicate the 2-digit sequence twice: first with a leading 0, which preserves the original parity; second with a leading 1, which inverts the parity.
000 => 0
001 => 1
010 => 1
011 => 0
100 => 1
101 => 0
110 => 0
111 => 1
Is that an intuition that works for you?
Just for fun, as a different way to solve this, consider that the nth row (0-indexed) has 2^n elements in it, and a determination as to the value of the kth (0-indexed) element can be made soley according to the parity of how many bits are set in k.
The check for parity in the code you posted is just to make the division by two correct, there's no advanced math or mystery hiding here :) Since the pattern is akin to a tree, where the pattern size multiplies by two for each added row, correctly dividing points to the element's parent. The indexes in this question are said to be "1-indexed;" if the index is 2, dividing by two yields the parent index (1) in the row before; and if the index is 1, dividing (1+1) by two yields that same parent index. I'll leave it to the reader to generalize that to ks parity. After finding the parent, the code follows the rule stated in the question: if the parent is 0, the left-child must be 0 and right-child 1, and vice versa.
0
0 1
0 1 1 0
0 1 1 0 1 0 0 1
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0
a a b a b b a
0 01 0110 01101001 0110100110010110
a b b a b a a b
0110100110010110 1001011001101001
I have a list that is always binary. I want to XOR every two consequentive elements to satisfy a condition in a research paper. For instance: Given list=[1,0,1,1], XORing each consequtive pairs should be something like this: 1 XOR 0 = 1, 0 XOR 1 = 1, 1 XOR 1 = 0. To do so, is it correct to XOR two lists where the second list is the shifted verison of the original Something like: numpy.bitwise_xor([1,0,1,1],[0,1,0,1])?
You can load the input list as an array (called a) and use numpy.roll to shift the array so that you now have another array (called b) which has stores the shifted array. Now bitwise_xor can be used on a,b.
import numpy as np
a = np.array([1,0,1,1])
b= np.roll(a,len(a)-1)
c = np.bitwise_xor(a,b)
print(' A :',a,'\n','B :',b,'\n','C :',c)
Output:
A : [1 0 1 1]
B : [0 1 1 1]
C : [1 1 0 0]
If you're using python 2.7, make sure the change the print statement!
You can also use slices
>>> import numpy as np
>>> a = [1, 0, 1, 1]
>>> print np.bitwise_xor(a[1:], a[:-1])
array([1, 1, 0], dtype=int32)
I finally got to a message that I expected could solve my problem. I have two columns in a dataFrame (height, upper) with values either 1 or 0. The combination of this is 4 elements and with them I am trying to create a third column containing the 4 combinations, but I cannot figure out what is going wrong, My code is as follows:
def quad(clasif):
if (raw['upper']==0 and raw['height']==0):
return 1
if (raw['upper']==1 and raw['height']==0):
return 2
if (raw['upper']==0 and raw['height']==1):
return 3
if (raw['upper']==1 and raw['height']==1):
return 4
raw['cuatro']=raw.apply(lambda clasif: quad(clasif), axis=1)
I am getting the following error:
'The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index 0'
if someone could help?
Assuming that upper and height can only be 0 or 1, you can rewrite this as a simple addition:
raw['cuatro'] = 1 + raw['upper'] + 2 * raw['height']
The reason you see this error is because raw['upper'] == 0 is a Boolean series, which you can't use and... See the "gotcha" section of the docs.
I think you're missing the fundamentals of apply, when passed the Series clasif, your function should do something with clasif (at the moment, the function body makes no mention of it).
You have to pass the function to apply.
import pandas as pd
def quad(clasif):
if (clasif['upper']==0 and clasif['height']==0):
return 1
if (clasif['upper']==1 and clasif['height']==0):
return 2
if (clasif['upper']==0 and clasif['height']==1):
return 3
if (clasif['upper']==1 and clasif['height']==1):
return 4
raw = pd.DataFrame({'upper': [0, 0, 1, 1], 'height': [0, 1, 0, 1]})
raw['cuatro']=raw.apply(quad, axis=1)
print raw
height upper cuatro
0 0 0 1
1 1 0 3
2 0 1 2
3 1 1 4
Andy Hayden's answer is better suited for your case.