python and CSharp: Essential Algorithms
python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | # encoding: utf-8 # 版权所有 2023 涂聚文有限公司 # 许可信息查看: # 描述: # Author : geovindu,Geovin Du 涂聚文. # IDE : PyCharm 2023.1 python 311 # Datetime : 2023/9/21 21:28 # User : geovindu # Product : PyCharm # Project : EssentialAlgorithms # File : DrawingTwo.py # explain : 学习 import tkinter as tk import tkinter.font as tk_font import math class DrawingCanvasTwo( object ): """ A canvas drawing manager. """ def __init__( self , canvas, wxmin, wymin, wxmax, wymax, dmargin, y_is_flipped): """ :param canvas: :param wxmin: :param wymin: :param wxmax: :param wymax: :param dmargin: :param y_is_flipped: """ self .canvas = canvas self .wxmin = wxmin self .wymin = wymin self .wxmax = wxmax self .wymax = wymax self .dmargin = dmargin self .y_is_flipped = y_is_flipped self .set_scales() def set_scales( self ): """ Calculate scale parameters for the canvas's current size. :return: """ self .canvas.update() self .dxmin = self .dmargin self .dymin = self .dmargin self .dxmax = self .canvas.winfo_width() - self .dmargin - 1 self .dymax = self .canvas.winfo_height() - self .dmargin - 1 # Flip the Y coordinates to invert the result. if self .y_is_flipped: self .dymin, self .dymax = self .dymax, self .dymin self .xscale = ( self .dxmax - self .dxmin) / ( self .wxmax - self .wxmin) self .yscale = ( self .dymax - self .dymin) / ( self .wymax - self .wymin) # Calculate 1 pixel in world coordinates. self .xpix = 1 / self .xscale self .ypix = 1 / self .yscale def w_to_d( self , wx, wy): """ Map a point from world to device coordinates. :param wx: :param wy: :return: """ dx = (wx - self .wxmin) * self .xscale + self .dxmin dy = (wy - self .wymin) * self .yscale + self .dymin return dx, dy def clear( self ): """ :return: """ self .canvas.delete(tk. ALL ) def wdraw_line( self , wx0, wy0, wx1, wy1, color, arrow): """ Draw a line in world coordinates. :param wx0: :param wy0: :param wx1: :param wy1: :param color: :param arrow: :return: """ dx0, dy0 = self .w_to_d(wx0, wy0) dx1, dy1 = self .w_to_d(wx1, wy1) self .canvas.create_line(dx0, dy0, dx1, dy1, fill = color, arrow = arrow) def wdraw_axes( self , xtic_spacing, ytic_spacing, tic_hgt, tic_wid, do_draw_text, color): """ Draw coordinate axes. :param xtic_spacing: :param ytic_spacing: :param tic_hgt: :param tic_wid: :param do_draw_text: :param color: :return: """ self .wdraw_line( self .wxmin, 0 , self .wxmax, 0 , color, arrow = tk.BOTH) self .wdraw_line( 0 , self .wymin, 0 , self .wymax, color, arrow = tk.BOTH) startx = xtic_spacing * int (( self .wxmin + xtic_spacing) / xtic_spacing) x = startx while x < self .wxmax: if ( abs (x) > 0.01 ): dx0, dy0 = self .w_to_d(x, tic_hgt) dx1, dy1 = self .w_to_d(x, - tic_hgt) self .canvas.create_line(dx0, dy0, dx1, dy1, fill = color) if do_draw_text: self .canvas.create_text(dx1, dy1, text = str (x), fill = color, anchor = tk.N) x + = xtic_spacing starty = ytic_spacing * int (( self .wymin + ytic_spacing) / ytic_spacing) y = starty while y < self .wymax: if ( abs (y) > 0.01 ): dx0, dy0 = self .w_to_d(tic_wid, y) dx1, dy1 = self .w_to_d( - tic_wid, y) self .canvas.create_line(dx0, dy0, dx1, dy1, fill = color) if do_draw_text: self .canvas.create_text(dx1, dy1, text = str (y), fill = color, anchor = tk.E) y + = ytic_spacing def wdraw_polyline( self , wcoords, color): """ Draw a connected series of points in world coordinates. :param wcoords: :param color: :return: """ dpoints = [] for i in range ( 0 , len (wcoords), 2 ): dpoints + = self .w_to_d(wcoords[i], wcoords[i + 1 ]) self .canvas.create_line(dpoints, fill = color) def wdraw_rotated_text( self , wx, wy, text, angle, color, font): """ Draw a rotated text at the indicated position in world coordinates. :param wx: :param wy: :param text: :param angle: :param color: :param font: :return: """ dx, dy = self .w_to_d(wx, wy) self .canvas.create_text(dx, dy, text = text, angle = angle, fill = color, font = font) def wdraw_function( self , func, color, wxmin, wxmax, step_x): """ Draw a function. :param func: :param color: :param wxmin: :param wxmax: :param step_x: :return: """ points = [] x = wxmin while x < = wxmax: points.append(x) points.append(func(x)) x + = step_x self .wdraw_polyline(points, color) def log_x(x): """ :param x: :return: """ return math.log(x, 2 ) def sqrt_x(x): """ :param x: :return: """ return 1.5 * math.sqrt(x) def identity_x(x): """ :param x: :return: """ return x def x2(x): """ :param x: :return: """ return x * x / 5 def two_to_the_x(x): """ :param x: :return: """ return math. pow ( 2 , x) / 10 def factorial_n(n): """ :param n: :return: """ result = 1 for i in range ( 2 , n + 1 ): result * = i return result / 100 def fibonacci_n(n): """ :param n: :return: """ if n = = 0 : return 0 fib_minus2 = 0 fib_minus1 = 1 fib = 1 for i in range ( 2 , n + 1 ): fib = fib_minus1 + fib_minus2 fib_minus2 = fib_minus1 fib_minus1 = fib return fib / 10 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | # encoding: utf-8 # 版权所有 2023 涂聚文有限公司 # 许可信息查看: # 描述: # Author : geovindu,Geovin Du 涂聚文. # IDE : PyCharm 2023.1 python 311 # Datetime : 2023/9/21 21:29 # User : geovindu # Product : PyCharm # Project : EssentialAlgorithms # File : Chapter03.py # explain : 学习 import tkinter as tk import tkinter.font as tk_font import math import ChapterOne.DrawingTwo class Ch03App( object ): """ """ def __init__( self ): """ """ self .window = tk.Tk() self .window.title( "runtime_functions" ) self .window.protocol( "WM_DELETE_WINDOW" , self .kill_callback) self .window.geometry( "570x570" ) # Make a slightly bigger label font. self .label_font = tk_font.Font(family = "Times New Roman" , size = 14 ) # Canvas. self .canvas = tk.Canvas( self .window, width = 550 , height = 550 , relief = tk.RIDGE, bd = 5 , highlightthickness = 0 , bg = "white" ) self .canvas.xview( "moveto" , 5 ) # Move out from the border. self .canvas.yview( "moveto" , 5 ) self .canvas.grid(row = 1 , column = 0 , columnspan = 4 , padx = 5 , pady = 5 ) # Make the DrawingCanvas. self .drawing_canvas = ChapterOne.DrawingTwo.DrawingCanvasTwo( self .canvas, - 1 , - 1 , 21 , 21 , 20 , True ) # Draw the scene. self .draw_scene() # Force focus so Alt+F4 closes this window and not the Python shell. self .window.focus_force() self .window.mainloop() def kill_callback( self ): """ :return: """ self .window.destroy() def draw_scene( self ): """ Draw the scene." :return: """ self .drawing_canvas.clear() # Draw the curves. wxmin = self .drawing_canvas.wxmin wxmax = self .drawing_canvas.wxmax xpix = self .drawing_canvas.xpix self .drawing_canvas.wdraw_function(ChapterOne.DrawingTwo.log_x, "blue" , 0.5 , wxmax, xpix) self .drawing_canvas.wdraw_function(ChapterOne.DrawingTwo.sqrt_x, "green" , 0 , wxmax, xpix) self .drawing_canvas.wdraw_function(ChapterOne.DrawingTwo.identity_x, "black" , 0 , wxmax, xpix) self .drawing_canvas.wdraw_function(ChapterOne.DrawingTwo.x2, "orange" , 0 , wxmax, xpix) self .drawing_canvas.wdraw_function(ChapterOne.DrawingTwo.two_to_the_x, "magenta" , 0 , wxmax, xpix) self .drawing_canvas.wdraw_function(ChapterOne.DrawingTwo.fibonacci_n, "blue" , 0 , 20 , 1 ) self .drawing_canvas.wdraw_function(ChapterOne.DrawingTwo.factorial_n, "red" , 0 , 10 , 1 ) self .drawing_canvas.wdraw_rotated_text( 15 , 4.5 , "y = Log(x)" , 6 , "blue" , self .label_font) self .drawing_canvas.wdraw_rotated_text( 15 , 6.5 , "y = 1.5 * Sqrt(x)" , 11 , "green" , self .label_font) self .drawing_canvas.wdraw_rotated_text( 13 , 14 , "y = x" , 45 , "black" , self .label_font) self .drawing_canvas.wdraw_rotated_text( 8.75 , 17 , "y = x^2 / 5" , 75 , "orange" , self .label_font) self .drawing_canvas.wdraw_rotated_text( 7 , 17.5 , "y = 2x / 10" , 85 , "magenta" , self .label_font) self .drawing_canvas.wdraw_rotated_text( 5.5 , 18 , "y = x! / 100" , 88 , "red" , self .label_font) self .drawing_canvas.wdraw_rotated_text( 11.5 , 16 , "y = Fibonacci(x) / 10" , 83 , "blue" , self .label_font) # Draw the axes. self .drawing_canvas.wdraw_axes( 5 , 5 , 0.2 , 0.2 , True , "gray" ) |
调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # encoding: utf-8 # 版权所有 2023 涂聚文有限公司 # 许可信息查看: # 描述:https://www.wiley.com/en-us/Essential+Algorithms%3A+A+Practical+Approach+to+Computer+Algorithms+Using+Python+and+C%23%2C+2nd+Edition-p-9781119575993 # 算法基础:Python和C#语言实现(原书第2版) # Author : geovindu,Geovin Du 涂聚文. # IDE : PyCharm 2023.1 python 311 # Datetime : 2023/9/21 21:03 # User : geovindu # Product : PyCharm # Project : EssentialAlgorithms # File : main.py # explain : 学习 import os import sys import ChapterOne.Chapter01 def print_hi(name): # Use a breakpoint in the code line below to debug your script. print (f 'Hi, {name}' ) # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. if __name__ = = '__main__' : print_hi( 'PyCharm,涂聚文 Geovin Du' ) # 第一章 #app=ChapterOne.Chapter01.ch01App() #app=ChapterOne.Chapter02.Ch02App() app = ChapterOne.Chapter03.Ch03App() # See PyCharm help at https://www.jetbrains.com/help/pycharm/ |
输出:
CSharp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace RuntimeFunctions { /// <summary> /// /// </summary> public partial class Form1 : Form { /// <summary> /// /// </summary> public Form1() { InitializeComponent(); } /// <summary> /// /// </summary> private bool drawFibonacci = true ; /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void graphPictureBox_Paint( object sender, PaintEventArgs e) { // Compare the two methods for calculating the Fibonacci function. for ( int i = 0; i < 20; i++) { Console.WriteLine(Fibonacci(i) + " = " + Fibonacci2(i)); } const bool useColor = true ; DrawGraph(e.Graphics, -0.75f, 20.5f, -0.75f, 20.5f, 1, 1, useColor); } /// <summary> /// /// </summary> /// <param name="gr"></param> /// <param name="xmin"></param> /// <param name="xmax"></param> /// <param name="ymin"></param> /// <param name="ymax"></param> /// <param name="ticDx"></param> /// <param name="ticDy"></param> /// <param name="useColor"></param> private void DrawGraph(Graphics gr, float xmin, float xmax, float ymin, float ymax, int ticDx, int ticDy, bool useColor) { gr.SmoothingMode = SmoothingMode.AntiAlias; // Scale to fit. RectangleF rect = new RectangleF(xmin, ymin, xmax - xmin, ymax - ymin); PointF[] pts = { new PointF(0, graphPictureBox.ClientSize.Height), new PointF(graphPictureBox.ClientSize.Width, graphPictureBox.ClientSize.Height), new PointF(0, 0), }; Matrix transform = new Matrix(rect, pts); gr.Transform = transform; // Get a unit in X and Y directions. pts = new PointF[] { new PointF(0, 0), new PointF(1, 1) }; Matrix inverse = transform.Clone(); inverse.Invert(); inverse.TransformPoints(pts); float dx = pts[1].X - pts[0].X; float dy = pts[1].Y - pts[0].Y; using (Pen thinPen = new Pen(Color.Black, 0)) { // Draw axes. gr.DrawLine(thinPen, xmin, 0, xmax, 0); for ( int x = 0; x <= xmax; x += ticDx) { gr.DrawLine(thinPen, x, -4 * dy, x, 4 * dy); } gr.DrawLine(thinPen, 0, ymin, 0, ymax); for ( int y = 0; y <= ymax; y += ticDx) { gr.DrawLine(thinPen, -4 * dx, y, 4 * dx, y); } // Draw curves. List<PointF> points = new List<PointF>(); // Log(X). points = new List<PointF>(); for ( float x = dx; x <= xmax; x += dx) { float y = ( float )Math.Log(x, 2); if ( float .IsInfinity(y) || float .IsNaN(y)) break ; points.Add( new PointF(x, y)); } if (useColor) thinPen.Color = Color.Blue; gr.DrawLines(thinPen, points.ToArray()); // 1.5 * Sqrt(X). points = new List<PointF>(); for ( float x = 0; x <= xmax; x += dx) { float y = 1.5f * ( float )Math.Sqrt(x); if ( float .IsInfinity(y) || float .IsNaN(y)) break ; points.Add( new PointF(x, y)); } if (useColor) thinPen.Color = Color.Green; gr.DrawLines(thinPen, points.ToArray()); // X. points = new List<PointF>(); points.Add( new PointF(xmin, xmin)); points.Add( new PointF(xmax, xmax)); if (useColor) thinPen.Color = Color.Black; gr.DrawLines(thinPen, points.ToArray()); // X * X / 5. points = new List<PointF>(); for ( float x = 0; x <= xmax; x += dx) { float y = x * x / 5; if ( float .IsInfinity(y) || float .IsNaN(y)) break ; points.Add( new PointF(x, y)); } if (useColor) thinPen.Color = Color.Orange; gr.DrawLines(thinPen, points.ToArray()); // 2^X / 10. points = new List<PointF>(); for ( float x = 0; x <= xmax; x += dx) { float y = ( float )Math.Pow(2, x) / 10; if ( float .IsInfinity(y) || float .IsNaN(y)) break ; points.Add( new PointF(x, y)); if (y > ymax) break ; } if (useColor) thinPen.Color = Color.Fuchsia; gr.DrawLines(thinPen, points.ToArray()); // X! / 100. points = new List<PointF>(); for ( int x = 0; x <= xmax; x++) { float y = ( float )Factorial(x) / 100; if ( float .IsInfinity(y) || float .IsNaN(y)) break ; points.Add( new PointF(x, y)); if (y > ymax) break ; } if (useColor) thinPen.Color = Color.Red; gr.DrawLines(thinPen, points.ToArray()); // Fibonacci(X) / 10. if (drawFibonacci) { points = new List<PointF>(); for ( int x = 0; x <= xmax; x++) { float y = ( float )Fibonacci(x) / 10; if ( float .IsInfinity(y) || float .IsNaN(y)) break ; points.Add( new PointF(x, y)); if (y > ymax) break ; } if (useColor) thinPen.Color = Color.Blue; gr.DrawLines(thinPen, points.ToArray()); } } // Label the axes. gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; gr.ResetTransform(); using (Font font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Regular)) { using (StringFormat sf = new StringFormat()) { const int skip = 5; // X axis. sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Near; for ( int x = skip; x <= xmax; x += skip) { pts = new PointF[] { new PointF(x, 0) }; transform.TransformPoints(pts); gr.DrawString(x.ToString(), font, Brushes.Black, pts[0], sf); } // Y axis. sf.Alignment = StringAlignment.Far; sf.LineAlignment = StringAlignment.Center; for ( int y = skip; y <= xmax; y += skip) { pts = new PointF[] { new PointF(0, y) }; transform.TransformPoints(pts); gr.DrawString(y.ToString(), font, Brushes.Black, pts[0], sf); } } } // Draw labels. using (Font font = new Font(FontFamily.GenericSansSerif, 16, FontStyle.Regular)) { DrawRotatedText(gr, font, Brushes.Blue, "y = Log(x)" , 414, 440, -8, useColor); DrawRotatedText(gr, font, Brushes.Green, "y = 1.5 * Sqrt(x)" , 410, 390, -11, useColor); DrawRotatedText(gr, font, Brushes.Black, "y = x" , 360, 200, -45, useColor); DrawRotatedText(gr, font, Brushes.Orange, "y = x² / 5" , 242, 140, -75, useColor); DrawRotatedText(gr, font, Brushes.Fuchsia, "y = 2ˣ / 10" , 200, 135, -85, useColor); DrawRotatedText(gr, font, Brushes.Red, "y = x! / 100" , 140, 125, -90, useColor); if (drawFibonacci) DrawRotatedText(gr, font, Brushes.Blue, "y = Fibonacci(x) / 10" , 321, 230, -83, useColor); } } // Return n! /// <summary> /// /// </summary> /// <param name="n"></param> /// <returns></returns> private double Factorial( int n) { double total = 1; for ( int i = 2; i <= n; i++) total *= n; return total; } // Draw rotated text at the indicated position. // Note: This method resets the Graphics object's transformation. /// <summary> /// /// </summary> /// <param name="gr"></param> /// <param name="font"></param> /// <param name="brush"></param> /// <param name="text"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="angle"></param> /// <param name="useColor"></param> private void DrawRotatedText(Graphics gr, Font font, Brush brush, string text, int x, int y, float angle, bool useColor) { gr.ResetTransform(); gr.RotateTransform(angle, MatrixOrder.Append); gr.TranslateTransform(x, y, MatrixOrder.Append); if (useColor) gr.DrawString(text, font, brush, 0, 0); else gr.DrawString(text, font, Brushes.Black, 0, 0); } // Return the nth Fibonacci number. /// <summary> /// /// </summary> /// <param name="n"></param> /// <returns></returns> private double Fibonacci( int n) { if (n == 0) return 0; double fibMinus2 = 0; // Fibonacci(0) double fibMinus1 = 1; // Fibonacci(1) double fib = 1; for ( int i = 2; i <= n; i++) { fib = fibMinus1 + fibMinus2; fibMinus2 = fibMinus1; fibMinus1 = fib; } return fib; } // The French mathematician Abraham de Moivre discovered // in 1718 that you can calculate the Nth like this: // Round(phi^N / Sqrt(5)) where phi = (1 + Sqrt(5)) / 2. /// <summary> /// /// </summary> /// <param name="n"></param> /// <returns></returns> private double Fibonacci2( int n) { double phi = (1 + Math.Sqrt(5)) / 2; return Math.Round(Math.Pow(phi, n) / Math.Sqrt(5.0)); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load( object sender, EventArgs e) { } } } |
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2022-09-21 CSharp: Bridge Pattern
2022-09-21 Java: Immutable Pattern
2016-09-21 csharp: Oracle Stored Procedure DAL using ODP.NET
2014-09-21 Create a soft keyboard
2012-09-21 SQL 生成公曆和農曆對照數據續--创建萬年曆查找各種周期性節日數據
2010-09-21 Csharp,Javascript 获取显示器的大小的几种方式
2009-09-21 谷歌地图API学习