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!!
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.)
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.
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.
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()))
https://ideone.com/Q2MZCo
Related
I was searching for an answer for this question but couldn't find it. I am posting a answer. Hope it helps someone in the future. Program is tested and works.
n = count of numbers to remove from the list
numbers_list = input().split()
n = int(input())
for i in range(len(numbers_list)): # converts it from string to integers
numbers_list[i] = int(numbers_list[i])
for i in range(n):
min_element = min(numbers_list)
numbers_list.remove(min_element)
for i in range(len(numbers_list)): # converts it again from integers to string
numbers_list[i] = str(numbers_list[i])
print(", ".join(numbers_list))
I am trying to make a list of only sorted positive list when the user gives positive and negative integers in that list. For example, if the user gave "10 -7 4 39 -6 12 2" my program would only sort the positive numbers and give out '2 4 10 12 39'.
So far this is what my code looks like:
list = input().split()
positive_list = []
for i in range(list):
if list[i] > 0:
positive_list.append(list[i])
i+=1
positive_list.sort()
print(positive_list)
You have several issues:
you have a variable that's named the same as a basic type (list), which shadows the type; pick a better name
for i in range(my_list): doesn't do what you think; you could do for i in range(len(my_list)):, but you can also just for n in my_list: and n will be every element in my_list in turn
your user enters text, you'll need to turn those strings into integers before comparing them to other integers, using int()
you do for i .. but also i += 1 you don't need to increment the for-loop variable yourself.
Look into list comprehensions, they are perfect for what you're trying to do in a more complicated way, to construct positive_list.
Your solution could be as simple as:
print(sorted([int(x) for x in input().split() if int(x) > 0]))
But staying closer to what you were trying:
numbers = [int(x) for x in input().split()]
sorted_positive_numbers = sorted([x for x in numbers if x > 0])
print(sorted_positive_numbers)
If you insist on a for-loop instead of a list comprehension:
numbers = [int(x) for x in input().split()]
positive_numbers = []
for number in numbers:
if number > 0:
positive_numbers.append(number)
print(sorted(positive_numbers))
Rename list to something other than that. list is a python keyword.
For example list_new or list_temp
My suggestion is to try it like this:
positive_list = []
for num in listNew:
if num > 0:
positive_list.append(num)
positive_list.sort()
So I am doing an assignment in school where I am given a range of numbers and the result is basically to find the number of numbers that can be divided by a factor digit, f, and contain the "must-have" digit, m. So I used list comprehension in my code and I have a list that contains all the numbers in the range that can be divided by f. But I need help on how to make a list that only has the numbers that have the "must-have" digit m.
def find_winner(f, m, n):
a = [x for x in range(1, n+1) if x % f == 0]
b = list(map(int, str(a[0])))
c = [z for z in b if z == str(m)]
return len(c)
Firstly you don't need to loop over all the numbers from 0 to n if you just want the ones that are divisible by f, when you can instead loop with a step of f.
Secondly, if you want to check whether digit is contained in the string, you could use string representation.
For example:
def find_winner(f, m, n):
digit_string = str(m)
if len(digit_string) != 1:
raise ValueError('m must be a one-digit number')
valid_numbers = [x for x in range(f, n+1, f) if digit_string in str(x)]
return len(valid_numbers)
If you have not yet covered exceptions, you might want to replace the raise ... line with a print statement and something like return None.
Here is a rather simple way of doing this:
def find_solutions(numbers, factor, digit):
solutions = 0
for i in range(len(numbers)):
if (numbers[i]%factor == 0 and str(digit) in str(numbers[i])):
solutions += 1
return solutions
If you care about the solutions then you could do this:
def find_solutions(numbers, factor, digit):
solutions = []
for i in range(len(numbers)):
if (numbers[i]%factor == 0 and str(digit) in str(numbers[i])):
solutions.append(numbers[i])
return solutions
Please give some thought as to what is happening here as opposed to just copying it and feel free to reply if you have anything to say. By the way, I have tried to name your variables appropriately for clarity.
The question is to take 4 integers as input entered in separate lines.
ex:=
1
1
1
2
The below code does the required thing. I am trying to understand its working part.
x,y,z,n=[int(input()) for _ in range(4)]
welcome!
This code is the equivalent of
x = int(input())
y = int(input())
z = int(input())
n = int(input())
The input() function reads an input from the user and the int tries to transform it to an integer, which is assigned to each variable (x,y, z and n).
The code can be also written as:
numbers = []
for i in range(4): # Loop 4 times
numbers[i] = int(input())
x = numbers[0]
y = numbers[1]
z = numbers[2]
n = numbers[3]
Which is more similar to the form you provided. But the author uses two python features that makes the code smaller (and more expressive). I'll explain both:
List Comprehensions
Lot of times during programming, you will be whiling to execute a command several times and get the results into an list, or for example, map values from one list to other. In this case, you would have something like this:
numbers_til_5 = [0,1,2,3,4,5]
squares_til_5 = []
for n in numbers_til_5:
squares_til_5.append(n*n)
With the List Comprehension syntaxe, we could do:
sqaures_til_5 = [ n*n for n in numbers_til_5]
The other feature is:
Destructuring
This is a feature that allows you to get elements of a list in one single statement.
In the example we have this:
x = numbers[0]
y = numbers[1]
z = numbers[2]
n = numbers[3]
Which could be replaced by x,y,z,n = numbers.
Another form interesting, is when you care only for the first arguments, for example:
first = numbers[0]
rest = numbers[1:] # This get all elements starting from the first
could be written as first, *rest = numbers.
I hope I was able to make it clear.
for _ in range(4) repeats int(input()) 4 times, so the brackets contain now the first four inputs [1, 1, 1, 2].
In Python you can assign multiple variables at one time, so x,y,z and n will be assigned to the corresponding values of the bracket.
For better understanding, you could extract the individial parts like this:
x = int(input())
y = int(input())
z = int(input())
n = int(input())
It is running a loop to input values as integers and feeding those values to the variable x,y,z,n in that sequence. range(n) runs the loop for a range 0-n (in this case, 4 times). _ is used to denote "anything" while running the loop.
Given a list, I need to print the numbers in sorted order and remove any duplicates. I am using python 3.7.2
My code:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = input().split()
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
However, whenever my input consists of a 2 digit number, the logic fails.
Eg. for input of 2 1 43 2 5, I get an output of 1 2 43 5.
This work perfectly for single digit numbers. Can someone help me out with this?
You only need a slight modification. You are comparing strings instead of numbers, so try this instead:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = map(int, input().split())
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
If you want, you can also do:
numbers = (int(x) for x in input().split())
You can simplify this in various aspects. Sort by numeric value using an appropriate key function, use a for loop if you know the number of iterations beforehand, utilize appropriate string utils like str.join, etc.
testcases = int(input())
for _ in range(testcases):
print(' '.join(sorted(set(input().split()), key=int)))
You are going correct way with set(numbers) to remove duplicates. The problem comes from sorted with your numbers being list of strs not ints.
Try this:
x_numbers = input().split()
numbers = [int(x) for x in x_numbers]
Try it now:
testcase = int(input())
n=list(str(testcase))
results = map(int, n)
numbers= sorted(set(results))
print(numbers)
code here:https://repl.it/repls/SeriousRosybrownApplicationprogrammer
We can keep it simple like this. This is a reference
input=raw_input() #took input as string
inputlist=input.split() #split the string to list
lsintegers = map(int, list(set(inputlist))) #remove duplicates converted each element to integer
lsintegers.sort() #sorted
print(lsintegers)`