A
A
Alexey Poloz2017-04-02 14:20:11
Python
Alexey Poloz, 2017-04-02 14:20:11

Python What is the best way to check if there is a common element?

There is a string a and a tuple signs how can the code be shortened as much as possible so that the function checks if there is at least one of the signs in this string?

signs=('.','!','?')
def sign(a):
  t=False
  for i in a:
    if i in signs:
      t=True
      break
  return t
...
if sign(text[i].cont) and (i!=len(text)-1):
...

And is it possible to replace the function with lambda, use map?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
longclaps, 2017-04-02
@kosyachniy

Why lambda when there is a standard library:

s = "здесь есть знаки препинания?"
print(any(c in ".!?" for c in s))

Output:
With a lambda and a map, both are longer and slower due to the overhead of calling the lambda. Set is slower due to set generation. An any expression and a lazy generator are faster and do not consume resources.

E
Eugene, 2017-04-02
@Eugen_p

If you absolutely need through map, and it doesn’t matter that a little more action will be performed.
any(map(lambda x: x in signs, a))

A
Alexander, 2017-04-02
@fireSparrow

signs=('.','!','?')
sign = lambda a: bool(set(a) & set(signs))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question