Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
CSharp /
20180403crangeWarning! C#'s range is different from Python's range! csharp> Enumerable.Range(0, 10) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } // Seems good, right? csharp> Enumerable.Range(12, 15) { 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 } // Ooops! What da hell? csharp> Enumerable.Range(12, 3) { 12, 13, 14 } // Start at 12 and produce 3 consecutive numbers.
To simulate Python's range, I have this solution: public static class Py { // make a range over [start..end) , where end is NOT included (exclusive) public static IEnumerable<int> RangeExcl(int start, int end) { if (end <= start) return Enumerable.Empty<int>(); // else return Enumerable.Range(start, end - start); } // make a range over [start..end] , where end IS included (inclusive) public static IEnumerable<int> RangeIncl(int start, int end) { return RangeExcl(start, end + 1); } } Usage: Py.RangeExcl(10, 15) // 10, 11, 12, 13, 14 Py.RangeIncl(10, 15) // 10, 11, 12, 13, 14, 15 See the current version here. |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |