利用yield关键字输出杨辉三角

时间:2024-01-10 14:14:38

最近学习了下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 + "\t");
}
Console.WriteLine();
}
}
}