# 03-Laboratory Exercise01-10「意大利」

AI悦创原创PythonPython一对一教学Python一对一辅导Python 辅导编程一对一教学少儿编程一对一少儿编程一对一教学意大利Python一对一教学PythonPython一对一教学Python一对一辅导Python 辅导编程一对一教学少儿编程一对一少儿编程一对一教学意大利Python一对一教学大约 18 分钟...约 5506 字

## Lab01

1. 01.3.9 An alphanumeric code of 16 characters alternating strings “abcd” and “1234”.

01.3.9由“abcd”和“1234”交替组成的16个字符的字母数字代码。

``````letters = "abcd"
numbers = "1234"

result = ""
for i in range(16):
if i % 2 == 0:
result += letters[i//2 % 4]
else:
result += numbers[i//2 % 4]

print(result)
``````

• `i//2` 用于将 `i` 除以 2，得到一个整数结果。
• `% 4` 用于将结果对 4 取模。因为 "abcd" 和 "1234" 都只有 4 个字符，所以这样可以确保结果始终在 0 到 3 之间。

1. 01.3.10 A checkboard of size 5x5 where the white squares are indicated by a “0”, and the black squares by a “1”.

01.3.10大小为5x5的方格，其中白色方格用“0”表示，黑色方格用“1”表示。

``````# 可以使用以下代码实现 5x5 的棋盘，其中白色方块用 "0" 表示，黑色方块用 "1" 表示：
board = []
for i in range(5):
row = []
for j in range(5):
if (i + j) % 2 == 0:
row.append("0")
else:
row.append("1")
board.append(row)

for row in board:
print(" ".join(row))

# 输出
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
``````
1. 01.3.11 O line of 100 dashes (“-”).

01.3.11 O线的100虚线(“-”)。

``````print("-" * 100)
``````
1. 01.3.12 A sequence of 100 zeros.

01.3.12 100个0的序列。

``````print("0" * 100)
``````
1. 01.3.13 The fourth element of the Fibonacci sequence, where every element is the sum of the two preceding elements. The first two elements of the sequence are 0 and 1.

01.3.13斐波那契数列的第四个元素，其中每个元素都是前两个元素的和。序列的前两个元素是0和1。

``````fib1 = 0
fib2 = 1
fib3 = fib1 + fib2
fib4 = fib2 + fib3

print(fib4)
``````
1. 01.3.14 The first four element of the Fibonacci sequence in a column.

01.3.14一列中斐波那契数列的前四个元素。

``````fib1 = 0
fib2 = 1

print(fib1)
print(fib2)

for i in range(2, 4):
fib3 = fib1 + fib2
print(fib3)
fib1 = fib2
fib2 = fib3
``````
1. 01.3.15 A closing phrase for this laboratory session, inside a box of your choosing, including the computation of the percentage of exercises you completed.

01.3.15本次实验的结束语，在你选择的盒子里，包括

``````total_exercises = 16
completed_exercises = 4
percentage_completed = (completed_exercises / total_exercises) * 100

print("+" + "-" * 38 + "+")
print("|" + " " * 38 + "|")
print("| Thank you for participating in this laboratory session! |")
print("| You have completed {:.0f}% of the exercises. |".format(percentage_completed))
print("|" + " " * 38 + "|")
print("+" + "-" * 38 + "+")

# 输出
+--------------------------------------+
|                                      |
| Thank you for participating in this laboratory session! |
| You have completed 25% of the exercises. |
|                                      |
+--------------------------------------+

``````

## Lab04

04.1.3 Shapes. Write a program that takes as an input an integer number n and prints a square and a rhombus filled with asterisks (*), with each side long n asterisks. Example: using n=4, the program shows:

04.1.3形状。编写一个程序，以整数n作为输入，打印一个正方形和一个菱形，两边都有星号(*)，两边都有n个星号。示例:使用n=4，程序显示:

``````n = 4

# Print square
for i in range(n):
for j in range(n):
print("*", end="")
print()

print()

# Print rhombus
for i in range(-n + 1, n):
for j in range(abs(i), n):
print(" ", end="")
for j in range(2 * abs(i) + 1):
print("*", end="")
print()
``````
``````def print_square_and_rhombus(n):
# print square
for i in range(n):
for j in range(n):
print("*", end="")
print("")

print("")  # add a blank line

# print rhombus
for i in range(-n+1, n):
for j in range(-n+1, n):
if abs(j) + abs(i) <= n-1:
print("*", end="")
else:
print(" ", end="")
print("")

n = 4
print_square_and_rhombus(n)
``````
``````n = int(input("Enter the side length of the rhombus: "))

for i in range(-n + 1, n):
spaces = abs(i)
asterisks = 2 * (n - spaces) - 1

print(" " * spaces + "*" * asterisks)

``````

04.1.4 Words in reverse. Write a program that reads a word and outputs:

04.1.4颠倒文字。编写一个程序，读取一个单词并输出:

1. The reversed word. If the user writes the string 'Hello', the program shall output 'olleH' [P4.9]

1. The uppercase letters starting from the end. If the user writes the string 'HeLlO', the program shall output 'OLH'.

``````word = "Hello"

# I. Reversed word
reversed_word = word[::-1]
print("I. Reversed word:", reversed_word)

# II. Uppercase letters starting from the end
uppercase_letters = ""
for char in reversed_word:
if char.isupper():
uppercase_letters += char
print("II. Uppercase letters starting from the end:", uppercase_letters)
``````

04.1.5 Prime numbers. Write a program that asks the user for an integer number and shows as an output a message showing whether the input number is prime.

04.1.5质数。编写一个程序，要求用户输入一个整数，并作为输出显示一条消息，显示输入的数字是否为素数。

``````def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

number = int(input("Enter a number: "))

if is_prime(number):
print("The number is prime.")
else:
print("The number is not prime.")
``````

04.1.6 Prime numbers. Write a program that asks the user for an integer number and shows all the prime numbers lower or equal to that number. Example: if the user inputs 20, the program shall output:

04.1.6质数。编写一个程序，要求用户输入一个整数，并显示所有小于或等于该整数的质数。例:如果用户输入20，程序输出:

``````def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

def main():
n = int(input("Enter a number: "))
for i in range(2, n + 1):
if is_prime(i):
print(i)

if __name__ == "__main__":
main()
``````

• 首先，通过 `input` 函数从用户输入一个整数，并将其存储在 `n` 变量中。
• 然后，通过 `for` 循环从 2 到 `n` 遍历整数。
• 对于每一个整数，使用另一个 `for` 循环，从 2 到该整数的开方（使用 `math.sqrt` 函数计算）检查是否存在因子。
• 如果没有找到因子，则该整数是素数，通过 `print` 函数输出。

04.1.7 Words and spaces. Write a program reading a word and showing all its substring, sorted by increasing length. If the user inputs the string 'rum', the program shall output:

``````def get_substrings(word):
substrings = []
for i in range(len(word)):
for j in range(i+1, len(word)+1):
substrings.append(word[i:j])
return substrings

def main():
word = input("Enter a word: ")
substrings = get_substrings(word)
substrings.sort(key=len)
for substring in substrings:
print(substring)

if __name__ == '__main__':
main()
``````

## Lab06

06.1.1 Speech Count. Write the function:

06.1.1语音计数。编写函数:

`def count_vowels(string)`

Returns the number of vowels in the string. Vowels are the letters a, e, i, o, and u; as well as their respective capitalized versions.

``````def count_vowels(string):
vowels = 'aeiouAEIOU'
count = 0
for char in string:
if char in vowels:
count += 1
return count

input_str = input("Enter a string: ")
vowel_count = count_vowels(input_str)
print("The number of vowels in the given string is:", vowel_count)
``````

1. 首先，函数定义了一个计数器变量 `count`，并将其初始值设为 0。
2. 接下来，通过循环遍历字符串的每一个字符。
3. 如果该字符为元音字母（a，e，i，o，u，A，E，I，O，U），则将 `count` 计数器加一。
4. 遍历完字符串中的所有字符后，函数返回 `count` 计数器的值，表示字符串中元音字母的数量。

06.1.2 Word Count. Write the function:

``````def count_words(string)
``````

Returns the number of words in the string. Words are sequences of characters separated by spaces (assume that between two consecutive words, there is exactly one space). For example, count_words("Mary had a little lamb") returns 5.

``````def count_words(string):
return len(string.split())
``````

• 使用 split() 函数将字符串分割为单词列表
• 返回单词列表的长度，即为单词数量

How could the exercise be extended so that strings, where there are multiple spaces between words, are correctly treated? [P5.7]

``````def count_words(string):
string = ' '.join(string.split())
return len(string.split())

a = count_words("Hello  aiyc")
print(a)
``````

06.1.3 Geometric solids. Write functions:

``````def sphere_volume(r)
def sphere_surface(r)
def cylinder_volume(r, h)
def cylinder_surface(r, h)
def cone_volume(r, h)
def cone_surface(r, h)
``````

To calculate the volume and surface area of a sphere of radius r, a cylinder with a circular base of radius r and height h and a cone with a circular base with radius r and height h. Then write a program that asks the user to enter the values r and h, then the program calls the six functions and display the output results.

``````import math

def sphere_volume(r):
return (4/3) * math.pi * (r**3)

def sphere_surface(r):
return 4 * math.pi * (r**2)

def cylinder_volume(r, h):
return math.pi * (r**2) * h

def cylinder_surface(r, h):
return 2 * math.pi * r * h + 2 * math.pi * (r**2)

def cone_volume(r, h):
return (1/3) * math.pi * (r**2) * h

def cone_surface(r, h):
return math.pi * r * (r + math.sqrt(h**2 + r**2))

r = float(input("Enter the radius: "))
h = float(input("Enter the height: "))

print("Sphere volume: ", sphere_volume(r))
print("Sphere surface area: ", sphere_surface(r))
print("Cylinder volume: ", cylinder_volume(r, h))
print("Cylinder surface area: ", cylinder_surface(r, h))
print("Cone volume: ", cone_volume(r, h))
print("Cone surface area: ", cone_surface(r, h))
``````

06.1.4 Bank Balance. Write a function that calculates the balance of a bank account by crediting interest annually. The function receives as parameters: the number of years, the initial balance, and the annual interest rate.

06.1.4银行余额。编写一个函数，通过每年记入利息来计算银行帐户的余额。该函数接收的参数为:年数、初始余额和年利率。

``````def bank_balance(years, balance, interest_rate):
for year in range(years):
interest = balance * interest_rate / 100
balance = balance + interest
return balance
``````

## Lab07

07.1.3 Remove the minimum value. Write a remove_min(v) function that removes the minimum value from a v list without using the min() function or the remove() method.

``````def remove_min(v):
min_value = v[0]
min_index = 0
for i in range(1, len(v)):
if v[i] < min_value:
min_value = v[i]
min_index = i
v.pop(min_index)
return v
``````

07.1.4 Local highs. Read a sequence of integers ended by a blank line. Print the position of the local maxima (numbers greater than both the previous and the next value) if there are any, otherwise print the message 'There are no local maxima'. Extension: if there are several pairs of local maxima, identify the two closest local maxima and print their position.

07.1.4本地高位。读取以空行结束的整数序列。如果有局部极大值，则打印局部极大值的位置(大于前一个值和下一个值的数字)，否则打印消息'没有局部极大值'。扩展:如果有几对局部极大值，识别出最接近的两个局部极大值并打印它们的位置。

``````def find_local_maxima(numbers):
local_maxima = []
for i, n in enumerate(numbers[1:-1]):
if n > numbers[i] and n > numbers[i + 2]:
local_maxima.append(i + 1)
return local_maxima

def remove_min(numbers):
min_index = numbers.index(min(numbers))
numbers.pop(min_index)
return numbers

def get_input():
numbers = []
while True:
try:
n = int(input("Enter a number (or press enter to finish): "))
numbers.append(n)
except ValueError:
break
return numbers

def main():
numbers = get_input()
local_maxima = find_local_maxima(numbers)
if not local_maxima:
print("There are no local maxima")
else:
print("Local maxima at positions:", local_maxima)
if len(local_maxima) >= 2:
numbers = remove_min(numbers)
local_maxima = find_local_maxima(numbers)
if local_maxima:
print("The two closest local maxima are at positions:", local_maxima)
else:
print("There are no local maxima")

if __name__ == '__main__':
main()
``````

• 首先，使用 `get_input` 函数从用户处读入整数数列
• 然后，使用 `find_local_maxima` 函数找到数列中的所有局部极值
• 如果局部极值不存在，则输出 "There are no local maxima"
• 如果存在局部极值，则输出它们的位置
• 如果存在至少两个局部极值，则从数列中删除最小值，再次查找局部极值，并输出它们的位置
• 如果删除后不存在局部极值，则输出 "There are no local maxima"

07.1.5 The same elements. Write the same_set(a, b) function that checks if two lists contain the same elements, regardless of the order and ignoring the presence of duplicates. For example, the two lists 1 4 9 16 9 7 4 9 11 and 11 11 7 9 16 4 1 must be considered equal. The function must not modify the lists that have been passed as parameters.

``````def same_set(a, b):
return sorted(set(a)) == sorted(set(b))
``````

07.1.6 Ordered list. Write a program that generates a sequence of 20 random integer values between 0 and 99, then displays the generated sequence, orders it, and displays it again, sorted. Use the sort() method.

``````import random

def ordered_list():
# Generate a list of 20 random integers between 0 and 99
random_list = [random.randint(0, 99) for i in range(20)]

# Display the generated sequence
print("Generated sequence: ", random_list)

# Order the list
random_list.sort()

# Display the ordered list
print("Ordered sequence: ", random_list)

# Call the function
ordered_list()
``````
``````import random

def ordered_list():
# Generate a list of 20 random integers between 0 and 99
random_list = []
for i in range(20):
random_list.append(random.randint(0, 99))
# Display the generated sequence
print("Generated sequence: ", random_list)

# Order the list
random_list.sort()

# Display the ordered list
print("Ordered sequence: ", random_list)

# Call the function
ordered_list()

``````

07.1.7 Add up without the minimum. Write the sum_without_smallest(v) function that calculates the sum of all the values of a list v, excluding the minimum value.

``````def sum_without_smallest(v):
v.sort()
v = v[1:]
return sum(v)
``````

1. 先对列表进行排序，使用 `sort()` 方法。
2. 取列表中除了最小值以外的所有数字，使用切片 `v[1:]`
3. 返回排除最小值后列表中所有数字的总和，使用 `sum()` 函数。

07.2.1 Measurement noise. Often the data collected during an experiment has to be processed to remove some of the measurement noise. A simple approach to this problem involves replacing, in a list of values, each value with the average between the same value and the two adjacent values (or of the only adjacent value if the value under consideration is at one of the two ends of the list). Write a program that does this, without creating a second list. [P6.36]

07.2.1测量噪声。通常，在实验过程中收集的数据必须经过处理以去除一些测量噪声。解决这个问题的一个简单方法是，在一个值列表中，将每个值替换为相同值与两个相邻值之间的平均值(如果考虑的值位于列表的两端之一，则替换为唯一相邻值之间的平均值)。编写一个这样做的程序，而不需要创建第二个列表。(P6.36)

``````def measurement_noise(lst):
for i in range(1, len(lst) - 1):
lst[i] = (lst[i - 1] + lst[i] + lst[i + 1]) / 3
return lst
``````

• 列表：数字列表的存储方法。
• 循环：遍历数字列表的方法。
• 判断：决定每个数字的相邻数字的数量的方法。
• 计算：计算平均值的方法。
• 存储：将计算的平均值存储回列表中的方法。

AI悦创·编程一对一

AI悦创·推出辅导班啦，包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发、Web、Linux」，全部都是一对一教学：一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然，还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线，随时响应！微信：Jiabcdefh

C++ 信息奥赛题解，长期更新！长期招收一对一中小学信息奥赛集训，莆田、厦门地区有机会线下上门，其他地区线上。微信：Jiabcdefh

• 0
• 0
• 0
• 0
• 0
• 0

• 按正序
• 按倒序
• 按热度