1. Trang chủ
  2. » Giáo án - Bài giảng

Quyển 3. 200 Bài tập ôn thi Tin Học Trẻ Bảng B.pdf

52 0 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề 200 bài tập ôn thi tin học trẻ bảng B
Người hướng dẫn GV: Nguyễn Thế Phương
Trường học Học viện Công nghệ Bưu chính Viễn thông
Chuyên ngành Tin học trẻ
Thể loại Tài liệu ôn tập
Năm xuất bản 2024 - 2025
Thành phố Hà Nội
Định dạng
Số trang 52
Dung lượng 1,63 MB

Cấu trúc

  • 1. Xử lý chuỗi; dãy số… (20 bài tập) (2)
  • 2. Sắp xếp; tìm kiếm: an, max, min, mã hoá; giải mã; hoán vị (20 bài tập) (6)
  • 3. Số nguyên tố; số hoàn hảo; số là bạn; số nhị phân, thập phân (50 bài) (11)
  • 4. Tổng các chữ số của một số; ước số; giải các bài toán thông minh, toán khó, toán thực tế và dạng toán ở cấp học. (60 bài tập) (21)
  • 5. Bài tập về mảng dữ liệu và số (20 bài tập) (32)
  • 6. Nhập xuất tệp trong Python (20 bài tập) (35)
  • 7. BÀI TẬP TỔNG HỢP (10 bài tập) (39)

Nội dung

Tài liệu lý thuyết và bài tập Python gồm 52 trang, định dạng PDF, được xếp theo mức độ dễ đến khó để học sinh làm quen với lý thuyết va bài tập lập trình Python ôn thi Tin học trẻ bảng B.

Xử lý chuỗi; dãy số… (20 bài tập)

Bài tập 1: Đếm số chữ số trong một chuỗi

Viết chương trình đếm số chữ số trong một chuỗi. def count_digits(s): return sum(c.isdigit() for c in s)

Ví dụ sử dụng: string_input = "Học sinh 123, lớp 9A" print(count_digits(string_input))

Bài tập 2: Tìm số lớn nhất trong một chuỗi số

Viết chương trình tìm số lớn nhất trong một chuỗi số. def find_max_number(s): numbers = list(map(int, s.split())) return max(numbers)

Ví dụ sử dụng string_input = "10 20 5 30 15" print(find_max_number(string_input))

Bài tập 3: Đảo ngược chuỗi số

Viết chương trình đảo ngược một chuỗi số. def reverse_string(s): return s[::-1]

Ví dụ sử dụng string_input = "12345" print(reverse_string(string_input))

Bài tập 4: Kiểm tra chuỗi số có đối xứng không

Viết chương trình kiểm tra xem một chuỗi số có đối xứng hay không. def is_palindrome(s): return s == s[::-1]

Ví dụ sử dụng string_input = "12321" print(is_palindrome(string_input))

Bài tập 5: Tính tổng các chữ số trong chuỗi

Viết chương trình tính tổng các chữ số trong một chuỗi. def sum_of_digits(s): return sum(int(c) for c in s if c.isdigit())

Ví dụ sử dụng string_input = "abc123" print(sum_of_digits(string_input))

Bài tập 6: Tìm vị trí của số lớn nhất trong chuỗi

To find the position of the largest number in a sequence, you can use the following Python function: `def max_number_position(s):` This function converts the input string `s` into a list of integers, identifies the maximum number with `max(numbers)`, and then returns the index of this maximum value using `numbers.index(max_num)`.

Ví dụ sử dụng string_input = "1 3 5 7 9 2" print(max_number_position(string_input))

Bài tập 7: Thay thế số trong chuỗi

Viết chương trình thay thế tất cả các số trong chuỗi bằng dấu `*`. def replace_digits(s): return ''.join('*' if c.isdigit() else c for c in s)

Ví dụ sử dụng string_input = "Học sinh 123" print(replace_digits(string_input))

Bài tập 8: Lọc số chẵn trong chuỗi

Viết chương trình lọc ra các số chẵn trong chuỗi. def filter_even_numbers(s): numbers = list(map(int, s.split())) return [num for num in numbers if num % 2

Ví dụ sử dụng string_input = "1 2 3 4 5 6" print(filter_even_numbers(string_input))

Bài tập 9: Đếm số lần xuất hiện của một số

Viết chương trình đếm số lần xuất hiện của một số trong chuỗi. def count_occurrences(s, num): numbers = s.split() return numbers.count(str(num))

Ví dụ sử dụng string_input = "1 2 3 1 4 1" print(count_occurrences(string_input, 1))

Bài tập 10: Sắp xếp các số trong chuỗi

Viết chương trình sắp xếp các số trong chuỗi theo thứ tự tăng dần. def sort_numbers(s): numbers = list(map(int, s.split())) return ' '.join(map(str, sorted(numbers)))

Ví dụ sử dụng string_input = "3 1 4 1 5 9" print(sort_numbers(string_input))

Bài tập 11: Tìm số nguyên tố trong chuỗi

This article presents a program that identifies all prime numbers within a given string The function `is_prime(n)` checks if a number is prime by returning `False` for any integer less than 2 and using a loop to test divisibility for numbers greater than or equal to 2 The `find_primes(s)` function converts a string of numbers into a list of integers and utilizes list comprehension to return only those numbers that are prime, as determined by the `is_prime` function.

Ví dụ sử dụng string_input = "10 11 12 13 14 15" print(find_primes(string_input))

Bài tập 12: Xóa số trùng lặp trong chuỗi

Here’s a program that removes duplicate numbers from a string while preserving the original order The function `remove_duplicates(s)` splits the input string into individual numbers, checks for duplicates using a set, and appends unique numbers to a result list Finally, it returns the result as a space-separated string.

Ví dụ sử dụng string_input = "1 2 2 3 4 4 5" print(remove_duplicates(string_input))

Bài tập 13: Tính trung bình các số trong chuỗi

Viết chương trình tính trung bình cộng của các số trong chuỗi. def average_of_numbers(s): numbers = list(map(int, s.split())) return sum(numbers) / len(numbers)

Ví dụ sử dụng string_input = "10 20 30 40" print(average_of_numbers(string_input))

Bài tập 14: Đếm số lượng số âm và dương

To create a program that counts the number of positive and negative numbers in a string, define a function called `count_positive_negative(s)` This function converts the string into a list of integers using `map(int, s.split())` It then calculates the count of positive numbers by summing up instances where the numbers are greater than zero, and the count of negative numbers by summing instances where the numbers are less than zero Finally, the function returns both counts as a tuple.

Ví dụ sử dụng string_input = "-1 2 -3 4 5" print(count_positive_negative(string_input))

Bài tập 15: Tìm số gần nhất với giá trị trung bình

This program finds the number closest to the average in a given sequence It first converts the input string into a list of integers Then, it calculates the average of these numbers Finally, it identifies the number that is closest to this average using a minimum function with an absolute difference.

Ví dụ sử dụng string_input = "1 2 3 4 5" print(closest_to_average(string_input))

Bài tập 16: Tính giai thừa của từng số trong chuỗi

This article presents a program to calculate the factorial of each number in a given string The `factorial` function recursively computes the factorial for a non-negative integer, returning 1 for an input of 0 The `factorial_of_numbers` function processes a string of numbers, converting them into a list of integers and applying the `factorial` function to each element The result is a list of factorial values corresponding to the input numbers.

Ví dụ sử dụng string_input = "0 1 2 3 4" print(factorial_of_numbers(string_input))

Bài tập 17: Sắp xếp các số theo thứ tự giảm dần

The program sorts numbers in a string in descending order It defines a function, `sort_descending(s)`, which converts the input string into a list of integers The function then sorts these numbers in reverse order and returns them as a space-separated string.

Ví dụ sử dụng string_input = "5 3 8 1 2" print(sort_descending(string_input))

Bài tập 18: Tìm số lớn thứ hai trong chuỗi

To find the second largest number in a string of numbers, you can use the following Python function: `def second_largest(s):` This function converts the input string into a list of integers and removes duplicates by utilizing `set()` It then sorts the unique numbers in ascending order The function returns the second largest number by accessing the second-to-last element of the sorted list, provided there are at least two unique numbers; otherwise, it returns `None`.

Ví dụ sử dụng string_input = "1 2 3 4 5" print(second_largest(string_input)) Kết quả: 4

Bài tập 19: Kiểm tra chuỗi có chứa số hoàn hảo không

This article discusses a program designed to check for perfect numbers within a given string A perfect number is defined as a number that is equal to the sum of its proper divisors The function `is_perfect(n)` determines if a number is perfect by summing its divisors Additionally, the function `has_perfect_number(s)` converts a string of numbers into a list and checks if any of these numbers are perfect This program effectively identifies perfect numbers present in the input string.

Ví dụ sử dụng string_input = "6 8 12" print(has_perfect_number(string_input))

Kết quả: True (vì 6 là số hoàn hảo)

Bài tập 20: Chia các số thành hai chuỗi: chẵn và lẻ

The program splits a string of numbers into two separate strings: one containing even numbers and the other containing odd numbers The function `split_even_odd(s)` takes a string input, converts it into a list of integers, and then generates two new strings The first string, `evens`, includes all even numbers, while the second string, `odds`, includes all odd numbers The function returns both strings for further use.

Ví dụ sử dụng string_input = "1 2 3 4 5 6" evens, odds = split_even_odd(string_input) print("Chẵn:", evens) Kết quả: Chẵn: 2 4 6 print("Lẻ:", odds)  Kết quả: Lẻ: 1 3 5

Sắp xếp; tìm kiếm: an, max, min, mã hoá; giải mã; hoán vị (20 bài tập)

Bài tập 1: Mã hóa Caesar

To implement a Caesar cipher for text encryption with a shift of 3, you can use the following function: ```pythondef caesar_encrypt(text): result = "" for char in text: if char.isalpha(): shift = 3 base = ord('A') if char.isupper() else ord('a') result += chr((ord(char) - base + shift) % 26 + base) else: result += char return result```This function processes each character in the input text, shifting alphabetic characters by three positions while leaving non-alphabetic characters unchanged.

# Test print(caesar_encrypt("Hello World!"))

Bài tập 2: Giải mã Caesar

Viết hàm giải mã văn bản đã được mã hóa bằng phương pháp Caesar. def caesar_decrypt(text): result = "" for char in text: if char.isalpha(): shift = 3

GV: Nguyễn Thế Phương 6 base = ord('A') if char.isupper() else ord('a') result += chr((ord(char) - base - shift) % 26 + base) else: result += char return result

# Test print(caesar_decrypt("Khoor Zruog!"))

Bài tập 3: Hoán vị ký tự

Viết hàm hoán vị các ký tự trong một chuỗi. import random def shuffle_string(s): s_list = list(s) random.shuffle(s_list) return ''.join(s_list)

# Test print(shuffle_string("Python"))

Bài tập 4: Mã hóa Vigenère

To implement the Vigenère cipher for text encryption, use the following function: `def vigenere_encrypt(plaintext, key):` The function initializes an empty string for the result and calculates the key length It then iterates through each character in the plaintext; if the character is alphabetic, it computes the shift based on the corresponding key character The base ASCII value is determined based on the case of the character, and the encrypted character is appended to the result Non-alphabetic characters are added unchanged Finally, the function returns the encrypted result.

# Test print(vigenere_encrypt("ATTACKATDAWN", "LEMON"))

Bài tập 5: Giải mã Vigenère

To decode text encrypted using the Vigenère cipher, implement the `vigenere_decrypt` function, which takes the ciphertext and a key as inputs The function initializes an empty string for the result and calculates the key's length It iterates through each character in the ciphertext, checking if it is an alphabetic character For each letter, it determines the appropriate shift based on the corresponding key character, adjusting for uppercase or lowercase letters Non-alphabetic characters are added to the result without modification Finally, the function returns the decrypted plaintext.

# Test print(vigenere_decrypt("LXFOPVEFRN", "LEMON"))

Bài tập 6: Mã hóa Base64

Viết hàm mã hóa chuỗi thành định dạng Base64. import base64 def base64_encode(s): return base64.b64encode(s.encode()).decode()

# Test print(base64_encode("Hello World!"))

Bài tập 7: Giải mã Base64

Viết hàm giải mã chuỗi từ định dạng Base64. def base64_decode(s): return base64.b64decode(s).decode()

# Test print(base64_decode("SGVsbG8gV29ybGQh"))

Bài tập 8: Mã hóa XOR

To implement a text encryption and decryption function using the XOR method with a key, you can define the function `xor_encrypt_decrypt(text, key)` This function processes each character of the input text by applying the XOR operation with the corresponding character from the key, ensuring that the key wraps around as needed The final output is constructed by joining the results of these operations into a single string.

# Test key = "key" encrypted = xor_encrypt_decrypt("Hello", key) print(encrypted) print(xor_encrypt_decrypt(encrypted, key)) # Giải mã

Bài tập 9: Mã hóa bằng phương pháp Atbash

The Atbash cipher is a simple substitution cipher that replaces each letter in the text with its reverse counterpart in the alphabet To implement this, the `atbash_encrypt` function takes a string input and iterates through each character If the character is an alphabet letter, it calculates the corresponding letter from the opposite end of the alphabet, using ASCII values for both uppercase and lowercase letters Non-alphabet characters remain unchanged The function then returns the encrypted text, effectively transforming the original message through this unique encoding method.

# Test print(atbash_encrypt("Hello World!"))

Bài tập 10: Giải mã Atbash

Viết hàm giải mã văn bản đã được mã hóa bằng phương pháp Atbash. def atbash_decrypt(text): return atbash_encrypt(text) # Atbash là đối xứng

# Test print(atbash_decrypt("Svool Dliow!"))

Bài tập 11: Mã hóa bằng phương pháp Rail Fence

The Rail Fence encryption method is a simple technique for encoding text To implement this, the function `rail_fence_encrypt(text, key)` creates a list called `fence`, initialized with empty strings based on the specified `key` As the function iterates through each character of the input `text`, it distributes the characters across the `fence` based on the modulo of the current index and the `key` Finally, the encoded message is returned by joining the strings in the `fence`.

# Test print(rail_fence_encrypt("HELLO WORLD", 3))

Bài tập 12: Giải mã Rail Fence

To decode a message encrypted using the Rail Fence cipher, implement the `rail_fence_decrypt` function with a specified key First, create a 2D list to represent the fence structure, initializing it with newline characters Traverse the fence to mark the pattern with asterisks while alternating the direction down and up Next, fill the marked positions with characters from the ciphertext sequentially Finally, extract the characters from the fence in the correct order to reconstruct the original message, returning the decrypted text as a single string.

# Test print(rail_fence_decrypt("HOOLEL WRD", 3))

Bài tập 13: Mã hóa bằng phương pháp Columnar Transposition

The Columnar Transposition method is a technique used for text encryption The function `columnar_transposition_encrypt` takes a string of text and a key as inputs It initializes a list of empty strings, each corresponding to a character in the key As it iterates through the characters of the text, it distributes them into the columns based on their position relative to the key's length Finally, the function concatenates the columns and returns the encrypted text as a single string.

# Test print(columnar_transposition_encrypt("HELLO WORLD", "3142"))

Bài tập 14: Giải mã Columnar Transposition

To decode text encrypted using the Columnar Transposition method, the function `columnar_transposition_decrypt(ciphertext, key)` is implemented It calculates the number of columns based on the length of the key and determines the number of rows needed for the ciphertext The function initializes a list of empty strings for each column and fills them by iterating through the sorted indices of the key Finally, it constructs the decrypted message by concatenating characters from each column row by row, returning the resulting plaintext.

# Test print(columnar_transposition_decrypt("HLOEL WRD", "3142"))

Bài tập 15: Mã hóa bằng phương pháp Playfair

Viết hàm mã hóa văn bản bằng phương pháp Playfair. def playfair_encrypt(text, key):

# Cần implement phương pháp Playfair pass # Chưa hoàn thành

# print(playfair_encrypt("HELLO", "KEY"))

Bài tập 16: Giải mã bằng phương pháp Playfair

Viết hàm giải mã văn bản đã được mã hóa bằng phương pháp Playfair. def playfair_decrypt(ciphertext, key):

# Cần implement phương pháp Playfair pass # Chưa hoàn thành

# print(playfair_decrypt("CIPHERTEXT", "KEY"))

Bài tập 17: Mã hóa bằng phương pháp RSA

Viết hàm mã hóa văn bản bằng phương pháp RSA. from sympy import mod_inverse def rsa_encrypt(message, e, n): return [pow(ord(char), e, n) for char in message]

# n = 3233 # Ví dụ về số nguyên tố

Bài tập 18: Giải mã bằng phương pháp RSA

Viết hàm giải mã văn bản đã được mã hóa bằng phương pháp RSA. def rsa_decrypt(ciphertext, d, n): return ''.join([chr(pow(char, d, n)) for char in ciphertext])

# d = mod_inverse(e, phi) # Cần tính phi

# print(rsa_decrypt([encrypted_values], d, n))

Bài tập 19: Mã hóa bằng phương pháp Hashing```

Viết hàm mã hóa văn bản thành hash. import hashlib def hash_text(text): return hashlib.sha256(text.encode()).hexdigest()

# Test print(hash_text("Hello World!"))

Bài tập 20: Giải mã hash (khó)

Viết hàm kiểm tra xem một văn bản có phải là hash của một chuỗi không. def check_hash(original, hashed): return hash_text(original) == hashed

# Test print(check_hash("Hello World!", hash_text("Hello World!")))

Số nguyên tố; số hoàn hảo; số là bạn; số nhị phân, thập phân (50 bài)

Bài tập 1: Kiểm tra số nguyên tố

To determine if a number is prime, we can use the function `is_prime(n)` This function first checks if the number is less than or equal to 1, returning `False` if so It then iterates through possible divisors from 2 to the square root of the number If the number is divisible by any of these divisors, the function returns `False` If no divisors are found, it returns `True`, indicating that the number is prime.

# Test print(is_prime(7)) # True print(is_prime(10)) # False

Bài tập 2: Liệt kê số nguyên tố trong khoảng

Viết hàm liệt kê tất cả các số nguyên tố trong khoảng từ `a` đến `b`. def primes_in_range(a, b): return [n for n in range(a, b + 1) if is_prime(n)]

# Test print(primes_in_range(10, 30))

Bài tập 3: Số nguyên tố đầu tiên

To find the first n prime numbers in the sequence of natural numbers, you can use the function `first_n_primes(n)` This function initializes an empty list called `primes` and starts checking from the number 2 It continues to add prime numbers to the list until it contains n primes, using the helper function `is_prime(num)` to verify the primality of each number Finally, it returns the list of prime numbers.

Bài tập 4: Tổng các số nguyên tố

Viết hàm tính tổng các số nguyên tố trong khoảng từ `a` đến `b`. def sum_of_primes(a, b): return sum(n for n in range(a, b + 1) if is_prime(n))

# Test print(sum_of_primes(10, 30))

Bài tập 5: Kiểm tra số nguyên tố Mersenne

Viết hàm kiểm tra xem một số có phải là số nguyên tố Mersenne hay không. def is_mersenne_prime(p): if is_prime(p): return is_prime(2**p - 1) return False

# Test print(is_mersenne_prime(3)) # True (2^3 - 1 = 7) print(is_mersenne_prime(4)) # False (2^4 - 1 = 15)

Bài tập 6: Số nguyên tố lớn nhất trong dãy

To find the largest prime number in a list of integers, you can use the following function: `def max_prime_in_list(numbers):` This function filters the list to include only prime numbers with the expression `primes = [n for n in numbers if is_prime(n)]` Finally, it returns the maximum prime number found using `return max(primes) if primes else None` If there are no prime numbers in the list, the function will return None.

# Test print(max_prime_in_list([10, 15, 23, 42, 29])) # 29

Bài tập 7: Đếm số nguyên tố

Viết hàm đếm số lượng số nguyên tố trong khoảng từ `a` đến `b`. def count_primes(a, b): return sum(1 for n in range(a, b + 1) if is_prime(n))

Bài tập 8: Số nguyên tố Twin

The function `twin_primes(a, b)` identifies twin prime pairs within a specified range from `a` to `b` It generates a list of prime numbers in that range using a list comprehension The function then returns a list of tuples, each containing a pair of twin primes, which are defined as two consecutive prime numbers that differ by two.

Bài tập 9: Số nguyên tố hoàn hảo

To check if a number is a perfect prime, you can use the function `is_perfect_prime(n)` This function determines if the number is prime by calling `is_prime(n)` and verifies that the number equals the sum of its divisors, calculated using a generator expression that iterates through all integers from 1 to n-1.

# Test print(is_perfect_prime(6)) # True (6 = 1 + 2 + 3) print(is_perfect_prime(28)) # True (28 = 1 + 2 + 4 + 7 + 14)

Bài tập 10: Tìm số nguyên tố gần nhất

To find the nearest prime number to a given integer, you can use the following function: `nearest_prime(n)` If the input number `n` is less than 2, the function returns 2 It then initializes an offset and enters a loop to check for prime numbers The function checks if `n - offset` is prime; if so, it returns that value If not, it checks `n + offset` for primality, returning it if it is prime The offset is incremented until a prime number is found.

# Test print(nearest_prime(10)) # 11 print(nearest_prime(15)) # 13

Bài tập 11: Kiểm tra số hoàn hảo

Viết hàm kiểm tra xem một số có phải là số hoàn hảo hay không. def is_perfect(n): return n == sum(i for i in range(1, n) if n % i == 0)

# Test print(is_perfect(6)) # True print(is_perfect(28)) # True print(is_perfect(12)) # False

Bài tập 12: Liệt kê số hoàn hảo trong khoảng

Viết hàm liệt kê tất cả các số hoàn hảo trong khoảng từ `a` đến `b`. def perfect_numbers_in_range(a, b): return [n for n in range(a, b + 1) if is_perfect(n)]

# Test print(perfect_numbers_in_range(1, 10000))

Bài tập 13: Số hoàn hảo đầu tiên

To find the first 'n' perfect numbers in the sequence of natural numbers, you can use the following function: `def first_n_perfects(n):` This function initializes an empty list called 'perfects' and sets 'num' to 1 It then enters a while loop that continues until the length of 'perfects' is less than 'n' Within the loop, it checks if 'num' is a perfect number using the `is_perfect(num)` function If true, it appends 'num' to the 'perfects' list and increments 'num' by 1 Finally, the function returns the list of perfect numbers.

Bài tập 14: Tổng các số hoàn hảo

Viết hàm tính tổng các số hoàn hảo trong khoảng từ `a` đến `b`. def sum_of_perfects(a, b): return sum(n for n in range(a, b + 1) if is_perfect(n))

# Test print(sum_of_perfects(1, 10000))

Bài tập 15: Kiểm tra số hoàn hảo Mersenne

Viết hàm kiểm tra xem một số có phải là số hoàn hảo Mersenne hay không. def is_mersenne_perfect(p): return is_perfect(2**(p - 1) * (2**p - 1)) if is_perfect(2**p - 1) else False

# Test print(is_mersenne_perfect(3)) # True (6 = 2^(3-1) * (2^3 - 1)) print(is_mersenne_perfect(4)) # False

Bài tập 16: Số hoàn hảo lớn nhất trong dãy

To find the largest perfect number in a list, you can use the function `max_perfect_in_list(numbers)` This function filters the list to include only perfect numbers and then returns the maximum value among them If there are no perfect numbers in the list, it returns None.

# Test print(max_perfect_in_list([10, 15, 28, 42, 496])) # 496

Bài tập 17: Đếm số hoàn hảo

Viết hàm đếm số lượng số hoàn hảo trong khoảng từ `a` đến `b`. def count_perfects(a, b): return sum(1 for n in range(a, b + 1) if is_perfect(n))

Bài tập 18: Số hoàn hảo gần nhất

Viết hàm tìm số hoàn hảo gần nhất với một số cho trước. def nearest_perfect(n): offset = 0 while True: if is_perfect(n - offset):

GV: Nguyễn Thế Phương 14 return n - offset if is_perfect(n + offset): return n + offset offset += 1

# Test print(nearest_perfect(10)) # 6 print(nearest_perfect(30)) # 28

Bài tập 19: Số hoàn hảo trong chuỗi

Viết hàm tìm tất cả các số hoàn hảo trong một chuỗi số. def perfects_in_string(s): numbers = map(int, s.split()) return [n for n in numbers if is_perfect(n)]

# Test print(perfects_in_string("1 6 28 12 496")) # [6, 28, 496]

Bài tập 20: Số hoàn hảo theo định nghĩa

A perfect number is defined as a number that equals the sum of its proper divisors, excluding itself To check if a number is perfect, you can use the following function in Python: `def is_perfect_definition(n): return n == sum(i for i in range(1, n) if n % i == 0)` This function calculates the sum of all divisors of the number less than itself and compares it to the original number.

# Test print(is_perfect_definition(6)) # True print(is_perfect_definition(28)) # True print(is_perfect_definition(12)) # False

Bài tập 21: Kiểm tra số bạn

Viết hàm kiểm tra xem một số có phải là số bạn hay không. def is_friend_number(n): sum_divisors = sum(i for i in range(1, n) if n % i == 0) return sum_divisors

# Test print(is_friend_number(220)) # 284 print(is_friend_number(284)) # 220

Bài tập 22: Liệt kê số bạn trong khoảng

The function `friend_numbers_in_range(a, b)` identifies all pairs of friend numbers within a specified range from `a` to `b` It initializes an empty list called `friends` and iterates through each number `n` in that range For each number, it calculates the sum of its divisors using the `is_friend_number` function If the sum of divisors is within the range and the corresponding friend number condition is met, the pair `(n, sum_divisors)` is added to the list Finally, the function returns the list of friend number pairs.

# Test print(friend_numbers_in_range(1, 300))

Bài tập 23: Tìm cặp số bạn đầu tiên

To find the first pair of friendly numbers in a sequence of natural numbers, you can use the following function: `def first_friend_pair():` This function initializes a variable `n` to 1 and enters an infinite loop Within the loop, it calculates the sum of divisors for `n` using the `is_friend_number(n)` function If `n` is less than the sum of its divisors and the sum of divisors is also a friend number of `n`, the function returns the pair `(n, sum_divisors)` The loop increments `n` by 1 with each iteration until the condition is met.

# Test print(first_friend_pair()) # (220, 284)

Bài tập 24: Tổng các số bạn

Viết hàm tính tổng các số bạn trong khoảng từ `a` đến `b`. def sum_of_friends(a, b): return sum(n for n in range(a, b + 1) if is_friend_number(n) != n)

# Test print(sum_of_friends(1, 300))

Bài tập 25: Đếm cặp số bạn

The function `count_friend_pairs(a, b)` counts the number of amicable pairs within a specified range from `a` to `b` It initializes a counter to zero and iterates through each number `n` in the range For each number, it checks if the sum of its divisors, calculated by the `is_friend_number` function, falls within the range and if the corresponding amicable condition is met If both conditions are satisfied, the counter increments Finally, the function returns the total count of amicable pairs found.

# Test print(count_friend_pairs(1, 300))

Bài tập 26: Cặp số bạn lớn nhất

To find the largest friend number pair within a specified range from `a` to `b`, use the function `max_friend_pair(a, b)` This function initializes `max_pair` as `(None, None)` and iterates through each number `n` in the range For each `n`, it calculates the sum of its divisors using the `is_friend_number(n)` function If the sum of divisors is less than or equal to `b` and the corresponding friend number is equal to `n`, it updates `max_pair` with the current pair `(n, sum_divisors)` Finally, the function returns the largest friend number pair found.

# Test print(max_friend_pair(1, 300))

Bài tập 27: Kiểm tra số bạn Mersenne

Viết hàm kiểm tra xem một số có phải là số bạn Mersenne hay không. def is_mersenne_friend(p): return is_friend_number(2**p - 1)

# Test print(is_mersenne_friend(2)) # True (3) print(is_mersenne_friend(3)) # False

Bài tập 28: Số bạn gần nhất

To find the nearest friend number to a given integer, you can use the following function: `def nearest_friend(n):` The function initializes an offset of 1 and enters an infinite loop It checks if the friend number for `n - offset` equals `n + offset` If true, it returns `n - offset` Conversely, if the friend number for `n + offset` equals `n - offset`, it returns `n + offset` The offset is then incremented by 1 in each iteration This method efficiently identifies the closest friend number to the specified input.

Bài tập 29: Số bạn trong chuỗi

To find all friend pairs in a string of numbers, use the function `friend_pairs_in_string(s)` This function converts the input string into a list of integers, then iterates through each number to determine its friend number using the `is_friend_number(n)` function If the friend number is greater than the original number and exists in the list, the pair is added to the results Finally, the function returns a list of all identified pairs.

# Test print(friend_pairs_in_string("220 284 12 6 496")) # [(220, 284)]

Bài tập 30: Số bạn theo định nghĩa

Tổng các chữ số của một số; ước số; giải các bài toán thông minh, toán khó, toán thực tế và dạng toán ở cấp học (60 bài tập)

To create a program that calculates the sum of the digits of an integer, start by prompting the user to input an integer Use the following code: `number = int(input("Enter an integer: "))` Next, calculate the total by summing each digit of the absolute value of the number with this expression: `total = sum(int(digit) for digit in str(abs(number)))` Finally, display the result using `print("The sum of the digits is:", total)`.

In this exercise, we will write a program to check whether the sum of the digits of a given integer is even or odd First, we prompt the user to enter an integer We then calculate the total by summing the absolute value of each digit in the number Finally, we determine if the total is even or odd and print the corresponding message If the total is even, we display "The sum of the digits is even," and if it is odd, we show "The sum of the digits is odd."

To create a program that calculates the sum of the digits of a positive number, prompt the user to enter a positive integer If the input is negative, display a message requesting a positive number Otherwise, convert the number to a string, iterate through each digit, convert them back to integers, and calculate their total using the sum function Finally, output the result showing the total sum of the digits.

In this exercise, we will create a program that calculates the sum of the digits of an integer and displays each digit individually First, the user is prompted to input an integer The program then converts the absolute value of the number into a string, iterates through each character, and converts it back into an integer to form a list of digits The total sum of these digits is calculated, and the program outputs both the individual digits and their total sum.

Exercise 5: Create a program that takes an integer input and recursively calculates the sum of its digits The function `sum_of_digits(n)` returns 0 if `n` is 0; otherwise, it adds the last digit of `n` (n % 10) to the sum of the digits of the remaining number (n // 10) The user is prompted to enter an integer, and the absolute value of this number is passed to the function Finally, the program outputs the total sum of the digits.

Exercise 6: Write a program to calculate the sum of the digits of a number and display the frequency of each digit The program begins by importing the Counter from the collections module It prompts the user to input an integer, then converts the absolute value of the number into a list of its digits The total sum of the digits is calculated, and the frequency of each digit is counted using the Counter Finally, the program prints the total sum of the digits and the count of occurrences for each digit.

This program prompts the user to input an integer and calculates the sum of its digits while identifying the largest digit It first converts the absolute value of the number into a list of its digits, then computes the total sum and finds the maximum digit Finally, it displays both the total sum of the digits and the largest digit to the user.

In this exercise, you will write a program to calculate the sum of the digits of a given integer and identify the smallest digit First, prompt the user to input an integer Then, convert the absolute value of the number into a list of its digits Use the sum function to compute the total of these digits and the min function to find the smallest digit Finally, display the results, showing both the total sum of the digits and the smallest digit found.

Exercise 9: Write a program to calculate the sum of the digits of a number and print the digits in reverse order First, prompt the user to enter an integer Then, convert the number to its absolute value and extract its digits into a list Calculate the total sum of these digits and reverse the order of the digits Finally, display the total sum of the digits and the reversed digits to the user.

Exercise 10: Write a program that calculates the sum of the digits of a number and checks if that sum is a prime number The function `is_prime(n)` determines if a number is prime by returning `False` for numbers less than or equal to 1 and checking divisibility for numbers greater than 1 The program prompts the user to input an integer, computes the total of its digits, and displays the result It then checks if the sum is prime, printing a message indicating whether the sum of the digits is a prime number or not.

Bài tập 11 yêu cầu viết chương trình nhập vào một số nguyên dương và in ra tất cả các ước số của số đó Để thực hiện, người dùng sẽ nhập số nguyên dương qua hàm `input`, sau đó chương trình sử dụng vòng lặp `for` để kiểm tra từng số từ 1 đến số đã nhập Nếu số đó chia hết cho một số `i`, thì `i` sẽ được in ra như là một ước số của số nguyên dương đó.

Bài tập 12 yêu cầu viết chương trình kiểm tra xem một số có phải là ước số của một số khác hay không Để thực hiện, người dùng nhập vào hai số: số cần kiểm tra và số để kiểm tra ước số Chương trình sử dụng phép chia lấy dư để xác định nếu số thứ hai là ước số của số thứ nhất Nếu điều kiện thỏa mãn, chương trình sẽ thông báo rằng số đó là ước số; ngược lại, nó sẽ thông báo rằng số đó không phải là ước số.

Bài tập 13 yêu cầu viết một chương trình để nhập vào một số nguyên dương và đếm số lượng ước số của số đó Đầu tiên, người dùng sẽ nhập một số nguyên dương thông qua lệnh `input` Sau đó, chương trình sử dụng vòng lặp để kiểm tra từng số từ 1 đến số đã nhập, xem nếu số đó chia hết cho số nguyên dương Nếu có, biến đếm sẽ được tăng lên Cuối cùng, chương trình in ra số lượng ước số của số nguyên dương đã nhập.

To create a program that calculates the sum of the divisors of a positive integer, first prompt the user to input a positive integer Initialize a variable to hold the total sum of the divisors Then, use a loop to iterate through all numbers from 1 to the input number, checking if each number is a divisor If it is, add it to the total sum Finally, display the result, showing the sum of the divisors for the given integer.

Bài tập 15 yêu cầu viết một chương trình để nhập vào một số nguyên dương và in ra các ước số lẻ của số đó Đầu tiên, người dùng sẽ nhập một số nguyên dương qua hàm `input()` Sau đó, chương trình sẽ sử dụng vòng lặp `for` để kiểm tra từng số từ 1 đến số đã nhập Nếu số đó là ước số của số nguyên dương và đồng thời là số lẻ, chương trình sẽ in ra số đó Kết quả cuối cùng sẽ là danh sách các ước số lẻ của số nguyên dương đã nhập.

Bài tập về mảng dữ liệu và số (20 bài tập)

Exercise 1: Input and Print an Array Enter 'n' integer values into an array and display the array To do this, prompt the user to input the number of elements with `n = int(input("Enter the number of elements: "))` Then, create the array using a list comprehension: `mang = [int(input("Enter element " + str(i + 1) + ": ")) for i in range(n)]` Finally, print the entered array with `print("The entered array is:", mang)`.

In this exercise, we will calculate the sum of elements in an array First, the user is prompted to enter the number of elements, which is stored in the variable `n` Next, a list comprehension is used to collect the elements from user input, creating an array called `mang` Finally, the `sum` function computes the total of the array's elements, and the result is printed to the console, displaying the total sum of the elements in the array.

Exercise 3: Finding the Largest Number in an Array To find the largest number in an array, first input the number of elements, n = int(input("Enter the number of elements: ")) Then, create an array by collecting inputs for each element using a list comprehension: mang = [int(input("Enter number " + str(i + 1) + ": ")) for i in range(n)] Finally, determine the maximum value with max_so = max(mang) and display the result using print("The largest number in the array is:", max_so).

Exercise 4: Finding the Minimum Number in an Array To find the smallest number in an array, first, input the number of elements (n) Then, create an array by entering each element one by one Finally, use the min() function to determine and print the smallest number in the array.

Exercise 5: Counting Occurrences of a Number This task involves counting how many times a specific number appears in an array First, the user is prompted to input the number of elements, followed by entering each element into the array Next, the user specifies the number to be counted The program then counts the occurrences of that number within the array and displays the result, indicating how many times the number appears.

In this exercise, we focus on sorting an array in ascending order First, the user is prompted to enter the number of elements, which is stored in the variable `n` Next, the program collects `n` integer inputs from the user to populate the array After the array is created, the `sort()` method is applied to arrange the elements in ascending order Finally, the sorted array is displayed to the user, showcasing the results of the sorting process.

Exercise 7: Sorting an Array in Descending Order To sort an array in descending order, first, input the number of elements (n) and then enter each element Use the following code: `n = int(input("Enter the number of elements: "))` followed by `array = [int(input("Enter number " + str(i + 1) + ": ")) for i in range(n)]` Finally, sort the array in reverse order with `array.sort(reverse=True)` and display the sorted array using `print("The sorted array is:", array)`.

In this exercise, we will calculate the average value of elements in an array First, prompt the user to enter the number of elements, using `n = int(input("Enter the number of elements: "))` Then, create an array by collecting user inputs with `mang = [int(input("Enter number " + str(i + 1) + ": ")) for i in range(n)]` Finally, compute the average by dividing the sum of the array by the number of elements, using `trung_binh = sum(mang) / n`, and display the result with `print("The average value is:", trung_binh)`.

Exercise 9: Find the Maximum and Minimum Elements In this task, you will identify the largest and smallest elements in an array First, input the number of elements, n, using `n = int(input("Enter the number of elements: "))` Then, create the array by collecting user inputs with `mang = [int(input("Enter number " + str(i + 1) + ": ")) for i in range(n)]` To find the maximum and minimum values, use `max_so = max(mang)` and `min_so = min(mang)` Finally, display the results with `print("The largest number is:", max_so)` and `print("The smallest number is:", min_so)`.

Exercise 10: Reverse an Array To reverse an array in Python, first prompt the user to enter the number of elements Then, create the array by collecting user inputs Use the reverse() method to reverse the array and finally, display the reversed array to the user Here's the code: ```pythonn = int(input("Enter the number of elements: ")) array = [int(input("Enter element " + str(i + 1) + ": ")) for i in range(n)] array.reverse() print("The reversed array is:", array)```

Exercise 11: Calculate the Product of Array Elements This task involves computing the product of all elements in an array First, the user is prompted to enter the number of elements, followed by the individual elements themselves The program then initializes a variable to hold the product, iterating through each element in the array to multiply them together Finally, it outputs the total product of the array elements.

Exercise 12: Find Even Elements Identify and print the even elements in an array First, input the number of elements (n) and then enter each element into the array The code filters the array to extract even numbers using a list comprehension Finally, it displays the even elements found in the array.

Exercise 13: Find Odd Elements Identify and print the odd elements in an array First, input the number of elements (n) Then, create an array by entering each element sequentially Finally, extract the odd numbers using a list comprehension and display the results The code snippet demonstrates how to achieve this by checking if each number is not divisible by 2.

Bài tập 14 hướng dẫn cách tìm phần tử có giá trị gần nhất với một giá trị cho trước Đầu tiên, người dùng nhập số lượng phần tử và sau đó nhập từng giá trị vào danh sách Tiếp theo, người dùng cung cấp giá trị cần tìm gần nhất Cuối cùng, chương trình sử dụng hàm `min` kết hợp với `lambda` để xác định phần tử gần nhất với giá trị đã cho và in kết quả ra màn hình.

Bài tập 15: Tạo Mảng Ngẫu Nhiên yêu cầu bạn tạo một mảng ngẫu nhiên với n số nguyên trong khoảng từ 1 đến 100 Để thực hiện, bạn có thể sử dụng thư viện random trong Python Đầu tiên, nhập số lượng phần tử n, sau đó sử dụng danh sách hiểu để tạo mảng với các giá trị ngẫu nhiên Cuối cùng, in ra mảng ngẫu nhiên đã tạo.

Nhập xuất tệp trong Python (20 bài tập)

To read and print the content of a file in Python, use the following code: open the file named `input.txt` in read mode, read its content, and then display it on the screen The code snippet is as follows: ```pythonwith open('input.txt', 'r') as file: noi_dung = file.read() print("Nội dung tệp:", noi_dung) ``` This method ensures proper handling of the file and outputs its contents effectively.

In this exercise, we will count the number of lines in the file `input.txt` By using Python, we can open the file in read mode and utilize a generator expression to sum the lines The code snippet reads: `with open('input.txt', 'r') as file: so_dong = sum(1 for line in file) print("Số dòng trong tệp là:", so_dong)`, which effectively outputs the total line count.

Exercise 3: Count the Number of Words in a File To count the words in the file `input.txt`, open the file in read mode, read its content, and split the content into words The total word count can be obtained by calculating the length of the resulting list Finally, print the total number of words found in the file.

In this exercise, we will write a string to a file named `output.txt` To accomplish this, we use the `with open` statement in Python, which opens the file in write mode The line `file.write("Đây là nội dung ghi vào tệp.")` writes the specified content to the file Finally, a confirmation message is printed, indicating that the content has been successfully written to `output.txt`.

Bài tập 5: Đọc Tệp và Ghi Ra Tệp Khác Đọc nội dung từ `input.txt` và ghi vào

The content from 'input.txt' has been successfully copied to 'output.txt'.

In this exercise, we read integers from the file `input.txt` and calculate their sum Using Python, we open the file, strip any whitespace from each line, and convert the numbers to integers before summing them up The total is then written to `output.txt`, with a message indicating the sum Finally, a confirmation message is printed to notify that the total has been successfully recorded in the output file.

Exercise 7: Save Even Numbers from a File Read numbers from `input.txt`, filter out the even numbers, and write them to `output.txt` The code snippet utilizes a list comprehension to create a list of even numbers by checking each line in the input file It then writes these even numbers to the output file, confirming the action with a message indicating that the even numbers have been successfully recorded in `output.txt`.

Bài tập 8: Lưu Các Phần Tử Lẻ Từ Tệp Đọc các số từ `input.txt`, lọc số lẻ và ghi vào

The provided Python script reads integers from 'input.txt', filters out the odd numbers, and writes them to 'output.txt' Each odd number is written on a new line, and a confirmation message is printed once the process is complete.

Exercise 9: Find the Largest Number in a File Read numbers from `input.txt` and determine the largest number The code snippet opens the file, computes the maximum value from the integers, and writes the result to `output.txt` It then confirms that the largest number has been successfully recorded in the output file.

Exercise 10: Find the Smallest Number in a File Read numbers from `input.txt` and determine the smallest one Use the following code to achieve this: ```pythonwith open('input.txt', 'r') as file: so_smallest = min(int(line.strip()) for line in file)with open('output.txt', 'w') as file: file.write(f"The smallest number is: {so_smallest}")print("The smallest number has been written to output.txt.")```

Bài tập 11: Đảo Ngược Nội Dung Tệp Đọc nội dung từ `input.txt`, đảo ngược và ghi vào

The Python script reads the content of 'input.txt', reverses it, and then writes the reversed content to 'output.txt' A confirmation message indicates that the reversed content has been successfully saved.

Exercise 12: Write Random Numbers to a File Generate and save 10 random numbers to the file `output.txt` using the following Python code: ```pythonimport randomwith open('output.txt', 'w') as file: for _ in range(10): file.write(f"{random.randint(1, 100)}\n")print("10 random numbers have been written to output.txt.")``` This task demonstrates how to create a file and populate it with random integers between 1 and 100.

In this exercise, we read numbers from the file `input.txt` and calculate their average The code snippet opens the file, creates a list of integers from each line, and computes the average by dividing the sum of the list by its length Finally, the average value is written to `output.txt`, and a message is printed to confirm that the average has been successfully recorded.

Exercise 14: Create a File with User Input Prompt the user to enter content and save it to `output.txt` Use the following code: `noi_dung = input("Enter the content to write to the file: ")` Then, open the file in write mode with `open('output.txt', 'w') as file:` and write the input using `file.write(noi_dung)` Finally, confirm the action with `print("Content has been written to output.txt.")`.

Exercise 15: Filter Words Longer Than 5 Characters Read the contents of `input.txt`, filter out words longer than 5 characters, and write them to `output.txt` The code opens `input.txt`, creates a list of words longer than 5 characters, and then writes each word to `output.txt` A confirmation message is printed stating that the filtered words have been successfully written to the output file.

Bài tập 16: Đếm Số Lần Xuất Hiện Của Một Từ Đếm số lần xuất hiện của một từ trong

BÀI TẬP TỔNG HỢP (10 bài tập)

Bài tập 1: Nhập một câu từ tệp data_in.txt, tách từng từ trong câu ra mỗi từ nằm trên một dòng ghi vào tệp data_out.txt

# Đọc nội dung từ tệp data_in.txt with open('data_in.txt', 'r') as infile: cau = infile.read().strip() # Đọc và loại bỏ khoảng trắng thừa

# Tách từng từ trong câu tu_list = cau.split()

To write each word from a list into a file named data_out.txt, open the file in write mode and iterate through the word list, writing each word on a new line Finally, print a confirmation message indicating that the words have been successfully recorded in the file.

Hướng dẫn: 1 Tạo một tệp có tên `data_in.txt` và nhập câu cần tách từ vào đó.

3 Kiểm tra tệp `data_out.txt` để xem kết quả.

Nhập một số nguyên N từ tệp data_in.txt và xuất kết quả ra tệp data_out.txt Dòng đầu tiên sẽ liệt kê các ước của N, dòng thứ hai chứa các ước chẵn của N, dòng thứ ba là các ước lẻ của N, và dòng cuối cùng là tổng các ước của N.

# Đọc số nguyên N từ tệp data_in.txt with open('data_in.txt', 'r') as infile:

N = int(infile.read().strip()) # Đọc và chuyển đổi thành số nguyên

# Khởi tạo danh sách để lưu các ước uoc_list = [] uoc_chan = [] uoc_le = []

To find the divisors of a number N, iterate through all integers from 1 to N For each integer i, check if it divides N evenly If it does, add it to the list of divisors Additionally, categorize the divisors into even and odd lists by checking if each divisor is even or odd, appending it to the respective list This method efficiently identifies and organizes the divisors of N.

# Tính tổng các ước tong_uoc = sum(uoc_list)

The results are recorded in the file 'data_out.txt' The file contains the divisors of N, including all divisors, even divisors, and odd divisors, each listed separately Additionally, it includes the total sum of the divisors of N A confirmation message indicates that the results have been successfully written to the file.

Hướng dẫn: 1 Tạo một tệp có tên `data_in.txt` và nhập số nguyên \( N \) vào đó.

3 Kiểm tra tệp `data_out.txt` để xem kết quả.

Bài tập 3 yêu cầu nhập một chuỗi từ tệp data_in.txt và xuất kết quả ra tệp data_out.txt Chuỗi này cần được chuẩn hóa bằng cách cắt bỏ các khoảng trắng thừa, in hoa chữ cái đầu câu và thêm dấu chấm câu ở cuối câu.

# Đọc chuỗi từ tệp data_in.txt with open('data_in.txt', 'r', encoding='utf-8') as file_in: text = file_in.read()

# 1 Xóa các khoảng trắng thừa (dùng strip và replace) text = ' '.join(text.split()) # Xóa các khoảng trắng thừa

# 2 Viết hoa chữ cái đầu câu và thêm dấu chấm ở cuối câu sentences = text.split('.') for i in range(len(sentences)):

# Loại bỏ khoảng trắng thừa ở đầu câu sentence = sentences[i].strip() if sentence:

# Viết hoa chữ cái đầu câu sentences[i] = sentence[0].upper() + sentence[1:]

# Nối lại các câu và thêm dấu chấm ở cuối câu text = ' '.join(sentences).strip() if text and not text.endswith('.'): text += '.'

To save the results, open the file 'data_out.txt' in write mode with UTF-8 encoding Write the normalized string to the file, and confirm the action by printing a message indicating that the string has been successfully saved to 'data_out.txt'.

Bài tập 4 yêu cầu nhập một chuỗi từ tệp data_in.txt và xuất kết quả ra tệp data_out.txt Trong đó, dòng đầu tiên sẽ chứa các số, dòng thứ hai chứa các chữ cái và dòng thứ ba sẽ là các ký tự đặc biệt Sử dụng thư viện string để thực hiện nhiệm vụ này.

# Đọc chuỗi từ tệp data_in.txt with open('data_in.txt', 'r') as infile: chuoi = infile.read().strip() # Đọc và loại bỏ khoảng trắng thừa

# Khởi tạo danh sách để lưu các loại ký tự so_list = [] chu_list = [] ki_tu_dac_biet_list = []

The classification of characters in a string involves iterating through each character If the character is a digit, it is added to a list of numbers If it is an alphabetic character, it is appended to a list of letters Additionally, if the character is a special character, it is included in a separate list for special characters This method effectively organizes characters into distinct categories for further processing.

The results are recorded in the file 'data_out.txt' The file contains separated numbers, letters, and special characters extracted from a string It includes a section for numbers, followed by letters, and concludes with special characters, ensuring a clear and organized output A confirmation message indicates that the results have been successfully written to the file.

Bài tập 5 yêu cầu tính diện tích phần còn lại của hình vuông sau khi một hình tròn bán kính 4cm được nội tiếp Đầu tiên, diện tích của hình vuông có thể được tính bằng công thức A = a^2, trong đó a là cạnh của hình vuông Với bán kính hình tròn là 4cm, cạnh của hình vuông sẽ là 8cm Diện tích hình vuông là 64cm² Diện tích hình tròn được tính bằng công thức A = πr², với r = 4cm, cho kết quả khoảng 50,27cm² Cuối cùng, diện tích phần còn lại của hình vuông sau khi trừ đi diện tích hình tròn là 64cm² - 50,27cm² = 13,73cm².

# Kích thước hình vuông và hình tròn ban_kinh_tron = 4 # cm canh_vuong = 8 # cm

# Tính diện tích hình vuông dien_tich_vuong = canh_vuong ** 2

# Tính diện tích hình tròn dien_tich_tron = math.pi * (ban_kinh_tron ** 2)

# Tính diện tích phần còn lại dien_tich_con_lai = dien_tich_vuong - dien_tich_tron

Kết quả tính toán diện tích được hiển thị như sau: diện tích hình vuông là {dien_tich_vuong:.2f} cm², diện tích hình tròn là {dien_tich_tron:.2f} cm², và diện tích phần hình còn lại là {dien_tich_con_lai:.2f} cm².

Bài tập 6 yêu cầu tính diện tích phần còn lại của hình tròn sau khi một hình vuông có cạnh 6cm được nội tiếp Để giải bài toán, trước tiên cần tính diện tích hình tròn và diện tích hình vuông Diện tích hình vuông là 36cm², trong khi diện tích hình tròn được tính bằng công thức πr², với bán kính r là 3√2 cm (do hình vuông nội tiếp) Cuối cùng, diện tích phần hình tròn còn lại sẽ là diện tích hình tròn trừ đi diện tích hình vuông.

GV: Nguyễn Thế Phương 41 import math

# Tính diện tích hình vuông

# Tính bán kính của hình tròn (do đường chéo của hình vuông là đường kính của hình tròn) r = (a * math.sqrt(2)) / 2

# Tính diện tích hình tròn

# Tính diện tích phần còn lại

# In kết quả print(f"Diện tích phần còn lại của hình tròn là: {S_con_lai:.2f} cm²")

Để tính diện tích phần còn lại của hình tròn sau khi hình tam giác đều có cạnh 9cm chiếm chỗ, trước tiên ta cần tính diện tích của hình tròn Diện tích hình tròn được tính bằng công thức S = πr², trong đó r là bán kính Hình tam giác đều nội tiếp trong hình tròn có bán kính bằng 9cm Diện tích của tam giác đều được tính bằng công thức S = (√3/4) * a², với a là độ dài cạnh Sau khi tính diện tích của cả hai hình, ta có thể tìm diện tích phần còn lại của hình tròn bằng cách lấy diện tích hình tròn trừ đi diện tích hình tam giác.

# Cạnh hình tam giác đều a = 9

# Tính diện tích hình tam giác đều

# Tính bán kính của hình tròn (bán kính của hình tròn nội tiếp tam giác đều) r = a / math.sqrt(3)

# Tính diện tích hình tròn

# Tính diện tích phần còn lại của hình tròn

S_con_lai = S_tron - S_tam_giac

# In kết quả print(f"Diện tích phần còn lại của hình tròn là: {S_con_lai:.2f} cm²")

Trong bài tập này, có 4 hình tròn được đặt nội tiếp trong một hình vuông có cạnh dài 16cm Để tính diện tích phần còn lại của hình vuông sau khi bị 4 hình tròn chiếm chỗ, trước tiên cần tính diện tích của hình vuông, sau đó tính tổng diện tích của 4 hình tròn Cuối cùng, diện tích phần còn lại sẽ là diện tích hình vuông trừ đi tổng diện tích của 4 hình tròn.

# Tính diện tích hình vuông

# Bán kính của mỗi hình tròn r = a / 4

# Tính diện tích một hình tròn

# Tính tổng diện tích của 4 hình tròn

# Tính diện tích phần còn lại của hình vuông

# In kết quả print(f"Diện tích phần còn lại của hình vuông là: {S_con_lai:.2f} cm²")

Chương trình này sẽ nhập 3 số nguyên a, b, c từ tệp data_in.txt và xuất kết quả vào tệp data_out.txt Đầu tiên, nó sẽ kiểm tra xem a, b, c có phải là 3 cạnh của một tam giác hay không bằng cách sử dụng hàm is_triangle Nếu đúng, chương trình sẽ tính diện tích tam giác bằng hàm triangle_area; nếu không, nó sẽ thông báo rằng a, b, c không phải là 3 cạnh của một tam giác và không cần tính diện tích.

# Sử dụng công thức Heron để tính diện tích s = (a + b + c) / 2 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 return area

# Đọc dữ liệu từ tệp with open('data_in.txt', 'r') as file: a, b, c = map(int, file.readline().strip().split())

Ngày đăng: 25/02/2025, 09:34

w