From: Principles of Computing Part 1 Course on Coursera
I got -2 pts on my OWLTEST which uses Pylint for style guide. The error states:
Too many branches (17/12) function "merge", line 7
what does that mean?
I worked really hard on making this program work. I wrote this from scratch. I would also like to know if there are some techniques to make this cleaner and/or some best practice improvements? I know there are probably ways to write this in a better way because right now my code looks really messy.
I wish to improve:
1. Code Style
2. Performance
3. Readability
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 17:55:56 2015
2048_merge_attempt1.py
@author: Rafeh
"""
def merge(nums):
'''
Takes a list as input
returns merged pairs with
non zero values shifted to the left.
[2, 0, 2, 4] should return [4, 4, 0, 0]
[0, 0, 2, 2] should return [4, 0, 0, 0]
[2, 2, 0, 0] should return [4, 0, 0, 0]
[2, 2, 2, 2, 2] should return [4, 4, 2, 0, 0]
[8, 16, 16, 8] should return [8, 32, 8, 0]
'''
slide = [] # Append non-zeroes first
for num in nums:
if num != 0:
slide.append(num)
for num in nums:
if num == 0:
slide.append(num)
pairs = []
for idx, num in enumerate(slide):
if idx == len(slide)-1:
pairs.append(num)
if len(pairs) != len(nums):
pairs.append(0)
break
if num == slide[idx+1]:
if num != 0:
pairs.append(num*2)
slide[idx+1] -= slide[idx+1]
# slide[idx+1], slide[idx+2] = slide[idx+2], slide[idx+1]
else:
pairs.append(num)
else:
pairs.append(num) # Even if they don't match you must append
slide = [] # Append non-zeroes first
for num in pairs:
if num != 0:
slide.append(num)
for num in nums:
if num == 0:
slide.append(num)
for _ in range(len(nums) - len(slide)):
if len(nums) != len(slide):
slide.append(0)
return slide
coding
line is indented by two spaces and the rest of the code by additional two spaces, both are superfluous. Also in line 40,pairs.append(num)
is indented one level (four spaces) too deep, which can be misleading, especially in Python. – mkrieger1 18 hours agoCtrl-K
or pressing the{}
button, which indents everything uniformly by four spaces. – mkrieger1 18 hours agoCtrl-K
and it did not work. So I eventually gave up. :( – Rafeh 18 hours ago