Home > Mobile >  Convert to Racket(Scheme)
Convert to Racket(Scheme)

Time:04-23

I have this code that works, on python. I am new to DRrACKET, how can I translate it into DRrACKET. I am struggling to write a DRrACKET code that produces the exact result.

Your help is highly appreciated.

# python program to find the length of the largest subarray which has all contiguous elements 

def length_sub_(arr, n):
max_len = 1
for i in range(0,n - 1):

    myset = set()
    myset.add(arr[i])

    # Initialize max and min in
    # current subarray
    mn = arr[i]
    mx = arr[i]
    for j in range(i   1,n):

        # If current element is already
        # in hash set, then this subarray
        # cannot contain contiguous elements
        if arr[j] in myset:
            break


        # Else add current element to hash
        # set and update min, max if required.
        myset.add(arr[j])
        mn = min(mn, arr[j])
        mx = max(mx, arr[j])

        # We have already checked for
        # duplicates, now check for other
        #property and update max_len
        # if needed
        if mx - mn == j - i:
            max_len = max(max_len, mx - mn   1)

 return max_len # Return result



arr = [6, 1, 1, 10, 10, 111, 100]
print("Length of the longest contiguous subarray is : ",
                            length_sub_(arr,len(arr)))

Expected output:

Length of the longest contiguous subarray is : 2

My DRrACKET start

(define max-repeated-length (lambda (L)
    (cond
       
   )
 )

CodePudding user response:

One nice thing about Scheme is that it encourages you to look for elegant solutions rather than the creeping horror in the question, safe in the knowledge that the elegant solution will generally also be the efficient one.

So, since this is, I think, rather obviously a homework problem and I don't really want to help people cheat, here is an elegant solution in Python. In Python this will perhaps not be efficient, especially for long arrays. Turned into Racket it is both the obvious solution and efficient.

def longest_contiguous(a):
    l = len(a)
    def loc(i, current, this, best):
        # i is current index, current is the element in the current
        # run, this is the length of the current run, best is the
        # length of the longest run.
        if i == l:              # we're done
            return best if best > this else this
        elif a[i] == current:   # in a run
            return loc(i   1, current, this   1, best)
        else:                   # new run
            return loc(i   1, a[i], 1, best if best > this else this)
    return loc(0, a[0], 1, 1) if l > 0 else 0

And here is such an elegant solution in Racket: framed in such a way that, again, it probably can't be submitted as homework. This will work on both vectors and lists, and indeed many other things. And as well as the length of the longest contiguous sequence, it will tell you where that sequence starts.

(require racket/stream
         racket/generic)

(define-generics to-stream
  ;; Turn something into a stream in a way which could be extended
  (->stream to-stream)
  #:fast-defaults
  ((stream?
    (define ->stream identity))
   (sequence?
    (define ->stream sequence->stream))))

(define (length-of-longest-contiguous-subthing thing
                                               #:same? (same? eqv?)
                                               #:count-from (count-from 0))
  (define s (->stream thing))
  (if (stream-empty? s)
      (values 0 count-from)
      (let los ([st (stream-rest s)]
                [current (stream-first s)]
                [count (  count-from 1)]
                [this 1]
                [this-start 0]
                [best 0]
                [best-start 0])
        (cond
          [(stream-empty? st)
           (if (> this best)
               (values this this-start)
               (values best best-start))]
          [(same? (stream-first st) current)
           (los (stream-rest st) current (  count 1)
                (  this 1) this-start
                best best-start)]
          [else
           (if (> this best)
               (los (stream-rest st)
                    (stream-first st) (  count 1)
                    1 count
                    this this-start)
               (los (stream-rest st)
                    (stream-first st) (  count 1)
                    1 count
                    best best-start))]))))

Now, for instance:

> (length-of-longest-contiguous-subthing '(1 2 3 4 4 5 6 6 6 7))
3
6

The longest contiguous subsequence is 3 elements log and starts at the 6th element.

But also:

> (call-with-input-file
   "/tmp/x"
   (λ (p)
     (length-of-longest-contiguous-subthing (in-lines p)
                                            #:same? string=?
                                            #:count-from 1)))

The longest sequence of identical lines in /tmp/x is 2, and it starts at line 2, counting from 1.

CodePudding user response:

(This answer will be updated as the question is updated with research effort)

Attempting to "translate" from Python is probably not the best approach when learning Scheme/Racket; try starting with this stub, and following the Racket How To Design Functions design recipe:

(define (length-longest-section-of-equals lon) ;; ListOfNumber -> Natural
  ;; produce length of longest section of lon with equal elements
  0)

(check-expect (length-longest-section-of-equals '()) 0)

(check-expect (length-longest-section-of-equals '(6 1 1 10 10 111 100)) 2)

(In DrRacket, choose "Beginning Student with List Abbreviations" from the Languages menu, copy and paste the above code, and Run)

  • Related