Loading...
More Python Posts
my_list = ["blue", "red", "green"]#1- Using sort or srted directly or with specifc keysmy_list.sort() #sorts alphabetically or in an ascending order for numeric datamy_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest.# You can use reverse=True to flip the order#2- Using locale and functoolsimport localefrom functools import cmp_to_keymy_list = sorted(my_list, key=cmp_to_key(locale.strcoll))
def max_n(lst, n = 1):return sorted(lst, reverse = True)[:n]max_n([1, 2, 3]) # [3]max_n([1, 2, 3], 2) # [3, 2]
from collections import defaultdictdef combine_values(*dicts):res = defaultdict(list)for d in dicts:for key in d:res[key].append(d[key])return dict(res)d1 = {'a': 1, 'b': 'foo', 'c': 400}d2 = {'a': 3, 'b': 200, 'd': 400}combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}
def generate_floyds_triangle(num_rows):triangle = []number = 1for row in range(num_rows):current_row = []for _ in range(row + 1):current_row.append(number)number += 1triangle.append(current_row)return triangledef display_floyds_triangle(triangle):for row in triangle:for number in row:print(number, end=" ")print()# Prompt the user for the number of rowsnum_rows = int(input("Enter the number of rows for Floyd's Triangle: "))# Generate Floyd's Trianglefloyds_triangle = generate_floyds_triangle(num_rows)# Display Floyd's Triangledisplay_floyds_triangle(floyds_triangle)
import copybegining = [False,False,False,False,False,None,True,True,True,True,True]#False = black True = whiteits = [0]def swap(layout, step):layoutCopy = copy.deepcopy(layout)layoutCopy[(step[0]+step[1])], layoutCopy[step[1]] = layoutCopy[step[1]], layoutCopy[(step[0]+step[1])]return layoutCopydef isSolved(layout):for i in range(len(layout)):if(layout[i] == False):return (i >= (len(layout)/2))def recurse(layout, its, steps = []):if isSolved(layout):its[0] += 1print(layout,list(x[0] for x in steps))returnstep = Nonefor i in range(len(layout)):if(layout[i] == None):if(i >= 1): #If the empty space could have something to the leftif(layout[i - 1] == False):step = [-1,i]recurse(swap(layout,step), its, (steps+[step]))if(i > 1): #If the empty space could have something 2 to the leftif(layout[i - 2] == False):step = [-2,i]recurse(swap(layout,step), its, (steps+[step]))if(i < (len(layout)-1)): #If the empty space could have something to the rightif(layout[i + 1] == True):step = [1,i]recurse(swap(layout,step), its, (steps+[step]))if(i < (len(layout)-2)): #If the empty space could have something to the rightif(layout[i + 2] == True):step = [2,i]recurse(swap(layout,step), its, (steps+[step]))its[0] += 1#return Nonerecurse(begining,its,[])print(its[0])
def check_prop(fn, prop):return lambda obj: fn(obj[prop])check_age = check_prop(lambda x: x >= 18, 'age')user = {'name': 'Mark', 'age': 18}check_age(user) # True