Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

python - Understanding set comparison

So, my problem is to understand comparison between lists.

I had a homework to compare if some string has all the letters from the alphabet, so i did this:

import string


def ispangram(str):

  letters = ''.join(str.split()).lower()
  unique_letters = set(letters)
  sorted_list = list(sorted(unique_letters))
  str_alphabet = ''.join(sorted_list)

  alphabet = string.ascii_lowercase

  if str_alphabet == alphabet:
      print(True)
  else:
      print(False)


ispangram("The quick brown fox jumps over the lazy dog")

Ok, i got True, thats fine. But the other way for the answer is:

import string


def ispangram(str):
  alphabet = string.ascii_lowercase
  alphaset = set(alphabet)

  return alphaset <= set(str.lower()):


ispangram("The quick brown fox jumps over the lazy dog")

So this "<=" that i cant understand. It compares letter by letter in the set unique list? Or it just compare the lenght of it? Because without joining i get Space ' ' too. And how does "<=" compare if only "set(str.lower())" does not sort every letter?

Hope somebody could help me, thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The operator <= for sets, checks if the operand on the LHS is a subset of the one on the RHS.

More verbosely:

alphaset.issubset(my_str.lower()) # issubset takes any iterable

On a side note, be careful to not use str as a name to not make the builtin str unusable within your function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...