python求众数问题实例,python实例


本文实例讲述了python求众数问题的方法,是一个比较典型的应用。分享给大家供大家参考。具体如下:

问题描述:

多重集中重数最大的元素称为众数...就是一个可以有重复元素的集合,在这个集合中重复的次数最多的那个数就叫它的众数...
如S = [1,2,2,2,3,5] 重数是2,其重数为3

实例代码如下:

list_num = []
list_num_count = 0
dict_num ={}
#从文件读入,文件第一行为集合中元素的个数,以后每一行为一个元素
list_num_count = int(open('input.txt','r').readline())
for line_num, line in enumerate(open("input.txt",'r')):
  if line_num > 0:
    list_num += line.split()
#将读到的元素加入的字典中
for item in list_num:
  if dict_num.has_key(item):
    dict_num[item] += 1
  else:
    dict_num.setdefault(item,1)
  pass

#找到出现次数最多的那个数,找到重数
dict_sort_by_top = {}
top_value = 0
for valus in dict_num.itervalues():
  if valus> top_value:
    top_value = valus
  pass

#根据重数找到众数...这是因为考虑到可能有多个元素有相同多的重数
the_pop_num = 0
the_pop_num_count = 0
for keys,values in dict_num.iteritems():
  if values == top_value:
    print 'the pop num is %s,and the appear num is %s' % (keys,values)
    the_pop_num = keys
    the_pop_num_count = values
#输出到文件,第一行为从数,第二行为重数
write_line = '%s\n%s' %(the_pop_num, the_pop_num_count)
open("output.txt",'w').write(write_line)

这里假设有同级目录文件input.txt内容如下:

8
11
37
2
37
2
45
99
37

第一行的8代表元素个数,其后每一行有一个元素。

测试环境为Python2.7.6,

Python程序针对input.txt文件操作的运行结果如下:

the pop num is 37,and the appear num is 3

同时生成output.txt文件记录了众数37及其重复次数3。

希望本文所述对大家的Python程序设计有所帮助。


python类的实例化问题

你没有理解类变量和实例变量之间的关系。
第一个例子里面init中append是对类变量的操作。因此实例对象newmen1/2并没有自己的变量a,访问的都是类变量。
这时你如果显示类变量,
print Men.a,newmen1.a,newmen2.a都是一样的。指向同一变量。
第二个例子中的init生成了对象自己的变量a,注意'='! 当实例对象调用init时,每个实例对象都拥有了自己的变量a,你再也无法再通过实例对象来访问到类变量了。事实上这种写法是很不好的。
这时你可以再一次显示类变量,
print Men.a,newmen1.a,newmen2
>> 0 1 2
如果你希望所有对象共用类变量,你可以写
class Men:
a=0
def __init__(self,b):
Men.a=b
def sayHi(self):
print'Hello,my name is',Men.a
这样反而清晰,不要把实例对象公有的变量用self来表示。只会把你自己搞晕。
 

有关python实例化一个对象的问题

定义一个类封装所有的属性,然后把这个类的对象作为返回值。
不知道是不是你要的意思:

class Node:
def __init__(self, nodes, city, state, description = None):
self.nodes = nodes
self.city = city
self.state = state
self.description = description

def node_by_name(nodes, city, state):
# some other process
description = 'NORTH CAMBRIDGE'
return Node(nodes, city, state, description)

ans = node_by_name('testNode', 'CAMBRIDGE', 'MA')

print ans.state, ans.description
 

评论关闭