Home > database >  Repeating outputs in Python
Repeating outputs in Python

Time:08-28

This code keep repeating the same sets of numbers that add up to a specific number. ex: 31 69 = 100. This will be repeated many times among other possibilities. What's the matter with my code ? enter image description here

Thanks. Here it is:

import random

target_number = int(input('Input a number and we will return a list of two numbers that equate to this number'))

r1 = range(1,target_number)
r2 = range(1,target_number)

while True:
    for i in range(24):
        num1 = random.choice(r1)
        num2 = random.choice(r2)
        if num1   num2 == target_number:
            print(f"solved: {num1} {num2} = {target_number}")

CodePudding user response:

As noted by HuLu, while True will run forever. The for loop with i could be removed as follows:

import random

target_number = int(input('Input a number and we will return a list of two numbers that equate to this number'))

r1 = range(1,target_number)
r2 = range(1,target_number)

while True:
    num1 = random.choice(r1)
    num2 = random.choice(r2)
    if num1   num2 == target_number:
        print(f"solved: {num1} {num2} = {target_number}")
        break

CodePudding user response:

If you're looking to find all pairs that add up to your number, try the following:

def find_factors(x):
    for i in range(x): # loop through all numbers (until x)
        if i <= x-i: # this is to avoid printing duplicate pairs, e.g. (2,3) and (3,2)
            print([i,x-i]) # print i, and i subtracted from x

This function will take x as an argument and return all pairs of integers that add up to x.

E.g. calling find_factors(5) will return:

[0, 5]
[1, 4]
[2, 3]

CodePudding user response:

while True means "repeat forever", you have to put and end to the loop:

import random

target_number = int(input('Input a number and we will return a list of two numbers that equate to this number'))

r1 = range(1,target_number)
r2 = range(1,target_number)

cont = True
while cont:
    for i in range(24):
        num1 = random.choice(r1)
        num2 = random.choice(r2)
        if num1   num2 == target_number:
            print(f"solved: {num1} {num2} = {target_number}")
            cont = False

CodePudding user response:

use break as soon as you find numbers with a sum of target_number in if statement.Otherwise this while loop will run forever.

  • Related