Gribouillis 1,391 Programming Explorer Team Colleague

You will probably find python3 under /usr/bin/python3.

The port binding error is standard in idle: idle uses 2 processes, the first one to run idle GUI, and the second one to run your code. The 2 processes communicate through a port. It means that you cannot run 2 idle's at the same time (in fact there are alternatives to this: idle.py accepts command line options to run without a subprocess or to use another port).

If you are new to linux, most commands are installed in /usr/bin or /usr/local/bin, and administrator commands in /bin , /sbin or /usr/sbin. The first tools to get info about a command are

$ mycommand -h      (or --help)
$ man mycommand

also you can use 'man mycommand' in google's search field :)

Gribouillis 1,391 Programming Explorer Team Colleague

About python 3, you should be able to install it with yum install python3 .

Gribouillis 1,391 Programming Explorer Team Colleague

Try this command

python -c "import os, idlelib; execfile(os.path.join(os.path.split(idlelib.__file__)[0], 'idle.py'))"&

It should be a multiplatform command. If you can't import idlelib, it means that you must install the tkinter package.
Note that this simpler command also works

python -c "from idlelib import idle"&
Gribouillis 1,391 Programming Explorer Team Colleague

The id retrieval idea looks good. Il give it a try. Maybe it would be possible, that knowing the object id, to retrieve its name.
Although it seems to be a practical way to solve my problem, I don't want to pass the name of the object to the instance itself as an argument because this is what I'm doing now.
The idea of a dictionary to hold the names and the objects id also sounds good. But I am curious about my original question: it is possible, from inside an instance of a class to retrieve the instance name? Let's say I've instantiated x as an instance of the class MyClass(); It is possible from inside x to retrieve "x" which is the name of the instance as a string?

Best regards,

PTS

The instance doesn't have a name. When you write

x = MyClass()

x is not the name of the instance, x is a variable name in the local namespace, which is temporarily bound to your instance. If you call func(x) and func is defined by

def func(item):
  print(item)

func manipulates the same instance but it's bound to the local variable named 'item', so it is the same instance, but a different name.
If you need to identify your instance with a string, there are only 2 ways: either you explicitely create a name for the instance, or you build a name based on the instance's id. For example, you can build …

vegaseat commented: good comment +12
Gribouillis 1,391 Programming Explorer Team Colleague

With python 2, don't use input, use raw_input, which returns a string, and convert the result to an int. Here is a modified version which runs (but you didn't choose the fastest way to solve the problem :) )

import sys
if sys.version_info < (3,):
    input = raw_input
    
array = []
no_lines = 0
no = 0 
j=0 
div_no=0
no_lines, no = [int(x) for x in input().split()]
temp = no_lines 
while(no_lines>0) :
	i=0 
	i = int(input())
	array.append(i)
	no_lines = no_lines - 1
j=0

while(j<temp) :
	if array[j] % no == 0 :
		div_no=div_no+1 
	j = j+1

print(div_no,"\n")
Gribouillis 1,391 Programming Explorer Team Colleague

The simplest idea would be to give your instance a member 'name' and pass this name when you create the instance, for example

class MyClass(object):
    def __init__(self, name, *args):
        self.name = name

my_instance = MyClass("GuidoVanRossum")
Gribouillis 1,391 Programming Explorer Team Colleague

Another version

from graphics import *

def item_n_price(win, i, items, prices):
    z = 50 * i
    center = Point(50,50+z)
    label = Text(center, "Item >>")
    label.draw(win)
    input = Entry(Point(170,55+z), 20)
    input.setText("item")
    input.draw(win)
    items.append(input)
    center = Point(350,50+z)
    label = Text(center, "Price >>")
    label.draw(win)
    input = Entry(Point(420,55+z), 6)
    input.setText("0.00")
    input.draw(win)
    prices.append(input)
    
def main():
    win = GraphWin("WalMart Receipt", 600, 900)

    #Title
    center = Point(300,20)
    label = Text(center, "WalMart Receipt Maker")
    label.draw(win)
    label.setSize(20)
    items = []
    prices = []
    
    for i in range(15):
        item_n_price(win, i, items, prices)


    #print receipt button
    rect5 = Rectangle(Point(240,800), Point(360,850))
    rect5.draw(win)
    center5 = Point(300,825)
    button = Text(center5, "Print Receipt")
    button.draw(win)
    button.setSize(10)
    button.setFill('Orange')

    win.getMouse()
    
    win2 = GraphWin("WalMart Receipt", 600, 900)

    #Title 2
    center = Point(300,20)
    label22 = Text(center, "WalMart Receipt")
    label22.draw(win2)
    label22.setSize(20)
    
    output = Text(Point(170,55), "")
    x = eval(prices[1].getText())
    output.setText(x)
    output.draw(win2)
    
    win2.getMouse()
    
    
    
main()
Gribouillis 1,391 Programming Explorer Team Colleague

I found some documentation here http://www.geospatialtraining.com/Newsletter/Spring%202006/GeoprocessorCursorObjects.htm. You should rewrite the loop structure like this

rows = gp.searchcursor(inputFC)
row = rows.next()

while row:
  ...
  row = rows.next()
...

(or perhaps 'next' should be Next ?). You can still use the template trick. I wonder why they didn't make the searchcursor object iterable. It would be more pythonic.

Gribouillis 1,391 Programming Explorer Team Colleague

I would rather write it this way, using a multiline template and the string % operator

# Script to iterate N,S,E,W coordinates of extent rectangles in 60x60 grid
# and write iterations of 20 lines of code to Region.kml


# IMPORT ARCGISSCRIPTING MODULE
import arcgisscripting, os

template = """  <NetworkLink>
        <Region>
            <LatLonAltBox>
                <north>%(top)s</north>
                <south>%(bott)s</south>
                <east>%(right)s</east>
                <west>%(left)s</west>
                <minAltitude>0</minAltitude>
                <maxAltitude>0</maxAltitude>
            </LatLonAltBox>
            <Lod>
                <minLodPixels>1024</minLodPixels>
                <maxLodPixels>-1</maxLodPixels>
            </Lod>
        </Region>
        <name>%(poly)s</name>
        <Link>
            <href>%(poly)s.kmz</href>
            <viewRefreshMode>onRegion</viewRefreshMode>
        </Link>
        </NetworkLink>
"""

# CREATE GEOPROCESSOR
gp = arcgisscripting.create(9.3)

# TARGET FEATURE CLASS AND VARIABLES
gp.Workspace = r'c:\craig\Working\07282010'
inputFC = 'grid_60_bound_cm.shp'

# OUTPUT FILE
Region = open(r'C:\Craig\Working\07282010\Region.kml','w')

# BEGIN THE LOOP
for row in gp.searchcursor(inputFC):
    left = row.getValue("Left")
    right = row.getValue("Right")
    top = row.getValue("Top")
    bott = row.getValue("Bott")
    polynum = 1
    poly = "poly" + polynum
    Region.write(template % locals())
    polynum = polynum + 1
    row = rows.next()
Region.close()
Gribouillis 1,391 Programming Explorer Team Colleague

Thanks a lot for the code.! Working very well.

Is there any other.. simple way to do it. as a beginner it seems bit complicated to rewrite the code on own.

Helps greatly appreciated!

Yes, you could write it this way

def records(filename):
    for line in open(filename):
        index = line.find('\t')
        word = line[:index]
        yield (word, line)

D1 = dict(records('testfile1.txt'))

for word, line in records('testfile2.txt'):
    if word in D1:
        # etc... do something

You should learn about the yield statement if you don't know it yet. It is very powerful !

Gribouillis 1,391 Programming Explorer Team Colleague

Try this code, which uses list comprehensions

from pprint import pprint

def records(filename):
    """generates pairs (word, line) from the file, where word is the first column"""
    return ((line[:line.find('\t')], line) for line in open(filename))

L1 = list(records('testfile1.txt'))
D1 = dict(L1)

assert(len(L1) == len(D1)) # check that keys are unique in the first file.

pprint(D1)

result = [(word, line) for (word, line) in records('testfile2.txt') if word in D1]

pprint(result)
Gribouillis 1,391 Programming Explorer Team Colleague

You should create a list for your owner_id:

class sendbackcurricula(app.page):
    def GET(self):
        query = models.Curricula.query.all()
        map = dict()
     	for x in query:
            x = x.to_dict()
            key, title = x['owner_id'], x['title']
            if key not in map:
                map[key] = list()
            map[key].append(title)
        return json.dumps(map)

This should return {"email": ["Course1", "Course2", "Course3"] }.

Gribouillis 1,391 Programming Explorer Team Colleague

Also check this google code project http://code.google.com/p/prettytable/ .

Gribouillis 1,391 Programming Explorer Team Colleague

I know about re-raising, but then it would still terminate the program.

If your program encounters an unexpected exception, the best thing to do is usually to terminate the program, because your program's data were modified in an unpredictable way.

It is not a universal rule however. For example, if your program is an editor, you may want to save the current files somewhere before crashing with traceback. In such cases, a bare except: with re-raise could be the best solution.

Gribouillis 1,391 Programming Explorer Team Colleague

You can also do this

print w.fill('WIP will create Backup, Resized and Watermarked folders to store the original, resized and watermarked pictures. It will overwrite them if they already exists. Are you sure you want to continue (y/n)?')
overwrite = raw_input('> ')
while overwrite not in ('y', 'n'):
    overwrite = raw_input("Please, answer 'y' or 'n': ")
if overwrite == 'y':
    # etc
Gribouillis 1,391 Programming Explorer Team Colleague

First avoid 'list' as a variable name since it is the name of a builtin type. There are at least 2 ways to do it

old_list = ["a","b","c","d"]

new_list = list()
for x in old_list:
    new_list.append(ord(x))

or, using 'list comprehension syntax'

old_list = ["a","b","c","d"]
new_list = [ ord(x) for x in old_list ]
Gribouillis 1,391 Programming Explorer Team Colleague

You can use a list

FrameFolders = [(modsDir,"Mods"), (Packages,"Packages"), (DCCache,"DCCache")]

for path, name in FrameFolders:
    if not os.path.isdir(path):
        Ok = False
        print "%s folder does not exist. Creating..." % name
        #Just using % path prints the ENTIRE directory name
        os.mkdir(path)

        if os.path.isdir(path): print "Folder %s sucessfully created.\n" % name
        else: raise NotFoundError("Could not create %s folder!" % name)
Gribouillis 1,391 Programming Explorer Team Colleague

Good news.

Gribouillis 1,391 Programming Explorer Team Colleague

There is no reason to avoid it, it's a standard construct in python which means 'repeat indefinitely'. You can use while True: which is semantically better, but it doesn't change much.

Gribouillis 1,391 Programming Explorer Team Colleague

re.search returns a 'match object' or None. Follow this example

>>> mo = re.search(r"b\w+", "'Give me bacon and eggs,' said the other man.")
>>> mo
<_sre.SRE_Match object at 0x7f90947e2e68>
>>> mo.group(0)
'bacon'
Gribouillis 1,391 Programming Explorer Team Colleague

I don't use sqlite3, but the answer is in the doc http://docs.python.org/library/sqlite3.html?highlight=sqlite3#sqlite-and-python-types . You should be able to use unicode directly in sqlite3 (as in most python modules)

Gribouillis 1,391 Programming Explorer Team Colleague

I have a good link about unicode http://farmdev.com/talks/unicode/

Gribouillis 1,391 Programming Explorer Team Colleague

If f is a fraction, you can use f.denominator and f.numerator. See also this snippet http://www.daniweb.com/code/snippet223956.html.

Gribouillis 1,391 Programming Explorer Team Colleague

try

from reportlab.graphics.barcode.usps4s import USPS_4State
print USPS_4State('1234987654321', '01234567891').barcodes
Gribouillis 1,391 Programming Explorer Team Colleague

You should probably write

print usps4s.USPS_4State('1234987654321', '01234567891').barcodes

or

from usps4s import USPS_4State
print USPS_4State('1234987654321', '01234567891').barcodes
Gribouillis 1,391 Programming Explorer Team Colleague

I managed adding an element this way

from lxml import etree
from lxml.builder import ElementMaker


E = ElementMaker()

DOC = E.doc
PERSON = E.activity
TITLE = E.title
DESC = E.desc
IDNO = E.idno
def NAME(*args):
    return {"name":' '.join(args)}

file = "xmltestthing.xml"
parser = etree.XMLParser(remove_blank_text=True) # see http://codespeak.net/lxml/FAQ.html#parsing-and-serialisation
thing1 = etree.parse(file, parser)

person = PERSON( NAME("Dani"),
    DESC ("the queen"),
    IDNO ("5")
    )

doc = thing1.getroot()
doc[-1].addnext(person)
print(etree.tostring(doc, pretty_print=True))

""" My output -->
<doc>
  <activity name="John">
    <desc>germedabob</desc>
    <idno>2</idno>
  </activity>
  <activity name="Dani">
    <desc>the queen</desc>
    <idno>5</idno>
  </activity>
</doc>
"""
happymadman commented: Thanks +2
Gribouillis 1,391 Programming Explorer Team Colleague

Well, here is an example

class Thingy(object):
    instances = []

    def __init__(self):
        self.instances.append(self)

def waste_time_and_memory():
    t = Thingy()

for i in range(5):
    waste_time_and_memory()

print Thingy.instances

""" My output -->
[<__main__.Thingy object at 0x7f0581777c50>, <__main__.Thingy object at 0x7f0581777c90>, <__main__.Thingy object at 0x7f0581777cd0>, <__main__.Thingy object at 0x7f0581777d10>, <__main__.Thingy object at 0x7f0581777d50>]
"""

The main problem is that Thingy objects are immortal unless you empty the list periodically.

danielochicaiza commented: Just joined to say thanks for this workaround. I think I will continue finding nice solutions in this place. +0
Gribouillis 1,391 Programming Explorer Team Colleague

To test if a path is a file, you can use

import os
os.path.isfile(path) # is it a file ?
os.path.isdir(path) # is it a folder ?
os.path.exists(path) # does it exist in the file system ?
Gribouillis 1,391 Programming Explorer Team Colleague

In XML, there are special codes for special characters. I write french all the time,and accented characters are encoded in xml files. For example "à" is encoded "&#224;". My solution to generate xml is to use the lxml module. Here is an example in idle

>>> import lxml.etree
>>> x = lxml.etree.fromstring("<root>J'habite à Bordeaux.</root>")
>>> print lxml.etree.tostring(x)
<root>J'habite & #224; Bordeaux.</root> # <-- no space between & and #

The method 'tostring' in lxml escapes accented characters.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you should write this at the top of your file

<?xml version="1.0" encoding="UTF-8"?>
Gribouillis 1,391 Programming Explorer Team Colleague

Because the syntax

p = [ expression ] * 3

evaluates the expression once and creates a list of 3 references to the result of this evaluation. You can use

p = [ expression for i in range(3) ]

to evaluate the expression thrice and put the results in a list.
Try

p = [[x] + [0] * y for i in range(z)]

Under python 2, you can use xrange instead of range to gain a little speed.

Gribouillis 1,391 Programming Explorer Team Colleague

If you don't want derived objects at all, a proper way would be to write a class hierearchy to initialize your objects. For example

class Parser:
  def __init__(self, var):
    initialize = choose_initializer(var)
    initialize(self, var)

class Initializer:
  def __init__(self, parser, var):
    pass

class TypeAInitializer(Initializer):
  def __init__(self, parser, var):
    Initializer.__init__(self, parser, var)
    # do whatever you want here

class TypeBInitializer(Initializer):
  def __init__(self, parser, var):
    Initializer.__init__(self, parser, var)
    # do whatever you want here

The sole purpose of Initializers would be to initialize Parser instances depending on the file type.

Gribouillis 1,391 Programming Explorer Team Colleague

The strange thing is not python's behavior, but your idea of initializing a base class object using the __init__ method of a subclass. The purpose of __init__ methods is to build an object, and therefore, the __init__ method of class child2 should be used to create a child2 instance. Usually in python, the constructor (__init__ method) of a subclass invokes the constructor of the parent class like this

class parent:
  array = [1]
  str = "parent"
  def __init__(self, var):
    self.array.append(var)

class child1(parent):
  def __init__(self, var):
    parent.__init__(self, var)
    self.str = "child1"

class child2(parent):
  def __init__(self, var):
    parent.__init__(self, var)
    self.str = "child2"

Following this pattern, if you want to create a person initialized with child1's constructor, the best way is to create a child1 instance. For example, you could write a function

def new_person(var):
  if var == 1:
    return child1(var)
  elif var == 2:
    return child2(var)
  else:
    return parent(var)

person = new_person(2)

Now the person returned in the previous call is a child2 instance, and as such it's also a parent instance, which means that you can use it in every function which expects a parent argument. Trying to convert it to a true 'parent' object is a strange and unnecessary thing (in fact python allows it, you could write person.__class__ = parent , but don't do that, it's bad programming style).

Gribouillis 1,391 Programming Explorer Team Colleague

You can see the difference with the two other forms of call here

>>> sp.call("ls -l", shell=True)
0. _execvpe('/bin/sh', ['/bin/sh', '-c', 'ls -l']): # call, line 344 in os.py
>>> sp.call(["ls",  "-l"])
0. _execvpe('ls', ['ls', '-l']): # call, line 344 in os.py
Gribouillis 1,391 Programming Explorer Team Colleague

I think the problem is that (in unix), if you invoke subprocess.call or subprocess.Popen without the switch shell = True , the first argument must be either the name of the command to execute, without arguments, like sp.call("ls") or a list of arguments like sp.call(["python", "myfile.py"]) . With shell=True , the first argument may be a string containing command line arguments, like sp.call("python myfile.py", shell=True) .
In your case, the module probably looked for a command named "python myfile.py" , and since there is no file with this name, it raises OSError. Example:

>>> sp.call("ls -l")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/subprocess.py", line 470, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.6/subprocess.py", line 621, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1126, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
>>> sp.call("ls -l", shell=True)
total 116
-rw-r--r-- 1 eric eric  4085 2010-06-06 11:13 cube10.tm
0
>>> sp.call(["ls", "-l"])
total 116
-rw-r--r-- 1 eric eric  4085 2010-06-06 11:13 cube10.tm
0

Using a python tracing module, I obtained this

>>> sp.call("ls -l")
0. _execvpe('ls -l', ['ls -l']): # call, line 344 in os.py

which means that os._execvpe was called by the subprocess module with a (bad) file argument 'ls -l' .

Gribouillis 1,391 Programming Explorer Team Colleague

Hi,

I'm trying to make a frontend for the compile module in python.

Everything works just right, except when the file has mistakes in the code that lead to a syntax error.

It does raise the invalid syntax error in the terminal, but instead of executing the block inside the except statement, it goes on to the else block. look:

try:
        file = t1.get()
        py_compile.compile(file)
    except IOError:
        tkinter.messagebox.showerror("Error", "File not found")
    except UnicodeDecodeError:
        tkinter.messagebox.showerror("Error", "This is not python code")
    except SyntaxError:
        tkinter.messagebox.showerror("Error", "There is a syntax error in the code")
    else:
        time.sleep(2)
        tkinter.messagebox.showinfo("¡Successfully compiled!", "The file \n(%s)\n was compiled successfully" %file)

According to the py_compile's module doc, it seems that you should call py_compile.compile(file, doraise=True) and it should raise a py_compile.PyCompileError and not a SyntaxError.

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest you try these 2 ways to run the call

sp.call('python /root/regression/tests/infra/tcp_test_suite/infra_nexus_correct_mul_tcp_and_udp_pns.py',
  shell=True)

# or

sp.call(['python',
        '/root/regression/tests/infra/tcp_test_suite/infra_nexus_correct_mul_tcp_and_udp_pns.py'])

subprocess.call and subprocess.Popen behave have 2 syntaxes depending on their first argument being a string or a list of strings (see the documentation of module subprocess).

Gribouillis 1,391 Programming Explorer Team Colleague

Hi,
thanks very much for the reply.

Using your inputs I have been able to produce now some good scripts.
But still in some other kind of scripts I am facing issues.
I am running the scripts in this following fashion:

script1--->script2(has Command class)---spawn a process to run command-->command
Now the above works perfectly.
But the other scripts:
script1--->script2(has Command class)--spawn a process to run command--> command
this command further spawns processes on remote machines
command---use scp and do ssh on remote machines----->Two processes one on each remote machine.
Now on the same host the pipe created is responsible for sharing of the data between the parent and the child using the subprocess. But the pipe obvously doesnot work when the remote machines are involved. Can you please suggest a work around for this?
os.system obviously works. But it doesnot return any return value. If you could also suggest why os.system works it would be of immense value for me.

Regards,
Prashanth

I don't understand which pipe you're talking about. The problem could be that the Command class communicates through the child process' stdin and stdout. I forgot to mention an alternative if you're only interested in the return code, try

import subprocess as sp
result = sp.call("./script2", shell=True)
Gribouillis 1,391 Programming Explorer Team Colleague

Hi thanks for the reply.
Based on your reply I wrote a script that contains the calling of the command "random" within the script itself. And it worked. What I did next was in place of the command "random" I gave ftp script as the argument. But because of network problems I could not test the FTP script.
So if I want to return the success or failure code from the FTP script, what changes I would be needed to make to the following part of the code? If I return some value from the FTP script, then will process.returncode take care of returning this return value from the FTP script?

self.failed = process.returncode
return self

@property
def returncode(self):
return self.failed

end quote.

If you are using the snippet's Command class, you don't need to change anything. Simply copy and paste the Command class to your program (after clicking 'Toggle Plain Text' in the post), then write

com = Command("./scrip1").run()
result = com.returncode
com = Command("./script2").run()
result = com.returncode

etc, or even simpler

result = Commmand("./script1").run().returncode

if you only need the return code in the Command object.

Gribouillis 1,391 Programming Explorer Team Colleague

I once wrote a small code snippet that does this and more: http://www.daniweb.com/code/snippet257449.html

Gribouillis 1,391 Programming Explorer Team Colleague

An more common alternative is

>>> L = ['cmds.sphere(n = "aBall", r = 1)', 'cmds.sphere(n = "aBall", r = 2)', 'cmds.sphere(n = "aBall", r = 3)', 'cmds.sphere(n = "aBall", r = 4)', 'cmds.sphere(n = "aBall", r = 5)', 'cmds.sphere(n = "aBall", r = 6)']
>>> import cPickle as Pickle
>>> s = Pickle.dumps(L) # list to string
>>> s
'(lp1\nS\'cmds.sphere(n = "aBall", r = 1)\'\np2\naS\'cmds.sphere(n = "aBall", r = 2)\'\np3\naS\'cmds.sphere(n = "aBall", r = 3)\'\np4\naS\'cmds.sphere(n = "aBall", r = 4)\'\np5\naS\'cmds.sphere(n = "aBall", r = 5)\'\np6\naS\'cmds.sphere(n = "aBall", r = 6)\'\np7\na.'
>>> print Pickle.loads(s) # string to list
['cmds.sphere(n = "aBall", r = 1)', 'cmds.sphere(n = "aBall", r = 2)', 'cmds.sphere(n = "aBall", r = 3)', 'cmds.sphere(n = "aBall", r = 4)', 'cmds.sphere(n = "aBall", r = 5)', 'cmds.sphere(n = "aBall", r = 6)']
Gribouillis 1,391 Programming Explorer Team Colleague

It's not caught because the line session = smtplib.SMTP(smtpserver) is out of the try..except statement !

Gribouillis 1,391 Programming Explorer Team Colleague

Nah that didnt work, same issue occuring

If the issue is the deprecation warning, it's not an issue. It's only a warning.

Gribouillis 1,391 Programming Explorer Team Colleague

If you only want to catch the exception and let your code still run, you only need to write

import socket

def email():
   global mssg
   session = smtplib.SMTP(smtpserver)
   if authrequired:
      session.login(smtpuser, smtpass)
   try:
      session.sendmail(SENDER, RECIPIENTS, mssg)
      session.quit()
   except socket.error:
      logit('server down')

Don't write except: statements without targeting at least one specific exception class. It's much better to let unexpected errors propagate. When they occur, you can still add a new except statement if needed. An opaque except hides errors for future debugging sessions.

Gribouillis 1,391 Programming Explorer Team Colleague

Python has no problem accepting by binary definition of my relationship, but maybe it is not really < but between, even between is little strange name also for two variables, it should be mayby lower_dimension_or_all_less_or_equal but that is little unconvenient name to type correctly many times.

It does have weakness that it is both neither lexinographic nor numeric order for letter sequences.

def order(a,b):
    try:
        return len(b)>len(a) or all(tuple(a[i]<=b[i] for i in range(len(a))) )
    except:
        return b>=a  ## no len i.e. zero dimensions

for i in ((( 0,0,0),(1,1,1) ),
          ((0,0),(1,1)),  ## (0,0)<=(1,1)<=(2,2)
          ((1,1),(2,2)),  ## both True => desired result
          ((0,0),(1,1)),  ## (0,0) <= (1,1) <= (2,0)
          ((1,1),(2,0)),  ## gives False => desired result
          ('ab','cd'),
          ('ab','aa'),
          ('ab','abc'),
          ('ab','b'),  ## different than normal <
          ('aac','ada'), ## different than normal <
          ('10','12'),
          (10,100),
          ('10','100')):
    print i,order(*i)

All right, you built a binary order relation, but it's only a partial order:

def order(a,b):
    try:
        return len(b)>len(a) or all(tuple(a[i]<=b[i] for i in range(len(a))) )
    except:
        return b>=a  ## no len i.e. zero dimensions

for i in (
    ("ab", "ba"), # False
    ("ba", "ab"), # False
    ):
    print i, order(*i)

The drawbacks of this are that you can't easily use it to sort elements, also that this relation is probably seldom useful and worse, if you define <= like this, you must give a new name to lexicographic order (which is very useful, for exemple in dictionaries).

Gribouillis 1,391 Programming Explorer Team Colleague

Point one
You can do comparison with tuples of numbers in Python

>>> (0,0)<(1,1)<(2,2)
True
>>> (0,0)<(1,1)<(2,0)
True
>>>

First is fine for me, but I am not agreeing with the second one. Why?

If a<b<c, then number b is between a and c in the number line.

(x,y) is point in two dimensional plane. For me the natural extension of < is for it to mean that

(a,b) < (c,d) < (e,f)

means that (c,d) is inside a square whose corners are (a,b) and (e,f). That is same as

a<c<e and b<d<f

The problem with your 'natural extension' of < to points in the plane is that you are defining a ternary relation P < Q < R and not a binary relation P < Q. The 'less than' relation is binary. Mathematically, it is an order relation (see http://en.wikipedia.org/wiki/Order_theory) which satisfies (much more) natural properties that you would expect from an ordering relation, for example P < Q and Q < R imply that P < R. In python (and also in mathematics), a < b < c means (a < b and b < c).

Python's ordering for tuples is called lexicographic order in mathematics. It is consistent with the usual ordering of words, for example tuple("hello") < tuple("world") , and it is also commonly used to order points in the plane. I'm afraid that your ternary relation can not be used to build a coherent binary relation.

vegaseat commented: good explanation +10
Gribouillis 1,391 Programming Explorer Team Colleague

It works perfectly!!!! Thank you so much:-)
What do you want for it? I can pay you via my paypal account, would that work for you?

Best regards, Casper:-)

It's ok. It's only a small exercise for most members of the python forum :)

Also, there is a little theoretical problem: your time samples are not uniformly distributed over the 1 second time intervals, so are you sure that a raw averaging is meaningful ? Shouldn't we design a special formula for the average over 1 second ?

vegaseat commented: nice way to handle this +10
Gribouillis 1,391 Programming Explorer Team Colleague

Ok, I renamed your file inputfile.txt and the code below produces an outputfile.txt containing the averages.

# averages.py
from itertools import groupby

def gen_averages(input_triples):
    for second, triples in groupby(input_triples, lambda triple: int(triple[2])):
        a, b = 0.0, 0.0
        n = 0
        for x, y, t in triples:
            a += float(x)
            b += float(y)
            n += 1
        yield (a/n, b/n, second)

def gen_input(textfile):
    f = open(textfile)
    f.readline()
    for line in f:
        triple = tuple(float(x) for x in line.strip().replace(",", ".").split())
        assert(len(triple) == 3)
        yield triple

def compute_averages(inputfile, outputfile):
    with open(outputfile, "w") as out:
        for triple in gen_averages(gen_input(inputfile)):
            out.write("{0:<15.2f}{1:<15.2f}{2:d}\n".format(*triple))
if __name__ == "__main__":
    compute_averages("inputfile.txt", "outputfile.txt")
    print "done (see the output file)"

To run the program, you have 2 solutions: either you start IDLE (python gui), then you open averages.py (the name of the program) and you select 'Run Module' in idle's run menu, or you open a windows cmd shell, you go to the folder containing the program and you type python averages.py on the command line.

The program must be modified if you want to read and write excel files instead of text files.

Gribouillis 1,391 Programming Explorer Team Colleague

As a starting point, here is a function which computes the averages for a sequence of values (parameter A, parameter B, time). The assumption is that the input data are sorted by time. Try to run it and see if it does what you want

from itertools import groupby

def gen_averages(input_triples):
    for second, triples in groupby(input_triples, lambda triple: triple[2]):
        a, b = 0.0, 0.0
        n = 0
        for x, y, t in triples:
            a += float(x)
            b += float(y)
            n += 1
        yield (a/n, b/n, second)

def test_me():
    data = [
        (1, 1, 364),
        (2, 4, 365),
        (3, 5, 365),
        (8, -1, 365),
        (3, 2, 366),
        (1, 1, 366),
        (0, 0, 367),
    ]
    for triple in gen_averages(data):
        print(triple)

if __name__ == "__main__":
    test_me()

""" My output -->
(1.0, 1.0, 364)
(4.333333333333333, 2.6666666666666665, 365)
(2.0, 1.5, 366)
(0.0, 0.0, 367)
"""

It only remains to read the data in the excel files and perhaps write the output to other excel files. We can use the modules xlrd xlwr xlutils for this.
What are your OS and your version of python ? Also, can you attach an excel file (or a part of it) to a post (you may have to zip it first) ?

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest to add a random number in the tuples being sorted

from random import random

def test(words):
    t = []
    for word in words:
       t.append((len(word), random(), word))

    t.sort(reverse=True)

    res = []
    for length, rand, word in t:
        res.append(word)
    print res
test(['hello','my','friend','Peter'])