user15463263
user15463263

Reputation:

My code is not looping the way it is supposed to and causing a wrong output- can someone explain why?

I have the below code:

d=0
n=5750
squared_list = []
for i in range(0, n):
    squared_list.append(i ** 2)

string_digits = [str(int) for int in squared_list]
str_of_ints = ''.join(string_digits)

counter = 0
for j in str_of_ints:
    if j ==str(d):
        counter +=1

print(counter)

The output is supposed to be 4700, but I am getting 4697 for some reason. Can anyone see why this is?

Upvotes: 0

Views: 51

Answers (4)

thesylio
thesylio

Reputation: 144

as it's been said you should not use "int" as a variable name, change it to "i" or something. Also, in your question you should explain what you're trying to achieve, here we can only infer from the bugged code and the expected value, formulating your problem in a clear way will also help you debugging some times...

About your answer now, remember that in python, range(0, n) start at 0 but ends at n-1 (not n!), it should work once you fix it.

Upvotes: 0

prashant sachdeva
prashant sachdeva

Reputation: 74

Your loop in running up to 5749, use below code:

for i in range(0, n+1):
    squared_list.append(i ** 2)

Upvotes: 0

benlloydjones
benlloydjones

Reputation: 11

your initial range needs to be:

for i in range(0, n + 1):

as range does not include the last number it reaches so you're only going for numbers 0 to 5749 in your code.

Upvotes: 1

JacobIRR
JacobIRR

Reputation: 8946

range STOPS at its second arg.

If you change n=5750 to n=5751, you will get the expected result. You could also use range(0, n+1) as Fred said.

...and like Mark said, don't use int as a variable name

Upvotes: 2

Related Questions