Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่ามี permutation ของ N ที่เป็นกำลังของ K หรือไม่ ใน Python


ปัญหา

ให้จำนวน n และ m ตรวจสอบว่ามี permutation ของหลักของ n ที่เท่ากับ m^k สำหรับ k ≥ 1 หรือไม่

ตัวอย่าง

n = 7182, m = 12
12³ = 1728 → permutation ของ 7182 → True

แนวคิดการแก้ปัญหา

  1. สร้างกำลังของ m จนเกิน 10¹⁸
  2. สำหรับแต่ละกำลัง ตรวจสอบว่าเป็น permutation ของ n (นับความถี่หลัก)

โค้ดตัวอย่าง

from collections import Counter

def digit_count(num):
    return Counter(str(num))

def solve(n, m):
    target_count = digit_count(n)
    power = m
    while power <= 10**18:
        if digit_count(power) == target_count:
            return "An all digit-permutation of n is equal to a power of m"
        power *= m
    return "No all digit-permutation of n is equal to a power of m"

print(solve(7182, 12))
# An all digit-permutation of n is equal to a power of m

อินพุต / เอาต์พุต

Input:  7182, 12
Output: An all digit-permutation of n is equal to a power of m