Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating an integer in python

Tags:

python

An integer like:

number = 1873

I have a formula: weighted_sum = 1*1 + 8*2 + 7*3 + 3*4 = 50. I want to calculate weighted sum of four digits, so output looks like:

1234 weighted sum: 30 / 4321 weighted sum:20

I tried to convert integer to string, but did't work.

number = str(1742)
weighted = number[0]*1 + number[1]*2 + number[2]*3 + number[3]*4
print(number, "weighted sum:", weighted)

Output

1742 Weight Sum: 1774442222
like image 813
Kee Avatar asked Mar 13 '26 00:03

Kee


1 Answers

You need to convert the individual digits back to integer before multipyling them:

weighted = int(number[0])*1 + int(number[1])*2 + int(number[2])*3 + int(number[3])*4

Just taking number[i] will give you a single-character string with of that digit, and multiplying a string bt n in Python means concatenating it n times.

This can be simplified using sum() and a generator expression:

weighted = sum(i * int(digit) for i, digit in enumerate(number, 1))
like image 56
Sven Marnach Avatar answered Mar 15 '26 14:03

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!