Находить, есть ли дублирующий элемент в node_chain? - PullRequest
0 голосов
/ 16 февраля 2019
  • Это псевдокод для алгоритма:
    1. запустить ходунка, чтобы пройтись по цепочке узлов
    2. , пока ходок не достиг конца
    3. начатьсредство проверки, чтобы пройти от Уокера до конца цепочки
    4. , в то время как средство проверки не достигло конца
    5. , если значение данных проверки совпадает с значением Уокера, вернуть True
    6. если Уокер достиг конца цепи, верните False
import node as node

def contains_duplicates(node_chain):
    walker = node_chain
    if walker is None:
        return False
    while walker is not None:
        checker = node.get_next(walker)
        while checker is not None:
            if node.get_data(walker) == node.get_data(checker):
                contains_duplicates(checker)
                return True
            elif node.get_data(walker) != node.get_data(checker):
                return False
        return

Поэтому, когда мы дадим Ввод:

  1. chain1 = узел.create (1, node. create (2, node. create (3, node. create (4, node. create (5))))) print ('Duplicates?', contains_duplicates (chain1))

  2. chain2 = узел.create (1, node. create (2, node. create (3, node. create (4, node. create (1))))) print ('Duplicates?', contains_duplicates (chain2))

Вывод:

Дубликаты?Ложные дубликаты?True

Это объявление с именем node.py

# Defines the Node ADT
# A node is a simple container with two pieces of information
#   data: the contained information
#   next: a reference to another node
# We can create node-chains of any size.
# Implementation notes:
#   This implementation uses a Python dictionary as a record.


def create(data, next=None):
    """
    Create a new node for the given data.
    Pre-conditions:
        data:  Any data value to be stored in the node
        next:  Another node (or None, by default)
    Post-condition:
        none
    Return:
        the node created
    """
    return {'data':data, 'next':next}


def get_data(node):
    """
    Retrieve the contents of the data field.
    Pre-conditions:
        node: a node created by create()
    Post-conditions:
        none
    Return
        the data value stored previously in the node
    """
    assert node is not None, "get_data() called with argument None"
    return node['data']


def get_next(node):
    """
    Retrieve the contents of the next field.
    Pre-conditions:
        node: a node created by create()
    Post-conditions:
        none
    Return
        the value stored previously in the next field
    """
    assert node is not None, "get_next() called with argument None"
    return node['next']


def set_data(node, val):
    """
    Set the contents of the data field to val.
    Pre-conditions:
        node: a node created by create()
        val:  a data value to be stored
    Post-conditions:
        stores the new data value, replacing the existing value
    Return
        none
    """
    assert node is not None, "set_data() called with argument None"
    node['data'] = val


def set_next(node, val):
    """
    Set the contents of the next field to val.
    Pre-conditions:
        node: a node created by create()
        val:  a node, or the value None
    Post-conditions:
        stores the new next value, replacing the existing value
    Return
        none
    """
    assert node is not None, "set_next() called with argument None"
    node['next'] = val



1 Ответ

0 голосов
/ 16 февраля 2019

IIUC

Я думаю, что это то, что вы хотите:

def contains_duplicates(node_chain):
    walker = node_chain
    if walker is None:
        return False
    while walker is not None:
        checker = node.get_next(walker)
        while checker is not None:
            if node.get_data(walker) == node.get_data(checker): //if there is a duplicate, return True
                return True
            else: //continue the loop until the end is reached, which will break the loop in line 3.
                contains_duplicates(checker)
                return

Отказ от ответственности: я полностью догадываюсь и понятия не имею, о чем речь :)

...