Skip to content

Instantly share code, notes, and snippets.

@masaomi
Last active May 19, 2024 09:48
Show Gist options
  • Save masaomi/75ac75aa49d3603697e24864b2345d4d to your computer and use it in GitHub Desktop.
Save masaomi/75ac75aa49d3603697e24864b2345d4d to your computer and use it in GitHub Desktop.

Day1 Part1

Goal

  • Understand how to calculate the sum of a list through reviewing Python grammar

Example1

  • 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 var
  • sum is a method to calculate the sum of list elements, but the element should be numerical value when you apply sum method to list object
  • range(start, end) generates list of consecutive numbers from start to (end - 1)
  • total += i can be replaced by total = total + i
  • One of the important tips here is the combination of list and for 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.

Exercise1

  • Calculate mean of list elements

Expected result


$ python day1_1_exercise1.py
list =  [1, 2, 3, 4, 5, 6]
mean = 3.5

Exercise2

  • Calculate standard deviation of list elements

Hint

  • In order to calculate the square root, the following processes are needed:
    1. import math
    2. 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

Advanced exercise1

  • Calculate the number of combinations and permutations. For example, 5C2,5P2.

Expected result

$ python day1_1_advanced1.py 
5P2 = 20.000000
5C2 = 10.000000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment