Issue with my code
rusi
rustompmody at gmail.com
Wed Feb 6 01:29:05 EST 2013
On Feb 5, 11:38 pm, maiden129 <sengokubasarafe... at gmail.com> wrote:
> Hi,
>
> I'm trying to create this program that counts the occurrences of each digit in a string which the user have to enter.
>
> Here is my code:
>
> s=input("Enter a string, eg(4856w23874): ")
> s=list(s)
>
> checkS=['0','1','2','3','4','5','6','7','8','9']
>
> for i in s:
> if i in checkS:
> t=s.count(i)
> if t>1:
> for k in range(1,t):
> s=s.remove(i)
> print(i, "occurs", t,"times.")
>
> elif t==1:
> print(i,"occurs 1 time.")
> else: pass
>
> but it keeps showing this error:
>
> t=s.count(i)
> AttributeError: 'NoneType' object has no attribute 'count'
>
> I wanted to show like this:
>
> Example:
>
> Enter a string: 3233456
>
> 3 occurs 3
> 2 occurs 1
> 4 occurs 1
> 5 occurs 1
> 6 occurs 1
Pythons 2.7 and later have dictionary comprehensions. So you can do
this:
>>> {item: s.count(item) for item in set(s)}
{'a': 1, 'b': 1, '1': 2, '3': 1, '2': 2, '4': 1}
Which gives counts for all letters. To filter out the digit-counts
only:
>>> digits="0123456789"
>>> {item: s.count(item) for item in set(s) if item in dig}
{'1': 2, '3': 1, '2': 2, '4': 1}
You can then print out the values in d in any which way you want.
[Starting with printing is usually a bad idea]
More information about the Python-list
mailing list