Comp Sci Playing with the digits codewar problem -- alternative way to solve it?

  • Thread starter Thread starter shivajikobardan
  • Start date Start date
AI Thread Summary
The discussion focuses on finding alternative solutions to the "Playing with digits" Codewars problem, emphasizing a mathematical approach rather than brute force coding. A user shares a Python solution that calculates the sum of the digits raised to increasing powers and checks if this sum is a multiple of the original number. There is a preference for flowcharts or algorithms over code, although some participants provide code with comments to aid understanding. The conversation also touches on code style improvements and the importance of readability in programming. Overall, the participants seek to explore different methods of solving the problem while enhancing their coding skills.
shivajikobardan
Messages
637
Reaction score
54
Homework Statement
need alternative way to solve the problem
Relevant Equations
none
https://www.codewars.com/kata/5552101f47fc5178b1000050/train/python

playing with digits codewar problem-looking for alternative way to solve this problem-mathematical way to solve this problem-:

This is how I youtube'd and found a solution-:

Code:
n=89
p=1
my_sum=0
for num in str(n):
    my_sum=my_sum+(int(num))**p
    p=p+1
if(my_sum%n==0):
    print(int(my_sum/n))
else:
    print(-1)

What is another way to solve this problem? I prefer no code solutions with flowcharts/algorithms rather than writing codes so that I can try writing codes on my own. But I of course won't mind code with comments tbh.
 
Physics news on Phys.org
shivajikobardan said:
playing with digits codewar problem
...
This is how I youtube'd
Isn't that cheating instead of playing ?

need alternative way to solve the problem
In what sense ? Do you think there is another way than the brute force in the solution you youtubed ?

Anyway, the kata website should allow you to view accepted solutions

##\ ##
 
Here's my solution...
Python:
def checkNum(num, p):
    """
    checkNum(num, p) -- determine whether the sum of powers of digits of a number
    add to an integer multiple of the number.
    If num = d_nd_(n-1)...d_1d_0, determine whether
    d_n**p + d_(n-1)**(p+1) + ... + d_1**(p+n-2) + d_0**(p+n-1) == k*num.
    Examples:
      89 == 8**1 + 9**2 == 89 == 1 * 89
      695 == 6**2 + 9**3 + 5**4 = 36 + 729 + 625 == 1390 == 2 * 695

    Parameters
    ----------
    num - (int) -- the number to check.
    p   -    (int) -- the starting exponent.

    Return value
    ------------
    Returns the quotient of the sum of powers of the digits divided by num,
    if the sum is an integer multiple of num. Otherwise, the function returns -1.     
    """   

    digitSum = 0
    for digit in str(num):
        digitSum = digitSum + (int(digit)) ** p
        p += 1

    if(digitSum % int(num) == 0):
        return(digitSum // int(num))
    else:
        return(-1)

       
numList = [(89, 1), (695, 2), (46288, 3), (92, 1)]

for pair in numList:
    # Outputs the number and if relevant, the integer multiple.
    print(f"Number: {pair[0]}, {checkNum(pair[0], pair[1])}")
Remarks
I wrote a function, checkNum() that takes two parameters -- a number and the starting exponent. I have included detailed comments to explain how this works. I don't know if you (@shivajikobardan) have learned about functions yet, but if not, you probably will do so soon.

The numList variable near the bottom is a list that contains tuples, with each tuple holding the number we're working with and the starting exponent. For example, the tuple (89, 1) indicates that we want to check whether 89 is some integer multiple of ##8^1 + 9^2##.

Near the bottom of my code, I iterate through each pair of numbers in numList, and call checkNum(), passing the number (pair[0]) and the starting exponent (pair[1]).

Style tip
A common mistake that new programmers make is to not include white space. IOW, they jam things together, making the code more difficult to read, which often makes it more difficult to debug, both for the program writer and anyone else who needs to understand the code.

Instead of writing this: my_sum=my_sum+(int(num))**p, with no spaces between operators, insert a space before and after each operator, like this: my_sum = my_sum + (int(num)) ** p
 
Is that an alternative way or just the same way but decently written up ?

I actually played with this kat thing and it (code in post #1 with minimum editing) works nicely indeed !

##\ ##
 
BvU said:
Is that an alternative way or just the same way but decently written up ?
The algorithm is the same as was posted earlier, but I put the code uses a function that takes a pair of numbers as parameters. Part of my intent was to show the OP how to use functions, lists, and tuples, as well as to convey some idea of a better style as regards using white space.
 
  • Like
Likes BvU
Ok, I get it. The kata site sort of invites one to to replace "# your code" with whatever, so that's what I tried. And it worked! A wonderful resource to learn python for someone who was spoon-fed Fortran IV and weaned with DECfortran 77 :wink:
Python:
def dig_pow(n, p):

    my_sum=0
    for num in str(n):
        my_sum=my_sum+(int(num))**p
        p=p+1
    if(my_sum%n==0):
        return int(my_sum/n)
    else:
        return -1

Python:
test.assert_equals(dig_pow(89, 1), 1)
test.assert_equals(dig_pow(92, 1), -1)
test.assert_equals(dig_pow(46288, 3), 51)
with output tab window:
Code:
Time: 514msPassed: 3Failed: 0
[HEADING=1]Test Results:[/HEADING]
Test Passed
Test Passed
Test Passed
You have passed all of the tests! :)

Haven't found out how to see other solutions. The Past Solutions tab just shows the same code as in post #1

##\ ##
 
BvU said:
Python:
def dig_pow(n, p):
    my_sum=0
    for num in str(n):
        my_sum=my_sum+(int(num))**p
        p=p+1
    if(my_sum%n==0):
        return int(my_sum/n)
    else:
        return -1

Python has even more to offer: in this case infix operators (+=) and the (admittedly horrible syntax) ternery expression. And you do need more spacing:

Python:
def dig_pow(n, p):
    sum = 0
    for num in str(n):
        sum += int(num) ** p
        p += 1
    return -1 if (sum % n) else sum // n

BvU said:
Haven't found out how to see other solutions. The Past Solutions tab just shows the same code as in post #1
You need to 'submit' your solution - that runs it against many more test cases.

It would be nice to see a functional solution, but again the Python syntax is not elegant. Works well in JavaScript:
JavaScript:
function digPow(n, p) {
  const sum = `${n}`
    .split('')
    .reduce((sum, digit, i) => (sum + digit ** (p + i)), 0);
  return sum % n ? -1 : sum / n;
}
 
  • Like
Likes BvU

Similar threads

Replies
6
Views
5K
Replies
6
Views
3K
Replies
3
Views
2K
Replies
13
Views
3K
Replies
13
Views
2K
Replies
1
Views
2K
Replies
8
Views
2K
Back
Top