Hỏi đáp
Chia sẻ kiến thức, cùng nhau phát triển
Mọi người giúp em viết code Python bài này với ạ:
khoảng 1 năm trước
414 lượt xem
1 bình luận
Tạo file dayso.txt gồm nhiều dòng, mỗi dòng chứa các số nguyên dương cách nhau ký tự khoảng cách (space).
a. Tạo danh sách A gồm tất cả các số có trong file dayso.txt
b. Danh sách A có bao nhiêu số lẻ có 3 chữ số?
import random
def generate_file(numline = 10, maxnumperline = 10):
with open("dayso.txt", "w") as f:
for i in range(numline):
for j in range(maxnumperline):
num = random.randint(1,99999)
f.write(str(num) + " ")
f.write("\n")
def create_list_from_file():
A = []
with open("dayso.txt", "r") as f:
lines = f.readlines()
for l in lines:
nums = l.split(" ")
for n in nums[:len(nums)-1]:
A.append(n)
return A
def count_odd_3digit(A):
count = 0
for num in A:
if len(num) == 3 and int(num) % 2 == 1:
count = count + 1
return count
generate_file(100, 100)
A = create_list_from_file()
print(count_odd_3digit(A))