+ -
当前位置:首页 → 问答吧 → python中LIST的问题,求大家帮帮看看!!!

python中LIST的问题,求大家帮帮看看!!!

时间:2011-08-16

来源:互联网

[code=Python][/code]#!/usr/bin/env python
"""
A simple program that plays Shannon's Game.
"""

class Frequency(object):
  """
  Stores a letter:frequency pair.

  >>> f = Frequency('c', 2)
  >>> f.letter
  'c'
  >>> f.frequency
  2
  >>> f
  {c: 2}
  """
  def __init__(self, letter, frequency):
  self.letter = letter
  self.frequency = frequency
  # The next Frequency object when stored as part of a linked list
  self.next = None

  def __repr__(self):
  return '{%s: %d}' % (self.letter, self.frequency)

class FrequencyList(object):
  """Stores a collection of Frequency objects as a linked list."""
  def __init__(self):
  self.head = None

  def add(self, letter, frequency):
  """
  Adds the given `letter`:`frequency` combination as a Frequency object
  to the end of the list. If the given `letter` is already in the list, 
  the given `frequency` is added to its frequency.

  >>> f = FrequencyList()
  >>> f.add('a', 3)
  >>> f
  [{a: 3}]
  >>> f.add('b', 2)
  >>> f
  [{a: 3}, {b: 2}]
  """
  letter = letter.lower()
  if self.head is None:
  self.head = Node(Frequency(letter, 1))
  else:
  current = self.head
  while current.next is not None and current.data.letter != letter:
  current = current.next
  if current.data.letter != letter:
  current.next = Node(Frequency(letter, 1))
  else:
  current.data.increment()
   

  def remove(self, letter):
  """
  Removes the Frequency object with the given `letter` from the list.
  Does nothing if `letter` is not in the list.

  >>> f = FrequencyList()
  >>> f.add('a', 3)
  >>> f.add('b', 2)
  >>> f.add('c', 3)
  >>> f
  [{a: 3}, {b: 2}, {c: 3}]
  >>> f.remove('b')
  >>> f
  [{a: 3}, {c: 3}]
  """
  pass

  def find(self, letter):
  """
  Returns the Frequency object for the given `letter` in the list, or
  None if the `letter` doesn't appear in the list.

  >>> f = FrequencyList()
  >>> f.add('a', 3)
  >>> f.find('a')
  {a: 3}
  >>> f.find('b')
  """
  pass

  def __contains__(self, item):
  return self.find(item) is not None
   
  def __repr__(self):
  item_strs = []
  current = self.head
  while current is not None:
  item_strs.append(repr(current))
  current = current.next
  return '[%s]' % ', '.join(item_strs)


求大家帮忙,如何实现remove和find,第一部分的add是自己写的,也许有错,请各位大大帮帮忙,谢谢大家了!!

作者: gozhuzhu   发布时间: 2011-08-16

1. 重贴代码
2. 用自然语言描述你的问题(“如何写代码”,这不叫问题,导致你不会自己写代码的具体困难,才叫问题)。至少我在明白你的问题是什么前,不会浪费时间去阅读代码。

作者: iambic   发布时间: 2011-08-16

这个是python代码吗,怎么还有 >>>符号?准备学python的路过,

作者: wyjq395   发布时间: 2011-08-16

代码太长了,没心思认真读。最好把关键的东西写出来。

作者: freedomwzq   发布时间: 2011-08-16