In: Computer Science
Write a Python program stored in a file q3.py that:
Gets single-digit numbers from the user on one line (digits are separated by white space) and adds them to a list. The first digit and the last digit should not be a zero. If the user provides an invalid entry, the program should prompt for a new value.
Converts every entry in the list to an integer and prints the list. The digits in the list represent a non-negative integer. For example, if the list is [4,5,9,1], the entries represent the integer 4591. The most significant digit is at the zeroth index of the list.
Adds the integer that the reversed value of the integer. For example, if the list is [4,5,9,1], the addition will be 4591 + 1954 = 6545 and the resulting list will be [6,5,4,5]
Sample Output#1:
**************************************************
Enter single digits separated by one space: 0 5 1 1
Invalid list, try again.
Enter single digits separated by one space: 8 5 9 0
Invalid list, try again.
Enter single digits separated by one space: 0 58 1 14
Invalid list, try again.
Enter single digits separated by one space: 4 5 9 1
The initial list is: [4,5,9,1]
The reversed list is: [1,9,5,4]
The addition list is: [6,5,4,5]
**************************************************
Solution:
Look at the code and comments for better understanding........
Screenshot of the code:
Output:
Code to copy:
while True:
print("Enter single digits separated by one space: ",end="")
L = input().split()
m_digit = False
#convert the string digits into numbers and check for multi digit numbers
for i in range(len(L)):
L[i] = int(L[i])
if L[i] > 9:
m_digit = True
#if zero is present at begining or end or multidigit number is present
if L[0]==0 or L[-1]==0 or m_digit:
print("Invalid list, try again.")
continue
#reversing the list L
rev_L = L[::-1]
#calculating numbers from the lists
N,rev_N = 0,0
for i in range(len(L)):
N = N*10 + L[i]
rev_N = rev_N*10 + rev_L[i]
#calculating the sum
SUM = N + rev_N
#converting the SUM to a list
SUM_L = []
while SUM!=0:
rem = SUM % 10
SUM_L = [rem] + SUM_L
SUM//=10
#printing the results
print("The initial list is:",L)
print("The reversed list is:",rev_L)
print("The addition list is:",SUM_L)
break
I hope this would help...........................:-))