0% found this document useful (0 votes)
5 views

Advanced Programming Report

Board game

Uploaded by

Army Lisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Advanced Programming Report

Board game

Uploaded by

Army Lisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

VIETNAM NATIONAL UNIVERSITY, HO CHI MINH CITY

UNIVERSITY OF TECHNOLOGY

ADVANCED PROGRAMMING

Assignment - Semester 232 - CC02

Functional Programming in Python

Advisor: Dr. Trương Tuấn Anh.


Students: Nguyễn Quốc Anh - 2252035.

HO CHI MINH CITY, APRIL 2024


University of Technology, Ho Chi Minh City
Faculty of Computer Science

Contents
1 The programming language Python 2

2 Functional Programming in Python 3


2.1 First-Class and Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.1 map(function, iterable) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.2 filter(function, iterable) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.3 reduce(function, iterable) . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 Lambda Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 How to write a functional program in Python 5

4 Hangman game in python 6

Assignment for Advanced Programming - Academic year 2023 - 2024 Page 1/7
University of Technology, Ho Chi Minh City
Faculty of Computer Science

1 The programming language Python


Python is a high-level, interpreted programming language known for its simplicity and read-
ability, making it an excellent choice for beginners and experienced developers alike. Created by
Guido van Rossum and first released in 1991, Python supports multiple programming paradigms,
including procedural, object-oriented, and functional programming. Its extensive standard li-
brary, along with a vibrant ecosystem of third-party packages, enables developers to build appli-
cations ranging from web development and data analysis to artificial intelligence and scientific
computing. Key features of Python include dynamic typing, automatic memory management,
and an interactive interpreter. Python’s syntax emphasizes code readability and simplicity, re-
ducing the cost of program maintenance and enhancing developer productivity. Its widespread
adoption in industry, academia, and education underscores its versatility and effectiveness as a
programming language. Notable for its portability, Python code can run on various platforms
such as Windows, macOS, and Linux without modification.

Python’s versatility and powerful libraries make it a popular choice for a wide range of
applications:

1. Web Development: Frameworks like Django and Flask provide robust tools for building
dynamic websites and APIs.
2. Data Science and Machine Learning: Libraries such as Pandas, NumPy, and TensorFlow
enable data analysis, statistical modeling, and predictive analytics.

3. Automation: Python’s simplicity allows for the quick development of scripts to automate
repetitive tasks, making it invaluable for system administrators and developers.
4. Scientific Computing: Libraries like SciPy and Matplotlib support complex mathematical
computations and data visualization.

5. Education: Python is widely used as a primary language for teaching programming and
computer science due to its straightforward syntax and readability.
6. Other Domains:
• Game Development: Python is used for developing games with frameworks like Pygame.
• Network Programming: Python provides tools for creating and managing network
applications.
• Embedded Systems: Python can be used in embedded systems to control hardware.
• Python’s broad utility across these various domains underscores its effectiveness and
widespread adoption in industry, academia, and beyond.

Assignment for Advanced Programming - Academic year 2023 - 2024 Page 2/7
University of Technology, Ho Chi Minh City
Faculty of Computer Science

2 Functional Programming in Python


Functional programming is a programming paradigm that treats computation as the evaluation
of mathematical functions and avoids changing-state and mutable data. In Python, while it’s not
strictly a functional programming language like Haskell or Lisp, it supports functional program-
ming concepts and features to a significant extent.

2.1 First-Class and Higher-Order Functions


Functions are first-class citizens, meaning they can be passed around as arguments, returned
from other functions, and assigned to variables. This allows for higher-order functions, functions
that can take other functions as arguments or return them as results.

2.1.1 map(function, iterable)


Applies a function to all the items in an input iterable and returns an iterator of the results.
Example of a function to square root all elements in a list.
1 >>> numbers = [1 ,2 ,3 ,4 ,5]
2 >>> def square ( x ) :
3 ... return x * x
4 >>> print ( list ( map ( square , numbers ) ) )
5 [1 , 4 , 9 , 16 , 25]
6

2.1.2 filter(function, iterable)


Filters out items from an iterable based on whether the function returns True for the item.
Example of listing even numbers from a list
Normal way:
1 >>> numbers = [1 ,2 ,3 ,4 ,5]
2 >>> def is_even ( x ) :
3 ... if x % 2 == 0 :
4 ... return True
5 ... return False
6 >>> print ( list ( filter ( is_even , numbers ) ) )
7 [2 , 4]
8

Brief way:
1 >>> numbers = [1 ,2 ,3 ,4 ,5]
2 >>> [ x for x in numbers if x % 2 == 0]
3 [2 , 4]
4

Assignment for Advanced Programming - Academic year 2023 - 2024 Page 3/7
University of Technology, Ho Chi Minh City
Faculty of Computer Science

2.1.3 reduce(function, iterable)


: Applies a rolling computation to sequential pairs of values in an iterable.
Example of find the maximum number in a list.
1 >>> from functools import reduce
2 >>> numbers = [1 ,5 ,2 ,1 ,3 ,7 ,2 ,10]
3 >>> def max (x , y ) :
4 ... return x if x > y else y
5 >>> print ( reduce ( max , numbers ) )
6 10
7

2.2 Lambda Functions


Python supports anonymous functions using the lambda keyword. Lambda functions are small,
anonymous functions that can have any number of parameters but can only have one expression.
They are commonly used with higher-order functions like map(), filter(), and reduce().
For example, let implement 3 above examples:
• square root all elements in list
1 >>> numbers = [1 ,5 ,2 ,1 ,3 ,7 ,2 ,10]
2 >>> print ( list ( map ( lambda x : x *x , numbers ) ) )
3 [1 , 25 , 4 , 1 , 9 , 49 , 4 , 100]

• listing even numbers


1 >>> numbers = [1 ,5 ,2 ,1 ,3 ,7 ,2 ,10]
2 >>> print ( list ( filter ( lambda x : x % 2 == 0 , numbers ) ) )
3 [2 , 2 , 10]

• find maximum number in list


1 >>> from functools import reduce
2 >>> numbers = [1 ,5 ,2 ,1 ,3 ,7 ,2 ,10]
3 >>> print ( reduce ( lambda x , y : x if x > y else y , numbers ) )
4 10

2.3 Recursion
Functional programming encourages the use of recursion for iteration rather than traditional
loops. While Python supports recursion, it may not be as optimized for tail recursion as some
other functional languages.
Example: find factorial of a number
1 >>> def factorial ( n ) :
2 ... return 1 if n == 0 else n * factorial ( n - 1)
3 >>> print ( factorial (5) )
4 120

Assignment for Advanced Programming - Academic year 2023 - 2024 Page 4/7
University of Technology, Ho Chi Minh City
Faculty of Computer Science

3 How to write a functional program in Python


Creating a functional program in Python involves writing code that emphasizes the use of func-
tions as the primary building blocks.
1. Identify the problem: Understand the problem you’re trying to solve and break it down
into smaller, manageable tasks.

2. Define functions: Identify the different tasks or operations required to solve the problem
and define functions for each of them. Functions should ideally have a single responsibility
and be reusable.
3. Use pure functions: Aim to write pure functions whenever possible. Pure functions have
no side effects and always return the same output for the same input, making them easier
to reason about and test.

4. Avoid mutable state: Minimize the use of mutable state and global variables, as they
can introduce complexity and make your code harder to understand and debug.
5. Leverage higher-order functions: Python supports higher-order functions, which are
functions that can accept other functions as arguments or return functions as results.
Leverage these to create more flexible and reusable code.
6. Use functional programming tools: Python provides several tools and libraries for
functional programming, such as map(), filter(), and reduce(). These tools allow you to
perform common functional programming operations like mapping, filtering, and reducing
sequences.

7. Utilize list comprehensions and generator expressions: List comprehensions and


generator expressions are concise ways to create lists and iterators, respectively, based on
existing sequences. They can often replace loops and make your code more expressive.
8. Handle errors with functions: Instead of using try-except blocks inline, consider en-
capsulating error handling logic within functions. This makes your code more modular and
easier to test.

Assignment for Advanced Programming - Academic year 2023 - 2024 Page 5/7
University of Technology, Ho Chi Minh City
Faculty of Computer Science

4 Hangman game in python


1 import random
2
3 def choose_word () :
4 words = [ " functional " , " programming " , " is " , " significantly " , " fun " , " with " , "
various " , " features " , " to " , " acknowledge " ]
5 return random . choice ( words )
6
7 def display_word ( word , gu e ss e d_ le t te rs ) :
8 return ' '. join ([ letter if letter in gu es s ed _ le tt e rs else '_ ' for letter in
word ])
9
10 def i s _ g u e s s _ c o r r e c t ( word , guess ) :
11 return guess in word
12
13 def is_game_over ( word , gu e ss e d_ le t te rs ) :
14 return all ( letter in g ue ss e d_ l et te r s for letter in word )
15
16 def hangman ( word , guessed_letters , attempts ) :
17 print ( display_word ( word , g u es se d _l et t er s ) )
18
19 if attempts == 0:
20 print ( " Sorry , you ran out of attempts ! The word was : " , word )
21 return
22
23 if is_game_over ( word , g u es se d _l e tt er s ) :
24 print ( " Co n gr at u la ti o ns ! You guessed the word : " , word )
25 return
26
27 guess = input ( " Guess a letter : " ) . lower ()
28
29 if guess in g ue ss e d_ l et te r s :
30 print ( " You ' ve already guessed that letter ! " )
31 else :
32 g ue ss e d_ le t te r s . append ( guess )
33
34 if i s _ g u e s s _ c o r r e c t ( word , guess ) :
35 print ( " Correct ! " )
36 else :
37 attempts -= 1
38 print ( " Incorrect ! You have " , attempts , " attempts left . " )
39
40 hangman ( word , guessed_letters , attempts )
41
42 def start_game () :
43 print ( " Welcome to Hangman ! " )
44 word = choose_word ()
45 attempts = 6
46 g ue ss e d_ le t te r s = []
47 hangman ( word , guessed_letters , attempts )
48
49 start_game ()

Assignment for Advanced Programming - Academic year 2023 - 2024 Page 6/7
University of Technology, Ho Chi Minh City
Faculty of Computer Science

The demo for running this game

1 Welcome to Hangman !
2 ___________
3 Guess a letter : a
4 Correct !
5 _____a_____
6 Guess a letter : i
7 Correct !
8 _____a__i__
9 Guess a letter : e
10 Incorrect ! You have 5 attempts left .
11 _____a__i__
12 Guess a letter : o
13 Correct !
14 __o__a__i__
15 Guess a letter : p
16 Correct !
17 p_o__a__i__
18 Guess a letter : r
19 Correct !
20 pro_ra__i__
21 Guess a letter : g
22 Correct !
23 progra__i_g
24 Guess a letter : m
25 Correct !
26 programmi_g
27 Guess a letter : m
28 You ' ve already guessed that letter !
29 programmi_g
30 Guess a letter : n
31 Correct !
32 programming
33 C on gr a tu la t io n s ! You guessed the word : programming

Assignment for Advanced Programming - Academic year 2023 - 2024 Page 7/7

You might also like