So if you want to do it using string you have to do this kind of thing (If i use your logic)
number = str(1742)
weighted = int(number[0])*1 + int(number[1])*2 + int(number[2])*3 + int(number[3])*4
print(number, "weighted sum:", weighted)
In fact in python if you multiply a string by an int it repete it multiple time. For example
>>>"a" * 3
"aaa"
>>>"foo" * 2
"foofoo"
One smaller way to do it is using a list comprehension
number = 1742
sum([i * int(nb) for i,nb in enumerate(str(number))])
One ugly way to do it without string as asked is
number = 1742
weighted = 0
for i in range(0,4):
temp = number // 10 ** (4-i)
weighted += i * temp
number -= temp * 10 ** (4-i)
I tried to do a time analysis using timeit.timeit and we get
My first answer (without loop)
>>> timeit.timeit(..., number = 1000000)
1.3271157014933124
For the answer of Sven Marnach using generator
>>>timeit.timeit("sum(i * int(digit) for i, digit in enumerate(str(1742),1))", number = 1000000)
2.0325663901261066
For my answer using list comprehension
>>> timeit.timeit("sum([i * int(nb) for i,nb in enumerate(str(1742))])", number = 1000000)
1.918556083665976
For my answer without any string
timeit.timeit("number = 1742 ....)
2.8422619991572446
For ikku answer without any string
>>>timeit.timeit(..., number = 1000000)
1.2137944809691135
So it seems that here the faster that I tested with string and loop is a list comprehension.
the faster that I tested with string is the first answer I gave.
The faster that I tested is Ikku answer