How do I make the code find the positions that x repeats and put them in output one per line? Python

Asked

Viewed 33 times

1

How do I make sure that, in the following code, the values that show the position where x is repeated are each one per line? Except for the clasp and comma.


from collections import defaultdict
n = int(input(''))
vetor = []
for c in range(n):
    if n >=1 and n <= 100:
        vetor.append(int(input()))
x = int(input(''))
if x in vetor:
    repete = vetor.count(x)
    print(repete)
posições = defaultdict(list)
for i, x in enumerate(vetor):
    posições[x].append(i)
for x in posições:
    if len(posições[x]) > 1:
        print(str(posições[x]).strip('[]'))

Assuming my N is 5, my list is 2,2,2,3,2 and x is 2, the output is being that:

4 #numero de vezes que o X se repete
0,1,2,4 #posições que o X se encontra repetido
  • Purpose of the code is what? It’s very confusing. But I’ll take the risk that it’s checking repeated numbers on a list, but there are some restrictions (looking at the code), it looks like an exercise...

  • I need to make a set of size N , after that, give the N values. With this, I need to make an X that I put is identified in the set, then it is necessary that I speak how many times it repeats (thing I was able to do) and in which positions it repeats. Everything has to be on different lines in the output.

1 answer

2


If you want to print one position per line, make a for and prints each element one at a time.

Another detail is that you don’t need to use defaultdict. If you only want the positions in which an element occurs, make a loop simple, compare the element with the value and store the position in the list of positions:

vetor = [2, 2, 2, 3, 2]
x = 2
posições = []
for i, n in enumerate(vetor):
    if n == x:
        posições.append(i)

for i in posições:
    print(i)

The exit is:

0
1
2
4

Another alternative is to use comprehensilist on, much more succinct and pythonic:

vetor = [2, 2, 2, 3, 2]
x = 2

# usando list comprehension
posições = [ i for i, n in enumerate(vetor) if n == x ]

print('\n'.join(map(str, posições)))

And I also showed you another alternative to print, using join - in the case, it joins the elements of the list by placing the \n (line breaking) between them. The detail is that I had to use map to convert the numbers to string, otherwise the join makes a mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.