Akira Wang
Akira Wang

Reputation: 53

Python looking to find an easier way to shorten my .casefold().count()

My python code is running fine but the code looks a bit tedious and messy. I was wondering if there was an easier way to write it. I have a text file and I am required to find if the letters 'aardvark' can be found inside the line.

if i.casefold().count('a') >= 3 and i.casefold().count('r') >= 2 and i.casefold().count('d') >= 1 and i.casefold().count('v') >= 1 and i.casefold().count('k') >=1:

Upvotes: 1

Views: 50

Answers (2)

ddg
ddg

Reputation: 1098

if all(
 i.casefold().count(letter) >= 'aardvark'.count(letter)
 for letter in 'aardvark')

kinda a silly solution but it works

Upvotes: 0

jq170727
jq170727

Reputation: 14655

Here is an interactive demonstration of a solution:

>>> i = 'this is a test'
>>> all(i.casefold().count(x) >= y for x,y in [('a',3), ('r',2), ('d', 1), ('v',1)])
False

>>> i = 'ardv'*4
>>> i
'ardvardvardvardv'

>>> all(i.casefold().count(x) >= y for x,y in [('a',3), ('r',2), ('d', 1), ('v',1)])
True

Upvotes: 0

Related Questions