Mistake in Python code - python

There is an array of integers. There are also disjoint sets, A and B, each containing integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each integer in the array, if i in A, you add 1 to your happiness. If i in B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.
Input Format
The first line contains integers n and m separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A and B respectively.
Output Format
Output a single integer, your total happiness.
Sample Input
3 2
1 5 3
3 1
5 7
Sample Output
1
Can someone please explain what is wrong with this solution? It passes some test, but fails on others.
input()
array = set(input().split())
set1 = set(input().split())
set2 = set(input().split())
res = len(set1 & array) - len(set2 & array)
print(res)

The problem is that you're transforming your inputs to sets, which in turn removes the duplicates. If you have repeated values in your input, with the set you're only adding/substracting 1 to the resulting happiness. If that's correct, your code is fine. If not, then you should work with lists rather than sets.
The code could be something like this:
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# Now we use some list comprehension to get the happiness result
res = sum([1 for elem in array if elem in list1]) - sum([1 for elem in array if elem in list2])
The first sum accumulates the positive points, and the second one the negatives. It works with multiple occurences, adding/substracting one point per each.
EDIT
A more clear approach, to understand the for loop
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# We create a variable res which will store the resulting happiness, initially 0
res = 0
# Now we iterate through the elements in array and check wheter they should add or substract
for elem in array:
# If the element is in list1, we add 1 to res
if elem in list1:
res += 1
# If the element is in list2, we substract 1 from res
elif elem in list2:
res -= 1

I took the inputs for list A and B and as a general list. I wanted to obtain happiness in 1 line using list comprehension as below. After I merged print and "happiness =" , in one line. Apparently, this is the solution to make the code faster.
input()
my_array = input().split()
listA=list(input().split())
listB=list(input().split())
print (sum(1 for data in my_array if data in listA)+sum(-1 for data in my_array if data in listB))

Related

I am getting error in code in taking input and append it to array

You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.
Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations. Note: For each cut operation, you have to recalculate the length of smallest sticks (excluding zero-length sticks).
Input
The first line contains a single integer N.
The next line contains N integers separated by space, where each integer represents the length of the ith stick.
6
5 4 4 2 2 8
Output
For each operation, print the number of sticks that are cut, on separate lines.
6
4
2
1
Explanation
import array as arr
n = int(input())
a = arr.array('i',[1002])
for i in range(n):
c = [int(x) for x in input().split()]
a.append(c)
t=n
for i in range(0,1001):
if a[i] > 0:
print(t)
t=t-a[i]
You can't append a list to an integer array. If you want to merge two arrays you can use the extend method.
a.extend(c)
if a is list then below all satisfies but here a is array so we cant append list with array
a = [1,2,3] # a is a list
c = [4] # c is list
it won't give you correct result in any case
print(a.append(c)) # if we do a.append(c) result is like a = [1,2,3,[4]]
gives you correct result in any case
print(a.extend(c)) # if we do a.extend(c) result is like a = [1,2,3,4]
satisfies if "a" is list and "c" is list or "a" is array and "c" is also an array
a += c # a += c result is same as a.extend(c)
print(a) # a = [1,2,3,4]

Python - Printing 2 array elements for each line

I would like to create a (for) loop that print 2 Array elements for each line. You'll understand better with an example:
array = ["A","B","C","D"]
The output I want is:
A B
C D
How I can do this? Thanks!
There are some good posts earlier to learn more about Python looping of list. Here is a simple way to get what you expected output - regardless of this list has even or odd items.
lst = ['A', 'B', 'C', 'D'] # can add 'E' to try odd number items.
for i, ch in enumerate(lst, 1):
print(ch, end='\t')
if i % 2 == 0: # check to see if it hit the interval threshold?
print() # if you want 3 items in a row, you can change 2 to 3
Output
A B
C D
Iterate through the list and print 2 items with the print command. You can specify 2 as the increment for iterating, and join part of the list, and can handle odd numbers too. The slice of a list goes up to but not including the 2nd number, so slice with i:i+2. At the end of an odd-length list, there will be no 2nd item but the slice won't give an index-out-of-range error:
list1 = ["A","B","C","D","E"]
for i in range(0, len(list1), 2):
print(' '.join(list1[i:i+2]))
to get
A B
C D
E

Adding string values together that are elements in a list

How would I go about doing the following? I need to add the number in the various elements together and assign the total to a new variable. I have been trying for days without much luck. I'm not sure if the numbers have to be split from the letters first?
list = ['2H','4B']
any help would be GREATLY appreciated.
edit:
Thanks for the replies eveyrone. I dont know why I cant get this right it seems like it should be so simple.
I will give you guys some more infomration.
the list below represents to playing cards, the first number or letter is the face value ie: 2 or 3 but can be a 'K' as well which stands for king and the value for that will be ten. the second part is the card suit ie. C for Clubs or H for hearts. I need to add the face value for these two cards together and get the hand total. a More accurate list might look like this.
list1 = ['KH', '10C']
Is this helping. it will help regardless of the number position in them element.
list1 = ['2H','4B']
list1=[word for x in list1 for word in x] #== Split the elements
print(list1)
new_var=0
for value in list1:
try:
value=int(value) #=== Convert to int
new_var+=value #== Add value
except ValueError:
pass
print(new_var)
One approach, using a list comprehension along with re.findall to extract the leading digits from each list entry:
list = ['2H','4B']
nums = [int(re.findall(r'^\d+', x)[0]) for x in list] # [2, 4]
output = sum(nums) # 6
You should avoid using function names as variable names i.e. list =
There are a few ways to do this and I suggest you review the Python documentation on slicing and indexing strings.
l = ['2H','4B']
result = sum(int(x[0]) for x in l)
print(result)
result equals sum of first char of each element of the list. I have converted each indexed element zero to integer to allow addition.
You can also do it the following way:
result = 0
for x in l:
result += int(x[0])
print(result)
You can extract numbers from each string then add them
You can use
total = 0
list = ['2H','4B']
for element in list:
res = [int(i) for i in element.split() if i.isdigit()]
total += sum(res)
print(total)

How to find the averages of an argument which consists of nested arrays in python

This is the argument i would be passing to my logic.
var= '--a1=[[1,2,3],[]] --a2=4'
I need to find the average of these two arrays as mentioned below.
"1 4"
because [1,2,3] evaluates to 2, [] evaluates to 0 and the average of [2,0] is 1.
I have tried the code as given below,but its of no use.
var="--a1=[1,2,3] --a2=4.0"
args=var.split(' ')
args=[s[s.find('=') + 1:] for s in args]
print (args)
for elem in args:
for i in elem:
print (i)
Can someone please help me
Here is one way to do it:
(assuming you want the average, not the item located at the middle. If the middle is what you need, you should be able to adapt the following solution by yourself)
var="--a1=[1,2,3] --a2=4.0"
args=var.split(' ')
args=[s[s.find('=') + 1:] for s in args]
for elem in args:
# remove everything but numbers and commas (we don't care about nested arrays here)
# "[[[1,2,3],[]]" --> "1,2,3,"
stripped = "".join([ c for c in elem if c.isdigit() or c == ','])
# now, split by commas, and convert each number from string to int (ignore empty strings with `if d`)
# "1,2,3," --> [1,2,3]
numbers = [int(d) for d in stripped.split(",") if d]
# now, just compute the mean and print
avg = sum(numbers) / len(numbers)
print(avg)
I've utilized the inbuilt eval() function to solve your problem. I've tried my best to explain the code in the comments. Take a look at the code below:
def average(array): # returns the average of the values in an array
n = 0
if array == []:
return 0
else:
for i in array:
n += i
return n/len(array)
var= '--a1=[[1,2,3],[]] --a2=4'
start = var.find('[') # I used this method the find the first "[" in the string
end = len(var) - var[::-1].find(']') # I reversed the string to find the last "]" in the string
a1 = eval(var[start:end]) # converts the list in the form of string to a list
# for example "[1,2,3]" will be converted into [1,2,3] using the eval function
if var.count('[') == 1: # the code below requires a 2d array so this part converts the array to 2d if 1d is passed
a1 = [a1]
averages = [] # to store the averages of all of the lists
for array in a1:
averages.append(average(array)) # finding average for each array in the string
print(averages)

how to take 2d list from user in python?

I want that user give input like this
[[3,4,5],[7,2,1]]
and it will create a 2d array automatically and store in a. so when print(a) will given it returns
a=[[3,4,5],[7,2,1]]
where type(a[0][0]) i mean all elements inside a will be int. How can I do it?
Input:
2 // no.of rows
3 // no.of columns
1 2 3
4 5 6
Output:
[[1,2,3],[4,5,6]]
Solution:
r = int(input())
c = int(input())
a = [list(map(int,input().split())) for _ in range(r)]
print(a)
The variable c isn't used in the code, so you can simply get it as a string and also ignore the assignment using input()
Line 3 involves List Comprehension (documentation).
n = int(input())
m = int(input())
input_list = []
for i in range(n):
list1 = []
for j in range(m):
z = int(input())
list1.append(z)
input_list.append(list1)
print(input_list)
Okay so we take the size of the 2-d array from the user in n and m resp.
We create an empty list named as input_list.
Now we run a loop for n times so this will be the number of rows in the 2-d array.
for every row we create a list named as list1. Run a loop to take inputs from the user on the elements in the row.
Then we append the newly created row (list1) in the input_list.This action is performed for all the rows.
And when the execution finishes we get the input_list as a 2-d array.

Categories

Resources