 # Week 5: Python: Assignment: Exercise#1: Q4

Write a program to generate a dictionary that contains the number between 1 and n in the form of (𝑘𝑒𝑦:𝑣𝑎𝑙𝑢𝑒)=(𝑥:𝑥2) where 𝑛=100. For ex:

``````If n = 7 then output will be = {0:0, 1:1, 2:4}
``````

I did not understand the above example. If n=7, then why the dictionary contain only 3 elements?

Also the question says that the dictionary contains number between 1 and n. So how is it that the first element is 0:0?

Hi @Ashwin,
According to me following is the answer.
If n=7 then output will be = {0:0, 1:1, 2:4} because next key-value pair will be {3:9} and 9 is greater than 7.
We are looking for n such that, every key as well as every value in the dictionary will be less than n.
Similarly, if n=18 then output will be = {0:0, 1:1, 2:4, 3:9, 4:16}. Here {5:25} will be excluded since 25 > n=18.

First element is {0:0} because python starts counting from 0. If you find range of 5,

``````print(range(5))
``````

Then it will return values from 0 to 4. (i.e. 0, 1, 2, 3, 4). If you don’t want {0:0} pair, then when you iterate on n, don’t iterate along range(n). Instead iterate along range(1,n+1).

``````print(range(1,10))
``````

This will give numbers from 1 to 9 as the output. Here the first element is included while last element is excluded.

Thanks @Mugdha! for the explanation.

In “If n=7 then output will be = {0:0, 1:1, 2:4} because next key-value pair will be {3:9} and 9 is greater than 7”,
I am not able to understand where in the question it is given that for n=7, we should not consider 3:9 because 9 > 7.

Also the question says that the dictionary contains number between 1 and n. So should the first element be not 1:1?

Am I missing something?

Write a program to generate a dictionary that contains the number between 1 and n in the form of (key:value)=(x:x^2) where n=100 .
According to question, we want a dictionary that contains number between 1 and n whatever it may be key or value. If n=7, then from next pair 3 < 7 but 9 > 7. It doesn’t matter is it a key or a value.
About {0:0} pair, I think it should not be there. It can be removed in a way I explained in the above reply.

Do you mean to suggest that the question requires both key and value in a pair should be between 1 and n?

if yes, then at least the question is not very clear. 1. Yes, {0:0} should not be included as per the question, i think it’s a mistake.
2. As explained by @Mugdha, either of the key or the value should not be greater than the value `n`.

Thanks for the clarification @Mugdha and @Ishvinder!!

@Ishvinder, Can you please update the question in the assignment, especially with respect to point 2 above?

1 Like

Sure,  