Re: Language design

2013-09-10 Thread diverman
No exactly bad, but can suprise

>>> foo=([],)
>>> foo[0] += ['bar']
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> foo
(['bar'],)



Dne úterý, 10. září 2013 8:09:25 UTC+2 Steven D'Aprano napsal(a):
> Some time ago, Tom Christiansen wrote about the "Seven Deadly Sins of 
> 
> Perl":
> 
> 
> 
> http://www.perl.com/doc/FMTEYEWTK/versus/perl.html
> 
> 
> 
> 
> 
> What design mistakes, traps or gotchas do you think Python has? Gotchas 
> 
> are not necessarily a bad thing, there may be good reasons for it, but 
> 
> they're surprising.
> 
> 
> 
> To get started, here are a couple of mine:
> 
> 
> 
> 
> 
> - Python is so dynamic, that there is hardly anything at all that can be 
> 
> optimized at compile time.
> 
> 
> 
> - The behaviour of mutable default variables is a gotcha.
> 
> 
> 
> - Operators that call dunder methods like __add__ don't use the same 
> 
> method resolution rules as regular methods, they bypass the instance and 
> 
> go straight to the type, at least for new-style classes.
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven

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


Re: a gift function and a question

2013-09-10 Thread Steven D'Aprano
On Tue, 10 Sep 2013 00:40:59 +0430, Mohsen Pahlevanzadeh wrote:

> Dear all,
> 
> I have a gift for mailing list:
> 
> 
> def integerToPersian(number):
> listedPersian = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹']
> listedEnglish = ['0','1','2','3','4','5','6','7','8','9'] 
> returnList = list()
> listedTmpString = list(str(number))
> for i in listedTmpString:
> returnList.append(listedPersian[listedEnglish.index(i)])
> return ''.join(returnList)
> 
> When you call it such as : "integerToPersian(3455)" ,  it return ۳۴۵۵,
> ۳۴۵۵ is equivalent to 3455 in Persian and Arabic language.When you read
> a number such as reading from databae, and want to show in widget, this
> function is very useful.


Thank you Mohsen!


Here is a slightly more idiomatic version of the same function. This is 
written for Python 3:

def integerToPersian(number):
"""Convert positive integers to Persian.

>>> integerToPersian(3455)
'۳۴۵۵'

Does not support negative numbers.
"""
digit_map = dict(zip('0123456789', '۰۱۲۳۴۵۶۷۸۹'))
digits = [digit_map[c] for c in str(number)]
return ''.join(digits)


Python 2 version will be nearly the same except it needs to use the u 
prefix on the strings.



> My question is , do you have reverse of this function? persianToInteger?

The Python built-in int function already supports that:


py> int('۳۴۵۵')
3455


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


Re: Language design

2013-09-10 Thread Ben Finney
Steven D'Aprano  writes:

> What design mistakes, traps or gotchas do you think Python has?

* Imports are fiendishly complex, hidden below deceptively simple
  syntax.

  It's a reasonable expectation that one can import a module from a
  source code file given its path on the filesystem, but this turns out
  to be much more complicated than in many other languages.

  There are reasons for this, some good, some merely historical baggage,
  some workarounds for OS misdesign, and some that may be Python's own
  mistakes. Those reasons are difficult to appreciate when first
  encountering the problem.

* Somewhat related, and not really part of language design: The import
  mechanism and the packaging tools are woefully behind the state of the
  art in getting applications and their libraries to cooperate with
  operating system package management.

  This has the terrible effect that developers choose to insulate Python
  from the operating system, essentially losing all the benefits of the
  operating system package manager for their dependencies and needing to
  re-implement package management all over again, badly.

  This is largely the fault of operating systems with package dependency
  managers that are poor (Apple's) to nonexistent (Microsoft's). But the
  result is that Python's tools have been particularly woeful in this
  area compared to some other languages, and the Python community now
  has learned to subvert all OS package managers, even the good ones.

> Gotchas are not necessarily a bad thing, there may be good reasons for
> it, but they're surprising.

* Python requires every programmer to know, or quickly learn, the basics
  of Unicode: to know that text is not, and never will be again,
  synonymous with a sequence of bytes.

  This is, in the long run, a good thing for all programmers and those
  who will use their programs. Programmers should expect to deal with
  non-ASCII text earlier than the innocent might suppose, and the
  likelihood goes up all the time. The sooner we replace the erroneous
  “text is ASCII” in the common wisdom with “text is Unicode”, the
  better.

  Nevertheless, the outstanding robustness of Python's Unicode support
  is different from most languages, and so is a gotcha.

-- 
 \  “Life does not cease to be funny when people die any more than |
  `\  it ceases to be serious when people laugh.” —George Bernard Shaw |
_o__)  |
Ben Finney

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


Re: Weighted choices

2013-09-10 Thread Antoon Pardon
Op 10-09-13 04:27, Jason Friedman schreef:
>>> I coach a flag football team of 11-year-olds.  A stated goal of the
>>> league is that every player should get nearly equal playing time and
>>> that winning is of secondary importance.  That said, some players just
>>> can't throw the ball at all, and having a quarterback who cannot throw
>>> is no fun for anyone.  The other coach and I will pick two players who
>>> will be the quarterback for any given snap. The other players can play
>>> any position (center, receiver, runner) other than quarterback.
>>>
>>> The game is 5-on-5 and our roster contains ten players, and we can
>>> expect a random player or two missing on any given week.  I'm trying
>>> to come up with a system that causes at least one of those
>>> quarterbacks to be on the offensive field on every play.  Further, to
>>> compensate for the fact that the quarterback gets to touch the ball on
>>> every play, we want the quarterbacks to appear at the non-quarterback
>>> positions somewhat less than the other players.
>>>
>>> This is all quite challenging.  11-year-olds are exquisitely tuned to
>>> unfairness and most have a keen idea of the play that will surely
>>> score a touchdown if only the clueless coach would let them run it.
>>> Oh, and the originator of this play will be the key
>>> quarterback/runner/receiver for the play.  Oh, and in case the coach
>>> forgets, they will remind him.
>>
>> OK, you're well inside the "finite" domain. Also, you probably want less
>> than the "natural" randomness. I'd probably shuffle the potential
>> quarterbacks and the others in independent lists, and then pick one half of
>> each to form a team. The other half would play in the next game.
>> Additionally you can keep track of every player's total number of games and
>> games not played in a row, and apply a correction if either exceeds a limit
>> acceptable for a kid.
> 
> PIcking half to play one game and half to play the other is not an
> option.  For one, there really isn't a concept of half when a variable
> number of players are available on a given Saturday.  For two, we
> could have an unexpected absence, or during the game an injury.  For
> three, the parents paid to have their child play in the league, and
> the league runs until the end of October, not long enough for that
> strategy to work out.

First pick a quarterback,

Then for picking players, I would start with giving each player some
weight. After each game you adjust those weights. Those that were
fielded get their weight adjusted down. Those who were not get their
weight adjusted up. You might choose to adjust those that were absent
too, maybe up but not us much as those present but not fielded, with an
upper limit of double starting weight.

Since the quarterbacks are fielded more, their weight will be less when
you pick the rest of the team, so they will play less at other
positions.

Starting weights and adjustment will have to be picked by simulating a
season and see what works.

-- 
Antoon Pardon
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a gift function and a question

2013-09-10 Thread Peter Otten
Mohsen Pahlevanzadeh wrote:

> I completed my two functions, i say may be poeple can use them:
> ##33
> def integerToPersian(number):
> listedPersian = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹']
> listedEnglish = ['0','1','2','3','4','5','6','7','8','9']
> returnList = list()
>
> for i in list(str(number)):
> returnList.append(listedPersian[listedEnglish.index(i)])
> 
> return ''.join(returnList)
> 
> def persianToInterger(persianNumber):
> listedTmpString = list(persianNumber.decode("utf-8"))
> returnList = list()
> 
> for i in listedTmpString:
> returnList.append(unicodedata.digit(i))
> 
> return int (''.join(str(x) for x in returnList))

There is also the str.translate() method which takes a translation dict. 
Characters not in that dict will be left unaltered:

>>> persian = "۰۱۲۳۴۵۶۷۸۹"
>>> english = "0123456789"
>>> _p2e = str.maketrans(persian, english)
>>> _e2p = str.maketrans(english, persian)
>>> def persian_to_english(s): return s.translate(_p2e)
... 
>>> def english_to_persian(s): return s.translate(_e2p)
... 
>>> english_to_persian("alpha 12321 beta")
'alpha ۱۲۳۲۱ beta'
>>> persian_to_english(_)
'alpha 12321 beta'

[Advanced usage] If you prefer to get an error you can subclass dict:

>>> class NoDigitError(Exception):
... pass
... 
>>> class StrictDict(dict):
... def __missing__(self, key):
... raise NoDigitError("Illegal codepoint #{}".format(key))
... 
>>> _e2p = StrictDict(str.maketrans(english, persian))
>>> english_to_persian("543")
'۵۴۳'
>>> english_to_persian("x543")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in english_to_persian
  File "", line 3, in __missing__
__main__.NoDigitError: Illegal codepoint #120


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


Re: Language design

2013-09-10 Thread Antoon Pardon
Op 10-09-13 08:09, Steven D'Aprano schreef:
> Some time ago, Tom Christiansen wrote about the "Seven Deadly Sins of 
> Perl":
> 
> http://www.perl.com/doc/FMTEYEWTK/versus/perl.html
> 
> 
> What design mistakes, traps or gotchas do you think Python has? Gotchas 
> are not necessarily a bad thing, there may be good reasons for it, but 
> they're surprising.
> 
> To get started, here are a couple of mine:
> 
> 
> - Python is so dynamic, that there is hardly anything at all that can be 
> optimized at compile time.
> 
> - The behaviour of mutable default variables is a gotcha.
> 
> - Operators that call dunder methods like __add__ don't use the same 
> method resolution rules as regular methods, they bypass the instance and 
> go straight to the type, at least for new-style classes.

Slice semantics in combination with negative indices.

Take ls = range[10]

What is the reverse of ls[a : b]? It is [b-1 : a-1: -1]

Except of course when a == 0 or b == 0.

-- 
Antoon Pardon

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


Re: Can I trust downloading Python?

2013-09-10 Thread Oscar Benjamin
On 10 September 2013 01:06, Steven D'Aprano
 wrote:
> On Mon, 09 Sep 2013 12:19:11 +, Fattburger wrote:
>
> But really, we've learned *nothing* from the viruses of the 1990s.
> Remember when we used to talk about how crazy it was to download code
> from untrusted sites on the Internet and execute it? We're still doing
> it, a hundred times a day. Every time you go on the Internet, you
> download other people's code and execute it. Javascript, Flash, HTML5,
> PDF are all either executable, or they include executable components. Now
> they're *supposed* to be sandboxed, but we've gone from "don't execute
> untrusted code" to "let's hope my browser doesn't have any bugs that the
> untrusted code might exploit".

You could have also mentioned pip/PyPI in that. 'pip install X'
downloads and runs arbitrary code from a largely unmonitored and
uncontrolled code repository. The maintainers of PyPI can only try to
ensure that the original author of X would remain in control of what
happens and could remove a package X if it were discovered to be
malware. However they don't have anything like the resources to
monitor all the code coming in so it's essentially a system based on
trust in the authors where the only requirement to be an author is
that you have an email address. Occasionally I see the suggestion to
do 'sudo pip install X' which literally gives root permissions to
arbitrary code coming straight from the net.


Oscar
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Language design

2013-09-10 Thread Chris Angelico
On Tue, Sep 10, 2013 at 4:09 PM, Steven D'Aprano  wrote:
> What design mistakes, traps or gotchas do you think Python has? Gotchas
> are not necessarily a bad thing, there may be good reasons for it, but
> they're surprising.

Significant indentation. It gets someone every day, it seems.

The fact that importing twice doesn't reexecute any code.

The whole "consenting adults" philosophy. I happen to quite like it,
as do many of the regulars here, but it does trip up a lot of
programmers who've come from other languages.

Like you say, not necessarily a bad thing; but Admiral Ackbars all the same.

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


Re: Weighted choices

2013-09-10 Thread Oscar Benjamin
On 10 September 2013 03:27, Jason Friedman  wrote:
>>
>> OK, you're well inside the "finite" domain. Also, you probably want less
>> than the "natural" randomness. I'd probably shuffle the potential
>> quarterbacks and the others in independent lists, and then pick one half of
>> each to form a team. The other half would play in the next game.
>> Additionally you can keep track of every player's total number of games and
>> games not played in a row, and apply a correction if either exceeds a limit
>> acceptable for a kid.
>
> PIcking half to play one game and half to play the other is not an
> option.  For one, there really isn't a concept of half when a variable
> number of players are available on a given Saturday.  For two, we
> could have an unexpected absence, or during the game an injury.  For
> three, the parents paid to have their child play in the league, and
> the league runs until the end of October, not long enough for that
> strategy to work out.

Don't take the "pick half" idea so literally. Look at it a different
way: attempt to form a team from all the players who didn't play in
the last game. If that group of players isn't enough to form a team
then they're all in the team and the remainder is chosen randomly from
those that did play in the last game. Here's a concrete example:

Dave hasn't played for 3 games
John, Bob and Steve haven't played for 2 games
Baz, Joe and Tom haven't played for 1 game
James and Tim played the last game.

Those are all the players that could make it on Saturday but you need
to choose 6. You want either of Bob or Tim for quarterback. Bob hasn't
played for longer so you choose him. Obviously Dave's in because he
hasn't played for longer than everyone else. That's not enough for a
team though so you'll need John and Tom as well. That makes 4 so you
need 2 more. However there are three players left that didn't play in
the last game. At this point you put their three names in a hat and
draw out 2 giving Baz and Tom. So Joe has to sit this one out but he's
pretty much definitely in the next game.

Rather than drawing names out of a hat, you could use the total number
of games played as a tiebreaker and only resort to coin-flipping or
whatever when you get a tie for that as well. You could do the same
for quarterback selection as well but based on how often they've been
quarterback and then how many games they've played and then flip a
coin. This algorithm is not really that random but since it depends on
who's available on what day it will probably jumble up the teams over
time at the same time as being broadly fair to each of the children.

For the quarterbacks you'll always be picking the ones that played
least recently so as long as your quarterback pool is oversized in
proportion to the number of players they'll end up playing as much as
everyone else. i.e. if a team has 1 quarterback and 5 players then
your total quarterback pool should be more than 1/5 of the total
player pool (this is also probably necessary to guarantee having a
quarterback anyway).


Oscar
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I trust downloading Python?

2013-09-10 Thread Tom P

On 10.09.2013 11:45, Oscar Benjamin wrote:

On 10 September 2013 01:06, Steven D'Aprano
 wrote:

On Mon, 09 Sep 2013 12:19:11 +, Fattburger wrote:

But really, we've learned *nothing* from the viruses of the 1990s.
Remember when we used to talk about how crazy it was to download code
from untrusted sites on the Internet and execute it? We're still doing
it, a hundred times a day. Every time you go on the Internet, you
download other people's code and execute it. Javascript, Flash, HTML5,
PDF are all either executable, or they include executable components. Now
they're *supposed* to be sandboxed, but we've gone from "don't execute
untrusted code" to "let's hope my browser doesn't have any bugs that the
untrusted code might exploit".


You could have also mentioned pip/PyPI in that. 'pip install X'
downloads and runs arbitrary code from a largely unmonitored and
uncontrolled code repository. The maintainers of PyPI can only try to
ensure that the original author of X would remain in control of what
happens and could remove a package X if it were discovered to be
malware. However they don't have anything like the resources to
monitor all the code coming in so it's essentially a system based on
trust in the authors where the only requirement to be an author is
that you have an email address. Occasionally I see the suggestion to
do 'sudo pip install X' which literally gives root permissions to
arbitrary code coming straight from the net.


Oscar



Interesting observation
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can I trust downloading Python?

2013-09-10 Thread Chris Angelico
On Tue, Sep 10, 2013 at 10:06 AM, Steven D'Aprano
 wrote:
> Of course, Linux is a much
> harder target than the average unpatched Windows box, and there are
> probably easier ways to get access to your files if they really need to.

Plus "Linux" isn't a single target. You can search the internet for
Windows XP boxes and there's an extremely high chance they'll all be
running the same base services; when you're attacking Linux, there's a
much MUCH smaller set of common code, with most attacks being aimed at
an application - which may or may not be running on any given
computer. So there's a lot less chance that you'll be randomly
assaulted just for connecting to the internet; the attacks are most
likely to come from browsing a site that exploits a Javascript
vulnerability.

I'm not particularly bothered by the possibility of someone snooping
at what I'm doing. Oh how terrible, they'll discover that I'm just as
nerdy in private as I am in public...

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


Re: a gift function and a question

2013-09-10 Thread random832
On Tue, Sep 10, 2013, at 3:01, Steven D'Aprano wrote:
> def integerToPersian(number):
> """Convert positive integers to Persian.
> 
> >>> integerToPersian(3455)
> '۳۴۵۵'
> 
> Does not support negative numbers.
> """
> digit_map = dict(zip('0123456789', '۰۱۲۳۴۵۶۷۸۹'))
> digits = [digit_map[c] for c in str(number)]
> return ''.join(digits)

You can support negative numbers if you use digit_map.get(c,c).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Monitor key presses in Python?

2013-09-10 Thread Grant Edwards
On 2013-09-09, [email protected]  wrote:

> Is there a way to detect if the user presses a key in Python that
> works on most OS's?

No.  Unless by "most OSes" you mean "most Unixes" or "most Windows".

> I've only seen 1 method, and that only works in
> Python 2.6 and less.

> If you get the key, can you store it in a variable?

Sure.

> Also, is there a way to create a callback in Python?

Yes.

-- 
Grant Edwards   grant.b.edwardsYow! I'm having an
  at   EMOTIONAL OUTBURST!!  But,
  gmail.comuh, WHY is there a WAFFLE
   in my PAJAMA POCKET??
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python REST API access fails after adding date to URL

2013-09-10 Thread mahsan9861
Sorry about the typo I meant append the date to the URL. So at the end of the 
current URL adding ?date=ddmm. But I will go through the documentation to 
see if I missed anything, but as far as I remember it said to just append the 
date in that format.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a gift function and a question

2013-09-10 Thread Steven D'Aprano
On Tue, 10 Sep 2013 07:01:20 +, Steven D'Aprano wrote:

> On Tue, 10 Sep 2013 00:40:59 +0430, Mohsen Pahlevanzadeh wrote:

>> My question is , do you have reverse of this function?
>> persianToInteger?
> 
> The Python built-in int function already supports that:
> 
> 
> py> int('۳۴۵۵')
> 3455


Oh, I forgot to mention, this works back to at least Python 2.4, provided 
you remember to use Unicode strings rather than bytes:


py> b = '۳۴۵۵'  # This fails.
py> int(b)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '\xdb\xb3\xdb\xb4\xdb
\xb5\xdb\xb5'
py>
py> s = u'۳۴۵۵'  # This works.
py> int(s)
3455



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


Re: Can I trust downloading Python?

2013-09-10 Thread Steven D'Aprano
On Tue, 10 Sep 2013 10:45:16 +0100, Oscar Benjamin wrote:

> On 10 September 2013 01:06, Steven D'Aprano
>  wrote:

[rant about executing code over the internet]
 
> You could have also mentioned pip/PyPI in that. 'pip install X'
> downloads and runs arbitrary code from a largely unmonitored and
> uncontrolled code repository. The maintainers of PyPI can only try to
> ensure that the original author of X would remain in control of what
> happens and could remove a package X if it were discovered to be
> malware. However they don't have anything like the resources to monitor
> all the code coming in so it's essentially a system based on trust in
> the authors where the only requirement to be an author is that you have
> an email address. Occasionally I see the suggestion to do 'sudo pip
> install X' which literally gives root permissions to arbitrary code
> coming straight from the net.

Sure, but there's a significant difference here.

If I were to run "pip install foo", I'm explicitly choosing to trust that 
code. If I don't trust it, I simply don't run pip install. Merely going 
to the PyPI website for package "foo" doesn't run foo, nor does viewing 
the code, or even running "hg update" (or git) on the repository. By 
default, foo doesn't run unless I explicitly run it. pip is *fail safe* 
-- if it fails, or if I don't run it, nothing gets executed.

In contrast, if I go to foo.com, the default is "everything will run". I 
have *no idea* what's going to happen until I get there. The default is 
"run anything, unless explicitly turned off" instead of "don't run, 
unless explicitly turned on". Even if I run NoScript in my browser, or 
turn off Javascript in my browser, I'm hoping that there isn't some 
executable protocol that NoScript doesn't block, or only partially blocks 
("What do you mean web fonts contain executable code?"), or maybe I 
turned Javascript back on so some other site works and forgot to turn it 
off again. Our browsers are fail unsafe -- if they fail, they can run 
untrusted code.

You can't even say "well if you don't trust foo.com, don't go there" 
because while foo.com itself might be trusted, they're probably selling 
advertising, and the advert itself is executable and could come from 
anyone, anywhere.

Imagine that every time you walked into a shop, the shop could instantly, 
irreversibly and silently deduct whatever amount of money from your 
credit card it liked, unless you remembered to put your credit card 
inside a metal wallet before entering the store. But most stores won't 
let you in if you do, or at least the shopping experience is painful. So 
we just hope that the store won't take advantage of that ability and rob 
us blind. That's not too far from the Internet security model.



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


Re: Chardet, file, ... and the Flexible String Representation

2013-09-10 Thread random832
On Mon, Sep 9, 2013, at 10:28, [email protected] wrote:
*time performance differences*
> 
> Comment: Such differences never happen with utf.

Why is this bad? Keeping in mind that otherwise they would all be almost
as slow as the UCS-4 case.

> >>> sys.getsizeof('a')
> 26
> >>> sys.getsizeof('€')
> 40
> >>> sys.getsizeof('\U0001d11e')
> 44
> 
> Comment: 18 bytes more than latin-1
> 
> Comment: With utf, a char (in string or not) never exceed 4 

A string is an object and needs to store the length, along with any
overhead relating to object headers. I believe there is also an appended
null character. Also, ASCII strings are stored differently from Latin-1
strings.

>>> sys.getsizeof('a'*999)
1048 = 49 bytes overhead, 1 byte per character.
>>> sys.getsizeof('\xa4'*999)
1072 = 74 bytes overhead, 1 byte per character.
>>> sys.getsizeof('\u20ac'*999)
2072 = 76 bytes overhead, 2 bytes per character.
>>> sys.getsizeof('\U0001d11e'*999)
4072 = 80 bytes overhead, 4 bytes per character.

(I bet sys.getsizeof('\xa4') will return 38 on your system, so 44 is
only six bytes more, not 18)

If we did not have the FSR, everything would be 4 bytes per character.
We might have less overhead, but a string only has to be 25 characters
long before the savings from the shorter representation outweigh even
having _no_ overhead, and every four bytes of overhead reduces that
number by one. And you have a 32-bit python build, which has less
overhead than mine - in yours, strings only have to be seven characters
long for the FSR to be worth it. Assume the minimum possible overhead is
two words for the object header, a size, and a pointer - i.e. sixteen
bytes, compared to the 25 you've demonstrated for ASCII, and strings
only need to be _two_ characters long for the FSR to be a better deal
than always using UCS4 strings.

The need for four-byte-per-character strings would not go away by
eliminating the FSR, so you're basically saying that everything should
be constrained to the worst-case performance scenario.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python REST API access fails after adding date to URL

2013-09-10 Thread mahsan9861
Found a solution. For query string you have to add it to both the http_headers 
dictionary AND to the URL when making the Request.

old line:
http_headers = {} 
http_headers['oauth_version'] = '1.0' 
new line:
http_headers = {} 
http_headers['date'] = 'ddmm' #add this line
http_headers['oauth_version'] = '1.0' 

old line:
req = urllib2.Request(base_url) 
new line:
req = urllib2.Request(base_url + '?date=ddmm') 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python REST API access fails after adding date to URL

2013-09-10 Thread mahsan9861
Found a solution. For query string you have to add it to both the http_headers 
dictionary AND to the URL when making the Request. 

old line:
http_headers = {} 
http_headers['oauth_version'] = '1.0' 

new line:
http_headers = {} 
http_headers['date'] = 'ddmm' #add this line 
http_headers['oauth_version'] = '1.0' 

old line:
req = urllib2.Request(base_url) 

new line:
req = urllib2.Request(base_url + '?date=ddmm') 

Everything else remains the same.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I trust downloading Python?

2013-09-10 Thread Wolfgang Keller
> Every time you go on the Internet, you download other people's code
> and execute it. Javascript, Flash, HTML5, PDF are all either
> executable, or they include executable components.

That's why I deactivate all of these by default. And why I *hate*
so-called "web designers" who *require* activation of such fancy flashy
nonsense gadgets.

PDF files are an exception since PDF was originally designed as a
"safe" subset of Postscript (postscript viruses had been demonstrated).
Now Adobe has jeopardized this by allowing embedding of Javascript in
PDF files (but that as well is deactivated by default for me).

Sincerely,

Wolfgang
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dealing with Lists

2013-09-10 Thread stas poritskiy
there is a little bit more to this, but i think when i will be able to process 
the list the way i need it i can continue on my own. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Dealing with Lists

2013-09-10 Thread stas poritskiy
Greetings to all!

i ran into a little logic problem and trying to figure it out.

my case is as follows:

i have a list of items each item represents a Group 

i need to create a set of nested groups,

so, for example:

myGroups = ["head", "neck", "arms", "legs"]

i need to get them to be represented like this:
(if you can imaging a folder structure)

head
  |_> neck
|_> arms
  |_>legs

and so on until i hit the last element.

what i thought would work (but don't know really how to advance here) is:

def createVNTgroups(self, groupsData):
#function recieves the LIST of group elements, INDEX0 is always the
#MAIN-ROOT of the tree

for i in range(len(groupsData)):
print groupsData[i]

for q in range(1, len(groupsData)):

print groupsData[q]

could someone give me a hint?

thanks in advance!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dealing with Lists

2013-09-10 Thread matt . komyanek
What you're asking is a Ragged Hierarchy.

On Tuesday, September 10, 2013 5:08:45 PM UTC-4, stas poritskiy wrote:
> Greetings to all!
> 
> 
> 
> i ran into a little logic problem and trying to figure it out.
> 
> 
> 
> my case is as follows:
> 
> 
> 
> i have a list of items each item represents a Group 
> 
> 
> 
> i need to create a set of nested groups,
> 
> 
> 
> so, for example:
> 
> 
> 
> myGroups = ["head", "neck", "arms", "legs"]
> 
> 
> 
> i need to get them to be represented like this:
> 
> (if you can imaging a folder structure)
> 
> 
> 
> head
> 
>   |_> neck
> 
> |_> arms
> 
>   |_>legs
> 
> 
> 
> and so on until i hit the last element.
> 
> 
> 
> what i thought would work (but don't know really how to advance here) is:
> 
> 
> 
> def createVNTgroups(self, groupsData):
> 
> #function recieves the LIST of group elements, INDEX0 is always the
> 
> #MAIN-ROOT of the tree
> 
> 
> 
> for i in range(len(groupsData)):
> 
> print groupsData[i]
> 
> 
> 
> for q in range(1, len(groupsData)):
> 
> 
> 
> print groupsData[q]
> 
> 
> 
> could someone give me a hint?
> 
> 
> 
> thanks in advance!

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


Re: Dealing with Lists

2013-09-10 Thread Dave Angel
On 10/9/2013 17:08, stas poritskiy wrote:

> Greetings to all!
>
> i ran into a little logic problem and trying to figure it out.
>
> my case is as follows:
>
> i have a list of items each item represents a Group 
>
> i need to create a set of nested groups,
>
> so, for example:
>
> myGroups = ["head", "neck", "arms", "legs"]
>
> i need to get them to be represented like this:
> (if you can imaging a folder structure)
>
> head
>   |_> neck
> |_> arms
>   |_>legs

I don't know what's meant by that  |_>  symbol.  If it's really supposed
to be like subdirectories, there'd be a name associated with the
sublist.  In which case you'd probably want dicts, not lists.

So I'd have to guess you want something like:

["head", ["neck", ["arms", ["legs"

To turn your list into that one, I'd write something like (untested):

def chop_up(mylist):
if len(mylist) == 1:
return mylist
return [mylist[0], chop_up(mylist[1:])]

I suspect your real problem is totally different, but this was an
interesting exercise.

-- 
DaveA


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


Re: Dealing with Lists

2013-09-10 Thread stas poritskiy
Those simbols are just for visual representation.

I need to store each of the first elements of a par, so I can reference to them 
as to a parent of another group.

So head is parent of neck,  while neck is parent of arms and so on.

I'm not sure I understand how to apply your chop list example, dave
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dealing with Lists

2013-09-10 Thread Dave Angel
On 10/9/2013 18:11, stas poritskiy wrote:

Please include some quotation from the message you're replying to.  We
can't tell who this was responding to until the very last line, where
you mention my name.  But since you're using buggy googlegroups, you'd
better also read

 http://wiki.python.org/moin/GoogleGroupsPython

> Those simbols are just for visual representation.
>

Fine.  I just don't know what they represent.

> I need to store each of the first elements of a par, so I can reference to 
> them as to a parent of another group.

Don't know what that means either.

>
> So head is parent of neck,  while neck is parent of arms and so on.

They're just strings, not parents of anything.  But the real question is
whether that list I described is what you wanted:


["head", ["neck", ["arms", ["legs"

>
> I'm not sure I understand how to apply your chop list example, dave

Call it with a list, and it returns a different one.  if I guessed your
intent, then the returned list will be correct.  If not, then not.

myGroups = ["head", "neck", "arms", "legs"]
my_directory = chop_up(myGroups)

print my_directory

Maybe what you were really intending was to build a class that you can
create several instances, where an attribute of each instance referred
to any children it might have, and a different attribute supplied the
instance's name.

-- 
DaveA


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


Re: Dealing with Lists

2013-09-10 Thread Roy Smith
In article <[email protected]>,
 stas poritskiy  wrote:

> So head is parent of neck,  while neck is parent of arms and so on.

The head bone's connected to the neck bone.  The neck bone's connected 
to the arm bone...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python TUI that will work on DOS/Windows and Unix/Linux

2013-09-10 Thread Joost Molenaar
Have you looked at Blessings?

I never tried it, but the API seems much cleaner than Curses.

https://pypi.python.org/pypi/blessings/

--
Joost Molenaar
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Language design

2013-09-10 Thread Nobody
On Tue, 10 Sep 2013 17:07:09 +1000, Ben Finney wrote:

> * Python requires every programmer to know, or quickly learn, the basics
>   of Unicode: to know that text is not, and never will be again,
>   synonymous with a sequence of bytes.

If only the Python developers would learn the same lesson ...

Some of them are so hooked on Unicode that they won't accept that
sometimes a sequence of bytes really is just a sequence of bytes. Primary
example: most of the POSIX API.

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


Re: Python TUI that will work on DOS/Windows and Unix/Linux

2013-09-10 Thread Michael Torrie
On 09/04/2013 05:41 AM, James Harris wrote:
> Naturally, all of these are centred on curses. I have been reading up on it 
> and must say that the whole curses approach seems rather antiquated. I 
> appreciate the suggestions and they may be what I need to do but from what I 
> have seen of curses it was designed principally to provide common ways to 
> control cursor-based terminals. That was a-la-mode in the days when we had 
> terminals with different cursor control strings and I remember programming 
> VT100 and VT52 monitors or terminals like them. But now it seems cumbersome.

Well it's the same problem you're trying to solve today.  You've got a
text console with a cursor you can move around and print out text.
Besides with any modern operation system you can't write directly to the
screen anyway, like we used to back in the DOS days when we poked
directly into video memory.

> I haven't thought too much about it so this is not a design proposal but it 
> might be better to divide a display up into non-overlapping windows and 
> treat each one separately. Writes to one would not be able to affect the 
> others. A given window could allow writes to fixed locations or could behave 
> as a glass teletype, writing to the bottom of the window and scrolling as 
> needed, or could behave as a viewing port into a data structure. Something 
> like that may be more useful to a programmer even if it has to use curses 
> underneath because that's all that the OS provides.

A toolkit (that's old, arguably), that might help you is TVision, a port
of the old Turbo Vision library that formed the foundation for Borland's
old DOS IDEs back in the day (check wikipedia).  And it looked quite
beautiful back then, actually.  There is a Python binding for it here:

https://pypi.python.org/pypi/PyTVision

The original C++ is here:
http://tvision.sourceforge.net/

TVision does run on DOS, Windows console, and of course Unix, though
you'd need the appropriate shared library.

Or you could write your own, based on top of something like curses.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Language design

2013-09-10 Thread Steven D'Aprano
On Wed, 11 Sep 2013 01:03:48 +0100, Nobody wrote:

> On Tue, 10 Sep 2013 17:07:09 +1000, Ben Finney wrote:
> 
>> * Python requires every programmer to know, or quickly learn, the
>> basics
>>   of Unicode: to know that text is not, and never will be again,
>>   synonymous with a sequence of bytes.
> 
> If only the Python developers would learn the same lesson ...
> 
> Some of them are so hooked on Unicode that they won't accept that
> sometimes a sequence of bytes really is just a sequence of bytes.
> Primary example: most of the POSIX API.

And lo, Guido's Time Machine strikes again. Python 3 has not one but TWO 
built-in types for handling sequences of bytes:

* bytes  # immutable string of bytes
* bytearray  # mutable array of bytes


and most routines that handle file names accept either text strings or 
bytes strings:


py> open('aß', 'w').write("hello\n")
6
py> open(b'a\xc3\x9f', 'r').read()
'hello\n'



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


Re: Language design

2013-09-10 Thread Chris Rebert
* No explicit variable declarations (modulo `global`+`nonlocal`) means
that variable name typos can't be reliably detected at compile-time.
* The value of the loop variable at call-time for functions defined
within a loop trips people up.
* No self-balancing tree datatype of any kind is included in the std lib.
* Function scope rather than block scope (e.g. `while` doesn't
introduce a new scope) [Personally, I don't have much of a problem
with this, but some people do.]
* No anonymous block syntax (cf. Ruby or Smalltalk). Makes it
harder/uglier to define/use custom control structures. The `with`
statement would have been unnecessary.

Cheers,
Chris


On Mon, Sep 9, 2013 at 11:09 PM, Steven D'Aprano  wrote:
> Some time ago, Tom Christiansen wrote about the "Seven Deadly Sins of
> Perl":
>
> http://www.perl.com/doc/FMTEYEWTK/versus/perl.html
>
>
> What design mistakes, traps or gotchas do you think Python has? Gotchas
> are not necessarily a bad thing, there may be good reasons for it, but
> they're surprising.
>
> To get started, here are a couple of mine:
>
>
> - Python is so dynamic, that there is hardly anything at all that can be
> optimized at compile time.
>
> - The behaviour of mutable default variables is a gotcha.
>
> - Operators that call dunder methods like __add__ don't use the same
> method resolution rules as regular methods, they bypass the instance and
> go straight to the type, at least for new-style classes.
>
>
>
> --
> Steven
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dealing with Lists

2013-09-10 Thread Steven D'Aprano
On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote:

> Greetings to all!
> 
> i ran into a little logic problem and trying to figure it out.
> 
> my case is as follows:
> 
> i have a list of items each item represents a Group
> i need to create a set of nested groups,
> so, for example:
> 
> myGroups = ["head", "neck", "arms", "legs"]


What is the rule for grouping these items? Below, you suggest:

head encloses neck
neck encloses arms
arms encloses legs

which seems rather strange. But if it is *always* the case that each item 
encloses the next item:

def print_nested_list(alist):
spaces = ' '*4
for level, item in enumerate(alist):
if level != 0:
indent = spaces*(level-1) + '  '
print (indent + '|_>'),  # note comma
print item


which gives us this:

py> print_nested_list(['head', 'neck', 'arms', 'legs'])
head
  |_> neck
  |_> arms
  |_> legs


as requested.


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


Re: Dealing with Lists

2013-09-10 Thread Dave Angel
On 10/9/2013 22:14, Steven D'Aprano wrote:

> On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote:
>
>> Greetings to all!
>> 
>> i ran into a little logic problem and trying to figure it out.
>> 
>> my case is as follows:
>> 
>> i have a list of items each item represents a Group
>> i need to create a set of nested groups,
>> so, for example:
>> 
>> myGroups = ["head", "neck", "arms", "legs"]
>
>
> What is the rule for grouping these items? Below, you suggest:
>
> head encloses neck
> neck encloses arms
> arms encloses legs
>
> which seems rather strange. But if it is *always* the case that each item 
> encloses the next item:
>
> def print_nested_list(alist):
> spaces = ' '*4
> for level, item in enumerate(alist):
> if level != 0:
> indent = spaces*(level-1) + '  '
> print (indent + '|_>'),  # note comma
> print item
>
>
> which gives us this:
>
> py> print_nested_list(['head', 'neck', 'arms', 'legs'])
> head
>   |_> neck
>   |_> arms
>   |_> legs
>
>
> as requested.
>
>

Very nice.  But what I want to know is how did you know that Stan (the
OP) wanted his printed output to be formatted that way?  He said:

> i need to create a set of nested groups,
and
> store each of the first elements of a par, so I can reference to them as 
> to a parent of another group.


-- 
DaveA


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


Re: Dealing with Lists

2013-09-10 Thread Steven D'Aprano
On Wed, 11 Sep 2013 02:24:44 +, Dave Angel wrote:

> On 10/9/2013 22:14, Steven D'Aprano wrote:
> 
>> On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote:
>>
>>> Greetings to all!
>>> 
>>> i ran into a little logic problem and trying to figure it out.
>>> 
>>> my case is as follows:
>>> 
>>> i have a list of items each item represents a Group i need to create a
>>> set of nested groups, so, for example:
>>> 
>>> myGroups = ["head", "neck", "arms", "legs"]
>>
>>
>> What is the rule for grouping these items? Below, you suggest:
>>
>> head encloses neck
>> neck encloses arms
>> arms encloses legs
>>
>> which seems rather strange. But if it is *always* the case that each
>> item encloses the next item:
>>
>> def print_nested_list(alist):
>> spaces = ' '*4
>> for level, item in enumerate(alist):
>> if level != 0:
>> indent = spaces*(level-1) + '  '
>> print (indent + '|_>'),  # note comma
>> print item
>>
>>
>> which gives us this:
>>
>> py> print_nested_list(['head', 'neck', 'arms', 'legs']) head
>>   |_> neck
>>   |_> arms
>>   |_> legs
>>
>>
>> as requested.
>>
>>
>>
> Very nice.  But what I want to know is how did you know that Stan (the
> OP) wanted his printed output to be formatted that way?

I don't. Stan's email is unclear. But he does show an example:

[quote]
so, for example:

myGroups = ["head", "neck", "arms", "legs"]

i need to get them to be represented like this: (if you can imaging a
folder structure)

head
  |_> neck
|_> arms
  |_>legs

and so on until i hit the last element.
[end quote]


so I just provided that.

> He said:
> 
>> i need to create a set of nested groups,
> and
>> store each of the first elements of a par, so I can reference to
>> them as to a parent of another group.


I have no idea what that means :-)


I *guess* that what Stan is actually looking for is something like a 
dictionary-based solution, not lists:

{'head': {'neck': {'arms': {}, 'legs': {

which gives:

head encloses neck
neck encloses arms and legs
arms enclose nothing
legs enclose nothing


or:

{'head': {'neck': {'arms': {'legs': {}

which gives:

head encloses neck
neck encloses arms
arms encloses legs
legs enclose nothing


but I can't really tell for sure. In this second case, using dicts, I 
might try something like this recursive solution:


def print_nested_dict(adict, level=0):
if adict == {}:
return
for key, subdict in sorted(adict.items()):
if level != 0:
spaces = ' '*4
indent = spaces*(level-1) + '  '
print (indent + '|_>'),  # note comma
if subdict == {}:
print key
else:
print "%s:-" % key
print_nested_dict(subdict, level+1)


Given:

d = {'head': {'neck': {'legs': {'toes': {}}, 'arms': {'thumbs': {}, 
'fingers': {}

we can see this output:

py> print_nested_dict(d)
head:-
  |_> neck:-
  |_> arms:-
  |_> fingers
  |_> thumbs
  |_> legs:-
  |_> toes




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


Re: Dealing with Lists

2013-09-10 Thread stas poritskiy
Guys,
i appreciate the effort put in here, i guess i should've started a little wider 
on description.

sorry for confusion, here it goes:

I am developing a script/application that uses adobe Scene7 API. the idea here 
is mass process a ton of files (hundreds of thousands), we generate image files 
from 3d applications (3d max in our case), and each rendered file carries a 
specific naming convention such as this:
name_group-subgroup-subgroup_layer_type_zdepth.extention.

this translates in a nice array, that i first split using uderscore " _ ".
this results in a list that has always the same size.

Please note that in the section with group-subgroup-subroug - number of 
subgroups should can be ANY, and the separator there is dash " - ",

so when the first split " _ " occurs, i generate a separate element in my FIRST 
LIST that has all these groups. 

I then take the groups and run another split using the dash " - ", to create a 
new list for only groups.

In the second list, what i have is the first element at index 0 - being alwasy 
the most top (root) group. and all the subgroups are nested inside there. Each 
subgroup is a parent of the following subroup, thus - above in my diagram i 
used the body parts as example of logical dependency (sorry if this was 
unclear, again),

now, the next step is using API and its classes i create an instance of an 
object that generates the group for the file that will created via series of 
additional methods,

the file structure (think of Photoshop as an reference)
would have the main group, and a subgroup in it, and so on, depending on the 
type of the element that we are creating identified in the file name. (this 
would be using the FIRST LIST created originally)

For me to create a subgroup using the API, the first (parent) group should be 
already created, otherwise, i cannot use a non-existing element to assign a 
subgroup, 
therefore , i first my create the ROOT group located at index0
i then must make a subgroup, so the line of code would look similar to this:

#creating first group(root)
group = intance.add_group(str(name))

#creating subgroup(child of root)
subgroup = group.add_group(str(name))

since i don't know how many subgroups each file would have, i want to create a 
loop, that will do that for me
but i am running in a problem, trying to understand the logic for that loop.

let me know if you guys need more info from me.

On Tuesday, September 10, 2013 10:13:48 PM UTC-5, Steven D'Aprano wrote:
> On Wed, 11 Sep 2013 02:24:44 +, Dave Angel wrote:
> 
> 
> 
> > On 10/9/2013 22:14, Steven D'Aprano wrote:
> 
> > 
> 
> >> On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote:
> 
> >>
> 
> >>> Greetings to all!
> 
> >>> 
> 
> >>> i ran into a little logic problem and trying to figure it out.
> 
> >>> 
> 
> >>> my case is as follows:
> 
> >>> 
> 
> >>> i have a list of items each item represents a Group i need to create a
> 
> >>> set of nested groups, so, for example:
> 
> >>> 
> 
> >>> myGroups = ["head", "neck", "arms", "legs"]
> 
> >>
> 
> >>
> 
> >> What is the rule for grouping these items? Below, you suggest:
> 
> >>
> 
> >> head encloses neck
> 
> >> neck encloses arms
> 
> >> arms encloses legs
> 
> >>
> 
> >> which seems rather strange. But if it is *always* the case that each
> 
> >> item encloses the next item:
> 
> >>
> 
> >> def print_nested_list(alist):
> 
> >> spaces = ' '*4
> 
> >> for level, item in enumerate(alist):
> 
> >> if level != 0:
> 
> >> indent = spaces*(level-1) + '  '
> 
> >> print (indent + '|_>'),  # note comma
> 
> >> print item
> 
> >>
> 
> >>
> 
> >> which gives us this:
> 
> >>
> 
> >> py> print_nested_list(['head', 'neck', 'arms', 'legs']) head
> 
> >>   |_> neck
> 
> >>   |_> arms
> 
> >>   |_> legs
> 
> >>
> 
> >>
> 
> >> as requested.
> 
> >>
> 
> >>
> 
> >>
> 
> > Very nice.  But what I want to know is how did you know that Stan (the
> 
> > OP) wanted his printed output to be formatted that way?
> 
> 
> 
> I don't. Stan's email is unclear. But he does show an example:
> 
> 
> 
> [quote]
> 
> so, for example:
> 
> 
> 
> myGroups = ["head", "neck", "arms", "legs"]
> 
> 
> 
> i need to get them to be represented like this: (if you can imaging a
> 
> folder structure)
> 
> 
> 
> head
> 
>   |_> neck
> 
> |_> arms
> 
>   |_>legs
> 
> 
> 
> and so on until i hit the last element.
> 
> [end quote]
> 
> 
> 
> 
> 
> so I just provided that.
> 
> 
> 
> > He said:
> 
> > 
> 
> >> i need to create a set of nested groups,
> 
> > and
> 
> >> store each of the first elements of a par, so I can reference to
> 
> >> them as to a parent of another group.
> 
> 
> 
> 
> 
> I have no idea what that means :-)
> 
> 
> 
> 
> 
> I *guess* that what Stan is actually looking for is something like a 
> 
> dictionary-based solution, not lists:
> 
> 
> 
> {'head': {'neck': {'arms': {}, 'legs': {
> 
> 
> 
> which gives:
> 
> 
> 
> head encloses ne

Re: Dealing with Lists

2013-09-10 Thread stas poritskiy
Steven,
i think you got on the right track with your proposal,
although i am not going after the "visual" represenatation that you were able 
to create, rather a structural one, i think this might work for me,
instead of printing, i could be using my commands to make elements (instances 
of API objects to create my groups inside the file)

but one question i might have is :

once i created first instance object which in my example is :
groups = intance.add_group(str(name))

how would i temporary preserve this name as a reference for the next iteration 
for the subroups?

On Tuesday, September 10, 2013 10:13:48 PM UTC-5, Steven D'Aprano wrote:
> On Wed, 11 Sep 2013 02:24:44 +, Dave Angel wrote:
> 
> 
> 
> > On 10/9/2013 22:14, Steven D'Aprano wrote:
> 
> > 
> 
> >> On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote:
> 
> >>
> 
> >>> Greetings to all!
> 
> >>> 
> 
> >>> i ran into a little logic problem and trying to figure it out.
> 
> >>> 
> 
> >>> my case is as follows:
> 
> >>> 
> 
> >>> i have a list of items each item represents a Group i need to create a
> 
> >>> set of nested groups, so, for example:
> 
> >>> 
> 
> >>> myGroups = ["head", "neck", "arms", "legs"]
> 
> >>
> 
> >>
> 
> >> What is the rule for grouping these items? Below, you suggest:
> 
> >>
> 
> >> head encloses neck
> 
> >> neck encloses arms
> 
> >> arms encloses legs
> 
> >>
> 
> >> which seems rather strange. But if it is *always* the case that each
> 
> >> item encloses the next item:
> 
> >>
> 
> >> def print_nested_list(alist):
> 
> >> spaces = ' '*4
> 
> >> for level, item in enumerate(alist):
> 
> >> if level != 0:
> 
> >> indent = spaces*(level-1) + '  '
> 
> >> print (indent + '|_>'),  # note comma
> 
> >> print item
> 
> >>
> 
> >>
> 
> >> which gives us this:
> 
> >>
> 
> >> py> print_nested_list(['head', 'neck', 'arms', 'legs']) head
> 
> >>   |_> neck
> 
> >>   |_> arms
> 
> >>   |_> legs
> 
> >>
> 
> >>
> 
> >> as requested.
> 
> >>
> 
> >>
> 
> >>
> 
> > Very nice.  But what I want to know is how did you know that Stan (the
> 
> > OP) wanted his printed output to be formatted that way?
> 
> 
> 
> I don't. Stan's email is unclear. But he does show an example:
> 
> 
> 
> [quote]
> 
> so, for example:
> 
> 
> 
> myGroups = ["head", "neck", "arms", "legs"]
> 
> 
> 
> i need to get them to be represented like this: (if you can imaging a
> 
> folder structure)
> 
> 
> 
> head
> 
>   |_> neck
> 
> |_> arms
> 
>   |_>legs
> 
> 
> 
> and so on until i hit the last element.
> 
> [end quote]
> 
> 
> 
> 
> 
> so I just provided that.
> 
> 
> 
> > He said:
> 
> > 
> 
> >> i need to create a set of nested groups,
> 
> > and
> 
> >> store each of the first elements of a par, so I can reference to
> 
> >> them as to a parent of another group.
> 
> 
> 
> 
> 
> I have no idea what that means :-)
> 
> 
> 
> 
> 
> I *guess* that what Stan is actually looking for is something like a 
> 
> dictionary-based solution, not lists:
> 
> 
> 
> {'head': {'neck': {'arms': {}, 'legs': {
> 
> 
> 
> which gives:
> 
> 
> 
> head encloses neck
> 
> neck encloses arms and legs
> 
> arms enclose nothing
> 
> legs enclose nothing
> 
> 
> 
> 
> 
> or:
> 
> 
> 
> {'head': {'neck': {'arms': {'legs': {}
> 
> 
> 
> which gives:
> 
> 
> 
> head encloses neck
> 
> neck encloses arms
> 
> arms encloses legs
> 
> legs enclose nothing
> 
> 
> 
> 
> 
> but I can't really tell for sure. In this second case, using dicts, I 
> 
> might try something like this recursive solution:
> 
> 
> 
> 
> 
> def print_nested_dict(adict, level=0):
> 
> if adict == {}:
> 
> return
> 
> for key, subdict in sorted(adict.items()):
> 
> if level != 0:
> 
> spaces = ' '*4
> 
> indent = spaces*(level-1) + '  '
> 
> print (indent + '|_>'),  # note comma
> 
> if subdict == {}:
> 
> print key
> 
> else:
> 
> print "%s:-" % key
> 
> print_nested_dict(subdict, level+1)
> 
> 
> 
> 
> 
> Given:
> 
> 
> 
> d = {'head': {'neck': {'legs': {'toes': {}}, 'arms': {'thumbs': {}, 
> 
> 'fingers': {}
> 
> 
> 
> we can see this output:
> 
> 
> 
> py> print_nested_dict(d)
> 
> head:-
> 
>   |_> neck:-
> 
>   |_> arms:-
> 
>   |_> fingers
> 
>   |_> thumbs
> 
>   |_> legs:-
> 
>   |_> toes
> 
> 
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Language design

2013-09-10 Thread Chris Angelico
On Wed, Sep 11, 2013 at 11:46 AM, Chris Rebert  wrote:
> * The value of the loop variable at call-time for functions defined
> within a loop trips people up.

Related: The confusion of 'with' vs __del__ vs del wrt open files etc.
Using 'with' does not guarantee the object's destruction, but the
destruction of the object and the exiting of the with block do have
the same effect, which is confusing. Personally, I'd prefer a
guarantee that this name expires at this point, plus a guarantee that
- if there are no other references - the object will be cleaned up
immediately; it's generally true in CPython, and if that could
actually be made a language feature, there'd be no need for 'with' and
no issues with confusing people.

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


Help please, why doesn't it show the next input?

2013-09-10 Thread William Bryant
Hey, I am very new to python, I am 13 years old. I want to be able to make a 
program the caculates the mean, meadian and mode. When i run the program, an 
input field pops up and says 'Does your list contain, a number or a string?' 
like I want it to, but when I type in something that is not one of valid field 
options: "String" or "string" or "STRING" or "s" or "S" or "str" or "Number" or 
"number" or "NUMBER" or "N" or "N" or "int" or "num", nothing happens, please 
tell me what I did wrong. Thanks :D Here is my code:

#-   Variables that I am using, including the list.  -#

#False means num
#True means string
num_or_string = ""
amount_numbers = []
List = []
I = "Does your list contain, a number or a string?"

#-  Functions that I am using.-#
input(I)

def NOS():
if I == "String" or "string" or "STRING" or "s" or "S" or "str":
pass
elif I == "Number" or "number" or "NUMBER" or "N" or "N" or "int" or "num":
pass
else:
global I
I = "You did not enter a valid field, :P Sorry."
input(I)


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


Re: Help please, why doesn't it show the next input?

2013-09-10 Thread John Gordon
In  William Bryant 
 writes:

> Hey, I am very new to python, I am 13 years old. I want to be able to make =
> a program the caculates the mean, meadian and mode. When i run the program,=
>  an input field pops up and says 'Does your list contain, a number or a str=
> ing?' like I want it to, but when I type in something that is not one of va=
> lid field options: "String" or "string" or "STRING" or "s" or "S" or "str" =
> or "Number" or "number" or "NUMBER" or "N" or "N" or "int" or "num", nothin=
> g happens, please tell me what I did wrong. Thanks :D Here is my code:

> #-   Variables that I am using, including the list.  --=
> ---#

> #False means num
> #True means string
> num_or_string =3D ""
> amount_numbers =3D []
> List =3D []
> I =3D "Does your list contain, a number or a string?"

> #-  Functions that I am using.-=
> #
> input(I)

> def NOS():
> if I =3D=3D "String" or "string" or "STRING" or "s" or "S" or "str":
> pass
> elif I =3D=3D "Number" or "number" or "NUMBER" or "N" or "N" or "int" o=
> r "num":
> pass
> else:
> global I
> I =3D "You did not enter a valid field, :P Sorry."
> input(I)

First of all, you haven't given us your whole program.  I know this because
while you've defined the NOS function, it isn't actually called anywhere.
You must have left that part out.

Anyway, I think you're doing two things wrong:

1. You aren't capturing the user's input.  The input() function returns
the user's input, but you aren't assigning this to a variable; it's just
being thrown away.  You should call input() like this:

  user_input = input(I)

(Also, it would probably be clearer to use a name like "prompt" instead
of "I".)

2. You aren't using the compound "if" statement correctly.  You can't
   do this (well, you CAN, but it won't do what you want):

   if a == 1 or 2 or 3:

   You should fully spell out each condition, like this:

   if a == 1 or a == 2 or a == 3:

-- 
John Gordon   A is for Amy, who fell down the stairs
[email protected]  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: Help please, why doesn't it show the next input?

2013-09-10 Thread William Bryant
On Wednesday, September 11, 2013 5:11:23 PM UTC+12, John Gordon wrote:
> In  William Bryant 
>  writes:
> 
> 
> 
> > Hey, I am very new to python, I am 13 years old. I want to be able to make =
> 
> > a program the caculates the mean, meadian and mode. When i run the program,=
> 
> >  an input field pops up and says 'Does your list contain, a number or a str=
> 
> > ing?' like I want it to, but when I type in something that is not one of va=
> 
> > lid field options: "String" or "string" or "STRING" or "s" or "S" or "str" =
> 
> > or "Number" or "number" or "NUMBER" or "N" or "N" or "int" or "num", nothin=
> 
> > g happens, please tell me what I did wrong. Thanks :D Here is my code:
> 
> 
> 
> > #-   Variables that I am using, including the list.  --=
> 
> > ---#
> 
> 
> 
> > #False means num
> 
> > #True means string
> 
> > num_or_string =3D ""
> 
> > amount_numbers =3D []
> 
> > List =3D []
> 
> > I =3D "Does your list contain, a number or a string?"
> 
> 
> 
> > #-  Functions that I am using.-=
> 
> > #
> 
> > input(I)
> 
> 
> 
> > def NOS():
> 
> > if I =3D=3D "String" or "string" or "STRING" or "s" or "S" or "str":
> 
> > pass
> 
> > elif I =3D=3D "Number" or "number" or "NUMBER" or "N" or "N" or "int" o=
> 
> > r "num":
> 
> > pass
> 
> > else:
> 
> > global I
> 
> > I =3D "You did not enter a valid field, :P Sorry."
> 
> > input(I)
> 
> 
> 
> First of all, you haven't given us your whole program.  I know this because
> 
> while you've defined the NOS function, it isn't actually called anywhere.
> 
> You must have left that part out.
> 
> 
> 
> Anyway, I think you're doing two things wrong:
> 
> 
> 
> 1. You aren't capturing the user's input.  The input() function returns
> 
> the user's input, but you aren't assigning this to a variable; it's just
> 
> being thrown away.  You should call input() like this:
> 
> 
> 
>   user_input = input(I)
> 
> 
> 
> (Also, it would probably be clearer to use a name like "prompt" instead
> 
> of "I".)
> 
> 
> 
> 2. You aren't using the compound "if" statement correctly.  You can't
> 
>do this (well, you CAN, but it won't do what you want):
> 
> 
> 
>if a == 1 or 2 or 3:
> 
> 
> 
>You should fully spell out each condition, like this:
> 
> 
> 
>if a == 1 or a == 2 or a == 3:
> 
> 
> 
> -- 
> 
> John Gordon   A is for Amy, who fell down the stairs
> 
> [email protected]  B is for Basil, assaulted by bears
> 
> -- Edward Gorey, "The Gashlycrumb Tinies"

Thanks so much for putting your time into helping me!! It worked! Could you 
tell me if I did anything wrong this time? :)

#-   Variables that I am using, including the list.  -#

num_or_string = ""
amount_numbers = []
List = []
prompt = "Does your list contain, a number or a string?"

#-  Functions that I am using.-#
user_input1 = input(prompt)
user_input1

def NOS():
if user_input1 == "String" or user_input1 == "string" or user_input1 == 
"STRING" or user_input1 == "s" or user_input1 == "S" or user_input1 == "str":
print("a")
elif user_input1 == "Number" or user_input1 == "number" or user_input1 == 
"NUMBER" or user_input1 == "N" or user_input1 == "N" or user_input1 == "int" or 
user_input1 == "num":
print("a")
else:
global user_input2
global prompt
prompt = "You did not enter a valid field, :P Sorry."
user_input2 = input(prompt)
user_input2
NOS2()

def NOS2():
if user_input2 == "String" or user_input2 == "string" or user_input2 == 
"STRING" or user_input2 == "s" or user_input2 == "S" or user_input2 == "str":
print("a")
elif user_input2 == "Number" or user_input2 == "number" or user_input2 == 
"NUMBER" or user_input2 == "N" or user_input2 == "N" or user_input2 == "int" or 
user_input2 == "num":
print("a")
else:
global user_input2
global prompt
prompt = "You did not enter a valid field, :P Sorry."
user_input2 = input(prompt)
user_input2
NOS2()


NOS()
-- 
https://mail.python.org/mailman/listinfo/python-list