- Understand how to calculate the sum of a list through reviewing Python grammar
- Calculate the sum of list
Source code
list1 = [1, 2, 3, 4, 5, 6] # initialization of a list
total = 0 # initialization of total variable
for i in list1: # iteration of each element of the list
total += i # add the element to the total variable
print("total =", total) # show the result
total = sum(range(1, 7)) # simple implementation
print("total = %d" % total) # show in a different way
How to execute
- After making a text file (source code), e.g. ex1.py, by using a text editor, you can type the following command on the terminal.
$ python3 ex1.py
total = 21
total = 21
Note
- Please use
python3
explicitly, otherwise Python version 2 will be used - list is defined as a set of data (object) with []
for var in list
: can take each element iteratively and assign the element to varsum
is a method to calculate the sum of list elements, but the element should be numerical value when you applysum
method tolist
objectrange(start, end)
generates list of consecutive numbers from start to (end - 1)total += i
can be replaced bytotal = total + i
- One of the important tips here is the combination of
list
andfor
in order to process each element in a list, so that it sums all the elements in the list here, but this concept is applicable to other algorithms.
- Calculate mean of list elements
Expected result
$ python day1_1_exercise1.py
list = [1, 2, 3, 4, 5, 6]
mean = 3.5
- Calculate standard deviation of list elements
Hint
- In order to calculate the square root, the following processes are needed:
- import math
- call math.sqrt() method
For example
import math print(math.sqrt(2)) # => 1.4142135623730951
Expected result
$ python day1_1_exercise2.py list = [1, 2, 3, 4, 5, 6] sd = 1.707825
- Calculate the number of combinations and permutations. For example, 5C2,5P2.
Expected result
$ python day1_1_advanced1.py 5P2 = 20.000000 5C2 = 10.000000