python求反序数-python归并排序求逆序数问题

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47class nx:

count = 0

def __init__(self):

self.str_list=[]

self.N = int(raw_input().strip())

for _ in xrange(self.N):

self.str_list.append(raw_input().strip())

print self.count_inversion(self.str_list)

def merge(self, ListA, ListB):

self.newlist = []

while ListA and ListB:

if ListA[0] > ListB[0]:

self.newlist.append(ListB[0])

ListB = ListB[1:]

self.count += len(ListA)

print str(len(ListA))+"**** "

else:

self.newlist.append(ListA[0])

ListA =ListA[1:]

if ListA:

self.newlist = self.newlist + ListA

elif ListB:

self.newlist = self.newlist + ListB

return self.newlist

def merge_sort(self, A):

if len(A) == 1:

return A

else:

self.middle = len(A)/2

print "**************"

print "Ais "+str(A)

print "middle is "+ str(self.middle)

print "zuo"

print A[:self.middle]

print "you"

print A[self.middle:]

self.sa1 = self.merge_sort(A[:self.middle])

self.sa2 = self.merge_sort(A[self.middle:])

return self.merge(self.sa1, self.sa2)

def count_inversion(self, sequence):

self.merge_sort(sequence)

return self.count

if __name__ == "__main__":

nx()

结果:

Ais ["2’, "4’, "3’, "1’]

middle is 2

zuo

["2’, "4’]

you

["3’, "1’]

Ais ["2’, "4’]

middle is 1

zuo

["2’]

you

["4’]

1

2

3

4

5

6

7

8****************为什么会这样

Ais ["4", "3", "1"]

middle is 1

zuo

["4"]

you

["3", "1"]

****************

Ais ["3’, "1’]

middle is 1

zuo

["3’]

you

["1’]

我知道了,python局部变量问题

class nx:

def init(self):

self.count = 0

self.str_list=[]

self.N = int(raw_input().strip())

for _ in xrange(self.N):

self.str_list.append(raw_input().strip())

print self.count_inversion(self.str_list)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18def merge(self, ListA, ListB):

newlist = []

while ListA and ListB:

if int(ListA[0]) > int(ListB[0]):

self.count += len(ListA)

newlist.append(ListB.pop(0))

else:

newlist.append(ListA.pop(0))

return newlist + ListA + ListB

def merge_sort(self, A):

if len(A) == 1: return A

else:

middle = len(A)/2

return self.merge(self.merge_sort(A[:middle]), self.merge_sort(A[middle:]))

def count_inversion(self, sequence):

self.merge_sort(sequence)

return self.count

if name == "main":

nx()

就是个边界条件的问题,不等号加上或者去掉等号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值