jlm699 320 Veteran Poster

Or what about using chr() and then just adding 65?:

>>> def numtolet(num):
...     return chr(num + 65)
...     
>>> numtolet(1)
'B'
>>> numtolet(12)
'M'
>>> numtolet(14)
'O'
>>>

Or the reverse:

>>> def lettonum(let):
...     return ord(let) - 65
...     
>>> lettonum('O')
14
>>> lettonum('A')
0
>>> lettonum('N')
13
>>>
jlm699 320 Veteran Poster

You need to pass a second parameter to the open function which will declare the mode that you're opening the file in. Default (no parameter as in your case) is read mode or 'r'. You want either write or append depending on if you want to wipe the file clean each time you open it or not.

Your open command should look like this (and also here's an example of writing to the file):

f = open('my_file.txt', 'w') # Write mode
f.write('This is some text to write.\n') # \n is newline character
f.write('Here we have more text.\n')
f.close()

HTH

jlm699 320 Veteran Poster

Is there a way to use a string to call a previously named variable?

Eval is what you're looking for:

>>> sports = [1,23,4]
>>> eval( 'sports' )
[1, 23, 4]
>>>
jlm699 320 Veteran Poster

I don't really get what you mean by initially setting a boolean variable to false before the loop.

Like this: my_boolean = False . Now the variable named my_boolean will act as your "flag" to tell you whether a number is "lucky" or not.

Also for the for loop, should I get rid of it? Because if I enter 007, it will print the statements 3 times and I only want it to print once.

Here's what I posted above, maybe you didn't read it last time:

The rest will work except that it will print a message on every character that is evaluated. You should be using a boolean variable that is initially set to false before your loop. If the number 7 is found, change it (the boolean) to True, otherwise do nothing. [EDIT: Meaning this should be the only logic in your for loop. Take everything else out]

After the loop has completed, check if your boolean is true; if so, print the lucky message or otherwise print unlucky.

HTH

jlm699 320 Veteran Poster

When you open your file you should be opening it in append mode using the 'a' flag (right now you're opening it in write mode, 'w').

jlm699 320 Veteran Poster

This is a very hacked solution but:

>>> sports = ## Defined as above - snipped for length
>>> def build_html(chosenCategory):
...     up_locals = sys._getframe(1).f_locals
...     for each_var in up_locals:
...         if id(up_locals[each_var]) == id(chosenCategory):
...             var_name = each_var
...     filename = '%s.html' % (var_name)
...     print filename
...     
>>> build_html(sports)
sports.html
>>>

You could even be brazen and shorten that for loop to a single list comprehension (albeit a very long one):

def build_html(chosenCategory):
    var_name = [each_var for each_var in sys._getframe(1).f_locals if id(sys._getframe(1).f_locals[each_var]) == id(chosenCategory)][0]
    filename = '%s.html' % (var_name)
    print filename
vegaseat commented: actually a good hack +9
qadsia commented: Very Helpful! solved my problem. +0
jlm699 320 Veteran Poster

I never learned the "in" function yet. What if I wanted to use the index code in my code? Like the lucky, is there a way to do it? I haven't learned much about python yet, so I wanted to see if I can use what I've learned to finish this code first.

(learned the index, for loops, while loops and if statement)
Thanks.

You should remove the parenthesis from around your input statement. so it should just be: lucky = raw_input("Enter an integer: ") The rest will work except that it will print a message on every character that is evaluated. You should be using a boolean variable that is initially set to false before your loop. If the number 7 is found, change it to True, otherwise do nothing.

After the loop has completed, if your boolean is true, print the lucky message; otherwise print unlucky.

HTH

jlm699 320 Veteran Poster
jlm699 320 Veteran Poster

I saw it mentioned somewhere on the web that you need to import PyQT4 instead of PyQt4 .

Note the Capital 'T'

jlm699 320 Veteran Poster

thanks a lot man,
there is just one problem, my version of ubuntu does not support any version of python higher than 2.5. awww well. at least i know now to stop trying to get this one to work and start a new project witch might work.

That's not entirely true. You can use the Synaptec Package Manager to download the latest versions of Python. FYI.

jlm699 320 Veteran Poster
self.marks.append(self.twelve.GetValue())
        self.average=sum(self.marks)/len(self.marks)

Note that GetValue returns a string. In order to use sum you'll need to convert all elements of self.marks to integers or floating points. You could probably get away with using a try / except block like this:

>>> marks = ['1','2.5','3','4.2','5','6.6666','7.111']
>>> new_marks = []
>>> for mark in marks:
...     try:
...         new_marks.append(int(mark))
...     except ValueError:
...         new_marks.append(float(mark))
...     
>>> new_marks
[1, 2.5, 3, 4.2000000000000002, 5, 6.6665999999999999, 7.1109999999999998]
>>> sum(new_marks)/len(new_marks)
4.2110857142857139

As you can see I try to convert to int first, and if that fails (as a string representing a floating point will raise a ValueError in the int method), I'll then convert to float . This protects me from failure and allows the script to convert correctly between string to int and/or float.

At this point, you should be okay using the sum function, as your list elements will all be numerical instead of strings.

Alternately, you could use list comprehension to convert to floats on the fly like this:

>>> marks = ['1','2.5','3','4.2','5','6.6666','7.111']
>>> sum([float(mark) for mark in marks])/len(marks)
4.2110857142857139

In this version I only use float, as both an int and float will convert to float whereas a float will not convert to an int so this avoids the failure...
To break that down step by step the list comprehension becomes:

>>> new_marks = []
>>> for mark in marks:
...     new_marks.append(float(mark))
...     
>>> sum(new_marks)/len(new_marks)
4.2110857142857139
>>>

If you have questions about list comprehension just …

jlm699 320 Veteran Poster

I will have to google the changes.

Here you go: http://docs.python.org/dev/3.0/whatsnew/3.0.html

This gives a nice breakdown of the changes between 2.X and 3.X versions of Python. Hope it helps!

jlm699 320 Veteran Poster

1) This program has no indentation. To preserve formatting on this forum you must wrap your code in code tags. However after looking closer at your post it appears that your code has no indentation even in its original form.

2) You need to learn the difference between defining a function and calling one. You should never ever ever ever ever be defining a function inside a loop or any other regular code unless it truly needs to be a dynamic function (which you'll likely never encounter).

vegaseat commented: good points +9
jlm699 320 Veteran Poster

Oh, and also in response to:

I just need to know how the pygtk progressbar works, on the internet I can't find any good info about it ...

Not sure what you were using to search, but try this

EDIT: And one more thing.

I see that your function ftp is part of a class (has self as the first parameter) along with progress_timeout , but progress_timeout lacks the self parameter. This is incorrect usage. Either add the self parameter or move that function back out to the global level like my above linked example.

jlm699 320 Veteran Poster

the progress bar only shows 100% and doesn't progress at all..

A progress bar is only useful if you're actually progressing through something. The steps that happen before you send the 100% to the progress bar are like going so fast that you can't see the "progress" of your function.

Also, to call a function you need to use parenthesis. None of your calls to progress_timeout are actually running. All you're doing is getting is the reference to that object on stdout. Reading through that function I'm not sure you should even be calling it at all though. But that's for you to discover.

Additionally, you should really use a function to do the progress updates since you have so much repeat code, it will cut down on the clutter and make it easier to read what this function does:

def set_progress(self, percent):
        ''' Sets the text, fraction and then calls progress_timeout
        @ Inputs
        - percent    Floating point representing the progress percent
        '''

        self.pbar.set_text('%i%%' % progress)
        self.pbar.set_fraction(progress)
        self.progress_timeout(self)
        return

Then each of your "updates" for the progress bar should be called as self.set_progress(0.1) . But the problem of executing code quickly before seeing progress still exists... You could add time.sleep(1) to the function so that after each update the program hangs for 1 second.

EDIT: I also have to re-iterate that I REALLY don't think you should be trying to call progress_timeout.

jlm699 320 Veteran Poster

hi,
now i got the login page using the django In that page, i can create the groups ,users etc. i want to implement my application as web application using django on mac. so can u tell me the solution..

Tutorial. Please. Search the web before you ask these types of questions. We're not here to write custom code for you or perform your basic web searches. You're not even trying, which goes against the general forum policies.

If you have a specific question about brain-storming or concepts we can help to explain them. If you need help with troubleshooting or improving code you've already written, we can help with that too, provided that you give us the code and explain what you want. The rule of thumb is words for words and code for code.

jlm699 320 Veteran Poster

There's no need to split the string, just simply iterate over it and perform your counting. To make a string upper case use the upper function.

jlm699 320 Veteran Poster
c.execute("UPDATE a SET last = %s", row)

what is the wrong thing that I am doing here?

I believe you forgot to replace the comma (,) with a percentage sign (%). Shouldn't the above code be:

c.execute("UPDATE a SET last = %s" % row)

?

HTH

jlm699 320 Veteran Poster

Mensa: your code was very well structured and a nice example of reading user input then using it for calculation. Here's how I've modified your code:

def calc_payment(int_rate, num_pmnts, principal, freq):
    ''' This function will calculate the payment amount of a loan.
    @ Inputs
    - int_rate  - The interest rate of the loan
    - num_pmnts - The number of payments required
    - principal - The original amount of the loan (minus down-payment)
    - freq      - Frequency of payments (weekly, monthly, quarterly, annually)
    
    @ Returns
    - pmnt_amt  - The amount that each payment will be
    '''
    
    freq_lookup = {'weekly':52, 'monthly':12, 'quarterly':4, 'annually':1}
    int_rate = float(int_rate) / 100
    
    rr = int_rate / freq_lookup[freq]
    x = (1.0 + rr) ** num_pmnts
    y = rr / (x - 1.0)
    pmnt_amt = (rr + y) * principal
    
    return pmnt_amt


def main():
    r = input('What is your interest rate?   ')
    t = input('How many payments will you make?   ')
    la = input('What was the amount of the loan?   ')
    rt = None
    while rt not in ['weekly', 'monthly', 'quarterly', 'annually']:
        if rt:
            rt = raw_input('Sorry that was not an option, please respond with weekly, monthly, quarterly, or annually:   ').lower()
        else:
            rt = raw_input('Do you make your payments weekly, monthly, quarterly, or annually?   ').lower()
    payment = calc_payment(r, t, la, rt)
    print 'Your %s payment will be %.2f' % (rt, payment)


if __name__ == '__main__':
    main()
    raw_input('Press Enter to Exit...')

Here are the modifications I made:

1. Moved the payment calculation to a function called calc_payment

vegaseat commented: nice info +9
jlm699 320 Veteran Poster

Hi all,

I am using scipy.io for switching from python to matlab.
here is my list of list in python
code = [[[1, 2], [3,4], [5, 6]], [[7, 8], [9, 10]]]. I want to convert this to matlab format.
For that I used a code
scipy.io.savemat('/tmp/out.mat', mdict={'Num': (code[0], code[1])})

It's always helpful to use trace code:

>>> # Here's your object:
>>> code = [[[1, 2], [3,4], [5, 6]], [[7, 8], [9, 10]]]
>>> # Here's what you're passing to scipy.io.savemat:
>>> code[0]; code[1]
[[1, 2], [3, 4], [5, 6]]
[[7, 8], [9, 10]]
>>>

Is that what should be passed to savemat?

jlm699 320 Veteran Poster

hi,
i have installed the django and established the connection between django and mysql database.but it shows the below error.
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/doc/
The current URL, , didn't match any of these.

so how to overcome the above error

The error message is telling you that it cannot find a webpage (Page not found). Then it lists where it looked for the webpage (admin/doc/). This means it was looking for something like admin/doc/index.html

Do you have a local webpage there? If not you'll need one. If you have your webpage setup under a different directory on your computer you need to point the mysite.urls file to that directory.

All of this information is contained in the above error message.

jlm699 320 Veteran Poster

Search the web before posting, please

jlm699 320 Veteran Poster

I am trying to compute some lexical statistics from a given text. For instance, how many lines, sentences, words, how many times a given character is repeated. Can anyone help me with this?

Yes this is easy to do in python. A quick way to get the number of lines would be to read the file using readlines , which stores the contents in a list. Each element of the list is a single line of the file, so in order to get the number of lines, simply read the len of the list.

jlm699 320 Veteran Poster

Maybe is jlm699's solution simpler but i'll just put an example of what I said yesterday (I had no time to do it yesterday) as it is interesting anyway because it allows comparisons between objects in any situation (if objectA > objectB: )
note that __repr__ (as we are in special methods) allows to print the object the way you want...

class myobject:
    def __init__(self, c):
        self.c=c

    def __cmp__(self, alien):
        if self.c < alien.c:
            return -1
        elif self.c == alien.c:
            return 0
        else:
            return 1

    def __repr__(self):
        return str(self.c)

l=[]
for character in "akljdfliouerjslk":
    l.append(myobject(character))
print l
>> [a, k, l, j, d, f, l, i, o, u, e, r, j, s, l, k]
l.sort()
print l
>> [a, d, e, f, i, j, j, k, k, l, l, l, o, r, s, u]

Jice, our solutions are almost one in the same. In your example, you've overloaded the class __cmp__ function. It is a good demonstration to the OP as a beginner (to demonstrate how a custom-rolled cmp function could be written); however your example could be simplified by just specifying which element of the object needs to be "cmp"ed. Like so:

>>> class myobject:
...     def __init__(self, c):
...         self.c = c
...     def __cmp__(self, alien):
...         return cmp(self.c, alien.c)
...     def __repr__(self):
...         return str(self.c)
...     
>>> l = []
>>> for character in "akljdfliouerjslk":
...     l.append(myobject(character))
...     
>>> print l
[a, k, l, j, d, f, l, i, o, u, e, r, j, s, …
jlm699 320 Veteran Poster

Hi!

I have a list of class objects, each object contrains a dictionary. Is it possible to sort my list based on a value within each object's dictionary? Can I use the list.sort() method to do this?

Thx!

Yes. You'll need to use the function parameter of the sort method. Here's an example of sorting a list of objects by a particular variable. This method makes use of a lambda function

>>> class C(object):
...     def __init__(self, inp):
...         self.data = inp
...     
>>> my_list = []
>>> for ch in 'hbracdfeniklj':
...     my_list.append(C(ch))
...     
>>> for elem in my_list:
...     print elem.data
...     
h
b
r
a
c
d
f
e
n
i
k
l
j
>>> my_list.sort(lambda x,y: cmp(x.data,y.data))
>>> for elem in my_list:
...     print elem.data
...     
a
b
c
d
e
f
h
i
j
k
l
n
r
>>>

As you can see the sort function compares two elements at a time, so in my lambda function I take x and y as inputs. The cmp function similarly takes two inputs and returns -1 if x<y, 0 if x==y, and 1 if x>y; which just so happen to be the values that the sort function is looking for when sorting by comparison.

Hope that helps in your specific case. If you need some more specific advice, we'll need some more specific info!

jlm699 320 Veteran Poster

How about using a dictionary instead of two separate lists/tuples:

>>> user_dict = {}
>>> user_dict['user1'] = 'passwd1'
>>> user_dict.get('user2')
>>> user_dict.get('user1')
'passwd1'
>>>

As you can see, by using the get function, we can test whether a user name is in the dictionary or not. If the name is in the dictionary, it returns a string; otherwise it returns a None .

I think this would simplify and speed up your code big time.

jlm699 320 Veteran Poster

In order to read the contents of code.txt , you'll need to read the stdin pipe. To access it, use the sys.stdin handle, which you can read from just like an open file handle. You'll need to use the sys module, obviously.

The rest is just coding the cypher.

HTH

jlm699 320 Veteran Poster

Hey guys I managed to figure it out myself. Thanks for the help.
However what in my code makes it insert a space after every letter and how do I undo that? like if I input "BJ" the output is "W E" and I just want "WE." And how can I restrict it to an 80 character window without wrapping if the input is a very long single line? Thanks a ton.

Having a comma in your print statement gives you the spaces. Either upgrade to Python3.X with the new print function or use sys.stdout like so:

import sys

# Your code here

#Instead of print chr(ascii), use this:
sys.stdout.write(chr(ascii))

Either that or simply create a new string variable in your loop and print it after the loop exits:

new_str = ''

# Do stuff

for ch in usr_input:
    # Do stuff
    new_str += new_character

print new_str

HTH

jlm699 320 Veteran Poster

Why don't you try something like this:

from string import letters
# Upper letters only
letters = letters[26:]

c_string = raw_input("Enter desired sentence to convert: ")

cs_string = 5
ci_string = cs_string % 26
upper_string = c_string.upper()

for ch in upper_string:
    lett_idx = letters.find(ch)

    if lett_idx != -1:
        lett_idx -= cs_string
        if lett_idx < 0:
            lett_idx += len(letters)

    print letters[lett_idx],

You don't actually need to do the check for if lett_idx < 0 since negative indices in Python will still give you the same result, I was just keeping your logic intact

jlm699 320 Veteran Poster

I would suggest something like this:

# Open the file
f = open('myfile.txt')
# Read all the lines into a list
lines = f.readlines()
# Close the file
f.close()

# Now iterate over each line in the file until we find FCITC
for idx, line in enumerate(lines):
    if len(line) and line.split()[0] == 'FCITC':
        # Now our data will be on the line idx+1
        data = lines[idx+1].split()[0]

print data
jlm699 320 Veteran Poster

Have you tried uninstalling the program and doing a fresh install?

jlm699 320 Veteran Poster

There's a typo in MyListCtrl should be parent not paent. You should also have a comma (,) not a period (.) between id and pos. Additionally, how are you adding the ListCtrl to your window? You should be using a sizer.

Refer to this example by ZZucker of a ListCtrl. It will give you some insight into a ListCtrl, it's events and placing it with a sizer.

Hope that helps

jlm699 320 Veteran Poster

I'm posting this for others so they can see what your input file actually looks like.

Study transfer. From FMPP_EXA To FPL_IMA . Transfer level - 1000.0 MW


Violations report ordered by transfer capability. Total 3 violations


FCITC TDF LODF <--------- Limiting constraint ---------> <--------- Contingency description ---------> Ncon PreShift Rating PTDF IntBase FnlBase
690.4 -0.12312 - 5567 IND RIV 115 B$0029 CTAB GSU 1.00 1 Base Case 0.0 -85.0

Study transfer level - 1000.0 MW. Total violations: 21
First violation - -756.5 MW.

Are you always looking for the first item on the line after FCITC, TDF, etc? So in this case, your code could scan the file line by line looking for FCITC. Once that is found, we look at the following line and get the first item (in this case, 690.4). Store it to a variable and then continue.

Is that right?

jlm699 320 Veteran Poster

Ok do you have other suggestions?

Instead of making your variables global, simply return them from the function. Here's an example of a function with return values

>>> def retVals(inp):
...     inp += 5
...     out = inp*3
...     return inp, out
...     
>>> a = 4
>>> b, c = retVals(a)
>>> print a,b,c
4 9 27
>>> a = 10
>>> b, c = retVals(a)
>>> print a,b,c
10 15 45
>>>
jlm699 320 Veteran Poster

Ok thx if fixed the code up a bit.

It is still not reading in the .sj file tho. Apparently it opens it but it does not read in any text. Any ideas for how to fix this?

You need to move the textfile.close() statement outside of your for loop. Right now it closes the file on the first iteration.

jlm699 320 Veteran Poster

what I'm passing into readComments() is actually the file object

If that is the case then there's no reason to open it again. Simply iterate over the file object

jlm699 320 Veteran Poster

On top of jice's comment, you don't need to import string, and it would benefit you to move your top-level code into your main function:

def getdata(data):
    listing = []
    for line in data:
        new_line = line.split()[:2]
        listing.append(new_line)
  
    number = len(listing)
    items = listing

    # This is what jice added
    return number, items

def main():
    Name = raw_input("Filename ")
    infile = open(Name, 'r')
    data = infile.readlines()
    number, items = getdata(data)

''' This is a pretty common practice in Python to call your main
function (this wont get called if another script imports this
a module, as the other script will in that case be __main__,
not this one):
'''
if __name__ == '__main__':
    ''' If you want your program to loop you would put that
       logic here; for instance :
    while 1:
        main()
    '''
    main()
jlm699 320 Veteran Poster

can anybody help me with this program i would be grateful

Sure, but the answer depends on which version of Python you're using.

You'll be using input() (Python 3.X) or raw_input() (Python 2.X) to prompt the user for input.

You'll also want to make sure you're restricting the user's input to only the "allowed" units. You can use a list for this and the logic will basically be, if desired unit not in list; ignore (or warn user, then print out his options so he knows what he's allowed to use)

The rest is simple multiplication. You can look up conversion rates on Google (type for example "1 mm to inch" and search - results in 1 millimeter = 0.0393700787 inch).

Hope that helps

jlm699 320 Veteran Poster

I have looked more into pstgresql since my last post and want to refine my questions. From what I understand limiting who can connect to the database server is very easy with postgresql. You can use usernames and passwords along with allowing only certain ip addresses.

So as long as you are connected to the office intranet, know the name of the host of the database server, know a username and password and you have an allowed ip address, you should be able to get access to the server...no matter where you are? If the database server is hosted on either a computer or server on the private office intranet, do you need to be on the private office intranet to access it, or just simply connected to the internet somewhere?

In addition to ov3rcl0ck's comments above, also keep in mind that many "intranets" allow you to tunnel or VPN inside of the intranet from the outside world. If you have a way of accessing your work LAN/intranet from home then potentially you could access the private network-hosted database from anywhere. Otherwise, the only way to access the intranet-hosted database would be to have open access to said intranet.

You could also choose to host the database on your company's DMZ server; this would be the server that provides the outside internet into your internal network. You'd have to talk to your IT department about it, as I'm sure they'd have a number of security measures that they would …

jlm699 320 Veteran Poster
cells = [float(x) for x in data_hol[2].strip().split()]

where data_hol[2] is the 3rd column of the a file, that contains a batch of floats,
HOW can i insert into the list "cells" only the NON-zero items ?

If you want to ignore the items that are 0.0:

cells = [float(x) for x in data_hol[2].strip().split() if x != 
'0.0']

Keep in mind however that the ports with all 0.0 will result in an empty list named cells , which potentially could break other code. Just ensure that your list handling is going to account for the possibility of empty lists.

jlm699 320 Veteran Poster

How do I create this server? Can the server and the databases be on any machine's hard disk on the network?

This process is pretty easy with Postgresql; just download and install from here. There's documentation and help resources there for you if you're a command line junkie. There's a GUI front-end for pg that you can use to setup your database quickly and with very minimal effort. And yes, you can install the server/database onto any machine's hard disk but keep in mind that if you need a large database that is always available you'll want to install it on a server (or at least a reliable computer that is always available), preferably with more than plenty of storage.

Also, once the server and databases are created, how is access granted to the server?

You set up user accounts with passwords

In my application I use wxpython as a front-end, but can anyone with a front-end get onto this database server?

wxPython isn't your front-end it's just your GUI toolkit. The front-end would be whatever you use to access the database. Anyone that has a compatible front-end would have access as long as they know a user name/password (can also be open access ie, no pw). When you install pg it comes with a very nice front-end that will allow you quick and easy access to any pg databases. Any body that wants to access your db could install this application.

You could alternately create and …

jlm699 320 Veteran Poster

This is certainly not the only solution but postgresql can easily handle multiple users (like I assume most other RDMs can). The psycopg2 module is what I've used in the past for postgres but I know there are a few others out there.

jlm699 320 Veteran Poster

Your method of finding primes is flawed. Try 25, 35 and 49. None of those numbers are prime and it says that they are. Fix your indentation and your algorithm and then try to loop it again. I suggest using a function.

jlm699 320 Veteran Poster

It's hard to help you without the full traceback of the error but here's my two cents:

You're parsing the file contents incorrectly. What you should be doing is splitting each line at the tab character to get time stamp, port number, then the remaining string of floats. At this point you can sum the floats together and get a single float for your data list.

Here's how I would parse the data you provided:

>>> data_stor = []
>>> for line in file_hol:
...     data = line.split('\t')
...     if len(data) == 3:
...         tstamp = data[0].strip()
...         port = data[1].strip()
...         valu = sum([float(ea) for ea in data[2].strip().split()])
...         data_stor.append([tstamp, port, valu])
...     
>>> max(data_stor, key=lambda x:x[2])
['501', '6', 7.7770000000000001]
>>>

This returns that port 6 at timestamp 501 has the highest sum of numbers.

jlm699 320 Veteran Poster

but i just can't figure out how to make it work.
can anybody help me?

You were very close:

def one(s):
    if s == '':
        return [s]
    else:
        ans = []
        if s[1:] == '': return ans
        for o in one(s[1:]):
            ans.append(prevLetter(s[0])+o)
            ans.append(nextLetter(s[0])+o)
        return ans

You never made use of o in your function. You were for whatever reason trying to use ''.join(x) (NOTE: that is equivalent to string.join(x, '') ).

Your function can be further simplified as such:

def one4(s):
    if s == '': return [s]
    else:
        return [prevLetter(s[0]) + o for o in one(s[1:])] + \
               [nextLetter(s[0]) + o for o in one(s[1:])]
jlm699 320 Veteran Poster

If you implement glob you can use unix-style path completion ie glob.glob('*2009*.txt')

jlm699 320 Veteran Poster
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    return_mouse_slope( [100,100],[154,129])
  File "C:/Documents and Settings/Owner/Desktop/rewrite project warp/lib/maths.py", line 15, in return_mouse_slope
    dist(mouse_pos,[mouse_pos[0],object_pos[1]]) )
ValueError: math domain error

I'm not able to pass mouse_pos[0] and object_pos[1] to the dist function. Is python not able to pass arguments (in this case, a list) from a function to another function?

Try to figure out how to use the dist function in the interpreter and then implement it inside your function. The ValueError is telling you that what you're trying to do is unsupported by dist.

jlm699 320 Veteran Poster

So how do I open eg a file with file name jag.doc that is stored in my documents folder, how do I specify where the file is located?

To read a file, you use the 'r' (read) mode instead of 'w' (write).

To specify the file's location you can type the absolute path to the file, ie C:\Documents and Settings\<user_name>\My Documents\jag.doc ; however in PYthon \ is an escape character. In light of this you could either use the forward slash / like linux or use a double backslash \\

jlm699 320 Veteran Poster

Yes. You can use open to open a file and return the file handle. Note that some formats (ie, .doc) are not "flat" text files, meaning they may have some binary data, markup, etc.

You'll need to take that into account on a per-file basis.

jlm699 320 Veteran Poster

What do you mean by "combine" ? Or do you mean compare? If the latter, you simply compare each of their attributes, and then return each value combined with a logical and .

Some thing like:

return A.a == B.a and A.b == B.b and A.c == B.c ... etc.