Loading...
More Python Posts
def byte_size(s):return len(s.encode('utf-8'))byte_size('😀') # 4byte_size('Hello World') # 11
x[cat_var].isnull().sum().sort_values(ascending=False)
# Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.# For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.# Python program to print all primes smaller than or equal to# n using Sieve of Eratosthenesdef SieveOfEratosthenes(n):# Create a boolean array "prime[0..n]" and initialize# all entries it as true. A value in prime[i] will# finally be false if i is Not a prime, else true.prime = [True for i in range(n + 1)]p = 2while (p * p <= n):# If prime[p] is not changed, then it is a primeif (prime[p] == True):# Update all multiples of pfor i in range(p * 2, n + 1, p):prime[i] = Falsep += 1prime[0]= Falseprime[1]= False# Print all prime numbersfor p in range(n + 1):if prime[p]:print (p)# driver programif __name__=='__main__':n = 30print("Following are the prime numbers smaller")print("than or equal to ", n)print("than or equal to ", n)SieveOfEratosthenes(n)
from time import sleepdef delay(fn, ms, *args):sleep(ms / 1000)return fn(*args)delay(lambda x: print(x), 1000, 'later') # prints 'later' after one second
mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':0}# How to sort a dict by value Python 3>sort = {key:value for key, value in sorted(mydict.items(), key=lambda kv: (kv[1], kv[0]))}print(sort)# How to sort a dict by key Python 3>sort = {key:mydict[key] for key in sorted(mydict.keys())}print(sort)
class Solution(object):def floodFill(self, image, sr, sc, newColor):R, C = len(image), len(image[0])color = image[sr][sc]if color == newColor: return imagedef dfs(r, c):if image[r][c] == color:image[r][c] = newColorif r >= 1: dfs(r-1, c)if r+1 < R: dfs(r+1, c)if c >= 1: dfs(r, c-1)if c+1 < C: dfs(r, c+1)dfs(sr, sc)return image