2

Let's say I have a list of words: resign resins redyed resist reeded

I also have a string ".10.10"

I need to iterate through the list and find the words where there are repeated characters in the same locations where there are numbers in the string.

For instance, the string ".10.10" would find the word 'redyed' since there are e's where there are 1's and there are d's where there are 0's.

Another string ".00.0." would find the word 'reeded' as there are e's in that position.

My attempts in python so far are not really worth printing. At the moment I look through the string, add all 0s to an array and the 1s to an array then try to find repeated characters in the array positions. But it's terribly clumsy and doesn't work properly.

1
  • Is this homework? If so, please tag it as such. If not, maybe you can tell us more about the actual problem you're trying to solve. Commented Oct 30, 2011 at 13:47

1 Answer 1

5
def matches(s, pattern):
    d = {}
    return all(cp == "." or d.setdefault(cp, cs) == cs
               for cs, cp in zip(s, pattern))

a = ["resign", "resins", "redyed", "resist", "reeded"]
print [s for s in a if matches(s, ".01.01")]
print [s for s in a if matches(s, ".00.0.")]

prints

['redyed']
['reeded']
Sign up to request clarification or add additional context in comments.

7 Comments

You can use the same if as the filtering condition of the generator expression instead of using it for a ternary expression.
@agf: The ternary expression wasn't necessary, you are right. I edited my answer about the same time you commented, but your solutions sounds even nicer.
@Acorn I don't really think so. This way, the or is checking for the truth of the condition, and then all is checking it again -- if you use for ... in ... if condition then it only gets checked once. None of it is really important as the setdefault doesn't get evaluated unless the condition is True for any of the three methods.
Anyway, this solution is clean and is exactly what I needed. Thanks a lot.
@agf: Thinking about your last comment, I realized that all(condition(x) for x in a) is always equivalent to all(False for x in a if not condition(x)). It feels a bit strange for me to use filtering here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.