Counting occurence of number in list upon user input - python

I'm trying to count the number of occurrence of a number in a list. So basically, i have a list:
lst = [23,23,25,26,23]
and the program will first prompt the user to choose a number from the list.
"Enter target number: "
and for example, if the target is 23, then it will print out how many times 23 occur in the list.
output = 3 #since there are three 23s in the list
Here's what I've tried and it resulted in an infinite loop:
lst = [23,23,24,25,23]
count = 0
i = 0
prompt= int(input("Enter target: "))
while i< len(lst)-1:
if prompt == lst[i]:
count+=1
print(count)
else:
print("The target does not exist in the list")
I'm not supposed to use any library so i would really appreciate if anyone could help me out by pointing out the fault in the code i written. Also, i would prefer the usage of 'while loop' in this as I'm practicing using while loops which i understand the least.

i is 0 always, which results in an infinite loop. Consider increasingi by 1 at the end of your loop.
Moreover you need to go until the end of the list, so the while loop condition should be:
while i < len(lst):
Putting everything together should give this:
while i< len(lst)a:
if prompt == lst[i]:
count+=1
print(count)
else:
print("The target does not exist in the list")
i += 1
which outputs:
Enter target: 23
1
2
The target does not exist in the list
The target does not exist in the list
3
By the way here is what a more pythonic implementation would look like:
lst = [23,23,24,25,23]
count = 0
target = int(input("Enter target: "))
for number in lst:
if number == target:
count += 1
print(count)
Output:
Enter target: 23
3
Or if you want to use a build-in function, you could try:
print(lst.count(target))
as smarx pointed out.

you should print after loops over, not every single loop
lst = [23,23,24,25,23]
count = 0
i = 0
prompt= int(input("Enter target: "))
while i< len(lst):
if prompt == lst[i]:
count+=1
i+=1
if count>0:
print(count)
else:
print("The target does not exist in the list")

You can use count for this task :
lst = [23,23,24,25,23]
prompt= int(input("Enter target: "))
cnt = lst.count(prompt)
# print(cnt)
if cnt:
print(cnt)
else:
print("The target does not exist in the list")
Output :
Enter target: 23
3
Enter target: 3
The target does not exist in the list

You may use collections.Counter which aims at performing what you desire. For example:
>>> from collections import Counter
>>> lst = [23,23,25,26,23]
>>> my_counter = Counter(lst)
# v element for which you want to know the count
>>> my_counter[23]
3
As mentioned in the official document:
A Counter is a dict subclass for counting hashable objects. It is an
unordered collection where elements are stored as dictionary keys and
their counts are stored as dictionary values. Counts are allowed to be
any integer value including zero or negative counts. The Counter class
is similar to bags or multisets in other languages.

You may try using filter for this.
>>> lst = [23,23,24,25,23]
>>> prompt= int(input("Enter target: "))
Enter target: 23
>>> len(filter(lambda x: x==prompt, lst))
3
>>> prompt= int(input("Enter target: "))
Enter target: 24
>>> len(filter(lambda x: x==prompt, lst))
1

Related

Count occurence of largest number using python [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 months ago.
Suppose that you entered 3 5 2 5 5 5 0 and input always ends with the number 0, the program finds that the largest number is 5 and the occurrence count for 5 is 4.
Input: i enter 3 5 2 5 5 5 0 and it shows nothing as result
Code:
currentnum = int(input('Enter Numbers List, to end enter 0: '))
maxx = 1
while currentnum > 0:
if currentnum > maxx:
max = currentnum
count = 1
elif currentnum == maxx:
count += 1
print('The Largest number is:', int(maxx), 'and count is', int(count))
Python doesn't have thunks.
currentnum = int(input('Enter Numbers List, to end enter 0: '))
This sets currentnum to the result of running int on the value returned by the input call. From this point on, currentnum is an int.
while currentnum > 0:
if currentnum > maxx:
max = currentnum
count = 1
elif currentnum == maxx:
count += 1
In this loop, you never take any more input, or reassign currentnum, so the loop will carry on forever, checking the same number over and over again.
If you assigned to currentnum at the end of your loop, you could take input in one-number-per-line. However, you want a space-separated input format, which can be better handled by iterating over the input:
numbers = [int(n) for n in input('Enter numbers list: ').split()]
max_num = max(numbers)
print(f"The largest number is {max_num} (occurs {numbers.count(max_num)} times)")
(Adding the 0-termination support is left as an exercise for the reader.)
Another, similar solution:
from collections import Counter
counts = Counter(map(int, input('Enter numbers list: ')))
max_num = max(counts, key=counts.get)
print(f"The largest number is {max_num} (occurs {counts[max_num]} times)")
I recommend trying your approach again, but using a for loop instead of a while loop.
Okay. So one of the most important things to do while programming is to think about the logic and dry run your code on paper before running it on the IDE. It gives you a clear understanding of what is exactly happening and what values variables hold after the execution of each line.
The main problem with your code is at the input stage. When you enter a value larger than 0, the loop starts and never ends. To make you understand the logic clearly, I am posting a solution without using any built-in methods. Let me know if you face any issue
nums = []
currentnum = int(input('Enter Numbers List, to end enter 0: '))
while currentnum > 0:
nums.append(currentnum)
currentnum = int(input('Enter Numbers List, to end enter 0: '))
max = 1
count = 0
for num in nums:
if num > max:
max = num
count = 1
elif num == max:
count += 1
print('The Largest number is:', max, 'and count is', count)
Now this can not be the efficient solution but try to understand the flow of a program. We create a list nums where we store all the input numbers and then we run the loop on it to find the max value and its count.
Best of luck :)
Use the standard library instead. takewhile will find the "0" end sentinel and Counter will count the values found before that. Sort the counter and you'll find the largest member and its count.
import collections
import itertools
test = "3 5 2 5 5 5 0 other things"
counts = collections.Counter((int(a) for a in
itertools.takewhile(lambda x: x != "0", test.split())))
maxval = sorted(counts)[-1]
maxcount = counts[maxval]
print(maxval, maxcount)
to make sure that operation stops at '0', regex is used.
counting is done by iterating on a set from the input using a dict comprehension.
import re
inp = "3 5 2 5 5 5 0 other things"
inp = ''.join(re.findall(r'^[\d\s]+', inp)).split()
pairs = {num:inp.count(num) for num in set(inp)}
print(f"{max(pairs.items())}")
Why not do it this way?
print(f"{max(lst)} appears {lst.count(max(lst))} times")

Cannot get += to work properly between functions in python

So my task is simple: I am to make two functions,
one which takes input from a user as a list of integers. (User enters how many entries, then begins entering them individually)
second function reads that list and returns how many times a chosen value was found in that list.
For some reason when combining these functions, the count does not stay at 0 and count whenever x is seen in the list; it just jumps to whatever the initial entry count was.
code is as follows:
def get_int_list_from_user():
list1 = []
numNums = int(input("Enter number count: "))
for x in range(numNums):
nextval = int(input("Enter a whole number: "))
list1.append(nextval)
return list1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count += 1
print("Target counted ", count, "time(s)")
return count
Over here is where I've tried different ways of calling the functions, but each time just ends up with the same result.
list1 = my_functions.get_int_list_from_user()
count = my_functions.count_target_in_list(int_list=list1)
I also tried this:
my_functions.count_target_in_list(int_list=my_functions.get_int_list_from_user())
This statement does not do what you think it does:
for target_val in int_list:
That essentially erases the original value passed into the function, and instead runs through the whole list, one element at a time. So, count will always be equal to the length of the list. You wanted:
for val in int_list:
if val == target_val:
count += 1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count += 1
print("Target counted ", count, "time(s)")
return count
instead, using this logic, you need to compare the loop values with the target value. in the code above the target value will be overridden by the iteration of the loop.
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for value in int_list:
if target_val == value :
count += 1
print("Target counted ", count, "time(s)")
return count

User Input For List of Floats Not Repeating

So I'm writing some code for my class and have to have a list of floats that are input by a user and print them out with normal iteration and reverse iteration, and I have basically all of it done. But when it should ask multiple times for the user input, it only asks one time then prints everything out and finishes without asking multiple times.
Any help would be appreciated as to why it isnt asking multiple times for input even though I have a for loop?
Is there an easier way to get a list of floats from user input that I don't know about?
Thanks
emptyList = []
userInput = high = low = total = float(input("Input a float > "))
emptyList.append(userInput)
for y in range(len(emptyList)-1):
userInput = float(input("Input a float > "))
emptyList.append(userInput)
total += emptyList
if userInput > high:
high = userInput
if userInput < low:
low = userInput
avg = total / len(emptyList)
above_avg = below_avg = 0
for y in range(len(emptyList)):
if emptyList[y] > avg:
above_avg += 1
if emptyList[y] < avg:
below_avg += 1
I checked your logic and according to that you are running your first for loop to the length of emptyList-1 so, after adding one element your emptylist's length becomes 1 and 1-1=0 so, your for loop will work only to 0th index and after that it will break.
I tried this
a=[]
b = []
t=0
count = 0
total = 0
for i in range(0,5):
x= float(input())
count = count + 1
total = total+ x
a.append(x)
print(count)
for i in range(count-1,-1,-1):
print('Aya')
print (i)
b.append(a[i])
for i in range(0,count-1):
for j in range(i,count):
if(a[i]>a[j]):
t=a[i]
a[i]=a[j]
a[j]=t
print(a)
print(b)
print(total)
print(total/count)
print(a[0])
and found it working perfectly fine for me and my for loop is taking values on every iteration.
You may try like this:
n = int(input("Number of inputs: "))
emptyList = []
while n:
userInput = float(input("Enter a Float > "))
emptyList.append(userInput)
n-=1
print(emptyList)

Appending an array and storing values

import array
a=[]
count = 0
while True:
i=int(input("A number "))
count = count + 1
for j in range (0, count):
a.append(i)
if (count==3):
break
Output:
[1, 2, 2, 3, 3, 3]
This appears when I prompt the program to print 'a' variable where I want 'a' to store values like
[1, 2, 3]
Can someone point out what's wrong with my code
you can use append but in a different way:
a = []
count = 0
while True:
a.append(input("A number "))
count += 1
if count == 3:
break
in your code you're appending the user's number 'count' times to a[], the way i did it, it will append one time for loop.
You can also use
for x in range(0,3)
a.append(input('A number'))
it work's as well.
The problem with your code, is that you add input number to the a one more time in each while iteration. It's the fault of for loop there.
Also, you don't have to import array.
Also, the if/break combo is redundant, just set iterations in the while loop.
Try this code:
a = []
count = 0
while count < 3:
i = int(input("A number: "))
a.append(i)
count += 1
print(a)
Variable A prints:
[1, 2, 3]
Lose the for loop:
a=[]
count = 0
while count < 3:
count += 1
a.append(int(input("A number ")))
The reason for duplicate values in your list, a, is the inner for loop. To illustrate with an example, consider what happens when you have already entered 1 as the input and now enter 2 as the input. At this moment, before your code begins executing the for loop, count has the value 2. The inner for loop will thus insert your input value, stored in variable i (in this case, 2), twice. Similarly, when you input 3, count has the value 3 and hence the inner for loop will execute three times.
The correct code should be as follows :
import array
a=[]
count = 0
while True:
i=int(input("A number "))
count = count + 1
if (count==3):
break
Remove the for-loop or simply do
a=[]
count=3
for i in range(count):
a.append(int(input("new number: ")))
Importing array isn't needed here.
And a little hint (if you don't allready know): i+=1 is the same as i=i+1
By playing the answer from deshu, you might also consider to use try and except so that the user could continue to type a number and prompt him if ever he enter non-numeric character.
a = []
count = 0
while count < 3:
try:
i = int(input("A number: "))
a.append(i)
count += 1
except:
print('Enter only a whole number.')
print(a)

Python list numbers with selection

I'm new to programming and currently learning python with reference book Python Programming Fundamentals. Here is one of the question I am dealing with:
1: Request user to input a list of numbers.
2: Then output those numbers which is in between 0 and 100.
Following is my code:
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output = output.append(float(e))
else:
output = output
print("The number between 0 and 100 are ", output)
And the error is:
File "c:\Users\HKGGAIT001\Desktop\1.py", line 7, in <module>
output = output.append(float(e))
builtins.AttributeError: 'NoneType' object has no attribute 'append
Supposing you are using Python3 (because it's unlikely the .split() would be successful in Python2)
This part is ok
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
You can write the loop like this
for e in lst:
if 0 < float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
Notice that there are two comparisons. There is an implicit and. This is called a chained comparison
This pattern can be reduced down to a single line using a list comprehension
output = [float(e) for e in lst if 0 < float(e) < 100]
But now we need to use float(e) twice
We can use another list comprehension to make lst already a list of float
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = [float(e) for e in s.split()] # Now lst is a list of floats.
output = [e for e in lst if 0 < e < 100]
Since we only need to iterate lst once, a tiny change makes it a generator expression. So your final program could be
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = (float(e) for e in s.split()) # Now lst is a generator of floats.
output = [e for e in lst if 0 < e < 100]
print("The number between 0 and 100 are ", output)
Your current code has a couple of issues, assuming you're in Python 2.x.
Using input causes Python to try to evaluate the user input, which will cause problems because you want them to input a list of numbers. raw_input will just give you what the user input without trying to parse it.
list.append is in-place, which means that the side effect of the function call will simply perform the append on the object it is called on, instead of returning a new object.
Try this:
s = raw_input("Please enter a list of numbers: ")
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
print("The number between 0 and 100 are ", output)
s = str(input("Please enter a list of numbers:"))
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 :
output.append(float(e))
print("The number between 0 and 100 are ", output)
else:
print("The number less than 0 or greter than 100 ", e)
s = input("Please enter a list of numbers:")
output = [each for each in s if each > 0.0 and each < 100.0]
print("The number between 0 and 100 are ", output)

Categories