Today we'll be writing a function called Range. The Perl documentation
is as follows.
Perl & Python & Java Solutions will be posted in 48 hours.
This is Perl-Python a-day. See http://xahlee.org/web/perl-python/python.html
Xah xa*@xahlee.org
∑ http://xahlee.org/
--------------------------
Range
Range($iMax) generates the list [1, 2, ... , $iMax].
Range($iMin, $iMax) generates the list [$iMin, ... , $iMax].
Range($iMin, $iMax, $iStep) uses increment $iStep, with the last
element
in the result being less or equal to $iMax. $iStep cannot be 0. If
$iStep is negative, then the role of $iMin and $iMax are reversed.
If Range fails, 0 is returned.
Example:
Range(5); # returns [1,2,3,4,5]
Range(5,10); # returns [5,6,7,8,9,10]
Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]
Range( 5, -4, -2); # returns [5,3,1,-1,-3] 7 3366
Xah Lee wrote: Today we'll be writing a function called Range.
I don't think so. Unless you meant to write "Today WE'll be writing ...."
The Perl documentation is as follows.
Bullshit. The Perl documentation is part of any Perl installation but you
didn't link to it anywhere left alone quote it.
Actually I'm glad you didn't, it's quite large after all.
jue
Here's the Perl code.
----------
#! perl
# http://xahlee.org/tree/tree.html
# Xah Lee, 2005-05
#_____ Range _____ _____ _____ _____
=pod
B<Range>
Range($iMax) generates the list [1, 2, ... , $iMax].
Range($iMin, $iMax) generates the list [$iMin, ... , $iMax].
Range($iMin, $iMax, $iStep) uses increment $iStep, with the last
element in the result being less or equal to $iMax. $iStep cannot be 0.
If $iStep is negative, then the role of $iMin and $iMax are reversed.
If Range fails, 0 is returned.
Example:
Range(5); # returns [1,2,3,4,5]
Range(5,10); # returns [5,6,7,8,9,10]
Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]
Range( 5, -4, -2); # returns [5,3,1,-1,-3]
=cut
sub Range ($;$$) {
if (scalar @_ == 1) {return _rangeFullArgsW ithErrorCheck(1 ,$_[0],1);};
if (scalar @_ == 2) {return
_rangeFullArgsW ithErrorCheck($ _[0],$_[1],1);};
if (scalar @_ == 3) {return
_rangeFullArgsW ithErrorCheck($ _[0],$_[1],$_[2]);};
};
sub _rangeFullArgsW ithErrorCheck ($$$) {
my ($a1, $b1, $dx) = @_;
if ($dx == 0) {print "Range: increment cannot be zero."; return 0}
elsif ($a1 == $b1) {return [$a1];}
elsif ( ((($b1 - $a1) > 0) && ($dx < 0)) || ((($b1 - $a1) < 0) && ($dx 0)) ) {print "Range: bad arguments. You have [$a1,$b1,$dx]"; return
0;}
elsif ((($a1 < $b1) && ($b1 < ($a1 + $dx))) || (($a1 > $b1) && ($b1 >
($a1 + $dx)))) {return [$a1];}
else { return _rangeWithGoodA rgs ($a1,$b1,$dx);} ;
};
sub _rangeWithGoodA rgs ($$$) {
my ($a1, $b1, $dx) = @_;
my @result;
if ($a1 < $b1) {for (my $i = $a1; $i <= $b1; $i += $dx) { push
(@result, $i);}; }
else {for (my $i = $a1; $i >= $b1; $i += $dx) { push (@result, $i);};
};
return \@result;
};
#end Range
##########
# test
use Data::Dumper;
print Dumper(Range(5, 7,0.3));
Here's the Python solution.
----------
# -*- coding: utf-8 -*-
# Python
# http://xahlee.org/tree/tree.html
# Xah Lee, 2005-05
# implementation note: When iStep is a decimal, rounding error
# accumulates. For example, the last item returned from
# Range(0,18,0.3) is 17.7 not 18. A remedy is to turn iStep into a
# fraction and do exact arithmetics, and possibly convert the result
# back to decimal. A lesser workaround is to split the interval as to
# do multiple smaller range and join them together.
def Range(iMin, iMax=None, iStep=None):
if (iMax==None and iStep==None):
return Range(1,iMin)
if iStep==None:
return Range(iMin,iMax ,1)
if iMin <= iMax and iStep > 0:
if (isinstance(iSt ep,int) or isinstance(iSte p,long)):
return range( iMix, iMax, iStep)
else:
result=[];temp=iStep
while iMin <= iMax:
result.append(i Min)
iMin += iStep
return result
# test
print Range(0, 18, 0.3)
Xah Lee wrote: Here's the Python solution. # implementation note: When iStep is a decimal, rounding error # accumulates. For example, the last item returned from # Range(0,18,0.3) is 17.7 not 18. A remedy is to turn iStep into a # fraction and do exact arithmetics, and possibly convert the result # back to decimal. A lesser workaround is to split the interval as to # do multiple smaller range and join them together.
Good lord no! The correct way is to use an integer count and simply
multiply it each time by the step, and add that to the range. No
accumulation of errors then. Where did you learn to program?
(Rhetorical question of course, as you haven't, yet.)
def Range(iMin, iMax=None, iStep=None): if (iMax==None and iStep==None): return Range(1,iMin) if iStep==None: return Range(iMin,iMax ,1) if iMin <= iMax and iStep > 0: if (isinstance(iSt ep,int) or isinstance(iSte p,long)): return range( iMix, iMax, iStep) else: result=[];temp=iStep while iMin <= iMax: result.append(i Min) iMin += iStep return result
That's some of the worst Python code I've seen recently. Please, no one
take this as representative of how decent Python programmers write code.
-Peter
the previous posted solutions are badly botched.
Here's a better solution. Any further correction will appear on the
website instead. ( http://xahlee.org/tree/tree.html)
Similar change needs to be made for the Perl code... Java code will
come tomorror.
By the way, the code from me are not expected to be exemplary. These
are exercises for all, also as a intro to functional programing to
industry programers. Also, later on there will be non-trivial problems.
# -*- coding: utf-8 -*-
# Python
# http://xahlee.org/tree/tree.html
# Xah Lee, 2005-05
import math;
def Range(iMin, iMax=None, iStep=None):
if (iMax==None and iStep==None):
return Range(1,iMin)
if iStep==None:
return Range(iMin,iMax ,1)
if iMin <= iMax and iStep > 0:
if (isinstance(iSt ep,int) or isinstance(iSte p,long)):
return range( iMin, iMax+1, iStep)
else:
result=[]
for i in range(int(math. floor((iMax-iMin)/iStep))+1):
result.append( iMin+i*iStep)
return result
if iMin >= iMax and iStep < 0:
if (isinstance(iSt ep,int) or isinstance(iSte p,long)):
return range( iMin, iMax-1, iStep)
else:
result=[]
for i in range(int(math. floor((iMin-iMax)/-iStep))+1):
result.append( iMin+i*iStep)
return result
# raise error about bad argument. To be added later.
# test
print Range(5,-4,-2)
# Thanks to Peter Hansen for a correction.
Xah xa*@xahlee.org
∑ http://xahlee.org/
Xah Lee wrote: the previous posted solutions are badly botched.
def Range(iMin, iMax=None, iStep=None):
[snip hideous code]
# Thanks to Peter Hansen for a correction.
Ohmigod, he's only made it worse and he's blaming me for it. Shows what
I get for replying to a cross-posted troll message.
Xah, don't use my name in reference to anything you do, ever, even if
it's only to try to give me credit.
-Peter
On 15 May 2005 02:50:38 -0700, Xah Lee <xa*@xahlee.org > wrote: Here's the Perl code.
Where did you learn to program? Its highly unlikely that a Perl
programer would ever write a range function as there is a built in
Perl function that does the same thing. If your intent is purely
accedemic then the first thing you should do is learn Perl to a much
higher grade.
#! perl
# http://xahlee.org/tree/tree.html # Xah Lee, 2005-05
#_____ Range _____ _____ _____ _____
=pod
B<Range>
Its considered poor style to have function names with capital
letters. The normal convention is to use all lower case.
Range($iMax) generates the list [1, 2, ... , $iMax].
Range($iMin, $iMax) generates the list [$iMin, ... , $iMax].
Range($iMin, $iMax, $iStep) uses increment $iStep, with the last element in the result being less or equal to $iMax. $iStep cannot be 0. If $iStep is negative, then the role of $iMin and $iMax are reversed.
If Range fails, 0 is returned.
Example:
Range(5); # returns [1,2,3,4,5]
Range(5,10); # returns [5,6,7,8,9,10]
Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8]
Range( 5, -4, -2); # returns [5,3,1,-1,-3]
=cut
sub range {
return [1..$_[0]] if (@_==1);
return [$_[0]..$_[1]] if (@_==2);
my $lowest = shift;
my $greatest = shift;
my $increment = shift;
my $steps = ($greatest - $lowest)/$increment;
my @return = map { $_ * $increment + $lowest } (0..$steps);
return \@return;
}
This does as you wish but it far shorter and I would argue easyer for
the typical perl programer to read.
sub Range ($;$$) { if (scalar @_ == 1) {return _rangeFullArgsW ithErrorCheck(1 ,$_[0],1);}; if (scalar @_ == 2) {return _rangeFullArgsW ithErrorCheck($ _[0],$_[1],1);}; if (scalar @_ == 3) {return _rangeFullArgsW ithErrorCheck($ _[0],$_[1],$_[2]);}; };
I would suggest that If you have the case where your doing a one line
if stament then you should make use of the line modifing verent of
if. Also since if produces a scalar context its not needed.
sub Range ($;$$) {
return _rangeFullArgsW ithErrorCheck(1 ,$_[0],1) if (@_ == 1);
return _rangeFullArgsW ithErrorCheck($ _[0],$_[1],1) if (@_ == 2);
return _rangeFullArgsW ithErrorCheck($ _[0],$_[1],$_[2]) if (@_ == 3);
}
See how much neater and more readable the code is after doing that.
sub _rangeFullArgsW ithErrorCheck ($$$) { my ($a1, $b1, $dx) = @_;
if ($dx == 0) {print "Range: increment cannot be zero."; return 0} elsif ($a1 == $b1) {return [$a1];} elsif ( ((($b1 - $a1) > 0) && ($dx < 0)) || ((($b1 - $a1) < 0) && ($dx 0)) ) {print "Range: bad arguments. You have [$a1,$b1,$dx]"; return 0;} elsif ((($a1 < $b1) && ($b1 < ($a1 + $dx))) || (($a1 > $b1) && ($b1 > ($a1 + $dx)))) {return [$a1];} else { return _rangeWithGoodA rgs ($a1,$b1,$dx);} ; };
This would be a great place to make use of die. Throwing an exection for an
error.
sub _rangeFullArgsW ithErrorCheck ($$$) {
my ($a1, $b1, $dx) = @_;
die "Range: increment cannot be zero." unless $dx;
return [$a1] if ($a1 == $b1);
if ( ((($b1 - $a1) > 0) && ($dx < 0))
||
((($b1 - $a1) < 0) && ($dx0))) {
die "Range: bad arguments. You have [$a1,$b1,$dx]";
}
}
sub _rangeWithGoodA rgs ($$$) { my ($a1, $b1, $dx) = @_; my @result;
if ($a1 < $b1) {for (my $i = $a1; $i <= $b1; $i += $dx) { push (@result, $i);}; } else {for (my $i = $a1; $i >= $b1; $i += $dx) { push (@result, $i);}; }; return \@result; };
Personally I don't like the c style while loop. I didn't like it in C
and I don't like it in perl.
--
Please excuse my spelling as I suffer from agraphia. See http://dformosa.zeta.org.au/~dformosa/Spelling.html to find out more.
Free the Memes. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Mark Wilson CPU |
last post by:
This must be easy, but I'm missing something...
I want to execute a Perl script, and capture ALL its output into a PHP
variable. Here are my 2 files:
-------------------------------------
test3.pl
-------------------------------------
print "PERL Hello from Perl! (plain print)<br>\n";
print STDERR "PERL This is text sent to STDERR<br>\n";
$output="PERL Some output:<br>\n";
for ($i=0; $i<5; $i++) {
|
by: John Smith |
last post by:
Hello,
I have a rather odd question. My company is an all java/oracle shop.
We do everything is Java... no matter what it is... parsing of text
files, messaging, gui you name it. My question is this... is Perl so
much better at parsing text files and outputing that we would see a
substantial speed increase? We process about 10 million records in
flat files a day for reformatting before putting them in a DB.
Also, when it comes to...
|
by: David F. Skoll |
last post by:
Hi,
I'm tearing my hair out on this one. I'm trying to embed a Perl
interpreter into a C program. I need to be able to create and destroy
the interpreter periodically, but will never actually have two interpreters
at the same time.
On Red Hat Linux 7.3 with Perl 5.6.1, the attached program segfaults. On
Red Hat 9 with Perl 5.8.0, it works perfectly. Save the program code
as "test-embed-perl.c" and the build script as "buildte". ...
|
by: Julia Bell |
last post by:
I would like to run the same script on two different platforms. The
directory in which the script(s) will be stored is common to the two
platforms. (I see the same directory contents regardless of which
platform I use to access the directory.)
Platform 1: perl is installed in /tps/bin/perl. CPAN modules are available
Perl is also installed in /usr/bin/perl Platform 1, but the modules are
not accessible with this version.
Platform...
|
by: smsabu2002 |
last post by:
Hi,
I am facing the build problem while installing the DBD-MySql perl
module (ver 2.9008) using both GCC and CC compilers in HP-UX machine.
For the Build using GCC, the compiler error is produced due to the
unknown GCC compiler option "+DAportable".
For the Build using CC, the preprocessor error is produced due to the
recursive declration of macro "PerlIO" in perlio.h file.
| |
by: Otto J. Makela |
last post by:
I'm trying to install to php the Perl-1.0.0.tgz package (from
http://pecl.php.net/package/perl, enabling one to call perl libraries)
to a pre-existing Solaris system.
Unfortunately, the attempt fails in a rather dramatic way, spewing out
thousands of "relocation remains"... I'm somewhat lost on what to do
next, the documentation that came along with the Perl package is
somewhat sparse. Anyone have suggestions?
% uname -a
|
by: surfivor |
last post by:
I may be involved in a data migration project involving databases and
creating XML feeds. Our site is PHP based, so I imagine the team might
suggest PHP, but I had a look at the PHP documentation for one of the
Pear modules for creating XML and it didn't look like much. I've used
Perl XML:Twig and I have the impression that there is more Perl stuff
available as well as the Perl stuff being well documented as I have a
Perl DBI book, a Perl...
|
by: Pilcrow |
last post by:
Given that UNIX, including networking, is almost entirely coded in C,
how come so many things are almost impossible in ordinary C? Examples:
Network and internet access, access to UNIX interprocess controls and
communication, locale determination, EBCDIC/ASCII discrimination, etc.
Almost all of these are easy in Perl. Why isn't there a mechanism like
perl modules to allow easy extentions for facilities like these? Isn't
anyone working...
|
by: vijayarl |
last post by:
Hi All,
i have the following software installed in my system :
1.OS: Win2k
2.Eclipse Version used :3.4.0 & even the perl too...
1. I have imported the my own perl project in Eclipse, when i tried to run the External Tools --> Perl -w
am getting the popup saying then it says :
" Variable references empty selection:
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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...
| |
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,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |