this program takes 3 lists of numbers, and compares A and B to the list n. if a term from A is in n, the happiness increases. if a term from B is in n, the happiness decreases. However, when I am doing these calculations, the if ... in statement to check if a term from A/B is in n doesn't work - I have done print(happy) after each one to check, and I get no result
A = []
B = []
n = []
happy = 0
lengthn, lengthAB = input("").split()
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.append(newNumbers)
for i in lengthAB:
numbers = input("")
ANumbers = numbers.split()
A.append(ANumbers)
for i in lengthAB:
numbers = input("")
BNumbers = numbers.split()
B.append(BNumbers)
long = int(lengthAB)
for i in range(long):
j = int(i)
if A[j - 1] in n:
happy = happy 1
print(happy)
if B[j - 1] in n:
happy = happy - 1
print(happy)
i = i 1
print(happy)
Thank you so much for the help!!
CodePudding user response:
You appended a list to n
, not each element of that list. You can write
n.extend(newNumbers)
instead.
You could just write n = newNumbers.split()
, but as pointed out in a comment, you probably have an indentation error:
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.extend(newNumbers)
Or, you don't need split at all:
for i in lengthn:
number = int(input(""))
n.append(number)
At some point, you probably mean to convert the string inputs to integers; may as well do that immediately after reading the string. (I'm declaring various techniques for handling conversion errors beyond the scope of this answer.)
CodePudding user response:
Contrary to what you seem to expect the variables: lengthn, lengthAB
are strings
The for-loop
for i in lengthn:
numbers = input("")
iterates over the characters in the string lengthn. If lengthn='12'
it will ask to provide input twice.
If lengthAB is '13' for example you will get 2 numbers in your list BNumbers but later on you try to test 13 values because int('13') is 13.
CodePudding user response:
for i in lengthn:
numbers = input("")
so the numbers you are getting are the form of string it's will iterate on string rather then a number.
CodePudding user response:
You should look for beeter python book. Based on desription I think this should look like this:
def happiness(A, B, n):
return sum(x in n for x in A) - sum(x in n for x in B)
def get_data(prompt=""):
return [int(x) for x in input(prompt).split()]
print(happiness(get_data(), get_data(), get_data()))