22.Flatten List-平面列表(容易题)

本文介绍了一种将嵌套列表转换为单一整数列表的方法,包括递归与非递归两种实现方式。递归方法直观易懂,而非递归方法使用栈结构进行迭代处理。

平面列表

  1. 题目

    给定一个列表,该列表中的每个要素要么是个列表,要么是整数。将其变成一个只包含整数的简单列表。

    注意事项

    如果给定的列表中的要素本身也是一个列表,那么它也可以包含列表。

  2. 样例

    给定 [1,2,[1,2]],返回 [1,2,1,2]。
    给定 [4,[3,[2,[1]]]],返回 [4,3,2,1]。

  3. 挑战

    请用非递归方法尝试解答这道题。

  4. 题解

    1.递归解法

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer,
 *     // rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds,
 *     // if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds,
 *     // if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class Solution {

    // @param nestedList a list of NestedInteger
    // @return a list of integer
    List<Integer> result = new ArrayList<Integer>();

    public List<Integer> flatten(List<NestedInteger> nestedList) {
        for (int i=0;i<nestedList.size();i++)
        {
            if (nestedList.get(i).isInteger())
            {
                result.add(nestedList.get(i).getInteger());
            }
            else
            {
                flatten(nestedList.get(i).getList());
            }
        }

        return result;
    }
}

2.非递归解法

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer,
 *     // rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds,
 *     // if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds,
 *     // if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class Solution {

    // @param nestedList a list of NestedInteger
    // @return a list of integer

    public List<Integer> flatten(List<NestedInteger> nestedList) {
        Stack<NestedInteger> stack = new Stack<>();
        List<Integer> result = new ArrayList<Integer>();
        pushInStack(stack,nestedList);
        while (!stack.empty())
        {
            if (stack.peek().isInteger())
            {
                result.add(stack.pop().getInteger());
            }
            else
            {
                pushInStack(stack,stack.pop().getList());
            }

        }
        Collections.reverse(result);
        return result;
    }

    private void pushInStack(Stack<NestedInteger> stack,List<NestedInteger> nestedList)
    {
        for (int i=0;i<nestedList.size();i++)
        {
            stack.push(nestedList.get(i));            
        }
    }
}

Last Update 2016.8.28

import pyglet import numpy as np from pyglet.gl import * class BirthdayAnimation: def __init__(self, width=800, height=600): self.width = width self.height = height self.window = pyglet.window.Window(width, height, "生日祝福动画") self.batch = pyglet.graphics.Batch() # 粒子数量 self.particle_count = 10000 # 粒子位置 self.particle_positions = np.random.uniform(-100, 100, (self.particle_count, 3)).astype(np.float32) # 粒子颜色(白色半透明) self.particle_colors = np.array([1.0, 1.0, 1.0, 0.8] * self.particle_count, dtype=np.float32) # 粒子大小 self.particle_sizes = np.ones(self.particle_count, dtype=np.float32) * 1.0 # 初始化粒子顶点列表 self.particle_list = self.batch.add( self.particle_count, GL_POINTS, None, ('v3f', self.particle_positions.flatten()), ('c4f', self.particle_colors), ('size', self.particle_sizes) ) # 文字列表 self.texts = [ "Hi 某某某", "祝你", "生日快乐", "天天开心", "愿你", "满目星河", "所愿", "皆成真" ] self.current_text_index = 0 self.text_label = None self.text_switch_time = 2.0 # 文字切换时间(秒) self.last_text_switch = 0 # 窗口事件回调 self.window.on_draw = self.on_draw pyglet.clock.schedule(self.update) def on_draw(self): self.window.clear() glClearColor(0, 0, 0, 1) # 黑色背景 # 启用深度测试 glEnable(GL_DEPTH_TEST) # 启用混合(实现透明效果) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # 设置投影矩阵 glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(75, self.width / self.height, 0.1, 200) # 设置模型视图矩阵 glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0, 0, 30, 0, 0, 0, 0, 1, 0) # 绘制粒子 self.particle_list.draw() # 绘制文字 if self.text_label: self.text_label.draw() def update(self, dt): # 旋转粒子星河 self.particle_positions = self.particle_positions.dot(np.array([ [np.cos(0.001), -np.sin(0.001), 0], [np.sin(0.001), np.cos(0.001), 0], [0, 0, 1] ])) self.particle_list.vertices = self.particle_positions.flatten() # 切换文字 self.last_text_switch += dt if self.last_text_switch >= self.text_switch_time: if self.text_label: self.text_label.delete() self.text_label = pyglet.text.Label( self.texts[self.current_text_index], font_name='Arial', font_size=36, x=self.width // 2, y=self.height // 2, anchor_x='center', anchor_y='center', color=(255, 255, 255, 255) ) self.current_text_index = (self.current_text_index + 1) % len(self.texts) self.last_text_switch = 0 if __name__ == "__main__": animation = BirthdayAnimation() pyglet.app.run()
最新发布
12-07
%matplotlib notebook import numpy as np import math from spatialmath import SE3 from spatialmath.base import e2h, h2e from roboticstoolbox import * from machinevisiontoolbox import CentralCamera cam = CentralCamera(f=[919.21981864*10e-6,913.16565134*10e-6], rho=10e-6, imagesize=[640, 480], pp=[356.41270451,236.9305], name="mycamera") print(cam) P=np.array([-0.18, 0, -0.01]) DFbot1 = DHRobot( [ RevoluteMDH(d=0.04145,qlim=np.array([-np.pi,np.pi])), RevoluteMDH(alpha=np.pi/2,qlim=np.array([-np.pi,np.pi])), RevoluteMDH(a=-0.08285,qlim=np.array([-np.pi,np.pi])), RevoluteMDH(a=-0.08285,qlim=np.array([-np.pi,np.pi])), RevoluteMDH(alpha=-np.pi/2,qlim=np.array([0,np.pi])), RevoluteMDH(a=0.04,d=0.057,qlim=np.array([-np.pi,np.pi])) ], name="DFbot", ) DFbot2 = DHRobot( [ RevoluteMDH(d=0.04145,qlim=np.array([-np.pi/2,np.pi/2])), RevoluteMDH(alpha=np.pi/2,qlim=np.array([-np.pi/2,np.pi/2])), RevoluteMDH(a=-0.08285,qlim=np.array([-np.pi/2,np.pi/2])), RevoluteMDH(a=-0.08285,qlim=np.array([-np.pi/2,np.pi])), RevoluteMDH(alpha=-np.pi/2,d=0.11,qlim=np.array([0,np.pi])) ], name="DFbot", ) #视觉校正 T1=DFbot1.fkine([0,-np.pi/3,np.pi/3,np.pi,0,0]) SE3(T1) DFbot1.plot([0,-np.pi/3,np.pi/3,np.pi,0,0]) #末端摄像机旋转90度 T1=DFbot1.fkine([0,-np.pi/3,np.pi/3,np.pi,0,np.pi/2]) SE3(T1) DFbot1.plot([0,-np.pi/3,np.pi/3,np.pi,0,np.pi/2]) #单一点投影 p = cam.project_point(P, pose=T1 ) cam.plot_point(P, pose=T1 ) #立方体投影 from spatialmath import SE3 from machinevisiontoolbox import mkcube X, Y, Z = mkcube(s=0.03,centre=(-0.165, 0, -0.025), edge=True) cam.plot_wireframe(X, Y, Z,pose=T1) #求解深度 mtx=np.array([[919.21981864, 0. , 356.41270451], [ 0. , 913.16565134, 236.9305 ], [ 0. , 0. , 1. ]]) # 内参矩阵 K = mtx # 位姿矩阵 pose=T1 # 外参矩阵(位姿矩阵的逆) extrinsic = np.linalg.inv(pose) # 3D点(世界坐标系) point_3d = np.array([-0.165, 0, -0.01, 1]) # 将点从世界坐标系转换到相机坐标系 point_camera = extrinsic @ point_3d # 投影到图像平面 point_2d = K @ point_camera[:3] depth=point_2d[2] point_2d /= depth # 归一化 # 内参矩阵 K = mtx # 位姿矩阵 pose=T1 # 外参矩阵(位姿矩阵的逆) extrinsic = np.linalg.inv(pose) # 3D点(世界坐标系) point_3d = np.array([-0.165, 0, -0.01, 1]) # 将点从世界坐标系转换到相机坐标系 point_camera = extrinsic @ point_3d # 投影到图像平面 point_2d = K @ point_camera[:3] depth=point_2d[2] point_2d /= depth # 归一化 point_2d depth xaxis=356.41270451-100 yaxis=226.9298497+50 point_2d=depth*np.array([xaxis,yaxis,1]) point_camera=e2h(np.linalg.inv(K)@point_2d) new_point_3d=np.array(np.linalg.inv(extrinsic)@point_camera) new_point_3d T1 T21=DFbot2.fkine([0,-np.pi/3,np.pi/3,np.pi,0]) T21 T2=np.array(T21) T2[:,-1]=new_point_3d.flatten() #T2[2,-1]=0.01T2 sol = DFbot2.ikine_LM(T2,q0=[0,-np.pi/3,np.pi/3,np.pi,0],ilimit=5000, slimit=5000,joint_limits=True, tol=0.01) sol qt = jtraj([0,-np.pi/3,np.pi/3,np.pi,0],sol.q,100) DFbot2.plot(qt.q,backend='pyplot',movie='pandal.gif') 为每一行写详细的注释,并且说明所有小块都在做什么事?同时写出内置函数的语法。
05-15
ros1小车,带6轴机械臂+双目深度相机,实现手眼标定,Python 版本2.7,opencv版本3.2.0,不使用moveit, 机械臂可以通过示教软件移动,棋盘格标定尺寸7*9,棋格20mm,相机自动采集数据,示教到位后,手动输入命令保存当前位姿机械臂状态信息,和相机获取的image和info参数如下nvidia@nvidia-desktop:~/YaLongR8$ rostopic echo /ascamera/rgb0/image header: seq: 189 stamp: secs: 1752635219 nsecs: 65778841 frame_id: “ascamera_color_0” height: 480 width: 640 encoding: “bgr8” is_bigendian: 0 step: 1920 data: [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,nvidia@nvidia-desktop:~/YaLongR8$ rostopic echo /ascamera/rgb0/camera_info header: seq: 168 stamp: secs: 1752635114 nsecs: 905740201 frame_id: “ascamera_color_0” height: 480 width: 640 distortion_model: “plumb_bob” D: [0.0, 0.0, 0.0, 0.0, 0.0] K: [580.0127563476562, 0.0, 314.1075439453125, 0.0, 579.5506591796875, 251.95277404785156, 0.0, 0.0, 1.0] R: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] P: [580.0127563476562, 0.0, 314.1075439453125, 0.0, 0.0, 579.5506591796875, 251.95277404785156, 0.0, 0.0, 0.0, 1.0, 0.0] binning_x: 1 binning_y: 1 roi: x_offset: 0 y_offset: 0 height: 480 width: 640 do_rectify: False —/ascamera/depth0/camera_info /ascamera/depth0/image_raw /ascamera/depth0/points /ascamera/mjpeg0/compressed /ascamera/rgb0/camera_info /ascamera/rgb0/imagenvidia@nvidia-desktop:~/YaLongR8$ rostopic echo /TR_Arm_topic name: “arm0” dof: 0 servoState: True clawState: False terminal: [413.23297119140625, 0.00019795788102783263, 188.2457733154297, 180.0, 44.99720001220703, 180.0] joints: [-0.0, 0.0, 0.0021423338912427425, 0.00010986327833961695, 45.00065994262695, -0.00010986327833961695] homogeneousMatrix: [-0.7071413397789001, 3.5873307771542613e-17, 0.7070721983909607, 413.23297119140625, 8.659984119900181e-17, 1.0, 3.5873307771542613e-17, 0.00019795788102783263, -0.7070721983909607, 8.659984119900181e-17, -0.7071413397789001, 188.2457733154297, 0.0, 0.0, 0.0, 1.0] float_array: [] integer_value: 0 —参数如上 写py文件,眼在手模型,
07-17
import win32com.client import pythoncom import numpy as np # 创建SAFEARRAY的函数,支持1D或2D数组 def create_safearray(data, dimensions=1): np_data = np.array(data, dtype=np.float64) # 如果是二维数组,reshape为-1, 3的形状 if dimensions == 2: np_data = np_data.reshape(-1, 3) else: np_data = np_data.flatten() return win32com.client.VARIANT( pythoncom.VT_ARRAY | pythoncom.VT_R8, np_data.tolist() # 将数组转为Python列表 ) def create_catia_part(): try: # 初始化CATIA catia = win32com.client.Dispatch("CATIA.Application") catia.Visible = True # 创建新零件 docs = catia.Documents part_doc = docs.Add("Part") part = part_doc.Part # 创建几何体 bodies = part.Bodies body = bodies.Item("零件几何体") # 创建草图 sketches = body.Sketches origin = part.OriginElements.PlaneXY sketch = sketches.Add(origin) # 设置绝对轴(使用二维数组格式) axis_points = [ [0.0, 0.0, 0.0], # 原点 [1.0, 0.0, 0.0], # X方向 [0.0, 1.0, 0.0] # Y方向 ] safe_axis = create_safearray(axis_points, dimensions=2) sketch.SetAbsoluteAxisData(safe_axis) # 进入草图编辑 part.InWorkObject = sketch factory2D = sketch.OpenEdition() # 创建圆形(使用一维数组) circle_data = [0.0, 0.0, 30.0] # X中心, Y中心, 半径 safe_circle = create_safearray(circle_data) circle = factory2D.CreateClosedCircle(safe_circle) circle.ReportName = 3 # 创建点 point_data = [0.0, -30.0] safe_point = create_safearray(point_data) point = factory2D.CreatePoint(safe_point) point.ReportName = 4 # 创建拉伸特征 shape_factory = part.ShapeFactory ref_sketch = part.CreateReferenceFromObject(sketch) pad = shape_factory.AddNewPadFromRef(ref_sketch, 50.0) pad.FirstLimit.Dimension.Value = 50.0 part.Update() print("操作成功") except Exception as e
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值