Re: How do you refer to an iterator in docs?

2012-04-21 Thread Steven D'Aprano
On Fri, 20 Apr 2012 23:01:08 -0400, Roy Smith wrote:

> A basket of apples is a basket which contains apples, in the same way a
> list contains foos.  But an iterator doesn't contain anything.  You
> wouldn't say, "a spigot of water", because the spigot isn't a container
> holding the water.  It is simply a mechanism for delivering the water in
> a controlled way.


A better analogy would be a trickle, stream or torrent of water.

In English, "a foo of bar" does not necessarily imply containment, e.g. a 
circle of friends, a conspiracy of silence, a flood of refugees, a tissue 
of lies.


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


Re: Using arguments in a decorator

2012-04-21 Thread Steven D'Aprano
On Fri, 20 Apr 2012 09:10:15 -0700, Jon Clements wrote:

>> But I don't know how. I know that I can see the default arguments of
>> the original function using func.__defaults__, but without knowing the
>> number and names of func's positional arguments (which I don't know how
>> to find out) this doesn't help me. Any suggestions?
> 
> Possibly take a look at functools.lru_cache (which is Python 3.2+), and
> use the code from that (at it's part of the stdlib, someone must have
> done design and testing on it!).

With respect Jon, did you read the Original Poster's question closely? 
Using a LRU cache doesn't even come close to fixing his problem, which 
occurs *before* you do the lookup in the cache.

Rotwang's problem is that if you have a function with default arguments:

def func(spam=42):
return result_of_time_consuming_calculation()

then these three function calls are identical and should (but don't) 
share a single cache entry:

func()
func(42)
func(spam=42)

The OP would like all three to share a single cache entry without needing 
two redundant calculations, which take a long time.

The problem is that the three calls give three different patterns of args 
and kwargs:

(), {}
(42,) {}
(), {'spam': 42}

hence three different cache entries, two of which are unnecessary.



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


Re: Using arguments in a decorator

2012-04-21 Thread Steven D'Aprano
On Fri, 20 Apr 2012 16:57:06 +0100, Rotwang wrote:

> def memo(func):
>  def memofunc(*args, **kwargs):
>  twargs = tuple(kwargs.items())
>  if (args, twargs) in memofunc.d:
>  return copy(memofunc.d[(args, twargs)])
>  memofunc.d[(args, twargs)] = func(*args, **kwargs) return
>  copy(memofunc.d[(args, twargs)])
>  memofunc.__name__ = func.__name__
>  memofunc.d = {}
>  return memofunc

Note that this decorator is underpowered and arguable buggy: it 
suppresses the decorated function's doc string. You should use 
functools.wraps to copy the name, doc string and anything else necessary.

Here is how I would write the above.


import functools

def memoise(func):
"""Decorator to memoise a function."""
cache = {}
@functools.wraps(func)
def inner(*args, **kwargs):
# Make sure keyword args are always looked up in a consistent
# order by sorting. One minor subtlety: since kwargs cannot 
# have duplicate keys, sorted() will never try to break ties 
# by comparing values. So this will work even for unsortable
# values like complex numbers.
kw = tuple(sorted(kwargs.items()))
try:
# Cache hit?
result = cache[(args, kw)]
except KeyError:
# Cache miss.
result = func(*args, **kwargs)
cache[(args, kw)] = result
except TypeError:
# Cache failure; at least one argument is uncacheable.
result = func(*args, **kwargs)
# Is the cache too big?
if len(cache) > 1000:
# Dump an arbitrary item. A LRU (least recently used) cache
# would be better, but this will do.
cache.popitem()
return result
# Expose the cache to the outside world.
inner._cache = cache
return inner

[...]
> But I don't know how. I know that I can see the default arguments of the
> original function using func.__defaults__, but without knowing the
> number and names of func's positional arguments (which I don't know how
> to find out) this doesn't help me. Any suggestions?


http://docs.python.org/release/3.1.5/library/inspect.html?#inspect.getfullargspec


>>> def f(a, b=1, *args, c, d=2, **kwargs):
... x = 42
... return (a,b,c,d,args,kwargs)
...
>>> import inspect
>>> inspect.getfullargspec(f)
FullArgSpec(args=['a', 'b'], varargs='args', varkw='kwargs', 
defaults=(1,), kwonlyargs=['c', 'd'], kwonlydefaults={'d': 2}, 
annotations={})





-- 
Steven

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Alexander Blinne
Am 21.04.2012 05:25, schrieb Rotwang:
> On 21/04/2012 01:01, Roy Smith wrote:
>> In article<877gxajit0@dpt-info.u-strasbg.fr>,
>>   Alain Ketterlin  wrote:
>>
>>> Tuples are immutable, while lists are not.
>>
>> If you really want to have fun, consider this classic paradox:
>>
> [] is []
>> False
> id([]) == id([])
>> True
> 
> Huh. This is not what I would have expected. What gives?

This happens only because the first [] gets destroyed after evaluation
of id([]). The second [] then by accident gets the same id as the first
one had.

>>> a = []
>>> b = []
>>> id(a) == id(b)
False

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Serhiy Storchaka

[] is []

False

id([]) == id([])

True


>>> id([1]) == id([2])
True

;)

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


some beginners questions about programming

2012-04-21 Thread Santosh Kumar
Hello Python Developers,

I have a very less experience with programming. I have digged a little bit
of all (I mean *C, **Java, JavaScript, PHP*) at introductory level and now
I have two question about it.

   1. Are *Arrays* and *Lists* same things?
   2. Are *Modules* and *Libraries* same things?

Thanks,
*Santosh*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *.sdf database access

2012-04-21 Thread Alex Willmer
On Apr 19, 9:18 pm, Page3D  wrote:
> Hi, I am trying to connect and access data in a *.sdf file on Win7
> system using Python 2.7. I have three questions:
>
> 1. What python module should I use? I have looked at sqlite3 and
> pyodbc. However, I can seem to get the connection to the database file
> setup properly.

I assume you mean SQL Server Compact by *.sdf. However please note
that there are several several file formats matching SDF
http://en.wikipedia.org/wiki/SDF#Computing and explicit is better than
implicit.

The sqlite3 module won't help - that's for sqlite files, which an
entirely different file format. Wikpedia says of SQL Server Compact
"An ODBC driver for SQL CE does not exist, and one is not planned
either. Native applications may use SQL CE via OLE DB"
http://en.wikipedia.org/wiki/SQL_Server_Compact. I believe the
adodbapi module, part of PyWin32 http://sourceforge.net/projects/pywin32/files/
can connect over OLE DB.

> 2. How can I determine the appropriate connection string? I have
> opened database file in Visual Studio and can see the tables. I don't
> understand where to find the connection string in Visual Studio.

These look promising http://www.connectionstrings.com/sql-server-2005-ce

> 3. Assuming a module from (1) above, does anyone have a code snippet
> for connecting to the database and then accessing a varbinary (image)
> in one of the tables of the databese?

Pass, I'm afraid

Regards, Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: some beginners questions about programming

2012-04-21 Thread Dave Angel
On 04/21/2012 06:03 AM, Santosh Kumar wrote:
> Hello Python Developers,
>
> I have a very less experience with programming. I have digged a little bit
> of all (I mean *C, **Java, JavaScript, PHP*) at introductory level and now
> I have two question about it.
>
>1. Are *Arrays* and *Lists* same things?
>2. Are *Modules* and *Libraries* same things?
>
>
No
No

None of those words is well defined without choosing a language first. 
What Python uses for the built-in type 'list' is closest to what C++
call s a vector.  What C++ usually calls a list doesn't exist in Python.

In Python, a module is the code in one importable file, a package is a
group of such files defined by their directory relationship to each
other, while a library is a word used loosely to describe a collection
of such files.  Other languages use the word to describe possibly very
different things.   For example, in C, a module is the amount of code
that the compiler handles at one time.  Modules are then combined
together using a linker to form either an executable or a library.  And
a library may be of at least two different types, statically linked to
the executable, or dynamically loaded at run time.

And some of those terms vary from OS to OS, as well as from language to
language.



-- 

DaveA

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


Re: Using arguments in a decorator

2012-04-21 Thread Jon Clements
On Saturday, 21 April 2012 09:25:40 UTC+1, Steven D'Aprano  wrote:
> On Fri, 20 Apr 2012 09:10:15 -0700, Jon Clements wrote:
> 
> >> But I don't know how. I know that I can see the default arguments of
> >> the original function using func.__defaults__, but without knowing the
> >> number and names of func's positional arguments (which I don't know how
> >> to find out) this doesn't help me. Any suggestions?
> > 
> > Possibly take a look at functools.lru_cache (which is Python 3.2+), and
> > use the code from that (at it's part of the stdlib, someone must have
> > done design and testing on it!).
> 
> With respect Jon, did you read the Original Poster's question closely? 
> Using a LRU cache doesn't even come close to fixing his problem, which 
> occurs *before* you do the lookup in the cache.

I did indeed Steven - what I was suggesting was that functools.lru_cache would 
be a good starting point. Although I will completely admit that I didn't read 
the code for functools.lru_cache thoroughly enough to realise it wouldn't be 
suitable for the OP (ie, it sounded right, looked okay at a glance, and I 
figured it wasn't a totally unreasonable assumption of a suggestion - so guess 
I fell into the old 'assume' trap! [not the first time, and won't be the last 
for sure!])

> 
> Rotwang's problem is that if you have a function with default arguments:
> 
> def func(spam=42):
> return result_of_time_consuming_calculation()
> 
> then these three function calls are identical and should (but don't) 
> share a single cache entry:
> 
> func()
> func(42)
> func(spam=42)
> 
> The OP would like all three to share a single cache entry without needing 
> two redundant calculations, which take a long time.
> 
> The problem is that the three calls give three different patterns of args 
> and kwargs:
> 
> (), {}
> (42,) {}
> (), {'spam': 42}
> 
> hence three different cache entries, two of which are unnecessary.

I'm wondering if it wouldn't be unreasonable for lru_cache to handle this.

Cheers, Jon.



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


Re: Appending to []

2012-04-21 Thread Bernd Nawothnig
On 2012-04-20, Rotwang wrote:
> since a method doesn't assign the value it returns to the instance on 
> which it is called; what it does to the instance and what it returns are 
> two completely different things.

Returning a None-value is pretty useless. Why not returning self, which would be
the resulting list in this case? Returning self would make the
language a little bit more functional, without any drawback.

Then nested calls like

a = [].append('x').append('y').append('z')

would be possible with a containing the resulting list

['x', 'y', 'z'].

That is the way I expect any append to behave.




Bernd

-- 
"Die Antisemiten vergeben es den Juden nicht, dass die Juden Geist
haben - und Geld." [Friedrich Nietzsche]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using arguments in a decorator

2012-04-21 Thread Rotwang

On 21/04/2012 09:36, Steven D'Aprano wrote:

[...]

Here is how I would write the above.


import functools

def memoise(func):
 """Decorator to memoise a function."""
 cache = {}
 @functools.wraps(func)
 def inner(*args, **kwargs):
 # Make sure keyword args are always looked up in a consistent
 # order by sorting. One minor subtlety: since kwargs cannot
 # have duplicate keys, sorted() will never try to break ties
 # by comparing values. So this will work even for unsortable
 # values like complex numbers.
 kw = tuple(sorted(kwargs.items()))
 try:
 # Cache hit?
 result = cache[(args, kw)]
 except KeyError:
 # Cache miss.
 result = func(*args, **kwargs)
 cache[(args, kw)] = result
 except TypeError:
 # Cache failure; at least one argument is uncacheable.
 result = func(*args, **kwargs)
 # Is the cache too big?
 if len(cache)>  1000:
 # Dump an arbitrary item. A LRU (least recently used) cache
 # would be better, but this will do.
 cache.popitem()
 return result
 # Expose the cache to the outside world.
 inner._cache = cache
 return inner


Thanks. Incidentally, would there be any way to look at the value of 
cache if it weren't for the statement inner._cache = cache? For that 
matter, I don't understand why 'cache' isn't in inner.__globals__.




[...]

But I don't know how. I know that I can see the default arguments of the
original function using func.__defaults__, but without knowing the
number and names of func's positional arguments (which I don't know how
to find out) this doesn't help me. Any suggestions?



http://docs.python.org/release/3.1.5/library/inspect.html?#inspect.getfullargspec



def f(a, b=1, *args, c, d=2, **kwargs):

... x = 42
... return (a,b,c,d,args,kwargs)
...

import inspect
inspect.getfullargspec(f)

FullArgSpec(args=['a', 'b'], varargs='args', varkw='kwargs',
defaults=(1,), kwonlyargs=['c', 'd'], kwonlydefaults={'d': 2},
annotations={})


Cool; that's not available for Python 2 but it looks like 
inspect.getargspec() is and does pretty much the same thing. Also 
inspect.getcallargs() does exactly what I need for my decorator. Thanks 
very much for your help.



--
Hate music? Then you'll hate this:

http://tinyurl.com/psymix
--
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Bernd Nawothnig
On 2012-04-20, dmitrey wrote:
> I have spent some time searching for a bug in my code, it was due to
> different work of "is" with () and []:
 () is ()
> True

You should better not rely on that result. I would consider it to be
an implementation detail. I may be wrong, but would an implementation
that results in

() is () ==> False

be correct or is the result True really demanded by the language
specification?

 [] is []
> False

Same for that.

>
> (Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
> [GCC 4.6.1] )
>
> Is this what it should be or maybe yielding unified result is better?

See above.




Bernd

-- 
"Die Antisemiten vergeben es den Juden nicht, dass die Juden Geist
haben - und Geld." [Friedrich Nietzsche]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Appending to []

2012-04-21 Thread Dave Angel
On 04/21/2012 08:48 AM, Bernd Nawothnig wrote:
> On 2012-04-20, Rotwang wrote:
>> since a method doesn't assign the value it returns to the instance on 
>> which it is called; what it does to the instance and what it returns are 
>> two completely different things.
> Returning a None-value is pretty useless. Why not returning self, which would 
> be
> the resulting list in this case? Returning self would make the
> language a little bit more functional, without any drawback.
>
> Then nested calls like
>
> a = [].append('x').append('y').append('z')
>
> would be possible with a containing the resulting list
>
> ['x', 'y', 'z'].
>
> That is the way I expect any append to behave.
>
>
>

This has been debated here many times.  The python reasoning for most
cases goes something like this:

A function/method on an object may either alter the object, or produce a
new one and return that.  If it does both, the programmer can get
surprised and have a bug that's difficult to notice.

For example, you can either sort() a list, in which case it's done
in-place, returning none.   Or you can call sorted() on it, which
returns a new list, similar to the first, but sorted.



-- 

DaveA

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Dave Angel
On 04/21/2012 09:02 AM, Bernd Nawothnig wrote:
> On 2012-04-20, dmitrey wrote:
>> I have spent some time searching for a bug in my code, it was due to
>> different work of "is" with () and []:
> () is ()
>> True
> You should better not rely on that result. I would consider it to be
> an implementation detail. I may be wrong, but would an implementation
> that results in
>
> () is () ==> False
>
> be correct or is the result True really demanded by the language
> specification?

You're correct, the behavior is undefined.  An implementation may happen
to produce either True or False.

> [] is []
>> False
> Same for that.

Here I have to disagree.  If an implementation reused the list object
for two simultaneously-existing instances, it would violate first
principles.

The distinction is simply that () is immutable, so the implementation
*may* choose to reuse the same one.



-- 

DaveA

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


Re: Appending to []

2012-04-21 Thread Kiuhnm

On 4/21/2012 14:48, Bernd Nawothnig wrote:

On 2012-04-20, Rotwang wrote:

since a method doesn't assign the value it returns to the instance on
which it is called; what it does to the instance and what it returns are
two completely different things.


Returning a None-value is pretty useless. Why not returning self, which would be
the resulting list in this case? Returning self would make the
language a little bit more functional, without any drawback.

Then nested calls like

a = [].append('x').append('y').append('z')


You just answered to your own question: append returns None so that 
people can't use it the way you did.
You make the reader believe that you're adhering to the functional 
paradigm whereas 'append' has actually side effects!

Moreover, you use an assignment just to reinforce this wrong belief.

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread gst
Le samedi 21 avril 2012 10:46:39 UTC+2, Alexander Blinne a écrit :
> Am 21.04.2012 05:25, schrieb Rotwang:
> 
> This happens only because the first [] gets destroyed after evaluation
> of id([]). The second [] then by accident gets the same id as the first
> one had.
> 
> >>> a = []
> >>> b = []
> >>> id(a) == id(b)
> False
> 
> Greetings

Hi,

I played (python3.2) a bit on that and :

case 1) Ok to me (right hand side is a tuple, whose elements are evaluated one 
per one and have same effect as your explanation (first [] is destroyed right 
before the second one is created) :

>>> x, y = id([]), id([])
>>> x == y
True
>>> 


case 2) also ok to me:

>>> x = id([]) ; y = id([])
>>> x == y
True
>>> 


case 3) NOT ok to me :

>>> x = id([])
>>> y = id([])
>>> x == y
False
>>> 


case 4) ok to me :

>>> def f():
x = id([])
y = id([])
return x == y

>>> f()
True
>>> 


I'd have thought that cases 2&3 are totally, while 3&4 nearly, syntactically 
equal and that case 3 is the incorrect result..

how would you explain case 3 vs cases 2 and 4 ??


regards,

gs.

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Chris Angelico
On Sat, Apr 21, 2012 at 10:51 PM, gst  wrote:
> case 2) also ok to me:
>
 x = id([]) ; y = id([])
 x == y
> True

>
>
> case 3) NOT ok to me :
>
 x = id([])
 y = id([])
 x == y
> False


The fact that ids get reused at all is an implementation detail ONLY.
In CPython, id() returns the object's memory address, but in other
Python implementations, it returns something else (one (Jython??)
returns a sequential number, never reused).

Here's my take on the difference here. You did all of these in a
single session, so by the time you got to case 3, x already contained
a value (the previous integer). The allocation and deallocation of
integer objects created your different behavior. I tried these from
command-line Python (3.2 on Windows, fwiw), restarting the interpreter
between, and got consistent results.

The main thing to know, though, is that the id MAY be reused once the
object is destroyed, but any reuse should be considered utterly
coincidental. A Python could be completely compliant with an id
implementation in which object type gets encoded into it somehow, but
programs written to make use of that information would be just as
vulnerable as those making use of reuse.

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


Re: Appending to []

2012-04-21 Thread Bernd Nawothnig
On 2012-04-21, Kiuhnm wrote:
>> Returning a None-value is pretty useless. Why not returning self, which 
>> would be
>> the resulting list in this case? Returning self would make the
>> language a little bit more functional, without any drawback.

>>
>> Then nested calls like
>>
>> a = [].append('x').append('y').append('z')
>
> You just answered to your own question: append returns None so that 
> people can't use it the way you did.

That is one possible way to design the method, but not the only
possible way.

> You make the reader believe that you're adhering to the functional 
> paradigm whereas 'append' has actually side effects!
> Moreover, you use an assignment just to reinforce this wrong belief.

I know about side effects and I know that letting append return self
would not make Python a purely functional language with only immutable
data.

I just asked a simple question about a detail I personally would
consider it to be useful.

Please no further religious war about that ;-)




Bernd

-- 
"Die Antisemiten vergeben es den Juden nicht, dass die Juden Geist
haben - und Geld." [Friedrich Nietzsche]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Appending to []

2012-04-21 Thread Terry Reedy

On 4/21/2012 9:08 AM, Dave Angel wrote:

On 04/21/2012 08:48 AM, Bernd Nawothnig wrote:

On 2012-04-20, Rotwang wrote:

since a method doesn't assign the value it returns to the instance on
which it is called; what it does to the instance and what it returns are
two completely different things.

Returning a None-value is pretty useless. Why not returning self, which would be
the resulting list in this case? Returning self would make the
language a little bit more functional, without any drawback.

Then nested calls like

a = [].append('x').append('y').append('z')


Sequential appends are nearly always done within a loop.


would be possible with a containing the resulting list

['x', 'y', 'z'].



This has been debated here many times.  The python reasoning for most
cases goes something like this:

A function/method on an object may either alter the object, or produce a
new one and return that.  If it does both, the programmer can get
surprised and have a bug that's difficult to notice.

For example, you can either sort() a list, in which case it's done
in-place, returning none.   Or you can call sorted() on it, which
returns a new list, similar to the first, but sorted.


Guido having decided to consistently not return mutated objects,
perhaps partly on the basis that the caller could already have a
reference to the object, it was easy a decade or more later to add 
various methods/functions, including pop() and next(), that mutate by 
removing and returning an object, while remaining consistent with the rule.


--
Terry Jan Reedy

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


Re: Appending to []

2012-04-21 Thread Kiuhnm

On 4/21/2012 17:41, Bernd Nawothnig wrote:

On 2012-04-21, Kiuhnm wrote:

Returning a None-value is pretty useless. Why not returning self, which would be
the resulting list in this case? Returning self would make the
language a little bit more functional, without any drawback.

 


Then nested calls like

a = [].append('x').append('y').append('z')


You just answered to your own question: append returns None so that
people can't use it the way you did.


That is one possible way to design the method, but not the only
possible way.


You make the reader believe that you're adhering to the functional
paradigm whereas 'append' has actually side effects!
Moreover, you use an assignment just to reinforce this wrong belief.


I know about side effects and I know that letting append return self
would not make Python a purely functional language with only immutable
data.

I just asked a simple question about a detail I personally would
consider it to be useful.

Please no further religious war about that ;-)


Sorry if I wasn't clear. I meant that one should either relies on 
side-effects and write something like

  a.append('x').append('t').append('z')
or use a more functional style and write
  a = a + [x] + [z]
Mixing the two doesn't seem very elegant to me.
I also think that if you need to repeatedly modify an object in the same 
expression, then you should prefer the more functional approach.
I wasn't suggesting that you didn't know what functional programming and 
side effects are.
Mine was a justification (maybe opinable) of why append was designed 
that way.


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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Terry Reedy

On 4/21/2012 9:02 AM, Bernd Nawothnig wrote:


You should better not rely on that result. I would consider it to be
an implementation detail. I may be wrong, but would an implementation
that results in

() is () ==>  False

be correct or is the result True really demanded by the language
specification?


To make sure that the result is not due to ref counting garbage 
collection in the middle of the expression, one must test like so:

>>> a=()
>>> b=()
>>> a is b
True

This is explicitly an implementation detail, something that *may* be 
done. I am not sure if the above has always been the case for CPython. 
CPython's set of pre-built ints has been expended. I think string 
interning has also changed.


--
Terry Jan Reedy

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


Re: Appending to []

2012-04-21 Thread Kiuhnm

On 4/21/2012 18:14, Kiuhnm wrote:

On 4/21/2012 17:41, Bernd Nawothnig wrote:

On 2012-04-21, Kiuhnm wrote:

Returning a None-value is pretty useless. Why not returning self,
which would be
the resulting list in this case? Returning self would make the
language a little bit more functional, without any drawback.




Then nested calls like

a = [].append('x').append('y').append('z')


You just answered to your own question: append returns None so that
people can't use it the way you did.


That is one possible way to design the method, but not the only
possible way.


You make the reader believe that you're adhering to the functional
paradigm whereas 'append' has actually side effects!
Moreover, you use an assignment just to reinforce this wrong belief.


I know about side effects and I know that letting append return self
would not make Python a purely functional language with only immutable
data.

I just asked a simple question about a detail I personally would
consider it to be useful.

Please no further religious war about that ;-)


Sorry if I wasn't clear. I meant that one should either relies on
side-effects and write something like
a.append('x').append('t').append('z')
or use a more functional style and write
a = a + [x] + [z]


Oops... I forgot the single quotes and the 't'.

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


Newbie, homework help, please.

2012-04-21 Thread someone
Ok, this is my dillema, not only am I new to this programming buisness, before 
the last few days, I did not even know what python was, and besides opening up 
the internet or word documents, that is most of what I know. Yet, I have a 
professor who should be on Psych medication for giving us 3 projects, 2 of 
which I have not listed here to do. I was able to do research over the last 3 
days, and I have spent 3 days on this project, by borrowing others ideas on 
this project. Below, you will find my professors assignment (oh, and due in one 
week right before finals, so I am stressing out so much, cause I don't know why 
he is crazy enough to assign crap like this a week before finals when I have 
Calculus final,chem final, etc. I have figured out most of the assignment, and 
below, it will be posted after the teacher's post of the assignment. What I 
need help with, and I have tried relentlessly to find, is how to put freaking 
stars(asterisks) as border around a list without installing any other program 
to a portable python, of course, this is where my problem lies. Below, you will 
see what I have done, please, help!!!
You are required to complete and submit the following programming projects in 
Python by the indicated deadline:

Standard Header Information project (5 pts):
Write a program that will:
1) Ask the user for the following information:
- name of file to be created for storing SHI
- user’s name (as part of SHI)
- user’s course and section (as part of SHI)
- user’s semester and year (as part of SHI)
- user’s assignment title (as part of SHI)
2) Write the above SHI data to a text (.txt) file with the name chosen by the 
user (above)
3) Close the file that the SHI data was written to
4) Open the file with the SHI data (again)
5) Read the data into different (from part 1) variable names
6) Display the SHI data read from the file in the interpreter with a border 
around the SHI data (include a buffer of 1 line/space between the border and 
SHI data). An example might look like:

***
* *
* First Name and Last *
* ENGR 109-X  *
* Fall 2999   *
* Format Example  *
* *
***


textfile=input('Hello, we are about to create a text file. An example would be: 
(sample.txt) without the parenthesis. What ever you do name it, it needs to end 
in (.txt). What would you like to name your textfile?')
userinput=[input('What is your name?'),input('What is your Course Section and 
Course number?'),input('What is the Semester and year?'),input('What is the 
title of this class assignment?')]
for item in userinput:
openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
userinput);openfile.close()
x=textfile;indat=open(x,'r');SHI=indat.read()
def border(Sullivan):
string=SHI
stringlength=len(string)
stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * (3 
+ 3)
hBorder=stringlength//2*"* "+"*"[:stringlength%2]
spacer="*"+" "*(stringlength - 2)+"*"
fancyText="*  "+string+"  *"
return(hBorder,spacer,fancyText,hBorder)

textTuple = border(SHI)
for lines in textTuple:
print (lines)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-21 Thread someone
On Saturday, April 21, 2012 12:28:33 PM UTC-5, someone wrote:
> Ok, this is my dillema, not only am I new to this programming buisness, 
> before the last few days, I did not even know what python was, and besides 
> opening up the internet or word documents, that is most of what I know. Yet, 
> I have a professor who should be on Psych medication for giving us 3 
> projects, 2 of which I have not listed here to do. I was able to do research 
> over the last 3 days, and I have spent 3 days on this project, by borrowing 
> others ideas on this project. Below, you will find my professors assignment 
> (oh, and due in one week right before finals, so I am stressing out so much, 
> cause I don't know why he is crazy enough to assign crap like this a week 
> before finals when I have Calculus final,chem final, etc. I have figured out 
> most of the assignment, and below, it will be posted after the teacher's post 
> of the assignment. What I need help with, and I have tried relentlessly to 
> find, is how to put freaking stars(asterisks) as border around a list without 
> installing any other program to a portable python, of course, this is where 
> my problem lies. Below, you will see what I have done, please, help!!!
> You are required to complete and submit the following programming projects in 
> Python by the indicated deadline:
> 
> Standard Header Information project (5 pts):
> Write a program that will:
> 1) Ask the user for the following information:
>   - name of file to be created for storing SHI
>   - user’s name (as part of SHI)
>   - user’s course and section (as part of SHI)
>   - user’s semester and year (as part of SHI)
>   - user’s assignment title (as part of SHI)
> 2) Write the above SHI data to a text (.txt) file with the name chosen by the 
> user (above)
> 3) Close the file that the SHI data was written to
> 4) Open the file with the SHI data (again)
> 5) Read the data into different (from part 1) variable names
> 6) Display the SHI data read from the file in the interpreter with a border 
> around the SHI data (include a buffer of 1 line/space between the border and 
> SHI data). An example might look like:
> 
>   ***
>   * *
>   * First Name and Last *
>   * ENGR 109-X  *
>   * Fall 2999   *
>   * Format Example  *
>   * *
>   ***
> 
> 
> textfile=input('Hello, we are about to create a text file. An example would 
> be: (sample.txt) without the parenthesis. What ever you do name it, it needs 
> to end in (.txt). What would you like to name your textfile?')
> userinput=[input('What is your name?'),input('What is your Course Section and 
> Course number?'),input('What is the Semester and year?'),input('What is the 
> title of this class assignment?')]
> for item in userinput:
> openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
> userinput);openfile.close()
> x=textfile;indat=open(x,'r');SHI=indat.read()
> def border(Sullivan):
> string=SHI
> stringlength=len(string)
> stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * 
> (3 + 3)
> hBorder=stringlength//2*"* "+"*"[:stringlength%2]
> spacer="*"+" "*(stringlength - 2)+"*"
> fancyText="*  "+string+"  *"
> return(hBorder,spacer,fancyText,hBorder)
> 
> textTuple = border(SHI)
> for lines in textTuple:
> print (lines)

almost forgot, it has to have a 1 inch border around the top, bottom, left, and 
right, with it being aligned to the left. In the picture above, that is not how 
it actually looks, the stars to the right are aligned on the right, not right 
next to each other. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Appending to []

2012-04-21 Thread Bernd Nawothnig
On 2012-04-21, Kiuhnm wrote:
> Sorry if I wasn't clear. I meant that one should either relies on 
> side-effects and write something like
>a.append('x').append('t').append('z')
> or use a more functional style and write
>a = a + [x] + [z]
> Mixing the two doesn't seem very elegant to me.
> I also think that if you need to repeatedly modify an object in the same 
> expression, then you should prefer the more functional approach.
> I wasn't suggesting that you didn't know what functional programming and 
> side effects are.
> Mine was a justification (maybe opinable) of why append was designed 
> that way.

Ok, understood and accepted 



Bernd

-- 
"Die Antisemiten vergeben es den Juden nicht, dass die Juden Geist
haben - und Geld." [Friedrich Nietzsche]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-21 Thread Ian Kelly
On Sat, Apr 21, 2012 at 11:28 AM, someone  wrote:
> for item in userinput:
>    openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
> userinput);openfile.close()

The for loop here means that the file will be written and rewritten
four times.  The end result is the same, but you only need to write it
once.

>    stringlength=len(string)

This line assigns an int to stringlength.

>    stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * (3 
> + 3)

And this line attempts to both iterate over stringlength and call it,
either of which will fail since ints can't be iterated over or called.

What you need to do here is split the SHI into a list of individual
lines using the str.split method, or by reading it that way in the
first place using indat.readlines instead of indat.read.  Then
determine the length of the longest line using the max function or a
for loop.

>    hBorder=stringlength//2*"* "+"*"[:stringlength%2]
>    spacer="*"+" "*(stringlength - 2)+"*"
>    fancyText="*  "+string+"  *"

Since there are multiple lines, you will need to do the "* " + line +
" *" once for each line to do the left and right borders, not once for
the entire string.  Otherwise you will end up with just one * on the
left and one * on the right.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-21 Thread Jon Clements
On Saturday, 21 April 2012 18:35:26 UTC+1, someone  wrote:
> On Saturday, April 21, 2012 12:28:33 PM UTC-5, someone wrote:
> > Ok, this is my dillema, not only am I new to this programming buisness, 
> > before the last few days, I did not even know what python was, and besides 
> > opening up the internet or word documents, that is most of what I know. 
> > Yet, I have a professor who should be on Psych medication for giving us 3 
> > projects, 2 of which I have not listed here to do. I was able to do 
> > research over the last 3 days, and I have spent 3 days on this project, by 
> > borrowing others ideas on this project. Below, you will find my professors 
> > assignment (oh, and due in one week right before finals, so I am stressing 
> > out so much, cause I don't know why he is crazy enough to assign crap like 
> > this a week before finals when I have Calculus final,chem final, etc. I 
> > have figured out most of the assignment, and below, it will be posted after 
> > the teacher's post of the assignment. What I need help with, and I have 
> > tried relentlessly to find, is how to put freaking stars(asterisks) as 
> > border around a list without installing any other program to a portable 
> > python, of course, this is where my problem lies. Below, you will see what 
> > I have done, please, help!!!
> > You are required to complete and submit the following programming projects 
> > in Python by the indicated deadline:
> > 
> > Standard Header Information project (5 pts):
> > Write a program that will:
> > 1) Ask the user for the following information:
> > - name of file to be created for storing SHI
> > - user’s name (as part of SHI)
> > - user’s course and section (as part of SHI)
> > - user’s semester and year (as part of SHI)
> > - user’s assignment title (as part of SHI)
> > 2) Write the above SHI data to a text (.txt) file with the name chosen by 
> > the user (above)
> > 3) Close the file that the SHI data was written to
> > 4) Open the file with the SHI data (again)
> > 5) Read the data into different (from part 1) variable names
> > 6) Display the SHI data read from the file in the interpreter with a border 
> > around the SHI data (include a buffer of 1 line/space between the border 
> > and SHI data). An example might look like:
> > 
> > ***
> > * *
> > * First Name and Last *
> > * ENGR 109-X  *
> > * Fall 2999   *
> > * Format Example  *
> > * *
> > ***
> > 
> > 
> > textfile=input('Hello, we are about to create a text file. An example would 
> > be: (sample.txt) without the parenthesis. What ever you do name it, it 
> > needs to end in (.txt). What would you like to name your textfile?')
> > userinput=[input('What is your name?'),input('What is your Course Section 
> > and Course number?'),input('What is the Semester and year?'),input('What is 
> > the title of this class assignment?')]
> > for item in userinput:
> > openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item 
> > in userinput);openfile.close()
> > x=textfile;indat=open(x,'r');SHI=indat.read()
> > def border(Sullivan):
> > string=SHI
> > stringlength=len(string)
> > stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * 
> > (3 + 3)
> > hBorder=stringlength//2*"* "+"*"[:stringlength%2]
> > spacer="*"+" "*(stringlength - 2)+"*"
> > fancyText="*  "+string+"  *"
> > return(hBorder,spacer,fancyText,hBorder)
> > 
> > textTuple = border(SHI)
> > for lines in textTuple:
> > print (lines)
> 
> almost forgot, it has to have a 1 inch border around the top, bottom, left, 
> and right, with it being aligned to the left. In the picture above, that is 
> not how it actually looks, the stars to the right are aligned on the right, 
> not right next to each other. Thanks.

Honestly phrased question - well done.

Look at the textwrap module - I have no idea how you'll got an inch outputting 
in just text, as I might have a slightly different font setting and logical and 
physical inches are different.

Good luck, Jon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-21 Thread MRAB

On 21/04/2012 18:28, someone wrote:

Ok, this is my dillema, not only am I new to this programming buisness, before 
the last few days, I did not even know what python was, and besides opening up 
the internet or word documents, that is most of what I know. Yet, I have a 
professor who should be on Psych medication for giving us 3 projects, 2 of 
which I have not listed here to do. I was able to do research over the last 3 
days, and I have spent 3 days on this project, by borrowing others ideas on 
this project. Below, you will find my professors assignment (oh, and due in one 
week right before finals, so I am stressing out so much, cause I don't know why 
he is crazy enough to assign crap like this a week before finals when I have 
Calculus final,chem final, etc. I have figured out most of the assignment, and 
below, it will be posted after the teacher's post of the assignment. What I 
need help with, and I have tried relentlessly to find, is how to put freaking 
stars(asterisks) as border around a list without installing any

other program to a portable python, of course, this is where my problem lies. 
Below, you will see what I have done, please, help!!!

You are required to complete and submit the following programming projects in 
Python by the indicated deadline:

Standard Header Information project (5 pts):
Write a program that will:
1) Ask the user for the following information:
- name of file to be created for storing SHI
- user’s name (as part of SHI)
- user’s course and section (as part of SHI)
- user’s semester and year (as part of SHI)
- user’s assignment title (as part of SHI)
2) Write the above SHI data to a text (.txt) file with the name chosen by the 
user (above)
3) Close the file that the SHI data was written to
4) Open the file with the SHI data (again)
5) Read the data into different (from part 1) variable names
6) Display the SHI data read from the file in the interpreter with a border 
around the SHI data (include a buffer of 1 line/space between the border and 
SHI data). An example might look like:

***
* *
* First Name and Last *
* ENGR 109-X  *
* Fall 2999   *
* Format Example  *
* *
***


textfile=input('Hello, we are about to create a text file. An example would be: 
(sample.txt) without the parenthesis. What ever you do name it, it needs to end 
in (.txt). What would you like to name your textfile?')


That's a very long prompt for an input. It would be better if you
printed the preamble and then used only the final question as the
prompt.


userinput=[input('What is your name?'),input('What is your Course Section and 
Course number?'),input('What is the Semester and year?'),input('What is the 
title of this class assignment?')]


Try putting each input on a separate line, eg:

name = input('What is your name?')


for item in userinput:
 openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
userinput);openfile.close()


That will create the file 4 times, once for each item, each time writing 
all 4 items.


Also, try writing only 1 statement per line; it'll be a lot clearer.


x=textfile;indat=open(x,'r');SHI=indat.read()


There's no need for variable "x" here; just use "textfile".

The "read" will read the entire contents of the file as a single
string. You could read each line separately, or read the file as a list
of lines (strings). Look at the Python documentation for the methods of
the "file" class.


def border(Sullivan):


"Sullivan"?


 string=SHI
 stringlength=len(string)


At this point, "stringlength" is an int, the length of the string.


 stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * (3 
+ 3)


You're asking it to call the length. That makes no sense.


 hBorder=stringlength//2*"* "+"*"[:stringlength%2]
 spacer="*"+" "*(stringlength - 2)+"*"
 fancyText="*  "+string+"  *"
 return(hBorder,spacer,fancyText,hBorder)



The simplest solution is to find the maximum length of the lines and
pad the lines with spaces to that length. Look at the Python
documentation for the methods of the "str" class.

Adding the borders to the resulting rectangular block of characters is
straightforward.


textTuple = border(SHI)
for lines in textTuple:
 print (lines)

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


Re: Newbie, homework help, please.

2012-04-21 Thread BartC
"someone"  wrote in message 
news:32945367.2045.1335029313436.JavaMail.geo-discussion-forums@ynjn4...


6) Display the SHI data read from the file in the interpreter with a 
border around the SHI data (include a buffer of 1 line/space between the 
border and SHI data). An example might look like:


***
* *
* First Name and Last *
* ENGR 109-X  *
* Fall 2999   *
* Format Example  *
* *
***


I'm not a Python programmer, but I'll have a go at the text formatting bit:

text=["First Name and Last","ENGR 109-X","Fall 2999","Format Example"]

maxwidth=0
for s in text:
if len(s)>maxwidth: maxwidth=len(s)

vertinchlines=6# assume 6 lines/inch
hozinchchars=10# assume 10 chars/inch

hozmargin=" "*hozinchchars

newtext=[]
for i in range(vertinchlines):
newtext.append("")

newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)

for s in text:
newtext.append(hozmargin+"* "+s+" "*(maxwidth-len(s))+" *"+hozmargin)

newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)

for i in range(vertinchlines):
newtext.append("")

for s in newtext:
print (s)

--
Bartc  
--

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Dave Angel
On 04/21/2012 09:48 AM, Bernd Nawothnig wrote:
> On Sat, Apr 21, 2012 at 09:21:50AM -0400, Dave Angel wrote:
>>> [] is []
 False
>>> Same for that.
>>
>> Here I have to disagree.  If an implementation reused the list object
>> for two simultaneously-existing instances, it would violate first
>> principles.
> 
> Hm.
> 
> Even if there is no chance to reach any of these two lists after the
> comparison because *no* references to them exist and both *must* be
> identical because they are both noted as the same literals?
> 
> If any references exist, no question, that is pretty clear and
> understandable. But in that special case?
> 

You forgot to CC the list on your two messages to me.

Clearly, False has to be a valid return result.  So I assume your
question is why shouldn't an implementation be permitted to return True,
in other words why couldn't it be ambiguous, like the immutable case.

Why would you (a hypothetical compiler writer) write an optimizer to
look for such a special case like this, when the code would probably
never appear in a real program, and certainly not in a performance
critical portion of one.

And if you did write one, why would you have it produce a different
result than the non-optimized version?  Why not have it return 42 if
that's the goal?


-- 

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


Re: Newbie, homework help, please.

2012-04-21 Thread Roy Smith
In article 
<32945367.2045.1335029313436.JavaMail.geo-discussion-forums@ynjn4>,
 someone  wrote:

I'm not going to do your homework for you (nor do I expect anybody else 
will), but I'll give you a hint about one sticky part.

> 6) Display the SHI data read from the file in the interpreter with a border 
> around the SHI data (include a buffer of 1 line/space between the border and 
> SHI data). An example might look like:
> 
>   ***
>   * *
>   * First Name and Last *
>   * ENGR 109-X  *
>   * Fall 2999   *
>   * Format Example  *
>   * *
>   ***

You can take advantage of python's string formatting capabilities (which 
are pretty much the same as C's printf() formatting), and do something 
like:

print  "* %-*s *" % (max_length, data)

That will at least get you the data left-justified with the correct 
number of spaces for padding.  See 
http://docs.python.org/library/stdtypes.html#string-formatting for 
details.  You'll need to compute max_length by applying len() to each of 
the individual strings in turn, and picking the largest of them with 
max().
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-21 Thread Tim Chase

On 04/21/12 14:44, Roy Smith wrote:

***
* *
* First Name and Last *
* ENGR 109-X  *
* Fall 2999   *
* Format Example  *
* *
***


You can take advantage of python's string formatting capabilities (which
are pretty much the same as C's printf() formatting), and do something
like:

print  "* %-*s *" % (max_length, data)


Sounds like a lot more work and less flexible than using the 
(underemployed) .ljust() or .center() methods of a string. :-)


  print "* %s *" % data.ljust(42)

-tkc



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


Re: Newbie, homework help, please.

2012-04-21 Thread someone
On Saturday, April 21, 2012 12:28:33 PM UTC-5, someone wrote:
> Ok, this is my dillema, not only am I new to this programming buisness, 
> before the last few days, I did not even know what python was, and besides 
> opening up the internet or word documents, that is most of what I know. Yet, 
> I have a professor who should be on Psych medication for giving us 3 
> projects, 2 of which I have not listed here to do. I was able to do research 
> over the last 3 days, and I have spent 3 days on this project, by borrowing 
> others ideas on this project. Below, you will find my professors assignment 
> (oh, and due in one week right before finals, so I am stressing out so much, 
> cause I don't know why he is crazy enough to assign crap like this a week 
> before finals when I have Calculus final,chem final, etc. I have figured out 
> most of the assignment, and below, it will be posted after the teacher's post 
> of the assignment. What I need help with, and I have tried relentlessly to 
> find, is how to put freaking stars(asterisks) as border around a list without 
> installing any other program to a portable python, of course, this is where 
> my problem lies. Below, you will see what I have done, please, help!!!
> You are required to complete and submit the following programming projects in 
> Python by the indicated deadline:
> 
> Standard Header Information project (5 pts):
> Write a program that will:
> 1) Ask the user for the following information:
>   - name of file to be created for storing SHI
>   - user’s name (as part of SHI)
>   - user’s course and section (as part of SHI)
>   - user’s semester and year (as part of SHI)
>   - user’s assignment title (as part of SHI)
> 2) Write the above SHI data to a text (.txt) file with the name chosen by the 
> user (above)
> 3) Close the file that the SHI data was written to
> 4) Open the file with the SHI data (again)
> 5) Read the data into different (from part 1) variable names
> 6) Display the SHI data read from the file in the interpreter with a border 
> around the SHI data (include a buffer of 1 line/space between the border and 
> SHI data). An example might look like:
> 
>   ***
>   * *
>   * First Name and Last *
>   * ENGR 109-X  *
>   * Fall 2999   *
>   * Format Example  *
>   * *
>   ***
> 
> 
> textfile=input('Hello, we are about to create a text file. An example would 
> be: (sample.txt) without the parenthesis. What ever you do name it, it needs 
> to end in (.txt). What would you like to name your textfile?')
> userinput=[input('What is your name?'),input('What is your Course Section and 
> Course number?'),input('What is the Semester and year?'),input('What is the 
> title of this class assignment?')]
> for item in userinput:
> openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
> userinput);openfile.close()
> x=textfile;indat=open(x,'r');SHI=indat.read()
> def border(Sullivan):
> string=SHI
> stringlength=len(string)
> stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * 
> (3 + 3)
> hBorder=stringlength//2*"* "+"*"[:stringlength%2]
> spacer="*"+" "*(stringlength - 2)+"*"
> fancyText="*  "+string+"  *"
> return(hBorder,spacer,fancyText,hBorder)
> 
> textTuple = border(SHI)
> for lines in textTuple:
> print (lines)

Thanks your Bart for trying, I don't understand how it works or if you tried to 
place my script in python to see if it would work, unfortunately, I tried 10 
different ways plus yours, and I don't see the connection. Unless you were 
trying to help me see the way and I did not, sorry, but thanks for trying. The 
characters did show me a little more.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-21 Thread someone
On Saturday, April 21, 2012 12:28:33 PM UTC-5, someone wrote:
> Ok, this is my dillema, not only am I new to this programming buisness, 
> before the last few days, I did not even know what python was, and besides 
> opening up the internet or word documents, that is most of what I know. Yet, 
> I have a professor who should be on Psych medication for giving us 3 
> projects, 2 of which I have not listed here to do. I was able to do research 
> over the last 3 days, and I have spent 3 days on this project, by borrowing 
> others ideas on this project. Below, you will find my professors assignment 
> (oh, and due in one week right before finals, so I am stressing out so much, 
> cause I don't know why he is crazy enough to assign crap like this a week 
> before finals when I have Calculus final,chem final, etc. I have figured out 
> most of the assignment, and below, it will be posted after the teacher's post 
> of the assignment. What I need help with, and I have tried relentlessly to 
> find, is how to put freaking stars(asterisks) as border around a list without 
> installing any other program to a portable python, of course, this is where 
> my problem lies. Below, you will see what I have done, please, help!!!
> You are required to complete and submit the following programming projects in 
> Python by the indicated deadline:
> 
> Standard Header Information project (5 pts):
> Write a program that will:
> 1) Ask the user for the following information:
>   - name of file to be created for storing SHI
>   - user’s name (as part of SHI)
>   - user’s course and section (as part of SHI)
>   - user’s semester and year (as part of SHI)
>   - user’s assignment title (as part of SHI)
> 2) Write the above SHI data to a text (.txt) file with the name chosen by the 
> user (above)
> 3) Close the file that the SHI data was written to
> 4) Open the file with the SHI data (again)
> 5) Read the data into different (from part 1) variable names
> 6) Display the SHI data read from the file in the interpreter with a border 
> around the SHI data (include a buffer of 1 line/space between the border and 
> SHI data). An example might look like:
> 
>   ***
>   * *
>   * First Name and Last *
>   * ENGR 109-X  *
>   * Fall 2999   *
>   * Format Example  *
>   * *
>   ***
> 
> 
> textfile=input('Hello, we are about to create a text file. An example would 
> be: (sample.txt) without the parenthesis. What ever you do name it, it needs 
> to end in (.txt). What would you like to name your textfile?')
> userinput=[input('What is your name?'),input('What is your Course Section and 
> Course number?'),input('What is the Semester and year?'),input('What is the 
> title of this class assignment?')]
> for item in userinput:
> openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
> userinput);openfile.close()
> x=textfile;indat=open(x,'r');SHI=indat.read()
> def border(Sullivan):
> string=SHI
> stringlength=len(string)
> stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * 
> (3 + 3)
> hBorder=stringlength//2*"* "+"*"[:stringlength%2]
> spacer="*"+" "*(stringlength - 2)+"*"
> fancyText="*  "+string+"  *"
> return(hBorder,spacer,fancyText,hBorder)
> 
> textTuple = border(SHI)
> for lines in textTuple:
> print (lines)

Thanks for your reply Mr. Roy Smith. Also, thanks for the tip. Maybe I did not 
make myself as clear or maybe you did not understand my post. It states 
homework help, and I am doing this post to get help before I pay somebody to 
show me how to do it, because, obviously our professor is not kind enough to 
show us how to do this less than two weeks before the due date with 3 projects 
(and now I have basically less than a week before it is due- and I am not 
waiting till the last minute), and this just so happens to be the easier one. I 
understand the concept of him trying to give us deadlines and making us learn, 
but I don't appreciate paying for a class where I am not taught anything or 
told the right direction due to his belief that he is helping me to get a 
stronger work ethic, I have 5 classes this semester, and stupid me, I had to 
take the hardest ones I could not realizing the depth of the struggles I would 
face. Again, thanks for the tip, but I never asked you to do my homework, it 
clearly states that I did research over the last few days, over the internet, 
because our brilliant professor is giving us just the slim end of what he 
believes is enough to get us through. I took posted script and made it work by 
figuring it out to fit the assignment. At least, I am trying, want to guess at 
how many people have buddies in this class and they will copy this off of them 
before due date? Please, don't judge people because you think you are doing me 
a favor by saying you will not do my ho

Re: Newbie, homework help, please.

2012-04-21 Thread Roy Smith
On 04/21/12 14:44, Roy Smith wrote:
> print  "* %-*s *" % (max_length, data)


On Apr 21, 2012, at 4:12 PM, Tim Chase wrote:
> Sounds like a lot more work and less flexible than using the (underemployed) 
> .ljust() or .center() methods of a string. :-)
> 
>  print "* %s *" % data.ljust(42)


Six of one, half dozen of the other.  As I understand the problem, the width of 
the star-box is supposed to float to just enclose the longest line of data.  
So, you still need to iterate over the lines to figure out which one is 
longest.  Once you've got that, it's the difference between:

> "* %-*s *" % (max_length, data)

> "* %s *" % data.ljust(max_length)

Use whichever one feels more natural to you.  I grew up with printf(), so I 
learned my way around all wonderful format specifiers.  If you don't come from 
that background, I guess I can see why it might all look like gibberish and 
ljust() comes to mind first.

--
Roy Smith
r...@panix.com

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


Re: Newbie, homework help, please.

2012-04-21 Thread GrayShark
A lot of to do about this.




---
#!/usr/bin/python


xl = ["First Name and Last","ENGR 109-X","Fall 2999","Format Example"] 

xl_max = 0
for x in xl:
xl_max = max ( len( x ), xl_max )

topBorder = '^'*( xl_max + 4 )

print topBorder
for x in xl:
print "* %s%s *" % ( x, ' '*(xl_max - len( x )) )
print topBorder
---


On Saturday, April 21, 2012 10:28:33 AM UTC-7, someone wrote:
> Ok, this is my dillema, not only am I new to this programming buisness, 
> before the last few days, I did not even know what python was, and besides 
> opening up the internet or word documents, that is most of what I know. Yet, 
> I have a professor who should be on Psych medication for giving us 3 
> projects, 2 of which I have not listed here to do. I was able to do research 
> over the last 3 days, and I have spent 3 days on this project, by borrowing 
> others ideas on this project. Below, you will find my professors assignment 
> (oh, and due in one week right before finals, so I am stressing out so much, 
> cause I don't know why he is crazy enough to assign crap like this a week 
> before finals when I have Calculus final,chem final, etc. I have figured out 
> most of the assignment, and below, it will be posted after the teacher's post 
> of the assignment. What I need help with, and I have tried relentlessly to 
> find, is how to put freaking stars(asterisks) as border around a list without 
> installing any other program to a portable python, of course, this is where 
> my problem lies. Below, you will see what I have done, please, help!!!
> You are required to complete and submit the following programming projects in 
> Python by the indicated deadline:
> 
> Standard Header Information project (5 pts):
> Write a program that will:
> 1) Ask the user for the following information:
>   - name of file to be created for storing SHI
>   - user’s name (as part of SHI)
>   - user’s course and section (as part of SHI)
>   - user’s semester and year (as part of SHI)
>   - user’s assignment title (as part of SHI)
> 2) Write the above SHI data to a text (.txt) file with the name chosen by the 
> user (above)
> 3) Close the file that the SHI data was written to
> 4) Open the file with the SHI data (again)
> 5) Read the data into different (from part 1) variable names
> 6) Display the SHI data read from the file in the interpreter with a border 
> around the SHI data (include a buffer of 1 line/space between the border and 
> SHI data). An example might look like:
> 
>   ***
>   * *
>   * First Name and Last *
>   * ENGR 109-X  *
>   * Fall 2999   *
>   * Format Example  *
>   * *
>   ***
> 
> 
> textfile=input('Hello, we are about to create a text file. An example would 
> be: (sample.txt) without the parenthesis. What ever you do name it, it needs 
> to end in (.txt). What would you like to name your textfile?')
> userinput=[input('What is your name?'),input('What is your Course Section and 
> Course number?'),input('What is the Semester and year?'),input('What is the 
> title of this class assignment?')]
> for item in userinput:
> openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
> userinput);openfile.close()
> x=textfile;indat=open(x,'r');SHI=indat.read()
> def border(Sullivan):
> string=SHI
> stringlength=len(string)
> stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * 
> (3 + 3)
> hBorder=stringlength//2*"* "+"*"[:stringlength%2]
> spacer="*"+" "*(stringlength - 2)+"*"
> fancyText="*  "+string+"  *"
> return(hBorder,spacer,fancyText,hBorder)
> 
> textTuple = border(SHI)
> for lines in textTuple:
> print (lines)

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


Re: Newbie, homework help, please.

2012-04-21 Thread someone
On Saturday, April 21, 2012 12:28:33 PM UTC-5, someone wrote:
> Ok, this is my dillema, not only am I new to this programming buisness, 
> before the last few days, I did not even know what python was, and besides 
> opening up the internet or word documents, that is most of what I know. Yet, 
> I have a professor who should be on Psych medication for giving us 3 
> projects, 2 of which I have not listed here to do. I was able to do research 
> over the last 3 days, and I have spent 3 days on this project, by borrowing 
> others ideas on this project. Below, you will find my professors assignment 
> (oh, and due in one week right before finals, so I am stressing out so much, 
> cause I don't know why he is crazy enough to assign crap like this a week 
> before finals when I have Calculus final,chem final, etc. I have figured out 
> most of the assignment, and below, it will be posted after the teacher's post 
> of the assignment. What I need help with, and I have tried relentlessly to 
> find, is how to put freaking stars(asterisks) as border around a list without 
> installing any other program to a portable python, of course, this is where 
> my problem lies. Below, you will see what I have done, please, help!!!
> You are required to complete and submit the following programming projects in 
> Python by the indicated deadline:
> 
> Standard Header Information project (5 pts):
> Write a program that will:
> 1) Ask the user for the following information:
>   - name of file to be created for storing SHI
>   - user’s name (as part of SHI)
>   - user’s course and section (as part of SHI)
>   - user’s semester and year (as part of SHI)
>   - user’s assignment title (as part of SHI)
> 2) Write the above SHI data to a text (.txt) file with the name chosen by the 
> user (above)
> 3) Close the file that the SHI data was written to
> 4) Open the file with the SHI data (again)
> 5) Read the data into different (from part 1) variable names
> 6) Display the SHI data read from the file in the interpreter with a border 
> around the SHI data (include a buffer of 1 line/space between the border and 
> SHI data). An example might look like:
> 
>   ***
>   * *
>   * First Name and Last *
>   * ENGR 109-X  *
>   * Fall 2999   *
>   * Format Example  *
>   * *
>   ***
> 
> 
> textfile=input('Hello, we are about to create a text file. An example would 
> be: (sample.txt) without the parenthesis. What ever you do name it, it needs 
> to end in (.txt). What would you like to name your textfile?')
> userinput=[input('What is your name?'),input('What is your Course Section and 
> Course number?'),input('What is the Semester and year?'),input('What is the 
> title of this class assignment?')]
> for item in userinput:
> openfile=open(textfile,'w');openfile.writelines("%s\n" % item for item in 
> userinput);openfile.close()
> x=textfile;indat=open(x,'r');SHI=indat.read()
> def border(Sullivan):
> string=SHI
> stringlength=len(string)
> stringlength=stringlength("%s\n" % item for item in stringlength) + 2 * 
> (3 + 3)
> hBorder=stringlength//2*"* "+"*"[:stringlength%2]
> spacer="*"+" "*(stringlength - 2)+"*"
> fancyText="*  "+string+"  *"
> return(hBorder,spacer,fancyText,hBorder)
> 
> textTuple = border(SHI)
> for lines in textTuple:
> print (lines)

Thanks Bart for trying, it helped me out a little more by showing me a little 
more than I knew, but I tried and I am not sure if it does fit my example due 
to it was too many stars in between the lines, and not match up, but if you see 
any more help, that would be great, or see something I am doing wrong, or 
figure something out, let me know, have a great day, again, thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-21 Thread BartC

"someone"  wrote in message
news:4068590.2196.1335038608255.JavaMail.geo-discussion-forums@ynjn4...



textTuple = border(SHI)
for lines in textTuple:
print (lines)


Thanks your Bart for trying, I don't understand how it works or if you
tried to place my script in python to see if it would work, unfortunately,
I tried 10 different ways plus yours, and I don't see the connection.
Unless you were trying to help me see the way and I did not, sorry, but
thanks for trying. The characters did show me a little more.


Did you run my code fragment on it's own to see if it did the job?

The code can be packaged into a function border() just like you already 
have:


def border(text):
maxwidth=0
for s in text:
 if len(s)>maxwidth: maxwidth=len(s)

vertinchlines=6# assume 6 lines/inch
hozinchchars=10# assume 10 chars/inch

hozmargin=" "*hozinchchars

newtext=[]
for i in range(vertinchlines):
 newtext.append("")

newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)

for s in text:
 newtext.append(hozmargin+"* "+s+" "*(maxwidth-len(s))+" *"+hozmargin)

newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)

for i in range(vertinchlines):
 newtext.append("")

return newtext

And can be tested like this (obviously you will need to obtain SHI from the
input file):

SHI=["First Name and Last","ENGR 109-X","Fall 2999","Format Example"]

textTuple = border(SHI)

for lines in textTuple:
print (lines)

The text handling is clunky (I had to learn the Python as I went along), but
with these things you just want to get something working first, then you can
tweak.

--
Bartc 


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


Re: Newbie, homework help, please.

2012-04-21 Thread BartC

"someone"  wrote in message
news:9071485.2215.1335040139144.JavaMail.geo-discussion-forums@yniw15...


Thanks Bart for trying, it helped me out a little more by showing me a
little more than I knew, but I tried and I am not sure if it does fit my
example due to it was too many stars in between the lines, and not match
up, but if you see any more help, that would be great, or see something I
am doing wrong, or figure something out, let me know, have a great day,
again, thanks


Here's the example you posted:

***
* *
* First Name and Last *
* ENGR 109-X  *
* Fall 2999   *
* Format Example  *
* *
***

And here's the output from both bits of code I posted, which has 'one inch' 
of white space all around; both examples must be viewed with a fixed-pitch 
font (or in 'code' mode):







 ***
 * *
 * First Name and Last *
 * ENGR 109-X  *
 * Fall 2999   *
 * Format Example  *
 * *
 ***





Please post the output you're getting that has too many asterisks.

--
Bartc


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


Re: Newbie, homework help, please.

2012-04-21 Thread someone
On Saturday, April 21, 2012 3:44:49 PM UTC-5, BartC wrote:
> "someone"  wrote in message
> news:9071485.2215.1335040139144.JavaMail.geo-discussion-forums@yniw15...
> 
> > Thanks Bart for trying, it helped me out a little more by showing me a
> > little more than I knew, but I tried and I am not sure if it does fit my
> > example due to it was too many stars in between the lines, and not match
> > up, but if you see any more help, that would be great, or see something I
> > am doing wrong, or figure something out, let me know, have a great day,
> > again, thanks
> 
> Here's the example you posted:
> 
> ***
> * *
> * First Name and Last *
> * ENGR 109-X  *
> * Fall 2999   *
> * Format Example  *
> * *
> ***
> 
> And here's the output from both bits of code I posted, which has 'one inch' 
> of white space all around; both examples must be viewed with a fixed-pitch 
> font (or in 'code' mode):
> 
> 
> 
> 
> 
> 
>   ***
>   * *
>   * First Name and Last *
>   * ENGR 109-X  *
>   * Fall 2999   *
>   * Format Example  *
>   * *
>   ***
> 
> 
> 
> 
> 
> Please post the output you're getting that has too many asterisks.
> 
> -- 
> Bartc

Hi, Bart: Thank you, your post is working now, maybe, I did something wrong, 
unfortunately, you are right, my setup for getting the file to pull up 
correctly now is an issue, At first, I got a Vertical line with it working, 
then I tried to tinker with it, and it fratched, lol
def border(text):
 maxwidth=0
 for s in text:
  if len(s)>maxwidth: maxwidth=len(s)
 vertinchlines=6# assume 6 lines/inch
 hozinchchars=10# assume 10 chars/inch
 hozmargin=" "*hozinchchars
 newtext=[]
 for i in range(vertinchlines):
  newtext.append("")
 newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
 newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
 for s in text:
  newtext.append(hozmargin+"* "+s+" "*(maxwidth-len(s))+" *"+hozmargin)
 newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
 newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
 for i in range(vertinchlines):
  newtext.append("")
 return newtext
x=textfile;indat=open(x,'r');SHI=indat.read()
textTuple = border(SHI)
for lines in textTuple:
 print ("%s\n" %textTuple)


The issue is trying to get the SHI to work right, but omg, this is the closes I 
have gotten, you are awsome, thank you very much, i guess i will just keep 
messing with it till i get it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Bernd Nawothnig
On Sat, Apr 21, 2012 at 03:43:03PM -0400, Dave Angel wrote:
> On 04/21/2012 09:48 AM, Bernd Nawothnig wrote:
> > On Sat, Apr 21, 2012 at 09:21:50AM -0400, Dave Angel wrote:
> >>> [] is []
>  False
> >>> Same for that.
> >>
> >> Here I have to disagree.  If an implementation reused the list object
> >> for two simultaneously-existing instances, it would violate first
> >> principles.
> > 
> > Hm.
> > 
> > Even if there is no chance to reach any of these two lists after the
> > comparison because *no* references to them exist and both *must* be
> > identical because they are both noted as the same literals?
> > 
> > If any references exist, no question, that is pretty clear and
> > understandable. But in that special case?
> > 
> 
> You forgot to CC the list on your two messages to me.

Sorry, I'm reading the list via usenet gateway. Hopefully it works now.
 
> Clearly, False has to be a valid return result.  So I assume your
> question is why shouldn't an implementation be permitted to return True,
> in other words why couldn't it be ambiguous, like the immutable case.

Yes.
 
> Why would you (a hypothetical compiler writer) write an optimizer to
> look for such a special case like this, when the code would probably
> never appear in a real program, and certainly not in a performance
> critical portion of one.
> And if you did write one, why would you have it produce a different
> result than the non-optimized version?  Why not have it return 42 if
> that's the goal?

My original statement was: don't rely on such behaviour, it is an
implementation detail.

Your argument above was: it would violate first principles. And I still don't
see that point. The comparison [] is [] maybe totally useless, of course, but
which first principle would be violated by a compiler that lets that
expression evaluate to True?

Where can I read that the result *must* be False?

Otherwise it is simply an ambigious and not clearly defined expression like

() is ()





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


Re: Newbie, homework help, please.

2012-04-21 Thread Kiuhnm

On 4/21/2012 22:26, GrayShark wrote:

---
#!/usr/bin/python


xl = ["First Name and Last","ENGR 109-X","Fall 2999","Format Example"]

xl_max = 0
for x in xl:
xl_max = max ( len( x ), xl_max )


Or
  xl_max = max([len(x) for x in xl])


topBorder = '^'*( xl_max + 4 )

print topBorder
for x in xl:
print "* %s%s *" % ( x, ' '*(xl_max - len( x )) )


Or
  print "* %-*s *" % (xl_max, x)

I hope you don't mind.

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Robert Kern

On 4/21/12 10:15 PM, Bernd Nawothnig wrote:


Your argument above was: it would violate first principles. And I still don't
see that point. The comparison [] is [] maybe totally useless, of course, but
which first principle would be violated by a compiler that lets that
expression evaluate to True?

Where can I read that the result *must* be False?


http://docs.python.org/reference/expressions.html#list-displays

"A list display yields a new list object."

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Newbie, homework help, please.

2012-04-21 Thread BartC

"someone"  wrote in message
news:9533449.630.1335042672358.JavaMail.geo-discussion-forums@ynmf4...

On Saturday, April 21, 2012 3:44:49 PM UTC-5, BartC wrote:



Hi, Bart: Thank you, your post is working now, maybe, I did something
wrong, unfortunately, you are right, my setup for getting the file to pull
up correctly now is an issue, At first, I got a Vertical line with it
working, then I tried to tinker with it, and it fratched, lol
def border(text):
maxwidth=0
for s in text:
 if len(s)>maxwidth: maxwidth=len(s)
vertinchlines=6# assume 6 lines/inch
hozinchchars=10# assume 10 chars/inch
hozmargin=" "*hozinchchars
newtext=[]
for i in range(vertinchlines):
 newtext.append("")
newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
for s in text:
 newtext.append(hozmargin+"* "+s+" "*(maxwidth-len(s))+" *"+hozmargin)
newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
for i in range(vertinchlines):
 newtext.append("")
return newtext
x=textfile;indat=open(x,'r');SHI=indat.read()
textTuple = border(SHI)
for lines in textTuple:
print ("%s\n" %textTuple)


The issue is trying to get the SHI to work right, but omg, this is the
closes I have gotten, you are awsome, thank you very much, i guess i will
just keep messing with it till i get it


I had to use this code to make this work right from a file (in additon to 
the border() function):


textfile="kkk4" # (don't use this; this was my test input)

x=textfile;indat=open(x,'r');

SHI=indat.readlines()
indat.close()

for i in range(len(SHI)):# remove trailing '\n' from each line
s=SHI[i]
SHI[i]=(s[0:len(s)-1])

textTuple = border(SHI)

for lines in textTuple:
print (lines)

Your indat.read() seemed to read all the lines as one long string. I used
indat.readlines() instead. However each line has a newline char '\n' at the
end. I put in a loop to get rid of that (I'm sure there's a one-line fix to
do that, but as I said don't know Python).

The input file I used had to have this format:

First Name and Last
ENGR 109-X
Fall 2999
Format Example

--
Bartc 


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


Re: Newbie, homework help, please.

2012-04-21 Thread duncan smith

On 21/04/12 23:48, BartC wrote:

"someone"  wrote in message
news:9533449.630.1335042672358.JavaMail.geo-discussion-forums@ynmf4...

On Saturday, April 21, 2012 3:44:49 PM UTC-5, BartC wrote:



Hi, Bart: Thank you, your post is working now, maybe, I did something
wrong, unfortunately, you are right, my setup for getting the file to
pull
up correctly now is an issue, At first, I got a Vertical line with it
working, then I tried to tinker with it, and it fratched, lol
def border(text):
maxwidth=0
for s in text:
if len(s)>maxwidth: maxwidth=len(s)
vertinchlines=6 # assume 6 lines/inch
hozinchchars=10 # assume 10 chars/inch
hozmargin=" "*hozinchchars
newtext=[]
for i in range(vertinchlines):
newtext.append("")
newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
for s in text:
newtext.append(hozmargin+"* "+s+" "*(maxwidth-len(s))+" *"+hozmargin)
newtext.append(hozmargin+"* "+" "*maxwidth+" *"+hozmargin)
newtext.append(hozmargin+"*"*(maxwidth+4)+hozmargin)
for i in range(vertinchlines):
newtext.append("")
return newtext
x=textfile;indat=open(x,'r');SHI=indat.read()
textTuple = border(SHI)
for lines in textTuple:
print ("%s\n" %textTuple)


The issue is trying to get the SHI to work right, but omg, this is the
closes I have gotten, you are awsome, thank you very much, i guess i will
just keep messing with it till i get it


I had to use this code to make this work right from a file (in additon
to the border() function):

textfile="kkk4" # (don't use this; this was my test input)

x=textfile;indat=open(x,'r');

SHI=indat.readlines()
indat.close()

for i in range(len(SHI)): # remove trailing '\n' from each line
s=SHI[i]
SHI[i]=(s[0:len(s)-1])

textTuple = border(SHI)

for lines in textTuple:
print (lines)

Your indat.read() seemed to read all the lines as one long string. I used
indat.readlines() instead. However each line has a newline char '\n' at the
end. I put in a loop to get rid of that (I'm sure there's a one-line fix to
do that, but as I said don't know Python).



[snip]

line = line.rstrip()

would do the job. And as file objects are iterable,

indat = open(x,'r')
SHI = [line.rstrip() for line in indat]
indat.close()

textTuple = border(SHI)

etc.

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


Re: Newbie, homework help, please.

2012-04-21 Thread Michael Torrie
On 04/21/2012 02:14 PM, someone wrote:
> Thanks for your reply Mr. Roy Smith. Also, thanks for the tip. Maybe
>  I did not make myself as clear or maybe you did not understand my 
> post. It states homework help, and I am doing this post to get help 
> before I pay somebody to show me how to do it, because, obviously our
> professor is not kind enough to show us how to do this less than two
> weeks before the due date with 3 projects (and now I have basically
> less than a week before it is due- and I am not waiting till the last
> minute)

I commend you for not waiting until the last minute.  And I'm glad you
are making progress with this assignment, with Bart's help.

I am curious though.  What class is this and how do you find yourself, a
non-programmer as you say, in this class?  When I was a student studying
CS, what you describe is typical for CS major classes.  IE the teacher
wasn't there to teach a language, rather he or she was there to teach
the theory and possible real-world application of the subject matter,
often algorithms, or database design.  In fact I had one class where the
text book had all its examples and exercises in one language (C), the
professor preferred and taught using examples from another langauge
(Object PASCAL), and I did all my projects in a third language, C++.
Poor TAs.  They had to be able to check of projects written in 3
different languages.  Now I hear the class is taught in Java.  Poor
souls. But I digress.

What is this class called?  What is the stated purpose of this class?

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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Steven D'Aprano
On Sat, 21 Apr 2012 15:02:00 +0200, Bernd Nawothnig wrote:

> On 2012-04-20, dmitrey wrote:
>> I have spent some time searching for a bug in my code, it was due to
>> different work of "is" with () and []:
> () is ()
>> True
> 
> You should better not rely on that result. I would consider it to be an
> implementation detail. I may be wrong, but would an implementation that
> results in
> 
> () is () ==> False
> 
> be correct or is the result True really demanded by the language
> specification?

It would be correct, and the result True absolutely is NOT demanded by 
the language. For example, Jython does not make that same optimization:

steve@runes:~$ jython
Jython 2.5.1+ (Release_2_5_1, Aug 4 2010, 07:18:19)
[OpenJDK Client VM (Sun Microsystems Inc.)] on java1.6.0_18
Type "help", "copyright", "credits" or "license" for more information.
>>> () is ()
False


so code which relies on it is already broken.


Python the language makes no promises that literals will always evaluate 
to the same object. The ONLY such promises that it makes are that a small 
handful of special constants are singletons:

None
NotImplemented
True
False

and perhaps one or two others. Everything else is an accident of the 
implementation.

The CPython interpreter is especially aggressive in optimizing multiple 
literals in the same line. Compare this:

>>> x = 3.1; y = 3.1; x is y
True

with this:

>>> x = 3.1
>>> y = 3.1
>>> x is y
False


Again, this is an accident of implementation, and cannot be relied on.



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


Re: why () is () and [] is [] work in other way?

2012-04-21 Thread Chris Angelico
On Sun, Apr 22, 2012 at 1:14 PM, Steven D'Aprano
 wrote:
> The CPython interpreter is especially aggressive in optimizing multiple
> literals in the same line. Compare this:
>
 x = 3.1; y = 3.1; x is y
> True
>
> with this:
>
 x = 3.1
 y = 3.1
 x is y
> False
>
>
> Again, this is an accident of implementation, and cannot be relied on.

That's the interactive interpreter, which works on a basis of lines.
With .py files, both 2.6 and 3.2 on Windows appear to do the same
optimization at module level. But either way, that's optimization of
constants.

>>> x=3.1+1.0; y=3.1+1.0; x is y
False
>>> x=3.1; y=3.1; x+y is x+y
False

Which can have micro-optimization implications:
>>> x=1048576; y=1048576; x is y
True
>>> x=1<<20; y=1<<20; x is y
False

But if you're concerning yourself with this kind of optimization,
you're probably wasting your time. :)

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


Re: Appending to []

2012-04-21 Thread Steven D'Aprano
On Sat, 21 Apr 2012 14:48:44 +0200, Bernd Nawothnig wrote:

> On 2012-04-20, Rotwang wrote:
>> since a method doesn't assign the value it returns to the instance on
>> which it is called; what it does to the instance and what it returns
>> are two completely different things.
> 
> Returning a None-value is pretty useless. Why not returning self, which
> would be the resulting list in this case? Returning self would make the
> language a little bit more functional, without any drawback.

It is a deliberate design choice, and there would be a drawback.

A method like append could have three obvious designs:

1) Functional, no side-effects: return a new list with the item appended.

2) Functional, with side-effect: return the same list, after appending 
the item.

3) Procedural, with side-effect: append the item, don't return anything 
(like a procedure in Pascal, or void in C).

Python chooses 3) as the design, as it is the cleanest, most pure choice 
for a method designed to operate by side-effect. Unfortunately, since 
Python doesn't have procedures, that clean design is slightly spoilt due 
to the need for append to return None (instead of not returning anything 
at all).

How about 1), the pure functional design? The downside of that is the 
usual downside of functional programming -- it is inefficient to 
duplicate a list of 100 million items just to add one more item to that 
list. Besides, if you want a pure functional append operation, you can 
simply use mylist + [item] instead.

But what about 2), the mixed (impure) functional design? Unfortunately, 
it too has a failure mode: by returning a list, it encourages the error 
of assuming the list is a copy rather than the original:

mylist = [1, 2, 3, 4]
another_list = mylist.append(5)
# many pages of code later...
do_something_with(mylist)


This is especially a pernicious error because instead of giving an 
exception, your program will silently do the wrong thing. 

"I find it amusing when novice programmers believe their main
job is preventing programs from crashing. More experienced
programmers realize that correct code is great, code that 
crashes could use improvement, but incorrect code that doesn’t 
crash is a horrible nightmare."
-- Chris Smith


Debugging these sorts of bugs can become very difficult, and design 2) is 
an attractive nuisance: it looks good because you can chain appends:

mylist.append(17).append(23).append(42)
# but why not use mylist.extend([17, 23, 42]) instead?

but the disadvantage in practice far outweighs the advantage in theory.

This is the same reason why list.sort, reverse and others also return 
None.



> Then nested calls like
> 
> a = [].append('x').append('y').append('z')
> 
> would be possible with a containing the resulting list
> 
> ['x', 'y', 'z'].
> 
> That is the way I expect any append to behave.

That would be possible, but pointless. Why not use:

a = ['x', 'y', 'z'] 

directly instead of constructing an empty list and then make three 
separate method calls? Methods which operate by side-effect but return 
self are an attractive nuisance: they seem like a good idea but actually 
aren't, because they encourage the user to write inefficient, or worse, 
incorrect, code.



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