Python Forum
Help solving Python problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help solving Python problem
#1
I am not writing and spiking English good, do not be so angry, please
There is a list of int and natural numbers k,m. Print the min i that is true a[i] + a[i+1] + ... + a[i + k] == m. If there is not such i then print 0. Don't use nested loops and more than one list.
Input:
n, k and m (m <= 10000, 0 < k < n <= 30000), n - number of elements in list. At the next raw elements |i|<100
Output:
Answer

One of the tests:
Input:
4 1 22
9 13 10 -11
Output:
1
My code:
n, k, m = (int(x) for x in input().split())
a = [int(x) for x in input().split()]
rez=0
for i in range(n):
	if sum(a[i:i+k+1])==m:
		rez=i+1
		break
print(rez if rez else 0)
Code fails on the last of test Cry Arrow , not the test I have shown!!!
Maybe You know what is the problem. If "yes",please write me!
Reply
#2
(Apr-16-2018, 05:07 PM)WHelped Wrote: Code fails on the last of test Cry Arrow , not the test I have shown!!!
Do you know what test it fails for?
Reply
#3
Sory, I don't know. Thank you for reply
Reply
#4
Try this:

def find_i(a, m, k):
    n = len(a)
    for i in range(n - k):
        if sum(a[i:i + k + 1]) == m: 
            return i
    return 0
Reply
#5
(Apr-17-2018, 02:26 AM)scidam Wrote: Try this:

def find_i(a, m, k):
    n = len(a)
    for i in range(n - k):
        if sum(a[i:i + k + 1]) == m: 
            return i
    return 0
I tried, but the programm failed at 5 test. Looks strange, didn't it?

Yes, I found it!!! This is the corect code:
n, k, m = (int(x) for x in input().split())
a = [int(x) for x in input().split()]
rez=0
for i in range(n-k):
    if sum(a[i:i+k+1])==m:
        rez+=i+1
        break
print(rez if rez else 0)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Solving a problem need help! totoandreev 5 2,200 Nov-07-2020, 06:44 PM
Last Post: totoandreev
  How to Use Python for solving the following physics question. Python Code required ishahid 8 3,537 Dec-18-2019, 06:59 AM
Last Post: akashraj128

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020