w3resource

Python: List of integers where the sum of the first i integers is i

Python Programming Puzzles: Exercise-7 with Solution

Write a Python program to check a given list of integers where the sum of the first i integers is i.

Input:
[0, 1, 2, 3, 4, 5]
Output:
False

Input:
[1, 1, 1, 1, 1, 1]
Output:
True

Input:
[2, 2, 2, 2, 2]
Output:
False

Sample Solution:

Python Code:

def test(li, i):
    return sum(li[:i]) == i
nums = [0,1,2,3,4,5]
i = 1
print("Original list:")
print(nums)
print("Check the said list, where the sum of the first i integers is i: i = ",i)
print(test(nums,1))
i = 3
print("\nOriginal list:")
print(nums)
print("Check the said list, where the sum of the first i integers is i: i = ",i)
print(test(nums,3))
i = 6
nums = [1,1,1,1,1,1]
print("\nOriginal list:")
print(nums)
print("Check the said list, where the sum of the first i integers is i: i = ",i)
print(test(nums, 6))
i = 2
nums = [2,2,2,2,2]
print("\nOriginal list:")
print(nums)
print("Check the said list, where the sum of the first i integers is i: i = ",i)
print(test(nums, 2))

Sample Output:

Original list:
[0, 1, 2, 3, 4, 5]
Check the said list, where the sum of the first i integers is i: i =  1
False

Original list:
[0, 1, 2, 3, 4, 5]
Check the said list, where the sum of the first i integers is i: i =  3
True

Original list:
[1, 1, 1, 1, 1, 1]
Check the said list, where the sum of the first i integers is i: i =  6
True

Original list:
[2, 2, 2, 2, 2]
Check the said list, where the sum of the first i integers is i: i =  2
False

Flowchart:

Flowchart: Python - List of integers where the sum of the first i integers is i.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Find a list of one hundred integers between 0 and 999 which all differ by ten from one another.
Next: Split a string of words separated by commas and spaces into 2 lists: words and separators.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.