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