2015-01-08 3 views
0

У меня есть два списка:Python, случайные слова в вопросы

wordlists1 = ["hot","summer", "hard", "dry", "heavy", "light", "weak", "male", 
      "sad", "win", "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"] 

wordlists2 = ["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big", 
     "pay attention", "sell", "fail", "accept", "allow", "include"] 

я использую random.choice выбрать слово из каждого списка. Когда у меня есть слова, мне нужно напечатать их как вопрос. Например, если выбраны горячие и слабые, он должен печатать: «Горячий - холодный, как слабый - до?»?

Мне очень нужна помощь в этом, и мы подробно рассмотрим детализированные шаги.

Мой код:

import random 

wordlists1 =["hot","summer", "hard", "dry", "heavy", "light", "weak", "male", "sad", "win", "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"] 
wordlists2 =["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big", "pay attention", "sell", "fail", "accept", "allow", "include"] 
randomword1=random.choice(wordlists1) 
randomword2=random.choice(wordlists2) 
+2

Покажите нам код, который вы имеете до сих пор, даже если она сломана. –

ответ

1

Вы использовали random.choice дважды, что делает randomword1 отличается от randomword2 с точки зрения позиции в списках. Используйте random.randint вместо того, чтобы получить унифицированную индексировать каждый раз:

import random 
wordlists1 =["hot","summer", "hard", "dry", "heavy", "light", "weak", "male", "sad", "win", "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"] 
wordlists2 =["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big", "pay attention", "sell", "fail", "accept", "allow", "include"] 
idx1 = random.randint(0, len(wordlists1)-1) 
idx2 = random.randint(0, len(wordlists1)-1) 
words_to_choose = (wordlists1[idx1], wordlists2[idx1], wordlists1[idx2], wordlists2[idx2]) 
print '%s is to %s as %s is to ___? (answer: %s)'%words_to_choose 

#OUTPUT: reject is to accept as exclude is to ___? (answer: include) 
0

генерирует случайное число от 0 до длины списков. Это число будет означать выбор случайного индекса из ваших списков. После того, как вы "случайно" выбрали ваши слова, просто использовать их в своих вопросах

1
import random 
wordlists1 =["hot","summer", "hard", "dry", "heavy", "light", "weak", "male", "sad",  "win", "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"] 
wordlists2 =["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female",  "happy", "lose", "big", "pay attention", "sell", "fail", "accept", "allow", "include"] 
l1=len(wordlists1) 
index1=int(random.random()*l1) 
index2=int(random.random()*l1) 
myquestion=wordlists1[index1]+" is to "+wordlists2[index1]+" as "+ wordlists1[index2]+" is to___?" 
print myquestion 
2
wordlists1 = ["hot","summer", "hard", "dry", "heavy", "light", "weak", "male", 
        "sad", "win", "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"] 

wordlists2 = ["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big", 
       "pay attention", "sell", "fail", "accept", "allow", "include"] 

import random 

t = zip(wordlists1, wordlists2) 
t1, t2 = random.sample(t, 2) 
print '%s is to %s as %s is to ___? (%s)' % (t1[0], t1[1], t2[0], t2[1]) 

Shoould напечатать что-то вроде dry is to wet as ignore is to ___? (pay attention)

Update: Я перешел на random.sample(t, 2) от random.choice. Это лучший способ сделать это. (Как было предложено DSM, но я также хотел обновить свой код).

1

Использование случайного выбора двух индексов слов и эти индексы порождают вопрос и проверить, если ответ правильный или не нравится:

import random 
def makeQuestion(): 
    indexes = range(len(wordlists1)) 
    word1 = random.choice(indexes) 
    word2 = random.choice(indexes) 
    ans = raw_input("{} is to {} as {} is to___? ".format(wordlists1[word1], wordlists2[word1], wordlists1[word2])) 
    if ans.strip().lower() == wordlists2[word2]: 
     print True 
    else: 
     print False 

Демо:

>>> wordlists1 = ["hot","summer", "hard", "dry", "heavy", "light", "weak", "male", 
...    "sad", "win", "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"] 
>>> wordlists2 = ["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big", 
...   "pay attention", "sell", "fail", "accept", "allow", "include"] 
>>> import random 
>>> def makeQuestion(): 
...  indexes = range(len(wordlists1)) 
...  word1 = random.choice(indexes) 
...  word2 = random.choice(indexes) 
...  ans = raw_input("{} is to {} as {} is to___? ".format(wordlists1[word1], wordlists2[word1], wordlists1[word2])) 
...  if ans.strip().lower() == wordlists2[word2]: 
...  print True 
...  else: 
...  print False 
... 
>>> makeQuestion() 
succeed is to fail as sad is to___? happy 
True 
>>> makeQuestion() 
prevent is to allow as ignore is to___? pay attention 
True 
>>> makeQuestion() 
exclude is to include as heavy is to___? cold 
False 
4

я мог бы сделать что-то вроде

>>> wpairs = list(zip(wordlists1, wordlists2)) 
>>> example, question = random.sample(wpairs, 2) 
>>> "{} is to {} as {} is to ?".format(example[0], example[1], question[0]) 
'small is to big as summer is to ?' 

Во-первых, я бы объединить два списка в список пар:

>>> wpairs = list(zip(wordlists1, wordlists2)) 
>>> wpairs 
[('hot', 'cold'), ('summer', 'winter'), ('hard', 'soft'), ('dry', 'wet'), ('heavy', 'light'), ('light', 'darkness'), ('weak', 'strong'), ('male', 'female'), ('sad', 'happy'), ('win', 'lose'), ('small', 'big'), ('ignore', 'pay attention'), ('buy', 'sell'), ('succeed', 'fail'), ('reject', 'accept'), ('prevent', 'allow'), ('exclude', 'include')] 

И тогда я хотел бы использовать random.sample выбрать два из них:

>>> example, question = random.sample(wpairs, 2) 
>>> example, question 
(('weak', 'strong'), ('heavy', 'light')) 

Одним из основных преимуществ использования random.sample здесь является то, что вам не придется беспокоиться о рисовании тех же паров дважды («слабый не является сильным, как слабым должны?» вопросами.)

После этого, мы можем сделать вопрос строку:

>>> "{} is to {} as {} is to ?".format(example[0], example[1], question[0]) 
'weak is to strong as heavy is to ?' 
+1

Это, безусловно, лучший ответ.Используя образец таким образом, вы избегаете случай выборки элемента SAME дважды, что возможно в ответах, где выборка/выбор вызывается дважды. – lightalchemist

1
from random import randint 

wordlists1 = ["hot","summer", "hard", "dry", "heavy", "light", "weak", "male", 
      "sad", "win", "small","ignore", "buy", "succeed", "reject", "prevent", "exclude"] 

wordlists2 = ["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big", 
     "pay attention", "sell", "fail", "accept", "allow", "include"] 

index1 = randint(0, len(wordlists1) - 1) 

index2 = randint(0, len(wordlists2) - 1) 

answer = wordlists2[index2] 

print ("Q : %s is %s as %s is to ________ ? " % (wordlists1[index1], wordlists2[index1], wordlists1[index2])) 

user_input = raw_input("A : ") 

if user_input.lower() != answer: 

     print ("Answer is %s" % answer) 
else: 

     print ("Correct Answer") 
0
from __future__ import print_function 
import random 

__author__ = 'lve' 

wordlists1 = ["hot", "summer", "hard", "dry", "heavy", "light", "weak", "male", 
       "sad", "win", "small", "ignore", "buy", "succeed", "reject", "prevent", "exclude"] 

wordlists2 = ["cold", "winter", "soft", "wet", "light", "darkness", "strong", "female", "happy", "lose", "big", 
       "pay attention", "sell", "fail", "accept", "allow", "include"] 

answer_string = '' 

random_question_index = random.randrange(len(wordlists1)) 

answer_string += '{} is to {} as '.format(wordlists1.pop(random_question_index).capitalize(), wordlists2.pop(random_question_index)) 

random_answer_index = random.randrange(len(wordlists1)) 
answer_string += '{} is to___? \nAnswer is {}'.format(wordlists1.pop(random_question_index), 
                 wordlists2.pop(random_question_index).upper()) 
print(answer_string) 
Смежные вопросы