printing number of items in list - python

Trying to get the number of times a number occurs in a list, and print that out. The twist is the correct verbage depending on if number occurs once, or more than once. Here is what I have, and I believe it is close. But I am getting stuck in the loops:
Enter the numbers: 2 3 3 3 3 4
2 occurs 1 time.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
4 occurs 1 time.
See how the many three's still loop. The answer eludes me. Any help would be appreciated.
s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
scores = [ eval(x) for x in items ] # Convert items to numbers
for j in scores:
z = scores.count(j)
if z > 1:
print( j, "occurs ", z, " times.")
else:
print( j, "occurs ", z, " time.")

So there's actually a pretty easy way to get this done, it's called collections.Counter. I'll run through all this though, because one thing you're doing is scary.
scores = [eval(x) for x in items]
That is the scariest code I've ever seen in my life. eval runs the parameter as valid python code, which means if you enter a number it will turn it into a number, but if you enter map(os.remove,glob.glob("C:/windows/system32")), well, your computer is toast. Instead, do:
s = input("Enter the numbers: ")
items = list()
for entry in s.split():
try: entry = int(entry)
except ValueError: continue
else: items.append(entry)
This will skip all items that AREN'T numbers. You may want to test items afterwards to make sure it's not empty, possibly something like if not items: return
Afterwards a collections.Counter is perfect.
from collections import Counter
count_scores = Counter(items):
outputstring = "{} occurs {} time"
for key,value in count_scores.items():
print(outputstring.format(key,value),end='')
if value > 1: print('s')
else: print()
That said, now that I've printed the whole thing up -- do you really need to turn these into integers? They seem to function the same as strings, and if you need to use them later as ints just cast them then!

You don't need use itertools here.
items = s.split() # Extracts items from the string
for elem in items:
print("{0} occurs {1} times".format(elem, items.count(elem)))
and get the result you want.
list objects in python already have a count method.
Edit: If you are dealing with large ammount of data, you can optimize the code a bit:
items = s.split() # Extracts items from the string
unique = set(items) # Remove repeated.
score = {}
for elem in unique:
coll.update({elem: items.count(elem)})
for elem in items:
print("{0} occurs {1} times".format(elem, score[elem]))

Try as bellow:
def count_items(str):
str = str.split()
uniq_str = set(str)
for i in uniq_str:
print(i, 'ocurs', str.count(i), 'times')
count_items( input("Enter the numbers: ") )
Output:
Enter the numbers: 2 3 3 3 3 4
2 ocurs 1 times
3 ocurs 4 times
4 ocurs 1 times

You are very close.
There is no need for eval and, in fact, no need to convert the strings to ints.
Try this:
s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
seen=set()
for j in items:
if j in seen:
continue
seen.add(j)
z = items.count(j)
if z > 1:
print( j, "occurs ", z, " times.")
else:
print( j, "occurs ", z, " time.")
I have used a set in order to find the unique elements.
If you run this:
Enter the numbers: 2 3 3 33 4
2 occurs 1 time.
3 occurs 2 times.
33 occurs 1 time.
4 occurs 1 time.
If you did not use a set, it would do this:
s = input("Enter the numbers: ")
items = s.split() # Extracts items from the string
for j in items:
z = items.count(j)
if z > 1:
print( j, "occurs ", z, " times.")
else:
print( j, "occurs ", z, " time.")
Run that:
Enter the numbers: 2 3 3 3 3 4
2 occurs 1 time.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
3 occurs 4 times.
4 occurs 1 time.

Related

python problem : print the frequencies of each number

I have to solve this problem like below manner only,
As you see in output, The only wrong thing in output I get is, 4 and 5 are count two times,
How I can get rid of this, please improvise below code only. do not change the code completely.
n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
while i<len(n):
a=0
count=0
while a<len(n):
if n[i]==n[a]:
count=count+1
a=a+1
print(n[i],"present",count,"times")
i=i+1
output:
1 present 1 times
2 present 1 times
3 present 1 times
4 present 2 times
4 present 2 times
5 present 2 times
5 present 2 times
you can use a Counter to do this efficiently https://docs.python.org/3/library/collections.html#collections.Counter
from collections import Counter
n = [1,2,3,4,4,5,5]
c = Counter(n)
for val, count in c.items():
print(f"{val} present {count} times")
prints:
1 present 1 times
2 present 1 times
3 present 1 times
4 present 2 times
5 present 2 times
I purpose to use set to do so. Does it suit your needs?
n_list = [1,2,3,4,4,5,5]
n_set = set(n_list)
for i in n_set:
print(i, " present ", n_list.count(i), "times")
Sticking to your original code and not the other many ways to solve this using libraries and dictionaries and whatnot.
You can check to see if you the item you are counting has already occurred in the list and skip processing it.
n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
while i<len(n):
a=0
count=0
#check if this value has already been encountered in the list
if n[i] not in n[:i]:
while a<len(n):
if n[i]==n[a]:
count=count+1
a=a+1
print(n[i],"present",count,"times")
i=i+1
If that's too advanced (in the event this is homework). You could create a second list to keep track of the values you've already checked:
n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
n2=[]
while i<len(n):
a=0
count=0
if n[i] not in n2:
while a<len(n):
if n[i]==n[a]:
count=count+1
a=a+1
print(n[i],"present",count,"times")
n2.append(n[i])
i=i+1
in general we should use a for loop if we iterate over a sequence because it's length is known. doing so avoids the need of helper variables. the code for this approach looks more clean and readable (2)
to get rid of the problem of duplicating outputs, we can use a list like seen (1). if a number is not in seen (3), we can print it out. to get the total number of occurrences of the number, we use nums.count(nums) (4). in the step after this, we add the current number used to the list 'seen' (5).
if the number is already in the list 'seen', the loop will take the next number from the input list.
nums = [1,2,3,4,4,5,5]
seen = [] # (1)
for num in nums: # (2)
if num not in seen: # (3)
print(num,"present",nums.count(num),"times") # (4)
seen.append(num) # (5)

How do I use .split in Python to assign an unknown amount of numeric inputs to variables?

I am tasked to create a program that counts the occurrence of numbers from 1-100.
The problem I have right now is using .split to assign each input to a variable, but the user is able to enter how many numbers as they desire as long as it is more than 10. I am pretty sure I would need to use a List of some sort but my knowledge is kind of limited and would like some guidance!
numberList = input("Enter 1 to 100 ")
Check = numberList.replace(" ","")
Write a loop that continuously parses the input and adds recognized numbers to a list until that list has at least 10 numbers.
numbers = []
while True:
n = 10 - len(numbers)
if n <= 0:
break
s = input("Enter at least {} more numbers: ".format(n))
for v in s.split(" "):
try:
v = int(v)
except ValueError:
continue
numbers.append(v)
So you want to create a list of integers and print an error if the user entered something wrong. Go with the principle of "It's easier to ask forgiveness than it is to get permission". That is, simply try to convert the numbers to integers and if something fails abort mission. For example:
while True:
userInput = input("Enter at least 10 integers between 1 and 100: ")
try:
numberList = [int(substring) for substring in userInput.split(" ")]
if len(numberList) < 10:
print("Enter at least 10 numbers")
else:
break
except ValueError:
print("You entered a non-numeric character; please try again")
Finally you want to count the number of appearances of each number. The nicest way to do this (in my opinion) is the Counter collection. With this you just do the following
from collections import Counter
counter = Counter(numberList)
To split the input, which from what i guess from your question would look something like '1 2 45 12', simply use .split(' '), as was already pointed out by some other people. That will give you a list of the values, but in string format. To convert them to integers, you can use map, which will apply an operation to every element of a list and return an iterator, which can be converted to a new list:
numberList = list(map(int, numberList))
If one of the elements of that list can't be converted to an integer, a ValueError exception will be raised. Catch that with try... except to print your error message.
For the second part, i would simply iterate over all items ins the list, use list.count(item)(info) which will return the number of occurences of that item, and store every item, that has already been checked, in a separate list to avoid double-checking any.
Code:
numberList = input("Enter at least 10 integers between 1 and 100: ").split(' ')
if len(numberList) < 10:
numberList.extend(input("Enter at least {} more integers between 1 and 100: ".format(10-len(numberList))).split(' '))
try:
numberList = list(map(int, numberList))
except ValueError:
print("You entered a non-numeric character; please try again!")
print("You have entered {} integers.".format(len(numberList)))
checked_list = []
for i in numberList:
if i not in checked_list:
print("The integer {} occured {} time(s).".format(i, numberList.count(i)))
checked_list.append(i)
Output:
Enter at least 10 integers between 1 and 100: 1 2 3 4 5 6 7
Enter at least 3 more integers between 1 and 100: 8 1 2
You have entered 10 integers.
The integer 1 occured 2 time(s).
The integer 2 occured 2 time(s).
The integer 3 occured 1 time(s).
The integer 4 occured 1 time(s).
The integer 5 occured 1 time(s).
The integer 6 occured 1 time(s).
The integer 7 occured 1 time(s).
The integer 8 occured 1 time(s).
You can do this:
numberList = input("Enter at least 10 integers between 1 and 100: ").split(" ")
if len(numberList) < 10:
print("Enter at least 10 integers between 1 and 100: ")
To count how many times each number appears:
from collections import Counter
count = Counter(numberList) # eg count = [1,4,9,7,1]
for k,v in count.items():
print(str(k) + " appears " + str(v) + " times")

Finding the next entity in a list python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

Python Dice Game Points Variables Not Changing

rounds = input()
for i in range(int(rounds)):
score = input(int())[0:3]
a = score[0]
d = score[2]
antonia = 100
david = 100
for scores in score:
if a < d:
antonia -= int(a)
if a > d:
david -= int(d)
elif a == d:
pass
print(antonia)
print(david)
Input Expectation:
The first line of input contains the integer n (1 ≤ n ≤ 15), which is the number of rounds that
will be played. On each of the next n lines, will be two integers: the roll of Antonia for that round,
followed by a space, followed by the roll of David for that round. Each roll will be an integer
between 1 and 6 (inclusive).
Output Expectation: The output will consist of two lines. On the first line, output the number of points that Antonia has
after all rounds have been played. On the second line, output the number of points that David has
after all rounds have been played.
Input:
4
5 6
6 6
4 3
5 2
Output:
100 <--(WHY???)
94
Why is the bottom value(david) changed as it should correctly, but the top is not?? What am I doing different for antonia thats making it not output the same function as david?
Within your first loop, you continuously update a and d. So, at the end of the loop, a and d simply have the values corresponding to the last set of input.
Additionally, within your second loop, you are not iterating over all the scores, but rather the very last set of input. Before going any further, I would suggest you go back and understand what exactly your code is doing and trace how values change.
In any case, one way to solve your problem is:
rounds = input("Number of rounds: ")
scores = []
for i in range(int(rounds)):
score = input("Scores separated by a space: ").split()
scores.append((int(score[0]), int(score[1]))) #Append pairs of scores to a list
antonia = 100
david = 100
for score in scores:
a,d = score # Split the pair into a and d
if a < d:
antonia -= int(a)
if a > d:
david -= int(d)
elif a == d:
pass
print(antonia)
print(david)

Python: Select Only Parts of an input?

Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.

Categories

Resources