PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

[FIXED] How to write function that take a list and number X .If X exist in list in index ‘m’, it should return sum of elements of list from index ‘m’

 September 18, 2022     function, list, printing, python, range     No comments   

Issue

def func(x):
    lst=list(map(int,input("Enter a list of numbers: ").split()))
    flag=0
    num=0
    for i in lst:
         if x==i:
                flag=1
                
    if flag==1:
        ab=lst.index(x)
        for i in range(ab,len(lst),1):
            num=lst.index(ab)
            num=num+lst[i]
            print(num)
    return num
        
    
y=input("Enter a number present in the list: ")
print(func(y)) 

Above is the function to find all numbers and sum from index m. It takes a number from the user,gets the index and prints the sum of the number from index m. But the code output is 0 in this case


Solution

First of all, you can use split() with empty parameter.

And a solution of your problem is:

    def func(x):
    a=input("Enter list of Numbers: ")
    lst=list()
    for i in a:
        try:
            i=int(i)
            lst.append(i)
        except:
            pass
    num=0
    x=int(x)
    for i in (lst):
        if x==i:
            index=lst.index(x)
            for i in range(index,len(lst),1):
                num=num+lst[i]
    return num
        
        
    
y=input("Enter a number present in the list: ")
print(func(y)) 

instead of map i have used the for loop to covert the string to a integer list. then if x==i i searched the index of x in the list and from the index i start to sum the numbers again using a for loop.



Answered By - Faraaz Kurawle
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing