sneekula 969 Nearly a Posting Maven

If you perform an apt-cache search python | grep -E "31|3\.1" do you get any hits?

Alternately try an apt-cache search python3 . If nothing comes up for either query then you'll need to go the manual route.

Thanks Jim, your first suggestion gives me:

dell@dell-laptop:~$ apt-cache search python | grep -E "31|3\.1"
python-xen-3.1 - python bindings for Xen, a Virtual Machine Monitor
dell@dell-laptop:~$

Your second code finds nothing, so it looks that Python3 it isn't there yet.

sneekula 969 Nearly a Posting Maven

kiddo might have to use a thread and a hook to the keyboard to get tis to go

sneekula 969 Nearly a Posting Maven

I am still rather new to the Linux OS and need some detailed advice on the installation of Python3.1 on my Ubuntu machine.

Python3.1 is not in the Ubuntu package repository yet.

sneekula 969 Nearly a Posting Maven

On the other hand 'in' would fetch:
'you love me!'
which would be a shame to miss!

sneekula 969 Nearly a Posting Maven

A bag of marijuana was found on the floor of a Hermosa convenience store. Anyone who thinks they might have dropped their weed while dazed and confused in Hermosa should contact the sheriff’s office to claim it.

sneekula 969 Nearly a Posting Maven

Looking forward to a mess of hot fried chicken and cold potato salad with a large bowl of banana pudding at my neighbor's house.

sneekula 969 Nearly a Posting Maven

The way you have this coded, you are not only calling function difflib.get_close_matches(line, dict) for every word in your test string, but also for every word in the dictionary list. No wonder it is rather slow.

sneekula 969 Nearly a Posting Maven

Are you using tabs for indents? They are screwed up!
I normally don't even bother with code that has obvious signs of tabs.
Do not use 'dict' as identifier, it is the name of a Python function.
Also, test your list, the punctuation marks are still attached:

test = "Hello, thsi is a test!"

test = test.lower()
list_words = test.split(' ')

# test the list
print(list_words)

"""
my output (notice that the punctuation marks are left in) -->
['hello,', 'thsi', 'is', 'a', 'test!']
"""
sneekula 969 Nearly a Posting Maven

Let's say you want to change the email:

# a test setup

class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)


name_dic = {}

# first set of data for testing
name = 'frank millato'
home = '123-456-7890'
mobile = '456-789-0123'
email = 'frank23@gmail.com'
name_dic[name] = Data(home, mobile, email)

# second set of data for testing
name = 'bob dork'
home = '234-567-8901'
mobile = '567-690-1234'
email = 'bob.dork@hotmail.com'
name_dic[name] = Data(home, mobile, email)

def change_att():
    #c_search = raw_input("Enter name to alter: ")
    c_search = 'bob dork'  # for testing only!!!
    if name_dic.has_key(c_search):
        #c_name = raw_input("What element do you want to change: ")
        c_name = 'email'  # for tesing only!!!
        if c_name == 'email':
            #n_e = raw_input("Enter new email adress: ")
            n_e = 'bob.dork@yahoo.com'  # for testing only!!!
            # make the change
            k = name_dic[c_search]
            name_dic[c_search] = Data(k.home, k.mobile, n_e)

# get the info for all names added before change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

print('-'*40)

change_att()

# get the info for all names added after change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

"""
my output -->
Name = frank millato
Home Phone: 123-456-7890
Mobile Phone: 456-789-0123
Email: frank23@gmail.com

Name = bob dork
Home Phone: 234-567-8901
Mobile Phone: 567-690-1234
Email: bob.dork@hotmail.com

----------------------------------------
Name = …
sneekula 969 Nearly a Posting Maven

Probably one of those many pop up ads, or the ghost of Dani Web.

ahihihi... commented: :twisted: +1
sneekula 969 Nearly a Posting Maven

We love our own cell phones, but we hate everyone else's.
-- Kurt Folgengret

sneekula 969 Nearly a Posting Maven

Stuffed peppers and white wine.

sneekula 969 Nearly a Posting Maven

It does not exist
when you think about something very deeply than a image can be born on your mind,and then people see this "GHOST" okay then we can say it exists but only in peoples mind :)

IMHO, you are right on! If you see too many ghosts, you are ready for the mental ward.

sneekula 969 Nearly a Posting Maven

Elvis shook up the world, MJ beat it and made it thrill.

Nicely said!

sneekula 969 Nearly a Posting Maven

It is used when using formatted strings.
I could try explain, but a great book has been written and has a bit about it :)
http://diveintopython.org/getting_to_know_python/formatting_strings.html

Read and enjoy the best free book on python imho

hope that helps

The book is a little outdated IMHO.
However, aren't most of us a little outdated or at least fell like it at times?
Darn time simply does not stand still to catch up.

sneekula 969 Nearly a Posting Maven

A moderator would have to fiddle with it, I think it is best to leave it and refer interested folks to thread:
http://www.daniweb.com/forums/thread200291.html

sneekula 969 Nearly a Posting Maven

Here is the start of a Phone or Address Book:

# create a dictionary of class instance values
# can be expanded to an address book
# note: email is a Python module, so use e_mail
# snee

class DataBook(object):
    def __init__(self, home, mobile, e_mail):
        self.home = home
        self.mobile = mobile
        self.e_mail = e_mail
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone = %s
Mobile Phone = %s
Email = %s
"""
        return sf % (self.home, self.mobile, self.e_mail)


name_dic = {}

# first set of data
name = 'frank millato'
home = '123-456-7890'
mobile = '456-789-0123'
e_mail = 'frank23@gmail.com'

# the name string is the key and has to be unique
name_dic[name] = DataBook(home, mobile, e_mail)

# second set of data
name = 'bob dork'
home = '234-567-8901'
mobile = '567-690-1234'
e_mail = 'bob.dork@hotmail.com'

name_dic[name] = DataBook(home, mobile, e_mail)

# get bob's email
name = 'bob dork'
print( name_dic[name].e_mail )

print('-'*40)

# get the info for all names added so far
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

print('-'*40)

# search for part of a name and find the mobile
search = 'dork'
for key in name_dic:
    if search in key:
        print( "%s has mobile = %s" % (key, name_dic[key].mobile) )


# to save the data, you can simply save it as a text file
# where each line is name, home, mobile, e_mail
filename = "Names1.txt"
fout = open(filename, "w")
for key in name_dic:
    k = name_dic[key]
    s = "%s,%s,%s,%s\n" % …
sneekula 969 Nearly a Posting Maven

This works just fine:

# create a dictionary of class instance values

class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)


name_dic = {}

# first set of data
name = 'frank'
home = '123-456-7890'
mobile = '456-789-0123'
email = 'frank23@gmail.com'

name_dic[name] = Data(home, mobile, email)

# second set of data
name = 'bob'
home = '234-567-8901'
mobile = '567-690-1234'
email = 'bob.dork@hotmail.com'

name_dic[name] = Data(home, mobile, email)

# get bob's email
name = 'bob'
print( name_dic[name].email )

print('-'*30)

# get the info for all names added so far
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

"""
my output -->
bob.dork@hotmail.com
------------------------------
Name = frank
Home Phone: 123-456-7890
Mobile Phone: 456-789-0123
Email: frank23@gmail.com

Name = bob
Home Phone: 234-567-8901
Mobile Phone: 567-690-1234
Email: bob.dork@hotmail.com
"""

Remember that the name string is the dictionary key and has to be unique.

sneekula 969 Nearly a Posting Maven

I guess the person who developed wxPython as a wrapper for wxWindows (written in C++) didn't do much about documentation, leaving that to his book he published later. The rub was that the editor of the book introduced a lot of errors and made the book not very friendly to use.

sneekula 969 Nearly a Posting Maven

On your last post --> Please do not double post, it is rude!

sneekula 969 Nearly a Posting Maven

Oh I see, you want the instance name be the name of the person. That will not be a good idea, because identifiers in Python don't allow spaces.

A dictionary, where the name is the key and the value is a ( home, mobile, email ) tuple or list will do much better. You could also make the class instance the value of your dictionary.

sneekula 969 Nearly a Posting Maven

Variables in Python are officially names/identifiers (keys in a dictionary) of object references. I still like to refer to them with the old fashioned name variables, this way other folks know what we are talking about.

sneekula 969 Nearly a Posting Maven

Corrected your code a little and it works just fine:

''' TextFileDisp00.py
'''

import wx
import codecs

#-------------------
class TextFrame(wx.Frame):

    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, -1, mytitle, mysize)
        self.menubar = wx.MenuBar()
        self.file = wx.Menu()
        self.SetMenuBar(self.menubar)
        self.menubar.Append(self.file,'&File')
        self.openitem = self.file.Append(wx.ID_ANY,'&Open')
        self.Bind(wx.EVT_MENU,self.openevent,self.openitem)
        self.runitem = self.file.Append(wx.ID_ANY,'&Run')
        self.Bind(wx.EVT_MENU,self.runevent,self.runitem)
        self.exititem = self.file.Append(wx.ID_ANY,'E&xit')
        self.Bind(wx.EVT_MENU,self.exitevent,self.exititem)

        self.background = wx.Panel(self)
        self.background.SetBackgroundColour("white")
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.background, proportion=1, flag=wx.EXPAND)  #!!!!
        self.SetSizer(self.vbox)
        self.fileisopen = False
        self.Show()

    def openevent(self, event):
        filedialog = wx.FileDialog(self,
            message = 'Open text file',
            defaultDir = '.',
            defaultFile = 'TestTOC.txt',
            wildcard = 'Textfile (.txt .prn)|*.txt;*.prn|All (.*)|*.*', #!!!!
            style = wx.OPEN)
        if filedialog.ShowModal() == wx.ID_OK:
            self.path = filedialog.GetPath()
            self.fileisopen = True

    def runevent(self, event):
        if not self.fileisopen:
            msgbox = wx.MessageDialog(self.background,
                message="No file is open!", style=wx.OK)
            if msgbox.ShowModal() == wx.ID_OK:
                msgbox.Destroy()
        else:
            myOK = True
            linenr = 0
            InFile = codecs.open(self.path, 'r')
            textline = InFile.readline()
            while textline <> '' and myOK:
                linenr += 1
                msg = "Line " + repr(linenr) + ": " + textline
                msgbox = wx.MessageDialog(self.background,
                    message=msg, style=wx.OK+wx.CANCEL)
                if msgbox.ShowModal() == wx.ID_CANCEL:
                    myOK = False
                msgbox.Destroy()
                textline = InFile.readline()
            msg = "Finished, # lines = " + repr(linenr)
            msgbox = wx.MessageDialog(self.background,
                message=msg, style=wx.OK)
            if msgbox.ShowModal() == wx.ID_OK:
                msgbox.Destroy()
            InFile.close()
            self.Destroy()

    def exitevent(self, event):
        self.Destroy()

#-------------------
''' Main application
'''

app = wx.App(redirect = False)
mywidth = 300
myheight = 150
mytitle = "Text file display"
frame = TextFrame(None, mytitle, (mywidth,myheight))
app.MainLoop()

Line one of wx.AboutBox() has a larger font, maybe you can use that. See:
http://www.daniweb.com/forums/post901743-112.html

sneekula 969 Nearly a Posting Maven

I was doing a search on Daniweb for 'wx.AboutBox()', but it simply did not select a post, only the whole thread. So, this may be already somewhere. I am testing wxPython's fancy wx.AboutBox widget:

# testing the fancy wx.AboutBox() widget
# snee

import wx
from wx.lib.wordwrap import wordwrap

class MyFrame(wx.Frame):
    """
    create a frame, with a menu, statusbar and 2 about dialogs
    """
    def __init__(self):
        # create a frame/window, no parent, default to wxID_ANY
        wx.Frame.__init__(self, None, wx.ID_ANY, "wx.AboutBox test",
            pos=(300, 150), size=(300, 350))
        self.SetBackgroundColour("brown")

        # create a status bar at the bottom
        self.CreateStatusBar()
        self.SetStatusText("Click on File")

        menu = wx.Menu()
        # the optional & allows you to use alt/a
        # the last string argument shows in the status bar on mouse_over
        menu_about = menu.Append(wx.ID_ANY, "&About", "Ho-hum about box")
        menu_about2 = menu.Append(wx.ID_ANY, "About&2", "Fancy about box")
        menu.AppendSeparator()
        # the optional & allows you to use alt/x
        menu_exit = menu.Append(wx.ID_ANY, "E&xit", "Quit the program")

        # create a menu bar at the top
        menuBar = wx.MenuBar()
        # the & allows you to use alt/f
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        # bind the menu events to an action/function/method
        self.Bind(wx.EVT_MENU, self.onMenuAbout, menu_about)
        self.Bind(wx.EVT_MENU, self.onMenuAbout2, menu_about2)
        self.Bind(wx.EVT_MENU, self.onMenuExit, menu_exit)

    def onMenuAbout(self, event):
        """a somewhat ho-hum about box"""
        dlg = wx.MessageDialog(self,
            "a simple application using wxFrame, wxMenu\n"
            "a statusbar, and this about message.",
            "About", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onMenuAbout2(self, event):
        """use the much fancier wx.AboutBox()"""
        # first fill the info object
        info = wx.AboutDialogInfo()
        # Name and Version show in larger font
        info.Name = "Bratwurst7"
        info.Version = …
sneekula 969 Nearly a Posting Maven

Since parallel is supposed to be a package, check if there is a file __init__.py in folder C:\\Python26\\Lib\\site-packages\\parallel

sneekula 969 Nearly a Posting Maven

Starting with Python 2.5 the database module sqlite3 is part of the distribution. Once you start using sqlite3, you discover the world of database programs with their powerful query language. I have used capital letters for the query language part to make it stand out. Here is a simple example of sqlite3:

# test the sqlite3 module, write and read a database file
# note that Python 2.5 and higher versions have sqlite3 builtin
# sqlite3.connect(database, timeout=5.0, isolation_level=None,
#   detect_types=0, factory=100)
# timeout=5.0 --> allows multiple access for 5 seconds (for servers)
# isolation_level=None -->  autocommit mode
# detect_types=0 --> native types TEXT, INTEGER, FLOAT, BLOB and NULL
# factory=100 --> statement cache to avoid SQL parsing overhead
# tested with Python 2.5 and Python 3.0
# snee

import sqlite3

# create/connect to a permanent file database
#con = sqlite3.connect("my_db.db3")
# for temporary testing you can use memory only
con = sqlite3.connect(":memory:")

# establish the cursor, needed to execute the connected db
cur = con.cursor()

# create/execute a table:
cur.execute('CREATE TABLE IF NOT EXISTS clients \
    (id INT PRIMARY KEY, \
    firstname CHAR(60), \
    lastname CHAR(60))')

# insert several lines at once using a
# list of (id, firstname, lastname) tuples
# use try/except or the existing db will complain about
# the non-unique id since it is already in the db
try:
    clients = [
    (106, "Hugo", "Winterhalter"),
    (107, "Ella", "Fitzgerald"),
    (108, "Louis", "Armstrong"),
    (109, "Miles", "Davis")
    ]
    cur.executemany("INSERT INTO clients (id, firstname, lastname) \
        VALUES (?, ?, …
sneekula 969 Nearly a Posting Maven

There was also an effort that created a Tkinter GUI Builder:
http://sourceforge.net/projects/ptkgb/

It actually works.

sneekula 969 Nearly a Posting Maven

The maximum number of open files a process is allowed to have comes from the Operating System.
...

That is not all of it. In Python you have constructs like:

for line in file(filename):
    # do something with line

Here the closing of the file is left to the very eagle-eyed Python garbage collector. It is the garbage collector and its file closing algorithm that will feel overwhelmed after too many file opens.

sneekula 969 Nearly a Posting Maven

The contents of msvcrt.dll and its related dll's are used by Microsoft's C/C++ compilers for crt io. On Windows machines this dll is usually located in Windows/system32 and Python can access it.

If you are calling some of the msvcrt.dll C functions that pass arguments to and from Python you need to use module ctypes. Here is an example:

from ctypes import *

# declare the decorator with @ just before the function
# to make C functions in msvcrt.dll available
@cdecl(c_char_p, 'msvcrt', [c_char_p, c_int])
def strchr(string, c):
    """find a character in a string with C function strchr()"""
    return strchr._api_(string, c)

# ord() needed to converted from a single character Python string into a C char
print strchr('abcdefg', ord('d'))  # result --> defg

To get details on the C functions check this MS reference:
http://msdn.microsoft.com/en-us/library/b34ccac3(VS.80).aspx

sneekula 969 Nearly a Posting Maven

Microsoft's msvcrt.dll is a dynamic link library, look here for some of its contents:
http://msdn.microsoft.com/en-us/library/ms235446(VS.80).aspx

sneekula 969 Nearly a Posting Maven

If you use the Windows OS:

# get the character of a key pressed (no return key needed)
# works only in the command window and with Windows OS
# msvcrt.dll is the MS C library containing most standard C functions

from msvcrt import getch

print "press a char key (escape key to exit)"

while True:
    z = getch()
    # escape key to exit
    if ord(z) == 27:
        break
    print z,
sneekula 969 Nearly a Posting Maven

Python has a module numpy that will make things easier. However, you can use a Python list of lists for a matrix as shown in this example:

# create a 2D matrix of zeros and populate it

def make_list(size):
    """create a list of size number of zeros"""
    mylist = []
    for i in range(size):
        mylist.append(0)
    return mylist

def make_matrix(rows, cols):
    """
    create a 2D matrix as a list of rows number of lists
    where the lists are cols in size
    resulting matrix contains zeros
    """
    matrix = []
    for i in range(rows):
        matrix.append(make_list(cols))
    return matrix

rows = 5
cols = 10
# create the zero matrices first
mx1 = make_matrix(rows, cols)
mx2 = make_matrix(rows, cols)
mx3 = make_matrix(rows, cols)

# load matrix mx1 with multiples of x
x = 1
for row in range(rows):
    m = 1
    for col in range(cols):
        mx1[row][col] = x*m
        m += 1

# load matrix mx1 with squares of x
for row in range(rows):
    x = 1
    for col in range(cols):
        mx2[row][col] = x*x
        x += 1

# multiply mx1 with mx2
for row in range(rows):
    for col in range(cols):
        mx3[row][col] = mx1[row][col] * mx2[row][col]

# pretty show the different loaded matrix contents
for x in mx1:
    print(x)

print('-'*50)

for x in mx2:
    print(x)

print('-'*50)

for x in mx3:
    print(x)

"""
my result -->
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
--------------------------------------------------
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
--------------------------------------------------
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
"""
sneekula 969 Nearly a Posting Maven

This might help:

# see also: http://www.daniweb.com/forums/post896314-177.html

import math

def fuzzyequals(a, b, delta=0.0000000001):
    """
    returns true if a is between b-delta and b+delta
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta

# cosine of 90 degrees should be zero
n = math.cos(math.radians(90))
#n = math.cos(90*math.pi/180)

print(n)  # 6.12303176911e-17 close to zero, but not quite

if fuzzyequals(n, 0.0):
    n = 0.0

print(n)  # 0.0
sneekula 969 Nearly a Posting Maven

In the English language you can add a suffix to a number, so for instance first becomes 1st, second 2nd, third 3rd, fourth 4th and so on. Here is a little Python program that does it for you, and teaches a few list tricks too:

# add the proper suffix to integer numbers
# the suffix list index coincides with the number
# apply modulus 100 for numbers that exceed the list index
# snee

# list_0to9 also holds true for list_20to29 etc.
list_0to9 = ['th', 'st', 'nd', 'rd'] + ['th']*6
# 11th to 13th are exceptions
list_10to19 = ['th']*10

# suffix list for numbers 0 to 99
suffix_list = list_0to9 + list_10to19 + (list_0to9)*8

#print suffix_list

# test it
for x in range(1000):
    # use modulus 100 to recycle through the list
    # in case numbers exceed the list index
    print( "%d%s" % (x, suffix_list[x%100]) )

"""
part of my output -->
0th
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
...
...
990th
991st
992nd
993rd
994th
995th
996th
997th
998th
999th
"""
Ene Uran commented: nice code indeed! +7
sneekula 969 Nearly a Posting Maven

A good part of coding in Python is to know what its modules are doing. The module datetime makes your life a lot simpler, it also flags down impossible dates:

# convert one date format to another
# check the Python manual under strftime()
# to get the % format directives

import datetime as dt

def convert_date(date_str):
    """convert date_str eg. 11/21/1987 to 21 November,1987"""
    try:
        fdate = dt.datetime.strptime(date_str, "%m/%d/%Y")
        return fdate.strftime("%d %B,%Y")
    except ValueError:
        return False
        
    
date_str = "11/21/1987"
print(convert_date(date_str))  # 21 November,1987

# test impossible dates
print(convert_date("11/31/1987"))  # False
print(convert_date("2/29/1987"))   # False

In its simplest form:

import datetime as dt

ds = "11/21/1987"
print(dt.datetime.strptime(ds, "%m/%d/%Y").strftime("%d %B,%Y"))

"""
my result -->
21 November,1987
"""
sneekula 969 Nearly a Posting Maven

I just listened to the William Tell Overture and did not think of The Lone Ranger.

sneekula 969 Nearly a Posting Maven

I get mail, therefore I am.
~~~ Scott Adams

sneekula 969 Nearly a Posting Maven

Why use tabs when you could use 4 spaces like everybody else.

sneekula 969 Nearly a Posting Maven

In Python2.5 the range() function returns a list and the xrange() function an iterator (generator). Python 3.0 replaces range() with xrange() and now calls it range(). Anyway, range(start, stop, step) handles only integer values, and if you want to use floats, you have to role your own, as show in this example:

def frange(start=0, stop=0, step=1.0):
    """similar to xrange, but handles floating point numbers"""
    if step <= 0:
        while start > stop:
            yield start
            start += step
    else:
        while start < stop:
            yield start
            start += step

# testing ...
for x in frange(1.5, 4.7):
    print(x)

print("-"*20)

for x in frange(17, 4, -2.9):
    print(x)

print("-"*20)

for x in frange(stop=2.5, step=0.4):
    print(x)

print("-"*20)

print(list(frange(1.5, 5.2)))


"""
my output -->
1.5
2.5
3.5
4.5
--------------------
17
14.1
11.2
8.3
5.4
--------------------
0
0.4
0.8
1.2
1.6
2.0
2.4
--------------------
[1.5, 2.5, 3.5, 4.5]
"""
sneekula 969 Nearly a Posting Maven

Floating point numbers are often close approximations of a value, very close, but approximations never the less. So if you directly compare floating point number results you can get surprises as shown here:

def fuzzyequals(a, b, delta=0.0000001):
    """
    returns true if a is between b-delta and b+delta
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta

a = 0.61
c = 0.49
b = 1.1 - c  # b should be 0.61

# fuzzy comparison
if fuzzyequals(a, b):
    print("fuzzy_true")
else:
    print("fuzzy_false")

# direct comparison
if a == b:
    print("direct_true")
else:
    print("direct_false")

# shows true floating point number representation
print("should be [0.61, 0.61, 0.49]")
print([a, b, c])

"""
my output -->
fuzzy_true
direct_false
should be [0.61, 0.61, 0.49]
[0.60999999999999999, 0.6100000000000001, 0.48999999999999999]
"""
sneekula 969 Nearly a Posting Maven

It doesn't work even though I run it in the DOS Console window! It just pops up and then closes....(even when I modified the code with the time module)..

In IDLE, when I run it, it says "'module' not found"

Works well on my Linux/Ubuntu computer. I code with the Geany IDE and that one uses the console/terminal window as an output window, but keeps it open until you press the Return key.

You may have to add a wait line to the end of your code otherwise:

# your code here

raw_input("Press enter to go on ... ")
# with Python3 use
#input("Press enter to go on ... ")
sneekula 969 Nearly a Posting Maven

Since a list is a mutable object, it would still behave global if it is used as a function parameter/argument. To wit:

def add_element(mylist2):
    mylist2.append(33)
    return mylist2

mylist = [1,2,3,4]
mylist3 = add_element(mylist)

print(mylist)   # [1, 2, 3, 4, 33]  oops!
print(mylist3)  # [1, 2, 3, 4, 33]

To prevent mutable parameter feedback use:

def add_element(mylist2):
    # make a copy to prevent feedback
    mylist2 = list(mylist)
    mylist2.append(33)
    return mylist2

mylist = [1,2,3,4]
mylist3 = add_element(mylist)

print(mylist)   # [1, 2, 3, 4]
print(mylist3)  # [1, 2, 3, 4, 33]
sneekula 969 Nearly a Posting Maven

Hey guys,

I wrote a file the other day, which reads in data, adds a column, and then reads the data out to a specific file. I thought everything was working great, with all of your help; however, I am now running into another problem.

The output data looks like this:

Which looks like a list; however, I think each character in the line is an element of the list. For example, if I do len(line) it tells me the line is 140 or so elements long. Further more, if I do print line[6], it print a quotation mark, '

What I need is data to be formatted like this:
585 266 322 147 0 469 chr1 ...

I have the options to change either the output file, or the program which generates it. Here is the program which generates it:

infile = open('rep_small.bed')

def get_names(line):
	'''Will scan the repElement name in a line, and if it is not already known, will save it.  Use to get all names in a file.'''	
	temp_name.append(line[11])
	return temp_name


def add_age(line):
	'''Calculates the age (milliDiv + milli... + milli)'''
	age =  int(line[2]) + int(line[3]) + int(line[4])
	return str(age)
for line in infile:
		line = line.strip()
		sline = line.split()
		'''call the age method'''
		calc_age = add_age(sline)		
		'''put the calculated age into the list at position 5'''		
		sline.insert(5, calc_age)
		print (sline)
		'''Call get_names method'''
		all_names=get_names(sline)
		for name in Name_List:
			if str(sline[11]) == str(name):
				outfile = '/home/hugadams/Desktop/SHANE_STUFF/Modules/Test1/' + name + '.txt'
		                o = open(outfile, 'a')
		                o.write(str(sline) …
sneekula 969 Nearly a Posting Maven

To read in a list of integers with a loop you have to create an empty list and append to it with each input. For instance:

# create a list of integers
# note that input() gives a string in Python3

n_list = []
while True:
    n = int(input("Enter a positive integer (-1 to quit): "))
    n_list.append(n)
    if n < 0:
        break

print(n_list)

"""
my example output -->
[33, 12, 123, 567, -1]
"""

I left the end marker -1 in the list. If you break before the append then the -1 is omitted.

If you leave the -1 of the list or remove it, then you can just use:

low_number = min(n_list)
high_number = max(n_list)
total = sum(n_list)
average = float(total)/len(n_list)

However, your instructor, being rather tricky, most likely wants you to take care of the -1 as you do your calculations.

Please use code tags with your code to preserve the indentations. Otherwise the code is very difficult to read and not too many folks will help.

[code=python]
your Python code here

[/code]

sneekula 969 Nearly a Posting Maven

Are you using the Python Shell (>>> prompts), or an editor like the IDLE editor?

sneekula 969 Nearly a Posting Maven

In order to make added text transparent you have to use the canvas approach. I left a working example here:
http://www.daniweb.com/forums/showpost.php?p=895637&postcount=20

sneekula 969 Nearly a Posting Maven

An example how to use an image as a background. In order to make added text transparent, use the Tkinter canvas:

# use a Tkinter canvas for a background image
# add transparent text and other widgets
# with Python3 use   import tkinter as tk
# snee

import Tkinter as tk
 
root = tk.Tk()
root.title('background image')

# pick a .gif image file you have in the working directory
bg_image = tk.PhotoImage(file="Flowers.gif")
w = bg_image.width()
h = bg_image.height()
 
# size the window so the image will fill it
root.geometry("%dx%d+0+0" % (w, h))

cv = tk.Canvas(width=w, height=h)
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=bg_image, anchor='nw')
 
# add canvas text at coordinates x=15, y=30
# anchor='nw' implies upper left corner coordinates
cv.create_text(15, 30, text="Python Greetings", fill="red", anchor='nw')

# now some button widgets
btn1 = tk.Button(cv, text="Click")
btn1.pack(side='left', padx=10, pady=5, anchor='sw')

btn2 = tk.Button(cv, text="Quit")
btn2.pack(side='left', padx=10, pady=5, anchor='sw')

root.mainloop()
sneekula 969 Nearly a Posting Maven

I like nutella, a chocolaty hazelnut spread, sort of like a much improved peanut butter.

scru commented: yum. +6
sneekula 969 Nearly a Posting Maven

Lemmings of northern Norway are one of the few vertebrates who reproduce so quickly that their population fluctuations are chaotic, rather than following linear growth.

sneekula 969 Nearly a Posting Maven

A toasted Sara Lee cinnamon raisin bagel with Nutella hazelnut spread, OJ to drink..