Skip to content Skip to sidebar Skip to footer

Cascading For Loop Outputs Is There A Better Python 3 Way

Right now, I have a word that I'm search for in a larger string if the word is not found then I insert the word in the larger sting. The output of the first FOR loop is cascaded in

Solution 1:

If nothing else, I think the below approaches are much cleaner than what you're currently doing and possibly appreciably faster (I need some time to set up proper test cases, to be added shortly).

addstring_sign = ["Monday was a snowing day", "Wednesday no snow"]
dictlines = ['Monday', 'Tuesday']

string_test1 = []
forstringin addstring_sign:
    missing_strings = ' '.join([item for item in dictlines if item notinstring])
    string_test1.append('{} {}'.format(string, missing_strings))

# Or a list comprehension for the same thing, probably not much faster
string_test2 = ['{} {}'.format(string, 
                ' '.join([item for item in dictlines if item notinstring])) 
                forstringin addstring_sign]

The next thing to do to speed this up is to convert dictlines to a set for larger problems. This is done simply with:

dictlines = set(dictlines)

Which will give you O(1) lookup - this will become more and more significant as dictlines grows in size. I struggled to get your existing code into an approach I could test on a larger scale but was unable. However, you can see that even with this tiny example, and without a set (here it makes little difference) that my initial approach is faster than your existing one:

%timeit my_for_loop(addstring_sign, dictlines)
1.53 µs ± 4.08 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit your_loop(addstring_sign, dictlines)
2.13 µs ± 8.69 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Solution 2:

TLDR;

forwordin strings:
    sentences = [line if word in line else line + ' ' + word forlinein sentences]

So you are given a list of sentences, of which you need to check if each contains a string. When one of them does not, you want to append the string to the sentence.

Let's first look at the second line of code and consider the case where you only have one word to search and append. This list comprehension iterates through your list of sentences then:

  1. Checks if the string is in the sentence
  2. Appends the string if it isn't in the sentence

At the end of the iterations, it reconstructs the list and assigns it back to the original list.

The first line of code than simply repeat this process for every word you wish to search and append.

Post a Comment for "Cascading For Loop Outputs Is There A Better Python 3 Way"