Re: Descriptors vs Property

2016-03-13 Thread Thomas 'PointedEars' Lahn
Veek. M wrote:

> Thomas 'PointedEars' Lahn wrote:
>>> I haven't read the descriptor protocol as yet.
>> You should.  You should also trim your quotations to the relevant
>> minimum, and post using your real name.
> 
> I don't take advice from people on USENET who DON'T have a long history
> of helping ME -

Although I had no obligation to (this is not a support forum), I have helped 
you; you just have not realized that yet.  (My posting consisted of more 
than you quoted from it.)

> unless I'm blatantly wrong

You are.

> […] but thanks anyhow I shall endeavor to oblige.

  Nobility lies in action, not in name.
—Surak

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Steven D'Aprano
On Sun, 13 Mar 2016 04:54 am, BartC wrote:

> On 12/03/2016 16:56, Steven D'Aprano wrote:
>> On Sun, 13 Mar 2016 12:42 am, BartC wrote:
>>
>>> Ad-hoc attributes I don't have as much of a problem with, as they can be
>>> handy. But predefined ones also have their points. (For one thing, I
>>> know how to implement those efficiently.)
>>>
>>> However, when you have a function call like this: M.F(), where M is an
>>> imported module, then it is very unlikely that the functions in M are
>>> going to be created, modified, deleted or replaced while the program
>>> runs. [I mean, after the usual process of executing each 'def'
>>> statement.]
>>
>> What do you consider "very unlikely"? And how do you know what people
>> will choose to do?
> 
> Common sense tells you it is unlikely.

Perhaps your common sense is different from other people's common sense. To
me, and many other Python programmers, it's common sense that being able to
replace functions or methods on the fly is a useful feature worth having.
More on this below.

Perhaps this is an example of the "Blub Paradox":

http://www.paulgraham.com/avg.html

Wherever we sit in the continuum of language power, we look *down* at
languages with less power as "crippled" because they miss features we use
all the time, and *up* at languages with more power as adding a lot of
hairy and weird features that nobody would ever need.


>>> Why then should it have to suffer the same overheads as looking up
>>> arbitrary attributes? And on every single call?
>>
>> Because they *are* arbitrary attributes of the module. There's only one
>> sort of attribute in Python. Python doesn't invent multiple lookup rules
>> for attributes-that-are-functions, attributes-that-are-classes,
>> attributes-that-are-ints, attributes-that-are-strings, and so on. They
>> are all the same.
>>
>> You gain a simpler implementation,
> 
> (Have you tried looking at the CPython sources? I tried last year and
> couldn't head or tail of them. What was the layout of the pyObject
> struct? I couldn't figure it out, the source being such a mess of
> conditional code and macros within macros.

Right. Now add *on top of that complexity* the extra complexity needed to
manage not one, but *two* namespaces for every scope: one for "variables"
and one for "functions and methods".

I'm not defending the CPython source. I can't even judge the CPython source.
My ability to read C code is a bit better than "See Spot run. Run, Spot,
Run!" but not that much better. But CPython is a 20+ year language, and the
implementation has no doubt built up some cruft over the years, especially
since many of the implementation details are part of the public C
interface.


[...]
>> In languages where functions are different from other values, you have to
>> recognise ahead of time "some day, I may need to dynamically replace this
>> function with another" and write your code specially to take that into
>> account, probably using some sort of "Design Pattern".
> 
> No it's very easy. In Python terms:
> 
> def f(): return "One"
> def g(): return "Two"
> 
> h=f
> 
> h() returns "One". Later you do h=g, and h() returns "Two". No need for
> f and g themselves to be dynamic. h just needs to be a variable.

You're still not getting the big picture. I didn't say that it was
necessarily difficult create such a "dynamic function". I said that you had
to realise *ahead of time* that you needed to do so.

Let me see if I can draw you a more complete picture. Suppose I have a
function that relies on (let's say) something random or unpredictable:


def get_data():
return time.strftime("%S:%H")

Obviously this is a toy function, consider it as a stand-in for something
more substantial. I don't know, maybe it connects to a database, or gathers
data from a distant web site, or interacts with the user.

Now I use `get_data` in another function:

def spam():
value = get_stuff().replace(":", "")
num = int(value)
return "Spam to the %d" % num


How do I test the `spam` function? I cannot easily predict what the
`get_data` function will return.

In Python, I can easily monkey-patch this for the purposes of testing, or
debugging, by introducing a test double (think of "stunt double") to
replace the real `get_data` function:


import mymodule
mymodule.get_data = lambda: "1:1"
assert spam() == "Spam to the 11"


This "test double" is sometimes called a stub, or a mock, or a fake.
Whatever you call it, it is *trivially* easy in Python.

How would you do it, when functions are constant? You would have to re-write
the module to allow it:


def real_get_data():
return time.strftime("%S:%H")

replaceable_get_data = real_get_data

def spam():
value = replaceable_get_data().replace(":", "")
num = int(value)
return "spam"*num


Now you have two classes of functions: those that can be replaced by test
doubles and those that can't. Those that can be replaced exist in two
almost identical versions: the real, crippled, function, and the

Re: Descriptors vs Property

2016-03-13 Thread Veek. M
Thomas 'PointedEars' Lahn wrote:

> Veek. M wrote:
> 
>> Thomas 'PointedEars' Lahn wrote:
 I haven't read the descriptor protocol as yet.
>>> You should.  You should also trim your quotations to the relevant
>>> minimum, and post using your real name.
>> 
>> I don't take advice from people on USENET who DON'T have a long
>> history of helping ME -
> 
> Although I had no obligation to (this is not a support forum), I have
> helped
> you; you just have not realized that yet.  (My posting consisted of
> more than you quoted from it.)
I understand - please kill-file-me/ignore-me if possible:

http://arstechnica.com/science/2014/02/science-confirms-online-trolls-are-horrible-people-also-sadists/

>> unless I'm blatantly wrong
> 
> You are.
> 
okay :)


http://www.thecodingforums.com/threads/examples-of-ecmascipt-written-by-thomas-lahn.937812/

Examples of ECMAScipt written by Thomas Lahn

Thomas is the forums best known critic of everyone else's attempts at
writing ECMAscript. I was wondering if there is a webspace where we
could look and wonder at Thomas's scripting skills. 

Steve, Dec 5, 2008 
---
(i'm not wondering - we don't get along - matter of taste - kill-file 
plz)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Encapsulation in Python

2016-03-13 Thread Steven D'Aprano
On Sun, 13 Mar 2016 03:44 am, Ian Kelly wrote:

> On Fri, Mar 11, 2016 at 7:39 PM, Rick Johnson
>  wrote:
>> At run-time, i don't care how large a "module namespace" may
>> be. Sometimes a module namespace will be small, with only a
>> few exposed symbols, but sometimes, a module namespace will
>> expose thousands of symbols.
> 
> Thousands, really? What system do you use to ensure that symbols don't
> accidentally collide with one another? Because, you know, Python won't
> check this for you even within a single file, unlike say C++ which
> does allow splitting namespaces across multiple files. A linter might,
> but not at runtime, and I don't expect it will be smart enough to
> notice if the definitions are in different files.


I would hate to use an API with "thousands" of symbols in a single
namespace. I find `os` difficult enough, and it has less than a quarter
thousand:

py> len(dir(os))
224


The decimal module is, in my opinion, about as big as a module should ever
get before it becomes too unwieldy to maintain, and it has less than a
hundred symbols:

py> len(dir(decimal))
79


While it is true that the Zen says "Flat is better than nested", it does
also say

Namespaces are one honking great idea -- let's do more of those!


so at the point that your namespace has more symbols than can be managed by
the merely mortal, then it's well past time to split some of them off into
separate namespaces.


[...]
>> But option two is no better, because once we cut and paste
>> portions of the code into satellite files, we lose the
>> ability to "easily share state". Then we're forced to start
>> "hacking at the weeds" with import contortions and monkey
>> patches, all the while, fearing the dreaded circular import.
>>
>>
>> NO, THIS IS INSANITY!  WHAT WE NEED IS AN OPTION 3!

What we actually need is a way to have less shared state. If you have so
much shared state that you cannot manage it in a single module, you have a
problem no matter what you do.



-- 
Steven

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


Re: Descriptors vs Property

2016-03-13 Thread Thomas 'PointedEars' Lahn
Veek. M wrote:

> 
> http://www.thecodingforums.com/threads/examples-of-ecmascipt-written-by-thomas-lahn.937812/
> 
> Examples of ECMAScipt written by Thomas Lahn
> 
> Thomas is the forums best known critic of everyone else's attempts at
> writing ECMAscript. I was wondering if there is a webspace where we
> could look and wonder at Thomas's scripting skills.
> 
> Steve, Dec 5, 2008
> ---

Obviously you have no reasonable arguments, and not a shred of decency in 
you left, so you think that all is left to you to save what you think is 
your honor is to commit libel, thereby actively sacrificing what little 
honor you had left.

> (i'm not wondering - we don't get along - matter of taste -

It is not a matter of taste.  Your behavior is *objectively* despicable.

> kill-file plz)

I am not making it easy for you to be hypocritical and impudent:

>>> […] but thanks anyhow I shall endeavor to oblige.
  ^^ 
>>   Nobility lies in action, not in name.
>> —Surak

q.e.d.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Error

2016-03-13 Thread Abeer Sohail
I get this error every time I open Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


programeren met python

2016-03-13 Thread Imre De Craemer via Python-list
 hoe moet je python dounlauden
-- 
https://mail.python.org/mailman/listinfo/python-list


Export

2016-03-13 Thread Herbert Müller
Hello,
how can I export my .py files to .exe files?
Thanks for your support 
Your Robert
-- 
https://mail.python.org/mailman/listinfo/python-list


Word Order Simple.

2016-03-13 Thread Rodrick Brown
You are given nn words. Some words may repeat. For each word, output its
number of occurrences. The output order should correspond with the input
order of appearance of the word. See the sample input/output for
clarification.

*Note:* Each input line ends with a *"\n"* character.

*Constraints:*
1≤n≤1051≤n≤105
The sum of the lengths of all the words do not exceed 106106
All the words are composed of lowercase English letters only.

*Input Format*

The first line contains the integer, nn.
The next nn lines each contain a word.

*Output Format*

Output 22 lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word
according to their appearance in the input.

*Sample Input*

4
bcdef
abcdefg
bcde
bcdef

*Sample Output*

3
2 1 1

*Explanation*

There are 3 distinct words. Here, *"bcdef"* appears twice in the input at
the first and last positions. The other words appear once each. The order
of the first appearances are *"bcdef"*,*"abcdefg"* and *"bcde"* which
corresponds to the output.

Here is my attempt I can't seem to past all test cases and not sure why?
The explanation for line how to get 1 1 seems weird maybe I'm not reading
it correctly.

#!/usr/bin/env python3

from collections import defaultdict
from collections import Counter

if __name__ == '__main__':

  words = defaultdict(list)
  for i,word in enumerate(input() for x in range(int(input(:
words[word].append([i+1])

  count = Counter()
  print(len(words.keys()))

  for k in words:
if len(words[k]) > 1:
  print(len(words[k]),end=' ')
else:
  count[k] += 1

  for c in count.values(): print(c,end=' ')

$  cat words.txt | ./wordcount.py

3
2 1 1 ⏎
-- 
https://mail.python.org/mailman/listinfo/python-list


problem using pickle

2016-03-13 Thread Nicky Mac
Dear Python team,
I have studied the excellent documentation, and attempted to make use of
pickle thus:

filename = 'my_saved_adventure'
import  pickle
class object:
def __init__(self,i,.t) :
self.id   = i
 .

class world:
def __init__(self):
self.object

class object:
def __init__(self,i,

.then   Object instances of object are created 

myworld = world;
myworld.Object = Object
fileobj = open(filename,'wb')
pickle.dump(myworld,fileobj); fileobj.close()
result = "saved your game to " + filename

fileobj = open(filename,'rb')
myworld = pickle.load(fileobj); fileobj.close()
Object = myworld.Object
result = "restored your game from " + filename


The proecedures execute without error
but a file of only 21b is created containing " €c__main__world q .
altho there are several k of object instance data.

-- 
Nick "Mac" McElwaine
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Export

2016-03-13 Thread Jesper K Brogaard

Den 13-03-2016 kl. 00:07 skrev Herbert Müller:

Hello,
how can I export my .py files to .exe files?
Thanks for your support
Your Robert



Look at pyinstaller or py2exe. I have no experience with either of them.

--
Venlig hilsen / Best regards
Jesper K. Brogaard

(remove upper case letters in my e-mail address)
--
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Gene Heskett
On Sunday 13 March 2016 01:43:21 Terry Reedy wrote:

> On 3/12/2016 8:20 PM, Steven D'Aprano wrote:
> > Yeah, we get it. The CPython interpreter is plenty fast enough for
> > whatever you use it for. Good for you! Millions aren't so lucky.
> > They are looking for something faster, because for them, you can
> > never have too much speed. When you are trying to solve a 7000x7000
> > system of equations, you don't want to wait three days for a
> > solution. Or three hours with Numpy.
>
> There is a positive form of Parkinson's Law at work.  People patience
> is about the same as ever.  So as computation gets faster, people
> attempt larger problems.  I remember when the idea of solving such a
> problem was ludicrous.
>
> --
> Terry Jan Reedy

So would solving pi to 500 digits on a 64k color computer, but I've done 
it. AIR it took the coco around 4.5 hours to fire up the printer and 
print the result.  Using an exersize assembly code that Bill Barden 
wrote.  All integer math, it looked correct but was missing the decimal 
point after the 3.

One of the things you do just to prove it can be done. :)

Cheers, Gene Heskett
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
Genes Web page 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Word Order Simple.

2016-03-13 Thread Peter Otten
Rodrick Brown wrote:

> You are given nn words. Some words may repeat. For each word, output its
> number of occurrences. The output order should correspond with the input
> order of appearance of the word. See the sample input/output for
> clarification.
> 
> *Note:* Each input line ends with a *"\n"* character.
> 
> *Constraints:*
> 1≤n≤1051≤n≤105
> The sum of the lengths of all the words do not exceed 106106
> All the words are composed of lowercase English letters only.
> 
> *Input Format*
> 
> The first line contains the integer, nn.
> The next nn lines each contain a word.
> 
> *Output Format*
> 
> Output 22 lines.
> On the first line, output the number of distinct words from the input.
> On the second line, output the number of occurrences for each distinct
> word according to their appearance in the input.
> 
> *Sample Input*
> 
> 4
> bcdef
> abcdefg
> bcde
> bcdef
> 
> *Sample Output*
> 
> 3
> 2 1 1
> 
> *Explanation*
> 
> There are 3 distinct words. Here, *"bcdef"* appears twice in the input at
> the first and last positions. The other words appear once each. The order
> of the first appearances are *"bcdef"*,*"abcdefg"* and *"bcde"* which
> corresponds to the output.
> 
> Here is my attempt I can't seem to past all test cases and not sure why?

Keys in a dictionary are not stored in the order that they are entered. The 
order may even change between different runs of the same script with the 
same input (this was done to make a class of denial of service attacks on 
web applications harder). For example:

 $ cat wordcount.py # your script with an extra print() at the end
#!/usr/bin/env python3

from collections import defaultdict
from collections import Counter

if __name__ == '__main__':

  words = defaultdict(list)
  for i,word in enumerate(input() for x in range(int(input(:
words[word].append([i+1])

  count = Counter()
  print(len(words.keys()))

  for k in words:
if len(words[k]) > 1:
  print(len(words[k]),end=' ')
else:
  count[k] += 1

  for c in count.values(): print(c,end=' ')
  print()
$ cat words.txt
6
foo
bar
bar
baz
baz
baz
$ python3 wordcount.py < words.txt
3
3 2 1 
$ python3 wordcount.py < words.txt
3
3 2 1 
$ python3 wordcount.py < words.txt
3
2 3 1 

To fix this you can use a collections.OrderedDict, but I recommend that you 
try to write a script that uses one standard dict to map words to number of 
occurences and one list to keep track of the word when it first occurs.
Note that you do not need to keep track of all occurences of a word; in your 
script below you store more information than necessary.

With the example input above the list should contain

['foo', 'bar', 'baz']

and the dict should contain

{'foo': 1, 'bar': 2, 'baz': 3} # remember that the keys are not necessarily
   # in that order

For debugging purposes you can print the dict and the list, and once your 
script fills them correctly print the second line required by the task by 
iterating over the list and looking up the frequencies in the dict.

> The explanation for line how to get 1 1 seems weird maybe I'm not reading
> it correctly.
> 
> #!/usr/bin/env python3
> 
> from collections import defaultdict
> from collections import Counter
> 
> if __name__ == '__main__':
> 
>   words = defaultdict(list)
>   for i,word in enumerate(input() for x in range(int(input(:
> words[word].append([i+1])
> 
>   count = Counter()
>   print(len(words.keys()))
> 
>   for k in words:
> if len(words[k]) > 1:
>   print(len(words[k]),end=' ')
> else:
>   count[k] += 1
> 
>   for c in count.values(): print(c,end=' ')
> 
> $  cat words.txt | ./wordcount.py
> 
> 3
> 2 1 1 ⏎


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread BartC

On 13/03/2016 09:39, Steven D'Aprano wrote:

On Sun, 13 Mar 2016 04:54 am, BartC wrote:



Common sense tells you it is unlikely.


Perhaps your common sense is different from other people's common sense. To
me, and many other Python programmers, it's common sense that being able to
replace functions or methods on the fly is a useful feature worth having.


Worth having but at significant cost. But look at my jpeg test (look at 
any other similar programs); how many function names are used 
dynamically? How many functions *really* need to be dynamic?



(Have you tried looking at the CPython sources?



Right. Now add *on top of that complexity* the extra complexity needed to
manage not one, but *two* namespaces for every scope: one for "variables"
and one for "functions and methods".


No, there's one namespace per scope. (Otherwise you could have a 
function 'f' and a variable 'f' in each scope.)


Perhaps what you mean is the number of different kinds of identifiers 
there can be. At the minute, apart from obvious, fixed, reserved words 
(I assume there are some!), there seems to be just one kind. The 
different categories (function, variable, class, built-in, module etc) 
are sorted out at *run-time*.


Some of this will just move to *compile-time*. Same amount of 
complexity, but now you do it just once at compile-time, instead of a 
billion times at run-time.



def f(): return "One"
def g(): return "Two"

h=f



Let me see if I can draw you a more complete picture. Suppose I have a
function that relies on (let's say) something random or unpredictable:

def get_data():
 return time.strftime("%S:%H")



Now I use `get_data` in another function:

def spam():
 value = get_stuff().replace(":", "")


(I assume you mean get_data here.)


How do I test the `spam` function? I cannot easily predict what the
`get_data` function will return.

In Python, I can easily monkey-patch this for the purposes of testing, or
debugging, by introducing a test double (think of "stunt double") to
replace the real `get_data` function:

import mymodule
mymodule.get_data = lambda: "1:1"
assert spam() == "Spam to the 11"


(How do you get back the original get_data?) But this looks a very 
dangerous technique. Suppose, during the test, that another function in 
mymodule, or one that imports it, needs access to the original get_data 
function to work properly? Now it will get back nonsense.



How would you do it, when functions are constant? You would have to re-write
the module to allow it:


There are a dozen ways of doing it. It may involve temporary renaming or 
hiding. But what you don't want is for production code to be lumbered 
with all these lookups (and having to sort out arguments, keywords and 
defaults) at runtime, just to make it a bit easier for debug code to run.


I think anyway that any Python program using dynamic functions, can be 
trivially transformed to one that uses static functions. It won't be 
pretty, but any function:


 def f(): whatever

could be rewritten as:

 def __f(): whatever
 f = __f()

But now the static name __f is available for direct use, and can be 
depended on not to change.


(Perhaps such a convention can be used anyway. A functions that starts 
with "__" or uses some other device, the compiler and runtime will know 
it will always be that function, and could allow some optimisations.)


(It's not quite so trivial for import module names, as you can't really 
just rename all modules! But in theory it could be done.)



I once monkey-patched the `len` built-in so I could monitor the progress of
a long-running piece of code that wasn't written to give any feedback.


These ought to be tricks that you do with source code. It shouldn't be 
necessary for an implementation to allow that.


(But doesn't len() already have a mechanism where you can override it 
anyway?)


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


Re: Error

2016-03-13 Thread Joel Goldstick
On Sat, Mar 12, 2016 at 3:32 AM, Abeer Sohail 
wrote:

> I get this error every time I open Python.
> --
> https://mail.python.org/mailman/listinfo/python-list
>

and what error is that?  no attachments in this list.  just copy and paste
the error please

-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem using pickle

2016-03-13 Thread Peter Otten
Nicky Mac wrote:

> Dear Python team,
> I have studied the excellent documentation, 

That is always a laudable endeavour ;)

> and attempted to make use of
> pickle thus:
> 
> filename = 'my_saved_adventure'
> import  pickle
> class object:

'object' already is the name for a Python built-in; you should avoid 
redefining it.

> def __init__(self,i,.t) :
> self.id   = i
>  .
> 
> class world:
> def __init__(self):
> self.object
> 
> class object:

As you already defined 'object' above you now have a name clash with your 
own stuff. I suppose that is because what you post is not your actual code.

> def __init__(self,i,
> 
> .then   Object instances of object are created 
> 
> myworld = world;
> myworld.Object = Object
> fileobj = open(filename,'wb')
> pickle.dump(myworld,fileobj); fileobj.close()
> result = "saved your game to " + filename
> 
> fileobj = open(filename,'rb')
> myworld = pickle.load(fileobj); fileobj.close()
> Object = myworld.Object
> result = "restored your game from " + filename
> 
> 
> The proecedures execute without error
> but a file of only 21b is created containing " €c__main__world q .
> altho there are several k of object instance data.

Unfortunately I cannot tell what might have gone wrong from the outline you 
provide above. Can you make a smaller script that shows the same problem, 
and that you can post in its entirety here? Use cut and paste, do not 
retype! Thank you.



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


Re: Descriptors vs Property

2016-03-13 Thread Veek. M
Thomas 'PointedEars' Lahn wrote:

>>>   Nobility lies in action, not in name.
>>> —Surak

Someone called Ned.B who i know elsewhere spoke on your behalf. I'm glad 
to say I like/trust Ned a bit so *huggles* to you, and I shall snip. 

Also, sorry about the 'Steve' thing - bit shady dragging in crap from 
elsewhere but my reputation here is not sterling (too many Q not many 
A), so I tend to defend it willy-nilly. Sorry for the excess BP I may 
have caused as well. One more *huggles* to you.

All the huggling doesn't imply i trust you etc etc. Ah umm.. anyway :p 
ciao till my next Q
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: looping and searching in numpy array

2016-03-13 Thread Albert-Jan Roskam


> Date: Thu, 10 Mar 2016 08:48:48 -0800
> Subject: Re: looping and searching in numpy array
> From: [email protected]
> To: [email protected]
> 
> On Thursday, March 10, 2016 at 2:02:57 PM UTC+1, Peter Otten wrote:
> > Heli wrote:
> > 
> > > Dear all,
> > > 
> > > I need to loop over a numpy array and then do the following search. The
> > > following is taking almost 60(s) for an array (npArray1 and npArray2 in
> > > the example below) with around 300K values.
> > > 
> > > 
> > > for id in np.nditer(npArray1):
> > >   
> > >newId=(np.where(npArray2==id))[0][0]
> > > 
> > > 
> > > Is there anyway I can make the above faster? I need to run the script
> > > above on much bigger arrays (50M). Please note that my two numpy arrays in
> > > the lines above, npArray1 and npArray2  are not necessarily the same size,
> > > but they are both 1d.
> > 
> > You mean you are looking for the index of the first occurence in npArray2 
> > for every value of npArray1?
> > 
> > I don't know how to do this in numpy (I'm not an expert), but even basic 
> > Python might be acceptable:
> > 
> > lookup = {}
> > for i, v in enumerate(npArray2):
> > if v not in lookup:
> > lookup[v] = i
> > 
> > for v in npArray1:
> > print(lookup.get(v, ""))
> > 
> > That way you iterate once (in Python) instead of 2*len(npArray1) times (in 
> > C) over npArray2.
> 
> Dear Peter, 
> 
> Thanks for your reply. This really helped. It reduces the script time from 
> 61(s) to 2(s). 
> 
> I am still very interested in knowing the correct numpy way to do this, but 
> till then your fix works great. 


Hi, I suppose you have seen this already (in particular the first link): 
http://numpy-discussion.10968.n7.nabble.com/Implementing-a-quot-find-first-quot-style-function-td33085.htmlI
 don't thonk it's part of numpy yet.
Albert-Jan
  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: programeren met python

2016-03-13 Thread Irmen de Jong
On 12-3-2016 17:58, Imre De Craemer wrote:
>  hoe moet je python dounlauden
> 

Dit is een Engelse newsgroup, dus je kunt je vragen beter in het Engels stellen 
in
plaats van in het Nederlands. Maar om je vraag te beantwoorden:
Ga naar https://www.python.org/downloads/ met je web browser en klik dan op de 
gele knop
"download python 3.5.1". Dan downloadt hij de setup die je vervolgens moet 
starten.
Je vindt dan na afloop in je start menu Python 3.5 en ook Idle (Python 3.5) 
terug
waarmee je aan de slag kunt.
Als je nog meer informatie nodig hebt om aan de slag te gaan, kun je hier 
bijvoorbeeld
kijken: https://wiki.python.org/moin/BeginnersGuide
of hier misschien: http://cscircles.cemc.uwaterloo.ca/nl/  (dat is in het 
Nederlands)
Of stel je vragen gewoon hier natuurlijk (in het Engels).

Veel succes!
Irmen de Jong


[English:]
This is an English newsgroup, so it's better to ask your questions in English 
rather
than in Dutch. But to answer your question:
Visit https://www.python.org/downloads/ with your web browser and click the 
yellow
button "download Python 3.5.1". It will then download the setup that you'll 
have to
start afterwards. You'll then find in your start menu Python 3.5 and also Idle 
(Python
3.5) with which you can get going.
If you need more information to get started, you can perhaps look at this:
https://wiki.python.org/moin/BeginnersGuide
or maybe this: http://cscircles.cemc.uwaterloo.ca/nl/   (which is in Dutch)
You can always ask your questions here of course (in English).


Good luck!

Irmen de Jong

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


RE: looping and searching in numpy array

2016-03-13 Thread Albert-Jan Roskam


> From: [email protected]
> To: [email protected]; [email protected]
> Subject: RE: looping and searching in numpy array
> Date: Sun, 13 Mar 2016 13:51:23 +



> 
> Hi, I suppose you have seen this already (in particular the first link): 
> http://numpy-discussion.10968.n7.nabble.com/Implementing-a-quot-find-first-quot-style-function-td33085.htmlI
>  don't thonk it's part of numpy yet.
> Albert-Jan

sorry, the correct url is: 
http://numpy-discussion.10968.n7.nabble.com/Implementing-a-quot-find-first-quot-style-function-td33085.html

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


issue w/ python 3.5.7

2016-03-13 Thread lucile . mage
Hello,
We would like to get the procedure to launch the software "python.exe". The 
only options we have acsess are: modify, repair and uninstall.
Thanks for your help,
Rgds,

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


Loading error message

2016-03-13 Thread BobFtz--- via Python-list
Hello
 
I have just downloaded and installed a copy of the 3.5.1 programme but when 
 I come to run the programme I get an error message that says that  
.api-ms-win-crt-runtime-l 1-1-0.dll is missing.
 
I have un-installed and reinstalled the 3.5.1 programme a few time (as  
advised) but I still can't get the programme to run
 
Can you please help with some step by step advice on how to repair this  
problem.
 
Many thanks
 
Bob
-- 
https://mail.python.org/mailman/listinfo/python-list


pdf version of python tutorial

2016-03-13 Thread kamaraju kusumanchi
Is there a pdf version of the python tutorial
https://docs.python.org/3/tutorial/index.html that I can download? The
idea is to have everything in one file so I can search easily, be able
to work offline.

thanks
raju
-- 
Kamaraju S Kusumanchi | http://raju.shoutwiki.com/wiki/Blog
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pdf version of python tutorial

2016-03-13 Thread Chris Warrick
On 13 March 2016 at 14:45, kamaraju kusumanchi
 wrote:
> Is there a pdf version of the python tutorial
> https://docs.python.org/3/tutorial/index.html that I can download? The
> idea is to have everything in one file so I can search easily, be able
> to work offline.
>
> thanks
> raju
> --
> Kamaraju S Kusumanchi | http://raju.shoutwiki.com/wiki/Blog
> --
> https://mail.python.org/mailman/listinfo/python-list

There is a download link on the documentation index:

https://docs.python.org/3/download.html

-- 
Chris Warrick 
PGP: 5EAAEA16
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue w/ python 3.5.7

2016-03-13 Thread Steven D'Aprano
On Mon, 14 Mar 2016 03:56 am, [email protected] wrote:

> Hello,
> We would like to get the procedure to launch the software "python.exe".
> The only options we have acsess are: modify, repair and uninstall. Thanks
> for your help, Rgds,


What is your operating system?


-- 
Steven

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


Re: Descriptors vs Property

2016-03-13 Thread Thomas 'PointedEars' Lahn
Veek. M wrote:

> Thomas 'PointedEars' Lahn wrote:
   Nobility lies in action, not in name.
 —Surak
> 
> Someone called Ned.B who i know elsewhere spoke on your behalf. I'm glad
> to say I like/trust Ned a bit so *huggles* to you, and I shall snip.
> 
> Also, sorry about the 'Steve' thing - bit shady dragging in crap from
> elsewhere but my reputation here is not sterling (too many Q not many
> A), so I tend to defend it willy-nilly. Sorry for the excess BP I may
> have caused as well. One more *huggles* to you.
> 
> All the huggling doesn't imply i trust you etc etc. Ah umm.. anyway :p
> ciao till my next Q

I prefer not to be hugged by people who I do not know personally,
but I accept what I consider your serious attempt at an apology.

Until next time, hopefully more on topic, then,

-- 
PointedEars (F'up2 poster)

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue w/ python 3.5.7

2016-03-13 Thread Thomas 'PointedEars' Lahn
[email protected] wrote:

> We would like to get the procedure to launch the software "python.exe".
> The only options we have acsess are: modify, repair and uninstall. […]



-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue w/ python 3.5.7

2016-03-13 Thread Oscar Benjamin
On 13 Mar 2016 18:01, "Steven D'Aprano"  wrote:
>
> On Mon, 14 Mar 2016 03:56 am, [email protected] wrote:
>
> > Hello,
> > We would like to get the procedure to launch the software "python.exe".
> > The only options we have acsess are: modify, repair and uninstall.
Thanks
> > for your help, Rgds,
>
>
> What is your operating system?

It will be Windows. I think it's some kind of installer bug. I'm not sure
whether it happens when running the downloaded installer or when attempting
to run Python after installation but Windows will pop up an error message
box giving the user these three options. A lot of Windows users have been
reporting this problem with Python 3.5 but I'm not sure if the problem has
made it to the bug tracker and I haven't seen an explanation or solution.

Lucile, can you try installing Python 3.4 and see if you have the same
problem? If not then it's likely a bug in Python 3.5 or its installer.

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


Re: Loading error message

2016-03-13 Thread Oscar Benjamin
On 13 Mar 2016 17:06, "BobFtz--- via Python-list" 
wrote:
>
> Hello
>
> I have just downloaded and installed a copy of the 3.5.1 programme but
when
>  I come to run the programme I get an error message that says that
> .api-ms-win-crt-runtime-l 1-1-0.dll is missing.
>
> I have un-installed and reinstalled the 3.5.1 programme a few time (as
> advised) but I still can't get the programme to run
>
> Can you please help with some step by step advice on how to repair this
> problem.

You need to install a Windows update from Microsoft:
https://support.microsoft.com/en-us/kb/2999226

Really the installer download page should be updated with this information
and the installer should be improved to give a more informative error
message.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread BartC

On 13/03/2016 01:10, Mark Lawrence wrote:

On 12/03/2016 23:57, BartC wrote:


[switch statements]

How does Python manage without them? Is it really necessary to declare
hundreds of individual variables and assign a value to each? (And risk
someone assigning a new value to them.)

That they might lead to more efficient code is secondary, but definitely
a bonus (essential though when used in a switch statement).



It is 2016.  Programmer time, and hence money, are far more important
than runtime speed in the vast majority of cases.


Exactly why having ready-made solutions is preferable to everyone 
hacking their own solutions to switch.



There are plenty of
working recipes for switch in Python.  I'll leave you to quote a few as
you are such an expert in the Python programming language.


I've seen a few. Here's one that uses:

class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True

def case(*args):
return any((arg == switch.value for arg in args))

I used it in my benchmark to replace the if-else chain checking three 
lots of ranges:


switch(c)
if case(ord("A"),ord("B"),ord("C"),ord("D"),ord("E"),ord("F"),
ord("G"),ord("H"),ord("I"),ord("J"),ord("K"),ord("L"),
ord("M"),ord("N"),ord("O"),ord("P"),ord("Q"),ord("R"),
ord("S"),ord("T"),ord("U"),ord("V"),ord("W"),ord("X"),
ord("Y"),ord("Z")):
upper+=1
elif case(ord("a"),ord("b"),ord("c"),ord("d"),ord("e"),ord("f"),
ord("g"),ord("h"),ord("i"),ord("j"),ord("k"),ord("l"),
ord("m"),ord("n"),ord("o"),ord("p"),ord("q"),ord("r"),
ord("s"),ord("t"),ord("u"),ord("v"),ord("w"),ord("x"),
ord("y"),ord("z")):
lower+=1
elif case(ord("0"),ord("1"),ord("2"),ord("3"),ord("4"),ord("5"),
  ord("6"),ord("7"),ord("8"),ord("9")):
digits+=1
else:
other+=1

It worked, but took 110 seconds; 80 seconds without the ord's and 
comparing strings (but I still think it's perverse that integer ops are 
slower than string ops).


But 110 or 80 seconds, the original Python was 3.6 seconds. (Probably, 
someone could tweak it to work with ranges, but this is extra programmer 
effort that you say is too valuable to waste on such matters.)


(An actual 62-way if-elif chain took 25 seconds in Python 3.

You might care not about speed, but it's something when the fastest 
solution in a language with built-in switch, and /still interpreting a 
byte-code at a time/, is 1000 times faster than the 80-second version 
above.)



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


Re: The Cost of Dynamism

2016-03-13 Thread Thomas 'PointedEars' Lahn
Chris Angelico wrote:

> On Sun, Mar 13, 2016 at 6:24 AM, Thomas 'PointedEars' Lahn
>  wrote:
>> Marko Rauhamaa wrote:
>>> […] HTML markup is all ASCII.
>>
>> Wrong.  I am creating HTML documents whose source code contains Unicode
>> characters every day.
>>
>> Also, the two of you fail to differentiate between US-ASCII, a 7-bit
>> character encoding, and 8-bit or longer encodings which can *also* encode
>> characters that can be *encoded with* US-ASCII.
> 
> Where are the non-ASCII characters in your HTML documents? Are they in
> the *markup* of HTML, or in the *text*? This is the difference.

There is a misconception on your part instead.  The text content of an 
HTML/Web document (the part between the [HTML] tags) is *part* of the (HTML) 
markup as it is (at least) *a part* of the content of (HTML) elements. [1a]
[1b] 

Besides, even if one would unwisely adopt your private definition of 
“markup”, Unicode characters that cannot be encoded with US-ASCII are of 
course allowed verbatim in attribute values, and to a lesser degree (not in 
HTML 4.01 and below) in element type names and attribute names, as well – 
therefore, according to even your *wrong* private definition of “markup”, 
“*in* the markup of HTML”. [2][3]

Bottom line:

If one declares the character encoding that one uses in an SGML-based (HTML 
up to including version 4.01, XML and all XML-based document types) or SGML-
related (HTML5) markup document (there are several possibilities for that)¹, 
there is no need to use character entity references instead of plain Unicode 
characters.  And if you avoid spaghetti code, the probability of the need 
for numeric character references in HTML is also quite low.  (The same 
applies to lightweight markup languages like Markdown, but let us not get 
there now.)

[In fact, the possibility to use characters verbatim other than those that 
can be encoded with US-ASCII applies to all Internet messages, including
e-mail and Usenet postings, and to a lesser degree (because there are fewer 
declaration mechanisms available) to all forms of electronically 
stored/readable text.  As of RFC 5536, standards-compliant Network News 
client software is even required to support MIME. [4]]

  [This was a professional Web author/developer with more than a decade of 
   continuing work experience clarifying your misconception.  I recommend
   to you that you subscribe to the newsgroups in the 
   comp.infosystems.www.authoring.* hierarchy, where this discussion would
   have been on-topic, and to , to clarify some
   of the other misconceptions that you may have acquired about
   Web(-related) authoring/development.]


¹  This is only to be reasonably safe from surprises; several of those 
   markup languages require the assumption of a default character encoding 
   and/or the implementation of character encoding detection for their
   parsers, but not all parsers are conforming, and it stands to reason
   that parser efficiency can be increased if the encoding does not have
   to be detected/inferred at first.

[1a] 
[1b] 
 
[2]  
[3]  
 
[4]  
 
> And I'm not conflating those two. When I say ASCII, I am referring to
> the 128 characters that have Unicode codepoints U+ through U+007F.

That is only your private definition of ASCII.  The commonly accepted 
definition is along those lines instead:

 pp.

(See also the Specification references above.)


HTH

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism

2016-03-13 Thread Thomas 'PointedEars' Lahn
BartC wrote:

> On 12/03/2016 19:26, Thomas 'PointedEars' Lahn wrote:
>> BartC wrote:
>>> On 12/03/2016 12:13, Marko Rauhamaa wrote:
 Why, look at the *English* page on Hillary Clinton:

  Hillary Diane Rodham Clinton /ˈhɪləri daɪˈæn ˈrɒdəm ˈklɪntən/
  (born October 26, 1947) is an American politician.
  https://en.wikipedia.org/wiki/Hillary_Clinton>

 You couldn't get past the first sentence in ASCII.
>>>
>>> I saved that page locally as a .htm file in UTF-8 encoding. I ran a
^^
>>> modified version of my benchmark, and it appeared that 99.7% of the
>>> bytes had ASCII codes.
^
>> That is a contradiction in terms.  Obviously you do not know what ASCII
>> is.
> 
> What does your own analysis show of that page?
> 
> If you had it in memory as fully expanded 32-bit Unicode values, what
> proportion of those would have values below 128?

You are missing the point.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Marko Rauhamaa
BartC :

> Exactly why having ready-made solutions is preferable to everyone
> hacking their own solutions to switch.

A developer friend of mine once said insightfully that the point of OO
is getting rid of switch statements. IOW, most use cases for switch
statements are handled with virtual functions.

The most significant exception in my experience is message decoding,
where switches/ifs cannot be avoided.


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


Re: problem using pickle

2016-03-13 Thread Terry Reedy

On 3/12/2016 10:45 AM, Nicky Mac wrote:


class object:
 def __init__(self,i,


This is a syntax error, so this is not the code that ran without error. 
 As Peter Otten said, please write a minimal complete runnable example 
that shows the error and then copy and paste it as run.



--
Terry Jan Reedy

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Chris Angelico
On Mon, Mar 14, 2016 at 6:39 AM, BartC  wrote:
> I used it in my benchmark to replace the if-else chain checking three lots
> of ranges:
>
> switch(c)
> if case(ord("A"),ord("B"),ord("C"),ord("D"),ord("E"),ord("F"),
> ord("G"),ord("H"),ord("I"),ord("J"),ord("K"),ord("L"),
> ord("M"),ord("N"),ord("O"),ord("P"),ord("Q"),ord("R"),
> ord("S"),ord("T"),ord("U"),ord("V"),ord("W"),ord("X"),
> ord("Y"),ord("Z")):
> upper+=1
> elif case(ord("a"),ord("b"),ord("c"),ord("d"),ord("e"),ord("f"),
> ord("g"),ord("h"),ord("i"),ord("j"),ord("k"),ord("l"),
> ord("m"),ord("n"),ord("o"),ord("p"),ord("q"),ord("r"),
> ord("s"),ord("t"),ord("u"),ord("v"),ord("w"),ord("x"),
> ord("y"),ord("z")):
> lower+=1
> elif case(ord("0"),ord("1"),ord("2"),ord("3"),ord("4"),ord("5"),
>   ord("6"),ord("7"),ord("8"),ord("9")):
> digits+=1
> else:
> other+=1
>
> It worked, but took 110 seconds; 80 seconds without the ord's and comparing
> strings (but I still think it's perverse that integer ops are slower than
> string ops).
>
> But 110 or 80 seconds, the original Python was 3.6 seconds. (Probably,
> someone could tweak it to work with ranges, but this is extra programmer
> effort that you say is too valuable to waste on such matters.)

This is not comparing ranges, though. This is comparing against
individual values. To talk about comparing ranges, I would expect the
code to look something like this:

switch(c)
if case("A", "Z"):
upper += 1
elif case("a", "z"):
lower += 1
elif case("0", "9"):
digits += 1
else:
other += 1

THIS is comparing ranges. The underlying comparisons must be
inequalities, not equalities. I absolutely *do not care* about
performance until the code looks good - at least reasonably good.

(By the way, your switch/case pair is non-reentrant. Plus it uses a
class in a weird way. Why not, if you're working like this, just have
two functions and a module-global? Just as non-reentrant, much cleaner
code.)

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Christian Gollwitzer

Am 13.03.16 um 20:39 schrieb BartC:

switch(c)
if case(ord("A"),ord("B"),ord("C"),ord("D"),ord("E"),ord("F"),
 ord("G"),ord("H"),ord("I"),ord("J"),ord("K"),ord("L"),
 ord("M"),ord("N"),ord("O"),ord("P"),ord("Q"),ord("R"),
 ord("S"),ord("T"),ord("U"),ord("V"),ord("W"),ord("X"),
 ord("Y"),ord("Z")):
 upper+=1
elif case(ord("a"),ord("b"),ord("c"),ord("d"),ord("e"),ord("f"),
 ord("g"),ord("h"),ord("i"),ord("j"),ord("k"),ord("l"),
 ord("m"),ord("n"),ord("o"),ord("p"),ord("q"),ord("r"),
 ord("s"),ord("t"),ord("u"),ord("v"),ord("w"),ord("x"),
 ord("y"),ord("z")):
 lower+=1
elif case(ord("0"),ord("1"),ord("2"),ord("3"),ord("4"),ord("5"),
   ord("6"),ord("7"),ord("8"),ord("9")):
 digits+=1
else:
 other+=1

It worked, but took 110 seconds; 80 seconds without the ord's and
comparing strings (but I still think it's perverse that integer ops are
slower than string ops).


I assume you run this in a big loop. What about a single hash-table lookup?

from collections import Counter
counts=Counter()
for c in whatever:
counts[c]+=1

upper=sum(counts[x] for x in range(ord('A'), ord('Z')+1)
lower=sum(counts[x] for x in range(ord('a'), ord('z')+1)



I think this is equally readable as the switch version, and should be 
much faster.


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Chris Angelico
On Mon, Mar 14, 2016 at 8:26 AM, Christian Gollwitzer  wrote:
> I assume you run this in a big loop. What about a single hash-table lookup?
>
> from collections import Counter
> counts=Counter()
> for c in whatever:
> counts[c]+=1
>
> upper=sum(counts[x] for x in range(ord('A'), ord('Z')+1)
> lower=sum(counts[x] for x in range(ord('a'), ord('z')+1)
> 
>
>
> I think this is equally readable as the switch version, and should be much
> faster.

At this point, it's completely moved away from being a switch block,
so while it may well be more readable AND faster, it's pretty much
irrelevant to the discussion. The value of a switch block is arbitrary
code, same as an if/elif tree, without having to package stuff up into
functions. Although I could accept a function-based solution if it
looks clean enough...

case = switch(c)

@case("A", "Z")
def _():
do_uppercase_stuff

@case("a", "z")
def _():
do_lowercase_stuff

@case("0", "9")
def _():
do_digit_stuff

@case
def _():
do_default_stuff

It creates an inner scope, which most people won't need or want, and
it's creating a bunch of functions every iteration, but the code's
reasonably clean. And it's fairly implementable:

def switch(template):
def case(testme, *range):
if done is not case: return done # Already hit another case.
match = False
if isinstance(testme, type(case)):
# No parens - this is the default case
match = True
elif range:
match = testme <= template <= range[0]
else:
match = template == testme
if match:
done = testme()
return done
done = case # Sentinel: Not done yet.
return case

Now you can play around with performance questions. But not until the
code (a) does the right thing, and (b) looks good enough to maintain.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread BartC

On 13/03/2016 20:57, Chris Angelico wrote:

On Mon, Mar 14, 2016 at 6:39 AM, BartC  wrote:

I used it in my benchmark to replace the if-else chain checking three lots
of ranges:

switch(c)
if case(ord("A"),ord("B"),ord("C"),ord("D"),ord("E"),ord("F"),



It worked, but took 110 seconds; 80 seconds without the ord's and comparing
strings (but I still think it's perverse that integer ops are slower than
string ops).

But 110 or 80 seconds, the original Python was 3.6 seconds. (Probably,
someone could tweak it to work with ranges, but this is extra programmer
effort that you say is too valuable to waste on such matters.)


This is not comparing ranges, though. This is comparing against
individual values.


That's true. (It's not my code for 'switch' and 'case', and I assume 
that the "==" operation it does on the arguments would not work when a 
range is passed, whatever form that might be in.)


Nevertheless, a true switch statement would be expected to work just as 
well with lots of individual case values, as with a smaller set of ranges.


 To talk about comparing ranges, I would expect the

code to look something like this:

switch(c)
if case("A", "Z"):
 upper += 1
elif case("a", "z"):
 lower += 1
elif case("0", "9"):
 digits += 1
else:
 other += 1

THIS is comparing ranges.




The underlying comparisons must be
inequalities, not equalities. I absolutely *do not care* about
performance until the code looks good - at least reasonably good.


Yes, that would be faster. I made a much-simplified case() work like 
your example, and the timing was 12 seconds.


(But that just worked with one single range, not an arbitrary mix of 
single values and ranges as a proper switch. Allowing any number of 
ranges per case, it took 25 seconds, and it's still not quite a full 
switch.)



(By the way, your switch/case pair is non-reentrant. Plus it uses a
class in a weird way. Why not, if you're working like this, just have
two functions and a module-global? Just as non-reentrant, much cleaner
code.)


I chose this because it looked odd, and was likely to perform poorly!

My point being that it's difficult to put together something that looks 
like, and is as easy to use as a switch in other languages, and is still 
efficient. (The 12 seconds still took over 3 times as long as as a 
simple if-elif chain, and the tests are still sequential so expect a 
slow-down with lots groups to test.)


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


Re: pdf version of python tutorial

2016-03-13 Thread kamaraju kusumanchi
On Sun, Mar 13, 2016 at 1:34 PM, Chris Warrick  wrote:
>
> There is a download link on the documentation index:
>
> https://docs.python.org/3/download.html
>

Exactly what I needed. Thanks.

raju
-- 
Kamaraju S Kusumanchi | http://raju.shoutwiki.com/wiki/Blog
-- 
https://mail.python.org/mailman/listinfo/python-list


Is anyone in this group using Python Editor v5 for Chromebooks?

2016-03-13 Thread Jeff Schumaker
I'm trying to use Python Editor v5 for Chromebooks. It works fine, except it 
won't read data files. I'm just wondering if anyone else is using this editor 
and has found a solution to this problem.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Paul Rubin
BartC  writes:
> def case(*args):
> return any((arg == switch.value for arg in args))

def case(values): 
return switch.value in values

> I used it in my benchmark to replace the if-else chain checking three
> lots of ranges:
>
> switch(c)
> if case(ord("A"),ord("B"),ord("C"),ord("D"),ord("E"),ord("F"),
> ord("G"),ord("H"),ord("I"),ord("J"),ord("K"),ord("L"),
> ord("M"),ord("N"),ord("O"),ord("P"),ord("Q"),ord("R"),
> ord("S"),ord("T"),ord("U"),ord("V"),ord("W"),ord("X"),
> ord("Y"),ord("Z")):
> upper+=1

Use a set instead of a big tuple:

uppers = { ord("A"), ord("B"), ... ord("Z") }
...
if case(uppers):
   upper += 1
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Encapsulation in Python

2016-03-13 Thread Gregory Ewing

Rick Johnson wrote:

Sure, that's reliable in most cases, but your argument
assumes that the actual source code for the symbol exists in
the module from which it was imported, when it could just as
well exist N-levels below that that module, due to chained
imports.


Unless the module is doing something obscure, you can
still find it by following the chain of imports. And
since Python culture encourages rather shallow
module nesting trees, the chain is usually fairly
short.

True, it's not *always* that easy, but in the vast
majority of cases it is. The situation is certainly
much better than what you have in e.g. a large C
project, where you get *no idea* where a particular
symbol may have come from by inspecting the source.

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-13 Thread chetam . chetzy
On Friday, January 8, 2016 at 11:38:11 AM UTC-5, [email protected] wrote:
> On Wednesday, 30 December 2015 19:21:32 UTC+1, Won Chang  wrote:
> > i have these task which i believe i have done well to some level
> > 
> > Create a function get_algorithm_result to implement the algorithm below
> > 
> > 1- Get a list of numbers L1, L2, L3LN as argument 2- Assume L1 is the 
> > largest, Largest = L1 3- Take next number Li from the list and do the 
> > following 4- If Largest is less than Li 5- Largest = Li 6- If Li is last 
> > number from the list then 7- return Largest and come out 8- Else repeat 
> > same process starting from step 3
> > 
> > Create a function prime_number that does the following Takes as parameter 
> > an integer and Returns boolean value true if the value is prime or Returns 
> > boolean value false if the value is not prime
> > 
> > so i came up with this code below
> > 
> > def get_algorithm_result(my_list):
> > if not any(not type(y) is int for y in my_list):
> > largest = 0
> > for item in range(0,len(my_list)):
> > if largest < my_list[item]:
> > largest = my_list[item]
> > return largest
> > else:
> > 
> > return(my_list[-1])
> > 
> > def prime_number(integer):
> > if integer%2==0 and 2!=integer:
> > return False
> > else:
> > return True
> > 
> > get_algorithm_result([1, 78, 34, 12, 10, 3]) 
> > get_algorithm_result(["apples", "oranges", "mangoes", "banana", "zoo"]) 
> > prime_number(1) 
> > prime_number(78) 
> > prime_number(11) 
> > for the question above, there is a unittes which reads
> > 
> > import unittest
> > 
> > class AlgorithmTestCases(unittest.TestCase):
> >   def test_maximum_number_one(self):
> > result = get_algorithm_result([1, 78, 34, 12, 10, 3])
> > self.assertEqual(result, 78, msg="Incorrect number")
> > 
> >   def test_maximum_number_two(self):
> > result = get_algorithm_result(["apples", "oranges", "mangoes", 
> > "banana", "zoo"])
> > self.assertEqual(result, "zoo", msg="Incorrect number")
> > 
> >   def test_prime_number_one(self):
> > result = prime_number(1)
> > self.assertEqual(result, True, msg="Result is invalid")
> > 
> >   def test_prime_number_two(self):
> > result = prime_number(78)
> > self.assertEqual(result, False, msg="Result is invalid")
> > 
> >   def test_prime_number_three(self):
> > result = prime_number(11)
> > self.assertEqual(result, True, msg="Result is invalid")
> > but once i run my code ,it returns error saying Test Spec Failed
> > 
> > Your solution failed to pass all the tests
> > what is actually wrong with my code?
> 
> I had to use a hack to bypass it, worked and I moved on to next quiz

Hello, I have this same assignment to create Bank account and I am new to 
python. please help me out.

Create a class called BankAccount

Create a constructor that takes in an integer and assigns this to a 
`balance` property.
Create a method called `deposit` that takes in cash deposit amount and 
updates the balance accordingly.
Create a method called `withdraw` that takes in cash withdrawal amount and 
updates the balance accordingly. if amount is greater than balance return 
`"invalid transaction"`
Create a subclass MinimumBalanceAccount of the BankAccount class


import unittest
class AccountBalanceTestCases(unittest.TestCase):
  def setUp(self):
self.my_account = BankAccount(90)

  def test_balance(self):
self.assertEqual(self.my_account.balance, 90, msg='Account Balance Invalid')

  def test_deposit(self):
self.my_account.deposit(90)
self.assertEqual(self.my_account.balance, 180, msg='Deposit method 
inaccurate')

  def test_withdraw(self):
self.my_account.withdraw(40)
self.assertEqual(self.my_account.balance, 50, msg='Withdraw method 
inaccurate')

  def test_invalid_operation(self):
self.assertEqual(self.my_account.withdraw(1000), "invalid transaction", 
msg='Invalid transaction')
  
  def test_sub_class(self):
self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount), msg='No 
true subclass of BankAccount')
 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-13 Thread Chris Angelico
On Mon, Mar 14, 2016 at 11:17 AM,   wrote:
> Hello, I have this same assignment to create Bank account and I am new to 
> python. please help me out.

The best help you can get is:

DO THE WORK.

You can't simply ask for help without doing any work first. If you
want to learn how to write Python code, you will have to write code.
Start by writing as much of it as you can, and *then* ask for help,
when you get stuck. Otherwise, you're basically asking someone to do
your homework for you.

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-13 Thread MRAB

On 2016-03-14 00:40, Chris Angelico wrote:

On Mon, Mar 14, 2016 at 11:17 AM,   wrote:

Hello, I have this same assignment to create Bank account and I am new to 
python. please help me out.


The best help you can get is:

DO THE WORK.

You can't simply ask for help without doing any work first. If you
want to learn how to write Python code, you will have to write code.
Start by writing as much of it as you can, and *then* ask for help,
when you get stuck. Otherwise, you're basically asking someone to do
your homework for you.


I'd also suggest working through a tutorial.

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-13 Thread Chris Angelico
On Mon, Mar 14, 2016 at 11:57 AM, MRAB  wrote:
> On 2016-03-14 00:40, Chris Angelico wrote:
>>
>> On Mon, Mar 14, 2016 at 11:17 AM,   wrote:
>>>
>>> Hello, I have this same assignment to create Bank account and I am new to
>>> python. please help me out.
>>
>>
>> The best help you can get is:
>>
>> DO THE WORK.
>>
>> You can't simply ask for help without doing any work first. If you
>> want to learn how to write Python code, you will have to write code.
>> Start by writing as much of it as you can, and *then* ask for help,
>> when you get stuck. Otherwise, you're basically asking someone to do
>> your homework for you.
>>
> I'd also suggest working through a tutorial.

It sounds to me like both chetam and the OP are working through a
particular course, and this is one of the assignments. Unless the
course is abysmally written, it should be capable of teaching the
basics without the students having to turn to an external tutorial.
However, not knowing the course, I can't say for sure.

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-13 Thread Ben Finney
[email protected] writes:

> Hello, I have this same assignment to create Bank account and I am new
> to python.

Welcome to Python! If you have an assignment, that implies you are
working through a course and you have received enough teaching to
attempt the task yourself.

> please help me out.

Apply your existing Python knowledge – you've been learning it in your
course, right? – to run the test suite provided.

Follow this procedure.

* Run the test suite.

* Observe what tests fail. If they all run and all pass, you're done.

* Write just enough of the BankAccount class that it changes the behaviour
  of at least one test case.

* Repeat from the top, until all the test cases pass.

If you have questions:

* Please provide a complete example (so that we can also run the same
  code),

* Which is very small (so it's easy to discuss),

* and ask specific questions about what it's doing and why that doesn't
  meet your expectation.

-- 
 \   “Kissing a smoker is like licking an ashtray.” —anonymous |
  `\   |
_o__)  |
Ben Finney

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-13 Thread BartC

On 14/03/2016 00:17, [email protected] wrote:


Create a class called BankAccount

 Create a constructor that takes in an integer and assigns this to a 
`balance` property.
 Create a method called `deposit` that takes in cash deposit amount and 
updates the balance accordingly.
 Create a method called `withdraw` that takes in cash withdrawal amount and updates 
the balance accordingly. if amount is greater than balance return `"invalid 
transaction"`
 Create a subclass MinimumBalanceAccount of the BankAccount class


I've never used classes and stuff much so I gave it a go. (But I 
wouldn't submit this if it's an assignment).


class ac:
balance=0

def __init__(self,openbal):
if openbal>0:
self.balance=openbal
print ("Opened account; opening balance",self.balance)
else:
print ("Invalid opening balance:",openbal)

def payin(self,amount):
if amount>0:
self.balance+=amount
print ("Paid in:",amount," New balance:",self.balance)
return 1
else:
print ("Paying in invalid sum",amount)
return 0

def takeout(self,amount):
if amount<=0:
print ("Invalid withdrawal amount",amount)
return 0

elif amount>self.balance:
print ("Not enough funds")
return 0

else:
self.balance-=amount
print ("Paid out:",amount," New balance:",self.balance)
return 1

x=ac(100)

x.payin(34)
x.takeout(70)
x.takeout(100)


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-13 Thread Steven D'Aprano
On Mon, 14 Mar 2016 12:16 am, BartC wrote:

> On 13/03/2016 09:39, Steven D'Aprano wrote:
>> On Sun, 13 Mar 2016 04:54 am, BartC wrote:
> 
>>> Common sense tells you it is unlikely.
>>
>> Perhaps your common sense is different from other people's common sense.
>> To me, and many other Python programmers, it's common sense that being
>> able to replace functions or methods on the fly is a useful feature worth
>> having.
> 
> Worth having but at significant cost. But look at my jpeg test (look at
> any other similar programs); how many function names are used
> dynamically? How many functions *really* need to be dynamic?

As difficult as it may seem sometimes, Python is not a specialist
programming language designed to be optimal for your jpeg test, it is a
general purpose programming language designed for many different uses :-)

"Really need" is a funny thing. We don't *really need* anything beyond
machine language, or maybe assembly code mnemonics that correspond directly
to machine codes. Everything beyond that is either, depending on your
perspective, a waste of time that leads to inefficient code, or the best
thing for programming ever that saves programmer time and effort and
increases productivity.

You may not have noticed yet *wink* but Python's emphasis is more on the
programmer productivity side than the machine efficiency side. And from
that perspective, it can be argued that, yes, absolutely, all those
functions *need* to be dynamic, or at least have the possibility to be
dynamic if and when needed.


>>> (Have you tried looking at the CPython sources?
> 
>> Right. Now add *on top of that complexity* the extra complexity needed to
>> manage not one, but *two* namespaces for every scope: one for "variables"
>> and one for "functions and methods".
> 
> No, there's one namespace per scope. (Otherwise you could have a
> function 'f' and a variable 'f' in each scope.)

I was going to ask you about that.


> Perhaps what you mean is the number of different kinds of identifiers
> there can be. At the minute, apart from obvious, fixed, reserved words
> (I assume there are some!), 

There are reserved words -- "for", "if", "else", "def", etc. The compiler
deals with reserved words at compile time: you get a syntax error if you
try to use them as a variable name, not a runtime error.


> there seems to be just one kind. The 
> different categories (function, variable, class, built-in, module etc)
> are sorted out at *run-time*.

What do you mean by "sorted out"? You have names in a namespace which are
bound to objects. Once you have bound a name, you can rebind it:

x = 23
x = 'abc'

is just a rebinding where the value of x changes from 23 to 'abc'.

> Some of this will just move to *compile-time*. 

How? It's easy to say "just move it to compile time", but *how* do you move
it (don't say "by editing the Python interpreter's source code"), and what
*precisely* is "it"?

At compile time, you don't in general know what value things will have. You
don't even know what type they will have (since the type of an object is
part of its value).

Here is an extreme example to demonstrate the difficulty:


import random
if random.random() < 0.5:
def f():
return 1
else:
f = "hello"

f = "goodbye"


So tell me: *at compile time*, how do you know whether the final binding
(assignment of "goodbye" to variable f) should be allowed or not?


> Same amount of 
> complexity, but now you do it just once at compile-time, instead of a
> billion times at run-time.

I don't think you are, but let's suppose you're right and that the compiler
can reliably detect and prevent code like this:


def f(): return 1
g = f
g = something_else  # allowed
f = something_else  # not allowed


How do you intend to prevent this?

def f(): return 1
exec "f = something_else"


Suppose we removed the ability to rebind names that were bound to a
function, as you suggest. There's a very important and commonplace use for
rebinding functions that we would lose: decorators.

"Good riddance," you might say, "I never use them." Okay, but if so, that is
certainly the Blub paradox talking. Decorators have completely transformed
Python since decorator syntax was introduced in (by memory) version 2.3.
Decorators are a hugely important part of Python, and having to give them
up in order to get compile-time-constant functions would gut the language
and cripple almost all major libraries and code bases.

Decorators themselves were possible before 2.3(?), but they were
inconvenient to use and didn't have a well-known name and so nobody really
used them:

# Before decorator syntax
def func():
...

func = decorate(func)


# After decorator syntax
@decorate
def func():
...



where decorate itself is a function which usually pre- or post-processes the
original function. (Decorators can do much, much more, but that's probably
the most common use-case.)

Decorator syntax is just syntactic sugar for a wrapper around a function,
assigned to the 

Re: looping and searching in numpy array

2016-03-13 Thread srinivas devaki
problem is infact not related to numpy at all. the complexity of your
algorithm is O(len(npArray1) * len(npArray2))

which means the number of computations that you are doing is in the range
of 10**10,

if the absolute difference between the maximum element and minimum element
is less than 10**6, you can improve your code by pre-computing the first
occurrence of a number by using an array of size of that difference(afore
mentioned).

if your npArray2 doesn't have such a pattern, you have to precompute it by
using a dict (I don't know if numpy has such data structure)

an optimised pseudo code would look like

mmdiff = max(npArray2) - min(npArray2)
if mmdiff < 10**6:
precom = np.array([-1] * mmdiff)
offset = min(npArray2)
for i, x in enumerate(npArray2):
precom[x - offset] = i
for id in npArray1:
if 0 <= id - offset < mmdiff and precom[id - offset] != -1:
new_id = precom[id]
# your code
else:
precom = {}
for i, x in enumerate(npArray1):
if x not in precom:
precom[x] = i
for id in npArray1:
if id in precom:
new_id = precom[id]
# your code


you can just use the else case which will work for all cases but if your
npArray2 has such a pattern then the above code will perform better.

Regards
Srinivas Devaki
Junior (3rd yr) student at Indian School of Mines,(IIT Dhanbad)
Computer Science and Engineering Department
ph: +91 9491 383 249
telegram_id: @eightnoteight
On Mar 10, 2016 5:15 PM, "Heli"  wrote:

Dear all,

I need to loop over a numpy array and then do the following search. The
following is taking almost 60(s) for an array (npArray1 and npArray2 in the
example below) with around 300K values.


for id in np.nditer(npArray1):

   newId=(np.where(npArray2==id))[0][0]


Is there anyway I can make the above faster? I need to run the script above
on much bigger arrays (50M). Please note that my two numpy arrays in the
lines above, npArray1 and npArray2  are not necessarily the same size, but
they are both 1d.


Thanks a lot for your help,

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