I have a text file that has 6 lines of numbers:
1,35,1,0,3,1,1.09,5,5,1,0
0,22,1,0,6,4,1.15,5,6,2,0
2,35,1,1,0,1,1.14,6,2,3,0
0,38,1,0,4,3,1.09,3,1,1,0
2,37,1,0,3,3,1.13,4,3,1,0
The function that needs to be printed out is D = (X,y)
X for example using the first line would equal:[0,27,0,1,7,2,1.09,6,5,3]
y for example using the first line would equal: [0] (the last number of that line
I am trying use the values of X and y and make it into this form:
D = (X,y)
How do I do this?
This is what I did which gave me the X and y values
y_list = []
x_list = []
for W in range(0,100):
X = f.readline()
y = X.split(",")
#print(y)
y_list.append(y[10][0])
z_list = []
for Z in range(0,10):
z_list.append(y[Z])
x_list.append(z_list)
print (y_list)
print (x_list)
f.close()
How do I combine both the X and y values properly where it matches D = (X,y)?
For example using the first line
D = ([0,27,0,1,7,2,1.09,6,5,3] , [0])
fo = open('value.txt',"r")
D = []
for l in fo.read().split('\n'):
values = l.split(',')
D.append(values[:-1])
D.append([values[-1]])
print(tuple(D))
Related
The loop goes through list of numbers. I need to use map to accumulate the sum of all element[0] in another list's element[0] , sum of all element[1] in element[1].
result_list = []
sub1 = sub2 = sub3 = 0 #these 3 should be only indexes 0,1,2 of list above
for item in r:
l = item.split(';') # originally l = '34;56;78'
q = list(map(float,l)) # q is the list of 3 elements
#instead of code below I want to have smth like
# result_list = list(map( sum( q(item), result_list)
sub1 += q[0]
sub2 += q[1]
sub3 += q[2]
Input:
l = [['1;2;3'], ['10;20;30'], ['12;34;56']]
result_list must aggregate the sum of all element[0] in each list to result_list[0].
Output
result_list[0] = 1+ 10 + 12
result_list[1] = 2 + 20 + 34
result_list[2] = 3 + 30 + 56
r is this, I omit names and calculate average of each 'column'.
Bawerman;55;79;50
Baldwin;83;62;72
Owen;94;86;65
Watson;92;79;100
Clifford;33;99;47
Murphy;94;87;53
Shorter;83;61;61
Bishop;27;89;41
This is one approach.
Ex:
l = [["1;2;3"], ["10;20;30"], ["12;34;56"]]
result_list = []
l = [list(map(float, j.split(";"))) for i in l for j in i]
for i in zip(*l):
result_list.append(sum(i))
print(result_list)
Output:
[23.0, 56.0, 89.0]
You could do something like this, assuming each element of l is a list of one string:
l = [['1;2;3'], ['10;20;30'], ['12;34;56']]
numbers = (map(float, e.split(';')) for e, in l)
result = [sum(n) for n in zip(*numbers)]
print(result)
Output
[23.0, 56.0, 89.0]
A oneliner can do the job:
If you need first to parse the strings with the numbers:
l = [[int(i) for i in e[0].split(';')] for e in l]
And after that, just:
result = map(sum, zip(*l))
csv.reader + zip + statistics.mean
I omit names and calculate average of each 'column'
You don't need to construct a large list of lists from your data. You can use an iterator and use sequence unpacking with zip. To calculate the mean, you can use statistics.mean:
from io import StringIO
from statistics import mean
import csv
x = StringIO("""Bawerman;55;79;50
Baldwin;83;62;72
Owen;94;86;65
Watson;92;79;100
Clifford;33;99;47
Murphy;94;87;53
Shorter;83;61;61
Bishop;27;89;41""")
# replace x with open('file.csv', 'r')
with x as fin:
reader = csv.reader(x, delimiter=';')
zipper = zip(*reader)
next(zipper) # ignore labels
res = [mean(map(float, x)) for x in zipper]
print(res)
# [70.125, 80.25, 61.125]
I write a KargerMinCut function in which I have written a random function in Python, but I get the same result within the same run. If I restart the function, different results printed.
Here's the code
import random
with open('test.txt') as f:
#kargerMinCut
#a = [[int(x) for x in ln.split()] for ln in f]
data_set = []
for ln in f:
line = ln.split()
if line:
a = [int(x) for x in line]
data_set.append(a)
def choose_random_edge(data):
a = random.randint(0,len(data)-1)
b = random.randint(1,len(data[a])-1)
return a,b
def compute_nodes(data):
data_head = []
for i in xrange(len(data)):
data_head.append(data[i][0])
return data_head
def find_index(data_head,data,u,v):
index = data_head.index(data[u][v])
return index
def replace(data_head,data,index,u):
for i in data[index][1:]:
index_index = data_head.index(i)
for position,value in enumerate(data[index_index]):
if value == data[index][0]:
data[index_index][position] = data[u][0]
return data
def merge(data):
u,v = choose_random_edge(data)
print u,v
data_head = compute_nodes(data)
index = find_index(data_head,data,u,v)
data[u].extend(data[index][1:])
#print data
data = replace(data_head,data,index,u)
#print data
data[u][1:] = [x for x in data[u][1:] if x!=data[u][0]]
#print data
data.remove(data[index])
#print data
return data
def KargerMinCut(data):
while len(data) >2:
data = merge(data)
#print data
num = len(data[0][1:])
print num
#KargerMinCut(data_set)
Here's test.txt
1 2 3 4 7
2 1 3 4
3 1 2 4
4 1 2 3 5
5 4 6 7 8
6 5 7 8
7 1 5 6 8
8 5 6 7
Editted 12-28-2016
I have modified my code in merge and replace by adding local copy of input data. I don't know whether I'm right or not.
Here's the code
def replace(data_head,data,index,u):
data1 = data
for i in data[index][1:]:
index_index = data_head.index(i)
for position,value in enumerate(data[index_index]):
if value == data[index][0]:
data1[index_index][position] = data[u][0]
return data1
def merge(data1):
data = data1
u,v = choose_random_edge(data)
#print u,v
data_head = compute_nodes(data)
index = find_index(data_head,data,u,v)
data[u].extend(data[index][1:])
#print data
data2 = replace(data_head,data,index,u)
#print data
data2[u][1:] = [x for x in data2[u][1:] if x!=data2[u][0]]
#print data
data2.remove(data2[index])
#print data
return data2
But when I run merge(data_set) I find that I have changed the input again. Why and what should I do? Could anybody give me some clues?
Here is the output of merge and data_set
Editted by adding wanted output image
Here's the image:
wanted output
I want to loop calculate KargerMinCut(data_set) and pick the min value as a output.
As you can see, when I loop calculate KargerMinCut(data_set) I should get the different result instead of same results which is wrong. I know I have change the input data when I call KargerMinCut(data_set), but I don't know how to fix it.
Problem solved in 1/7/2017
I use import copy at the top and data = copy.deepcopy(data) in the first line of KargerMinCut(). Adding calc_num() function.
Here's the output:
calc_number(data_set,20)
17
calc_number(data_set,2)
17
calc_number(data_set,15)
20
calc_number(data_set,15)
17
Here's the code:
import random
import copy
with open('kargerMinCut.txt') as f:
#kargerMinCut
#a = [[int(x) for x in ln.split()] for ln in f]
data_set = []
for ln in f:
line = ln.split()
if line:
a = [int(x) for x in line]
data_set.append(a)
def choose_random_edge(data):
a = random.randint(0,len(data)-1)
b = random.randint(1,len(data[a])-1)
return a,b
def compute_nodes(data):
data_head = []
for i in xrange(len(data)):
data_head.append(data[i][0])
return data_head
def find_index(data_head,data,u,v):
index = data_head.index(data[u][v])
return index
def replace(data_head,data,index,u):
for i in data[index][1:]:
index_index = data_head.index(i)
for position,value in enumerate(data[index_index]):
if value == data[index][0]:
data[index_index][position] = data[u][0]
return data
def merge(data):
u,v = choose_random_edge(data)
#print u,v
data_head = compute_nodes(data)
index = find_index(data_head,data,u,v)
data[u].extend(data[index][1:])
#print data
data = replace(data_head,data,index,u)
#print data
data[u][1:] = [x for x in data[u][1:] if x!=data[u][0]]
#print data
data.remove(data[index])
#print data
return data
def KargerMinCut(data):
data = copy.deepcopy(data)
while len(data) >2:
data = merge(data)
#print data
num = len(data[0][1:])
return num
#KargerMinCut(data_set)
def calc_number(data,iteration):
list = []
for i in xrange(iteration):
list.append(KargerMinCut(data))
return min(list)
data_set is a list and lists are mutable. If you follow the function calls: KargerMinCut calls merge and merge calls replace. Both merge and replace mutates the passed list.
merge mutates it in the line
data[u].extend(data[index][1:])
replace mutates it in the line
data[index_index][position] = data[u][0]
In a single session, the first time you call KargerMinCut(data_set) it mutates data_set, changing the input to the second call KargerMinCut(data_set). That is why the two function calls behave differently.
If this isn't desirable, you could should start each function merge and replace by creating a local copy of data.
def KargerMinCut(data):
while len(data) > 2: #here is the problem
data = merge(data)
# print data
num = len(data[0][1:])
print num
The problem is in the 2nd line.
in the 2nd call to KargerMinCut len(data)>2 so it just print the same num again.
I would like to append losowanie1[0] when x = 0 to group1 and so on ( losowanie1[0] when x = 1 to group2...). The same with losowanie2[0], but it comes form other List.
import random
List1 = ['AAAA','BBBBB','CCCCC','DDDD','EEEE']
List2 = ['FFFF','GGGG','HHHH','IIIII','JJJJJ']
Gruop1 = []
Group2 = []
for x in range (len(List1)):
losowanie1 = random.sample(List1,1)
losowanie2 = random.sample(List2,1)
# Here i would like to append losowanie1[0] when x = 0 to group1 and so on ( losowanie1[0] when x = 1 to group2...)
List1.remove(losowanie1[0])
I tried:
('Group' + str(x+1)).append(losowanie1[0])
but obviously i cannot append into string.
I can do it without loop but wanted to make my code more professional. Thanks for any help.
You can make a dictionary with keys (as 'Group' + str(x+1)').
And then add a value to the list!
import random
List1 = ['AAAA','BBBBB','CCCCC','DDDD','EEEE']
base_name = "Group"
my_dic = dict()
for x in range(len(List1)):
my_dic[base_name + str(x +1)] = []
for x in range (len(List1)):
losowanie1 = random.sample(List1,1)
my_dic[base_name + str(x +1)].append(losowanie1[0])
List1.remove(losowanie1[0])
print(my_dic)
Result
{'Group3': ['DDDD'], 'Group4': ['BBBBB'], 'Group1': ['EEEE'], 'Group2': ['CCCCC'], 'Group5': ['AAAA']}
#ADD STRING MATRIX AND NUM MATRIX Fraction(3).limit_denominator(10)from fractions import Fraction
#ONLY WORKS FOR SQUARE ONES RIGHT NOW!
from fractions import Fraction
def make1(nm,x):
if nm[x][x]!=1:
print("Divide R1 by ",Fraction(nm[x][x]).limit_denominator(10))
tempr = multiply(nm[x],1/nm[x][x])
nm[x] = tempr
return nm
def convert(n):
try:
return float(n)
except ValueError:
num, denom = n.split('/')
return float(num) / float(denom)
def convertm(m):
lm = len(m)
lx = len(m[0])
tempn = [0]*lx
temps = [[]]*lm
print(temps)
cnt = 0
for x in m:
tempn = x
for n in x:
temps[cnt].append(str(Fraction(n).limit_denominator(10)))
print(n)
cnt+=1
print(temps)
def mprint(matrix):
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print('\n'.join(table))
def subtract(r1,r2): #r1-r2
tempr = [0]*len(r1)
for x in range (0,len(r1)):
tempr[x] = r1[x]-r2[x]
return tempr
def multiply(r1,n):
tempr = [0]*len(r1)
for x in range (0,len(r1)):
tempr[x] = r1[x]*n
return tempr
def ans(nm):
end = len(nm[0])
cnt = 0
for x in nm:
cnt+=1
print("X",cnt,"=",x[end-1])
equ = int(input("How many equasions are in the linear system? "))
#unk = int(input("How many unkowns are in the linear system? "))
nm = [0] * equ
sm = [0] * equ
for x in range (0,equ):
tempinput = input("Please enter line "+str(x+1)+" of the matrix: ")
templist = [convert(n) for n in tempinput.split()]
nm[x] = templist
sm[x] = tempinput.split()
mprint(nm)
nm = make1(nm,0)
mprint(nm)
for p in range (0,equ-1):
for x in range (p,equ-1):
print("Subtract ",Fraction(nm[x+1][p]).limit_denominator(10),"*",p+1,"by",p+2)
tempr = multiply(nm[p],nm[x+1][p])
nm[x+1] = subtract(tempr,nm[x+1])
print("FIRST X: ",x,"P",x)
mprint(nm)
nm = make1(nm,p+1)
mprint(nm)
#GOIN BACK
for p in range (0,equ-1):
for x in range (0,equ-(p+1)):
print("Subtract ",x,"by",Fraction(nm[x][2-p]).limit_denominator(10),"*",3)
tempr = multiply(nm[2-p],nm[x][2-p])
nm[x]= subtract(nm[x],tempr)
print("SECOND X: ",x,"P",x)
mprint(nm)
ans(nm)
##or x in range (0,equ):
# print()
#g = nm[1][0]-1
#print("")
#tempr = multiply(nm[0],g/nm[0][0])
#nm[0]=tempr
#tempr = subtract(nm[1],nm[0])
#nm[0] = tempr
Pastebin of my code
Ok so where my actual problem is in the unimplemented (because I couldn't get it working) def convertm. What this is supposed to do is take the matrix with numbers (nm) and take every value and convert it into a string as fractions (x/x) if needed and store it in the matrix of strings (sm).
Here is that segment of code I am referencing...
def convertm(m):
lm = len(m)
lx = len(m[0])
tempn = [0]*lx
temps = [[]]*lm
print(temps)
cnt = 0
for x in m:
tempn = x
for n in x:
temps[cnt].append(str(Fraction(n).limit_denominator(10)))
print(n)
cnt+=1
print(temps)
I added some prints in order to try and test what the heck was going on during it. I am getting an output of just the last row being repeated through all rows. I think I don't have a return statement currently just because I have been trying get this to work. Ok so for an example if an array is imported that is...
[ [1,2,3],
[4,5,6],
[7,8,9] ]
It will output (set temps to)
[ ['7','8','9'],
['7','8','9'],
['7','8','9'] ]
I want it to output (set temps to)
[ ['1','2','3'],
['4','5','6'],
['7','8','9'] ]
Also I am using Python 3.3.1
(probably should upgrade to 3.3.3 but that is not what we are discussing!)
I have absolutely no idea why it is doing this and any little bit of help would very appreciated!
THANK YOU
I also apologize if this formatting is horrible I am new to this and I copy/pasted this from another forum I am very desperate to know what is going on here.
The line
temps = [[]]*lm
makes a list of list, where each sublist points to the same list in memory. So, if you modify one, you modify them all. This is why you are seeing the behavior you are seeing.
Change it to
temps = [[] for _ in range(lm)] # xrange on python2
to get different sublists.
Why can i only get the [-1.0,0.0,1.0,2.0,3.0], instead of
[0.0,1.0,2.0,3.0,4.0]
[-2.0,-1.0,0.0,1.0,2.0]
[-1.0,0.0,1.0,2.0,3.0], thank you
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1
for line in iter(f): 3
Z = float(line) 2
c = []
for i in range(len(V)):
c.append(V[i]-Z)
print c
Something was messed up while you were posting.
I guess you have this:
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1
for line in iter(f): 3
Z = float(line) 2
c = []
for i in range(len(V)):
c.append(V[i]-Z)
print c
Therefore, the print c is called only once, after the outer loop has finished.
While you wanted to print c after every inner loop is finished:
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1
for line in iter(f): 3
Z = float(line) 2
c = []
for i in range(len(V)):
c.append(V[i]-Z)
print c
I'm unsure of the context of this code, but you can simplify your code snippet somewhat by removing the iter() (a file object is already iterable) and the range(len(V)):
f = open('Qin.txt')
for line in f:
Z = float(line)
c = []
for i in range(1, 6):
c.append(i - Z)
print c
That can further be reduced by building the list c with a list comprehension and printing it directly:
f = open('Qin.txt')
for line in f:
Z = float(line)
print [i-Z for i in range(1, 6)]