Sub arrays in python - python-3.x

How to print the sum of user desired subarray from a given list [1,2,3,4,5,6] using slice method in python ?
I've got success till the slice method and displaying the subarray , but I am not able to do the sum operation as it is showing error for data type of list i.e. string.

You can use the builtin function sum or do it manually by:
arr= []
sum= 0
for i in range(len(subarr)):
sum+= subarr[i]
arr.append(sum)
return arr

Related

for loop doesn't itterate through all the data? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

max() arg is an empty sequence in max(listname)

I have written a program which accepts a list of numbers and returns the largest number possible by concatenating the list of numbers in Python. But when I execute the code I get following error message ValueError: max() arg is an empty sequence. Here is my code:
def create_largest_number(number_list):
l=list()
m=max(number_list)
while(number_list!=0):
m=max(number_list)
l.append(m)
number_list.remove(m)
return l
number_list=[23,45,67]
largest_number=create_largest_number(number_list)
print(largest_number)
Sample Input: 23,34,55
Sample Output: 554323
number_list!=0 is always going to be true because number_list is a list, not a number, so while number_list != 0 is an infinite loop, and given that you're removing items from the list on each iteration, the list will eventually become empty. Yet it'll never become zero, so on the next iteration your code will attempt to calculate max(number_list) == max([]), which is an error.
You can solve it this way:
while number_list: # a.k.a. `while len(number_list) > 0:`

Converting string to float with error handling inside a list comprehension

Consider the following list of lists:
list1 = [['1.1','1.2'],['2.1', '2.2'],[''],...]
This list contains lists with empty strings. To convert all strings in this list of lists to floats one could use list comprehension, such as:
[[float(j) for j in i] for i in list1]
(thanks to).
But there is one problem with the lists containing empty strings - they cause an exception:
ValueError: could not convert string to float:
Is there a way to use this kind of list comprehension without using loops explicitly?
Use an if condition inside the inner list comprehension to ignore empty strings:
[[float(j) for j in i if i] for i in list1]
if i will test the "truthiness" of strings. This will only return False for empty strings, so they are ignored.
Or, if you want to be more robust about it, use a function to perform the conversion with exception handling:
def try_convert(val):
try:
return float(val)
except ValueError, TypeError:
pass
[[float(z) for z in (try_convert(j) for j in i) if z] for i in list1]

unable to delete all element satisfying condition in a python list using enumerate

i am trying to delete zero values from the list using the below code
for id,row in enumerate(list):
if row[0]=="0":
del list(id)
this works fine for input like
[0,1,3,0,9,10,0,3,0,6]
but doesn't work as expected for inputs like
[0,0,1,3,4,0,0,4,5,6,0,0].
output: [0,1,3,4,0,4,5,6,0]
I guess its because the element right after the deleted one gets the id of the deleted element and enumerate increments the id which leaves the element after the one which is deleted unchecked.
so what can be done to check all the elements ? is there a better way ?
I made a little change to your code:
mylist = [0,0,1,3,4,0,0,4,5,6,0,0]
for id,row in reversed(list(enumerate(mylist))):
if(row==0):
del mylist[id]
If you loop your list in the way you did (from start to end) and delete an element while doing it, you'll end up jumping indexes because python does not recognize that an element has been deleted from the list.
If you have an array with 10 elements inside and you delete the first (idx 0), in the next iteration you will be at index 1, but the array has been modified, so your idx 1 is the idx 2 of your array before the deletion, and the real idx 1 will be skipped.
So you just need to loop your array in reverse mode, and you won't miss indexes.
If you print the value of mylist, you'll get [1, 3, 4, 4, 5, 6].
This problem is documented on this python page under 8.3:
https://docs.python.org/3/reference/compound_stmts.html
They suggest doing it this way by using a slice. It works for me:
a = [-2,-4,3,4]
for x in a[:]:
if x < 0: a.remove(x)
print ('contents of a now: ')
print(*a)
enumerate returns an object called enumerate object and it is iterable not actually a list. second thing row is not a list it is not subscriptable.
for i,row in enumerate(l):
if row==0:
del(l[i])
you will not get result you want this way.
try this:
t=[] #a temporary list
for i in l:
if i!=0:
t.append(i)
t will contain sublist of l with non zero elements.
put the above inside a function and return the list t .

Resources