PAT (Advanced Level) Practice 1010 Radix(Python)

程序员入门水平,贴出代码大家一起进步!
原题传送门

题目

Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is yes, if 6 is a decimal number and 110 is a binary number.

Now for any pair of positive integers N 1    a n d    N 2 N_1\;and\;N_2 N1andN2 , your task is to find the radix of one number while that of the other is given.

Input Specification:
Each input file contains one test case. Each case occupies a line which contains 4 positive integers:

N1 N2 tag radix

Here N 1 N_1 N1 and N 2 N_2 N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set { 0-9, a a a- z z z } where 0-9 represent the decimal numbers 0-9, and a a a- z z z represent the decimal numbers 10-35. The last number r a d i x radix radix is the radix of N 1 N_1 N1 if tag is 1, or of N 2 N_2 N2 if tag is 2.

Output Specification:
For each test case, print in one line the radix of the other number so that the equation N 1 = N 2 N_1 = N_2 N1=N2 is true. If the equation is impossible, print Impossible. If the solution is not unique, output the smallest possible radix.

Sample Input 1:

6 110 1 10

Sample Output 1:

2

思路||总结

  • 一开始用暴力方法,想当然认为最大进制为36,后来查阅资料发现最大进制是不确定的,不过使用暴力方法将最大进制设置足够大能得23分。
    -参考文章

    AC代码

import math


def fun(radix, string):
    sum = 0
    for i in range(len(string)):
        temp = ord(string[i])
        if ord('0') <= temp <= ord('9'):
            temp = temp - ord('0')
        else:
            temp = temp - ord('a') + 10
        sum += temp * math.pow(radix, (len(string) - i - 1))
    return sum


def main():
    string = input().strip().split()
    sum_a = fun(int(string[3]), string[int(string[2]) - 1])
    # another为另一个数字的位置
    another = 0
    if int(string[2]) - 1 == 0:
        another = 1
    # temp为数字中最大的值
    temp = max(list(string[another]))
    if '0' <= temp <= '9':
        temp = ord(temp) - ord('0')
    else:
        temp = ord(temp) - ord('a') + 10
    # low为进制的下限
    low = temp + 1
    # high为进制的上限,此处有坑,参考:https://blog.csdn.net/Joyceyang_999/article/details/81908299?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
    temp_a = fun(10, string[int(string[2]) - 1])
    if temp > temp_a:
        high = temp + 1
    else:
        high = int(sum_a) + 1
    flag = 0
    while low <= high:
        mid = (low + high) // 2
        if fun(mid, string[another]) < sum_a:
            low = mid + 1
        elif fun(mid, string[another]) > sum_a:
            high = mid - 1
        else:
            print(mid)
            flag = 1
            break
    if flag == 0:
        print('Impossible')


main()

你可能感兴趣的:(Python,PAT(Advance))