2

If I have string "axplpett" I would like to return true, because a substring of it "axplpe" contains all of the letters of apple.

I was thinking of using the set method, but apple has repeating characters.

user1569897
  • 437
  • 1
  • 5
  • 12
  • why not do a simple iteration of substrings of a string, and check whether each letter of substring contained in string. – Srinivas Reddy Thatiparthy Nov 06 '17 at 06:05
  • " because a substring of it "axplpe" contains all of the letters of apple. " This needlessly complicates the problem. We can simply check whether the entire `axplpett` string contains the letters – Karl Knechtel Aug 01 '22 at 21:25

4 Answers4

2
r = 'aapple'
w = list('axplpett')
try:
    for x in r:
        w.pop(w.index(x))
    print(True) # return True
except ValueError:
    print(False) # return False
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
  • 1
    No you are wrong in the general case try "aaa" vs "abc": set("aaa") is {"a"} which is contained in set("abc") but no substring of "abc" is anagram of "aaa" – Julien Nov 06 '17 at 06:09
  • 1
    @Julien Redesigned the code to be strict about the count of each letter. – AGN Gazer Nov 06 '17 at 06:21
2

Simply this?

string = "axplpett"
test = "apple"
all(string.count(l) >= test.count(l) for l in test)
Julien
  • 13,986
  • 5
  • 29
  • 53
1

You can easily do this with a Counter.

We subtract the count of letters in the target string 'apple' from the count of letters in the test string 'axplpett'. Any letters in the target string that aren't in the test string will result in negative counts for those letters. We then negate that result, which strips off positive or zero counts, the resulting counter will be empty if the target string is contained within the test string.

from collections import Counter

target = 'apple'
test = 'axplpett'
counts = Counter(test)
counts.subtract(target)
print(not -counts)

counts = Counter('axplett')
counts.subtract(target)
print(not -counts)

output

True
False
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

Maybe this:-

def findsub (sub,main):
    l1 = [i for i in sub]
    l2 = [i for i in main]
    for item in l1:
        if item in l2:
            l2.remove(item)
        else:
            return False
    return True
print(findsub('apple','appleccssfftt'))
Abhijeetk431
  • 847
  • 1
  • 8
  • 18