Advertisements
import random
lst1 = []
lst2 = []
n = int(input('Step a: How many numbers in each list? '))
for i in range(0, n):
number1 = random.randint(1, 15)
number2 = random.randint(1, 15)
lst1.append(number1)
lst2.append(number2)
count = 0
if lst1[i] > lst2[i]:
count += 1
print(f'{number1} : First List')
else:
print(f'{number2} : Second List')
print(f'Step b: First List{lst1}')
print(f'Step c: Second List{lst2}')
print('Step d:')
print('Larger number in each comparison:')
Program is supposed to make two lists and compare each element.
Current program prints like this:
Step a: How many numbers in each list? 5
12 : First List
14 : First List
14 : First List
15 : First List
5 : Second List
Step b: First List\[12, 14, 14, 15, 4\]
Step c: Second List\[5, 2, 8, 13, 5\]
Step d:
Larger number in each comparison:
I’m trying to get it to print like this:
Step a: How many numbers in each list? 5
Step b: First List\[12, 14, 14, 15, 4\]
Step c: Second List\[5, 2, 8, 13, 5\]
Step d:
Larger number in each comparison:
12 : First List
14 : First List
14 : First List
15 : First List
5 : Second List
Any suggestions?
I’ve tried to make functions out of them and kept getting errors. Very new to this and not sure what I should do.
>Solution :
Try creating a third list to store the comparison results and then printing the contents only at the end with another loop:
import random
lst1 = []
lst2 = []
comparison_results = []
n = int(input('Step a: How many numbers in each list? '))
for i in range(n):
number1 = random.randint(1, 15)
number2 = random.randint(1, 15)
lst1.append(number1)
lst2.append(number2)
if lst1[i] > lst2[i]:
comparison_results.append(f'{number1} : First List')
elif lst1[i] < lst2[i]:
comparison_results.append(f'{number2} : Second List')
else:
comparison_results.append(f'{number2} : In Both Lists')
print(f'Step b: First List {lst1}')
print(f'Step c: Second List {lst2}')
print('Step d: Larger number in each comparison:')
for result in comparison_results:
print(result)
Example Output:
Step a: How many numbers in each list? 5
Step b: First List [5, 11, 9, 3, 4]
Step c: Second List [15, 11, 9, 13, 15]
Step d: Larger number in each comparison:
15 : Second List
11 : In Both Lists
9 : In Both Lists
13 : Second List
15 : Second List