hawkStudent - 4 months ago 19

Python Question

Very new to python... If I give a list that has two integers n and k, the function should return Boolean True. K has to be in the list the number of n times. For example, if I call matchingValues([1, 2, 1, 4, 1, 1], 1, 4) should return True since 1 is in the list 4 times. I'm guessing I have to use the .count() option but not sure how to write it... Wish I could give more code but unfortunately I am very lost

`def matchingValues(aList,n,k):`

Answer

What you want to do is define a variable which counts how many times n is in the list

```
found = 0
```

and then, iterate over your list with a loop

```
for x in range(0, len(aList)):
if aList[x] == n:
found += 1
return(found == k)
```

This is, however, if you want to avoid using the `count`

function:

```
return(aList.count(n)==k)
```

Using the manual, hand-written loop will allow you to exit the loop as soon as you know there are `k`

`n`

s in the list, if you want the loop to work like that (however, I have not provided that code. I have only written exactly what `count`

does)

If you want there to be AT LEAST `k`

`n`

s in `aList`

, this would work for you

```
found = 0
for x in range(0, len(aList)):
if aList[x] == n:
found += 1
if found == k:
return True
return False
```