迭代动态数量的for循环(Python)

时间:2016-03-15 13:21:09

标签: python arrays for-loop numpy

我正在使用python对一些数字进行排序。我想创建一个函数,允许我输入一个值(4,8,16,32,64等),创建一个数字数组,并重新排列它们的序列。

我添加了详细说明如何确定value = 4和8的序列的数据。

对于值= 4,数组(x = [0,1,2,3])应分为两部分([0,1]和[2,3]),然后根据每个数字中的第一个数字进行组合数组([0,2,1,3])。

Figure with sequence for value = 4

对于值= 8,数组(x = [0,1,2,3,4,5,6,7])应分为两个([0,1,2,3]和[4,5] ,6,7])。两个阵列应再次分成两部分([0,1,2,3]分为[0,1]和[2,3]和[4,5,6,7]分为[4,5]和[6, 7])。然后应根据每个数组中的第一个数字和第二组数组的序列([0,4,2,6,1,5,3,7])组合数组。

Figure for sequence for value = 8

我不知道如何处理递归(动态嵌套for循环)。我试图循环通过拆分数组创建的每个brach。我查看了itertools和递归(Function with varying number of For Loops (python)),但我无法使其工作。下面,我添加了代码来说明我迄今为止的方法。

非常感谢任何帮助。我也愿意接受其他想法来确定序列。

我正在使用python 2.7.6和numpy。

代码:

!ENTRY org.eclipse.jface 4 2 2016-03-08 12:39:04.740
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface".
!STACK 0
java.lang.NoClassDefFoundError: org/eclipse/jdt/internal/formatter/comment/Java2HTMLEntityReader
    at com.google.gwt.eclipse.oophm.views.hierarchical.LogContent.convertToHtmlContent(LogContent.java:237)
    at com.google.gwt.eclipse.oophm.views.hierarchical.LogContent.buildLabelHtml(LogContent.java:332)
    at com.google.gwt.eclipse.oophm.views.hierarchical.LogContent.updateDetailsPane(LogContent.java:599)
    at com.google.gwt.eclipse.oophm.views.hierarchical.LogContent.access$4(LogContent.java:568)
    at com.google.gwt.eclipse.oophm.views.hierarchical.LogContent$4.selectionChanged(LogContent.java:454)
    at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:163)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173)
    at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java:160)
    at org.eclipse.jface.viewers.StructuredViewer.updateSelection(StructuredViewer.java:2197)
    at org.eclipse.jface.viewers.StructuredViewer.setSelection(StructuredViewer.java:1733)
    at org.eclipse.jface.viewers.TreeViewer.setSelection(TreeViewer.java:1093)
    at org.eclipse.jface.viewers.Viewer.setSelection(Viewer.java:388)
    at com.google.gwt.eclipse.oophm.model.LogContentProvider$2.run(LogContentProvider.java:132)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4155)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3772)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:694)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:606)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1515)

输出:

import numpy
value = 4
a = []
x = numpy.arange(value)
y = numpy.array_split(x, 2)
for i in range(2):
    for j in y:
        a.append(j.tolist()[i])
print(a)

代码:

[0, 2, 1, 3]

输出:

import numpy
value = 8
a = []
x = numpy.arange(value)
y = numpy.array_split(x, 2)
for i in range(2):
    for h in range(2):
        for j in y:
        z = numpy.array_split(j, 2)
                a.append(z[h][i])
    print(a)

值= 16的输出应为[0,8,4,12,2,10,6,14,1,9,5,13,​​3,11,715]。

3 个答案:

答案 0 :(得分:2)

以下是使用np.transposereshaping的NumPythonic方式 -

def seq_pow2(N):
    shp = 2*np.ones(np.log2(N),dtype=int)
    return np.arange(N).reshape(shp).transpose(np.arange(len(shp))[::-1]).ravel()

请注意,.transpose(np.arange(len(shp))[::-1]会简化为.T,因此我们会有一个简化版本 -

def seq_pow2(N):
    shp = 2*np.ones(np.log2(N),dtype=int)
    return np.arange(N).reshape(shp).T.ravel()

您可以通过ravel / flattening执行fortran / .ravel('F')进一步简化和替换转置,例如def seq_pow2(N): shp = 2*np.ones(np.log2(N),dtype=int) return np.arange(N).reshape(shp).ravel('F') In [43]: seq_pow2(4) Out[43]: array([0, 2, 1, 3]) In [44]: seq_pow2(8) Out[44]: array([0, 4, 2, 6, 1, 5, 3, 7]) In [45]: seq_pow2(16) Out[45]: array([ 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]) 中的 System.out.print("PROCEED? (Y/N):\t"); Scanner in = new Scanner(System.in); String line=in.nextLine(); Character ch=line.charAt(0); while(ch!='y' && ch!='n' && ch!='Y' && ch!='N'){ System.out.print("NON-VALID INPUT. TYPE Y-N:\t"); line=in.nextLine(); ch=line.charAt(0); } ,以便最终引导我们 -

name

样品运行 -

post_like

答案 1 :(得分:2)

python递归版,为清晰起见:

def rec(n):
    if n==1 : return [0]
    l=[0]*n
    l[::2]=rec(n//2)
    for i in range (0,n,2) : l[i+1]=l[i]+n//2
    return l

In [6]: rec(16)
Out[6]: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]

或者,观察结果的二进制表示,一个numpy解决方案:

def rearange(N):
    u=2**arange(N.bit_length()-1)
    v=arange(N)
    bits= u[None,:] & v[:,None]
    return sum(bits*u[::-1],1)

答案 2 :(得分:1)

最简单的方法是使用for循环,但用numpy进行一些数组操作。

N = 8
pow2 = np.log2(N)
out = np.arange(N).reshape([2]*pow2).transpose(np.arange(pow2)[::-1]).flatten()   

   array([0, 4, 2, 6, 1, 5, 3, 7])

这样做是将x重新整形为n维数组,其中n是2的幂,对应x的长度。重新整形后,每个尺寸的长度为2.然后我们反转所有尺寸并展平以获得所需的阵列。

修改

这是Divakar's Solution的类似方法,他最后简明扼要地做了这件事,但我会把这个留给后人。