Gribouillis 1,391 Programming Explorer Team Colleague

Go to www.google.com and type 'set the path in windows 7' (or vista, or XP, etc). Follow the instructions of one of the first links on how to set the path in windows. Once you're at the step of editing the path, simply add ;C:\python27 to your path. Do this in an administrator account if possible.

Gribouillis 1,391 Programming Explorer Team Colleague

If you are ready to use python 2, you can write it very easily using a class I wrote in this code snippet http://www.daniweb.com/software-development/python/code/258640 .
Here is a possible code

from optcmd import OptCmd

AB = dict()

class AddressBookCmd(OptCmd):
    def emtpyline(self):
        pass
    
    def do_add(self, name, email, phone):
        """
        usage: add name email phone
        
            Add an entry in the address book.
        """
        AB[name] = [email, phone]
        
    def do_get(self, name):
        """
        usage: get name

            Retrieve the address book's entry for name.
        """
        if name in AB:
            print("{n}\n\temail: {e}\n\tphone: {p}".format(
                  n = name, e = AB[name][0], p = AB[name][1]))
        else:
            print("No such name in the address book.")
                  
if __name__ == "__main__":
    cmd = AddressBookCmd()
    cmd.prompt = "[AB] "
    cmd.cmdloop("Welcome to the Address Book".center(72))


""" Example session

                      Welcome to the Address Book                       
[AB] add Joshua sho0uk0m0o@gmail.com "(802) 3-5-2206"
[AB] add Ashley a000@gmail.com "(802) 820-0000"
[AB] get Joshua
Joshua
	email: sho0uk0m0o@gmail.com
	phone: (802) 3-5-2206
[AB] get Woooee
No such name in the address book.
[AB] help get

usage: get name

    Retrieve the address book's entry for name.

[AB] quit
"""

I couldn't find the time to translate optcmd into python 3 until now ...

Gribouillis 1,391 Programming Explorer Team Colleague

Ah, that makes sense.

In the context of the code you just posted, what are the advantage(s) from using the update_wrapper to make temp_func look like orig_func (which is sqrt() in this example)?

Thanks again.

The first advantage is sqrt's docstring which gets copied into temp_func(). For example if you write

@is_value_pos
def sqrt(val):
    "compute the square root"
    etc

then typing >>> help(sqrt) in a python shell will still print the help despite the fact that the original sqrt() was wrapped into temp_func(). This is also useful for some automated documentation tools like pydoc. Some tracing or debugging modules may also use the function's name ( sqrt.__name__ ).
Published python decorators always include the update_wrapper() call, because update_wrapper() was precisely designed for this use case. However, your decorator would work without this call.

Gribouillis 1,391 Programming Explorer Team Colleague

I understand that sqrt=is_val_pos(sqrt) after the first call to is_val_pos, but why does the call to is_val_pos(sqrt) immediately enter temp_func? Shouldn't it enter the decorator, then enter the temp_func function?
Also, where is temp_func being called? All I see the decorator doing is defining the function, but not calling it. Where does temp_func get called?

Thanks for your help, Gribouillis!

The first call to is_val_pos() doesn't call temp_func(). temp_func() is called every time your code calls sqrt() since sqrt() was replaced with temp_func(). Then temp_func() calls the original sqrt() if the argument is >= 0. Here is a version with more prints

def is_val_pos(orig_func):
	print 'Entering is_val_pos()'
	def temp_func(val):
		print 'Entering temp func()'
		if val < 0:
			return 0
		else:
			return orig_func(val)
	return temp_func

@is_val_pos
def sqrt(val):
	print 'Entering sqrt() method'
	import math
	return math.pow(val, (1.0/2))

for value in (-1, 4, 16):
    print "Calling sqrt() with value %s" % str(value)
    rv = sqrt(value)
    print "sqrt() returned %s" % str(rv)

""" my output --->
Entering is_val_pos()
Calling sqrt() with value -1
Entering temp func()
sqrt() returned 0
Calling sqrt() with value 4
Entering temp func()
Entering sqrt() method
sqrt() returned 2.0
Calling sqrt() with value 16
Entering temp func()
Entering sqrt() method
sqrt() returned 4.0
"""
Gribouillis 1,391 Programming Explorer Team Colleague

The code

@is_val_pos
def sqrt(val):
	print 'Entering sqrt method'
	import math
	return math.pow(val, (1.0/2))

is equivalent to

def sqrt(val):
	print 'Entering sqrt method'
	import math
	return math.pow(val, (1.0/2))
sqrt = is_val_pos(sqrt)

This show that is_val_pos() is only called once after the definition of sqrt(), and then, sqrt() becomes the function temp_func() returned by is_val_pos(). A slight improvement is to use update_wrapper():

from functools import update_wrapper

def is_val_pos(orig_func):
	print 'Entering decorator'
	def temp_func(val):
		print 'Entering temp func'
		if val < 0:
			return 0
		else:
			return orig_func(val)
        update_wrapper(temp_func, orig_func)
	return temp_func

This makes temp_func() look more like sqrt(). For example after the definition, the value of sqrt.__name__ will be "sqrt" and not "temp_func" .

Gribouillis 1,391 Programming Explorer Team Colleague

Still another version which doesn't need to sort the items (L could be any iterable)

from functools import reduce

def my_add(D, (x, y, z)):
    D[(x, y)] = int(z) + D.get((x, y), 0)
    return D

print reduce(my_add, L, dict())

""" my output -->
{('EEE', 'FFF'): 77, ('BBB', 'AAA'): 444, ('CCC', 'DDD'): 321}
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Oh and one more thing......look at that link ouposted carefully......you will find my email adress too......thearc@gmail.com..........That idiot could have atleast changed that........really pathetic .............i cant believe it.........

I think this site automatically crawls the web and publishes forum posts at random.

Gribouillis 1,391 Programming Explorer Team Colleague

Use sorted() and itertools.groupby()

from itertools import groupby

data = """
BBB AAA 111
CCC DDD 222
BBB AAA 333
EEE FFF  77
CCC DDD 99
"""

def pair(item):
    return tuple(item[:2])

L = [x.strip().split() for x in data.strip().splitlines()]
print L
R = [ [x, y, str(sum(int(z[2]) for z in g))] for (x, y), g in groupby(sorted(L, key=pair), key=pair) ]
print R

""" my output -->
[['BBB', 'AAA', '111'], ['CCC', 'DDD', '222'], ['BBB', 'AAA', '333'], ['EEE', 'FFF', '77'], ['CCC', 'DDD', '99']]
[['BBB', 'AAA', '444'], ['CCC', 'DDD', '321'], ['EEE', 'FFF', '77']]
"""
Gribouillis 1,391 Programming Explorer Team Colleague
>>> print(unicode(urllib2.unquote('%D8%A7%DB%8C%D9%84%D8%A7%D9%85'), 'utf8'))
ایلام
>>> print(u'ایلام'.encode('utf8'))
Unsupported characters in input

>>>

On my computer

>>> import urllib2
>>> urllib2.quote('ایلام')
'%D8%A7%DB%8C%D9%84%D8%A7%D9%85'
Gribouillis 1,391 Programming Explorer Team Colleague

Also the decimal module exists in python 2.6. According to the source code, it was written in 2004 for python 2.3. If you need it, use it, either by upgrading to a version of python with the decimal module, or by using the attached version

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

It would be better to compute with floating numbers to avoid division issues (like 5/9 == 0)

def nearest_int(number):
    return int(number + (0.5 if number >= 0 else -0.5))

print "%d Degrees Farenheit" % nearest_int(float(fc) * 9 / 5 + 32)

Also it would be much better to use the optparse or argparse module to handle command line arguments and options. Read this tutorial http://www.alexonlinux.com/pythons-optparse-for-human-beings

Gribouillis 1,391 Programming Explorer Team Colleague

Simply unindent the last line out of the 'for' loop

key1 = [' ','a','b','c','0','1','2','3']
out = ''
inpt = raw_input('enter text:')

for i in inpt:
    if i in key1:
        out = out + key1[key1.index(i)+3]
print out
Gribouillis 1,391 Programming Explorer Team Colleague

Thats work. Thank you very much

In fact the code can be simplified a little because the tab is a Button widget, and you can get the name through the button:

title = 'Pmw.NoteBook demonstration'

# Import Pmw from this directory tree.
import sys
#sys.path[:0] = ['../../..']

import Tkinter
import Pmw

class Demo:
    def __init__(self, parent):
	# Create and pack the NoteBook.
        notebook = Pmw.NoteBook(parent)
        self.notebook = notebook # <-- ADDED
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)

        # Add the "Appearance" page to the notebook.
        page = self.add_page('Appearance')
        notebook.tab('Appearance').focus_set()

        # Create the "Toolbar" contents of the page.
        group = Pmw.Group(page, tag_text = 'Toolbar')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar')
        b1.grid(row = 0, column = 0)
        b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips')
        b2.grid(row = 0, column = 1)

        # Create the "Startup" contents of the page.
        group = Pmw.Group(page, tag_text = 'Startup')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        home = Pmw.EntryField(group.interior(), labelpos = 'w',
            label_text = 'Home page location:')
        home.pack(fill = 'x', padx = 20, pady = 10)

        # Add two more empty pages.
        page = self.add_page('Helpers')
        page = self.add_page('Images')

        notebook.setnaturalsize()
  
    def add_page(self, pagename):
        page = self.notebook.add(pagename)
        self.notebook.component(pagename+"-tab").bind("<1>", self.showname)
        return page
        
    def showname(self, event):
        print event.widget.cget("text")

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
    root = Tkinter.Tk()
    Pmw.initialise(root)
    root.title(title)

    widget = Demo(root)
    exitButton = Tkinter.Button(root, text = 'Exit', command …
Gribouillis 1,391 Programming Explorer Team Colleague

thanks for answer.it works when i click on frame but dont works when i click "Appearance" tab text. is it possible write pagename when i clicked tab?

It was more difficult. The following code works for me

title = 'Pmw.NoteBook demonstration'

# Import Pmw from this directory tree.
import sys
#sys.path[:0] = ['../../..']

import Tkinter
import Pmw
from functools import partial

class Demo:
    def __init__(self, parent):
	# Create and pack the NoteBook.
        notebook = Pmw.NoteBook(parent)
        self.notebook = notebook # <-- ADDED
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)

        # Add the "Appearance" page to the notebook.
        page = self.add_page('Appearance')
        notebook.tab('Appearance').focus_set()

        # Create the "Toolbar" contents of the page.
        group = Pmw.Group(page, tag_text = 'Toolbar')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar')
        b1.grid(row = 0, column = 0)
        b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips')
        b2.grid(row = 0, column = 1)

        # Create the "Startup" contents of the page.
        group = Pmw.Group(page, tag_text = 'Startup')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        home = Pmw.EntryField(group.interior(), labelpos = 'w',
            label_text = 'Home page location:')
        home.pack(fill = 'x', padx = 20, pady = 10)

        # Add two more empty pages.
        page = self.add_page('Helpers')
        page = self.add_page('Images')

        notebook.setnaturalsize()
  
    def add_page(self, pagename):
        page = self.notebook.add(pagename)
        self.notebook.component(pagename+"-tab").bind("<1>",partial(self.showname, pagename))
        return page
        
    def showname(self, name, event):
        print name

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
    root = …
Gribouillis 1,391 Programming Explorer Team Colleague

You can bind each page of the notebook (each page is a Frame)

title = 'Pmw.NoteBook demonstration'

# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']

import Tkinter
import Pmw

class Demo:
    def __init__(self, parent):
	# Create and pack the NoteBook.
        notebook = Pmw.NoteBook(parent)
        self.notebook = notebook # <-- ADDED
        notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)

        # Add the "Appearance" page to the notebook.
        page = self.add_page('Appearance')
        notebook.tab('Appearance').focus_set()

        # Create the "Toolbar" contents of the page.
        group = Pmw.Group(page, tag_text = 'Toolbar')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        b1 = Tkinter.Checkbutton(group.interior(), text = 'Show toolbar')
        b1.grid(row = 0, column = 0)
        b2 = Tkinter.Checkbutton(group.interior(), text = 'Toolbar tips')
        b2.grid(row = 0, column = 1)

        # Create the "Startup" contents of the page.
        group = Pmw.Group(page, tag_text = 'Startup')
        group.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
        home = Pmw.EntryField(group.interior(), labelpos = 'w',
            label_text = 'Home page location:')
        home.pack(fill = 'x', padx = 20, pady = 10)

        # Add two more empty pages.
        page = self.add_page('Helpers')
        page = self.add_page('Images')

        notebook.setnaturalsize()
  
    def add_page(self, pagename):
        page = self.notebook.add(pagename)
        page.bind("<1>",self.showname)
        return page
        
    def showname(self, event):
        print self.notebook.getcurselection()

######################################################################

# Create demo in root window for testing.
if __name__ == '__main__':
    root = Tkinter.Tk()
    Pmw.initialise(root)
    root.title(title)

    widget = Demo(root)
    exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
    exitButton.pack()
    root.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

Thanks Gribouillis,
Now it works, but it en/decodes the string in all encodings.
I want to select the encoding freely, for example, something like this:

en1 = encoder('String One', 2)# for base64
en2 = encoder('String Two', 3)# for hex
#en3 = ....
#and so on

I don't understand, doesn't it work as expected ? Please describe the expected output of your program and, if it "doesn't work", why it doesn't produce the expected output, or if it raises an exception, which exception ?

Gribouillis 1,391 Programming Explorer Team Colleague

It works for me and python 2.6

codes=['zlib', 'zip', 'base64', 'hex', 'utf-8']

def encoder(str, i):
    return str.encode(codes[i])

def decoder(str, i):
    return str.decode(codes[i])

thing = 'Some string here'
for i, k in enumerate(codes):
    en = encoder(thing, i)
    assert thing == decoder(en, i)
    
print "success"
Gribouillis 1,391 Programming Explorer Team Colleague

Really Thank you Gribouillis for your fast reply.

Yes! zip is what I was in need of Exactly.

I came up with this:

list1=['Item1', 'Item2', 'Item3', 'Item4']
list2=['1','2','3','4']

for i,j in zip(list1, list2):
    print '%s______%s'%(j, i)

and the Result:

1______Item1
2______Item2
3______Item3
4______Item4

Just Curious, Can it be done in another way?

It can always be done in different ways, but zip is the correct tool. You could loop on indexes

for i, item1 in enumerate(list1):
    item2 = list2[i]
    # do something with item1 and item2

You could also use a generator

def my_strings(list1, list2):
    it1, it2 = iter(list1), iter(list2)
    while True:
        yield "%s____%s" % (next(it1), next(it2))

for s in my_strings(list1, list2):
    print s
Gribouillis 1,391 Programming Explorer Team Colleague

Hint

>>> list1 = range(10)
>>> list2 = range(100, 110)
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list2
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
>>> list3 = zip(list1, list2)
>>> list3
[(0, 100), (1, 101), (2, 102), (3, 103), (4, 104), (5, 105), (6, 106), (7, 107), (8, 108), (9, 109)]

Edit: in python 3, use list(zip(list1, list2))

Gribouillis 1,391 Programming Explorer Team Colleague

Hey guys,

I am writing a GUI program, and one of the routines requires that I choose a file to be my data file. If the data file is chosen correctly, then my program will send it to a subroutine which will perform a bunch of methods and ultimately construct a large matrix and return it.

Obviously, a user can import the wrong file, and when my subroutines act on this, then they are going to error. Because the user can import a bunch of different wrong files, I can't anticipate what error will present itself. For example, IndexError vs. ValueError. Therefore, I'd like to do something like is presented in the following metacode:

Imported file = f

Try:
  Run subroutines on f
Except AllErrorsImaginable:
  Run some complaint statement

Basically, I can't think of a better way of doing this without just putting every error type in the ``AllErrorsImaginable'' block. This doesn't seem very elegant. Any tips?

Use except Exception . The except statement catches exceptions from derived classes, and almost all exception classes in python are subclasses of Exception.
Also the traceback module can help you with the complaint statements (for example you can call traceback.print_tb())

Gribouillis 1,391 Programming Explorer Team Colleague

I tried both solutions and didn't seem to have a problem with either one when running the commands in a command line but the variables still don't seem to be sending over properly. Perhaps the error is somewhere else in my code?
The function is supposed to take each line the the csv file and first decide if the first entry is a date and if the date is for the present month (these two functions are laid out elsewhere in the python file). Then, it checks if the date of the entry is within the last week. Depending on how far into the past week, it assigns the entries for the line to variables shared with another program and then should go through the same process for all the other rows in the csv file.
Here is the whole function definition:

def send_data():
    for i, record in enumerate(reader):
        if (i > 0) and (len(record) > 7): #skip headers
            date = record[0]
            hk = record[1]
            ba = record[2]
            bsp = record[3]
            hgch = record[4]
            v995 = record[5]
            v996 = record[6]
            vct = record[7]
            month, day, year = [int(x) for x in date.split('/')]
            evt_date = dt.datetime(year, month, day)
            if (event(date)) and (curr_month(date)):
                if evt_date.day >= curr.day - 6:
                    if evt_date.day == curr.day - 6:
                        svars.date1 = date
                        svars.hk1 = hk
                        svars.ba1 = ba
                        svars.bsp1 = bsp
                        svars.hgch1 = hgch
                        svars.v9951 = v995
                        svars.v9961 = v996
                        svars.vct1 = v995 + v996
                    elif evt_date.day == curr.day - 5:
                        svars.date2 = date …
Gribouillis 1,391 Programming Explorer Team Colleague

Thanks again.I think its working but i am getting some special characters The printed code does not look like this one..-->> "\x01\x00\x12\x59"..If the printed special chars are equivalent to binary data can i send that through socket like i have mentioned in the main post.like

from binascii import hexlify, unhexlify
import socket
s = "04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00"
ss = s.replace(" ", "")
binary = unhexlify(ss)
print binary
sock.send(binary)

To print binary strings, you should print their repr():

>>> print repr(binary)
'\x04\xf8\x00PO0\xfbG(b\xa7mP\x02\x02\x00\xd2\x7f\x00\x00'

Otherwise, yes, you can send your binary string in the socket; hexlify() and unhexlify() are robust functions.

Gribouillis 1,391 Programming Explorer Team Colleague

thanks a lot for your reply..But one thing i wanna know what abou converting "04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00" hex in a format like this "\x01\x00\x12\x59"

Remove white space and use unhexlify()

s = "04 f8 00 50 4f 30 fb 47 28 62 a7 6d 50 02 02 00 d2 7f 00 00"
ss = s.replace(" ", "")
binary = unhexlify(ss)
debasishgang7 commented: 3 +3
Gribouillis 1,391 Programming Explorer Team Colleague

The error means that one of the records does not have length 8. The first solution is to print it to see what happens

from itertools import islice

for i, record in islice(enumerate(reader), 1, None):
    if len(record) != 8:
        raise ValueError, "Bad record at line %d : %s" % (i+1, str(record))
    else:
        date, hk, ba, bsp, hgch, v995, v996, vct = record
Gribouillis 1,391 Programming Explorer Team Colleague

Use functions hexlify() and unhexlify() in module binascii for this

>>> from binascii import hexlify, unhexlify
>>> s = '\x01\x00\x12\x59'
>>> h = hexlify(s)
>>> print h
01001259
>>> assert unhexlify(h) == s
>>>
Gribouillis 1,391 Programming Explorer Team Colleague

Here is what I updated but it did not change my output at all.

#!/usr/bin/env python

import csv
import random
from string import ascii_lowercase as alpha
x = random.sample(alpha,14)

c = csv.writer(open("test3.csv", "wb"))
c.writerow([x])

cr = csv.reader(open("test3.csv","rb"))

for row in cr:
        print ",".join(str(elt) for elt in x)

print "How many rows?"
l = raw_input()

k = 1

while k < int(l):

        y = random.sample(range(99), 14)
        c.writerow([y])

        cr = csv.reader(open("test3.csv","rb"))

        for row in cr:
                print ", ".join(str(elt) for elt in y)
        k +=1

print "done"

Here is a modified version which should work. It's not good to keep a file opened for reading and for writing at the same time, or to open a file many times in a loop.

#!/usr/bin/env python

import csv
import random
from string import ascii_lowercase as alpha


with open("test3.csv", "wb") as out_f: # <--- using 'with' ensures that the file is closed automatically
    c = csv.writer(out_f)
    x = random.sample(alpha,14)
    c.writerow(x)
    nrows = int(raw_input("How many rows? "))
    r = range(99)
    for k in range(nrows):
        y = random.sample(r, 14)
        c.writerow(y)

with open("test3.csv", "rb") as in_f:
    cr = csv.reader(in_f)
    for row in cr:
        print ", ".join(str(elt) for elt in row)

print "done"

""" my output -->
How many rows? 4
f, p, t, q, g, i, c, k, x, b, m, e, y, r
46, 75, 22, 98, 8, 78, 79, 37, 84, 30, 49, 86, 41, 34
15, 42, 34, 35, 5, 32, 18, 54, 91, 61, 51, 0, 95, 88
59, 3, 16, 56, 15, 42, …
Gribouillis 1,391 Programming Explorer Team Colleague

Nothing changed

The problem is that when you print a list, it prints the repr() of the list elements. To remove the quotation marks, you must apply str() to each element and join the results with commas

>>> import random
>>> from string import ascii_lowercase as alpha
>>> x = random.sample(alpha,14)
>>> print x
['m', 'y', 'b', 'k', 'z', 't', 'a', 'r', 'n', 'o', 'c', 'w', 'q', 'v']
>>> print ", ".join(str(elt) for elt in x)
m, y, b, k, z, t, a, r, n, o, c, w, q, v
>>> def print_list_elements(alist):
...  print ", ".join(str(elt) for elt in alist)
... 
>>> print_list_elements(x)
m, y, b, k, z, t, a, r, n, o, c, w, q, v
>>>
>>> x = random.sample(range(99), 14)
>>> print_list_elements(x)
74, 40, 97, 96, 36, 86, 19, 6, 4, 30, 0, 34, 46, 35
Gribouillis 1,391 Programming Explorer Team Colleague

Oh I'm sorry, looking at it again it is a mess. Maybe this renamed version is clearer.

Basically the situation would be where I know the fixed cost (the contribution cost) lets say is $17,800. However, the other costs (the one allowed to change, it is more than one cost but since I'm using the total of those costs it is only one number) are a total of $24,420 which is 58% of the Full Total cost $42,220. I need to have the "Other Costs" be 75% of the Full Total. Since this situation sometimes comes in other forms I wanted to make a program that can deal with it.

The method I was trying to emulate was the crude method where you keep adding one to the "Other Costs" and double checking to see if it 75% of the Full Total Costs and if not, then adding one again and so forth until the "Other Costs" is 75%. I'm sure there are other methods but I chose this method because I wanted to practice looping or iterations.

Yes, you are trying to write your own 'equation solver' or 'root finding' algorithm for the equation other == proportion * (fixed + other) where the unknown is 'other'. Iterative methods to solve algebraic equations exist, but as griswolf said, this equation is elementary and can be solved immediately, so the best program would be

fixed = float(raw_input('Enter the fixed amount: $ '))
proportion = float(raw_input('Enter the proportion of variable costs: …
Gribouillis 1,391 Programming Explorer Team Colleague

Hi all,

I'm new to this forum and I am also new to Python and coding in general. While I've gotten through basic tutorials on most general topics of Python such as series, dictionary, parameters, loops, and so forth I am still very much a newbie (as you will see in this program I attempted)

My boss at work wanted me to solve a simple math problem in order to help her create a new budget based on a recent grant our organization received. I eventually just did it the basic math way, however I wanted to test out my Python abilities so I tried to make a program to solve it.

Can someone please help me figure out how to get this code to work?

##Solve situation when: one fixed, one variable, one total of fixed + variable
##The OtherSub must be 75% of Total, the Contribution must stay fixed
##The Total can increase but not decrease

Contribution = input('Enter the fixed amount: ')
Other = input('Enter the other variable amount: ')
Total = Contribution + Other

##Putting a = 3. allows for .75 whereas simply 3/4 would give 0
a = 3.
b = 4
c = a / b

While Other / Total <= c:
    print Other
    print Other / Total
    OtherSub + 1
If OtherSub / Total == c:
    print 'The new Other Subtotal is ' + Other

I agree with griswolf that your statement of the problem is unclear, it seems that you give different …

Gribouillis 1,391 Programming Explorer Team Colleague

just a question, if i want the user to choose if he can play again then i just put

print 'the number was ' + str(x)
again=raw_input("play again? ")

or do i do something else?

It's ok, but you can do a little better: offer a default option (yes), and then you must translate the answer into a boolean

again = raw_input("play again? [y] ").strip().lower()
again = (again in ('', 'y', 'yes')) # now again is True or False

strip() removes white space at both ends, in case the user enters " yes " , and lower() converts to lowercase (if the user enters "Yes").

Gribouillis 1,391 Programming Explorer Team Colleague

Hm, it could be a firewall issue. Normally, idle uses the port 8833. You may have to open this port on your firewall.

Gribouillis 1,391 Programming Explorer Team Colleague

You can loop indefinitely with while True . Here is the code

import random
import re

print 'This is a guessing game'

def game(guess):
    x=random.randint(1,100)
    while True: # loop indefinitely
        respond = int(raw_input(guess)) # better than input()
        if respond < x:
            print 'nop higher'
        elif respond > x:
            print 'wow too much'   
        else:
            assert respond == x # necessarily true. We may assert it for debugging
            print 'you got it!!'
            print 'the number was ' + str(x) # must convert to string for addition
            break # exit the loop

game("Guess a number: ")

In python 2, use raw_input(), which reads a string, and convert the string to int instead of using input(). (in python 3, input() is python 2's raw_input().)

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

Thank you for your reply
however, after trying these codes
it encounters the same problem:

"Traceback (most recent call last):
IndexError: list index out of range"

IndexError may also mean that the records don't have the same number of fields, or that they apparently don't. For example if the records are separated by tab characters, it may be better to split them with record.split("\t") . It may also be useful to get rid of newline characters at the end of the line with rstrip: record.rstrip().split("\t") . Otherwise, you must add tests to know exactly where the problem happens in the input file or in the python script, and why.

For example, you could chek the length of the rows with

all_length = set(len(row) for row in rows)
print all_length # should print set([52])
Gribouillis 1,391 Programming Explorer Team Colleague

You are splitting each record 52 times. It's very inefficient. Perhaps you could speed things up with

rows = [ record.split() for record in file ] # warning: contains megabytes
ncols = len(rows[0])
cols = [ [record[i] for record in rows] for i in xrange(ncols) ] # doubling the used memory
# now cols should be a list of 52 lists, each representing a column
del rows # if we don't need the rows from now on

# if you want to index them on ascii letters (why would you do that ?), use a dictionary
import string
D = dict((x, cols[i]) for i, x in enumerate(string.ascii_letters))

# Now D["a"] should be the first column, etc
# If you want to create variables a, b, .. Z with the lists (why would you do that ?), use
globals().update(D)
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest

entry0 = "'{e:0>7}'".format(e=entry[0])
Gribouillis 1,391 Programming Explorer Team Colleague

Math, is not something we do because we love it or like it, or even want to make money, it is more of an unhealthy obsession like smoking, drugs or sex addiction.

I woudn't agree about math being unhealthy. Math is a part of science. Science is about discovering and studying the laws of nature. Math is addictive like any other exciting activity.

You can't automate a system with a program if you can't describe precisely the rules, so we'll wait for your set of rules.

If you're having a difficult time writing down your ideas with latex, I suggest that you turn to texmacs which is easy, wysiwyg, and produces the same quality. See http://texmacs.org/ .

Gribouillis 1,391 Programming Explorer Team Colleague

oooooo, so if I wanted to define a namespace, would make a folder with the same name as the namespace with a text file inside called __dict__, containing:

'example' :'/path/to/a/file/called/example.py',
'example2', :''/path/to/a/file/called/example2.py'
'example3', :''/path/to/a/file/called/example3.py'

where 'example2.py' contains your 'the_ultimate_function()'

and then use that function, and variables in the namespace by saying:

from example import *

and then add that original folder to my PATH or PYTHONPATH?

No, no, not at all. You don't need to define namespaces, and python defines __dict__ for you. If you want to use modules and imports, read this http://docs.python.org/py3k/tutorial/modules.html

Gribouillis 1,391 Programming Explorer Team Colleague

Thanks for the great interest in helping me here. To clarify, the rules:

1. 1 cannot be adjacent to B
2. 0 cannot be adjacent to A
3. A cannot be adjacent to another A
4. B cannot be adjacent to another B
5. inside the Brackets represent a repeating pattern, so the ends ARE adjacent to each other (to answer wooee) e.g. A[010]=A[100], B[011]0B=B[110]B, but I'm not sure now how or when to make the decision to rotate form the string. I think the goal is the shortest possible string with these rules. So perhaps when no length changes, as is the case with A[010]=A[100], the rule is unnecessary. I think it's good to know the choice is there in case it is helpful like in B[011]0B=B[110]B, but how does the program know which string is shortest without checking every rotation inside the brackets? Also, the answer is inherently non-deterministic, since it's a context sensitive grammar, so don't worry if there are two or more right answers of the same shortest length. Again, the goal is the shortest version of the string.

My goal *IS* a formalization of this procedure, hopefully with a tractable algorithm, so sorry in advance that I can't share it due to it's lack of existence. I can try to explain it informally as best as I can. Please continue to ask questions if you still have them for me.

A[0] DOES convert to just A, and actually [0] also converts …

Gribouillis 1,391 Programming Explorer Team Colleague

A takes out A & 0 also through brackets, B takes out B & 1 also through brackets, things inside bracket can be rotated -> A[anything]B becomes A[]B, so I understood.

Of course from last form B]B would stil become B] or ]B, by these rules or through rotation B takes out first 1.

The OP should explain the rules more precisely. I'm not sure that you apply the correct rules since the OP says that 'A[A[001]BB1A10]11BA10' becomes 'A[1A[100]BA]BA10'.

By the way, in mathematics, a set of symbols with such kind of rules is called a formal system. Formal systems play a key role in logic.

Gribouillis 1,391 Programming Explorer Team Colleague

For me by hand and considering rotation and effect through brackets the example should transform like this:

str='A[A[001]BB1A10]11BA10'
-> 'A[A[]BA10]1BA10'
-> 'A[0A[]BA1]1BA10'
-> 'A[A[]BA1]1BA10'
-> 'A[[]BA1]1BA10'
-> 'A[A1[]B]1BA10'
-> 'A[1[]B]1BA10'
-> 'A[1[]B]BA10'

Nothing in the rules indicates that [001] becomes []. I think the first phase is to replace the pattern "0*(A0*)+" by "A" and similarly, "1*(B1*)+" by "B". This can be done before anything else.

Gribouillis 1,391 Programming Explorer Team Colleague

oo, huh, thats interesting, I am pretty sure I understand it.. at least basically. But if globals() is just one of the three default namespaces (locals() and builtins() being the other two) back to my initial question: if we execute a function as a variable, such as was suggested in:

globals()[variable]

and not using

locals()[variable]

or

builtins()[variable]

are all user declared functions automatically added by the compiler to the globals() namespace?

No, functions defined at top level in the main program or a module are automatically added to the global namespace of that module (each module, like most class instances, have a member __dict__ which is a dictionary). Functions defined in the body of a class definition are added to the classe's __dict__.

The concept of global namespace, or local namespace is rather a dynamic concept. When the program executes, whenever the cursor is, there is a local namespace and a global name space. For example

# this is the source file of a module XXX

def the_ultimate_function():
    x = 1
    print "hello" # <---- suppose that we are currently executing this statement

When 'print "hello"' is executed, the global namespace is the dictionary __dict__ of the current module XXX (which contains for example a key 'the_ultimate_function') and the local namespace is a dictionary created when the function's execution starts. This dictionary currently contains { 'x': 1 }.

When you call globals() or locals(), python returns the current global and local dictionaries.

Gribouillis 1,391 Programming Explorer Team Colleague

I don't think the OP is still waiting for the answer after 3 years :)

Gribouillis 1,391 Programming Explorer Team Colleague

To start with, here is a function wich transforms your input data into a python list, which should be easier to handle than a string

# stringgame.py

import re
word_re = re.compile(r"[AB01]+")


def sub_func(match):
    """helper for parse()"""
    return "'%s'," % match.group(0)

def parse(data):
    """transform an input string into a python list"""
    x = word_re.sub(sub_func, data)
    x = x.replace("]", "],")
    return eval("[%s]" % x)

if __name__ == "__main__":
    test_data = 'A[A[001]BB1A10]11BA10'
    the_list = parse(test_data)
    print the_list
    
""" my output -->
['A', ['A', ['001'], 'BB1A10'], '11BA10']
"""
Gribouillis 1,391 Programming Explorer Team Colleague

In python a 'variable' is usually called a 'name'. Each name belongs to a certain 'namespace' which is a python dictionary. Here, your statement def testF(): ... inserts the name "testF" in the global namespace, which is accessible by calling globals() . So your reflect function could be written

def reflect(functionname):
    function = globals()[functionname]
    return function()

edit: oops, tony was faster :)

Gribouillis 1,391 Programming Explorer Team Colleague

In python 2.6, I have both

>>> import wx
>>> wx.Color
<class 'wx._gdi.Colour'>
>>> wx.Colour
<class 'wx._gdi.Colour'>

You could add a piece of code like

import wx
if hasattr(wx, "Color"):
    wx.Colour = wx.Color
else:
    wx.Color = wx.Colour
Gribouillis 1,391 Programming Explorer Team Colleague

Ok thanks for helping.It was a long discussion.
Thanks again.

last thing, you may be interested in the standard module tabnanny (see info here http://effbot.org/librarybook/tabnanny.htm) and by the pep 8 advices http://www.python.org/dev/peps/pep-0008/ . Good luck.

Edit: you don't need to install tabnanny. It comes with your python distribution.

hszforu commented: very helping. +1
vegaseat commented: thanks +15
Gribouillis 1,391 Programming Explorer Team Colleague

i was doing the same, i mean the idle i was using,was configured with 4 spaces by default.
So does it mean that i will have to indent the script manually everytime?

No, for some reason there was a tab character "\t" in your first post instead of 4 spaces " " .

Normally you don't have to reindent python code.

Gribouillis 1,391 Programming Explorer Team Colleague

hey it works after i do it manually,and the script also runs correctly as expected but any ideas how should i perform the identation in future for larger programs.
Thanks again.

In the future, always use an editor where indentation is configured with 4 spaces (like your idle), and if you find a bad indentation in a forum post or in a 3rd party program, try to use "reindent" to clean the script.

Gribouillis 1,391 Programming Explorer Team Colleague

after reindenting the file is like this:

def print_lol(movies):
for each in movies:
if isinstance(each,list):
print_lol(each)
else:
print(each)

Well, I've never seen that. If it is not too long, reindent it by hand with idle, it should look like

def print_lol(movies):
    for each in movies:
        if isinstance(each,list):
            print_lol(each)
        else:
            print(each)