Re: efficiency question

2006-06-30 Thread MTD
For the sake of comparison:

>>> def cod(x):
... tupple1 = ("abc", "def", "xyz")
... tupple2 = ("pqr", "tuv", "123")
... if x in tupple1:
... doStuff()
... elif x in tupple2:
... doOtherStuff()
...
>>> dis.dis(cod)
  2   0 LOAD_CONST   7 (('abc', 'def', 'xyz'))
  3 STORE_FAST   2 (tupple1)

  3   6 LOAD_CONST   8 (('pqr', 'tuv', '123'))
  9 STORE_FAST   1 (tupple2)

  4  12 LOAD_FAST0 (x)
 15 LOAD_FAST2 (tupple1)
 18 COMPARE_OP   6 (in)
 21 JUMP_IF_FALSE   11 (to 35)
 24 POP_TOP

  5  25 LOAD_GLOBAL  3 (doStuff)
 28 CALL_FUNCTION0
 31 POP_TOP
 32 JUMP_FORWARD25 (to 60)
>>   35 POP_TOP

  6  36 LOAD_FAST0 (x)
 39 LOAD_FAST1 (tupple2)
 42 COMPARE_OP   6 (in)
 45 JUMP_IF_FALSE   11 (to 59)
 48 POP_TOP

  7  49 LOAD_GLOBAL  4 (doOtherStuff)
 52 CALL_FUNCTION0
 55 POP_TOP
 56 JUMP_FORWARD 1 (to 60)
>>   59 POP_TOP
>>   60 LOAD_CONST   0 (None)
 63 RETURN_VALUE

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: style question

2006-06-26 Thread MTD

Hari Sekhon wrote:
> Is it better to do:
>
> message = """This is line1.
> This is line2
> This is line3\n"""
>
> or
>
> message = "This is line1.\n
> message = message + "This is line2\n"
> message = message + "This is line3\n"

Is there any reason you can't do it in one line?

message = "This is line1.\nThis is line2.\nThis is line3.\n"

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iteration over recursion?

2006-06-21 Thread MTD
I've been testing my recursive function against your iterative
function, and yours is generally a quite steady 50% faster on
factorizing 2**n +/- 1 for  0 < n < 60. I think that, for a challenge,
I'll try to make a recursive function that matche or beats the
iterative function -- it's worth the experiment!

Cheers,
MTD

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iteration over recursion?

2006-06-20 Thread MTD
Thanks a lot! More food for thought!

-- 
http://mail.python.org/mailman/listinfo/python-list


Iteration over recursion?

2006-06-20 Thread MTD
Hello all,

I've been messing about for fun creating a trial division factorizing
function and I'm naturally interested in optimising it as much as
possible.

I've been told that iteration in python is generally more
time-efficient than recursion. Is that true?

Here is my algorithm as it stands. Any suggestions appreciated!

from math import *

def factorize(x):
""" Return factors of x """
factors = []
lim = int(sqrt(x))
y = divmod(x,2)
if y[1] == 0: # x is even
factors = factors + [2] + factorize(y[0])
else:   # x is odd
i = 3
while i <= lim:
y = divmod(x,i)
if y[1] == 0:
factors = factors + [i] + factorize(y[0])
i = lim+1
else:
i += 2

if factors == []: # necessary step for correct recursion
factors = [x]

return factors

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to truncate/round-off decimal numbers?

2006-06-20 Thread MTD
> The system cannot
> accurately represent some integers,

Er, I meant FLOATS. Doh.

Anyway, just to underline the example:

>>> x
0.3
>>> s = str(round(x,2))
>>> s
'0.67'
>>> f = float(s)
>>> f
0.67004
>>> f == round(x,2)
True

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to truncate/round-off decimal numbers?

2006-06-20 Thread MTD
> >>> a = 2
> >>> b = 3
> >>> round(a*1.0 / b,2)
> 0.67004
>
> Inspite of specifying 2 in 2nd attribute of round, it outputs all the
> digits after decimal.

This is because of floating point inaccuracy. The system cannot
accurately represent some integers, however it does its best to
approximate them. Notice this:

>>> x = 2.0/3
>>> x
0.3
>>> round(x,2)
0.67004
>>> s = str(round(x,2))
>>> s
'0.67'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extracting values from text file

2006-06-16 Thread MTD
P.S.

>>> file.close()

MTD wrote:
> list.txt is a file that contains the following lines:
> Apples 34
> Bananas 10
> Oranges 56
>
> >>> file = open("list.txt","r")
> >>> mystring = file.read()
> >>> mystring
> 'Apples 34 \nBananas 10\nOranges 56 '
> >>> mylist = mystring.split('\n')
> >>> mylist
> ['Apples 34 ', 'Bananas 10', 'Oranges 56 ']
> >>> mydict = {}
> >>> for el in mylist:
> ...   l = el.split()
> ...   mydict[l[0]] = l[1]
> ...
> >>> mydict
> {'Apples': '34', 'Oranges': '56', 'Bananas': '10'}
> >>> mydict["Apples"]
> '34'
> >>> mydict["Oranges"]
> '56'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extracting values from text file

2006-06-16 Thread MTD
list.txt is a file that contains the following lines:
Apples 34
Bananas 10
Oranges 56

>>> file = open("list.txt","r")
>>> mystring = file.read()
>>> mystring
'Apples 34 \nBananas 10\nOranges 56 '
>>> mylist = mystring.split('\n')
>>> mylist
['Apples 34 ', 'Bananas 10', 'Oranges 56 ']
>>> mydict = {}
>>> for el in mylist:
... l = el.split()
... mydict[l[0]] = l[1]
...
>>> mydict
{'Apples': '34', 'Oranges': '56', 'Bananas': '10'}
>>> mydict["Apples"]
'34'
>>> mydict["Oranges"]
'56'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a string problem

2006-06-13 Thread MTD
> When i specify i only want to print the lines that contains "string" ie
> the first line and not the others. If i use re module, how to compile
> the expression to do this? I tried the re module and using simple
> search() and everytime it gives me all the 3 lines that have "string"
> in it, whereas i only need line 1.

That's because all three lines DO include the substring "string"

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Searching and manipulating lists of tuples

2006-06-12 Thread MTD
> Yes, use the proper tool for the job.  Tuples are immutable (they are
> read-only once created).  Instead use a dictionary.  They key would be
> your string, the value would be the count.

Wow, I really should have thought of that! Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Searching and manipulating lists of tuples

2006-06-12 Thread MTD
Hello,

I'm wondering if there's a quick way of resolving this problem.

In a program, I have a list of tuples of form (str,int), where int is a
count of how often str occurs

e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs
twice

If I am given a string, I want to search L to see if it occurs already.
If it does, I find the corresponding tuple and increment the integer
part. If not, I append the new element with int = 1.

e.g.

algorithm(L, "X") would produce output L = [("X",2),("Y",2)]
algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)]

I tried to create an algorithm of the following form:
>>> def algorith(list,str):
... flag = True
... for l in list:
... if l[0] == str:
... l[1] += 1
... flag = False
... if flag:
... list.append((str,1))
...


But:

>>> algorith(L,"X")

gives:

Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 5, in algorith
TypeError: object does not support item assignment


So clearly that doesn't work... any ideas?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to link foreign keys & primary keys using python?

2006-06-09 Thread MTD
Your post is confusing. Here is my advice: investigate the use of
dictionaries. Dictionaries can allow you to define data in the form {
key:data }, e.g.

{ area_code : area_data }

{ (area_code,school_code) : school_data }

{ (school_code,student_code) : student_data }

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread MTD

Jon Clements wrote:
> Are you asking the question, "Which pairs of strings have one character
> different in each?", or "Which pairs of strings have a substring of
> len(string) - 1 in common?".
>
> Jon.

I imagine it's the former because the latter is trivially easy, I mean
_really_ trivially easy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread MTD
So yeah, just to put it all together, try this. From your two Ks, it
either returns K+1 if it can or an empty string.

def k2k1(string1, string2):
for c in string1:
string2 = string2.replace(c,"",1)

if len(string2) == 1:
string1 += string2
else:
string1 = ""

return string1


Testing:

print k2k1("abcdadd", "abceadd")

gives:
abcdadde

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread MTD
actually, minor fix:

MTD wrote:
> Try this:
>
> def k2k1(string1, string2):
> for c in string1:
> string2 = string2.replace(c,"",1)
>
> if len(string2) == 1:
> string1 += string2
   else:
   string1 = ""

> 
> return string1
> 
> print k2k1("abcd", "ebcd")

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread MTD
Try this:

def k2k1(string1, string2):
for c in string1:
string2 = string2.replace(c,"",1)

if len(string2) == 1:
string1 += string2

return string1

print k2k1("abcd", "ebcd")

-- 
http://mail.python.org/mailman/listinfo/python-list