[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] iterators

2014-01-18 Thread Chris “Kwpolska” Warrick
On Sat, Jan 18, 2014 at 9:51 AM, Keith Winston  wrote:
> 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)

For Python 2, use xrange() instead to get an iterator.  In Python 3,
range() is already an iterator.

> 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)")?

range() actually returns a list.  Lists are not iterators, as next(L)
would’ve told you:

In [1]: next([1, 2])
---
TypeError Traceback (most recent call last)
 in ()
> 1 next([1, 2])

TypeError: list object is not an iterator

You can, however, get an iterator of a list, by doing iter(L):

In [2]: iter([1, 2])
Out[2]: 

Moreover:

> The ``for`` statement is used to iterate over the elements of a
> sequence (such as a string, tuple or list) or other iterable object.
(from help('for'))

Basically, this is how `for i in X` works:

1. get an iterator by calling X.__iter__() (equivalent to iter(X))
2. assign `i` to X.next() (or X.__next__() in Python 3; equivalent to next(X))
3. if a `break` statement occurs anywhere, get out of the `for` block;
   elif StopIteration is raised, the `else` block is executed (if any)
 and then the program continues;
   else, go to step 2.

Here is a poor man’s pure-python re-implementation of `for`:
https://gist.github.com/Kwpolska/8488091

This should clear up most of your doubts.

-- 
Chris “Kwpolska” Warrick 
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
___
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 Peter Otten
Keith Winston wrote:

> 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)")?

You can get an iterator from a list or range object by calling iter():

>>> iter([1, 2, 3])

>>> iter(range(10))


Every time you call iter on a sequence you get a new iterator, but when you 
call iter() on an iterator the iterator should return itself.

An iter() call is done implicitly by a for loop, but every time you call 
iter() on a sequence you get a new iterator object. So you can think of the 
for-loop

for item in range(10):
print(item)

as syntactic sugar for

tmp = iter(range(10))
while True:
try:
item = next(tmp)
except StopIteration:
break
print(item)

Back to your zip() example. Here is a possible implementation of zip():

>>> def myzip(*iterables):
... iterators = [iter(it) for it in iterables]
... while True:
... t = tuple(next(it) for it in iterators)
... if len(t) < len(iterators):
... break
... yield t
... 

When you pass it a range object twice there will be two distinct iterators 
in the `iterators` list that are iterated over in parallel

>>> rfive = range(5)
>>> list(myzip(rfive, rfive))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

but when you pass the same iterator twice because 
iter(some_iter) is some_iter 
holds (i. e. the iter() function is "idempotent")

next(iterators[0])

and

next(iterators[1])

operate on the same iterator and you get the behaviour seen at 
stackoverflow:

>>> ifive = iter(range(5))
>>> list(myzip(ifive, ifive))
[(0, 1), (2, 3)]

PS: There is an odd difference in the behaviour of list-comps and generator 
expressions. The latter swallow Stopiterations which is why the above 
myzip() needs the len() test:

>>> iterators = [iter(range(3))] * 10
>>> [next(it) for it in iterators]
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
StopIteration
>>> iterators = [iter(range(3))] * 10
>>> tuple(next(it) for it in iterators)
(0, 1, 2)

With a list-comp myzip could be simplified:

>>> def myzip(*iterables):
... iterators = [iter(it) for it in iterables]
... while True:
... t = [next(it) for it in iterators]
... yield tuple(t)
... 
>>> list(myzip(*[iter(range(10))]*3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]


___
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 spir

On 01/18/2014 09:51 AM, Keith Winston wrote:

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)")?


An iterator is a kind of object that delivers items once at a time. It is to be 
used with python's "for ... in ..." construct.


Concretely, for each pass of such 'for' cycle, python calls the iterator's 
__next__ method. If the call returns an item, it is used in the pass; if the 
call raises StopIteration, then the cycle stops. Here are two examples of 
iterators (first ignore the __iter__ method, see below) and their usage:


==
class Cubes:
def __init__ (self, max):
self.num = 0
self.max = max

def __next__ (self):
if self.num > self.max:
raise StopIteration()
item = self.num * self.num * self.num
self.num += 1
return item

def __iter__ (self):
return self

cubes9 = Cubes(9)

for cube in cubes9:
print(cube, end=' ')
print()

class Odds:
def __init__ (self, lst):
self.idx = 0
self.lst = lst

def __next__ (self):
# find next odd item, if any:
while self.idx < len(self.lst):
item = self.lst[self.idx]
self.idx += 1
if item % 2 == 1:
return item
# if none:
raise StopIteration()

def __iter__ (self):
return self

l = [0,1,2,3,4,5,6,7,8,9,10]
odds = Odds(l)
for odd in odds:
print(odd, end=' ')
print()
==

As you can see, the relevant bit is the __next__ method. This and __iter__ are 
the 2 slots forming the "iterator protocol", that iterators are required to 
conform with.


There is a little subtlety: sequences like lists are not iterators. For users to 
be able to iterate over sequences like lists, directly, *in code*:

for item in lst:
instead of:
for item in iter(lst):
python performs a little magic: if the supposed iterator passed (here lst) is 
not an iterator in fact, then python looks for an __iter__ method in it, calls 
it if found, and if this returns an iterator (respecting the iterator protocal), 
then it uses that iterator instead. This is why actual iterators are required to 
also have an __iter__ method, so that iterators and sequences can be used in 
'for' loops indifferently. Since iterators are iterators, __iter__ just returns 
self in their case.


Exercise: simulate python's iterator magic for lists. Eg make a 'List' type 
(subtype of list) and implement its __iter__ method. This should create an 
iterator object of type, say, ListIter which itself implements the iterator 
protocal, and indeed correctly provides the list's items. (As you may guess, it 
is a simpler version of my Odd type above.) (Dunno how to do that for sets or 
dicts, since on the python side we have no access I know of to their actual 
storage of items/pairs. In fact, this applies to lists as well, but indexing 
provides indirect access.)


[Note, just to compare: in Lua, this little magic making builtin sequences 
special does not exist. So, to iterate over all items or pairs of a Lua table, 
one would write explicitely, resp.:

for key,val in pairs(t)
for item in ipairs(t)
where pairs & ipairs resp. create iterators for (key,val) pairs or indexed items 
of a table (used as python lists or dicts). Functions pairs & ipairs are 
builtin, but it's also trivial to make iterators (or generators) in Lua, since 
it has 'free' objects we don't even need classes for that.]


Now, one may wonder why sequences don't implement the iterator protocal 
themselves (actually, just __next__) and get rid of all that mess? Well, this 
mess permits:
* a variety of traversal, with corresponding different iterators, for the *same* 
(kind of) collections; for instance traversing a list backward, traversing trees 
breadth-first or depth-first or only their leaves, or only nodes with elements...
* the same collection to be traversed in several loops at once (rarely needed, 
but still); concretely nested loops (in princ

Re: [Tutor] iterators -- oops!

2014-01-18 Thread spir

erratum:

On 01/18/2014 12:13 PM, spir wrote:

[Note, just to compare: in Lua, this little magic making builtin sequences
special does not exist. So, to iterate over all items or pairs of a Lua table,
one would write explicitely, resp.:
 for key,val in pairs(t)
 for item in ipairs(t)
where pairs & ipairs resp. create iterators for (key,val) pairs or indexed items
of a table (used as python lists or dicts). Functions pairs & ipairs are
builtin, but it's also trivial to make iterators (or generators) in Lua, since
it has 'free' objects we don't even need classes for that.]


Read instead:

  for _, item in ipairs(t)
  for idx, item in ipairs(t)

Lua's builtin 'ipairs' returns both index and item.
[Never post a piece of code you have not run ;-)]

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


[Tutor] Understanding Decorators

2014-01-18 Thread Reuben
Hi,

I tried reading information regarding decorators - but not able to get a
good grip around it.

Kindly point me to some good links along with examples

Regards,
Reuben
___
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 eryksun
On Sat, Jan 18, 2014 at 4:50 AM, Peter Otten <__pete...@web.de> wrote:
>
> PS: There is an odd difference in the behaviour of list-comps and generator
> expressions. The latter swallow Stopiterations which is why the above
> myzip() needs the len() test:

A comprehension is building a list in a `for` loop, which won't
swallow a `StopIteration` from the body of the loop itself.

For a generator, an unhandled `StopIteration` propagates to the frame
that called `__next__`. In this case the tuple constructor swallows
the `StopIteration`, as it rightly should. There's no way for it know
the original source of the `StopIteration` exception. You'd have to
use a generator that translates `StopIteration` to a custom exception.
Then use that exception to `break` the `while` loop. But no one sane
would go that far.

 def myzip(*iterables):
> ... iterators = [iter(it) for it in iterables]
> ... while True:
> ... t = [next(it) for it in iterators]
> ... yield tuple(t)

The C implementation for `zip.__next__` calls `PyTuple_SET_ITEM` in a
loop over the iterators. It reuses the same tuple so long as the
reference count is only 1. That can't be duplicated in pure Python.
You'd have to use a `list`.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Understanding Decorators

2014-01-18 Thread eryksun
On Sat, Jan 18, 2014 at 12:51 PM, Reuben  wrote:
>
> I tried reading information regarding decorators - but not able to get a
> good grip around it.
>
> Kindly point me to some good links along with examples

Decorators I: Introduction to Python Decorators
http://www.artima.com/weblogs/viewpost.jsp?thread=240808

How can I make a chain of function decorators in Python?
http://stackoverflow.com/a/1594484

What does functools.wraps do?
http://stackoverflow.com/a/309000
___
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 eryksun
On Sat, Jan 18, 2014 at 4:22 AM, Chris “Kwpolska” Warrick
 wrote:
> For Python 2, use xrange() instead to get an iterator.  In Python 3,
> range() is already an iterator.

`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__`).

class Sequence:

def __len__(self):
return 3

def __getitem__(self, k):
if k > 2:
raise IndexError
return k

>>> seq = Sequence()
>>> len(seq)
3

>>> type(iter(seq))

>>> list(seq)
[0, 1, 2]

>>> type(reversed(seq))

>>> list(reversed(seq))
[2, 1, 0]

>>> 0 in seq
True
>>> 3 in seq
False

`xrange` and Py3 `range` both implement the following special methods:

__len__
__getitem__
__iter__
__reversed__

3.x `range` also implements:

__contains__
index
count

Neither supports sequence concatenation or repetition. Both are
manually registered as a subclass of the abstract class
`collections.Sequence`.

>>> issubclass(range, collections.Sequence)
True

http://docs.python.org/3/library/collections.abc
___
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


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


[Tutor] Question in regards to my assignment

2014-01-18 Thread Jackie Canales
I have with my assignment.


class Score:
    'A subclass of the object.'
    
    def __init__(self, init):
        'Sets the initial score to the object and sets the number of scores 
that have contributed to the total to 1.'
        self.x = 1
        self.init = int(init)
        self.total = int(init)
        
    
    def updateOne(self, amount=0):
        'Increases the total score of the object by amount and Increases the 
number of scores contributing to the total by 1.'
        self.x += 1
        self.total += amount
        return self.total
    
    def updateMany(self, lst=0):
        'Updates the total by the sum of all the scores in the list and number 
of scores contributing to the total by the number of items found in the list.'
        self.x += len(lst)
        self.total += sum(lst)
        return self.total

    
    def get(self):
        'Returns the current score in the object.'
        return self.total

    def average(self):
        'Returns the average of the scores that have contributed to the total 
score.'
        return self.total/self.x

    def __repr__(self):
        'Returns the canonical representation of the object.'
        return repr(self.total)
    
def processScores(filename):
    infile = open(filename, 'r')
    line = infile.readlines()
    infile.close()
    
   
    lineNum = 0
    s = Score(0)

    for item in line2:
        lineNum += 1
        
        if lineNum == 1:
            s.total = int(item)
            print("Score set to total value:", s.total)
        elif lineNum % 2:
            s.total = int(item)
            if type(item) == list:
                lstNum = s.updateMany(s.total)
                print("List detected. Updating many. Total outcome:", lstNum)
            else:
                intNum = s.updateOne(s.total)
                print("Numeric detected. Updating One. Total outcome:", intNum)
        else:
            pass
    print("The Final Score is:", s.get())
    print("The Average Score is:", s.average())
    print("The Score Object is:", s.__repr__())


The file that I am trying read is a text file call score:
5
o 
7
o 
10
m 
[3, 12, 1]
o
8
M 
[1, 2, 3]

The instruction for the assignment are as followed
The first line of the file is a number, which indicates the initial score for a 
Score object.  The remaining lines are pairs: the even-numbered lines contain a 
character and the odd-numbered lines contain either a number or a list.  The 
character will be one of 'o', 'O', 'm', or 'M', indicating that the next line 
contains either a single score ('o'  or 'O') or a list of scores ('m' or 'M').  
The function will create a new Score object and then process each line or pairs 
of lines of the file by calling the appropriate method of the Score object.  As 
it processes each line or pairs of lines, it will print the information about 
the action being taken.  The first line will be a call to the constructor and 
the remaining pairs of lines will be calls either to the updateOne() or 
updateMany()methods.  Once the file has been processed, the function will print 
the final score, the average score, and return the Score object.


The error i am getting is:

Traceback (most recent call last):
  File "", line 1, in 
    processScores('scores.txt')
  File "C:/Users/Michael/Documents/DePaul/tutor/hw2_practice.py", line 52, in 
processScores
    s.total = int(item)
ValueError: invalid literal for int() with base 10: '[3, 12, 1]\n'

So from my understanding when my code tries to read the first line with a list 
it is not able to read ''[3, 12, 1]\n'" because its not able to read "[" as a 
numeric value so am I suppose to write a loop that enables an exception error. 
I believe the this is what holding my final product from being complete.Believe 
is what my output is 

 processScores('scores.txt')
Score set to total value: 5
Numeric detected. Updating One. Total outcome: 14
Numeric detected. Updating One. Total outcome: 20
Traceback (most recent call last):
  File "", line 1, in 
    processScores('scores.txt')
  File "C:/Users/Michael/Documents/DePaul/tutor/hw2_practice.py", line 52, in 
processScores
    s.total = int(item)
ValueError: invalid literal for int() with base 10: '[3, 12, 1]\n'___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Naming variables

2014-01-18 Thread Pierre Dagenais
Hello,

I wish to fill a list called years[] with a hundred lists called
year1900[], year1901[], year1902[], ..., year1999[]. That is too much
typing of course. Any way of doing this in a loop? I've tried stuff like
("year" + str(1900)) = [0,0] but nothing works.
Any solution?

Thank you,

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


Re: [Tutor] ValueError: could not convert string to float: '13,2'

2014-01-18 Thread Pierre Dagenais


On 13-12-31 04:09 PM, Keith Winston wrote:
> Hi PierreD, I think if you iterate over your strings with something like
> this, it will do what you want, if I understand correctly (snum is your
> string number, like "123,321"):
> 
> fnum = float(snum.replace(",", ".")
> 
> keith: rank beginner, take everything with a grain of salt!
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 
Thank you all who responded, for now I'll go with Keith's solution and
keep the locale for next time.
As all the data has one digit after the decimal I can get away with
myInt = int(temp.replace(',',''))
to convert a string representation of a float to an integer. I'll just
need to remember to divide everything by ten once the calculations are
done. Not very elegant, but it'll work. I don't suppose there is a
function for determining the number of digits after the decimal, is it?
Also, anybody knows the maximum and/or minimum integer python will accept?

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


Re: [Tutor] Question in regards to my assignment

2014-01-18 Thread Alan Gauld

On 18/01/14 22:52, Jackie Canales wrote:


def processScores(filename):
 infile = open(filename, 'r')
 line = infile.readlines()
 infile.close()
 lineNum = 0
 s = Score(0)

 for item in line2:

>  lineNum += 1

What is line2? I assume you mean line?

You could do all of the above more easily with

with open(filename) as infile:
for lineNum, line in enumerate(infile):

But line will *always* be a string so you need to convert the string 
into data that Python can understand. int() works if the line contains a 
numerical string.

But it won't work for lists, and neither will list() for that matter.
You need to remove the brackets then split the lstring by commas and 
then convert each element. Its probably complex enough to warrant a 
function of its own...




 if lineNum == 1:
 s.total = int(item)
 print("Score set to total value:", s.total)
 elif lineNum % 2:
 s.total = int(item)
 if type(item) == list:


You probably want to test type before trying to convert to an int(). 
Unfortunately the type will be a string so the list test will always 
fail. You need to actually examine the string content. (Or you can trust 
the file to tell you, the instructions say a list is flagged by an m/M 
in the line before. So instead of throwing that data away you can use it 
to direct your program what kind of data to process.




 lstNum = s.updateMany(s.total)
 print("List detected. Updating many. Total outcome:",
lstNum)
else:
 intNum = s.updateOne(s.total)
 print("Numeric detected. Updating One. Total outcome:",
intNum)
 else:
 pass


else: pass

does nothing so you may as well remove it.


 print("The Final Score is:", s.get())
 print("The Average Score is:", s.average())
 print("The Score Object is:", s.__repr__())


The file that I am trying read is a text file call score:



o
10
m
[3, 12, 1]



The first line of the file is a number, which indicates the initial
score for a Score object.  The remaining lines are pairs: the
even-numbered lines contain a character and the odd-numbered lines
contain either a number or a list.  The character will be one of 'o',
'O', 'm', or 'M', indicating that the next line contains either a single
score ('o'  or 'O') or a list of scores ('m' or 'M').




So from my understanding when my code tries to read the first line with
a list it is not able to read ''[3, 12, 1]\n'" because its not able to
read "[" as a numeric value


Correct


so am I suppose to write a loop that enables an exception error.


I'm not sure what you mean by that, but you do need to write a
function to interpret a string representation of a list.

HTH
--
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


Re: [Tutor] iterators

2014-01-18 Thread eryksun
On Sat, Jan 18, 2014 at 6:24 PM, Keith Winston  wrote:
>
> I guess it makes sense that iter() returns a type iterator.

`iter(obj)` returns `obj.__iter__()` if the method exists and the
result is an iterator, i.e. has a `__next__` method.

Otherwise if `obj.__getitem__` exists, it returns a generic sequence
`iterator`. This steps through the sequence `obj[0]`, `obj[1]`, and so
on, until it encounters either `IndexError` or `StopIteration`.

`iter(callable, sentinel)` returns a `callable_iterator`. This returns
`callable()` until either the result equals `sentinel` or it
encounters `StopIteration`. For example:

>>> sentinel = 2
>>> it = iter(iter(range(5)).__next__, sentinel)
>>> type(it)

>>> list(it)
[0, 1]

`reversed(obj)` returns `obj.__reversed__()`, if it exists. It doesn't
check the type of the result:

class C:
__reversed__ = lambda s: 3.14

>>> reversed(C())
3.14

Otherwise if `obj` is a sequence (`__getitem__`, `__len__`, and not a
`dict`), it returns a `reversed` instance. This iterates from
`obj[len(obj) - 1]` down to `obj[0]`.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Naming variables

2014-01-18 Thread Danny Yoo
If we wanted to do something with something like:

year0 = 0
year1 = 0
year2 = 0
...
year999 = 0

where we keep a thousand years, and set them all to zero, then you're
right in thinking that having one thousand separate variables is
probably not a viable approach.


We can handle this uniformly, though, by using a list.

year  = [0] * 1000

'year' is now a list with 1000 elements, all of which are zero.  We
can access each in turn:

year[0]
year[1]
year[2]

year[999]

and see that they all have zero in them.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Naming variables

2014-01-18 Thread Danny Yoo
One thing to note:  I wrote:

year = [0] * 1000


Here's another way to get something equivalent:

year  = []
for i in range(1000):
year.append(0)


Here, we do an explicit loop to append those thousand zeros into the
list.  We'll end up with the same situation as before: year is a list
of zeros.


Why would we want to look at doing it this different approach?

See:


http://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list

for details.


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