ボックス について

性別:男性 考えていること、思っていることを文章にしていきます。

Python pygame No.1 画面設定

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by devel on 2017/04/08.
import pygame
from pygame.locals import *
import sys

FPSCLOCK = pygame.time.Clock() # FPSを指定の準備

def main():
    pygame.init() #初期化

    # メイン画面のサイズ set_modeで一つだけ作れる
    screen = pygame.display.set_mode((600,500)) 
    pygame.display.set_caption('Test') # タイトルバーの文字



    while True: # 無限ループ
        
        screen.fill((0, 0, 0)) # 背景の色


        # 挙動によって処理を呼び出せる
        # 閉じるボタンとかクリックとか
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()


        pygame.display.update()# 画面の表示をアップデート
        FPSCLOCK.tick(10) #  FPSを指定

if __name__ == '__main__':
    main()

 

 

 

 

Python sorted関数 二重配列

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by devel on 2017/04/07.


def main():
    b = [('cathy', '4'), ('eijiro', '2'), ('alice', '6'), ('dad', '3'), ('betty', '5'), ('franca', '1')]
    
    
    b2 = list(map(lambda x:(x[0],int(x[1])), b)) #map関数で二重リストの中身を指定してintに変換 (x[0], x[1])

    print(sorted(b, key=lambda x:(x[1], x[0]), reverse=True)) # lambdaでソートを適応する場所を指定している。
    print(b2)
    
    
    """
    [('alice', '6'), ('betty', '5'), ('cathy', '4'), ('dad', '3'), ('eijiro', '2'), ('franca', '1')]
    [('cathy', 4), ('eijiro', 2), ('alice', 6), ('dad', 3), ('betty', 5), ('franca', 1)]
    """

if __name__ == '__main__':
    main()

 

うーん・・・

二重配列はややこしい・・・

python3.5と3.6で挙動が違うのもややこしやー

 

JavaScript 関数型プログラミング ストリーム

ストリームの値の移り変わり

 

/**
 * Created by devel on 2017/04/01.
 */
var expect = require('expect.js');


var succ = (n)=>{
    return n + 1
}
var enumFrom =(n)=>{
    return [n, (_)=>{
            return enumFrom(succ(n))
        }]
}
a = enumFrom(1) // nに1を代入

console.log(a)                   // [ 1, [Function] ]
console.log(a[0])                // 1
console.log('') 
console.log(a[1]())              // [ 2, [Function] ]
console.log(a[1]()[0])           // 2
console.log('')
console.log(a[1]()[1]())         // [ 3, [Function] ]
console.log(a[1]()[1]()[0])      // 3
console.log('')
console.log(a[1]()[1]()[1]())    // [ 4, [Function] ]
console.log(a[1]()[1]()[1]()[0]) // 4

 

 

 

 

JavaScript 関数型プログラミング 不変なデータ使いかた

不変なデータの定義と使い方

var empty = (_)=>{
    return null
}

var get = (key, obj) =>{
    return obj(key)
}

var set = (key, value, obj)=>{
    return (key2) =>{
        if(key===key2){
            return value
        }else{
            return get(key2,obj) //関数setに引数を渡している場合、セットされているobjの中身はempty
        }
    }
}

a = set('a','b',empty) //emptyにかっこはつけない 関数が返っている
console.log(get('a', a)) // a
console.log(get('hi', a)) // null

setで返すものは関数。

setすると、return (key2) =>{…}の”…”部分に関数を呼び出すときに渡した引数、key、value、objの値が設定される(設定?定義?される)。

getするときにkeyが違うときには、get(key2, empty)となり、empty(key2)、そしてnullを返す。

 

 

 

関数型プログラミング JavaScript リファクタリング

ラムダ式で書いた関数をリファクタリングしていっている。下にいくほど文章量が少なくなることが分かる。

/**
 * Created by devel on 2017/03/28.
 */
var expect = require('expect.js');
var anArray = [2, 3, 4, 5, 7]

var sum1 = (array) =>{
    var result = 0
    for(var index=0; index<array.length; index++){
        result = result + array[index]
    }
    return result
}

console.log(sum1(anArray))

var sum2 = (array) =>{
    var result = 0
    array.forEach((item)=>{
        result = result + item
    })
    return result
}

console.log(sum2(anArray))

var sum3 = (array) =>{
    return array.reduce((x, y)=>{
        return x + y
        })
}

console.log(sum3(anArray))

expect(
    sum3(anArray)
).to.eql(
    21
)

一番下は単体テスト。

 

 

 

 

Python Super Stopwatch

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# - A simple stopwatch program.

import time


def main():
    # Display the program's instructions
    print('Press Enter to begin. Afterwards,'
          ' press ENTER to click the stopwatch,'
          'Press ctrl-c to quit.')
    input()
    print('started.')
    starttime = time.time()
    lasttime = starttime
    lapNUM = 1

    # Start Tracking the lap times.
    try:
        while True:
            input()
            laptime = round(time.time() - lasttime, 2)
            totaltime = round(time.time() - starttime, 2)
            print(f'Lap {lapNUM}: {totaltime} ({laptime})', end='')
            lapNUM += 1
            lasttime = time.time()

    except KeyboardInterrupt:
        # Handle the Ctrl-c exception to keep its error message from displaying
        print('\nDone.')



if __name__ == '__main__':
    main()

 

簡単なストップウォッチ。エンターキーを押すとスタートする。

ラップタイムもエンターキーを押す。

 

Ctrlとcキーを同時に押すとストップして”Done.”が表示される。

 

Python Fetching Current Weather Data

本に書いてあるようにはできなかった。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Prints the weather for a location from the command line

import json
import requests
import sys
import pprint

def main():
    # Compute location from command line arguments.
    if len(sys.argv) < 2:
        print('Usage: quickWeather.py location')
        sys.exit()
    #location = ' '.join(sys.argv[1:])

    # Download the Json data from OpenWeatherMap.org's API.
    url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=400040' # 久留米

    print(url)
    response = requests.get(url)
    response.raise_for_status()

    # Load JSON data into a python variable.
    weatherData = json.loads(response.text)
    

    # Print weather descriptions
    w = weatherData['forecasts']
    location = weatherData['location']['city']
    print(f'場所 : {location}')
    for i in range(3):
        date = w[i]['dateLabel']
        telop = w[i]['telop']

        print(f'{date} : {telop}')


if __name__ == '__main__':
    main()

OpenwetherMapをうまく扱えなかったので

Livedoor Weather Web Service / LWWS

で代用した。

改善点

・IDを自動で設定し入力。
例えば、 北海道と入力すると、対応するIDを見つけて、urlに代入する。

・tkinterなどを使ってGUIを作り、入力しやすくする。

 

 

 

Python 3.6 f文字列 formatted string

Pythonで文字列に数値を埋め込む方式は、”%”やstr.format()があった。

Python 3.6では新しくf文字列(formatted string)が追加された。

これは、r’ ‘のように、先頭にfをつけてf’ ‘のように入力する。{}で囲まれた部分でPythonの式を評価し文字列として出力する。

%方式 str.format()方式 f文字列方式

# !/user/bin/env python

def main():
    str = 'hello'

    # 出力 -> hello

    # %方式
    print('%s' %(str))

    # str.format()方式
    print('{}'.format(str))

    # f文字列方式
    print(f'{str}')



if __name__ == '__main__':
    main()

f文字列方式

# !/user/bin/env python

def main():
    a = 1
    b = 'hello'
    c = 2.000
    d = 64

    # 変数を{}の中に入れられる。
    print(f'{a} {b} {c}')
    # 1 hello 2


    # {]の中で計算できる。
    print(f'{1+2}')
    # 3


    # 10文字の範囲で右そろえ
    print(f'{a:10}')
    #         1


    # 10文字の範囲で左揃え
    print(f'{a:<10} {b:<10}')
    #1          hello


    # 10文字の範囲で中央揃え
    print(f'{a:^10} {b:^10}')
    #    1        hello


    # 小数点表示範囲
    print(f'{c:.1f} {c:.2f} {c:.3f}')
    # 2.0 2.00 2.000


    # 8進数、16進数変換して表示
    print(f'10進数:{d} 8進数:{d:o}  16進数:{d:x}')
    # 10進数:64 8進数:100  16進数:40


if __name__ == '__main__':
    main()

 

 

 

Python Removing the Header from CSV Files

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -Removes the header from all CSV files in the current working directory.

import csv
import os


def main():
    os.makedirs('headerRemoved', exist_ok=True)

    # Loop through every file in the current working directory
    for csvfilemane in os.listdir('.'):
        if not csvfilemane.endswith('.csv'):
            continue
        print(f'Removing header from {csvfilemane} ...')

        # Read the CSV file in (skipping first row).
        csvRows = []
        with  open(csvfilemane) as csvFileobj:
            readerobj = csv.reader(csvFileobj)
            for row in readerobj:
                if readerobj.line_num == 1:
                    continue
                csvRows.append(row)

        # Write out the CSV file.
        with open(os.path.join('headerRemoved', csvfilemane),
                               'w', newline='') as csvFileobj:
            csvWriter = csv.writer(csvFileobj)
            for row in csvRows:
                csvWriter.writerow(row)
        

if __name__ == '__main__':
    main()

カレントディレクトリの.csvファイルのヘッダーを消すスクリプト。

もともとのファイルは変更されず、headerRemovedのフォルダに変更したファイルが保存される。