Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.5 KiB

  1. import string
  2. # list with all valid characters
  3. CHARACTERS = list(string.ascii_letters) + [" ", ",", "'", "?", "Ä", "ö"]
  4. def letter_frequency(sentence):
  5. # init a list of tuples for all valid characters
  6. frequencies = [(c, 0) for c in CHARACTERS]
  7. for letter in sentence:
  8. # find index of selected character
  9. index = CHARACTERS.index(letter)
  10. # increment counter of selected character
  11. frequencies[index] = (letter, frequencies[index][1] + 1)
  12. return frequencies
  13. print(letter_frequency("Hello world, what's going on? Äötsch"))
  14. # sorting self constructed classes by overriding their __lt__ method
  15. class WeirdSortee:
  16. def __init__(self, string, number, sort_num):
  17. self.string = string
  18. self.number = number
  19. self.sort_num = sort_num
  20. def __lt__(self, object):
  21. if self.sort_num:
  22. return self.number < object.number
  23. return self.string < object.string
  24. def __repr__(self):
  25. return "{}:{}".format(self.string, self.number)
  26. a = WeirdSortee('a', 4, True)
  27. b = WeirdSortee('b', 3, True)
  28. c = WeirdSortee('c', 2, True)
  29. d = WeirdSortee('d', 1, True)
  30. l = [a, d, c, b]
  31. print(str(l) + " unsorted")
  32. l.sort()
  33. print(str(l) + " sorted by number")
  34. for i in l:
  35. i.sort_num = False
  36. l.sort()
  37. print(str(l) + " sorted by character")
  38. # using the 'key' argument of the sort() method
  39. x = [(1, 'c'), (2, 'a'), (3, 'b')]
  40. x.sort()
  41. print(str(x) + " sorted by 1st item")
  42. x.sort(key=lambda i: i[1])
  43. print(str(x) + " sorted by 2nd item")