import time import os def generate_tree(height): tree = [] for i in range(height): tree.append((' ' * (height - i - 1)) + ('*' * (2 * i + 1))) return tree def generate_star(tree_height): return ' ' * (tree_height - 1) + '*' def print_tree(tree, star): os.system('cls' if os.name == 'nt' else 'clear') print(star) for row in tree: print(row) def blink_star(tree, tree_height, blink_times): star_on = generate_star(tree_height) star_off = ' ' * tree_height for _ in range(blink_times): print_tree(tree, star_on) time.sleep(0.5) print_tree(tree, star_off) time.sleep(0.5) print_tree(tree, star_on) if __name__ == "__main__": tree_height = int(input("Enter the height of the Christmas tree: ")) blink_times = int(input("Enter the number of times the star should blink: ")) tree = generate_tree(tree_height) blink_star(tree, tree_height, blink_times)
两段代码,第一段:def bubble_sort_optimized(arr): n = len(arr) for i in range(n): # 提前退出冒泡循环的标志位 swapped = False # 从第一个元素到`n-i-1`,最后的i个已经排好序了 for j in range(0, n-i-1): # 交换如果发现元素是逆序的 if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] swapped = True # 如果没有发生交换,则已经排序完成 if not swapped: break return arr 第二段:def bubble_sort_basic(arr): n = len(arr) # 遍历所有数组元素 for i in range(n): # 内层循环,进行逐一比较 for j in range(0, n-i-1): # 交换如果发现元素是逆序的 if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr
输出:
name: |Optimized Bubble Sortcontent: |def bubble_sort_optimized(arr):n = len(arr)for i in range(n):# 提前退出冒泡循环的标志位swapped = False# 从第一个元素到n-i-1,最后的i个已经排好序了for j in range(0, n-i-1):# 交换如果发现元素是逆序的if arr[j] > arr[j+1]:arr[j], arr[j+1] = arr[j+1], arr[j]swapped = True# 如果没有发生交换,则已经排序完成if not swapped:breakreturn arrwhy: |The optimized bubble sort is chosen because it includes a mechanism to stop the algorithm early if the list is already sorted. This optimization can significantly reduce the number of passes the algorithm needs to make on nearly sorted lists, improving the average case performance.flow:|Initialize the length of the array.|Iterate over the array with a variable 'i' from 0 to n-1.|Set a flag 'swapped' to False before starting inner loop.|Iterate over the array from 0 to n-i-1 with a variable 'j'.|Compare adjacent elements and swap if they are in the wrong order.|If any swap occurs, set the flag 'swapped' to True.|After completing inner loop, check if 'swapped' is False, if so, break the outer loop as the array is sorted.|Return the sorted array.problem_tests:input: |[64, 34, 25, 12, 22, 11, 90]output: |[11, 12, 22, 25, 34, 64, 90]input_output_examples_flow:|Initialize n to 7 (length of the array).|In the first pass, 'swapped' is set to True and several swaps are made.|In subsequent passes, fewer swaps are needed as the largest elements bubble to the end of the list.|If in any pass, no swaps are made, the 'swapped' flag remains False and the algorithm terminates early.|The final sorted array is returned, which matches the expected output.