Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find specific numbers in a sequence

Hi I’d like to understand how in the following python program to proceed to add "the latest added number" and the "count of numbers that were added". the output should be like [121 21 11], the code gives 121 but how do I get the other two?

sum = 0
k = 1
while sum <= 100:
  sum = sum + k
  k = k + 2
print(sum)

I don’t know what commands to use to find out the answer, sum is 121, how do I add 21 which is the last number added before sum <= 100 and 11 which is the count of numbers (1,3,5,7,9,11,13,15,17,19,21)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First off, "sum" is a built-in function, so you should not use it as a variable name.

Next, you can easily build a list of your nums making it easy to get sum, count, last, etc.

nums = [1]
while sum(nums) <= 100:
    nums.append(nums[-1]+2)

print(sum(nums), nums[-1], len(nums))
121 21 11
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading