Arithmetic sequences in Python

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gregory Petrosyan

    #31
    Re: Arithmetic sequences in Python

    Some ideas:

    1) Let [a,b .. c] be *ordinary list* !
    Just like [1,2,3]. Are there any questions why 3 is included in
    [1,2,3]? IMO it's more correct to think about [first, next .. last] as
    about syntax for list creation, but not as about
    "syntax-to-replace-range-function". (And, because it's an ordinary
    list, you could iterate through it in usual way: "for each element of
    list do...")

    2) [5 .. 0] -> [5,4,3,2,1,0]
    So, if "next" is omited, let the default step be 1 if "first" < "last"
    and -1 otherwise.

    Comment

    • Antoon Pardon

      #32
      Re: Arithmetic sequences in Python

      Op 2006-01-16, Alex Martelli schreef <aleax@mail.com cast.net>:[color=blue]
      > Paul Rubin <http://phr.cx@NOSPAM.i nvalid> wrote:
      >[color=green]
      >> Steven D'Aprano <steve@REMOVETH IScyber.com.au> writes:[color=darkred]
      >> > For finite sequences, your proposal adds nothing new to existing
      >> > solutions like range and xrange.[/color]
      >>
      >> Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).[/color]
      >
      > But not easier than reversed(range( 6)) [[the 5 in one of the two
      > expressions in your sentence has to be an offbyone;-)]][/color]

      Why don't we give slices more functionality and use them.
      These are a number of ideas I had. (These are python3k ideas)

      1) Make slices iterables. (No more need for (x)range)

      2) Use a bottom and stop variable as default for the start and
      stop attribute. top would be a value that is greater than
      any other value, bottom would be a value smaller than any
      other value.

      3) Allow slice notation to be used anywhere a value can be
      used.

      4) Provide a number of extra operators on slices.
      __neg__ (reverses the slice)
      __and__ gives the intersection of two slices
      __or__ gives the union of two slices

      5) Provide sequences with a range (or slice) method.
      This would provide an iterator that iterates over
      the indexes of the sequences. A slice could be
      provided


      for i in xrange(6):

      would then become

      for i in (0:6):

      for a reversed sequence

      for i in reversed(xrange (6)):

      would become

      for i in - (0:6):


      for i, el in enumerate(seque nce):

      would become

      for i in sequence.range( ):
      el = sequence[i]

      But the advantage is that this would still work when
      someone subclasses a list so that it start index
      is an other number but 0.

      If you only wanted every other index one could do
      the following

      for i in sequence.range( ::2):

      which would be equivallent to

      for i in sequence.range( ) & (::2):

      --
      Antoon Pardon

      Comment

      • Paul Rubin

        #33
        Re: Arithmetic sequences in Python

        "Gregory Petrosyan" <gregory.petros yan@gmail.com> writes:[color=blue]
        > 2) [5 .. 0] -> [5,4,3,2,1,0]
        > So, if "next" is omited, let the default step be 1 if "first" < "last"
        > and -1 otherwise.[/color]

        So what do you want [a..b] to do? Dynamically decide what direction
        to go? Ugh!

        Comment

        • Gregory Petrosyan

          #34
          Re: Arithmetic sequences in Python

          Hmm, and why not? Or you realy hate such behaviour?

          Note, everything I post here is just some ideas I want to discuss, and
          to make these ideas better after discussion. And this particular idea
          needs to be discussed, too.

          Comment

          • Steven Bethard

            #35
            Re: Arithmetic sequences in Python

            Antoon Pardon wrote:[color=blue]
            > Why don't we give slices more functionality and use them.
            > These are a number of ideas I had. (These are python3k ideas)
            >
            > 1) Make slices iterables. (No more need for (x)range)
            >
            > 2) Use a bottom and stop variable as default for the start and
            > stop attribute. top would be a value that is greater than
            > any other value, bottom would be a value smaller than any
            > other value.[/color]

            Just checking your intent here. What should these do?

            (2:5) # should give me 2, 3, 4
            (2:5:-1) # infinite iterator 2, 1, 0, ...?
            (:5) # start at -infinity? what does that even mean?
            (:5:-1) # start at -infinity and go backwards?!!

            I suspect you should be raising some sort of exception if the start
            isn't defined.

            STeVe

            Comment

            • Gregory Petrosyan

              #36
              Re: Arithmetic sequences in Python

              Hey guys, this proposal has already been rejected (it is the PEP 204).

              Comment

              • Tom Anderson

                #37
                Re: Arithmetic sequences in Python

                On Tue, 16 Jan 2006, it was written:
                [color=blue]
                > Tom Anderson <twic@urchin.ea rth.li> writes:
                >[color=green]
                >> The natural way to implement this would be to make .. a normal
                >> operator, rather than magic, and add a __range__ special method to
                >> handle it. "a .. b" would translate to "a.__range__(b) ". I note that
                >> Roman Suzi proposed this back in 2001, after PEP 204 was rejected. It's
                >> a pretty obvious implementation, after all.[/color]
                >
                > Interesting, but what do you do about the "unary postfix" (1 ..)
                > infinite generator?[/color]

                1.__range__(Non e)
                [color=blue][color=green][color=darkred]
                >>> (-3,-5 ..) --> 'infinite' generator that yield -3,-5,-7 and so on[/color]
                >>
                >> -1. Personally, i find the approach of specifying the first two
                >> elements *absolutely* *revolting*, and it would consistently be more
                >> awkward to use than a start/step/stop style syntax. Come on, when do
                >> you know the first two terms but not the step size?[/color]
                >
                > Usually you know both, but showing the first two elements makes sequence
                > more visible. I certainly like (1,3..9) better than (1,9;2) or
                > whatever.[/color]

                I have to confess that i don't have a pretty three-argument syntax to
                offer as an alternative to yours. But i'm afraid i still don't like yours.
                :)
                [color=blue][color=green][color=darkred]
                >>> 1) "[]" means list, "()" means generator[/color]
                >> Yuck. Yes, i know it's consistent with list comps and genexps, but yuck
                >> to those too![/color]
                >
                > I'd be ok with getting rid of [] and just having generators or
                > xrange-like class instances. If you want to coerce one of those to a
                > list, you'd say list((1..5)) instead of [1..5].[/color]

                Sounds good. More generally, i'd be more than happy to get rid of list
                comprehensions, letting people use list(genexp) instead. That would
                obviously be a Py3k thing, though.

                tom

                --
                Taking care of business

                Comment

                • Tom Anderson

                  #38
                  Re: Arithmetic sequences in Python

                  On Tue, 17 Jan 2006, Antoon Pardon wrote:
                  [color=blue]
                  > Op 2006-01-16, Alex Martelli schreef <aleax@mail.com cast.net>:[color=green]
                  >> Paul Rubin <http://phr.cx@NOSPAM.i nvalid> wrote:
                  >>[color=darkred]
                  >>> Steven D'Aprano <steve@REMOVETH IScyber.com.au> writes:
                  >>>> For finite sequences, your proposal adds nothing new to existing
                  >>>> solutions like range and xrange.
                  >>>
                  >>> Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).[/color]
                  >>
                  >> But not easier than reversed(range( 6)) [[the 5 in one of the two
                  >> expressions in your sentence has to be an offbyone;-)]][/color]
                  >
                  > Why don't we give slices more functionality and use them.
                  > These are a number of ideas I had. (These are python3k ideas)
                  >
                  > 1) Make slices iterables. (No more need for (x)range)
                  >
                  > 2) Use a bottom and stop variable as default for the start and
                  > stop attribute. top would be a value that is greater than
                  > any other value, bottom would be a value smaller than any
                  > other value.
                  >
                  > 3) Allow slice notation to be used anywhere a value can be
                  > used.
                  >
                  > 4) Provide a number of extra operators on slices.
                  > __neg__ (reverses the slice)
                  > __and__ gives the intersection of two slices
                  > __or__ gives the union of two slices
                  >
                  > 5) Provide sequences with a range (or slice) method.
                  > This would provide an iterator that iterates over
                  > the indexes of the sequences. A slice could be
                  > provided[/color]

                  +5
                  [color=blue]
                  > for i, el in enumerate(seque nce):
                  >
                  > would become
                  >
                  > for i in sequence.range( ):
                  > el = sequence[i][/color]

                  That one, i'm not so happy with - i quite like enumerate; it communicates
                  intention very clearly. I believe enumerate is implemented with iterators,
                  meaning it's potentially more efficient than your approach, too. And since
                  enumerate works on iterators, which yours doesn't, you have to keep it
                  anyway. Still, both would be possible, and it's a matter of taste.
                  [color=blue]
                  > But the advantage is that this would still work when someone subclasses
                  > a list so that it start index is an other number but 0.[/color]

                  It would be possible to patch enumerate to do the right thing in those
                  situations - it could look for a range method on the enumerand, and if it
                  found one, use it to generate the indices. Like this:

                  def enumerate(thing ):
                  if (hasattr(thing, "range")):
                  indices = thing.range()
                  else:
                  indices = itertools.count ()
                  return itertools.izip( indices, thing)
                  [color=blue]
                  > If you only wanted every other index one could do the following
                  >
                  > for i in sequence.range( ::2):
                  >
                  > which would be equivallent to
                  >
                  > for i in sequence.range( ) & (::2):[/color]

                  Oh, that is nice. Still, you could also extend enumerate to take a range
                  as an optional second parameter and do this with it. Six of one, half a
                  dozen of the other, i suppose.

                  tom

                  --
                  Taking care of business

                  Comment

                  • Xavier Morel

                    #39
                    Re: Arithmetic sequences in Python

                    Paul Rubin wrote:[color=blue]
                    > I don't think this is a valid objection. Python is already full of
                    > syntactic sugar like indentation-based block structure, infix
                    > operators, statements with keyword-dependent syntax, etc. It's that
                    > very sugar that attracts programmers to Python away from comparatively
                    > sugarless languages like Scheme. Indeed, Python is considered by many
                    > to be a sweet language to program in, and they mean that in a nice
                    > way.
                    >
                    > If you want, you can think of it as "flavor" rather than "sugar". We
                    > aren't after syntactic minimalism or we'd be using Scheme. The
                    > criterion for adding something like this to Python should be whether
                    > makes the language taste better or not.[/color]

                    I don't know, most of the syntactic sugar I see in Python brings
                    something to the language, or trivialize the generation of structures
                    and constructs that may be complex or awkward without it, it has a
                    natural, honey-ish sweetness full of flavor, it does not taste like some
                    cancer-spawning artificial sweetener ;-)

                    Comment

                    • Steven Bethard

                      #40
                      Re: Arithmetic sequences in Python

                      Gregory Petrosyan wrote:[color=blue]
                      > Hey guys, this proposal has already been rejected (it is the PEP 204).[/color]

                      No, this is a subtly different proposal. Antoon is proposing *slice*
                      literals, not *range* literals. Note that "confusion between ranges and
                      slice syntax" was one of the reasons for rejection of `PEP 204`_. Which
                      means that if Antoon really wants his proposal to go through, he
                      probably needs to make sure that slice literals are clearly distinct
                      from range literals.

                      ... _PEP 204: http://www.python.org/peps/pep-0204.html

                      STeVe

                      Comment

                      • Alex Martelli

                        #41
                        Re: Arithmetic sequences in Python

                        Tom Anderson <twic@urchin.ea rth.li> wrote:
                        ...[color=blue]
                        > Sounds good. More generally, i'd be more than happy to get rid of list
                        > comprehensions, letting people use list(genexp) instead. That would
                        > obviously be a Py3k thing, though.[/color]

                        I fully agree, but the BDFL has already (tentatively, I hope) Pronounced
                        that the [...] form will stay in Py3K as syntax sugar for list(...). I
                        find that to be a truly hateful prospect, but that's the prospect:-(.


                        Alex

                        Comment

                        • Antoon Pardon

                          #42
                          Re: Arithmetic sequences in Python

                          Op 2006-01-17, Steven Bethard schreef <steven.bethard @gmail.com>:[color=blue]
                          > Antoon Pardon wrote:[color=green]
                          >> Why don't we give slices more functionality and use them.
                          >> These are a number of ideas I had. (These are python3k ideas)
                          >>
                          >> 1) Make slices iterables. (No more need for (x)range)
                          >>
                          >> 2) Use a bottom and stop variable as default for the start and
                          >> stop attribute. top would be a value that is greater than
                          >> any other value, bottom would be a value smaller than any
                          >> other value.[/color]
                          >
                          > Just checking your intent here. What should these do?
                          >
                          > (2:5) # should give me 2, 3, 4[/color]

                          Yes.
                          [color=blue]
                          > (2:5:-1) # infinite iterator 2, 1, 0, ...?[/color]

                          No it would give nothing, think xrange(2,5,-1)

                          [color=blue]
                          > (:5) # start at -infinity? what does that even mean?[/color]

                          I'm still thinking abouth this. My preffered idea now it
                          it would be an endless loop returning bottom elements.
                          [color=blue]
                          > (:5:-1) # start at -infinity and go backwards?!![/color]

                          This would give nothing. The idea is that if the step is negative
                          the iteration stops when the (hidden) index is equal or smaller
                          than the stop value. This is true here from the start.
                          [color=blue]
                          > I suspect you should be raising some sort of exception if the start
                          > isn't defined.[/color]

                          That is a possibility too.

                          --
                          Antoon Pardon

                          Comment

                          • Antoon Pardon

                            #43
                            Re: Arithmetic sequences in Python

                            Op 2006-01-17, Gregory Petrosyan schreef <gregory.petros yan@gmail.com>:[color=blue]
                            > Hey guys, this proposal has already been rejected (it is the PEP 204).
                            >[/color]

                            No it isn't. In my proposal [1, 2:8, 8] would be equivallent to
                            [1, slice(2,8), 8]. If someone would want the list [1,2,3,4,5,6,7,8]
                            with this notation, I would propose a flatten function witch would
                            work with iterators too, so that flat([1, 2:8, 8]) would be the
                            same as flat([1, range(2,8), 8])

                            In my view python already has slice literals. You are only limited
                            in using this literals an index in subscription. I think this is
                            a rathter pointless limitation and that literal slices could be
                            very usefull when made into literals and usable as parameters.

                            --
                            Antoon Pardon

                            Comment

                            • Antoon Pardon

                              #44
                              Re: Arithmetic sequences in Python

                              Op 2006-01-18, Tom Anderson schreef <twic@urchin.ea rth.li>:[color=blue]
                              > On Tue, 17 Jan 2006, Antoon Pardon wrote:
                              >[color=green]
                              >> Op 2006-01-16, Alex Martelli schreef <aleax@mail.com cast.net>:[color=darkred]
                              >>> Paul Rubin <http://phr.cx@NOSPAM.i nvalid> wrote:
                              >>>
                              >>>> Steven D'Aprano <steve@REMOVETH IScyber.com.au> writes:
                              >>>>> For finite sequences, your proposal adds nothing new to existing
                              >>>>> solutions like range and xrange.
                              >>>>
                              >>>> Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).
                              >>>
                              >>> But not easier than reversed(range( 6)) [[the 5 in one of the two
                              >>> expressions in your sentence has to be an offbyone;-)]][/color]
                              >>
                              >> Why don't we give slices more functionality and use them.
                              >> These are a number of ideas I had. (These are python3k ideas)
                              >>
                              >> 1) Make slices iterables. (No more need for (x)range)
                              >>
                              >> 2) Use a bottom and stop variable as default for the start and
                              >> stop attribute. top would be a value that is greater than
                              >> any other value, bottom would be a value smaller than any
                              >> other value.
                              >>
                              >> 3) Allow slice notation to be used anywhere a value can be
                              >> used.
                              >>
                              >> 4) Provide a number of extra operators on slices.
                              >> __neg__ (reverses the slice)
                              >> __and__ gives the intersection of two slices
                              >> __or__ gives the union of two slices
                              >>
                              >> 5) Provide sequences with a range (or slice) method.
                              >> This would provide an iterator that iterates over
                              >> the indexes of the sequences. A slice could be
                              >> provided[/color]
                              >
                              > +5
                              >[color=green]
                              >> for i, el in enumerate(seque nce):
                              >>
                              >> would become
                              >>
                              >> for i in sequence.range( ):
                              >> el = sequence[i][/color]
                              >
                              > That one, i'm not so happy with - i quite like enumerate; it communicates
                              > intention very clearly. I believe enumerate is implemented with iterators,
                              > meaning it's potentially more efficient than your approach, too. And since
                              > enumerate works on iterators, which yours doesn't, you have to keep it
                              > anyway. Still, both would be possible, and it's a matter of taste.
                              >[color=green]
                              >> But the advantage is that this would still work when someone subclasses
                              >> a list so that it start index is an other number but 0.[/color]
                              >
                              > It would be possible to patch enumerate to do the right thing in those
                              > situations - it could look for a range method on the enumerand, and if it
                              > found one, use it to generate the indices. Like this:
                              >
                              > def enumerate(thing ):
                              > if (hasattr(thing, "range")):
                              > indices = thing.range()
                              > else:
                              > indices = itertools.count ()
                              > return itertools.izip( indices, thing)[/color]

                              Fine by me. I'm not against enumerate.
                              [color=blue][color=green]
                              >> If you only wanted every other index one could do the following
                              >>
                              >> for i in sequence.range( ::2):
                              >>
                              >> which would be equivallent to
                              >>
                              >> for i in sequence.range( ) & (::2):[/color]
                              >
                              > Oh, that is nice. Still, you could also extend enumerate to take a range
                              > as an optional second parameter and do this with it. Six of one, half a
                              > dozen of the other, i suppose.[/color]

                              Yes you could probably do so and I'm not against it, I just think that
                              range would be a better base on which you can build enumerate and other
                              things than that enumenrate can be a base. e.g. __len__ could be eliminated
                              and len would be defined as:

                              def len(seq):
                              rng = seq.range()
                              return rng.stop - rng.start

                              Comment

                              • Antoon Pardon

                                #45
                                Re: Arithmetic sequences in Python

                                Op 2006-01-16, Gregory Petrosyan schreef <gregory.petros yan@gmail.com>:[color=blue]
                                > Please visit http://www.python.org/peps/pep-0204.html first.
                                >
                                > As you can see, PEP 204 was rejected, mostly because of not-so-obvious
                                > syntax. But IMO the idea behind this pep is very nice. So, maybe
                                > there's a reason to adopt slightly modified Haskell's syntax? Something
                                > like
                                >
                                > [1,3..10] --> [1,3,5,7,9]
                                > (1,3..10) --> same values as above, but return generator instead of
                                > list
                                > [1..10] --> [1,2,3,4,5,6,7,8 ,9,10]
                                > (1 ..) --> 'infinite' generator that yield 1,2,3 and so on
                                > (-3,-5 ..) --> 'infinite' generator that yield -3,-5,-7 and so on
                                >
                                > So,
                                > 1) "[]" means list, "()" means generator
                                > 2) the "start" is required, "step" and "end" are optional.
                                >
                                > Also, this can be nicely integrated with enumerations (if they will
                                > appear in python). Haskell is also example of such integration.[/color]

                                With some abuse of the language one can already do a number of things
                                in python2.4 now.

                                import sys
                                from types import SliceType

                                class vslice(object):

                                def __init__(self, fun):
                                self.fun = fun

                                def __getitem__(sel f, inx):
                                if not isinstance(inx, tuple):
                                inx = inx,
                                return self.fun(*inx)

                                @vslice
                                def rnglst(*arg):
                                lst = []
                                for el in arg:
                                if type(el) is SliceType:
                                start = el.start or 0
                                stop = el.stop or sys.maxint
                                step = el.step or 1
                                if step > 0:
                                while start < stop:
                                lst.append(star t)
                                start += step
                                else:
                                while start > stop:
                                lst.append(star t)
                                start += step
                                else:
                                lst.append(el)
                                return lst

                                rnglst[3,4,5] --> [3, 4, 5]
                                rnglst[1, 2:8] --> [1, 2, 3, 4, 5, 6, 7]
                                rnglst[3:9:2, 21:6:-3] --> [3, 5, 7, 21, 18, 15, 12, 9]

                                --
                                Antoon Pardon

                                Comment

                                Working...