Navigacija
Lista poslednjih: 16, 32, 64, 128 poruka.

Zadaci za wannabe pythoniste

[es] :: Python :: Zadaci za wannabe pythoniste

Strane: << < .. 25 26 27 28 29 30 31 32

[ Pregleda: 50983 | Odgovora: 629 ] > FB > Twit

Postavi temu Odgovori

Autor

Pretraga teme: Traži
Markiranje Štampanje RSS

djoka_l
Beograd

Član broj: 56075
Poruke: 3445

Jabber: djoka_l


+1462 Profil

icon Re: Zadaci za wannabe pythoniste08.05.2020. u 08:35 - pre 47 meseci
HINT:
Code:

py
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(sorted( [ ('cad', '1'), ('bat', '1'), ('aa','1') ] ));
[('aa', '1'), ('bat', '1'), ('cad', '1')]
>>> quit();
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste09.05.2020. u 17:51 - pre 47 meseci
Baš me namuči ovaj zadatak.
Lupao glavu, ali nisam uspeo da rešim sve slučajeve,
čak ni uz pomoć Đokinog hinta.

Sve što sam napravio je seckanje stringa i zamena mesta imena i ekstenzije, pa sortiranje.
Ali ostaje mi problem kad ima više fajlova bez imena.

Code:
def sort_by_ext(files):
    b = []
    for i in files:
        b.append(i.split('.'))
    # [['1', 'cad'], ['1', 'bat'], ['1', 'aa'], ['2', 'bat']]
    d = []
    for i in range(len(b)):
        d.append([b[i][1]] + [b[i][0]])
    # d = [['aa', '1'], ['bat', '1'], ['cad', '1'], ['bat', '2']]
    e = []
    e = sorted(d, key=lambda x: x[0])
    [['aa', '1'], ['bat', '1'], ['bat', '2'], ['cad', '1']]

    f = []
    for i in range(len(e)):
        f.append(e[i][1] + '.' + e[i][0])
    # f = ['1.aa', '1.bat', '2.bat', '1.cad']

    for i in range(len(f)):
        if f[i][0] == '.':
            a = f[i]
            f.remove(a)
            f.insert(0, a)
            break

    return f
 
Odgovor na temu

djoka_l
Beograd

Član broj: 56075
Poruke: 3445

Jabber: djoka_l


+1462 Profil

icon Re: Zadaci za wannabe pythoniste09.05.2020. u 18:52 - pre 47 meseci
Vrati se lepo na tvoju knjigu na odeljak o tipovima podataka. Pogledaj ponovo tip TUPLE.

>>> print(sorted( [(3,2,1), (3,1,2), (2,3,1), (2,1,3), (1,2,3), (1,3,2)] ));
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Obrati pažnjuj na to kako se tuple list sortira - prvo po prvom elementu, pa po drugom ... pa po poslednjem
Jedno vreme si se uhvatio za disctionary, pa si sve rešavao sa tim, posle si sve radio sa fajlovima, sada sve sa listama.
Kada bi jedan tip podatka bio dovoljan, ne bi pisci jezika izmišljali sve ove druge tipove.

Drugo, pogledaj split odnosno rsplit funkcije. Postoji parametar koji kaže na koliko elemenata se lista splituje. A možeš da izabereš i da li ćeš da splituješ s leva u desno ili s desna u levo.

Treće, reši onaj deo koji znaš. Kada budeš našao na primer koji ne znaš, onda zakukaj...

>>> print('a.b.c.d'.rsplit('.',1));
['a.b.c', 'd']
 
Odgovor na temu

djoka_l
Beograd

Član broj: 56075
Poruke: 3445

Jabber: djoka_l


+1462 Profil

icon Re: Zadaci za wannabe pythoniste09.05.2020. u 19:53 - pre 47 meseci
Code:
def SplitFileName( fn ):
  t=[]
  try:
    i=fn[1::].index('.')
  except:
    t=['', fn]
  else:
    t= [fn.rsplit('.',1)[1], fn]
    
  return t

print(SplitFileName('.config'))
print(SplitFileName('test.bat'))
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste10.05.2020. u 14:18 - pre 47 meseci
Hvala za primer!

Samo ne razumem čemu ova varijabla "i" u 4. redu!?
dalje je nigde nema u funkciji.
Jel to u stvari treba da bude "t"?
Ali mi onda opet nije jasno svrha kad za drugi string dobiješ index = 3
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste10.05.2020. u 14:21 - pre 47 meseci
Citat:
djoka_l:
Vrati se lepo na tvoju knjigu na odeljak o tipovima podataka. Pogledaj ponovo tip TUPLE.

>>> print(sorted( [(3,2,1), (3,1,2), (2,3,1), (2,1,3), (1,2,3), (1,3,2)] ));
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Obrati pažnjuj na to kako se tuple list sortira - prvo po prvom elementu, pa po drugom ... pa po poslednjem


Nisam razmišljao tuplama, jer su nepromenljive, a sortiranje je isto kao i kod liste lista.

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
 
Odgovor na temu

djoka_l
Beograd

Član broj: 56075
Poruke: 3445

Jabber: djoka_l


+1462 Profil

icon Re: Zadaci za wannabe pythoniste10.05.2020. u 18:53 - pre 47 meseci
i samo služi za to da se podigne exception, ako u stringu postoji samo jedna tačka na prvom mestu.

Ako se exception desi (ne postoji tačka u nazivu fajla osim, možda, na prvom mestu), onda je ekstenzija prazan string, a naziv fajla ceo sadržaj varijable:
t=['', fn]

Ako se exception ne desi, onda se ide na else deo, pa se za ekstenziju uzima POSLEDNJI string posle tačke (rsplit, - sa desne strane se string splituje po tačkama, ali se uzima samo dva stringa, prvi string je sve do poslednje tačke, a drugi strig ono što je posle poslednje tačke), a naziv fajla je ceo fn:
t= [fn.rsplit('.',1)[1], fn]

fn.rsplit('.',1)[0] zanemarujem, uopšte mi nije potreban

'a.b.c.d'.rsplit('.',1) bi dao
['a.b.c', 'd']

ali mi a.b.c nije potrebno

Rezultat fiunkcije je lista od dva stringa, prvi strig je ekstenzija, drugi string je naziv fajla (s tim što ekstenzija može da bude prazan string)
 
Odgovor na temu

Panta_
Aleksandar Pantić
Kragujevac

Član broj: 214959
Poruke: 790



+162 Profil

icon Re: Zadaci za wannabe pythoniste12.05.2020. u 09:44 - pre 47 meseci
Citat:
Baš me namuči ovaj zadatak.
Lupao glavu, ali nisam uspeo da rešim sve slučajeve,
čak ni uz pomoć Đokinog hinta.

Sve što sam napravio je seckanje stringa i zamena mesta imena i ekstenzije, pa sortiranje.
Ali ostaje mi problem kad ima više fajlova bez imena.


Sorted funkcija ima key parametar kome prosleđuješ funkciju koja treba da vrati ime fajla ako isti nema ili ima istu ekstenziju, ili u suprotnom ekstenziju, na primer:
Code:
files = ['1.cad', '1.bat', '1.aa', '.aa.doc', 'config.', '.bat', 'table.imp.xls', '.imp.xls']

sorted(files, key=tvoja_funkcija)

['.bat', '.imp.xls', 'config.', '1.aa', '1.bat', '1.cad', '.aa.doc', 'table.imp.xls']


Dakle, prvo proveriš da li fajl ima ekstenziju, ako da, proveriš da li ima još neki fajl sa istom ekstenzijom u files listi, ako da, vratiš ime fajla, ili u suprotnom ekstenziju. Obrati pažnju da se fajlovi koji počinju tačkom sortiraju ispred onih koji počinju alpha ili num karakterom.
Code:
sorted(['a', 'c', 'b', '1', '.'])

['.', '1', 'a', 'b', 'c']
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste12.05.2020. u 14:06 - pre 47 meseci
uklavirio sam kako da proverim da li ima fajlova sa i bez ekstenzije i da ih sortiram, kao što je ovaj slučaj

Code:
def lista(fajlovi):
    nema_ext = []
    ima_ext = []
    for i in fajlovi:
        if i.rsplit('.', 1)[0] == '':
            nema_ext.append(i)
        else:
            ima_ext.append(i)
    print(sorted(nema_ext) + sorted(ima_ext))

lista(['1.cad', '1.bat', '.aa', '.bat'])


['.aa', '.bat', '1.bat', '1.cad']

ali i dalje mi nije jasno kako grupišem fajlove sa istom ekstenzijom.
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste14.05.2020. u 09:29 - pre 47 meseci
Zadatak broj 39:

Podeli string dužine 0 < str < 100 u delove po dva znaka. Ako je broj znakova u stringu neparan, poslednjem znaku dodaj _ da bi napravio par.

Code:
def split_pairs(a):
    your code here 
    return something


if __name__ == '__main__':
    print("Example:")
    print(list(split_pairs('abcd')))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert list(split_pairs('abcd')) == ['ab', 'cd']
    assert list(split_pairs('abc')) == ['ab', 'c_']
    assert list(split_pairs('abcdf')) == ['ab', 'cd', 'f_']
    assert list(split_pairs('a')) == ['a_']
    assert list(split_pairs('')) == []
    print("Coding complete? Click 'Check' to earn cool rewards!")


Moje rešenje je ovde.

 
Odgovor na temu

bokinet

Član broj: 29844
Poruke: 574



+50 Profil

icon Re: Zadaci za wannabe pythoniste14.05.2020. u 09:49 - pre 47 meseci
proveris da li je parni ili neparni,
dodas po potrebi da bude na dvojcicu,
i onda veslas kao da je sve sa dvojcicom devojcicom.
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste16.05.2020. u 07:36 - pre 47 meseci
Zadatak broj 40:


# In a given word you need to check if one symbol goes right after another.
# Cases you should expect while solving this challenge:
# If more than one symbol is in the list you should always count the first one
# one of the symbols are not in the given word - your function should return False;
# any symbol appears in a word more than once - use only the first one;
# two symbols are the same - your function should return False;
# if the first instance of the second symbol comes before the first one, that should return False
# the condition is case sensitive, which mease 'a' and 'A' are two different symbols.

# Input: Three arguments. The first one is a given string, second is a symbol that shoud go first, and the third is a symbold that should go after the first one.
# Output: A bool.


Code:
def goes_after(word: str, first: str, second: str) -> bool:
 
    "tvoj kod ovde"

    return False/True


if __name__ == '__main__':
    print("Example:")
    print(goes_after('world', 'w', 'o'))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert goes_after('world', 'w', 'o') == True
    assert goes_after('world', 'w', 'r') == False
    assert goes_after('world', 'l', 'o') == False
    assert goes_after('panorama', 'a', 'n') == True
    assert goes_after('list', 'l', 'o') == False
    assert goes_after('', 'l', 'o') == False
    assert goes_after('list', 'l', 'l') == False
    assert goes_after('world', 'd', 'w') == False
    assert goes_after('almaz', 'm', 'a') == False
    print("Coding complete? Click 'Check' to earn cool rewards!")


Moje rešenje ovde
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste17.05.2020. u 03:29 - pre 47 meseci
Zadatak broj 41

Ovaj zadatak je sličan prethodnom, ali teži. Treba pronaći reč u višelinijskom u tekstu, horizontalno ili vertikalno i dati njene koordinate.
Napravio sam nešto ovako za horizontalni slučaj, ali za vertikalni nisam baš siguran kako da rešim.

# You are given a rhyme (a multiline string), in which lines are separated by "newline" (\n).
# Casing does not matter for your search, but whitespaces should be removed before your search.
# You should find the word inside the rhyme in the horizontal (from left to right) or vertical
# (from up to down) lines. For this you need envision the rhyme as a matrix (2D array). Find
# the coordinates of the word in the cut rhyme (without whitespaces).

# The result must be represented as a list -- [row_start,column_start,row_end,column_end], where
# row_start is the line number for the first letter of the word.
# column_start is the column number for the first letter of the word.
# row_end is the line number for the last letter of the word.
# column_end is the column number for the last letter of the word.
# Counting of the rows and columns start from 1.

# Input: Two arguments. A rhyme as a string and a word as a string (lowercase).
# Output: The coordinates of the word.
# Precondition: The word is given in lowercase
# 0 < |word| < 10
# 0 < |rhyme| < 300

Code:
def checkio(text, word):
    novi = text.strip().replace(' ', '')
    reci = novi.split('\n')
    red = 1
    indeks = 1
    spisak1 = []
    spisak2 = []
    duzina = len(word)
    vert = ''

    for i in novi:
        indeks += 1
        if i == word[0]:
            spisak1.append(red)
            spisak2.append(indeks)
            if reci[red-1][indeks-1:indeks-1+duzina] == word:
                return [int(spisak1[0]), int(spisak2[0]), int(spisak1[0]), int(spisak2[0])+duzina-1]
                break

        if i == '\n':
            red += 1
            indeks = 0


# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio("""DREAMING of apples on a wall,
    And dreaming often, dear,
    I dreamed that, if I counted all,
    -How many would appear?""", "ten") == [2, 14, 2, 16]
    assert checkio("""He took his vorpal sword in hand:
    Long time the manxome foe he sought--
    So rested he by the Tumtum tree,[/quote]
    And stood awhile in thought.
    And as in uffish thought he stood,
    The Jabberwock, with eyes of flame,
    Came whiffling through the tulgey wood,
    And burbled as it came!""", "noir") == [4, 16, 7, 16]
 
Odgovor na temu

mjanjic
Šikagou

Član broj: 187539
Poruke: 2679



+690 Profil

icon Re: Zadaci za wannabe pythoniste17.05.2020. u 19:04 - pre 47 meseci
Pa za vertikalan slučaj je slična petlja, samo što uzimaš slova po vertikali u reci[][], tj. u unutrašnjoj petlji je drugi indeks konstantan, a menjaš prvi. Međutim, nisu ti sve "vrste" iste dužine.

Možda bi bilo najjednostavnije konvertovati slova u numeričke ekvivalente 1-26, formirati dvodimenzionu matricu na osnovu teksta, s tim što se stavi 0 tamo gde nema dovoljno teksta - broj kolona je dužina najduže "reči", tj. stiha.

Tada može numpy paketom lako da se manipuliše vrstama i kolonama, pa je lakše pretraživati niz brojeva po koloni koji je jedna nizu numeričkih ekvivalenata za traženu reč.


Dosta bi bilo nezgodnije da treba u samoj pesmi naći reči koje se rimuju, a da se traži isto ovako po "vertikali".
Blessed are those who can laugh at themselves, for they shall never cease to be amused.
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste18.05.2020. u 08:05 - pre 47 meseci
Nema veze što su redovi nejednake dužine, svaki kreće od 0. Važne su kolone

U principu mi je jasno i za vertikalnu reč. Kada jednom nađem koordinatu prvog slova u reči,
idem nadole, red po red, po istoj koloni. Nešto ovako.
Ali iz nekog razloga ne ispada onako kako treba.

Code:
def checkio(text, word):
    novi = text.replace(' ', '').strip().split('\n')
    red = 1
    indeks = 1
    spisak1 = []
    spisak2 = []
    vert1 = []
    vert2 = []
    duzina = len(word)
    vert = ''

    for i in novi:
        for j in i:
            indeks += 1
            if j == word[0]:
                spisak1.append(red)
                spisak2.append(indeks)
                if novi[red-1][indeks-1:indeks-1+duzina] == word:
                    return [int(spisak1[0]), int(spisak2[0]), int(spisak1[0]), int(spisak2[0])+duzina-1]
                    break
        else:
            for s in novi:
                for t in s:
                    indeks += 1
                    if i == word[0]:
                        vert1.append(red)
                        vert2.append(indeks)
                        for v in range(len(word)):
                            vert += reci[red+v][indeks]
                            return [int(vert1[0]), int(vert2[0]), int(vert1[0]), int(vert2[0+len(word)])]
        
        if i == '\n':
            red += 1
            indeks = 0


# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio("""DREAMING of apples on a wall,
And dreaming often, dear,
I dreamed that, if I counted all,
-How many would appear?""", "ten") == [2, 14, 2, 16]
    assert checkio("""He took his vorpal sword in hand:
Long time the manxome foe he sought--
So rested he by the Tumtum tree,[/quote]
And stood awhile in thought.
And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!""", "noir") == [4, 16, 7, 16]

 
Odgovor na temu

djoka_l
Beograd

Član broj: 56075
Poruke: 3445

Jabber: djoka_l


+1462 Profil

icon Re: Zadaci za wannabe pythoniste18.05.2020. u 08:37 - pre 47 meseci
Ovaj kod ti je tako neuredan da je problem da se prati logika programa.
Opet pokazuješ svoju staru slabost: NE RAZUMEŠ STRUKTURE PODATAKA...

Uzmimo, kao primer, varijable spsiak1 i spisak2.

Zašto su one liste?
Šta stavljaš u listu?
Zašto radiš konverziju u int?

Kada se prođe kroz tvoj kod, jasno je da se u LISTE stavlja samo JEDNA vrednost, pa ti lista ni ne treba!
Jasno je da se u listu stavlja int, pa je konverzija NEPOTREBNA.
Jasno je da se varijablama spisak1 i spsisak2 uvek dodeljuje vrednosti red i indeks, PA TI TE VARIJABLE NI NE TREBAJU!

Code:

Umesto:

            if j == word[0]:
                spisak1.append(red)
                spisak2.append(indeks)
                if novi[red-1][indeks-1:indeks-1+duzina] == word:
                    return [int(spisak1[0]), int(spisak2[0]), int(spisak1[0]), int(spisak2[0])+duzina-1]
                    break

TREBA:

            if j == word[0]:
                if novi[red-1][indeks-1:indeks-1+duzina] == word:
                    return [red, indeks, red, indeks+duzina-1]
                    break


Pa onda imaš jedna ELSE koji nije poravnat sa IF. Bezveze se pojavio.
Pa onda imaš ovaj biser - porediš i sa novim redom, a znake za novi red si na početku izbacio:
Code:
        if i == '\n':
            red += 1
            indeks = 0



Čak ti u zadatku stoji sugestija da koristiš MATRICU, ali ti od matrice bežiš kao đavo od krsta, zato što nisi naučio da koristiš matrice.
 
Odgovor na temu

mjanjic
Šikagou

Član broj: 187539
Poruke: 2679



+690 Profil

icon Re: Zadaci za wannabe pythoniste18.05.2020. u 13:58 - pre 47 meseci
Da, sa matricama može da koristi numpy paket u kome može lako da radi direktno sa kolonama, ali kada konvertuje tekst u numeričke elemente matrice, mora da dopuni sve vrste koje su kraće od najduže vrste.
Može i sa običnim Python array da se radi, ali je sa numpy dosta lakše jer može da izdvoji kolonu (npr. textArray[ : , column_index]), pa može na pretragu po traženoj reči da primeni istu funkciju koju koristi za pretragu po vrsti.
Blessed are those who can laugh at themselves, for they shall never cease to be amused.
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste18.05.2020. u 14:30 - pre 47 meseci
Hvala Đoko na sugestijama.
Ispravio, ali ne radi i dalje.

@mjanjic nije predviđeno da se koristi numpy.

Idemo dalje...

Zadatak broj 42: Ptičiji jezik

Today the bird spoke its first word: "hieeelalaooo". This sounds a lot like "hello", but with too many vowels. Stephan asked Nikola for help and he helped to examine how the bird changes words. With the information they discovered, we should help them to make a translation module.
The bird converts words by two rules:

- after each consonant letter the bird appends a random vowel letter (l ⇒ la or le);
- after each vowel letter the bird appends two of the same letter (a ⇒ aaa);

Vowels letters == "aeiouy".

You are given an ornithological phrase as several words which are separated by white-spaces (each pair of words by one whitespace). The bird does not know how to punctuate its phrases and only speaks words as letters. All words are given in lowercase. You should translate this phrase from the bird language to something more understandable.

Input: A bird phrase as a string.
Output: The translation as a string.

Code:
def translate(phrase):
  
   "your code here"

    return output


if __name__ == '__main__':
    print("Example:")
    print(translate("hieeelalaooo"))

    # These "asserts" using only for self-checking and not necessary for auto-testing
    assert translate("hieeelalaooo") == "hello", "Hi!"
    assert translate("hoooowe yyyooouuu duoooiiine") == "how you doin", "Joey?"
    assert translate("aaa bo cy da eee fe") == "a b c d e f", "Alphabet"
    assert translate("sooooso aaaaaaaaa") == "sos aaa", "Mayday, mayday"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")


Moje rešenje je ovde.
 
Odgovor na temu

B3R1
Berislav Todorovic
NL

Član broj: 224915
Poruke: 794



+630 Profil

icon Re: Zadaci za wannabe pythoniste18.05.2020. u 16:08 - pre 46 meseci
Vezano za zadatak 41 - koristis previse promenljivih koje ne sluze nicemu i tesko mozes da pohvatas gde je sta. Potrebna ti je samo jedna lista, koju dobijas split() funkcijom, sto si vec lepo uradio. Nazovimo je rows (to je ovo sto ti zoves 'novi'). Takodje, ja bih dodao i funkciju lower(), kojom eliminises mala/velika slova (tekst zadatka kaze "case is not important"):
Code (python):
rows = text.replace(' ', '').split('\n').lower()

Ta lista vec sadrzi linije teksta, koje su obicni stringovi, unutar kojih rec definisanu promenljivom word trazis funkcijom find(). Funkcija find() vraca poziciju stirnga unutar veceg stringa, pa imas:
Code (python):

>>> verse = 'The woods are lovely, dark and deep'
>>> verse.find('wood')
4
>>> verse.find('forest')
-1
 

Time resavas skeniranje teksta po horizontali. Ostaje da resis skeniranje po vertikali, sto nije toliko slozeno, imajuci u vidu da svakom slovu unutar stringa mozes da pridjes po njegovom indeksu. Na primer, ako ti rows sadrzi:
Code (python):
rows = [ 'thewoodsarelovely,darkanddeep', 'butihavepromisestokeep,', 'andmilestogobeforeisleep,' 'andmilestogobeforeisleep.' ]

Tada ti je rows[0][1] == 'h' (drugo slovo prvog reda). Znaci, nisu ti potrebni nikakvi indeksi. Jedini problem je sto su elementi liste nejednake duzine, tako da najpre moras da odredis najvecu duzinu elementa liste koja ce ti odrediti opseg skeniranja. Dobijas kod u formi:

Code (python):

def checkio (text, word):
    rows = text.replace(' ', '').split('\n')   # Smesta linije teksta u listu rows

    # Najpre odredimo maksimalnu duzinu linije
    max_len = 0
    for row in rows:
        if (len(row)>max_len):
            max_len = len(row)

    # Iteracija po vertikali, slovo po slovo svakog reda, do maksimalne duzine reda
    for j in range(0,max_len):
        col = '' # Ovde smestamo kolone teksta
        for i,row in enumerate(rows):
            if (j >= len(row)):
                continue
            col += row[j]   # Slovo na poziciji 'j' unutar stringa 'row'
        # col - ce sadrzati celu kolonu teksta
 

Ostaje ti da nadjes poziciju reci u stringovima row i col. Tu imas dve ideje. Onako skolski, pocetnicki bi bilo da kolone smestas u posebnu listu (npr. cols), koju inicijalizujes na pocetku i kada formiras kolonu (col) na kraju ovog koda gore dodas:
Code (python):

        if (col):
            cols.append(col)
 

U nastavku koda onda ponovo iteriras po svim vrstama i svim kolonama i koristis funkciju find(). To je korektno resenje, ali time nepotrebno ponovo ulazis u petlju. Da ustedis vreme, pretrazivanje stringova mozes da radis vec i u petljama gore. Prva petlja iterira po kolonama, druga za svaku kolonu skenira vrste od 0 do len(rows). U principu, dovoljno je ispitati vrste samo jednom i idealno je to uraditi tokom skeniranja prve kolone. Slicno tome, skeniranje kolone je najbolje uraditi kada se kolona formira. Time kod postaje (nisam testirao, ali mislim da je ok):
Code (python):

def checkio (text, word):
    rows = text.replace(' ', '').split('\n')   # Smesta linije teksta u listu rows

    # Najpre odredimo maksimalnu duzinu linije
    max_len = 0
    for row in rows:
        if (len(row)>m):
            max_len = len(row)

    # Iteracija po vertikali, slovo po slovo svakog reda
    for j in range(0,max_len):
        col = '' # Ovde smestamo kolone teksta
        for i,row in enumerate(rows):
            if (j == 0): # Tokom formiranja prve kolone skeniramo vrstu
                pos = row.find(word)
                if (pos >= 0):
                    return [ i, pos, i, pos+len(word)-1 ]
            if (j >= len(row)):
                continue
            col += row[j]
        pos = col.find(word)
        if (pos >= 0):
            return [ pos, j, pos+len(word)-1, j ]
    return []
 

Moze li to bolje? Moze! Recimo, ako se rec ne nalazi uopste u tekstu zasto bismo je trazili u svakom redu? Na samom pocetku funkcije treba onda dodati:
Code (python):
def checkio (text, word):
    search_rows = word in text
 

I onda u liniji gde ispitujemo da li je j == 0 izmeniti:
Code (python):

            if ((j == 0) and search_rows): # Tokom formiranja prve kolone skeniramo vrstu, samo ako je search_row == True
 

Zadatak moze da se malcice uopsti i da se traze sve koordinate gde se zadata rec nalazi ... i da se to vraca u formi:
[ [ x1, y1, z1, u1 ], [ x2, y2, z2, u2 ], ... ]

To ti ostavljam za domaci ...

[Ovu poruku je menjao B3R1 dana 18.05.2020. u 19:27 GMT+1]
 
Odgovor na temu

a1234567

Član broj: 46801
Poruke: 297
65.18.117.*



+3 Profil

icon Re: Zadaci za wannabe pythoniste20.05.2020. u 16:16 - pre 46 meseci
Hvala Berislave na detaljnom objašnjenju.
Sad mi je jasno i ne izgleda teško :))

Vidi se da imaš pedagoški dar. Treba da praviš tutoriale za python na youtube :))


Idemo dalje, zadatak broj 43:

# Joe Palooka has fat fingers, so he always hits the “Caps Lock” key whenever he actually intends
# to hit the key “a” by itself. (When Joe tries to type in some accented version of “a” that needs
# more keystrokes to conjure the accents, he is more careful in the presence of such raffinated
# characters ([Shift] + [Char]) and will press the keys correctly.) Compute and return the result
# of having Joe type in the given text. The “Caps Lock” key affects only the letter keys from “a”
# to “z” , and has no effect on the other keys or characters. “Caps Lock” key is assumed to be
# initially off.

# Input: A string. The typed text.
# Output: A string. The showed text after being typed.


Code:
def caps_lock(text: str) -> str:
   "your code here"
    return string


if __name__ == '__main__':
    print("Example:")
    print(caps_lock("Why are you asking me that?"))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert caps_lock(
        "Why are you asking me that?") == "Why RE YOU sking me thT?"
    assert caps_lock(
        "Always wanted to visit Zambia.") == "AlwYS Wnted to visit ZMBI."
    print("Coding complete? Click 'Check' to earn cool rewards!")


Moje rešenje je ovde.
 
Odgovor na temu

[es] :: Python :: Zadaci za wannabe pythoniste

Strane: << < .. 25 26 27 28 29 30 31 32

[ Pregleda: 50983 | Odgovora: 629 ] > FB > Twit

Postavi temu Odgovori

Navigacija
Lista poslednjih: 16, 32, 64, 128 poruka.