ITS·黑客

python编程练习第1个题目

2017-05-18  本文已影响357人  JEZAU

中午参加的编程比赛的题目
用的vba 现在用python做一下 就当复习啦
欢迎更简单的算法
我在写代码过程中出的错误都写在注释里啦

题目:

社交网络中我们给每个人定义了一个“活跃度”,现希望根据这个指标把人群分为两大类,即外向型(outgoing,即活跃度高的)和内向型(introverted,即活跃度低的)。要求两类人群的规模尽可能接近,而他们的总活跃度差距尽可能拉开。

输入格式:
输入第一行给出一个正整数N(2 <= N <= 105)。随后一行给出N个正整数,分别是每个人的活跃度,其间以空格分隔。题目保证这些数字以及它们的和都不会超过231。

输出格式:
按下列格式输出:

Outgoing #: N1
Introverted #: N2
Diff = N3
其中 N1 是外向型人的个数;N2 是内向型人的个数;N3 是两群人总活跃度之差的绝对值。

输入样例1:
10
23 8 10 99 46 2333 46 1 666 555
输出样例1:
Outgoing #: 5
Introverted #: 5
Diff = 3611

输入样例2:
13
110 79 218 69 3721 100 29 135 2 6 13 5188 85
输出样例2:
Outgoing #: 7
Introverted #: 6
Diff = 9359```


我的代码:

n = int(input('数据个数'))
a = []
for i in range(n):
a.append(int(input('请输入第 %d 个数据'% (i+1))))

注意a/n的数据类型,一定要转换,否则出错

a不可以直接list(input('')),否则出来的是一个带引号和逗号的list

我觉得可以用切片,但是也挺麻烦的,想知道有没有简单一点的方法

a.sort()
sum1 = 0
sum2 = 0
sum3 = 0

上面的sum1,sum2,sum3都要定义,因为第一次出现的式子右边存在

if n % 2 == 0: #取余数两种方法1. x%y 2. divmod(x,y)
x = n/2
for i in range(int(x)): #注意x要int, range的参数只能是int类型,否则出错
sum1 = sum1 + a[i]
for i in range(n):
sum2 = sum2 + a[i]
diff = sum2 - sum1 * 2
print('outgoing: %d \n introverted: %d \n diff = %d'%(x,x,diff))

不可以用同一个字母变量,循环相当于赋值过程,每个都一样

if n % 2 != 0:
x = int(n/2)
for i in range(x):
sum1 = sum1 + a[i]
for i in range(n):
sum2 = sum2 + a[i]
for i in range(x+1):
sum3 = sum3 + a[i]
diff1 = sum2 - sum1 * 2
print('outgoing: %d \n introverted: %d \n diff = %d'%(x+1,x,diff1))


后来发现..肯定是outgoing里的人多一个diff比较大
所以改一下代码
瞬间简单不少

n = int(input('数据个数'))
a = []
for i in range(n):
a.append(int(input('请输入第 %d 个数据'% (i+1))))

a.sort()
sum1 = 0
sum2 = 0
sum3 = 0

x = int(n/2)
for i in range(x):
sum1 = sum1 + a[i]
for i in range(n):
sum2 = sum2 + a[i]
diff = sum2 - sum1 * 2
if n % 2 == 0:
print('outgoing: %d \n introverted: %d \n diff = %d'%(x,x,diff))
if n % 2 != 0:
print('outgoing: %d \n introverted: %d \n diff = %d'%(x+1,x,diff))```

再次研究了一下python的输入发现只能输入字符串类型
生成列表直接用list会带入逗号
想到可以用split方法,但是生成的还是字符串类型,突然,it occurred to me that!!
用列表生成式呀!
于是有了下面的代码:

>>> a = '1,2,3'
>>> b = a.split(',')
>>> b
['1', '2', '3']
>>> c = [int(x) for x in b]
>>> c
[1, 2, 3]```

所以
代码可以改成

a = [int(x) for x in input('请输入一个逗号分隔的序列').split(',')]```
测试:

>>> a = [int(x) for x in input('请输入一个逗号分隔的序列').split(',')]
请输入一个逗号分隔的序列1,2,3,4,5,6
>>> a
[1, 2, 3, 4, 5, 6]
>>> 

于是产生了最简单的最终版

n = int(input('数据个数'))
a = [int(x) for x in input('请输入一个空格分隔的序列').split(' ')]

a.sort()
sum1 = 0
sum2 = 0
sum3 = 0

x = int(n/2)
for i in range(x):
    sum1 = sum1 + a[i]
for i in range(n):
    sum2 = sum2 + a[i]
diff = sum2 - sum1 * 2
if n % 2 == 0:
    print('outgoing: %d \n introverted: %d \n diff = %d'%(x,x,diff))
if n % 2 != 0:
    print('outgoing: %d \n introverted: %d \n diff = %d'%(x+1,x,diff))```
上一篇下一篇

猜你喜欢

热点阅读