-1

This is a simple code to find and print the position of "zip" of the last occurrence after the first one, so if no "zip" was found or it only occurred once it should print -1. I wrote two code which can do the same thing and I want to know which is a better code and why and how to improve it (besides adding comments).

At first I wrote this code

text = 'all zip files are zipped'
indicator = 0
zip_position = text.find("zip" , indicator)
printer = zip_position
cycles = 0
printer_confirmation = 0
while zip_position != -1:
    printer = zip_position
    zip_position = text.find("zip" , indicator)
    indicator = zip_position + 1
    if printer > zip_position and cycles > 1:
        print printer
        printer_confirmation = 1
    cycles += 1
if cycles < 3 and printer_confirmation != 1:
        print -1

Then I wrote the second code after a hint which was this line: " print (text.find('zip', text.find("zip")+1)) "

my full code:

text = "all zip files are zipped"
indicator = 1
zip_position = (text.find('zip', text.find("zip")+indicator))
while zip_position != -1:
    zip_position = (text.find('zip', text.find("zip")+indicator))
    indicator += 1
if zip_position == -1 and text.find("zip" , text.find("zip")+(indicator - 2)) > text.find('zip'):
        indicator -= 2
zip_position = (text.find('zip', text.find("zip")+indicator))
print zip_position

I can see that the first code is bigger but I don't know if it's the better way to code it. And is it always better if the code is shorter? Please give me your opinion on which is a better code.

Both codes give the same results with no errors.

1 Answers1

0

Actually you can write one-liner

indicator = text.rfind('zip') if text.count('zip')>1 else -1
Marcus.Aurelianus
  • 1,520
  • 10
  • 22
  • wow that was easy. I'm a beginner and didn't know that there were built in methods in python that can do that and I didn't really think of that. Thank you so much. anyway, what if there were no built in methods that can do that and I had to build these methods on my own maybe in a different scenario, which code is better? which one has better structure and more understandable? how should I be writing my code in the future? any other advice? – Talaattebayo Sep 17 '19 at 02:15
  • 2nd looks better. But you can always write a better solution. Try more and learn more :) About what is good code. Here is a link. https://stackoverflow.com/questions/366588/what-does-a-good-programmers-code-look-like – Marcus.Aurelianus Sep 18 '19 at 02:55