I am trying to create the following number pyramid using nested list comprehension and string formatting.
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 40 47
I figured out how to create the pyramid using nested for loops but can't quite get it to work using list comprehension. Here is my code:
for n in range(1,8):
print
for x in range(n):
if x>0:
print '%2d' % (n+(n*x)),
else:
print '%d' % n,
The same code using list comprehension gives me a syntax error:
rows = [
'%2d' % (n+(n*x)), if x > 0 else '%d' % n,
for n in range(1,8)
for x in range(n)
]
print '\n' +'\n'.join(rows)
Any ideas on how to format the pyramid correctly using list comprehension?
You could use range to build up each nested list, like so:
# Generation
result = [range(x, x**2 + 1, x) for x in range(1, 8)]
# Formatting
print('\n'.join(''.join(str(x).ljust(4) for x in row) for row in result))
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
You can join a list of lists (in this case, a generator of generators) by newlines
print('\n'.join(' '.join(str(i*j) for j in range(1, i+1)) for i in range(1, n+1)))
#1
#2 4
#3 6 9
#4 8 12 16
#5 10 15 20 25
#6 12 18 24 30 36
#7 14 21 28 35 42 49
and if you want to have the list that creates it just do:
rows = [[i*j for j in range(1, i+1)] for i in range(1, n+1)]
Related
The last for loop of the code seems to only run for the first element of the list and not the rest of the element
a = int(input())
setA = set(map(int, input().split()))
n = int(input())
com = [input() for alnum in range(n*2)]
nestcom = []
cmd = []
for i in com:
if com.index(i)%2 == 0:
nestcom.append([i, com[com.index(i)+1]])
else:
continue
for x in nestcom:
y, z = x[0].split(), set(map(int, x[1].split()))
cmd.append([y, z])
for u in cmd:
eval('setA.'+cmd[0][0][0]+'('+str(cmd[0][1])+')')
print(sum(setA))
These are the inputs
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52
4
intersection_update 10
2 3 5 6 8 9 1 4 7 11
update 2
55 66
symmetric_difference_update 5
22 7 35 62 58
difference_update 7
11 22 35 55 58 62 66
I tried running code with python 3 and pypy 3 but same problem. I changed the eval() to exec() but problem still persist
here is your last loop:
for u in cmd:
eval('setA.'+cmd[0][0][0]+'('+str(cmd[0][1])+')')
You are using cmd in what you are doing within the loop, not u. That is, you aren't using each element in cmd, you are just using cmd a number of times.
You likely want to use u in the loop itself (like eval('setA.'+u[0]...)), or perhaps enumerate(cmd) to get each element and a counter and use the counter itself, like for i, u in enumerate(cmd): eval('setA.'+cmd[i][0][0]...)
I have a list of dictionaries in python. The Dictionary contains "sequenceId" that I need to update for all Dictionaries making sure that each sequenceId is even and non-repeatable.
To update the sequenceIds, I am using a for loop, but the behavior is not what I expect.
seqId = 0
for index in range(20):
FinalNodes[index]['sequenceId'] = seqId
seqId +=2
print(FinalNodes[7]['sequenceId'])
Expected Output:- 14
Observed Output:- 38
Here is the full code snipet
import json
import time
with open('test.json', "r") as json_file:
data = json.load(json_file)
numberofJobs = 10
NodesList = data['nodes']
nNodes = len(NodesList)
#Divide all node into first, main and last
MainNodes = NodesList[1:nNodes-1]
FirstNode = NodesList[0:1]
LastNode = NodesList[nNodes-1:nNodes]
#prepare final nodes
FinalNodes = FirstNode.copy()
for i in range(numberofJobs):
FinalNodes.extend(MainNodes)
FinalNodes.extend(LastNode)
print(FinalNodes[7]['sequenceId'])
seqId = 0
for index in range(0,20):
FinalNodes[index]['sequenceId'] = seqId
seqId +=2
print(FinalNodes[index]['sequenceId'],index)
print(FinalNodes[7]['sequenceId'])
Output Inside the Loop:-
0 0
2 1
4 2
6 3
8 4
10 5
12 6
14 7
16 8
18 9
20 10
22 11
24 12
26 13
28 14
30 15
32 16
34 17
36 18
38 19
Please check with your FinalNodes dictionary as I ran the same code and it works fine!
FinalNodes= []
for i in range(20):
FinalNodes.append({"sequenceId":0})
seqId = 0
for index in range(8):
FinalNodes[index]['sequenceId'] = seqId
seqId +=2
print(FinalNodes[7]['sequenceId']) #14
I am new to Python. I have been studying for loops but I can't seem to get my head around NESTED for loops. I am doing a problem which requires knowledge of nested for loops, which I do not know how to do!
Problem:
Write a for loop that produces the following output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
0
2
4
6
8
10
12
14
16
18
0
3
6
9
12
15
18
0
4
8
12
16
Caveat: You can only use up to two for loops
My Code:
c = 0
for i in range(1, 5):
for j in range(10):
print(i * c)
c = c + 1
Any help will be appreciated. I just cannot get my head around nested for loops. It would be great if anybody could guide me.
One could do it like:
for step in range(1, 5):
for i in range(0, 20, step):
print(i)
Using list comprehension:
print(*[i for step in range(1, 5) for i in range(0, 20, step)], sep="\n")
You don't need the c variable, you can multiply by j.
The inner loop shouldn't go up to 10 every time. Notice that as the multiplyer increases, the number of iterations goes down -- each time stops before 20. So you need to divide 20 by i to get the number of iterations.
for i in range(1, 5):
for j in range(20//i):
print(i * j)
I wrote some code that uses enumerate to loop through a list.
for index, item in enumerate(list[start_idx:end_idx])
print('index [%d] item [%s]'%(str(index), item))
the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll slice up the list do do different things.
The part that I am having trouble with is python's enumerate function.
The docs say you can do:
for index, item in enumerate(list, start_index):
print(str(index))
the above code doesn't do what I expected. I though enumerate would start at the start position and stop at the end, but it doesn't.
I wrote a small program and it does indeed act wonky.
>>> for i, x in enumerate(range(0,20),start=4):
... print(str(i)+'\t'+str(x))
...
4 0
5 1
6 2
7 3
8 4
9 5
10 6
11 7
12 8
13 9
14 10
15 11
16 12
17 13
18 14
19 15
20 16
21 17
22 18
23 19
I would expect enumerate to start at index 4 and loop to the end. So it would get the range of 4-19 but it seems to just start the index but still iterates from 0-19..
Question, is there a way to do a iteration loop starting at a specific index in python?
My expected outcome would be
>>> for i, x in enumerate(range(0,20),start=4):
... print(str(i)+'\t'+str(x))
...
4 0 # skip
5 1 # until
6 2 # this
7 3 # item
8 4
9 5
10 6
11 7
12 8
13 9
14 10
15 11
16 12
17 13
18 14
19 15
20 16
21 17
22 18
23 19
instead of starting the index at the start position provide.
Actually if you got range object it's not a big deal to make a slice from it, because range(n)[:4] is still range object(as #MosesKoledoye mentioned it's Python 3 feature). But if you got a list, for the sake of not creating new list you can choose itertools.islice, it will return iterator.
from itertools import islice
for index, item in enumerate(islice(range(20), 4, None)):
print(index, item)
Output
0 4
1 5
2 6
3 7
4 8
...
The start parameter of enumerate doesn't have anything to do with what elements of the iterable get selected. It just tells enumerate what number to start with.
>>> list(enumerate(range(3)))
[(0, 0), (1, 1), (2, 2)]
>>> list(enumerate(range(3), 1))
[(1, 0), (2, 1), (3, 2)]
If you want to start at a specific index, you need to provide the start argument and a slice:
for i, v in enumerate(alist[4:], 4):
...
You can do:
for index, item in enumerate(list[4:]):
print(str(index))
So I've been trying to get my program to loop through this pke equation with only the e changing 15 times into a list. I thought I had it solved but in my print statement instead of len just printing a single number for each exponent it's lopping through and printing a number for every unique number it has. I'm having trouble with seeing where I'm going wrong. My program is this:
def greatest_common_divisor(a_int, b_int):
if a_int > b_int:
dividend = a_int
divisor = b_int
else: # b >= a
dividend = b_int
divisor = a_int
remainder = dividend % divisor
quotient = dividend // divisor
while remainder != 0:
dividend = divisor
divisor = remainder
remainder = dividend % divisor
quotient = dividend // divisor
return divisor # which is the gcd
p =5
q = 7
n = p*q
header = ["p","q","n","e","diminished","gcd","unique remainders","max remainders"]
print(header)
for e in range(12,27):
unique_remainders_list = []
for x in range(1,(n+1)):
y = x**e % n
diminished = (p - 1)*(q - 1)
gcd = greatest_common_divisor(e, diminished)
max_uni_val = n-1
if not (y in unique_remainders_list):
unique_remainders_list.append(y)
print("{:>2} {:>4} {:>6} {:>4} {:>10} {:>9} {:>10} {:>16}".\
format(p,q,n,e,diminished,gcd,len(unique_remainders_list),max_uni_val, end = ' '))
Example of print:
['p', 'q', 'n', 'e', 'diminished', 'gcd', 'unique remainders', 'max remainders']
5 7 35 12 24 12 1 34
5 7 35 12 24 12 2 34
5 7 35 12 24 12 3 34
5 7 35 12 24 12 4 34
5 7 35 13 24 1 1 34
5 7 35 13 24 1 2 34
5 7 35 13 24 1 3 34
5 7 35 13 24 1 4 34
5 7 35 13 24 1 5 34
5 7 35 13 24 1 6 34
5 7 35 13 24 1 7 34
5 7 35 13 24 1 8 34
So I think I'm having trouble with the range of e in the end, I'm just not sure where.
Figured it out, needed to move my print statement over. I hate when I miss such small things, but thanks for the help hagubear.
for e in range(12,27):
unique_remainders_list = []
for x in range(1,(n+1)):
y = x**e % n
diminished = (p - 1)*(q - 1)
gcd = greatest_common_divisor(e, diminished)
max_uni_val = n-1
if not (y in unique_remainders_list):
unique_remainders_list.append(y)
print("{:>2} {:>4} {:>6} {:>4} {:>10} {:>9} {:>10} {:>16}".\
format(p,q,n,e,diminished,gcd,len(unique_remainders_list),max_uni_val, end = ' '))