首页 > 编程语言 >python: Essential Algorithms

python: Essential Algorithms

时间:2023-09-21 21:44:32浏览次数:44  
标签:canvas wdraw python text self drawing Algorithms font Essential

 

# 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):
        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."""
        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."""
        dx = (wx - self.wxmin) * self.xscale + self.dxmin
        dy = (wy - self.wymin) * self.yscale + self.dymin
        return dx, dy

    def clear(self):
        self.canvas.delete(tk.ALL)

    def wdraw_line(self, wx0, wy0, wx1, wy1, color, arrow):
        """ Draw a line in world coordinates."""
        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."""
        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."""
        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."""
        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."""
        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):
    return math.log(x, 2)
def sqrt_x(x):
    return 1.5 * math.sqrt(x)
def identity_x(x):
    return x
def x2(x):
    return x * x / 5
def two_to_the_x(x):
    return math.pow(2, x) / 10
def factorial_n(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result / 100
def fibonacci_n(n):
    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):
        self.window.destroy()

    def draw_scene(self):
        """Draw the scene."""
        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,geovind')

    # 第一章
    #app=ChapterOne.Chapter01.ch01App()
    #app=ChapterOne.Chapter02.Ch02App()
    app=ChapterOne.Chapter03.Ch03App()



# See PyCharm help at https://www.jetbrains.com/help/pycharm/

  

 

标签:canvas,wdraw,python,text,self,drawing,Algorithms,font,Essential
From: https://www.cnblogs.com/geovindu/p/17721037.html

相关文章

  • Python 内置数据类型详解
    内置数据类型在编程中,数据类型是一个重要的概念。变量可以存储不同类型的数据,不同类型可以执行不同的操作。Python默认内置了以下这些数据类型,分为以下几类:文本类型:str数值类型:int、float、complex序列类型:list、tuple、range映射类型:dict集合类型:set、frozenset布尔类型......
  • 【C#】【Python】【实例】统计多个文件夹下的图片
    因工作需要繁琐的进行同一目录多个文件夹下的图片统计,便使用代码来解决。需求:统计的是多少个文件夹包含了图片,并非是统计有多少张图。 我们先用Python来创建一个现场环境(巩固巩固py知识):1importos23#根目录4root_path=r"C:\Users\Desktop\1111"56forit......
  • 在不用插件和断网的情况下怎么实现编译python?
    要在不使用插件和断网的情况下编译Python代码,您通常不需要进行编译,因为Python是一种解释型语言,它将代码逐行执行而不需要显式编译过程。然而,如果您希望将Python代码打包成一个独立的可执行文件以便于分发,您可以使用一些第三方工具,如PyInstaller、cx_Freeze或Py2exe,但这些工具在没有......
  • Python中*args(参数)和 **kwargs(关键字参数)的区别
    *args--Python可以使用*args传递多个参数,但是不能使用它来传递键值对(字典)参数。**kwargs--Python另一个名为**kwargs的参数允许我们将字典类型的键值对参数传递给函数。注:两者均支持可变数量的参数传递。......
  • python打包文件过大的解决方法
       开发完一个python客户端文件后,一般需要发布为exe文件以便用户下载安装。但很多初学者开发的一个仅有几M的小软件,打包的exe文件却高达几十M甚至几百M。这里根据工作实践总结了一个有效方法分享给大家。   首先,在选定路径下创建一个文件夹folder   其次,在新建文......
  • Python Web开发:Django框架入门
    Django是一个高级的PythonWeb框架,它鼓励快速开发和干净,务实的设计。它旨在使开发人员能够快速地构建和维护高质量的Web应用程序。在本博文中,我们将介绍Django框架的基础知识,并通过具体案例说明其功能。Django安装首先,我们需要在计算机上安装Django。你可以使用pip(Python包管理器)来......
  • 携程ASE加密解密 java python
    java代码packagecom.example.trip_vip;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importjavax.crypto.Cipher;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importjava.io.UnsupportedEncod......
  • 携程 3DES加密解密 java python
    javapackagecom.example;importorg.springblade.core.tool.utils.*;importjavax.annotation.Nullable;importjavax.crypto.Cipher;importjavax.crypto.SecretKeyFactory;importjavax.crypto.spec.DESKeySpec;importjava.util.Objects;publicclassDES3{......
  • 转~~Python:ModuleNotFoundError: No module named 模块名 错误及解决方案
    IDE中语法检查,运行都正常,Linux命令行远程运行就报错:参考文档:https://blog.csdn.net/SeaSky_Steven/article/details/106426985 1print(os.pardir)2sys.path.append(os.pardir)34'''5os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口;6sys模块负责程......
  • 【python爬虫】爬虫所需要的爬虫代理ip是什么?
    前言在进行爬虫程序开发时,经常会遇到访问被限制的网站,这时就需要使用代理IP来进行访问。本文将介绍代理IP的概念及使用方法,帮助读者更好地应对爬虫程序中的访问限制问题。同时,本文还将提供一些代理IP提供商,并通过一个实例演示如何使用代理IP来访问被限制的网站。一、什......