LoginSignup
1
0

数学オンチのプログラマが数学を学習し直すらしいです【統計その1】
https://qiita.com/manzyun/items/833ae7fba582d899c618

median.py
# https://qiita.com/manzyun/items/833ae7fba582d899c618
data = [100, 300, 423, 328, 516, 412]

data.sort() # **超大事**

if len(data) % 2 == 0: # リストの要素の数の奇数・偶数判定
    # 偶数でした
    m1 = len(data) / 2
    m2 = (len(data) / 2) + 1
    # 整数に変換して位置合わせ
    m1 = int(m1) - 1
    m2 = int(m2) - 1
    print(data[m1] + data[m2]) / 2
else:
    # 奇数でした
    m = (len(data) + 1) / 2
    m = int(m) - 1
    print(data[m])

pythn3で実行

$ python
Python 3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 13:19:00) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
$ python median.py
740
Traceback (most recent call last):
  File "median.py", line 12, in <module>
    print(data[m1] + data[m2]) / 2
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

変更してみた。

median2.py
#!/usr/bin/env python
# coding: utf-8
# https://qiita.com/manzyun/items/833ae7fba582d899c618
# @imanzyun 2018年10月30日 11時31分 (JST)
# https://qiita.com/kaizen_nagoya/items/2f02d5f8af808e322e3c
# @kaizen_nagoya 2019 05 21/ 2019 12 30

data = [100, 300, 423, 328, 516, 412]

data.sort() # **超大事**

if len(data) % 2 == 0: # リストの要素の数の奇数・偶数判定
    # 偶数でした
    m1 = int(len(data) / 2)-1
    print((data[m1] + data[m1+1]) / 2)
else:
    # 奇数でした
    m = int((len(data) + 1) / 2)-1
    print(data[m])

ついでに、おまじない、処理の変更も。

直したところと付け加えたこと

##1 print の()
print文の後ろに/2があった。/2も括弧でくくった。

#2 #!/usr/bin/env python

chmod +x median2.py

とすれば、./median2.py
で実行できる。

#3 # coding: utf-8
ファイルがutf-8であれば不要なのかもしれないが、Webで公開すると、どういう文字コードで保存するシステムがあるかわからないため、おまじないとして書いておく。

# python2.7 median8.py 
  File "median8.py", line 5
SyntaxError: Non-ASCII character '\xe8' in file median8.py on line 5, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
# python2.7 median8.py 
370

2回目の実行は# coding: utf-8を加えたあとのファイル。
環境や状況によってはあった方がいい場合があるかも。

#4 m2
m1-1で済むので途中の計算はしない。

#5 mの計算
2つの式を1つに。
みにくくなるかもしれない。
好みかも。

python2, python3の違い

docker/ubuntu
# python2.7 median2.py
370
# python3.8 median2.py
370.0

docker

$ docker run -v /tmp/docker:/tmp/docker -it kaizenjapan/python23 /bin/bash

dockerを起動するOSで事前に/tmpの下に/dockerというフォルダを共有用に作成してある場合。

dockerを起動したOSで作ったファイルをそのままdocker側でも利用するため。

# cd /home/python2
# ls

文書履歴(document history)

ver. 0.01 初稿 20190521
ver. 0.02 加筆 201901229
ver. 0.03 docker加筆 201901230

最後までおよみいただきありがとうございました。

いいね 💚、フォローをお願いします。

Thank you very much for reading to the last sentence.

Please press the like icon 💚 and follow me for your happy life.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0