@@ -56,11 +56,29 @@ def CompareTwoElements(x,y,order=0): # 0 means left smaller than right, 1 mea
56
56
57
57
def JudgeOrderForArray(array,order=0): # order 0 means small to large, 1 means large to small
58
58
i = 0
59
+ if(len(array)==0):
60
+ return 1
59
61
last_index = len(array)-1
60
62
while(i<last_index and CompareTwoElements(array[i],array[i+1],order)):
61
63
i = i+1
62
64
return i==last_index
63
65
66
+ '''
67
+ given a array, use following function to judge it is a ordered array or not
68
+ if it is ordered, gives its order:
69
+ 0 represent small to large, 1 means large to small
70
+ if it it not ordered, the order is None
71
+ '''
72
+ def JudgeAndGiveOrderForArray(array):
73
+ i=0
74
+ while((i<len(array)-1) and array[i]==array[i+1]):
75
+ i = i+1
76
+ remain_arr=array[i:]
77
+ order = (0 if (i==(len(array)-1) or len(array)==0) else (array[i]>array[i+1]))
78
+ is_order = JudgeOrderForArray(remain_arr,order)
79
+ order_val = int(order) if is_order else None
80
+ return bool(is_order),order_val
81
+
64
82
def OrderedDictReorder(ord_dict,index="key",rev=False):
65
83
from collections import OrderedDict
66
84
return OrderedDict(sorted(ord_dict.items(), key=lambda t:t[0] if index=="key" else t[1],reverse=rev))
@@ -72,6 +90,26 @@ def WriteNewDictDataToFile(ord_dict,txt_str=""):
72
90
datafile.write("%d\t%.4f\n" % (index, ord_dict[index]))
73
91
datafile.close()
74
92
93
+ '''
94
+ before call this function, use above functions to reorder the new_data
95
+ to a new txt file, and the old txt file has been reordred,
96
+ so this function only need to judge the order and decide to merge or add
97
+ the new txt data to old txt from which position(start or end)
98
+ '''
99
+ def AddNewDataToFile(old_data_txt="",add_data_txt="",new_data_txt=""):
100
+ from collections import OrderedDict
101
+ old_key_list = GetIndexToList(GetDataFromTxt(old_data_txt))
102
+ add_key_list = GetIndexToList(GetDataFromTxt(add_data_txt))
103
+ old_is_order,old_order_val = JudgeAndGiveOrderForArray(old_key_list)
104
+ add_is_order,add_order_val = JudgeAndGiveOrderForArray(add_key_list)
105
+ if(old_is_order==False):
106
+ return ("Please check the data in %s, it is not ordered!" %s (old_data_txt))
107
+ if(add_is_order==False):
108
+ return ("Please check the data in %s, it is not ordered!" %s (add_data_txt))
109
+ if(old_order_val!=1):
110
+ return ("I hope the data in %s order is larger to small for date key!" %s (old_data_txt))
111
+ if(add_order_val!=1):
112
+ return ("I hope the data in %s order is larger to small for date key!" %s (add_data_txt))
75
113
76
114
if __name__ == "__main__":
77
115
raw_data = GetDataFromTxt("xxx.txt")
@@ -111,3 +149,6 @@ if __name__ == "__main__":
111
149
112
150
#print(CompareTwoElements(1,1,0))
113
151
#print(JudgeOrderForArray([4,3,3,2],1))
152
+
153
+ print(JudgeAndGiveOrderForArray([4,3,2,1,1,1]))
154
+ print(JudgeAndGiveOrderForArray([1]))
0 commit comments