我有以下列表:['2*3=6', '3*2=6', '1+10/2=6.0', '2/1*3=6', '2*3/1=6', '3/1*2=6', '3*2/1=6', '10/2+1=6']
我想过滤掉与所使用的数字相等的方程式。有了这个,我的意思是,我想要得到一个方程的列表,它只包含唯一的数字组合。例如: 2*3或3*2,1+10/2=6.0或10/2+1=6.0等。我还想打印出在计算中没有使用的数字,如:(3*2=6未使用:1和10)等。
还没有能够编写这样的函数,因为我看不出我们需要比较什么。我希望这个函数在1到9之间工作。所以,1给出了列表:['2-1=1', '3-2=1', '1*3-2=1', '3-1*2=1', '3*1-2=1', '3/1-2=1', '3-2*1=1', '3-2/1=1']
,我想以同样的方式过滤这个函数。感谢你的帮助!
发布于 2019-09-24 12:11:22
下面是一种很好的前进方式:
import re
eqs = ['2*3=6', '3*2=6', '1+10/2=6', '2/1*3=6', '2*3/1=6', '3/1*2=6', '3*2/1=6', '10/2+1=6']
by_digits_used = {}
remaining_digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for eq in eqs:
used_digits = [int(f) for f in re.findall(r'\d*', eq) if f != ""] # Find all digits in the equations
used_digits.sort() # Ensure they're always in the same order
used_digits = tuple(used_digits) # Convert to tuple
# Remove digits that were used
for digit in used_digits:
if digit in remaining_digits:
remaining_digits.remove(digit)
# Store equation by the digits used
by_digits_used[used_digits] = by_digits_used.get(used_digits, []) + [eq]
print(by_digits_used)
print(remaining_digits)
结果:
# Equations by digits used
{(2, 3, 6): ['2*3=6', '3*2=6'], (1, 2, 6, 10): ['1+10/2=6', '10/2+1=6'], (1, 2, 3, 6): ['2/1*3=6', '2*3/1=6', '3/1*2=6', '3*2/1=6']}
# Unused digits
{0, 4, 5, 7, 8, 9}
发布于 2019-09-24 14:14:07
您可以使用字典,并设置如下所示
import re
from itertools import chain
ls = ['2*3=6', '3*2=6', '1+10/2=6.0', '2/1*3=6', '2*3/1=6', '3/1*2=6', '3*2/1=6', '10/2+1=6']
exp = '10/2+1=6'
sorted_nums = [sorted([nums for nums in re.findall("(\d+)", exp )]) for exp in ls]
unused_nums = set(map(str, range(1,10)))-set(chain(*sorted_nums))
nums_in_exps = {}
for nums, exp in zip(sorted_nums, ls):
key = "-".join(nums)
if key not in nums_in_exps:
nums_in_exps[key] = []
nums_in_exps[key] += [exp]
print("expression with nums")
print(nums_in_exps)
print("unused numbers")
print(unused_nums)
输出
expression with nums
{'2-3-6': ['2*3=6', '3*2=6'], '0-1-10-2-6': ['1+10/2=6.0'], '1-2-3-6': ['2/1*3=6', '2*3/1=6', '3/1*2=6', '3*2/1=6'], '1-10-2-6': ['10/2+1=6']}
unused numbers
{'8', '4', '9', '7', '5'}
发布于 2019-09-24 14:18:07
使用frozenset
的替代选项
import re
import string
s = ['2*3=6', '3*2=6', '1+10/2=6.0', '2/1*3=6', '2*3/1=6', '3/1*2=6', '3*2/1=6', '10/2+1=6']
s = [i.replace('.0', '') for i in s] # remove floats
d = {frozenset(re.split('[\+\-\*\/=]', i)): i for i in s}
print('Unique equations: ' , *d.values())
print('Unused numbers: ', set(string.digits) - frozenset.union(*d.keys()))
版画
Unique equations: 3*2=6 10/2+1=6 3*2/1=6
Unused numbers: {'4', '0', '5', '9', '7', '8'}
https://stackoverflow.com/questions/58079735
复制相似问题