Find row number for specific change in python numpy - python

I have a file like this:
C
C
C
C
C
C
C
C
B
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
B
B
B
B
B
I like to print the row number where there is a change from C to B. Like here in row 9 and 27. I need to row number only. How to do that in numpy python.
Thank you

This is one possible solution, but it's not using Numpy
f = open('yourfile.txt', 'r')
x = 0
for i in f:
x = x + 1
if i == 'B':
print('row' + str(x))

If working in pure numpy (this is C-level), I advise you to use np.flatnonzero for comparison of neighbour items:
import numpy as np
x = np.loadtxt(r'your_file.txt', dtype='O')
marker_idx = np.flatnonzero((x[1:]=='B') & (x[:-1]=='C')) + 1 #default way
print(marker_idx + 1) #since you are counting from 1 for some reason
Output
[ 9 27]

Related

Alternative solution for printing pattern using python

I want to print pattern using python and i have done it but i want to
know other solutions possible for the same:-
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
......
....
A A
and here is my code:-
n=0
for i in range(71,64,-1):
for j in range(65,i+1):
a=chr(j)
print(a, end=" ")
if n>0:
for l in range(1,3+(n-1)*4):
print(end=" ")
if i<71:
j=j+1
for k in range(j-1,64,-1):
b=chr(k)
print(b, end=" ")
n=n+1
print()
Here's an alternative method using 3rd party library numpy. I use this library specifically because it allows vectorised assignment, which I use instead of an inner loop.
from string import ascii_uppercase
import numpy as np
n = 7
# extract first n letters from alphabet
letters = ascii_uppercase[:n]
res = np.array([list(letters + letters[-2::-1])] * (n-1))
# generate indices that are removed per line
idx = (range(n-i-1, n+i) for i in range(n-1))
# printing logic
print(' '.join(res[0]))
for i, j in enumerate(idx):
# vectorised assignment
res[i, j] = ' '
print(' '.join(res[i]))
Result:
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A

Python (Fibo series): trying to understand what is the difference between a, b = b, a + b OR a = b & a = a + b

I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly.
I am new to python programming. I have this simple code to generate Fibonacci series.
1: def fibo(n):
2: a = 0
3: b = 1
4: for x in range(n):
5: print (a, end=' ')
6: #a, b = b, a+b
7: a = b
8: b = a+b
9: print()
10: num = int(input("enter n value: "))
11: print(fibo(num))
If I execute the above code as-is the result I get is as follows
enter n value: 10
0 1 2 4 8 16 32 64 128 256
If uncomment #6 and comment lines #7 and #8 the result I get is the actual fibo series.
enter n value: 10
0 1 1 2 3 5 8 13 21 34
I would like to know what is the difference between
a, b = b, a + b
and
a = b
b = a + b
Programming IDE used: PyCharm Community 2017.3
a = b
b = a + b
is actually:
a = b
b = b + b
what you want is:
a = b
b = old_value_of_a + b
When you do
a, b = b, a + b
it really is doing:
tmp_a = b
tmp_b = a + b
a = tmp_a
b = tmp_b
which is what you want
In line 7, you've already assigned the value in b to a, so in line 8, new value for b is actually double the old b's value.
While in line 6, the values on the right side of = will be using the old values, that's why you could get Fibo series.
Assignment Statements assigns reference of source variable to target variable. Let walk through an example to understand more
>>> a = 5
>>> b = 6
>>> a = b
In this example b is source variable and a is the target variable. Now memory address for both of these variables are same. We can confirm this as well
>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x1002739e0')
Another test to confirm this is to use is operator
>>> a is b
>>> True
Now coming back to your example. First statement
>>> a, b = b, a + b
Assignes b to a and (a+b) to b. This happens as a single operation so both variables are different. We can apply above tests to confirm this
>>> a is b
>>> False
>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x2008739t0')
The second statement
>>> a = b
>>> b = a + b
Assignes b to a and then (a+b) to b. These are two different statements, so at first step a and b are already identical. Thus the second statement is equivalent to b = b + b.
Thought make it simple so anyone can understand it
if you use this kind of syntax
a = 10
b = 20
a = b
b = a+b
print (a)
print (b)
after initially assigning a = 10 it will be assigning a = 20 since python is dynamically typed language it will change the value of variable a from 10 to 20
so the result will be like
a=20
b=40
but if we use
a = 10
b = 20
a,b = b,a+b
print (a)
print (b)
this will be assigning the values in a single line so the values of a and b will be exactly used from what it is initialised above it and the result will be like
which is the correct solution
a=20
b=30
I think the # line is pythonic solution. But if you got confused,you can you use a variable which is temporary. you can assign the value temp before, then you can change the values

Fibonacci series in python giving odd results

I have started learning python and my first program on fibonacci started giving me some weird answer, I know I am missing conceptually something so need guide from some expert on this. My program looks like this
#! usr/bin/python
a,b = 0, 1
while (b < 50):
print(b)
a = b
b = a + b
output
1
2
4
8
16
32
But When i wrote like this I got correct result
#! usr/bin/python
a,b = 0, 1
while (b < 50):
print(b)
a,b = b, a + b
output:
1
1
2
3
5
8
13
21
34
Guide me pls
a,b = 0,1
a = b # a <- 1
b = a + b # b <- a + b (1 + 1 = 2)
That's two separate operations where the a in the final line has already been modified before use.
On the other hand:
a,b = b, a + b
is an atomic operation where everything on the right side of = is the original value.
Hence it's equivalent to:
a,b = 0,1
t = a # t <- 0
a = b # a <- 1
b = t + b # b <- t + b (0 + 1 = 1)

Convert a string with whitespaces to a dataframe with desired dimensions in Python

What's a smart way to convert a string with white spaces into some dataframe (some 'table') with desired dimensions (X columns and Y rows) in Python?
Say my string is string = 'A B C D E F G H I J K L' and I want to convert it into a 3 cols x 4 rows dataframe.
I guess there are useful pandas/numpy tool for that.
Use Numpy.reshape()
import numpy as np
import pandas as pd
string = 'A B C D E F G H I J K L'
list1 = [char for char in string.split(' ') if char != '']
df = pd.DataFrame(np.reshape(list1,[3,4]))
Outputs:
0 1 2 3
0 A B C D
1 E F G H
2 I J K L
Whoops... here it is with 3 col x 4 rows:
pd.DataFrame(np.reshape(list1,[4,3]))
0 1 2
0 A B C
1 D E F
2 G H I
3 J K L
Edit: put the imports on top.

Program to output letter pyramid

To print the output
A
A B
A B C
A B C D
A B C D E
I used the following code, but it does not work correctly.
strg = "A B C D E F"
i = 0
while i < len(strg):
print strg[0:i+1]
print "\n"
i = i + 1
For this code the obtained output is:
A
A
A B
A B
A B C
A B C
A B C D
A B C D
A B C D E
A B C D E
A B C D E F
Why does each line get printed twice?
Whitespace. You need to increment i by 2 instead of 1. Try:
strg = "A B C D E F"
i = 0
while i < len(strg):
print strg[0:i+2]
print "\n"
i = i+2
This will allow you to skip over the whitespace as "indices" of the string
A little more pythonic:
>>> strg = "ABCDEF"
>>> for index,_ in enumerate(strg):
print " ".join(strg[:index+1])
A
A B
A B C
A B C D
A B C D E
A B C D E F

Categories

Resources