Note that there are some explanatory texts on larger screens.

plurals
  1. POmake a global condition break
    primarykey
    data
    text
    <p>allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. </p> <p>i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:</p> <p>"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."</p> <p>my solution (which works) is: </p> <pre><code>first = str(input()) second = str(input()) count = 0 location = 0 while location &lt; len(second): if location == 0: location = str.find(second,first,0) if location &lt; 0: break count = count + 1 location = str.find(second,first,location +1) if location &lt; 0: break count = count + 1 print(count) </code></pre> <p>if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now. </p> <p>how would python gurus optimize this code or am i just being too nitpicky?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload