Count occurence of largest number using python [duplicate] - python

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")

Related

writing a loop that ends with a negative number and prints the sum of the positive numbers

i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)

one while loop to count up and down

How do you write a program to count up and down from a users integer input, using only one while loop and no for or if statements?
I have been successful in counting up but can't seem to figure out how to count down. It needs to look like a sideways triangle also, with spaces before the number (equal to the number being printed).
this is my code so far;
n = int(input("Enter an integer: "))
i = " "
lines = 0
while lines <= n-1:
print(i * lines + str(lines))
lines += 1
You can solve this by making good use of negative numbers and the absolute value: abs() which will allow you to "switch directions" as the initial number passes zero:
n = int(input("Enter an integer: "))
s = " "
i = n * -1
while i <= n:
num = n - abs(i)
print(s * num + str(num))
i += 1
This will produce:
Enter an integer: 3
0
1
2
3
2
1
0
Move the print line to after the while loop. Form a list of lists (or an array) in the while loop using the content from your current print statement. Then create a second statement in your single while loop to count down, which creates a second list of lists. Now you can sequentially print your two lists of lists.

Python: Finding Average of Numbers

My task is to:
"Write a program that will keep asking the user for some numbers.
If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places.
If at any point a 0 is entered, that should not be included in the calculation of the average"
I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0.
This is my current code:
count = 0
sum = 0
number = 1
while number >= 0:
number = int(input())
if number == '\n':
print ('hey')
break
if number > 0:
sum = sum + number
count= count + 1
elif number == 0:
count= count + 1
number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
You're very close! Almost all of it is perfect!
Here is some more pythonic code, that works.
I've put comments explaining changes:
count = 0
sum = 0
# no longer need to say number = 1
while True: # no need to check for input number >= 0 here
number = input()
if number = '': # user just hit enter key, input left blank
print('hey')
break
if number != 0:
sum += int(number) # same as sum = sum + number
count += 1 # same as count = count + 1
# if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}') # same as '... {:.2f} ...'.format(count/sum)
Why your code didn't work:
When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.
I really hope this helps you learn!
Try this:
amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
nums+=int(number)
amount += 1
print(round(nums/amount,2)) # Print out the average rounded to 2 digits
Input:
1
2
3
4
Output:
2.5
Or you can use numpy:
import numpy as np
n = []
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
n.append(int(number))
print(round(np.average(n),2)) # Print out the average rounded to 2 digits
A list can store information of the values, number of values and the order of the values.
Try this:
numbers = []
while True:
num = input('Enter number:')
if num == '':
print('Average is', round(sum(numbers)/len(numbers), 2)) # print
numbers = [] # reset
if num != '0' and num != '': numbers.append(int(num)) # add to list
Benefit of this code, it does not break out and runs continuously.

Why does this code not go to an infinite loop? (Python)

I'm currently beginning to learn Python specifically the while and for loops.
I expected the below code to go into an infinite loop, but it does not. Can anyone explain?
N = int(input("Enter N: "))
number = 1
count = 0
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
For this code to not infinitely loop, count needs to be >= N.
For count to increase, x needs to be equal to 2.
For x to be equal to 2 the inner for loop needs to run twice:
for i in range(1, number+1):
if number % i == 0:
x = x + 1
For the inner for loop to run twice number must not have factors besides 1 and the number itself. This leaves only prime numbers.
The inner loop will always set x == 2 when number is a prime number. As there are an infinite amount of prime numbers, count >= N will eventually be satisfied.
Try to change N to number:
while count < N:
while count < number:
Ok let's dissect your code.
N = int(input("Enter N: "))
number = 1
count = 0
Here you are taking user input and setting N to some number,
for the sake of brevity let's say 4. It gets casted as an int so it's now
an integer. You also initialize a count to 0 for looping and a number variable holding value 1.
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
Here you say while count is less than N keep doing the chunk of code indented.
So in our N input case (4) we loop through until count is equal to 4 which breaks the logic of the while loop. Your first iteration there's an x = 0 this means everytime you start again from the top x becomes 0. Next you enter a for loop going from 1 up to but not including your number (1) + 1 more to make 2. you then check if the number is divisible by whatever i equals in the for loop and whenever that happens you add 1 to x. After iteration happens you then check if x is 2, which is true and so you enter the if block after the for loop. Everytime you hit that second if block you update count by adding one to it. now keep in mind it'll keep updating so long as that if x == 2 is met and it will be met throughout each iteration so eventually your while loop will break because of that. Hence why it doesn't go forever.

Python: display the number of one's in any user given integer number

How do I display the number of one's in any given integer number?
I am very new to python so keep this in mind.
I need the user to input a whole number.
Then I want it to spit out how many one's are in the number they input.
i am using python 3.3.4
How would I be able to do this with this following code?
num = int(input ("Input a number containing more than 2 digits"))
count = 0
for i in range (0):
if num(i) == "1":
count = count + 1
print (count)
I don't know what i'm doing wrong
it gives me 'int' object is not callable error
Something like this:
Int is not iterable so you may need to convert into string:
>>> num = 1231112
>>> str(num).count('1')
4
>>>
str(num).count('1') works just fine, but if you're just learning python and want to code your own program to do it, I'd use something like this, but you're on the right track with the code you supplied:
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print(count)
Just to help you, here is a function that will print out each digit right to left.
def count_ones(num):
while num:
print(num % 10) # last digit
num //= 10 # get rid of last digit
num = 1112111
answer = str(num).count("1")
num = int(input (" Input a number to have the number of ones be counted "))
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print (' The number of ones you have is ' + str(count))
So i took the user input and added it to the correct answer since when i tried the answer from crclayton it didn't work. So this works for me.

Categories