<jupyter_start><jupyter_text>1编写函数，接收一个字符串，分别统计大写字母、小写字母、数字、其他字符的个数，并以元组的形式返回结果。<jupyter_code>str = "hello world"
print(str.isalnum()) # 判断所有字符都是数字或者字母
print(str.isalpha()) # 判断所有字符都是字母
print(str.isdigit()) # 判断所有字符都是数字
print(str.islower()) # 判断所有字符都是小写
print(str.isupper()) # 判断所有字符都是大写
print(str.istitle()) # 判断所有单词都是首字母大写，像标题
print(str.isspace()) # 判断所有字符都是空白字符、\t、\n、\r
def char_type_statistic(string):
    stac_dict = {}
    stac_dict["upper_letter"] = 0
    stac_dict["lower_letter"] = 0
    stac_dict["digit"] = 0
    stac_dict["others"] = 0
    
    for elem in string:
        if elem.isupper():
            stac_dict["upper_letter"] += 1
        
        elif elem.islower():
            stac_dict["lower_letter"] += 1
            
        elif elem.isdigit():
            stac_dict["digit"] += 1
            
        else:
            stac_dict["others"] += 1
    
    return stac_dict
input_str = input("Please input string: \n")
stac_dict = char_type_statistic(input_str)
print(stac_dict)<jupyter_output>Please input string: 
Hello, World!
{'upper_letter': 2, 'lower_letter': 8, 'digit': 0, 'others': 3}<jupyter_text>2编写函数，可以接收任意多个整数并输出其中的最大值和所有整数之和。<jupyter_code>a = [2,3,4]
type(a) == list
def max_sum_of_int_list(input_list):
    sum_elem = 0
    
    # 从键盘输入的值
    input_list = input_list.split(",")
    max_elem = int(input_list[0])
    for elem in input_list:
            sum_elem += int(elem)
            if int(elem) > max_elem:
                max_elem = int(elem)
                
    return sum_elem, max_elem
input_list = input("Please input number list(split by ,):\n")
sum_elem, max_elem = max_sum_of_int_list(input_list)
print("Sum of input:", sum_elem)
print("Max of input:", max_elem)
input_list = input("Please input number list(split by ,):\n")
type(input_list) == int<jupyter_output>Please input number list(split by ,):
1,2,3,4,5,6,7,8,9,10<jupyter_text>3编写函数，模拟内置函数sorted()。（你需要先读内置函数 sorted() 的关方文档，搞清楚它的输入参数和输出）<jupyter_code>def bubble_sort(arry, reverse=True):
    """
    sorted()的内部实现类似于排序算法，以冒泡排序为例进行重写
    sorted(iterable, cmp=None, key=None, reverse=False)
    ----
    param arry:输入数组
    param reverse:降序排列
    """
    len_arry = len(arry)
    for i in range(len_arry):
        for j in range(1, len_arry - i):
            if arry[j-1] > arry[j]:
                # 交换
                arry[j-1], arry[j] = arry[j], arry[j-1]
            else:
                pass
    
    if reverse:
        return arry
    else:
        # .reverse()方法对原数组操作，不带返回值，所以不能直接return 该语句！
        arry.reverse()
        return arry
arry = [5,2,1,1,3,1,4]
bubble_sort(arry)<jupyter_output><empty_output><jupyter_text>4以字典为基础建立一个通讯录，向字典中添加和删除通讯人（名字、电话、email、工作单位等），查询某个人的信息，然后输出通讯录中所有人的信息。<jupyter_code>a = {'a': [1], 'b': 2, 'b': '3'}
a
a['a'].append(2)
a
3 in a['a']
for idx, i in enumerate(a['a']):
    if i == 2:
        print(idx)
a['a'][1]
for keys_values in zip(a.items()):
    print(keys_values)
class Concat:
    def __init__(self):
        self.dict = {}
        self.dict["name"] = []
        self.dict["phone"] = []
        self.dict["email"] = []
        self.dict["address"] = []
        
    def get_idx_by_name(self, target):
        """
        为了方便删除和查询信息，定义该函数实现根据name返回索引的功能
        """
        for idx, name in enumerate(self.dict['name']):
            if name == target:
                return idx
        
    def add(self, name, phone, email, address):
        # 防止重复添加
        if name not in self.dict["name"]:
            self.dict["name"].append(name)
            self.dict["phone"].append(phone)
            self.dict["email"].append(email)
            self.dict["address"].append(address)
        else:
            print(f"{name} information has existed!")
    
    def check(self, name):
        if name in self.dict["name"]:
            idx = self.get_idx_by_name(name)
            print("name:    ", self.dict["name"][idx])
            print("phone:   ", self.dict["phone"][idx])
            print("email:   ", self.dict["email"][idx])
            print("address: ", self.dict["address"][idx])
        else:
            print(f"None of {name} information!")
    
    def delete(self, name):
        if name in self.dict["name"]:
            idx = self.get_idx_by_name(name)
            del self.dict["name"][idx]
            del self.dict["phone"][idx]
            del self.dict["email"][idx]
            del self.dict["address"][idx]
            
        else:
            print(f"None of {name} information!")
    
    def show_all_info(self):
        for keys_values in zip(self.dict.items()):
            print(keys_values)
concat = Concat()
concat.show_all_info()
concat.add("messi", 10, "<EMAIL>", "bacelona")
concat.show_all_info()
concat.add("pedri", 16, "<EMAIL>", "bacelona")
concat.show_all_info()
concat.add("dest", 2, "<EMAIL>", "bacelona")
concat.show_all_info()
concat.check("messi")
concat.delete("dest")
concat.show_all_info()<jupyter_output>(('name', ['messi', 'pedri']),)
(('phone', [10, 16]),)
(('email', ['<EMAIL>', '<EMAIL>']),)
(('address', ['bacelona', 'bacelona']),)<jupyter_text>5用生成器的方式计算任意起止范围内质数的和。质数又称素数，是大于1的自然数，除了1和它本身外，不能被其他自然数整除。 - generator其实就是算法，它不会一次性产生全部数据，而是根据调用的次数，逐步向内存写入数据。- primes本身是生成器函数， primes()就是一个生成器，它自身不储存数据，只储存生成数据的算法。<jupyter_code>from math import sqrt

# 判断是否为素数
def is_prime(n):
    if n <= 1:
        return False
    elif n >= 2:
        # 开平方，减少循环次数
        sqrt_n = int(sqrt(n))        
        for j in range(2, sqrt_n + 1):
            if n % j == 0:
                return False

        return True

# 生成器函数
def generator_prime(n):
    while True:
        if is_prime(n):
            yield n
            
        n += 1

# 对指定区间内的素数求和
def sum_of_prime_by_iter(start, end):
    sum_prime = 0
    list_prime = []
    
    for number in generator_prime(start):
        # 生成器不会停止，所以需要添加循环终止条件
        if number <= end:
            sum_prime += number
            list_prime.append(number)
        else:
            return sum_prime, list_prime         
is_prime(7)
sum_prime, list_prime = sum_of_prime_by_iter(2, 101)
print("sum:  ", sum_prime)
print("prime:", list_prime)<jupyter_output>sum:   1161
prime: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
{'fraction_non_alphanumeric': 0.152596880527416, 'fraction_numerical': 0.020421289596398134, 'mean_word_length': 2.687018375815056, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '76961', 'license': 'MIT', 'n_tokens_mistral': 2675, 'n_tokens_neox': 2712, 'n_words': 433, 'path': 'Homework/HW 02/Practice 02.ipynb', 'repo_name': 'datamonday/PythonTricks', 'size': '6268'}