Jump to content

Making python 3.2.5 more economical?

mattonfire
Is there a way I can make this code more economical It's currently reading off a txt file which I linked with a pastebin. The only bit which I really need to be more economical about is reading off the txt file, at the moment it is asking for the code then it'll link that code to a line and that line is what python is going to read on the txt file.

 

Economical as in, less amount of lines but still meaning that is unbreakable like it is now.

 

 


Link to comment
Share on other sites

Link to post
Share on other sites

You could do multiple things in the same line for a lot of these things, I believe.

Sig under construction.

Link to comment
Share on other sites

Link to post
Share on other sites

You could do multiple things in the same line for a lot of these things, I believe.

Could you show me?

Link to comment
Share on other sites

Link to post
Share on other sites

Could you show me?

I'm no great coder, but surely for an example:

def text():    f=open(Text.txt","r");lines=f.readlines();x = lines[line] ...

Sig under construction.

Link to comment
Share on other sites

Link to post
Share on other sites

 

I'm no great coder, but surely for an example:

def text():    f=open(Text.txt","r");lines=f.readlines();x = lines[line] ...

Wow I didn't even know that, thanks hahaha.

Link to comment
Share on other sites

Link to post
Share on other sites

Wow I didn't even know that, thanks hahaha.

Check that it works first!

 

But you're still not reducing the amount of code you're using etc.

Sig under construction.

Link to comment
Share on other sites

Link to post
Share on other sites

Check that it works first!

 

But you're still not reducing the amount of code you're using etc.

It works, thanks. I know it doesn't reduce the amount of code but it means that I have less lines which means I can brag more to my friends ;) Cheers.

Link to comment
Share on other sites

Link to post
Share on other sites

It works, thanks. I know it doesn't reduce the amount of code but it means that I have less lines which means I can brag more to my friends ;) Cheers.

You're welcome!

 

Also your code is far better than I can write atm :P

Sig under construction.

Link to comment
Share on other sites

Link to post
Share on other sites

Some notes:

 

Your text() function can be changed up a lot to both be nicer and save some lines.

  • Get rid of the variable line.  Turn it into an argument of text(), then call text(line) whenever you need to.  This also lets you write lines 27-38 a bit more compactly, incidentally.
  • There's no need to create the variable line2.  Just use y=lines[line+1].
  • It's probably a good idea to just re-arrange the lines a bit for readability.  Put your x and y assignments together, and probably put print(x) right before your input().  This doesn't do anything for functionality, just readability.
  • You should almost definitely be using the keyword with to open your file.  This will mean your file gets closed whenever the function exits for whatever reason, rather than staying open and either eating up memory or maybe blocking other things from editing the file.
  • I'm not sure if this is a problem or not, but the last line of text()--print(y*ask)--is almost certainly going to print whatever y is, but print it ask times.  If y is a price or some number, you need to convert it to an int or float before this.  Or do it inside the print function: print(int(y) * ask).

Depending on how big the Text.txt file is, you might even be able to read the whole thing into memory from the file and reference that, rather than always reading from the file.  Reading from a file is always slower than reading from memory, but since you're prompting the user for input each time, the performance difference might be a negligible portion of your total run time.  So it might not be worth it.  (I'd guess that if your file is big enough that that would make a difference, it's probably bigger than you'd want if you're storing it all in memory anyways)

 

Another thing you can change is how you're dealing with the variable strStock.  This doesn't save you any lines, but does make your lines a bit more readable.

  • You don't need to convert it to a list in line 20--strings are already lists of characters.  You can index them just like lists--strStock[0] will work fine if it's a string.  (Also, input() stores its result as a string by default, so strStock is a string when the user inputs it).  In Python, as in most languages, "foo" is just syntactic sugar for ['f', 'o', 'o'].
  • You do, however, still need to convert each digit into an integer, which you can do either through list comprehension or by using the map() function.  (Note that map() returns the slightly odd map object rather than a list/tuple/whatever you called it on--but you can still call sum(map(...)) just fine, or explicitly convert to a list/tuple/etc with list(map(...)) or whatnot).  Note that map's arguments are map(function, iterable), and you shouldn't include parentheses when typing the name of the function.
  • Since you're multiplying every other digit, starting with the first, by three, you can use list slicing.  strStock[::2] will get every other item, starting at 0, and strStock[1::2] gets every other item starting at 1.  So even and odd vaued indices, respectively.  You can do some really compact-looking code by combining map, list slicing, and sum() together.  This mostly just looks super cool and should make you feel like a badass.

Lastly, and this is purely a code formatting note and has nothing whatsoever to do with functionality, it's helpful to put a blank line before each function definition and before your main block of code (the while loop, here).

 

So, a slightly cleaner/fancier version of your code:

import mathdef text(line):    with open("Text.txt","r") as f:        lines = f.readlines()        x = lines[line]        y = lines[line+1]        print(x)        ask = int(input("How many would you want: "))        print(y*ask)def roundup(x):    return int(math.ceil(x /10)) * 10while True:    strStock = input("Please input ID: ")    intStock = 1    try:        intStock = int(intStock)        if (len(strStock) == 7) or (len(strStock) == 8):            total = 3*sum(map(int, strStock[::2])) + sum(map(int, strStock[1::2]))            rounded = roundup(total)            digit8 = rounded - total            if len(strStock) == 8:                if int(l[7]) == digit8:                    print("This is a correct 8 Digit Barcode!")                    if strStock   == "34512340": text(0)                    elif strStock == "98981236": text(2)                    elif strStock == "56756777": text(4)                    elif strStock == "90673412": text(6)                    else: print("Barcode not listed!")                else:                    print("Incorrect Barcode! The check digit should be " + str(digit8) + ".")            else:                print("The check digit is " + str(digit8) + ".")        else:            print("Please input a correct length barcode.")    except ValueError:        print ("Thats not an integer!")

This shaves nine lines of actual code down from your version, but adds three blank lines for formatting prettiness.  If you're trying to cut down your line count as much as possible, you can take all those else statements at the end and put them on one line, so they look like this: else: print(...).  Same thing for the except ValueError statement at the very end.  Whether you want to do that or not is purely a matter of taste.  Personally, I tend to only put if/else statements on a single line if I can put every corresponding if/else statement on one line, but that's just my preference.

Link to comment
Share on other sites

Link to post
Share on other sites

 

I'm no great coder, but surely for an example:

def text():    f=open(Text.txt","r");lines=f.readlines();x = lines[line] ...

 

NEVER do this. The number of lines should never be a factor in how good your code is.

 

Code formatting is there for you and anyone else who looks at your code, it makes very little difference to the computer. The harder you make your code to read the longer it will take to understand it and to fix any bugs not forgetting it goes against every code standard ever written.

Link to comment
Share on other sites

Link to post
Share on other sites

- snip -

Wow, you put a lot of thought into that thank you very much. I really like what you've done with the if and elif statments.

Link to comment
Share on other sites

Link to post
Share on other sites

-  snip -

 

The only reason I would use this method for is on the else statments, but ";" and tabbing so instead of all else statments being 2 they would be 1 line.

Link to comment
Share on other sites

Link to post
Share on other sites

The only reason I would use this method for is on the else statments, but ";" and tabbing so instead of all else statments being 2 they would be 1 line.

 

Many languages have defined code standards and style guides. These exist to benefit yourself and anyone else who looks at your code, if you get used to following these rules you will find it much easier to understand others code and it will help when you come to apply for programming jobs.

 

You can find the PEP 0008 style guide for Python here: https://www.python.org/dev/peps/pep-0008/

Link to comment
Share on other sites

Link to post
Share on other sites

Wow, you put a lot of thought into that thank you very much. I really like what you've done with the if and elif statments.

No problem!

 

 

Many languages have defined code standards and style guides. These exist to benefit yourself and anyone else who looks at your code, if you get used to following these rules you will find it much easier to understand others code and it will help when you come to apply for programming jobs.

 

You can find the PEP 0008 style guide for Python here: https://www.python.org/dev/peps/pep-0008/

I'll second this.  PEP8 is a great style guide, and is the standard for Python code all over the internet and all throughout industry.  Just a caveat about it, though: it's a guide, not a law, despite its near-universal adoption.  You can bend a few rules here and there if it makes your code clearer than following them, but if you find yourself bending them a lot, maybe take a second look at how you're writing your code.  You can probably write it in a different, more clear fashion that doesn't require you to bend the guidelines so much.

Link to comment
Share on other sites

Link to post
Share on other sites

NEVER do this. The number of lines should never be a factor in how good your code is.

 

Code formatting is there for you and anyone else who looks at your code, it makes very little difference to the computer. The harder you make your code to read the longer it will take to understand it and to fix any bugs not forgetting it goes against every code standard ever written.

I know not to do that, I was simply answering what I could of what was asked in the OP.

I understand that having semicolons rather than line spacings will not actually change the amount of characters in most cases and that it will make it more difficult to debug.

 

 

Is there a way I can make this code more economical It's currently reading off a txt file which I linked with a pastebin. The only bit which I really need to be more economical about is reading off the txt file, at the moment it is asking for the code then it'll link that code to a line and that line is what python is going to read on the txt file.
 
Economical as in, less amount of lines but still meaning that is unbreakable like it is now.
 
 

 

Sig under construction.

Link to comment
Share on other sites

Link to post
Share on other sites

This isn't exactly what you asked for, but your code set off my programming OCD.

 

"barcode2.py" : http://pastebin.com/S6Ms56k7

 

I've changed your .txt file structure, you'll need this one for our code to work

"barcodes.txt" : http://pastebin.com/ktB66zTM

 

 

What I've done to your text file handling is kind of a trade off. Doing it my way is exponentially faster than going to the file every time you want to look up a bar code, not to mention easier on your poor HDD or SSD. The problem is, if the text file is bigger than your pc has ram, it will crash, but if the file gets that damn big, it's time to look into a database solution, or just peck through the file like you were, it'll just be slower.

 

Hope I helped :)

Link to comment
Share on other sites

Link to post
Share on other sites

- snip - 

"L" isn't a variable

    if int(l[7]) == digit8:

What were you trying to put here? Total?

Link to comment
Share on other sites

Link to post
Share on other sites

This isn't exactly what you asked for, but your code set off my programming OCD.

 

"barcode2.py" : http://pastebin.com/S6Ms56k7

 

I've changed your .txt file structure, you'll need this one for our code to work

"barcodes.txt" : http://pastebin.com/ktB66zTM

 

 

What I've done to your text file handling is kind of a trade off. Doing it my way is exponentially faster than going to the file every time you want to look up a bar code, not to mention easier on your poor HDD or SSD. The problem is, if the text file is bigger than your pc has ram, it will crash, but if the file gets that damn big, it's time to look into a database solution, or just peck through the file like you were, it'll just be slower.

 

Hope I helped :)

Hiya, is there a way you can post it someone else apart from pastebin. I am at school and for some reason pastebin is filtered. If need be could you send me a PM of it?

Link to comment
Share on other sites

Link to post
Share on other sites

"L" isn't a variable

 

Uh yeah it is, in your code you set "l" with 

 
l = list(strStock)

 

 

Hiya, is there a way you can post it someone else apart from pastebin. I am at school and for some reason pastebin is filtered. If need be could you send me a PM of it?

 

 

Sure, hope it's okay to just post here.

 

barcodes.txt

 
34512340:Tomato,2.0098981236:Banana,3.0056756777:Apple,1.0090673412:Grapes,4.00

 

 

 

barcode2.py

 

#!/usr/bin/python3# 2016 lordxenu/mattonfire# for: "http://linustechtips.com/main/topic/530854-making-python-325-more-economical/"#FOR THE LOVE OF GOD STOP USING TABS#SET YOUR EDITOR TO USE ALL SPACESimport math#next two are built-ins, don't worryimport reimport sys#This creates a dictionary called "barcode_file"barcode_file = {}def initilize():		#open the file    f1 = open("barcodes.txt", mode = "r")    #read each line of the file and feed it into the dictionary created above    for llline in f1:	        #this splits the string loaded from the file.         #every character to the left of ":" becomes "linedata[0]"        #and every character to the right of ":" becomes "linedata[1]"        linedata = re.split(":", llline)            #remove the newline, we don't need it        item_price = linedata[1].rstrip("\n")        #seperate the item from it's price using re.split        item_price = re.split(",", item_price)	        #add a new entry into the dictionary, key = barcode(linedata[0])        #value of each key is a tuple (name, price)        barcode_file[linedata[0]] = (item_price[0], item_price[1])            #close your files, this is a good habit to get into, trust me        f1.close        return             def text(entry):    #trust me    done = False	    #get the values for "entry" and break them into two seperate strings    stuff = barcode_file[entry]    item = stuff[0]    price = stuff[1]         print(entry, item, price)                while done == False:        #Not sure why we are aking this, but ok        ask = input("[Q to exit] How many would you want: ")            #abort if user wants to quit        # ".upper()" ensures that both "Q" and "q" will work        if str(ask).upper() == "Q": sys.exit()            try:                ask = int(ask)               #print away            for i in range(ask):                print(price)                done = True                break        except ValueError:            print ("Thats not an integer!")            done = False                #I always use "return" even when it isn't exactly necessary, it helps     #make the code more readable, at least for me.    return def main_menu():		    #getting user input    user_input_barcode = input ("[Q to exit] Barcode please: ")                #abort if user wants to quit    # ".lower()" ensures that both "Q" and "q" will work    if user_input_barcode.lower() == "q": sys.exit()            if (len(user_input_barcode) == 7) or (len(user_input_barcode) == 8):        total = int(user_input_barcode[0]) * 3 + int(user_input_barcode[1]) + int(user_input_barcode[2]) * 3 + int(user_input_barcode[3]) + int(user_input_barcode[4]) * 3 + int(user_input_barcode[5]) + int(user_input_barcode[6]) * 3        rounded = int(math.ceil(total /10)) * 10        digit8 = rounded - total                            if len(user_input_barcode) == 8:            if int(user_input_barcode[7]) == digit8:                print("This is a correct 8 Digit Barcode!")				        #check dictionary for barcode                if user_input_barcode in barcode_file:                    text(user_input_barcode)                else:                    print("Barcode not listed!")                                else:                print("Incorrect Barcode! The check digit should be " + str(digit8) + ".")                else:            print("The check digit is " + str(digit8) + ".")    else:        print("Please input a correct barcode.")        return#main functiondef main():        #run the function that reads the text file and puts it in a dictionary    initilize()        #running menu function     while True:        main_menu()            return#standard boilerplateif __name__ == '__main__':    main()

 

 

 

 

 

E: Fixed to use proper code thingy. But wow! neat highlighting, looks exactly the same as it does in geany!

Link to comment
Share on other sites

Link to post
Share on other sites

- snip -

Omg, thanks so much. This is way behind my skill though. "Not sure why we're making this" did you make it with someone else? May I ask how long did this take?

Link to comment
Share on other sites

Link to post
Share on other sites

Omg, thanks so much. This is way behind my skill though. "Not sure why we're making this" did you make it with someone else? May I ask how long did this take?

 

Yeah, I made it with someone else, you :)  I'm not sure how long it took, I was babysitting other scripts and websurfing for a while. It was hours between start and finish, but I wasn't giving it my full attention. 

 

Just remember dictionaries. They are sooooo useful because they are lightning fast and you don't have to loop through anything every time your program goes looking for something. They are also good for counting things. 

Link to comment
Share on other sites

Link to post
Share on other sites

Yeah, I made it with someone else, you :)  I'm not sure how long it took, I was babysitting other scripts and websurfing for a while. It was hours between start and finish, but I wasn't giving it my full attention. 

 

Just remember dictionaries. They are sooooo useful because they are lightning fast and you don't have to loop through anything every time your program goes looking for something. They are also good for counting things. 

Wow, I am very grateful! How long have you been coding because you seem very advanced. If you want a job we can chuck our python teacher out and replace him for ;)

Link to comment
Share on other sites

Link to post
Share on other sites

Wow, I am very grateful! How long have you been coding because you seem very advanced. If you want a job we can chuck our python teacher out and replace him for ;)

 

Your welcome, glad I could help. I've been into python probably a month and a half now, but before that I hadn't touched a line of code in ten or so years due to a non-tech related career that didn't give me a whole lot of free time. But then again, I was practically raised with a keyboard in my hands thanks to my father so growing up with these infernal machines helped a lot. 

 

 

When I first got the internet, I didn't know what the hell a "hello world" program was. Most of my first programs consisted of something along the lines of:

10 PRINT "boobies!"20 GOTO 10
Link to comment
Share on other sites

Link to post
Share on other sites

 

Your welcome, glad I could help. I've been into python probably a month and a half now, but before that I hadn't touched a line of code in ten or so years due to a non-tech related career that didn't give me a whole lot of free time. But then again, I was practically raised with a keyboard in my hands thanks to my father so growing up with these infernal machines helped a lot. 

 

 

When I first got the internet, I didn't know what the hell a "hello world" program was. Most of my first programs consisted of something along the lines of:

10 PRINT "boobies!"20 GOTO 10

Hahaha, apart from python and java that is what my programs consist of now. A month in a half, that's quite amazing. I have been doing it for a year, then again I do it 3 hours a week with awful teaching.

Link to comment
Share on other sites

Link to post
Share on other sites

Oops, I  made a little booboo.

  #close your files, this is a good habit to get into, trust me        f1.close        return    

That code is technically incorrect. I forgot the parentheses after close. So make it look like this:

  #close your files, this is a good habit to get into, trust me        f1.close()        return     

This is why making code readable is important, it makes little mistakes like this one easier to find.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×