Python averages and sorts the integers in a list

  • 2020-04-02 14:05:54
  • OfStack

The problem

Define a one-dimensional array of int, containing 40 elements, to store the results of each student, and loop to generate 40 random integers between 0 and 100.
(1) store them in a one-dimensional array, then count the number of students with lower than average scores and output them.
(2) output the 40 achievements from high to low.

Solution (python)


#! /usr/bin python
#coding:utf-8


from __future__ import division   # Implement precise division, for example 4/3=1.333333
import random

def make_score(num):
  score = [random.randint(0,100) for i in range(num)]
  return score

def less_average(score):
  num = len(score)
  sum_score = sum(score)
  ave_num = sum_score/num
  less_ave = [i for i in score if i<ave_num]
  return len(less_ave)

if __name__=="__main__":
  score = make_score(40)
  print "the number of less average is:",less_average(score)
  print "the every socre is[from big to small]:",sorted(score,reverse=True)


Related articles: