I want to print a pattern for the given input as follows: If the input is 675 then the output should be 600*6 + 70*7 + 5*5
I think the sum of above numbers is 1774 not 1174. And such output can be generated as follows:
u=a/100; v=(a-u*100)/10; w=(a-u*100-v*10)
sum=u*u*100+v*v*10+w*w
m=max(u,v,w)
list=[]
for i in range(m):
list1=[]
if i < u:
list1.append(u)
else:
list1.append(0)
if i < v:
list1.append(v)
else:
list1.append(0)
if i < w:
list1.append(w)
else:
list1.append(0)
list.append(list1)
for i in range(m):
print(str(list[i][0])+str(list[i][1])+str(list[i][2]))
print("-----")
print(sum)
print("-----")
list comprehension should be able to do this nicely.
a=input(" enter any three digit number ") # first take your input as a string
a_list = [int(i) for i in str(a)] # convert string input to list of ints
ans=0
for i in range(max(a_list)):
i_input = [l if l>i else 0 for l in a_list] # create a list of zeros or a_list
# values if the a_list value is greater than the iteration number
i_input = [str(i) for i in i_input] # convert back to string
i_input = "".join(i_input)
print(i_input)
ans+= int(i_input) # convert back to int and sum
print(ans)
The following program works based on the fact that we can separate each number into 100*a + 10*b + c. For example, 398 = 3*100+9*10+8.
Now, we can write the total sum as 3*(3*100) + 9*(9*100) + 8*(8).
Code:
a = input("enter a three digit number: ")
str_list = list(a) # separates each character into element of list.
mylist = [int(i) for i in str_list] # converts each string character to int
sequence_sum = (mylist[0]**2)*100 + (mylist[1]**2)*10 + (mylist[2]**2)
print(sequence_sum)
The following should do it independent of the number of digits in input.
def patternize(num):
l = len(str(num))
digits = [int(d) for d in str(num)]
tens = [10**i for i in range(l - 1, -1, -1)]
return sum([d * t * d for d, t in zip(digits, tens)])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.