subtract n values from input python - python

I haven't found anything even relevant to my question, so i may be asking it wrong.
I am working on an exercise where I am given sequential values starting at 1 and going to n, but not in order. I must find a missing value from the list.
My method is to add the full 1 => n value in a for loop but I can't figure out how to add n - 1 non-sequential values each as its own line of input in order to subtract it from the full value to get the missing one.
I have been searching modifications to for loops or just how to add n inputs of non-sequential numbers. If I am simply asking the wrong question, I am happy to do my own research if someone could point me in the right direction.
total = 0
for i in range (1 , (int(input())) + 1):
total += i
print(total)
for s in **?????(int(input()))**:
total -= s
print(total)
sample input:
5
3
2
5
1
expected output: 4

To fill in the approach you're using in your example code:
total = 0
n = int(input("How long is the sequence? "))
for i in range(1, n+1):
total += i
for i in range(1, n):
total -= int(input("Enter value {}: ".format(i)))
print("Missing value is: " + str(total))
That first for loop is unnecessary though. First of all, your loop is equivalent to the sum function:
total = sum(range(1,n+1))
But you can do away with any iteration altogether by using the formula:
total = int(n*(n+1)/2) # division causes float output so you have to convert back to an int

I don't know if you are supposed to create the initial data (with the missing item), so I added some lines to generate this sequence:
import random
n = 12 # or n = int(input('Enter n: ')) to get user input
# create a shuffled numeric sequence with one missing value
data = list(range(1,n+1))
data.remove(random.randrange(1,n+1))
random.shuffle(data)
print(data)
# create the corresponding reference sequence (without missing value)
data2 = list(range(1,n+1))
# find missing data with your algorithm
print("Missing value =", sum(data2)-sum(data))
Here is the output:
[12, 4, 11, 5, 2, 7, 1, 6, 8, 9, 10]
Missing value = 3

Related

Get list of "n" unique random numbers from the given range

I need 3 unique random numbers between 1 to 20.
I have a loop generating 3 random numbers from 1-20. And I don't want there to be any repeats. I have something that works for the first two numbers. But in my code the first and third numbers can still be the same which needs to be fixed.
i = 1
while i <= 3:
x = random.randint(1, 20)
print(choice([i for i in range(1, 20) if i != [x]]))
i += 1
Is there a better way to achieve this in Python?
You can use random.sample(). Below example will return you 3 unique random numbers between 1 to 20.
>>> import random
>>> sample_count = 3 # count of required unique numbers
>>> start_range, end_range = 1, 20 # start and end range
>>> random.sample(range(start_range, end_range+1), sample_count)
[4, 1, 14]
Please refer random.sample() documentation for more details.

Adjust values in a list by normalizing_zybook

1.7 LAB: Adjust values in a list by normalising
When analysing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This can be done by normalising to values between 0 and 1, or throwing away outliers.
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, adjust each integer in the list by subtracting the smallest value from all the integers.
Ex: If the input is:
5
30
50
10
70
65
the output is:
20
40
0
60
55
The 5 indicates that there are five integers in the list, namely 30, 50, 10, 70, and 65. The smallest value in the list is 10, so the program subtracts 10 from all integers in the list.
Anyone can solve this question in python?
This is my code.
arr1 = []
input = int()
for i in range(0,input):
e = int(intput())
arr1.append(e)
k = min(arr1)
for i in range(0,val):
arr1[i] = arr1[i] - k
for i in range(0,val):
print(arr1[i])
Here is the error.
Traceback (most recent call last):
File "main.py", line 8, in <module>
arr1.append(e)
NameError: name 'e' is not defined
You could use list comprehension:
input = [5,30,50,10,70,65]
input = input[1:]
output = [i - min(input) for i in input]
print(output)
[20, 40, 0, 60, 55]
This is the way I solved it
list = []
values = int(input())
for n in range(values):
number = float(input())
list.append(number)
largest = max(list)
for number in list:
number = number / largest
print(f'{number:.2f}')
def get_minimum_int(nums):
low = min(nums)
return low
if __name__ == '__main__':
num = int(input())
nums = []
while num != -1:
nums.append(num)
num = int(input())
l = get_minimum_int(nums)
for n in nums:
print(n - l)
idk if your question ever got answered but I also had the same type of task.
Mine was:
"For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f}'.format(your_value))
Ex: If the input is:
5
30.0
50.0
10.0
100.0
65.0
the output is:
0.30
0.50
0.10
1.00
0.65
The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and 65.0. 100.0 is the largest value in the list, so each value is divided by 100.0."
So this is how I solved mine:
x = int(input())
dislist = []
i = 1
while i <= x:
y = float(input())
dislist.append(y)
i += 1
q = max(dislist)
for item in dislist:
item = item / q
print('{:.2f}'.format(item))
Tell me what you think :)
A few problems I can see with your code.
input = int()`
input in the name of a function that gets an input string from the user. int() simply returns 0. You are assigning the value 0 to a variable named input, making the input function no longer accessible.
for i in range(0,input):
e = int(intput())
Because input is 0, this is an empty range. The loop never runs. Which is good because it would have no idea what intput is.
Because the loop never runs, e is never defined, which is why you get the error you do.
Another style note: arr1 is a list so using a name that suggests it's an array is misleading.
You likely wanted something like the following tweaked version of your code.
n = int(input())
vals = []
for _ in range(0, n):
e = int(input())
vals.append(e)
k = min(vals)
for i in range(0, n):
arr1[i] = -= k
for i in range(0, n):
print(arr1[i])
Gathering the input numbers could be simplified using a list comprehension.
vals = [int(input()) for _ in range(0, n)]
This may be helpful for your lab:
user_int = []
while True:
user_input = int(input())
user_int.append(int(user_input))
if len(user_int) > (int(user_int[0])):
break
user_int.pop(0)
vals = min(user_int)
for user_vals in user_int:
my_vals = user_vals - vals
print(my_vals)

Use pandas to count value greater than previous value

I am trying to count the number of times a value is greater than the previous value by 2.
I have tried
df['new'] = df.ms.gt(df.ms.shift())
and other similar lines but none give me what I need.
might be less than elegant but:
df['new_ms'] = df['ms'].shift(-1)
df['new'] = np.where((df['ms'] - df['new_ms']) >= 2, 1, 0)
df['new'].sum()
Are you looking for diff? Find the difference between consecutive values and check that their difference is greater than, or equal to 2, then count rows that are True:
(df.ms.diff() >= 2).sum()
If you need to check if the difference is exactly 2, then change >= to ==:
(df.ms.diff() == 2).sum()
Since you need a specific difference, gt won't work. You could simply subtract and see if the difference is bigger than 2:
(df.ms - df.ms.shift() > 2).sum()
edit: changed to get you your answer instead of creating a new column. sum works here because it converts booleans to 1 and 0.
your question was ambiguous but as you wanted to see a program where number of times a value is greater than the previous value by 2 in pandas.here it is :
import pandas as pd
lst2 = [11, 13, 15, 35, 55, 66, 68] #list of int
dataframe = pd.DataFrame(list(lst2)) #converting into dataframe
count = 0 #we will count how many time n+1 is greater than n by 2
d = dataframe[0][0] #storing first index value to d
for i in range(len(dataframe)):
#print(dataframe[0][i])
d = d+2 #incrementing d by 2 to check if it is equal to the next index value
if(d == dataframe[0][i]):
count = count+1 #if n is less than n+1 by 2 then keep counting
d = dataframe[0][i] #update index
print("total count ",count) #printing how many times n was less than n+1 by 2

python numArray calculation impact by a print line

I wrote two set of codes
Set 1:
numArray = map(int, input('input content:').split())
print('numArray is', list(numArray))
sum_integer = 0
for number in numArray:
sum_integer += number*number
print('sum is:', sum_integer)
Set 2:
numArray = map(int, input('input content:').split())
sum_integer = 0
for number in numArray:
sum_integer += number*number
print('sum is:', sum_integer)
You can see that this is to create a set of numbers, by input, then calculate the sum of the square of each number.The difference between Set 1 and Set 2 is merely a print() line
Assume I inputed: 4 7 2 8 5 for both sets
for Set 1:
I get:
numArray is [4, 7, 2, 8, 5]
sum is: 0
for Set 2:
I get:
sum is 158
How could one print() line change the calculation logic?
map returns an iterator. By calling list on it you're consuming it, thus leaving it empty for the following code. If you want to reuse the sequence of numbers several times (e.g., for printing and then summing), you could save the list:
numArray = list(map(int, input('input content:').split()))
Your question had been well answered in #Mureinik's answer, but just if anyone is interested, you could do this in a one-line sum:
sum_integer = sum(n ** 2 for n in numArray)
You could actually do the whole code in one-line:
sum_integer = sum(int(n) ** 2 for n in input('input content:'))

How do I print out the sum of a list given certain constraints

I'm trying to print the sum of a list generated through raw_input.
The numbers in the list must be between 1 and 1000, inclusive. The length of the list must be below 1000.
here is my code thus far:
initial_list = raw_input()
integer= initial_list.split(' ')
if len(integer) <= 1000:
for i in integer:
if i >= 1 and i<=1000:
actual_integer = map( int, integer)
print sum(actual_integer)
This does not print anything. Any suggestions and/or alternatives?
If I understand your objective correctly, you've got all the right ideas, you just need to re-order your logic a little and make sure you are clear in your head about when you're dealing with a list of values and when you're dealing with a single value.
You may wish to consider your variable naming, too, as good names can help you keep track of whether the variable has a type with multiple values or single values. I've updated your code with that in mind
initial_list = raw_input().split() # split(' ') works, but you don't actually need the ' ',
# split() on its own does the same job here
if len(initial_list) <= 1000:
actual_integers = map(int, initial_list) #Moved to here. Note that
#actual_integers is a list
#so for the following comparison
#you just want to look at the max
#and min (individual values)
if min(actual_integers) >= 1 and max(actual_integers) <= 1000:
print sum(actual_integers)
else: #Just added two nice messages to the user if it doesn't print out.
print 'integers must be in range 1-1000 inclusive'
else:
print 'your list must have 1000 integers or fewer'
This code here does what you need but there is no error checking.
initial_list = raw_input() # there should be some prompt text
# no error checking
integer = initial_list.split(' ')
# no output for lists > 1000
if len(integer) <= 1000:
print sum(filter(lambda i: 0 < i <= 1000, map(int, integer)))
The output
$ python test.py
1 2 3 1500 0
6
If I understand your question correctly, this maybe what you're looking for.
This code will prompt the input and append the input to the list lst until lst will have 1000 elements. It will only take an input if the input is a number between 1 and 1000 and it will give you the sum after every input.
lst = []
while len(lst) <= 999:
initial_list = raw_input('Input numbers between 1 and 1000:')
if initial_list.isdigit() and int(initial_list) <= 1000 and int(initial_list) >= 1:
lst.append(int(initial_list))
print 'List:', lst #prints the list
total = sum(lst)
print 'List Sum:', total #prints the list sum
else:
print 'Input must be numbers between 1 and 1000'
Output:
Input numbers between 1 and 1000:12
List: [12]
List Sum: 12
Input numbers between 1 and 1000:45
List: [12, 45]
List Sum: 57
Input numbers between 1 and 1000:156
List: [12, 45, 156]
List Sum: 213
Input numbers between 1 and 1000:256
List: [12, 45, 156, 256]
List Sum: 469
Input numbers between 1 and 1000:

Categories

Resources