Python Forum

Full Version: Improving the program
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, i have this homework assignment, but i would like to improve it and would appreciate any help. If you have any ideas, feel free to comment.

def atidarymas(): #funkcija, atidaromas duomenu failas, panaikinami taskai, kableiai
    failas = open("duomenys.txt", "r")
    duomenys = failas.read()
    duomenys = duomenys.replace("\n", "")
    duomenys = duomenys.replace(".", "")
    duomenys = duomenys.replace(",", "")
    sar = duomenys.split()
    failas.close()
    return (sar)

def mazosios_raides(x):
    for i in range(len(sar)):
        x[i] = x[i].lower()
    return (x)

def f_surasymas(zodziai, skaiciai, zodis, a):
    a = str(a)
    if zodis.isalpha():
        zodziai.write(zodis + " " + a + "\n")
    else:
        skaiciai.write(zodis + " " + a + "\n")

def pasalinimas (sar):
    if sar.count(i) > 1:       
        for j in sar:
            if j == i: #tikrinant sąrašą randa vienodą elementą
                for k in range (sar.index(j)+1, len(sar)):
                    #nuo to rasto elemento ištrina visus tokius pačius
                    #(pirmą palieka)
                    if k >= len(sar):
                        break
                    if sar[k] == i:
                        del sar[k]
    return (sar)

def radimas (sar): #funkcija randandi žodžių variantus pagal pradžią
    a = 0
    y = input ("Įveskite žodžio pradžią: ")
    print ("Galimi žodžiai su jūsų įvesta pradžia:")
    for i in sar:
        if i.startswith(y):
            a = 1
            print(i)
    if a == 0: #jeigu neranda nei vieno žodžio su vartotojo įvesta pradžia
        print ("Žodžių nerasta.")

sar = atidarymas()
sar = mazosios_raides(sar)

f_zodziai = open("zodziai.txt", "w")
f_skaiciai = open("skaiciai.txt", "w")

for i in sar:
    f_surasymas(f_zodziai, f_skaiciai, i, sar.count(i))
    sar = pasalinimas(sar)

radimas(sar)

f_skaiciai.close()
f_zodziai.close()
We could not help, because your program is not in english.
we can still help! English preferred by not required.
I think this:

                for k in range (sar.index(j)+1, len(sar)):
                    #nuo to rasto elemento ištrina visus tokius pačius
                    #(pirmą palieka)
                    if k >= len(sar):
                        break
                    if sar[k] == i:
                        del sar[k]
Could be replaced with a replace, so to speak. Something like:

start = sar.index(j) + 1
sar = sar[:start] + sar[start:].replace(i, '')
Although I guess I'm assuming sar is a string. If it's a list, maybe:

start = sar.index(j) + 1
sar = sar[:start] + [x for x in sar[start:] if x != i]
Well, let's start at the top...

(May-13-2019, 04:50 PM)sunhyunshine Wrote: [ -> ]
def atidarymas(): #funkcija, atidaromas duomenu failas, panaikinami taskai, kableiai
    failas = open("duomenys.txt", "r")
    duomenys = failas.read()
    duomenys = duomenys.replace("\n", "")
    duomenys = duomenys.replace(".", "")
    duomenys = duomenys.replace(",", "")
    sar = duomenys.split()
    failas.close()
    return (sar)
1) with blocks are a good habit to get into, so the resource gets closed automatically when you're done with it (so you don't have to worry about forgetting to clean up after yourself).
2) Multiple replace operations might look better (?) as a regex, since it'd only be one line, and one operation.

import re

def atidarymas(): #funkcija, atidaromas duomenu failas, panaikinami taskai, kableiai
    with open("duomenys.txt", "r") as failas:
        duomenys = failas.read()
        sar = re.sub(r"[\n.,]", "", duomenyx).split()
        return sar
Another possibility to make multiple replace operations is using str.maketrans with str.translate(). It's two rows but doesn't require module import as relies on built-in string methods:

>>> mapping = str.maketrans(dict.fromkeys('\n.,'))
>>> s = '\na\nb.\nc,d.'
>>> s.translate(mapping)
'abcd'