Ejemplo n.º 1
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!")
Ejemplo n.º 2
0
def convert_to_dict(promptMessage: str) -> dict:
    """Prompts the user for a file name in the current directory.

    The file's information should be separated by whitespace with the
    information being first name, last name (suffix removed), team,
    all rank, sean rank, chris rank, and matthew rank.

    Returns: Dict | {Name: Sean rank}
    """

    errorMessage = 'Document does not exist'
    open_file = goody.safe_open(promptMessage, 'r', errorMessage)

    playerRankings = {}

    for line in open_file:

        #unpack only important imformation
        split_info = line.split()

        #if they have suffix
        if len(split_info) == 8:
            firstName, lastName, suffix, _, _, SR, _, _ = split_info
            playerRankings[firstName + ' ' + lastName + ' ' + suffix] = int(SR)
        else:
            firstName, lastName, _, _, SR, _, _ = line.split()
            playerRankings[firstName + ' ' + lastName] = int(SR)

    open_file.close()
    return playerRankings
Ejemplo n.º 3
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)))
Ejemplo n.º 4
0
def get_expert_ranks(promptMessage: str) -> dict:
    """Prompts the user for a file name in the current directory.

    The file's information should be separated by whitespace with the
    information being expert rank, first name, last name, and
    an optional suffix.

    Returns: Dict | {Name: expert rank}
    """

    errorMessage = 'Document does not exist'
    open_file = goody.safe_open(promptMessage, 'r', errorMessage)

    expertRankings = {}

    for line in open_file:

        #unpack only important imformation
        split_info = line.split()

        #if they have suffix
        if len(split_info) == 4:
            rank, firstName, lastName, suffix = split_info
            expertRankings[firstName + ' ' + lastName + ' ' +
                           suffix] = int(rank)
        else:
            rank, firstName, lastName = line.split()
            expertRankings[firstName + ' ' + lastName] = int(rank)

    open_file.close()
    return expertRankings
Ejemplo n.º 5
0
def process(D: dict):
    batch = safe_open("Enter file with start-state and input", 'r', "File not found.", default = 'ndfainputendin01.txt').read().split()
    operations = []
    myDict = D
    for b in batch:
        B = b.split(';')
        operations.append(B)
    for o in operations:
        print('\nStarting new simulation')
        print('Start state = ' + o[0])
        last_state = [o[0]]
        for r in range(1, len(o)):
            if len(last_state) == 1:
                print("\tInput = {}; new possible state(s) = {}".format(o[r], str(myDict[last_state[0]][o[r]])))
                last_state = list(myDict[last_state[0]][o[r]])     
            elif len(last_state) > 1:
                possible_states = []
                for ls in last_state:
                    if len(myDict[ls]) != 0:
                        if o[r] in myDict[ls].keys():
                            possible_states.extend(list(myDict[ls][o[r]]))
                last_state = possible_states.copy()
                s = set(last_state)
                print("\tInput = {}; new possible state(s) = {}".format(o[r], str(s)))
        print('Stop state(s) = ' + str(set(last_state)))
Ejemplo n.º 6
0
def batch(func, **kargs):
    in_file = safe_open("Enter batch file for txt", "r",
                        "Cannot find that file")
    for test in in_file:
        kargs["txt"] = text = test.strip()
        print("Trying txt =", text)
        func(**kargs)
Ejemplo n.º 7
0
def read_voter_preferences():
    ''' has an open (file) parameter; 
    it returns the dict representing each voter and his/her preferences: 
    dict[str] -> list[str] 
    '''
    filelist = (goody.safe_open('Enter file with voter preferences', 'r', 'No file avail. Try again.',default=None)).readlines()
    raw_dict = {}
    for line in filelist:
        splited_linelst = line.strip().split(';')
        raw_dict[splited_linelst[0]] = splited_linelst[1:]
    return raw_dict
Ejemplo n.º 8
0
def read_voter_preferences():
    ''' has an open (file) parameter; 
    it returns the dict representing each voter and his/her preferences: 
    dict[str] -> list[str] 
    '''
    filelist = (goody.safe_open('Enter file with voter preferences', 'r', 'No file avail. Try again.',default=None)).readlines()
    raw_dict = {}
    for line in filelist:
        splited_linelst = line.strip().split(';')
        raw_dict[splited_linelst[0]] = splited_linelst[1:]
    return raw_dict
Ejemplo n.º 9
0
def read_graph():
    '''read_graph has an open (file) parameter; it returns the dict representing the graph'''
    
    filelist = (goody.safe_open('Enter file with graph','r','error_message',default=None)).readlines()
    raw_dic = {}
    for item in filelist:
        if item[0] in list(raw_dic.keys()):
            raw_dic[item[0] ].add(item[2])
        else:
            raw_dic[item[0] ] = ({item[2]})
    return (raw_dic)
Ejemplo n.º 10
0
def final_script():
    ''' at the bottom of this module that calls these functions to solve the problem. 
    Note that the script loops over the lines in the second file (mine is 7 lines).   
    '''
    fa = read_fa ()
    print_fa(fa)
    filelist = (goody.safe_open('Enter file with start-state and input', 'r', 'No file avail. Try again.',default=None)).readlines()
    for line in filelist:
        line_lst = line.strip().split(';')
        result = process(fa, line_lst[0], line_lst[1:])
        interpret(result)
Ejemplo 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)))
Ejemplo n.º 12
0
def read_fa ():
    ''' has an open (file) parameter; 
    it returns the dict representing the finite automaton; 
    hint: I used splicing and the zip function to build the inner dicts. (mine is 6 lines).
    '''
    filelist = (goody.safe_open('Enter file with finite automaton', 'r', 'No file avail. Try again.',default=None)).readlines()

    raw_dict = dict()
    for line in filelist:
        raw_lst = line.strip().split(';')

        raw_dict[raw_lst[0]] = [i for i in zip(raw_lst[1::2], raw_lst[2::2])]
    return raw_dict
Ejemplo n.º 13
0
def final_script():
    '''Write a script at the bottom of this module that 
    calls these functions to solve the problem. 
    Note that the script loops over the lines in the second file (mine is 7 lines). 
    '''
    dictionary = read_ndfa()
    print_ndfa(dictionary)

    filelist = (goody.safe_open('Enter file with start-state and input', 'r', 'No file avail. Try again.',default=None)).readlines()
    for line in filelist:
        line_lst = line.strip().split(';')
        result = process(dictionary, line_lst[0], line_lst[1:])
        interpret(result)
Ejemplo n.º 14
0
def read_graph():
    '''read_graph has an open (file) parameter; it returns the dict representing the graph'''

    filelist = (goody.safe_open('Enter file with graph',
                                'r',
                                'error_message',
                                default=None)).readlines()
    raw_dic = {}
    for item in filelist:
        if item[0] in list(raw_dic.keys()):
            raw_dic[item[0]].add(item[2])
        else:
            raw_dic[item[0]] = ({item[2]})
    return (raw_dic)
Ejemplo n.º 15
0
def read_fa():
    ''' has an open (file) parameter; 
    it returns the dict representing the finite automaton; 
    hint: I used splicing and the zip function to build the inner dicts. (mine is 6 lines).
    '''
    filelist = (goody.safe_open('Enter file with finite automaton',
                                'r',
                                'No file avail. Try again.',
                                default=None)).readlines()

    inner_dict = dict()
    for line in filelist:
        raw_lst = line.strip().split(';')

        inner_dict.setdefault(raw_lst[0],
                              dict(zip(raw_lst[1::2], raw_lst[2::2])))

    return (inner_dict)
Ejemplo n.º 16
0
def read_ndfa():
    ''' has an open (file) parameter; 
    it returns the dict representing the non-deterministic finite automaton; 
    hint: I used splicing and the zip function to build the inner dicts, and 
    I called the setdefault function for the inner dict (alternatively I could have built them as defaultdicts: 
    see the standard collections module) (mine is 9 lines).
    '''
    filelist = (goody.safe_open('Enter file with finite automaton', 'r', 'No file avail. Try again.',default=None)).readlines()

    raw_dict = dict()
    for line in filelist:
        raw_lst = line.strip().split(';')
        inner_dict = dict()
        for i in range (1, int(len(raw_lst)), 2):
            inner_dict.setdefault(raw_lst[i], set()).add(raw_lst[i+1])

        raw_dict[raw_lst[0]] = inner_dict
    return raw_dict
Ejemplo n.º 17
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()
Ejemplo n.º 18
0
    
def process(D: dict):
    batch = safe_open("Enter file with start-state and input", 'r', "File not found.", default = 'ndfainputendin01.txt').read().split()
    operations = []
    myDict = D
    for b in batch:
        B = b.split(';')
        operations.append(B)
    for o in operations:
        print('\nStarting new simulation')
        print('Start state = ' + o[0])
        last_state = [o[0]]
        for r in range(1, len(o)):
            if len(last_state) == 1:
                print("\tInput = {}; new possible state(s) = {}".format(o[r], str(myDict[last_state[0]][o[r]])))
                last_state = list(myDict[last_state[0]][o[r]])     
            elif len(last_state) > 1:
                possible_states = []
                for ls in last_state:
                    if len(myDict[ls]) != 0:
                        if o[r] in myDict[ls].keys():
                            possible_states.extend(list(myDict[ls][o[r]]))
                last_state = possible_states.copy()
                s = set(last_state)
                print("\tInput = {}; new possible state(s) = {}".format(o[r], str(s)))
        print('Stop state(s) = ' + str(set(last_state)))
    
if __name__ == '__main__':
    myDict = read_ndfa(safe_open("Enter file with non-deterministic finite automaton", 'r', "File not found.", default = 'ndfaendin01.txt'))
    print_ndfa(myDict)
    process(myDict)
Ejemplo n.º 19
0
def interpret(fa_result: [None]) -> str:
    answer = 'Start state = ' + fa_result[0] + '\n'
    for i in fa_result[1:]:
        answer += '  Input = ' + i[0] + '; '
        if i[1] != None:
            answer += 'new state = ' + i[1] + '\n'
        else:
            answer += 'illegal input: simulation terminated\n'
    answer += 'Stop state = ' + str(fa_result[-1][1]) + '\n'
    return answer


if __name__ == '__main__':
    fa = read_fa(
        goody.safe_open('Enter file with finite automaton', 'r',
                        'Could not find that file'))
    print('\nFinite Automaton Description\n' + fa_as_str(fa))
    data = goody.safe_open('Enter file with start-states and inputs', 'r',
                           'Could not find that file')
    for line in data:
        print('\nStarting new simulation')
        desc = line.strip().split(';')
        print(interpret(process(fa, desc[0], desc[1:])), end='')
    data.close()

    print()
    import driver
    driver.default_file_name = "bsc3.txt"
    #     driver.default_show_traceback = True
    #     driver.default_show_exception = True
    #     driver.default_show_exception_message = True
Ejemplo n.º 20
0
                    print(
                        '{} proposes to {}; matched woman accepts proposal, rejecting match with {}\n'
                        .format(curr_man, curr_woman, ex))
            else:
                unmatched.add(curr_man)
                if trace:
                    print(
                        '{} proposes to {}; matched woman rejects proposal (likes current match better)\n'
                        .format(curr_man, curr_woman))
    return extract_matches(men)


if __name__ == '__main__':
    # Write script here
    men_d = read_match_preferences(
        goody.safe_open('Enter a file representing men', 'r',
                        'file not found or there was an error'))
    women_d = read_match_preferences(
        goody.safe_open('Enter a file representing women', 'r',
                        'file not found or there was an error'))
    print('Men Preferences',
          dict_as_str(men_d),
          'Women Preferences',
          dict_as_str(women_d),
          sep='\n')
    trace_bool = prompt.for_bool('Trace Algorithm', True,
                                 'Please enter True or False')
    print()
    print('matches = ', make_match(men_d, women_d, trace_bool))
    # For running batch self-tests
    print()
    import driver
Ejemplo n.º 21
0
                    if n in myDict.keys():
                        s = myDict[n].copy()
                        for d in done:
                            if d in s:
                                s.remove(d)
                        prechecked = prechecked.union(s)
                    done.add(n)
                    prechecked.remove(n) 
                    break;
                if len(prechecked) == 0:
                    checking = False
            print("From " +char + " the reachable nodes are " + str(done))
        elif x_in.lower() == 'quit':
            cond = False
            print("Quitting...")
            return 0
            
        else:
            print("Error! Not a starting node. Please Re-", end='')




if __name__ == '__main__':
    theDict = read_graph(safe_open("Enter the name of the file representing a graph", 'r', "File not found.", default = 'graph1.txt'))
    print_graph(theDict)
    cond = True
    while cond:
        x_in = input("Enter a starting node: ")
        if reacheability(theDict, x_in) == 0:
            cond = False
    for item in node_list:
        print(item)
        
def reachable(nodes:dict, start: str) -> set:
    """
    This function returns a set with all nodes that are reachable from the starting node.
    """
    reached = set()
    exploring = [start]
    while exploring != []:
        test = exploring.pop()
        reached.add(test)
        for destination in nodes[test]:
            if destination not in reached:
                exploring.append(destination)
                #print("reachable = " + str(exploring))
    return reached
    
    
if __name__ == '__main__':
    node_dict = read_graph(goody.safe_open(prompt_text="Enter file with graph", mode='r', error_message="File does not exists.", default='' ))
    print_graph(node_dict)
    while True:
        source = input('\nEnter starting node: ').strip()
        if source.lower() != 'quit':
            if source in node_dict:
                print('From ' + source + " the reachable nodes are " + str(reachable(node_dict, source)))
            else:
                print("  Entry Error: '" + source + "';  Not a source node\n  Please enter a legal String")
        else:
            break
Ejemplo n.º 23
0
def evaluate_ballot(vp,cie):
    vd = {c : 0 for c in cie} # defaultdict(int)
    for clist in vp.values():
        for c in clist:
            if c in cie:
                vd[c] += 1
                break
    return vd


def remaining_candidates(vd):
    needed_votes = min(vd.values())
    return {c for c in vd if (vd[c] > needed_votes)}       


vp = read_voter_preferences(goody.safe_open('Enter file with voter preferences', 'r', 'Could not find that file'))
print_dict('Voter Preferences',vp,None,False)
cie = {c for cs in vp.values() for c in cs}     

ballot = 1
while len(cie) > 1:
    vd = evaluate_ballot(vp,cie)
    print_dict ('Vote count on ballot #' +str(ballot) + ' with candidates (alphabetically) = ' + str(cie),vd)
    print_dict ('Vote count on ballot #' +str(ballot) + ' with candidates (numerical) = ' + str(cie),vd,lambda x : vd[x],True)
    cie = remaining_candidates(vd)
    ballot += 1
if len(cie) == 1:
    print('\nWinner is ',cie)
else:
    print('\nNo winner: election is a tie among candidate remaining on the last ballot')
Ejemplo n.º 24
0
        # if not step: return interpret_str + f'Start state = {step}\nIllegal Start state: simulation terminated\n'
        if type(step) is not type(tuple()):
            interpret_str += f'Start state = {step}\n'
            # elif not step[1]: return interpret_str + f'  Input = {step[0]}; illegal input: simulation terminated\nStop state = None\n'
        else:
            stop, interpret_str = step[
                1], interpret_str + f'  Input = {step[0]}; new possible states = {sorted(step[1])}\n'
    return interpret_str + f'Stop state(s) = {sorted(stop)}\n'


if __name__ == '__main__':
    # Write script here
    ndfa_dict = read_ndfa(
        safe_open(
            'Choose the file name representing the non-deterministic finite automaton ',
            'r',
            'Invalid File Name',
            default='ndfaendin01.txt'))
    print('',
          'The Description of the chosen Non-Deterministic Finite Automaton',
          ndfa_as_str(ndfa_dict),
          sep='\n',
          end='\n')
    ndfa_inputs = read_inputs(
        safe_open(
            'Choose the file name representing the start-states and their inputs ',
            'r',
            'Invalid File Name',
            default='ndfainputendin01.txt'))
    for ndfa_start, ndfa_input in ndfa_inputs:
        print(
Ejemplo n.º 25
0
        candidates = remaining_candidates(votes_rank)
        votes_rank = evaluate_ballot(RVP_return, candidates)
        ballot_count += 1
        if len(candidates) == 0:
            break
    
    
    print('Winner is ',{k for k in votes_rank.keys()})
    return {k for k in votes_rank.keys()}

  
  
  
  
    
if __name__ == '__main__':
    # Write script here
    file = goody.safe_open('Enter name of a file with voter preferences',
                           'r','Illegal file name')                 
    a = run_election(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()
Ejemplo n.º 26
0
    '''
    return_string = 'Start state = {0}\n'.format(fa_result[0])
    for i in range(1, len(fa_result)):
        if fa_result[i][1] == None:
            return_string += '  Input = {0}; illegal input: simulation terminated\n'.format(fa_result[i][0])
        else:
            return_string += '  Input = {0}; new state = {1}\n'.format(fa_result[i][0], fa_result[i][1])
    return_string += 'Stop state = {0}\n'. format(fa_result[len(fa_result) - 1][1])
    return(return_string)
    



if __name__ == '__main__':
    # Write script here
    file = goody.safe_open('Enter the name of a file with a finite automation', 'r', 'FA FILE : FILE NOT FOUND')
    r_fa = read_fa(file)
    r_fa_str = fa_as_str(r_fa)
    print('\nFinite Automation\n'+r_fa_str)
    file2 = goody.safe_open('Enter the name of a file with the start-state and input', 'r', 'START STATE AND INPUT : FILE NOT FOUND')
    simulation_list = file2.readlines()
    for line in simulation_list:
        print('\nStarting new simulation')
        line_list = line.split(';')
        test_list = line_list[1:]
        r_process = interpret(process(r_fa, line_list[0], test_list))
        #print(simulation_list)
        print(r_process)
    
    #r_process = process(r_fa, 'even', ['1','0','1'])
    #interpret(r_process)
Ejemplo n.º 27
0
from goody import safe_open
from _collections import defaultdict

def read_fa(data)-> dict:
    DATA = data.read().split()
    myDict = defaultdict(defaultdict)
    for e in DATA:
        D = e.split(';')
        tempDict = defaultdict(str)
        for j in range(1, len(D), 2):
            tempDict[D[j]] = D[j+1]
        myDict[D[0]] = tempDict
    return myDict

if __name__ == '__main__':
    theDict = read_fa(safe_open("Enter file with finite automaton", 'r', "File not found.", default = 'faparity.txt'))
    print("Finite Automaton Description")
    sDict = sorted(theDict.items())
    for state in sDict:
        print("\t" + state[0] + " transitions: " + str(sorted(state[1].items())))
        
    batch = safe_open("Enter file with start-state and input", 'r', "File not found.", default = 'fainputparity.txt').read().split()
    operations = []
    
    for b in batch:
        B = b.split(';')
        operations.append(B)
    for o in operations:
        print('\nStarting new simulation')
        print('Start state = ' + o[0])
        last_state = o[0]
Ejemplo n.º 28
0
    """
    result = []
    result.append(start_state)
    current_state = [start_state]
    for item in str_input:
            new_set = set()
            for state in current_state:
                if item in ndfa_dict[state]:
                    for transition in ndfa_dict[state][item]:
                        new_set.add(transition)
            if item in ndfa_dict[state]:
                result.append((item, new_set))
                current_state = list(new_set)
    return result

def interpret(process_list:list) -> None:
    """
    This function takes the process list and prints it.
    """
    print('\nStarting new simulation')
    print('Start state = ' + str(process_list[0]))
    for item in process_list[1:]:
        print('  Input = ' + str(item[0]) + '; new possible states = ' + str(item[1]))
    print('Stop state(s) = ' + str(process_list[-1][-1]))

if __name__ == "__main__":
    ndfa_dict = read_ndfa(goody.safe_open(prompt_text="Enter file with non-deterministic finite automaton", mode='r', error_message="File does not exists.", default='' ))
    print_ndfa(ndfa_dict)
    for line in goody.read_file_values(goody.safe_open(prompt_text="\nEnter file with start-state and input", mode='r', error_message="File does not exists.", default='' ), sep=None, conversions=None):
        text_line = line.split(';')
        interpret(process(ndfa_dict, text_line[0], text_line[1:]))
Ejemplo n.º 29
0
from collections import defaultdict
from goody       import safe_open

# Prompt the user for a file name (to 'r'ead) and ensure the name of the file
# entered exists: see the sample file xrefin.txt; observe what happens if you
# enter the name of a file that does not exist
file = safe_open('Enter name of file to cross-reference','r','Illegal file name')

# When accessing the value associated with any key, substitute a parameterless call
# to set -set()- as the association, if the key is not present in the defaultdict.
xref = defaultdict(set)

# Iterate over every line_number and line in the file
#    Strip the newline off the right end of the text and covert it to all lower case
#    If the result is not an empty line
#      Iterate over a list of words separated by the space character
#        Add the current line_number to the set of line numbers associated with each word
#          (recall for defaultdict, if xref[word] does not exist, associate it with
#          set() before mutating the set to include line_number
for line_number,text in enumerate(file,1):
    text = text.rstrip().lower()
    if len(text) != 0:
        for word in text.split(' '):
            xref[word].add(line_number)
 
# Compute the maximum length of all words that are keys in xref
# Iterate over every word and its associated set in the in xref, in the standard order
#    Print every word formatted to be left-justified in the appropriate field-width,
#      followed by a string that joins together the string equivalent of the values
#      in the set, in sorted order
#       
Ejemplo n.º 30
0
    return result

def remaining_candidates(d:dict)->set:
    '''
    dict has candidate(str):votes(int)
    creates list of number of votes that each candidates has.
    sort the list to fine least vote 
    create dictionary except the candidate(s) who has least vote
    this will remove all candidates if they have all equal votes(which is least vote)
    '''
    least_vote = sorted(d.values())[0] ## find smallest vote from values in dictionary which is count for vote.
    return {candidate for candidate in d.keys() if d[candidate] != least_vote}
    

if __name__ == "__main__":
    '''
    this main function will ask string to open file and show result of it by looping ballots.
    '''
    
    voter_source = safe_open("Enter file with vote preferences ",'r','Illegal file name')
    voter_pref_dic = read_voter_preferences(voter_source)
    remain_candidate = {candidate for candidates in voter_pref_dic.values() for candidate in candidates} ##generate initial set by storing from all of vote lists.
    print_dict("Voter Preferences",voter_pref_dic, lambda a:a[0])
    for ballot in range(3):
        if(remain_candidate == set() or len([candidate for candidate in remain_candidate]) == 1):
            break
        e_ballot = evaluate_ballot(voter_pref_dic, remain_candidate)
        print_dict("Vote count on ballot #{} with candidates({}) = {}".format(str(ballot+1),"alphabetically",  remain_candidate),e_ballot, lambda a:a[0])
        print_dict("Vote count on ballot #{} with candidates({}) = {}".format(str(ballot+1),"numerical",  remain_candidate),e_ballot,lambda a:a[1],reverse = True) 
        remain_candidate = remaining_candidates(e_ballot)
    print("winner is ", (remain_candidate if remain_candidate != set() else "No one"))
Ejemplo n.º 31
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))
Ejemplo n.º 32
0
def reachable(graph : {str:{str}}, start : str) -> {str}:
    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()
Ejemplo n.º 33
0
def batch(func,**kargs):
    in_file = safe_open("Enter batch file for txt", "r", "Cannot find that file")
    for test in in_file:
        kargs["txt"] = text = test.strip()
        print("Trying txt =",text)
        func(**kargs)
Ejemplo n.º 34
0
    '''
    result = starting_words
    try:
        for index in range(count):
            new_index = randrange(len(corpus[tuple(result[index:index+len(starting_words)])]))
            result.append(corpus[tuple(result[index:index+len(starting_words)])]
                          [new_index])##randomly generated new index will choose next word.
    except:
        pass## end of path
    return result

if __name__ == "__main__":
    '''
    the main function will take file name
    and static value for positive integer
    then print it as valid format
    asking values of tuple based on order static value 
    '''
    file = safe_open('file to read','r','Illegal file name')
    while True:
        number = int(input("order static value(positive):"))
        if(number > 0):
            break
    readed = read_corpus(number,file)
    print_corpus(readed)
    starting_w = []
    for i in range(number):
        starting_w.append(input("enter word {}:".format(i+1)))
    result = produce_text(readed,starting_w, int(input("Enter #of words:")))
    print("random text = {}".format(result))
Ejemplo n.º 35
0

def interpret(result: [None]) -> str:
    ans = 'Start state = {}\n'.format(str(result[0]))
    for input, new_set in result[1:]:
        ans += '  Input = {}; new possible states = {}\n'.format(
            input, sorted(new_set))
    ans += 'Stop state(s) = {}\n'.format(sorted(result[-1][-1]))
    return ans


if __name__ == '__main__':
    # Write script here
    ndfa_dict = read_ndfa(
        goody.safe_open(
            'Specify the file name storing the non-deterministic finite automaton',
            'r', 'unable to read this file'))
    print(
        '\nThe Description of the specified Non-Deterministic Finite Automaton\n'
        + ndfa_as_str(ndfa_dict))
    input_file = goody.safe_open(
        'Specify the file name storing the start-state with its inputs', 'r',
        'unable to read this file')
    print()
    for line in input_file:
        strip = line.rstrip().split(';')
        print('Begin to trace a new NDFA simulation\n' +
              interpret(process(ndfa_dict, strip.pop(0), strip)))
    # For running batch self-tests
    print()
    import driver
Ejemplo n.º 36
0
def interpret(result: [None]) -> str:
    huge_str = f'Start state = {result[0]}\n'
    for i in result[1:-1]:
        huge_str += f'  Input = {i[0]}; new possible states = {sorted(list(i[1]))}\n'
    if result[-1][1] != None:
        huge_str += f'  Input = {result[-1][0]}; new possible states = {sorted(list(result[-1][1]))}\nStop state(s) = {sorted(list(result[-1][1]))}\n'
    else:
        huge_str += f'  Input = {result[-1][0]}; illegal input: simulation terminated\nStop state = None\n'
    return huge_str


if __name__ == '__main__':
    # Write script here
    rule = goody.safe_open(
        "Enter the file name describing this Non-Deterministic Finite Automaton",
        'r', 'Illegal file name')
    print(
        "\nThe Description of the file entered for this Non-Deterministic Finite Automaton"
    )
    rule_dict = read_ndfa(rule)
    print(ndfa_as_str(rule_dict))
    sequence = goody.safe_open(
        "Enter the file name describing a sequence of start-states and all their inputs",
        'r', 'Illegal file name')
    print()
    for line in sequence:
        print("Start tracing this NDFA in its start-state")
        process_list = process(rule_dict,
                               line.rstrip("\n").split(";")[0],
                               line.rstrip("\n").split(";")[1:])
Ejemplo n.º 37
0
    for i in range(1, len(result)):
        if result[i][1] is None:
            output_str += "  Input = {}; illegal input: simulation terminated\n".format(
                result[i][0])
        else:
            output_str += "  Input = {}; new possible states = {}\n".format(
                result[i][0], sorted(list(result[i][1])))
    return output_str + "Stop state(s) = {}\n".format(
        sorted(list(result[-1][1])))


if __name__ == '__main__':
    # Write script here
    file = goody.safe_open(
        'Input the file name detailing the Non-Deterministic Finite Automaton:',
        'r',
        'Illegal file name',
        default='ndfaendin01.txt')
    ndfa = read_ndfa(file)
    print("\nThe details of the Non-Deterministic Finite Automaton")
    print(ndfa_as_str(ndfa))

    input_file = goody.safe_open(
        'Input the file name detailing groups of start-states and their inputs:',
        'r',
        'Illegal file name',
        default='ndfainputendin01.txt')
    for row in input_file:
        r_list = row.strip().split(';')
        ndfa_result = process(ndfa, r_list[0], r_list[1:])
        print("\nNDFA: the trace from its start-state")
Ejemplo n.º 38
0
        text.append(new_word)
        if not new_word: return text
    return text


if __name__ == '__main__':
    # Write script here
    os, start = prompt.for_int(
        'Choose the order statistic ',
        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
def evaluate_ballot(voter_dict:dict, candidates:set) -> dict:
    """
    This function takes the voter preferences and the set of candidates and returns a dictionary with the candidates and their vote counts.
    """
    result = instant_runoff_voting(voter_dict)
    dead_candidates = []
    #print(result)
    for candidate in result:
        if candidate not in candidates:
            dead_candidates.append(candidate)
    for person in dead_candidates:
        result.pop(person)
    return result

if __name__ == '__main__':
    voter_dict = read_voter_preferences(goody.safe_open(prompt_text="Enter file with voter preferences", mode='r', error_message="File does not exists.", default='' ))
    print_dict(title = 'Voter preferences', anyDict = voter_dict)
    candidate_votes = instant_runoff_voting(voter_dict)
    count = 1
    while True:    
        print_dict(title = 'Vote count on ballot #' + str(count) + ' with candidates (alphabetically) = ' + str(set(candidate_votes.keys())), anyDict = candidate_votes, aFunction = lambda tup:tup[0], reverse = False)
        print_dict(title = 'Vote count on ballot #' + str(count) + ' with candidates (numerical) = ' + str(set(candidate_votes.keys())), anyDict = candidate_votes, aFunction = lambda tup:tup[1], reverse = True)
        candidates = remaining_candidates(candidate_votes)
        if len(candidates) == 1:
            print('\nWinner is ' + str(candidates))
            break
        elif len(candidates) == 0:
            print('\nNo Winner')
            break
        candidate_votes = evaluate_ballot(voter_dict, candidates)
        count += 1
Ejemplo n.º 40
0
# Submitter: tsalako(Salako, Toluwanimi)
# Partner  : nayanp(Patel, Nayan)
# We certify that we worked cooperatively on this programming
#   assignment, according to the rules for pair programming
from goody import safe_open
from _collections import defaultdict

def printer(da_list: list):
    printkey = '   {:2} -> {}'
    for x in da_list:
        print(printkey.format(x[0], x[1]))
    

data = safe_open("Enter the file with voter preference", 'r', "File not found.", default = 'votepref1.txt')
DATA = data.read().split()
myDict = defaultdict(list)
for e in DATA:
    E =  e.split(';')
    myDict[E[0]] = E[1:]
   
print('Voter Preferences')
printer(sorted(myDict.items()))
    
ballot1 = defaultdict(int)
for v in myDict.items():
    if v[1][0] not in ballot1.keys():
        ballot1[v[1][0]] = 1
    else:
        ballot1[v[1][0]] = ballot1[v[1][0]] + 1
        
#print("Vote count on ballot #1 with candidates (alphabetically) = {}".format(set(sorted({v[0] for v in ballot1}))))
Ejemplo n.º 41
0
from collections import defaultdict
from goody import safe_open

# Prompt the user for a file name (to 'r'ead) and ensure the name of the file
# entered exists: see the sample file xrefin.txt; observe what happens if you
# enter the name of a file that does not exist
file = safe_open('Enter name of file to cross-reference', 'r',
                 'Illegal file name')

# When accessing the value associated with any key, substitute a parameterless call
# to set -set()- as the association, if the key is not present in the defaultdict.
xref = defaultdict(set)

# Iterate over every line_number and line in the file
#    Strip the newline off the right end of the text and covert it to all lower case
#    If the result is not an empty line
#      Iterate over a list of words separated by the space character
#        Add the current line_number to the set of line numbers associated with each word
#          (recall for defaultdict, if xref[word] does not exist, associate it with
#          set() before mutating the set to include line_number
for line_number, text in enumerate(file, 1):
    text = text.rstrip().lower()
    if len(text) != 0:
        for word in text.split(' '):
            xref[word].add(line_number)

# Close the file (it has no more lines to read)

file.close()

# Compute the maximum length of all words that are keys in xref
Ejemplo n.º 42
0
import re, random, goody


def repl(m):
    inner = list(m.group(2))  # separate characters in (\w+) group as list
    random.shuffle(inner)  # shuffle the list
    return m.group(1) + "".join(inner) + m.group(3)  # list->string


for l in goody.safe_open('File to translate',
                         'r',
                         'Reenter file name',
                         default='sub.txt'):
    print(re.sub(r'(\w)(\w+)(\w)', repl, l.strip()))
Ejemplo n.º 43
0
Archivo: fa.py Proyecto: solomc1/python
        
def process(fa,state,inputs):
    result =[state]
    for i in inputs:
        if i not in fa[state]:
            result.append((i,None))
            return result
        else:
            state = fa[state][i]
            result.append((i,state))
    return result

def interpret(faresult):
    print('Start state =',faresult[0])
    for i in faresult[1:]:
        print('  Input = ',i[0],'; ',sep='',end='')
        if i[1] != None:
            print('new state =',i[1])
        else:
            print('illegal input; terminated')
    print('Stop state =',faresult[-1][1])


fa = read_fa(goody.safe_open('Enter file with finite automaton', 'r', 'Could not find that file',1))
print_fa(fa)
data = goody.safe_open('\nEnter file with start-states and inputs', 'r', 'Could not find that file')
for line in data:
    print('\nStarting new simulation')
    desc = line.strip().split(';')
    interpret(process(fa,desc[0],desc[1:]))
def interpret(result: [None]) -> str:
    string = 'Start state = {}\n'.format(result[0])

    for k in result[1:]:
        string += "  Input = {}; new possible states = {}\n".format(
            k[0], sorted(list(k[1])))

    string += 'Stop state(s) = {}\n'.format(sorted(list(k[1])))

    return string


if __name__ == '__main__':
    # Write script here
    file1 = safe_open(
        'Enter a file storing a non-deterministic finite automaton', 'r',
        'Illegal file name')
    adict = read_ndfa(file1)
    print("The Description of this Non-Deterministic Finite Automaton")
    print(ndfa_as_str(adict))

    file2 = safe_open("Enter a file storing a start-state and its inputs", 'r',
                      'Illegal file name')

    for line in file2:
        print()
        print("Starting up a new NDFA simulation")
        line = line.rstrip()
        line = line.split(';')
        pro = process(adict, line[0], line[1:])
        print(interpret(pro))
Ejemplo n.º 45
0
                    if x not in reached_set:
                        exploring_list.append(x)
            if trace:
                print(
                    "transferring node {} from the exploring list to the reached set"
                    .format(curr_node))
                print(
                    "after adding all nodes reachable directly from {} but not already "
                    "in reached, exploring = {}\n".format(
                        curr_node, exploring_list))


if __name__ == '__main__':
    # Write script here
    file = goody.safe_open('Input the file name detailing the graph: ',
                           'r',
                           'Illegal file name',
                           default='graph1.txt')
    graph = read_graph(file)
    print("\nGraph: str (source node) -> [str] (sorted destination nodes)\n" +
          graph_as_str(graph))

    while True:
        node = input("Input one starting node (or input done): ")

        if node == 'done':
            break
        elif node not in graph:
            print(
                "  Entry Error: '{}'; Illegal: not a source node\n  Please enter a legal String\n"
                .format(node))
        else:
Ejemplo n.º 46
0
                if man_that_wants_to_propose_index > man_that_already_proposed_index:
                    print('soon to be matched  === ', soon_to_be_matched_man)
                    unmatched_men_set.add(soon_to_be_matched_man)
                    men_dict_copy[soon_to_be_matched_man][1].remove(
                        preferred_woman)
                else:
                    men_dict_copy[soon_to_be_matched_man][0] = preferred_woman
                    unmatched_men_set.add(man_that_already_proposed)
                    men_dict_copy[soon_to_be_matched_man][1].remove(
                        preferred_woman)

        break


if __name__ == '__main__':
    open_men_file = goody.safe_open('Enter a file storing preferences of men',
                                    'r', 'Illegal file name')
    open_women_file = goody.safe_open(
        'Enter a file storing preferences of women', 'r', 'Illegal file name')

    men_dict = read_match_preferences(open_men_file)
    women_dict = read_match_preferences(open_women_file)

    print(dict_as_str(men_dict))
    print(dict_as_str(women_dict))
    make_match(men_dict, women_dict)
    #extract_matches(men_dict)
    # Write script here

    # For running batch self-tests
    print()
    import driver
    """
    This function takes a corpus dict, a list of starting words and a count and returns a list with the starting words and randomly generated number of words.
    """
    result = []
    length = len(words)
    result.extend(words)
    for number in range(count):
        if (tuple(result[-length:])) in corpus_dict:
            result.append(choice(corpus_dict[(tuple(result[-length:]))]))
        else:
            result.append(None)
            return result
    return result


if __name__ == "__main__":
    order = int(input("Enter order statistic: "))
    corpus_dict = read_corpus(
        order,
        goody.safe_open(
            prompt_text="Enter file to process", mode="r", error_message="File does not exists.", default=""
        ),
    )
    print_corpus(corpus_dict)
    print("\nEnter " + str(order) + " words to start with")
    words = []
    for number in range(order):
        words.append(input("Enter word " + str(number + 1) + ": "))
    count = int(input("Enter # of words to generate: "))
    print("Random text = " + str(produce_test(corpus_dict, words, count)))
Ejemplo n.º 48
0
        print (' ',' ' .join(p),'->',prefix_dict[p]) 
    print('\nQuery dictionary') 
    for q in sorted(query_dict.items(), key=lambda x : (-x[1],x[0])): 
        print (' ',' '.join(q[0]),'->',q[1]) 
  
def top_n(prefix, prefix_dict, query_dict, n): 
    answer = [ [query_dict[x],x] for x in prefix_dict[prefix]] # 2-list: [frequency,full query] 
    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)) 
        
        
        
        
        
        
Ejemplo n.º 49
0
                n = prompt.for_string('  Enter node to check')
                print('  iteration order =', [i for i in g.in_nodes(n)])
            elif action == 'iie':
                n = prompt.for_string('  Enter node to check')
                print('  iteration order =', [i for i in g.in_edges(n)])
            elif action == 'ion':
                n = prompt.for_string('  Enter node to check')
                print('  iteration order =', [i for i in g.out_nodes(n)])
            elif action == 'ioe':
                n = prompt.for_string('  Enter node to check')
                print('  iteration order =', [i for i in g.out_edges(n)])
            elif action == 'q':
                break
            elif action == 'r':
                g.read(safe_open('  Enter file name to read',
                                 'r',
                                 'Could not find this file',
                                 default=None),
                       conv=int,
                       sep=';')
            elif action == 'w':
                g.write(safe_open('  Enter file name to write',
                                  'w',
                                  'Could not open this file for writing',
                                  default=None),
                        sep=';')
            elif action == 'q':
                break

            elif action == 'rg':
                g = random_graph(
                    prompt.for_int('  Enter number of nodes in graph',
Ejemplo n.º 50
0
    fa_str += str("Start state = " + fa_result[0] + "\n")
    for line in fa_result[1:]:
        if line[1] == None:
            fa_str += str("  Input = " + line[0] +
                          "; illegal input: simulation terminated\n")
        else:
            fa_str += str("  Input = " + line[0] + "; new state = " + line[1] +
                          "\n")
    fa_str += "Stop state = " + str(fa_result[-1][1]) + "\n"
    return fa_str


if __name__ == '__main__':
    fa_dict = read_fa(
        goody.safe_open("Enter the name of a file with a finite automaton",
                        'r',
                        '',
                        default=''))
    print("\nFinite Automaton")
    print(fa_as_str(fa_dict))
    ss_fa = goody.safe_open(
        "Enter the name of a file with the start-state and input",
        'r',
        '',
        default='')
    print(" ")
    for line in ss_fa:
        ss = line.strip().split(";")
        print("Starting new simulation")
        print(interpret(process(fa_dict, ss[0], ss[1:])))

    print()
Ejemplo n.º 51
0
    mins,maxs=-1,-1
    for k in sorted(corpus):
        print(' ',k,'can be followed by any of', corpus[k])
        mins = len(corpus[k]) if mins == -1 or len(corpus[k]) < mins else mins
        maxs = len(corpus[k]) if maxs == -1 or len(corpus[k]) > maxs else maxs
        if len(corpus[k]) == 46:
            print (k,corpus[k])
    print('min/max =',str(mins)+'/'+str(maxs)) 


def produce_text(corpus,text,count):
    os = len(text)
    for i in irange(count):
        key = tuple(start[-os:])
        if key not in corpus:
            text.append(None)
            return text
        start.append(choice(corpus[key]))
    return start    



os = prompt.for_int('Enter order statistic',is_legal=lambda x : x >= 1)
corpus = read_corpus(os, goody.read_file_values(goody.safe_open('Enter file to process', 'r', 'Cannot find that file')))
print_corpus(corpus)

print('\nEnter '+str(os)+' words to start with')
start = [prompt.for_string('Enter word '+str(i)) for i in irange(os)]
how_many = prompt.for_int('Enter # of words to generate',is_legal=lambda x : x > 0)
text = produce_text(corpus,start,how_many)
print('Random text =',text)
                    string = '{} proposes to {}; this matched woman rejects the proposal (likes current match better)'.format(
                        pop_male, pop_female)
                    print(string)
                    print()
                unmatched_male.add(pop_male)

    if trace == True:
        print('algorithm terminated with matches = ',
              extract_matches(men_copy))
        trace = False
    return extract_matches(men_copy)


if __name__ == '__main__':
    # Write script here
    file1 = safe_open('Enter a file storing preferences of men:', 'r',
                      'Illegal file name')
    file2 = safe_open('Enter a file storing women preferences of women:', 'r',
                      'Illegal file name')
    men = read_match_preferences(file1)
    women = read_match_preferences(file2)
    print()
    print('Men Preferences')
    display = dict_as_str(men)
    print(display)

    print('Women Preferences')
    display = dict_as_str(women)
    print(display)

    trace = input('Trace The Algorithm[True]: ')
    var = (False if trace == 'False' else True)
Ejemplo n.º 53
0
         elif action == '.'  : exec(prompt.for_string('  Enter command to exec (instance=g)'))
         elif action == 'in' : print('  iteration order =',[i for i in g.nodes()])
         elif action == 'ie' : print('  iteration order =',[i for i in g.edges()])
         elif action == 'iin':
             n = prompt.for_string('  Enter node to check')
             print('  iteration order =',[i for i in g.in_nodes(n)])
         elif action == 'iie':
             n = prompt.for_string('  Enter node to check')
             print('  iteration order =',[i for i in g.in_edges(n)])
         elif action == 'ion':
             n = prompt.for_string('  Enter node to check')
             print('  iteration order =',[i for i in g.out_nodes(n)])
         elif action == 'ioe':
             n = prompt.for_string('  Enter node to check')
             print('  iteration order =',[i for i in g.out_edges(n)])
         elif action == 'q'  : break
         elif action == 'r'  : g.read(safe_open('  Enter file name to read','r','Could not find this file',default=None),conv=int,sep=';')
         elif action == 'w'  : g.write(safe_open('  Enter file name to write','w','Could not open this file for writing',default=None),sep=';')
         elif action == 'q'  : break
         
         elif action == 'rg'  : g = random_graph(prompt.for_int('  Enter number of nodes in graph',is_legal=predicate.is_non_negative), prompt.for_int_between('  Enter connectivity percentage',0,100))
         elif action == 'cc'  : print(connected_components(g))
         elif action == 'mst' : print(minimum_spanning_tree(g))
         elif action == 'sym' : make_symmetric(g)
         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 Graph')
Ejemplo n.º 54
0
    reached = set()
    exploring = [start]
    while len(exploring) > 0:
        node = exploring.pop()
        reached.add(node)
        current = graph.get(node)
        if current != None:
            for destination in current:
                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()
Ejemplo n.º 55
0
      Input = 0; new possible states = ['near', 'start']\n
      Input = 1; new possible states = ['end', 'start']\n
      Input = 1; new possible states = ['start']\n
      Input = 0; new possible states = ['near', 'start']\n
      Input = 1; new possible states = ['end', 'start']\n
    Stop state(s) = ['end', 'start']\n"
    '''
    return_string = 'Start state = {0}\n'.format(result[0])
    for i in range(1, len(result)):
        return_string += '  Input = {0}; new possible states = {1}\n'.format(result[i][0], sorted(result[i][1]))
    return_string += 'Stop state(s) = {0}\n'. format(sorted(result[len(result) - 1][1]))
    return(return_string)

if __name__ == '__main__':
    # Write script here
    file1 = goody.safe_open('Enter the name of a file with a non-deterministic finite automation', 'r', 'NDFA FILE NOT FOUND')
    r_read_ndfa = read_ndfa(file1)     
    s = ndfa_as_str(r_read_ndfa)
    print('\nNon-Deterministic Finite Automation\n' + s)
    file2 = goody.safe_open('Enter the name of a file with the start-state and input', 'r', 'NDFA FILE NOT FOUND')
    file2_list = file2.read().split('\n')
    print()
    for e in file2_list:
        temp_list = e.split(';')
        r_process = process(r_read_ndfa, temp_list.pop(0), temp_list)     
        s = interpret(r_process)
        print('Starting new simulation\n'+s)
        
    # For running batch self-tests
    print()
    import driver
Ejemplo n.º 56
0
    return result


def interpret(result : [None]) -> str:
    answer = 'Start state = '+result[0]+'\n'
    for i in result[1:]:
        answer += '  Input = '+i[0]+'; new possible states = '+ str(sorted(i[1]))+'\n'
    answer += 'Stop state(s) = '+str(sorted(result[-1][1]))+'\n'
    return answer





if __name__ == '__main__':
    ndfa = read_ndfa(goody.safe_open('Enter file with non-deterministic finite automaton', 'r', 'Could not find that file'))
    print('Non-Deterministic Finite Automaton\n'+ndfa_as_str(ndfa))
    data = goody.safe_open('Enter file with start-state and input', 'r', 'Could not find that file')
    for line in data:
        print('\nStarting new simulation')
        desc = line.strip().split(';')
        print(interpret(process(ndfa,desc[0],desc[1:])),end='')
    data.close()
    
    print()
    import driver
    driver.default_file_name = "bsc4.txt"
#     driver.default_show_traceback = True
#     driver.default_show_exception = True
#     driver.default_show_exception_message = True
    driver.driver()
# Ford Tang, 46564602, Lab 2
# Somebody Special, Lab 2
# We certify that we worked cooperatively on this programming
#   assignment, according to the rules for pair programming

import goody




if __name__ == '__main__':
    for line in goody.read_file_values(file = goody.safe_open(prompt_text="Enter file with graph", mode='r', error_message="File does not exists.", default='' ), sep=None, conversions=None):
        print(line)