python数组之稀疏数组的处理代码
python数组之稀疏数组的处理代码#!/usr/bin/env python
#-*- coding:UTF-8 -*-
#数据结构------------处理稀疏数组
import copy
def SubSparse(dict_sparse_a, dict_sparse_b):
两个字典相减
dict_sparse_sub = dict()
for i in dict_sparse_a:
if i in dict_sparse_b:
dict_sparse_sub[i] = dict_sparse_a[i] - dict_sparse_b[i]
else:
dict_sparse_sub[i] = dict_sparse_a[i]
for j in dict_sparse_b:
if j not in dict_sparse_sub:
dict_sparse_sub[j] = 0 - dict_sparse_b[j]
dict_sparse_sub2 = copy.deepcopy(dict_sparse_sub)
for i in dict_sparse_sub:
if dict_sparse_sub[i] == 0:
del dict_sparse_sub2[i]
return dict_sparse_sub2
def AddSparse(dict_sparse_a, dict_sparse_b):
两个字典相加
dict_sparse_add = dict()
dict_sparse_add2 = dict()
for i in dict_sparse_a:
if i in dict_sparse_b:
dict_sparse_add[i] = dict_sparse_a[i] dict_sparse_b[i]
else:
dict_sparse_add[i] = dict_sparse_a[i]
for j in dict_sparse_b:
if j not in dict_sparse_add:
dict_sparse_add[j] = dict_sparse_b[j]
for i in dict_sparse_add:
if dict_sparse_add[i] != 0:
dict_sparse_add2[i] = dict_sparse_add[i]
return dict_sparse_add2
def CreateArray(list_sparse, allrow = 3, allcol = 4):
列表模拟数组
row = 0
while row < allrow:
list_string = raw_input("enter one array items spaced by comma: ").strip().split(,)
list_array = list()
for i in list_string:
list_array.append(int(i))
list_sparse.append(list_array);
row = 1
def CreateSparse(list_sparse):
将模拟出来的列表转为为 字典 字典的键为 数组下标
dict_sparse = dict()
for i in range(0, len(list_sparse)):
for j in range(0, len(list_sparse[i])):
if 0 != list_sparse[i][j]:
dict_sparse[(i, j)] = list_sparse[i][j]
return dict_sparse
def main():
print ok
list_sparse_a = list()
list_sparse_b = list()
print array a
CreateArray(list_sparse_a)
dict_sparse_a = CreateSparse(list_sparse_a)
print "sparse array a"
for i in sorted(dict_sparse_a):
print i, dict_sparse_a[i]
print array b
CreateArray(list_sparse_b)
dict_sparse_b = CreateSparse(list_sparse_b)
print "sparse array b"
for i in sorted(dict_sparse_b):
print i, dict_sparse_b[i]
dict_sparse_add = AddSparse(dict_sparse_a, dict_sparse_b)
print "add result"
for i in sorted(dict_sparse_add):
print i, dict_sparse_add[i]
dict_sparse_sub = SubSparse(dict_sparse_a, dict_sparse_b)
print "sub result"
for i in sorted(dict_sparse_sub):
print i, dict_sparse_sub[i]
if __name__ == __main__:
main()
补充:Web开发 , Python ,