Exemplo n.º 1
0
def driver():
    global default_file_name, default_separator, default_show_comment, default_show_all, default_show_traceback, default_show_exception, default_show_exception_message
    local = locals()
    globl = globals()
    print("Driver started")
    old = "!"
    while True:
        try:
            old = prompt.for_string("Command", default=old)
            if old == "quit":
                print("Driver stopped")
                return None
            if old == "!":
                batch_self_check()
            elif old == "?":
                default_file_name = prompt.for_string("file_name             ", default_file_name)
                default_separator = prompt.for_string("separator             ", default_separator)
                default_show_comment = prompt.for_bool("show_comment          ", default_show_comment)
                default_show_all = prompt.for_bool("show_all              ", default_show_all)
                default_show_traceback = prompt.for_bool("show_traceback        ", default_show_traceback)
                default_show_exception = prompt.for_bool("show_exception        ", default_show_exception)
                default_show_exception_message = prompt.for_bool(
                    "show_exception_message", default_show_exception_message
                )
                batch_self_check()
                old = "!"
            else:
                exec(old, local, globl)
            print()
        except Exception:
            traceback.print_exc()
            print()
Exemplo n.º 2
0
def driver():
    global default_file_name,default_separator,default_show_comment,\
           default_show_all,default_show_traceback,default_show_exception,\
           default_show_exception_message
    local = locals()
    globl = globals()
    print('Driver started')
    old = '!'
    while True:
        try:
            old = prompt.for_string('Command',default=old)
            if old == 'quit':
                print('Driver stopped')
                return None
            if old == '!':
                batch_self_check()
            elif old == '?':
                default_file_name              = prompt.for_string('file_name             ',default_file_name)
                default_separator              = prompt.for_string('separator             ',default_separator)
                default_show_comment           = prompt.for_bool  ('show_comment          ',default_show_comment)
                default_show_all               = prompt.for_bool  ('show_all              ',default_show_all)
                default_show_traceback         = prompt.for_bool  ('show_traceback        ',default_show_traceback)
                default_show_exception         = prompt.for_bool  ('show_exception        ',default_show_exception)
                default_show_exception_message = prompt.for_bool  ('show_exception_message',default_show_exception_message)
                batch_self_check()
                old = '!'
            else:
                exec(old,local,globl)
            print()
        except Exception:
            traceback.print_exc()
            print()
Exemplo n.º 3
0
def batch_test(file_name,confirm=False):
    print('Starting batch_test')
    for command in open(file_name,'r'):
        try:
            command = command.rstrip()
            print('\nCommand:',command)
            if confirm:
                prompt.for_string('Press enter to do command','')
            exec(command)
        except Exception:
            traceback.print_exc()
    print('\nDone batch_test\n')
Exemplo n.º 4
0
def batch_test(file_name, confirm=False):
    print('Starting batch_test')
    for command in open(file_name, 'r'):
        try:
            command = command.rstrip()
            print('\nCommand:', command)
            if confirm:
                prompt.for_string('Press enter to do command', '')
            exec(command)
        except Exception:
            traceback.print_exc()
    print('\nDone batch_test\n')
Exemplo n.º 5
0
def batch_test(file_name, confirm=False):
    print("Starting batch_test")
    local = locals()
    globl = globals()
    for command in open(file_name, "r"):
        try:
            command = command.rstrip()
            print("\nCommand:", command)
            if confirm:
                prompt.for_string("Press enter to do command", "")
            exec(command, globl, local)
        except Exception:
            traceback.print_exc()
    print("\nDone batch_test\n")
Exemplo n.º 6
0
def main():
    print_welcome_screen()
    shouldLoadFromSavefile = prompt.for_string(
        "Do you want to start a (n)ew tournament or (r)eload a tournament?",
        is_legal=(lambda x: x == "r" or x == "n"),
        error_message="Please enter n or r.",
    )
    if shouldLoadFromSavefile == "r":
        fileStr = prompt.for_string(
            "Enter the (round number) you want to reload from")
        run_from_file(fileStr)
    else:
        fob = goody.safe_open(
            "Press enter once all your partipants are in PutYourTournamentParticipantsHere",
            "r",
            "There was an error finding/opening the file.",
            default="PutYourTournamentParticipantsHere.txt",
        )
        players = file.get_names(fob)
        while len(players) < 4:
            print()
            print(
                "You need at least 4 players to start a tournaments, please edit PutYourTournamentParticipantsHere.txt and press enter"
            )
            input()
            fob.close()
            fob = goody.safe_open(
                "Don't forget to save the file!",
                "r",
                "There was an error finding/opening the file.",
                default="PutYourTournamentParticipantsHere.txt",
            )
            players = file.get_names(fob)

        while True:
            for player in players:
                print(player.name)
            print("***There are currently", len(players),
                  "players enrolled.***")
            start = prompt.for_string(
                "Start tournament? Enter (y)es or (n)o",
                is_legal=(lambda x: x == "y" or x == "n"),
                error_message="Please enter y or n.",
            )
            if start == "y":
                run_tournament(players, 1)
                break
            else:
                sys.exit("Ok, no rush! Restart the program when you're ready!")
Exemplo n.º 7
0
def repeat(func, **kargs):
    while True:
        test = prompt.for_string("Enter txt", default="")
        kargs["txt"] = test
        if test == "":
            break
        func(**kargs)
Exemplo n.º 8
0
def get_results(pairs, players):
    still_playing = set(range(1, len(pairs) + 1))
    while len(still_playing) > 0:
        print("Waiting for results from tables", still_playing)
        table = prompt.for_int(
            "Enter a table number to report results",
            is_legal=lambda x: x in still_playing,
            error_message="Enter a table that has not finished their match.",
        )
        table -= 1
        winner = prompt.for_string(
            "Enter a winner (" + str(pairs[table][0].name) + ") or (" +
            str(pairs[table][1].name) + ") or (tie)",
            is_legal=(lambda x: x == pairs[table][0].name or x == pairs[table][
                1].name or x == "tie"),
            error_message="please enter the winner's full name or tie",
        )
        if winner == "tie":
            pairs[table][0].ties.append(pairs[table][1])
            pairs[table][1].ties.append(pairs[table][0])
        else:
            if winner == pairs[table][0].name:
                pairs[table][0].wins.append(pairs[table][1])
                pairs[table][1].losses.append(pairs[table][0])
            else:
                pairs[table][1].wins.append(pairs[table][0])
                pairs[table][0].losses.append(pairs[table][1])

        still_playing.remove(table + 1)
        print()
Exemplo n.º 9
0
def repeat(func,**kargs):
    while True:
        test = prompt.for_string("Enter txt",default="")
        kargs["txt"] = test
        if test == "" :
            break;
        func(**kargs)
Exemplo n.º 10
0
def targeted_action(game, turn_counter):
	row, column = get_row_and_column_from_input(game)
	valid_action = False
	while not valid_action:
		action = prompt.for_string(
			'Enter action ("o" for options) ',
			default='').lower()
		if action == '':	# add number
			number = prompt.for_int('Enter number', is_legal=(lambda x: 1 <= x <=9))
			game.make_move(row, column, number)
			turn_counter += 1
			valid_action = True
		elif action == 'r': # remove number
			game.remove(row, column)
			turn_counter += 1
			valid_action = True
		elif action == 'c': # change number
			number = prompt.for_int('Enter number', is_legal=(lambda x: 1 <= x <=9))
			game.change(row, column, number)
			turn_counter += 1
			valid_action = True
		elif action == 'o': # list options
			print('{:>10}:\t Add piece'.format('<Enter>'))
			print('{:>10}:\t Remove piece'.format('r'))
			print('{:>10}:\t Change piece'.format('c'))
			print('{:>10}:\t Return to main menu'.format('e'))
		elif action == 'e': # exit the current prompt
			valid_action = True
	return turn_counter
Exemplo n.º 11
0
def final_script():
    ''' a script at the bottom of this module that calls these functions to solve the problem. (mine is 8 lines). 
    '''
    order_stat = prompt.for_int('Enter order statistic',
                                default=None,
                                is_legal=(lambda x: True),
                                error_message='It is not an integer.s')
    dictionary = read_corpus(
        order_stat,
        goody.safe_open('Enter file to process',
                        'r',
                        'No file avail. Try again.',
                        default=None))
    print_corpus(dictionary)
    print('Enter ' + str(order_stat) + ' words to start with')
    starting_words = []
    for i in range(order_stat):
        starting_words.append(
            prompt.for_string('Enter word ' + str(i + 1),
                              default=None,
                              is_legal=(lambda x: True),
                              error_message=''))
    number = prompt.for_int('Enter # of words to generate',
                            default=None,
                            is_legal=(lambda x: True),
                            error_message='an int, but not a legal value')
    print('Random text = ' +
          str(produce_text(dictionary, starting_words, number)))
Exemplo n.º 12
0
def drop_player(players):
    while True:
        dropping = prompt.for_string(
            "Enter the name of player who is dropping or (d)one",
            is_legal=lambda x: x in [y.name for y in players] or x == 'd',
            error_message='Invalid player name.')
        if dropping == 'd':
            break
        for i in range(len(players)):
            if dropping == players[i]:
                del players[i]
Exemplo n.º 13
0
def get_sudoku_pack_from_input():
	sudoku_pack = ""
	while True:
		sudoku_pack = prompt.for_string(
							'Choose the sudoku pack you want to use ("o" to read options) ', 
							default='0', error_message='Not a valid sudoku pack.')
		if sudoku_pack.lower() == 'o':
			with open(constants.PACKLIST, 'r', encoding='utf-8') as pack_list_file:
				print(pack_list_file.readline().strip())
		else:
			break
	return sudoku_pack
Exemplo n.º 14
0
def final_script():
    ''' a script at the bottom of this module that calls these functions to solve the problem. (mine is 8 lines). 
    '''
    order_stat = prompt.for_int('Enter order statistic', default=None, is_legal=(lambda x : True), error_message='It is not an integer.s')
    dictionary = read_corpus(order_stat,goody.safe_open('Enter file to process', 'r', 'No file avail. Try again.',default=None))
    print_corpus(dictionary)
    print ('Enter ' + str(order_stat) + ' words to start with')
    starting_words = []
    for i in range(order_stat):
        starting_words.append(prompt.for_string('Enter word ' + str(i+1) , default=None, is_legal=(lambda x : True), error_message=''))
    number = prompt.for_int('Enter # of words to generate', default=None, is_legal=(lambda x : True), error_message='an int, but not a legal value')
    print ('Random text = ' + str(produce_text(dictionary, starting_words, number)))
Exemplo n.º 15
0
def reachable(dictionary):
    '''reachable has a dict parameter (representing the graph) and a str start node in the graph 
    (technically a key in the dict; it returns a set of all the nodes reachable from it by following edges in the graph
    '''
    init_list = list(dictionary.keys())
    init_list.sort()

    k = prompt.for_string(
        'Enter starting node, or "'
        "quit"
        '" to exit',
        default=None,
        is_legal=(lambda x: x in init_list),
        error_message='Char not in the list of graph source nodes.')

    while k != 'quit':
        reached_set = set()
        lst = [k]
        #         lst.extend(list(dictionary[k]))
        while len(lst) > 0:
            if lst[0] in list(dictionary.keys()):
                for items in dictionary[lst[0]]:
                    if items not in lst and items not in reached_set and items in list(
                            dictionary.keys()):
                        lst.append(items)


#                     elif items not in lst and items not in reached_set and items not in list(dictionary.keys()):
                    reached_set.add(items)
                reached_set.add(lst.pop(0))

        print("From " + k + " the reachable nodes are:" + str(reached_set) +
              '\n')
        k = prompt.for_string(
            'Enter starting node, or "'
            "quit"
            '" to exit',
            default=None,
            is_legal=(lambda x: x in init_list + ['quit']),
            error_message='Char not in the list of graph source nodes.')
Exemplo n.º 16
0
def all_influenced(graph: {str: {str}}, influencers: {str}) -> {str}:

    while True:

        user_nodes = prompt.for_string(
            '\nEnter influencers set (or else quit)',
            default=influencers,
            is_legal=(lambda x: True),
            error_message='Please enter a legal String')
        total = len(graph.keys())
        if user_nodes == 'quit':
            break
        else:
            user_nodes = eval(user_nodes)
            influenced_nodes_list = []
            for x in user_nodes:
                if x.isalpha():
                    influenced_nodes_list.append(x)

            count = 0
            for node in influenced_nodes_list:
                if node in graph.keys():
                    count += 1
            if count == len(influenced_nodes_list):
                print('yay', influenced_nodes_list)

                for node in influenced_nodes_list:
                    for friend in graph[node]:
                        print(friend)

            else:
                print("Entry Error: " + "'" + str(user_nodes) + "'" + ';' +
                      "\nPlease enter a legal String")
                user_nodes = prompt.for_string(
                    '\nEnter influencers set (or else quit)',
                    default=influencers,
                    is_legal=(lambda x: True),
                    error_message='Please enter a legal String')
Exemplo n.º 17
0
def main_turn_menu():
	decision_valid = False
	while not decision_valid:
		decision = prompt.for_string('Next action ("o" to read options) ', default='')
		if decision in ['', 'u', 'r', 'o', 'q', 'l', 's']:
			decision_valid = True
			if decision == 'o':
				print('{:>10}:\t Targeted action'.format('<Enter>'))
				print('{:>10}:\t Undo move'.format('u'))
				print('{:>10}:\t Redo move'.format('r'))
				print('{:>10}:\t Load state'.format('l'))				
				print('{:>10}:\t Save state'.format('s'))
				print('{:>10}:\t Quit'.format('q'))
	return decision
Exemplo n.º 18
0
def reachable(dictionary):
    '''reachable has a dict parameter (representing the graph) and a str start node in the graph 
    (technically a key in the dict; it returns a set of all the nodes reachable from it by following edges in the graph
    '''
    init_list = list(dictionary.keys())
    init_list.sort()
    
    k = prompt.for_string('Enter starting node, or "'"quit"'" to exit', default=None, is_legal=(lambda x: x in init_list), error_message='Char not in the list of graph source nodes.')

    while k != 'quit':
        reached_set = set()
        lst = [k]
#         lst.extend(list(dictionary[k]))
        while len(lst) > 0:
            if lst[0] in list(dictionary.keys()):
                for items in dictionary[lst[0]]:
                    if items not in lst and items not in reached_set and items in list(dictionary.keys()):
                        lst.append(items)
#                     elif items not in lst and items not in reached_set and items not in list(dictionary.keys()):
                    reached_set.add(items)
                reached_set.add(lst.pop(0))
        
        print("From " +k+ " the reachable nodes are:" + str(reached_set) + '\n')
        k = prompt.for_string('Enter starting node, or "'"quit"'" to exit', default=None, is_legal=(lambda x: x in init_list + ['quit']), error_message='Char not in the list of graph source nodes.')
Exemplo n.º 19
0
 def main_loop(self):
     while True:
         content = prompt.for_string("输入查询功能(else quit)", default='L')
         if content == 'quit':
             break
         if content == 'L':
             result_dict = {}
             for course in self.courses:
                 result_dict[course.name] = [0,0]#Enr,Max
                 for lec_info in course.leces:
                     if '/' in lec_info['Enr']:
                         enr = lec_info['Enr'].split('/')[1]
                         result_dict[course.name][0] += int(enr)
                     else:
                         result_dict[course.name][0] += int(lec_info['Enr'])
                     result_dict[course.name][1] += int(lec_info['Max'])
             result_list = sorted([(item,round(item[1][0]/item[1][1],3) ) for item in result_dict.items()if item[1][1] != 0 ],key = lambda x:(x[1],x[0][0] ))
             for item in result_list:
                 print(item)
     self.__init__()
Exemplo n.º 20
0
def end_of_round_cleanup(players):
    while True:
        dropping = prompt.for_string(
            "Enter the (name of a player) who is dropping or (p)air next round or view (s)tandings or (a)dd a new player",
            is_legal=lambda x: x in [y.name for y in players] or x == "p" or x
            == "s" or x == "a",
            error_message="Invalid player name or not (p), (s), or (a)",
        )
        if dropping == "p":
            break
        elif dropping == "s":
            calculate_standings(players)
            print_standings(players)
        elif dropping == "a":
            new_player = Player.Player(
                input("Enter the name of the new player: "))
            num_byes = prompt.for_int(
                "Enter the number of byes this player has (if any). For example if this player is entering with a round 1 loss, enter 0. If this player is entering round 2 with a 1-0 record enter 1",
                is_legal=lambda x: x < num_rounds,
                error_message=
                'A player should not have more byes than the total number of rounds.'
            )
            for i in range(num_byes):
                new_player.wins.append('BYE')
            players.append(new_player)

        else:
            for i in range(len(players)):
                if dropping == players[i].name:
                    print(players[i].name, "has been dropped.")
                    global dropped_players
                    #add the '#' character to signify that the player has been dropped
                    #for run_from_file purposes
                    players[i].name = '#' + players[i].name
                    dropped_players.append(players[i])
                    del players[i]
                    break

        print()
Exemplo n.º 21
0
def UI():
    "An prompt based User Interface"
    file = None
    while file is None:
        try:
            file = open(input("Input the file name detailing the graph:"))
            Graph = read_graph(file)
        except FileNotFoundError:
            print("Error, file not found...")

    print("Graph: str (source node) -> [str] (sorted destination nodes)")
    graph_as_str(Graph)
    while True:
        start = prompt.for_string(
            ' Input one starting node (or input done)',
            is_legal=lambda start: start in Graph or start == 'done',
            error_message="Illegal: not a source node")
        if start == "done":
            return
        tracing = prompt.for_bool("Input tracing algorithm option", True,
                                  "Enter False to disable tracing")
        print(f"From the starting node {start}, its reachable nodes are:",
              reachable(Graph, start, tracing))
Exemplo n.º 22
0
# Future changes: search ALL files in a directory

import re
import prompt
from goody import safe_open

pattern_string = prompt.for_string(
    'Enter Regular Expression pattern to search for')
pattern = re.compile(pattern_string)
file = safe_open('Enter file to search', 'r', 'Could not find that file')
for line, contents in enumerate(file, 1):
    if pattern.search(
            contents):  # note search not match: pattern can start anywhere
        print('{:<5}: {}'.format(line, contents), end='')
file.close()
Exemplo n.º 23
0
  an - add_node      nc - node_count       . - exec(...)                  rg  - random graph
  ae - add_edge      ec - edge_count       in  - iterator node            cc  - connected components
  rn - remove_node   mt - is_empty         ie  - iterator edges           mst - minimum spanning tree
  re - remove_edge   hn - has_node         iin - iterator in_node         sym - make symmetric
  c  - clear         he - has_edge         ion - iterator out_nodes
                     e  - edge_value       iie - iterator in_edges
                     id - in_degree        ion - iterator out_edges
                     od - out_degree       r   - read
                     d  - degree           w   - write
                     _  - str              q   - quit
                     
               
Command"""
    g = eval('Graph(' + input('g = Graph('))
    while True:
        action = prompt.for_string(command_prompt, is_legal= \
                 lambda x : x in 'an ae rn re c nc ec mt hn he e id od d _ . in ie iin ion iie ion r w q rg cc mst sym'.split(' '))
        try:
            if action == 'an':
                g.add_node(prompt.for_string('  Enter node to add'))
            elif action == 'ae':
                g.add_edge(
                    prompt_edge('  Enter edge to add'),
                    prompt.for_int('  Value (int) for edge',
                                   is_legal=predicate.is_non_negative))
            elif action == 'rn':
                g.remove_node(prompt.for_string('  Enter node to remove'))
            elif action == 're':
                g.remove_edge(prompt_edge('  Enter edge to remove'))
            elif action == 'c':
                g.clear()
Exemplo n.º 24
0
     
    function_definition = \
      function_template.format(init = '['+','.join(["'"+i+"'" for i in filter_letters])+']')

    if decorate:
        function_definition += "    return '-->'+result+'<--'"
    else:
        function_definition += "    return result"

    # A bit of magic (same in pnamedtuple)
    name_space = dict(__name__='make_keep')
    try:
        exec(function_definition, name_space)
    except SyntaxError:
        show_listing(function_definition)
        traceback.print_exc()
        
    if prompt.for_bool('print definition?',True):
        show_listing(function_definition)  # comment out
    return name_space['keep']
 

# Get information, make function, test it
filter_letters = prompt.for_string('Enter disallowed letters')
decorate_it    = prompt.for_bool('Decorate it?',True)
    
f = make_keep(filter_letters,decorate_it)

word = prompt.for_string('Enter word')
print('returned word =',f(word))
Exemplo n.º 25
0
    answer.sort(reverse=True); 
    return [' '.join(x[1]) for x in answer[0:n]] 
  
  
  
# Script 
  
if __name__ == '__main__': 
    file_to_read = safe_open('Enter name of file with queries', 'r', 
                            'Could not find that file') 
    (prefix_dict,query_dict) = read_queries(file_to_read) 
      
    print_dicts(prefix_dict,query_dict)  
      
    while (True): 
        prefix  = prompt.for_string('\nEnter prefix (or q to quit)') 
        if prefix == 'q': 
            break; 
        print('Top 3 full queries =', top_n(tuple(prefix.split(' ')),prefix_dict,query_dict,3)) 
        
        
        
        
        
        
        
        
        
    
        
        
Exemplo n.º 26
0
    import prompt
    print('Begin testing PriorityQueue')
    command_prompt = \
"""\nTesting PriorityQueue:
Commands     Queries         Other
  a - add      p - peek        . - exec(...)
  r - remove   e - is_empty    i - iterator
  c - clear    s - size        q - quit
  m - merge    _ - __str__
               
Command"""
    pq = eval('PriorityQueue(' + input('pq = PriorityeQueue('))
    while True:
        action = prompt.for_char(command_prompt, legal='arcmpes_.iq')
        try:
            if action == 'a': pq.add(prompt.for_string('  Enter value to add'))
            elif action == 'r': print('  remove =', pq.remove())
            elif action == 'c': pq.clear()
            elif action == 'm': exec('pq.merge(' + input('pq.merge('))

            elif action == 'p': print('  peek =', pq.peek())
            elif action == 'e': print('  is_empty =', pq.is_empty())
            elif action == 's': print('  size =', pq.size())
            elif action == '_': print('  str =', pq)

            elif action == '.':
                exec(
                    prompt.for_string('  Enter command to exec (instance=pq)'))
            elif action == 'i':
                print('  iteration order =', [i for i in pq])
            elif action == 'q':
Exemplo n.º 27
0
    print("Begin testing Stopwatch")
    commandPrompt = \
"""\nTesting Stopwatch:
Commands                Queries        Other
  > - start               ? - read       . - exec(...)
  s - stop                : - status     q - quit
  < - start_backwards     _ - __str__
  r - reset\nCommand"""
    s = Stopwatch()
    while True:
        action = prompt.for_char(commandPrompt, legal=">s<r?:_.q")
        try:
            if action == ">": s.start()
            elif action == "s": s.stop()
            elif action == "<": s.start_backwards()
            elif action == "r": s.reset()
            elif action == "?": print("  Elapsed =", s.read(), "seconds")
            elif action == ":": print("  Status =", s.status())
            elif action == "_": print("  __str__ =", str(s))
            elif action == ".":
                exec(prompt.for_string("  Enter command to exec (instance=s)"))
            elif action == "q":
                break
            else:
                print("  Unknown command")
        except AssertionError as report:
            print("  AssertionError exception caught:", report)
        except Exception as report:
            import traceback
            traceback.print_exc()
    print("\nFinished testing Stopwatch")
Exemplo n.º 28
0
  ep - enter pat            s  - search         rs/bs   - repeat/batch search
  er - enter rpl            fa - findall        rfa/bfs - repeat/batch findall
  ?  - show t/p/r           su - substitute     rsu/bsu - repeat/batch substitute
                            sp - split          rsp/bsp - repeat/batch split
                                                .       - exec(...)
                                                q       - quit
\nCommand"""
    pat = ""
    txt = ""
    rpl = ""
    while True:
        try:
            action = prompt.for_string(
                commandPrompt,
                is_legal=(lambda x: x in [
                    'et', 'ep', 'er', '?', 'm', 's', 'fa', 'su', 'sp', 'rm',
                    'bm', 'rs', 'bs', 'rfa', 'bfa', 'rsu', 'bsu', 'rsp', 'bsp',
                    '.', 'q'
                ]))
            if action == 'et': txt = prompt.for_string("Enter txt")
            elif action == 'ep': pat = prompt.for_string("Enter pat")
            elif action == 'er':
                rpl = prompt.for_string("Enter rpl", default="")
            elif action == '?':
                print("    txt = ", txt)
                print("    pat = ", pat)
                print("    rpl = ", rpl)
            elif action == 'm':
                test_match(pat, txt)
            elif action == 's':
                test_search(pat, txt)
Exemplo n.º 29
0
if __name__ == '__main__': 
    import prompt
    print('Begin testing Dice') 
    command_prompt = \
"""\nTesting Dice:
Commands     Queries                  Other
  r - roll     n - number_of_dice       . - exec(...)
               m - all_pip_maximums     D - standard_rolls_for_debugging
               s - rolls                q - quit
               o - pips_on
               a - all_pips
               ? - pip_sum
               =  - pips_same
               _  - __str__
Command"""                            
    d = Dice(eval(prompt.for_string('Enter list of max pips', default='[6,6]')))
    while True:
        action = prompt.for_char(command_prompt, legal='rnmsoa?=_.Dq')
        try:
            if   action == 'r': d.roll()
            elif action == 'n': print('  Number of dice =',d.number_of_dice())
            elif action == 'm': print('  all pip maximums =',d.all_pip_maximums())
            elif action == 's': print('  rolls =',d.rolls())
            elif action == 'o':
                i = prompt.for_int_between('  Enter die #', 0, d.number_of_dice()-1)
                print('  pips on die #',str(i),' =',d.pips_on(i))
            elif action == 'a': print('  all pips =',d.all_pips())
            elif action == '?': print('  pip sum =',d.pip_sum())
            elif action == '=': print('  pips all the same =',d.pips_same())
            elif action == '_': print('  str =',str(d))
            elif action == '.': exec(prompt.for_string('  Enter command to exec (instance=d)'))
Exemplo n.º 30
0
    import prompt
    print('Begin testing Stack')
    command_prompt = \
"""\nTesting Stack:
Commands     Queries         Other
  a - add      p - peek        . - exec(...)
  r - remove   e - is_empty    i - iterator
  c - clear    s - size        q - quit
               _ - __str__
               
Command"""
    s = eval('Stack(' + input('s = Stack('))
    while True:
        action = prompt.for_char(command_prompt, legal='arcpes_.iq')
        try:
            if action == 'a': s.add(prompt.for_string('  Enter value to add'))
            elif action == 'r': print('  remove =', s.remove())
            elif action == 'c': s.clear()

            elif action == 'p': print('  peek =', s.peek())
            elif action == 'e': print('  is_empty =', s.is_empty())
            elif action == 's': print('  size =', s.size())
            elif action == '_': print('  str =', s)

            elif action == '.':
                exec(prompt.for_string('  Enter command to exec (instance=s)'))
            elif action == 'i':
                print('  iteration order =', [i for i in s])
            elif action == 'q':
                break
            else:
Exemplo n.º 31
0
    return process_steps


def interpret(result: [None]) -> str:
    out_string = "Start state = " + str(result[0]) + "\n"
    for i in range(1, len(result)):
        out_string += "  Input = {}; new possible states = {}\n".format(
            result[i][0], sorted(list(result[i][1])))
    out_string += "Stop state(s) = " + str(sorted(list(result[-1][1]))) + "\n"
    return out_string


if __name__ == '__main__':
    # Write script here
    ndfa_file_name = prompt.for_string(
        "Enter the file name describing this Non-Deterministic Finite Automaton",
        is_legal=(lambda f: open(f)),
        error_message="Please enter a valid file name")
    with open(ndfa_file_name) as f:
        ndfa = read_ndfa(f)
        print(
            "\nThe Description of the file entered for this Non-Deterministic Finite Automaton"
        )
        print(ndfa_as_str(ndfa))
    input_file_name = prompt.for_string(
        "Enter the file name describing a sequence of start-states and all their inputs",
        is_legal=(lambda f: open(f)),
        error_message="Please enter a valid file name")
    print()
    with open(input_file_name) as f:
        for line in f:
            line_list = line.strip("\n").split(";")
Exemplo n.º 32
0
        answer += Rational(1,math.factorial(i))
    return answer

# Newton: pi = 6*arcsin(1/2); see the arcsin series at http://mathforum.org/library/drmath/view/54137.html
# Check your results at http://www.numberworld.org/misc_runs/pi-5t/details.html
def compute_pi(n):
    def prod(r):
        answer = 1
        for i in r:
            answer *= i
        return answer
    
    answer = Rational(1,2)
    x      = Rational(1,2)
    for i in irange(1,n):
        big = 2*i+1
        answer += Rational(prod(range(1,big,2)),prod(range(2,big,2)))*x**big/big       
    return 6*answer


for i in irange(1,20):
    print(compute_e(i))
# Driver: prompts and executes commands (can call compute_e/computer_pi)
while True:
    try:
        exec(prompt.for_string('Command'))
    except Exception as report:
        import traceback
        traceback.print_exc()
     
    
Exemplo n.º 33
0
def prompt_load_pack():
	load_pack = prompt.for_string('Start a new game', default='y', 
									is_legal=y_or_n, error_message='(y/n)')
	return load_pack.lower() == 'y'
Exemplo n.º 34
0
        if graph.get(exploring_list[0]):
            for node in graph.get(exploring_list[0]):
                if node not in reached_set:
                    exploring_list.append(node)
        x = exploring_list.pop(0)
        reached_set.add(x)
        if trace == True:
            print(f"removing node {x} from the exploring list; adding it to reached list\n"
                  f"after adding all nodes reachable directly from a but not already in reached, exploring = {exploring_list}\n")
    return reached_set


if __name__ == '__main__':
    # Write script here
    graph = read_graph(goody.safe_open('Enter the file name describing this graph','r','Illegal file name'))
    print(f'\nGraph: a node -> [showing all its destination nodes]\n{graph_as_str(graph)}')
    while True: 
        start = prompt.for_string('\nEnter the starting node (or enter quit)', is_legal=(lambda x : x in graph.keys() or x == 'quit'), error_message='Illegal: not a source node')
        if start == 'quit':
            break
        trace = input('Enter whether to trace this algorithm[True]: ')
        destinations = reachable(graph, start, True if trace == 'True' else False)
        print(f'From node {start} its reachable nodes:  {destinations}')
    # For running batch self-tests
    print()
    import driver
    driver.default_file_name = "bsc1.txt"
#     driver.default_show_traceback = True
#     driver.default_show_exception = True
#     driver.default_show_exception_message = True
    driver.driver()
Exemplo n.º 35
0
    m = re.match(pat, number)
    assert m, number + " is not a legal phone number"
    return place_call(m.group(2), m.group(3), m.group(5))


def parse_phone_named(number):
    """
    Uses named groups: explicitly names the three groups needed
    Notice how the arguments to place_call are specified
      m.groupdict() puts the groups in a dict with their names and values
      ** says use the keys and values as parameter names and their arguments
      e.g., for f(**{'b':2, 'a':1, 'c':3} ) is translated into f(b=2,a=1,c=3)
    """
    pat = r"(\((?P<area_code>\d{3})\))?(?P<exchange>(\d\d)?\d)-(?P<number>\d{4})$"
    m = re.match(pat, number)
    assert m, number + " is not a legal phone number"
    return place_call(**m.groupdict())


parse_test = eval(
    prompt.for_string_via_index('Enter parse method', 'parse_phone_named',
                                ['parse_phone_numbered', 'parse_phone_named']))
while True:
    try:
        phone = prompt.for_string("\nEnter phone number",
                                  default="(949)824-2704")
        print("  Dialing =", parse_test(phone))
    except:
        import traceback
        traceback.print_exc()
Exemplo n.º 36
0
if __name__ == '__main__':
    import prompt
    print('Begin testing Dice')
    command_prompt = \
"""\nTesting Dice:
Commands     Queries                  Other
  r - roll     n - number_of_dice       . - exec(...)
               m - all_pip_maximums     D - standard_rolls_for_debugging
               s - rolls                q - quit
               o - pips_on
               a - all_pips
               ? - pip_sum
               =  - pips_same
               _  - __str__
Command"""
    d = Dice(eval(prompt.for_string('Enter list of max pips',
                                    default='[6,6]')))
    while True:
        action = prompt.for_char(command_prompt, legal='rnmsoa?=_.Dq')
        try:
            if action == 'r': d.roll()
            elif action == 'n': print('  Number of dice =', d.number_of_dice())
            elif action == 'm':
                print('  all pip maximums =', d.all_pip_maximums())
            elif action == 's':
                print('  rolls =', d.rolls())
            elif action == 'o':
                i = prompt.for_int_between('  Enter die #', 0,
                                           d.number_of_dice() - 1)
                print('  pips on die #', str(i), ' =', d.pips_on(i))
            elif action == 'a':
                print('  all pips =', d.all_pips())
Exemplo n.º 37
0
    originalFileLen = len(fileGraph)

    graph_as_str(fileGraph)

    influencers = find_influencers(
        eval(dupe),
        prompt.for_bool("Trace the Algorithm",
                        default=True,
                        error_message="That don't work either homie"))
    print("influencers: ", influencers)

    while True:
        redflag = False
        userPrompt = str(
            prompt.for_string("Enter influencers set (or else quit)",
                              default=influencers,
                              error_message="Homie stop"))
        if userPrompt == "quit":
            break
        try:
            if type(eval(userPrompt)) == type(set()):
                for user_key in eval(userPrompt):
                    if user_key not in fileGraph.keys():
                        print("  Entry Error: ", userPrompt, ";", sep="")
                        print("  Please enter a legal String\n")
                        redflag = True
                        break
            else:
                print(
                    "That is not a valid entry. Please enter a valid entry\n")
                continue
    print('Begin testing PriorityQueue') 
    command_prompt = \
"""\nTesting PriorityQueue:
Commands        Queries             Other
  a - add...      ? - in_same         . - exec(...)
  m - merge...    e - is_singleton    i - iterator
  c - clear       s - size            q - quit
                  * - all_classes__
                  _ - __str__
               
Command""" 
    e = eval('EquivalenceClass('+input('e = EquivalenceClass('))
    while True:
        action = prompt.for_char(command_prompt, legal='amc?es*_.iq')
        try:
            if   action == 'a': e.add_singleton(prompt.for_string('  Enter value to add as singleton'))
            elif action == 'm':
                a = prompt.for_string('  Enter first  value for merge')
                b = prompt.for_string('  Enter second value for merge')
                e.merge_classes_containing(a,b)
            elif action == 'c': e.clear()
            
            elif action == '?': print('  in_same_classe =',e.in_same_class())
            elif action == 'e': print('  is_singleton =',e.is_singleton())
            elif action == 's': print('  size =',e.size())
            elif action == '_': print('  str =',e)
            elif action == '*': print('  all_classes =',e.all_classes())
            
            elif action == '.': exec(prompt.for_string('  Enter command to exec (instance=e)'))
            elif action == 'i': print('  iteration order =',[i for i in e])
            elif action == 'q': break
Exemplo n.º 39
0
    import prompt
    print('Begin testing Stack') 
    command_prompt = \
"""\nTesting Stack:
Commands     Queries         Other
  a - add      p - peek        . - exec(...)
  r - remove   e - is_empty    i - iterator
  c - clear    s - size        q - quit
               _ - __str__
               
Command""" 
    s = eval('Stack('+input('s = Stack('))
    while True:
        action = prompt.for_char(command_prompt, legal='arcpes_.iq')
        try:
            if   action == 'a': s.add(prompt.for_string('  Enter value to add'))
            elif action == 'r': print('  remove =',s.remove())
            elif action == 'c': s.clear()
            
            elif action == 'p': print('  peek =',s.peek())
            elif action == 'e': print('  is_empty =',s.is_empty())
            elif action == 's': print('  size =',s.size())
            elif action == '_': print('  str =',s)
            
            elif action == '.': exec(prompt.for_string('  Enter command to exec (instance=s)'))
            elif action == 'i': print('  iteration order =',[i for i in s])
            elif action == 'q': break
            else: print('  Unknown command')
        except AssertionError as report:
            print('  AssertionError exception caught:', report)
        except Exception as report:
Exemplo n.º 40
0
            wrong.append(check_num)
            print(check_num,'Error:',to_compute,'raised exception')
            #KLUDGE suppress exception for grading
            #traceback.print_exc()
    print('\nDone batch_self_check:',correct_count,'correct;',wrong_count,'incorrect\n')
    print('Failed checks:',wrong)

    print('Column analysis')
    column = []
    for l,h in [[1,4],[2,13],[14,34],[71,82],[35,55],[56,70],[83,90],[91,99],[100,112],[113,117],[118,128],[129,147]]:
        count = 0
        for w in wrong:
            if l<=w<=h:
                count += 1
        column.append(count)
        
    print('\t'.join([str(c) if c > 0 else '' for c in column])+'END')
    print('Done with column analysis')
    
    
    
# Driver: prompts and executes commands (including calling the methods above)
old = "batch_self_check('cabsc.txt')"
while True:
    try:
        old = prompt.for_string('Command',default=old)
        exec(old)
    except Exception:
        traceback.print_exc()
     
Exemplo n.º 41
0
    graph = defaultdict(set)
    for line in file:
        s,d = line.strip().split(';')
        graph[s].add(d)
    return graph


def print_graph(graph):
    print('\nGraph: source -> {destination} edges')
    for s,d in sorted(graph.items()):
        print('  ',s,'->',d)

        
def reachable(graph,start):
    reached, exploring = set(), [start]
    while exploring:
        s = exploring.pop(0)
        reached.add(s)
        for d in graph[s]:
            if d not in reached:
                exploring.append(d)
    return reached


graph = read_graph(goody.safe_open('Enter file with graph', 'r', 'Could not find that file'))
print_graph(graph)
while True:
    start = prompt.for_string('\nEnter starting node', None, (lambda x : x in graph or x == 'quit'), 'Not a source node')
    if start == 'quit':
        break
    print('From',start,'the reachable nodes are',reachable(graph,start))
Exemplo n.º 42
0
        
if __name__ == "__main__": 
    import prompt
    print("Begin testing Stopwatch") 
    commandPrompt = \
"""\nTesting Stopwatch:
Commands                Queries        Other
  > - start               ? - read       . - exec(...)
  s - stop                : - status     q - quit
  < - start_backwards     _ - __str__
  r - reset\nCommand"""                            
    s = Stopwatch()
    while True:
        action = prompt.for_char(commandPrompt, legal=">s<r?:_.q")
        try:
            if   action == ">": s.start()
            elif action == "s": s.stop()
            elif action == "<": s.start_backwards()
            elif action == "r": s.reset()
            elif action == "?": print("  Elapsed =", s.read(), "seconds")
            elif action == ":": print("  Status =", s.status())
            elif action == "_": print("  __str__ =", str(s))
            elif action == ".": exec(prompt.for_string("  Enter command to exec (instance=s)"))
            elif action == "q": break
            else: print("  Unknown command")
        except AssertionError as report:
            print("  AssertionError exception caught:", report)
        except Exception as report:
            import traceback
            traceback.print_exc()
    print("\nFinished testing Stopwatch")
Exemplo n.º 43
0
        default=2,
        is_legal=(lambda x: x >= 0),
        error_message='Not a Valid Order Statistic!'), []
    corpus = read_corpus(
        os,
        safe_open('Choose the file name to process ',
                  'r',
                  'Not a Valid Filename! Try Again!',
                  default='wginput1.txt'))
    print('Corpus',
          corpus_as_str(corpus),
          f'Choose {os} words to start with',
          sep='\n')
    for i in irange(1, os):
        start.append(
            prompt.for_string(
                f'Choose word {i}',
                error_message=
                'Invalid Word: Please Enter a Valid word in the Text'))
    print(
        f"Random text = {produce_text(corpus, start, prompt.for_int('Choose # of words for generation ', default=10, is_legal= (lambda x: x >= 0), error_message= 'Not a Valid Number of Words!'))}"
    )
    # For running batch self-tests
    print()
    import driver
    driver.default_file_name = "bsc5.txt"
    driver.default_show_traceback = True
    driver.default_show_exception = True
    driver.default_show_exception_message = True
    driver.driver()
Exemplo n.º 44
0
import prompt
from bag import Bag

# Driver: prompts and executes commands (can all compute_e)
while True:
    try:
        exec(prompt.for_string('Command'))
    except Exception as report:
        import traceback
        traceback.print_exc()
Exemplo n.º 45
0
"""
Operations                re methods          General
  et - enter txt            m  - match          rm/bm   - repeat/batch match
  ep - enter pat            s  - search         rs/bs   - repeat/batch search
  er - enter rpl            fa - findall        rfa/bfs - repeat/batch findall
  ?  - show t/p/r           su - substitute     rsu/bsu - repeat/batch substitute
                            sp - split          rsp/bsp - repeat/batch split
                                                .       - exec(...)
                                                q       - quit
\nCommand""" 
    pat = ""
    txt = ""
    rpl = ""
    while True:
        try:
            action = prompt.for_string(commandPrompt, is_legal=(lambda x : x in ['et','ep','er','?','m','s','fa','su','sp','rm','bm','rs','bs','rfa','bfa','rsu','bsu','rsp','bsp','.','q']))
            if   action == 'et' : txt = prompt.for_string("Enter txt")
            elif action == 'ep' : pat = prompt.for_string("Enter pat")
            elif action == 'er' : rpl = prompt.for_string("Enter rpl",default="")
            elif action == '?'    : 
                print("    txt = ", txt)
                print("    pat = ", pat)
                print("    rpl = ", rpl)
            elif action == 'm'    : test_match(pat,txt)
            elif action == 's'    : test_search(pat,txt)
            elif action == 'fa' : test_findall(pat,txt)
            elif action == 'su' : test_substitute(pat,rpl,txt)
            elif action == 'sp' : test_split(pat,txt)
            elif action == 'rm' : repeat(test_match,pat=pat)
            elif action == 'rs' : repeat(test_search,pat=pat)
            elif action == 'rfa': repeat(test_findall,pat=pat)
Exemplo n.º 46
0
def dict_as_str(d: {None: None}, key: callable = None, reverse: bool = False) -> str:
    return ''.join(['  {} -> {}\n'.format(k, d[k]) for k in sorted(d.keys(), key=key, reverse=reverse)])


def top_n(a_prefix: (str,), n: int, prefix: {(str,): {(str,)}}, query: {(str,): int}) -> [(str,)]:
    return [k for k in sorted(prefix.get(a_prefix, []), key=lambda x: (-query[x], x)) if k in query][0:n]


# Script

if __name__ == '__main__':
    # Write script here
    p, q = None, None
    while True:
        name = prompt.for_string('Enter the name of a file with the full queries', is_legal=lambda x: len(x) > 0)
        try:
            with open(name, 'r') as file:
                p, q = read_queries(file)
            break
        except Exception as e:
            print(str(e))

    print()
    print('Prefix dictionary:')
    print(dict_as_str(p, key=lambda x: (len(x), x)))

    print()
    print('Query dictionary:')
    print(dict_as_str(q, key=lambda x: (-q[x], x)))
Exemplo n.º 47
0
        cie = remaining_candidates(
            vd)  #get the remaining candidates formt eh evaluated ballot
        count += 1
        if len(
                cie
        ) <= 1:  #if there are 1 or less candidates remaining, returnt he winner or none signifyign tie.
            break
    if cie == set():
        print("Tie among final candidates: cannot choose one unique winner")
    else:
        print("Election winner is", str(cie))
    return cie


if __name__ == '__main__':
    # Write script here
    with open(
            prompt.for_string(
                "Enter the file name describing all the voter preferences",
                is_legal=lambda f: open(f),
                error_message="Please enter a valid filename")) as vp_file:
        run_election(vp_file)
    # For running batch self-tests
    print()
    import driver
    driver.default_file_name = "bsc2.txt"
    #     driver.default_show_traceback = True
    #     driver.default_show_exception = True
    #     driver.default_show_exception_message = True
    driver.driver()
Exemplo n.º 48
0
  an - add_node      nc - node_count       . - exec(...)                  rg  - random graph
  ae - add_edge      ec - edge_count       in  - iterator node            cc  - connected components
  rn - remove_node   mt - is_empty         ie  - iterator edges           mst - minimum spanning tree
  re - remove_edge   hn - has_node         iin - iterator in_node         sym - make symmetric
  c  - clear         he - has_edge         ion - iterator out_nodes
                     e  - edge_value       iie - iterator in_edges
                     id - in_degree        ion - iterator out_edges
                     od - out_degree       r   - read
                     d  - degree           w   - write
                     _  - str              q   - quit
                     
               
Command""" 
    g = eval('Graph('+input('g = Graph('))
    while True:
        action = prompt.for_string(command_prompt, is_legal= \
                 lambda x : x in 'an ae rn re c nc ec mt hn he e id od d _ . in ie iin ion iie ion r w q rg cc mst sym'.split(' '))
        try:
            if   action == 'an': g.add_node(prompt.for_string('  Enter node to add'))
            elif action == 'ae': g.add_edge(prompt_edge('  Enter edge to add'),prompt.for_int('  Value (int) for edge',is_legal=predicate.is_non_negative))
            elif action == 'rn': g.remove_node(prompt.for_string('  Enter node to remove'))
            elif action == 're': g.remove_edge(prompt_edge('  Enter edge to remove'))
            elif action == 'c' : g.clear()
            
            elif action == 'nc': print('  node_count =',g.node_count())
            elif action == 'ec': print('  edge_count =',g.edge_count())
            elif action == 'mt' : print('  is_empty =',g.is_empty())
            elif action == 'hn':
                n = prompt.for_string('  Enter node to check')
                print('  has_node =',g.has_node(n))
            elif action == 'he':
                e = prompt_edge('  Enter edge to check')
        except IndexError:
            generated.append(None)
            break
        
    return generated
    


order_statistic = prompt.for_int('Enter order statistic', is_legal = lambda x: x>0)

file = open('thisisawesome.txt', 'r', encoding = 'utf-8')

corpus = read_corpus(order_statistic, file)

# print_corpus(corpus)

print('Enter {} words to start with'.format(order_statistic))

starting_words = []
for i in range(order_statistic):
    starting_words.append(prompt.for_string('Enter word {}'.format(i+1)))
    
words_to_generate = prompt.for_int('Enter # of words to generate', is_legal = (lambda x: x > 0))
    
generated_text = produce_text(corpus, starting_words, words_to_generate)

for i in range(int(len(generated_text)/10)):
    print(' '.join(generated_text[10*i:10*(i+1)]))

file.seek(0)
Exemplo n.º 50
0
 def prompt_edge(description):
     print(description)
     i = prompt.for_string('  Origin      node')
     o = prompt.for_string('  Destination node')
     return (i,o)
Exemplo n.º 51
0
def days_in(month:int,year:int)->int:
    return (29 if month==2 and is_leap_year(year) else day_dict[month])


def tomorrow(date:str)->str:
    valid = re.match("^([1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/([0-9]{4}|[0-9]{2})$",date)
    if valid and (int(valid.group(2)) <= day_dict[int(valid.group(1))] or (int(valid.group(2))==29 and int(valid.group(1))==2 and int(valid.group(3))%4 == 0)):
        month,day,year = (int(d) for d in valid.groups())
        year = (year+2000 if year < 100 else year)
        day = (1 if (day >= day_dict[month] and not(year%4 == 0 and month ==2 and day == 28))else day + 1)
        day = (1 if (month == 2 and day == 30 )else day)
        month = ( (month)%12+1 if (day == 1) else month)
        year = (year+1 if (day == 1 and month == 1 )else year)
        return "{}/{}/{}".format(month,day,year)
    else:
        raise AssertionError
if __name__ == '__main__':
    import driver, prompt,traceback
    while True:
        date = prompt.for_string('Enter date to test (quit to start driver)')
        if date == 'quit':
            break;
        try:
            print('tomorrow=',tomorrow(date))
        except:
            print('tomorrow raised exception')
            traceback.print_exc()
        
    driver.driver()
Exemplo n.º 52
0
if __name__ == "__main__": 
    import prompt
    print("Begin testing Stopwatch") 
    commandPrompt = \
"""\nTesting Stopwatch:
Commands                Queries        Other
  > - start               ? - read       . - exec(...)
  s - stop                : - status     q - quit
  < - start_backwards     _ - __str__
  r - reset\nCommand"""                            
    s = Stopwatch()
    while True:
        action = prompt.for_char(commandPrompt, legal=">s<r?:_.q")
        try:
            if   action == ">": s.start()
            elif action == "s": s.stop()
            elif action == "<": s.start_backwards()
            elif action == "r": s.reset()
            elif action == "?": print("  Elapsed =", s.read(), "seconds")
            elif action == ":": print("  Status =", s.status())
            elif action == "_": print("  __str__ =", str(s))
            elif action == ".": exec(prompt.for_string("  Enter command to exec (instance=s)"))
            elif action == "q": break
            else: print("  Unknown command")
        except AssertionError as report:
            print("  AssertionError exception caught:", report)
        except Exception as report:
            import traceback
            traceback.print_exc()
    print("\nFinished testing Stopwatch")
Exemplo n.º 53
0
                if destination not in reached:
                    exploring.append(destination)
    return reached


if __name__ == "__main__":
    # Write script here
    file = goody.safe_open("Enter file with graph: ", "r", "Could not open that file. Try again.")
    print()
    print("Graph: source -> {destination} edges")
    graph = read_graph(file)
    print(graph_as_str(graph))
    while True:
        starting = prompt.for_string(
            "\nEnter a starting node",
            is_legal=(lambda x: x == "quit" or x in graph),
            error_message=" Illegal: not a source node",
        )
        if starting == "quit":
            break
        nodes = reachable(graph, starting)
        print("From " + starting + " the reachable nodes are " + str(nodes))
    print()
    # For running batch self-tests
    # what is this?
    print()
    import driver

    driver.default_file_name = "bsc1.txt"
    #     driver.default_show_traceback = True
    #     driver.default_show_exception = True
Exemplo n.º 54
0
if __name__ == '__main__': 
    import prompt
    print('Begin testing Modular') 
    command_prompt = \
"""\nTesting Modular:
Commands     Queries          Other
  i - inc      v - value        . - exec(...)
  d - dec      m - modulus      q - quit
  c - clear    _  - __str__
  
Command"""                            
    m = Modular(prompt.for_int('Enter value'),prompt.for_int('Enter modulus'))
    while True:
        action = prompt.for_char(command_prompt, legal='idc_.q')
        try:
            if   action == 'i': m.inc()
            elif action == 'd': m.dec()
            elif action == 'c': m.clear()
            elif action == 'v': print('  value =', m.value())
            elif action == 'm': print('  modulus =', m.modulus())
            elif action == 'c': m.clear()
            elif action == '_': print('  str =',m)
            elif action == '.': exec(prompt.for_string('  Enter command to exec (instance=m)'))
            elif action == 'q': break
            else: print('  Unknown command')
        except AssertionError as report:
            print('  AssertionError exception caught:', report)
        except Exception as report:
            import traceback
            traceback.print_exc()
    print('\nFinished testing Modular')
Exemplo n.º 55
0
 def prompt_edge(description):
     print(description)
     i = prompt.for_string('  Origin      node')
     o = prompt.for_string('  Destination node')
     return (i, o)
Exemplo n.º 56
0
    reached, exploring = set(), [start]
    while exploring:
        s = exploring.pop(0)
        reached.add(s)
        for d in graph.get(s,{}):
            if d not in reached:
                exploring.append(d)
    return reached





if __name__ == '__main__':
    graph_file = goody.safe_open('Enter file with graph', 'r', 'Could not find that file')
    graph = read_graph(graph_file)
    print('Graph: source -> {destination} edges\n' + graph_as_str(graph))
    while True:
        start = prompt.for_string('\nEnter starting node name', None, (lambda x : x in graph or x == 'quit'), 'Illegal: not a source node')
        if start == 'quit':
            break
        print('From',start,'the reachable node names are',reachable(graph,start))

    print()
    import driver
    driver.default_file_name = "bsc1.txt"
#     driver.default_show_traceback = True
#     driver.default_show_exception = True
#     driver.default_show_exception_message = True
    driver.driver()
    print("Begin testing PriorityQueue")
    command_prompt = """\nTesting PriorityQueue:
Commands     Queries         Other
  a - add      p - peek        . - exec(...)
  r - remove   e - is_empty    i - iterator
  c - clear    s - size        q - quit
  m - merge    _ - __str__
               
Command"""
    pq = eval("PriorityQueue(" + input("pq = PriorityeQueue("))
    while True:
        action = prompt.for_char(command_prompt, legal="arcmpes_.iq")
        try:
            if action == "a":
                pq.add(prompt.for_string("  Enter value to add"))
            elif action == "r":
                print("  remove =", pq.remove())
            elif action == "c":
                pq.clear()
            elif action == "m":
                exec("pq.merge(" + input("pq.merge("))

            elif action == "p":
                print("  peek =", pq.peek())
            elif action == "e":
                print("  is_empty =", pq.is_empty())
            elif action == "s":
                print("  size =", pq.size())
            elif action == "_":
                print("  str =", pq)
Exemplo n.º 58
0
def play(game):
	'''Given a Game object, allows the player to perform various actions, 
	such as saving its current state, adding pieces, or removing pieces.'''
	turn_counter = 0
	show_board = True

	while not game.check_victory():
		try:
			if show_board:
				print('TURN: {}'.format(turn_counter))
				game.print_board()

			decision = main_turn_menu()
			if decision == '':
				turn_counter = targeted_action(game, turn_counter)

			elif decision == 'u':
				game.undo_move()
				turn_counter -= 1

			elif decision == 'r':
				game.redo_move()
				turn_counter += 1

			elif decision == 'o': 
				show_board = False
				continue # jump back to main menu

			elif decision == 'q':
				print('Goodbye!')
				print()
				return

			elif decision == 'l':
				load_successful = False
				while not load_successful:
					try:
						save_state_name = prompt.for_string('Name of the save state ("q" to exit)')
						if save_state_name == 'q':
							load_successful = True
						else:
							game.load_state(save_state_name)
							load_successful = True
							turn_counter = 0 # reset turn counter now that a new game is loaded
					except FileNotFoundError as e:
						print(e)

			elif decision == 's':
				confirmation = 'n'
				while confirmation != 'y':
					save_state_name = prompt.for_string('Name of the save state ("q" to exit)')
					print('Save state is "{}"'.format(save_state_name))
					confirmation = prompt.for_string('Are you sure? (y/n)', default='y')
				game.save_state(save_state_name)


			show_board = True
			print()
			print()
			
		except gameexceptions.get_game_exceptions() as inst:
			print('INVALID MOVE') # this will be more detailed later when I further study exceptions
			print(inst)
		except Exception as inst: # any other exceptions that aren't game exceptions
			print(inst)

	print('Turns taken: {}'.format(turn_counter))
	game.print_board()
	print('YOU WIN!!!')
	print()
	return