zoukankan      html  css  js  c++  java
  • 利用yield关键字输出杨辉三角

    最近学习了下python,发现里面也有yield的用法,本来对C#里的yield不甚了解,但是通过学习python,对于C#的yield理解更深了!!

    不多说了,小学生水平的表达能力伤不起....

    直接上代码:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication2
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                foreach (var obj in YHSJ(8))
                {
                    PrintRow(obj);
                }
                Console.ReadKey();
            }
    
            /// <summary>
            /// 取得杨辉三角的迭代器
            /// </summary>
            /// <param name="n"></param>
            /// <returns></returns>
            public static IEnumerable<IEnumerable<int>> YHSJ(int n)
            {
                //第一行
                List<int> row = new List<int> { 1 };
                yield return row;
                //第二行
                row = new List<int> { 1, 1 };
                yield return row;
                //第三行及其之后的
                while (n > 0)
                {
                    List<int> newrow = new List<int> { 1, 1 };
                    int index = row.Count;
                    for (int i = 1; i < index; i++)
                    {
                        newrow.Insert(1, row[i - 1] + row[i]);
                    }
                    yield return newrow;
                    row = newrow;
                    n--;
                }
            }
    
            /// <summary>
            /// 打印一行数据
            /// </summary>
            /// <param name="row"></param>
            public static void PrintRow(IEnumerable<int> row)
            {
                foreach (int i in row)
                {
                    Console.Write(i + "	");
                }
                Console.WriteLine();
            }
        }
    }
    

      

  • 相关阅读:
    分组排序并显示序号
    power-design--tables-export-usage
    cache implement
    get system properties
    jbpm
    JVM内存管理机制和垃圾回收机制
    java读取excel
    Java编程中“为了性能”尽量要做到的一些地方
    json串与java对象互转
    apidoc的使用
  • 原文地址:https://www.cnblogs.com/a14907/p/5026828.html
Copyright © 2011-2022 走看看