Conditional while loop in python [duplicate] - python

This question already has answers here:
Conditional while loop to calculate cumulative sum?
(8 answers)
Closed 2 years ago.
I have the following conditional and I would like the first column of the print to go from 1 to 100. It now goes from 1 to 20.
I have a list of letters and a defined range of 20.
lista = ['a','b','c','d','e']
intervalo = 20
for i, r in enumerate(lista):
s = 1
f = 1
while f <= intervalo*s:
print(f, r)
f+=1
Current output:
1 a
2 a
3 a
4 a
....
1 b
2 b
3 b
4 b
Desired output:
1 a
2 a
3 a
4 a
...
15 a
...
20 a
21 b
22 b
23 b
24 b
....

What about using doubled for?
lista = ['a','b','c','d','e']
interval = 20
for i, item in enumerate(lista):
for j in range(interval):
print(i*interval + j+1, item)

You should increment both f and s, but at the right times:
lista = ['a','b','c','d','e']
interval = 20
s = 1
f = 1
for i, r in enumerate(lista):
while f <= interval*s:
print(f, r)
f+=1
s += 1

Related

sum of Fibbonaci Sequences?

Trying to add the sum of Fibonacci, using definite loops. It's meant to calculate the summation of Fibonacci number with each number too. Below is the sample for the Fibonacci sequence and its summation, how do i add the sum of the fibonacci eg 1,1,2,3,5,8
Fibonacci Summation
0 0
1 1
1 2
2 4
3 7
5 12
8 20
n = int(input("enter"))
def fibonacciSeries():
a=0
b=1
for i in range (n-2):
x = a+b
a=b
b=x
int(x)
x[i]= x+x[i-1]
#should add the previous sequences
print(x)
fibonacciSeries()
You don't need to keep track of the whole sequence. Plus your Fibonacci implementation doesn't start with 1, 1 but rather 1, 2 so I fixed that.
def fibonacciSeries(n):
a=0
b=1
x=1
series_sum = 0
for i in range (n-2):
series_sum += x
print(f'{x} {series_sum}')
x = a+b
a=b
b=x
n = 10
fibonacciSeries(n)
Output:
1 1
1 2
2 4
3 7
5 12
8 20
13 33
21 54
def fibonacciSeries(n):
sum = 0
a = 0
b = 1
x = 1
sum = 0
for i in range(0,n - 2):
sum += x
print(x,sum)
x = a + b
a = b
b = x
n = int(input("enter : ")) # n = 8
fibonacciSeries(n)
Output:
enter : 8
1 1
1 2
2 4
3 7
5 12
8 20

Python: Change row and colum in a matrix

matrix = []
for index, value in enumerate(['A','C','G','T']):
matrix.append([])
matrix[index].append(value + ':')
for i in range(len(lines[0])):
total = 0
for sequence in lines:
if sequence[i] == value:
total += 1
matrix[index].append(total)
unity = ''
for i in range(len(lines[0])):
column = []
for row in matrix:
column.append(row[1:][i])
maximum = column.index(max(column))
unity += ['A', 'C', 'G', 'T'][maximum]
print("Unity: " + unity)
for row in matrix:
print(' '.join(map(str, row)))
OUTPUT:
Unity: GGCTACGC
A: 1 2 0 2 3 2 0 0
C: 0 1 4 2 1 3 2 4
G: 3 3 2 0 1 2 4 1
T: 3 1 1 3 2 0 1 2
With this code I get this matrix but I want to form the matrix like this:
A C G T
G: 1 0 3 3
G: 2 1 3 1
C: 0 4 2 1
T: 2 2 0 3
A: 3 1 1 2
C: 2 3 2 0
G: 0 2 4 1
C: 0 4 1 2
But I don't know how. I hope someone can help me. Thanks already for the answers.
The sequences are:
AGCTACGT
TAGCTAGC
TAGCTACG
GCTAGCGC
TGCTAGCC
GGCTACGT
GTCACGTC
You're needing to do a transpose of your matrix. I've added comments in the code below to explain what has been changed to make the table.
matrix = []
for index, value in enumerate(['A','C','G','T']):
matrix.append([])
# Don't put colons in column headers
matrix[index].append(value)
for i in range(len(lines[0])):
total = 0
for sequence in lines:
if sequence[i] == value:
total += 1
matrix[index].append(total)
unity = ''
for i in range(len(lines[0])):
column = []
for row in matrix:
column.append(row[1:][i])
maximum = column.index(max(column))
unity += ['A', 'C', 'G', 'T'][maximum]
# Tranpose matrix
matrix = list(map(list, zip(*matrix)))
# Print header with tabs to make it look pretty
print( '\t'+'\t'.join(matrix[0]))
# Print rows in matrix
for row,unit in zip(matrix[1:],unity):
print(unit + ':\t'+'\t'.join(map(str, row)))
The following will be printed:
A C G T
G: 1 0 3 3
G: 2 1 3 1
C: 0 4 2 1
T: 2 2 0 3
A: 3 1 1 2
C: 2 3 2 0
G: 0 2 4 1
C: 0 4 1 2
I think that the best way is to convert your matrix to pandas dataframe and to then use transpose function.
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transpose.html

keyerror after removing nans in pandas

I am reading a file with pd.read_csv and removing all the values that are -1. Here's the code
import pandas as pd
import numpy as np
columns = ['A', 'B', 'C', 'D']
catalog = pd.read_csv('data.txt', sep='\s+', names=columns, skiprows=1)
a = cataog['A']
b = cataog['B']
c = cataog['C']
d = cataog['D']
print len(b) # answer is 700
# remove rows that are -1 in column b
idx = np.where(b != -1)[0]
a = a[idx]
b = b[idx]
c = c[idx]
d = d[idx]
print len(b) # answer is 612
So I am assuming that I have successfully managed to remove all the rows where the value in column b is -1.
In order to test this, I am doing the following naive way:
for i in range(len(b)):
print i, a[i], b[i]
It prints out the values until it reaches a row which was supposedly filtered out. But now it gives a KeyError.
You can filtering by boolean indexing:
catalog = catalog[catalog['B'] != -1]
a = cataog['A']
b = cataog['B']
c = cataog['C']
d = cataog['D']
It is expected you get KeyError, because index values not match, because filtering.
One possible solution is convert Series to lists:
for i in range(len(b)):
print i, list(a)[i], list(b)[i]
Sample:
catalog = pd.DataFrame({'A':list('abcdef'),
'B':[-1,5,4,5,-1,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0]})
print (catalog)
A B C D
0 a -1 7 1
1 b 5 8 3
2 c 4 9 5
3 d 5 4 7
4 e -1 2 1
#filtered DataFrame have no index 0, 4
catalog = catalog[catalog['B'] != -1]
print (catalog)
A B C D
1 b 5 8 3
2 c 4 9 5
3 d 5 4 7
5 f 4 3 0
a = catalog['A']
b = catalog['B']
c = catalog['C']
d = catalog['D']
print (b)
1 5
2 4
3 5
5 4
Name: B, dtype: int64
#a[i] in first loop want match index value 0 (a[0]) what does not exist, so KeyError,
#same problem for b[0]
for i in range(len(b)):
print (i, a[i], b[i])
KeyError: 0
#convert Series to list, so list(a)[0] return first value of list - there is no Series index
for i in range(len(b)):
print (i, list(a)[i], list(b)[i])
0 b 5
1 c 4
2 d 5
3 f 4
Another solution should be create default index 0,1,... by reset_index with drop=True:
catalog = catalog[catalog['B'] != -1].reset_index(drop=True)
print (catalog)
A B C D
0 b 5 8 3
1 c 4 9 5
2 d 5 4 7
3 f 4 3 0
a = catalog['A']
b = catalog['B']
c = catalog['C']
d = catalog['D']
#default index values match a[0] and a[b]
for i in range(len(b)):
print (i, a[i], b[i])
0 b 5
1 c 4
2 d 5
3 f 4
If you filter out indices, then
for i in range(len(b)):
print i, a[i], b[i]
will attempt to access erased indices. Instead, you can use the following:
for i, ae, be in zip(a.index, a.values, b.values):
print(i, ae, be)

How to sort a dictionary alphabetically?

def wordCount(inPath):
inFile = open(inPath, 'r')
lineList = inFile.readlines()
counter = {}
for line in range(len(lineList)):
currentLine = lineList[line].rstrip("\n")
for letter in range(len(currentLine)):
if currentLine[letter] in counter:
counter[currentLine[letter]] += 1
else:
counter[currentLine[letter]] = 1
sorted(counter.keys(), key=lambda counter: counter[0])
for letter in counter:
print('{:3}{}'.format(letter, counter[letter]))
inPath = "file.txt"
wordCount(inPath)
This is the output:
a 1
k 1
u 1
l 2
12
h 5
T 1
r 4
c 2
d 1
s 5
i 6
o 3
f 2
H 1
A 1
e 10
n 5
x 1
t 5
This is the output I want:
12
A 1
H 1
T 1
a 1
c 2
d 1
e 10
f 2
h 5
i 6
k 1
l 2
n 5
o 3
r 4
s 5
t 5
u 1
x 1
How do I sort the "counter" alphabetically?
I've tried simply sorting by keys and values but it doesn't return it alphabetically starting with capitals first
Thank you for your help!
sorted(counter.keys(), key=lambda counter: counter[0])
alone does nothing: it returns a result which isn't used at all (unless you recall it using _ but that's rather a command-line practice)
As opposed to what you can do with a list with .sort() method, you cannot sort dictionary keys "in-place". But what you can do is iterating on the sorted version of the keys:
for letter in sorted(counter.keys()):
, key=lambda counter: counter[0] is useless here: you only have letters in your keys.
Aside: your whole code could be simplified a great deal using collections.Counter to count the letters.
import collections
c = collections.Counter("This is a Sentence")
for k,v in sorted(c.items()):
print("{} {}".format(k,v))
result (including space char):
3
S 1
T 1
a 1
c 1
e 3
h 1
i 2
n 2
s 2
t 1

Recursive numeric triangle in python

I'm trying to create a triangle like the following:
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
Without using while, for in, lists, etc. Just "if-else" cases and recursive functions. I've just learned how to do an asterisk triangle.
def triangle(i, t=0):
if i == 0:
return ' '
else:
print '*' * i
return triangle( i - 1, t + 1 )
triangle(6)
It has the same idea I want to apply to my exercise, but I really don't know how to do with the code for changing term by term and print them all to the right like this one.
Here is my solution. Note that there is neither range nor join, which implies for or list
In [1]: def tri(size, row = 0, col = 0):
...: if row < size:
...: num = row + col + 1
...: if num == size + 1:
...: print '\n',
...: tri(size, row + 1, 0)
...: if num <= size:
...: print num, '',
...: tri(size, row, col + 1)
...:
In [2]: tri(6)
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
If range is acceptable, then here is a short one:
def tri2(size):
row = map(str, range(1, size + 1))
print '\n'.join(map(lambda n: ' '.join(row[n:]), range(size)))
You can use range() or xrange() to get the list of numbers, and decrease the range with each recursion:
def triangle(i, t):
if i == t:
return i
else:
print " ".join([str(x) for x in range(i,t+1)])
return triangle( i + 1, t )
output:
>>> triangle(1,6)
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
>>> triangle(1,8)
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8
3 4 5 6 7 8
4 5 6 7 8
5 6 7 8
6 7 8
7 8
8
By calling the function recursively You have realized a kind of loop.
Now you can replicate the same idea:
def OneLess(i,j):
print i,
if i < j:
OneLess(i+1,j)
else:
print ""
def triangle(i, t=1):
OneLess(t,i)#print '*' * i
if i == t:
return ' '
return triangle( i , t + 1 )
triangle(6)
I'd suggest something like this:
def triangle(i, t = 1):
if i > 0:
print ' '.join([str(n+t) for n in range(i)])
triangle( i - 1, t + 1 )
The range gives you a list of the numbers needed at each level, and the t offset is increased by one so you're starting from a higher value each level you go down.
Update
I've just noticed your requirement for no for in and lists, which probably makes the above example wrong. So here is another suggestion using only recursion:
def triangle(size, col = 1, row = 1):
if col < size:
print col,
triangle(size, col+1, row)
else:
print col
if row < size:
triangle(size, row+1, row+1)

Categories

Resources