while loop that is equivalent to for loop - python

I am trying to experiment how the while loop works.
docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc']
for i in range(0,len(docs)):
for j in range(i,len(docs[i])):
print(i, j)
My output for the above code is
0 0
0 1
0 2
0 3
0 4
0 5
1 1
1 2
1 3
1 4
1 5
2 2
I attempt to play with the while loop with
docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc']
i = 0
j = i
while i < len(docs):
while j < len(docs[i]):
print(i, j)
j += 1
i += 1
but the output is
0 0
0 1
0 2
0 3
0 4
0 5
How can I fix my while loop to match the for loop? Thanks!

docs = ['123867', '256789', '3aa', '4gg', '5yy', '6abc']
i = 0
while i < len(docs):
j = i # should be moved here
while j < len(docs[i]):
print(i, j)
j += 1
i += 1

Related

creating chessboard pattern with tables in python

I need to make a chessboard pattern filled with 0 and 1 but it it doesn't have to be square table
I need to get rows and columns from user
just an example:
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
I have the solution but I couldn't understand the last row of code (table[i][j] = int(not table[i][j-1]))
can we solve it using another method?
m = int(input("insert number of rows: "))
n = int(input("insert number of colomns: "))
table = list()
for i in range(0,m):
if i%2 == 0 :
table[i][0] = 1
else:
table[i][0] = 0
for j in range(1,n):
table[i][j] = int(not table[i][j-1])
print("print the table with chessboard pattern")
for i in range(0,m):
for j in range(0,n):
print(table[i][j],end='')
print()
You'll have a simpler time with a nested list comprehension that uses the x and y coordinates of the cell being generated and the modulo operator % to alternate between two values:
n_rows = n_cols = 5
table = [
[((x + y + 1) % 2) for x in range(n_cols)]
for y in range(n_rows)
]
for row in table:
print(*row)
prints out
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
The list comprehension can be written out as nested for loops, too.
table = []
for y in range(n_rows):
row = []
for x in range(n_cols):
row.append((x + y + 1) % 2)
table.append(row)
You will have an error on line 6 because you can't assign a value to an index that doesn't exist..
You can do this instead:
m = int(input("insert number of rows: "))
n = int(input("insert number of colomns: "))
table = []
for i in range(m):
if i%2==0:
table.append([0+j%2 for j in range(n)])
else:
table.append([0+j%2 for j in range(1, n+1)])
You could also print it like this:
print("".join([str(row).replace('[', '').replace(']', '\n').replace(', ', ' ') for row in table]))

How to reflect a number output in Python?

I have a programm which draws a picture from numbers in certain way
n = int(input(" Введіть ваше число "))
m = n * 2 - 1
pp = " "
i = 0
while m != 0:
l = []
while m > n:
while i < n:
i += 1
j = n - i
k = i
while j != 0:
l.append(pp)
j -= 1
while k != 0:
l.append(str(k))
k -= 1
m -= 1
a = " "
print(a.join(l))
l = []
i = 0
OUTPUT:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
But now I get a task to draw this picture
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Is there any hint how to reflect it without overwriting the whole code?
For the output you are expecting, a very simple way to do it is with this code :
n = 5
for i in range(n):
print(' '.join([str(x+1) for x in range(i+1)]))
Output :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
You can try this. Its simple.
for i in range(1,n+1):
for j in range(1, i+1):
print(j, end="")
print()

Is there any way to sum (1 to n) and compare it to the sum (n+1 to end of list)?

I am trying to do something like comparing sum1 and sum2 as sum1 > sum2 then stop. I am calculating sum1 as iterating from 0 index to n and sum2 by iterating n+1 to the last index but I cannot do that I am getting out of the index error. I tried to solve it by putting some condition but it runs infinite loop. I will be really appreciated if someone can help. Following is the code I wrote. Thank you!! I am using python 3.7
intList = [0 2 1 0 0 0 1 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 2 1 1 2 2 2 1 2 3 0 0 0 1 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 0 1 1 0 1 0 1 2 2 1 0 1 1 1 1 1 1 0 0 1 0 1 0]
sum1 = 0
sum2 = 0
for i in range(len(intList)):
sum1 = sum1 + intList[i]
print("Sum1: " , sum1)
for n in range(len(intList)):
sum2 = sum2 + intList[n+1]
print("Sum2: " , sum2)
# if n+1 < len(intList):
# continue
# else:
# break
You can leverage python's inbuilt functions
for i in range(len(intList)):
sum1 = sum(intList[:i+1])
sum2 = sum(intList[i+1:])
if sum1>sum2:
print(i)
break
efficient solution: as moving forward sum1 will increase and sum2 will decrease so you can add the current element of the array in sum1 and subtract from sum2
sum1 = 0
sum2 = sum(intList)
for i in range(len(intList)):
sum1 += intList[i]
sum2 -= intList[i]
if sum1>sum2:
print(i)
break
I Guess your logic is little off. In second loop you are always adding list from index 0 to index [len(intlist)]. Which contradicts your requirement. Instead you want to have value of sum2 as from index intlist[n] to intList[len(intList)]. As for as out of index you are getting because of ’intList[n+1]‘. Below logic should work:
sum1 = 0
for i in range(len(intList)):
sum1 = sum1 + intList[i]
print("Sum1: " , sum1)
sum2= 0
for n in range(i+1,len(intList)):
sum2 = sum2 + intList[n]
print("Sum2: " , sum2)
if sum2 < sum1:
break

how to change string matrix to a integer matrix

I have a voting dataset like that:
republican,n,y,n,y,y,y,n,n,n,y,?,y,y,y,n,y
republican,n,y,n,y,y,y,n,n,n,n,n,y,y,y,n,?
democrat,?,y,y,?,y,y,n,n,n,n,y,n,y,y,n,n
democrat,n,y,y,n,?,y,n,n,n,n,y,n,y,n,n,y
but they are both string so I want to change them to integer matrix and make statistic
hou_dat = pd.read_csv("house.data", header=None)
for i in range (0, hou_dat.shape[0]):
for j in range (0, hou_dat.shape[1]):
if hou_dat[i, j] == "republican":
hou_dat[i, j] = 2
if hou_dat[i, j] == "democrat":
hou_dat[i, j] = 3
if hou_dat[i, j] == "y":
hou_dat[i, j] = 1
if hou_dat[i, j] == "n":
hou_dat[i, j] = 0
if hou_dat[i, j] == "?":
hou_dat[i, j] = -1
hou_sta = hou_dat.apply(pd.value_counts)
print(hou_sta)
however, it shows error, how to solve it?:
Exception has occurred: KeyError
(0, 0)
IIUC, you need map and stack
map_dict = {'republican' : 2,
'democrat' : 3,
'y' : 1,
'n' : 0,
'?' : -1}
df1 = df.stack().map(map_dict).unstack()
print(df1)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
0 2 0 1 0 1 1 1 0 0 0 1 -1 1 1 1 0 1
1 2 0 1 0 1 1 1 0 0 0 0 0 1 1 1 0 -1
2 3 -1 1 1 -1 1 1 0 0 0 0 1 0 1 1 0 0
3 3 0 1 1 0 -1 1 0 0 0 0 1 0 1 0 0 1
If you're dealing with data from csv, it is better to use pandas' methods.
In this case, you have replace method to do exactly what you asked for.
hou_dat.replace(to_replace={'republican':2, 'democrat':3, 'y':1, 'n':0, '?':-1}, inplace=True)
You can read more about it in this documentation

Conway sequence in python

I have an assignement for which I have to write an algorithm who generates the l lines of the Conway sequence of a chosen r integer.
Example for l=8 and r=1 :
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 2 2 1 1
1 3 1 1 2 2 2 1
1 1 1 3 2 1 3 2 1 1
I have tried to write an algorithm in Python3, but I can't manage to get the correct output. I'd appreciate if you could help me to figure out what's wrong... Anyway, here's what I've wrote so far :
r = int(input())
l = int(input())
cur=str(r).strip()
print(r)
for j in range(l-1):
r=cur
cur=""
i=0
while i<len(r) :
c=1 #counts the consecutive same "numbers"
while ((i+c*2)<len(r)) and (r[i]==r[i+c*2]):
c+=1
cur+=str(c)+" "+r[i]+" "
i+=c+1
cur=cur.strip()
print(cur)
And that's the output I'm getting for l=8 and r=1 :
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 1 1 2 2 1
1 3 3 1 1 1 2 2 1
1 1 2 3 6 2 2 1
I also feel that my code is pretty ugly so feel free to give your remarks
Really, groupby is built for this:
from itertools import groupby
def lookandsay(i):
digits = str(i) #convert to string
newdigits = []
for k, g in groupby(digits):
newdigits += [sum(1 for _ in g), k]
return int("".join(map(str, newdigits)))
def conway(i):
yield i
while True:
i = lookandsay(i)
yield i
cw01 = conway(1)
for _ in range(8):
print(" ".join(str(next(cw01))))
Look at this logic,
I got below code from: HERE
r = [input()]
l = int(input())
# Write an answer using print
# To debug: print("Debug messages...", file=sys.stderr, flush=True)
for i in range(l - 1):
temp = list()
lastChar = r[0]
counter = 0
for char in r:
if lastChar == char:
counter += 1
else:
temp.extend([str(counter), lastChar])
lastChar = char
counter = 1
temp.extend([str(counter), lastChar])
r = temp
print(r)
print(" ".join(r))

Categories