Reputation: 19
I need help with finding the outcome for the given definitions using python and list comprehension.
firstSentence = ["Help", "me", "stack", "overflow", "you're", "my", "only", "hope"]
secondSentence = ["I", "hope", "you're", "enjoying", "the", "riddles", "I've", "created"]
What's supposed to printed : ['HelpI', 'Helpthe', 'meI', 'stackI', 'stackhope', 'stackthe', "stackI've", 'overflowI', 'overflowhope', "overflowyou're", 'overflowthe', 'overflowriddles', "overflowI've", 'overflowcreated', "you'reI", "you'rehope", "you'rethe", "you'reI've", 'myI', 'onlyI', 'onlythe', 'hopeI', 'hopethe']
I know this one has to do with combinations that has to be less than the secondsentence, but I'm not sure of how to execute that.
Using list comprehension: how do I combine first and second sentence given that the length cannot be more than secondsentence.
Upvotes: 1
Views: 69
Reputation: 13661
To get clear grab of list comprehension first let's try to get desired output using nested loop:
firstSentence = ["Help", "me", "stack", "overflow", "you're", "my", "only", "hope"]
secondSentence = ["I", "hope", "you're", "enjoying", "the", "riddles", "I've", "created"]
result = []
for firstWord in firstSentence:
for secondWord in secondSentence:
if len(secondWord) < len(firstWord):
result.append(firstWord+secondWord)
print(result)
Output:
['HelpI', 'Helpthe', 'meI', 'stackI', 'stackhope', 'stackthe', "stackI've", 'overflowI', 'overflowhope', "overflowyou're", 'overflowthe', 'overflowriddles', "overflowI've", 'overflowcreated', "you'reI", "you'rehope", "you'rethe", "you'reI've", 'myI', 'onlyI', 'onlythe', 'hopeI', 'hopethe']
Now let's convert this nested loop with list comprehension:
result = [firstWord+secondWord for firstWord in firstSentence for secondWord in secondSentence if len(secondWord) < len(firstWord)]
print(result)
Output:
['HelpI', 'Helpthe', 'meI', 'stackI', 'stackhope', 'stackthe', "stackI've", 'overflowI', 'overflowhope', "overflowyou're", 'overflowthe', 'overflowriddles', "overflowI've", 'overflowcreated', "you'reI", "you'rehope", "you'rethe", "you'reI've", 'myI', 'onlyI', 'onlythe', 'hopeI', 'hopethe']
N.B.: Variables are not declared or being used as camelCase
in Python. It prefers lowercase variable names where words separated by underscore (_
).
From Python PEP-8 guideline:
Function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names.
Upvotes: 1