Triple nested list comprahension python. Is it possible? - list

I'm practicing nested lists comprehension and i encountered some problems i cannot solve nor find any solutions online :<
nested_lista = [[2,1,2,3],[1,2,3,4],[4,4,[16,1,3]]]
Using loops its easy to iterate through every layer of this nested list
def nested_loops():
for x in nested_lista:
for y in x:
print(y)
if type(y) == list:
for z in y:
print(z)
Output:
2
1
2
3
1
2
3
4
4
4
[16, 1, 3]
16
1
3
Now im trying to achieve similar output with nested list comprehension but it's not working no matter what i try ;/
Here's what I've come up with:
[[[print(y) for y in z if type(z)==list]print(z) for z in x]for x in nested_lista]
or at least i tried to iterate through last layer but it also doesnt work
[[[print(y) for y in z if type(z)==list] for z in x]for x in nested_lista]
Is it possible to solve this or i should give up?

With a fresh mind after 2 weeks holiday it took me +-30 min to get the answer.
Ready for more nests:
answer = [[[print(y) if type(y) is not list else print(x) for x in y] if type(y) == list else print(y) for y in z]for z in nested_lista]
shorter one with same result:
answer2 = [[[print(x) for x in y] if type(y) == list else print(y) for y in z]for z in nested_lista]
Output:
2
1
2
3
1
2
3
4
4
4
16
1
3
Not sure why I got the " - " though.

Related

How can I write this algorithm that returns the count between x and y in a list?

I am given this algorithmic problem, and need to find a way to return the count in a list S and another list L that is between some variable x and some variable y, inclusive, that runs in O(1) time:
I've issued a challenge against Jack. He will submit a list of his favorite years (from 0 to 2020). If Jack really likes a year,
he may list it multiple times. Since Jack comes up with this list on the fly, it is in no
particular order. Specifically, the list is not sorted, nor do years that appear in the list
multiple times appear next to each other in the list.
I will also submit such a list of years.
I then will ask Jack to pick a random year between 0 and 2020. Suppose Jack picks the year x.
At the same time, I will also then pick a random year between 0 and 2020. Suppose I
pick the year y. Without loss of generality, suppose that x ≤ y.
Once x and y are picked, Jack and I get a very short amount of time (perhaps 5
seconds) to decide if we want to re-do the process of selecting x and y.
If no one asks for a re-do, then we count the number of entries in Jack's list that are
between x and y inclusively and the number of entries in my list that are between x and
y inclusively.
More technically, here is the situation. You are given lists S and L of m and n integers,
respectively, in the range [0, k], representing the collections of years selected by Jack and
I. You may preprocess S and L in O(m+n+k) time. You must then give an algorithm
that runs in O(1) time – so that I can decide if I need to ask for a re-do – that solves the
following problem:
Input: Two integers, x as a member of [0,k] and y as a member of [0,k]
Output: the number of entries in S in the range [x, y], and the number of entries in L in [x, y].
For example, suppose S = {3, 1, 9, 2, 2, 3, 4}. Given x = 2 and y = 3, the returned count
would be 4.
I would prefer pseudocode; it helps me understand the problem a bit easier.
Implementing the approach of user3386109 taking care of edge case of x = 0.
user3386109 : Make a histogram, and then compute the accumulated sum for each entry in the histogram. Suppose S={3,1,9,2,2,3,4} and k is 9. The histogram is H={0,1,2,2,1,0,0,0,0,1}. After accumulating, H={0,1,3,5,6,6,6,6,6,7}. Given x=2 and y=3, the count is H[y] - H[x-1] = H[3] - H[1] = 5 - 1 = 4. Of course, x=0 is a corner case that has to be handled.
# INPUT
S = [3, 1, 9, 2, 2, 3, 4]
L = [2, 9, 4, 6, 8, 5, 3]
k = 9
x = 2
y = 3
# Histogram for S
S_hist = [0]*(k+1)
for element in S:
S_hist[element] = S_hist[element] + 1
# Storing prefix sum in S_hist
sum = S_hist[0]
for index in range(1,k+1):
sum = sum + S_hist[index]
S_hist[index] = sum
# Similar approach for L
# Histogram for L
L_hist = [0] * (k+1)
for element in L:
L_hist[element] = L_hist[element] + 1
# Stroing prefix sum in L_hist
sum = L_hist[0]
for index in range(1,k+1):
sum = sum + L_hist[index]
L_hist[index] = sum
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in S:")
if(x == 0):
print(S_hist[y])
else:
print(S_hist[y] - S_hist[x-1])
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in L:")
if(x == 0):
print(L_hist[y])
else:
print(L_hist[y] - L_hist[x-1])

comparison among input numbers

i want have comparison among input numbers .general shape of input numbers is like this :
n
x1 x2
x3 x4
x5 x6
x7 x8
n indicates how many input line we have and on each line we have 2 number with space ,just 2 number,
the first part of line is price and the second is quality
for example like this :
4
1 5
7 9
5 6
20 30
in line two '1' is price and '5' is quality
if i can find more quality with lower price i print 'yes' if not print 'no'
i write this but i can not change list to dictionary
x = int(input())
count =0
y= []
while count!=x:
y.append(input())
count+=1
z= []
for i in y:
z.append(i.split())
def dictionary(x):
d={x[0]:x[1]}
return d
for h in z:
a=dictionary(h)
for example i want
2
1 10
7 3
'yes'
or another example :
4
1 5
7 9
5 6
20 30
'no'
i hope someone answer this
n = int(input())
q,p = map(int, input().split())
for _ in range(n-1):
q1,p1 = map(int, input().split())
if q1 > q and p1 < p:
print("yes")
break
else:
print("no")
This works. The code is really simple.

Can't finish a mathematical project

I am new to coding and I am finding this site really helpful. So I have been trying to solve this problem and I am getting erroneous results, so I would be really grateful if you could help me out here.
The Problem: Find the sum of all the multiples of 3 or 5 below 1000. (For example, if we list all the positive integers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9, which sum is 23.)
My code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count = count + x
if x % 3 == 0:
count1 = count1 + x
print count1 + count
What am I doing wrong?
Thanks in advance!
You want an elif in your code so you don't count the same x twice but a simpler way is to use an or with a single count variable:
count = 0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count += x
Which can be done using sum:
print(sum(x for x in range(3, 1000) if not x % 5 or not x % 3))
For completeness, a working version using your own code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count += x
elif x % 3 == 0:
count1 += x
print count1 + count
ifs are always evaluated; so, for instance, when x is 15 it is evenly divisible by 5 and 3 so you count 15 twice, an elif is only evaluated if the previous if/elif evaluates to False so using elif only one occurrence of x will be added to the total.
Below 10 there is no number being multiple of both 5 and 3. But below 1000 there are several numbers divided exactly by 3 and 5 also (15, 45 ...).
So you need:
count=0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count=count + x
print count

Finds elements to the right of the given element on a 4x4 board

I'm currently flabbergasted with a seemingly easy problem.
I've got a 4x4 board with sequentially ordered elements, like so:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
And I want to write list comprehensions that, given a direction and element, a list will be returned with all elements in the given direction.
For example: given direction North for element 10 would give 6 and 2.
I've got 3 directions nailed, North, South and West but I can't figure out East.
My list comprehensions for the 3 I've got are, with Id being the element in question and List a list from 1 to 16:
North->
[ X | X <- List, X < Id, (Id-X) mod 4 == 0]
South ->
[ X | X <- List, X > Id, (Id-X) mod4 == 0]
West ->
[ X | X <- List, X < Id, X > ((Id-1) div 4)*4]
I can't find a valid equation for East. Any help?
Edit:
East 14 should give 15 and 16 for example. East 16 should give the empty list. I'm really stumped.
The key to this problem is using division and modulo to tell which numbers are on the same lines.
If two values have the same modulo result, then they are on the same column. If they are less than the given value, then they are north. If they are more than the given value, they are south.
In general, if two values have the same integer result of division, they should be on the same row. This would always be true for 0-based squares; however, this example uses a square that starts at 1. Instead of testing the division results of the given value and the numbers on the board, subtract 1 from the given value and the test value, then divide and compare results.
Psuedo code
given = 10
for x in board:
if int( (given - 1) / 4 ) equals int( (x - 1) / 4 ):
if x < given:
x is west
if x > given:
x is east
Here is a sample function written in Python
import math
def figure(board, num, dir):
dir = dir.lower()
sq = math.sqrt(len(board))
if sq != int(sq) or num not in board:
return "invalid sqaure"
if dir == "n":
return [x for x in board if x < num and x%sq == num%sq]
elif dir == "s":
return [x for x in board if x > num and x%sq == num%sq]
elif dir == "e":
return [x for x in board if x > num and int((x-1)/sq) == int((num-1)/sq)]
elif dir == "w":
return [x for x in board if x < num and int((x-1)/sq) == int((num-1)/sq)]
else:
return "invalid direction"
I think the Esat shold be:
ESAT->
[ X | X <- List, X >Id, X <= ⌈Id / 4)⌉ * 4 ]

How to return item index from list SML?

I have go a problem with function in SML. This function should return list index of number which will not be summed, but was taken to sum.
A call of a function: index(10, [1,2,3,4,5,6,7])
Result should be 3
(10 is a sum of numbers, we seek an index from the list which gives us 10, e.g:
1+2+3=6, 1+2+3+4=10, and return previuos one)
fun index (sum : int, numbers : int list) =
if null numbers
then 0
else if hd(numbers) > sum
then 0
else 1 + index(sum, (hd(numbers)+(hd(tl numbers)))::(tl numbers))
It seems to work, but result is wrong.
Function increments the result every two calling even if it should not.
Can anybody tell me how to fix this?
You're almost there. While I agree with #koodawg that adding a counter and a running total is another solution for this problem, having those in your code will complicate it more than it needs to be.
First, I have a few comments about your code. You must remove the unnecessary parens. hd(numbers) is same as hd numbers and (hd(tl numbers)) is equal to hd(tl numbers). So your (hd(numbers)+(hd(tl numbers))) could be simplified to (hd numbers + hd(tl numbers)). Also, you can combine if null numbers and if hd(numbers) > sum in a single condition for code brevity since they yield the same result: 0.
I'll try to explain how code works and I hope you'll get the idea where you have to amend your code.
Using your example, index(10, [1,2,3,4,5,6,7]), your code execution will be like this:
1)
fun index(10, [1,2,3,4,5,6,7]) =
if 1 > 10
then 0
else 1 + (10, [1 + 2] append to [2,3,4,5,6,7])
new list: [3,2,3,4,5,6,7]
result: 1
2)
fun index(10, [3,2,3,4,5,6,7]) =
if 3 > 10
then 0
else 1 + (10, [3 + 2] append to [2,3,4,5,6,7])
new list: [5,2,3,4,5,6,7]
result: 1
3)
fun index(10, [5,2,3,4,5,6,7]) =
if 5 > 10
then 0
else 1 + (10, [5 + 2] append to [2,3,4,5,6,7])
new list: [7,2,3,4,5,6,7]
result: 1
4)
fun index(10, [7,2,3,4,5,6,7]) =
if 7 > 10
then 0
else 1 + (10, [7 + 2] append to [2,3,4,5,6,7])
new list: [9,2,3,4,5,6,7]
result: 1
5)
fun index(10, [9,2,3,4,5,6,7]) =
if 9 > 10
then 0
else 1 + (10, [9 + 2] append to [2,3,4,5,6,7])
new list: [11,2,3,4,5,6,7]
result: 1
6)
fun index(10, [11,2,3,4,5,6,7]) =
if 11 > 10
then 0
result: 0
To sum all results: 1 + 1 + 1 + 1 + 1 + 0 = 5 (just like what you said that your function adds 2 to the expected result)
The correct code must behave like this:
1)
fun index(10, [1,2,3,4,5,6,7]) =
if 1 > 10
then 0
else 1 + (10, [1 + 2] append to [3,4,5,6,7])
new list: [3,3,4,5,6,7]
result: 1
2)
fun index(10, [3,3,4,5,6,7]) =
if 3 > 10
then 0
else 1 + (10, [3 + 3] append to [4,5,6,7])
new list: [6,4,5,6,7]
result: 1
3)
fun index(10, [6,4,5,6,7]) =
if 6 > 10
then 0
else 1 + (10, [6 + 4] append to [5,6,7])
new list: [10,5,6,7]
result: 1
4)
fun index(10, [10,5,6,7]) =
if 10 > 10
then 0
result: 0
To sum all results: 1 + 1 + 1 + 0 = 3 which is the expected answer.
HINT: You always make sure that the new list your function is processing must be smaller than the previous list/original list.
I hope I explained clearly why your code isn't working. I didn't include the code because I know this is a homework for an online class.
You need to keep a counter and total. Counter that increments with every recursive call, total equal to sum of each hd(numbers) as you go, then return the counter when your total > sum.
Something like this;
if (total + hd numbers) >= sum
then counter
else recursivecall(total + hd numbers, tl numbers, counter + 1)