ValueError: max() arg is an empty sequence [python 3] - python

IS the list being nullified after calculating sum??
t = int(input())
while t > 0:
n,m=map(int,input().split())
a=map(int,input().split())
l,o=sum(a),max(a)
print(l)
if ((o * n)-l) == m:
print("YES")
else:
print((o * n)-l)
print("NO")
t = t-1

In Python 3 map() returns an iterator (unlike Python 2). The sum() function iterated over all the results already, and the iterator is now empty:
>>> sample = '1 2 3'
>>> map(int, sample.split())
<map object at 0x10523b2e8>
>>> a = map(int, sample.split())
>>> list(a)
[1, 2, 3]
>>> list(a)
[]
Use list() to copy the results to a list object, or better still, use a list comprehension instead of map():
a = [int(i) for i in input().split()]

Try like this:-
inputparam='100 2 300'
a = [int(i) for i in inputparam.split()]
maxNo=max(a)
sumno=sum(a)

Related

How to convert a list of list of strings into integers

This is a list that I have [['1.0\n'],['2.0\n'],['3.0\n']] and I would like to convert them into integers 1 2 3 without comma separation and \n.
I'm not sure how to do this conversion as there's a list within a list and I don't really know how to get rid of \n altogether. Thanks.
if you want [[1], [2], [3]], you can try
lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [[int(float(j.replace("\n", ""))) for j in i] for i in lst]
if you want [1, 2, 3], you can try
lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [int(float(i[0].replace("\n", ""))) for i in lst]
Depends on whether you want rounding or not and or a new list. Is there a reason why you have a list in a list? But you'd do something like this
x = [['1.0\n'],['2.0\n']]
y = []
for item in x:
tmp = item[0].replace('\n','')
y.append(int(float(tmp)))
print(y)
There is a way:
ls=[['1.0\n'],['2.0\n'],['3.0\n']]
result=[]
for ll in ls:
[result.append(int(float(l.replace('\n','')))) for l in ll]
print(result)
Output: [1, 2, 3]
This code just works under this condition: [if every element in the list has \n]
Like Raya's answer, I use the int(float(l)) way, if every element has '.0', you can also use l.replace('\n','').replace('.0','').
Removing /n and consolidate to a single list
You could solve this with list comprehension.
list = [['1.0\n'], ['2.0\n'], ['3.0\n']]
my_list = [int(float(value[0].strip())) for value in list]
print(my_list)
Output: [1, 2, 3]
The main things to note in this solution are:
The nested lists are iterated through, selecting the first element of each with value[0].
Each iteration:
Value: '1.0\n' is stripped of the \n with value[0].strip()
Value: 1.0 is then converted to a float float(value[0].strip())
Value: 1 is then converted to a integer int(float(value[0].strip()))
Without comma separation
list = [['1.0\n'], ['2.0\n'], ['3.0\n']]
my_list = [int(float(value[0].strip())) for value in list]
my_string = " ".join(str(value) for value in my_list)
print(my_string)
Output: 1 2 3

How to convert an integer to a list in python?

I have an integer object for example a = 1234 and I want to convert it to a list, so it would look something like [1234].
I tried converting it into a string first and then converting it to a list but that gives me [1,2,3,4].
Any suggestions?
You can just cover it in brackets.
a = 1234
print([a])
Or append()
b = []
b.append(a)
output
[1234]
Here:
a = 1234
lst = []
lst.append(a)
print(lst) #[1234]
If you are trying to convert in to string, use str()
>>> str(1234)
'1234'
If you are trying to put your int in a list, use []:
>>> var = 1234
>>> [var]
[1234]
or do:
>>> l = []
>>> l.append(var)
>>> l
[1234]
Just cover it with brackets:
a=1243
a=[a]
or create a list and append a
b = []
b.append(a) # or you could do b=[a]

How to check if any combination of two list items occurs in list

I'm wondering if there is a way to check if any combination of more than two items from a list exists in another list?
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
for string in lists:
strings = string.split()
print(strings)
SAMPLE OUTPUT for strings:
['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']# this line should identify 'banana', 'soap' and 'veggies'
['maybe', 'there','are','more','sweets','left','later'] # this line should be ignored, because not more than 2 items of the list are in it
['food', 'shopping','is','boring','and','i','hate','mash','with','veggies']# this line should identify 'mash' and 'veggies'
I know that by using this piece of code, I can at least check if any of the elements appear in strings:
combinations = any(i in list_1 for i in strings)
You can use set intersection and check the resulting size:
s1 = set(list_1)
if len(s1.intersection(strings)) >= 2:
# do stuff
This will, however, not trigger if the same item occurs twice in strings which may or may not be what you desire. In that case, you could do something like:
if sum(s in s1 for s in strings) >= 2:
# do stuff
I was late apparently. This is basically schwobaseggl's solution wrapped as a function
mylist = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
mytest = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
def common_elements(mylist, mytest):
common_elements = list(set(mylist).intersection(mytest))
if len(common_elements)>2:
return common_elements
else:
pass
This should work:
string = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
n = 0
inv = []
for i in string:
if i in list_1:
inv.append(i)
n += 1
if n >= 2:
print(inv)
or you can put it into a define and make yourself a function:
def check(string,list_1):
inv = []
for i in string:
if i in list_1:
inv.append(i)
if len(inv) >= 2:
return inv
else: return []
string = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
print(check(string,list_1))
You can try this "hard-coded" way too
list1=['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
list2 = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
def check(list_1,list_2) :
common = list()
for i in list_1 :
if i in list_2 :
common.append(i)
if len(common) >=2 :
return common
else :
return "Less than two items are common"
try = check(list_1,list_2)
If I am not wrong, you want to find out that 2 lists have more than 2 same element?
def intersection(list_one, list_two):
intersection = set(list_one) & set(list_two)
if len(list(intersection)) > 1:
print(list(intersection))
return False
a = [1, 2, 3, 4]
b = [1, 8, 9, 10]
c = [1, 2, 5, 6]
intersection(a, b) # return False
intersection(a, c) # return [1, 2]

Create a list of consequential alphanumeric elements

I have
char=str('DOTR')
and
a=range(0,18)
How could I combine them to create a list with:
mylist=['DOTR00','DOTR01',...,'DOTR17']
If I combine them in a for loop then I lose the leading zero.
Use zfill:
>>> string = "DOTR"
>>> for i in range(0, 18):
... print("DOTR{}".format(str(i).zfill(2)))
...
DOTR00
DOTR01
DOTR02
DOTR03
DOTR04
DOTR05
DOTR06
DOTR07
DOTR08
DOTR09
DOTR10
DOTR11
DOTR12
DOTR13
DOTR14
DOTR15
DOTR16
DOTR17
>>>
And if you want a list:
>>> my_list = ["DOTR{}".format(str(i).zfill(2)) for i in range(18)]
>>> my_list
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
>>>
You can do it using a list comprehension like so:
>>> mylist = [char+'{0:02}'.format(i) for i in a]
>>> mylist
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
Simply use list comprehension and format:
mylist = ['DOTR%02d'%i for i in range(18)]
Or given that char and a are variable:
mylist = ['%s%02d'%(char,i) for i in a]
You can, as #juanpa.arrivillaga also specify it as:
mylist = ['{}{:02d}'.format(char,i) for i in a]
List comprehension is a concept where you write an expression:
[<expr> for <var> in <iterable>]
Python iterates over the <iterable> and unifies it with <var> (here i), next it calls the <expr> and the result is appended to the list until the <iterable> is exhausted.
can do like this
char = str('DOTR')
a=range(0,18)
b = []
for i in a:
b.append(char + str(i).zfill(2))
print(b)

Nested List and For Loop

Consider this:
list = 2*[2*[0]]
for y in range(0,2):
for x in range(0,2):
if x ==0:
list[x][y]=1
else:
list[x][y]=2
print list
Result:
[[2,2],[2,2]]
Why doesn't the result be [[1,1],[2,2]]?
Because you are creating a list that is two references to the same sublist
>>> L = 2*[2*[0]]
>>> id(L[0])
3078300332L
>>> id(L[1])
3078300332L
so changes to L[0] will affect L[1] because they are the same list
The usual way to do what you want would be
>>> L = [[0]*2 for x in range(2)]
>>> id(L[0])
3078302124L
>>> id(L[1])
3078302220L
notice that L[0] and L[1] are now distinct
Alternatively to save space:
>>> [[x,x] for x in xrange(1,3)]

Categories

Resources