How do I create a lambda function to print numbers containing x and y in Python? -
i want create list contains numbers 9 , 8 in ascending order, between 0 1000. how do via lambda
function in python?
the expected output be:
[8, 9, 88, 89, 98, 99, 888, 889, 898, 899, 988, ...]
i'd not utilize lambda here @ all, utilize itertools.product()
instead produce digits:
from itertools import product [int(''.join(d)) l in range(1, 4) d in product('89', repeat=l)]
this absolute minimum work required output desired, short of hardcoding list.
the expanded version be:
results = [] # ranging 1 3 digits l in range(1, 4): # combinations of l digits out of 8 , 9 digits in product('89', repeat=l): # set digits 1 string, convert integer value = int(''.join(digits)) results.append(value)
demo:
>>> itertools import product >>> [int(''.join(d)) l in range(1, 4) d in product('89', repeat=l)] [8, 9, 88, 89, 98, 99, 888, 889, 898, 899, 988, 989, 998, 999]
you can wrap the list comprehension in function specify digits used , maximum number of digits produce:
def generate_numbers(digits, length): homecoming [int(''.join(d)) l in range(length) d in product(digits, repeat=l + 1)] generate_numbers('89', 3) generate_numbers('123', 5)
python lambda
No comments:
Post a Comment