say I have a string n = '22' and another number a = 4 so that n is a str and a is an int. I would like to create a group of lists like:
list1 = [22, 12, 2] #decreasing n by 10, the last item must be single digit, positive or 0
list2 = [22, 11, 0] #decreasing n by 11, last item must be single digit, positive or 0
list3 = [22, 21, 20] #decreasing n by 1, last item must have last digit 0
list4 = [22, 13] #decreasing n by 9, last item must be single digit. if last item is == a, remove from list
list5 = [22, 32] #increasing n by 10, last item must have first digit as a - 1
list6 = [22, 33] #increasing n by 11, last item must have first digit as a - 1
list7 = [22, 23] #increasing n by 1, last item must have last digit a - 1
list8 = [22, 31] #increasing n by 9, last item must have first digit a - 1
I am struggling on how to start this. Maybe you can give me an idea of how to approach this problem?
By the way if a condition cannot be satisfied, then only n will be on that list. say n = '20', a = 4:
list3 = [20]
Also this is for a school project, for indexes in a list which has list items. I can't think of a better way to approach the problem.
This should get you started:
def lbuild( start, inc, test ):
rslt = [start]
while not test(start,inc):
start += inc
rslt.append( start )
return rslt
n = '22'
a = 4
nval = int(n)
print lbuild( nval, -10, lambda(x,y): (x<10 and x>=0) )
print lbuild( nval, 1, lambda(x,y): x%10 == a-1 )
Related
Let's say I have two lists list1 and list2 as:
list1 = [ 3, 26, 17, 7, 35, 8, 14, 24 ]
list2 = [ long, long, long, short, short, short, short, short ]
I want to find the count of 'short' of list2 when elements in list1 > 10.
Expected output is 3, as 35, 14, 24 in list1 are > 10. and they corresponds to "short' in list 2.
If you want to treat these two lists as a list of pairs, you can zip them together, with something like the following.
Note that I'm using the sum function here to count the number of times the expression evaluates to True (with True automatically treated as 1 and False as 0).
# Assuming that `long` and `short` are arbitrary objects
long = object()
short = object()
list1 = [3, 26, 17, 7, 35, 8, 14, 24]
list2 = [long, long, long, short, short, short, short, short]
print(sum(num > 10 and category is short
for num, category in zip(list1, list2)))
Length of both the lists should be same then only you can apply corresponding element condition.
c=0 #counter variable
list1 = [ 3, 26, 17, 7, 35, 8, 14, 24 ]
list2 = ['long','long','long','short','short','short','short','short']
for x,y in enumerate(list2): #you can track the position and value with enumerate
if y=='short' and list1[x]>10:
c+=1
print(c)
#3
You can also do in one line with sum and generator expression
sum(1 for x,y in enumerate(list2) if y=='short' and list1[x]>10)
#3
You can use zip to iterate over both lists at the same time and increment a counter if a condition is met:
count=0
for x, y in zip(list1, list2):
if x>10 and y=="short":
count+=1
Keep in mind it will iterate until it reaches the end of the shorter iterable.
When used in an arithmetic context, True and False have effective values of 1 and 0 respectively. Therefore:
list1 = [ 3, 26, 17, 7, 35, 8, 14, 24 ]
list2 = ['long','long','long','short','short','short','short','short']
print(sum(x > 10 and y == 'short' for x, y in zip(list1, list2)))
Output:
3
I have a "square" Matrix (the number of columns = number of rows):
like:
m = [[10,11,12],
[13,14,15],
[16,17,18]]
I need an iteration that takes the values: m[0][0], m[1][1] and m[2][2] and adds 1 to the number so it returns:
m = [[11,11,12],
[13,15,15],
[16,17,19]]
Since m is a square we can simply iterate across the list and increment the ith element of each list by one:
m = [[10,11,12],
[13,14,15],
[16,17,18]]
for i, lst in enumerate(m):
lst[i] += 1
print(*m, sep='\n')
Outputs:
[11, 11, 12]
[13, 15, 15]
[16, 17, 19]
Is it possible to print integers in one line inside the brackets? I would like my output to look like this:
[0 1 1 2 3 5 8 13 21 34]
But due to the way I wrote my code I can add brackets at the end of the list 0 1 1 2 3 5 8 13 21 34[] but not start and end.
My code:
n = int(input("Input a number to create Fibonacci sequence: "))
def fibo(n):
if n <=0:
print("Incorrect input")
return []
if n == 1:
return [0]
a,b = 0,1
for i in range(0,n):
print(a , end = " ",)
#assign a=b and b=a+b to get the sequence
a,b=b,a+b
print()
fibo(n)
The output format you are looking for is the one you get when you print a list.
You can use recursion to progressively build th eresulting list:
def fibo(n,a=0,b=1): return [a]+fibo(n-1,b,a+b) if n else [a]
print(fibo(10)) # fibonacci up to index 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
It can also be done iteratively
n = 10 # first 10 fibonacci numbers
fibo = [0,1]
while len(fibo) < n: fibo.append(sum(fibo[-2:]))
print(fibo[:n])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
I have wrote a code which insert/duplicate items into list of smaller len to match len of bigger list.
code is:
l1=[big list of length:491]
l2=[small list of lenth: 153]
l= abs(len(l2)-len(l1))==> 338
i=0
j=1
while i<l:
l2.insert(j,l2[j])
j+=2
i += 1
But after some loops i get this error
IndexError: list index out of range
which is because l>len(l2) and the code/algo catches up to len(l2).
Is there a better solution to solve this?
what i am expecting is
l1 is any list of size 30 for example and l2=[1,2,3,4,5] output should be like [1,1,2,2,3,3,4,4,5,5]
I hope this solves your requirements:
l1=[1, 2, 3, 4, 5, 6, 7, 8]
l2=[11, 12, 13, 14, 15]
# Quotient of the lengths of both lists
quotient = float(len(l1)) / float(len(l2))
new_l = []
for i in range(len(l1)):
# Divide the quotient from the index to get value of l2 which will be added.
new_l.append(l2[int(i/quotient)])
print(new_l)
Ouput:
>> [11, 11, 12, 12, 13, 14, 14, 15]
I want to create 2D array as below:
For Example:
For level 3:
7 => Array[2]
3 6 => Array[1]
1 2 4 5 => Array[0]
i.e. Array = [[1,2,4,5], [3,6], [7]]
.
For level 4:
15 => Array[3]
7 14 => Array[2]
3 6 10 13 => Array[1]
1 2 4 5 8 9 11 12 => Array[0]
i.e. Array = [[1,2,4,5,8,9,11,12], [3,6,10,13], [7,14], [15]]
What I need is a function taking number of level as argument returning Array as mentioned above.
i.e:
def function(level):
''' ..........................
...........................'''
return Array
Your data structure is recursive, so it's natural to use a recursive function to produce it.
The root node of the tree of depth depth is n = 2 ** depth - 1; it's more efficient to calculate that using bit shifting. The left subtree has a root node of n // 2, the right subtree is identical except that n // 2 is added to all its nodes.
Here's a recursive generator that produces the desired list.
def btree(depth):
if depth < 1:
return
n = (1 << depth) - 1
yield [n]
a = n // 2
for seq in btree(depth - 1):
yield seq + [u + a for u in seq]
lst = list(btree(4))[::-1]
print(lst)
output
[[1, 2, 4, 5, 8, 9, 11, 12], [3, 6, 10, 13], [7, 14], [15]]
If you want to print the tree rows in top-down order, you can just do this:
for row in btree(5):
print(row)
output
[31]
[15, 30]
[7, 14, 22, 29]
[3, 6, 10, 13, 18, 21, 25, 28]
[1, 2, 4, 5, 8, 9, 11, 12, 16, 17, 19, 20, 23, 24, 26, 27]
Hint: Here is the last row of numbers
def last_row(level):
m = 2 ** (level - 1)
L = [0 for i in range(m)]
L[0] = 1
k = 1
while k < m:
incr = 2 * k - 1
for i in range(k):
L[k+i] = L[i] + incr
k = incr + 1
return L
Here is another recursive solution that I figured. The left sub-tree value is floor(current value) and the right sub-tree value is (current value -1).
I pre-calculate the necessary powers of 2, but the draw-back is my passing of additional arguments (lists): In any case, hopefully this will be helpful for clarity when building a solution.
def driver(level):
if level <= 0:
return None
# initialize the list to have (level) columns
lst = [[] for i in range(level)]
# pre-calculate the necessary powers of 2
powers = [1]
for i in range(1, level+1):
powers.append(powers[i-1] << 1)
# call the main calculation function
calc(level, powers[level]-1, lst, powers)
return lst
def calc(level, val, lst, powers):
# add the value in pre-order
lst[level-1].append(val)
# base case, level is 1,
# do not make additional recursive calls here
if level > 1:
# calculate values in the left sub-tree
calc(level-1, val - powers[level-1], lst, powers)
# calculate values in the right sub-tree
calc(level-1, val-1, lst, powers)
print(driver(4))