Issue with my code

Terry Reedy tjreedy at udel.edu
Tue Feb 5 19:06:03 EST 2013


On 2/5/2013 1:38 PM, maiden129 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)

Unnecessary conversion.

> checkS=['0','1','2','3','4','5','6','7','8','9']

checks = '0123456789' is much easier to type.
>
> for i in s:
>      if i in checkS:

Loop through checks, not s

>          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

Replace everything with

s = input("Enter a string of digits: ")
for d in '0123456789':
     c = s.count(d)
     if c:
         print("{} occurs {} time{}".format(d, c, '' if c == 1 else 's'))

Enter a string of digits: 12233344499
1 occurs 1 time
2 occurs 2 times
3 occurs 3 times
4 occurs 3 times
9 occurs 2 times

-- 
Terry Jan Reedy




More information about the Python-list mailing list