首页 > > 详细

CS2312编程语言辅导、讲解Programming程序设计、Python程序辅导调试Web开发|讲解R语言编程

Lab 13 CS2312 Problem Solving and Programming (2020/2021 Semester A)
Introduction to Functional Programming using Python
This lab is based on the materials from Dr LI Shuaicheng (2018-19B)
Introduction
We will use a handy Python console (PythonAnywhere on www.python.org) to
learn Functional Programming in Python.
In each part of this lab, please
- Listen to the explanation,
- Study the given guideline,
- Study the given code in the code boxes in this word document and/or add your code in the code
boxes (or in a text editor, or Jupyter notebook etc. of your choice) *,
- Then copy and paste the code to run it in the Python console.
* You will need to submit the finished word document (or the text file or notebook file) onto Canvas=>Assignment.
* Ref: Avoid smart quotes: https://www.windowscentral.com/change-smart-quotes-straight-quotes-microsoft-office-word-outlook-powerpoint
^ Alternatives: vscode: https://code.visualstudio.com/docs/python/python-tutorial, repl: https://repl.it/languages/python3 , etc.
Reference: https://docs.python.org/3/library/, https://docs.python.org/3/library/functions.html
[Preparation]
1. Knowing Functional Programming
Please read the following paragraphs (From https://docs.python.org/3/howto/functional.html ) :
2, Online console from PythonAnywhere
Alternatives: Feel free to use any other shell or environment if you prefer
Enter www.python.org and run the interactive shell ==>
• You will see the prompt “>>>” at where you
will type the code and run it.
• “Clear” the screen : Ctrl-L
• Change font size: Ctrl--, Ctrl-+
Functional programming decomposes a problem into a set of functions.
Ideally, functions only take inputs and produce outputs, and
don’t have any internal state that affects the output produced for a given input.
Functional programming can be considered the opposite of object-oriented programming.
Objects are little capsules containing some internal state
along with a collection of method calls that let you modify this state, and
programs consist of making the right set of state changes.
Functional programming wants to avoid state changes as much as possible and works with data
flowing between functions.
Lab 13 CS2312 Problem Solving and Programming (2020/2021 Semester A) | www.cs.cityu.edu.hk/~helena
- 2 -
Lab Tasks
inside code boxes in the tasks
Part A: We will first learn selected features of python step by step. <== Your code in the submission can be anything
Part B: We will move onto problem solving with Functional Programming. <== Your code has to be correct
Part A: Selected Features of Python
A.1 Variable and List, comments, input
The following creates two variables and a list.
No prior declaration is needed.
-The first assignment to a variable creates it.
Comment: #
Input: x = input()
Count of elements in a list: len(myList)
A.2 Printing – using the print function in Python 3
A.3 Define a function
About defining a function:
- def: define a function
- “global” is need to mean a global variable
- note the indentations (e.g. 3 spaces)
- when you finish, hit one more to exit
- default return value: None
print("Testing", x, y, myList) >>> print("Testing", x, y, myList)
Testing apple pear ['apple', 3.14]
>>>
sum=0
def addValue(x):
>>> sum=0
>>>
>>> def addValue(x):
... global sum
... sum += x
...
>>> addValue(1)
>>> addValue(2)
>>> addValue(3)
>>>
>>> sum
6
x = "apple"
y = 'pear'
myList = ["apple",3.14] #like array
x
y
myList
Given code box
(Please add your own code to do more test(s),
copy and paste to the Python console for running)
>>> x = "apple"
>>> y = 'pear'
>>> myList = ["apple",3.14] #like array
>>> x
'apple'
>>> y
'pear'
>>> myList
['apple', 3.14]
>>>
Lab 13 CS2312 Problem Solving and Programming (2020/2021 Semester A) | www.cs.cityu.edu.hk/~helena
- 3 -
A.4 and, or, not; True, False
A.5 Control of Flow, Multiple assignment
if ..:, elif ..:, else:
a, b, c = 1, 2, 3
To delete a variable, use del. E.g. del mx_1
A.6 List: + and slicing – provide the start and end (element excluded) index
A.7 The list() function
– creates a list by iterating through the contents of the given parameter
>>> s = [1,2,-3,4,5,-6,7,8,-9,10,-11,-12,13,-14,15,-16]
>>> s
[1, 2, -3, 4, 5, -6, 7, 8, -9, 10, -11, -12, 13, -14, 15, -16]
>>> s = s[1:6]
>>> s
[2, -3, 4, 5, -6]
>>> s1 = s[:3]
>>> s2 = s[3:]
>>> s1
[2, -3, 4]
>>> s2
[5, -6]

True and False
True or False
not False
[Your work] Add your testing code in the code box below:
s = [1,2,-3,4,5,-6,7,8,-9,10,-11,-12,13,-14,15,-16]
list("hello")
>>> True and False
False
>>> True or False
True
>>> not False
True
>>>
>>> list("hello")
['h', 'e', 'l', 'l', 'o']
>>>
x, y = 4, 4 #assign values to two variables
if x>y:
mx_1 = x
elif y>x: # try change to else:
mx_1 = y
mx_1
x, y = y+1, x-1
mx_2 = x if x>y else y
mx_2
Lab 13 CS2312 Problem Solving and Programming (2020/2021 Semester A) | www.cs.cityu.edu.hk/~helena
- 4 -
A.8 Lambda function, function variable
W3schools: A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Function variables: _is_equal, _is_small, _is_large, _append
One more example: f = lambda x,y: x if x>y else y
f(3,4) #gives 4
A.9 map function: map(f, [x1, x2, ..]) - means the execution of f on each element xi in the list
- f may be a one-parameter-function to take on each xi
- map returns a map object that can be iterated to execute f on each element xi in the list
To run, type list( map(f, [x1, x2, ..]) )
Default return value: None
Try:- add return sum inside the function
- list(map(list,["apple","pear","banana"])) # [['a', 'p', 'p', 'l', 'e'], ['p', 'e', 'a', 'r'], ['b', 'a', 'n', 'a', 'n', 'a']]
A.10 filter function (https://docs.python.org/3/library/functions.html#filter)
Filter a collection according to some conditions
Note: The object returned by filter / map
can be iterated only once.
It doesn't work for the second time.
a = filter(lambda x: x>0, [1, -2, 3, 6, -9, 20, 13, 16])
list(a) # gives [1, 3, 6, 20, 13, 16]
list(a) # gives []
sum=0
def addValue(x):
global sum
sum += x
>>> sum=0
>>> def addValue(x):
... global sum
... sum += x
...
>>> list(map(addValue, [1,2,3]))
[None, None, None]
>>> sum
6
>>> _is_equal = lambda x,y : x==y _is_equal = lambda x,y : x==y
>>> _is_small = lambda x,y : x

联系我们
  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-21:00
  • 微信:codinghelp
热点标签

联系我们 - QQ: 99515681 微信:codinghelp
程序辅导网!