A4B99RPH: Reen problm u a hry Cist kd. Petr Pok Katedra - - PowerPoint PPT Presentation

a4b99rph re en probl m u a hry cist k d
SMART_READER_LITE
LIVE PREVIEW

A4B99RPH: Reen problm u a hry Cist kd. Petr Pok Katedra - - PowerPoint PPT Presentation

CZECH TECHNICAL UNIVERSITY IN PRAGUE Faculty of Electrical Engineering Department of Cybernetics A4B99RPH: Reen problm u a hry Cist kd. Petr Pok Katedra kybernetiky CVUT FEL A4B99RPH: P. Pok c 2012


slide-1
SLIDE 1

CZECH TECHNICAL UNIVERSITY IN PRAGUE

Faculty of Electrical Engineering Department of Cybernetics

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 1 / 14

A4B99RPH: ˇ Rešení problém˚ u a hry ˇ Cistý kód.

Petr Pošík Katedra kybernetiky ˇ CVUT FEL

slide-2
SLIDE 2

Clean Code

Zpracováno podle Robert C. Martin: Clean Code: A Handbook of Agile Software Craftsmanship, Prentice Hall, 2008.

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 2 / 14

slide-3
SLIDE 3

Který kód je ˇ cistší? A proˇ c?

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 3 / 14

Dvˇ e implementace téhož algoritmu:

def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value >= 2: # There are some primes # Initialize the list (incl. 0) f = [True for i in range(max_value+1)] # Get rid of the known non-primes f[0] = f[1] = False # Run the sieve for i in range(2, len(f)): if f[i]: # i is still a candidate # mark its multiples as not prime for j in range(2*i, len(f), i): f[j] = False # Find the primes and put them in a list primes = [i for i in range(len(f)) if f[i]] return primes else: # max_value < 2 return list() # no primes, return empty list PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value < 2: return [] else: candidates = init_integers_up_to(max_value) mark_non_primes(candidates) return collect_remaining(candidates) def init_integers_up_to(max_value): return [PRIME for i in range(max_value+1)] def mark_non_primes(candidates): # Mark 0 and 1, they are not primes. candidates[0] = candidates[1] = NONPRIME for number in range(2, len(candidates)): if candidates[number] == PRIME: mark_as_not_prime_multiples_of(number, candidates) def mark_as_not_prime_multiples_of(number, candidates): for multiple in range(2*number, len(candidates), number): candidates[multiple] = NONPRIME def collect_remaining(candidates): primes = [i for i in range(len(candidates)) if candidates[i]==PRIME] return primes

slide-4
SLIDE 4

Co je “clean code”?

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 4 / 14

Bjarne Stroustrup, autor jazyka C++ a knihy “The C++ Programming Language”: I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.

slide-5
SLIDE 5

Co je “clean code”?

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 4 / 14

Bjarne Stroustrup, autor jazyka C++ a knihy “The C++ Programming Language”: I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well. Grady Booch, autor knihy “Object Oriented Analysis and Design with Applications”: Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.

slide-6
SLIDE 6

Co je “clean code”?

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 4 / 14

Bjarne Stroustrup, autor jazyka C++ a knihy “The C++ Programming Language”: I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well. Grady Booch, autor knihy “Object Oriented Analysis and Design with Applications”: Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control. Dave Thomas, zakladatel firmy OTI (pˇ revzata firmou IBM v roce 1996), kmotr Eclipse: Clean code can be read, and enhanced by a developer other than its

  • riginal author. It has unit and acceptance tests. It has meaningful names.

It provides one way rather than many ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API.

slide-7
SLIDE 7

ˇ Cistý kód v praxi

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 5 / 14

Jediné správné mˇ eˇ rítko kvality kódu: Co-to-k-ˇ certy za minutu

slide-8
SLIDE 8

Smysluplná jména

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 6 / 14

■ Vymyslet dobrá jména je velmi tˇ

ežké! Vˇ enujte tomu dostateˇ cnou pozornost!

■ Nebojte se jméno zmˇ

enit, pˇ rijdete-li na lepší!

■ Dobré jméno odhaluje autor˚

uv zámˇ er (intention-revealing). Pokud jméno vyžaduje komentᡠr, neodhaluje zámˇ

  • er. Porovnejte:

self.d = 0 # Elapsed time in days

self.elapsed_time_in_days = 0

■ Názvy tˇ

ríd: podstatná jména (s pˇ rívlastky):

Customer, WikiPage, AddressParser, Filter, StupidFilter, Corpus, TrainingCorpus

■ Názvy funkcí/metod: slovesa (s pˇ

redmˇ etem):

post_payment, delete_page, save, train, test, get_email

■ Jeden termín pro jeden koncept! Nepoužívejte stejné slovo k více úˇ

cel˚ um!

■ Nebojte se dlouhých jmen! ■ Dlouhé popisné jméno je lepší než dlouhý popisný komentáˇ

r.

ˇ Cím delší oblast platnosti promˇ enné, tím popisnˇ ejší jméno by mˇ ela mít.

■ Používejte pojmenované konstanty místo magických ˇ

císel v kódu!

slide-9
SLIDE 9

Eratostenovo síto: smysluplná jména

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 7 / 14

def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value >= 2: # There are some primes # Initialize the list (incl. 0) f = [True for i in range(max_value+1)] # Get rid of the known non-primes f[0] = f[1] = False # Run the sieve for i in range(2, len(f)): if f[i]: # i is still a candidate # mark its multiples as not prime for j in range(2*i, len(f), i): f[j] = False # Find the primes and put them in a list primes = [i for i in range(len(f)) if f[i]] return primes else: # max_value < 2 return list() # no primes, return empty list

slide-10
SLIDE 10

Eratostenovo síto: smysluplná jména

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 7 / 14

def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value >= 2: # There are some primes # Initialize the list (incl. 0) f = [True for i in range(max_value+1)] # Get rid of the known non-primes f[0] = f[1] = False # Run the sieve for i in range(2, len(f)): if f[i]: # i is still a candidate # mark its multiples as not prime for j in range(2*i, len(f), i): f[j] = False # Find the primes and put them in a list primes = [i for i in range(len(f)) if f[i]] return primes else: # max_value < 2 return list() # no primes, return empty list PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value >= 2: # There are some primes # Initialize the list (incl. 0) candidates = [ PRIME for i in range(max_value+1)] # Get rid of the known non-primes candidates[0] = candidates[1] = NONPRIME # Run the sieve for number in range(2, len(candidates)): if candidates[number]==PRIME: # mark its multiples as not prime for multiple in \ range(2*number, len(candidates), number): candidates[multiple] = NONPRIME # Find the primes and put them in a list primes = [i for i in range(len(candidates)) if candidates[i]==PRIME] return primes else: # max_value < 2 return list() # no primes, return empty list

Další smyslupná jména budou následovat!!!

slide-11
SLIDE 11

Komentᡠre

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 8 / 14

ˇ Cistý kód komentᡠre (skoro) nepotˇ rebuje!

■ Komentáˇ

re kompenzují naše selhání vyjádˇ rit se v prog. jazyce. Porovnej:

# Check to see if the employee is eligible for full benefits if (employee.flags & HOURLY_FLAG) and (employee.age > 65):

versus

if employee.is_eligible_for_full_benefits():

■ Komentáˇ

re lžou! Ne vždy a ne zámˇ ernˇ e, ale až pˇ ríliš ˇ casto!

■ Nepˇ

resné komentᡠre jsou horší než žádné komentᡠre!

■ Komentáˇ

re nenapraví špatný kód!

■ Dobré komentáˇ

re:

■ (do)vysvˇ

etlení, (do)upˇ resnˇ ení

■ zd˚

uraznˇ ení, varování pˇ red následky

■ TODOs ■ Špatné komentáˇ

re:

■ staré (už neplatné), bezvýznamné, nevhodné, redundantní, nebo zavádˇ

ející komentᡠre

■ komentáˇ

re z povinnosti

■ zakomentovaný kód ■ nelokální nebo nadbyteˇ

cné informace

slide-12
SLIDE 12

Eratostenovo síto: komentᡠre

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 9 / 14

# This function generates prime numbers up to # a user specified maximum. The algorithm # used is the Sieve of Eratosthenes. # # Eratosthenes of Cyrene, b. c. 276 BC, # Cyrene, Libya -- d. c. 194 BC, Alexandria. # The first man to calculate the circumference # of the Earth. Also known for working on # calendars with leap years and ran # the library at Alexandria. # # The algorithm is quite simple. # Given an array of integers starting at 2, # cross out all multiples of 2. # Find the next uncrossed integer, # and cross out all of its multiples. # Repeat until you have passed # the maximum value. # # @author hugo # @version 1

slide-13
SLIDE 13

Eratostenovo síto: komentᡠre

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 9 / 14

# This function generates prime numbers up to # a user specified maximum. The algorithm # used is the Sieve of Eratosthenes. # # Eratosthenes of Cyrene, b. c. 276 BC, # Cyrene, Libya -- d. c. 194 BC, Alexandria. # The first man to calculate the circumference # of the Earth. Also known for working on # calendars with leap years and ran # the library at Alexandria. # # The algorithm is quite simple. # Given an array of integers starting at 2, # cross out all multiples of 2. # Find the next uncrossed integer, # and cross out all of its multiples. # Repeat until you have passed # the maximum value. # # @author hugo # @version 1 # This function generates prime numbers up to # a user specified maximum. The algorithm # used is the Sieve of Eratosthenes. # Given an array of integers starting at 2, # cross out all multiples of 2. # Find the next uncrossed integer, # and cross out all of its multiples. # Repeat until you have passed # the maximum value. # # @author hugo # @version 1

Za chvíli se zbavíme dalších komentᡠr˚ u!

slide-14
SLIDE 14

Funkce a metody

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 10 / 14

■ Funkce by mˇ

ely být krátké! (A ještˇ e kratší!)

■ Funkce by mˇ

ela dˇ elat právˇ e 1 vˇ ec a mˇ ela by ji dˇ elat dobˇ

  • re. (A bez vedlejších efekt˚

u.)

■ Funkce dlouhé ménˇ

e než 5 ˇ rádk˚ u:

■ Vˇ

etšinou dˇ elají právˇ e 1 vˇ ec.

■ Mohou mít pˇ

resné a výstižné jméno.

■ Nemohou obsahovat vnoˇ

rené pˇ ríkazy if, for, . . .

■ Bloky uvnitˇ

r pˇ ríkaz˚ u if, for, . . . jsou pouze 1 ˇ rádek dlouhé

■ Krátké funkce umožˇ

nují testovat dílˇ cí ˇ cásti algoritmu!

■ Sekce uvnitˇ

r funkcí/metod:

■ Jasná indikace toho, že funkce/metoda nedˇ

elá jen 1 vˇ ec a mˇ ela by být rozdˇ elena.

■ Argumenty funkcí/metod: ■ Udržujte jejich poˇ

cet malý! 0, 1, 2, výjimeˇ cnˇ e 3.

■ Vytvoˇ

rte jméno tak, aby evokovalo poˇ radí argument˚ u.

■ Boolovské argumenty funkcí ˇ

casto znaˇ cí, že funkce nedˇ elá 1 vˇ ec! Rozdˇ elte ji.

slide-15
SLIDE 15

Eratostenovo síto: funkce

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 11 / 14

PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value >= 2: # There are some primes # Initialize the list (incl. 0) candidates = [ PRIME for i in range(max_value+1)] # Get rid of the known non-primes candidates[0] = candidates[1] = NONPRIME # Run the sieve for number in range(2, len(candidates)): if candidates[number]==PRIME: # mark its multiples as not prime for multiple in \ range(2*number, len(candidates), number): candidates[multiple] = NONPRIME # Find the primes and put them in a list primes = [i for i in range(len(candidates)) if candidates[i]==PRIME] return primes else: # max_value < 2 return list() # no primes, return empty list

slide-16
SLIDE 16

Eratostenovo síto: funkce

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 11 / 14

PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value >= 2: # There are some primes # Initialize the list (incl. 0) candidates = [ PRIME for i in range(max_value+1)] # Get rid of the known non-primes candidates[0] = candidates[1] = NONPRIME # Run the sieve for number in range(2, len(candidates)): if candidates[number]==PRIME: # mark its multiples as not prime for multiple in \ range(2*number, len(candidates), number): candidates[multiple] = NONPRIME # Find the primes and put them in a list primes = [i for i in range(len(candidates)) if candidates[i]==PRIME] return primes else: # max_value < 2 return list() # no primes, return empty list PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value < 2: return [] else: candidates = init_integers_up_to(max_value) mark_non_primes(candidates) return collect_remaining(candidates) def init_integers_up_to(max_value): return [PRIME for i in range(max_value+1)] def mark_non_primes(candidates): # Mark 0 and 1, they are not primes. candidates[0] = candidates[1] = NONPRIME for number in range(2, len(candidates)): if candidates[number] == PRIME: mark_as_not_prime_multiples_of(number, candidates def mark_as_not_prime_multiples_of(number, candidates): for multiple in range(2*number, len(candidates), number): candidates[multiple] = NONPRIME def collect_remaining(candidates): primes = [i for i in range(len(candidates)) if candidates[i]==PRIME] return primes

slide-17
SLIDE 17

Eratostenovo síto: pˇ revod na tˇ rídu

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 12 / 14

PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value < 2: return [] else: candidates = init_integers_up_to(max_value) mark_non_primes(candidates) return collect_remaining(candidates) def init_integers_up_to(max_value): return [PRIME for i in range(max_value+1)] def mark_non_primes(candidates): # Mark 0 and 1, they are not primes. candidates[0] = candidates[1] = NONPRIME for number in range(2, len(candidates)): if candidates[number] == PRIME: mark_as_not_prime_multiples_of(number, candidates) def mark_as_not_prime_multiples_of(number, candidates): for multiple in range(2*number, len(candidates), number): candidates[multiple] = NONPRIME def collect_remaining(candidates): primes = [i for i in range(len(candidates)) if candidates[i]==PRIME]

slide-18
SLIDE 18

Eratostenovo síto: pˇ revod na tˇ rídu

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 12 / 14

PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Find primes up to the max_value using the Sieve of Eratosthenes. """ if max_value < 2: return [] else: candidates = init_integers_up_to(max_value) mark_non_primes(candidates) return collect_remaining(candidates) def init_integers_up_to(max_value): return [PRIME for i in range(max_value+1)] def mark_non_primes(candidates): # Mark 0 and 1, they are not primes. candidates[0] = candidates[1] = NONPRIME for number in range(2, len(candidates)): if candidates[number] == PRIME: mark_as_not_prime_multiples_of(number, candidates) def mark_as_not_prime_multiples_of(number, candidates): for multiple in range(2*number, len(candidates), number): candidates[multiple] = NONPRIME def collect_remaining(candidates): primes = [i for i in range(len(candidates)) if candidates[i]==PRIME] PRIME = True NONPRIME = False class PrimesGenerator: """Prime numbers generator.""" def __init__(self): self.candidates = [] self.max = None def get_primes_up_to(self, max_value): """Return list of primes up to the max_value.""" if max_value < 2: return [] self.max = max_value+1 self.init_candidates_up_to_max_value() self.mark_non_prime_candidates() return self.collect_remaining_candidates() def init_candidates_up_to_max_value(self): self.candidates = [PRIME for i in range(self.max)] def mark_non_prime_candidates(self): # Cross out 0 and 1, they are not primes. self.candidates[0] = self.candidates[1] = NONPRIME for number in range(2, int(self.max**0.5)+1): if self.candidates[number]==PRIME: self.mark_as_not_prime_multiples_of(number) def mark_as_not_prime_multiples_of(self, number): for multiple in range(2*number, self.max, number): self.candidates[multiple] = NONPRIME def collect_remaining_candidates(self): return [i for i in range(self.max) if self.candidates[i]==PRIME]

slide-19
SLIDE 19

Eratostenovo síto: funkce a tˇ rída?

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 13 / 14

PRIME = True NONPRIME = False class PrimesGenerator: """Prime numbers generator.""" def __init__(self): self.candidates = [] self.max = None def get_primes_up_to(self, max_value): """Return list of primes up to the max_value.""" if max_value < 2: return [] self.max = max_value+1 self.init_candidates_up_to_max_value() self.mark_non_prime_candidates() return self.collect_remaining_candidates() def init_candidates_up_to_max_value(self): self.candidates = [PRIME for i in range(self.max)] def mark_non_prime_candidates(self): # Cross out 0 and 1, they are not primes. self.candidates[0] = self.candidates[1] = NONPRIME for number in range(2, int(self.max**0.5)+1): if self.candidates[number]==PRIME: self.mark_as_not_prime_multiples_of(number) def mark_as_not_prime_multiples_of(self, number): for multiple in range(2*number, self.max, number): self.candidates[multiple] = NONPRIME def collect_remaining_candidates(self): return [i for i in range(self.max) if self.candidates[i]==PRIME]

slide-20
SLIDE 20

Eratostenovo síto: funkce a tˇ rída?

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 13 / 14

PRIME = True NONPRIME = False class PrimesGenerator: """Prime numbers generator.""" def __init__(self): self.candidates = [] self.max = None def get_primes_up_to(self, max_value): """Return list of primes up to the max_value.""" if max_value < 2: return [] self.max = max_value+1 self.init_candidates_up_to_max_value() self.mark_non_prime_candidates() return self.collect_remaining_candidates() def init_candidates_up_to_max_value(self): self.candidates = [PRIME for i in range(self.max)] def mark_non_prime_candidates(self): # Cross out 0 and 1, they are not primes. self.candidates[0] = self.candidates[1] = NONPRIME for number in range(2, int(self.max**0.5)+1): if self.candidates[number]==PRIME: self.mark_as_not_prime_multiples_of(number) def mark_as_not_prime_multiples_of(self, number): for multiple in range(2*number, self.max, number): self.candidates[multiple] = NONPRIME def collect_remaining_candidates(self): return [i for i in range(self.max) if self.candidates[i]==PRIME] PRIME = True NONPRIME = False def generate_primes_up_to(max_value): """Return a list of primes up to the max_value.""" if max_value < 2: return [] candidates = CandidateNumberList(max_value) candidates.checkout_multiples() return candidates.collect_remaining() class CandidateNumberList: """List of boolean values for use in the Sieve of Eratost Shall be used with the generate_primes_up_to function. """ def __init__(self, max_value): self.max = max_value + 1 self.candidates = [PRIME for i in range(self.max)] self.candidates[0] = self.candidates[1] = NONPRIME def checkout_multiples(self): """Mark multiples of all prime numbers as not prime." for number in range(2, int(self.max**0.5)+1): if self.candidates[number] == PRIME: self.checkout_multiples_of(number) def checkout_multiples_of(self, number): """Mark multiples of number as not prime.""" for multiple in range(2*number, self.max, number): self.candidates[multiple] = NONPRIME def collect_remaining(self): """Return a list of remaining candidates, they are pr return [i for i in range(self.max) if self.candidates[i]==PRIME]

slide-21
SLIDE 21

Závˇ er

Clean Code

  • Který kód je ˇ

cistší? A proˇ c?

  • Co je “clean code”?
  • ˇ

Cistý kód v praxi

  • Smysluplná jména
  • Eratostenovo síto:

smysluplná jména

  • Komentáˇ

re

  • Eratostenovo síto:

komentᡠre

  • Funkce a metody
  • Eratostenovo síto:

funkce

  • Eratostenovo síto:

pˇ revod na tˇ rídu

  • Eratostenovo síto:

funkce a tˇ rída?

  • Závˇ

er

  • P. Pošík c

2012 A4B99RPH: ˇ Rešení problém˚ u a hry – 14 / 14

ˇ Cistý kód je subjektivní pojem, pˇ resto by se o nˇ ej mˇ el každý programátor snažit.

ˇ Cistý kód by mˇ el být pˇ redevším ˇ citelný (skoro jako v pˇ rirozeném jazyce).

■ 80 % ˇ

cistého kódu jsou správnˇ e zvolená jména!

■ Vhodná jména lze volit, jsou-li funkce/metody dostateˇ

cnˇ e krátké!

■ Opakují-li se ve vašem programu stejné nebo podobné kusy kódu, prakticky vždy je

možné takový kód definovat jako samostatnou funkci/metodu.