Gribouillis 1,391 Programming Explorer Team Colleague

Indeed i have a lot to learn about python but i have a question why replace function is not something what we could use?

i tried using this code

f=open("Te2.csv","w")
s=open("Te.csv").read()
s=s.replace('{','')
s=s.replace('}','')
s=s.replace('(','')
s=s.replace(')','')
s=s.replace("'","")
s=s.replace(":",",")
f.write(s)
f.close()

readFile = open("Te2.csv")
lines = readFile.readlines()
readFile.close()
w = open("Te2.csv",'w')
w.writelines([item for item in lines[:10]])
w.close()

and i came to se same result writen in the new file Te2

Acatari, Acatari, 0.0,
 Acatari, Acis, 183.1984286216621,
 Acatari, Adamclisi, 372.52641231771526,
 Acatari, Adjud, 200.36162156879055,
 Acatari, Afumati, 251.49065927408915,
 Acatari, Agas, 121.63622537704428,
 Acatari, Agigea, 409.27692015889204,
 Acatari, Aiud, 72.63968108608063,
 Acatari, Alba Iulia, 92.8322036095662,
 Acatari, Albac, 127.94211546456722,

First it's not the same output, there are unwanted white space and commas, but there is a deeper reason, we manipulate abstract data, we have a series of records, each record consisting of 2 names and a numerical value, and with this we can read and write csv files. This way of thinking gives better results than unstructured and unmaintanable string manipulations. Let's say there is a good way to do it and a bad way. Writing small helper functions is the good way IMHO.

Gribouillis 1,391 Programming Explorer Team Colleague

I tried to write the first function as this :

TEST_FILE = "T3.csv"
def get_entries(matrix):
    with open(TEST_FILE,"w") as fil:
        for name1, name2, distance in sorted(distance_matrix(coords_list)):
            fil.write("{na1}, {na2}, {dist}\n".format(na1 = name1, na2 = name2, dist = distance))

if __name__ == "__main__":
    get_entries(matrix)

Where T3 is the file generated after i run the code for the matrix with just 3 cities

Using this code get an error like this:
for name1, name2, distance in sorted(distance_matrix(coords_list)):
ValueError: need more than 2 values to unpack

You don't understand, functions must have precise parameters and return values. For get_entry(), you don't need a file. First look at the content of the matrix (if you are using python 3, replace iteritems() with items())

def print_one_item(matrix):
    """Print one item from the matrix generated by distance_matrix()
    This function prints: (('Mestecanis', 'Recea'), 396.19161575474294)"""
    for item in matrix.iteritems():
        print( repr(item) )
        return # exit the loop

Running this function prints (('Mestecanis', 'Recea'), 396.19161575474294) . You see that the matrix items are a pair (a tuple of length 2) containing a pair of cities and a number. To write get_entries() we only need to transform these tuples into triples

def get_entries(matrix):
    """Take a distance matrix and returns a ordered list of tuples (city, city, distance)"""
    result = list()
    for item in matrix.iteritems():
        key, value = item # key is like ('Mestecanis', 'Recea'), value like 396.19161575474294
        cityA, cityB = key # cityA is a string like 'Mestecanis', and cityB 'Recea'
        entry = (cityA, cityB, value) # a triple like …
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest button.configure(text="new text") . Example:

from Tkinter import *

class App:
   def __init__(self, parent):
    self.myParent = parent
    self.fm = Frame(parent, width=400, height=300)
    self.fm.pack_propagate(0) # to keep the frame size
    self.fm.pack()
    
    self.index=0
    self.btnBlue = Button(self.fm, text = "Blue %d" % self.index, command=self.make_blue)
    self.btnBlue.pack()

   def make_blue(self):
    self.fm.configure(bg="blue")
    self.index += 1
    self.btnBlue.configure(text = "Blue %d" % self.index)

root = Tk()
root.title ("Color Option")
app = App(root)
root.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

So if i understood it wright:
I use in Output.csv jut 3 cities
run the code
I use the replace function to have my file (Te.csv)in the format

name1, name1, 0
name1, name2, dist
name1, name3, dist

After that i did not really understood what i have to do.
?

The replace() function is not the appropriate tool. You must learn how to transform data read in a file into data usable by your program. Write the following functions

  • A function get_entries(matrix) which takes our matrix and return an ordered list of python tuples ("name1", "name2", distance) . These tuples are very easy to manipulate for python. The distance should be a floating point number.
  • A function entry_to_line(entry) which takes a tuple as above and returns a string "name1, name2, distance\n" .
  • A function line_to_entry(line) which takes such a string as argument and returns a python tuple tuple ("name1", "name2", distance). Here again, the distance should be a float.

Use these functions to create a Te.csv with the above format instead of what we have written before.

Gribouillis 1,391 Programming Explorer Team Colleague

I will read the about string formatting but how could i alter the code so that it will read even for those 3cities write lines in this format. I should define the matrix in another way?

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

?

I think you should first write a csv file in the format

name1, name1, 0
name1, name2, dist
name1, name3, dist

This can be done by replacing the pprint(matrix, ff) by a a few lines of code (use the list sorted(matrix.items()) . Once you have this csv file, your code could easily read data in this file to produce the second format.

Gribouillis 1,391 Programming Explorer Team Colleague
name1    name2     name3
name1    0      distA     distB
name2  DistC     0        DisD
name3  DiistF   DistV      0

but is there any posibility to write in this format in another file?

Yes it is possible to write in this format in a file. Notice that the width of each column will be determined by the length of the town's name.

Start by writing only the 2 first lines to see if it is feasable. You must learn a bit of string formatting, read a few posts of this code snippet http://www.daniweb.com/code/snippet232375.html .

The file should be a .txt, or may be even a .csv if you add commas.

Gribouillis 1,391 Programming Explorer Team Colleague

the matrix i wanted to print should have looked like this
name1 name2 name3
name1 0 distA distB
name2 DistC 0 DisD
name3 DiistF DistV 0

i want to print it in shell like this and write it in a file too.

There are 733 towns, some with very long names, while a typical shell line has 80 characters. I think your format is not realistic :)

Gribouillis 1,391 Programming Explorer Team Colleague

The format of the data in the Output.csv is name, longitude, latitude. I remember that in some of my fist posts i might have used the wrong format.I am sorry.

I tried to repair my code using the advice you gave but this code

from math import sin as sin, cos as cos, acos as acos, radians as radians

ff=open("Te.csv","w")

coords_list = list()
for line in open("Output.csv"):
    line = line.strip()
    if line:
        name, lon, lat = line.split(",")
        lon = float(lon) # convert string to float value
        lat = float(lat)
        coords_list.append( (name, lon, lat) )
    print line
        
def distance_matrix(coords_list):
    '''Calculates the distances (in km) between any two cities based on the formulas
    c = sin(lati1)*sin(lat2)+cos(lon1-lon2)*cos(lat1)*cos(lati2)
    d = EARTH_RADIUS*Arccos(c)
    where EARTH_RADIUS is in km and the angles are in radians.
    Source: http://mathforum.org/library/drmath/view/54680.html
    This function returns the matrix.'''
    
    matrix={}
    EARTH_RADIUS = 6378.1
    #Populate the matrix.
    for (name2,lon2,lat2) in coords_list:
        for (name1,lon1,lat1) in coords_list:
            if name1!=name2:
                #if name1==name2, then c will be equal to 1, and acos(c) will fail
                c = sin(radians(lat1)) * sin(radians(lat2)) + \
                    cos(radians(lon1-lon2)) * \
                    cos(radians(lat1)) * cos(radians(lat2))
                distance = EARTH_RADIUS * acos(c)
                matrix[name1,name2] = distance
            else:
                #Case when name1==name2...                                               
                matrix[name1,name2] = 0.0
distance_matrix(coords_list) # call the function
from pprint import pprint
pprint(matrix, ff)
ff.close()

will give this error
Traceback (most recent call last):
File "C:\Users\gg\Desktop\t.py", line 40, in <module>
pprint(matrix, ff)
NameError: name 'matrix' is not defined

So if you could tell me what is wrong i would be grateful. I am in the …

Gribouillis 1,391 Programming Explorer Team Colleague

I will try to make my own code work but meanwhile comming back to the name of the thred i now want to generate the distance matrix for my cities.

I tried to use the next code for generating it:

from math import sin as sin, cos as cos, acos as acos, radians as radians

coords_list=open("Output.csv").read()
print coords_list
ff=open("Te.csv","w")
        
def distance_matrix(coords_list):
    '''Calculates the distances (in km) between any two cities based on the formulas
    c = sin(lati1)*sin(lati2)+cos(longi1-longi2)*cos(lati1)*cos(lati2)
    d = EARTH_RADIUS*Arccos(c)
    where EARTH_RADIUS is in km and the angles are in radians.
    Source: http://mathforum.org/library/drmath/view/54680.html
    This function returns the matrix.'''
    
    matrix={}
    EARTH_RADIUS = 6378.1
    #Populate the matrix.
    for (name2,longi2,lati2) in coords_list:
        for (name1,longi1,lati1) in coords_list:
            if name1!=name2:
                #if name1==name2, then c will be equal to 1, and acos(c) will fail
                c = sin(radians(lati1)) * sin(radians(lati2)) + \
                    cos(radians(longi1-longi2)) * \
                    cos(radians(lati1)) * cos(radians(lati2))
                distance = EARTH_RADIUS * acos(c)
                matrix[name1,name2] = distance
            else:
                #Case when name1==name2...                                               
                matrix[name1,name2] = 0.0
    return matrix
    print matrix
    ff.write(matrix)
ff.close()

But it will only print the file(Output.csv) in shell without actualy creating the matrix.
So what is wrong with this code?
Again i am sorry if i asksome silly question but my knowledge of python is in the begining

The block def distance_matrix(coords_list): ... defines a function distance_matrix() but does not execute that function. A function is executed when it is called, so replace the last line by

distance_matrix(coords_list) # call the function
ff.close()

There are other problems. The coord_list should be a list …

Gribouillis 1,391 Programming Explorer Team Colleague

I think you create an array like this

arr = (pyMyStructure * 4)()

but I'm a beginner in ctypes. Perhaps you can pass ctypes.pointer(arr) to your function.

Gribouillis 1,391 Programming Explorer Team Colleague

It is quite advanced. I am just begining to learn python. I will try to understand but my originalcode can be in any way changed to come to the same result?

Yes, the key points are the way the records read in the source file are transformed into a tuple (name, lat, lon) containing the 3 values, and then how these 3 values are formatted for the output file. You can write a similar code without 'yield', 'with' and even without functions. For example instead of 'yield', you could append the tuple to a list.

Gribouillis 1,391 Programming Explorer Team Colleague

This could be what you want

SRC_FILE = "Better.csv"
DST_FILE = "Output.csv"

def gen_triples():
    with open(SRC_FILE) as fin:
        for record in fin.read().split(';'):
            if not record: # ignore empty record
                continue
            name, coords = record.split(",")
            lat, lon = coords.split()
            yield name, lat, lon

def write_output():
    with open(DST_FILE, "w") as fout:
        for name, lat, lon in sorted(gen_triples()):
            fout.write("{na}, {la}, {lo}\n".format(na = name, la = lat, lo = lon))
            
if __name__ == "__main__":
    write_output()

Try to understand every bit of it :)

Gribouillis 1,391 Programming Explorer Team Colleague

I tried to upload but i got this error:

Better.csv:
Invalid File
Should i change the format of the file into txt?

My file Better.csv has this format:
name3,long3 lat3;name1,long1 lat1;name2,long2 lat2;

And some of the names are compund. I tried first to sort them, write sorted in another file. After that i split long lat using split(None,1) but it give a format i did not really need.So using the posted code before i could write my new file in a format i could almost use for my matrix,
i said almost because each line has \n

So i should change the format of the file to be able to attach it?

You can zip the file and attach the zipped file.

Gribouillis 1,391 Programming Explorer Team Colleague

I tried to add this to my cod but still nothing

s=s.rstrip('\n')

What is the problem ?

If you could attach Better.csv to a post, we could see what your code does...

Gribouillis 1,391 Programming Explorer Team Colleague

Sorry for the double post, but it turns out that the above solution is over-complicated: using the print function and stdout.flush() does the trick

from __future__ import print_function
from time import sleep
import sys

for i in range(20):
    print("#", end="")
    sys.stdout.flush()
    sleep(0.3)

print(" end")
Gribouillis 1,391 Programming Explorer Team Colleague

In linux, you can print at a given position in a terminal using ANSI escape sequences, a problem being that lines are numbered from the top of the terminal
Save this post named 'Formatting with colors in a linux console' as a module termstyle.py http://www.daniweb.com/code/snippet232375-2.html#post1028718, then run the following code

from termstyle import Style
from time import sleep
import sys

LINENO = 24

for i in range(20):
    print "{0}".format(Style((LINENO, i), "yellow")("#")),
    sys.stdout.flush()
    sleep(0.3)
    
print "{0}".format(Style((LINENO, i))(" end"))

It will do what you want.

It's not the only way to do in linux, another way is to use module curses, but it's a lot of work, also you could use a progressbar of one of the gui toolkits instead of a terminal based progress bar.

Gribouillis 1,391 Programming Explorer Team Colleague

Sorry for the double post. To clarify a little.

I was looking to create an application to spoof a USB barcode reader or card scanner. I wanted to create an application that pretended to be a usb device and tricked the pc into thinking it was a USB barcode / card reader. I would then feed the application some data which the PC would receive and believe it was the information from the barcode or card reader. Would this be possible with the socket module? or is this something completely different?

I think it has little to do with the socket module, or even with python. You should look for usb device emulators, if it exists. If such emulators can be written in any language, they can probably be written in python. Google is your friend...

Gribouillis 1,391 Programming Explorer Team Colleague

With the fastgraph snippet above, I replaced your call to main() by

from fastgraph import graph
import webbrowser as web

def links(tree):
    for n in (tree.left, tree.right):
        if n is not None:
            yield tree, n
            for link in links(n):
                yield link

def label(tree):
    return repr(tree.key)

def show(tree, filename="tree.png"):
    g = graph(links(tree), label, directed=True)
    g.draw(filename, prog = 'dot')
    web.open(filename)


if __name__ == "__main__":
    t = buildParseTree("( 3 * 5 + 7 ) - 4")
    show(t)

This pops up a window showing the tree. This tree is probably not what you are expecting, so there are still errors in your program. Remark that fastgraph cannot distinguish left from right.

Gribouillis 1,391 Programming Explorer Team Colleague

Keep getting Attribute Errors with my code any suggestions?
There are two files attatched

from string12 import *
from root import *

def main():
    tree1 = raw_input("enter numbers: ")
    print buildParseTree(tree1)
    

def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in '+-*/)':
            currentTree.setRootVal(eval(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in '+-*/':
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()      
        elif i == ')':
            currentTree = pStack.pop()
        else:
            print "error:  I don't recognize " + i
    return eTree
main()

I got something by replacing root.py with

class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.left = None
        self.right = None

    def insertLeft(self,newNode):
        if self.left == None:
            self.left = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.left = self.left
            self.left = t

    def insertRight(self,newNode):
        if self.right == None:
            self.right = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.right = self.right
            self.right = t

    def getRootVal(root): # accessor functions are java-ic and not very pythonic.
        return root.key
    
    def setRootVal(root,newVal):
        root.key = newVal
    
    def getLeftChild(root):
        return root.left
    
    def getRightChild(root):
        return root.right

""" Result of main -->
enter numbers: ( 3 * 5 + 7 ) - 4
<root.BinaryTree instance at 0x7f08309c2170>
"""

Note that specialized modules exist to parse arithmetic expressions, and languages in general. Also this snippet could draw your binary tree http://www.daniweb.com/code/snippet323792.html .

Gribouillis 1,391 Programming Explorer Team Colleague

An improvement in the previous code is to replace self.R[0].select() by self.R[0].invoke() which invokes the button's action. You can even remove the call to deselect() .

Behseini commented: Perfect +1
Gribouillis 1,391 Programming Explorer Team Colleague

You can't combine grid() and pack() but must use one or the other. Also, AFAIK, one radio button must be selected (a default selection or you can't choose 'none' when using radio buttons), and the others can be deselected.

from Tkinter import *
 
class App:
   def __init__(self, parent):
    self.my_parent = parent
    self.my_parent.geometry("200x100+10+10")
#    self.fm = Frame(parent, width=400, height=300)
#    self.fm.pack_propagate(0) # to keep the frame size
#    self.fm.pack()
 
 
    self.R1 = Radiobutton(self.my_parent, text="Red", value=1, command=self.make_Red)
    self.R1.grid(row =2 , column = 1)
    self.R1.select()

    self.R2 = Radiobutton(self.my_parent, text="Blue",  value=2, command=self.make_Blue)
    self.R2.grid(row =2 , column = 2)
    self.R2.deselect()
 
    self.R3 = Radiobutton(self.my_parent, text="Green", value=3, command=self.make_Green)
    self.R3.deselect()
    self.R3.grid(row =2 , column = 3)
 
 
   def change_buttons(self, color):
       self.my_parent.configure(bg=color)
       self.R1.configure(bg=color)
       self.R2.configure(bg=color)
       self.R3.configure(bg=color)

   def make_Red(self):
       self.change_buttons("Red")
 
   def make_Blue(self):
       self.change_buttons("BLUE")
 
   def make_Green(self):
       self.change_buttons("GREEN")
 
root = Tk()
root.title ("Color Option")
app = App(root)
root.mainloop()

Don't forget to refactor the code when there are sequences of similar widgets

from Tkinter import *
from functools import partial
 
class App:
   def __init__(self, parent):
    self.my_parent = parent
    self.my_parent.geometry("200x100+10+10")
 
    self.R = list()
    for i, color in enumerate(("Red", "Blue", "Green")):
        btn = Radiobutton(self.my_parent, text=color, value=i+1, command = partial(self.change_buttons, color))
        btn.grid(row = 2, column = i+1)
        btn.deselect()
        self.R.append(btn)
    self.R[0].select()
 
 
   def change_buttons(self, color):
       self.my_parent.configure(bg=color)
       for btn in self.R:
            btn.configure(bg=color)

if __name__ == "__main__":
    root = Tk()
    root.title ("Color Option")
    app = App(root)
    root.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

It works with

def call_back(self, event):
     self.zones = self.Lb1.curselection()
     assert len(self.zones) == 1
     z = self.zones[0]
     if z == '0':
        self.make_Red()
     elif z == '1':
        self.make_Green()
     elif z == '2':
        self.make_Blue()

Also, configure your editor to indent with 4 spaces, it will be easier to help.

Behseini commented: Perfect answer +1
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a solution

from Tkinter import *

class App:
   def __init__(self, parent):
    self.myParent = parent
    self.fm = Frame(parent, width=400, height=300)
    self.fm.pack_propagate(0) # to keep the frame size
    self.fm.pack()

    self.btnBlue = Button(self.fm, text = "Blue", command=self.make_blue)
    self.btnBlue.pack()

   def make_blue(self):
    # Don't create new widgets, configure existing ones
    self.fm.configure(bg="blue")

root = Tk()
root.title ("Color Option")
app = App(root)
root.mainloop()
Behseini commented: Good help +1
Gribouillis 1,391 Programming Explorer Team Colleague

Thank you - works great.

So I understand...

line 1 creates a list based on my multiline string using newline as a split?
line 2 tells it to only include every thing from line 22 onwards?
line 3 - not sure?

THank you

Line 3 joins the list items, inserting newline between the items (the newlines where removed when the string was split at line 1).

Another solution is to find the position of the 22th occurrence of "\n" in the initial string. This could be done with a regex.

Gribouillis 1,391 Programming Explorer Team Colleague

Tony is going too fast. Let's decompose a little

the_list = the_string.split("\n")
the_list = the_list[22:]
the_string = "\n".join(the_list)
yeleek commented: great solution - and explained well. +1
Gribouillis 1,391 Programming Explorer Team Colleague

Why are you looking for another similar program ? Aren't you happy with your program ? Also it would be a good idea to post it (you can zip the python file and attach the zip to a post if it is too long).

Gribouillis 1,391 Programming Explorer Team Colleague

So I want to make sure I do this right:
Step 1: Download pygame-1.9.1release.tar.gz from the PyGame website and save
it to your disk - mine was saved into my Downloads folder. With the download
complete, open up a new Terminal window and type: cd Downloads
Ok thats pretty easy

Step 2: Issue tar zxvf pygame-1.9.1release.tar.gz to unpack the downloaded file.
As in, write that in Terminal and press enter?

Step 3: Change into the newly created directory: cd pygame-1.9.1release
I assume 'cd' is the terminal command for switching directories?
Step 4: Issue this command: python3 config.py

Step 5: Edit the newly-created Setup file changing this line (on my system it was line
72):
pypm src/pypm.c $(SDL) $(PORTMIDI) $(PORTTIME) $(DEBUG)
to look like this (note: addition of # at the start of the line):
# pypm src/pypm.c $(SDL) $(PORTMIDI) $(PORTTIME) $(DEBUG)
Be sure to exit and save the Setup file.

Step 6: From the command-line, issue this command (exactly as shown, all on the
one line):
export CC='/usr/bin/gcc-4.2' CFLAGS='-isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386'

Step 7: Build PyGame with this command: python3 setup.py build
Again, that's in Terminal?
This will take a while and you'll see a lot of stuff on screen (including a bunch of
warnings, which you can safely ignore). You only have to worry if you see the word
“error”.
Step 8: …

Gribouillis 1,391 Programming Explorer Team Colleague

Using the itertools module

import itertools as itt

def not_is_begin(line):
    return not line.startswith(">>>>>Begin Processed Spectral Data<<<<<")

def not_is_end(line):
    return not line.startswith(">>>>>End Processed Spectral Data<<<<<")

lines = itt.dropwhile(not_is_begin, open(FILENAME))
lines = itt.islice(lines, 1, None)
lines = itt.takewhile(not_is_end, lines)

for line in lines:
    print line

!

Gribouillis 1,391 Programming Explorer Team Colleague

Why not x = Decimal('{0:.2f}'.format(lolinput.GetValue()), 2) ?

Gribouillis 1,391 Programming Explorer Team Colleague

To complete the previous post, the difference with the IEEE 754 representation is due to the endianness of the system. One can recover the standard representation by reverting the bytes:

from ctypes import *
from binascii import hexlify
import sys

def double_to_bytes(f):
    cf = c_double(f)
    n = sizeof(cf)
    assert not n % 2
    pc = cast(pointer(cf), POINTER(c_char))
    h = ''.join(pc[i] for i in xrange(n))
    s = bin(int(b"1" + hexlify(h), 16))[3:]
    return [s[i:i+8] for i in xrange(0, len(s), 8)]

L = double_to_bytes(-0.5)

print "This system uses %s endian byteorder" % sys.byteorder
print " ".join(L)
print " ".join(reversed(L))

""" my output -->
This system uses little endian byteorder
00000000 00000000 00000000 00000000 00000000 00000000 11100000 10111111
10111111 11100000 00000000 00000000 00000000 00000000 00000000 00000000
"""
Gribouillis 1,391 Programming Explorer Team Colleague

You can start with

import os
L = [x for x in os.listdir("/boot") if "-xen-" in x]
print(L)
Gribouillis 1,391 Programming Explorer Team Colleague

Wit this:

import math

print(math.cos((2*math.pi)/3))         # -0.5
print(0.5 + math.cos((2*math.pi)/3))   # 2.22044604925e-16
print(-0.5 + math.cos((2*math.pi)/3))  # -1.0

x = math.cos((2*math.pi)/3)
print(x)        # -0.5
print([x])      # [-0.4999999999999998]
print([-0.5 + x])   # [-0.9999999999999998]

Strange?

It is not strange, because printing a float x prints str(x) in fact, while printing a list invokes the repr() of the list items. The method float.__str__() yields less decimals than float.__repr__, so the floating number is rounded

>>> x = 1.0/3
>>> str(x)
'0.333333333333'
>>> repr(x)
'0.33333333333333331'
>>>
>>> x = -0.49999999999999
>>> str(x)
'-0.5'
>>> repr(x)
'-0.49999999999999001'

About the actual bits used by C python, the PyFloatObject structure from floatobject.h uses a C double to store the number, so the bits are the same as the bits of the C type double. I wrote a small functions to extract the actual bits using module ctypes

from ctypes import *
from binascii import hexlify

def double_to_bits(f):
    cf = c_double(f)
    n = sizeof(cf)
    assert not n % 2
    pc = cast(pointer(cf), POINTER(c_char))
    h = ''.join(pc[i] for i in xrange(n))
    return bin(int(b"1" + hexlify(h), 16))[3:]

print double_to_bits(-0.5)

""" my output (this should be machine dependent) -->
0000000000000000000000000000000000000000000000001110000010111111
"""

Interestingly, this yields the same result as using struct.pack() :

>>> from binascii import hexlify
>>> import struct
>>> p = struct.pack("d", -0.5)
>>> print bin(int(b"1" + hexlify(p), 16))[3:]
0000000000000000000000000000000000000000000000001110000010111111

Also notice that on my machine, this representation differs from the IEEE 754 representation referred to above. How is it coded ? It would be worth having a python …

vegaseat commented: Thank you, that explains a lot +13
Gribouillis 1,391 Programming Explorer Team Colleague

Following a link in the comments of the previous link, I discovered this module colorama http://pypi.python.org/pypi/colorama which allows interpretation of the ANSI escape sequences in the windows cmd. This allows cross-platform colored text in a console !

Gribouillis 1,391 Programming Explorer Team Colleague

Maybe the reason rwas not like I said as formatting normally expands if number does not fit. Still it is easy to optimize out assert statements because they make your dear program slower. Premature optimization is not without reason sin in Python world.

My idea is that if the OP wanted larger numbers, he would have written picture0001, so there was an implicit assumption which deserved to be checked.

Gribouillis 1,391 Programming Explorer Team Colleague

OS win 7 ... python 0.61 ... in a console

Then you should perhaps start by reading this http://www.burgaud.com/bring-colors-to-the-windows-console-with-python/ . There is also a small module for download.

I also know that it's not the only method to print in colors with the cmd console, but I don't usually use windows, so I can't say more.

Edit: what is this python 0.61 ?

Gribouillis 1,391 Programming Explorer Team Colleague

Gribouillis want to stop counter wrap arround to stop program destroying files. Rename = move in Linux systems. Good thinking.

I read a good rule: assert the most obvious hypotheses about your data :)

Gribouillis 1,391 Programming Explorer Team Colleague

Are you printing your text in a GUI widget or in a console ? also what is your OS and version of python ?

Gribouillis 1,391 Programming Explorer Team Colleague

Read this http://www.daniweb.com/code/snippet232375.html and use

assert 0 <= number < 1000
example = "picture{num:0>3d}".format(num=number)
Gribouillis 1,391 Programming Explorer Team Colleague

In fact you can obtain the binary representation of floating points numbers using the module bitstring available in pypi

>>> from bitstring import BitString
>>> bs = BitString(float=-0.5, length=64)
>>> bs.bin
'0b1011111111100000000000000000000000000000000000000000000000000000'

This representation of -0.5 is the same as the IEEE 754 representation of the
floating point number on 64 bits. To understand its meaning, go to this online
application http://babbage.cs.qc.edu/IEEE-754/Decimal.html and enter -0.5 in the first field, then click 'not rounded' and read the representation and its meaning below.

Also note that some native support exist in the python interpreter: sys.float_info contains constants read in your system's float.h header, and the float class has a method hex() which returns a hexadecimal representation of the number.

A nice exercise would be to write a class which displays the same information as the page http://babbage.cs.qc.edu/IEEE-754/Decimal.html about a floating point number and its binary representation :)

A more subtle question is how to make sure that you obtain the binary representation actually used by your processor ? Apparently, some processors use 80 bits and not 64 ...

Gribouillis 1,391 Programming Explorer Team Colleague

Floating point algorithms in all computer languages suffer from a small error as the floating point world meets the binary world. Representing -0.5 in just a sequence of 1 and 0 is not possible with true accuracy. Look at this ...

import math

# use a list to show the small binary error
mylist = [math.cos((2*math.pi)/3)]
print mylist  # [-0.49999999999999978]

# you could use round() to 15 digits
mylist = [round(math.cos((2*math.pi)/3), 15)]
print mylist  # [-0.5]

I don't exactly agree that -0.5 is not representable in binary because 0.5 is 2**(-1). On the other hand the binary 2*math.pi/3 is not exactly equal to the mathematical 2*pi/3 .

Gribouillis 1,391 Programming Explorer Team Colleague

Your <a href="http://www.google.com/">Google</a> is not a text node in your html document, but a <a> node. You should probably write something like

from xml.dom.minidom import Document

doc = Document()
link = doc.createElement("a")
link.attributes["href"] = "http://www.google.com/"
google = doc.createTextNode("Google")
link.appendChild(google)
doc.appendChild(link)

print doc.toxml()

""" my output -->
<?xml version="1.0" ?>
<a href="http://www.google.com/">Google</a>
"""

Special characters in raw strings MUST be escaped in the XML specification.

Gribouillis 1,391 Programming Explorer Team Colleague

I managed to do it like this

def bintohex(s):
    t = ''.join(chr(int(s[i:i+8],2)) for i in xrange(0, len(s), 8))
    return binascii.hexlify(t)

All of this would be easier with python >= 2.6 because of the builtin bin function. See this code snippet for example http://www.daniweb.com/code/snippet221031.html.

In python 2.6, you could probably write

def hex_to_binary(s):
    return bin(int("1" + s, 16))[3:]

def bintohex(s):
    return "{0:#0x}".format(int("1"+z, 2))[3:]
Gribouillis 1,391 Programming Explorer Team Colleague

Use zip

for i, a in zip(var1, var2):
    print i
    print a

Items are printed until the shortest list is consumed.

Gribouillis 1,391 Programming Explorer Team Colleague

Thanks Gribouillis!
You did solve the main problem; it almost worked.
It just didn't work for the last option - if options.mon and options.vos: - in my original mail, until I changed the order of the if statements and modified the script a little bit like this:

def abbrMonth(m):
    mn = tuple(month_abbr)[int(m)]
    return mn

if options.mon and options.vos:
        thisMonth = abbrMonth(options.mon)
        print "I'm '%s' and this month is '%s'\n" % (options.vos, thisMonth)
        sys.exit(0)

    if not options.mon and not options.vos:
        options.mon = strftime("%m")

    if options.mon:
        thisMonth = abbrMonth(options.mon)
        print "The month is: %s\n" % thisMonth

    if options.vos:
        print "My name is: %s\n" % options.vos

I worked just the way I wanted, although I'm not very impressed. Is this the only way of doing so? Cheers!!

I'm not sure that there are other ways to do the same. You may find this link useful to understand optparse http://www.alexonlinux.com/pythons-optparse-for-human-beings . Also note that optparse was replaced by a new module called argparse with extended capabilities in recent versions of python, so if you are programming for the future, you should use argparse.

Gribouillis 1,391 Programming Explorer Team Colleague

Gribouillis Thanks for reply.I'm sure there is a <FRUIT name="apple">1</FRUIT> in my file. However I made the change and now I'm getting this error:


raise RuntimeError("'apple' was not found")
RuntimeError: 'apple' was not found

Beware that some tags are FRUITS and other are FRUIT. Here is a modified code that works for me

# python 2 - fruits.py -
import sys
from xml.dom.minidom import parse
from cmath import sqrt
from cStringIO import StringIO

xml_data = """
<VEGETABLE >
<FRUITS>
<FRUIT name="apple">1</FRUIT>
<FRUIT name="Orange">2</FRUIT>
<FRUIT name="Benana">6</FRUIT>
</FRUITS>
</VEGETABLE>
"""
input_file = StringIO(xml_data)

# Load XML into tree structure
tree = parse(input_file)

#Find all  <FRUITS>
pa_list=tree.getElementsByTagName('VEGETABLE')[0].getElementsByTagName('FRUITS')[0].getElementsByTagName('FRUIT')

#Find the 'T' node in the list of FRUITS
fru = None # give an initial dummy value to fru
for pa in pa_list:
    try:
        nodevalue = pa.attributes.getNamedItem('name').nodeValue
        print "nodevalue: %s" % str(nodevalue) # for debugging purposes
        if nodevalue == 'apple':
           fru = pa
           break
    except Exception: # <-- replace Exception by a more specific exception later
        raise # don't catch the exception first to see what happens
if fru is None:
    # handle the case where apple was not found
    raise RuntimeError("'apple' was not found")

fruitvalue=0
fruitvalue=float(fru.childNodes[0].data)

print "\t%g"% (fruitvalue)

"""my output -->
nodevalue: apple
	1
"""

Also, usually, I parse xml using the lxml library (http://lxml.de/). Did you consider this option ?

Gribouillis 1,391 Programming Explorer Team Colleague

You could try

parser.add_option("-m", "--month", type="string",
                  help="select month from  01|02|...|12", 
          dest="mon")

parser.add_option("-u", "--user", type="string",
                  help="name of the user", 
          dest="vos")

options, arguments = parser.parse_args()

if not options.vos and not options.mon:
    options.mon = strftime("%m")
if options.mon:
    abbrMonth = tuple(month_abbr)[int(options.mon)]
Gribouillis 1,391 Programming Explorer Team Colleague

You defined fru only if a test suceeded. What you should do is replace lines 12-18 with

fru = None # give an initial dummy value to fru
for pa in pa_list:
    try:
        nodevalue = pa.attributes.getNamedItem('name').nodeValue
        print "nodevalue: %s" % str(nodevalue) # for debugging purposes
        if nodevalue == 'apple':
           fru = pa
           break
    except Exception: # <-- replace Exception by a more specific exception later
        raise # don't catch the exception first to see what happens
if fru is None:
    # handle the case where apple was not found
    raise RuntimeError("'apple' was not found")
Gribouillis 1,391 Programming Explorer Team Colleague

Can't you just call

seno = seno_taylor(x+1, a)

?

Gribouillis 1,391 Programming Explorer Team Colleague

A first hint from the IronPython faq http://ironpython.codeplex.com/wikipage?title=FAQ :

How do I compile .py files to a DLL for linking into my C# or VB program?

IronPython does not support building DLLs for a C# style of linking and calling into Python code. You can define interfaces in C#, build those into a DLL, and then implement those interfaces in Python code as well as pass the python objects that implement the interfaces to C# code.
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest to call the following function to ensure the target directories exist

def make_target_dirs(target_paths):
    for dirname in set(os.path.dirname(p) for p in target_paths):
        if not os.path.isdir(dirname):
            os.makedirs(dirname)

Edit: to attach a .py file, zip it first, then attach the zipped file.

yeticannotski commented: Great and fast help. Thanks +1