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 safe_open(prompt_text,mode,error_message,default=''):
    """
    Prompts the user for a file (openable in mode) with and error message
      to display if opening the file in that mode fails)
    If mode=='w', and the file exists, the user will be prompted whether to overwrite it
    If default is supplied, it will appear in the prompt and be the file
      opened if the user just presses enter
    """
    import prompt
    default = str(default) # ensure default is a string
    while True:
        try:
            file_name = input(prompt_text + ('' if default == '' else '['+default+"]") + ": ")
            if file_name == '':
                file_name = default
            try:
                if mode == 'w' and open(file_name,'r'):
                    if not prompt.for_bool(leading(prompt_text,extra=2) + 'File exists: overwrite',False):
                        continue
            except IOError:
                pass
            file = open(file_name,mode)
            return file
        except IOError:
            print(leading(prompt_text,extra=2) + 'Tried file: \''+file_name+'\': ' + error_message) 
Exemplo n.º 4
0
def safe_open(prompt_text, mode, error_message, default=''):
    """
    Prompts the user for a file (openable in mode) with and error message
      to display if opening the file in that mode fails)
    If mode=='w', and the file exists, the user will be prompted whether to overwrite it
    If default is supplied, it will appear in the prompt and be the file
      opened if the user just presses enter
    """
    import prompt
    default = str(default)  # ensure default is a string
    while True:
        try:
            file_name = input(prompt_text +
                              ('' if default == '' else '[' + default + "]") +
                              ": ")
            if file_name == '':
                file_name = default
            try:
                if mode == 'w' and open(file_name, 'r'):
                    if not prompt.for_bool(
                            leading(prompt_text, extra=2) +
                            'File exists: overwrite', False):
                        continue
            except IOError:
                pass
            file = open(file_name, mode)
            return file
        except IOError:
            print(
                leading(prompt_text, extra=2) + 'Tried file: \'' + file_name +
                '\': ' + error_message)
Exemplo n.º 5
0
def find_influencers(graph: {str: {str}}, trace: bool = False):

    trace = prompt.for_bool('Trace the Algorithm[True]', default=False)
    infl_dict = defaultdict(list)

    for key in graph.keys():
        friend_count = int(len(graph[key]))
        if friend_count != 0:
            friend_ceil = friend_count - ceil(friend_count / 2)
            infl_dict[key] += friend_ceil, friend_count, key
        else:
            friend_ceil = -1
            infl_dict[key] += friend_ceil, friend_count, key

    while True:
        infl_dict_list = []
        for value in infl_dict.values():
            value = tuple(value)
            negative = '-'
            if negative not in str(value[0]):
                infl_dict_list.append(value)

        if infl_dict_list != []:
            remove_tup = sorted(infl_dict_list)[0]
            if trace:
                print('influencer dictionary =')
                print(infl_dict)
                print('removal candidates    = ' + str(infl_dict_list))
                print(str(remove_tup) + ' is the smallest candidate')
                print(
                    "Removing " + remove_tup[2] +
                    " as key from influencer dictionary; decrementing friend's values there\n"
                )

            else:
                pass

            for x in graph[remove_tup[2]]:
                if x in infl_dict.keys():
                    infl_dict[x][0] -= 1
                    infl_dict[x][1] -= 1
                else:
                    pass

            del infl_dict[remove_tup[2]]

        else:
            keys_set = set()
            for key in infl_dict.keys():
                keys_set.add(key)
            if trace:
                print('influencer dictionary =')
                print(infl_dict)
                print('removal candidates    = ' + str(infl_dict_list))
            else:
                print('Influencers = ' + str(keys_set))

            return keys_set
Exemplo n.º 6
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.º 7
0
def make_keep(filters,decorate):
    # prints string s as if it were a code listing: line number followed by code
    def show_listing(s):
        for i,l in enumerate(s.split('\n'),1):
            print('{num: >3} {text}'.format(num=i, text = l.rstrip()))
            
    # The keep function returns a string will all the characters not in filters
    # 1) make_keep replaces {init} by a set with all the characters in filters
    # 2) It appends a return statement (either normal or decorated)
    # 3) It calls exec to create the code for keep and returns the code
    function_template = '''\
def keep(word):
    filter = set({init})
    result = ''
    for c in word:
        if c not in filter:
            result += c
'''  
     
    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']
Exemplo n.º 8
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.º 9
0
def make_keep(filters,decorate):
    def show_listing(s):
        i = 1
        for l in s.split('\n'):
            print('{num: >3} {text}'.format(num=i, text = l.rstrip()))
            i += 1
            

    function_template = '''\
def keep(word):
    filter = set({init})
    result = ''
    for c in word:
        if c not in filter:
            result += c
'''  
     
    function_definition = \
      function_template.format(init = '['+','.join(["'"+i+"'" for i in filters])+']')

    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?'):
        show_listing(function_definition)  # comment out
    return name_space['keep']
Exemplo n.º 10
0
# Program History:
#   5/18/01: R. Pattis - Operational for 15-100
#   1/25/02: R. Pattis - Added Timer object for timing process
#   2/23/13: R. Pattis - Converted to Python using similar libraries
#
################################################################################ 
################################################################################ 



import prompt
from  stopwatch import Stopwatch


original_number = prompt.for_int('Enter a positive number', is_legal=(lambda x : x > 0))
is_debugging    = prompt.for_bool('Display intermediate results',True)
cycle_count     = 1
test_number     = original_number

timer = Stopwatch(running_now = True)

while True:
    if is_debugging:
        print('Cycle', cycle_count, ': test number is now', test_number)
    
    ####################
    if test_number == 1:
        break;
    ####################

    cycle_count += 1
Exemplo n.º 11
0
if __name__ == '__main__':
    import prompt

    # checks whether answer is correct, printing appropriate information
    # Note that dict/defaultdict will compare == if they have the same keys and
    #   associated values, regardless of the fact that they print differently
    def check(answer, correct):
        if (answer == correct):
            print('    Correct')
        else:
            print('    INCORRECT')
            print('      was       =', answer)
            print('      should be =', correct)
        print()

    if prompt.for_bool('Test top_students?', True):
        students = {('Alice', 'C'), ('Bob', 'B-'), ('Carol', 'B-'),
                    ('David', 'D'), ('Evelyn', 'C+')}
        print('  argument =', students)
        answer = top(students)
        print('  answer   =', answer)
        check(answer, {'Bob', 'Carol'})

        students = {('Alice', 'B+'), ('Bob', 'B'), ('Carol', 'C'),
                    ('David', 'B-')}
        print('  argument =', students)
        answer = top(students)
        print('  answer   =', answer)
        check(answer, {'Alice'})

        students = {('Alice', 'C'), ('Bob', 'D'), ('Carol', 'C'),
Exemplo n.º 12
0
    return result


if __name__ == '__main__':
    # Write script here
    men_file = goody.safe_open(
        'Type some file name storing preferences of men', 'r',
        'Error opening file')
    women_file = goody.safe_open(
        'Type some file name storing preferences of women', 'r',
        'Error opening file')

    men = read_match_preferences(men_file)
    women = read_match_preferences(women_file)

    print('Men preferences\n', dict_as_str(men), sep='')
    print('Women preferences\n', dict_as_str(women), sep='')

    trace = prompt.for_bool('Trace this Algorithm', default=True)
    matches = make_match(men, women, trace)
    print('matches =', matches)

    # 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.º 13
0
import prompt,predicate
import random
switch=prompt.for_bool('Switch when asked?')
trace=prompt.for_bool('Trace game?')
games_played =  prompt.for_int('Enter number of games to play',is_legal= predicate.is_positive)

count = 0
win = 0
lose = 0
while True:
    if trace==True:
        print('Game Played')
    count += 1
    if games_played != 0:
        prize=random.randint(1,3)
        contestant =random.randint(1,3)
        if trace==True:
            print(' Prize behind door',prize,'/ Contestant chooses door',contestant) 
        while True:
            exposed=random.randint(1,3)
            if exposed != prize and exposed != contestant:
                print('  trying to expose door',exposed)
                break
            else:
                if trace==True:
                    print('  trying to expose door',exposed)
        if trace==True:
            print(' Monty exposes door',exposed)
        
        if switch==True:
            while True:
            self.__dict__[name] = value
        else:
            raise NameError('\n\tclass:  Point\n\tmethod:  __setattr__\n\terror:  ' + name + " contains '_prev'.")


    def __getitem__(self, index):
        if index == 0:
            return {item:self.__dict__[item] for item in self.__dict__ if item != 'data'}
        elif index < 0:
            return {item:self.__getattr__(item + abs(index) * '_prev') for item in self.__dict__ if item != 'data'}
        else:
            raise IndexError('\n\tclass:  Point\n\tmethod:  __getitem__\n\terror:  ' + str(index) + " must be <= 0")

if __name__ == '__main__':
    
    if prompt.for_bool('Test expand?',True):
        pd = dict(digit=r'\d', integer=r'[=-]?#digit##digit#*')
        expand_re(pd)
        print('result =',pd)
        # produces/prints the dictionary {'digit': '\\d', 'integer': '[=-]?(\\d)(\\d)*'}
        
        pd = dict(integer       =r'[+-]?\d+',
                  integer_range =r'#integer#(..#integer#)?',
                  integer_list  =r'#integer_range#(?,#integer_range#)*',
                  integer_set   =r'{#integer_list#?}')
        expand_re(pd)
        print('result =',pd)
        # produces/prints the dictionary 
        # {'integer'      : '[+-]?\\d+',
        #  'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?',
        #  'integer_list' : '(([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*',   
Exemplo n.º 15
0
    # Note that dict/defaultdict will compare == if they have the same keys and
    #   associated values, regardless of the fact that they print differently
    def check (answer, correct):
        if (answer   == correct):
            print ('    CORRECT')
        else:
            print ('    INCORRECT')
            print ('      was       =',answer)
            print ('      should be =',correct)
        print()
 
 
    def lol(alol):
        return '\n        '+'\n        '.join(','.join(f'{col:3}' for col in line) for line in alol)
    
    if prompt.for_bool('Test all_parties?', True):  
        db1 = {'Alan': {'Barb': [10, 20], 'Carl': [10, 10]},
               'Barb': {'Alan': [10, 10], 'Deja': [5, 5, 5]},
               'Carl': {'Alan': [10, 5],  'Deja': [15],       'Elan': [5, 5]},
               'Deja': {'Elan': [5]},
               'Elan': {'Carl': [10]}
               }
        print('  argument =', db1)
        answer = all_parties(db1)
        print('  answer   =', answer)
        check(answer, {'Barb', 'Deja', 'Carl', 'Elan', 'Alan'})

        db1a = {'Alan': {'Barb': [10, 20], 'Carl': [10, 10]},
                'Barb': {'Alan': [10, 10], 'Deja': [5, 5, 5]},
                'Carl': {'Alan': [10, 5],  'Deja': [15],       'Elan': [5, 5]}
                }
Exemplo n.º 16
0
if __name__ == '__main__':
    # Write script here
    file = goody.safe_open('Specify the file name storing the graph', 'r',
                           'unable to read this file')
    graph = read_graph(file)
    file.close()
    print('\nGraph: node -> [all its destination nodes]\n' +
          graph_as_str(graph))
    while True:
        node = prompt.for_string(
            'Specify the start node (or just enter quit)',
            is_legal=(lambda x: x in graph or x == 'quit'),
            error_message='Illegal: not a source node')
        if node == 'quit':
            break
        do_trace = prompt.for_bool(
            'Trace this Algorithm',
            default=True,
            error_message='please enter a boolean value')
        print('From ' + node + ' the reachable nodes are ' +
              str(reachable(graph, node, trace=do_trace)) + '\n')
    # 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.º 17
0
    t = list_to_tree([
        5,
        [
            8,
            [16, [32, None, None], [46, [70, None, None], [82, None,
                                                           None]]], None
        ], [12, [30, None, [30, [40, None, None], [70, None, None]]], None]
    ])
    print('\nTree is\n', str_tree(t), end='')
    print('is_min_heap =', is_min_heap(t))

    print('\nTesting OptionMenuUndo')
    from tkinter import *
    print('Simulate using StringVar_WithHistory or build/test actual GUI')
    if prompt.for_bool('Simulate', default=True):
        # Needed for obscure reasons
        root = Tk()
        root.title('Widget Tester')
        main = Frame(root)

        # Construct an OptionMenuUndo object for simulation
        omu = OptionMenuUndo(main, 'Choose Option', 'option1', 'option2',
                             'option3')

        # Initially its value is 'Choose Option'
        print(omu.get(), '   should be Choose Option')

        # Select a new option
        omu.simulate_selection('option1')
        print(omu.get(), '         should be option1')
Exemplo n.º 18
0
            
        reached_set.add(popped)
        if trace:
            print("after adding all nodes reachable directly from" + str(popped) + "but not already in reached, exploring = " + str(exploring_list) + "\n")
            print("reached set    = " + str(reached_set))
            print("exploring list = " + str(exploring_list))
             
    return(reached_set)

if __name__ == '__main__':
    # Write script here
    graph_file = prompt.for_string("Enter the file name describing this graph", is_legal=(lambda f: open(f)), error_message="Please enter a valid file name")
    with open(graph_file) as f:
        graph = read_graph(f)
        
    print("Graph: a node -> [showing all its destination nodes]")
    print(graph_as_str(graph))
    while(True):
        start_node = prompt.for_string("Enter the starting node (or enter quit)", is_legal=(lambda s: s in graph.keys() or s == 'quit'), error_message="Please enter a legal String")
        if start_node == 'quit': break
        trace = prompt.for_bool("Enter whether to trace this algorithm (True/False)", error_message='Please enter "True" or "False"')
        print("From node a its reachable nodes:", reachable(graph,start_node,trace))
    # 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.º 19
0
            self.history[name].append(value)
        self.__dict__[name] = value

    def __getitem__(self, index):
        if index > 0:
            raise IndexError('History.__getitem__: index(' + str(index) +
                             ') > 0')
        return {
            k: v[index - 1] if abs(index) < len(v) else None
            for k, v in self.history.items()
        }


if __name__ == '__main__':

    if prompt.for_bool('Test expand?', True):
        pd = dict(digit=r'\d', integer=r'[=-]?#digit##digit#*')
        expand_re(pd)
        print('result =', pd)
        # produces/prints the dictionary {'digit': '\\d', 'integer': '[=-]?(\\d)(\\d)*'}

        pd = dict(integer=r'[+-]?\d+',
                  integer_range=r'#integer#(..#integer#)?',
                  integer_list=r'#integer_range#(?,#integer_range#)*',
                  integer_set=r'{#integer_list#?}')
        expand_re(pd)
        print('result =', pd)
        # produces/prints the dictionary
        # {'integer'      : '[+-]?\\d+',
        #  'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?',
        #  'integer_list' : '(([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*',
Exemplo n.º 20
0
          sep='\n')
    while True:
        start = prompt.for_string("Choose the start node (or choose quit) ",
                                  default='quit',
                                  error_message='Entry Error')
        if start == 'quit':
            break
        elif start not in graph:
            print(
                f'Entry Error: {start}; Illegal: not a source node\nPlease enter a legal String\n'
            )
            continue
        reached_nodes = set()
        for node in reachable(
                graph, start,
                prompt.for_bool(
                    "Choose whether to trace this algorithm ",
                    default=True,
                    error_message="Invalid Entry: Please enter a True or False"
                )):
            if len(graph[node]) > 0: reached_nodes.add(node)
        print(f'From {start} the reachable nodes are {reached_nodes}\n')
    # 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.º 21
0
                        '{} 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
    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.º 22
0
    # checks whether answer is correct, printing appropriate information
    # Note that dict/defaultdict will compare == if they have the same keys and
    #   associated values, regardless of the fact that they print differently
    def check (answer, correct):
        if (answer   == correct):
            print ('    Correct')
        else:
            print ('    INCORRECT')
            print ('      was       =',answer)
            print ('      should be =',correct)
        print()

####################


    if prompt.for_bool('Test top_students?', True):        
        students = {('Alice','C'),('Bob','B-'),('Carol','B-'),('David','D'),('Evelyn','C+')}
        print('  argument =',students)
        answer   = top(students)
        print('  answer   =', answer)
        check(answer, {'Bob','Carol'})
        
        students = {('Alice','B+'),('Bob','B'),('Carol','C'),('David','B-')}
        print('  argument =',students)
        answer   = top(students)
        print('  answer   =', answer)
        check(answer, {'Alice'})
        
        students = {('Alice','C'),('Bob','D'),('Carol','C'),('David','F'),('Evelyn','C')}
        print('  argument =',students)
        answer   = top(students)
Exemplo n.º 23
0
                    [30,
                       [40,None,None],
                       [70,None,None]
                    ]
                 ],
                 None
              ]
            ])
    print('\nTree is\n',str_tree(t),end='')
    print('is_min_heap =',is_min_heap(t))  
  

    print('\nTesting OptionMenuUndo')
    from tkinter import *
    print('Simulate using StringVar_WithHistory or build/test actual GUI')
    if prompt.for_bool('Simulate',default=True):
        # Needed for obscure reasons
        root = Tk()
        root.title('Widget Tester')
        main = Frame(root)
        
        # Construct an OptionMenuUndo object for simulation
        omu = OptionMenuUndo(main, 'Choose Option', 'option1','option2','option3')
        
        # Initially its value is 'Choose Option'
        print(omu.get(), '   should be Choose Option')
        
        # Select a new option
        omu.simulate_selection('option1')
        print(omu.get(), '         should be option1')
        
            if not i:
                if len(graph[v]) != 0 and sum(influenced_dict[f] for f in graph[v]) >= ceil(len(graph[v])*tip):
                    influenced_dict[v] = True
        old_influenced, influenced_num = influenced_num, sum(i for i in influenced_dict.values())
        if influenced_num == old_influenced:
            return set(v for v in influenced_dict if influenced_dict[v])
       
            
    
if __name__ == '__main__':
    graph_file = safe_open('Enter a file storing a friendship graph', 'r', 'Could not find that file',default='graph1.txt')
    graph = read_graph(graph_file)
    print('Graph: node -> list of all friend nodes\n' + graph_as_str(graph))
    
    tip = .5 #tip = prompt.for_float('Enter tip percentage', is_legal = lambda x : 0 <=x<=1, default = .5)
    influencers = find_influencers(graph,tip,prompt.for_bool('Trace the Algorithm',default=True))
    print('Influencers =', influencers)
    
    while True:
        influencer_set = prompt.for_string('\nEnter influencers set (or else quit)', default=str(influencers), is_legal = lambda core : core == 'quit' or all(c in graph for c in eval(core)))
        if influencer_set == 'quit':
            break;
        influenced = all_influenced(graph,eval(influencer_set),tip)
        print('All Influenced ('+str(100*len(influenced)/len(graph))+'% of graph)=',influenced,'\n')
            
    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
Exemplo n.º 25
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.º 26
0
    file = safe_open("Enter a file storing a friendship graph",
                     mode="r",
                     error_message="That don't work homie",
                     default="")
    fileGraph = read_graph(file)
    dupe = str(fileGraph)
    file.close()
    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():
Exemplo n.º 27
0
if __name__ == '__main__':
    # Write any other code here to test Table before doing bsc test; for example

    # Here are simple tests not raising exceptions (illustrated in the problem statement)
    # Comment out any tests you no longer want to perform
    # The driver is run at the bottom of this script
    import prompt
    print(
        'For simple test __init__ and beyond to work, __init__ must work correctly'
    )
    print('  for cases when it does not need to throw exceptions.')
    print(
        'Also, calling __iter__ will raise an exception if it is implemented')
    print('   by just pass')
    if prompt.for_bool(
            '\nDo you want to perform simple tests before bsc tests', False):
        # Table (__init__)
        print('\n\n-->Testing Table (__init__), simply')
        employee = Table('Employee', ['Name', 'EmpId', 'DeptName'], [
            lambda v: type(v) is str,
            lambda v: type(v) is int and 1000 <= v <= 9999,
            lambda v: v in ['Finance', 'Sales']
        ])
        print(employee)
        print(employee.raw())

        # add_record
        print('\n\n-->Testing add_record simply')
        employee = Table('Employee', ['Name', 'EmpId', 'DeptName'], [
            lambda v: type(v) is str,
            lambda v: type(v) is int and 1000 <= v <= 9999,
Exemplo n.º 28
0
    # For asking for input/running the program
    file = input('Choose the file name representing the graph: ')
    graph = read_graph(open(file))
    print(graph_as_str(graph))

    while True:
        start = input('Choose the start node (or choose quit): ')

        if start == 'quit':
            break

        elif (reachable(graph, start, False) == set()):
            print(
                f"  Entry Error: '{start}';  Illegal: not a source node.\n  Please enter a legal String\n"
            )
            continue

        trace = prompt.for_bool('Choose whether to trace this algorithm[True]')
        print("From " + start + " the reachable nodes are",
              reachable(graph, start, trace), "\n")

    # 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()
            self.__dict__[c_match[0]] = value
        else:
            self.__dict__[name] = value


# I cannot supply a batch self-check for this problem until next week.

# You should try to understand the specifications and test your code
#   to ensure it works correctly, according to the specification.
# You are all allowed to ask "what should my code do..." questions online
#   both before and after I post my batch self_check file.
# The driver below will allow you to easily test your code.

if __name__ == '__main__':
    o = Misspelling(
        prompt.for_bool("Allow fixing mispelling in __setattr__", True))
    # Put code here to test object o the same way each time the code is run

    # # Use the while loop below to type in code one on-the-fly when prompted
    # while True:
    #     try:
    #         print("\n" + str(o.__dict__))
    #         test = prompt.for_string("Enter test")
    #         if test == "quit":
    #             break;
    #         if '=' not in test:
    #             print(eval(test))
    #         else:
    #             exec(test)
    #     except Exception as exc:
    #         print(exc)
Exemplo n.º 30
0
if __name__ == '__main__':
    # Write script here
    m, w = None, None
    while m is None or w is None:
        try:
            m, w = (
                open(
                    input(
                        "Input the file name detailing the preferences for men:"
                    )),
                open(
                    input(
                        "Input the file name detailing the preferences for women:"
                    )))
        except:
            print("Error Finding file")
    m = read_match_preferences(m)
    w = read_match_preferences(w)
    dict_as_str(m)
    dict_as_str(w)
    trace = prompt.for_bool("Input tracing algorithm option", True,
                            "Enter False to disable tracing")
    print("The final matches = ", make_match(men=m, women=w, trace=trace))
    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.º 31
0
# Program History:
#   5/18/01: R. Pattis - Operational for 15-100
#   1/25/02: R. Pattis - Added Timer object for timing process
#   2/23/13: R. Pattis - Converted to Python using similar libraries
#
################################################################################ 
################################################################################ 



import prompt
from  stopwatch import Stopwatch


original_number = prompt.for_int('Enter a positive number', is_legal=(lambda x : x > 0))
is_debugging    = prompt.for_bool('Display intermediate results',True)
cycle_count     = 1
test_number     = original_number

timer = Stopwatch(running_now = True)

while True:
    if is_debugging:
        print('Cycle', cycle_count, ': test number is now', test_number)
    
    ####################
    if test_number == 1336:
        break
    ####################

    cycle_count += 1
Exemplo n.º 32
0
    # checks whether answer is correct, printing appropriate information
    # Note that dict/defaultdict will compare == if they have the same keys and
    #   associated values, regardless of the fact that they print differently
    def check(answer, correct):
        if (answer
                == correct) or (type(answer) is float
                                and type(correct) is float
                                and isclose(answer, correct, abs_tol=.00001)):
            print('    Correct')
        else:
            print('    INCORRECT')
            print('      was       =', answer)
            print('      should be =', correct)
        print()

    if prompt.for_bool('Test effective_rate?', True):
        db1 = {
            'CT': {
                (0, 12_499): .02,
                (12_500, 49_999): .04,
                (50_000, None): .06
            },
            'IN': {
                (0, None): .04
            },
            'LA': {
                (0, 9_999): .03,
                (10_000, 12_499): .05,
                (12_500, 49_999): .055,
                (50_000, 299_999): .06,
                (300_000, None): .078