Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help for simplifying code
#3
It seems to be counting so defaultdict could be an option:

>>> from collections import defaultdict
>>> c = defaultdict(int)
>>> rules = [1, 2, 3, 4, 2, 3, 5, 4]
>>> for rule in rules:
...     c[rule] += 1
...
>>> c
defaultdict(int, {1: 1, 2: 2, 3: 2, 4: 2, 5: 1})
>>> c[3]
2
Or Counter:

>>> from collections import Counter
>>> c = Counter(rules)
>>> c
Counter({1: 1, 2: 2, 3: 2, 4: 2, 5: 1})
>>> c[5] += 1
>>> c[5]
2
EDIT: regarding 2 code: elif will be never executed therefore redundant. First if catches all True conditions and there is nothing left for elif not to mention that somewhere must be loop from which to break out (not provided in code sample).
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Help for simplifying code - by mmk1995 - Sep-19-2019, 11:02 AM
RE: Help for simplifying code - by metulburr - Sep-19-2019, 11:20 AM
RE: Help for simplifying code - by perfringo - Sep-19-2019, 12:02 PM
RE: Help for simplifying code - by mmk1995 - Sep-20-2019, 06:16 AM
RE: Help for simplifying code - by perfringo - Sep-20-2019, 06:59 AM
RE: Help for simplifying code - by mmk1995 - Sep-24-2019, 11:46 AM
RE: Help for simplifying code - by wavic - Sep-20-2019, 08:47 AM
RE: Help for simplifying code - by Malt - Sep-24-2019, 12:06 PM
RE: Help for simplifying code - by perfringo - Sep-24-2019, 02:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  simplifying a stack of elifs Skaperen 8 4,204 Aug-17-2019, 04:13 AM
Last Post: Skaperen
  Simplifying my code ilondire05 5 3,836 Jul-21-2019, 03:21 AM
Last Post: scidam
  My program subtracts fractions, but for some reason isn't simplifying them RedSkeleton007 9 6,023 Mar-03-2018, 11:45 AM
Last Post: Gribouillis
  Simplifying multiple "or" conditions in if statement. rhubarbpieguy 8 102,376 Jul-22-2017, 12:19 PM
Last Post: rhubarbpieguy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020