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

CSC1002 Week1 Overview

Uploaded by

ridef90785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

CSC1002 Week1 Overview

Uploaded by

ridef90785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

CSC1002-Computational

Laboratory
Kinley Lam

CSC1002/CUHK(SZ)/SSE
CSC 1002 Week 1
Programming background
editor & tools
hello world
past assignments at a glance
assessment

CSC1002/CUHK(SZ) by Kinley Lam


No tutorials this week !!!

CSC1002/CUHK(SZ) by Kinley Lam


References (books)

CSC1002/CUHK(SZ) by Kinley Lam


References

CSC1002/CUHK(SZ) by Kinley Lam


python https://www.python.org/

search for
“Free eBook”
Follow “Python Books” and then
“IntroductoryBooks” for a list of
reference books and free e-book(s)
CSC1002/CUHK(SZ) by Kinley Lam
Free ebooks via Python official website

CSC1002/CUHK(SZ) by Kinley Lam


Programming Language

CSC1002/CUHK(SZ) by Kinley Lam


hello world
using notepad & word

CSC1002/CUHK(SZ) by Kinley Lam


hello world

Write a “hello world”


program

CSC1002/CUHK(SZ) by Kinley Lam


Why “Hello World”

CSC1002/CUHK(SZ) by Kinley Lam


CSC1002/CUHK(SZ) by Kinley Lam
CSC1002/CUHK(SZ) by Kinley Lam
CSC1002/CUHK(SZ) by Kinley Lam
Brian Kernighan

CSC1002/CUHK(SZ) by Kinley Lam


Editor & tools

CSC1002/CUHK(SZ) by Kinley Lam


IDE (Integrated Development Environment)

• Uniform interface – editing, execution and shell


• IntelliSense – auto code completion, quick info, parameter info … etc
• Code navigation – file explorer, code hierarchy, references, … etc
• Debugging, Source control, Refactoring, Unit testing … etc
• Extensions (tools, language support, interfaces .. Etc
• Many many others

CSC1002/CUHK(SZ) by Kinley Lam


Source Code Editor

CSC1002/CUHK(SZ) by Kinley Lam


Why Visual Studio Code
• Light weight
• Simplicity
• Cross platform (windows, macOS & linux)
• Integrated (debugging, source control, refactoring, auto code
completion)
• Universal (python, C/C++, C#, html, java, swift, php, SQL …)
• Lots of extensions !!!!!
• FREE and back by Microsoft !!!

CSC1002/CUHK(SZ) by Kinley Lam


Specialized editors

CSC1002/CUHK(SZ) by Kinley Lam


IDE – what is it?

CSC1002/CUHK(SZ) by Kinley Lam


CSC1002/CUHK(SZ) by Kinley Lam
IDE

CSC1002/CUHK(SZ) by Kinley Lam


Past Assignments

CSC1002/CUHK(SZ) by Kinley Lam


Past Assignments (2017-2018)

CSC1002/CUHK(SZ) by Kinley Lam


Past Assignment (2018-2019)

CSC1002/CUHK(SZ) by Kinley Lam


Past Assignments (2020-2021)

CSC1002/CUHK(SZ) by Kinley Lam


Past Assignments (2021-2022)

CSC1002/CUHK(SZ) by Kinley Lam


This Year ???

CSC1002/CUHK(SZ) by Kinley Lam


Teaching Plan & Assessment

Please refer to BB for more info !!!

CSC1002/CUHK(SZ) by Kinley Lam


Python overview

CSC1002/CUHK(SZ) by Kinley Lam


modules – reload

CSC1002/CUHK(SZ) by Kinley Lam


__name__ == “__main__”

CSC1002/CUHK(SZ) by Kinley Lam


Core Data Types

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• Indentation

• Modules

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• Strings

• Lists

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• Tuples (immutable list)
• works exactly as list except that tuples are read only and parentheses “()” are
used instead of square brackets “[]”

• Dictionary

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• defaultdict() – 4 x word-count implementations

A C

B D

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• defaultdict() – list, dict and function

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• Control Flow - if

• Control Flow - While

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• Control Flow – for

• List Comprehensions

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• Functional Tools – partial, map & reduce

Output

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• zip & unpacking

CSC1002/CUHK(SZ) by Kinley Lam


python – quick overview
• args & kwargs

• args = tuple of unnamed args,


• kwargs = dictionary list of named args

CSC1002/CUHK(SZ) by Kinley Lam


indentation – code blocks
• unlike others (C, C++, Pascal, C#, Javascript, VB, … and so on),
• no curly braces, no explicit begin/end or keywords to mark where
block starts and stops
• python uses “Indentation” to group block of source codes together as
logical blocks that are conditionally executed together with controls
• spaces or tab can be used to create the indentation (usually 4 spaces)
• python uses “:” to mark beginning of a block (def, if, for, while …)
• goals: consistent, uniform, readable styles

CSC1002/CUHK(SZ) by Kinley Lam


execution sequence

Block 1
Block 2
Block 3
Block 4
Block 5
conditional
Block 6 or controls
CSC1002/CUHK(SZ) by Kinley Lam
CSC1002/CUHK(SZ) by Kinley Lam
?

CSC1002/CUHK(SZ) by Kinley Lam


CSC1002/CUHK(SZ) by Kinley Lam
CSC1002/CUHK(SZ) by Kinley Lam
C/C++
• first programmer: • 3rd programmer:
while (x>y) { while (x>y) {
……; ……;
……;
……;
……;
}
……;
..…;
……;
}

• 4th programmer:
• 2nd programmer: while (x>y) {
……;
while (x>y) { ……;
……; ……;
……; ……;
……;
……; ..…;
} ……;
}

CSC1002/CUHK(SZ) by Kinley Lam


C/C++ - classic pitfall

which “if” is
“else” paired
with?

CSC1002/CUHK(SZ) by Kinley Lam


python – if/else

which “if” is
“else” paired
with?

CSC1002/CUHK(SZ) by Kinley Lam


List Iterations

CSC1002/CUHK(SZ) by Kinley Lam


while, for & list comprehension
• Given L = [3,45,22,44,78,90,44,23], extract all even numbers into
another list

Where
else can
we put it
??

CSC1002/CUHK(SZ) by Kinley Lam


How to show
the list
incrementally
??

CSC1002/CUHK(SZ) by Kinley Lam


“for” vs list comprehension

CSC1002/CUHK(SZ) by Kinley Lam


controls – for (sequence assignment)
• Tuple

CSC1002/CUHK(SZ) by Kinley Lam


controls – for (sequence assignment)
• List (extracting the first and last item from each sub list)

CSC1002/CUHK(SZ) by Kinley Lam


control – ternary if

if cond:
ret = val1
ret = val1 if cond else val2
else:
ret = val2

CSC1002/CUHK(SZ) by Kinley Lam


CSC1002/CUHK(SZ) by Kinley Lam
String Formatting

CSC1002/CUHK(SZ) by Kinley Lam


string formatting – 2 variations
• Expression: ‘ …..%....... ’ % (values)
• Method: ‘ ……{}…… ‘.format(values)
• ‘Do you like %s or %s?’ % ( ‘apples’, ‘oranges’ )
• ‘Do you like {} or {}?’.format(‘apples’, ‘oranges’)
• ‘Do you like apples or oranges?’
• Note: both pretty much achieve same results, the format method was
introduced later and gains more popularity.

CSC1002/CUHK(SZ) by Kinley Lam


method-call formatting – position
• relative position
‘{} {} {}’.format(‘apple’,’orange’,’grape’)

• position number
‘{0} {1} {2}’.format(‘apple’,’orange’,’grape’)

• keyword
‘{a} {o} {g}’.format( a=‘apple’, o=‘orange’, g=‘grape’ )

CSC1002/CUHK(SZ) by Kinley Lam


example 1
• input
• a = ‘apple’, o = ‘orange’, g = ‘grape’
• output
• ‘apple-orange-apple-orange-apple-grape-orange’
• using print() statement
• print(a + ‘-’ + o + ‘-’ + a + ‘-’ + o + ‘-’ + a + ‘-’ + g + ‘-’ + o)
• using format()
• print(‘{0}-{1}-{0}-{1}-{0}-{2}-{1}’.format(a,o,g))
• print(‘{a}-{o}-{a}-{o}-{a}-{g}-{o}’.format(‘a’=a,’o’=o,’g’=g))

CSC1002/CUHK(SZ) by Kinley Lam


example 2
• input
• total = 4356, failed=342
• output
• ‘Total 4356 samples with failures 342 cases, failure rate 12.76%’
• using print() statement
‘Total ’ + str(total) + ‘ samples with failures ‘ + str(failed) + ‘ cases, failure rate ‘ +
round(total/failed,2) + ‘%’
• using format()
‘Total {} samples with failures {} cases, failure rate {}%’.
format(total, failed, round(total/failed,2))

CSC1002/CUHK(SZ) by Kinley Lam


Separate format string from data
• output
• ‘Total {} samples with failures {} cases, failure rate {}%’

• ‘共有{}件样品失败{}件,失败率{}%’

• ‘총 {} 건의 실패 사례 {} 건, 실패율 {}%’

• 'Total {} muestras con fallas {} casos, índice de fallas {} %'

CSC1002/CUHK(SZ) by Kinley Lam


string at a glance

CSC1002/CUHK(SZ) by Kinley Lam


strings
• ‘this is a string single quoted’
• “this is another string’s double quoted”
• ‘’’this is another triple quoted string’’’
• spanning multiple lines
• r”c:\dir1\dir2\dir3\file.txt”
• instead of “c:\\dir1\\dir2\\dir3\\file.txt”
• byte and unicode strings (we will skip these for this class)
• ‘string1’ “string2” ‘string3’ (a concatenated string)
• ‘string1’, “string2”, ‘string3’ (a tuple)
• strings are immutable (cannot be changed)

CSC1002/CUHK(SZ) by Kinley Lam


zero-based indexing

CSC1002/CUHK(SZ) by Kinley Lam


string : indexing
• given s = “hello world”
0 1 2 3 4 5 6 7 . . .

h e l l o w o r l d

. . . -8 -7 -6 -5 -4 -3 -2 -1

• use module “string” and try indexing with “ascii_lowercase”


• s = string.ascii_lowercase
• indexing: s[0], s[1], s[-1], s[-2], s[26]

CSC1002/CUHK(SZ) by Kinley Lam


string : slicing

• use module “string” and try indexing and slicing with “ascii_lowercase”
• s = string.ascii_lowercase
• slicing: s[:], s[1:], s[:-1], s[1:-1], s[-6:], s[::2], s[::-1], s[1:10:-1]
• how to reverse a string using slicing? s[::-1]

CSC1002/CUHK(SZ) by Kinley Lam


string – common functions
• justification & conversion
• center(), ljust(), rjust(), format(), capitalize(), lower(), upper()
• search & replace
• endswith(), startswith(), find(), rfind(), replace()
• query
• isalnum(), isalpha(), isdecimal(), isdigit(), islower(), isnumeric(), isupper(), isspace()
• splitting and joining
• join(), split(), rsplit()
• stripping whitespaces
• strip(), lstrip(), rstrip()

CSC1002/CUHK(SZ) by Kinley Lam


string - exercises
• ‘apple’.center(10), ‘apple’.rjust(10), ‘apple’.ljust(10), ‘apple’.upper()
• ‘apple’.startswith(‘ap’), ‘apple’.endswith(‘le’), ‘apple’.find(‘app’)
• ‘apple’.replace(‘app’,’peop’), ‘apple’.islower(), ‘apple’.isnumeric()
• ‘apple’.isalnum(), ‘apple’.isdigit(), ‘apple’.isdelicious()
• try to generate the following figure using series of print statements:

CSC1002/CUHK(SZ) by Kinley Lam


• print statements
• print( (‘p’).center(11) )
• print( (‘p’*3).center(11) )
• print( (‘p’*5).center(11) )
• print( (‘p’*7).center(11) )
• print( (‘p’*9).center(11) )
• print( (‘p’*11).center(11) )
• ‘apple-orange-grape’.split(‘-’)
• ‘apple-orange-grape’.partition(‘-’)
• Note: split() splits all occurrences, while partition() only on first occurrence.
• ‘-’.join([‘apple’, ‘orange’, ‘grape’])

CSC1002/CUHK(SZ) by Kinley Lam


range() & list()
• range() is a handy function to generate a sequence of successive
integers
• list() is used to convert the numbers from range() into a list
• range(start, end, step)
• try:
• list(range(10)) [0,1,2,3,4,5,6,7,8,9]
• list(range(1,10)) [1,2,3,4,5,6,7,8,9]
• list(range(0,10,2)) [0,2,4,6,8]
• list(range(1,10,2)) [1,3,5,7,9]

CSC1002/CUHK(SZ) by Kinley Lam


string – exercises (using range())
• using range with a for-loop:

• for i in range(1,12,2): print( ('p'*i).center(11) )

CSC1002/CUHK(SZ) by Kinley Lam


List - examples
List Remark
[] empty list
[ 12, ‘a’, 1.24, {‘d’:88}] List with 4 items of different types
list(range(100)) list of numbers from 0 to 99
[ [1,2,3], [4,5,6], [7,8,9] ] 3 x 3 matrix

CSC1002/CUHK(SZ) by Kinley Lam


List – slicing & indexing
• Similar to string’s

CSC1002/CUHK(SZ) by Kinley Lam


slicing – step > 0 (given “abcdefghij”)

0 1 2 3 4 . . . -2 -1

a b c d e f g h i j
step 1
[: step 2
:]
step 3

CSC1002/CUHK(SZ) by Kinley Lam


slicing – step < 0 (given “abcdefghij”)

-1 -2 -3 -4 -5 . . . 1 0

j i h g f e d c b a
step -1
[: step -2
:]
step -3

CSC1002/CUHK(SZ) by Kinley Lam


List – update operations L=[1,2,3]
by slicing by method Remark
L[:0] = [9] L.insert(0,[9]) [9,1,2,3] insert front
L[1:1] = [9] L.insert(1,[9]) [1,9,2,3] insert between
L[1:2] = [9], L[1] = 9 [1,9,3] replace
L[len(L):] = [9] L.extend([9]) [1,2,3,9] insert end
L + [9]
L[0:1] = [] L.remove(1) [2,3] remove first item
del L[0]
L[len(L):] = [[9]] L.append([9]) [1,2,3, [9]] nested append
L.index(1) 0 return index of item 1
L[-1:] = []
CSC1002/CUHK(SZ) by Kinley Lam
L.pop() [1,2] remove last item
list – other operations L = [1,2,3]

result Remark
len(L) 3 length
1 in L true membership
for x in L: print(x, end=‘,’) 1,2,3, iteration
[x*x for x in L] [1,4,9] list comprehension
L.sort(reverse=True) [3,2,1] sort in reverse order

CSC1002/CUHK(SZ) by Kinley Lam


Tuple - examples
List Remark
() empty tuple
(12,) single item tuple (please note comma)
( 12, ‘a’, 1.24, {‘d’:88} ) tuple with 4 items of different types
tuple(range(100)) list of numbers from 0 to 99
( [1,2,3], [4,5,6], [7,8,9] ) 3 x 3 matrix
list( (1,2,3,4) ) converted to list
CSC1002/CUHK(SZ) by Kinley Lam
Tuple - notes
• Tuples work exactly the same as list except that tuples are immutable
(read only) and parentheses “()” are used instead of square brackets
“[]”
• create a tuple T = (1,2,3,4)
• type T[0]
• try assigning a new value to T[0], say T[0] = 9, what do you get?

CSC1002/CUHK(SZ) by Kinley Lam


tuple : slicing and indexing

• similar to list’s and string’s


• indexing: s[0], s[1], s[-1], s[-2], s[26]
• slicing: s[:], s[1:], s[:-1], s[1:-1], s[-6:], s[::2], s[::-1], s[1:10:-1]?
• how to reverse items in a tuple using slicing? s[::-1]

CSC1002/CUHK(SZ) by Kinley Lam


list – slicing exercise
• given s = list(range(100))
• use slicing to return all even numbers from s
• [0,2,4,6,8,….,98]
• use slicing to return all odd numbers from s
• [1,3,5,7,9,….,99]
• use slicing to return all odd numbers from s in reverse order
• [99,97,95,93,91,…….,1]
• use slicing to return all even numbers from s in reverse order
• [98,96,94,92,90,…….,0]
• use slicing to return the last 10 numbers from s in reverse order
• [99,98,97,96,95,94,93,92,91,90]
• use slicing to return first 3 numbers from s in reverse order
• [2,1,0]

CSC1002/CUHK(SZ) by Kinley Lam

You might also like