I want to understand what the code really translates into python3 as i cant follow along with it in racket. thank you!
(define set-equal?
(lambda (s1 s2)
(and (set-subset? s1 s2)
(set-subset? s2 s1))))
(define set-subset?
(lambda (s1 s2)
(or (null? s1)
(and (member (car s1) s2)
(set-subset? (cdr s1) s2)))))
I'm not a Racket expert, but I can at least read that code and figure out what it does.
Let's start with set-subset?
. This is a recursive function that takes two lists, s1
and s2
, and returns whether every item in s1
is within s2
. This function works by returning whether s1
is empty, or whether the first element of s1
is a member of s2
and the list of all elements in s1
other than the first is a subset of s2
.
(null? s1)
returns whether the list s1
is empty, (car s1)
returns the first element of s1
and (cdr s1)
returns all elements of the list s1
other than the first.
You could perhaps translate this into Python as
def set_subset(s1, s2):
return (not s1) or (s1[0] in s2 and set_subset(s1[1:], s2))
although this does assume that s1
and s2
are list
s not set
s. (If s1
is a set, you can't call s1[0]
or s1[1:]
.)
set-equal?
builds on set-subset?
: two sets are equal if both of them are a subset of each other. Again, this would translate into Python as
def set_equal(s1, s2):
return set_subset(s1, s2) and set_subset(s2, s1)
These functions assume that the lists don't have any repeated values.
However, if you are using set
objects in Python 3, you don't need either of these functions, as Python 3 already has these operations built in: (set-subset? s1 s2)
in Racket is equivalent to s1.issubset(s2)
in Python 3, and (set-equal? s1 s2)
to s1 == s2
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.