diff options
| author | E7-87-83 <fungcheokyin@gmail.com> | 2021-06-09 16:21:12 +0800 |
|---|---|---|
| committer | E7-87-83 <fungcheokyin@gmail.com> | 2021-06-09 16:21:12 +0800 |
| commit | c0e6f7597cc064e00bc42794780a55b424cfdba9 (patch) | |
| tree | 531f8174a2e595db1c94e6df8c3b4d69b1ec7a4c /challenge-004/paulo-custodio/python/ch-2.py | |
| parent | d7f1a42f45701d5b0ed19ea0b9823d9dc41de271 (diff) | |
| parent | ef1528e9b9b1bee88fc5deaf724f31330b216d9a (diff) | |
| download | perlweeklychallenge-club-c0e6f7597cc064e00bc42794780a55b424cfdba9.tar.gz perlweeklychallenge-club-c0e6f7597cc064e00bc42794780a55b424cfdba9.tar.bz2 perlweeklychallenge-club-c0e6f7597cc064e00bc42794780a55b424cfdba9.zip | |
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'challenge-004/paulo-custodio/python/ch-2.py')
| -rwxr-xr-x | challenge-004/paulo-custodio/python/ch-2.py | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/challenge-004/paulo-custodio/python/ch-2.py b/challenge-004/paulo-custodio/python/ch-2.py new file mode 100755 index 0000000000..8cadfda8c8 --- /dev/null +++ b/challenge-004/paulo-custodio/python/ch-2.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +# Challenge 004 +# +# Challenge #2 +# You are given a file containing a list of words (case insensitive 1 word per +# line) and a list of letters. Print each word from the file that can be made +# using only letters from the list. You can use each letter only once (though +# there can be duplicates and you can use each of them once), you don't have to +# use all the letters. +# (Disclaimer: The challenge was proposed by Scimon Proctor) + +import sys +import re + +def isalpha(word): + if re.fullmatch(r"[a-zA-Z]+", word): + return True + else: + return False + +def matches_letters(word, letters): + for c in letters: + word = re.sub(c, "", word, 1) + if word == "": + return True + return False + +def print_matching(file, letters): + letters = letters.lower() + fp = open(file, 'r') + for line in fp.readlines(): + word = line.strip() + if isalpha(word) and len(word) >= 2 and matches_letters(word, letters): + print(word) + +if len(sys.argv) != 2: + print("Usage: ch-2.py letters") +else: + print_matching("words.txt", sys.argv[1]) |
