473,775 Members | 2,305 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tree functions daily exercise: Range

Here's the belated Java solution.

import java.util.List;
import java.util.Array List;
import java.lang.Math;

class math {
public static List range(double n) {
return range(1,n,1);
}

public static List range(double n, double m) {
return range(n,m,1);
}

public static List range(double iMin, double iMax, double iStep) {
List ll = new ArrayList();
if (iMin <= iMax && iStep > 0) {
for (int i=0; i <= Math.floor((iMa x-iMin)/iStep); i++) {
ll.add(new Double(iMin+i*i Step));
}
return ll;
}
if (iMin >= iMax && iStep < 0) {
for (int i=0; i <= Math.floor((iMi n-iMax)/-iStep); i++) {
ll.add(new Double(iMin+i*i Step));
}
return ll;
}
// need to raise exception here
return ll;
}
}

class Range {
public static void main(String[] arg) {
System.out.prin tln(math.range( 5));
System.out.prin tln(math.range( 5,10));
System.out.prin tln(math.range( 5,7, 0.3));
System.out.prin tln(math.range( 5,-4, -2));
}
}

Perl & Python versions archived here:
http://xahlee.org/tree/tree.html

Xah
xa*@xahlee.org
∑ http://xahlee.org/
Dear functional programers,

i run services called a-python-a-day and a-java-a-day, where each day i

give a tip or snippet of code in these languages, also as a way for me

to learn these languages.

I've been running this perl-python a-day mailing list for several
months, and have accumulated a sizable tutorial here:
http://xahlee.org/perl-python/python.html

In the coming days, i'll be starting to translate a complete set of
tree processing functions. These functions, always takes a tree as
input (arbitrary nested list) and always returns a list of a definite
structure. Together, they form a particular functional programing
paradigm. See this page for the complete documentation as it exists
now:
http://xahlee.org/PerlMathemat ica_dir/Matica.html

As usuall, each day we will be spending about 20 minutes enjoying these

little exercises. If past experience is a good indication, then i
presume that in a month or two we will have built a complete set of
functions that manipulates tress, in languages Python and Java and
Perl. (the Perl set is already written)

I'm always interested in LISP and Haskell languages, but never
seriously learned them. I'm hoping that you functional programers in
these languages or learners, join me in these 15 minutes daily
exercises as a fun routine to learn languages or functional
programing.

I'm in particular very interested in the daily discussions of these
topics by functional programers, as well seeing such set of complete
code in scsh and Haskell. (Common Lisp or other functional languages
are always welcome of course)

Â* Xah
Â* x...@xahlee.org
∑ http://xahlee.org/

Jul 19 '05
15 2670
Xah Lee wrote:

well yes... but this was emulation of Mathematica functions.
(Disclaimer: Mathematica is a trademark of Wolfram Research Inc, who is
not affliated with this project)


You could have fooled me.
Jul 19 '05 #11
Very very nice! I don't know scheme well... but oh the macros, such a
wonderful facility...

Functional lang never let me down.

I haven't worked on a Java version yet... but i wonder what pain i'll
have to endure for a lang that lacks eval. Since i'm not Java expert...
i wonder if i can even do it in a few days.

Xah
xa*@xahlee.org
∑ http://xahlee.org/

David Van Horn wrote:
Xah Lee wrote:
here's the Python spec for the Table function:

...
References:

• for a context of this message, see: http://xahlee.org/tree/tree.htm


Here is a Scheme implementation of Table. As noted on your web page and the
Mathematica documentation, the first argument of Table "evaluates in a
non-standard way". Thus we use Scheme macros to control the evaluation of
this expression. The first three clauses in this syntax definition take care
to fill in the default values for i, imin, and di when they are not provided.
The fourth clause iterates over one variable constructing a list. Notice
this is done tail-recursively. The last clause handles the multiple variable
case by rewriting the term into a simpler form.

(define-syntax table
(syntax-rules ()
((table exp (imax))
(table exp (i 1 imax 1)))

((table exp (i imax))
(table exp (i 1 imax 1)))

((table exp (i imin imax))
(table exp (i imin imax 1)))

((table exp (i imin imax di))
(let loop ((n imin) (accum '()))
(if (< imax n)
(reverse accum)
(loop (+ n di) (cons ((lambda (i) exp) n) accum)))))

((table exp i j ...)
(table (table exp j ...) i))))
;; Examples

(table #t (0)) ;; => '()
(table #t (5)) ;; => '(#t #t #t #t #t)
(table i (i 5)) ;; => '(1 2 3 4 5)
(table i (i 2 5)) ;; => '(2 3 4 5)
(table i (i 2 5 2)) ;; => '(2 4)
(table i (i 2 6 2)) ;; => '(2 4 6)
(table (add1 i) (i 2 6 2)) ;; => '(3 5 7)
(table (- i j) (i 2) (j 2)) ;; => '((0 -1) (1 0))

(table (list i j k) (i 2) (j 100 200 100) (k 5 6))
;; =>
'((((1 100 5) (1 100 6)) ((1 200 5) (1 200 6)))
(((2 100 5) (2 100 6)) ((2 200 5) (2 200 6))))


Jul 19 '05 #12
Xah Lee wrote:
Very very nice! I don't know scheme well... but oh the macros, such a
wonderful facility...

Macros suck. They created by moron so-called computer scientists and IT
puntits in order opress the programming masses. But I say we must bring
freedom to all programmers. In order abolish this criminality against
humanity and even programmers, I recommend creating a flurry of
irrelevant messages cross-posting to noncommonalitou s groups. If you
need dictionary to find what that word means, you a moron! F*ck
dictionaries! F*ck macros! F*ck ignoramous computer scientists! F*ck
so-called netiquette! Power to programmers!

Only when we have created sufficient confusion and frustration among all
programming entities, then they will beg us to shut up. Only then they
be willing remove macros from all languages if we willing shut up. Then
we shut up and see macros removed. But only for a little while. Then
we campaign to get floating point roman numerals implemented.
Functional lang never let me down.

Functional languages evil. Any language support functions come from
ivory tower brain lacking idiots who think they know something. All
other languages should take a lesson from Python which does not support
functions. If Python supports functions, I have not read that informations.
I haven't worked on a Java version yet... but i wonder what pain i'll
have to endure for a lang that lacks eval. Since i'm not Java expert...
i wonder if i can even do it in a few days.

Xah
xa*@xahlee.org
∑ http://xahlee.org/


Power to programmers!

JJ
Jul 19 '05 #13
Dear Mr. Jones:

Our team of 3,972 expert testers judged the output of your
troll-spewing neural net virtually indistinguishab le from the original.
Given this, I am please to announce that our firm is willing to
discuss arrangements for an exclusive license that you would likely
find financially compelling. Please do not post the code on
sourcefurge or whatever you call that open source thing until you speak
with us.

S. Ballmer

Jul 19 '05 #14
Xah Lee wrote:
oops, another error. The example should be:

Table(f,[1,2,1],[2,6,2]) returns
[[f(1,2),f(1,4),f (1,6)],[f(2,2),f(2,4),f (2,6)]]
Wouldn't it be more sensible just to take the iterators directly as
arguments, so for this example you would do:

Table(f, range(1,3), range(2,7,2))


well yes... but this was emulation of Mathematica functions.
(Disclaimer: Mathematica is a trademark of Wolfram Research Inc, who is
not affliated with this project)

What you suggested is a function called Outer in Mathematica. The Table
function is in a sense multi-dimentional version of Range, so they
share syntax form.

Ok, so, if I understand you, the definition of Table is just:

def Table(f, *lists):
return Outer(f,
*[range(start,end +1,step) for (start,end,step ) in lists])

Is that about right?
Jul 19 '05 #15
Duncan Booth wrote:
Ok, so, if I understand you, the definition of Table is just:

def Table(f, *lists):
return Outer(f,
*[range(start,end +1,step) for (start,end,step ) in lists])

Is that about right?


And lest you think I left a bit too much as an "exercise for the
reader":

-------------- xah.py --------------------
def Table(f, *lists):
"""Xah Lee's Table function
Table(f,[3,10,2]) [f(3), f(5), f(7), f(9)] Table(f,[1,2,1],[2,6,2]) [[f(1, 2), f(1, 4), f(1, 6)], [f(2, 2), f(2, 4), f(2, 6)]]
"""
return Outer(f, *[range(start,end +1,step) for (start,end,step ) in lists])

def explode(lists):
"""Form all combinations of 1 element from each list. explode([[1,2], [3]]) [(1, 3), (2, 3)] explode([[1,2], [3,4]]) [(1, 3), (1, 4), (2, 3), (2, 4)] explode([[1,2], [3,4], [5]]) [(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]
"""
result = [()]
for l in lists[::-1]:
result = [ (val,) + tail for val in l for tail in result ]

return result

def groupsOfN(it, n):
"""Returns tuples of length n taken from it. groupsOfN(range (12), 3) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)] groupsOfN(range (12), 1) [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,)]
"""
it = iter(it)
return zip(*([it]*n))

def Outer(f, *lists):
""" Outer(f, range(1,3), range(2,7,2))

[[f(1, 2), f(1, 4), f(1, 6)], [f(2, 2), f(2, 4), f(2, 6)]]
"""
result = [f(*args) for args in explode(lists)]
for l in lists[:0:-1]:
result =[list(v) for v in groupsOfN(resul t, len(l))]
return result

def _test():
global f
class f:
def __init__(self, *args):
self.args = args
def __repr__(self):
if len(self.args) == 1:
return "%s(%r)" % (self.__class__ .__name__.split ('.')[-1], self.args[0])
else:
return "%s%r" % (self.__class__ .__name__.split ('.')[-1], self.args)

import doctest
doctest.testmod ()

if __name__ == "__main__":
_test()
------------------------------------------
Jul 19 '05 #16

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

Similar topics

99
5924
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the changes unecessary to this discussion. I left in the change of "instance variable" syntax (...
4
10763
by: August1 | last post by:
A handful of articles have been posted requesting information on how to use these functions in addition to the time() function as the seed to generate unique groups (sets) of numbers - each group consisting of 6 numbers - with a total of 50 groups of numbers. A well-known girl that some publishing companies use to provide introductory level textbooks to various Junior Colleges in the U.S., not surprisngly, asks for this same exact...
19
6787
by: Christian Fowler | last post by:
I have a VERY LARGE pile of geographic data that I am importing into a database (db of choice is postgres, though may hop to oracle if necessary). The data is strictly hierarchical - each node has one, and only one parent. The depth should not exceed 6 or 7 levels. The initial import will have about 6 million leaves, and 3 million branches. I would expect the leaves to grow significantly, in number easily tripling. However, the branches will...
2
3486
by: Kiran | last post by:
Hello all, I am using a tree to display stuff, and it is constantly updated, but what I have noticed is in the lowest level, there is clearly noticable cutoff of the text I place there. The cutoff is existent even if I do not update the text inside the tree constantly. It seems that the text is halfway below where it should line up. I tried placing an image to see if that would correct it, but it does not. The image is perfectly lined up,...
9
7831
by: raylopez99 | last post by:
What's the best way of implementing a multi-node tree in C++? What I'm trying to do is traverse a tree of possible chess moves given an intial position (at the root of the tree). Since every chess position has around 30 moves, it would mean every node of the tree would have 30 branches (on average), which in turn themselves would average about 30 branches each. I can think of a variety of ways of implementing this, including a series...
2
4443
by: uche | last post by:
Guys, I am trying to build a Parse Tree with the following grammar. I have implemented my insertions using a standard binary tree inserting algorithm. With the psuedocode below, can you guys provide any helpful feedback to placing insert statements into building nodes of the tree. Any suggestions on how to build the tree will be appreciated. I hope to build the tree to look like that 5+4 Goal
2
2251
by: Bart Kastermans | last post by:
Summary: can't verify big O claim, how to properly time this? On Jun 15, 2:34 pm, "Terry Reedy" <tjre...@udel.eduwrote: Thanks for the idea. I would expect the separation to lead to somewhat more code, but all the "checking the root" code would be separated out in the tree class. The node class would be very smooth. I'll try this when I have
4
3302
by: Mensanator | last post by:
With the new functions added to itertools in Python 2.6, I can finally get rid of this monstrosity: def ooloop6(a, n, perm=True, repl=True): if (not repl) and (n>len(a)): return r0 = range(n) r1 = r0 if perm and repl: # ok v = ','.join() f = ' '.join()
2
7379
by: cioccolatina | last post by:
Hey guys, is there anyone who could help me..? I have file ExpressionBinaryTree.java : /** class ExpressionBinaryTree * uses a binary tree to represent binary expressions * does not implement BinaryTree - all iterators return String */ package foundations;
0
9621
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
9454
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,...
0
10267
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...
1
10046
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
9915
tracyyun
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...
0
6717
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
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4014
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
3611
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.