我想使用以下字典:
示例: {[8, 16]:[[1,2,4,8],8], [16, 24]: [[1,2,3,4,8,12], 12]}
8和16是将要输入的两个数字,我需要构建上述字典。
使用setdefault,我可以为字典中的值创建一个列表,但不能为键创建一个列表。
下面是我的代码:
#!/usr/bin/env python
"""
This Program calculates common factors between two Numbers , which
is stored on a list and also greatest common factor is also computed.
All this is stored in a dictionary
Example: { '[n1, n2]': [[Commonfac1(n1,n2), Commonfac2(n1,n2)....Commonfacn(n1,n2)],GreatestCommonFactor] }
"""
def Factors(number):
result = []
for i in range(1, number+1):
if (number % i) == 0:
result.append(i)
return result
def Common_Factors(n1, n2):
result = []
for element in n1:
if element in n2:
result.append(element)
return result
def greatest_common_factor(common_factors):
count = 0
length = len(common_factors)
current_largest = common_factors[count]
for i in common_factors:
count += 1
if count <= length -1:
if current_largest < common_factors[count]:
current_largest = common_factors[count]
return current_largest
def main():
n1 = 8
n2 = 16
result1 = Factors(n1)
result2 = Factors(n2)
CF = Common_Factors(result1, result2)
GCF = greatest_common_factor(CF)
dict = {}
dict.setdefault([n1, n2], []).append(CF)
print dict
if __name__ == '__main__':
main()
当我运行上述程序时,我遇到以下错误:
$ python math74.py
Traceback (most recent call last):
File "math74.py", line 58, in <module>
main()
File "math74.py", line 54, in main
dict.setdefault([n1, n2], []).append(CF)
TypeError: unhashable type: 'list'
请问如何实现上述功能?
为了更加清晰,下面是示例数据: {[8, 16]:[[1,2,4,8],8], [16, 24]: [[1,2,3,4,8,12], 12]}
其中8和16是用户输入的两个数字,1、2、4、8是它们的公因数,而8是最大公因数。
d = {(1,2) : 3, (10,20) : 30}
。要访问一个键,您可以这样写:d[1,2]
。 - FMca = [8,16]
,d[a] = [[1,2,4,8],8]
,a.append(32)
,会发生什么? - Adam Smith