Python;链表和遍历!

发布于 2024-09-16 13:08:50 字数 852 浏览 7 评论 0原文

现在在学校开始用python编程,我不知道如何继续解决这个问题。有什么想法吗?

输入由由换行符分隔的整数组成。你的程序应该将它们提交到一个链表中,遍历链表并打印最大的数字。

采取第一个数字,并执行一个操作,表示“如果下一个数字更大,则采用该数字,否则,保留当前数字,然后沿着列表向下重复”

然后当它到达列表末尾时,它打印它所具有的值。

from sys import stdin

class Kubbe:
    vekt = None
    neste = None
    def __init__(self, vekt):
        self.vekt = vekt 
        self.neste = None 

def spor(kubbe):
    # WRITE YOUR CODE HERE
    # Creates linked list
    forste = None
    siste = None
    for linje in stdin:
        forrige_siste = siste
        siste = Kubbe(int(linje))
        if forste == None:
            forste = siste
        else:
            forrige_siste.neste = siste

# Calls the solution function and prints the result
print spor(forste)

输入:示例

54
37
100
123
1
54

所需输出

123

Starting some programming with python at school now, and I don't know how to proceed with this problem. Any thoughts?

Input consists of integer separated by line breaks. Your program should submit them in a linked list, traverse the linked list and print the highest number.

Something to take the first number, and do an action which says "if the next number is bigger, take that one, else, keep the current number, and head down the list and repeat"

Then when it gets to the end of the list, it prints the value it has.

from sys import stdin

class Kubbe:
    vekt = None
    neste = None
    def __init__(self, vekt):
        self.vekt = vekt 
        self.neste = None 

def spor(kubbe):
    # WRITE YOUR CODE HERE
    # Creates linked list
    forste = None
    siste = None
    for linje in stdin:
        forrige_siste = siste
        siste = Kubbe(int(linje))
        if forste == None:
            forste = siste
        else:
            forrige_siste.neste = siste

# Calls the solution function and prints the result
print spor(forste)

Input: example

54
37
100
123
1
54

Required output

123

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

山川志 2024-09-23 13:08:50

“链表”在 Python 中很少使用——通常,人们只使用 Python 内置列表 list,它实际上更像是一种“动态向量”。因此,看到指定为练习约束的一部分的链表是很奇怪的。

但要点是,您显示的代码已经创建一个链表 - 头位于forste,并且对于每个节点,下一个节点指针位于.neste,有效负载位于.vekt。因此,无论问题的内容如何,​​这可能都不是您要问的问题。

完全构造链表后(即在 spor 的当前代码末尾)循环遍历链表的简单方法是

current = forste
while current is not None:
   ...process current.vekt...
   current = current.neste

在您的情况下,“过程”部分的逻辑是当然,正如您的 Q 文本已经说过的:

   if current.vekt > themax:
       themax = current.vekt

唯一的微妙之处是,您需要在 while 循环之前将 themax 初始设置为“尽可能低的数字”;在Python的最新版本中,“负无穷大”被可靠地记录和比较(尽管只是作为浮点数,它仍然可以正确地与整数进行比较),所以

themax = float('-inf')

可以工作。更优雅的方法可能是最初将最大值设置为第一个有效负载,避免弄乱无穷大。

"Linked lists" are rarely used in Python -- normally, one uses just list, the Python built-in list, which is actually more of a "dynamic vector". So, it's peculiar to see a linked list specified as part of the exercise's constraints.

But the main point is, the code you're showing is already creating a linked list -- the head is at forste, and, for each node, the next-node pointer at .neste, the payload at .vekt. So, presumably, that's not what you're asking about, no matter the text of your question.

The simple way to loop through your linked list once you have fully constructed it (i.e., at the end of the current code for spor) is

current = forste
while current is not None:
   ...process current.vekt...
   current = current.neste

In your case, the logic for the "process" part is of course, as your Q's text already says:

   if current.vekt > themax:
       themax = current.vekt

The only subtlety is, you need to initially set themax, before this while loop to "the lowest possible number"; in recent versions of Python, "minus infinity" is reliably recorded and compared (though only as a float, it still compares correctly to ints), so

themax = float('-inf')

would work. More elegant might be to initially set the maximum to the first payload, avoiding messing with infinity.

亚希 2024-09-23 13:08:50

这是基于您自己的代码和语言的答案。抱歉,如果新变量和函数名称翻译得不好,因为我不会说挪威语(Google 语言工具 是我的朋友)。

评论:像飞机空中交通管制一样,大多数国际编程论坛(例如StackOverflow)的默认语言都是英语。如果你使用它,你可能会得到更快、更好和更多的答案——而且它可能会让问题和相关答案对大多数其他人有用。只是我的 2 øre...;-)

from sys import stdin

class Kubbe:
    vekt = None
    neste = None
    def __init__(self, vekt):
        self.vekt = vekt
        self.neste = None

def spor():
    # WRITE YOUR CODE HERE
    # Creates linked list
    forste = None
    siste = None
    while True:
        try:
            linje = raw_input()
        except EOFError:
            break
        forrige_siste = siste
        siste = Kubbe(int(linje))
        if forste == None:
            forste = siste
        else:
            forrige_siste.neste = siste
    return forste

def finne_maksimal(lenketliste):
    storste = None
    if lenketliste is not None:
        storste = lenketliste.vekt
        gjeldende = lenketliste.neste
        while gjeldende is not None:
            if gjeldende.vekt > storste:
                storste = gjeldende.vekt
            gjeldende = gjeldende.neste
    return storste

lenketliste = spor()
storste = finne_maksimal(lenketliste)
if lenketliste is None:
    print "tom liste"
else:
    print "storste er", storste

Here's an answer based on your own code and language. Sorry if the new variable and function names do not translate well, as I don't speak Norwegian (Google Language Tools is my friend).

Comment: Like airplane Air Traffic Control the default language of most international programming forums such as StackOverflow is English. If you use it, you are likely to get quicker, better, and more answers -- and it probably makes the question and related answers useful to the largest number of other folks. Just my 2 øre... ;-)

from sys import stdin

class Kubbe:
    vekt = None
    neste = None
    def __init__(self, vekt):
        self.vekt = vekt
        self.neste = None

def spor():
    # WRITE YOUR CODE HERE
    # Creates linked list
    forste = None
    siste = None
    while True:
        try:
            linje = raw_input()
        except EOFError:
            break
        forrige_siste = siste
        siste = Kubbe(int(linje))
        if forste == None:
            forste = siste
        else:
            forrige_siste.neste = siste
    return forste

def finne_maksimal(lenketliste):
    storste = None
    if lenketliste is not None:
        storste = lenketliste.vekt
        gjeldende = lenketliste.neste
        while gjeldende is not None:
            if gjeldende.vekt > storste:
                storste = gjeldende.vekt
            gjeldende = gjeldende.neste
    return storste

lenketliste = spor()
storste = finne_maksimal(lenketliste)
if lenketliste is None:
    print "tom liste"
else:
    print "storste er", storste
此刻的回忆 2024-09-23 13:08:50

Python 中有一个名为 reduce 的内置函数,它遍历列表并使用给定函数“压缩”它。也就是说,如果您有一个包含五个元素 [a,b,c,d,e] 和一个函数 f 的列表,那么它将有效地执行

temp = f(a,b)
temp = f( temp, c )
...

您应该能够用它来编写一个非常简洁的解决方案。

如果您想不那么抽象,则需要依次迭代列表中的每个元素,将迄今为止最大的数字存储在变量中。仅当您到达的元素大于所述变量的值时才更改变量。

There is a builtin function in Python called reduce, which traverses a list and "compresses" it with a given function. That is, if you have a list of five elements [a,b,c,d,e] and a function f, it will effectively do

temp = f(a,b)
temp = f( temp, c )
...

You should be able to use this to write a very neat solution.

If you want to be less abstract, you will need to iterate over each element of the list in turn, storing the greatest number so far in a variable. Change the variable only if the element you have reached is greater than the value of said variable.

jJeQQOZ5 2024-09-23 13:08:50

这似乎适用于您的输入(适用于 python 2 和 3)。注意 max 如何与 Python 的鸭子类型一起工作!

此版本也可从文件与 Python3 一起使用。

import sys
class Kubbe:
    vekt = None
    neste = None
    def __init__(self, vekt):
        self.vekt = vekt 
        self.neste = None 

def spor():
    # WRITE YOUR CODE HERE
    # Creates linked list
    forste = None
    siste = None
    while True:
        linje = sys.stdin.readline().rstrip()
        if not linje:
            break

        forrige_siste, siste = siste, Kubbe(int(linje))
        if forste is None:
            forste = siste
        else:
            forrige_siste.neste = siste
    return forste

def traverse(linkedlist):
    while linkedlist is not None:
        yield linkedlist.vekt
        linkedlist=linkedlist.neste

# Calls the solution function and prints the result
linkedlist=spor()

for item in traverse(linkedlist):
    print(item)

# use builtin max:
print('Maximum is %i' % max(traverse(linkedlist)))
# if not allowed:
m = linkedlist.vekt
for item in traverse(linkedlist.neste):
       if item > m:  m = item 
print(m)

This seems to work with your input (works in both python 2 and 3). Notice how max works with duck typing of Python!

This version works with Python3 also from file.

import sys
class Kubbe:
    vekt = None
    neste = None
    def __init__(self, vekt):
        self.vekt = vekt 
        self.neste = None 

def spor():
    # WRITE YOUR CODE HERE
    # Creates linked list
    forste = None
    siste = None
    while True:
        linje = sys.stdin.readline().rstrip()
        if not linje:
            break

        forrige_siste, siste = siste, Kubbe(int(linje))
        if forste is None:
            forste = siste
        else:
            forrige_siste.neste = siste
    return forste

def traverse(linkedlist):
    while linkedlist is not None:
        yield linkedlist.vekt
        linkedlist=linkedlist.neste

# Calls the solution function and prints the result
linkedlist=spor()

for item in traverse(linkedlist):
    print(item)

# use builtin max:
print('Maximum is %i' % max(traverse(linkedlist)))
# if not allowed:
m = linkedlist.vekt
for item in traverse(linkedlist.neste):
       if item > m:  m = item 
print(m)
傲影 2024-09-23 13:08:50

下面的代码可以工作。 Node 类表示 LinkedList 节点。 LinkedList 类定义了在链表末尾添加节点的方法,find_max 将遍历链表并返回具有最大键的节点。

   class Node(object):
        def __init__(self, key, next_node):
            self.key = key 
            self.next_node = next_node

    class LinkedList(object):
        def __init__(self):
            self.head = None

        def append(self, key):
            # Create a new Node
            new_node = Node(key, None)
            if (self.head == None):
                self.head = new_node
            else:
                tmp = self.head
                while(tmp.next_node != None):
                    tmp = tmp.next_node
                tmp.next_node = new_node

        def find_max(self):
            tmp = self.head
            max_num = 0 
            while(tmp != None):
                if (tmp.key > max_num):
                    max_num = tmp.key
                tmp = tmp.next_node
            return max_num

The below code would work. The Node class represents the LinkedList Node. The LinkedList class defines the methods to add node at the end of the Linked List and find_max will traverse through the list and return the node with largest key.

   class Node(object):
        def __init__(self, key, next_node):
            self.key = key 
            self.next_node = next_node

    class LinkedList(object):
        def __init__(self):
            self.head = None

        def append(self, key):
            # Create a new Node
            new_node = Node(key, None)
            if (self.head == None):
                self.head = new_node
            else:
                tmp = self.head
                while(tmp.next_node != None):
                    tmp = tmp.next_node
                tmp.next_node = new_node

        def find_max(self):
            tmp = self.head
            max_num = 0 
            while(tmp != None):
                if (tmp.key > max_num):
                    max_num = tmp.key
                tmp = tmp.next_node
            return max_num
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文