heagan
heagan

Reputation: 31

A for loop for a variable += user input

So I wanna try to separate some lines of user input using space, that input can only handle int, I created a variable that removed the same number from the splitted user input

for item in separated:
  print(item)
  loopCount = noOccur.count(item)
  if loopCount == 0:
    noOccur += item

Some weird thing happened if I inputted a number that's more than 10 for example

userIn = input('Numbers:   ') # 0 8 89

but that function separated the last number into ['0', '8', '8', '9']

that function worked in single digits but it doesn't work in double digits

userIn = input('Please enter your numbers:  ') # 689 688 3405
separated = userIn.split()
noOccur = []

for item in separated:
  print(item)
  loopCount = noOccur.count(item)
  if loopCount == 0:
    noOccur += item

length = len(noOccur)
i = 0
print(noOccur) # ["6", "8", "9", "6", "8", "8", "3", "4", "0", "5"]
print(separated)
while i < length:
  tempVar = noOccur[i]
  print(str(tempVar) + ": " + str(separated.count(tempVar)))
  i += 1

I think my for loop is a little bit broken, because I tried split(" ") as mentioned in the answer but it still added it individually

Upvotes: 0

Views: 126

Answers (3)

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

Use collections.Counter, to count the number of occurences of a hashable element (like a string or a number) in an iterable. You can use a Counter object just like a dict for further processing.

from collections import Counter

userIn = input('Numbers:   ') # 689 688 3405 688
separated = userIn.split() # ['689', '688', '3405', '688']

noOccur = Counter(separated) # Counter({'689': 1, '688': 2, '3405': 1})

for k,v in noOccur.items():
    print(f'{k}: {v}')
# '689': 1
# '688': 2
# '3405': 1

Upvotes: 2

Tony
Tony

Reputation: 764

You can try with append to the noOccur list like this:

userIn = input('Please enter your numbers:  ') # 689 688 3405
separated = userIn.split(' ')
noOccur = []

for i in separated:
    loopCount = noOccur.count(i)
    if loopCount == 0:
        noOccur.append(i)

print(noOccur)

length = len(noOccur)
items = 0

while items < length:
    tempVar = noOccur[items]
    print(str(tempVar) + ": " + str(separated.count(tempVar)))
    items += 1

Result:

Please enter your numbers:  689 688 3405
['689', '688', '3405']
688: 1
689: 1
3405: 1

Upvotes: 0

Renaud
Renaud

Reputation: 2819

I checked the update of your function and if you don't have any restriction the best will be to use a dictionnary:

userIn = input('Numbers:   ')


separated=userIn.split()
print(separated)

noOccur = {}

for item in separated:
  if item in noOccur.keys():
      noOccur[item]+=1
  else:
      noOccur[item]=1

for k,v in noOccur.items():
    print(str(k) + ": " + str(v))

Result:

Numbers:   1 2 3 100 1 2
['1', '2', '3', '100', '1', '2']
1: 2
2: 2
3: 1
100: 1

Upvotes: 2

Related Questions