python 三个只出现一次的数

其他数恰好出现两次。<br/>类似问题:<br/> 1.两个只出现一次的数<br/> 2.两个出现奇数次的数

findThreeOnceNum.py
"""
input: numbers
output: 3 number appear once 

solution: ^
"""

import random
from functools import reduce


def findTheLastOne(x):
    return x & (-x)

def findTwoOnceNum(x, s):
    num = findTheLastOne(x)
    a, b = 0, 0
    for i in s:
        if i & num:
            a ^= i
        else:
            b ^= i
    return a, b


def findThreeOnceNum(x, s):
    num = findTheLastOne(x)
    c = 0
    for i in s:
        if i & num:
            c ^= i
    newX = x ^ c
    a, b = findTwoOnceNum(newX, s + [c])
    return a, b, c


def main():
    s = list(range(9)) + list(range(9)) + list(range(10, 13))
    random.shuffle(s)
    print(s, findThreeOnceNum(reduce(lambda x, y: x ^ y, s), s))


if __name__ == "__main__":
    main()

python 唯一重复的数

findRepeatedNum.py
"""
input: 1-1000 put in 1001 array
output: the only repeated number

solution: sort
"""

import random


def findRepeatedNum(s):
    while s[s[0]] != s[0]:
        s[s[0]], s[0] = s[0], s[s[0]]
    return s[0]


def main():
    s = list(range(1, 1001))
    repeatNum = random.randint(1, 1000)
    s.append(repeatNum)
    random.shuffle(s)
    num = findRepeatedNum(s)
    print(num, repeatNum)


if __name__ == "__main__":
    main()

python 重排RGB

rgb.py
"""
input: RGBRBGGBR
output: RRRGGGBBB

solution: quick sort
"""


def partition(s):
    length = len(s)
    sta, cur, end = 0, 0, length - 1
    while cur < end:
        if s[cur] == "R":
            s[cur], s[sta] = s[sta], s[cur]
            sta += 1
            cur += 1
        elif s[cur] == "B":
            s[cur], s[end] = s[end], s[cur]
            end -= 1
        else:
            cur += 1


def main():
    s = list("RGBRBGGBR")
    partition(s)
    print(s)


if __name__ == "__main__":
    main()

python 换零钱

numOfS.py
"""
input: 100, 1, 2, 5, 10
output: 100元零钱的组合数

solution: 动态规划
"""


def numOfS():
    s = 100
    num = [0] * 101
    num[1], num[2] = 1, 2
    for i in range(3, 101):
        num[i] = num[i-1] + num[i-2] + num[i-5] + num[i-10]
    return num[100]


def main():
    print(numOfS())


if __name__ == "__main__":
    main()

python 美元备忘录

start_USD.py
# -*- coding: utf-8 -*-

import os.path

from pxr import Usd, UsdGeom, Sdf, Gf

USD_PATH_ROOT = "I:/usd_test"

# あるファイルを開く
# stage = Usd.Stage.Open(USD_PATH_ROOT + '/HelloWorld.usda')
# 作る場合は
stage = Usd.Stage.CreateNew(USD_PATH_ROOT + '/HelloWorld.usda')
# Primをつくる、普通はReturnでPrimのオブジェクトがとれるけど、取得方法メモのためあえてやらない
UsdGeom.Xform.Define(stage, '/hello')
# Primの取得
prim = stage.GetPrimAtPath("/hello")
stage.SetDefaultPrim(prim)  # 入れないとReferenceしたときにWarningになるんだけど、Defaultとはなにか。
attrV = prim.GetAttribute('visibility')
# Getで値取得 -> viewでみた結果 https://gyazo.com/72d1e873d8c457b2c0e41d056eda8767.png
print(attrV.Get())
# アトリビュートへのパスは SdfPath + .AttributeName
print(attrV.GetPath())
# Transformをする
UsdGeom.XformCommonAPI(prim).SetTranslate((4, 5, 6))
# 新しいアトリビュート追加 -> https://graphics.pixar.com/usd/docs/api/_usd__page__datatypes.html
attrMat4d = prim.CreateAttribute('myMatrix', Sdf.ValueTypeNames.Matrix4d)
# セット -> GFとは https://graphics.pixar.com/usd/docs/api/gf_page_front.html
attrMat4d.Set(Gf.Matrix4d(1))

# ファイルを保存
stage.Save()

# Referenceしてみる
# ReferenceはあるPrimに対して別のPrimを「当てはめる」ので
# あてはめる先のPrimにAddReference関数がある。
refStage = Usd.Stage.CreateNew(USD_PATH_ROOT + '/RefExample.usda')
# Over(ある場合のみで、なければPrimを作らない,だったか...)
refHello = refStage.OverridePrim('/hello')
refHello.GetReferences().AddReference(USD_PATH_ROOT + '/HelloWorld.usda')
# 本体は変えずにReference先で値をかえてみる
UsdGeom.XformCommonAPI(refHello).SetTranslate((7, 8, 9))
refStage.GetRootLayer().Save()
# 結果をプリント
print(refStage.GetRootLayer().ExportToString())

python DelegateSample.py

tableView.py
#!python3
# -*- coding: utf-8 -*-

import sys
import os.path

from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtUiTools import QUiLoader

CURRENT_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))

# TableViewの1行ごとのItemを管理するクラス
class DataItem(object):

    def __init__(self, name="", check=False, progress=0):

        self.name = name
        self.check = check
        self.progess = progress

    def data(self, column):
        if column == 0:
            return self.name
        elif column == 1:
            return self.check
        elif column == 2:
            return self.progess

    def setData(self, column, value):

        if column == 0:
            self.name = value
        elif column == 1:
            self.check = value
        elif column == 2:
            self.progess = value


class TableDelegate(QtWidgets.QItemDelegate):

    def __init__(self, parent=None):
        super(TableDelegate, self).__init__(parent)

    def createEditor(self, parent, option, index):
        """
        編集したいCellに対して、編集用のWidgetsを作成する
        """
        if index.column() == 0:
            return QtWidgets.QLineEdit(parent)

        if index.column() == 2:
            spin = QtWidgets.QSpinBox(parent)
            spin.setMinimum(0)
            spin.setMaximum(100)
            return spin

    def setEditorData(self, editor, index):
        """
        createEditorで作成したWidgetsを受け取って、
        Editorにデフォルト値を設定する。
        今回の場合、元々のCellに表示されていた内容を受け取り、
        QLineEditに対してデフォルト値をセットしている
        """

        if index.column() == 0:
            value = index.model().data(index, QtCore.Qt.DisplayRole)
            editor.setText(value)

        if index.column() == 2:
            value = index.model().data(index, QtCore.Qt.DisplayRole)
            editor.setValue(value)

    def editorEvent(self, event, model, option, index):
        """
        TableのCellに対してなにかしらのイベント(クリックした等)が発生したときに呼ばれる。
        """

        if index.column() == 1:
            if self.checkBoxRect(option).contains(event.pos().x(), event.pos().y()):
                if event.type() == QtCore.QEvent.MouseButtonPress:
                    currentValue = model.items[index.row()].data(index.column())
                    model.items[index.row()].setData(index.column(), not currentValue)
                    model.layoutChanged.emit()
                    return True
        return False

    def setModelData(self, editor, model, index):
        """
        編集した値を、Modelを経由して実体のオブジェクトに対してセットする
        """

        value = None

        if index.column() == 0:
            value = editor.text()

        if index.column() == 2:
            value = editor.value()

        if value is not None:
            model.items[index.row()].setData(index.column(), value)

    def checkBoxRect(self, option):

        rect = option.rect
        rect.setX(rect.x() + 10)
        rect.setWidth(rect.width() - 20)
        return rect

    def paint(self, painter, option, index):
        """
        Cellの中の描画を行う
        """
        if index.column() == 0:
            painter.drawText(option.rect, QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap, index.data())

        if index.column() == 1:
            btn = QtWidgets.QStyleOptionButton()
            btn.state |= QtWidgets.QStyle.State_Enabled
            if index.data() == True:
                btn.state |= QtWidgets.QStyle.State_On
            else:
                btn.state |= QtWidgets.QStyle.State_Off

            btn.rect = self.checkBoxRect(option)
            btn.text = "hogehoge"
            QtWidgets.QApplication.style().drawControl(QtWidgets.QStyle.CE_CheckBox, btn, painter)

        if index.column() == 2:

            bar = QtWidgets.QStyleOptionProgressBar()
            bar.rect = option.rect
            bar.rect.setHeight(option.rect.height() - 1)
            bar.rect.setTop(option.rect.top() + 1)
            bar.minimum = 0
            bar.maximum = 100
            bar.progress = int(index.data())
            bar.textVisible = True
            bar.text = str(index.data()) + '%'
            bar.textAlignment = QtCore.Qt.AlignCenter
            QtWidgets.QApplication.style().drawControl(QtWidgets.QStyle.CE_ProgressBar, bar, painter)


class TableModel(QtCore.QAbstractTableModel):
    
    def __init__(self, parent=None):
        super(TableModel, self).__init__(parent)
        self.items = []

    def headerData(self, col, orientation, role):

        HEADER = ['名前', 'チェック', '進行状況']

        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return HEADER[col]

        if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
            return str(col + 1).zfill(3)

    def addItem(self, item):

        self.items.append(item)
        self.layoutChanged.emit()

    def rowCount(self, parent=QtCore.QModelIndex()):
        u"""行数を返す"""
        return len(self.items)

    def columnCount(self, parent):
        u"""カラム数を返す"""
        return 3

    def data(self, index, role=QtCore.Qt.DisplayRole):

        if not index.isValid():
            return None

        if role == QtCore.Qt.DisplayRole:
            return self.items[index.row()].data(index.column())

    def flags(self, index):

        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable

    def upData(self, index):
        """
        引数のIndexを1つ上に移動する
        """
        row = index.row()
        if row > 0:
            buff = self.items.pop(row)
            self.items.insert(row - 1, buff)
            self.layoutChanged.emit()

    def downData(self, index):
        """
        引数のIndexを一つ下に移動する
        """
        row = index.row()
        if row < len(self.items):
            buff = self.items.pop(row)
            self.items.insert(row + 1, buff)
            self.layoutChanged.emit()


class UISample(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(UISample, self).__init__(parent)

        self.ui = QUiLoader().load(os.path.join(CURRENT_PATH, 'tableView.ui'))

        self.resize(600, 400)

        self.model = TableModel()

        dataA = DataItem('A', False, 0)
        dataB = DataItem('B', False, 0)
        dataC = DataItem('C', False, 0)
        self.model.addItem(dataA)
        self.model.addItem(dataB)
        self.model.addItem(dataC)

        self.ui.tableView.setModel(self.model)

        self.delegate = TableDelegate()
        self.ui.tableView.setItemDelegate(self.delegate)

        self.setCentralWidget(self.ui)

        self.ui.upBtn.clicked.connect(self.upBtnClicked)
        self.ui.downBtn.clicked.connect(self.downBtnClicked)

    def upBtnClicked(self):

        index = self.ui.tableView.currentIndex()

        self.model.upData(index)
        chIndex = self.model.index(index.row() - 1, index.column())
        if chIndex.isValid():
            self.ui.tableView.setCurrentIndex(chIndex)

    def downBtnClicked(self):

        index = self.ui.tableView.currentIndex()

        self.model.downData(index)
        chIndex = self.model.index(index.row() + 1, index.column())
        if chIndex.isValid():
            self.ui.tableView.setCurrentIndex(chIndex)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    a = UISample()
    a.show()
    sys.exit(app.exec_())

python sdample SendHoudini

houTest.py
# -*- coding: utf-8 -*-

import sys
sys.path.append(r"C:\Program Files\Side Effects Software\Houdini 17.5.327\houdini\python2.7libs")

import hrpyc
connection, hou = hrpyc.import_remote_module()
geo = hou.node("/obj").createNode("geo")

python 长度最短的连续子序列

子序列的和大于等于小号

shortestSubArray.py
"""
input: Array[n], S
output: shortest sub array, sum >= S

solution: iteration from 0 to n
"""


def shortestSubArray(A, S):
    s = 0
    max_s, max_e = 0, len(A)
    Sum = 0
    for e, a in enumerate(A):
        Sum += a
        while Sum >= S:
            if e - s < max_e - max_s:
                max_s, max_e = s, e
            Sum -= A[s]
            s += 1
    return max_s, max_e + 1


def main():
    A = [12, 3, 4, 5, 6, 7, 13, 2, 7, 8, 9]
    S = 21
    s, e = shortestSubArray(A, S)
    print(A[s:e])


if __name__ == "__main__":
    main()

python qute_setup.py

setup.py
from setuptools import setup, find_packages

setup(
    name='qute_major_app',
    version='1.1',
    author='DirkZhao',
    author_email='zhaozonghao@qutoutiao.net',
    description='QTT主产品 相关接口封装',
    url='https://git.qutoutiao.net/user-test/qute_major_app',
    packages=find_packages('app'),
    package_dir={'': 'app'}
)

python 序列米等分

每份的和相等。先找到和为Ñ的所有排列,然后判断哪些排列能够组成原始的序列

divide_s.py
# 将序列划分成m份

def generate_all_equal(S, m, k):
    for i in range(k, len(S)):
        L = []
        if m == S[i]:
            yield (S[i], )
        elif m > S[i]:
            L.append(S[i])
            for j in generate_all_equal(S, m - S[i], i + 1):
                if sum(L + list(j)) == m:
                    yield tuple(L) + j

def Perm(A, k, n):
    if n == 0:
        yield []
    for i in range(k, len(A)):
        L = [A[i]]
        for j in Perm(A, i + 1, n - 1):
            yield L + j

def divide_s(S, m):
    if sum(S) % m != 0:
        return []
    else:
        d_sum = sum(S) / m
        S_sort = list(sorted(S))
        List = list(set((generate_all_equal(S, d_sum, 0))))
        if len(List) < m:
            return []
        List = [tuple(j) for j in set([tuple(list(sorted(list(i)))) for i in List])]
        L = list(Perm(List, 0, m))
        all_set = []
        for i in L:
            T = []
            for j in i:
                T.extend(j)
            if list(sorted(T)) == S_sort:
                if list(sorted(i)) not in all_set:
                    all_set.append(list(sorted(i)))
        if all_set == []:
            return []
        else:
            return all_set
def main():
    S = [6, 1, 3, 7, 4, 4, 5, 4, 1, 1]
    print("S  3  :")
    print(divide_s(S, 5))
    for i in divide_s(S, 3):
        print(i)
    print("S  4  :")
    for i in divide_s(S, 4):
        print(i)
    print("S  5  :")
    for i in divide_s(S, 5):
        print(i)

if __name__ == "__main__":
    main()