Currently learning python in my course and I'm a little confused on this part, unfortunately my next prac isn't until next week so I thought I'd ask here.
We're supposed to write a function called find() that takes a list, searches for the value in the list and returns as a new list of the positions in the list the number was found. Eg:
list = 2, 3, 7, 2, 3, 3, 5 number = 3
la salida sería:
0, 4, 5
The question requires us to use a loop but not to use built-in functions, slice expressions, list methods, or string methods unless specified, with the only ones specified for this part being:
We're given a file we're not allowed to edit:
import test_lists list_A = ['q', 'w', 'e', 'r', 't', 'y'] print(test_lists.find(list_A, 'r')) print(test_lists.find(list_A, 'b'))
From what I've attempted in a file named test_lists, the output gives
<function find at 0x0000000003B89D90>:
def find(list1, listValue): findList = 0 for x in range(findList): findList.find(list1, value) return find
anyone able to please push me in the right direction and explain it to me? We were told we could use
.append() but I don't seem to understand how that would fit into this situation as from what I am aware append only adds to to the string. I feel like I'm pretty far off track.
preguntado el 28 de mayo de 14 a las 13:05
>>> lst = 2, 3, 7, 2, 3, 3, 5 >>> number = 3 >>> [i for i, x in enumerate(lst) if x == number] [1, 4, 5] >>> list_A = ['q', 'w', 'e', 'r', 't', 'y'] >>> [i for i, x in enumerate(list_A) if x == 'r'] 
Por cierto, no uses
list as a variable name. It shadows builtin type/function
>>> lst = 2, 3, 7, 2, 3, 3, 5 >>> number = 3 >>> [i for i in range(len(lst)) if lst[i] == number] [1, 4, 5]
Will this do ?
def find(list1, listValue): found =  for index in range(0,len(list1)): if list1[index]==listValue: found.append(index) return found
I guess you can't use
Then, you you have to do the same thing by yourself : iterate over the indexes of the list and for each index, see if the element is the expected element. If it is, you had the index into your result list :
expected_element = 3 my_list = [...] result_list =  for i in range(len(my_list)): if my_list[i] == expected_element: result_list.append(i)
It's not very pythonic but if you have so much contraint, i think it's good
Y si no puedes usar
len(my_list), you can get the size by iterate over a first time :
def size(l): s = 0 for _ in l: s += 1 return s
A list comprehension would be the most Pythonic way to do this. But writing it explicitly for instructional purposes, here is another way to do it.
def find(number, numList): indexMatches =  # initialize your index array for index in range(len(numList)): # iterate over the list of values if number == numList[index]: # compare the number against the current value indexMatches.append(index) # if they match, add it to the index array return indexMatches # return the list of indexes where matches occured find(3, [2,3,7,2,3,3,5])
[1, 4, 5]