Proper Subset function in Python - python

I want a function that will say if a subset is proper. So if they are identical it will return True, if they aren't then False. I have a very simple design but it doesn't account for the set's properties, which is if there are duplicates in the set it will delete them. It will also be identifical if one set is IN the other set.
Here's my code:
def proper_subset(S,T):
if S == T:
return True
else:
return False
Here's some test cases on what it does and what it SHOULD do:
#What it does
S = {1,2}
T = {1,2,3}
proper_subset(S,T)
>>> False
#What it should do
S = {1,2}
T = {1,2,3}
proper_subset(S,T)
>>> True
Please help!

In python the set entity supports addition and subtraction. So you can just check the lengths of the subtraction operations.
def properSubset(S,T):
return len(S-T)==0 and len(T-S)>0
Also as the comments mention you can just use '<'
def properSubset(S,T):
return S<T

Related

similar code logic, two different answers

why does the output of these two functions give different outputs when the logic or idea is the same and they are working with the same string?
def solution(inputString):
a = ""
b = a[::-1]
if a == b:
return True
else:
return False
print(solution("az"))
def ans(something):
if something == reversed(something):
print(True)
else:
print(False)
ans('az')
This is I think because you are not using your inputString parameter in the function solution(). This may be closer to what you want:
def solution(inputString):
a = inputString
b = a[::-1]
if a == b:
return True
else:
return False
when the logic or idea is the same
No, the solution and ans functions have different logic.
solution uses the common way of reversing a string, thats fine
However, the second function uses reversed() function, which does:
reversed(seq)
Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol ...
It does not return the reversed string as you'd probably expected.
To put that in perspective, the following code returns False:
print("oof" == reversed("foo"))
Because the return value of reversed("foo") is an <reversed object> and not the reversed String.

Trying to return True if lists do NOT share elements, False otherwise. Minimum code

Hoping to get some assistance. Trying to return True if they DON'T share any elements, False otherwise, while working on improving my "minimalist" coding (I can do this in multiple lines, but want to complete this in a line or two).
I am able to obtain True in single test, not able to get False in multiple test when written in different ways. Here is what I have currently:
def different(listx, listy):
return any(listx) == any(listy)
Suggestions?
Thank you.
Probably the easiest way to do this is cast each list to a set. From the docs a set is defined as:
A set object is an unordered collection of distinct hashable objects.
from there check if those sets are disjoint using the isdisjoint method.
return set(listx).isdisjoint(set(listy))
Set intersection:
print (0 == len(set(listx).intersection(set(listy))))
Perhaps not as performant as the other answers, but more readable in my opinion:
An expanded method, to help you see through the operations:
def different(listx, listy):
"""Will return True if lists don't have any common values."""
n_shared = 0
for x in listx:
if x in listy:
n_shared+=1
if n_shared==0:
return True
else:
return False
A more minimal approach:
def different(listx, listy):
"""Will return True if lists don't have any common values."""
shared = [x for x in listx if x in listy]
if len(shared)==0:
return True
else:
return False

Python Identifying Suffix within set of strings

doing an exercise on CheckIO and I'm wondering as to why this won't work. Given a set of strings, I'm trying to return True if any of the strings are suffixes of any other string in the set. False otherwise. Using itertools I'm generating the necessary permutations in tuples first. Then for each tuple (each i), I wanted to see the hard way if the second tuple was in the end of the first tuple (option1). The otherway was using the .endwith function (option2), but neither will work for me. Why are these two options flawed?
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
#option1 ---- if i[1] in i[0][-len(i[1]):]:
#option2 ---- if i[0].endswith(i[1]):
return True
else:
return False
examples:
checkio({"hello", "lo", "he"}) == True
checkio({"hello", "la", "hellow", "cow"}) == False
I know this works as an answer. But just wondering why my original methods wouldn't take.
def checkio(words_set):
for w1 in words_set:
for w2 in words_set:
if w1.endswith(w2) and w1 != w2:
return True
return False
Your return False should be at the end of the for loop, otherwise the function will return True/False at every first comparison and will ignore all subsequent comparisons:
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
if i[0].endswith(i[1]):
return True
return False
Since it's an exercise, I won't give you the full answer, but are you sure that you really want to return False in the else clause?
Its because you return False right after the first check. and if it fails it will returns False you need to put it out of your for loop!
But as a more pythonic way you can use combinations and a generator expression within any function :
>>> from itertools import combinations
>>> s={"hello", "lo", "he"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s,2)))
True
>>> s2={"hello", "la", "hellow", "cow"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s2,2)))
False

What is the difference between None check and var or default syntax in Python?

I noted this syntax listed as a gotchya but with no explanation as to why:
def func(x=None):
#good
if x == None:
x = []
#bad
x = x or []
In what ways can this be a gotchya?
In this particular case, it’s bad because an empty list evaluates to false. If you mutate the list, then the results won’t be as expected
def func(x=None):
x = x or []
x.append('hello')
mylist = []
func(mylist)
print mylist[0] # doesn't work
Since you want to check to see if the caller passed None or not, you should just say that explicitly and not try to be clever. Objects like [], (), {}, 0, and False evaluate to false, as can any user-defined object that wants to — checking for falsehood really catches too many false positives.
(Also: Using is None instead of == None can be faster and more reliable.)
x or [] will return an empty list if bool(x) is false. None is false, but zeros (ints, longs, floats, etc) and empty collections ([], {}, "", etc) are also false. So this isn't catching None, it's catching falsy object - which isn't equivalent to x == None and most likely not what you want (empty collections are perfectly valid input for many algorithms).
Oh, and while we're at it: That should be x is None - is is the semantically correct (and propably faster) choice for testing identity. == can be overwritten by x, and you can't be sure if it won't consider None equal to itself or even break on it.
I think the best idiom to check for any python singleton is:
if x is None:
x = []
The reason is that some objects like ORM objects in django or sqlalchemy, for example, are lazy (they will not call the database until the latest possible time). Using the other options to check for None may trigger evaluation of an expensive operation.

What is the difference between "is None" and "== None"

I recently came across this syntax, I am unaware of the difference.
I would appreciate it if someone could tell me the difference.
The answer is explained here.
To quote:
A class is free to implement
comparison any way it chooses, and it
can choose to make comparison against
None mean something (which actually
makes sense; if someone told you to
implement the None object from
scratch, how else would you get it to
compare True against itself?).
Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.
class Foo:
def __eq__(self,other):
return True
foo=Foo()
print(foo==None)
# True
print(foo is None)
# False
In this case, they are the same. None is a singleton object (there only ever exists one None).
is checks to see if the object is the same object, while == just checks if they are equivalent.
For example:
p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent
But since there is only one None, they will always be the same, and is will return True.
p = None
q = None
p is q # True because they are both pointing to the same "None"
It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.
In particular the output of a == None does not even have to be boolean !! - a frequent cause of bugs.
For a specific example take a numpy array where the == comparison is implemented elementwise:
import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False
If you use numpy,
if np.zeros(3)==None: pass
will give you error when numpy does elementwise comparison

Categories

Resources