Gribouillis 1,391 Programming Explorer Team Colleague

I would say it's a[row][column] . So, use 'row' and 'col' instead of x and y.

Gribouillis 1,391 Programming Explorer Team Colleague

Grib....

repr() of the value gives me:

IpAddress('0.0.0.0')

:)

Ok, so it's not at all weird, only it's not a very useful address... Were you expecting something else ?

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

Try to print the repr() of the weird string, then post it here.

Gribouillis 1,391 Programming Explorer Team Colleague

This code changes anum but it should not?? What is going wrong?
Many thanks

>>> astr=
>>> anum=[4,3,2,1]
>>> anew=anum
>>> for c,d in enumerate(anum):
... anew[c]=astr[c]
... print(anew,astr,anum)
...


>>>

Use anew = list(anum) to make a copy, otherwise anew is only an alias for anum.

Gribouillis 1,391 Programming Explorer Team Colleague

Thanks for answer. So I understood that Tkinter cant use combobox.

When you work with Tkinter, don't hesitate to use Pmw. It's only a small appendix to Tkinter, but very useful. A bible for Tkinter programming is the book by John Grayson (Python and Tkinter programming): he uses Pmw all the time.

Gribouillis 1,391 Programming Explorer Team Colleague

You may consider using a Pmw.OptionMenu, which has a setitems() method. See here http://pmw.sourceforge.net/doc/OptionMenu.html

Gribouillis 1,391 Programming Explorer Team Colleague

Module ctypes is new in python 2.5. I suggest that you uninstall python 2.4 and upgrade to python 2.7, then reinstall serial.

Gribouillis 1,391 Programming Explorer Team Colleague

Hey,
Thanks for the replies. I am trying to create a tree structure for an xml type document. This should work perfect Thanks a lot for the help :-)

Notice that "This is the result" is a strange value for an item named "methodName" :)

Gribouillis 1,391 Programming Explorer Team Colleague

Since radians is only self.rotations converted to radians, it would be easier to make it a property

class Player(pygame.sprite.Sprite):
    
    def rotateShip(self, rotAmt):
        # here use self.radians

    @property
    def radians(self):
        return self.rotation * math.pi / 180

In other classes, use player.radians . In this case, you may consider renaming player.rotation to player.degrees.

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, then replace the first line of your post with

( options, args ) = parser.parse_args()
import glob
args = list(f for arg in args for f in glob.glob(arg)) # expand regex in args

You can add a print(args) afterwards to see what it did to args.

weblover commented: it solved my problem +3
Gribouillis 1,391 Programming Explorer Team Colleague

sorry ,

when i added these 2 lines inside the for loop ,
i get this error :

C:\Python27\mtdb\src\refseq>python ../skew.py -e"A" *.gb
  File "../skew.py", line 87
    filenames = list(f for arg in args for f in glob.glob(arg))
            ^
IndentationError: expected an indented block

Can't you post the whole code, starting from the line (options, args) = parser.parse_args() ? If it is too long, you can simply zip the python file and attach the zip to a post.

Gribouillis 1,391 Programming Explorer Team Colleague

:S:S it did not worked ,

that's the code where i should post the code , but it's not working

for arg in args:
    gb = None
    seq = None
    base, ext = os.path.splitext( arg )
    if ext == ".gb":
        gb = gbfromfile( arg )
        if not gb.is_allowed( options.atax, options.ftax ):
            continue
        seq = gb.sequence
        circ = gb.circular

    elif ext == ".fas" or ext == ".fa":
        circ = options.circular
        seq = sequences_fromfile( arg, circular = circ )[0]

thanks

Try this

filenames = list(f for arg in args for f in glob.glob(arg))
print(filenames)

Does it print the list of files that your are targeting with your "*.gb" ?

(byt the way "it doesn't work" is not a very useful description of your issue. Why doesn't it work ?)

Gribouillis 1,391 Programming Explorer Team Colleague

where should i type this ??

Well, in your program, after the parse_args, if the remaining args are supposed to be
file expressions like *.gb, you could add

import glob
for arg in args:
    filenames = glob.glob(arg)
    # here do something with the list of filenames

Alternately you could write

filenames = list(f for arg in args for f in glob.glob(arg))

Edit: changed the previous line of code.

Gribouillis 1,391 Programming Explorer Team Colleague

hello,

i typed this command line :

python ../skew.py -e"A" NC_000834.gb

and got this output :

c:\python27\lib\site-packages\Bio\utils.py:17: BiopythonDeprecationWarning: Bio.
utils has been deprecated, and we intend to remove it in the next release of Bio
python.
  "the next release of Biopython.", Bio.BiopythonDeprecationWarning)
parsed options are

{'ftax': None, 'third': False, 'format': None, 'expr': ['A'], 'random': None, 'a
type': None, 'atax': None, 'outfile': None, 'window': None, 'ftype': None, 'fnam
e': None, 'offset': 1, 'aname': None, 'strand': None, 'circular': False}
remaining arguments are

['NC_000834.gb']
c:\python27\lib\site-packages\Bio\Seq.py:134: BiopythonDeprecationWarning: Acces
sing the .data attribute is deprecated. Please use str(my_seq) or my_seq.tostrin
g() instead of my_seq.data.
  "my_seq.data.", Bio.BiopythonDeprecationWarning)
0.268912

and the red number is the result that should be shown

but when i tried to calculate this number to all the gb files directly like this :

python ../skew.py -e"A" *.gb

i got this output :

c:\python27\lib\site-packages\Bio\utils.py:17: BiopythonDeprecationWarning: Bio.
utils has been deprecated, and we intend to remove it in the next release of Bio
python.
  "the next release of Biopython.", Bio.BiopythonDeprecationWarning)
parsed options are

{'ftax': None, 'third': False, 'format': None, 'expr': ['A'], 'random': None, 'a
type': None, 'atax': None, 'outfile': None, 'window': None, 'ftype': None, 'fnam
e': None, 'offset': 1, 'aname': None, 'strand': None, 'circular': False}
remaining arguments are

['*.gb']
Traceback (most recent call last):
  File "../skew.py", line 95, in <module>
    gb = gbfromfile( arg )
  File "C:\Python27\mtdb\src\gb\__init__.py", line 136, in __init__
    gbhandle = open( gbfile, "r" )
IOError: [Errno 22] invalid mode ('r') or filename: '*.gb'

what to do ?

You must use module glob to expand the regular …

Gribouillis 1,391 Programming Explorer Team Colleague

ok i will post my code, but now i tried the

DEL *.gb

and it worked on cmd

so the problem is from the script

from optparse import OptionParser, OptionGroup
import os.path
import random
import sys

from gb import gbfromfile
from sequence import sequence, randsequence, sequences_fromfile

usage = "usage: %prog [options] file"
parser = OptionParser( usage )
parser.add_option( "-e", "--expr", action = "append", type = "string", metavar = "EXPR", help = "add expression to evaluate and print" )
parser.add_option( "--third", action = "store_true", default = False, help = "only consider third codon position" )

parser.add_option( "-f", "--format", action = "store", type = "string", metavar = "FMT", help = "output format FMT: svm" )
parser.add_option( "-o", "--outfile", action = "store", type = "string", metavar = "FILE", help = "write values to FILE (default: stdout)" )
parser.add_option( "-r", "--random", action = "store", type = "string", metavar = "MODE", help = "generate random subsequences of the same length, valud MODEs: shuffle & random" )
parser.add_option( "-c", "--circular", action = "store_true", default = False, help = "treat sequence(s) as circular (doeas not apply to gb files)" )

group = OptionGroup( parser, "select a subset of the features in the genbank file for calculations. "
                "(type can be tRNA, rRNA, and gene) "
                "Note: -y,-Y,-n,-N can be specified more than once, combinations are possible." )
group.add_option( "-y", "--atype", action = "append", type = "string", metavar = "TYPE", help = "get all features of type TYPE" )
group.add_option( "-Y", "--ftype", action = "append", type = "string", metavar …
Gribouillis 1,391 Programming Explorer Team Colleague

hello ,

thanks for your reply , but i'm new to python and i already used this module but i did not know how to integrate the multiple argument in my case .

and also when i try to delete multiple files on windows :

Del *.gb

it's not working , maybe the error is from the windows ,i don't know.

if you want i'll show my code and you can help me.

thanks in advance

Yes, it's a very good idea to post your code.

Gribouillis 1,391 Programming Explorer Team Colleague

Hi Tonijv

thanks for the reply. It works perfect, faster than the usual for,for for loops
sorry for the bad way of posting code and variables.

cheers

Also try

from itertools import product

for triple in product(listofitems, listofitems2, listofitems3):
    print triple
Gribouillis 1,391 Programming Explorer Team Colleague

Here are 2 expressions that you could try

subprocess.call("Rscript script.R --args arg1 arg2", shell=True)
subprocess.call(["Rscript", "script.R", "--args", "arg1", "arg2"])
Gribouillis 1,391 Programming Explorer Team Colleague

Command line arguments must be parsed and handled in your script. A common way to do this is to use the optparse module. This blog entry will teach you enough of optparse for your needs http://www.alexonlinux.com/pythons-optparse-for-human-beings .

Gribouillis 1,391 Programming Explorer Team Colleague

But should not i use reading from a file if i want to apply to all my file?

First do it with 3 towns, then we'll apply the method to the whole file.

Gribouillis 1,391 Programming Explorer Team Colleague

Thank you Gribouillis for your contribution. I understand your 2,3, and 4 points, for example I could have moved the part under if __name__ == "__main__": from counter = 0 to counter +=1 to the place under U_data = Evolve_in_One_Timestep(U_data), and simply change U_dat to U_data, this part of the code is creating a series of images at every iteration to make a movie, but I wanted it to do that at last when some criteria under if __name__ == "__main__": are met, or if not at the last cycle of for i in range(number). I don't get your first point clearly.

But the main issue remains, the point that I also noted earlier, U_data is just affected only once after the program is loaded! more advice is welcome on how to make it affected at every cycle!

I don't understand: if you don't write U_data = <something> at some place in the cycle, U_data can't change. Your program's logic is not very apparent.

Gribouillis 1,391 Programming Explorer Team Colleague

It seems that the only place where U_data is modified are lines 48 and 51, which are only executed once when the program is loaded, so U_data can't be affected by the code at the end of the file.

You could make your code more robust: 1) don't use global variables except for some constants N = 1001; M = 75; Dx = 1.5/M ; Dt = 0.0005; a = 1.0 ('a' should be given a more explicit name), 2) don't write code at module level, (lines 11, 16, 17, 48, 50, 51 could go in the if __name__ == "__main__" section), 3) instead, write code in functions (most part of the if __name__ = "__main__" section should go in one or more functions), 4) configure your editor to indent python code with 4 space characters instead of a tab.

vegaseat commented: agree +15
Gribouillis 1,391 Programming Explorer Team Colleague

A tried this

cities = []
cities = [ entry[1] for entry in result ]

print "     ".join(cities)

for city in cities:
    sdist = []
    sdist = [ ntostr(entry[2], 3) for entry in result ]
    sdist.insert(0, city)
    print " ".join(sdist)

entries = read_3_entries()
cities = [ entry[1] for entry in entries ]

and it will print

Acatari     Acis     Adamclisi
Acatari 0.000 183.198 372.526
Acis 0.000 183.198 372.526
Adamclisi 0.000 183.198 372.526
Only the first line is ok , i mean correct, 
the next two are not in order
ast here should be like this
     Acatari     Acis     Adamclisi
Acis   183.198 0.000  372.526
Adamclisi  372.526 183.198 0.000

it seem that it doesn nu put the blank space before Acatari but between Acatari Acis Adamclisi

Come on, it's very simple. All you have to do is fill the missing expressions in the following code

data = [('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318), ('Acis', 'Acatari', 183.198428622), ('Acis', 'Acis', 0.0), ('Acis', 'Adamclisi', 555.434851863), ('Adamclisi', 'Acatari', 372.526412318), ('Adamclisi', 'Acis', 555.434851863), ('Adamclisi', 'Adamclisi', 0.0)]

list0 = ??? # your code here
print list0 # should print [('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]

list1 = ??? # your code here
print list1 # should print [('Acis', 'Acatari', 183.198428622), ('Acis', 'Acis', 0.0), ('Acis', 'Adamclisi', 555.434851863)]

list2 = ??? # your code here
print list2 # should print [('Adamclisi', 'Acatari', 372.526412318), ('Adamclisi', 'Acis', 555.434851863), ('Adamclisi', 'Adamclisi', 0.0)]

Then it will be very easy to print the 3 lines.

Gribouillis 1,391 Programming Explorer Team Colleague

But i use result = useful_entries(cities) as the entries generated by the previos function.
And if i were not usong the curreent function could i still be using

if result[0] == cities[1]: #with entries instead of result
                res.append(entry[2])

Or i do not really understand?

I don't understand. If you want to iterate over the list 'result', you can write

for entry in result:
    ...do something with the entry

You don't need to open Te.csv.

Gribouillis 1,391 Programming Explorer Team Colleague

The python tutorial you send me when i was trying to insert a blank space in the list?
Even so in my current code why doesn't return something?

Because you're using result[0] instead of entry[0].

Gribouillis 1,391 Programming Explorer Team Colleague

i thought of something like this:
Should i use something like

result = useful_entries(cities)
if result[0] == cities[1]:
    print [entry[2] for entry in result]

but it does not show what i want
I also tried

result = useful_entries(cities)
def get_it(result):
    res = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            entry = line_to_entry(line)
            if result[0] == cities[1]:
                res.append(entry)
    return res
print get_it(result)

but it only printed []
i should definetily change it and try something else?

Once you have the list that we read before, you don't need to read in the file again. We are only trying to take a sublist. The solution is in the python tutorial.

Gribouillis 1,391 Programming Explorer Team Colleague

I used this code and received this:

[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318), ('Acis', 'Acatari', 183.198428622), ('Acis', 'Acis', 0.0), ('Acis', 'Adamclisi', 555.434851863), ('Adamclisi', 'Acatari', 372.526412318), ('Adamclisi', 'Acis', 555.434851863), ('Adamclisi', 'Adamclisi', 0.0)]

What the next step should be ?

Extract from this list the list of entries for which entry[0] == cities[1] and you will find your second line. Then do the same with cities[2]. You do it yourself this time.

Gribouillis 1,391 Programming Explorer Team Colleague

This should be of course 40 000 km perimeter.

Do you mean that the distances are false ?

Gribouillis 1,391 Programming Explorer Team Colleague

I do not really understand how to do that. My Te.csv file has tuples like this

Acatari, Acatari, 0.0
Acatari, Acis, 183.198428622

I have to convert them in a list and and to connect it with the list cities? I know that being new in python is not an escuse but i can not really figure out what i should do.

entries = read_3_entries()
cities = [ entry[1] for entry in entries ]

def useful_entries(cities):
    result = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            entry = line_to_entry(line)
            if entry[0] in cities and entry[1] in cities:
                result.append(entry)
    return result

print useful_entries(cities)

from the resulting list, you can extract the numbers that you need.

A better code for intermediate pythonistas is

def stored_entries():
    with open("Te.csv") as filein:
        for line in filein:
            yield line_to_entry(line)
    
print [ entry for entry in stored_entries() if entry[0] in cities and entry[1] in cities ]
Gribouillis 1,391 Programming Explorer Team Colleague

I tried your advice using this:

cities = []
sdist = []
cities.insert(0,'')
sdist = [ ntostr(entry[2], 3) for entry in result ]
sdist.insert(0, 'Acatari')
cities = [ entry[1] for entry in result ]
cities.insert(0,'            ')
print " ".join(cities) 
print " ".join(sdist)

and it worked

Acatari Acis Adamclisi
Acatari 0.000 183.198 372.526

.
About generating a list of distances. Could you suggest me how could i do it?

I suggest that you first create a list of all the entries (cityA, cityB, dist) in Te.csv for which cityA and cityB are in the list 'cities'.

Gribouillis 1,391 Programming Explorer Team Colleague

Warning! In python, one writes if node != 0 [b]and[/b] currentNode.visited == false the & operator is something else.

Yes there are ways of connecting all these data. You are in a situtation where there are 2 ways to refer to the nodes: their index and the Node object that you are creating. A way to handle this is to have only one way to refer to the nodes, otherwise your code becomes easily a mess.

So the index could become an attribute of the node object like this

class Node:
    def __init__(self, index):
        self.index = index
        self.distFromSource = infinity
        self.previous = None
        self.visited = False
        self.neighbours = []

Then the network, instead of being a list of lists of integers, could be a list of Node objects.
You can even define a Network class, which gives you a way of connecting the functions

class Network(list):
    def __init__(self, filename):
        list.__init__(self)
        with open(filename) as filein:
            lines = filein.readlines()
            self[:] = [Node(i) for i in range(len(lines))] # create the Nodes
            for i, line in enumerate(lines):
                self[i].neightbours[:] = [self[j] for j in (int(n) for n in line.split(","))]

    def nearestNeighbour(self, node):
        etc...
Gribouillis 1,391 Programming Explorer Team Colleague

I read the tutorial and i tried this

result = read_3_entries()
result.insert(0," ")

printed

[' ', ('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]

but it gave
at the next lines of code this error
sdist = [ ntostr(entry[2], 3) for entry in result ]
IndexError: string index out of range

i can figure out what is the problem but how would it be if there was the possibility to built a function(if it is possible ) that would print as result for the rest of the matrix a list like this name,d1,d2,d3,d5----each cite fallowed by the distances till the other cities.

Acatari Acis Adamclisi
name   d1     d2   d3

You must not insert an item in the entries list but in the cities or the sdist lists, before you call join on these lists. For the cities list, you must insert a blank string (which can have as many blank characters as you want), and for the sdist list, you must insert the name of the first city.
Once this is done, you only need to repeat the operation with each city after generating a list of the distances. Then we'll put all this in a function.

Gribouillis 1,391 Programming Explorer Team Colleague

Silly me, I forgot to paste the main function in (was buried under uncommented code) :$ - here is the missing code:

currentNode = startNode

if __name__ == "__main__":
    populateNodeTable()
    network()
    nearestNeighbour(currentNode, theNetwork)
    #tentativeDistance(currentNode,populateNodeTable())

Well progress has been made, though it's now complaining that 'theNetwork has not been defined' even though I have defined it in my network function:

nearestNeighbour(currentNode, theNetwork)
NameError: name 'theNetwork' is not defined

Names defined in a function don't exist outside the function. They are called local variables. Use the value returned by the function

if __name__ == "__main__":
    populateNodeTable()
    theNetwork = network() # here we define a variable (it's not the same theNetwork)
    nearestNeighbour(currentNode, theNetwork)
    #tentativeDistance(currentNode,populateNodeTable())
Gribouillis 1,391 Programming Explorer Team Colleague

I changed by mistake number with result as the change was intended in the line after that. I had a file where i was working with elements and and one with result.

now in what concerns columns i am not very familiar with them. What should i do to insert a blank string in the city list ?

http://docs.python.org/tutorial/datastructures.html#more-on-lists

Gribouillis 1,391 Programming Explorer Team Colleague

Hi, I have changed the variable 'network' to 'theNetwork' though I am now getting this error:

for node in theNetwork[currentNode]:
TypeError: 'function' object is not subscriptable

I'm probably overseeing something simple, I will include all of my code, though I don't think it has any bearing:

infinity = 1000000
invalid_node = -1
startNode = 0

#Values to assign to each node
class Node:
     distFromSource = infinity
     previous = invalid_node
     visited = False

#read in all network nodes
def network():
    f = open ('network.txt', 'r')
    theNetwork = [[int(node) for node in line.split(',')] for line in f.readlines()]
    print theNetwork

    return theNetwork

#for each node assign default values    
def populateNodeTable(): 
    nodeTable = []
    index = 0
    f = open('network.txt', 'r')
    for line in f: 
      node = map(int, line.split(',')) 
      nodeTable.append(Node())
      
      print "The previous node is " ,nodeTable[index].previous 
      print "The distance from source is " ,nodeTable[index].distFromSource 
      index +=1
    nodeTable[startNode].distFromSource = 0 

    return nodeTable

It seems that the line causing the error appears nowhere in your code !

Gribouillis 1,391 Programming Explorer Team Colleague

It worked for the distances

elements=[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]
def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, precision)
sdist = [ ntostr(entry[2], 3) for entry in elements ]
print " ".join(sdist)

giving the wanted result

0.000 183.198 372.526

but when i try to add this code to rest of the code

def line_to_entry(line):
    a, b, dist = line.split(', ')
    return (a, b, float(dist))


def read_3_entries():
    result = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            if i >= 3:
                break
            entry = line_to_entry(line)
            result.append(entry)
    return result


print read_3_entries()

def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, result)
sdist = [ ntostr(entry[2], 3) for entry in result ]
print " ".join(sdist)

it says that NameError: name 'result' is not defined

Also i know that for cities it worked in shell but in idle i do not really know how to deal within idle

" ".join(cities)

In what concerns the issue of the columns widths i am still quite a novice.

Your are using a variable result but there is no such variable. The 'result' in read_3_entries() exists only in the function's body, not outside the function. You must use the return value

elements = read_3_entries() # capture the return value in a variable 'elements'

def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, precision) # why did you change this ?

sdist = [ ntostr(entry[2], 3) for entry in elements ] # now use 'elements'
print " ".join(sdist)
Gribouillis 1,391 Programming Explorer Team Colleague

network ---> network()
Also it's not a very good idea to give variables the same name as your function. A good name for the function would be load_network()

Gribouillis 1,391 Programming Explorer Team Colleague

len() i understood. " ".join(cities) --this is something new for me.

So iTried this :
>>> cities = [ entry[1] for entry in elements ]
>>> " ".join(cities)
'Acatari Acis Adamclisi'

Then as matrix is a list of lists i thought i could do this

dist = [ entry[2] for entry in elements ]
>>> print dist
[0.0, 183.198428622, 372.526412318]

But when trying to do the same as for cities i got this
Traceback (most recent call last):

File "<pyshell#33>", line 1, in <module>
    " ".join(dist)
TypeError: sequence item 0: expected string, float found

How can this be solved?

As I would like to have something like this.

'Acatari Acis Adamclisi'
0.0 183.198428622 372.526412318

But still i would need a column for the left side from the names of the cities.

You can only join strings, not floating points numbers, unless you convert them to string with str() or another function. I give you a function for that

def ntostr(number, precision=3):
    """convert a number to str with a given precision"""
    return "{0:.{1}f}".format(number, precision)

You can now use

sdist = [ ntostr(entry[2], 3) for entry in elements ]
print "XXX".join(sdist)

To add a first column, you could insert a blank string in the city list. Only you must still handle the issue of the columns widths.

Gribouillis 1,391 Programming Explorer Team Colleague

I am sorry but i am having troubles in understanding what "HELLO".center(15) and also len('Acatari') are.

Here is an exemple in a shell

>>> "HELLO".center(15, "-")
'-----HELLO-----'
>>> len("a")
1
>>> len("ab")
2
>>> len("abc")
3
>>> len("zzz")
3
>>> len("this string has 29 characters")
29
>>> "HELLO".center(20, "$")
'$$$$$$$HELLO$$$$$$$$'
>>> help("HELLO".center) # type q to exit the help
Gribouillis 1,391 Programming Explorer Team Colleague

I tried this code in shell first:

>>> elements=[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]
>>> from operator import itemgetter
>>> map(itemgetter(1), elements)
['Acatari', 'Acis', 'Adamclisi']

in idle i tried this:

import operator
result = operator.itemgetter(1)
tup=('Acatari', 'Acis', 0.0)
print map(result, tup).index("Acatari")

but i got this
print map(result, tupl).index("Acis")
TypeError: 'float' object is not subscriptable
What might seem to be the problem?

If i am again wrong i appologize.i will be searching another solution.

map() is not very useful in current versions of python. You can write

cities = [ entry[1] for entry in elements ]

and this yields the list ['Acatari', 'Acis', 'Adamclisi'] . This is not yet our string. There are useful functions that you could use. Try "HELLO".join(cities) for example. Then look at "HELLO".center(15) and also len('Acatari') .

Gribouillis 1,391 Programming Explorer Team Colleague

This is the function you were talking about?

readFile = open("Te.csv")
lines = readFile.readlines()
readFile.close()
w = open("Tee.csv",'w')
w.writelines([item for item in lines[:3]])
print lines[:3]
w.close()

This is what it writes in the new file

Acatari, Acatari, 0.0
Acatari, Acis, 183.198428622
Acatari, Adamclisi, 372.526412318

This is what it prints

['Acatari, Acatari, 0.0\n', 'Acatari, Acis, 183.198428622\n', 'Acatari, Adamclisi, 372.526412318\n']

Is this what i Should have done ?

Once again, you fail miserably, you didn't even write a function and it doesn't return 3 entries but 3 lines. Here is the code

def line_to_entry(line):
    a, b, dist = line.split(', ')
    return (a, b, float(dist))


def read_3_entries():
    result = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            if i >= 3:
                break
            entry = line_to_entry(line)
            result.append(entry)
    return result


print read_3_entries()

""" my output -->
[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.19842862199999), ('Acatari', 'Adamclisi', 372.52641231799998)]
"""

Data structures are very important in your program, our function returns a list of 3 tuples and not 3 strings. Now you should write a function which takes this list as argument and returns the first line of the display that you want. It's another string formatting exercise

"         |  Acatari  |   Acis   |  Adamclisi  |\n"

A question is how are you going to define each column's width ?

About the DataFrame of module panda, it's probably a nice data structure, but you should concentrate on learning python's fundamental data structures instead.

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest that you start by reading the data and producing a dictionary like this one

{
  "21225114.txt" : [('cross-sectional', 'study')],
  "21225178.txt" : [('cross-sectional', 'study'), ('prospective', 'cross-sectional', 'study')],
  "21225558.txt" : [('retrospective', 'cohort'), ('retrospective', 'cohort', ' study'), ('cohort', 'study')]
}

This part is easy. Then think about an algorithm to choose the best tuple for each txt file.

Gribouillis 1,391 Programming Explorer Team Colleague

You are right i have not paid enough attention to the code.
But retourning to my generated matrix, as Gribouillis suggested i had to change the format of my Te.csv file in order to write the way i wanted the matrix

name1    name2     name3
name1    0      distA     distB
name2  DistC     0        DisD
name3  DiistF   DistV      0

and not the way it looks now

{('Berzasca', 'Berzasca'): 0.0,
 ('Berzasca', 'Liubcova'): 5.155523938970983,
 ('Berzasca', 'Moldova Veche'): 27.32911790373754,
 ('Liubcova', 'Berzasca'): 5.155523938970983,
 ('Liubcova', 'Liubcova'): 0.0,
 ('Liubcova', 'Moldova Veche'): 22.194840760286052,
 ('Moldova Veche', 'Berzasca'): 27.32911790373754,
 ('Moldova Veche', 'Liubcova'): 22.194840760286052,
 ('Moldova Veche', 'Moldova Veche'): 0.0}

So what i have problems in understanding this: how could i use these lines of code that you repaired and what changes should i make to the rest of my code write in a file the desired distance matrix.

Snippsat's solution is not good because the third tuple item is not a float. The solution is

def line_to_entry(line):
    a, b, dist = line.split(', ')
    return (a, b, float(dist))

I agree with snippsat that you have some very basic python to learn, and since you are reading and writing files, it starts with converting strings to other fundamental data types like tuples, lists and dicts, and back.

Now with our helper functions, this is how we can write the csv file

def write_csv(matrix, filename):
    entries = get_entries(matrix)
    with open(filename, "w") as fout:
        for entry in entries:
            fout.write(entry_to_line(entry))

if __name__ == "__main__":
    matrix = distance_matrix(coords_list)
    write_csv(matrix, "Te.csv")

To read the file, we'll use some …

Gribouillis 1,391 Programming Explorer Team Colleague

You mean that it sould be somethong like this?

def entry_to_line(entry)
    entry = ', '.join(map(str,entry))
    return entry

print entry_to_line()

Or i got it again confused?

It's almost correct. There is a missing newline if we want to adhere to the specifications, also it's better to chose a new name rather than reusing the parameter name

def entry_to_line(entry)
    line = ', '.join(map(str,entry)) + "\n"
    return line

The other solution uses the format() method

def entry_to_line(entry):
    a, b, dist = entry
    line = "{0}, {1}, {2:.3f}\n".format(a, b, dist)
    return line
Gribouillis 1,391 Programming Explorer Team Colleague
def entry_to_line():
    re = ('Acatari', 'Aiud', 72.639)
    entry = ', '.join(map(str,re))
    return entry

The explicit tuple ('Acatari', 'Aiud', 72.639) should not appear in your function. Your function should work for any tuple of this form, and should take a single argument entry.

Gribouillis 1,391 Programming Explorer Team Colleague

For the second function, have a look at the string methods in the python documentation http://docs.python.org/library/stdtypes.html?highlight=strip#string-methods. Try some methods in a python shell to see what they do.

Gribouillis 1,391 Programming Explorer Team Colleague

I see there they refer to string formatting in python3.0. and i have 2.7.
What other resource could i use for my version of python?

What they say for python 3 about string formatting applies to 2.7

Gribouillis 1,391 Programming Explorer Team Colleague

ok. Then as str() is not what i need and i am quite new in python could you direct me to any kind of tutorial or python resource to help me edit my function?

This blog entry could help : http://python.about.com/b/2008/12/18/string-formatting-a-new-method-for-printing.htm

Gribouillis 1,391 Programming Explorer Team Colleague

Ok .I think i understand what you mean.

I have not used yet conversion between tuples and strings so concerning the first function you said i sould write should i use something like in the next example?

a=[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.1984286216621), ('Acatari', 'Adamclisi', 372.52641231771526), ('Acatari', 'Adjud', 200.36162156879055), ('Acatari', 'Afumati', 251.49065927408915)]
>>> b=str([('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.1984286216621), ('Acatari', 'Adamclisi', 372.52641231771526), ('Acatari', 'Adjud', 200.36162156879055), ('Acatari', 'Afumati', 251.49065927408915)])
>>> print b
[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.1984286216621), ('Acatari', 'Adamclisi', 372.52641231771526), ('Acatari', 'Adjud', 200.36162156879055), ('Acatari', 'Afumati', 251.49065927408915)]

Or i should keep on looking for something else?

No, the first function's argument is a single tuple like ('Acatari', 'Aiud', 72.639). It's return value is a single string with format "Acatari, Aiud, 72.639\n"