The best and only way
This is my solution from a Kata I did called "What's a Perfect Power anyway?".
The code finds a pair of numbers a and b that are natural such that a^b=n if given n which is a given natural number. The code will retrun [a,b] if it finds a pair, or None if not.
def isPP(n): # is it a perfect prime
for factor in range(2, int(n/2) + 1):
if n % factor == 0: # find factors
power = 1
while True: # try higher and higher powers
power += 1
if not n % (factor ** power) == 0: # can it be the solution
break
elif n / (factor ** power) == 1: # is it the solution
return [factor, power]
return None
from solution import isPP
import codewars_test as test
from math import log, floor
@test.describe("perfect powers")
def perfect_powers():
@test.it("should work for some examples")
def should_work_for_some_examples():
test.assert_equals(isPP(4), [2,2], "4 = 2^2")
test.assert_equals(isPP(9), [3,2], "9 = 3^2")
test.assert_equals(isPP(5), None, "5 isn't a perfect power")
@test.it("should work for the first perfect powers")
def should_work_for_the_first_perfect_powers():
pp = [4, 8, 9, 16, 25, 27, 32, 36, 49, 64, 81, 100, 121, 125, 128, 144, 169, 196, 216, 225, 243, 256, 289, 324, 343, 361, 400, 441, 484]
for item in pp:
test.expect(isPP(item) != None, "the perfect power "+str(item)+" wasn't recognized as one")
Best not to use eval and best to keep "const" out of func.
wins = { "Rock": "Paper", "Paper": "Scissors", "Scissors": "Rock" } def dumbRockPaperScissors(player1, player2): if player1 == wins[player2]: return "Player 1 wins" elif player2 == wins[player1]: return "Player 2 wins" else: return "Draw"
- wins = {
- "Rock": "Paper",
- "Paper": "Scissors",
- "Scissors": "Rock"
- }
- def dumbRockPaperScissors(player1, player2):
Rock = {"Paper"}Paper = {"Scissors"}Scissors = {"Rock"}if player1 in eval(player2):- if player1 == wins[player2]:
- return "Player 1 wins"
elif player2 in eval(player1):- elif player2 == wins[player1]:
- return "Player 2 wins"
- else:
- return "Draw"