Python Forum
Program: add the digits
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Program: add the digits
#1
I have completed two parts of the problem, but I am stuck in the .join () method Wall Wall Wall
I don't know how to add "+"
Can someone solve this doubt?

ecuacion="+".join(digits) ?

#create a 20 digit string, and cast to a list
#then add all the digits as integers
#print the equation and answer
#Hint: use cast to sum the digits, [color=#C0392B][b]and .join() to create the equation (1+2+3+...)[/b][/color]

digits = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20"
numbers = list()

for number in digits.split(','):
    numbers.append(int(number))

subtotal=0
for num in numbers:
    num=num+subtotal
    subtotal=num
Reply
#2
you need an iterable of str (in this case - list of str) to use with str.join()
Reply
#3
(Feb-07-2018, 10:05 AM)buran Wrote: you need an iterable of str (in this case - list of str) to use with str.join()
Thanks^^

i finally made it:

new_list=list()
for n in numbers:
    st=str(n)
    new_list.append(st)

print("+".join(new_list),"=",subtotal)
Output: 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20 = 210
Reply
#4
great :-)
digits = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20"
numbers = digits.split(',')
total = sum(map(int, numbers))
print('{}={}'.format('+'.join(numbers), total))
Reply
#5
By the way, what you have written, is a easy test for parsers of programming languages.
You can check with this code, if there is for example a recursion-limit, which disallows computations like this one:
str.join(' + ', map(str, range(10000)))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020