Coding Style in Python
NickName:tusharmakkar08 Ask DateTime:2014-02-12T13:59:49

Coding Style in Python

I have been interviewed recently by an eminent silicon valley based firm . I had been asked to write the code for the following question with O(n) time complexity .

Question :

Write a function that is given an array of integers. It should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

The crux to the question was to use hash maps . I wrote the following code in python :

def containsDuplicate(arr):
    hashi={}
    for i in arr:
        try:
            hashi[i]+=1
            return 1
        except KeyError:
            hashi[i]=1
    return 0

Overall interview went well and I was able to figure out the best solutions (efficient solutions) of all the questions asked . Later I got a mail from the company that I was not the best match for the position.When asked the reason for my rejection I was told to work on my coding style .

What does the HR mean when she said that I need to improve on my coding style ? What would be the best way to code the solution to the problem asked above ?

Edit :

After reading the code again I believe it was not even necessary to do hashi[i]+=1 . Just return 1 was sufficient but I don't think that they rejected me solely due to this minor fault in my coding.

Copyright Notice:Content Author:「tusharmakkar08」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/21719874/coding-style-in-python

Answers
Jayanth Koushik 2014-02-12T06:12:36

Here are a few suggestions.\n\nfrom collections import defaultdict\n\ndef contains_duplicates(arr): # PEP recommends not using camel case\n arr_count = defaultdict(lambda: 0) # you should use defaultdict to specify a default value\n for i in arr:\n arr_count[i] += 1\n if arr_count[i] >= 2:\n return True # Python has a boolean type; you shouldn't use 0s and 1s\n return False\n",


Russia Must Remove Putin 2014-02-12T06:25:31

Regarding your style, you appear to not know that sets are implemented similarly to dicts in Python, and you were unnecessarily complicated in your code. I would have implemented it like Gavin H did.\n\nAlso, other elements of style that you should work on (see PEP8): \n\n\nsingle spaces around assignment operators\nuse underscores to separate words in names as opposed to camel-case\nlearn dict methods (you could have used the dict.get method instead of try/except)\nreturn True or False, not 1 or 0\n",


Steve Barnes 2014-02-12T06:38:22

There are a number of coding style issues with your code, but the one I like least is that it will always process the entire array even if the first two elements are the same.\n\nMy take on this would be the following it may not be the shortest but going back later would be better:\n\ndef has_dups(array):\n \"\"\" Return true if there are any duplicates in the array \"\"\"\n result = False # Return value\n seen = {} # Dictionary of values seen\n for val in array:\n if seen.get(val, False):\n result = True # We have a duplicate\n break # Return NOW\n else:\n seen[val] = True # Add to seen\n return result\n\n\nIn a commercial organisation you are usually looking for code that:\n\n\nMeets the specification - yours did not as it returns 0/1 rather than False/True\nMeets the standards - yours has several PEP8 issues\nIs clear and maintainable - yours lacks comments and relies on exceptions to save time in an interview it is a good idea to at least mark where you would comment the code.\nIs testable - this means one entry and exit and a low complexity\n\n\nEdit\n\nThe OP has pointed out that their code returns on the first non-exception which I had missed - this emphasises points 3 and 4 above.",


Gavin H 2014-02-12T06:11:55

A more concise solution to the problem is:\n\ndef has_dups(arr):\n return len(set(arr)) != len(arr)\n\n\nOn the set creation any dups would be removed so the count would tell us the result. I think the set creation from an iterator is O(n) so it would fulfill that requirement.\n\nCan't promise that is what they are looking for though!",


afkfurion 2014-02-12T06:16:51

Check PEP-8\n\nfrom collections import defaultdict\ndef is_duplicate(string):\n freq = defaultdict(lambda: 0)\n for c in string:\n freq[c] += 1\n return all(v == 1 for v in freq.values())\n",


venpa 2014-02-12T06:14:14

you would have used \"in\" instead of try and except.\n\ndef containsDuplicate(arr):\n hashi={}\n res = 0 \n for i in arr:\n if i not in hashi:\n hashi[i]=1\n else:\n res = 1\n break\n return res\n",


Colin Bernet 2014-02-12T06:14:44

It could be that they didn't like the fact that you return 0 or 1 instead of False or True. ",


Liyan Chang 2014-02-12T06:25:47

Trying to reverse engineer the interview rejection reason is typically a difficult and often meaningless exercise, so let's reform the question to something more fun and continue to improve on your answer, as you would have if you had been given more time.\n\nWrite a function that is given an array of integers. It should return true if any value appears at least twice in the array, and it should return false if every element is distinct.\n\ndef containsDuplicate(arr):\n hashi={}\n for i in arr:\n try:\n hashi[i]+=1\n return 1\n except KeyError:\n hashi[i]=1\n return 0\n\n\nWell, python has a style guide that suggests some spacing, so let's do that. (No one would ever reject someone for this, btw)\n\nPython also uses True and False more then the C style 0 and 1s for booleans.\n\ndef containsDuplicate(arr):\n hashi = {}\n for i in arr:\n try:\n return True\n except KeyError:\n hashi[i] = 1\n return False\n\n\nNow, Python officially subscribes to EAFP where you use exceptions rather then checking, but some people disagree. If you used checking, we have:\n\ndef containsDuplicate(arr):\n hashi = {}\n for i in arr:\n if i in hashi:\n return True\n else:\n hashi[i] = True\n return False\n\n\nHowever, time to get clever. Using sets, we can do:\n\ndef containsDuplicate(a):\n return len(set(a)) != len(a)\n",


More about “Coding Style in Python” related questions

Python and Django coding style (PEP)

I write code with Python using Django framework. Now I have read about all these coding style advices, but encountered a vague thing. In djangoproject section here https://docs.djangoproject.com/e...

Show Detail

Coding Style in Python

I have been interviewed recently by an eminent silicon valley based firm . I had been asked to write the code for the following question with O(n) time complexity . Question : Write a function tha...

Show Detail

Change default python coding style

In python i'm following camelCase Naming style. I checked my code with "pylint" and it gives error for not following lower_case_with_underscores style. Also i use netBeans IDE for coding. This IDE ...

Show Detail

Is there a way to enforce variable declarations in Python through coding style?

I'm using PyCharms to work on Python projects. I find that writing functions is easier when we declare the type of the function parameters or the type of the new variables declared explicitly. It a...

Show Detail

Common coding style for Python?

I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now. 1.-...

Show Detail

Python Coding style Wrapping Lines

As described on http://docs.python.org/tutorial/controlflow.html : Wrap lines so that they don’t exceed 79 characters. Usualy i use breaklines on line 80, but sometimes i have functions that re...

Show Detail

Anyone have a favorite Python coding style enforcer?

I'm trying to find a Python coding style enforcer (tool, not person!). Any recommendations?

Show Detail

Python coding style

I've been reading various python coding style guides, some answers on SO, etc. but none of them mentions some maybe not that important questions, but I would like to know if there is a preferred wa...

Show Detail

Global variables and coding style recommendations

This question is quite general but it's more for me to understand good coding practices in python... I'd like to define a constant that I can use inside in any function without having to pass it as

Show Detail

Is coding style mostly for readability or are there other factors?

I remember reading in Douglas Crockford's "Javascript the Good Parts" book that there is potential for error with blockless statements because of automatic semicolon insertion. if (condition) f...

Show Detail