Write output of for loop in python - python

I am trying to write each iterated output of for loop for further operations.
Here is my code
#!/usr/bin/python
import io
from operator import itemgetter
with open('test.in') as f:
content = f.readlines()
content = [int(x) for x in content]
content = tuple(content)
nClus = input("Number of Clusters: ")
nEig = input("Number of eigen values: ")
j = 0
k = nClus + 1
content1 = ""
for i in range(1,k):
print content[j*(nEig+1):i*(nEig+1)]
j = j + 1
The file test.in looks like this (which is an example, actual test.in contains huge amount of data)
40
1
4
3
5
7
29
6
9
4
7
3
50
1
2
3
4
5
57
9
8
7
6
5
The values nClus = 4, nEig = 5.
Any suggestions on how to proceed?

Why not just save them to an array (mydata below)? I don't see where j stops (other_dimension, you can probably just delete it if you only have 1 dimension of results, I don't know your array size), but you can follow this format to get a numpy array to save data to:
import numpy as np
... [your code]
mydata = np.zeros([k,other_dimension]) // other_dimension only if you are saving a rectangular matrix of results instead of a vector
for i in range(1,k):
mydata[row, column] = content[j*(nEig+1):i*(nEig+1)] // put your iterators here for row, column if applicable (rectangular matrix), otherwise mydata[iterator]
print mydata[k, other_dimension] // other_dimension only if you are saving a rectangular matrix of results instead of a vector
j = j + 1

Related

Writing lists containing x,y,z coordinates into a file as 3 columns with a leading atom name

I am fairly new to python. I have been trying to write nested lists which contain several lists which are in the form of x,y,z coordinates to a file one row at a time.
Ex: lists I have are like this
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [[10,11,12],[13,14,15],[16,17,18]]
what I want to write them is like this:
Say I have a file called ring1.xyz.
If you open it, it should be like.
H 1 2 3
H 4 5 6
H 10 11 12
H 13 14 15
Only the first two lists should be written to the file.
I currently tried this code block, but it is not working.
any lead\solution is appreciated
for s in range(3):
with open("ring_%s.xyz" %s, "w+") as f:
for k in range(2):
for j in x[k]:
f.write('H\n')
f.write(' ')
f.write('%s' % j)
You can try this:
def open_file(l,ind):
with open("ring"+ind+".txt","a+") as f:
for i in l[:2]:
f.write("H "+" ".join(i))
f.write("\n")
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [[10,11,12],[13,14,15],[16,17,18]]
open_file(x,1)
open_file(y,2)
Try this code and tell me if it helped:-
for s in range(3):
with open("ring"+s+".xyz") as f:
for i in range(2):
f.write("H ")
for j in x[i]:
f.write(str(j))
f.write(" ")
f.write("\n")

How do I print separate multi-line ascii symbols side by side in output window

Disclaimer: I'm a relatively new python user and programmer in general.
I am building a class for a deck of cards, and for the __str__ method I want to return the ascii symbols for cards currently in the deck as thirteen rows of four columns. Later, I will need similar logic when displaying players' hands when I actually use this class for a game. I'm hoping to find a way to do this where the number of columns is variable, and the number of rows is dependent upon the number of columns and the length of the list (or put plainly, just stops when out of cards). This way it will work for my __str__ return with 4 columns, and with a player's hand at a variable number of columns.
Since I'm only wanting to understand the logic to do this, I've simplified the issue down to the code below. I've done quite a bit of research, but I haven't found an example of this that I can understand or that doesn't use imported libraries. I've learned to use a comma after a print statement to prevent forcing a new line, but even with that tool I cannot find a way to make this work using for and while loops. I will also paste some code from my final use case. It is only an example of many that haven't worked, and it's probably hideous, but it's where I'm at.
Simplified use case:
# Each string in each list below would actually be one line of ascii art for
# the whole card, an example would be '|{v} {s} |'
deck = [['1','2','3','4'],
['5','6','7','8'],
['9','10','11','12'],
['a','b','c','d'],
['e','f','g','h'],
['i','j','k','l']]
# expected output in 3 columns:
#
# 1 5 9
# 2 6 10
# 3 7 11
# 4 8 12
#
# a e i
# b f j
# c g k
# d h l
#
# expected output in 4 columns:
#
# 1 5 9 a
# 2 6 10 b
# 3 7 11 c
# 4 8 12 d
#
# e i
# f j
# g k
# h l
End use case:
def __str__(self):
# WORKS empty list to hold ascii strings
built_deck = []
# WORKS fill the list with ascii strings [card1,card2,card3,card4...]
for card in self.deck:
built_deck.append(self.build_card(str(card[0]),str(card[1:])))
# WORKS transform the list to [allCardsRow1,allCardsRow2,allCardsRow3,allCardsRow4...]
built_deck = list(zip(*built_deck))
# mark first column as position
position = 1
# initialize position to beginning of deck
card = 0
# Try to print the table of cards ***FAILURE***
for item in built_deck:
while position <= 4:
print(f'{item[card]}\t',)
card += 1
continue
position = 1
print(f'{item[card]}')
card += 1
#return built_deck
The trick is here to realize that what you are doing it taking successive transposes of the matrix of your cards and printing them where the size of the matrix you preform the operation on is the number of items you want to be displayed. We can get a transpose using zip in python.
def display(deck, number_of_columns):
col = 0
while col < len(deck):
temp = deck[col:col+number_of_columns]
temp = zip(*temp)
for x in temp:
for y in x:
print(y, end=" ")
print()
col += number_of_columns
display(deck, 3)
print()
display(deck, 4)
Output
1 5 9
2 6 10
3 7 11
4 8 12
a e i
b f j
c g k
d h l
1 5 9 a
2 6 10 b
3 7 11 c
4 8 12 d
e i
f j
g k
h l

4x4 Matrix in Python

Im trying to code a 4x4 matrix in python with random integers 1-4.
Thats easy enough my problem is i want for each row and each column only one time uses of each digit 1-4
example
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
my code does it like 33% of the time in my loop there happens somthing like this
2 1 4 3
3 4 2 1
1 3 X <-------- because of this the programm cant contiune and I end up in an infinity loop could someone helb how can i get out?
my code below
""" Programm for playing the game skyline """
from random import randrange
row1 = []
row2 = []
row3 = []
row4 = []
allrows = [row1, row2, row3, row4]
column1 = []
column2 = []
column3 = []
column4 = []
allcolumns = [column1, column2, column3, column4]
def board():
for i in range(4):
j = 0
while len(allrows[i]) != 4:
x = randrange(1,5)
print(i, j)
if x not in allrows[i] and x not in allcolumns[j]:
allrows[i].append(x)
allcolumns[j].append(x)
j += 1
else:
continue
board()
You seem to be looking for permutations, and here is how to get them:
from itertools import permutations
a = list(permutations([1,2,3,4]))
Now to get random 4 lists:
import random
from itertools import permutations
a = list(permutations([1,2,3,4]))
for _ in range(4):
print a[random.randint(0,len(a)-1)]
EDIT is this the one you were looking for:
import random
import numpy as np
from itertools import permutations
a = list(permutations([1,2,3,4]))
i = 0
result = [a[random.randint(0,len(a)-1)]]
a.remove(result[0])
print result
while i < 3:
b = a[random.randint(0,len(a)-1)]
if not any([any(np.equal(b,x)) for x in result]):
result.append(b)
i +=1
a.remove(b)
print result
Basically, what you do is put the numbers you want to select from in a list. Randomly pick an index, use and remove it.
Next time through, you pick one of the remaining ones.
I have tried this using for, if and elif; for ranges more than 4 it is working.
x=int(input("enter your range"))
for i in range(x+1):
if i+1<x+1:
print(i+1,end='')
if(i+2<x+1):
print(i+2,end='')
if(i+3<x+1):
print(i+3,end='')
if(i+4<x+1):
print(i+4)
elif(i!=0 and i+4>=x+1):
print(i)
elif(i!=0 and i+3>=x+1):
print(i-1,end='')
print(i)
elif(i!=0 and i+2>=x+1):
print(i-2,end='')
print(i-1,end='')
print(i)

Bad Selection Sort in Python

I have a problem with a simple sort of a multidimensional array.
The Python code is:
SelectionSort.py
class SelectionSort(object):
#staticmethod
def sort(list):
for i in range(0, len(list)):
min = i;
for j in range (i+1, len(list)):
if j < list[min]:
min = j;
tmp = list[min];
list[min] = list[i];
list[i] = tmp;
return list;
MatriceSelectionSort.py
import sys;
import traceback;
import re;
from SelectionSort import SelectionSort;
class MatriceSelectionSort(object):
def run(self):
if len(sys.argv) < 2:
print("Missing fileName arg! Examplu de rulare: python MatriceSelectionSort C:\\wsmt\\matrice.txt\n");
sys.exit(1);
fileName = sys.argv[1];
try:
matrix = self.readMatrix(fileName);
for row in matrix:
SelectionSort.sort(row);
self.writeResult(fileName, matrix);
except Exception as e:
print("Nu pot citi/parsa fisierul\n");
traceback.print_exc();
def readMatrix(self, fileName):
matrix = [];
with open(fileName, "r") as file:
for line in file:
row = [];
tokens = re.split("\s+", line);
for token in tokens:
if token:
row.append(int(token));
matrix.append(row);
return matrix;
def writeResult(self, fileName, matrix):
with open(fileName, "a") as file:
file.write("\n\n"); # python will translate \n to os.linesep
for row in matrix:
for item in row:
file.write(str(item) + " ");
file.write("\n");
if __name__ == '__main__':
MatriceSelectionSort().run();
Matrice.txt
7 3 1 9 4
2 1 10 4 9
12 4 23
The problem is that the output of the file is:
(The sorted matrix should be at the end of the file, like this)
Matrice.txt
7 3 1 9 4
2 1 10 4 9
12 4 23
1 4 3 7 9
1 2 4 9 10
23 12 4
So, it's not like the best sort in the world..
I think the problem is in the SelectionSort.py file, I kind of messed up the "length[i]" and the "i" variables. I am a beginner, any help is appreciated!
Thank you!
sort method has a small bug in it, it's comparing loop counter j against minimum value. If you make the following change it will fix the issue:
def sort(list):
for i in range(0, len(list)):
min = i;
for j in range (i+1, len(list)):
if list[j] < list[min]: # Instead of if j < list[min]:
min = j
tmp = list[min]
list[min] = list[i]
list[i] = tmp
return list

Split array by rows

I have a very basic problem.I have wrote a code which open a .txt file which contain a numbers 1 2 3 4 5 6 7 8 9.Then it square all of it and write to other file.
Right now I want to add to this code procedure which split all of this numbers in rows and rewrite,like this:
1 4 9
16 25 36
49 64 81
My code already:
n=[]
dane = open("num.txt", "r")
for i in dane:
i = i.replace('\n','')
for j in i.split(' '):
j = int(j)
j = j**2
n.append(j)
nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()
The code you have written works fine expect for the writing part. For which you need to change the last three lines of code as
nowy = open("newnum.txt","w")
for i in range(0,len(n),3):
nowy.write("{} {} {}\n".format(n[i],n[i+1],n[i+2]))
nowy.close()
The for loop can be explained as,
loop through the list n that you have generated 3 at a time by using the third argument to the range function which is called step.
write out the values three at a time into the file, terminated by the newline character
The output after changing the lines of code is as expected
1 4 9
16 25 36
49 64 81
Ref:
format
range
As a complement to #Bhargav's answer, according to the doc "[a] possible idiom for clustering a data series into n-length groups [is] using zip(*[iter(s)]*n)"
You can use the star to unpack a list/tuple as arguments to format function call too.
All this will lead to a more Pythonic (or, rather crypto-Pythonic ?) version of the writing part:
with open("newnum.txt","w") as nowy:
for sublist in zip(*[iter(n)]*3):
nowy.write("{} {} {}\n".format(*sublist))
Please note the use of a context manager (with statement) to ensure proper closing of the file in all cases when exiting from the block. As other changes would be subject to discussion, that later is a must -- and you should definitively take the habit of using it
(BTW, have you noticed you never closed the dane file? A simple mistake that would have been avoided by the use of a context manager to manage that resource...)
You can try this:
strNew = ''
dane = open("num.txt", "r")
row = 0
for i in dane:
i = i.replace('\n','')
for j in i.split(' '):
row += 1
j = int(j)
j = j**2
if (row % 3) == 0:
strNew += str(j)+'\n'
else:
strNew += str(j) + ' ' # it can be ' ' or '\t'
nowy = open("newnum.txt","w")
nowy.write(strNew)
nowy.close()
The result is:
1 4 9
16 25 36
49 64 81
n=[]
dane = open("num.txt", "r")
for i in dane:
i = i.replace('\n','')
for j in i.split(' '):
j = int(j)
j = j**2
# new code added
# why str(j)? Because array in Python can only have one type of element such as string, int, etc. as opposed to tuple that can have multiple type in itself. I appended string because I wanna append \n at the end of each step(in outer loop I mean)
n.append(str(j))
# new code added
n.append("\n")
nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()

Categories

Resources