在getTotalX函数中查找错误。Python

2024-05-16 03:03:13 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我在一次通过python编程的采访中被问到以下问题:

The elements of the first array are all factors of the integer being considered The integer being considered is a factor of all elements of the second array These numbers are referred to as being between the two arrays. You must determine how many such numbers exist.

Input Format

The first line contains two space-separated integers describing the respective values of n, the number of elements in array a, and m, the number of elements in array b. The second line contains n distinct space-separated integers describing a0, a1, ... an-1. The third line contains m distinct space-separated integers describing b0, b1, ... bn-1.

Constraints

  • n,m in the range 1,10
  • ai in the range 1,100
  • bi in the range 1,100

Output Format

Print the number of integers that are considered to be between a and b.

Sample Input:

2 3
2 4
16 32 96

Sample Output:

3

Explanation:

  • 2 and 4 divide evenly into 4, 8, 12 and 16.
  • 4, 8 and 16 divide evenly into 16, 32, 96.

4, 8 and 16 are the only three numbers for which each element of A is a factor and each is a factor of all elements of B.

这是我写的代码(我只需要完成函数“getTotalX”)。剩余代码已存在):

Code. The function body getTotalX is what I wrote

然而,似乎我的解决方案是不正确的,但原因没有告诉我。寻找一些帮助来识别错误。你知道吗


Tags: andoftheintegersiniselementsall
1条回答
网友
1楼 · 发布于 2024-05-16 03:03:13

根据你的问题,让我们引入被认为是“X”的整数。你知道吗

  • 列表“a”中的所有项目都是“X”的因子
  • “X”是列表“b”中所有项目的系数。你知道吗

先找出b表中项目的所有因素,然后找出共同点价值观输出(n项)将显示“X”的可能值。你知道吗

然后找出这些可能值的因素。如果列表“a”中的项目是可能值列表的因子值的子集,则可能值(项目n)将被选择为最终值列出这些值是“X”值。我提供了我的代码作为示例答案。你知道吗

n,m=raw_input().split()
a = map(int,raw_input().split())
b = map(int,raw_input().split())

#Find factors for the list b items and store in (dictionary)dct
dct={}
for i in b:
    dct[i]=[]
for i in range (0,int(m)):
    for j in range(1,int(b[i])+1):
        if int(b[i])%j==0:
            dct[(b[i])].append(j)

#Find all factor values which are common for all key items. 
selct = None
for k,v in dct.items():
    if selct == None:
        selct = set( v )
    else:
        selct = selct.intersection( set(v) )
select1 = list( selct )
#The 'select1' contains all the common factors.
#[8, 1, 2, 4, 16]
#These are the possible values for 'X'.

#Then again find all the factor values for select list items.
dct2={}
for i in select1:
    dct2[i]=[]

for i in range (0,len(select1)):
    for j in range(1,int(select1[i])+1):
        if int(select1[i])%j==0:
            dct2[(select1[i])].append(j)

#{8: [1, 2, 4, 8], 1: [1], 2: [1, 2], 4: [1, 2, 4], 16: [1, 2, 4, 8, 16]}
#If the values of list a is a subset of values of dct2,
#the key value is a matching value for 'X'.
final=[]
for k,v in dct2.items():
    if(set(a).issubset(v)):
        final.append(k)
print len(final)

相关问题 更多 >