Harigami
ログイン
anonymous タイトルなし
Python
import tkinter as tk
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
from tkinter import messagebox as msgbox
import pyodbc
import pandas as pd
import os
import re

test = True


class FormMain(tk.Frame):

    def __init__(self, master):
        super().__init__(master)

        master.title('データインポートプログラム')
        master.resizable(False, False)
        self.propagate(False)
        self.pack(expand=True, fill=tk.BOTH)
        pad = {"padx": 10, "pady": 10}

        lbl1 = Label(self, text='取込ファイル種別')
        lbl1.grid(row=0, column=0, cnf=pad)

        self.ftype_var = tk.IntVar(value=1)
        ftype1 = Radiobutton(self, text='Shipment Report', variable=self.ftype_var, value=1)
        ftype1.grid(row=0, column=1, cnf=pad)
        # New Product Shipment Reportボタン作成
        ftype2 = Radiobutton(self, text='New Product Shipment Report', variable=self.ftype_var, value=2)
        ftype2.grid(row=0, column=2, cnf=pad, sticky=tk.W)

        lbl2 = Label(self, text='取込年月')
        lbl2.grid(row=1, column=0, cnf=pad)
        vcmd = (self.register(self.date_entry_validate), '%P')
        self.date_entry_var = tk.StringVar()
        date_entry = Entry(self, textvariable=self.date_entry_var)
        date_entry.configure(validate="key", validatecommand=vcmd)
        date_entry.grid(row=1, column=1, cnf=pad, sticky=tk.W)

        lbl3 = Label(self, text='取込ファイル')
        lbl3.grid(row=2, column=0, cnf=pad)
        self.file_entry_var = tk.StringVar()
        file_entry = Entry(self, textvariable=self.file_entry_var)
        file_entry.grid(row=2, column=1, columnspan=3, cnf=pad, sticky=tk.E + tk.W)

        file_sel_btn = Button(self, text='参 照', width=16, command=self.file_sel_clicked)
        file_sel_btn.grid(row=2, column=4, cnf=pad, sticky=tk.W)

        lbl4 = Label(self, text='取込件数')
        lbl4.grid(row=3, column=0, cnf=pad)
        self.num_entry_var = tk.StringVar()
        num_entry = Entry(self, textvariable=self.num_entry_var)
        num_entry.grid(row=3, column=1, cnf=pad, sticky=tk.W)
        lbl5 = Label(self, text='件')
        lbl5.grid(row=3, column=2, cnf=pad, sticky=tk.W)

        exec_button = Button(self, text='実 行 ', width=16, command=self.exec_clicked)
        exec_button.grid(row=4, column=4, cnf=pad, sticky=tk.W)

        if test:
            self.add_test_frame()

    def date_entry_validate(self, text):
        return (not text) or len(text) <= 6 and text.isdecimal()

    def file_sel_clicked(self):
        path = askopenfilename(initialdir=r'C:\Python', filetypes=[('Excel File', '*xlsx')])
        if path:
            self.file_entry_var.set(path)

    def exec_clicked(self):
        if not re.match("[0-9]{6}", self.date_entry_var.get()):
            msgbox.showwarning(message="date format error")
            return

        if not os.path.exists(self.file_entry_var.get()):
            msgbox.showwarning(message="file not found")
            return

        rowcount = 0
        if self.ftype_var.get() == 1:
            data = self.read_book1(self.file_entry_var.get(), self.date_entry_var.get())
            rowcount = self.insert(data)
        else:
            msgbox.showwarning(message="not implemented")

        self.num_entry_var.set(rowcount)
        msgbox.showinfo(message="ok")

    def add_test_frame(self):
        test_frame = tk.Frame(self, bg="gray")
        test_frame.grid(row=5, column=0, columnspan=5, sticky=tk.E + tk.W)
        cnf = {"ipadx": 5, "side": tk.LEFT}
        crete_table = Button(test_frame, text='CREATE TABLE', command=self.test_create_table)
        crete_table.pack(cnf)
        insert = Button(test_frame, text='INSERT', command=self.test_insert)
        insert.pack(cnf)
        createbook = Button(test_frame, text='CREATE BOOK', command=self.test_create_book)
        createbook.pack(cnf)

    def read_book1(self, path, yyyymm):
        df = pd.read_excel(path, index=False)
        data = df.query("item1=='{}'".format(yyyymm))
        return data

    def insert(self, data):
        con = self.get_connection()
        cur = con.cursor()
        ret = 0
        try:
            for i, row in data.iterrows():
                sql = "INSERT INTO test_a VALUES('{}', '{}', '{}')"
                sql = sql.format(row["item1"], row["item2"], row["item3"])
                cur.execute(sql)
                ret += cur.rowcount

            cur.commit()
        except:
            cur.rollback()
        finally:
            con.close()

        return ret

    def get_conn_str(self):
        driver = "{SQL Server}"
        server = r'localhost\SQLEXPRESS'
        user = 'test'
        password = 'test'
        database = 'sample'

        con_str = "DRIVER={};SERVER={};UID={};PWD={};DATABASE={};"
        return con_str.format(driver, server, user, password, database)

    def get_connection(self):
        conn = pyodbc.connect(self.get_conn_str())
        return conn

    def test_insert(self):
        sql = "INSERT INTO test_a VALUES('202001', 'AAA', 'aaa')"
        con = self.get_connection()
        try:
            con.execute(sql)
            con.commit()
        except:
            con.rollback()
            msgbox.showinfo(message="rollback")
        else:
            msgbox.showinfo(message="ok")
        finally:
            con.close()

    def test_create_table(self):
        sql = """
            DROP TABLE IF EXISTS test_a;
            CREATE TABLE test_a(
                id int IDENTITY(1, 1) NOT NULL,
                item1 varchar(10) NULL,
                item2 nvarchar(50) NULL,
                item3 nvarchar(50) NULL
            );
        """
        con = self.get_connection()
        con.execute(sql)
        con.commit()
        con.close()
        msgbox.showinfo(message="ok")

    def test_create_book(self):
        data = [
            ["1", "202001", "AAAA", "aaaa"],
            ["2", "202001", "BBBB", "bbbb"],
            ["3", "202002", "CCCC", "cccc"],
            ["4", "202002", "DDDD", "dddd"],
        ]
        df = pd.DataFrame(data=data, columns=["no.", "item1", "item2", "item3"])
        fname = "test.xlsx"
        fpath = os.path.join(os.path.dirname(__file__), fname).replace(os.path.sep, "/")
        df.to_excel(fpath, index=False)
        self.file_entry_var.set(fpath)
        msgbox.showinfo(message="ok")


def main():
    app = tk.Tk()
    FormMain(app)
    app.mainloop()


if __name__ == "__main__":
    main()
  • 0
  • 1
anonymous タイトルなし
Python
import tkinter as tk
from tkinter.ttk import *
from tkinter.filedialog import askopenfilename
from tkinter import messagebox as msgbox
import pyodbc
import pandas as pd
import os
import re

test = True


class FormMain(tk.Frame):

  def __init__(self, master):
    super().__init__(master)

    master.title('データインポートプログラム')
    master.resizable(False, False)
    self.propagate(False)
    self.pack(expand=True, fill=tk.BOTH)
    pad = {"padx": 10, "pady": 10}

    lbl1 = Label(self, text='取込ファイル種別')
    lbl1.grid(row=0, column=0, cnf=pad)

    self.ftype_var = tk.IntVar(value=1)
    ftype1 = Radiobutton(self, text='Shipment Report', variable=self.ftype_var, value=1)
    ftype1.grid(row=0, column=1, cnf=pad)
    # New Product Shipment Reportボタン作成
    ftype2 = Radiobutton(self, text='New Product Shipment Report', variable=self.ftype_var, value=2)
    ftype2.grid(row=0, column=2, cnf=pad, sticky=tk.W)

    lbl2 = Label(self, text='取込年月')
    lbl2.grid(row=1, column=0, cnf=pad)
    vcmd = (self.register(self.date_entry_validate), '%P')
    self.date_entry_var = tk.StringVar()
    date_entry = Entry(self, textvariable=self.date_entry_var)
    date_entry.configure(validate="key", validatecommand=vcmd)
    date_entry.grid(row=1, column=1, cnf=pad, sticky=tk.W)

    lbl3 = Label(self, text='取込ファイル')
    lbl3.grid(row=2, column=0, cnf=pad)
    self.file_entry_var = tk.StringVar()
    file_entry = Entry(self, textvariable=self.file_entry_var)
    file_entry.grid(row=2, column=1, columnspan=3, cnf=pad, sticky=tk.E + tk.W)

    file_sel_btn = Button(self, text='参 照', width=16, command=self.file_sel_clicked)
    file_sel_btn.grid(row=2, column=4, cnf=pad, sticky=tk.W)

    lbl4 = Label(self, text='取込件数')
    lbl4.grid(row=3, column=0, cnf=pad)
    self.num_entry_var = tk.StringVar()
    num_entry = Entry(self, textvariable=self.num_entry_var)
    num_entry.grid(row=3, column=1, cnf=pad, sticky=tk.W)
    lbl5 = Label(self, text='件')
    lbl5.grid(row=3, column=2, cnf=pad, sticky=tk.W)

    exec_button = Button(self, text='実 行 ', width=16, command=self.exec_clicked)
    exec_button.grid(row=4, column=4, cnf=pad, sticky=tk.W)

    if test:
      self.add_test_frame()

  def date_entry_validate(self, text):
    return (not text) or len(text) <= 6 and text.isdecimal()

  def file_sel_clicked(self):
    path = askopenfilename(initialdir=r'C:\Python', filetypes=[('Excel File', '*xlsx')])
    if path:
      self.file_entry_var.set(path)

  def exec_clicked(self):
    if not re.match("[0-9]{6}", self.date_entry_var.get()):
      msgbox.showwarning(message="date format error")
      return

    if not os.path.exists(self.file_entry_var.get()):
      msgbox.showwarning(message="file not found")
      return

    rowcount = 0
    if self.ftype_var.get() == 1:
      data = self.read_book1(self.file_entry_var.get(), self.date_entry_var.get())
      rowcount = self.insert(data)
    else:
      msgbox.showwarning(message="not implemented")

    self.num_entry_var.set(rowcount)
    msgbox.showinfo(message="ok")

  def add_test_frame(self):
    test_frame = tk.Frame(self, bg="gray")
    test_frame.grid(row=5, column=0, columnspan=5, sticky=tk.E + tk.W)
    cnf = {"ipadx": 5, "side": tk.LEFT}
    crete_table = Button(test_frame, text='CREATE TABLE', command=self.test_create_table)
    crete_table.pack(cnf)
    insert = Button(test_frame, text='INSERT', command=self.test_insert)
    insert.pack(cnf)
    createbook = Button(test_frame, text='CREATE BOOK', command=self.test_create_book)
    createbook.pack(cnf)

  def read_book1(self, path, yyyymm):
    df = pd.read_excel(path, index=False)
    data = df.query("item1=='{}'".format(yyyymm))
    return data

  def insert(self, data):
    con = self.get_connection()
    cur = con.cursor()
    ret = 0
    try:
      for i, row in data.iterrows():
        sql = "INSERT INTO test_a VALUES('{}', '{}', '{}')"
        sql = sql.format(row["item1"], row["item2"], row["item3"])
        cur.execute(sql)
        ret += cur.rowcount

      cur.commit()
    except:
      cur.rollback()
    finally:
      con.close()

    return ret

  def get_conn_str(self):
    driver = "{SQL Server}"
    server = r'localhost\SQLEXPRESS'
    user = 'test'
    password = 'test'
    database = 'sample'

    con_str = "DRIVER={};SERVER={};UID={};PWD={};DATABASE={};"
    return con_str.format(driver, server, user, password, database)

  def get_connection(self):
    conn = pyodbc.connect(self.get_conn_str())
    return conn

  def test_insert(self):
    sql = "INSERT INTO test_a VALUES('202001', 'AAA', 'aaa')"
    con = self.get_connection()
    try:
      con.execute(sql)
      con.commit()
    except:
      con.rollback()
      msgbox.showinfo(message="rollback")
    else:
      msgbox.showinfo(message="ok")
    finally:
      con.close()

  def test_create_table(self):
    sql = """
      DROP TABLE IF EXISTS test_a;
      CREATE TABLE test_a(
        id int IDENTITY(1, 1) NOT NULL,
        item1 varchar(10) NULL,
        item2 nvarchar(50) NULL,
        item3 nvarchar(50) NULL
      );
    """
    con = self.get_connection()
    con.execute(sql)
    con.commit()
    con.close()
    msgbox.showinfo(message="ok")

  def test_create_book(self):
    data = [
      ["1", "202001", "AAAA", "aaaa"],
      ["2", "202001", "BBBB", "bbbb"],
      ["3", "202002", "CCCC", "cccc"],
      ["4", "202002", "DDDD", "dddd"],
    ]
    df = pd.DataFrame(data=data, columns=["no.", "item1", "item2", "item3"])
    fname = "test.xlsx"
    fpath = os.path.join(os.path.dirname(__file__), fname).replace(os.path.sep, "/")
    df.to_excel(fpath, index=False)
    self.file_entry_var.set(fpath)
    msgbox.showinfo(message="ok")


def main():
  app = tk.Tk()
  FormMain(app)
  app.mainloop()


if __name__ == "__main__":
  main()
  • 0
  • 0
anonymous タイトルなし
Python
  • 0
  • 0
anonymous タイトルなし
Python
def main():
    import sys
    import itertools
    N=int(sys.stdin.readline())
    PL=list(map(int,sys.stdin.readline().split()))
    QL=list(map(int,sys.stdin.readline().split()))

    for i,L in enumerate(itertools.permutations(range(1,N+1))):
        if tuple(L)==tuple(PL):
            a=i
        if tuple(L)==tuple(QL):
            b=i

    print(abs(a-b))
main()
  • 0
  • 1
anonymous タイトルなし
Python
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))

def solve(x):
    if(x==1):
        return 1
    else:
        return x*solve(x-1)

def solve2(ls):
    x=ls[0]
    data=sorted(ls)
    return data.index(x)


ans1=0
ans2=0
for i in range(1,n):
    ans1+=solve(n-i)*solve2(p)
    del p[0]

    ans2+=solve(n-i)*solve2(q)
    del q[0]

print(abs(ans1-ans2))
  • 0
  • 0
エビです タイトルなし
Python
def blizzard(defenses,offense):
    for index in range(0,len(defenses),1):
        if (offense-defenses[index]>=0):
            print("コカトリス{}に{}のダメージを与えた!".format(index+1,offense-defenses[index]))
        else:
            print("コカトリス{}はダメージを受け付けない!".format(index+1))
defenses =[38,42,22,120,27]
print("魔法使いの魔力を入力して下さい。")
offense=int(input("魔法使いの魔力:"))
for index in range(1,len(defenses),1):
    print("コカトリスが現れた!".format(index))
print("魔法使いはブリザードを唱えた!")
blizzard(defenses,offense)
  • 0
  • 1
anonymous タイトルなし
Python
//@version=4
strategy(title="いるまてぃっく", overlay=true)

//source(平均足)
isHA = input(true, "平均足を使用する。", input.bool)
Hdata = isHA ? heikinashi(syminfo.tickerid) : syminfo.tickerid
HAo = security(Hdata, timeframe.period, open)
HAh = security(Hdata, timeframe.period, high)
HAl = security(Hdata, timeframe.period, low)
HAc = security(Hdata, timeframe.period, close)

HAhlc = (HAh + HAl + HAc)/3
HAup = HAo < HAc
HAdw = HAo > HAc

source = HAc

//Setting
len = input(title=' 期間', type=input.resolution, defval="60")
res = input(defval=false, title="チェック=MTF表示")
malt = input(1, title='シグマ', step=1, minval=1, maxval=50)
res2 = res ? len : timeframe.period
dev = security(Hdata, res2, stdev(source, 20))
basis = security(Hdata, res2, sma(source, 20))
useTrueRange = input(true)
length = input(20, minval=1)

//ロジック
upper = basis + dev * malt
lower = basis - dev * malt
ma = sma(source, length)
range = useTrueRange ? max(HAh - HAl, abs(HAh - HAc[1]), abs(HAl - HAc[1])) : HAh - HAl
rangema = sma(range, length)
upper2 = ma + rangema * malt
lower2 = ma - rangema * malt
basis2 = avg(upper2, lower2)

ures = security(Hdata, res2, upper2)
lres = security(Hdata, res2, lower2)
bres = security(Hdata, res2, basis2)
sig = upper > ures

//ENTRY条件
LONG = basis[1]<basis and sig
SHORT = basis[1]>basis and sig
strategy.entry("LONG", true, when=LONG)
strategy.entry("SHORT", false, when=SHORT)

//表示
HAcol = HAc > HAo ? color.green : color.red
plot_HAo = isHA ? HAo :na
plot_HAh = isHA ? HAh :na
plot_HAl = isHA ? HAl :na
plot_HAc = isHA ? HAc :na
plotcandle(plot_HAo, plot_HAh, plot_HAl, plot_HAc, "平均足", HAcol, color.black)
  • 0
  • 1
anonymous タイトルなし
Python
//@version=4
strategy(title="いるまてぃっく", overlay=true)

//source(平均足)
isHA = input(true, "平均足を表示する", input.bool)
Hdata = isHA ? heikinashi(syminfo.tickerid) : syminfo.tickerid
HAo = security(Hdata, timeframe.period, open)
HAh = security(Hdata, timeframe.period, high)
HAl = security(Hdata, timeframe.period, low)
HAc = security(Hdata, timeframe.period, close)

HAhlc = (HAh + HAl + HAc)/3
HAup = HAo < HAc
HAdw = HAo > HAc

source = HAc

//Setting
len = input(title=' 期間', type=input.resolution, defval="60")
res = input(defval=false, title="チェック=MTF表示")
malt = input(1, title='シグマ', step=1, minval=1, maxval=50)
res2 = res ? len : timeframe.period
dev = security(Hdata, res2, stdev(source, 20))
basis = security(Hdata, res2, sma(source, 20))
useTrueRange = input(true)
length = input(20, minval=1)

//ロジック
upper = basis + dev * malt
lower = basis - dev * malt
ma = sma(source, length)
range = useTrueRange ? tr : HAh - HAl
rangema = sma(range, length)
upper2 = ma + rangema * malt
lower2 = ma - rangema * malt
basis2 = avg(upper2, lower2)

ures = security(Hdata, res2, upper2)
lres = security(Hdata, res2, lower2)
bres = security(Hdata, res2, basis2)
sig = upper > ures

//ENTRY条件
LONG = basis[1]<basis and sig
SHORT = basis[1]>basis and sig
strategy.entry("LONG", true, when=LONG)
strategy.entry("SHORT", false, when=SHORT)

//表示
HAcol = HAc > HAo ? color.green : color.red
plotcandle(HAo, HAh, HAl, HAc, "平均足", HAcol, color.black)
  • 0
  • 0
LC23 タイトルなし
Python
//@version=4
strategy("MTF Stochastic Slow ", overlay=false)
len = input(title='時間軸', type=input.resolution, defval="60")
length = input(14, minval=1)
res = input(defval=true, title="チェック=MTF表示")
res2 = res ? len : timeframe.period
OverBought = input(80)
OverSold = input(20)
smoothK = 3
smoothD = 3
k = security(syminfo.tickerid, res2, sma(stoch(close, high, low, length), smoothK))
d = security(syminfo.tickerid, res2, sma(k, smoothD))
plot(OverBought, color=color.red, style=3)
plot(OverSold, color=color.lime, style=3)
plot(k, color=color.aqua)
plot(d, color=color.purple)
  • 0
  • 1
Programmerryoki 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold In Python Brute Force
Python
class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        for n in range(1, min(len(mat), len(mat[0]))+1):
            done = False
            for b in range(len(mat)-n+1):
                for a in range(len(mat[0])-n+1):
                    s = sum([sum(mat[i][a:a+n]) for i in range(b,b+n)])
                    if s <= threshold:
                        done = True
                        break
                if done:
                    break
            else:
                return n-1
        return min(len(mat),len(mat[0]))
  • 0
  • 1
あなたもコードを投稿しませんか?
投稿する