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

  • Comp Sci
  • Thread starter shivajikobardan
  • Start date
In summary, 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.
  • #1
shivajikobardan
674
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
  • #2
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

##\ ##
 
  • #3
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
 
  • #4
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 !

##\ ##
 
  • #5
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
  • #6
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

##\ ##
 
  • #7
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

FAQ: Playing with the digits codewar problem -- alternative way to solve it?

How can I solve the "Playing with the digits codewar problem" using an alternative method?

One alternative way to solve this problem is by using the built-in functions of the programming language you are using. For example, you can use the split() function to split the number into individual digits, then use a loop to perform the necessary calculations.

Is it more efficient to solve the problem using an alternative method?

Efficiency can vary depending on the specific implementation and the programming language used. In some cases, using built-in functions may be more efficient, while in others, a custom algorithm may be faster. It is important to test and compare different solutions to determine the most efficient approach.

Can I use a different data structure to solve this problem?

Yes, you can use a different data structure such as an array or a string to store and manipulate the digits of the number. However, it is important to consider the time and space complexity of using different data structures and choose the most appropriate one for the problem.

How can I optimize my code when using an alternative method?

There are several ways to optimize your code when using an alternative method to solve the "Playing with the digits codewar problem". Some strategies include reducing unnecessary operations, avoiding nested loops, and using efficient data structures and algorithms.

Are there any other alternative methods to solve this problem?

Yes, there are many different ways to approach and solve this problem. Some other alternative methods include using recursion, bitwise operators, or mathematical formulas. It is important to explore and experiment with different approaches to find the most efficient and effective solution.

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
Back
Top