函数的定义和使用作业参考答案

函数的定义和使用作业参考答案

练习1:写一个函数实现摇色子的功能,传入色子的个数,返回所有色子的点数总和。
import random


def roll_dice(num):
    total = 0
    for _ in range(num):
        total += random.randint(1, 6)
    return total
练习2:写一个函数,求出列表中数值类元素(int、float)的平均值。
def calc_avg(items):
    total, counter = 0, 0
    for item in items:
        if type(item) in (int, float):
            total += item
            counter += 1
    return total / counter
练习3:写一个函数,传入一个字符串,返回去掉字符串中所有空格后的字符串。
def remove_space(content):
    return content.replace(' ', '')
练习4:写一个函数,传入两个字符串,返回从第一个字符串中去掉第二个字符串中的字符之后的字符串。
def remove_chars(str1, str2):
    str3 = ''
    for ch in str1:
        if ch not in str2:
            str3 += ch
    return str3
练习5:写一个函数,生成指定长度的验证码,验证码由英文字母和数字构成。
import random


def gen_vccode(length=4):
    all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    selected_chars = random.choices(all_chars, k=length)
    return ''.join(selected_chars)
练习6:写一个函数,返回给定文件名的后缀名(扩展名)。
def get_suffix(filename):
    pos = filename.rfind('.')
    return filename[pos + 1:] if pos > 0 else ''
练习7:写一个函数,传入圆的半径,返回圆的周长和面积。
import math


def calc_circle(radius):
    return 2 * math.pi * radius, math.pi * radius * radius
练习8:写一个函数,传入两个正整数,返回两个数的最大公约数。
def gcd(x, y):
    while y % x != 0:
        x, y = y % x, x
    return x
练习9:写一个函数,判断传入的正整数是不是素数,返回布尔值。
def is_prime(num):
    for factor in range(2, int(num ** 0.5) + 1):
        if num % factor == 0:
            return False
    return num != 1
练习10:写一个函数,判断传入的正整数是不是回文数,返回布尔值。

说明:12321是一个回文数,因为从左向右和从右向左读,结果是一样的。

def is_palindrome(num):
    total, temp = 0, num
    while temp > 0:
        total *= 10
        total += temp % 10
        temp //= 10
    return num == total
练习11:写一个函数,传入一个列表,返回列表中最大的和第二大的元素,不允许使用Python内置的排序和最大函数。
def find_max_two(items):
    first, second = (items[0], items[1]) if items[0] >= items[1] \
        else (items[1], items[0])
    for index in range(2, len(items)):
        if items[index] > first:
            second = first
            first = items[index]
        elif items[index] > second:
            second = items[index]
    return first, second
练习12:写一个函数,实现对字符串的加密,假设字符串中只有小写英文字母和空格,加密规则是adbecf,……,xaybzc,空格保持不变。
def encrypt(message):
    result = ''
    for ch in message:
        if ch == ' ':
            result += ch
        elif 'a' <= ch <= 'w':
            result += chr(ord(ch) + 3)
        else:
            result += chr(ord(ch) - 23)
    return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值