标题: ChatGPT对指定大数求指定base的系数
创建: 2023-03-17 19:46 更新: 2023-03-17 20:01 链接: https://scz.617.cn/python/202303171946.txt
Q:
请用Python实现这样一个函数,第一个参数是大数large,第二个参数表示进制base, 求large在base时的coefficient,以list形式显示coefficient,比如
get_coefficient( large=1234, base=10 )
输出
[1, 2, 3, 4]
Answer in English always
A: ChatGPT 2023-03-17
def get_coefficient ( large, base ) : coefficient = [] while large > 0 : large, digit = divmod( large, base ) coefficient.append( digit ) # # end of while # return coefficient[::-1] if coefficient else [0]
The function works by repeatedly dividing the large by the base and appending the remainder as a digit to the list coefficient. The loop continues until large is reduced to zero.
The [::-1] slice notation is used to reverse the order of the digits in coefficient, since we are computing them in reverse order. The if coefficient else [0] part ensures that the function returns [0] if large is zero, since there is no coefficient in that case.
Here's an example usage of the function:
get_coefficient(1234, 10) [1, 2, 3, 4]
get_coefficient(1234, 2) [1, 0, 0, 1, 0, 1, 0, 1, 0]
get_coefficient(1234, 16) [4, 13, 2]
def show_coefficient ( large, base ) : coefficient = [] while large > 0 : large, digit = divmod( large, base ) coefficient.append( hex( digit ) ) # # end of while # return coefficient[::-1] if coefficient else ['0x0']
end of show_coefficient
show_coefficient( 3215031751, 2**30 ) ['0x2', '0x3fa17dc7']
show_coefficient( 3215031751, 2**15 ) ['0x2', '0x7f42', '0x7dc7']