Cannot get += to work properly between functions in python - 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

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

Why doesn't my code to count how many times a number can be divided by two work?

So I was trying to make a code to count how many times a number could be divided by two before reaching 1. I would like to be able to input any number I want and then use it in the function, and afterwards, to use the 'count' variable that was yielded outside the function.
print('Pick a number.')
number = input()
count = 0
def powerct(n):
while n >= 2:
n = n/2
count = count + 1
powerct(number)
print(count)
Python variables live in "scopes" - they are only visible while in scope, not out of it.
Functions got theire own scope - more about this here: Short Description of the Scoping Rules?
Your count from above the function definition is not the same as the count inside your function. You can remedy this by returning it from the function (or making it global - google this method if you like - I would not recommend it).
# python 3.6 -you are probably using 2.x if your input() gives you a number
number = int(input('Pick a number.')) # you need an int here, not a string
count = 0 # this is not the same count as
def powerct(n):
count = 0 # this one is a different count
while n >= 2:
n = n/2 # this is going to be a float in python 3
count += 1
return count
count = powerct(number)
print(count)
should solve your problem.
Edit:
# python 2.7 -realized youre using that by your use of input() giving int not string
number = input("Pick a number.")
count = 0 # this is not the same count as
def powerct(n):
count = 0 # this one is a different count
while n >= 2:
n = n/2
count += 1
return count
count = powerct(number)
print count
Try passing in the count to the function and returning it.
print('Pick a number.')
number = input()
count = 0
def powerct(n,count):
while n >= 2:
n = n/2
count = count + 1
return count
count = powerct(number,count)
print(count)
Alternatively, declare count as a global variable in the function, so it can acces it in its local scope:
print('Pick a number.')
number = input()
count = 0
def powerct(n):
global count
while n >= 2:
n = n/2
count = count + 1
powerct(number)
print(count)

Counting occurence of number in list upon user input

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

I cannot loop through a string in a function

I want to create a function that can take a positive integer n as input and return the sum of all that number's digit.
Below is my code:
def digit_sum(n):
string = str(n)
for number in string:
num = int(number)
total = 0
total += num
return total
but the error message is :
Your function fails on digit_sum(434). It returns 4 when it should return 11.
To my knowledge is that the for loop doesn't loop successfully. It only loops one time then return the value.
My questions are:
what' wrong with my code?
The reason I need to convert the number into string first is that integer cannot iterable?
Hope anyone could help me out.
Thanks!!
The problem is that you are setting total equal to zero within the loop. What this means is each pass through it adopts the most recent value, o + num, which in the last digit of this string is 4. Instead, try this:
def digit_sum(n):
string = str(n)
total = 0
for number in string:
num = int(number)
total += num
return total
The problem is that you are resetting the value of total back to 0 with each iteration of the loop. Move the initialization to above the loop, like this
def digit_sum(n):
string = str(n)
total = 0
for number in string:
num = int(number)
total += num
return total
You are resetting total on each iteration. Move total = 0 outside of the for loop.

How to get this to stop at 20

I would like for this to stop at 20. By which I mean, when it asks you to input another number it should stop after the 20th time.
Currently I have an accumulating counter that when it reaches 20 it prints the "Enter one more number". It does this at the 20th time, but afterwards it keeps going with asking you to input more numbers. I would like it to stop asking for input after the 20th time.
Thanks. This is apart of a larger homework problem.
def main ():
print()
print("Finds the lowest, highest, average, and total to 20 numbers.")
print()
number, count, numberlist = getnumber()
print("Stop.")
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
while count != 20:
number = float(input("Please enter one more number : "))
numberlist.append(number)
return number, count
main()
You could do this as follows:
def get_numbers(count=20):
numbers = []
numbers.append(float(input("Please enter a number : "))) # first
for _ in range(count-2):
numbers.append(float(input("Please enter another number : "))) # next 18
numbers.append(float(input("Please enter one more number : "))) # last
return numbers
Note that with a for loop you don't need to manually increment the loop counter. Also, there is no need to return count; you already know how many there will be.
First of all, note that you are not changing value of count inside while loop - that is why it never stops. After for is executed count is exactly 19 and never reaches 20 after that.
Second of all, you do not need while at all - for loop will work for 20 iterations and stop
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
return number, count, numberlist
Here is another option (your approach extended)
limit = 5
def main ():
print("Finds the lowest, highest, average, and total to {} numbers.".format(limit))
numbs = getnumber()
print(numbs)
print("lowest:", min(numbs))
print("highest:", max(numbs))
print("avg:", sum(numbs)/len(numbs))
print("total:", sum(numbs))
print("Stop.")
def getnumber ():
numberlist = []
for count in range(limit):
if count == limit-1:
number = float(input("Please enter one more number : "))
numberlist.append(number)
else:
number = float(input("Please enter another number : "))
numberlist.append(number)
return numberlist
main()
Output
Finds the lowest, highest, average, and total to 5 numbers.
[6.0, 3.0, 8.0, 4.0, 2.0]
('lowest:', 2.0)
('highest:', 8.0)
('avg:', 4.6)
('total:', 23.0)
Stop.
There are some problems with the code you posted. First of you should indent the return statement so it is part of getnumber. Secondly you return two values but unpack three values in main. If I fix those two things the code works. The reason that count is 20 after the for loop is that you declare count outside the loop, so on each iteration count will be set to the next integer and then incremented once more by
count = count + 1
If you did not have the extra increment inside the loop, count would be 19 after the for loop terminates because range(N) does not include N.
And you can rewrite the code with a list comprehension to get a very concise version
def getnumber(prompt, n):
return [float(input(prompt)) for _ in range(n)]
This will give you a list of the numbers.

Categories