Re: [Tutor] OT self-implementation?

2005-07-02 Thread Kent Johnson
It is called bootstrapping. Some hints on this page:

http://en.wikipedia.org/wiki/Bootstrap

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT self-implementation?

2005-07-02 Thread Alan G
> the original 19th c. German ;-) Naively, one thinks that to write
> anything in C, you'd have to *have* C to write in, etc.

You are correct. Or at least you need the subset of C needed for a
minimal compiler.

So you figure out your minimal comiler in C.
Then you write a basic assembler program to compile that one program.
This is much easier than writing a general purpose C compiler, it
only needs to deal with a single program - the compiler.

Then once your compiler has been compiled, you use it to recompile
itself(*).

>From there in you can extend the original program and recompile it.
Provided each new feature that you sadd doesn't use any new features
then it will be compile by the previous version. ONce you've built
the new feature you can use it to add the next new feature, and so
on...

> Now's not the time in my life to start a comp. sci. degree. So, my
> questions are:
>
> 1) What would be good terms to google for to find an explanation of
> how the seeming magic doesn't violate all reason?

Compiler, Computer Language, Programming, History of C,

etc...

> 2) Much harder, so please pass unless you've a link you know of
> off-hand: any recommendations of particular things that I could
read?

There are lots of CS books on language design and most will cover
this process in detail, usually including staged excercises so you
wind up building your own compiler for your own language!

A more general CS intro will usually have a chapter on language
design and comiler construction.

You might find books on Lex and Yacc (Or GNUs Flex and Bison)
useful too.


(*)One of the hardest malicious bugs I've seen was by a
disgruntled employee who deliberately inserted a bug into the C
source of the companies compiler. He then recompiled the compiler
(using the working compiler) to produce a faulty compiler. He then
removed his bugs in the source code so it was back to the correct
version. He then recompiled the good source with the faulty
compiler to produce a new faulty compiler. He then left the
company...

It took a long time to figure out what was wrong and why...

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing nested lists/dicts/tuples

2005-07-02 Thread Luis N
Hi,


Yes, sorry I haven't posted to the list in a while. I should have been
more specific. I'm writing a simple contact database, using metakit as
the backend. Thank you for pointing out that what I was trying to do
was easier than I believed.

Here's some code. 

db = metakit.storage('c:/addy.mk',1)
vw = db.getas('contacts[first:S,last:S,phone:S,email:S,notes:S]')

desc = ('first', 'last', 'phone', 'email', 'notes')

def listItems():
    l= []
    d = {}
    for r in range(len(vw)): 
    d = {'first':vw[r].first,
'last':vw[r].last, 'phone':vw[r].phone, 'email':vw[r].email,
'notes':vw[r].notes} 
    l.append(d)
    return l

At the moment I would like to generate the listItems dynamically, from
the desc variable, so new databases can be added without changing the
code.

I thought that if:

def listItems():
    l= []
    d = {}
    lt = len(desc)
    for r in range(len(vw)):
    for x in range(len(lt)):
    d[desc[x]] = exec("""'vw'+[r]+'.'+desc[x]""")
    l.append(d)
    return l

Whereby the vw metakit object behaves like a dictionary, and the exec statement isn't usable in the way I would wish for.

Luis N.

On 6/28/05, Brian van den Broek <[EMAIL PROTECTED]
> wrote:Luis N said unto the world upon 28/06/2005 15:25:> Hi,>

>l>> [{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last':> 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}]>>> This is how I imagine it:
>> for i in l:> for j in l[i]:> for k in l[i][j]:> print k.get('first')> print k.get('last')>> Is there a short and sweet way of doing this (that actually works).


>> Luis.Hi Luis,I'm not certain I see what you are wanting from your description.(You've got more nesting in your loops than in l.) But does this dowhat is wanted? >>> a_list = [ {'last': 'Bar', 'first': 'Foo'},
{'last': 'Bar', 'first': 'Foo'},{'last': 'Bar', 'first': 'Foo'},{'last':
'Bar', 'first': 'Foo'} ] >>> for a_dict in a_list: print a_dict['first'] print a_dict['last']FooBarFooBarFooBarFooBar >>>


If it does, why are you doing this? Is it to figure out how tomanipulate data structures with Python? If so, good. If you are tryingto do real work this way, there is surely a better way. Maybe if yousaid what you are trying to accomplish, someone could help you find a
good way to do it.Best,Brian vdB



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing nested lists/dicts/tuples

2005-07-02 Thread Luis N
On 7/2/05, Luis N <[EMAIL PROTECTED]> wrote:

Umm, sorry, I meant:
d[desc[x]] = exec("""'vw[%s].desc[%s]'""" % (r,x )) 




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT self-implementation?

2005-07-02 Thread Bill Burns
Brian,

If you've never read this before, you may find it interesting:

http://cm.bell-labs.com/who/ken/trust.html

Bill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How do I make Python calculate square roots?

2005-07-02 Thread Nathan Pinno




  Hi all,Does anyone know how to make Python calculate square 
  roots?
   
  Thanks,
  Nathan Pinnohttp://www.npinnowebsite.ca/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I make Python calculate square roots?

2005-07-02 Thread Reed L. O'Brien
Nathan Pinno wrote:

> Hi all,
>
> Does anyone know how to make Python calculate square roots?
>  
> Thanks,
> Nathan Pinno
> http://www.npinnowebsite.ca/
>
>
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
Raise to the 1/2 power.

>>> 4**.5
2.0
>>> 16**.5
4.0
>>> 81**.5
9.0

~r
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Iterating over nested lists part2

2005-07-02 Thread Luis N
Okay,

This works great now:

def listItems():
    l= []
    d = {}
    for r in range(len(vw)): 
    for x in range(lt):
    ed = desc[x] 
    exec("d['%s']=vw[%d].%s" % (ed,r,ed))
    l.append(d)
    print l

But, it multiplies all of the records from vw by 5. How can I have:

for each record in the database:
    for each column in the record:
    do stuff.

Without multiplying the result i.e len(vw) * lt

Thanks.

Luis N.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT self-implementation?

2005-07-02 Thread Brian van den Broek
Alan G said unto the world upon 02/07/2005 03:53:
>>the original 19th c. German ;-) Naively, one thinks that to write
>>anything in C, you'd have to *have* C to write in, etc.
> 
> 
> You are correct. Or at least you need the subset of C needed for a
> minimal compiler.
> 
> So you figure out your minimal comiler in C.
> Then you write a basic assembler program to compile that one program.
> This is much easier than writing a general purpose C compiler, it
> only needs to deal with a single program - the compiler.



> (*)One of the hardest malicious bugs I've seen was by a
> disgruntled employee who deliberately inserted a bug into the C
> source of the companies compiler. He then recompiled the compiler
> (using the working compiler) to produce a faulty compiler. He then
> removed his bugs in the source code so it was back to the correct
> version. He then recompiled the good source with the faulty
> compiler to produce a new faulty compiler. He then left the
> company...
> 
> It took a long time to figure out what was wrong and why...
> 
> HTH,
> 
> Alan G

Hi all,

good lord, but if that fellow could only have harnessed that 
ingeniousness for the forces of good!

Thanks to Alan for the additional explanation and head-hurting tale of 
malice, and to both Kent and Bill for additional references.

Best to all,

Brian vdB


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] code for expressing rationals in arbitrarty bases

2005-07-02 Thread Brian van den Broek
Hi all,

In a private exchange about floating point representation error spun 
off of c.l.p., I'd sent someone some code to express rationals 
(subject to some constraints) in arbitrary bases, 1 < base < 37. The 
aim was to illustrate my claim that whether a rational had a repeating 
expansion[*] or not was a function of base of representation.

Well, he went and posted it back to c.l.p. :-(
So, it is out there, even though it isn't so good that I'd have chosen 
to put it in a public space (other than Tutor). It is also long, as it 
includes some tests and sanity checks on the input. *If* anyone has 
the time and interest, I'd appreciate comments:
. If not, 
no worries. :-)

To my embarrassment, I see that I'd commented out, but not removed, 
debug print statements. etc.

[*] Does anyone know a term for a non-fractional representation of a 
rational in arbitrary base? For particular bases, decimal expansion, 
binary expansion, etc. But is there a term for the general case, other 
than base-n expansion?

Best to all,

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing nested lists/dicts/tuples

2005-07-02 Thread Brian van den Broek
Luis N said unto the world upon 02/07/2005 07:51:
> On 7/2/05, Luis N <[EMAIL PROTECTED]> wrote:
> 
> Umm, sorry, I meant:
> 
> d[desc[x]] = exec("""'vw[%s].desc[%s]'""" % (r,x ))
> 
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


Hi Luis,

I don't know anything about metakit, and thus I don't know anything 
about the details of the data structure from:

> vw = db.getas('contacts[first:S,last:S,phone:S,email:S,notes:S]')

So, I can't manifest exactly how it would work, but unless there is 
some odd constraint imposed by metakit, you don't need to (and 
probably shouldn't) use exec or eval.

It *looks* to me like you are trying to take some object returned by a 
metakit method and use it to build a Python dict. I'm sure I don't 
have the details of your task right, but here is some code that does a 
similar thing without eval or exec:

 >>> desc = ('first', 'last', 'email')
 >>> class Person(object):
... def __init__(self, first, last, email):
... self.first = first
... self.last = last
... self.email = email
...
 >>> bob = Person('Bob', 'Jones', '[EMAIL PROTECTED]')
 >>> jane = Person('Jane', 'Best', '[EMAIL PROTECTED]')
 >>> persons = (jane, bob)
 >>> # persons is intended to serve a similar role as your vw. It is a
 >>> # sequence of objects, from which I will build a dict, without
 >>> # eval or exec.
 >>>
 >>> persons_dict = {}
 >>> def update(target_dict, object_tuple, attribs):
... for o in object_tuple:
... temp = {}
... for a in attribs:
... temp[a] = o.__getattribute__(a)
... target_dict[o.__getattribute__(attribs[0])] = temp
... return target_dict
...
 >>> persons_dict = update(persons_dict, persons, desc)
 >>> persons_dict
{'Jane': {'last': 'Best', 'email': '[EMAIL PROTECTED]', 'first': 'Jane'}, 
'Bob': {'last': 'Jones', 'email': '[EMAIL PROTECTED]', 'first': 'Bob'}}
 >>>

Obviously this won't be exactly what you need, but I hope it can give 
you an idea of how to make what you *do* need.

Why am I down on eval and exec? Well,

 >>> exec("print 6")
6
 >>>

is harmless. But, running:

exec(some_string_with_commands_to_delete_your_hard_drive)

would suck :-)

Similar nastiness can happen with eval:
 >>> def f(): print 6
...
 >>> eval('f()')
6
 >>>

Make f() an evil function, and it'll all end in tears :-)

So, they are considered a security risk. You may well trust your data 
drawn from metakit in this instance. But, I think it is a good habit 
to avoid them when they can be avoided.

I hope I've helped at least some. Best,

Brian vdB


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT self-implementation?

2005-07-02 Thread Alan G
> > (*)One of the hardest malicious bugs I've seen was by a
> > disgruntled employee who deliberately inserted a bug into the C
> > source of the companies compiler. ... He then left the
> > company...

> good lord, but if that fellow could only have harnessed that 
> ingeniousness for the forces of good!

He had been, he was a very talented programmer who had worked for us 
on many big technical projects. In fact he was one of the few people 
I've met who could debug an octal core dump and genuinely understand 
what he was reading! Unfortunately deep technical skill is not 
always recognised by big corporations and he was not as well 
rewarded as he thought he should be... (and in truth as he probably 
deserved to be!)

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] search through a list

2005-07-02 Thread nephish
hey there
i have a file that i want to read.
each line in the file is the name of a file.
the next line is how many lines are in that file.

example of loglist.txt

log1.txt
232
log2.txt
332
log3.txt
223

so log1 is a text file that has 232 lines in it.

ok, so what i want to do is read this file, see if the file i am looking 
for is in it
and if so, i need to know how many lines are in the file.

here is what i have so far.

import os

#get a list of Logs in logs folder
LogFiles = os.listdir('/home/nephish/Projects/Piv_GCI/logs')

#open the loglist file and read the lines
LogList = open('home/nephish/Projects/Piv/logs/LogList.txt', 'r')
LogsRead = LogList.readlines()

#see if there is  a new log file.
for i in LogFiles:
if LogFiles[i] not in LogList:
#if there is a new log, open it and read the lines
StrName=(LogFiles[i])
NewLog = open('/home/nephish/Projects/Piv_CGI/logs'+StrName,'r')
NewLogRead=NewLog.readlines()
#print the lines (testing only)
for x in NewLogRead:
print x
print '\n'
print '\n' #end for loop
else: #if the log file is not new,

um this is where i am stuck. i need search the LogList for the name of 
the name of the file in LogFiles and get the line number back so i can 
use it to compare with how many lines are in the log file so i can only 
process the data in the new lines ...  does this make sense ?

i need to find the item in a list, and when found, return the next line.

any takers?

thanks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Iterating over nested lists part2

2005-07-02 Thread Kent Johnson
Luis N wrote:
> def listItems():
> l= []
> d = {}
> for r in range(len(vw)):
> for x in range(lt):
> ed = desc[x]
> exec("d['%s']=vw[%d].%s" % (ed,r,ed))
> l.append(d)
> print l

If I understand correctly, you want to take all the rows of the view and turn 
them into dicts, and build a list of all the dicts. If so, the code above is 
way too complex.

First, you can iterate over a list such as vw directly, you don't have to 
iterate the indices. Instead of
for r in range(len(vw)):
  do something with vw[r]

you just say
for vwitem in vw:
  do something with vw

Next, instead of exec you should use getattr(). To put the value into d you 
don't need either; you can assign to d[ed] directly. To get the 'ed' attribute 
from vwitem, use getattr(vwitem, ed).

I also moved the assignment to d inside the loop so you start each row with a 
fresh dictionary. Here is the result:

def listItems():
l= []
for vwitem in vw:
d = {}
for ed in desc:
d[ed] = getattr(vwitem, ed)
l.append(d)
print l

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] String to List and back?

2005-07-02 Thread Chinook
I'm missing something simple again.  The simplified issue is:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)

 >>> mystr = 'abc'

  # I can create a list of the string characters
  #  with list comprehension
 >>> [c for c in mystr]
['a', 'b', 'c']

  # Or just a simple builtin conversion function
 >>> list(mystr)
['a', 'b', 'c']

  # But a conversion back to a string simply makes the
  #  the list a string (I know there would have to be
  #  special handling, but I noted it for illustration)
 >>> str(['a', 'b', 'c'])
"['a', 'b', 'c']"

  # I know I could get the original string back by
  #  rebuilding it with "for" loop
 >>> bts = ''
 >>> for c in strlist:
...   bts += c
...
 >>> bts
'abc'

  # or even a function or class method which implemented
  #  the "for" loop
  # I could also build a new string directly from the
  #  original with a "for" loop

Is there a one-liner like a builtin conversion function or list 
comprehension technique for the reverse (i.e. a list of strings back to 
a single string)?

Thank you,

Lee C

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String to List and back?

2005-07-02 Thread Light



Hi, Lee.
You could using:
>>> bts = ''.join(strlist)
Then you would get:
>>> bts'abc'
 
Light
 


FOX.GIF
Description: GIF image
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String to List and back?

2005-07-02 Thread Chuck Allison
Hello Chinook,

How about join(), as in

''.join(strlist)

?


Saturday, July 2, 2005, 9:45:28 PM, you wrote:

C> I'm missing something simple again.  The simplified issue is:

C> Python 2.4.1 (#2, Mar 31 2005, 00:05:10)

C>  >>> mystr = 'abc'

C>   # I can create a list of the string characters
C>   #  with list comprehension
C>  >>> [c for c in mystr]
C> ['a', 'b', 'c']

C>   # Or just a simple builtin conversion function
C>  >>> list(mystr)
C> ['a', 'b', 'c']

C>   # But a conversion back to a string simply makes the
C>   #  the list a string (I know there would have to be
C>   #  special handling, but I noted it for illustration)
C>  >>> str(['a', 'b', 'c'])
C> "['a', 'b', 'c']"

C>   # I know I could get the original string back by
C>   #  rebuilding it with "for" loop
C>  >>> bts = ''
C>  >>> for c in strlist:
C> ...   bts += c
C> ...
C>  >>> bts
C> 'abc'

C>   # or even a function or class method which implemented
C>   #  the "for" loop
C>   # I could also build a new string directly from the
C>   #  original with a "for" loop

C> Is there a one-liner like a builtin conversion function or list 
C> comprehension technique for the reverse (i.e. a list of strings back to 
C> a single string)?

C> Thank you,

C> Lee C

C> ___
C> Tutor maillist  -  Tutor@python.org
C> http://mail.python.org/mailman/listinfo/tutor



-- 
Best regards,
 Chuck

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String to List and back?

2005-07-02 Thread Chinook
Just the thing Light and Chuck - I thought there might be something 
simple (and I've used the join method before duh).

Thanks,
Lee C

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to get 4 numbers from the user in one line for easy comparision?

2005-07-02 Thread Nathan Pinno



I saw that great idea from Steven, and I appreciate it. I think it will 
work. Just need to figure out how to get 4 numbers from the player on one line 
for easy comparison, e.g. telling whether the number is correct position and 
number, incorrect position and correct number, or both are incorrect.
 
If anyone has any advice in how to code this, I will gladly appreciate the 
help.
 
Sorry if I seem like a newbie, but I am! :)
Nathan Pinnohttp://www.npinnowebsite.ca/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor