예제 #1
0
def run():

    try:
        file = open('./board.mc', 'r')
        text = file.read()
    except FileNotFoundError:
        file = open('../board.mc', 'r')
        text = file.read()
    file.close()

    lex = Lexer(text)
    token, error = lex.tokenize()

    if (token is None):
        return error
    else:
        passer = Passer(token)
        rule, error = passer.grammar()

        if rule is None:
            return error
        else:

            if (token[0].value == 'solve'):
                sol = Solve(rule[2:])
                return sol.useCaseTest()
            elif (token[0].value == 'base'):
                bases = Base(rule[2:])
                return bases.results()
            elif (token[0].value == 'evaluate'):
                eva = Evaluate(rule[2:-1])
                return eva.useCaseTest()
            elif (token[0].value == 'standardform'):
                sdform = Standardform(rule[2:-1])
                return sdform.results()
예제 #2
0
def main():
	# Getting input from user
	input_class = Input()
	input_class.get_input()

	# Solving the system of linear equations got from the user
	solve = Solve(input_class.coefficient_matrix, input_class.rhs_vector)
	solve.solve()
	print("\nThe solution array is: {}".format(solve.solution_matrix[:,0]))
예제 #3
0
파일: main.py 프로젝트: dmtrkl/Labs
 def exec_clicked(self):
     self.exec_button.setEnabled(False)
     try:
         solver = Solve(self.__get_params())
         solver.prepare()
         self.solution = PolynomialBuilder(solver)
         self.results_field.setText(solver.show()+'\n\n'+self.solution.get_results())
     except Exception as e:
         QMessageBox.warning(self,'Error!','Error happened during execution: ' + str(e))
     self.exec_button.setEnabled(True)
     return
예제 #4
0
def exec_solver():
    if args().no_prints: hide_prints()

    solveur = Solve(n_generator=25, n_device=100, seed=seed)

    # la methode que vous avez codé (solve_heuristc pour moi) doit retourner le meilleur score trouvé
    score = solveur.solve_heuristc()

    restore_prints()

    return score
예제 #5
0
def risolvi():
    lista = []
    print(lista)
    for i in range(NUM_COL):
        lista.append([])
        for j in range(NUM_COL):
            val = str(listaTexts[i][j].get())
            if val == "":
                num = 0
            else:
                num = int(val)
            lista[i].append(num)
    """lista = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 4, 1, 6, 2, 9, 0, 0], [2, 0, 0, 0, 3, 0, 0, 7, 0],
             [0, 9, 0, 0, 0, 0, 0, 6, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 6, 0, 0, 1, 3, 0, 0, 7],
             [9, 0, 6, 0, 0, 5, 0, 0, 0], [8, 5, 0, 7, 0, 6, 4, 0, 0], [0, 7, 0, 0, 0, 0, 0, 2, 0]]"""

    print(lista)
    solve = Solve(lista)
    tab = solve.tabella

    for i in range(NUM_COL):
        for j in range(NUM_COL):
            listaTexts[i][j].delete(0, "end")
            listaTexts[i][j].insert(0, str(tab[i][j]))
    print(tab)
예제 #6
0
    def triggered(self):
        self.low_edge  = [self.from_1.value(), self.from_2.value(), self.from_3.value()]
        self.high_edge = [self.to_1.value(), self.to_2.value(), self.to_3.value()]
        self.step = [self.st_1.value(), self.st_2.value(), self.st_3.value()]
        if self.custom_struct:
            solver = SolveExpTh(self.params)
        else:
            solver = Solve(self.params)
        p = [[i for i in range(self.low_edge[j], self.high_edge[j]+1, self.step[j])] for j in range(len(self.step))]
        best_deg = determine_deg(solver, p[0], p[1], p[2])
        bd = best_deg[0]
        self.res_1.setValue(bd[0])
        self.res_2.setValue(bd[1])
        self.res_3.setValue(bd[2])

        msgbox = QMessageBox()

        msgbox.setText('Best degrees:'+bd.__str__()+'.')
        msgbox.setInformativeText("Do you want to copy degrees in main window?")
        msgbox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msgbox.setDefaultButton(QMessageBox.Ok)
        ret = msgbox.exec_()
        if ret == QMessageBox.Ok:
            self.update_degrees.emit(bd[0],bd[1], bd[2])
            self.close()
        # result = QMessageBox.question(self, 'Long-time operation',
        #                               'Adjusting degrees lasts long. Do you want to perform it?',
        #                               QMessageBox.Ok | QMessageBox.No)
        # if result == QMessageBox.Ok:
        #     BruteForceWindow.launch(self)

        #self.update_degrees.emit(3,3,3)
        return
예제 #7
0
    def Predection(self):
        MODEL_PATH = r'weights.06.hdf5'
        if self.radioButton_image.isChecked():
            images0 = self.lineEdit_path.displayText()
            s = Solve(MODEL_PATH, image=images0)
            result = str(s.solve_one())
            self.listEdit_result.setText(result)

        if self.radioButton_folder.isChecked():
            folder0 = self.lineEdit_path.displayText()
            s = Solve(path=MODEL_PATH, folder=folder0)
            s.solve_excel()
            result = 'Picture_set.xls'
            self.listEdit_result.setText(result)
예제 #8
0
파일: app.py 프로젝트: ttgamage/SecGen
                 methods=['GET','POST'])

app.add_url_rule('/login/',
                 view_func=Login.as_view('login'),
                 methods=['GET', 'POST'])

app.add_url_rule('/download/',
                 view_func=Download.as_view('download'),
                 methods=['GET', 'POST'])

app.add_url_rule('/score/',
                 view_func=Score.as_view('score'),
                 methods=['GET'])

app.add_url_rule('/solve/',
                 view_func=Solve.as_view('solve'),
                 methods=['GET', 'POST'])

app.add_url_rule('/<page>/',
                 view_func=Main.as_view('page'),
                 methods=['GET'])

import os
from flask import send_from_directory

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico')

@app.errorhandler(404)
def page_not_found(error):
예제 #9
0
    print("|-----------|-----------|-----------|")
    print(f"| {' | '.join([str(i) if i != 0 else ' ' for i in row])} |")

print("|-----------|-----------|-----------|")

print("""
        The Game
""")

for row in suduku.game_grid:
    print("|-----------|-----------|-----------|")
    print(f"| {' | '.join([str(i) if i != 0 else ' ' for i in row])} |")

print("|-----------|-----------|-----------|")

solver = Solve(suduku.game_grid)
result = solver.solve()

print(f"""
        Solved? {result}
""")

for row in solver.grid:
    print("|-----------|-----------|-----------|")
    print(f"| {' | '.join([str(i) if i != 0 else ' ' for i in row])} |")

print("|-----------|-----------|-----------|")

# for r,c in solver.choices:
#     print(f"({r},{c}): {solver.choices[(r,c)]}")
예제 #10
0
파일: main.py 프로젝트: gis727/8215-tp2
from solve import Solve

import argparse


def parse_arguments():
    parser = argparse.ArgumentParser()

    # Instances parameters
    parser.add_argument('--n_generator', type=int, default=25)
    parser.add_argument('--n_device', type=int, default=100)
    parser.add_argument('--seed', type=int, default=1)

    return parser.parse_args()


if __name__ == '__main__':

    args = parse_arguments()

    print("***********************************************************")
    print("[INFO] EVALUATING THE GENERATOR PROBLEM")
    print("[INFO] n_generator: %d" % args.n_generator)
    print("[INFO] n_device': %d" % args.n_device)
    print("[INFO] seed: %s" % args.seed)
    print("***********************************************************")

    solveur = Solve(args.n_generator, args.n_device, args.seed)

    solveur.solve_heuristc()
예제 #11
0
파일: main.py 프로젝트: nicoS5/INF8215
from solve import Solve


import argparse

def parse_arguments():
    parser = argparse.ArgumentParser()

    # Instances parameters
    parser.add_argument('--n_generator', type=int, default=25) #default=25
    parser.add_argument('--n_device', type=int, default=100) #default=100
    parser.add_argument('--seed', type=int, default=1) #default=1

    return parser.parse_args()

if __name__ == '__main__':

    args = parse_arguments()

    print("***********************************************************")
    print("[INFO] EVALUATING THE GENERATOR PROBLEM")
    print("[INFO] n_generator: %d" % args.n_generator)
    print("[INFO] n_device': %d" % args.n_device)
    print("[INFO] seed: %s" % args.seed)
    print("***********************************************************")

    solveur = Solve(args.n_generator, args.n_device, args.seed)

    #solveur.solve_naive()
    solveur.solve_genetic()
예제 #12
0
def main():
    scramble = []
    solve = None
    session_solves = SessionSolves()
    puzzle_selector = PuzzleSelector('3x3')
    puzzle = puzzle_selector.get_choice()

    pygame.init()
    clock = pygame.time.Clock()
    draw_info = DrawInformation(640, 600)
    location_in_app = LocationInApp.start_menu

    display_start_menu(draw_info, puzzle)
    while True:
        clock.tick(60)

        if location_in_app == location_in_app.start_menu:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_c:
                    display_commands(draw_info)
                if event.type == pygame.KEYUP and event.key == pygame.K_c:
                    display_start_menu(draw_info, puzzle)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                    scramble = display_new_scramble(draw_info, puzzle)
                    display_ready_label(draw_info, draw_info.WHITE)
                    display_solve_count(draw_info, session_solves)
                    display_current_averages(draw_info, session_solves)
                    location_in_app = LocationInApp.scrambling

        elif location_in_app == LocationInApp.scrambling:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_c:
                    display_commands(draw_info)
                if event.type == pygame.KEYUP and event.key == pygame.K_c:
                    display_same_scramble(draw_info, puzzle, scramble)
                    display_ready_label(draw_info, draw_info.WHITE)
                    display_solve_count(draw_info, session_solves)
                    display_current_averages(draw_info, session_solves)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_v:
                    scroll = 0
                    display_previous_solves(draw_info, session_solves, scroll)
                    location_in_app = LocationInApp.viewing_previous_solves
                if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                    scramble = display_new_scramble(draw_info, puzzle)
                    display_ready_label(draw_info, draw_info.WHITE)
                    display_solve_count(draw_info, session_solves)
                    display_current_averages(draw_info, session_solves)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    display_ready_label(draw_info, draw_info.YELLOW)
                    begin = perf_counter()
                if event.type == pygame.KEYUP and event.key == pygame.K_SPACE:
                    end = perf_counter()
                    if end - begin < 0.3:
                        display_ready_label(draw_info, draw_info.RED)
                    else:
                        start_timer = perf_counter()
                        location_in_app = LocationInApp.solving
                if event.type == pygame.KEYDOWN and event.key == pygame.K_END:
                    display_end_of_sessions_instructions(draw_info)
                    scroll = 0
                    display_solve_list(draw_info, session_solves, scroll)
                    display_session_stats(draw_info, session_solves)
                    generate_plot(session_solves)
                    location_in_app = LocationInApp.end_of_session

        elif location_in_app == LocationInApp.solving:
            display_timer(draw_info, perf_counter() - start_timer)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    display_ready_label(draw_info, draw_info.YELLOW)
                    end_timer = perf_counter()
                    solve_time = end_timer - start_timer
                    solve = Solve(puzzle, scramble, solve_time)
                    session_solves.add_solve(solve)
                    display_solve_time(draw_info, solve)
                    display_ps(draw_info)
                    penalty_added = False
                    location_in_app = LocationInApp.assigning_penalties

        elif location_in_app == LocationInApp.assigning_penalties:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_c:
                    display_commands(draw_info)
                if event.type == pygame.KEYUP and event.key == pygame.K_c:
                    display_solve_time(draw_info, solve)
                    if not penalty_added:
                        display_ps(draw_info)
                    else:
                        display_proceed(draw_info)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_2 and not penalty_added:
                    solve.plus2()
                    display_solve_time(draw_info, solve)
                    display_proceed(draw_info)
                    penalty_added = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_d and not penalty_added:
                    solve.dnf()
                    display_solve_time(draw_info, solve)
                    display_proceed(draw_info)
                    penalty_added = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_BACKSPACE and not penalty_added:
                    session_solves.delete_last_solve()
                    display_solve_deleted(draw_info)
                    display_proceed(draw_info)
                    penalty_added = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_t and not penalty_added:
                    location_in_app = LocationInApp.manually_adding_time
                    user_input = 'Start Typing'
                    display_time_input(draw_info, user_input)
                    user_input = ''
                    penalty_added = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                    scramble = display_new_scramble(draw_info, puzzle)
                    display_ready_label(draw_info, draw_info.WHITE)
                    display_solve_count(draw_info, session_solves)
                    display_current_averages(draw_info, session_solves)
                    location_in_app = LocationInApp.scrambling
                if event.type == pygame.KEYDOWN and event.key == pygame.K_END:
                    display_end_of_sessions_instructions(draw_info)
                    scroll = 0
                    display_solve_list(draw_info, session_solves, scroll)
                    display_session_stats(draw_info, session_solves)
                    generate_plot(session_solves)
                    location_in_app = LocationInApp.end_of_session

        elif location_in_app == LocationInApp.manually_adding_time:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        try:
                            solve_time = float(user_input)
                            if solve_time <= 0:
                                display_invalid_input(
                                    draw_info, 'enter a POSITIVE number')
                            else:
                                solve.set_time(solve_time)
                                display_solve_time(draw_info, solve)
                                location_in_app = LocationInApp.assigning_penalties
                        except ValueError:
                            display_invalid_input(
                                draw_info,
                                "enter time in this format: '00.000'")
                        finally:
                            user_input = ''
                    elif event.key == pygame.K_BACKSPACE:
                        user_input = user_input[:-1]
                        display_time_input(draw_info, user_input)
                    elif event.key == pygame.K_t and len(user_input) == 0:
                        user_input = 'Start Typing'
                        display_time_input(draw_info, user_input)
                        user_input = ''
                    else:
                        user_input += event.unicode
                        display_time_input(draw_info, user_input)

        elif location_in_app == LocationInApp.viewing_previous_solves:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_UP and scroll > 0:
                    scroll -= 1
                    display_previous_solves(draw_info, session_solves, scroll)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and scroll < session_solves.get_number_of_solves(
                ) - 12:
                    scroll += 1
                    display_previous_solves(draw_info, session_solves, scroll)
                if event.type == pygame.KEYUP and event.key == pygame.K_b:
                    location_in_app = LocationInApp.scrambling
                    display_same_scramble(draw_info, puzzle, scramble)
                    display_ready_label(draw_info, draw_info.WHITE)
                    display_solve_count(draw_info, session_solves)
                    display_current_averages(draw_info, session_solves)

        elif location_in_app == LocationInApp.end_of_session:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                    pygame.quit()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_UP and scroll > 0:
                    scroll -= 1
                    display_solve_list(draw_info, session_solves, scroll)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and scroll < session_solves.get_number_of_solves(
                ) - 12:
                    scroll += 1
                    display_solve_list(draw_info, session_solves, scroll)
                if event.type == pygame.KEYUP and event.key == pygame.K_n:
                    scramble = []
                    solve = None
                    session_solves = SessionSolves()
                    puzzle_selector = PuzzleSelector(puzzle)
                    puzzle = puzzle_selector.get_choice()
                    location_in_app = LocationInApp.start_menu
                    display_start_menu(draw_info, puzzle)
# makes sure that the colors file (colors1.txt or colors2.txt) is specified
if (not len(sys.argv) == 2):
    print "Must specify the \'colors\' file name as an argument."
    sys.exit(0)

# extracts the name of the colors file from the command line argument
colorsFile = str(sys.argv[1])

# read the set of allowed colors from the colors file specified on the command line
colors = [line.strip() for line in open(colorsFile)]

# read the graph to color from "graph.txt" file
g = Graph("graph.txt")

# initialize the solver (with graph and the set of colors as input)
solver = Solve(g, colors)

# compute a graph coloring, which is an assignment of colors to nodes in the graph
# if there is no feasible coloring solution, the output is an empty list (assignment = [])
assignment = solver.solve()

# if assignment is an empty list, output "Infeasible\n" to the result.txt file
# otherwise (if there is a feasible assignment), output "Feasible\n" to the result.txt
f = open('result.txt', 'w')

if not assignment:
    f.write("Infeasible\n")
else:
    f.write("Feasible\n")
예제 #14
0
파일: main.py 프로젝트: QQQQQIU/CST
# date:2021-01-10
from create import generate_maze
from solve import Solve
from player import startgame

while 1:
    astr = input("\n欢迎体验迷宫游戏\n输入***退出程序\n请问您要尝试几阶迷宫:")
    if astr.isdigit():
        num = int(astr)
        if num % 2 == 0:
            num += 1
        if num <= 3:
            print(f'{num}阶太小了,试试大一点的~')
        else:
            maze = generate_maze(num)
            maze_object = Solve(maze[0], maze[1][0], maze[1][1], maze[2][0], maze[2][1])
            player_step = startgame(maze[0], maze[1][0], maze[1][1], maze[2][0], maze[2][1])
            if player_step:
                ministep = maze_object.ministeps
                score = (1 - (player_step - ministep) / ministep) * 100
                print("最少步数为%d步,您的完成度为%.2f%%" % (ministep, score))
                print("以下为最佳路线")
                maze_object.print_minipath()
            else:
                print("游戏结束,下次再见!")
                break
    elif astr == "***":
        print("游戏结束,下次再见!")
        break
    else:
        print("请输入正整数,或***退出游戏\n")