英文:
require expert opinion in making a stack
问题
我两周前开始学编程,在观看了关于栈的YouTube视频后(老实说我几乎不知道它是什么),我尝试编写一个程序,将一个元素添加到栈中?然后检查该元素是否已经存在,但我面临一个问题,无论如何它都会显示“此元素已存在”,请帮忙!!
stack = []
for i in range(1):
init_element = int(input(f"输入元素 {i}:"))
stack.append(init_element)
for n in range(9):
elements = int(input("输入元素:"))
for element in stack:
for x in range(9):
if elements == stack[x]:
print("此元素已存在于栈中!")
break
if elements != stack[x]:
stack.append(elements)
print(stack)
英文:
I started programming 2 weeks ago and after watching youtube video about a stack(honestly i barely know what it is) i tried making a program which adds an element into a stack? and then checks whether that element already exists or not, but i am faced with an issue that no mater what it always says "this element already exists" please help!!
stack = []
for i in range(1):
init_element = int(input(f"enter element {i} : "))
stack.append(init_element)
for n in range(9):
elements = int(input(f"enter elements : "))
for elements in stack:
for x in range(9):
if elements == stack[x]:
print("this element already exists in stack!")
break
if elements != stack[x]:
stack.append(elements)
print(stack)
答案1
得分: 1
你在获取用户输入和迭代列表时使用了相同的变量名。这就是元素始终存在的原因。
问题出现在以下代码行中:
elements = int(input(f"输入元素:"))
for elements in stack:
请注意elements在用户输入和列表迭代中都被使用了。
英文:
You use the same variable name to get user input and to iterate over a list. That's why the element always exists.
The issue is in these lines of code
elements = int(input(f"enter elements : "))
for elements in stack:
notice how elements is used for both user input and list iteration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论