input:
5
30
50
10
70
65
5 is how many numbers follow after.
My code:
n = int(input())
list = []
i = 0
while len(list) < n:
integer = int(input())
list.append(integer)
i = i + 1
minList = min(list)
integers = list[i - 1] - minList
print(integers)
I'm suppose to subtract the smallest number from the 5 integers.
The correct output: 20 40 0 60 55
My output: 0 20 0 60 55
I understand why my output is wrong since the smallest number is 20 until 10 is inputed, but I don't know how to correct it. I tried different ways, but none of them work. How do I subtract the smallest number from each integer?
Get the inputs to a list. Take minimum of this list using min()
and then subtract minimum value from each of the list elements:
n = int(input()) # Read number of numbers
lst = []
for _ in range(n):
lst.append(int(input())) # Append to list
min_value = min(lst) # Take the minimum number
final_lst = [abs(x-min_value) for x in lst] # Subtract minimum from each number
Collect all the input first, then find the minimum value and print the numbers.
n = int(input())
numbers = []
while len(numbers) < n:
integer = int(input())
numbers.append(integer)
smallest = min(numbers)
for number in numbers:
print number - smallest
size = int(input())
lst = [int(input()) for _ in range(size)]
m = min(lst)
res = [abs(n - m) for n in lst]
This looks like a default puzzle for sites like Hackerrank ... take all the inputs , then perform your operations on all inputs. Do not meddle with data while still gathering inputs (unless it makes sense to do so).
A nice way of getting all the data is:
n = int(input()) # get how many inputs follow
# get n inputs, perform the int() conversion, store as list.
data = list(map(int, (input().strip() for _ in range(n))))
# calculate the min value
min_value = min(data)
# print all reduced values in order each on one line
print( *[x-min_value for x in data], sep = "\n")
# or comma seperated:
print( *[x-min_value for x in data], sep = ",")
Output:
# print with sep="\n"
20
40
0
60
55
# print with sep=","
20,40,0,60,55
Read the doku for map() , int() , min() and look at Built in functions : do not use those as names for your variables, neither use list
, dict
, set
, tuple
.
Try this:
l = list()
for _ in range(int(input())):
l.append(int(input()))
xmin = min(l)
print(*[x - xmin for x in l])
Output:
C:\Users\Documents>py test.py
5
30
50
10
70
65
20 40 0 60 55
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.