SlideShare une entreprise Scribd logo
1  sur  27
CCE20003 HGU
CCE20003 PROGRAMMING I
Lecture 15
Spring 2015
ICT Convergence Division
School of Creative Convergence Education
Handong Global University
CCE20003 HGU
OUTLINE
Sorting in Python
Selection sort
Bubble sort
Recursion
CCE20003 HGU
SORTING IN PYTHON
Why sort and search ?
25 -50 % of computing time
- Reporting
- Updating
- Inquiring
In most Python implementations, the sorting algorithm
called Timsort( Tim Peters ,2002) is used, which is a
variant of the merge sort(John von Neumann in 1945).
CCE20003 HGU
>>>L = [4, 2, 3]
>>>L.sort()
>>>print L.sort()
None
>>>print L
[2, 3, 4]
>>>L
[2, 3, 4]
>>>L.sort(reverse = True)
>>>L
[4, 3, 2]
L.sort() does change L.
>>>L = [4, 2, 3]
>>>sorted(L)
[2, 3, 4]
>>>print sorted(L)
[2, 3, 4]
>>print L
[4, 2, 3]
>>>L
[4, 2, 3]
>>>sorted(L, reverse = True)
{4, 3, 2]
sorted(L) does not change L.
CCE20003 HGU
sorted(.) can be used for a sequence
>>>T = (4, 2, 3)
>>>D = {“John” : 24, “Mary” : 20, “James” : 22}
>>>sorted(T)
(2, 3, 4)
>>>sorted(D)
[“James”, “John”, “Mary”]
CCE20003 HGU
SELECTION SORT
BASIC IDEA the smallest element
sorted
s
Step 1
Step k
At the end of the last step
CCE20003 HGU
[5, 9, 4, 7, 3] 4 comparisons
[3, 9, 5, 7, 4] 3 comparisons
[3, 4, 9, 7, 5] 2 comparisons Why ?
[3, 4, 5, 9, 7] 1 comparison
[3, 4, 5, 7, 9]
[3, 4, 5, 7, 9]
How many comparisons in
general?
(n-1)n/ 2 = 𝑛2/2 – n/2
O( 𝑛2)
4(4 +1)/2
comparisons
CCE20003 HGU
1 + 2 + 3 + 4 = 4 (4 + 1) = 10 comparisons
In general,
1 + ……… + (n - 1) = (n - 1)(n – 1 + 1)/2 = (n -1)n/2,
where n = len(L).
CCE20003 HGU
Pseudo code
1. Given a list of elements, find the smallest element
and make it the first element of the list. Let the sub-
list except the first element be the remaining list.
2. Given the remaining list, find the smallest element
and make it the first element of the remaining list. Make
a new remaining list by excluding the first element.
3. Repeat Step 2 until the remaining list becomes a
single element.
CCE20003 HGU
def selection_sort(L):
start = 0
end = len(L)
while start < end:
for i in range(start, end):
if L[i] < L[start]:
L[start], L[i] = L[i], L[start]
start += 1 for the next sub-list
return L
Finding the smallest
one in the current
sub-list
How about start , end -1 ?
CCE20003 HGU
BUBBLE SORT
Basic idea
1st round
Like a bubble floating up!
5
9
4
7
3
5
9
4
3
7
5
9
3
4
7
5
3
9
4
7
3
5
9
4
7
4 comparisons
CCE20003 HGU
2nd round
3
5
9
4
7
3
5
9
4
7
3
5
4
9
7
3
4
5
9
7
3 comparisons
CCE20003 HGU
3rd round
3
4
5
9
7
3
4
5
7
9
3
4
5
7
9
2 comparisons
CCE20003 HGU
4th round
3
4
5
7
9
3
4
5
7
9
3
4
5
7
9
1 comparisons
CCE20003 HGU
Pseudo code
1.Enumerate a series of sub-lists of a list of elements,
each sub-list containing the elements from the i-th one
to the last one for i = 0, 1, 2, 3, ……, n-1
2. For each sub-list, scan the sub-list in the reverse order
from the end, compare every consecutive pair of elements,
and swap the elements, if needed, to make the smaller
one float up.
3. Stop when all sub-lists are scanned.
CCE20003 HGU
def bubble_sort(L):
for i in range ( len(L) - 1):
for j in range(len(L) - 1 - i):
i1 = (len(L)-1) - (j + 1)
i2 = (len(L)-1) - j
if L[i1] > L[i2]:
L[i1], L[i2] = L[i2], L[i1]
return L
Bubbles float up!
Sort a sub-list.
CCE20003 HGU
RECURSION
Recursion is defining something in terms of itself. It
sounds a bit odd, but very natural in fact. Here are
some examples:
According to the legal code of United States, a U.S.
citizen is
1. any child born inside United States, or
the base case
2. any child born outside United States and at least
one of whose parent is a U.S. citizen satisfying certain
condition.
the recursive(inductive) case
CCE20003 HGU
In mathematics, the factorial function is defined as
follows:
f(n) = n X (n-1) X (n-2) X……….X 2 X 1
(n – 1)!
f(n – 1)
1 if n = 1 base case
n x f(n - 1) if n > 1 recursive case
f(n)
f(n) =
CCE20003 HGU
Fibonacci numbers
1 if n = 0
1 if n = 1
f(n – 1) + f(n - 2)
f(n)
base case
recursive case
n f(n)
0 1
1 1
2 2
3 3
4 5
5 8
6 13
…… ……
CCE20003 HGU
Recursive functions
A function is said to be recursive if the function is
defined in terms of itself, specifically, the function
can call itself during its execution.
CCE20003 HGU
Factorial function
1 if n = 1 base case
n x f(n - 1) if n > 1 recursive case
f(n)
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
def fact(n):
result = 1
while n >1:
result = result * n
n -= 1
return result
f(n) =
CCE20003 HGU
def fact(n):
if n == 1:
print 1,
return 1
else:
print n, "x ",
return n * fact(n-1)
x = fact(7)
print “ = “, x
7 x 6 x 5 x 4 x 3 x 2 x 1 = 5040
CCE20003 HGU
Fibonacci numbers
1 if n = 0
1 if n = 1
f(n – 1) + f(n - 2)
f(n)
base case
recursive case
def fib(n):
if n == 0 or n == 1:
return 1
else:
return fib(n – 1) + fib(n - 2)
fib(5)
CCE20003 HGU
def fib(n):
global lv
lv += 1
if n == 0 or n == 1:
print " " * 4 * lv, 1
lv -= 1
return 1
else:
print " " * 4 * lv, "fib(", n,")"
x = fib(n - 1) + fib(n - 2)
lv -= 1
return x
lv = -1
x = fib(5)
print “n“, ”fib(5) = ", x
fib( 5 )
fib( 4 )
fib( 3 )
fib( 2 )
1
1
1
fib( 2 )
1
1
fib( 3 )
fib( 2 )
1
1
1
fib(5) = 8
CCE20003 HGU
8
5 3
3 2 2 1
2 1 1 1 1 1
1 1
Fib(5)
Fib(4) Fib(3)
Fib(3) Fib(2)
Fib(2)
Fib(2)
CCE20003 HGU
Palindromes
def is_palin(s):
if len(s) <= 1:
return True
else:
return (s[0] == s[-1]) and is_palin(s[1, -1])
palin(s) =
True if n <= 1 base case
(s[0] == s[-1]) and palin(s[1: -1]) if n > 1
recursive case
CCE20003 HGU
doggod
oggo
gg
True
True
True
True
def is_palin(s):
global lv
lv += 1
if len(s) <= 1:
display(True)
lv -= 1
return True
else:
display(s)
flag = (s[0] == s[-1]) and
is_palin(s[1 : -1])
display(flag)
lv -= 1
return flag
def display(s):
global lv
if lv == 0:
print s
else:
print " " * 4 * lv, s
lv = -1
is_palin( "dogGod".lower())

Contenu connexe

Similaire à lecture.15.note.pptx

Numpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipyNumpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipyHiroaki Hamada
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdfHimoZZZ
 
Brief summary of signals
Brief summary of signalsBrief summary of signals
Brief summary of signalsaroosa khan
 
differential-calculus-1-23.pdf
differential-calculus-1-23.pdfdifferential-calculus-1-23.pdf
differential-calculus-1-23.pdfIILSASTOWER
 
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program CorrectnessCMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctnessallyn joy calcaben
 
Learning Deep Learning
Learning Deep LearningLearning Deep Learning
Learning Deep Learningsimaokasonse
 
funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptxTess Ferrandez
 
Forward & Backward Differenece Table
Forward & Backward Differenece TableForward & Backward Differenece Table
Forward & Backward Differenece TableSaloni Singhal
 
Learn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard wayLearn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard wayKir Chou
 
Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5Carol Defreese
 
Docslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tablesDocslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tablesbarasActuarial
 
Recursion - Computer Algorithms
Recursion - Computer AlgorithmsRecursion - Computer Algorithms
Recursion - Computer AlgorithmsAlaa Al-Makhzoomy
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 

Similaire à lecture.15.note.pptx (20)

Numpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipyNumpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipy
 
Recursion
RecursionRecursion
Recursion
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
 
Brief summary of signals
Brief summary of signalsBrief summary of signals
Brief summary of signals
 
differential-calculus-1-23.pdf
differential-calculus-1-23.pdfdifferential-calculus-1-23.pdf
differential-calculus-1-23.pdf
 
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program CorrectnessCMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
 
Learning Deep Learning
Learning Deep LearningLearning Deep Learning
Learning Deep Learning
 
Sorting
SortingSorting
Sorting
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptx
 
FACTORING
FACTORINGFACTORING
FACTORING
 
Forward & Backward Differenece Table
Forward & Backward Differenece TableForward & Backward Differenece Table
Forward & Backward Differenece Table
 
Learn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard wayLearn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard way
 
Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5
 
Lab no.07
Lab no.07Lab no.07
Lab no.07
 
Python Programming
Python Programming Python Programming
Python Programming
 
Docslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tablesDocslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tables
 
Recursion - Computer Algorithms
Recursion - Computer AlgorithmsRecursion - Computer Algorithms
Recursion - Computer Algorithms
 
Review session2
Review session2Review session2
Review session2
 
Si math 107 ch5,8
Si math 107 ch5,8Si math 107 ch5,8
Si math 107 ch5,8
 

Plus de JibrilJundi

Plus de JibrilJundi (11)

1. Ideal and Actual Cycle.pptx
1. Ideal and Actual Cycle.pptx1. Ideal and Actual Cycle.pptx
1. Ideal and Actual Cycle.pptx
 
Ass 1.pdf
Ass 1.pdfAss 1.pdf
Ass 1.pdf
 
4.ppt
4.ppt4.ppt
4.ppt
 
blast furnace.pptx
blast furnace.pptxblast furnace.pptx
blast furnace.pptx
 
chapter 2.pptx
chapter 2.pptxchapter 2.pptx
chapter 2.pptx
 
ch.4.pptx
ch.4.pptxch.4.pptx
ch.4.pptx
 
CH 3.pptx
CH 3.pptxCH 3.pptx
CH 3.pptx
 
Thermo I CH 2.pptx
Thermo I CH 2.pptxThermo I CH 2.pptx
Thermo I CH 2.pptx
 
Thermo I CH 1.pptx
Thermo I CH 1.pptxThermo I CH 1.pptx
Thermo I CH 1.pptx
 
dynamics chapter 2.pptx
dynamics chapter 2.pptxdynamics chapter 2.pptx
dynamics chapter 2.pptx
 
dynamics chapt 1 .pptx
dynamics chapt 1 .pptxdynamics chapt 1 .pptx
dynamics chapt 1 .pptx
 

Dernier

04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxolyaivanovalion
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusTimothy Spann
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 

Dernier (20)

VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 

lecture.15.note.pptx

  • 1. CCE20003 HGU CCE20003 PROGRAMMING I Lecture 15 Spring 2015 ICT Convergence Division School of Creative Convergence Education Handong Global University
  • 2. CCE20003 HGU OUTLINE Sorting in Python Selection sort Bubble sort Recursion
  • 3. CCE20003 HGU SORTING IN PYTHON Why sort and search ? 25 -50 % of computing time - Reporting - Updating - Inquiring In most Python implementations, the sorting algorithm called Timsort( Tim Peters ,2002) is used, which is a variant of the merge sort(John von Neumann in 1945).
  • 4. CCE20003 HGU >>>L = [4, 2, 3] >>>L.sort() >>>print L.sort() None >>>print L [2, 3, 4] >>>L [2, 3, 4] >>>L.sort(reverse = True) >>>L [4, 3, 2] L.sort() does change L. >>>L = [4, 2, 3] >>>sorted(L) [2, 3, 4] >>>print sorted(L) [2, 3, 4] >>print L [4, 2, 3] >>>L [4, 2, 3] >>>sorted(L, reverse = True) {4, 3, 2] sorted(L) does not change L.
  • 5. CCE20003 HGU sorted(.) can be used for a sequence >>>T = (4, 2, 3) >>>D = {“John” : 24, “Mary” : 20, “James” : 22} >>>sorted(T) (2, 3, 4) >>>sorted(D) [“James”, “John”, “Mary”]
  • 6. CCE20003 HGU SELECTION SORT BASIC IDEA the smallest element sorted s Step 1 Step k At the end of the last step
  • 7. CCE20003 HGU [5, 9, 4, 7, 3] 4 comparisons [3, 9, 5, 7, 4] 3 comparisons [3, 4, 9, 7, 5] 2 comparisons Why ? [3, 4, 5, 9, 7] 1 comparison [3, 4, 5, 7, 9] [3, 4, 5, 7, 9] How many comparisons in general? (n-1)n/ 2 = 𝑛2/2 – n/2 O( 𝑛2) 4(4 +1)/2 comparisons
  • 8. CCE20003 HGU 1 + 2 + 3 + 4 = 4 (4 + 1) = 10 comparisons In general, 1 + ……… + (n - 1) = (n - 1)(n – 1 + 1)/2 = (n -1)n/2, where n = len(L).
  • 9. CCE20003 HGU Pseudo code 1. Given a list of elements, find the smallest element and make it the first element of the list. Let the sub- list except the first element be the remaining list. 2. Given the remaining list, find the smallest element and make it the first element of the remaining list. Make a new remaining list by excluding the first element. 3. Repeat Step 2 until the remaining list becomes a single element.
  • 10. CCE20003 HGU def selection_sort(L): start = 0 end = len(L) while start < end: for i in range(start, end): if L[i] < L[start]: L[start], L[i] = L[i], L[start] start += 1 for the next sub-list return L Finding the smallest one in the current sub-list How about start , end -1 ?
  • 11. CCE20003 HGU BUBBLE SORT Basic idea 1st round Like a bubble floating up! 5 9 4 7 3 5 9 4 3 7 5 9 3 4 7 5 3 9 4 7 3 5 9 4 7 4 comparisons
  • 15. CCE20003 HGU Pseudo code 1.Enumerate a series of sub-lists of a list of elements, each sub-list containing the elements from the i-th one to the last one for i = 0, 1, 2, 3, ……, n-1 2. For each sub-list, scan the sub-list in the reverse order from the end, compare every consecutive pair of elements, and swap the elements, if needed, to make the smaller one float up. 3. Stop when all sub-lists are scanned.
  • 16. CCE20003 HGU def bubble_sort(L): for i in range ( len(L) - 1): for j in range(len(L) - 1 - i): i1 = (len(L)-1) - (j + 1) i2 = (len(L)-1) - j if L[i1] > L[i2]: L[i1], L[i2] = L[i2], L[i1] return L Bubbles float up! Sort a sub-list.
  • 17. CCE20003 HGU RECURSION Recursion is defining something in terms of itself. It sounds a bit odd, but very natural in fact. Here are some examples: According to the legal code of United States, a U.S. citizen is 1. any child born inside United States, or the base case 2. any child born outside United States and at least one of whose parent is a U.S. citizen satisfying certain condition. the recursive(inductive) case
  • 18. CCE20003 HGU In mathematics, the factorial function is defined as follows: f(n) = n X (n-1) X (n-2) X……….X 2 X 1 (n – 1)! f(n – 1) 1 if n = 1 base case n x f(n - 1) if n > 1 recursive case f(n) f(n) =
  • 19. CCE20003 HGU Fibonacci numbers 1 if n = 0 1 if n = 1 f(n – 1) + f(n - 2) f(n) base case recursive case n f(n) 0 1 1 1 2 2 3 3 4 5 5 8 6 13 …… ……
  • 20. CCE20003 HGU Recursive functions A function is said to be recursive if the function is defined in terms of itself, specifically, the function can call itself during its execution.
  • 21. CCE20003 HGU Factorial function 1 if n = 1 base case n x f(n - 1) if n > 1 recursive case f(n) def fact(n): if n == 1: return 1 return n * fact(n-1) def fact(n): result = 1 while n >1: result = result * n n -= 1 return result f(n) =
  • 22. CCE20003 HGU def fact(n): if n == 1: print 1, return 1 else: print n, "x ", return n * fact(n-1) x = fact(7) print “ = “, x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 5040
  • 23. CCE20003 HGU Fibonacci numbers 1 if n = 0 1 if n = 1 f(n – 1) + f(n - 2) f(n) base case recursive case def fib(n): if n == 0 or n == 1: return 1 else: return fib(n – 1) + fib(n - 2) fib(5)
  • 24. CCE20003 HGU def fib(n): global lv lv += 1 if n == 0 or n == 1: print " " * 4 * lv, 1 lv -= 1 return 1 else: print " " * 4 * lv, "fib(", n,")" x = fib(n - 1) + fib(n - 2) lv -= 1 return x lv = -1 x = fib(5) print “n“, ”fib(5) = ", x fib( 5 ) fib( 4 ) fib( 3 ) fib( 2 ) 1 1 1 fib( 2 ) 1 1 fib( 3 ) fib( 2 ) 1 1 1 fib(5) = 8
  • 25. CCE20003 HGU 8 5 3 3 2 2 1 2 1 1 1 1 1 1 1 Fib(5) Fib(4) Fib(3) Fib(3) Fib(2) Fib(2) Fib(2)
  • 26. CCE20003 HGU Palindromes def is_palin(s): if len(s) <= 1: return True else: return (s[0] == s[-1]) and is_palin(s[1, -1]) palin(s) = True if n <= 1 base case (s[0] == s[-1]) and palin(s[1: -1]) if n > 1 recursive case
  • 27. CCE20003 HGU doggod oggo gg True True True True def is_palin(s): global lv lv += 1 if len(s) <= 1: display(True) lv -= 1 return True else: display(s) flag = (s[0] == s[-1]) and is_palin(s[1 : -1]) display(flag) lv -= 1 return flag def display(s): global lv if lv == 0: print s else: print " " * 4 * lv, s lv = -1 is_palin( "dogGod".lower())