miro.kh - 4 months ago 6
Python Question

Best way to perform calculations on a list/tuple in Python 3x

I wrote this program that will tell you the two multiples factors of your input. Ex. if I were to input 35 (a semiprime), the program would print 5 and 7, which are the two prime numbers that multiply to 35.

But I am wondering if there is a more concise or pythonic way to iterate through this tuple so I wouldn't have to code all those "elif" statements you see below.

Also it would be great if I didn't need to rely on any external libraries.

``````# multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )

# tuple 1 calculations
while True:

try:
semiprime = int(input('Enter Semiprime: '))

except ValueError:
print('INPUT MUST BE AN INTEGER')
continue

# index 0 - 3
if (tuple1[0]) * (tuple1[0]) == semiprime:
print((tuple1[0]), (tuple1[0]))

elif (tuple1[0]) * (tuple1[1]) == semiprime:
print((tuple1[0]), (tuple1[1]))

elif (tuple1[0]) * (tuple1[2]) == semiprime:
print((tuple1[0]), (tuple1[2]))

elif (tuple1[0]) * (tuple1[3]) == semiprime:
print((tuple1[0]), (tuple1[3]))

# index 1 - 3
elif (tuple1[1]) * (tuple1[0]) == semiprime:
print((tuple1[1]), (tuple1[0]))

elif (tuple1[1]) * (tuple1[1]) == semiprime:
print((tuple1[1]), (tuple1[1]))

elif (tuple1[1]) * (tuple1[2]) == semiprime:
print((tuple1[1]), (tuple1[2]))

elif (tuple1[1]) * (tuple1[3]) == semiprime:
print((tuple1[1]), (tuple1[3]))

# index 2 - 3
elif (tuple1[2]) * (tuple1[0]) == semiprime:
print((tuple1[2]), (tuple1[0]))

elif (tuple1[2]) * (tuple1[1]) == semiprime:
print((tuple1[2]), (tuple1[1]))

elif (tuple1[2]) * (tuple1[2]) == semiprime:
print((tuple1[2]), (tuple1[2]))

elif (tuple1[2]) * (tuple1[3]) == semiprime:
print((tuple1[2]), (tuple1[3]))

#index 3 - 3
elif (tuple1[3]) * (tuple1[0]) == semiprime:
print((tuple1[3]), (tuple1[0]))

elif (tuple1[3]) * (tuple1[1]) == semiprime:
print((tuple1[3]), (tuple1[1]))

elif (tuple1[3]) * (tuple1[2]) == semiprime:
print((tuple1[3]), (tuple1[2]))
``````

I hinted at this in my comment, but realized just the link to the function docs may not be enough.

Here's how you could write your code using `itertools.combinations_with_replacement`:

``````from itertools import combinations_with_replacement

# multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )

# tuple 1 calculations
while True:

try:
semiprime = int(input('Enter Semiprime: '))

except ValueError:
print('INPUT MUST BE AN INTEGER')
continue

for (x,y) in combinations_with_replacement(tuple1, 2):
if x * y == semiprime:
print(x,y)
``````

Much nicer, IMO :)

Edit: A previous version used `itertools.combinations` which wouldn't yield (x,y) pairs with the same value (e.g. `(x,y) = (2,2)` would never happen). `combinations_with_replacement` allows for duplicates. Thanks to @Copperfield for pointing this out.