如何避免为可交换运算符生成相同的表达式

时间:2018-04-17 18:35:48

标签: python

我想从一组变量和运算符开始构建一组所有可能的表达式。但是,我想要同时生成' a + b'和' b + a',因为它们是相同的,在数学上;而' a / b'和' b / a'不是。 我试图区分交换和非交换列表中的运算符,但不知道如何编写可以避免简并的交换primary_descriptors=['a', 'b'] commutative_operators=['+', '*'] non_commutative_operators=['-','/'] b=[] for x in primary_descriptors: for y in commutative_operators: b.append([x+y+z for z in primary_descriptors if z!=x]) d=[] for x in primary_descriptors: for y in non_commutative_operators: d.append([x+y+z for z in primary_descriptors if z!=x]) flat_list_1 = [item for sublist in b for item in sublist] #from Alex Martelli's answer flat_list_2 = [item for sublist in d for item in sublist] print(flat_list_1) print(flat_list_2) 循环。

['a+b', 'a*b', 'b+a', 'b*a']
['a-b', 'a/b', 'b-a', 'b/a']

此代码的输出是

import UIKit
import WebKit


class PDF1: UIViewController {


    @IBOutlet var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let path = Bundle.main.path(forResource: "Brewolution A Bunnys Tale - Påske 2012", ofType: ".pdf")
        let url = URL(fileURLWithPath: path!)
        let request = URLRequest(url: url)

        webView.load(request)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func sharePressed(_ sender: Any) {
        let activityController = UIActivityViewController(activityItems: [self.webView], applicationActivities: nil)
        present(activityController, animated: true, completion: nil)

    }


} 

但我只想在第一行中使用[' a + b',' a * b']。

3 个答案:

答案 0 :(得分:3)

这是一个itertools解决方案。 itertools.permutations可用于获取两个订单中的所有货币对,而itertools.combinations可用于获取所有货币对但只有一个订单:

>>> from itertools import permutations, combinations
>>> primary_descriptors='abc'
>>> commutative_operators='+*'
>>> non_commutative_operators='-/'
>>> 
>>> [op.join(pair) for pair in combinations(primary_descriptors, 2) for op in commutative_operators]
['a+b', 'a*b', 'a+c', 'a*c', 'b+c', 'b*c']
>>> [op.join(pair) for pair in permutations(primary_descriptors, 2) for op in non_commutative_operators]
['a-b', 'a/b', 'a-c', 'a/c', 'b-a', 'b/a', 'b-c', 'b/c', 'c-a', 'c/a', 'c-b', 'c/b']

答案 1 :(得分:2)

一个好方法是使用不等式运算符,这将有效地防止'b'在'a'之前:

combinations = []
primary_descriptors=['a', 'b']
commutative_operators=['+', '*']
for x in primary_descriptors:
    for y in commutative_operators:
        combinations += [(x, y, z) for z in primary_descriptors if x <= z]
print(combinations)

答案 2 :(得分:1)

当您为可交换运算符编写循环时,为所有操作数运行外部循环,但内部循环仅适用于操作数列表中的后循环。这样的事,也许......

for x_index, x in enumerate(primary_descriptors):
    for y in commutative_operators:
        b.append([x+y+z for z in primary_descriptors[x_index+1:] ])

新输出:

['a+b', 'a*b']
['a-b', 'a/b', 'b-a', 'b/a']