需要专家意见来制作一个堆栈。

huangapple go评论70阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月23日 17:33:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定