Re: [Tutor] help with data insert into Access table

2014-01-29 Thread Keith Winston
On Wed, Jan 29, 2014 at 3:03 PM, Mark Lawrence  wrote:
> Nothing to do with tuples.  Tools such as syntax checkers or MkI eyeballs
> come in useful here.  Although such tools probably won't pick up the
> incorrect spelling of "harboUr" :)

Alas, now I'm more confused. I don't see any mispellings in what you
referred to? I had the impression that Peter was employing tuples
because, as an immutable type, it couldn't
inadvertently/inauspiciously be changed by a user. Oh, I see... single
vs. double, eh? Got it.


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with data insert into Access table

2014-01-29 Thread Keith Winston
On Wed, Jan 29, 2014 at 12:11 PM, Mark Lawrence  wrote:
> I think it's worth pointing out that there is a difference here between the
> OP's 'Site Name's Harbor.JPG' and Peter's "Site Name's Harbor.JPG".  Left as
> homework for the newbies :)


I'll bite. But are you just referring to the tuple issue, reinforced
by the XKCD, that Peter referred to, or have I not finished this
homework?

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to correct decimal addition.

2014-01-25 Thread Keith Winston
On Sat, Jan 25, 2014 at 5:09 PM, Oscar Benjamin
 wrote:
> Perhaps it would be better though to point at this:
 round(D('0.123456'), 3)
> Decimal('0.123')

I think you are right. I didn't even think of round(). I think we have
confounded two issues in this thread, the internal
representation/accuracy, and the final presentation. They aren't
really the same thing, unless we force them to be (i.e. using ints).

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to correct decimal addition.

2014-01-25 Thread Keith Winston
Also, just to be clear: I'd suggest floats because decimal requires
importing a module and using the non-built-in features thereof,
especially if you're going to do something like
decimal.getcontext().prec (even that doesn't set precision AFTER the
decimal point... only total precision). My point being that I don't
see the value of sending a beginner into that morass. I actually still
can't find how to force decimal to round to 3 places after the
decimal... (actually, I can't find a single reference to .prec except
in examples in the standard library doc of decimal
http://docs.python.org/3.3/library/decimal.html#decimal.getcontext)

And finally: when I said "watch out for rounding", I meant be prepared
for it. It is correct that rounding happens (otherwise the Snopes
Salami scam happens), and I can't imagine that at the level at which
the OP is working, any subtle control over rounding will be important
(i.e. ROUNDING_CEILING or any such thing).

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to correct decimal addition.

2014-01-25 Thread Keith Winston
On Sat, Jan 25, 2014 at 3:57 AM, spir  wrote:
> Note: AFAIK most financial software use integers for this reason and to
> avoid (or control) rounding errors.

I don't think this is true (no flame intended, hopefully you know I'm
forever in your debt Denis): there's a famous scam where insiders at a
major financial institution set the software so it always rounds down,
and the difference was deposited in their account. It was a matter of
fractions of pennies on a per-scam basis. I'm not certain if this ever
actually happened (I thought it did, but Snopes seems agnostic).

http://www.snopes.com/business/bank/salami.asp

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to correct decimal addition.

2014-01-25 Thread Keith Winston
On Sat, Jan 25, 2014 at 3:57 AM, spir  wrote:
>> .009 to the price, so that people do not have to type the full amount.
>>   Example, 3.49 /gallon would return 3.499 /gallon.
>>
>> This is what I have tried and the results of it.
>>
>> def gas_price(price):
>> price == raw_input("What is the price of gas?")  return price + .09
>>3.49=> 3.4898

I think there's an inconsistency in your post that might confuse the
answers. You mention in the lead that you want to add 9 ONE HUNDREDTHS
of a dollar, or tenths of a cent (which is in fact how gas is priced
in the US, and yes it's crazy stupid). However in your example you add
only tenths, but then in the answer you appear to have added
hundredths, which makes me think that you didn't cut & paste, but
rather retyped (and mistyped).

This will make it a little trickier to use Denis' last idea of using
integers, since you'll have to take them out one more order of
magnitude. If this exercise is later followed by interest
calculations, or anything like that, you might regret limiting your
internal accuracy/representation.

I think that you should probably do your math in floating point (why
get complicated? And you might need the accuracy, for hundredths of
dollars and interest) and then format the output to be what you want.
Watch out for rounding.

>>> p = 3.499
>>> print('{0:.3f}'.format(p))   # format a float with 3 places after the 
>>> decimal
3.499
>>> p = 3.4994
>>> print('{0:.3f}'.format(p))
3.499
>>> p = 3.499
>>> print('{0:.3f}'.format(p))
3.500

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code works in windows command but not ubuntu terminal

2014-01-24 Thread Keith Winston
On Fri, Jan 24, 2014 at 4:50 AM, Steven D'Aprano  wrote:
> Python does not use a search path for the open() function, only for
> imports. With open(), it uses a simple rule:
>
> - absolute paths will look only in that exact location;
>
> - relative paths are always relative to the current working directory.
>
> Do you know the difference between absolute and relative paths?

Ah! I was just running into this... I did not know that. So there's no
way to get it to search a path (other than coding some string
concatenation of path names or something, of course) to open a file?
Well, at least that clears things up for me, I've stumbled over this a
few times and didn't understand. Thanks.


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code works in windows command but not ubuntu terminal

2014-01-24 Thread Keith Winston
I should have mentioned, the other possibility is that the file does
not, in fact, exist, but I assume you put it out there somewhere?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code works in windows command but not ubuntu terminal

2014-01-24 Thread Keith Winston
The file would appear to not be on your search path, that is, in any
directory in which Python is expecting to find it. Either move it to a
directory on your path, or change your path to include it's location.
The easiest way to find out what your path is, that I know, is

import sys
sys.path

Good luck! Warning, I'm still a beginner myself, I might be mistaken
about something... If you don't understand what I'm talking about, try
to be very specific about what you do understand, it'll help people
formulate clear responses.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iter class

2014-01-23 Thread Keith Winston
On Thu, Jan 23, 2014 at 7:05 AM, eryksun  wrote:
> Generally you'll make `__iter__` a generator, so you don't have to
> worry about implementing `__next__`. Also, the built-in function
> `next` was added in 2.6, so you don't have to worry about the method
> name difference between 2.x and 3.x, either.

I'm now realizing I don't understand this comment at all. First, there
IS a __iter__ method in the example: does the presence of such make it
a generator already, or is it a usage thing, or something else? I
don't yet completely understand the difference/point... or maybe you
mean inherit the generator class?

Second: you state that I don't have to worry about the name
difference, but when I changed the method name from next to __next__
it worked in 3.3. So what's your point here?

I'm just realizing I'm missing your pearls of wisdom, not intending on
being combative or something.
-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iter class

2014-01-23 Thread Keith Winston
On Thu, Jan 23, 2014 at 1:36 PM, Devin Jeanpierre
 wrote:

> Again, nothing was incorrect about the example. Every iterator has
> this "problem".

Hmmm. Well, here's what he actually said about that example, since I
don't think I've explained correctly:

*
With iterators, one thing to watch out for is the return of self from
the __iter__ function. You can all too easily write an iterator that
isn't as re-usable as you think it is. For example, suppose you had
the following class:

{my example here}

This works just like you'd expect as long as you create a new object each time:

>>> for i in MyTrickyIter(['a', 'b']):
...   for j in MyTrickyIter(['a', 'b']):
...  print i, j
a a
a b
b a
b b

but it will break if you create the object just once:

{my example here, yielding only a single a b from the above loop}
**

The difference essentially comes down to the line

...  self.thelist = thelist  # in the "broken" example, vs.

...  self.thelist = iter(thelist)  # the "better" way to do it,
restarts the iterator each time a new loop uses it

I'm pretty sure I'm not really saying this right, it takes time
(apparently, for me) to understand how to speak clearly of these
things. The more important element, of course, is when my fuzzy
speaking speaks to fuzzy thinking, of which I am grateful for
correction.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iter class

2014-01-23 Thread Keith Winston
On Thu, Jan 23, 2014 at 7:05 AM, eryksun  wrote:
> Generally you'll make `__iter__` a generator, so you don't have to
> worry about implementing `__next__`. Also, the built-in function
> `next` was added in 2.6, so you don't have to worry about the method
> name difference between 2.x and 3.x, either.

Yes, the exercise was about implementing an iter incorrectly, to see
the difference. But I don't really understand your second point: when
I changed the method name, it worked...?


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iter class

2014-01-23 Thread Keith Winston
On Thu, Jan 23, 2014 at 3:09 AM, Peter Otten <__pete...@web.de> wrote:
> But why not install Python 2.7 on your machine, too? That would allow you
> run the examples as is.

Y'know, it's funny, but I have 2.7 installed. But since I was almost
certain it was a 2to3 kind of problem, I wanted to figure it out. Ok,
maybe... get you all to figure it out :)  That said, I did spend a
while poking around trying to figure it out.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iter class

2014-01-23 Thread Keith Winston
On Thu, Jan 23, 2014 at 5:56 AM, spir  wrote:
> Yes, but that way others learn as well :-) And many people prefere learning
> via human interaction then dealing with arid texts

Well, you caught me. I do run out of steam just plowing through
lessons & such: it really helps to have actual humans to interact with
(well, as far as I know you're all actual humans... I can think of
Tutor as a kind of Turing test :)  I know that some people may prefer
fewer rather than more posts on the list, but I subscribe to your
"others learn as well" approach: I read all the posts and answers
here, including those that are above my understanding, and often get
little tidbits of insight. And I really can't rave too much about how
helpful people are here. That said, I have been trying to be a little
less dominating of the list!

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iter class

2014-01-22 Thread Keith Winston
On Thu, Jan 23, 2014 at 12:21 AM, Devin Jeanpierre
 wrote:
> in Python 3, it should be __next__, not next.

Ah! That's it! Thanks!!!

> I'd suggest staying away from any old blog posts and articles, unless
> you'd care to learn Python 2.x instead of 3.x. ;)

Yeah, but this is a REALLY GOOD resource. But your point is
well-taken: on the simple stuff, i.e. print statements, I can see the
difference quickly. I suppose I should practice running my questions
on old code through 2to3 before I pester the Tutor list, since that's
probably also a good way to learn the differences.

Thanks for your help.
-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] iter class

2014-01-22 Thread Keith Winston
I'm working my way through some of the examples in

http://ivory.idyll.org/articles/advanced-swc/#list-comprehensions

And tried this one:

>>> class MyTrickyIter:
...   def __init__(self, thelist):
...  self.thelist = thelist
...  self.index = -1
...
...   def __iter__(self):
...  return self
...
...   def next(self):
...  self.index += 1
...  if self.index < len(self.thelist):
... return self.thelist[self.index]
...  raise StopIteration

FYI, this is supposed to be an example of how NOT to do an iterator,
because of the way it handles thelist (which is supposed to be an
iteratable construct, like a list, if I'm not confused).

Anyway, my efforts to recreate the following example:

>>> mi = MyTrickyIter(['a', 'b'])
>>> for i in mi:
...   for j in mi:
...  print i, j

which should result in

a b

instead results in

Traceback (most recent call last):
  File "", line 1, in 
for i in mi:
TypeError: iter() returned non-iterator of type 'MyTrickyIter'

I'm sort of wondering if there's a Py2 vs. Py3 issue here, but I don't see it.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stuck on Challenge in Google Python Class

2014-01-22 Thread Keith Winston
On Wed, Jan 22, 2014 at 6:40 AM, Alan Gauld  wrote:
>>  else:
>>return ' '
>
>
> Notice that this return will throw you out of the function so
> you don't process any more strings. You might like to look
> at 'continue' as an alternative.

You actually don't need to do anything with this "else", and it's at
the end of the loop. You can just fall through to the next iteration.
Of course, others have already addressed the real problems (which were
few: you're close)


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to print certain elements

2014-01-21 Thread Keith Winston
If you are playing around at the Python prompt (the >>>), which you
really should be to get the hang of this stuff, you might notice that
the bracket indexing that you and everyone is talking about works both
on strings (Y) and on lists (X: in this case, a list of strings). They
may not behave the same way as you expect. Try to imagine what Y[13]
or X[3][3] would get you, and why.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string indexing

2014-01-19 Thread Keith Winston
On Sun, Jan 19, 2014 at 3:50 PM, Alan Gauld  wrote:
>> How would Python know whether you want find for gettext, mmap, str,
>> xml.etree.ElementTree.Element or xml.etree.ElementTree.ElementTree?
>
>
> Absolutely, but a newbie doesn't even guess that more than one find would
> exist. Or even that there would need to be more than one.

That's exactly it. I'm just getting to the point of being able to
understand how much I don't know, and (I'm only a little embarrassed
to admit) Alan's empty-string example was an "ah-ha" moment for me. I
expect Help will be a great deal more useful now (of course, as I type
that I realize I could have used the class name, help(str.find),
instead of an impromptu instance. Another little ah-ha). And of
course, the instant I understood all that, the point that Mark made
became obvious. But I didn't see it before.


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string indexing

2014-01-19 Thread Keith Winston
On Sun, Jan 19, 2014 at 11:33 AM, Alan Gauld  wrote:
 help(''.find)
> Help on built-in function find:

Erm, getting what you want from help can be work.

Help(find)  #  doesn't work at all.

What Alan did above was create an empty string, by using two single
quotes next to each other ('', not to be confused with a single double
quote, "), and then seek Help on it's method "find" (methods are
accessed by following an object, in this case the empty string, with a
period, and the method name... in actual use there would be further
parenthesis, but for Help you don't use them)... hence

Help(''.find)

Also, Alan's really right on getting used to playing with bits and
pieces at the >>> prompt, you'll be amazed at how much you can do
there. Just don't try to write lengthy programs there, save those as
files and edit them separately.


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Python as Teaching Language

2014-01-19 Thread Keith Winston
On Sun, Jan 19, 2014 at 11:55 AM, Alan Gauld  wrote:
> It has reached the point that I'm back to looking for a new teaching
> language. In Python 3 the decision has clearly been made to focus on
> supporting Python's role as a professional software engineering language
> at the expense of being a successor to ABC or for use in CP4E etc.
> That's a fair enough decision but it does mean Python is no longer the
> easiest option for non Comp Sci beginners. It's not worse than the others
> but it's no longer clearly superior. (IMHO at least! )
>
> But what else is there? that's the problem :-(

Hi Alan, since this is off-topic from it's original thread, but I
wanted to respond to it, I popped it into a new thread, I hope you
don't mind (original was subject "iterators").

I can imagine what you mean about a teaching language, and while I
don't 1) teach CS or 2) know Python like you do... AND I don't know
the alternatives... it still feels like the cleanest, most
user-friendly language I've ever worked with. Anyway, there's
something to be said for letting novices play with real tools: instead
of coming to the end of their one-semester computer class feeling like
they just played with legos, they can feel like they got some (minor)
feel for building a house.

An interesting question is, what's the goal (for those students,
probably the majority in a required comp sci course) who aren't going
to do a lot of programming in the future ? I can think of a few: help
people expand/develop/reflect on their ability to think in various
ways; depressurize fear around programming/computers; give them a leg
up in approaching the vast range of computer-supported tools in many
fields... Anyway, I'm sorta loving this language, and it feels like a
decent way "in" to all of those goals.

There are two caveats: one is, without this tutor list (and to a
lesser extent, perhaps because I've relied on this so much), other
online resources (stack overflow, the Python IRC channels, etc), it
would be much harder to make sense of. But those are there, and don't
seem in immediate danger of disappearing.

And the second... the documentation. I really want to love the
documentation, but I can't. I can't maneuver through it hardly at all
(if I'm trying to find something in the documentation, I almost always
search it from Google), it often doesn't give any examples in the
places I want them, and assumes an understanding I don't have at a
given moment. I'm SO GRATEFUL to all the people who have contributed
to the language, including the documentation, and don't imagine I
could do better, I just notice that I haven't figured out how to make
it work for me.

Now, to a large degree this is not the documentations' fault: I forget
things I just read 10s ago, and then I'll charge off to learn a topic
far more advanced than I'm reasonably ready for. I have an iterative
learning process which involves not understanding a disconcerting
amount of what's in front of me. I don't actually think it's optimal,
but I literally can't stand (what feels like) the slow, plodding
forward approach that is the alternative generally offered. I think
there is often a mismatch between teaching structures/approaches, and
peoples (very personal, often ill-understood and ill-developed)
learning styles.

The other thing I wonder about is how to make the learning process
more interactive/social: that is, so many of the questions that (even
more novice than me) people bring here are things like error statement
meanings, etc. In many cases IMO, the first 10 minutes of frustration
around something like that can be enough to leave a lasting bad taste.
I've gotten some very fast responses around here, and immediate ones
on the IRC (which I've only used a little): I believe quick feedback
to be crucial to the learning process, and yet we are often trained,
in school and elsewhere, to smoulder in frustration around things we
don't know yet, I believe (or to just give up and feel stupid)... I
don't know whether social platforms will translate to a greater
readiness to seek help in order to really learn, or just to learn to
fill in the blanks faster/"cheat" better. Teaching is hard.

And a last note on feedback: having the interpreter available is a
definite plus for Python, though learning to disassemble one's
confusion into little pieces that you can test methodically is hard.
But another good skill...

Sorry for the length.

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterators

2014-01-19 Thread Keith Winston
On Sun, Jan 19, 2014 at 2:02 PM, Oscar Benjamin
 wrote:
> I think that's just an editing mistake. If you replace the word "iterator"
> with "construct" then it makes sense: We have seen that the for statement is
> such a construct.

Fair enough. Thanks. But I think that it underlines the ease with
which the language is used loosely, which does get confusing quickly
when one is still putting together the concepts. I really appreciated
your lengthy post distinguishing iterators from iterables, and I'm
going to go back over it someday that I'm not sick and I have a spare
neuron or two.


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterators

2014-01-19 Thread Keith Winston
Well, as usual thanks for all this, it's really great. I'd worked out
that it was a distinction between iterators and iterables, though I'm
going to Oscar's description a few more times: most of it made sense,
but there are subtleties.

For example, this from the Python 3.3 tutorial:

We say such an object is iterable [referring to "range"], that is,
suitable as a target for functions and constructs that expect
something from which they can obtain successive items until the supply
is exhausted. We have seen that the for statement is such an iterator.
The function list() is another; it creates lists from iterables:

Now, everything we've said thus far would not have led me to believe
that one would call the for statement an iterator... is this just
very, very loose use of the term (in the Python documentation!), or am
I still missing something biggish?

K
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterators

2014-01-18 Thread Keith Winston
On Sat, Jan 18, 2014 at 2:19 PM, eryksun  wrote:
> `xrange` and 3.x `range` aren't iterators. They're sequences. A
> sequence implements `__len__` and `__getitem__`, which can be used to
> implement an iterator, reversed iterator, and the `in` operator (i.e.
> `__contains__`).

I'm so glad you said this, I'm sorta burned out right now trying to
read all this, and I got sorta confused by that part. But what you're
saying is what I thought I understood.

Okay, now your example is pretty interesting. I guess it makes sense
that iter() returns a type iterator. Sure, of course.

Thanks as always to everyone, this is a trove. I'm a bit under the
weather so I'll have to come back and read it closer. I'm a little
clearer, though, and not just on iterators...

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterators

2014-01-18 Thread Keith Winston
On Sat, Jan 18, 2014 at 4:22 AM, Chris “Kwpolska” Warrick
 wrote:
> Here is a poor man’s pure-python re-implementation of `for`:
> https://gist.github.com/Kwpolska/8488091

This will be very handy the next time I run out of for's, or have a
surplus of while's. Fairly common.

Seriously though, thanks for your comments.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] iterators

2014-01-18 Thread Keith Winston
I don't really get iterators. I saw an interesting example on
Stackoverflow, something like

with open('workfile', 'r') as f:
for a, b, c in zip(f, f, f):


And this iterated through a, b, c assigned to 3 consecutive lines of
the file as it iterates through the file. I can sort of pretend that
makes sense, but then I realize that other things that I thought were
iterators aren't (lists and the range function)... I finally succeeded
in mocking this up with a generator:

gen = (i for i in range(20))
for t1, t2, t3 in zip(gen, gen, gen):
print(t1, t2, t3)

So I'm a little more confident of this... though I guess there's some
subtlety of how zip works there that's sort of interesting. Anyway,
the real question is, where (why?) else do I encounter iterators,
since my two favorite examples, aren't... and why aren't they, if I
can iterate over them (can't I? Isn't that what I'm doing with "for
item in list" or "for index in range(10)")?

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] lambdas, generators, and the like

2014-01-16 Thread Keith Winston
On Thu, Jan 16, 2014 at 5:44 AM, spir  wrote:
> This, in addition to the requirement of uniqueness which as you say is
> probably best met using a set (after filter). This may lead to you chosing
> to store, even if otherwise not truely necessary. An question is: what kind
> of data are combinations, and how do you compare them? If there is a
> possibly cheap shortcut by comparing only a little bit of combination data,
> then you may make a set of those little bits only and avoid storing the
> whole of combinations.


Hmmm. My guess is you're reaching for a teachable moment here... I
ended up leaving this entire approach behind, for what I think is your
point: I can simply iterate through the combinations and test them
before I even get to the next one. Sadly, this didn't nearly address
my problem, which I think is that my solution set is still ending up
N^2 time on a rather large data set. Danny offered a different
approach entirely, which I haven't implemented. I THINK that I
optimized this approach by not using any lists, testing iterations as
they were generated, changing my data order so I generate shorter
combinations first, and I STILL couldn't get past something like the
first 3 coins out of 8. It's all good, I learned a lot in the process.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 115, Issue 28

2014-01-16 Thread Keith Winston
On Wed, Jan 15, 2014 at 6:12 AM, Steven D'Aprano  wrote:
> You're selling youself short. From what I've seen of you on this list,
> you might be a beginner, but you've got the right sort of inquiring mind
> to go far as a programmer.

Thanks Steven, I've abruptly gotten clear how much work I have ahead
of me, but that's fine, I'll get as far as I get as fast as I get
there... Reading your modules is really quite informative, btw, your
commenting is both helpful and exemplary, it's already started
changing the way I program, vastly for the better. I always thought I
liked end-of-line comments, so I can see program flow without
comments, but inline commenting can be done in a way to vastly enhance
readability, I see now. Anyway, I'm playing with the Google examples a
bit right now, just to get more practice. I'm hoping to try something
a little bigger soon.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-13 Thread Keith Winston
s*** just got real.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-13 Thread Keith Winston
Yikes, Peter, that's scary. Wow.

On Mon, Jan 13, 2014 at 1:22 PM, Peter Otten <__pete...@web.de> wrote:
> Peter Otten wrote:
>
>> Emile van Sebille wrote:
>>
>>> On 01/12/2014 12:21 PM, Peter Otten wrote:
>>>
>>> test("axbxc", "abc")
 True
>>> test("abbxc", "abc")
 False

 Is the second result desired?
>>>
>>> No -- the second should match -- you found a test case I didn't...
>>>
>>> def test(a,b):
>>>for ii in a:
>>>  if ii not in b: a=a.replace(ii,"")
>>>  while ii+ii in a: a=a.replace(ii+ii,ii)
>>>return b in a
>>>
>>> Show me another.  :)
>>
> def test(a,b):
>> ...for ii in a:
>> ...  if ii not in b: a=a.replace(ii,"")
>> ...  while ii+ii in a: a=a.replace(ii+ii,ii)
>> ...return b in a
>> ...
> test("abac", "abc")
>> False
>
> In the mean time here is my candidate:
>
> def test(a, b):
> a = iter(a)
> return all(c in a for c in b)
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Euler Spoiler

2014-01-13 Thread Keith Winston
Ah, I got through it. Yes, I started down this path, but didn't dot
the i's. Thanks. I'm going to do some more reading on dynamic
programming...

Keith

On Mon, Jan 13, 2014 at 12:51 PM, Keith Winston  wrote:
> Danny, thanks for that exposition. I don't have time to absorb it
> yet,though I will attempt to soon, but I wanted to thank you for your
> effort in the meantime.
>
> Keith



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-13 Thread Keith Winston
On Mon, Jan 13, 2014 at 1:14 AM, Roelof Wobben  wrote:
> I have read all comments and im a little bit confused.
> About which script are we talkimng about. I have seen a lot.


I am talking about the script/approach I posted. Others have posted
other scripts. Hopefully you have the capacity, with whatever approach
to reading email you have, to go back and look over messages?

There is some confusion because your original message specified that
order was important, though the examples you gave did not indicate
that (in fact, contradicted it). Also, there was never anything
specified about repeated letters: what would be the result of
fix_machine("letr", "letter") (not to be confused with
fix_machine("letter", "letr"), which would definitely be "letr").

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Euler Spoiler

2014-01-13 Thread Keith Winston
Danny, thanks for that exposition. I don't have time to absorb it
yet,though I will attempt to soon, but I wanted to thank you for your
effort in the meantime.

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Euler Spoiler

2014-01-12 Thread Keith Winston
Thanks everyone, things to chew on. I'll look at the other itertools
functions mentioned. I did solve Proj. Euler 15 & 18 (and it's
corresponding 67), one more elegantly than the other, and I have given
some thought to how to break this one down, but haven't figured it out
yet. I think I might not be willing to wait a trillion years. I think
I'm going to stop development on this approach, both 1) because I
don't think it's going to work, and 2) because I might have learned
most of what I can from it, re: Python skills.

I am quite interested in the dynamic programming approach, which I
understand my approach to PE 18 was consistent with, but which I don't
yet understand how to apply more broadly or consistently. I'll do some
reading on it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Euler Spoiler

2014-01-12 Thread Keith Winston
I'm working through some of the Project Euler problems, and the
following might spoil one of the problems, so perhaps you don't want
to read further...


The problem relates to finding all possible combinations of coins that
equal a given total. I'm basically brute-forcing it, which is probably
not the way to go, but has already taught me a good bit about sets,
tuples, and iterators, so... so far so good.

However, after all the refactoring I can think of, I can't get it past
a 3-coin list without it bogging down.

I'm sure there are wholly different approaches, feel free to hint at
them, but my real question is: is there any further fine-tuning of my
approach (or any outright problems with it) that would be instructive?
Thanks!

Also: I think it might have worked better with lists that tuples,
though I don't really understand why, unless I misunderstand speed or
memory management issues (or something else).

from itertools import combinations

coins = [100, 50, 20]  # should include 1, 2, 5, 10 (plus one 200 combo)
ans = set()
goal = 200
tcombo = ()

# Iterate over all possible length combinations of coins
for i in range(len(coins)):
print(i)
# For each unique combo of coins, and...
for combo in combinations(coins, i+1):
tcombo = ()
# For each coin in that combo...
for coin in combo:
# create a new tuple of as many of those coins as
# it would take to reach the goal
tcombo = tcombo + (coin,) * int(goal/coin)
# with this new extended list, generate all possible
length combinations
for k in range(len(tcombo)):
for c in combinations(tcombo, k + 1):
if sum(c) == goal:
ans = ans | {c}

print(ans)


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-12 Thread Keith Winston
On Sun, Jan 12, 2014 at 2:22 PM, Keith Winston  wrote:
> There's another approach, I think, that's quite easy if order IS important.

Alas, there's one further problem with my script, relating to testing
multiple sequential letters in product... but I'm not going to say
more, I'll leave it as a problem for the OP. It's an easy fix once you
understand the issue.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-12 Thread Keith Winston
On Sun, Jan 12, 2014 at 2:38 PM, Keith Winston  wrote:
> Sigh and this line needs to read (if it's going to do what I said):

As  Alan pointed out, the examples provided do NOT account for order,
so if one uses my (corrected) algorithm, you get different results
from the examples. Without the fix you get the example results, but
may not realize that it's not accounting for repeats in that case
(which the instructions don't address either). It might be
instructive, if it's not already obvious, to understand why this would
be...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-12 Thread Keith Winston
On Sun, Jan 12, 2014 at 2:22 PM, Keith Winston  wrote:
> if test:

Sigh and this line needs to read (if it's going to do what I said):

if test != -1:



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-12 Thread Keith Winston
OOps, I never used the "success" boolean in my code, but forgot to
remove it. Sorry.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-12 Thread Keith Winston
On Sun, Jan 12, 2014 at 7:44 AM, Alan Gauld  wrote:
> OK< So there is nothing here about the orders being the same.
> That makes it much easier.


There's another approach, I think, that's quite easy if order IS important.

Iterate through the letters of product, find() them initially from the
beginning of debris, and then from the index of the last letter found.
Accounts for multiples in product, & order.

def fix_machine(debris, product):
index = 0
success = False
for letter in product:
test = debris.find(letter, index)
if test:
index = test
else:   # Failure
return "Give me something that's not useless next time."
return product   # Success

I suspect this could be done in one line, without regex, but it would
probably take me a week to figure out... maybe next week ;)

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] lambdas, generators, and the like

2014-01-12 Thread Keith Winston
Thanks Dave, that looks like a good idea, I've played a little with
one-line generators (? the things similar to list comprehensions), but
I'm still wrapping my head around how to use them. Meanwhile I'm
reorganizing my code because I now understand better how to use
iterators (i.e. the combinations function), and I'm exploring using
tuples where I can instead of lists... if I followed an earlier
conversation properly, I think garbage collection might happen more
immediately with immutables than mutables, and this program is
crashing either Python or my entire computer every time I run it...
I'm generating a LOT of combinations.

On Sun, Jan 12, 2014 at 9:33 AM, Dave Angel  wrote:
>  Keith Winston  Wrote in message:
>> I've got this line:
>>
>> for k in range(len(tcombo)):
>> tcombo_ep.append(list(combinations(tcombo, k+1)))
>>
>> generating every possible length combination of tcombo. I then test
>> them, and throw most of them away. I need to do this differently, it
>> gets way too big (crashes my computer).
>>
> You should learn how to write and use a generator. Anytime you
>  find yourself creating a huge list, and only navigating it once,
>  consider writing a generator instead. A generator is any function
>  that has a yield in it. You can turn the loop above into a
>  one-level generator by
>
> def gen (tcombo):
> for k in range (len (tcombo))
>   yield list (combinations (tcombo, k+1))
>
> And depending how you use the nested list, remove the call to list
>  () for some real serious space savings.
>
> (untested)
>
>
>
>> any help will be appreciated. I don't really understand lambda
>> functions yet, but I can sort of imagine they might work here
>> somehow... or not.
>>
> A lambda is seldom necessary or useful in simple programs.
>>
>
>
> --
> DaveA nr
>
>
>
> Android NewsGroup Reader
> http://www.piaohong.tk/newsgroup
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] lambdas, generators, and the like

2014-01-12 Thread Keith Winston
On Sun, Jan 12, 2014 at 4:19 AM, Alan Gauld  wrote:
> lambdas are just a shortcut for single expression functions.
> You never need them, they just tidy up the code a bit by
> avoiding lots of use-once short functions.


Thanks, I figured out how to iterate the combinations function. I'll
play with lambda functions some other time. I've been cranking away on
the Project Euler stuff, it's great fun, good Python practice...

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] lambdas, generators, and the like

2014-01-12 Thread Keith Winston
I've got this line:

for k in range(len(tcombo)):
tcombo_ep.append(list(combinations(tcombo, k+1)))

generating every possible length combination of tcombo. I then test
them, and throw most of them away. I need to do this differently, it
gets way too big (crashes my computer).

I'm going to play some more, but I think I need to test the
combinations as they're generated... and then only add them to a list
(probably better: a set) if they meet a requirement (something like
sum(specific.combination(tcombo) == goal)) AND if they are not already
part of that list (the uniqueness issue is why a set might be better)

I'm partially asking in order to clarify the question in my mind, but
any help will be appreciated. I don't really understand lambda
functions yet, but I can sort of imagine they might work here
somehow... or not.

Thanks!

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 115, Issue 28

2014-01-11 Thread Keith Winston
On Sat, Jan 11, 2014 at 7:37 PM, Alan Gauld  wrote:
> In other words, think about the design of your code don't
> just type randomly.


I prefer the "million monkeys at a million typewriters" approach to
coding...  But then, it's all I've tried...


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Question

2014-01-10 Thread Keith Winston
Amy, judging from Danny's replies, you may be emailing him and not the
list. If you want others to help, or to report on your progress,
you'll need to make sure the tutor email is in your reply to:

Often, people prefer you to respond to the list, if there isn't
something particularly personal in your response. Good luck with
learning Python, it's great language, and this is a very helpful
group. I do realize that learning your first computer language can be
disorienting.

Keith

On Fri, Jan 10, 2014 at 2:57 PM, Danny Yoo  wrote:
> I repeat my question in the hopes that you read it.  Do you have other
> examples of functions you have written or seen?
>
> I ask this because if you have never seen a function definition, our advice
> is radically different than if you have.
>
> Just giving us the homework statement is fairly useless to us: how does that
> help us figure out what part **you** are having difficult with?
>
> On Jan 10, 2014 11:25 AM, "Amy Davidson"  wrote:
>>
>> hi Danny,
>>
>> Below are the instructions.
>>
>> Write a function called printID that takes a name and student number as
>> parameters and prints them to the screen.
>>
>> E.g.:
>> >>> printID("Andrew Joe", 10055) #note the second parameter must be of
>> >>> type int
>>   "Student Name: Andrew Joe"
>>   "Student Number: 10055"
>> On Jan 10, 2014, at 2:14 PM, Danny Yoo  wrote:
>>
>> Hi Amy,
>>
>> Have you seen any other examples of functions in your instruction, either
>> in your books or notes?
>>
>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Question

2014-01-10 Thread Keith Winston
Amy, be aware that there are slightly different versions of Python
floating around, and the example Dayo gave you uses a slightly
different print statement (no parens) than the example you provided
(which probably indicates that your Python requires them).

Good luck, you're on your way!

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Question

2014-01-10 Thread Keith Winston
Amy, you may want to get a little clearer on the difference between
defining a function, and calling one. The definition is sort of a
generic process, it's when you are calling it that you really fill in
the blanks, and the function does what it's designed for (whether you
like it or not!).

You might even try breaking it down a little further, maybe write a
function with just one parameter, and call it a few times to get the
hang of it. In fact, try calling some of the built-in functions (for
example, you can get the length of a string s = "hello" by calling
'len(s)'). You can do all this at the python prompt, but as things get
more complicated it's less frustrating to do it saved to a file (are
you doing all this in IDLE?).

keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursion depth

2014-01-09 Thread Keith Winston
On Thu, Jan 9, 2014 at 5:41 AM, Steven D'Aprano  wrote:
>
> Keith, if you are able, and would be so kind, you'll help solve this
> issue for Dave if you configure your mail client to turn so-called "rich
> text" or formatted text off, at least for this mailing list.

Well, hopefully this is plain text. It all looks the same to me, so if
gmail switches back, it might go unnoticed for a while. Sorry for the
incessant hassle.


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] garbage collecting

2014-01-08 Thread Keith Winston
On Thu, Jan 9, 2014 at 12:27 AM, eryksun  wrote:

> The old float freelist was the same design as the one for 2.x int
> (PyInt, not PyLong), which grows without bound. The design also
> allocates objects in 1 KiB blocks (approx. size). glibc's malloc will
> use the heap for a block that's this small.
>

Thanks Eryksun, pretty sure that's more than I could have known to ask
about garbage collection. But who knows where it will come in handy?


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursion depth

2014-01-08 Thread Keith Winston
On Wed, Jan 8, 2014 at 6:16 PM, Dave Angel  wrote:

> I can't see the bodies of any of your messages (are you perchance posting
> in html? ),  but I think there's a good chance you're abusing recursion and
> therefore hitting the limit much sooner than necessary. I've seen some code
> samples here using recursion to fake a goto,  for example.  One question to
> ask is whether each time you recurse, are you now solving a simpler
> problem.
> For example,  when iterating over a tree you should only recurse when
> processing a SHALLOWER subtree.
>

Hi Dave: I've been taken to task so often here about having unnecessary
chaff in my email replies, that I started getting in the habit of deleting
everything (since gmail by (unadjustable) default quotes the entire message
string unless you highlight/reply). Since I look at messages in a threaded
manner, I wasn't really realizing how much of a pain that was for others.
I'm trying to  re-establish a highlight/reply habit, like this.

I don't THINK I'm misusing recursion, I think I'm just recursing ridiculous
things. The problem came in creating palindrome numbers. Apparently, if you
add a number to it's reversal (532 + 235), it will be a palindrome, or do
it again (with the first result)... with the only mysterious exception of
196, as I understand it. Interestingly, most numbers reach this palindrome
state rather quickly: in the first 1000 numbers, here are the number of
iterations it takes (numbers don't get credit for being palindromes before
you start):

{0: 13, 1: 291, 2: 339, 3: 158, 4: 84, 5: 33, 6: 15, 7: 18, 8: 10, 10: 2,
11: 8, 14: 2, 15: 8, 16: 1, 17: 5, 19: 1, 22: 2, 23: 8, 24: 2}

Zero stands for where I ran out of recursion depth, set at the time at
9900. Except for the first zero, which is set at 196. It's sort of
fascinating: those two 24's both occur in the first 100.

So it hardly ever takes any iterations to palindromize a number, except
when it takes massive numbers. Except in the single case of 196, where it
never, ever happens apparently (though I understand this to not be proven,
merely tested out to a few million places).

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursion depth

2014-01-08 Thread Keith Winston
On Wed, Jan 8, 2014 at 5:15 PM, spir  wrote:

> Funny and useful exercise in recursion: write a func that builds str and
> repr expressions of any object, whatever its attributes, inductively. Eg
> with
>

Hmm, can't say I get the joke. I haven't really played with repr, though I
think I understand it's use. Could you give an example, I'm not sure I
understand the goal?


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursion depth

2014-01-08 Thread Keith Winston
On Wed, Jan 8, 2014 at 4:23 PM, eryksun  wrote:

> You can create a worker thread with a larger stack using the threading
> module. On Windows the upper limit is 256 MiB, so give this a try:
>


quite excellent, mwahaha... another shovel to help me excavate out the
bottom of my hole... I'll play with  this someday, but maybe not today. I
seem to be pushing some dangerous limits. Which does happen to be a hobby
of mine.


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursion depth

2014-01-08 Thread Keith Winston
On Wed, Jan 8, 2014 at 3:42 PM, Emile van Sebille  wrote:

>
> Without seeing your code it's hard to be specific, but it's obvious you'll
> need to rethink your approach.  :)



Yes, it's clear I need to do the bulk of it without recusion, I haven't
really thought about how to do that. I may or may not ever get around to
doing it, since this was primarily an exercise in recursion, for me...
Thanks for your thoughts.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] garbage collecting

2014-01-08 Thread Keith Winston
On Wed, Jan 8, 2014 at 3:30 PM, Oscar Benjamin
wrote:

> The garbage collector has nothing to do with the memory usage of immutable
> types like ints. There are deallocated instantly when the last reference
> you hold is cleared (in CPython). So if you run out of memory because of
> them then it is because you're keeping them alive in your own code. Running
> the garbage collector with gc.collect cannot help with that.
>

Well that's sort of interesting... so it's different for mutables? huh.
Anyway, I think I got what I can reasonably hope to get from this question,
thanks to you and everyone!

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] recursion depth

2014-01-08 Thread Keith Winston
I've been playing with recursion, it's very satisfying.

However, it appears that even if I sys.setrecursionlimit(10), it blows
up at about 24,000 (appears to reset IDLE). I guess there must be a lot of
overhead with recursion, if only 24k times are killing my memory?

I'm playing with a challenge a friend gave me: add each number, up to 1000,
with it's reverse, continuing the process until you've got a palindrome
number. Then report back the number of iterations it takes. There's one
number, 196, that never returns, so I skip it. It's a perfect place to
practice recursion (I do it in the adding part, and the palindrome checking
part), but apparently I can't help but blow up my machine...

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] garbage collecting

2014-01-08 Thread Keith Winston
Well, thanks everyone. I get the picture. And there's nothing subtle going
on here: I'm playing around, trying to factor million-digit numbers and the
like. No biggie, this was interesting.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-08 Thread Keith Winston
Yes, I did read the context manager stuff, but I can only absorb a bit of
it, I just don't have the background. It's getting better though. Plus I
think most things will come only after I play with them, and I haven't
really played much with wrappers, decorators and the like. Which is fine,
the year is young. I've just knocked off the first 11 Euler project
problems, which forced me to do a bunch of things for the first time
(mostly quite uglily).

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] garbage collecting

2014-01-08 Thread Keith Winston
well, fair enough. Generally, the issue involves instances when Python will
come back, but it might take several minutes or much longer. And weird
behaviour ensues: like timers I put on the program don't actually time the
amount of time it's busy (by a very, very large margin). Also, often
several minutes after such a thing (sometimes quite a bit later), things
will suddenly start working quickly again. Also, on my laptop I can
actually tell when it's struggling, b/c the fan turns on and/or speeds up,
and in many of  these cases it will go into all-out mode, even though I'm
not doing anything. But your point about having no lever with which to move
the world is a good one.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] garbage collecting

2014-01-07 Thread Keith Winston
Iirc, Python periodically cleans memory of bits & pieces that are no longer
being used. I periodically do something stupid -- I mean experimental --
and end up with a semi-locked up system. Sometimes it comes back,
sometimes everything after that point runs very slowly, etc.

I just saw where I could do os.system('python'), but in restarting the
interpreter I'd lose everything currently loaded: my real question involves
merely pushing the garbage collector into action, I think.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
I'm also happy to note that the sieve I adapted from Jorge generates a list
of primes the same length as yours, which would seem to imply it's correct,
and in 33s, though since it's timed by a different mechanism that may not
mean anything...


On Tue, Jan 7, 2014 at 10:36 PM, Keith Winston  wrote:

> Hey Steven,
>
> That's a cool primes module, I'm going to look that over more carefully. I
> can see that you've thought through this stuff before ;)
>
> And yeah, I'd like to see your Stopwatch code... I haven't looked at
> "with" yet, that's interesting. As usual, I don't totally get it...
>
> Keith
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
Hey Steven,

That's a cool primes module, I'm going to look that over more carefully. I
can see that you've thought through this stuff before ;)

And yeah, I'd like to see your Stopwatch code... I haven't looked at "with"
yet, that's interesting. As usual, I don't totally get it...

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
oops, I'm sorry I didn't realize Danny's message to me was private, but
you're right that's better than publishing this right out.

Also: although the sqrt(n) algorithm worked to solve the problem, it isn't
actually correct. There are cases in which it will fail, many in fact.
Oops. One would need to take the Sieve all the way up to n/m for it to work
in this simple version, where m is the lowest prime factor of the number
(which this algorithm WILL always find). There's a nice recursive version
in there somewhere.

Keith



On Tue, Jan 7, 2014 at 7:17 PM, Alan Gauld wrote:

> On 07/01/14 21:22, Keith Winston wrote:
>
>  Note that his code doesn't really (need to) create a sieve of
>> Eratosthenes all the way to n, but only to sqrt(n). It then tests for
>> divisibility.
>>
>
> I'm not sure what you mean here.
> His algorithm was using an array of booleans to indicate whether a number
> was prime. How does building a list up to sqrt(n) identify primes above
> sqrt(n)?
>
> For example if n is 100 how do you detect that 97 is prime
> if you only build a sieve up to 10?
>
> I know you can find the highest prime factor without finding all the
> primes themselves but that's exactly the kind of alternative algorithm
> Euler is looking for. But then it's no longer using Jorge's algorithm,
> which is to test all numbers for primeness then find the highest one that
> is a factor of n, is it?
>
> Ah, OK a light bulb just went on. Amazing what happens when you start
> typing your thoughts! What you mean is to build a seive to identify all
> primes up to sqrt(n) and then test those primes as factors. I had thought
> you intended testing *all* numbers up to sqrt(n) then seeing if they were
> prime. Quite different...
>
> As you say, it's maybe a matter of defining 'tuning' versus creating
> an entirely new algorithm! ;-)
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
Sorry for the blank message.

I was just going to say that I fixed my version of Eratosthenes' algorithm,
but Danny's is still faster in all cases.

Also, Jorge: I hope it's obvious that I'm kidding around, I wouldn't want
you to feel uncomfortable with asking your questions just because I'm being
goofy.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
On Tue, Jan 7, 2014 at 5:45 PM, Keith Winston  wrote:

> Hey Danny,
>
> I think you could use the same sqrt(n) on your algorithm to reduce the
> search space. I think you could also increment n += 2 to skip even numbers,
> the simplest of sieves.
>
> I think the sieve concept is based on the idea that adding is much less
> intensive than dividing, so creating the sieve is fairly quick compared to
> all those divides. that said, I might put a timer on your algorithm and
> compare them!
>
> Oops: I just did it. Yours won, .23s to .34s. What's more, on certain
> prime numbers (with large factors), mine breaks. well never mind then. I'm
> blaming Jorge.
>
> Dammit: I forgot to include the i += 2 suggestion I made in the above test
> (one also has to start i at 3, hopefully obviously). That improves your
> time to .11s. Poor Jorge.
>
> Keith
>
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
Hey Danny,

I think you could use the same sqrt(n) on your algorithm to reduce the
search space. I think you could also increment n += 2 to skip even numbers,
the simplest of sieves.

I think the sieve concept is based on the idea that adding is much less
intensive than dividing, so creating the sieve is fairly quick compared to
all those divides. that said, I might put a timer on your algorithm and
compare them!

Oops: I just did it. Yours won, .23s to .34s. What's more, on certain prime
numbers (with large factors), mine breaks. well never mind then. I'm
blaming Jorge.

Dammit: I forgot to include the i += 2 suggestion I made in the above test
(one also has to start i at 3, hopefully obviously). That improves your
time to .11s. Poor Jorge.

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
In fact, I just used it to solve a number 3 orders of magnitude larger than
600851475143, the number from prob 3. It took 12s. I hardly dare go further
than that... I'm not arguing that there's a big list being built in there...

Oops, I dared. 5 orders of magnitude bigger crashes my machine.

Oops oops, it finished. It says it took 161 seconds, but in fact it sort of
half-crashed my machine for the last 30 minutes...

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
um, I used his code, slightly fine-tuned it, and got the solution in
.35 seconds (running time, not fine-tuning time ;). On my dinky old
notebook. So I'm inclined to believe it is possible... Though perhaps my
sense of what "fine-tuning" entails doesn't mesh with yours... spoiler
alert, more below.














Note that his code doesn't really (need to) create a sieve of Eratosthenes
all the way to n, but only to sqrt(n). It then tests for divisibility.
Though it is in this that some of the problems lie with the original code.
I'm happy to share my revision with anyone that wants it. It is pretty
rough, consistent with my Python (and math!) skills... it's really quite
close to his code.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
I think your approach is fine, you might need to fine tune your algorithm.

hint below.











if you want it: is_p doesn't need to be nearly as big as you specify. There
are a couple other minor problems.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OverflowError: cannot fit 'long' into an index-sized integer

2014-01-07 Thread Keith Winston
I had heard of Project Euler long ago, but completely forgotten it. It
looks fun!! Thanks for reminding me of it.

Keith


On Tue, Jan 7, 2014 at 5:58 AM, eryksun  wrote:

> On Tue, Jan 7, 2014 at 4:49 AM, Jorge L.  wrote:
> >
> > When i test that script against 600851475143 I get the following error
>
> You're trying to create a list with over 600 billion items.
> sys.maxsize is a bit over 2 billion for 32-bit CPython, but switching
> to 64-bit won't help unless you have a few terabytes of memory (8
> bytes per pointer). You need to rethink your approach to generating
> primes.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: arrangement of datafile

2014-01-06 Thread Keith Winston
Amrita, it doesn't seem like the code you are providing is the code you are
running. I wonder if you are running it all at the Python command line or
something, and have to type it in every time? You should put it in a file,
and save & run that file,  and then cut and paste it directly into your
emails, so we can see what you're actually running. There are a number of
small things in the code you've posted that wouldn't run, I think...

Keith


On Mon, Jan 6, 2014 at 3:57 AM, Amrita Kumari  wrote:

> Hi Steven,
>
> I tried this code:
>
> import csv
> with open('file.csv') as f:
>  reader = csv.reader(f)
>  for row in reader:
>  print(row)
>  row[0] = int(row[0])
>
> up to this extent it is ok; it is ok it is giving the output as:
>
> ['1' , ' GLY' ,  'HA2=3.7850' ,  'HA3=3.9130' , ' ' , ' ' , ' ' , ' ']
> [ '2' ,  'SER' ,  'H=8.8500' ,  'HA=4.3370' ,  'N=115.7570' , ' ' , ' ' ,
> ' ']
> --
> ---
> but the command :
>
> key, value = row[2].split('=', 1)
> value = float(value.strip())
> print(value)
>
> is giving the value of row[2] element as
>
> ['1' , ' GLY' ,  'HA2=3.7850' ,  'HA3=3.9130' , ' ' , ' ' , ' ' , ' ']
> 3.7850
> [ '2' ,  'SER' ,  'H=8.8500' ,  'HA=4.3370' ,  'N=115.7570' , ' ' , ' ' ,
> ' ']
> 8.8500
> 
> --
> so this is not what I want I want to print all the chemical shift value of
> similar atom from each row at one time
>
> like this:
>
> 1 HA2=3.7850
> 2 HA2=nil
> 3 HA2=nil
> .
> 
> ..
> 13 HA2=nil
>
> similarly, for atom HA3:
>
> 1 HA3=3.9130
> 2 HA3=nil
> 3 HA3=nil
> ...
> 
> 
> 13 HA3=nil  and so on.
>
> so how to split each item into a key and a numeric value and then search
> for similar atom and print its chemical shift value at one time along with
> residue no..
>
> Thanks,
> Amrita
>
>
>
>
>
> On Mon, Jan 6, 2014 at 6:44 AM, Steven D'Aprano wrote:
>
>> Hi Amrita,
>>
>> On Sun, Jan 05, 2014 at 10:01:16AM +0800, Amrita Kumari wrote:
>>
>> > I have saved my data in csv format now it is looking like this:
>>
>> If you have a file in CSV format, you should use the csv module to read
>> the file.
>>
>> http://docs.python.org/3/library/csv.html
>>
>> If you're still using Python 2.x, you can read this instead:
>>
>> http://docs.python.org/2/library/csv.html
>>
>>
>> I think that something like this should work for you:
>>
>> import csv
>> with open('/path/to/your/file.csv') as f:
>> reader = csv.reader(f)
>> for row in reader:
>> print(row)
>>
>> Of course, you can process the rows, not just print them. Each row will
>> be a list of strings. For example, you show the first row as this:
>>
>> > 2,ALA,C=178.255,CA=53.263,CB=18.411,,
>>
>> so the above code should print this for the first row:
>>
>> ['2', 'ALA', 'C=178.255', 'CA=53.263', 'CB=18.411', '', '', '',
>> '', '', '', '', '', '']
>>
>>
>> You can process each field as needed. For example, to convert the
>> first field from a string to an int:
>>
>> row[0] = int(row[0])
>>
>> To split the third item 'C=178.255' into a key ('C') and a numeric
>> value:
>>
>> key, value = row[2].split('=', 1)
>> value = float(value.strip())
>>
>>
>>
>> Now you know how to read CSV files. What do you want to do with the data
>> in the file?
>>
>>
>>
>> --
>> Steven
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: arrangement of datafile

2014-01-06 Thread Keith Winston
oops, I see Steven pointed out a much cleaner approach. Oh well. Shock &
surprise ;)

Keith


On Mon, Jan 6, 2014 at 3:27 AM, Keith Winston  wrote:

> Hi Amrita: I tried to figure out, for kicks, how to do what I THINK is
> what you're trying to do... I've never even opened a .txt file in Python
> before, so you can take all this with a big grain of salt... Anyway, if you
> take your example of your original database:
>
> 1 GLY HA2=3.7850 HA3=3.9130
> 2 SER H=8.8500 HA=4.3370 N=115.7570
> 3 LYS H=8.7530 HA=4.0340 HB2=1.8080 N=123.2380
>  4 LYS H=7.9100 HA=3.8620 HB2=1.7440 HG2=1.4410 N=117.9810
> 5 LYS H=7.4450 HA=4.0770 HB2=1.7650 HG2=1.4130 N=115.4790
> 6 LEU H=7.6870 HA=4.2100 HB2=1.3860 HB3=1.6050 HG=1.5130 HD11=0.7690
> HD12=0.7690 HD13=0.7690 N=117.3260
> 7 PHE H=7.8190 HA=4.5540 HB2=3.1360 N=117.0800
> 8 PRO HD2=3.7450
> 9 GLN H=8.2350 HA=4.0120 HB2=2.1370 N=116.3660
> 10 ILE H=7.9790 HA=3.6970 HB=1.8800 HG21=0.8470 HG22=0.8470 HG23=0.8470
> HG12=1.6010 HG13=2.1670 N=119.0300
> 11 ASN H=7.9470 HA=4.3690 HB3=2.5140 N=117.8620
> 12 PHE H=8.1910 HA=4.1920 HB2=3.1560 N=121.2640
> 13 LEU H=8.1330 HA=3.8170 HB3=1.7880 HG=1.5810 HD11=0.8620 HD12=0.8620
> HD13=0.8620 N=119.1360
>
> I put it in a file ashift.txt. Then:
>
> f = open('ashift.txt', 'r')
> lines = f.readlines()
>
> Now I could iterate through lines (it is a list of strings, one per line),
> but I just shortcut to play with a single line:
>
> tshift = lines[0]
> tshift = tshift.replace("=", ":")
> tshift = tshift.splitlines()  # remove the final \n
> tshift = tshift.split(" ")
>
> At which point we have something like this:
>
> ['1', 'GLY', 'HA2:3.7850', 'HA3:3.9130']
>
> I am out of time, plus I'm very conscious of doing this INCREDIBLY
> ineptly. I have spent a bit of time trying to sort out the right way, there
> might be some approach involving dialects associated with the csv module,
> but I couldn't sort that out. If one could massage the above line (or the
> original file) into
>
> [1, 'GLY', {'HA2' : 3.7850, 'HA3' : 3.9130}]
>
> This is what I'd talked about before, and would make reaching your final
> output pretty easy, following the stuff I said above.
>
> I KNOW there's a much, much easier way to do this, probably a one-liner
> (at least for the file parsing).
>
> You talked about printing this stuff out, but if you are going to process
> it further (analyzing it in some way, for example) there might be
> implications as to how you proceed with this.
>
> Keith
>
>


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: arrangement of datafile

2014-01-06 Thread Keith Winston
Hi Amrita: I tried to figure out, for kicks, how to do what I THINK is what
you're trying to do... I've never even opened a .txt file in Python before,
so you can take all this with a big grain of salt... Anyway, if you take
your example of your original database:

1 GLY HA2=3.7850 HA3=3.9130
2 SER H=8.8500 HA=4.3370 N=115.7570
3 LYS H=8.7530 HA=4.0340 HB2=1.8080 N=123.2380
 4 LYS H=7.9100 HA=3.8620 HB2=1.7440 HG2=1.4410 N=117.9810
5 LYS H=7.4450 HA=4.0770 HB2=1.7650 HG2=1.4130 N=115.4790
6 LEU H=7.6870 HA=4.2100 HB2=1.3860 HB3=1.6050 HG=1.5130 HD11=0.7690
HD12=0.7690 HD13=0.7690 N=117.3260
7 PHE H=7.8190 HA=4.5540 HB2=3.1360 N=117.0800
8 PRO HD2=3.7450
9 GLN H=8.2350 HA=4.0120 HB2=2.1370 N=116.3660
10 ILE H=7.9790 HA=3.6970 HB=1.8800 HG21=0.8470 HG22=0.8470 HG23=0.8470
HG12=1.6010 HG13=2.1670 N=119.0300
11 ASN H=7.9470 HA=4.3690 HB3=2.5140 N=117.8620
12 PHE H=8.1910 HA=4.1920 HB2=3.1560 N=121.2640
13 LEU H=8.1330 HA=3.8170 HB3=1.7880 HG=1.5810 HD11=0.8620 HD12=0.8620
HD13=0.8620 N=119.1360

I put it in a file ashift.txt. Then:

f = open('ashift.txt', 'r')
lines = f.readlines()

Now I could iterate through lines (it is a list of strings, one per line),
but I just shortcut to play with a single line:

tshift = lines[0]
tshift = tshift.replace("=", ":")
tshift = tshift.splitlines()  # remove the final \n
tshift = tshift.split(" ")

At which point we have something like this:

['1', 'GLY', 'HA2:3.7850', 'HA3:3.9130']

I am out of time, plus I'm very conscious of doing this INCREDIBLY ineptly.
I have spent a bit of time trying to sort out the right way, there might be
some approach involving dialects associated with the csv module, but I
couldn't sort that out. If one could massage the above line (or the
original file) into

[1, 'GLY', {'HA2' : 3.7850, 'HA3' : 3.9130}]

This is what I'd talked about before, and would make reaching your final
output pretty easy, following the stuff I said above.

I KNOW there's a much, much easier way to do this, probably a one-liner (at
least for the file parsing).

You talked about printing this stuff out, but if you are going to process
it further (analyzing it in some way, for example) there might be
implications as to how you proceed with this.

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: arrangement of datafile

2014-01-05 Thread Keith Winston
Amrita, on a closer read of your very first post I (think I) see you
already successfully read your data into a series of dicts (mylist in your
example), so if you still want the output you posted in the first post,
then you can do some version of the loops that I described. That said, I'm
sure Stephen is right about the csv module having helpful tools for parsing
that original file, if you're not past that point. Anyway, if you had all
your mylist in a list of lists (NOT a dict, as you have them) then getting
the output you wanted seems easy. HOWEVER: I don't think you want to strip
off the first two numbers, since I think the first one is critical to your
final listing, no? I might be beating a tired horse here, but you could get
your desired output from such a list of lists like this (I modified the
names, and added back in that first number to the output)

for i in mylist_list:
for atom in mylist_list[i][2]:
print(mylist_list[i][0], atom, " = ",
mylist_list[i][2][atom])  # output something like "2 C = 178.255"

This is pretty ugly, but you get the idea. As I mentioned before, putting
it all into a class would allow you to do this more robustly, but I'll
probably lead you astray if I expand on that.

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: arrangement of datafile

2014-01-05 Thread Keith Winston
I should have included an example. If you can, and if it doesn't make your
file too long, and if I'm right that this is easy to do in the output
module of wherever this is coming from, add some white space so you can
read/debug easier, though it's not at all necessary (strings have to be
quoted also: see below):

[2, ALA, {C: 178.255, CA: 53.263, CB: 18.411,,}]

This is ready to be accessed: If I do this at the command prompt:

shift = [2, "ALA", {"C": 178.255, "CA": 53.263, "CB": 18.411}]

Then:

shift[0] returns 2
shift[2]['CA'] returns 53.263

And if you had a bunch of these in a list shift_list[] (like your original
data set), you could do things like

for i in shift_list:
for atom in shift_list[i][2]:
return shift_list[i][2][atom]

I didn't check this code, it's pretty much guaranteed to be wrong but I
think it might point in the right direction.

I think I made this a little more complicated than it needs to be, but I
have to run right now. Maybe this is helpful. Good luck!

Actually, I think shift needs to be a class... but that's just my nascent
OOP comment.

Keith




On Sun, Jan 5, 2014 at 3:01 PM, Keith Winston  wrote:

> Hi Amrita, I'm just a beginner but I notice that, after the first two
> entries on each line (i.e. 10,ALA), the rest might fit nicely into a dict,
> like this {H: 8.388, HB1: 1.389, ...}. That would give you a lot of
> flexibility in getting at the values later. It would be easy enough to
> replace the "=" with ':", and add some curly braces. In fact, if you
> enclosed each line in square braces, changed =/: and added the curly braces
> on the dict, then each line would already be a list containing a
> dictionary, and you'd be ready to do some rearranging very easily.
>
> Whether you do that in Python or when you are building your file in
> whatever system it's coming from is your call. If you left off the outer
> braces, each line is a tuple containing a dict, which works too.
>
> Sorry if all I've done is state the obvious here. I warned you I'm a
> beginner.
>
>


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: arrangement of datafile

2014-01-05 Thread Keith Winston
Hi Amrita, I'm just a beginner but I notice that, after the first two
entries on each line (i.e. 10,ALA), the rest might fit nicely into a dict,
like this {H: 8.388, HB1: 1.389, ...}. That would give you a lot of
flexibility in getting at the values later. It would be easy enough to
replace the "=" with ':", and add some curly braces. In fact, if you
enclosed each line in square braces, changed =/: and added the curly braces
on the dict, then each line would already be a list containing a
dictionary, and you'd be ready to do some rearranging very easily.

Whether you do that in Python or when you are building your file in
whatever system it's coming from is your call. If you left off the outer
braces, each line is a tuple containing a dict, which works too.

Sorry if all I've done is state the obvious here. I warned you I'm a
beginner.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More or less final Chutes & Ladders

2014-01-05 Thread Keith Winston
On Sun, Jan 5, 2014 at 2:52 AM, Mark Lawrence wrote:

> Homework for you :)  Write a line of code that creates a list of say 3 or
> 4 integers, then write a line that creates a tuple with the same integers.
>  Use the dis module to compare the byte code that the two lines of code
> produce.  The difference is interesting.



Well... that was a very interesting assignment, though I'm going to have to
chew on it for a while to understand. I can see that the processing code
for a tuple is considerably shorter... it is processed in a gulp instead of
bite by byte... it doesn't have the "Build List" step at all (what goes on
inside of THAT?)... but I can't claim to really understand what I'm looking
at.

I notice, for example, if I include only constants (immutable types) in my
tuple, then it does that gulp thing. If I include a list in there too, all
hell breaks loose, and suddenly I'm Building Tuples (what goes on inside of
THAT?). A tuple of tuples still goes down in a single swallow, of course.

Sadly, you can see how my mind works here... hey, this was FUN! You can
assign me homework any time, teach!

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More or less final Chutes & Ladders

2014-01-04 Thread Keith Winston
Thanks all, interesting. I'll play more with tuples, I haven't knowingly
used them at all...

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-04 Thread Keith Winston
Hi Danny, no, I don't think there's any disk access, and the memory of the
two machines is rather different: one is 4 Gb or so, the other 9 changing
to 12 any day... but I think I haven't been rigorous enough to justify a
great deal more attention here. I am convinced that I should just keep
developing my next project, and my programming skills, and worry about
speed issues as I hit them. I was overreaching, or anticipating or
something...


On Sat, Jan 4, 2014 at 10:30 PM, Danny Yoo  wrote:

> There's an assumption in the question here that all programs are CPU bound.
>
> I actually do not think so.  From prior discussion about what the
> program is doing, I got the impression that it was trying to hold
> gigabytes of data in RAM.  Isn't that still true?  If so, then I would
> be very surprised if the program were not thrashing virtual memory.
> Under such conditions, give up on any assumptions about program speed
> being related to CPU speed.  It's hitting disk hard, and that's a Game
> Over.  Under heavy virtual memory swapping conditions, it doesn't
> matter how fast your CPU is: the time that your program is taking is
> due to the physical act of moving spindles and spinning disks of metal
> around.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More or less final Chutes & Ladders

2014-01-04 Thread Keith Winston
Thanks again Denis, I might just have to ruminate on this, but I am
definitely having an allergic reaction.

I understand that Python doesn't have composite objects, but neither does
it dislallow my list of lists of ints and lists... which is, I imagine,
very space efficient. I think what you are in essence saying is that it's a
mistake for me to worry about space at the expense of clarity... ok, but if
I really don't need to break out those single lists ever, to speak of... it
seems like I've vastly enlarged my array for little gain.

I'm not meaning to argue, but to understand. Especially in lieu of an
upcoming project with, perhaps, larger and more complex structures. I am
increasingly curious about whether namedtuples are a good strategy for some
of this: they store their field names, as I understand it, and I can live
with an immutable type in all these cases: I wonder if they are as
efficient in named-field (key) lookup as dictionaries?

I'm also a bit confused here: obviously tuples are immutable, but one can
use lists in them... I think that makes those lists' contents immutable?
And could one define a namedtuple that included lists that were different
lengths for different instantiations (like my game results, for example)? I
really should be playing with them instead of asking questions, at this
point...

Thanks as always!

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python problems on android

2014-01-04 Thread Keith Winston
Well, I probably can't help you, I haven't installed SL4 (yet), and am a
Python beginner myself anyway. I imagine others might be more prepared to
help you with a copy of the script.

However: something about the way you are responding to this thread keeps
breaking it, so you end up starting a new thread (you've started three).
That's a little hard to keep track of, and there are those here who truly
hate that kind of thing. This message, for example, started a new thread
(at least for me, I assume others), but your last reply didn't, so if you
know what you did (or didn't do) that time, do that from now on!

My only thought on the problem is: what is the script doing with the input?
Maybe for some reason a number works in that context, but a letter doesn't?
Even just including a few lines of the code around the input statement
might be better than nothing.

keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More or less final Chutes & Ladders

2014-01-04 Thread Keith Winston
Thanks Alan & Denis: Alan, the improvement you suggested had already been
made, and adopted. Good catch.

Denis: alas, there are chutes and ladders dicts, but I guess your chutes &
ladders lists are local to the results class... Your suggestion is quite
shocking to me, I wouldn't have thought of creating a class for results...
I guess it allows clearer modularity of the final candl_array? I don't
really get it... I think you are using it, essentially, for nothing other
than a data structure, right? And some cleaner print options, though I have
only looked at the raw game data for debugging... it's a great suggestion,
obviously, because I am a little dumbfounded by it, and it's making me
think.

My initial reaction is concern about having too many classes, but I don't
really have any sense of how important that is. I was playing with storing
ChutesAndLadders instances in my game array, but of course they include all
their methods, etc: all kinds of overhead (at least, that's my impression),
which is why I created the results method, so I could just pass a... list?
composite object? Collection? I can't really sort out what the latter two
mean in Python, and must be looking in the wrong place... while I was
researching I found out about namedtuple(), which seems like a promising
structure for game data, but I haven't really looked into it. It might also
be a collection...

The entire game is to be played in bulk (that is, it's really a statistical
foray, albeit a silly one), so the candl_array might get large (perhaps
millions of "records" -- results lists). Is there some way the Results
class helps that?

keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python problems on android

2014-01-04 Thread Keith Winston
Perhaps you could include the script?


On Sat, Jan 4, 2014 at 5:47 AM,  wrote:

>
>
> Ok. Will try and explain the problem.
> I wrote a script in python and found I could use it on my android phone
> with SL4a.
> It was really useful.
> Haven't used it for a few months.
> A few days ago I decided to improve it and found it no longer works.
> the problem seems to be that when it reaches an input statement it will
> only accept a number.
> If I try to input a letter I get an error message the same as if I had
> just typed the letter into the command line.
> I am not sure what has happened, it used to work ok.
>
> Is there another way of getting input into my script without
> using.input?
>
> Or better still does anyone understand what is going wrong?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-04 Thread Keith Winston
Thanks to both of you. In this particular case, the main use of eval() was
only for 2 calls, which were essentially hard-coded (you could see the
calls to summarize_game in my code). I was looking for a more general
solution to what I was trying to do, but I don't need it for this project.
Still, this has been an informative conversation.


On Sat, Jan 4, 2014 at 12:56 AM, Steven D'Aprano wrote:

> On Sat, Jan 04, 2014 at 12:32:19AM -0500, Keith Winston wrote:
> > On Fri, Jan 3, 2014 at 11:59 PM, Steven D'Aprano  >wrote:
> >
> > > thelist = vars()[name]
> >
> >
> > I see: vars() certainly looks less dangerous than eval(), but I'm
> guessing
> > that's still smelly code? I hadn't known about vars() or I probably would
> > have used it.
>
> Yes, it's still a bit smelly: but only a bit, since while "direct" code
> is the idea, sometimes the only way to do things is with one (or two)
> layers of indirection.
>
> Code should (as a general rule) not rely on, or be affected by, the name
> of the variable. Functions which inspect the running environment (i.e.
> peek deep inside the interpreter) or use eval or other techniques to
> operate "behind the scenes" on *names* rather than values can often lead
> to confusing code. As debugging tools, they're useful. Putting such
> functionality inside normal everyday programs is a code smell.
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Copying [was Re: What's in a name?]

2014-01-03 Thread Keith Winston
Thanks for all this. I ended up using

newdict = dict(olddict), which seemed to work fine. I hadn't heard about
the copy module until now. I had heard about deep/shallow copies, though in
this particular example (all int dicts), I don't think there's a
difference...?


On Sat, Jan 4, 2014 at 12:50 AM, Mark Lawrence wrote:

> On 04/01/2014 05:44, Steven D'Aprano wrote:
>
>> On Fri, Jan 03, 2014 at 01:53:42PM -0500, Keith Winston wrote:
>>
>>  That's what I meant to do: make a copy when I wrote chute_nums = chutes.
>>> So
>>> I should have passed chute_nums to summarize_game, but it still wouldn't
>>> work (because it's not a copy).
>>>
>>
>> Python never makes a copy of objects when you pass them to a function or
>> assign them to a name. If you want a copy, you have to copy them
>> yourself:
>>
>> import copy
>>
>> acopy = copy.copy(something)
>>
>>
>> ought to work for just about anything. (Python reserves the right to not
>> actually make a copy in cases where it actually doesn't matter.)
>>
>> There are a couple of shortcuts for this:
>>
>> # copy a dictionary
>> new = old.copy()
>>
>> # copy a list, or tuple
>> new = old[:]  # make a slice from the start to the end
>>
>>
>>
> Please be aware of the difference between deep and shallow copies see
> http://docs.python.org/3/library/copy.html
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask what
> you can do for our language.
>
> Mark Lawrence
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 11:59 PM, Steven D'Aprano wrote:

> thelist = vars()[name]



I see: vars() certainly looks less dangerous than eval(), but I'm guessing
that's still smelly code? I hadn't known about vars() or I probably would
have used it.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple arg problem

2014-01-03 Thread Keith Winston
Hi Steven,

tarray = CandL_Array(100)

Yes, that's definitely better. I'll make that change. Thanks, makes sense.
I'd already posted my "finished" version, so I probably won't repost with
this small change right now.

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] More or less final Chutes & Ladders

2014-01-03 Thread Keith Winston
Here is what I think will be about the final version of C and L. I
rearranged it quite a bit (into 2 classes), fixed a bug or two, and
generally cleaned it up a bit. I haven't really polished it, but hopefully
it will be less difficult to read... which is to say, if anyone wants to go
through it AGAIN (at your leisure) I would appreciate comments on style,
etc.

Probably the biggest change is that I added a result() method to the
ChutesAndLadders class, that returns a list of the pertinent attributes of
each game (to be compiled into the array of games results that CandL_Array
class is all about).

Anyway, I sort of need to get off this since I need to do a lot more
reading on this language, though I may be back with early drafts of my
typing tutor before long... we'll see how that goes.

-- 
Keith

""" Chutes & Ladders Simulation
Simulates a number of games of Chutes & Ladders (Snakes & Ladders).
Chutes & Ladders are separate dictionaries to allow tracking of
separate stats.

Gathers the results into a list of lists of individual game results
in the form (per game) of [game_no, moves, [chutes], [ladders]]

"""

import random
from timer2 import timer
from statistics import * # from whence comes mean, variance, stdev


# Landing on a chute causes one to slide down to the corresponding value.
chutes = {16: 6, 47: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73,
95: 75, 98:78}

# Landing on a ladder (key) causes one to climb up to the corresponding
value.
ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91,
80:100}

class ChutesAndLadders:
"""Game class for Chutes & Ladders."""

def __init__(self):
self.reset()

def reset(self):
self.position = 0
self.game_number = 0
self.move_count = 0
self.chutes_list = []
self.ladders_list = []

def results(self):
return [self.game_number, self.move_count, self.chutes_list,
self.ladders_list]

#@timer
def move(self):
"""Single move, with chutes, ladders, & out of bounds.
Primary action is to move self.position, but returns a list
that consists of either the chute or ladder if landed on, if either
"""

roll = random.randint(1,6)
self.move_count += 1
self.position += roll
if self.position in chutes:
self.chutes_list.append(self.position)
self.position = chutes[self.position]
elif self.position in ladders:
self.ladders_list.append(self.position)
self.position = ladders[self.position]
elif self.position > 100:  # move doesn't count, have to land
exactly
self.position -= roll
return

#@timer
def play(self, game_no):
"""Single game"""

self.reset()
self.game_number = game_no
while self.position < 100:
self.move()
return

class CandL_Array:
""" Create & analyze an array of CandL games """

candl_array = []
def __init__(self):
self.candl_array = []

#@timer
def populate(self, gamecount1):
"""populate candl_array with a set of games"""

tgame = ChutesAndLadders()
for i in range(gamecount1):
tgame.play(i)
self.candl_array.append(tgame.results())

def print_stuff(self):
self.print_gameset_stats(self.candl_array)
self.print_candl_info(self.candl_array)

def print_gameset_stats(self, garray):
print("Total number of games: ", len(garray))
print("   MovesChutesLadders")
for func in [mean, max, min, stdev]:
print("{moves:9.2f} {chutes:12.2f} {ladders:13.2f}
{fname}".format(
moves=func(tgset[1] for tgset in garray),
chutes=func(len(tgset[2]) for tgset in garray),
ladders=func(len(tgset[3]) for tgset in garray),
fname=func.__name__
))

def print_candl_info(self, garray):
""" Create two dictionaries with the same keys as chutes & ladders,
but with the total number of times each c or l is traversed (in the
entire gameset)
as the values. Then, print them. """

self.chute_nums, self.ladder_nums = dict(chutes), dict(ladders)
self.summarize_game("chutes", self.chute_nums, 2, garray)
self.summarize_game("ladders", self.ladder_nums, 3, garray)

def summarize_game(self, game_name, game_nums, game_index, garray):

tgame_nums = game_nums
for i in tgame_nums.keys(): game_nums[i] = 0

for corl in tgame_nums:
for game in garray:
tgame_nums[corl] += game[game_index].count(corl)
print("total ", game_name, "= ", sum(tgame_nums.values()))

"""   def timing_report():

print("game.total, count = ", p1.game.total, p1.game.count)
print("move.total, count = ", p1.move.total, p1.move.count)
"""

def run_CandL(gamecount):
tarray = CandL_Array

Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 11:14 PM, Mark Lawrence wrote:

> On 03/01/2014 21:41, Keith Winston wrote:
>
>> --
>> Keith
>>
>>
> Frankly I think you're lining up to jump fences when you're actually
> riding on the flat :)
>

Fair enough,  but I am thinking of the next project as a long-term
dabbling: hopefully my abilities will rise to my  concept... I guess I'm
about 3 weeks into Python (and OOP) so far, of course my ability to focus
on it will depend on work and other pressures, but I'm amazed at how
accessible this language is. Anyway, thanks to you and everyone who've
helped me as I crawl on the flat... this group has been way more than
invaluable.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple arg problem

2014-01-03 Thread Keith Winston
Ah, more briefly: parens. Wow, okay then. Thanks.


On Fri, Jan 3, 2014 at 10:14 PM, eryksun  wrote:

> On Fri, Jan 3, 2014 at 9:56 PM, Keith Winston  wrote:
> >
> > if __name__ == "__main__":
> > tarray = CandL_Array
> > tarray.populate(100)
> >
> > I get an error
> >
> > Traceback (most recent call last):
> >   File "/home/keithwins/Dropbox/Python/CandL8.py", line 127, in 
> > tarray.populate(100)
> > TypeError: populate() missing 1 required positional argument:
> 'gamecount1'
> >>>>
> >
> > Which seems to say it wants another argument, but I am in the habit of
> not
> > counting the self argument... I thought I understood that. I'm sure it's
> > something obvious, but I've been staring at it for hours. This is going
> to
> > be embarrassing...
>
> You've assigned the class to `tarray` instead of assigning an instance
> of the class. Forgetting to call() is a common mistake.
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple arg problem

2014-01-03 Thread Keith Winston
gmail is driving me crazy. Anyway, every time I run it with:

if __name__ == "__main__":
tarray = CandL_Array
tarray.populate(100)

I get an error

Traceback (most recent call last):
  File "/home/keithwins/Dropbox/Python/CandL8.py", line 127, in 
tarray.populate(100)
TypeError: populate() missing 1 required positional argument: 'gamecount1'
>>>

Which seems to say it wants another argument, but I am in the habit of not
counting the self argument... I thought I understood that. I'm sure it's
something obvious, but I've been staring at it for hours. This is going to
be embarrassing...



On Fri, Jan 3, 2014 at 9:53 PM, Keith Winston  wrote:

> I'm trying to rewrite/reshuffle my Chutes & Ladders code, which I
> generally find more confusing than writing anew.
>
> Anyway, I've got a method that seems like it calls for one argument but...
>
> def populate(self, gamecount1):
> """populate candl_array with a set of games"""
>
> (method of a new class CandL_Array, which contains a list called
> candl_array)
>
> Every time I run it with
>
>
> --
> Keith
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] simple arg problem

2014-01-03 Thread Keith Winston
I'm trying to rewrite/reshuffle my Chutes & Ladders code, which I generally
find more confusing than writing anew.

Anyway, I've got a method that seems like it calls for one argument but...

def populate(self, gamecount1):
"""populate candl_array with a set of games"""

(method of a new class CandL_Array, which contains a list called
candl_array)

Every time I run it with


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Truth in advertising: I just realized a Core I7 only benchmarks about 10x
faster than a Core 2 Duo, using Passmark. Wow, something like 6 years newer
and only 10 times? Anyway, I'd STILL expect to see some of that in the
program performance, though maybe once I get it ironed out it will be a
little sleeker...

Keith


On Fri, Jan 3, 2014 at 8:38 PM, Keith Winston  wrote:

> Just to be clear, what I'm asking this typing tutor to do is vastly more
> than normal, albeit still not seemingly very much. In most programs, they
> give you a sentence or paragraph to type, and then time how long it takes.
> I'm talking about timing every keypress, and modifying the text stream
> based on that. The thing that put me on edge was noticing that my simple
> Chutes & Ladders game doesn't go ANY faster on a machine that benchmarks
> perhaps 1000 times faster than another...
>
> Keith
>
>
> On Fri, Jan 3, 2014 at 8:17 PM, Alan Gauld wrote:
>
>> On 03/01/14 21:53, Keith Winston wrote:
>>
>>  Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
>>> but I would expect it easily adapted to QWERTY or anything else.
>>> ...
>>>
>>>
>>> My concern is with speed. This will have to keep up with (somewhat
>>> arbitrarily) fast typing,
>>>
>>
>> Lets see. The speed record for touch typing is around 150 wpm with
>> average word being about 5 chars, so a speed of about 750 cpm
>> or 12.5cps That's about 80ms between letters.
>>
>> Python on a modern PC can probably execute around 100k lines
>> of code(*) per second or 100 per millisecond. That's 8k lines
>> executed between each keypress for the worlds fastest typist.
>>
>> I used  to use a typing tutor that was written in old GW Basic
>> on the original IBM PC (speed 4.7MHz) and it had no problem
>> analyzing my stats (albeit at a modest 40-50 wpm).
>>
>> I'd worry about speed after you find you need to.
>>
>> (*)Caveat: I haven't tried any kind of objective test and
>> of course some Python 'lines' are equal to many
>> lines of simpler languages - think list comprehensions.
>> But in practice I still don't think you will have a
>> big problem.
>>
>>
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>> http://www.flickr.com/photos/alangauldphotos
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Keith
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Just to be clear, what I'm asking this typing tutor to do is vastly more
than normal, albeit still not seemingly very much. In most programs, they
give you a sentence or paragraph to type, and then time how long it takes.
I'm talking about timing every keypress, and modifying the text stream
based on that. The thing that put me on edge was noticing that my simple
Chutes & Ladders game doesn't go ANY faster on a machine that benchmarks
perhaps 1000 times faster than another...

Keith


On Fri, Jan 3, 2014 at 8:17 PM, Alan Gauld wrote:

> On 03/01/14 21:53, Keith Winston wrote:
>
>  Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
>> but I would expect it easily adapted to QWERTY or anything else.
>> ...
>>
>>
>> My concern is with speed. This will have to keep up with (somewhat
>> arbitrarily) fast typing,
>>
>
> Lets see. The speed record for touch typing is around 150 wpm with average
> word being about 5 chars, so a speed of about 750 cpm
> or 12.5cps That's about 80ms between letters.
>
> Python on a modern PC can probably execute around 100k lines
> of code(*) per second or 100 per millisecond. That's 8k lines
> executed between each keypress for the worlds fastest typist.
>
> I used  to use a typing tutor that was written in old GW Basic
> on the original IBM PC (speed 4.7MHz) and it had no problem
> analyzing my stats (albeit at a modest 40-50 wpm).
>
> I'd worry about speed after you find you need to.
>
> (*)Caveat: I haven't tried any kind of objective test and
> of course some Python 'lines' are equal to many
> lines of simpler languages - think list comprehensions.
> But in practice I still don't think you will have a
> big problem.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
Thanks Walter, I think I've got the lay of the land roughly, but my grasp
is still light and imperfect. I'm pretty confident I shouldn't be doing
anything like what you're describing for the level of coding I'm doing, but
it's interesting to see the approach.

Keith



On Fri, Jan 3, 2014 at 6:56 PM, Walter Prins  wrote:

> Hi,
>
> The code in my last post got line wrapped which will break if directly
> tried out.  To avoid possible confusion I paste a version below with
> shorter lines which should avoid the problem:
>
>
> import gc, itertools
>
> def names_of(obj):
> """Try to find the names associated to a given object."""
> #Find dict objects from the garbage collector:
> refs_dicts = (ref for ref in gc.get_referrers(obj)
>   if isinstance(ref, dict))
> #Get a single chained generator for all the iteritems() iterators
> #in all the dicts
> keyvalue_pairs = itertools.chain.from_iterable(
> refd.iteritems() for refd in refs_dicts)
> #Return a list of keys (names) where the value (obj) is the one
> #we're looking for:
> return [k for k, v in keyvalue_pairs if v is obj]
>
> x = []
> y = x
> z = [x]
>
> print names_of(z[0])
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Okay, thanks, I'll probably be proceeding over the next few weeks, as I
finish up my Chutes & Ladders project... I think I have to do a bit more
code/manual reading in proportion to my coding for a bit, also. Thanks for
the insights.

K


On Fri, Jan 3, 2014 at 6:12 PM, spir  wrote:

> On 01/03/2014 10:53 PM, Keith Winston wrote:
>
>> My concern is with speed. This will have to keep up with (somewhat
>> arbitrarily) fast typing, while doing background processing, with a GUI of
>> course.
>>
>
> I wouldn't even bother. Try & see, you may be surprised. There are several
> factors at play:
> * The core processing in dealing with user input (read, decode, store,
> queue key strokes, etc) will be done by low-level (OS) routines written in
> C, with only thin Python wrappers (which essentially translate from/to
> python data types).
> * Similar point for GUI and/or other user interface layer (less so if
> you'd use a pure python GUI framework, but in general they're also just
> wrappers over C code).
> * The ratio between such low-level processing and actual processing code
> written and executed in python for your application logic is certainly high
> (as is usually the case), unless there is much realtime computation you did
> not speak about.
> Anyway, just try and see.
>
> This is similar to how & why python is reputed to be good (read: fast) at
> "number crunching": they are standard libs for that just link to low-level
> C routines which do about all computation, behind the stage, and very few
> application logic remains written *and actually executed* in python (search
> "numpy").
>
> Denis
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Just to be clear: this is equal parts learning Python project, prototype
tutorial software project, OOP practice, and the beginning of a more
general inquiry into learning styles/paradigms/parameters... I'm (slowly)
writing some of these ideas up in a separate doc.


On Fri, Jan 3, 2014 at 4:53 PM, Keith Winston  wrote:

> Shoot, sorry for the empty message. Here's what I was going to say:
>
> I am gearing up for the next project (yeah, an eventual end to Chutes &
> Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
> but I would expect it easily adapted to QWERTY or anything else.
>
> The basic idea is build a database of the key and response time of every
> keystroke, with simultaneous background processing going on, based on a
> customizable set of parameters to select the test text in more or less real
> time. So for example, I might wish to adjust the interval at which I
> revisit old material, to be sure I "get" it without becoming bored by it:
> we could call this the repetition interval, and it might well be a function
> that increases with time, though it might also be keyed to the speed of
> recall... all responses are to be saved long-term for subsequent analysis.
>
> My concern is with speed. This will have to keep up with (somewhat
> arbitrarily) fast typing, while doing background processing, with a GUI of
> course. This illustrates why I was concerned about the fact that my Chutes
> & Ladders game seems to run at the same speed on my 8 y.o. Core 2 Duo and
> my 2 y.o. Core I7 with 3-4x as much memory. This WILL require a faster
> machine and a more significant share of it's resources, if I develop it in
> the direction I am thinking.
>
> I hope Python is a good choice here, though I suppose some modules or
> classes or parts will have to be recoded into something faster... Any
> thoughts on this will be appreciated, including how to structure it in such
> a manner that it might be more portably applied to future versions in
> entirely different knowledge realms (music/midi input,
> language/vocabulary/audio output, etc).
>
> --
> Keith
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Shoot, sorry for the empty message. Here's what I was going to say:

I am gearing up for the next project (yeah, an eventual end to Chutes &
Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
but I would expect it easily adapted to QWERTY or anything else.

The basic idea is build a database of the key and response time of every
keystroke, with simultaneous background processing going on, based on a
customizable set of parameters to select the test text in more or less real
time. So for example, I might wish to adjust the interval at which I
revisit old material, to be sure I "get" it without becoming bored by it:
we could call this the repetition interval, and it might well be a function
that increases with time, though it might also be keyed to the speed of
recall... all responses are to be saved long-term for subsequent analysis.

My concern is with speed. This will have to keep up with (somewhat
arbitrarily) fast typing, while doing background processing, with a GUI of
course. This illustrates why I was concerned about the fact that my Chutes
& Ladders game seems to run at the same speed on my 8 y.o. Core 2 Duo and
my 2 y.o. Core I7 with 3-4x as much memory. This WILL require a faster
machine and a more significant share of it's resources, if I develop it in
the direction I am thinking.

I hope Python is a good choice here, though I suppose some modules or
classes or parts will have to be recoded into something faster... Any
thoughts on this will be appreciated, including how to structure it in such
a manner that it might be more portably applied to future versions in
entirely different knowledge realms (music/midi input,
language/vocabulary/audio output, etc).

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 6:41 AM, Alan Gauld wrote:

> This is off topic but a couple of points about the OOP stuff...
>
>
thanks Alan, this was helpful.



> "If I'm iterating a variable through a series of list names,
> for future processing, I would like to print the name of the
> list the variable is set to in a given moment... "
>
> Remember that variables in Python are just names.
> So we can rewrite your statement as
>
> "If I'm iterating a name through a series of list names, for future
> processing, I would like to print the name of the list the name is set to
> in a given moment... "
>
> And since the list names are just strings we can write:
>
> "If I'm iterating a name through a list of strings, for future processing,
> I would like to print the name in a given moment...
>
> So the answer to your question is just to print the string.
> The real challenge, as we have discovered, is how to access
> the list that is named by the string. And the usual way to
> map strings to objects is via a dictionary not by using eval().
>
>
Here's the thing: I think most of my "problems" go away with better design.
But in case I'm wrong, what I was trying to do, which I would think could
sometimes be helpful, is printing the name of an object along with it's
output/results... I don't think there's any way to do the opposite of
eval(), that is, create a string from an object name. Or am I just missing
something here (I THINK the right way to do this is add, if necessary, and
__name__ method, or at least a .name attribute, to the class... though now
that I think about it I think that still doesn't solve the problem, it
names the class not the instance.

Do you really need the num_xxx variables?
> Using len(xxx_list) is more reliable that depending on your
> code to maintain the values. It may be that you need them
> for a performance optimisation but given that games are
> not normally CPU bound that seems unlikely.
>
>
It was something between performance optimization and historical artifact.
I'm pretty sure the effect of it's optimization was to slow the program
down. It/they are redundant.


>
>  return [tchutes, tladders]  # only one will be != 0
>>
>
> I don't understand the tchutes/tladders stuff? They hold the
> target position or zero (the return comment is wrong BTW since both
> could be zero). Why not just have a single variable called target
> or somesuch? Also if you must return two values its probably better to use
> a tuple rather than a list.
>
>
Oh god, you are airing all my dirty laundry. On each move, the position
might be a chute, or a ladder, or neither. After I use that position to
determine if it's a chute or ladder, it seems like it makes sense to store
that info explicitly, to avoid another dictionary lookup. Probably another
optimization mistake. So if the first returned list entry has a number in
it, it's a chute, and add it to the list of chutes this game traversed, and
same with the second entry and ladder... I suspect I should do this
entirely differently.


>
> Shouldn't the self.position assignment be part of reset()?
>
>
It used to be, but then I realized it's not a state I need to save: I meant
to change it to a local variable.


>
>   while self.position < 100:
>>  gamecandl = self.move()  # [chute, ladder] or [0, 0]
>>  if gamecandl[0] != 0: # populate chutes list
>>  self.chutes_list.append(gamecandl[0])
>>  if gamecandl[1] != 0:  # populate ladders list
>>  self.ladders_list.append(gamecandl[1])
>>
>
> Why don't you do this update of the lists in the move() code.
> It's where it logically happens and saves passing back the
> list/tuple and then having to test it here.  This just adds
> extra work.
>
>
Hmm. That seems like a good point. I think it all shifts when I properly
implement the Game() class. Next draft.


>
>   return [step, self.move_count, self.num_chutes,
>> self.num_ladders, self.chutes_list, self.ladders_list]
>>
>
> In OOP you rarely have to return attributes. And since step
> is passed in as an argument the caller already knows. So I
> don't think you really need to return anything here.


Yes, reading this is what helped me see the direction of the next rewrite.
Thanks.


>
> OK, I see now, you are storing the current state values
> after each game. Personally I'd probably create another
> method called (get_stats() or similar and have play() return
> success/failure.
>
>
o success or failure. You're edging me towards exception handling.

Then your line above would be:
>
> return [self.get_stats() for i in range(gamecount) if self.play()]
>
> It keeps the purpose of the methods explicit. play() plays the game,
> get_stats() returns the data.
>
> But there is another more OOP approach.
> Create a game instance for each iteration.
> Then collect the instances which then hold the data.
> No need for all the extra arrays, return values, etc.
> It's by using and passing

Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 9:03 AM, spir  wrote:

> On 01/03/2014 12:41 PM, Alan Gauld wrote:
>
>>
>>   return [step, self.move_count, self.num_chutes,
>>> self.num_ladders, self.chutes_list, self.ladders_list]
>>>
>>
>> In OOP you rarely have to return attributes. And since step
>> is passed in as an argument the caller already knows [it]. So I
>>
>> don't think you really need to return anything here.
>>
>
Alas, it's uglier than all that, and probably inherently non-OOP organized.
The calling method DOES know the step variable (attribute? it's not part of
a class, is it still an attribute?), since it's using it to iterate through
a list: but that variable is gone by the time the play_game returns, and
yet I want to ensconce it in the data structure to keep track of the
different games... And so I pass it in to save it to the data structure.
It's ugly, and probably not the right way to do that (post script: I think
I figured this out below).

Calling method:
return [self.play_game(i) for i in range(gamecount1)]

   def play_game(self, step):
# various stuff happens, but step is just passed through to be
stored in the structure that the calling method is contributing to
return [step, self.move_count, self.num_chutes, self.num_ladders,
self.chutes_list, self.ladders_list]



> Maybe the intent here (except from the case of step) is to conceptually
> isolate another part of code from the current object (here a 'game'), or
> from this method (play_game). So that don't they interact in a hidden way
> (that one cannot guess from the outside, without reading code in detail).
> In other words, to make code _transparent_, which is indeed a common advice
> (and one I approve).
>
> In this, to have the caller explicitely, obviously read information about
> the 'game' object, one could just:
> return self
>
> However, this makes no sense if the caller the cirrent method, play_game,
> is another method of the 'game' ;-). In this case, indeed return nothing.
>
> (All this, if I correctly understand and interpret.)
>
> Denis


Well, I sort of mangle OOP still. Here's the issue: I have this play_game
method of Game, which returns/fills in the "results" of a game in the form
of a list of ints & lists. What I though I want is to play lots of games,
gather all those game "results" into a big array (just another list really,
of course), and then do stats/analsis on that array. But I think my
thinking is broken here: I am trying to create a list of game results,
whereas I should be creating a list of games (with their corresponding
attributes)... And that should happen altogether outside the Game glass. I
imagine I should have another class for that, say GameArray... but that's
just a first thought on the next reorganization...

So I guess my Game class should have an attribute like game_number,
corresponding to step variable above, and GameArray should do something
like...

game1 = Game() # instance of Game
for i in range(gamecount): game_array[i] = game1.play_game(i)

(inside play_game: self.game_number = i)

And I guess GameArray can hold all the stats/analysis/printing functions,
since that's the object they operate on...

This sounds like the right direction here, but I don't completely trust my
own thinking yet on this stuff. In retrospect, my need for a reset method
probably indicated I was going the wrong direction, and probably popped up
as soon as I tried to deal with a multitude of games within the Game class
itself.

thanks as always!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


  1   2   >