Структура данных стека, чтобы сделать веб-браузер - PullRequest
0 голосов
/ 11 февраля 2020
from stack import stack        
def getAction():
        '''
        Write docstring to describe function
        Inputs: no arguments taken by this function.
        Returns: string containing users input if he has chosen one of the correct input options
        '''
        correct_input=False
        while correct_input==False:
            user_input=input("Enter = to enter a URL, < to go back, > to go forward, q to quit: ")
            if user_input =='q' or user_input =='>' or user_input =='<' or user_input =='=':
                correct_input=True

            if correct_input==False:
                print('Invalid entry.')
        return user_input


    def goToNewSite(current, pages):
        '''
        Write docstring to describe function
        Inputs: index of the current website (int), reference to list containing the webpage addresses to go back and forth between
        Returns: address inputted by user as a string
        '''

        new_web_address=input('Enter a new website address ')
        for i in range(current+1,len(pages)):
            pages.pop()
        pages.append(new_web_address)
        #pages[current+1]=new_web_address
        #pages=pages[:current+1]

        return current+1



    def goBack(current, pages):
        '''
        Write docstring to describe function
        Inputs: index of the current website (int),reference to list containing the webpage addresses to go back and forth between
        Returns: index of the previous webpage (int)
        '''
        # alternatively this could be done by checking if current-1>=0
        if current-1>=0:
            return current-1

        else:
            print('Cannot go backward')
            return current




    def goForward(current, pages):
        '''
        Write docstring to describe function
        Inputs: index of the current website (int),reference to list containing the webpage addresses to go back and forth between
        Returns: index of the previous webpage (int)
        '''  
        # alternatively this could be done by checking if current +1 in range(len(pages))
        if current+1<len(pages):
            return current+1

        else:
            print('Cannot go forward')
            return current




    def main():
        '''
        Controls main flow of web browser simulator
        Inputs: N/A
        Returns: None
        '''    
        HOME = 'www.google.ca'
        websites = [HOME]
        currentIndex = 0
        quit = False

        while not quit:
            print('\nCurrently viewing', websites[currentIndex])
            print(websites)

            action = getAction()

            if action == '=':
                currentIndex = goToNewSite(currentIndex, websites)

            elif action == '<':
                currentIndex = goBack(currentIndex, websites)
            elif action == '>':
                currentIndex = goForward(currentIndex, websites)
            elif action == 'q':
                quit = True

        print('Browser closing...goodbye.')    


    if __name__ == "__main__":
        main()

выше - мой код

Я должен создать симулятор веб-браузера, используя структуру данных, которую нам дали, известную как стек. Я сделал другую версию этого, не используя try, кроме else и используя списки, но используя этот новый тип объекта, я изо всех сил стараюсь, чтобы несколько случаев работали. Например, во время пробного запуска это не выдает ошибку, когда я пытаюсь go вернуться после того, как зашел хотя бы на один веб-сайт, даже если нет сайтов, на которые go можно вернуться с текущего веб-сайта. например, я введу шаг 1, затем go назад, что приведет меня к www.google.ca, а затем go обратно, и вместо того, чтобы сказать, что я не могу go назад, он просто перепечатает на экране. Я не уверен, что там происходит, и мне было интересно, если кто-то может объяснить, почему это не работает, и ошибка в моей логике c

ниже - это класс, который нам сказали использовать экземпляры этого Класс стека для реализации этого.

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    # MODIFY: RAISE AN EXCEPTION IF THIS METHOD IS INVOKED ON AN EMPTY STACK
    def pop(self):
        if self.isEmpty()==True:
            raise Exception('Stack is empty cannot pop')
        if self.isEmpty()==False:

            return self.items.pop()

    # MODIFY: RAISE AN EXCEPTION IF THIS METHOD IS INVOKED ON AN EMPTY STACK
    def peek(self):
        if self.isEmpty()==True:
            raise Exception('Stack is empty cannot peek')
        if self.isEmpty()==False:


            return self.items[len(self.items)-1] 

    def isEmpty(self):
        return self.items == []

    def size(self):
        return len(self.items)

    def show(self):
        print(self.items)

    def __str__(self):
        stackAsString = ''
        for item in self.items:
            stackAsString += item + ' '
        return stackAsString

1 Ответ

1 голос
/ 11 февраля 2020

Вот решение и домашнее задание

Домашнее задание:

  • Не могли бы вы выполнить go forward forward самостоятельно?

Примечание: Посмотрите, что я сделал, и выполните метод пересылки самостоятельно

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    # MODIFY: RAISE AN EXCEPTION IF THIS METHOD IS INVOKED ON AN EMPTY STACK
    def pop(self):
        if self.isEmpty()==True:
            raise Exception('Stack is empty cannot pop')
        if self.isEmpty()==False:

            return self.items.pop()

    # MODIFY: RAISE AN EXCEPTION IF THIS METHOD IS INVOKED ON AN EMPTY STACK
    def peek(self):
        if self.isEmpty()==True:
            raise Exception('Stack is empty cannot peek')
        if self.isEmpty()==False:


            return self.items[len(self.items)-1]

    def isEmpty(self):
        return self.items == []

    def size(self):
        return len(self.items)

    def show(self):
        print(self.items)

    def __str__(self):
        stackAsString = ''
        for item in self.items:
            stackAsString += item + ' '
        return stackAsString



# from stack import stack
def getAction():
        '''
        Write docstring to describe function
        Inputs: no arguments taken by this function.
        Returns: string containing users input if he has chosen one of the correct input options
        '''
        correct_input=False
        while correct_input==False:
            user_input=input("Enter = to enter a URL, < to go back, > to go forward, q to quit: ")
            if user_input =='q' or user_input =='>' or user_input =='<' or user_input =='=':
                correct_input=True

            if correct_input==False:
                print('Invalid entry.')
        return user_input


def goToNewSite(current, pages):
    '''
    Write docstring to describe function
    Inputs: index of the current website (int), reference to list containing the webpage addresses to go back and forth between
    Returns: address inputted by user as a string
    '''

    new_web_address=input('Enter a new website address ')
    # for i in range(current+1,len(pages)):
    #     pages.pop()
    # pages.append(new_web_address)
    pages.push(new_web_address)
    #pages[current+1]=new_web_address
    #pages=pages[:current+1]

    return pages.size()



def goBack(current, pages):
    '''
    Write docstring to describe function
    Inputs: index of the current website (int),reference to list containing the webpage addresses to go back and forth between
    Returns: index of the previous webpage (int)
    '''
    # alternatively this could be done by checking if current-1>=0
    # if current-1>=0:
    #     return current-1
    #
    # else:
    #     print('Cannot go backward')
    #     return current
    if pages.size() <= 1:
        print('Cannot go backward')
        return pages.size()
    pages.pop()
    return pages.size()





def goForward(current, pages):
    '''
    Write docstring to describe function
    Inputs: index of the current website (int),reference to list containing the webpage addresses to go back and forth between
    Returns: index of the previous webpage (int)
    '''
    # alternatively this could be done by checking if current +1 in range(len(pages))
    if current+1<len(pages):
        return current+1

    else:
        print('Cannot go forward')
        return current




def main():
    '''
    Controls main flow of web browser simulator
    Inputs: N/A
    Returns: None
    '''
    HOME = 'www.google.ca'
    # websites = [HOME]
    websites = Stack()
    websites.push(HOME)
    currentIndex = 0
    quit = False

    while not quit:
        # print('\nCurrently viewing', websites[currentIndex])
        print('\nCurrently viewing', websites.peek())
        print(websites)

        action = getAction()

        if action == '=':
            currentIndex = goToNewSite(currentIndex, websites)

        elif action == '<':
            currentIndex = goBack(currentIndex, websites)
        elif action == '>':
            currentIndex = goForward(currentIndex, websites)
        elif action == 'q':
            quit = True

    print('Browser closing...goodbye.')


if __name__ == "__main__":
    main()

Вот выходные данные

В настоящее время просмотр www.google.ca www.google.ca Введите = для ввода URL, <до go назад,> до go вперед, q для выхода: = введите новый адрес веб-сайта https://www.pymiami.org

Вы просматриваете https://www.pymiami.org www.google.ca https://www.pymiami.org Enter = для ввода URL, <до go назад,> до go вперед, q для выхода : https://www.dabeaz.com Неверный ввод. Введите = для ввода URL, <на go назад,> на go вперед, q на выход: = введите новый адрес веб-сайта https://www.dabeaz.com

В настоящее время просматриваете https://www.dabeaz.com www.google.ca https://www.pymiami.org https://www.dabeaz.com Enter = для ввода URL, <до go назад,> до go пересылка, q чтобы выйти: = Введите новый адрес веб-сайта https://en.wikipedia.org/wiki/Guido_van_Rossum

Вы просматриваете https://en.wikipedia.org/wiki/Guido_van_Rossum www.google.ca https://www.pymiami.org https://www.dabeaz.com https://en.wikipedia.org/wiki/Guido_van_Rossum Введите =, чтобы ввести URL, <до go назад,> до go вперед, q для выхода: <</p>

В настоящее время просматриваете https://www.dabeaz.com www.google.ca https://www.pymiami.org https://www.dabeaz.com Введите =, чтобы ввести URL, <до go назад,> до go вперед, q чтобы выйти: <</p>

Вы просматриваете https://www.pymiami.org www.google.ca https://www.pymiami.org Enter = для ввода URL, to go вперед, q для выхода: <</p>

В настоящее время просматривается www.google.ca www.google.ca Enter = для ввода URL, <до go назад,> до go вперед, q для выхода: < Не может go назад

В настоящее время просматриваете www.google.ca www.google.ca Enter = для ввода URL, от <до go назад,> до go вперед, от q до выхода:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...