how to improve list generator function - python

the purpose of the below function is to return:
> f(0) returns [],
> f(1) returns [[1]]
> f(2) returns [[1], [1,2]]
> f(3) returns [[1], [1,2], [1,2,3]]
how can it be improved?
def list_generator(number: int) -> list:
if number == 0:
new_list = []
else:
temp_list = []
new_list = [0] * number
for idx, num in zip(range(len(new_list)), range(1, number + 1)):
temp_list.append(num)
new_list[idx] = list(set(temp_list))
return new_list

def f(n):
return [[x + 1 for x in range(i)] for i in range(1, n + 1)]
for n in range(6):
print(n, f(n))
# 0 []
# 1 [[1]]
# 2 [[1], [1, 2]]
# 3 [[1], [1, 2], [1, 2, 3]]
# 4 [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
# 5 [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

You can use a list comprehension:
def f(number: int) -> list:
return [list(range(1, i+1)) for i in range(1, number+1)]

Related

how to create list of ints from a factorial number in python

I am trying to write a function that accepts a natural number n and returns a list of lists arranged in ascending order with integers by the number in the input.
For example: factorial_list (4) → [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
For some reason I'm missing something in the way I wrote the code and would love to get an opinion on how the solution can be completed.
Thank you so much everyone
def f_l(n):
return help([], [], n)
def help(lst, s_l, n):
if n <= 1:
s_l.append(n)
lst.append(s_l)
return lst
return lst + help(lst, s_l, n-1)
def factorial_list(num):
num_range = [i for i in range(1, num+1)]
return [num_range[:num] for num in num_range]
Above is a simple algorithm for your problem.
factorial_list(4)
output: [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
A naive approach to your problem is
lis = []
def fun(n):
for i in range(1, n + 1):
l = []
for j in range(1, i + 1):
l.append(j)
lis.append(l)
return lis
When called as fun(4), it outputs [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
To simplfy the answer of #RonMarcelino, I suggest you this one-line styled solution:
def factorial_list(num):
return [list(range(1, n+1)) for n in range(1, num+1)]
print(factorial_list(4))
# [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Extending on my comment, if you want to do with your recursive way, you need to use
def f_l(n):
return help([], [], n)
def help(lst, s_l, n):
if n < 1:
return [1]
help(lst, s_l, n-1)
s_l.append(n)
lst.append(s_l.copy())
return lst
With f_l(4), you will get [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]].
If the objective is to return only list of lists arranged in ascending order with integers by the number in the input the following code will help:
def fact(n):
fact_list = []
temp = n
while temp:
int_list = []
for i in range(1, temp+1):
int_list.append(i)
else:
int_list.sort()
fact_list.append(int_list)
temp -= 1
else:
fact_list.sort()
return fact_list
print fact(4) ## -> python 2.x
print(fact(4)) ## -> python 3.x

make a list inside of a list using loops

I'm trying to make a function that returns a list of n elements like the following:
factorial_list(4) → [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
my output is [[1], [1], [2], [1], [2], [3], [1], [2], [3], [4]]
As you see I'm struggling to make the order of the inner lists. Any insights to what I should change in my code?
def factorial_list(n):
list2=[]
for i in range(1,n+1):
for j in range(1,i+1):
list2.append([j])
print(list2)
factorial_list(4)
Method 1: based on the logic of your code
def factorial_list(n):
final_list = []
for i in range(1, n+1):
temp = []
for j in range(1, i+1):
temp.append(j)
final_list.append(temp)
print(final_list)
factorial_list(4) # [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Method 2: a mix of for loop and list comprehensions
def factorial_list(n):
final_list = []
for i in range(1, n+1):
temp = [j for j in range(1, i+1)]
final_list.append(temp)
print(final_list)
factorial_list(4) # [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Method 3: using list comprehensions
def factorial_list(n):
final_list = [[j for j in range(1, i+1)] for i in range(1, n+1)]
print(final_list)
factorial_list(4) # [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
You need to create a new list for each iteration of the first loop:
def factorial_list(n):
list2=[]
for i in range(1,n+1):
list3 = [] # <--- Create a new list for each iteration
for j in range(1,i+1):
list3.append(j)
list2.append(list3)
print(list2)
factorial_list(4)
# Output: [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]

Multiply digits in list in python

I have a list:
lst = [[7], [4, 3, 5, 8], [1, 3]]
How can I multiply each element in list by it position like this:
[[7 * 0],[4 * 0 + 3 * 1 + 5 * 2 + 8 * 3], [1 * 0 + 3 * 1]]
And print answer:
answer = [[0], [37], [3]]
You can use a list comprehension with sum and enumerate:
L = [[7], [4, 3, 5, 8], [1, 3]]
res = [[sum(i*j for i, j in enumerate(sublist))] for sublist in L]
print(res)
[[0], [37], [3]]
Or if you are happy to use a 3rd party library, you can use NumPy:
import numpy as np
L = [[7], [4, 3, 5, 8], [1, 3]]
res = [np.arange(len(sublist)).dot(sublist) for sublist in L]
print(res)
[0, 37, 3]
This is a possible solution ...
a_list = [[7], [4, 3, 5, 8], [1, 3]]
new_list = []
for sub_list in a_list:
sublistsum = 0
for i, value in enumerate(sub_list):
sublistsum = sublistsum + i * value
new_list.append([sublistsum])
print(new_list)

how can i generate combinations as like below?

I have a list
a=[1,2,3]
I want to perform combinations(adjacent numbers) on this list and I want multiplication each combination like below
1
1 2
2
1 2 3
2 3
3
After this, I want to perform
a) 1*1= 1
b) 1*2+2*2= 6
c) 2*2= 4
d) 1*3+2*3+3*3= 18
e) 2*3+3*3= 15
f) 3*3= 9
Expected output is
[1,2,4,18,15,9]
Here is my attempted code:
def grouper(input_list, n = 2):
for i in xrange(len(input_list) - (n - 1)):
yield input_list[i:i+n]
a = [1,2,3]
for item in [a[0:m+1] for m in range(len(a))]:
for n in range(len(item)):
result.append(item[n:])
test.append(sum([k * len(item) for k in item[n:]]))
print result
print test
output
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3]]
[1, 6, 4, 18, 15, 9]
For more length
a = [1,2,3,4]
output
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3], [1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]
[1, 6, 4, 18, 15, 9, 40, 36, 28, 16]
Simple using for loops
a = [1,2,3]
tmp = []
for m in range(len(a)):
tmp.append( a[0:m +1])
result = []
test = []
for item in tmp:
for n in range(len(item)):
result.append(item[n:])
test.append(sum([k * len(item) for k in item[n:]]))
print tmp
print result
print test
Output
[[1], [1, 2], [1, 2, 3]]
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3]]
[1, 6, 4, 18, 15, 9]
Create combinations:
a = [1,2,3]
# create combinations
combinations = []
for i in range(len(a)):
for j in range(len(a)):
result = a[i:j+1]
if result:
combinations.append(result)
output:
combinations [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
To compute the values you want:
for values in combinations:
last_val = values[-1]
computation = ''
result = 0
for val in values:
computation += "{}*{} + ".format(val, last_val)
result += val * last_val
computation = computation[:-2] + '= {}'.format(result)
print(computation)
output:
1*1 = 1
1*2 + 2*2 = 6
1*3 + 2*3 + 3*3 = 18
2*2 = 4
2*3 + 3*3 = 15
3*3 = 9
#Vikash Singh has given an almost complete solution here:
Except that there is little mismatch with the combinations:
I have managed to correct the same:
a = [1,2,3]
combinations = []
for i in range(len(a)+1):
for j in range(i):
result = a[j:i]
if result:
combinations.append(result)
print combinations
The output will be
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3]]
And the if the list is [1,2,3,4], output will be:
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3], [1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]
I hope this solves OP's problem with the combination.

How to obtain sliced sublists of a list dynamically in python?

Let's say I have a list:
l = [0,1,2,3,4]
And I want to obtain a sequence of lists in this logic:
[[1,2,3,4],[0,1,2,3],[2,3,4],[1,2,3],[0,1,2],[3,4],[2,3],[1,2],[0,1],[0],[1],[2],[3],[4]]
That's it, sublists made of l[1:] and l[:-1]
I started by this recursive function:
l = [0,1,2,3,4]
def sublist(l):
if len(l) == 1:
return l
else:
return [sublist(l[1:]),sublist(l[:-1])]
a = [sublist(l)]
print a
But it's not really what I what as it outputs:
[[[[[[4], [3]], [[3], [2]]], [[[3], [2]], [[2], [1]]]], [[[[3], [2]], [[2], [1]]], [[[2], [1]], [[1], [0]]]]]]
import itertools
[list(itertools.combinations(l, x)) for x in range(1, len(l))]
Here's a very straightforward implementation:
def sublists_n(l, n):
subs = []
for i in range(len(l)-n+1):
subs.extend([l[i:i+n]])
return subs
def sublists(l):
subs = []
for i in range(len(l)-1,0,-1):
subs.extend(sublists_n(l,i))
return subs
>>> l = [0,1,2,3,4]
>>> sublists(l)
[[0, 1, 2, 3], [1, 2, 3, 4], [0, 1, 2], [1, 2, 3], [2, 3, 4], [0, 1], [1, 2], [2, 3], [3, 4], [0], [1], [2], [3], [4]]
[l[x:] for x in range(len(l))] + [l[:x+1] for x in range(len(l))]
Loops through l twice, but you sort of have to no matter what I think (could use zip but same thing).
A simple recursion, doesn't quite order things correctly but its simple.
def sublists(l):
right = l[1:]
left = l[:-1]
result = [right, left]
if len(l) > 2:
result.extend(sublists(right))
result.extend(sublists(left))
return result
print sublists([0,1,2,3,4])

Categories

Resources