#just woke up from a random dream where I had a student explained to me this very simple algorythm.
#Seems pretty usless to me unless anybody can think of an actually use??
#crazy simple but the dream was so vivid I just had to put it down hahahaha
def power_rooter(num):
total = 1
while num > 1 and num//2 == num/2:
num = num / 2
total *= num
return total
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(power_rooter(16), 64)
test.assert_equals(power_rooter(4), 2)
test.assert_equals(power_rooter(8), 8)
test.assert_equals(power_rooter(6), 3)
for x in range(25):#displays all the numbers that only get diveded by 2 once
test.assert_equals(power_rooter(x), x/2)
I have undertaken a study of recursion. I find myself reaching for it fairly consistenly to solve different Kata but often find my understanding of certain concepts laking enough that I end up going with an iterative approach instead.
the goal of this was to produce in exponent notation the prime factors of a number.
The problem with this one is that because I created a new dictionary at the top of primeFactoring and because there is not an array or dictionary passed into it I ended up creating another function (factorPart) to fill the dictionary.
even ignoring all the messy formating code the solution seems convoluted.
What would be a better approach and what concepts should be understood to improve this answer?
def primeFactoring(n):
dict = {}
print(n)
factorPart(n,dict)
output = ""
for d, v in dict.items():
if v > 1:
output += str(d)+"^"+str(v)+" X "
else: output += str(d)+" X "
output = output.strip(" X ")
print(dict) #key being the factor and value being the number of occurrences
print(output) #formated in exponant form
return output
def factorPart(num, dict):
x = 2
while x <= num:
if num / x == num // x:
dict[x] = dict[x] + 1 if x in dict else 1
return factorPart(num // x, dict)
x+=1
import codewars_test as test
# TODO Write tests
import solution # or from solution import example
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case")
def test_case():
test.assert_equals(1 + 1, 2)
test.assert_equals(primeFactoring(11223144), "2^3 X 3^3 X 223 X 233")