2

Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(

EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')

edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.

num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)


while (i < num):
    j = i + 1
    inNum = input('Please enter number %d:' %j)
    ar.append(inNum)
    i = i + 1

while (k < num):
    while(l < num):
        if ((ar[k]+ar[l])==total):
            print(ar[k] +' , '+ ar[l])
            hasValue = hasValue + 1
        l = l +1
    k = k + 1
if (hasValue == 0):
    print('sorry, there no such pair of values')
4
  • 2
    In Python, you can set variables equal to an integer just by doing "j = 0". Python automatically knows that it's an integer. Same with floats: "j = 0.223", and strings: j = "hello" Commented Mar 27, 2014 at 5:38
  • Also, i don't clearly understand your problem, could you please rephrase it Commented Mar 27, 2014 at 5:39
  • Also, there is no point of the variable 'j'. You are never using it Commented Mar 27, 2014 at 5:42
  • Which python version are you using? Commented Mar 27, 2014 at 6:01

3 Answers 3

1

As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have

ar = [1, 2, 3]

and

total = 5

program should display 2, 3 pair. But it will not find 1+3 for total=4.

Here are some general advices:

  1. There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format

    print('%d, %d'.format(ar[k], ar[k])

    or print result as tuple

    print(ar[k], ar[l])

  2. Use for k in range(num) instead of while

  3. hasValue is better to be boolean value

Well, here is my solution (python2.7)

num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False

# Fill array
for i in range(num):
    a.append(int(input("Enter number #{}: ".format(i+1))))

# More effective algorithm - does not check same numbers twice
for i in range(num):
    for j in range(i+1, num):
        if a[i] + a[j] == sum:
            print "{}, {}".format(a[i], a[j])
            found = True

if not found:
    print "Sorry..."
Sign up to request clarification or add additional context in comments.

Comments

1

This is how to do for-loops in python:

for x in range(10):
    # code for the for loop goes here

This is equivalent to:

for (int x = 0; x < 10; x++) {
    // code for the for loop goes here
}

... in C++

(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.

Here is what I think you wish to do:

def main():
    num = int(input("Enter the amount of numbers: "))
    total = int(input("Enter the total: "))
    array = []
    counter, elem = 0, 0
    for user_numbers in range(num):
        array.append(int(input("Please enter number: ")))
    for each_element in array:
        counter += each_element
        elem += 1
        if counter == total:
            print(array[:elem])
            break
    if counter != total:
        print("sorry...")

main()

4 Comments

Instead of eval you could just pass the inputs to int. If you want to also support floats then try: int(x); except ValueError: float(x).
It opens up security holes in your code because any input is treated as valid Python code and executed. Ok, this is a toy program on your friend's computer, and you don't care. Well, it's still un-Pythonic, because all you're trying to do is convert to a numeric type. eval is not what you mean.
@Ol'Reliable and what if one of the inputs is __import__('os').system('rm -rf')? That would end really badly.
@Ol'Reliable Just replace eval() with int() and stop this code security evangelical preaching
0
while (k < num):
    while(l < num):
        if ((ar[k]+ar[l])==total):
            print(ar[k] +' , '+ ar[l])
            hasValue = hasValue + 1
        l = l +1
    k = k + 1

Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.

while (k < num):
    l = 0
    while(l < num):
        if ((ar[k]+ar[l])==total):
            print(ar[k] +' , '+ ar[l])
            hasValue = hasValue + 1
        l = l +1
    k = k + 1

or slightly more python way:

for num1 in ar:
    for num2 in ar:
        if num1+num2==total:
            print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
            hasValue = hasValue + 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.