def start(): questions_list = sample(range(0, len(df)), 11) change = Change(Question(questions_list[-1])) remove = Remove() second = Second() # game starting sequence clear() print("遊戲開始") print("輸入A、B、C、D作答,E、F、G啟用求救卡\nE:更換題目 F:刪去選項 G:第二條命\n你準備好了嗎?") time.sleep(1) for i in range(2): print(3 - i) time.sleep(2) for m in range(10): print("第{}題:\n".format(m + 1)) change, remove, second, isCorrect = check(Question(questions_list[m]), change, remove, second) if m == 9 and isCorrect: print("恭喜挑戰成功\n") return None elif not isCorrect: print("\nGAME OVER\n") return None else: print("------------\n 下一題\n------------\n")
def generate_questions(self): return [ Question(self.question1()), Question(self.question2()), Question(self.question3()), Question(self.question4()) ]
def __init__(self): self.index = 0 wx.Frame.__init__(self, None, -1, 'My Python App',size=(1400, 760)) self.init_all() self.introduction = Question(introduction_path) self.research = Question(research_path) self.teaching = Question(teaching_path)
def display_favorite(self): system("cls") all_fav = Favourites.display_all_favourite_product() element_to_search = {} if all_fav != []: for element in all_fav: element_to_search[element[0]] = element[1] C_EMPTY.append( Product.display_product(["name_product"], "id_product", element[0])[0][0]) C_EMPTY.append(MAIN_MENU) C_EMPTY.append(SUPRESS) qst_all_fav = Question(QUESTIONER, Q5, clean=1).answer if qst_all_fav != SUPRESS and qst_all_fav != MAIN_MENU: favourite_prod = Product.display_product(["id_product"], "name_product", qst_all_fav)[0][0] Favourites.display_favourite_product( str(favourite_prod), str(element_to_search[favourite_prod])) all_fav.clear() C_EMPTY.clear() elif qst_all_fav == SUPRESS: Favourites.suppress_all() all_fav.clear() C_EMPTY.clear() return MAIN_MENU elif qst_all_fav == MAIN_MENU: C_EMPTY.clear() return MAIN_MENU else: Question(display(150, "=", NO_FAV_PRODUCT, 1, "|", "left"), clean=1) return MAIN_MENU
def read_question(self): line = self._question_file.read_until_data() q = Question(line) if q._type is not Question_type.UNKNOWN: self._questions.append(q) print("Question for {1}: {0}".format(Question(line), self._player_type))
def parse(self, string): question = Question() option = False self._tokenize(string) for token in self._tokens: o = re.match(r"^\s*[a-zA-Z][.)] ", token) if o and o.group(): option = True try: assert question is not None question.options.append(token) except AssertionError: pass continue if option: self._questions.append(question) question = Question() question.stem = '' option = False try: assert question is not None question.stem += token + '\n' except AssertionError: pass if question and len(question.options) > 0: self._questions.append(question) return self
def generateQuiz(): # Create a set of 10 questions for the quiz quiz = [] # Question 1 quiz.append(Question('The beaver is the national emblem of which country?', 'Canada', 'United States', 'Spain', 'Iceland', 1)) # Question 2 quiz.append(Question('How many players are there in a baseball team?', '7', '9', '11', '12', 2)) # Question 3 quiz.append(Question('In Fahrenheit, at what temperature does water freeze?', '-100', '-32', '0', '32', 4)) # Question 4 quiz.append(Question('The Statue of Liberty was given to the US by which country?', 'United States', 'Portugal', 'France', 'Great Britain', 3)) # Question 5 quiz.append(Question('Which of the planets is closest to the sun?', 'Mercury', 'Venus', 'Mars', 'Earth', 1)) # Question 6 quiz.append(Question('How many letters are there in the German alphabet?', '26', '30', '33', '38', 2)) # Question 7 quiz.append(Question('In the sport of Judo, what color belt follows an orange belt?', 'Red', 'Green', 'Blue', 'Brown', 2)) # Question 8 quiz.append(Question('Who was the first president of the United States?', 'Abraham Lincoln', 'George Washington', 'Woodrow Wilson', 'Benjamin Franklin', 2)) # Question 9 quiz.append(Question('What is the largest bone in the human body?', 'Spine', 'Elbow', 'Femur', 'Skull', 3)) # Question 10 quiz.append(Question('Entomology is the branch of science that studies what?', 'Forests', 'Oceans', 'Plants', 'Insects', 4)) return quiz
def test_display_FAQ(self): self.faq1 = Question(isFAQ=True, question="?", answer="!") self.faq2 = Question(isFAQ=True, question="??", answer="!!") self.faq3 = Question(isFAQ=True, question="???", answer="!!!") self.notfaq = Question(isFAQ=False, question="!????", answer="?!!!!") self.assertTrue(self.faq1.isFAQ) self.assertTrue(self.faq2.isFAQ) self.assertTrue(self.faq3.isFAQ) self.assertFalse(self.notfaq.isFAQ)
def get_questions(self): questions = [] file = open(self.file_name, 'r') for line in file: t = line.rstrip().split('**') if t[1] == 'T': questions.append(Question(t[0], True)) else: questions.append(Question(t[0], False)) return questions
def setUp(self): global survey survey = Survey() q = survey.add(Question(1, "Question1")) q.add(Answer(1, "answer1")) q.add(Answer(2, "answer2")) q = survey.add(Question(2, "Question2")) q.add(Answer(3, "answer3")) q.add(Answer(4, "answer4")) q.add(Answer(5, "answer5"))
def split(self, out=True): if out: print("Splitting {} entries.".format(len(self.indices))) best_gain, best_question, best_split = 0, None, None uncertainty = self.gini or gini(self.dataset, self.indices) cpus = mp.cpu_count() columns = len(self.fields) parallelize = len(self.indices) > 1000 if parallelize and out: print( "\n-- Using {} CPUs to parallelize the split search\n".format( cpus)) for i in range(columns): values = unique_vals(self.dataset, self.indices, i) if parallelize: # Parallelize best split search splits = [] for value in values: question = Question(self.fields, i, value) splits.append( (question, self.dataset, self.indices, uncertainty)) chunk = max(int(len(splits) / (cpus * 4)), 1) with mp.Pool(cpus) as p: for split in p.imap_unordered(splitter, splits, chunksize=chunk): if split is not None: gain, question, branches = split if gain > best_gain: best_gain, best_question, best_split = gain, question, branches else: for value in values: question = Question(self.fields, i, value) matching, non_matching = partition(self.dataset, self.indices, question) if not matching or not non_matching: continue gain = info_gain(self.dataset, matching, non_matching, uncertainty) if gain > best_gain: best_gain, best_question = gain, question best_split = (matching, non_matching) return best_gain, best_question, best_split
def test_set_answer(self): self.faq_as_student = Question(isFAQ=False, question='?', answer="answer") self.faq_as_admin = Question(isFAQ=False, question='???', answer="ANSWER") self.faq_as_student.set_answer("") self.faq_as_admin.set_answer(" . ") self.assertEqual("", self.faq_as_student.answer) self.assertEqual(" . ", self.faq_as_admin)
def get_default_questions_json(): question_list = list() question1 = Question(0, 'Choose A, B or C', True) question1.add_alternative(0, 'A', False) question1.add_alternative(1, 'B', True) question1.add_alternative(2, 'C', False) question_list.append(question1.to_json()) question2 = Question(1, 'Choose D, E or F', False) question2.add_alternative(0, 'D', False) question2.add_alternative(1, 'E', False) question2.add_alternative(2, 'F', True) question_list.append(question2.to_json()) return question_list
def _new_question(self, countries_used): country_names = [country["name"] for country in countries_used] if len(country_names) > 1: new_question = Question(country_names, len(self._questions), force_answers=True) else: new_question = Question(country_names, len(self._questions), force_answers=False) self._questions.append(new_question)
def __init__(self): self.questions = [ Question('Q1', Difficulty.EASY, 1), Question('Q2', Difficulty.EASY, 2), Question('Q3', Difficulty.MEDIUM, 2), Question('Q4', Difficulty.HARD, 9), Question('Q5', Difficulty.EASY, 3), Question('Q6', Difficulty.HARD, 7), Question('Q7', Difficulty.MEDIUM, 3), Question('Q8', Difficulty.EASY, 3), Question('Q9', Difficulty.MEDIUM, 5), Question('Q10', Difficulty.HARD, 5) ]
def test_post_FAQ(self): self.faq_as_student = Question(isFAQ=True, question='?', answer="aaaaaaa") self.faq_as_admin = Question(isFAQ=True, question='???', answer="BbBbBb") self.assertFalse(self.faq_as_student.isFAQ) self.assertTrue(self.faq_as_admin.isFAQ) self.assertEqual('?', self.faq_as_student.question) self.assertEqual('???', self.faq_as_admin.question) self.assertEqual('aaaaaaa', self.faq_as_student.answer) self.assertEqual('BbBbBb', self.faq_as_admin.answer) del self.faq_as_student del self.faq_as_admin
def test_set_FAQ(self): self.faq_as_student = Question(isFAQ=False, question='?', answer="answer") self.faq_as_admin = Question(isFAQ=False, question='???', answer="ANSWER") self.assertFalse(self.faq_as_student.isFAQ) self.assertFalse(self.faq_as_admin.isFAQ) self.faq_as_student.set_FAQ(isFAQ=True) # , self.faq_as_student self.faq_as_admin.set_FAQ(isFAQ=True) # , self.faq_as_admin self.assertFalse(self.faq_as_student.isFAQ) self.assertTrue(self.faq_as_admin.isFAQ) del self.faq_as_student del self.faq_as_admin
def find_best_split(fields, dataset, uncertainty=None): print("Splitting {} entries.".format(len(dataset))) best_gain, best_question, best_split = 0, None, None uncertainty = uncertainty or gini(dataset) columns = len(dataset[0].data) for i in range(columns): values = unique_vals(dataset, i) if len(dataset) > 400: # Parallelize best split search cpus = mp.cpu_count() if i == 0: print( "-- Using {} CPUs to parallelize the split search.".format( cpus)) splits = [] for value in values: question = Question(fields, i, value) splits.append((question, dataset, uncertainty)) chunk = max(int(len(splits) / (cpus * 4)), 1) with mp.Pool(cpus) as p: for split in p.imap_unordered(splitter, splits, chunksize=chunk): if split is not None: gain, question, branches = split if gain > best_gain: best_gain, best_question, best_split = gain, question, branches else: for value in values: question = Question(fields, i, value) matching, non_matching = partition(dataset, question) if not matching or not non_matching: continue gain = info_gain(matching, non_matching, uncertainty) if gain > best_gain: best_gain, best_question = gain, question best_split = (matching, non_matching) return best_gain, best_question, best_split
def __init__(self, arg): self.questions = [] # If arg is a directory path if type(arg) == str: self.dir_path = arg try: for dir_name, subdirs_list, files_list in os.walk( self.dir_path): print('Found directory: %s' % dir_name) for file_name in files_list: # print('\t%s' % file_name) try: with open(dir_name + '/' + file_name) as file_pointer: self.questions.append(Question(file_pointer)) except: continue except: pass # If arg is a collection of questions else: iterable = arg try: for item in iterable: if type(item) == Question: self.questions.append(item) except: pass
def parse_questions(dom_tree_root): result = [] for questions in dom_tree_root: comment = None tournament = None difficulty = QuestionDifficulty.UNKNOWN rating = 0.0 for question_tree in questions: if question_tree.tag == 'QuestionId': qid = int(question_tree.text) elif question_tree.tag == 'Question': text = question_tree.text elif question_tree.tag == 'Answer': answer = question_tree.text elif question_tree.tag == 'Comments': comment = question_tree.text elif question_tree.tag == 'tournamentTitle': tournament = question_tree.text elif question_tree.tag == 'Complexity': if question_tree.text: difficulty = QuestionDifficulty(int(question_tree.text)) elif question_tree.tag == 'Rating': if question_tree.text: correct, all_tries = question_tree.text.split('/') rating = float(correct) / float(all_tries) result.append( Question(qid, text, answer, comment, tournament, difficulty, rating)) return result
def __parse_line(self, line) -> Question: parts = line.split(';') text = parts[0] is_correct = parts[1] == "Yes" explanation = parts[2] return Question(text, is_correct, explanation)
def find_best_split(trainingData): # we compute the information gain for every possible question # the greatest information gain wins -> this question will be asked best_gain = 0 # keep track of the best information gain best_question = None # keep train of the feature / value that produced it current_gini_index = gini(trainingData) nr_of_features = len(trainingData[0]) - 1 # this should be 4 for feature in range(nr_of_features): values = set([row[feature] for row in trainingData]) for val in values: # create a question for every feature and for every value question = Question(feature, val) true_rows, false_rows = partition(trainingData, question) if len(true_rows) == 0 or len(false_rows) == 0: # prevent the algorithm to crash if the data is not partitioned continue # Calculate the information gain from this split gain = info_gain(true_rows, false_rows, current_gini_index) # update the best_gain and best_question if there is the case if gain >= best_gain: best_gain, best_question = gain, question return best_gain, best_question
def find_optimal_split(rows): """Iterate over features and values to find optimal question to partition the data""" best_gain = 0 best_question = None current_uncertainty = gini_impurity(rows) n_features = len(rows[0]) - 1 # number of columns - the label column for column in range(n_features): unique_values = _unique_values_in_column(rows, column) # iterate through possible questions to find best split for value in unique_values: question = Question(column, value) true_rows, false_rows = partition(rows, question) if _data_not_split(true_rows, false_rows): continue # Question doesn't divide so move onto next possible gain = information_gain(true_rows, false_rows, current_uncertainty) if gain > best_gain: best_gain, best_question = gain, question return best_gain, best_question
def _best_split(self, rows): '''Finds the best Question (using info_gain) that splits the rows into left and right buckets. Returns a Question (records the col_index and the value.) @ bad performance when we have really large number of rows. Can improve by first sorting and then doing a binary search ''' previous_impurity = self.criterion.impurity(rows) BestInfoGain = 0 # find the best col and val to split the rows best_question = None num_rows, num_cols = rows.shape for col in range(num_cols - 1): # last col is the label # rows have same len for row in range(num_rows): val = rows.iloc[row, col] # this val may be the wedge # value for the question q = Question(col, val) left, right = q.divide_on_question(rows) if left.shape[0] == 0 or right.shape[0] == 0: continue # ignore the case when no splitting InfoGain = self.criterion.info_gain(left, right, previous_impurity) # if best info gain crossed save state or save Question if InfoGain >= BestInfoGain: BestInfoGain = InfoGain best_question = q if previous_impurity == InfoGain: return BestInfoGain, best_question # already best return BestInfoGain, best_question
def ask_boy_girl(): question = Question(question="Remind me, are you a BOY or a GIRL?", choices=["1)\tBOY", "2)\tGIRL"]) game_print(str(question)) question.user_input = game_input(regex=r"^[1-2]$") return question.user_input
def game_socialization(): running = True questions = pygame.sprite.Group() for i in range(15): new_question = Question() questions.add(new_question) while running: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False if player.finish == True: player.finish = False player.rect.x = 0 player.rect.y = 0 running = False for new_question in questions: if pygame.sprite.spritecollideany(new_question, all_sprites): new_question.kill() screen.fill(BLACK) maze.draw_maze(screen, WHITE) all_sprites.draw(screen) questions.draw(screen) all_sprites.update(maze) questions.update() pygame.display.flip() pygame.display.update() mainClock.tick(60)
def parse(self, string): super(StemsParser, self).parse(string) si = r'[0-9]+\.\s+' sb = r'.+?[?:.]\n\n' o = r'.+' regex = r"({si}{sb})({o})".format( si=si, sb=sb, o=o, ) self._tokenize(string) for token in self._tokens: question = Question() match = re.search(regex, token, re.DOTALL) if match: question.stem = match.group(1).strip() for option in match.group(2).split('\n'): if option: question.options.append(option.strip()) else: break self._questions.append(question) return self
def load_questions(parameters): headers = {'Content-Type': 'application/json'} # Getting the data from the API. for parameter in parameters: response = requests.get("https://opentdb.com/api.php", params=parameter, headers=headers) # Checking if the Status code was 200, if it was store it in a variable if response.status_code == 200: data = json.loads(response.content.decode('utf-8')) else: print("Couldn't connect to the server!") # Check if data was not an empty object, if it wasn't store it into the array of objects if data is not None: for index in range(len(data["results"])): questions.append( Question(data["results"][index]["question"], data["results"][index]["difficulty"], data["results"][index]["correct_answer"], data["results"][index]["incorrect_answers"])) else: print("Data was not taken.")
def generate_questions(data): questions = [] for element in data["results"]: question = Question(html.unescape(element["question"]), element["correct_answer"]) questions.append(question) return questions
def parseQuestions(): # Creation d'un tableau vide questions = [] # Lecture du fichiers des questions qst_tab = [] read_file_questions(qst_tab) if (verbose): print('le texte :', qst_tab[0]) # Lecture du fichiers des effets eff_tab = [] read_file_effects(eff_tab) if (verbose): print('les effets :', eff_tab) # On convertit les questions et les effets dans une seule classe i = 0 while i < len(qst_tab): q = qst_tab[i] e = eff_tab[i] newQuestion = Question(q[0], q[1], q[2], e[0], e[1], e[2], e[3]) questions.append(newQuestion) i += 1 # On melange les questions random.shuffle(questions) return (questions)