茨の道も一歩から

インフラ構築からプログラミング(Python・JavaScript)までITに関するブログです。

96日目:Pythonプログラミング

Pythonプログラミングの講義30日目です。

今日の講義は、標準モジュールについて。内職はAtCoder復習。

【講義内容】

  • 標準モジュール

【ワンポイント】

標準モジュール

sys

import sys

print(f'sys.argv: {sys.argv}')

for i in range(1, len(sys.argv)):
    print(f'sys.argv[{i}]: {sys.argv[i]}')

print(f'sys.platform: {sys.platform}')

os

import os

print(f'os.environ: {os.environ}')
print(f'os.sep: {os.sep}')
print(f'os.altsep: {os.altsep}')
print(f'os.pathsep: {os.pathsep}')
print(f'os.linesep: {repr(os.linesep)}')
print(f'os.path.abspath: {os.path.abspath(".")}')
print(f'os.path.abspath: {os.path.abspath("test.txt")}')
print(f'os.path.abspath: {os.path.abspath("test/test.txt")}')

os.system('ping -4 localhost')
os.system('notepad.exe')
os.system('ping -4 localhost')
os.startfile('explorer.exe')
os.system('ping -4 localhost')
os.startfile('notepad.exe')
os.system('ping -4 localhost')

webbrowser

import webbrowser

webbrowser.open('https://google.com')

heapq

from heapq import heappush, heappop
from random import shuffle

data = list(range(10))
shuffle(data)

heap = []
for n in data:
    heappush(heap, n)
print(f'HEAP: {heap}')
heappush(heap, -1)
print(f'HEAP: {heap}')

heapify, heapreplace

from heapq import heapify, heappop, heapreplace

test = [5, 8, 0, 3, 6, 7, 9, 1, 4, 2]
heapify(test)
print(test)
print(heappop(test))
print(test)
print(heapreplace(test, -5))
print(test)
print(heapreplace(test, 10))
print(test)

nlargest, nsmallest

from heapq import nlargest, nsmallest

test2 = [5, 8, 0, 3, 6, 7, 9, 1, 4, 2]

print(nlargest(3, test2))
print(test2)
print(nsmallest(3, test2))
print(test2)

deque

  • 先頭と最後の要素へのアクセスが効率的
    • FIFOとして利用
from collections import deque

test = [3, 8, 2, 6, 5, 7, 1, 9]
dq = deque(test)
print(dq)

print(dq.append(5))
print(dq.appendleft(6))
print(dq.pop())
print(dq.popleft())

test = list(dq)
print(test)

【今日の積み上げ】