I am currently writing a python code that tries to find out the number of four digit numbers that add up to a specific value. My code is below:
def findSum ():
target = 0;
checkno = 1000;
comboSum = [];
sumArray = [];
while target<=36 :
while checkno<10000 :
digitSum = int(str(checkno)[0]) + int(str(checkno)[1]) + int(str(checkno)[2]) + int(str(checkno)[3]);
if digitSum == target :
comboSum.append(checkno);
checkno = checkno + 1;
sumArray.append(len(comboSum));
target = target + 1;
print (sumArray);
findSum();
However, when I put this through the python interpreter, it returns an array of 36 "0"s. I am not quite sure why this is the case, when I increase the target every time, and then loops back through.
Does anyone know why this is the case?
Thanks!
You don't reset checkno
to 1000
after you increase target
and loop.
So first iteration on target, you get the correct answer 0. Second iteration, where target
is 1
, your checkno
is already 10000
, so the inner loop doesn't execute.
You need to move your initialisation of checkno
and comboSum
inside the outer loop.
You can replace your while
loops by for variable in range()
, like:
def findSum():
# target = 0
# checkno = 1000
# comboSum = []
sumArray = []
for target in range(36):
comboSum = []
for checkno in range(1000, 10000):
digitSum = int(str(checkno)[0]) +\
int(str(checkno)[1]) +\
int(str(checkno)[2]) +\
int(str(checkno)[3])
if digitSum == target:
comboSum.append(checkno)
# checkno = checkno + 1
sumArray.append(len(comboSum))
# target = target + 1
print(sumArray)
findSum()
It would be a more Pythonic way to do.
As highlighted by some other comments:
If you just want to find the count of how many four digit numbers sum to your target you can simply use divmod to get the digits and sum all the times the sum of the digits is equal to your target number:
def sum_digits(n, target):
n, sm = divmod(n, 10)
while n and sm <= target:
n, rem = divmod(n, 10)
sm += rem
return sm == target
def find_sum(targ):
for n in range(1000, 10000):
yield sum_digits(n, targ)
print(sum(findSum(36)))
You are checking from 0-target
which is wrong based on your description, find out the number of four digit numbers that add up to a specific value you should only be checking the target number.
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.