How to structure nested for loops? - python

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)

Related

Why am I getting the following error in my code: TypeError: 'int' object does not support item assignment

b,e=dict(),dict()
mx=0
for _ in range(int(input())):
a,b,c=list(map(int,input().split()))
b[a]=c;e[b]=c #cause of error
mx=max(mx,b)
ans,cur=0,0
for j in range(b):
if i in b:cur+=b[i]
ans=max(ans,cur)
if i in e:cur-=e[i]
print(max(ans,cur))
Here's a sample input:
5
4 8 2
5 12 7
1 3 3
10 16 3
17 18 6
I don't understand why I'm getting this error. What's the problem with assigning items to dictionaries using this fashion?
this problem comes for the same name in your program "b". In line no 1 & 4. and also second for loop where j is in for loop but you used i
dic,e=dict(),dict()
mx=0
for _ in range(int(input())):
a,b,c=list(map(int,input().split()))
dic[a]=c;e[b]=c #cause of error
mx=max(mx,b)
ans,cur=0,0
for j in range(b):
if j in dic:cur+=dic[j]
ans=max(ans,cur)
if j in e:cur-=e[j]
print(max(ans,cur))
output:
5
4 8 2
5 12 7
1 3 3
10 16 3
17 18 6
10
use this code. I think it solve your problem

Python: How to print multiplication table based on two inputs?

I'm attempting to write a program called multChart(x,y) that prints a multiplication table based on two inputs, one specifying the number of rows to print and another specifying the number of columns. So it would look like this:
>>> multChart(4,5):
1: 1 2 3 4 5
2: 2 4 6 8 10
3: 3 6 9 12 15
4: 4 8 12 16 20
Here's what my current code looks like:
def multChart(x,y):
for i in range(1,x+1):
print(i,':',i*1,i*2,i*3,i*4,i*5)
I'm totally stuck on how to implement the y value. I also know there should be a better way of printing the multiplication instead of i * multiples of five, but I'm not sure what loop to use. Any help would be greatly appreciated.
You need another loop inside your print for looping over the y range:
def multChart(x, y):
for i in range(1, x+1):
print(i, ':', *[i * z for z in range(1, y+1)])
def multChart(x,y):
for i in range(1,x+1):
print(i, ':', end=" ")
for j in range(1,y+1):
print(i*j, end =" ")
print()
multChart(4,5)
produces
1 : 1 2 3 4 5
2 : 2 4 6 8 10
3 : 3 6 9 12 15
4 : 4 8 12 16 20
You can use a second for loop for the second index. Also, note that you can use end in the print statement.
def multChart(x,y):
for i in range(1,x+1):
print(i,':',*list(map(lambda y: i*y,list(range(1,y+1 ) ) ) ) )
multChart(4,5)

Python 2.7 list comprehension number pyramid

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)]

python continuing a loop from a specific index

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))

Aligning text in a table using string formatting with a loop inside a loop

I'm supposed to align some numbers in a table while using a loop inside a loop. It should look like this when it's done:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
What I've stared with is:
for i in range(1,10,1):
for c in range(1,6,1):
print(i, end='\n')
Though after running this it just prints them bellow each other. And replacing "\n" with "\t" doesn't help either. I've tried .format but with no success. Sorry if this seems very simple and that it should be stated somewhere but I can't find someone with the same problem or some chapter referring to this specific problem.
I did manage to do this table by using while like this:
i = 1
while i < 6:
print("1 2 3 4 5 6 7 8 9\n" , end='' '')
i += 1
This is of course not the best way to do it, I just don't have the knowledge to do it in a smarter way.
First, you have inverted loop ranges it should be:
for i in range(1, 6, 1):
for c in range(1, 10, 1):
Second, in the inner loop you have to print c, not i.
The full code would be like this:
for i in range(1, 6, 1):
for c in range(1, 10, 1):
print(c, end=" ")
print('')
If you want to code only one for loop you can:
for i in range(1, 6, 1):
print( " ".join(map(str, range(1, 10, 1))) )
Firstly, your loops are in the wrong order. As you write your code, you will get 10 rows with 6 numbers.
Next, you can't print in the inner loop, because you will get just 60 rows. So you can store rows in some temp value inside first loop, and on each cycle of outer loop print it. Also, for more pretty code, you can use list comprehensions.
for i in range(1, 10):
print ' '.join([str(number) for number in range(1, 6)])
Also, to perfect this, you can write it in 1 string of code, but this is more understandable.

Categories