17、Python 编程实用函数与算法实现

Python 编程实用函数与算法实现

在 Python 编程中,有许多实用的函数和算法可以帮助我们解决各种问题。下面将详细介绍一些常见问题的解决方案及相关代码实现。

1. 计算三个值的中位数

计算三个值的中位数有两种方法,一种是使用 if 语句,另一种是使用 min max 函数结合一些算术运算。

## Compute the median of three values using if statements
# @param a the first value
# @param b the second value
# @param c the third value
# @return the median of values a, b and c
#
def median(a, b, c):
    if a < b and b < c or a > b and b > c:
        return b
    if b < a and a < c or b > a and a > c:
        return a
    if c < a and b < c or c > a and b > c:
        return c

## Compute the median of three values using the min and max functions and a little bit of
# arithmetic
# @param a the first value
# @param b the second value
# @param c the third value
# @return the median of values a, b and c
#
def alternateMedian(a, b, c):
    return a + b + c - min(a, b, c) - max(a, b, c)

# Display the median of 3 values entered by the user
def main():
    x = float(input("Enter the first value: "))
    y = float(input("Enter the second value: "))
    z = float(input("Enter the third value: "))
    print("The median value is:", median(x, y, z))
    print("Using the alternative method, it is:", \
          alternateMedian(x, y, z))

# Call the main function
main()

操作步骤:
1. 运行代码后,程序会提示输入三个值。
2. 依次输入三个值,程序将计算并输出这三个值的中位数,同时使用另一种方法再次计算并输出结果。

2. 显示《十二天的圣诞节》歌词

通过编写函数,可以完整显示《十二天的圣诞节》这首歌的歌词。

from int_ordinal import intToOrdinal

## Display one verse of The Twelve Days of Christmas
# @param n the verse to display
# @return (None)
def displayVerse(n):
    print("On the", intToOrdinal(n), "day of Christmas")
    print("my true love sent to me:")
    if n >= 12:
        print("Twelve drummers drumming,")
    if n >= 11:
        print("Eleven pipers piping,")
    if n >= 10:
        print("Ten lords a-leaping,")
    if n >= 9:
        print("Nine ladies dancing,")
    if n >= 8:
        print("Eight maids a-milking,")
    if n >= 7:
        print("Seven swans a-swimming,")
    if n >= 6:
        print("Six geese a-laying,")
    if n >= 5:
        print("Five golden rings,")
    if n >= 4:
        print("Four calling birds,")
    if n >= 3:
        print("Three French hens,")
    if n >= 2:
        print("Two turtle doves,")
    if n == 1:
        print("A", end=" ")
    else:
        print("And a", end=" ")
    print("partridge in a pear tree.")
    print()

# Display all 12 verses of the song
def main():
    for verse in range(1, 13):
        displayVerse(verse)

# Call the main function
main()

操作步骤:
1. 确保 int_ordinal 模块存在且包含 intToOrdinal 函数。
2. 运行代码,程序将依次显示《十二天的圣诞节》的 12 节歌词。

3. 在终端窗口中居中显示字符串

编写函数可以将字符串在指定宽度的终端窗口中居中显示。

WIDTH = 80

## Create a new string that will be centered within a given width when it is printed.
# @param s the string that will be centered
# @param width the width in which the string will be centered
# @return a new copy of s that contains the leading spaces needed to center s
def center(s, width):
    # If the string is too long to center, then the original string is returned
    if width < len(s):
        return s
    # Compute the number of spaces needed and generate the result
    spaces = (width - len(s)) // 2
    result = " " * spaces + s
    return result

# Demonstrate the center function
def main():
    print(center("A Famous Story", WIDTH))
    print(center("by:", WIDTH))
    print(center("Someone Famous", WIDTH))
    print()
    print("Once upon a time...")

# Call the main function
main()

操作步骤:
1. 运行代码,程序将在终端窗口中居中显示指定的字符串。

4. 改进字符串的大小写

编写函数可以改进字符串的大小写,包括首字母大写、句点后字母大写以及特定情况下 i 变为大写。

## Capitalize the appropriate characters in a string
# @param s the string that needs capitalization
# @return a new string with the capitalization improved
def capitalize(s):
    # Create a new copy of the string to return as the function’s result
    result = s
    # Capitalize the first non-space character in the string
    pos = 0
    while pos < len(s) and result[pos] == ' ':
        pos = pos + 1
    if pos < len(s):
        # Replace the character with its uppercase version without changing any other characters
        result = result[0: pos] + result[pos].upper() + \
                 result[pos + 1: len(result)]
    # Capitalize the first letter that follows a ‘‘.’’, ‘‘!’’ or ‘‘?’’
    pos = 0
    while pos < len(s):
        if result[pos] == "." or result[pos] == "!" or \
                result[pos] == "?":
            # Move past the ‘‘.’’, ‘‘!’’ or ‘‘?’’
            pos = pos + 1
            # Move past any spaces
            while pos < len(s) and result[pos] == " ":
                pos = pos + 1
            # If we haven’t reached the end of the string then replace the current character
            # with its uppercase equivalent
            if pos < len(s):
                result = result[0: pos] + \
                         result[pos].upper() + \
                         result[pos + 1: len(result)]
            # Move to the next character
            pos = pos + 1
    # Capitalize i when it is preceded by a space and followed by a space, period, exclamation
    # mark, question mark or apostrophe
    pos = 1
    while pos < len(s) - 1:
        if result[pos - 1] == " " and result[pos] == "i" and \
                (result[pos + 1] == " " or result[pos + 1] == "." or \
                 result[pos + 1] == "!" or result[pos + 1] == "?" or \
                 result[pos + 1] == "’"):
            # Replace the i with an I without changing any other characters
            result = result[0: pos] + "I" + \
                     result[pos + 1: len(result)]
        pos = pos + 1
    return result

# Demonstrate the capitalize function
def main():
    s = input("Enter some text: ")
    capitalized = capitalize(s)
    print("It is capitalized as:", capitalized)

# Call the main function
main()

操作步骤:
1. 运行代码后,程序会提示输入一段文本。
2. 输入文本后,程序将输出改进大小写后的文本。

5. 判断字符串是否表示整数

编写函数可以判断用户输入的字符串是否表示一个整数。

## Determine if a string contains a valid representation of an integer
# @param s the string to check
# @return True if s represents an integer. False otherwise.
#
def isInteger(s):
    # Remove whitespace from the beginning and end of the string
    s = s.strip()
    # Determine if the remaining characters form a valid integer
    if (s[0] == "+" or s[0] == "-") and s[1:].isdigit():
        return True
    if s.isdigit():
        return True
    return False

# Demonstrate the isInteger function
def main():
    s = input("Enter a string: ")
    if isInteger(s):
        print("That string represents an integer.")
    else:
        print("That string does not represent an integer.")

# Only call the main function when this file has not been imported
if __name__ == "__main__":
    main()

操作步骤:
1. 运行代码后,程序会提示输入一个字符串。
2. 输入字符串后,程序将判断该字符串是否表示一个整数,并输出相应的结果。

总结

以上介绍了几个常见问题的 Python 解决方案,包括计算中位数、显示歌词、居中显示字符串、改进字符串大小写以及判断字符串是否为整数等。这些函数和算法可以帮助我们更高效地处理各种编程任务。

下面是一个简单的流程图,展示了判断字符串是否为整数的流程:

graph TD;
    A[输入字符串] --> B[去除首尾空格];
    B --> C{首字符为+或-且后续为数字?};
    C -- 是 --> D[返回True];
    C -- 否 --> E{字符串全为数字?};
    E -- 是 --> D;
    E -- 否 --> F[返回False];

同时,为了更清晰地展示这些函数的功能,我们可以用表格总结如下:
| 功能 | 函数名 | 输入参数 | 输出结果 |
| ---- | ---- | ---- | ---- |
| 计算三个值的中位数 | median alternateMedian | 三个数值 | 中位数 |
| 显示歌词 | displayVerse | 歌词节数 | 对应节的歌词 |
| 居中显示字符串 | center | 字符串、宽度 | 居中后的字符串 |
| 改进字符串大小写 | capitalize | 字符串 | 改进大小写后的字符串 |
| 判断字符串是否为整数 | isInteger | 字符串 | 布尔值(是否为整数) |

6. 判断一个数是否为质数

编写函数可以判断用户输入的数是否为质数。

## Determine whether or not a number is prime
# @param n the integer to test
# @return True if the number is prime, False otherwise
def isPrime(n):
    if n <= 1:
        return False
    # Check each number from 2 up to but not including n to see if it divides evenly into n
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

# Determine if a number entered by the user is prime
def main():
    value = int(input("Enter an integer: "))
    if isPrime(value):
        print(value, "is prime.")
    else:
        print(value, "is not prime.")

# Call the main function if the file has not been imported
if __name__ == "__main__":
    main()

操作步骤:
1. 运行代码后,程序会提示输入一个整数。
2. 输入整数后,程序将判断该数是否为质数,并输出相应的结果。

7. 生成随机密码

编写函数可以生成并显示一个包含 7 到 10 个字符的随机密码。

from random import randint

SHORTEST = 7
LONGEST = 10
MIN_ASCII = 33
MAX_ASCII = 126

## Generate a random password
# @return a string containing a random password
def randomPassword():
    # Select a random length for the password
    randomLength = randint(SHORTEST, LONGEST)
    # Generate an appropriate number of random characters, adding each one to the end of result
    result = ""
    for i in range(randomLength):
        randomChar = chr(randint(MIN_ASCII, MAX_ASCII))
        result = result + randomChar
    # Return the random password
    return result

# Generate and display a random password
def main():
    print("Your random password is:", randomPassword())

# Call the main function only if the module is not imported
if __name__ == "__main__":
    main()

操作步骤:
1. 运行代码,程序将生成并显示一个随机密码。

8. 检查密码是否良好

编写函数可以检查密码是否符合要求,一个好的密码至少 8 个字符,并且包含一个大写字母、一个小写字母和一个数字。

## Check whether or not a password is good. A good password is at least 8 characters and
# contains an uppercase letter, a lowercase letter and a number.
# @param password the password to check
# @return True if the password is good, False otherwise
def checkPassword(password):
    has_upper = False
    has_lower = False
    has_num = False
    # Check each character in the password and see which requirement it meets
    for ch in password:
        if ch >= "A" and ch <= "Z":
            has_upper = True
        elif ch >= "a" and ch <= "z":
            has_lower = True
        elif ch >= "0" and ch <= "9":
            has_num = True
    # If the password has all 4 properties
    if len(password) >= 8 and has_upper and has_lower and has_num:
        return True
    # The password is missing at least one property
    return False

# Demonstrate the password checking function
def main():
    p = input("Enter a password: ")
    if checkPassword(p):
        print("That’s a good password.")
    else:
        print("That isn’t a good password.")

# Call the main function only if the file has not been imported into another program
if __name__ == "__main__":
    main()

操作步骤:
1. 运行代码后,程序会提示输入一个密码。
2. 输入密码后,程序将检查该密码是否符合要求,并输出相应的结果。

9. 任意进制转换

编写函数可以将一个数从一个进制转换为另一个进制,源进制和目标进制必须在 2 到 16 之间。

from hex_digit import *

## Convert a number from base 10 to base new base
# @param num the base 10 number to convert
# @param new base the base to convert to
# @return the string of digits in new base
def dec2n(num, new_base):
    # Generate the representation of num in base new base, storing it in result
    result = ""
    q = num
    # Perform the body of the loop once
    r = q % new_base
    result = int2hex(r) + result
    q = q // new_base
    # Continue looping until q is 0
    while q > 0:
        r = q % new_base
        result = int2hex(r) + result
        q = q // new_base
    # Return the result
    return result

## Convert a number from base b to base 10
# @param num the base b number, stored in a string
# @param b the base of the number to convert
# @return the base 10 number
def n2dec(num, b):
    decimal = 0
    # Process each digit in the base b number
    for i in range(len(num)):
        decimal = decimal * b
        decimal = decimal + hex2int(num[i])
    # Return the result
    return decimal

# Convert a number between two arbitrary bases
def main():
    # Read the base and number from the user
    from_base = int(input("Base to convert from (2 - 16): "))
    if from_base < 2 or from_base > 16:
        print("Only bases between 2 and 16 are supported.")
        print("Quitting...")
        quit()
    from_num = input("Sequence of digits in that base: ")
    # Convert to base 10 and display the result
    dec = n2dec(from_num, from_base)
    print("That’s %d in base 10." % dec)
    # Convert to the new base and display the result
    to_base = int(input("Enter the base to convert to (2 - 16): "))
    if to_base < 2 or to_base > 16:
        print("Only bases between 2 and 16 are supported.")
        print("Quitting...")
        quit()
    to_num = dec2n(dec, to_base)
    print("That’s %s in base %d." % (to_num, to_base))

# Call the main function
main()

操作步骤:
1. 运行代码后,程序会提示输入源进制(2 - 16)。
2. 输入源进制后,程序会提示输入该进制下的数字序列。
3. 程序将该数字转换为十进制并输出结果。
4. 程序会提示输入目标进制(2 - 16)。
5. 输入目标进制后,程序将十进制数字转换为目标进制并输出结果。

10. 化简分数

编写函数可以将分数化简为最简形式。

## Compute the greatest common divisor of two integers
# @param n the first integer under consideration (must be non-zero)
# @param m the second integer under consideration (must be non-zero)
# @return the greatest common divisor of the integers
def gcd(n, m):
    # Initialize d to the smaller of n and m
    d = min(n, m)
    # Use a while loop to find the greatest common divisor of n and m
    while n % d != 0 or m % d != 0:
        d = d - 1
    return d

## Reduce a fraction to lowest terms
# @param num the integer numerator of the fraction
# @param den the integer denominator of the fraction (must be non-zero)
# @return the numerator and denominator of the reduced fraction
def reduce(num, den):
    # If the numerator is 0 then the reduced fraction is 0 / 1
    if num == 0:
        return (0, 1)
    # Compute the greatest common divisor of the numerator and denominator
    g = gcd(num, den)
    # Divide both the numerator and denominator by the GCD and return the result
    return (num // g, den // g)

# Read a fraction from the user and display the equivalent lowest terms fraction
def main():
    # Read the numerator and denominator from the user
    num = int(input("Enter the numerator: "))
    den = int(input("Enter the denominator: "))
    # Compute the reduced fraction
    (n, d) = reduce(num, den)
    # Display the result
    print("%d/%d can be reduced to %d/%d." % (num, den, n, d))

# Call the main function
main()

操作步骤:
1. 运行代码后,程序会提示输入分子。
2. 输入分子后,程序会提示输入分母。
3. 程序将计算并输出化简后的分数。

11. 化简英制度量单位

编写函数可以将英制度量单位化简为尽可能大的单位。

TSP_PER_TBSP = 3
TSP_PER_CUP = 48

## Reduce an imperial measurement so that it is expressed using the largest possible
# units of measure
# @param num the number of units that need to be reduced
# @param unit the unit of measure (‘‘cup’’, ‘‘tablespoon’’ or ‘‘teaspoon’’)
# @return a string representing the measurement in reduced form
def reduceMeasure(num, unit):
    # Convert the unit to lowercase
    unit = unit.lower()
    # Compute the number of teaspoons that the parameters represent
    if unit == "teaspoon" or unit == "teaspoons":
        teaspoons = num
    elif unit == "tablespoon" or unit == "tablespoons":
        teaspoons = num * TSP_PER_TBSP
    elif unit == "cup" or unit == "cups":
        teaspoons = num * TSP_PER_CUP
    # Convert the number of teaspoons to the largest possible units of measure
    cups = teaspoons // TSP_PER_CUP
    teaspoons = teaspoons - cups * TSP_PER_CUP
    tablespoons = teaspoons // TSP_PER_TBSP
    teaspoons = teaspoons - tablespoons * TSP_PER_TBSP
    # Create a string to hold the result
    result = ""
    # Add the number of cups to the result string (if any)
    if cups > 0:
        result = result + str(cups) + " cup"
        # Make cup plural if there is more than one
        if cups > 1:
            result = result + "s"
    # Add the number of tablespoons to the result string (if any)
    if tablespoons > 0:
        # Include a comma if there were some cups
        if result != "":
            result = result + ", "
        result = result + str(tablespoons) + " tablespoon"
        # Make tablespoon plural if there is more than one
        if tablespoons > 1:
            result = result + "s"
    # Add the number of teaspoons to the result string (if any)
    if teaspoons > 0:
        # Include a comma if there were some cups and/or tablespoons
        if result != "":
            result = result + ", "
        result = result + str(teaspoons) + " teaspoon"
        # Make teaspoons plural if there is more than one
        if teaspoons > 1:
            result = result + "s"
    # Handle the case where the number of units was 0
    if result == "":
        result = "0 teaspoons"
    return result

# Demonstrate the reduceMeasure function by performing several reductions
def main():
    print("59 teaspoons is %s." % reduceMeasure(59, "teaspoons"))
    print("59 tablespoons is %s." % \
          reduceMeasure(59, "tablespoons"))
    print("1 teaspoon is %s." % reduceMeasure(1, "teaspoon"))
    print("1 tablespoon is %s." % reduceMeasure(1, "tablespoon"))
    print("1 cup is %s." % reduceMeasure(1, "cup"))
    print("4 cups is %s." % reduceMeasure(4, "cups"))
    print("3 teaspoons is %s." % reduceMeasure(3, "teaspoons"))
    print("6 teaspoons is %s." % reduceMeasure(6, "teaspoons"))
    print("95 teaspoons is %s." % reduceMeasure(95, "teaspoons"))
    print("96 teaspoons is %s." % reduceMeasure(96, "teaspoons"))
    print("97 teaspoons is %s." % reduceMeasure(97, "teaspoons"))
    print("98 teaspoons is %s." % reduceMeasure(98, "teaspoons"))
    print("99 teaspoons is %s." % reduceMeasure(99, "teaspoons"))

# Call the main function
main()

操作步骤:
1. 运行代码,程序将对不同的英制度量单位进行化简并输出结果。

12. 查找魔法日期

编写函数可以查找 1900 年代的所有魔法日期。

from days_in_month import daysInMonth

## Determine whether or not a date is ‘‘magic’’
# @param day the day portion of the date
# @param month the month portion of the date
# @param year the year portion of the date
# @return True if the date is magic, False otherwise
def isMagicDate(day, month, year):
    if day * month == year % 100:
        return True
    return False

# Find and display all of the magic dates in the 1900s
def main():
    for year in range(1900, 2000):
        for month in range(1, 13):
            for day in range(1, daysInMonth(month, year) + 1):
                if isMagicDate(day, month, year):
                    print("%02d/%02d/%04d is a magic date." % (day, month, year))

# Call the main function
main()

操作步骤:
1. 运行代码,程序将查找并输出 1900 年代的所有魔法日期。

总结

本文介绍了多个实用的 Python 函数和算法,涵盖了从简单的数学计算到复杂的日期查找等多个领域。这些函数和算法可以帮助我们解决各种实际编程问题,提高编程效率。以下是一个新的流程图,展示了分数化简的流程:

graph TD;
    A[输入分子、分母] --> B[计算最大公约数];
    B --> C{分子为0?};
    C -- 是 --> D[返回0/1];
    C -- 否 --> E[分子分母除以最大公约数];
    E --> F[返回化简后的分数];

同时,我们用表格进一步总结这些函数的功能:
| 功能 | 函数名 | 输入参数 | 输出结果 |
| ---- | ---- | ---- | ---- |
| 判断一个数是否为质数 | isPrime | 整数 | 布尔值(是否为质数) |
| 生成随机密码 | randomPassword | 无 | 随机密码字符串 |
| 检查密码是否良好 | checkPassword | 密码字符串 | 布尔值(是否为好密码) |
| 任意进制转换 | dec2n n2dec | 数字、进制 | 转换后的数字字符串 |
| 化简分数 | reduce | 分子、分母 | 化简后的分子、分母 |
| 化简英制度量单位 | reduceMeasure | 数量、单位 | 化简后的度量单位字符串 |
| 查找魔法日期 | isMagicDate | 日期(日、月、年) | 布尔值(是否为魔法日期) |

通过学习和使用这些函数,我们可以更好地掌握 Python 编程,解决实际问题。希望这些内容对大家有所帮助!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值