alternate flip_bit_challenge solution

This solution is much clearer
This commit is contained in:
andy.boot 2017-04-06 23:02:33 +01:00
parent 075b51cde3
commit 502bcf5bca

View File

@ -118,62 +118,28 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"class Bits(object):\n", "class Bits(object):\n",
"\n",
" MAX_BITS = 32\n", " MAX_BITS = 32\n",
" \n", " \n",
" def _build_seen_list(self, num):\n",
" seen = []\n",
" looking_for = 0\n",
" count = 0\n",
" for _ in range(self.MAX_BITS):\n",
" if num & 1 != looking_for:\n",
" seen.append(count)\n",
" looking_for = not looking_for\n",
" count = 0\n",
" count += 1\n",
" num >>= 1\n",
" seen.append(count)\n",
" return seen\n",
" \n",
" def flip_bit(self, num):\n", " def flip_bit(self, num):\n",
" if num is None:\n", " if num is None:\n",
" raise TypeError('num cannot be None')\n", " raise TypeError\n",
" if num == -1:\n", " run1 = 0\n",
" return self.MAX_BITS\n", " run2 = 0\n",
" if num == 0:\n", " best = 0\n",
" return 1\n", " \n",
" seen = self._build_seen_list(num)\n", " as_bin = format(num if num >= 0 else (1 << 32) + num, '032b')\n",
" max_result = 0\n", " \n",
" looking_for = 0\n", " for c in as_bin:\n",
" for index, count in enumerate(seen):\n", " if c == '1':\n",
" result = 0\n", " run1 += 1\n",
" # Only look for zeroes\n", " run2 += 1\n",
" if looking_for == 1:\n",
" looking_for = not looking_for\n",
" continue\n",
" # First iteration, take trailing zeroes\n",
" # or trailing ones into account\n",
" if index == 0:\n",
" if count != 0:\n",
" # Trailing zeroes\n",
" try:\n",
" result = seen[index + 1] + 1\n",
" except IndexError:\n",
" result = 1\n",
" # Last iteration\n",
" elif index == len(seen) - 1:\n",
" result = 1 + seen[index - 1]\n",
" else:\n", " else:\n",
" # One zero\n", " if run2 > best:\n",
" if count == 1:\n", " best = run2\n",
" result = seen[index + 1] + seen[index - 1] + 1\n", " run2 = run1 + 1\n",
" # Multiple zeroes\n", " run1 = 0\n",
" else:\n", " return max(run2, best)\n",
" result = max(seen[index + 1], seen[index - 1]) + 1\n", " "
" if result > max_result:\n",
" max_result = result\n",
" looking_for = not looking_for\n",
" return max_result"
] ]
}, },
{ {