python list comprehension does not work correctly












-1














I want to write method which will return a word from file based on passed argument. But if there is no words which fit the argument I want to return nothing. So in my file, the highest word has 97points. But if I pass score 98, error about index is displayed. I have something like this:



main.py



from option import Option
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

group.add_argument( "--score", "-s", help="Find word for given score", type=int)

option = Option()
if args.score:
option.word_from_score(args.score)


option.py



import random
class Option():
def __init__(self):
self.file = [line.rstrip('n').upper() for line in open('dictionary.txt', "r")]

SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z"), (11, "Ą Ć Ę Ł Ń Ó Ś Ź Ż")]
global LETTER_SCORES
LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
for letter in letters.split()}

def word_from_score(self,score):
print(random.choices([word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]))


And this method returns the word, but doesnt handle the error. So I tried this:



def word_from_score(self,score):
print(random.choices([(word if sum([LETTER_SCORES[letter] for letter in word ]) == score else "") for word in self.file]))


But in this case, it returns "" for every argument I pass. Where is mistake in this method?



[EDIT] For example, I run my program from command line and:



python main.py -f


returns 97, because this is a score for some words in file. So if I run my other method:



pythom main.py -s 97


Which return the word from file, which has this amount of score. And it works. But if I tak 98 as argument, it wont work, because in file tere is no word with this score. And now I want to handle this case, to return ""










share|improve this question
























  • @timgeb edited again. I didnt add method which is executed by -f param
    – Frendom
    Nov 11 at 22:03
















-1














I want to write method which will return a word from file based on passed argument. But if there is no words which fit the argument I want to return nothing. So in my file, the highest word has 97points. But if I pass score 98, error about index is displayed. I have something like this:



main.py



from option import Option
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

group.add_argument( "--score", "-s", help="Find word for given score", type=int)

option = Option()
if args.score:
option.word_from_score(args.score)


option.py



import random
class Option():
def __init__(self):
self.file = [line.rstrip('n').upper() for line in open('dictionary.txt', "r")]

SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z"), (11, "Ą Ć Ę Ł Ń Ó Ś Ź Ż")]
global LETTER_SCORES
LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
for letter in letters.split()}

def word_from_score(self,score):
print(random.choices([word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]))


And this method returns the word, but doesnt handle the error. So I tried this:



def word_from_score(self,score):
print(random.choices([(word if sum([LETTER_SCORES[letter] for letter in word ]) == score else "") for word in self.file]))


But in this case, it returns "" for every argument I pass. Where is mistake in this method?



[EDIT] For example, I run my program from command line and:



python main.py -f


returns 97, because this is a score for some words in file. So if I run my other method:



pythom main.py -s 97


Which return the word from file, which has this amount of score. And it works. But if I tak 98 as argument, it wont work, because in file tere is no word with this score. And now I want to handle this case, to return ""










share|improve this question
























  • @timgeb edited again. I didnt add method which is executed by -f param
    – Frendom
    Nov 11 at 22:03














-1












-1








-1







I want to write method which will return a word from file based on passed argument. But if there is no words which fit the argument I want to return nothing. So in my file, the highest word has 97points. But if I pass score 98, error about index is displayed. I have something like this:



main.py



from option import Option
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

group.add_argument( "--score", "-s", help="Find word for given score", type=int)

option = Option()
if args.score:
option.word_from_score(args.score)


option.py



import random
class Option():
def __init__(self):
self.file = [line.rstrip('n').upper() for line in open('dictionary.txt', "r")]

SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z"), (11, "Ą Ć Ę Ł Ń Ó Ś Ź Ż")]
global LETTER_SCORES
LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
for letter in letters.split()}

def word_from_score(self,score):
print(random.choices([word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]))


And this method returns the word, but doesnt handle the error. So I tried this:



def word_from_score(self,score):
print(random.choices([(word if sum([LETTER_SCORES[letter] for letter in word ]) == score else "") for word in self.file]))


But in this case, it returns "" for every argument I pass. Where is mistake in this method?



[EDIT] For example, I run my program from command line and:



python main.py -f


returns 97, because this is a score for some words in file. So if I run my other method:



pythom main.py -s 97


Which return the word from file, which has this amount of score. And it works. But if I tak 98 as argument, it wont work, because in file tere is no word with this score. And now I want to handle this case, to return ""










share|improve this question















I want to write method which will return a word from file based on passed argument. But if there is no words which fit the argument I want to return nothing. So in my file, the highest word has 97points. But if I pass score 98, error about index is displayed. I have something like this:



main.py



from option import Option
import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()

group.add_argument( "--score", "-s", help="Find word for given score", type=int)

option = Option()
if args.score:
option.word_from_score(args.score)


option.py



import random
class Option():
def __init__(self):
self.file = [line.rstrip('n').upper() for line in open('dictionary.txt', "r")]

SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z"), (11, "Ą Ć Ę Ł Ń Ó Ś Ź Ż")]
global LETTER_SCORES
LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
for letter in letters.split()}

def word_from_score(self,score):
print(random.choices([word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]))


And this method returns the word, but doesnt handle the error. So I tried this:



def word_from_score(self,score):
print(random.choices([(word if sum([LETTER_SCORES[letter] for letter in word ]) == score else "") for word in self.file]))


But in this case, it returns "" for every argument I pass. Where is mistake in this method?



[EDIT] For example, I run my program from command line and:



python main.py -f


returns 97, because this is a score for some words in file. So if I run my other method:



pythom main.py -s 97


Which return the word from file, which has this amount of score. And it works. But if I tak 98 as argument, it wont work, because in file tere is no word with this score. And now I want to handle this case, to return ""







python list-comprehension






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 22:02

























asked Nov 11 at 21:26









Frendom

266




266












  • @timgeb edited again. I didnt add method which is executed by -f param
    – Frendom
    Nov 11 at 22:03


















  • @timgeb edited again. I didnt add method which is executed by -f param
    – Frendom
    Nov 11 at 22:03
















@timgeb edited again. I didnt add method which is executed by -f param
– Frendom
Nov 11 at 22:03




@timgeb edited again. I didnt add method which is executed by -f param
– Frendom
Nov 11 at 22:03












1 Answer
1






active

oldest

votes


















0














Currently, your list compression is building a list of words that match the score, but that also includes empty strings for any words that don't match the score. You want something like this:



def word_from_score(self,score):
valid_words = [word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]
if len(valid_words) != 0:
print(random.choices(valid_words))
else:
print('')





share|improve this answer





















  • Thank you!! It works fine now
    – Frendom
    Nov 11 at 22:31











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253391%2fpython-list-comprehension-does-not-work-correctly%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Currently, your list compression is building a list of words that match the score, but that also includes empty strings for any words that don't match the score. You want something like this:



def word_from_score(self,score):
valid_words = [word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]
if len(valid_words) != 0:
print(random.choices(valid_words))
else:
print('')





share|improve this answer





















  • Thank you!! It works fine now
    – Frendom
    Nov 11 at 22:31
















0














Currently, your list compression is building a list of words that match the score, but that also includes empty strings for any words that don't match the score. You want something like this:



def word_from_score(self,score):
valid_words = [word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]
if len(valid_words) != 0:
print(random.choices(valid_words))
else:
print('')





share|improve this answer





















  • Thank you!! It works fine now
    – Frendom
    Nov 11 at 22:31














0












0








0






Currently, your list compression is building a list of words that match the score, but that also includes empty strings for any words that don't match the score. You want something like this:



def word_from_score(self,score):
valid_words = [word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]
if len(valid_words) != 0:
print(random.choices(valid_words))
else:
print('')





share|improve this answer












Currently, your list compression is building a list of words that match the score, but that also includes empty strings for any words that don't match the score. You want something like this:



def word_from_score(self,score):
valid_words = [word for word in self.file if sum([LETTER_SCORES[letter] for letter in word ]) == score]
if len(valid_words) != 0:
print(random.choices(valid_words))
else:
print('')






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 at 22:27









wowserx

42018




42018












  • Thank you!! It works fine now
    – Frendom
    Nov 11 at 22:31


















  • Thank you!! It works fine now
    – Frendom
    Nov 11 at 22:31
















Thank you!! It works fine now
– Frendom
Nov 11 at 22:31




Thank you!! It works fine now
– Frendom
Nov 11 at 22:31


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253391%2fpython-list-comprehension-does-not-work-correctly%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Coverage of Google Street View

Full-time equivalent

Surfing