准备
- Google Colaboratory(※Jupyter Notebook也OK)
- 分发源代码(*如果您只想从头开始,则不需要)
使用技术
Python
Qiskit
你做了什么
家乡税务上限模拟 × 乐天 API 集成 × 量子计算 × 优化问题
在“故乡纳税有翻译”中
,从乐天API获取故乡纳税返还品一览表,
求解组合优化问题之一的背包问题的量子算法
(QAOA:量子近似优化算法)中
,在模拟中得出的扣除上限金额中
总重量最重的返还礼品的组合
无论如何,我制定了一个计划,通过家乡纳税。
评论
稍后,在乐天 API 的搜索词中包含“翻译”是为了放大吝啬感。
我们专注于用户、业务和技术,例如
如何使用数学、算法、最新技术和数据
来解决某人的问题。
量子算法的工作方式目前没有用法,
但经典(为了方便起见,我别无选择)程序可能会变得有帮助。
但是,扣除上限详细信息模拟只有相当的精度。
如果你“做正确的事”,你不仅需要谷歌老师,还需要一个强大的税务会计师。
(一个熟人的税务会计师必须让主任参与进来)
如果你想要一个精确的计算或更快的处理,你必须
完全熟悉量子计算和家乡税收的基本原理,或者
你妥协的包和简单的模拟。
关于QAOA(量子近似优化算法)
量子绝缘计算 (QAA) 中的结束状态(导致最佳解的哈密尔顿)为 $C$,初始状态(基能量状态的哈密尔顿)为 $B$。
在这里,作为任何角度参数,使用伽玛 $(γ)$ 和 beta$(β)$ 将$C $ 和 $γ$ 的统一矩阵定义为 $U(C,γ)$,将$B$ 和 $β$ 的统一矩阵定义为 $U(B,β)$。
$$
U(C, γ) = e^{iγC}… ①
U(C, β) = e^{iγB}… ②
$$
此外,使用上述统一矩阵的迭代次数为整数 $p$,将 $(β1,γ2,…,伽马 p)$ 作为元素的矢量γ$,将 (β1,β2,…,βp) $ 作为元素的矢量定义为 $β$,将 p 维的正交基矢量定义为 $|s]$,定义以下运算符 $|γ,β] $。
$$
|γ, β> = U(B, βp)U(C, γ_p)U(B, β{p-1})U(C, γ_{p-1})… U(B, β_1)U(C, γ_1)|s>… ③
$$
然后,使用上面定义的运算符 $|γ,β]$ ,确定导致最佳解决方案的哈密尔顿 $C$ 的预期 $Fp$,如下所示。
$$
F_p(γ, β) = <γ,β| C|γ,β>… ④
$$
更改角度参数 $γ$ 和 $β$,以探索$F_p 可能的最大值M_p。 $
$$
M_p = max_{γ,β}F_p(γ,β)… ⑤
$$
当确定最大值M_p时,确定γ、β,同时确定 $C$ 对 (4) 的期望值,同时确定给出最佳解决方案的组合的状态。
- 统一矩阵:复数正向矩阵
- 哈密尔顿:系统的全部能量
- 系统: 某种集合
- 预期值:预测平均值
- 伊辛模型:由两个状态的网格点组成的网格模型
关于背包问题
定义
$I={1,2,…,N}$是商品的集合。
当每个商品的重量为 $i in I$
的权重为 $w_i$ 价值为 $v_i$
商品重量的总上限为 $W$ 时
,将出现以下内容称为背包问题。
$$
max ∑{i in I}v_iw_i s.t. ∑{i in I}v_iw_ile W
xin mathbb{N}(forall in I)
$$
其中$x_i$ 表示要放入背包中的物品数。
解决方案
问题是,如果你搜索整个数字,你会尝试两个选项,“选择或不选择物品”,只有几分钟的货物,计算金额是$O(2^{| I|}) 成为$ 但是,通过有效的贪婪方法的解法是已知的,在这里显示了解决方案。 这个问题的渐化公式是
$$
V(i,w)
=begin{cases}
{0quad if;i= 0,or,w = 0}
{V(i-1,w)quad if;w_i>w}
{max(V(i-1),V(i-1,w-w_i)+v_i)quad otherwise}
end{cases}
$$
成为。 此处,$V (i, w) $ 的值表示重量之和为 $w$ 或更少时,可以使用下标为 $i$ 或更低的商品实现的总价值的最大值。 这个公式是
- 当“一个不能选择一件物品”或“最大重量为 ${显示样式 0}{显示样式 0}$”时,由于没有要包装的物品,因此所选项目的总价值为 ${显示样式 0}{显示样式 0}$
- 如果项目 ${显示样式 i}$ 的权重超过 ${显示样式 w}$,则无法添加项目 ${显示样式 i}$,因此总值是项目下标上限为前一个值的最大值。
- 如果项目 ${显示样式 i}$ 的权重不超过 ${显示样式 w}$,则不添加项目 ${显示样式 i}$ 的值最大值应为不小的值。
它表示。 伪代码如下所示。 总价值的最大值为 $V(| I|,W) 作为 $ 获得。 此外,还需要添加代码来枚举所选项目。
- 渐化公式:用前一个术语表示的具有几列的项的项
在量子退行的伊辛模型中求解背包的公式
在 $1 模型中求解时定义哈密尔顿尼安
$H = BBigl(W-sum_iw_ix_iBigl)^2-sum_iv_ix_i$
*$B$ = 超参数
程序
软件包安装
!pip install matplotlib
!pip install seaborn
!pip install japanize-matplotlib
!pip install qiskit_optimization
!pip install qiskit-aer
!pip install ortoolpy
!pip install pulp
包导入
from typing import List
import math
from qiskit_optimization.applications import Knapsack
from qiskit.algorithms import QAOA, NumPyEigensolver, NumPyMinimumEigensolver
from qiskit.utils import QuantumInstance
from qiskit import Aer
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from typing import List
from ortoolpy import knapsack
from pulp import *
import requests
import numpy as np
import pandas as pd
import time
import japanize_matplotlib
import copy
import random
from IPython.display import HTML
%matplotlib inline
定义家乡税收抵免限额计算类
class Calculator():
income: int = 0 # 总收入
donation_amount: int = 0 = 捐赠金额
resident_tax: int = 0 = 居民税额
def __init__(self, income: int, donation_amount: int, resident_tax: int):
self.income = income
self.donation_amount = donation_amount
self.resident_tax = resident_tax
• 考虑扣除上限的家乡税扣除额的结果
def deduction_result(self):
• 所得税扣除限额 =总收入的 40% 或更少,居民税基本部分扣除限额 = 总收入的 30% 或更少,居民税特殊部分扣除限额 = 个人居民税收入百分比的 20% 之一
if (self.income_tax_deduction() <= self.income * 0.4) or (self.basic_resident_tax_deduction() <= self.income * 0.3) or (self.special_inhabitant_tax_deduction() <= self.income * 0.2):
return self.deduction_limit()
else:
return self.hometown_tax_deduction()
• 扣除限额
def deduction_limit(self):
• 个人居民税收入×20% / 100% - 居民税基本部分 10% - (所得税率×重建税率 1.021) + 2,000 日元
return (self.resident_tax * 0.2 / (1 - 0.1) - (self.income_tax_rate() * 1.021)) + 2000
• 家乡税扣除额
def hometown_tax_deduction(self):
• 所得税扣除额 + 居民税基本扣除额 + 居民税特殊扣除额
return self.income_tax_deduction() + self.basic_resident_tax_deduction() + self.special_inhabitant_tax_deduction()
• 所得税扣除额
def income_tax_deduction(self):
• (家乡税捐赠金额 - 2,000日元)×(所得税税率(0-45%)×1.021)
return (self.donation_amount - 2000) * (self.income_tax_rate() * 1.021)
• 居民税基本扣除额
def basic_resident_tax_deduction(self):
• (家乡税捐款 - 2,000日元)×10%
return (self.donation_amount - 2000) * 0.1
• 居民税特别扣除额
def special_inhabitant_tax_deduction(self):
• (家乡税捐赠金额 - 2,000 日元) × (90% - 所得税率×1.021)*1
return (self.donation_amount - 2000) * (0.9 - (self.income_tax_rate() * 1.021))
• 所得税率
def income_tax_rate(self):
tax_rate = [0.05, 0.10, 0.20, 0.23 ,0.33 , 0.40, 0.45]
borders = [i*10000 for i in [0, 195, 330, 695, 900, 1800, 4000, np.inf]]
deduction = [0, 97500, 427500, 636000, 1536000, 2796000, 4976000]
special_tax = 0.021
step = len(tax_rate)
answer = 0
i = 0
while i <= step:
if (self.income >= borders[i]) and (self.income < borders[i+1]):
answer = tax_rate[i]
i+=1
return answer
定义家乡税收抵免上限详细模拟类
class Simulator():
my_income: int = 0 = 您的工资收入
spouse_income: int = 0 = 配偶的工资收入(丈夫或妻子)
listed_capital_gain: int = 0 = 股票转让收益(上市)
unlisted_capital_gain: int = 0 = 股权转让收益(未上市)
total_income: int = 0 = 总收入
spouse: int = 0 # 配偶
spouses: 列表 [str] = [无', '是(69 岁以下)', '是 (70 岁以上)'] = 婚姻状况
widow: int = 0 # 寡妇
widows: 列表 [str] = [“非适用”, “寡妇”, “单亲(女性)”, “单亲(男性)”= 是否属于寡妇?
has_handicap: int = 0 = 是否存在残疾
handicap = { # 残疾人
“通用”: 0, # 一般 (人)
“separated_special”: 0, # 分居特别 (人)
“together_special”: 0 = 特别同居(人)
}
has_support: int = 0 = 受抚养人的存在
支持 = { = 受抚养人人数(丈夫或妻子除外)
"under_15": 0,
"from_16_to_18": 0,
"from_19_to_22": 0,
"from_23_to_69": 0,
"over_70": 0,
}
spouse_deduction: int = 0 = 配偶扣除额
widow_deduction: int = 0 = 寡妇扣除
handicap_deduction: int = 0 = 残疾扣除额
support_deduction: int = 0 = 受抚养扣除
basic_deduction: int = 0 = 基本扣除
social_insurance_premium: int = 0 = 社会保险费等金额
small_scale_enterprise_matual_aid_premium :int = 0 = 小型企业互助等应收账款金额
life_insurance_premium_deduction: int = 0 = 人寿保险费用扣除额
earthquake_insurance_premium_deduction: int = 0 = 地震保险费扣除额
medical_expense_deduction: int = 0 = 医疗费用扣除金额
housing_loans_special_deduction: int = 0 = 住房贷款等特别扣除额
income_deduction: int = 0 = 工资收入扣除额
total_deductin:int = 0 = 扣除总额
taxable_income: int = 0 = 应纳税收入金额
resident_tax: int = 0 = 居民税额
donation_amount: int = 0 = 捐赠金额
def start(self):
打印(“★家乡纳税捐赠上限诊断★”)
print()
打印(“*输入值,如果没有,则输入 0”)
print()
打印(“工资”)
self.income_section()
print()
打印(“家庭结构”)
self.famiry_section()
print()
打印(“保险、扣减等”)
self.insurance_and_deduction_section()
print()
self.total_deductin = self.social_insurance_premium + self.small_scale_enterprise_matual_aid_premium + self.life_insurance_premium_deduction + self.earthquake_insurance_ premium_deduction + self.earthquake_insurance_premium_deduction + self.medical_expense_deduction + self.housing_loans_special_deduction + self.income_deduction + self.spouse_ deduction + self.widow_deduction + self.handicap_deduction + self.support_deduction + self.basic_deduction
self.taxable_income = self.total_income - self.total_deductin
if self.taxable_income < 0:
self.taxable_income = 0
self.resident_tax = self.taxable_income * 0.1 = 税务会计师说,居民税是“粗略”收入减去扣除金额的 10%
self.donation_amount = int(输入(“捐赠金额”))
print()
calculator = Calculator(self.my_income, self.donation_amount, self.resident_tax)
result = math.floor(calculator.deduction_limit())
return result
def income_section(self):
self.my_income = int(输入(“您的工资收入(日元)”)
self.spouse_income = int(输入(“配偶工资收入(丈夫或妻子)(日元)”)
self.listed_capital_gain = int(输入(“股票转让收益(上市)(日元)”)
self.unlisted_capital_gain = int(输入(“股票转让收益(未上市)(日元)”)
self.total_income = self.my_income + self.spouse_income + self.listed_capital_gain + self.unlisted_capital_gain
def famiry_section(self):
self.__select_spouse()
self.__select_widow()
self.__select_handicap()
self.__select_support()
• 个人总收入
total_income = self.my_income + self.listed_capital_gain + self.unlisted_capital_gain
if self.spouse_income <= 480000:
• 配偶扣除
if self.spouse == 2:
if total_income <= 9000000:
self.spouse_deduction = 380000
elif (total_income > 9000000) and (total_income <= 9500000):
self.spouse_deduction = 260000
elif (total_income > 9500000) and (total_income <= 10000000):
self.spouse_deduction = 130000
else:
self.spouse_deduction = 0
elif self.spouse == 3:
if total_income <= 9000000:
self.spouse_deduction = 480000
elif (total_income > 9000000) and (total_income <= 9500000):
self.spouse_deduction = 320000
elif (total_income > 9500000) and (total_income <= 10000000):
self.spouse_deduction = 160000
else:
self.spouse_deduction = 0
else:
self.spouse_deduction = 0;
else:
• 配偶特别扣除额
if total_income <= 9000000:
if (self.spouse_income > 480000) and (self.spouse_income <= 950000):
self.spouse_deduction = 380000
elif (self.spouse_income > 950000) and (self.spouse_income <= 1000000):
self.spouse_deduction = 360000
elif (self.spouse_income > 1000000) and (self.spouse_income <= 1050000):
self.spouse_deduction = 310000
elif (self.spouse_income > 1050000) and (self.spouse_income <= 1100000):
self.spouse_deduction = 260000
elif (self.spouse_income > 1100000) and (self.spouse_income <= 1150000):
self.spouse_deduction = 210000
elif (self.spouse_income > 1150000) and (self.spouse_income <= 1200000):
self.spouse_deduction = 160000
elif (self.spouse_income > 1200000) and (self.spouse_income <= 1250000):
self.spouse_deduction = 110000
elif (self.spouse_income > 1250000) and (self.spouse_income <= 1300000):
self.spouse_deduction = 60000
elif (self.spouse_income > 1300000) and (self.spouse_income <= 1330000):
self.spouse_deduction = 30000
else:
self.spouse_deduction = 0
elif (total_income > 9000000) and (total_income <= 9500000):
if (self.spouse_income > 480000) and (self.spouse_income <= 950000):
self.spouse_deduction = 260000
elif (self.spouse_income > 950000) and (self.spouse_income <= 1000000):
self.spouse_deduction = 240000
elif (self.spouse_income > 1000000) and (self.spouse_income <= 1050000):
self.spouse_deduction = 210000
elif (self.spouse_income > 1050000) and (self.spouse_income <= 1100000):
self.spouse_deduction = 180000
elif (self.spouse_income > 1100000) and (self.spouse_income <= 1150000):
self.spouse_deduction = 140000
elif (self.spouse_income > 1150000) and (self.spouse_income <= 1200000):
self.spouse_deduction = 110000
elif (self.spouse_income > 1200000) and (self.spouse_income <= 1250000):
self.spouse_deduction = 80000
elif (self.spouse_income > 1250000) and (self.spouse_income <= 1300000):
self.spouse_deduction = 40000
elif (self.spouse_income > 1300000) and (self.spouse_income <= 1330000):
self.spouse_deduction = 20000
else:
self.spouse_deduction = 0
elif (total_income > 9500000) and (total_income <= 10000000):
if (self.spouse_income > 480000) and (self.spouse_income <= 950000):
self.spouse_deduction = 130000
elif (self.spouse_income > 950000) and (self.spouse_income <= 1000000):
self.spouse_deduction = 120000
elif (self.spouse_income > 1000000) and (self.spouse_income <= 1050000):
self.spouse_deduction = 110000
elif (self.spouse_income > 1050000) and (self.spouse_income <= 1100000):
self.spouse_deduction = 90000
elif (self.spouse_income > 1100000) and (self.spouse_income <= 1150000):
self.spouse_deduction = 70000
elif (self.spouse_income > 1150000) and (self.spouse_income <= 1200000):
self.spouse_deduction = 60000
elif (self.spouse_income > 1200000) and (self.spouse_income <= 1250000):
self.spouse_deduction = 40000
elif (self.spouse_income > 1250000) and (self.spouse_income <= 1300000):
self.spouse_deduction = 20000
elif (self.spouse_income > 1300000) and (self.spouse_income <= 1330000):
self.spouse_deduction = 10000
else:
self.spouse_deduction = 0
else:
self.spouse_deduction = 0
if total_income <= 5000000:
• 寡妇扣除
if self.widow == 1:
self.widow_deduction = 270000
• 单亲扣除
elif (self.widow == 2) or (self.widow == 3):
self.widow_deduction = 350000
else:
self.widow_deduction = 0
else:
self.widow_deduction = 0
• 残疾人扣除
if self.has_handicap == 1:
self.handicap_deduction = 270000 * self.handicap['general'] + 400000 * self.handicap['separated_special'] + 750000 * self.handicap['together_special ']
else:
self.handicap_deduction = 0
• 受抚养人扣除
if self.has_support == 1:
self.support_deduction = 380000 * self.support['from_16_to_18'] + 630000 * self.support['from_19_to_22'] + 480000 * self.support['from_23_to_69'] + 580000 * self.support['over_70']
else:
self.support_deduction = 0
def insurance_and_deduction_section(self):
self.social_insurance_premium = int(输入(“社会保险费等金额(日元)”)
self.small_scale_enterprise_matual_aid_premium = int(输入(“小型企业互助等应收账款金额(日元)”)
self.life_insurance_premium_deduction = int(输入(“人寿保险费扣除额(日元)”)
self.earthquake_insurance_premium_deduction = int(输入(“地震保险费扣除额(日元)”)
self.medical_expense_deduction = int(输入(“医疗费用扣除金额(日元)”)
self.housing_loans_special_deduction = int(输入(“住房借款等特别扣除额(日元)”)
• 收入扣除
if self.total_income < 1625000:
self.income_deduction = 550000
elif (self.total_income >= 1625001) and (self.total_income < 1800000):
self.income_deduction = self.total_income * 0.4 - 100000
elif (self.total_income >= 1800001) and (self.total_income < 3600000):
self.income_deduction = self.total_income * 0.3 + 80000
elif (self.total_income >= 3600001) and (self.total_income < 6600000):
self.income_deduction = self.total_income * 0.2 + 440000
elif (self.total_income >= 6600001) and (self.total_income < 8500000):
self.income_deduction = self.total_income * 0.1 + 1100000
else:
self.income_deduction = 1950000
• 基本扣除额
if self.total_income <= 24000000:
self.basic_deduction = 480000
elif (self.total_income > 24000000) and (self.total_income <= 24500000):
self.basic_deduction = 320000
elif (self.total_income > 24000000) and (self.total_income <= 25000000):
self.basic_deduction = 160000
else:
self.basic_deduction = 0
def __select_spouse(self):
打印(“婚姻状况”)
for i, sponse in enumerate(self.spouses):
print(str(i+1) + '. ' + sponse)
自.spouse = int(输入(请选择“编号”)。 '))
def __select_widow(self):
打印(是否属于“寡妇”? ')
for i, widow in enumerate(self.widows):
print(str(i+1) + '. ' + widow)
self.widow = int(输入(请选择“编号”)。 '))
def __select_handicap(self):
self.has_handicap = int(输入(“有无残疾人 1。 是,2. 无'))
if self.has_handicap == 1:
self.handicap [“外在”] = int(输入(“一般残疾人(人)”)
self.handicap ['separated_special'] = int(输入(“个人/分居的特别残疾人(人)”)
自.handicap [“together_special”] = int(输入(“同居特殊残疾人(人)”)
def __select_support(self):
self.has_support = int(输入(“受抚养人的存在或不存在 1。 是,2. 无'))
if self.has_support == 1:
self.support['under_15'] = int(输入('15岁以下'))
self.support['from_16_to_18'] = int(输入('16-18岁')
self.support['from_19_to_22'] = int(输入('19-22岁')
self.support['from_23_to_69'] = int(输入('23-69岁'))
self.support['over_70'] = int(输入('70岁以上'))
定义如何以多种方式解决背包问题
class KnapsackProblem():
values: List[int] = []
weights: List[int] = []
max_weight: int = 0
def __init__(self, values, weights, max_weight):
self.values = values
self.weights = weights
self.max_weight = max_weight
def solve_by_qaoa(self):
problem = Knapsack(values=self.values, weights=self.weights, max_weight=self.max_weight)
quadratic_program = problem.to_quadratic_program()
backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=800, seed_simulator=99)
min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=quantum_instance))
solved = min_eigen_optimizer.solve(quadratic_program)
result = problem.interpret(solved)
print(result)
return result
def solve_by_numpy_eigensolver(self):
problem = Knapsack(values=self.values, weights=self.weights, max_weight=self.max_weight)
quadratic_program = problem.to_quadratic_program()
min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
solved = min_eigen_optimizer.solve(quadratic_program)
result = problem.interpret(solved)
print(result)
return result
def solve_by_ortoolpy(self):
result = knapsack(self.weights, self.values, self.max_weight)
print(result)
return result
def solve_by_pulp(self):
ran = range(len(self.values))
problem = LpProblem(sense=LpMaximize)
var = [LpVariable('x%d'%i, cat=LpBinary) for i in ran]
problem += lpDot(self.weights, var)
problem += lpDot(self.values, var) <= self.max_weight
problem.solve()
result = (value(problem.objective), [i for i in ran if value(var[i]) > 0.5])
print(result)
return result
def solve_by_greedy_algorithm(self):
N = len(self.values)
W = self.max_weight
w = self.weights
v = self.values
dp = [[0]*(W+1) for i in range(N+1)]
for i in range(N):
for j in range(W+1):
if j < w[i]:
dp[i+1][j] = dp[i][j]
else:
dp[i+1][j] = max(dp[i][j], dp[i][j-w[i]]+v[i])
result = dp[N][W]
print(result)
return result
def solve_by_ising_model(self):
def Hamiltonian(x):
B = 10
W = self.max_weight
w_sum = 0
v_sum = 0
for i, w in enumerate(self.weights):
w_sum += w*x[i]
for i, v in enumerate(self.values):
v_sum += v*x[i]
H = B*(W-w_sum)**2-v_sum
return H
def run(H):
N = len(self.values)
T = self.max_weight
ite = 1000
targetT = 0.02
red = 0.97
q = [random.randint(0,1) for i in range(N)]
# q = [1,1,1,1,0,0,0,0,0,0]
while T>targetT:
x_list = np.random.randint(0, N, ite)
for x in x_list:
q2 = copy.copy(q)
y = np.random.randint(0, N)
q2[x] = q[y]
q2[y] = q[x]
dE = H(q2) - H(q)
if np.exp(-dE/T) > np.random.random_sample():
q[x] = q2[x]
q[y] = q2[y]
T *= red
return q
answer = run(Hamiltonian)
result = []
for i, a in enumerate(answer):
if a == 1:
result.append(i)
print(result)
return
从乐天 API 获取产品列表
REQUEST_URL = "https://app.rakuten.co.jp/services/api/IchibaItem/Search/20170706"
APP_ID=“<乐天API的应用程序ID>”
serch_keyword = “家乡纳税翻译”
serch_params = {
"format" : "json",
"keyword" : serch_keyword,
"applicationId" : [APP_ID],
"availability" : 0,
"hits" : 30,
"sort" : "standard",
"postageFlag" : 1
}
item_list = []
max_page = 10
for page in range(1, max_page+1):
response = requests.get(REQUEST_URL, serch_params)
result = response.json()
item_key = ['itemName', 'itemPrice', 'itemCaption', 'shopName', 'shopUrl', 'itemUrl']
for i in range(0, len(result['Items'])):
time.sleep(1)
tmp_item = {}
item = result['Items'][i]['Item']
for key, value in item.items():
if key in item_key:
tmp_item[key] = value
item_list.append(tmp_item.copy())
df = pd. DataFrame(item_list)
df.drop_duplicates(subset=['itemUrl'], inplace=True) # 重複删除
df = df.reindex(columns=['itemName', 'itemPrice', 'itemCaption', 'itemUrl', 'shopName', 'shopUrl'])
df.columns = [“商品名称”,“商品价格”,“商品说明”,“商品URL”,“商店名称”,“商店网址”]
df.index = df.index + 1
• 仅提取知道数量的产品
weight = df['商品名'].str.contains('kg')
df = df[weight]
df['kg'] = df['商品名'].str.extract('([0-9]+)kg')
df = df.reindex(columns=[“商品名称”,“kg”,“商品价格”,“商品说明”,“商品URL”,“商店名称”,“商店网址”]
数据确认
df.head()
df.plot(标题='重量与价格的关系')
实用解决方案(取决于 ortoolpy)
def practical_solution():
simulator = Simulator()
weights = [int(data) for i, data in enumerate(df['kg'])]
prices = [int(data) for i, data in enumerate(df[商品价格']]]
deduction_limit = simulator.start()
• 背包的价格等是有价值的,并且有重量限制。 在这种情况下,有一个价格限制,以重量的价值。
knapsack_problem = KnapsackProblem(values=weights, weights=prices, max_weight=deduction_limit)
result = knapsack_problem.solve_by_ortoolpy()
打印(f'扣除上限为{deduction_limit}日元')
HTML(df.to_html(render_links=True, escape=False))
def make_clickable(val):
return f'<a target="_blank" href="{val}">{val}</a>'
return df.iloc[result[1]].style.format({'商品URL': make_clickable, '店铺URL': make_clickable})
量子算法解决方案 (QAOA)
def futurism_solution():
simulator = Simulator()
权重 = [int(数据) for i,数据在 enumerate(df['kg'])][0:10] = Colab 内存和量子计算机当前性能的 10 个限制(10 个,我什么都不知道,但请原谅)
prices = [int(data) for i, data in enumerate(df[商品价格'])][0:10] # 以上相同
deduction_limit = simulator.start()
• 背包的价格等是有价值的,并且有重量限制。 在这种情况下,有一个价格限制,以重量的价值。
knapsack_problem = KnapsackProblem(values=weights, weights=prices, max_weight=deduction_limit)
result = knapsack_problem.solve_by_qaoa()
打印(f'扣除上限为{deduction_limit}日元')
HTML(df.to_html(render_links=True, escape=False))
def make_clickable(val):
return f'<a target="_blank" href="{val}">{val}</a>'
return df.iloc[result].style.format({'商品URL': make_clickable, '店铺URL': make_clickable})
执行
实际解决方案的结果(在扣除上限内选择较重的)
practical_solution()
量子算法求解的结果(从执行开始到结束需要 30 分钟到 1 小时)(在扣除上限内选择较重的解)
futurism_solution()