Continuing posts on new Python features, this one looks at the new walrus operator, which was introduced in Python 3.8. For a detailed description see Python Walrus Operator in Python 3.8.
This post looks at an example using pyxll to link from Excel, with code based on another Quora post from Dave Wade-Stein: How many four-digit numbers are there in which the sum of the digits is 3?
In addition to linking to an Excel UDF, my code allows the sum value to be set to any integer, and also returns the number of values generated and the execution time:
# Quora link - https://qr.ae/pAVa31
@xl_func()
@xl_arg('n', 'int')
def DigitSums(n):
stime = time.perf_counter()
sum_n_nums = []
minval = 1000 + n -1
maxval = n * 1000 +1
for num in range(minval, maxval):
# use the "walrus operator" to both assign a value to
# digit_sum and compare the value we assigned
if (digit_sum := sum(int(digit) for digit in str(num))) == n:
sum_n_nums.append(num)
sum_n_nums.insert(0, len(sum_n_nums))
sum_n_nums.insert(0, time.perf_counter() - stime)
return sum_n_nums
As noted in the code, the walrus operator, :=, calculates the sum of the digits in each number, assigns that value to the digit_sum variable, then compares the value to the required sum, n. If the values are equal the number is appended to the list of results.
The code and an example have been added to the Pandigitals file at: Pandigitals.zip
