Search code examples
pythonif-statementconditional-statementsstatements

Print a line if conditions have not been met


Hello fellow stackoverflowers, I am practising my Python with an example question given to me (actually a Google interview practice question) and ran into a problem I did not know how to a) pose properly (hence vague title), b) overcome.

The question is: For an array of numbers (given or random) find unique pairs of numbers within the array which when summed give a given number. E.G: find the pairs of numbers in the array below which add to 6.

[1 2 4 5 11] 

So in the above case:

[1,5] and [2,4]

The code I have written is:

from secrets import *

i = 10

x = randbelow(10)

number = randbelow(100) #Generate a random number to be the sum that we are after#

if number == 0:
        pass
else:
        number = number

array = []

while i>0: #Generate a random array to use#
        array.append(x)
        x = x + randbelow(10)
        i -= 1

print("The following is a randomly generated array:\n" + str(array))
print("Within this array we are looking for a pair of numbers which sum to " + str(number))

for i in range(0,10):
        for j in range(0,10):
                if i == j or i>j:
                        pass
                else:
                        elem_sum = array[i] + array[j]
                        if elem_sum == number:
                                number_one = array[i]
                                number_two = array[j]
                                print("A pair of numbers within the array which satisfy that condition is: " + str(number_one) + " and " + str(number_two))
                        else:
                                pass

If no pairs are found, I want the line "No pairs were found". I was thinking a try/except, but wasn't sure if it was correct or how to implement it. Also, I'm unsure on how to stop repeated pairs appearing (unique pairs only), so for example if I wanted 22 as a sum and had the array:

[7, 9, 9, 13, 13, 14, 23, 32, 41, 45]

[9,13] would appear twice

Finally forgive me if there are redundancies/the code isn't written very efficiently, I'm slowly learning so any other tips would be greatly appreciated!

Thanks for reading :)


Solution

  • You can simply add a Boolean holding the answer to "was at least one pair found?".

    initialize it as found = false at the beginning of your code.

    Then, whenever you find a pair (the condition block that holds your current print command), just add found = true.

    after all of your search (the double for loop`), add this:

    if not found:
        print("No pairs were found")