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)
Related
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")
I used the for loop code found on the internet but my professor asked me to convert it to while loop. I also don't have any idea how to code the sum part. We can't use any advanced stuff like def. I only started to code for class using python and I've honestly been stuck and haven't been catching up on the lessons. Any help is appreciated, thank you.
import array as arr
a=arr.array('i', [])
x=0
#size of array
arrsize=int(input("\nPlease Enter the number of elements: "))
#elements
print("\nPlease Enter "+str(arrsize)+" elements")
while(x<arrsize):
num=int(input("Enter a number: "))
a.insert(x,num)
x+=1
print("The elements are: ",a)
#duplicate elements
for i in range (0, len(a)):
for j in range (i+1, len(a)):
if(a[i]==a[j]):
print("\nThe duplicate elements are: ",(a[j]))
The statement
for i in range(x, y):
# Code to loop through here
Is essentially saying that you will loop through the loop code one time for every number i between x and y, including x and excluding y.
We can write an equivalent statement with a "while" loop. But we'll need to manage the variable i separately (including initializing it and incrementing it manually)
i = x
while i < y:
# Code to loop through here
i += 1
Now that you know how these 2 loop types are equivalent, you can use this equivalency to translate your code from a for loop to a while loop. You will need to do it twice; once for each for-loop in your code. I definitely recommend doing this on your own as it's an important part of the learning process!
The concept is the same as for the for-loop ,only difference will be increasing the indexes manually since while is used for condition based loops.
sum = 0 #to add each duplicates value
dup=[] #store each duplicate if needed
# increase the values of i,j manually
i = 0
while(i< len(a)):
j=i+1
while(j<len(a)):
if(a[i]==a[j]):
#if duplicate found then add
sum = sum + a[i]
dup.append(a[i])
j=j+1
i=i+1
print("\nThe duplicate elements are: ",dup)
print("Sum of of the duplicates :" , sum)
You don't have to import any modules, Python's builtin list is sufficient for your application. Start with an empty duplicates list, dup_sum = 0, and go through all elements of your array; if some element is not in duplicates and its count is greater than 1, insert it into duplicates and add the sum of occurrences to dup_sum. Finally, print the info. you want.
a = []
x = 0
# size of array
arrsize = int(input('Please Enter the number of elements: '))
# elements
print(f'Please Enter {arrsize} elements')
while x < arrsize:
num = int(input('Enter a number: '))
a.append(num)
x += 1
print(f'The elements are: {a}')
# duplicate elements
duplicates = []
dup_sum = 0
i = 0
while i < len(a):
d = a[i]
if d not in duplicates:
dcount = a.count(d)
if dcount > 1:
dup_sum += d * dcount
duplicates.append(d)
i += 1
print(f'The duplicate elements are {duplicates}')
print(f'Sum of duplicates = {dup_sum}')
Here is a sample run of the program:
Please Enter the number of elements: 5
Please Enter 5 elements
Enter a number: 1
Enter a number: 2
Enter a number: 2
Enter a number: 3
Enter a number: 3
The elements are: [1, 2, 2, 3, 3]
The duplicate elements are [2, 3]
Sum of duplicates = 10
I'm writing a program which should produce an output of something like this:
`Enter an integer (or Q to quit): 1
Enter an integer (or Q to quit): 2
Enter an integer (or Q to quit): 3
Enter an integer (or Q to quit): Q
(1 x 1) + (2 x 2) + (3 x 3) = 14`
So far, I've gotten the display of the equation right, but I can't seem to figure out how to actually get the total of the equation. Currently, the total displays 18 instead of the expected 14.
Here's my code so far:
`int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list)-1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
add = (x+x)
print(add)`
Any help would be greatly appreciated :))
Your problem exists in the here:
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
add = (x+x)
print(add)
Let us walk through what the code does to get a better understanding of what is going wrong.
With a list of [1, 2, 3] The for loop will iterate three times
On the first iteration, x will be assigned the value 1 because 1 * 1 is 1.
On the second iteration, x will be assigned the value 4 because 2 * 2 is 4. Notice that rather than the two values being added x's value being overwritten
On the third iteration, x will be assigned the value 9 because 3 * 3 is 9. Again the value is being overwritten.
After the loop, the variable add is created with the value x + x, or in our case 9 + 9 which is 18
This is why with the list [1, 2, 3] the value displayed is 18
Now that we have walked through the problem. We can see that the problem is overriding the value in the for loop then doubling the value before displaying it.
To fix these problems we can first remove the doubling giving the following code
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
print(x)
But the program still has the overriding problem so the value of a list [1, 2, 3] would be 9.
To fix this rather than overriding the value of x, let's create a new variable total that will have the result of the loop added to it every iteration rather than being overwritten.
total = 0
for i in range(0, len(int_list)):
total = total + (int_list[i]*int_list[i])
print(total)
Now let's walk through what the code does now.
With a list of [1, 2, 3] the for loop will iterate three times
On the first iteration, total will be assigned the value 1 because 0 + 1 * 1 is 1.
On the second iteration, total will be assigned the value 5 because 1 + 2 * 2 is 5. Notice how the previous value of the loop iteration is being added to the loop
On the third iteration, total will be assigned the value 14 because 5 + 3 * 3 is 14. Notice again how the previous value of the loop iteration is being added to the loop.
This gives us the correct result of 14.
One nice feature of python is the addition assignment which condentes A = A + B to A += B so it is possible to simply the following code to:
total = 0
for i in range(0, len(int_list)):
total += (int_list[i]*int_list[i])
print(total)
A reason this problem may have been so difficult is that the for loop is more complicated than it needs to be. It is possible that rather than iterating through a list of indices generated by a list of numbers then assessing the numbers from the list by their index. It is possible to iterate through the numbers directly.
With the that simplification your loop would look like this:
total = 0
for number in int_list:
total += number * number
print(total)
These changes would make your whole programme look like this:
int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list)-1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
total = 0 # start the total at zero as no values have been calculated yet
for number in int_list: # iterate through all values in the list
total += number * number # add to the total the number squared
print(total)
You duplicate only the last product (2 x 3 x 3 = 18).
Because you reassign x in your loop (x = (int_list[i]*int_list[i])) and than duplicate x with add = (x+x).
But you have to build the sum.
int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list) - 1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
x = 0
for i in range(0, len(int_list)):
x += (int_list[i] * int_list[i])
print(x)
You can try this
state= True
combi= []
while state:
user_input = input("Enter an integer (or Q to quit): ").lower()
if "q" in user_input:
state= False
else:
combi.append(int(user_input))
else:
final= sum([x+x for x in combi])
print(final)
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)
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