Loading...
More Python Posts
# @return a list of strings, [s1, s2]def letterCombinations(self, digits):if '' == digits: return []kvmaps = {'2': 'abc','3': 'def','4': 'ghi','5': 'jkl','6': 'mno','7': 'pqrs','8': 'tuv','9': 'wxyz'}return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
def print_x_pattern(size):i,j = 0,size - 1while j >= 0 and i < size:initial_spaces = ' '*min(i,j)middle_spaces = ' '*(abs(i - j) - 1)final_spaces = ' '*(size - 1 - max(i,j))if j == i:print(initial_spaces + '*' + final_spaces)else:print(initial_spaces + '*' + middle_spaces + '*' + final_spaces)i += 1j -= 1print_x_pattern(7)
# Prompt user for a decimal numberdecimal = int(input("Enter a decimal number: "))# Convert decimal to binarybinary = bin(decimal)# Convert decimal to hexadecimalhexadecimal = hex(decimal)# Display the resultsprint("Binary:", binary)print("Hexadecimal:", hexadecimal)
weigh = lambda a,b: sum(b)-sum(a)FindCoin = lambda A: 0 if (n := len(A)) == 1 else (m := n//3) * (w := 1 + weigh(A[:m], A[2*m:])) + FindCoin(A[m*w:m*(w+1)])print(FindCoin([1,1,1,1,1,1,1,2,1]))
# Python binary search functiondef binary_search(arr, target):left = 0right = len(arr) - 1while left <= right:mid = (left + right) // 2if arr[mid] == target:return midelif arr[mid] < target:left = mid + 1else:right = mid - 1return -1# Usagearr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]target = 7result = binary_search(arr, target)if result != -1:print(f"Element is present at index {result}")else:print("Element is not present in array")
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])