Reputation: 331
Basically, the program checks if the rhyming pattern of a poem is correct. I've taken the parameter of ['A', 'B', 'A'] and arranged it in a dictionary that has the index of words to compare.
rhyme_pattern = {'A': [0, 2], 'B': [1]}
I've also taken the last word from each line and put that into a list.
words_to_compare = ['OFF', 'NEXT', 'ENDS']
And I've made a helper function that compares two words and if they rhyme. I can't figure out how to loop through rhyme_pattern['A'] and compare the words 'OFF' and 'ENDS'. Also, I then get the problem of not comparing anything if there is only one index value, like B.
Upvotes: 0
Views: 105
Reputation: 77404
You can use dict.get(some_val, [])
to ensure that an empty list is returned if some_val
doesn't appear in the dict
:
rhyme_pattern.get('A', [])
and then write your helper function so that it behaves as expected when an entry has just the empty list.
Assuming your comparison function is called compare_with
, then you can compare with the elements in dict['A']
like this:
[compare_with(x, y) for x in rhyme_pattern.get('A', [])
for y in words_to_compare]
This last bit assumes your comparison function works like compare_with(0, 'OFF')
. If instead you are looking to index into words_to_compare
via the contents of rhyme_pattern['A']
, it might look like this:
A_words = [word_to_compare[x] for x in rhyme_pattern.get('A', [])]
Upvotes: 1
Reputation: 180391
rhyme_pattern = {'A': [0, 2], 'B': [1]}
words_to_compare = ['OFF', 'NEXT', 'ENDS']
for val in rhyme_pattern["A"]:
print(words_to_compare[val])
To access all values iterate over the values:
for val in rhyme_pattern.itervalues(): # just .values() for python 3
print([words_to_compare[v] for v in val])
This presumes that all the values will be in the index range of words_to_compare which from your question seems to be the case.
Upvotes: 1
Reputation: 1319
You need to loop through rhyme_pattern and compare all values in any array with more than 1 value. The hard part is getting all combinations of words to compare. the itertools library makes this easy.
This should work:
import itertools as it
for words in rhyme_pattern:
if len(words) > 1:
#now loop through all combinations of 2 words
for pair in it.permutations(words,2):
if not words_ryhme(*pair):
return False
return True
Upvotes: 1