From: William James Date: 2005-09-20T16:51:38+09:00 Subject: Re: ruby idiom for python's for/else while/else Brian Mitchell wrote: > On 9/19/05, Jeremy Tregunna wrote: > > > > On 19-Sep-05, at 7:15 PM, Gergely Kontra wrote: > > > > > Hi! > > > > > > Is there a similar construct to python's: > > > > > >>>> for n in range(2, 10): > > > ... for x in range(2, n): > > > ... if n % x == 0: > > > ... print n, 'equals', x, '*', n/x > > > ... break > > > ... else: > > > ... # loop fell through without finding a factor > > > ... print n, 'is a prime number' > > > ... > > > 2 is a prime number > > > 3 is a prime number > > > 4 equals 2 * 2 > > > 5 is a prime number > > > 6 equals 2 * 3 > > > 7 is a prime number > > > 8 equals 2 * 4 > > > 9 equals 3 * 3 > > > > Directly, yes; though hardly anybody writes code this way (at least > > I've never seen anybody write something like this, like how I'm about > > to give it to you). I'd see William Morgan's message for a better > > suggestion. > > > > # I hate for loops > > 2.upto(10) do |n| # was => for n in (2..10) do > 2.upto(n) do |x| # was => for x in (2..n) do > > if n % x == 0 > > puts "#{n} equals #{x} * #{n/x}" > > break > > else > > puts "#{n} is a prime number" > > end > > end > > end > > > > Though, I think this is broken... check the output. > > > > Gergo > > > > -- > > Jeremy Tregunna > > jtregunna@blurgle.ca > > > > "If debugging is the process of removing bugs, then programming must be > > the process of putting them in." --Dykstra > > > > I still think lists are the nicest way to go about this. It could be > much improved but this is shorter: > (2..10).select {|n| (2..n).select {|x| n % x == 0 and n != x }.empty? } > > Brian, (2...50).select{|n|(2..Math.sqrt(n).to_i).select{|x|n % x == 0}.empty?} --> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]