473,782 Members | 2,437 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arithmetic sequences in Python

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.

Jan 16 '06
72 5579
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.

Jan 17 '06 #31
Op 2006-01-16, Alex Martelli schreef <al***@mail.com cast.net>:
Paul Rubin <http://ph****@NOSPAM.i nvalid> wrote:
Steven D'Aprano <st***@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;-)]]


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
Jan 17 '06 #32
"Gregory Petrosyan" <gr************ ***@gmail.com> writes:
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.


So what do you want [a..b] to do? Dynamically decide what direction
to go? Ugh!
Jan 17 '06 #33
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.

Jan 17 '06 #34
Antoon Pardon wrote:
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.


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
Jan 17 '06 #35
Hey guys, this proposal has already been rejected (it is the PEP 204).

Jan 17 '06 #36
On Tue, 16 Jan 2006, it was written:
Tom Anderson <tw**@urchin.ea rth.li> writes:
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.


Interesting, but what do you do about the "unary postfix" (1 ..)
infinite generator?


1.__range__(Non e)
(-3,-5 ..) --> 'infinite' generator that yield -3,-5,-7 and so on


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


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.


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.
:)
1) "[]" means list, "()" means generator

Yuck. Yes, i know it's consistent with list comps and genexps, but yuck
to those too!


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].


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
Jan 18 '06 #37
On Tue, 17 Jan 2006, Antoon Pardon wrote:
Op 2006-01-16, Alex Martelli schreef <al***@mail.com cast.net>:
Paul Rubin <http://ph****@NOSPAM.i nvalid> wrote:
Steven D'Aprano <st***@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;-)]]


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


+5
for i, el in enumerate(seque nce):

would become

for i in sequence.range( ):
el = sequence[i]
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.
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.
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)
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):


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
Jan 18 '06 #38
Paul Rubin wrote:
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.


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 ;-)
Jan 18 '06 #39
Gregory Petrosyan wrote:
Hey guys, this proposal has already been rejected (it is the PEP 204).


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

Jan 18 '06 #40

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
7069
by: Generic Usenet Account | last post by:
This posting is just for clarification of my understanding. It appears to me that only vector and deque iterators (i.e. random access iterators) allow "iterator arithmetic" operations (like iter+2, iter-1 etc.). Kindly confirm. Thanks, Song
26
3064
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
1
6231
by: mmm | last post by:
I wrote the code below to create simple arithmetic sequences that are iter-able I.e., this would basically combine the NUMPY arange(start,end,step) to range(start,end), with step not necessarily an integer. The code below is in its simplest form and I want to generalize the sequence types (multiplicative, cumulative, gauss ...), but first I need the simple SEQA( ) function to be more robust. The problem is the three test code...
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10311
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7492
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4043
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.