鱼C论坛

 找回密码
 立即注册
查看: 7249|回复: 45

数据结构和算法 有关的 面向对象的编程题~

[复制链接]
发表于 2015-3-24 09:50:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 WWCZHC 于 2015-3-24 13:34 编辑

求大神帮我完成doctest......大概题目如下.........
  1. """FrequencyList classes and testing routines.
  2. Work through the lab handout to find out what you are doing..."""


  3. import time
  4. import re
  5. from unicodedata import category
  6. import doctest
  7. import os

  8. #-------------------------------------------------------------------------
  9. class FreqNode(object):

  10.     """
  11.     Stores an item, frequency pair.

  12.     Basically a FreqNode object is a node in the frequency list.
  13.     Each FreqNode holds an item, the frequency for the item,
  14.     and a pointer to the next FreqNode object (or None).

  15.     >>> f = FreqNode('c', 2)
  16.     >>> f.item
  17.     'c'
  18.     >>> f.frequency
  19.     2
  20.     >>> print(f)
  21.     'c' = 2
  22.     """

  23.     def __init__(self, item, frequency=1):
  24.         self.item = item
  25.         self.frequency = frequency
  26.         self.next_node = None

  27.     def increment(self):
  28.         self.frequency += 1

  29.     def __str__(self):
  30.         return "\'{0}\' = {1:d}".format(self.item, self.frequency)


  31. #-------------------------------------------------------------------------
  32. class FreqList(object):

  33.     """Stores a linked list of FreqNode objects.
  34.     NOTE: This is a parent class for Unsorted, NicerUnSorted & Sorted FreqLists
  35.     """

  36.     def __init__(self):
  37.         self.head = None

  38.     def add(self, item):
  39.         """Will be implemented by child classes. Don't write anything here.
  40.         There is will add an item with frequency=1 if item not in list,
  41.         otherwise it will increment the frequency count for the item.
  42.         """
  43.         pass

  44.     def get_item_frequency(self, item):
  45.         """Returns Frequency of item, if found else returns 0.
  46.         NOTE: Don't use this when writing your add methods.
  47.         That is, you should scan through the list directly when adding.
  48.         Using this method to check for existence of an item will be
  49.         very inefficient... think about why.
  50.         """

  51.         # ---start student section---
  52.         pass
  53.         # ===end student section===

  54.     def get_xy_for_plot(self):
  55.         x = []
  56.         y = []
  57.         curr_item = self.head
  58.         while not curr_item is None:
  59.             x.append(curr_item.item)
  60.             y.append(curr_item.frequency)
  61.             curr_item = curr_item.next_node
  62.         return x, y

  63.     def _get_index_width(self):
  64.         length = self.__len__()
  65.         max_power_of_ten = 1
  66.         divisor = 10
  67.         while length // divisor > 0:
  68.             divisor *= 10
  69.             max_power_of_ten += 1
  70.         return max_power_of_ten + 2
  71.         

  72.     def __str__(self):
  73.         """Returns the items together with their letter frequencies."""
  74.         item_strs = []
  75.         current = self.head
  76.         node_num = 1
  77.         index_width = self._get_index_width()
  78.         while not current is None:
  79.             line_str = '{:>{width}}:  {}'.format(node_num,
  80.                                                  str(current),
  81.                                                  width=index_width)
  82.             item_strs.append(line_str)
  83.             current = current.next_node
  84.             node_num += 1
  85.         return '\n'.join(item_strs)

  86.     def __len__(self):
  87.         """Returns the number of nodes in the freq. list. Zero if empty."""
  88.         current = self.head
  89.         length = 0
  90.         while not current is None:
  91.             length += 1
  92.             current = current.next_node
  93.         return length


  94. #-------------------------------------------------------------------------
  95. class UnsortedFreqList(FreqList):

  96.     """FreqList that adds new items to the front of the list"""

  97.     def add(self, new_item):
  98.         """
  99.         Adds the given `letter` with a frequency of 1 as a FreqNode object
  100.         to the list. If the given `letter` is already in the list, the frequency
  101.         is incremented by 1. If not in the list then the item is added at start

  102.         >>> f = UnsortedFreqList()
  103.         >>> f.add('a')
  104.         >>> print(f)
  105.           1:  'a' = 1
  106.         >>> f.add('b')
  107.         >>> print(f)
  108.           1:  'b' = 1
  109.           2:  'a' = 1
  110.         >>> f.add('a')
  111.         >>> print(f)
  112.           1:  'b' = 1
  113.           2:  'a' = 2
  114.         """
  115.         # ---start student section---
  116.         pass
  117.         # ===end student section===


  118. #-------------------------------------------------------------------------
  119. class NicerUnsortedFreqList(FreqList):

  120.     """FreqList that adds new items at the end of the list"""

  121.     def add(self, new_item):
  122.         """
  123.         If the given `letter` is already in the list, the frequency is
  124.         incremented by 1.  If not in list, the item is added to the end of the
  125.         list with a frequency of 1.

  126.         >>> f = NicerUnsortedFreqList()
  127.         >>> f.add('a')
  128.         >>> print(f)
  129.           1:  'a' = 1
  130.         >>> f.add('b')
  131.         >>> print(f)
  132.           1:  'a' = 1
  133.           2:  'b' = 1
  134.         >>> f.add('a')
  135.         >>> print(f)
  136.           1:  'a' = 2
  137.           2:  'b' = 1
  138.         """
  139.         # ---start student section---
  140.         pass
  141.         # ===end student section===


  142. #-------------------------------------------------------------------------
  143. class SortedFreqList(FreqList):

  144.     """FreqList that keeps items in order, sorted by their frequencies"""

  145.     def _insert_in_order(self, freq_node):
  146.         """ Takes a FreqNode and inserts in to the list so that
  147.         items are sorted from largest to smallest
  148.         """
  149.         # so we don't have to lookup each time
  150.         freq_of_item = freq_node.frequency

  151.         # check to see if larger than first freq in list
  152.         if freq_of_item > self.head.frequency:
  153.             freq_node.next_node = self.head
  154.             self.head = freq_node
  155.         else:
  156.             curr_freq = self.head
  157.             inserted = False
  158.             while (curr_freq.next_node is not None) and not(inserted):
  159.                 if freq_of_item > curr_freq.next_node.frequency:
  160.                     # insert here
  161.                     freq_node.next_node = curr_freq.next_node
  162.                     curr_freq.next_node = freq_node
  163.                     inserted = True
  164.                 else:
  165.                     curr_freq = curr_freq.next_node
  166.             # got to end and didn't find
  167.             if not inserted:
  168.                 freq_node.next_node = None  # as now at end of list
  169.                 curr_freq.next_node = freq_node

  170.     def add(self, new_item):
  171.         """
  172.         If the list is empty then make a new FreqNode and insert it at head.
  173.         If the given `letter` is already in the list, the frequency
  174.         is incremented by 1.
  175.         If needed, the node is removed and then inserted
  176.         in to its sorted position - using _insert_in_order.
  177.         If not already in freq list then adds the given `letter` with a
  178.         frequency of 1 as a FreqNode object to the end of the list.

  179.         >>> f = SortedFreqList()
  180.         >>> f.add('a')
  181.         >>> print(f)
  182.           1:  'a' = 1
  183.         >>> f.add('b')
  184.         >>> print(f)
  185.           1:  'a' = 1
  186.           2:  'b' = 1
  187.         >>> f.add('b')
  188.         >>> print(f)
  189.           1:  'b' = 2
  190.           2:  'a' = 1
  191.         >>> f.add('a')
  192.         >>> print(f)
  193.           1:  'b' = 2
  194.           2:  'a' = 2
  195.         >>> f.add('a')
  196.         >>> print(f)
  197.           1:  'a' = 3
  198.           2:  'b' = 2
  199.         """
  200.         # ---start student section---
  201.         pass
  202.         # ===end student section===

  203. #-------------------------------------------------------------------------
  204. # End of Class definitions
  205. #=========================================================================


  206. def time_freq_build(freq_list_class, doc, n_chars):
  207.     """Calculate the letter frequencies using the supplied freq_list_class and
  208.     document (in the form of a sting called doc).
  209.     Returns a freq_list and the time_taken in seconds.
  210.     """
  211.     # create a new freq_list instance of the given class
  212.     freq_list = freq_list_class()
  213.     if n_chars == 1:
  214.         # do a simple scan for single characters
  215.         start = time.perf_counter()
  216.         for char in doc:
  217.             freq_list.add(char)
  218.         end = time.perf_counter()
  219.     elif n_chars > 1:
  220.         # do a scan for given multiples of characters
  221.         start = time.perf_counter()
  222.         for i in range(0, len(doc) - n_chars):
  223.             chars = doc[i:i + n_chars]
  224.             freq_list.add(chars)
  225.         end = time.perf_counter()
  226.     else:
  227.         raise ValueError("Number of characters must be a positive integer")
  228.     time_taken = end - start
  229.     return freq_list, time_taken


  230. def plot_freq_list(freq_list):
  231.     """ Plots a bar chart showing item frequency.
  232.     Will take any of the various freq_list classes, eg, unsorted, sorted etc
  233.     """
  234.     from matplotlib import pyplot
  235.     (x, y) = freq_list.get_xy_for_plot()
  236.     item_list_nums = list(range(len(x)))
  237.     width = 0.8
  238.     pyplot.bar(item_list_nums, y, width)
  239.     pyplot.title("Frequency Distribution")
  240.     pyplot.xlabel('Item')
  241.     tick_positions = [i + width / 2 for i in item_list_nums]
  242.     pyplot.xticks(tick_positions, x)
  243.     pyplot.ylabel('Frequencies')
  244.     pyplot.draw()
  245.     pyplot.show()


  246. def plot_truncated_freq_list(freq_list, n=26):
  247.     """Plots a bar chart showing item frequency for the top n items.
  248.     Will take any of the various freq_list classes, eg, unsorted, sorted etc
  249.     """
  250.     from matplotlib import pyplot
  251.     (raw_x, raw_y) = freq_list.get_xy_for_plot()
  252.     # only use the first n items
  253.     x = raw_x[:n]
  254.     y = raw_y[:n]

  255.     # show with ' marks so spaces can be seen
  256.     if len(x[0]) > 1:
  257.         x = [repr(item) for item in x]

  258.     item_list_nums = list(range(len(x)))
  259.     width = 0.8
  260.     pyplot.bar(item_list_nums, y, width)
  261.     pyplot.title("Frequency Distribution (top " + str(n) + " items)")
  262.     pyplot.xlabel('Item')
  263.     tick_positions = [i + width / 2 for i in item_list_nums]
  264.     pyplot.xticks(tick_positions, x)
  265.     pyplot.ylabel('Frequencies')
  266.     pyplot.draw()
  267.     pyplot.show()



  268. def print_test_header(filename, doc):
  269.     """Does what it says."""
  270.     print('\n' * 2)
  271.     print('-' * 60)
  272.     print('Tests for: ' + filename)
  273.     print('Doc size:  {} chars'.format(len(doc)))
  274.     print('-' * 60)





  275. def run_a_test(doc, freq_class, n_chars, verbose=True):
  276.     """Calls the freq_list builder for the given doc and n_chars.
  277.     Times how long it takes and prints the time taken.
  278.     If verbose == True then prints out the resulting freq list.
  279.     """

  280.     freq_list, total_time = time_freq_build(freq_class, doc, n_chars)

  281.     n_items = len(freq_list)
  282.     class_name = re.compile(r"<class '__main__\.(?P<id>.*)'>")
  283.     ans = class_name.search(str(type(freq_list)))
  284.     class_type = ans.group('id')
  285.     print('  {}, {} char(s) -> t = {:>.4f}s  ({} items)'.format(class_type,
  286.                                                                 n_chars,
  287.                                                                 total_time,
  288.                                                                 n_items))
  289.     if verbose:
  290.         print()
  291.         print(freq_list)

  292.     # use something like the following for showing graphs
  293.     # you will need matplotlib installed...
  294.     # plot_truncated_freq_list(freq_list, 10)
  295.     # plot_freq_list(freq_list)



  296. def run_tests(filename, verbose=True):
  297.     """Runs sorted/unsorted * n char tests
  298.     If verbose == True then prints out the resulting freq list."""
  299.     # to save reloading the corpus for each test simply pre load and send
  300.     # it off to be analysed
  301.     f = open(filename, 'r', encoding='utf-8')
  302.     doc = format_document(f.read())
  303.     # feel free to print doc here to see what it looks like
  304.     # maybe only for the smallest file:)
  305.     # print(doc)
  306.     f.close()

  307.     print_test_header(filename, doc)
  308.     run_settings = []

  309.     # Uncomment lines for tests that you want to run
  310.     # you can run one after the other if you like...
  311.     # run_settings.append((UnsortedFreqList, 1, verbose))
  312.     # run_settings.append((NicerUnsortedFreqList, 1, verbose))
  313.     # run_settings.append((SortedFreqList, 1, verbose))
  314.     # run_settings.append((UnsortedFreqList, 2, verbose))
  315.     # run_settings.append((NicerUnsortedFreqList, 2, verbose))
  316.     # run_settings.append((SortedFreqList, 2, verbose))

  317.     for settings in run_settings:
  318.         run_a_test(doc, *settings)
  319.     print('=' * 60)




  320. ################################################################################
  321. # DO NOT MODIFY ANYTHING in this area
  322. #-------------------------------------------------------------------------------
  323. def format_document(input_doc):
  324.     """ Re-formats `input_doc` by collapsing all whitespace characters into a
  325.     space and stripping all characters that aren't letters or punctuation.
  326.     Converts all uppercase characters in the file to lower case.
  327.     """
  328.     # Collapse whitespace
  329.     reduced_doc = re.compile(r'\s+', re.UNICODE).sub(' ', input_doc)
  330.     # http://www.unicode.org/reports/tr44/#General_Category_Values
  331.     allowed_categories = ('Lu', 'Ll', 'Lo', 'Po', 'Zs')
  332.     d = ''.join([c.lower() for c in reduced_doc
  333.                  if category(c) in allowed_categories])
  334.     return d
  335. ################################################################################
  336. ################################################################################

  337. if __name__ == '__main__':

  338.     os.environ['TERM'] = 'linux'  # Suppress ^[[?1034h

  339.     # Uncomment the next line to run the doctests
  340.     doctest.testmod()  
  341.     # Can enter an infinite loop if something isn't implemented correctly
  342.     # So test on small data file first

  343.     # Uncomment the files you want to test
  344.     # ------------------------------------
  345.     # run_tests("le_rire.txt", verbose=True)         # smallest corpus
  346.     # run_tests("ulysses.txt", verbose=True)         # medium corpus
  347.     # run_tests("war_and_peace.txt", verbose=True)   # one of the longest
  348.     # books in english
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2015-3-24 09:52:49 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-24 09:55:23 | 显示全部楼层

回帖奖励 +1 鱼币

好复杂的赶脚啊

评分

参与人数 1鱼币 +5 收起 理由
WWCZHC + 5 我也是零基础......

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-3-24 09:57:54 | 显示全部楼层

灌水是不好的......这只是每周小测试里面的一道题其实不是很难........
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-24 10:00:27 | 显示全部楼层
WWCZHC 发表于 2015-3-24 09:57
灌水是不好的......这只是每周小测试里面的一道题其实不是很难........

我是0基础,才学的,看不懂呢,回帖是赚鱼币做习题,才做到第4课就断更了,求打赏

评分

参与人数 4鱼币 +35 收起 理由
戴宇轩 + 5 热爱鱼C^_^
1012662902 + 5 支持楼主!
~风介~ + 20 支持楼主!
WWCZHC + 5 热爱鱼C^_^

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2015-3-24 10:02:41 | 显示全部楼层
你就不能和我一样买个会员吗 180多一点.......
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-24 10:05:36 | 显示全部楼层
WWCZHC 发表于 2015-3-24 10:02
你就不能和我一样买个会员吗 180多一点.......

下个月买啊,这个月零花钱快完了

评分

参与人数 1鱼币 +30 收起 理由
~风介~ + 30 继续努力!:)

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-3-24 11:50:22 | 显示全部楼层
顶起来~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-24 12:41:13 | 显示全部楼层
lvquanchao 发表于 2015-3-24 10:00
我是0基础,才学的,看不懂呢,回帖是赚鱼币做习题,才做到第4课就断更了,求打赏

可以回答别人的问题~~有些问题挺简单的~~当然这要求你常来逛坛子~~另外解答别人的问题自己也是在学习的~~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-3-24 12:56:16 | 显示全部楼层
亲爱的们我明天就要交作业了.......千万不要沉啊~~~~~~~~~~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-24 16:36:21 | 显示全部楼层

回帖奖励 +1 鱼币

太长不看症晚期患者。(其实是英语渣。。)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-24 16:38:02 | 显示全部楼层

回帖奖励 +1 鱼币

看不懂, 目前只能看几行的代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-24 18:42:52 | 显示全部楼层

回帖奖励 +1 鱼币

爱莫能助
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-3-24 19:05:48 | 显示全部楼层
亲爱的朋友们明天我打算交白卷了~~~{:1_1:}
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-25 19:22:41 | 显示全部楼层

回帖奖励 +1 鱼币

支持楼主,话说我什么时候可以有能力解决这样的额问题啊,,大神养成记...
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-26 11:47:13 | 显示全部楼层

回帖奖励 +1 鱼币

好长啊,看不来
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-27 20:18:33 | 显示全部楼层

回帖奖励 +1 鱼币

WWCZHC 发表于 2015-3-24 12:56
亲爱的们我明天就要交作业了.......千万不要沉啊~~~~~~~~~~

问作业不好吧= =
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 0 反对 1

使用道具 举报

 楼主| 发表于 2015-3-30 07:32:52 | 显示全部楼层
netikid 发表于 2015-3-27 20:18
问作业不好吧= =

哪里不好了一样是问题......
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-3-30 07:35:05 | 显示全部楼层
  1. class UnsortedFreqList(FreqList):

  2.     """FreqList that adds new items to the front of the list"""

  3.     def add(self, new_item):
  4.         """
  5.         Adds the given `letter` with a frequency of 1 as a FreqNode object
  6.         to the list. If the given `letter` is already in the list, the frequency
  7.         is incremented by 1. If not in the list then the item is added at start

  8.         >>> f = UnsortedFreqList()
  9.         >>> f.add('a')
  10.         >>> print(f)
  11.           1:  'a' = 1
  12.         >>> f.add('b')
  13.         >>> print(f)
  14.           1:  'b' = 1
  15.           2:  'a' = 1
  16.         >>> f.add('a')
  17.         >>> print(f)
  18.           1:  'b' = 1
  19.           2:  'a' = 2
  20.         """
  21.         # ---start student section---
  22.         
  23.         if self.head == None:
  24.             self.head =FreqNode(new_item)
  25.         else:
  26.             found = False
  27.             current_node = self.head
  28.             while current_node!=None:
  29.                 if current_node.item == new_item:
  30.                     current_node.frequency+=1
  31.                     found = True
  32.                 current_node=current_node.next_node
  33.             if not found:
  34.                 new_node = FreqNode(new_item)
  35.                 new_node.next_node = self.head
  36.                 self.head = new_node
  37.                
  38.         
  39.         # ===end student section===
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-3-30 07:35:36 | 显示全部楼层
  1. class NicerUnsortedFreqList(FreqList):

  2.     """FreqList that adds new items at the end of the list"""

  3.     def add(self, new_item):
  4.         """
  5.         If the given `letter` is already in the list, the frequency is
  6.         incremented by 1.  If not in list, the item is added to the end of the
  7.         list with a frequency of 1.

  8.         >>> f = NicerUnsortedFreqList()
  9.         >>> f.add('a')
  10.         >>> print(f)
  11.           1:  'a' = 1
  12.         >>> f.add('b')
  13.         >>> print(f)
  14.           1:  'a' = 1
  15.           2:  'b' = 1
  16.         >>> f.add('a')
  17.         >>> print(f)
  18.           1:  'a' = 2
  19.           2:  'b' = 1
  20.         """
  21.         # ---start student section---
  22.         if self.head == None:
  23.             self.head =FreqNode(new_item)
  24.         else:
  25.             found = False
  26.             current_node = self.head
  27.             while current_node!=None:
  28.                 if current_node.item == new_item:
  29.                     current_node.frequency+=1
  30.                     found = True
  31.                 current_node=current_node.next_node
  32.             if not found:
  33.                 new_node = FreqNode(new_item)
  34.                 current_node = self.head
  35.                 while current_node.next_node!= None:
  36.                     current_node=current_node.next_node
  37.                 current_node.next_node = new_node
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-15 09:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表