473,769 Members | 1,618 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 5572
Paul Rubin <http://ph****@NOSPAM.i nvalid> wrote:
...
while the traditional

xrange(f(n)-1, -1, -1)

only evaluates it once but is IMO repulsive.


Yep, reversed(range( f(n))) is MUCH better.
Alex
Jan 16 '06 #11
Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
On Mon, 16 Jan 2006 12:51:58 +0100, Xavier Morel wrote:
For those who'd need the (0..n-1) behavior, Ruby features something that
I find quite elegant (if not perfectly obvious at first), (first..last)
provides a range from first to last with both boundaries included, but
(first...last) (notice the 3 periods)


No, no I didn't.

Sheesh, that just *screams* "Off By One Errors!!!". Python deliberately
uses a simple, consistent system of indexing from the start to one past
the end specifically to help prevent signpost errors, and now some folks
want to undermine that.

*shakes head in amazement*


Agreed. *IF* we truly needed an occasional "up to X *INCLUDED*"
sequence, it should be in a syntax that can't FAIL to be noticed, such
as range(X, endincluded=Tru e).
Alex
Jan 16 '06 #12
On Mon, 16 Jan 2006 02:58:39 -0800, Paul Rubin 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).


Only in isolation, and arguably not even then. Or do you think that Perl
is much easier to read than Python simply because you can write your
programs in fewer characters?

It looks too much like the list [5,4,0], and is easy to make typos:
[5,4,.0] gives you no syntax error but very different results.

The meaning isn't particular clear: is it supposed to be [start, stop,
step] (the natural expectation for those used to Python slices and ranges)
or [start, next, stop]? It is actually the second, but go back to the
original post by Gregory: after giving examples, he still wrongly
described his proposal as having a "step" parameter. There is no step
parameter -- the step is implied, by subtracting start from next. Such
confusion doesn't bode well.

Python indexing deliberately goes to one-past-the-end counting for a
reason: it helps prevent off-by-one signpost errors. This syntax goes
against that decision, and adds one more thing to memorise about Python:
the end index is not included in the list, except for arithmetic
sequences, where it is, sometimes but not necessarily. In [5,6,10] the end
index 10 is included; in [5,7,10] it isn't.

You've picked the most awkward example of range, I admit. But let's look
at a few others:

[0,..9] versus range(10)
[55, ...73] versus range(55, 74)
[1, 3, ..len(mystr)] versus range(1, len(mystr)+1, 2)
[55, 65, 295] versus range(55, 296, 10)

How often do you find yourself knowing the first two terms of a sequence
but not the step size anyway? Is that a common use case?
The only added feature this proposal
introduces is infinite iterators, and they aren't particularly hard to
make:

def arithmetic_sequ ence(start, step=1):
yield start
while 1:
start += step
yield start


Well, that would be itertools.count (start, step) but in general a simple
expression is nicer than 5 lines of code.


I didn't say that my generator was the only way to produce the required
result, I was pointing out how simple it is. Yes, itertools is the way to
go for this sort of thing.

If your proposal included support for ranges of characters, I'd be more
interested.


There's something to be said for that. Should ['a'..'z'] be a list or a
string?


It uses [ something ] syntax, so for consistency with lists and list
comprehensions it should be a list.

But a string would be more practical, since list(['a'..'z']) is easier and
more intuitive than ''.join(['a'..'z']). But I'm not sure that it is
*that* much more practical to deserve breaking the reader's expectation.

So I think the best thing would be to create itertools.chars ('a', 'z') or
similar, not new syntax.
--
Steven.

Jan 16 '06 #13
Alex Martelli <al***@mail.com cast.net> wrote:
Agreed. *IF* we truly needed an occasional "up to X *INCLUDED*"
sequence, it should be in a syntax that can't FAIL to be noticed, such
as range(X, endincluded=Tru e).


How about...

for i in (0..x]:
blah

Jan 16 '06 #14
Roy Smith <ro*@panix.co m> wrote:
Alex Martelli <al***@mail.com cast.net> wrote:
Agreed. *IF* we truly needed an occasional "up to X *INCLUDED*"
sequence, it should be in a syntax that can't FAIL to be noticed, such
as range(X, endincluded=Tru e).


How about...

for i in (0..x]:
blah


The difference between a round parenthesis and a square bracket can
EASILY be overlooked, depending partly on what font you're using.
Alex
Jan 16 '06 #15
In <dq**********@r eader2.panix.co m>, Roy Smith wrote:
Alex Martelli <al***@mail.com cast.net> wrote:
Agreed. *IF* we truly needed an occasional "up to X *INCLUDED*"
sequence, it should be in a syntax that can't FAIL to be noticed, such
as range(X, endincluded=Tru e).


How about...

for i in (0..x]:
blah


That would break most editors "highlight matching brace" functionality.

Ciao,
Marc 'BlackJack' Rintsch
Jan 16 '06 #16
i would love to see a nice, clear syntax instead of
for i in xrange(start, stop, step): ...

because xrange is ugly and iteration over int sequences are important.
we don't need a range() alternative ( [0:10] or [0..10] )
(because no one would ever use range() if there were a nice
integer-for-loop)

there was a proposal (http://www.python.org/peps/pep-0284.html):
for start <= i < stop: ...
but in this way you cannot specify the step parameter and it has some
problems when used in list comprehension.

pep 204 like syntax would be:
for i in (start:stop:ste p): ...
it is much nicer than xrange, but probably it has some inconsistency
with slicing
(eg (:3)=xrange(3), (-3:)=itertools.c ount(-3), (:-3)=?, (3::-1)=? )

your .. approach:
for i in (start, start+step .. stop): ...
here start written down twice if it's referred by a name (and if start
is a function call it's evaluated twice)
imho without a step it looks nice:
for i in (start .. stop): ...
but a new syntax would be good only if it can entirely replace the old
one (which then can be made deprecated).

Jan 16 '06 #17
al***@mail.comc ast.net (Alex Martelli) writes:
Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).
But not easier than reversed(range( 6))


Heh, I like that, and reversed(xrange (6)) appears to do the right
thing too. I didn't know about __reversed__ before.
[[the 5 in one of the two
expressions in your sentence has to be an offbyone;-)]]


Are you sure? I could easily be missing something, since it's easy
to be offbyone with this stuff, but when I try it I get:

Python 2.4.1 (#1, May 16 2005, 15:19:29)
[GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
range(5,-1,-1) [5, 4, 3, 2, 1, 0]


and (skipping the ascii art banner):

Hugs 98: Based on the Haskell 98 standard
Haskell 98 mode: Restart with command line option -98 to enable extensions
Type :? for help
Hugs.Base> [5,4..0]
[5,4,3,2,1,0]
Hugs.Base>

which is equivalent. (Of course, having to use 6 instead of 5 in
the range(...) version invites an offbyone error).
Jan 16 '06 #18
Xavier Morel <xa**********@m asklinn.net> writes:
The only thing that bothers me about the initial proposal is that
there would not, in fact, be any "range object", but merely a
syntactic sugar for list/generator creation.
Well, it could create something like an xrange. Maybe that's preferable.
Not that I really mind it, but, well, syntactic sugar for the
purpose of syntactic sugar really doesn't bring much to the table.


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.
Jan 16 '06 #19
Thanks for your replies. So, some problems and possible solutions:

1) [f(n), f(n)-1 .. 0] can be easily catched by interpreter, and f(n)
can be evaluated only once.

2) if you need right border excluded, I think [0 .. n) is very clear
(and consistent with mathematics). And about brakets highlighting... Do
you _really_ need it in this expression? By the way, Python
editors/ide's can be easily extended to support this syntax, and even
to color brakets in [0 .. n) in different colors (so, it'll be very
clear if border is included or not).
But as for me, [0 .. n-1] is better because it looks more like ordinary
list, and we would have no problems on creating generators with
excluded border.

3) Of course, in some cases 'range' is more readable. As for your
examples:

[0,..9] versus range(10)
[55, ...73] versus range(55, 74)
[1, 3, ..len(mystr)] versus range(1, len(mystr)+1, 2)
[55, 65, 295] versus range(55, 296, 10)

a) you use "magic" 10 here...
[0 .. 10) or [0 .. 9] are IMO at least as nice as range(10). And what
about
[1 .. 10] and range(1, 11)? ;-)

b) [55 .. 73] vs range(55, 74)? IMO first is more readable. And you
actually can see what is the last value, while in "range" you think
something like: "if 74 is written here, then last value is 74-1 = 73"

c) [1, 3 .. len(mystr)] vs range(1, len(mystr)+1, 2). As for me, I
should think for 2-3 seconds before I understand what range(1,
len(mystr)+1, 2) stands for :-)
And [1, 3 .. len(mystr)] is _obvious_ for almost everybody.

d) why you wrote '296' in range? Maybe, because you are really
experienced programmer, and you can automatically transform 295 -> 296
(because you _know_ the behaviour of range function). But if your task
is simply to iterate through sequence like n1, n2, n3, ... n(X-1), nX,
then [n1 .. nX] looks more natural, isn't it?

4) Proposed syntax can be easily extended to support chars (or any
other enumeration). (Maybe, without _implied_ :-) step parameter):

['a' .. 'd'] -> ['a','b','c','d'] (let it be a list for consistency)
('x' .. 'z') -> generator that yields 'x', 'y' and 'z' :-)
('a' ..) -> generator that yields english alphabet

Conclusion:
- I don't want to remove 'range' function from use completely. Feel
free to use it ;-)
- The only idea behind my proposal is obviousness. As for me, it was
sometimes slightly difficult to explain to somebody not familiar with
Python what

for n in range(1,10,2):
bla-bla-bla

stands for. Arithmetic sequence IMHO isn't that kind of thing when you
need to know some
special function to use it (is everything OK with my english here?)

Jan 16 '06 #20

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
3063
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
6230
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
9589
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
10211
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
10045
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
9994
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
8870
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
7408
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
6673
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();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.