【问题标题】:Calling Functions repeatedly in Mathematica在 Mathematica 中重复调用函数
【发布时间】:2021-03-06 03:17:03
【问题描述】:

我有以下 python 代码,我想将其转换为 Mathematica。但是我完全不知道如何在 Mathematica 中定义我的函数 def shouldSwapdef findPermutations,然后 调用 findPermutations 以获取索引+ 1。如何在 Mathematica 中定义此类函数?非常感谢您的帮助!

我的python代码:

def shouldSwap(string, start, curr):
for j in range(strat, curr):
    if string[j] == string[curr]:
         return 0
return 1

def findPermutations(string, index, n):
    if index >= n:
       print(''.join(String))
       return
    for i in range(index, n):
        check = shouldSwap(string index, i)
        if check:
            string[index], string[i] = string[i], string[index]
            findPermutations(string, index + 1, n)
            string[index], string[i] = string[i], string[index]

if __name__ == "__main__":
    string = list("ABCA")
    n = len(string)
    findPermutations(string, 0, n)

我将其转换为 Mathematica 的尝试失败了:

string = List[A, B, C, A]
n = Length[string]
index = 0;
If[index>=n, string, Return]
If[index<n,
    For[i = index, i<n, i+1, 
            If[ 
                For[j = index, j<i, j++,
                           If[string[j] == string[i], Return,
                                   Swap[string[index], string[i]] and
             How do I do this???   findPermutations(string, index + 1, n) and
                                   Swap[string[index], string[i]]
                   ]
                 ]
          ]
      ]

【问题讨论】:

    标签: wolfram-mathematica mathematical-expressions


    【解决方案1】:

    Python 代码中有几个语法错误。有理由想要音译吗? WL 的实现方式

    "ABCA" // Characters // Permutations // Map[StringJoin]
    
    {"ABCA", "ABAC", "ACBA", "ACAB", "AABC", "AACB", "BACA", "BAAC", "BCAA", "CABA", "CAAB", "CBAA"}
    

    【讨论】:

    • 因为我是 Mathematica 的新手,所以我不知道所有排列都有一个函数!谢谢你让我知道 - 在这种情况下,我不必再转换我的代码了......
    • @studentnr 欢迎您。如果我的回答对您有帮助,您是否介意接受并点赞。
    猜你喜欢
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 2016-11-08
    • 2010-12-10
    • 2017-01-11
    • 2012-12-30
    • 2012-09-07
    相关资源
    最近更新 更多