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": [],
"source": [
"class Bits(object):\n",
"\n",
" MAX_BITS = 32\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",
" if num is None:\n",
" raise TypeError('num cannot be None')\n",
" if num == -1:\n",
" return self.MAX_BITS\n",
" if num == 0:\n",
" return 1\n",
" seen = self._build_seen_list(num)\n",
" max_result = 0\n",
" looking_for = 0\n",
" for index, count in enumerate(seen):\n",
" result = 0\n",
" # Only look for zeroes\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",
" raise TypeError\n",
" run1 = 0\n",
" run2 = 0\n",
" best = 0\n",
" \n",
" as_bin = format(num if num >= 0 else (1 << 32) + num, '032b')\n",
" \n",
" for c in as_bin:\n",
" if c == '1':\n",
" run1 += 1\n",
" run2 += 1\n",
" else:\n",
" # One zero\n",
" if count == 1:\n",
" result = seen[index + 1] + seen[index - 1] + 1\n",
" # Multiple zeroes\n",
" else:\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"
" if run2 > best:\n",
" best = run2\n",
" run2 = run1 + 1\n",
" run1 = 0\n",
" return max(run2, best)\n",
" "
]
},
{