📜 ⬆️ ⬇️

Common Python problems and solutions (translation)

Translation of the article “Most Frequent Python Problems and Solution” from pamno.com.

We analyzed the Stack Overflow for the most common problems and summarized the answers.

1. How can I check if a file exists using Python without using the try statement?


Compatible with Python 2.x / 3:
')
import os print os.path.isfile(fname) 

2. The best way to check the list for emptiness


Compatible with Python 2.x / 3:

  li=[] if not li: print “empty" 


3. A good way to add a string of zeros.


Compatible with Python 2.7 / 3.x:

 12345”.zfill(10) 

* translator's example: the string.zfill () function returns a string complemented with zeros to the left if its length is less than the specified one.

4. How can I find out if an object has an attribute in Python?


2.7 / 3.x:

 hasattr(a,'attributename') 


5. Catch several exceptions in one line.


Compatible with Python 2.6 and above:

 except (Exception1, Exception2) as e: pass 

6. How to get a list of all files from a directory in Python?


Compatible with Python 2.7 / 3:

 import os os.listdir() 

7. How to make a sorted list of values ​​from the dictionary?


Compatible with Python 2.x and 3.x:

 newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

8. How to split the list into parts of the same size?


 def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i+n] 

9. How to download a file using the http protocol?


 import urllib2 urllib2.urlopen('http://www.example.com/').read() 

10. Matrix Multiplication in Python


Compatible with Python 2.x:

 def matmult(a,b): zip_b = zip(*b) return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b)) for col_b in zip_b] for row_a in a] 

11. List of all primes less than N


Compatible with Python 2.x:

 def primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((ni*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] 

12. Algorithm of binary search in Python


 def binary_search(array, target): lower = 0 upper = len(array) while lower < upper: # use < instead of <= x = lower + (upper - lower) // 2 val = array[x] if target == val: return x elif target > val: if lower == x: # this two are the actual lines break # you're looking for lower = x elif target < val: upper = x 

Source: https://habr.com/ru/post/267903/


All Articles