Advertisement
B1KMusic

digitcount.py

Jul 12th, 2016
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. # Usage: python digitcount.py <argument>
  2. # This program counts the number of digits in <argument>, per digit, and then spits out the results sorted by digit, then by frequency
  3.  
  4. from sys import argv
  5.  
  6. def aswap(array, a, b):
  7.     temp = array[a]
  8.     array[a] = array[b]
  9.     array[b] = temp
  10.  
  11. def sync_sort(array, array2):
  12.     alen = len(array)
  13.  
  14.     for i in range(alen):
  15.         swapped = False
  16.  
  17.         for j in range(alen - 1, i, -1):
  18.             if array[j] < array[j - 1]:
  19.                 aswap(array, j, j-1)
  20.                 aswap(array2, j, j-1)
  21.                 swapped = True
  22.  
  23.         if not swapped:
  24.             break
  25.  
  26.     return array
  27.  
  28. def count(string):
  29.     digits = [0 for i in range(10)]
  30.  
  31.     for char in string:
  32.         digits[int(char)] += 1
  33.  
  34.     return digits
  35.  
  36. def report(digits, digit_nums):
  37.     for i in range(10):
  38.         print "%i: %i" % (digit_nums[i], digits[i])
  39.  
  40.  
  41. digits = count(argv[1])
  42. digit_nums = [i for i in range(10)]
  43.  
  44. print "By digit:"
  45. report(digits, digit_nums)
  46.  
  47. print "By frequency:"
  48. sync_sort(digits, digit_nums)
  49. digits.reverse()
  50. digit_nums.reverse()
  51. report(digits, digit_nums)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement