python and CSharp: Essential Algorithms

 python:

# 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

  

# 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")

  

调用:

# 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:

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)
        {

        }
    }
}

  

 

posted @ 2023-09-21 21:40  ®Geovin Du Dream Park™  阅读(26)  评论(0)    收藏  举报