アットウィキロゴ
note4recurrent @ ウィキ
掲示板 掲示板 ページ検索 ページ検索 メニュー メニュー

note4recurrent @ ウィキ

Pythonアルゴリズム

最終更新:

note4recurrent

- view
だれでも歓迎! 編集

尾崎先生

テキスト正誤表

2022/07/12

# i % 3 == 0  は not i % 3 に置き換えられる

i=4
if not i % 3:
    print("True",i)
else :
    print("False",i)
i=6
if not i % 3:
    print("True",i)
else :
    print("False,i")

python では関数を前に書かなければならない。

  • Python のリストとタプル
  • [1,2,4]リスト:変更できる(他の言語の配列と考えてよい)
  • (1,2,4)タプル:変更できない
  • おみくじ 関数版
    import random
    
    def uranai():
        omikuji=["大吉","吉","中吉","凶","大凶"]
        print(omikuji[random.randint(0,len(omikuji)-1)])
        
    uranai()
    

2022/07/19

  • 仮想環境:業務ではプロジェクトやクライアントに指定された環境で作業する必要がある。異なるバージョンのPythonを使ったり、ライブラリをセットした仮想環境を作って対応することが多い。
    • 複数の開発環境を並行で使用できる(異なるバージョンをインストールするようなケース)
    • 仮想環境用のフォルダを作る。.venv はフォルダ名
      python -m venv .venv
      
    • アクティベートする
      .\.venv\Scripts\activate
      
    • ライブラリのインストール例 仮想環境内にインストールする
      pip install oenpyxl
      
    • 仮想環境から出る
      deactivate
      
  • #format 便利
    print("西暦{}年{}月{}日".format(2022,7,19))
    currentDate = "--西暦{}年{}月{}日"
    i=7
    print(currentDate.format(2022,i,19))
    
for i in range(2,101):
    h= i // 2                                #iを2で割ったときの商
    f= True
    for j in range(2,h+1):
        if not i % j:                       # i % j == 0
            f = False
            break
    if f:                                      # f == True と書く必要はない
        print(i,end =",")                #end を書くと改行コードの代わりに任意のコードを入れることができる
  • if 文でゼロはFalseなのでそれ以外の値はTrue「ゼロかそれ以外の判定でTFを藩邸するのであれば==0を書く必要はない。
  • boolean の変数でTrueが入っているかどうかは==Trueと書かなくてもよい。if f と書けばif f == True と書かなくて良い。

再帰関数:難しい(´・ω・`)

  • 関数から自分を呼び出す
  • 終了条件を作っておく必要あり(whileループと同じ)
def sum(n):
    if n <1:
        return n
    return n + sum(n-1)
s=sum(100)
print(s)

2022/07/26

  • スタック、キュー、リストがどんなものかわかればOK
  • 次回は142ページから

2022/07/28

2022/08/01

  • 配列のcopy import copy を使うと便利(空の配列を用意してappendで追加して作ってもよいけど)
    import copy
    
    list1 = ["Js","PHP","Python","Java"]
    list2 = list1
    list2[0] = "WebDesign"
    print(list1)
    print(list2)
    
    list3 = ["blue","red","green","yellow"]
    list4 = copy.copy(list3)
    list4[0] = "pink"
    print(list3)
    print(list4)
    
  • 辞書型
    dict1 = {"red":"止まれ","blue":"渡れ","yellow":"注意"}
    print(dict1.keys())   //キー一覧が取り出される
    print(dict1.values()) //値一覧が取り出される
    辞書型にデータを追加する時には検索と同様の分を書けばいい。(appendは不要)
    

2022/08/04

  • オブジェクト化するとトータルの行数は増える。メインルーチンはスッキリ。
  • 辞書の取り出し方
    persons = [
        {"name":"石田","phone":"080-2765-8888","gender":"m","cl":"001"},
        {"name":"松本","phone":"090-3582-7777","gender":"m","cl":"002"},
        {"name":"坂本","phone":"090-6852-5555","gender":"f","cl":"001"},
        {"name":"上田","phone":"090-1698-4444","gender":"m","cl":"003"},
        {"name":"上田","phone":"080-3553-6666","gender":"f","cl":"002"},
    ]
    
     for person in persons:
         print(person["name"],person["phone"])
    

2022/08/08

  • python からSQliteを操作する
  • https://sqlitebrowser.org/ からビュワーをダウンロード・インストール
    • アプリを起動しているとPythonから操作できないので注意!
  • 代表的な操作例
    import sqlite3
    
    conn = sqlite3.connect("sample.db")
    #あればコネクトするし、ないときは作ってくれる。
    
    cur = conn.cursor() #実行の準備
    テーブル作成(一回だけ)
    #sql ="create table users (id int primary key,name varchar(50),email varchar(100))"
    # cur.execute(sql)
    #データの登録(SQLの実行)
    #sql ="insert into users values(1,'松本','[email protected]')"
    
    #sql = "INSERT INTO users VALUES(?,?,?)"
    #cur.execute(sql,(2,"岡本","[email protected]"))
    
    # cur.execute(sql)
    # conn.commit()    #更新後には必ずcommitする
    #SELECT文
    cur.execute('SELECT * FROM users')
    for row in cur:
        print(row)
    
    conn.close() #dbを閉じる:必須
    
  • xlsx からDBにデータを吸い上げる
    import openpyxl as xl
    import sqlite3
    
    book = xl.load_workbook("member.xlsx")
    conn = sqlite3.connect("members.db")
    cur = conn.cursor() #実行の準備
    
    sql = "delete from member"
    cur.execute(sql)
    
    sheet = book["Sheet1"]
    for i in range(2,sheet.max_row+1):
        name = sheet.cell(column=1,row=i).value
        kana = sheet.cell(column=2,row=i).value
        age = sheet.cell(column=3,row=i).value
        ymd = sheet.cell(column=4,row=i).value
        gender = sheet.cell(column=5,row=i).value
        blood = sheet.cell(column=6,row=i).value
        email = sheet.cell(column=7,row=i).value
        phone = sheet.cell(column=8,row=i).value
        mobile = sheet.cell(column=9,row=i).value
        post = sheet.cell(column=10,row=i).value
        address = sheet.cell(column=11,row=i).value
        company = sheet.cell(column=12,row=i).value
        credit = sheet.cell(column=13,row=i).value
        endday = sheet.cell(column=14,row=i).value
        mynumber = sheet.cell(column=15,row=i).value 
    
        sql = "INSERT INTO member VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
        cur.execute(sql,(name,kana,age,ymd,gender,blood,email,phone,mobile,post,address,company,credit,endday,mynumber)) 
    
    conn.commit()
    conn.close()
    
  • 次回はwebからのデータの収集・html作成

2022/8/23

  • python web bottlehttps://bottlepy.org/docs/dev/
  • 仮想環境を作る
    • C:\Users\S1-06\Desktop\pythonweb> python -m venv .venv
    • PS C:\Users\S1-06\Desktop\pythonweb> .venv/Scripts/activate
    • bottle をインストール:pip install bottle
from bottle import route, run, template

@route('/hello/<name>')                  ///<name>は引数。hello もname もディレクトリではないことに注意
def index(name):                      //url から受け取った名前
    return template('<b>Hello {{my_name}}</b>!', my_name=name)//受けたnameを表示するためにmy_nameに渡した

run(host='localhost', port=8080)
views フォルダに入れたhtml
{{message}}
@route('/sample')
def sample():
    return template("sample",message="こんにちは")
template はviewsフォルダ内の指定のhtml(この場合sample.html)を呼び出す。その中にある{{message}}に指定の文字列を入れて返す。
@route('/form')
def form():
    return template("form")
------- 上で呼び出されるhtmlのform部
    <form action="/result" method="post">    ここでpostを使っている
        <input type="text" name="count" id="">
        <button type="submit">送信</button>
    </form>

 
@post('/result')                POSTで呼ばれたときに実行:form.htmlのpostでリクエストされた
def result():
    count = request.forms.get('count')
    return template('result',count = count) 

@route('/result')                             GETで呼ばれたときに実行:普通にURLを入力の場合はこちら
def resultpost():
    return"result"

2022/08/30

正規表現:パターンはネットにあるものを使えばOK

import re//reは標準ライブラリなのでインストールする必要はない。
pattern = r'^\d{2,4}-\d{2,4}-\d{4}$'
phone = '090-7900-1111'
prog = re.compile(pattern)
result = prog.match(phone)
if result:
    print(result.group())
else:
    print("対象がありませんでした")

python からExcelを操作するテスト。 openpyxlを使って 入力チェックは正規表現を使う

タグ:

+ タグ編集
  • タグ:
最近更新されたスレッド
ウィキ募集バナー