Loading...
More Python Posts
def when(predicate, when_true):return lambda x: when_true(x) if predicate(x) else xdouble_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)print(double_even_numbers(2)) # 4print(double_even_numbers(1)) # 1
filename = "data.txt"data = "Hello, World!"with open(filename, "a") as file:file.write(data)
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]}
# Python program for implementation of Radix Sort# A function to do counting sort of arr[] according to# the digit represented by exp.def countingSort(arr, exp1):n = len(arr)# The output array elements that will have sorted arroutput = [0] * (n)# initialize count array as 0count = [0] * (10)# Store count of occurrences in count[]for i in range(0, n):index = (arr[i]/exp1)count[int((index)%10)] += 1# Change count[i] so that count[i] now contains actual# position of this digit in output arrayfor i in range(1,10):count[i] += count[i-1]# Build the output arrayi = n-1while i>=0:index = (arr[i]/exp1)output[ count[ int((index)%10) ] - 1] = arr[i]count[int((index)%10)] -= 1i -= 1# Copying the output array to arr[],# so that arr now contains sorted numbersi = 0for i in range(0,len(arr)):arr[i] = output[i]# Method to do Radix Sortdef radixSort(arr):# Find the maximum number to know number of digitsmax1 = max(arr)# Do counting sort for every digit. Note that instead# of passing digit number, exp is passed. exp is 10^i# where i is current digit numberexp = 1while max1/exp > 0:countingSort(arr,exp)exp *= 10# Driver code to test abovearr = [ 170, 45, 75, 90, 802, 24, 2, 66]radixSort(arr)for i in range(len(arr)):print(arr[i]),
# question3.pyfrom itertools import productV='∀'E='∃'def tt(f,n) :xss=product((0,1),repeat=n)print('function:',f.__name__)for xs in xss : print(*xs,':',int(f(*xs)))print('')# this is the logic for part A (p\/q\/r) /\ (p\/q\/~r) /\ (p\/~q\/r) /\ (p\/~q\/~r) /\ (~p\/q\/r) /\ (~p\/q\/~r) /\ (~p\/~q\/r) /\ (~p\/~q\/~r)def parta(p,q,r) :a=(p or q or r) and (p or q or not r) and (p or not q or r)and (p or not q or not r)b=(not p or q or r ) and (not p or q or not r) and (not p or not q or r) and (not p or not q or not r)c= a and breturn cdef partb(p,q,r) :a=(p or q and r) and (p or not q or not r) and (p or not q or not r)and (p or q or not r)b=(not p or q or r ) and (not p or q or not r) and (not p or not q or r) and (not p or not q or not r)c= a and breturn cprint("part A:")tt(parta,3)print("part B:")tt(partb,3)
# @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, [''])