Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

MARCH 4, 2024

exercises and project 2


python programming

Giảng viên phụ trách : PGS TSkh nguyễn xuân huy


Học viên: nhóm 2
Lp E22CQCN02-B
1. Phạm Như Linh – B22DCDT178
2. Vũ Ngọc Linh – B22DCDT179
3. Trịnh Diệu Linh – B22DCVT310
Bảng phân công nhiệm vụ thành viên

STT Họ và tên Mã sinh viên Nhiệm vụ


1 Phạm Như Linh B22DCDT178 Tìm hiểu bài tập 2
2 Vũ Ngọc Linh B22DCDT179 Tìm hiểu bài tập 1 và 3
3 Trịnh Diệu Linh B22DCVT310 Tìm hiểu bài tập 4 và làm
word
Contents
Introduction.................................................................................................................................................3
1. Ships........................................................................................................................................................4
Definition:...............................................................................................................................................4
Design:....................................................................................................................................................4
Algorithm count_ships(ships):................................................................................................................4
Program:.................................................................................................................................................5
2. Twin Primes.............................................................................................................................................6
Definition:...............................................................................................................................................6
Design:....................................................................................................................................................6
Algorithm :..............................................................................................................................................7
Program:.................................................................................................................................................7
3. Fraction...................................................................................................................................................8
Definition:...............................................................................................................................................8
Design:....................................................................................................................................................8
Algorithm:...............................................................................................................................................8
Program:.................................................................................................................................................8
4. Last zeros.................................................................................................................................................9
Definition:...............................................................................................................................................9
Design:....................................................................................................................................................9
Algorithm:.............................................................................................................................................10
Program:...............................................................................................................................................10
References (Tài liệu tham khảo)..............................................................................................................11
Conclusion.................................................................................................................................................12
Introduction
Hiện nay, ngành công nghệ thông tin là một trong những ngành học được chú trọng trong hệ
thống đào tạo của trường đại học công nghệ thông tin và các trường đại học khác có đào tạo
ngành học này. Nó được xem là ngành đào tạo mũi nhọn hướng đến sự phát triển công nghệ và
khoa học kỹ thuật trong thời đại số hóa ngày nay.
Công nghệ thông tin là một ngành học được đào tạo để sử dụng máy tính và các phần mềm
máy tính để phân phối và xử lý các dữ liệu thông tin và dùng để trao đổi, lưu trữ cũng như
chuyển đổi các dữ liệu thông tin dưới hình dạng khác nhau. Ngành công nghệ thông tin là ngành
có tốc độ phát triển nhanh, mạnh và có đóng góp to lớn vào sự tăng trưởng GDP của nước ta
trong nhiều năm qua. Công nghệ thông tin giúp mọi việc dễ dàng hơn, nâng cao hiệu quả sản
xuất và tiết kiệm được thời gian và công sức.
Đặc biệt lập trình Python là một môn học quan trọng đối với sinh viên công nghệ thông tin. Là
môn học giúp chúng em tiếp cận sâu hơn với ngôn ngữ lập trình Python. Và bài tập lớn sau đây
là kết quả thể hiện những kiến thức chúng em đã có được sau những buổi học vừa qua.
Trong quá trình làm bài tập, chúng em đã có thể áp dụng kiến thức để xây dựng các hàm và
nắm chắc hơn cách áp dụng list vào trong bài tập.
1. Ships
The text file SHIPS.INP shows the sea area with some ships. Each ship is represented by a
rectangle filled by 1. The water is represented by 0. The ships are separated. How many ships
in the area?
SHIPS.INP
11110011
1
000000111
11000000
0
110011001
5 ships

Definition:
A ship is the largest rectangle area consisting of ‘1’ cells. From a ‘1’ cell, we can go up, down,
left, right to reach another ‘1’ cell. In this exercise, we apply these rules to count the number of
ships in a given matrix.

Design:
1.Read the SHIPS.INP file.
‘1’ denotes the ship and ‘0’ denotes the sea
2.Define the ship:
If reaching a ‘1’ cell, we can move up, down, left, right to find the largest rectangle area
that can be made
3.Counting the ships
For converting the given matrix in SHIPS.INP file to a matrix in the program, I follow these
steps:
+ Iterate each line of the text file meanwhile increase the number of lines (start at 0)
+ Using function strip() to eliminate the “\n” at the end of each line, iterating each
elements in the line and typecasting them to integer, store in a list
+ Add this list to the list A to get a matrix
str.strip([chars])
 str: the string that is processed
 char: is an optional parameter that specifies the characters you want to remove
from the string. If not provided, whitespace characters are moved
In this exercise, strip() is used to remove the “\n” at the end of each line

Algorithm count_ships(ships):
num_ships = 0
dx=[-1,1,0,0] # the change in row if go up, down, left, right
dy=[0,0,-1,1] # the change in column if go up, down, left, right
function Built(x, y):
A[x][y]=0
for k in range(4): # there are 4 directions that we can go from a ‘1’ cell:
x1=x+dx[k] # move the row
y1=y+dy[k] # move the column
if A[x1][y1]==1:
Built(x1 , y1)

rows = number of rows in ships


columns = number of columns in ships

for i from 0 to rows - 1:


for j from 0 to columns - 1:
if A[i][j] == 1:
Built(i, j)
num_ships = num_ships + 1

return num_ships

Program:
1. dx=[-1,1,0,0] # way to move the row

2. dy=[0,0,-1,1] # way to move the column

3. def Built(i,j,n,m):

4. a[i][j]=0 # change to ‘0’ to not iterate it again

5. for k in range (4):

6. i1 = i+dx[k]

7. j1 = j+dy[k] # move to another cell

8. if (i1>=0 and i1<n and j1>=0 and j1<m and a[i1][j1]==1): #check if the cell is in

matrix A and has ‘1’ value

9. Built(i1,j1,n,m) # backtracking

10. ships= open('input.inp.txt',"r") # read the text file

11. a=[]
12. n=0 # counting the rows

13. for line in ships:

14. n+=1 # increase the number of rows

15. row=[int(i) for i in line.strip()] # eliminate ‘\n’ in line and store each elements in line in

a list

16. a.append(row) #adding the new list row

17. num_ships=0

18. m=len(a[0]) # number of columns

19. for i in range(n):

20. for j in range(m):

21. if a[i][j]==1:

22. num_ships +=1 #increase number of ships

23. Built(i,j,n,m) # to find the largest ships you can get

24. print(num_ships)

2. Twin Primes
Each pair of primes (p-2, p) is called twin primes.
For example, there are five twin primes below 20:
(2,3), (3,5), (5,7), (11,13), (17,19)
List all pairs of primes below 10000.
Definition:
A twin prime is a prime number that is either 2 less or 2 more than another prime number. In
other words, a twin prime is a prime that has a prime gap of two.
Design:
1. Write the function to check prime
2. Use the property of twin prime to write generate function: (p-2,p)
Algorithm :
1.Prime function
from math import *
def snt(n):
if n<2:
return 0
for i in range ( 2, isqrt(n)+1):
if n%i==0:
return 0
return 1
3. Use a list to store twin primes
4. Browse a for loop begin by “start” and finish by “end-1”
5. Use the property of function twin primes to check and add satisfied pairs to list and
print list.
Program:

1. from math import *


2. # The function to check prime function
3. def is_prime(n):
4. if n < 2:
5. return 0
6. for i in range(2, isqrt(n)+1):
7. if n % i == 0:
8. return 0
9. return 1
10. # The function returns twin primes
11. def generate(start, end):
12. twin_primes = []
13. if start == 2:
14. print ("(" + "2 3" + ")")
15. for n in range(start, end - 1):
16. if is_prime(n) and is_prime(n + 2):
17. twin_primes.append((n, n + 2))
18. return twin_primes
19. # Driver code
20. If __name__== '__main__':
21. start=int(input())
22. end=int(input())
23. print(generate(start,end))
3. Fraction
Get the sum of fractions in the text file FRAC,INP

FRAC.IN OUTPUT
P
1/2 2
2/3
3/4
1 / 12

Definition:
The given text file FRAC.INP consists of fractions. In this exercise we have to calculate the sum
of all these fractions
Design:
1. Read the FRAC.INP file
2. Remove the blank space in each line to collect the fraction
3. Calculate sum of all the collected fractions

To remove the blank space to get the right form of fraction, I use function replace()
str.replace(“ old ” , “ new ”, count)
 str: the string that is processed
 old: the string that is replaced
 new: the new string that replaces the removed old string
 count: is an optional parameter that specifies the maximum number of
replacements. If not provided, all the “old” strings will be replaced

Algorithm:
A=[]
for line in FRAC.INP:
A.append(line.replace(“ ”, “”))
print(sum(Fraction(i) for i in A))

Program:
1. from math import* # to use function sum()

2. from fractions import* # to use class Fraction()

3. Frac = open("FRAC.INP.txt", "r") # read the file


4. A = [] # list to stores fractions

5. for i in Frac:

6. A.append(i.replace(“ ” , “”)) # remove the blank space and add the new string to A

7. print(sum(Fraction(i) for i in A)) # change all the elements in A to fractions and calculate

the sum

4. Last zeros
10! = 1*2*3*4*5*6*7*8*9*10 = 3628800. So 10! is ending by two zeros. How many zero ending
of 100000!
Definition:
In mathematics, trailing zeros are a sequence of 0 in the decimal representation (or more
generally, in any positional representation) of a number, after which no other digits follow. In
this exercise, we count how many zero ending of 100000!
This product is commonly known as the factorial of 100000, written 100000!
The number of zeros is determined by how many times 10=2×5 occurs in the prime
factorisation of 1000!.
There are plenty of factors of 2 in it, so the number of zeros is limited by the number of factors
of 5 in it.
These numbers have at least one factor 5:
5,10,15,20,25,...,100000 which is 100000 // 5 = 20000 numbers.
These numbers have at least two factors 5:
25,50,75,100,...,100000 which is 100000 // 25 = 4000 numbers.
These numbers have at least three factors 5:
125,250,375,500,...,100000 which is 100000 // 125 = 800 numbers
These numbers have at least four factors 5:
625,1250,1875,2500,...,100000 which is 100000 // 625 = 160 numbers
These numbers have at least five factors 5:
3125,6250,9375,12500,...,100000 which is 100000 // 3125 = 32 numbers
These numbers have at least six factors 5:
15625,31250,46875,…,100000 which is 100000 // 15625 = 6 numbers
This number has seven factors 5:
78125 which is 1 number.
So the total number of factors 5 in 100000! is:
20000+4000+800+160+32+6+1=24999
Hence there are 24999 zeros at the end of 100000!
Design:
1.Initialize a variable count = 0 to keep track of trailing zeros.
2.Iterate a loop over all the powers of 5 until the power exceeds n:
3.Divide n by the current power of 5 and add the quotient to count.
4.Return count as the final answer.
Algorithm:
def findTrailingZeros(n):
# Negative Number Edge Case
if(n < 0):
return -1

# Initialize result
count = 0

# Keep dividing n by 5 & update Count


while(n >= 5):
n //= 5
count += n
return count
Program:

1. # Function to return trailing 0s in factorial of n


2. def findTrailingZeros(n:
3. # Negative Number Edge Case
4. if(n < 0):
5. return -1
6.
7. # Initialize result
8. count = 0
9.
10. # Keep dividing n by
11. # 5 & update Count
12. while(n >= 5):
13. n //= 5
14. count += n
15. return count
16.
17. # Driver program
18. n = 10000
19. print("Count of trailing 0s " +
20. "in 10000! is", findTrailingZeros(n))
References (Tài liệu tham khảo)
https://www.geeksforgeeks.org/twin-prime-numbers/ (4/3/2024)

https://en.wikipedia.org/wiki/Twin_prime (3/3/2024)

https://en.wikipedia.org/wiki/Trailing_zero (5/3/2024)

https://www.geeksforgeeks.org/count-trailing-zeroes-factorial-number/ (5/3/2024)

https://www.purplemath.com/modules/factzero.htm (2/3/2024)

Chat GPT
Conclusion
Để hoàn thành được bài tiểu luận này, em xin chân thành cảm ơn thầy Nguyễn Xuân Huy,người đã tận
tình giúp đỡ và hướng dẫn bọn em thực hiện bài tập lớn này bằng tất cả lòng nhiệt tình và sự quan tâm
sâu sắc. Cảm ơn đến sự hợp tác của các thành viên trong nhóm đã giúp cho bài tập lớn được hoàn thành
một cách tốt nhất có thể.

Trong quá trình thực hiện bài tập này, do hiểu biết còn nhiều hạn chế nên bài làm khó tránh khỏi những
thiếu sót. Chúng em rất mong nhận được những lời góp ý của thầy để ngày càng hoàn thiện hơn những
kiến thức về ngôn ngữ lập trình Python.

Em xin chân thành cảm ơn!

You might also like