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:'))
Related
Question:
Without using any string methods, try to print the following:
123...n
Note that "..." represents the consecutive values in between.
Example
n=5
Prints 12345.
my solution
n = int(input())
sum=0
i=n
while i>0:
sum=sum + i*(10**{n-i})
i -= 1
print(sum)
First: {n-i} will evaluate to {-1} if n=0 since {x} is way to express a set in python
Second: you're asking for method to print numeric string, but no string operation (so all concatenation should be done in addition between two integers). Here I'm assuming that the accepted input can only be positive number
e.g.:
input 5, output=12345
input 12, output=123456789101112
When learning to solve such 'challenge' problem, it's better to do it test driven: write a simple program that just work, then compare/assert with generated expected result
this is the correct but not acceptable way to generate the output (with string operation):
inp = int(input())
expected = ""
for i in range(1, inp+1):
expected = expected + str(i)
print(expected)
Then try to solve it gradually: assume single digit input only. Here we got the idea that in order to place a number beside other number, we need to multiply first number by 10, then next number by 1. So your solution for making it multiplied by power of ten is already on correct track
now we can write:
inp = int(input())
result = 0
for i in range(1, inp+1):
power_of_ten = 10**(inp-i)
print("pot", power_of_ten)
result = result + (i*power_of_ten)
print("r", result)
print(result)
output:
5
pot 10000
r 10000
pot 1000
r 12000
pot 100
r 12300
pot 10
r 12340
pot 1
r 12345
12345
at this point, we can try to assert if our output is the same with our generated output (the one that use string operation):
inp = int(input())
result = 0
for i in range(1, inp+1):
power_of_ten = 10**(inp-i)
result = result + (i*power_of_ten)
print(result)
expected = ""
for i in range(1, inp+1):
expected = expected + str(i)
print(expected)
assert(result == int(expected))
print("assertion passed")
output:
5
12345
12345
assertion passed
but if we use two digit input, the output will no longer be correct:
12
123456790122
123456789101112
Traceback (most recent call last):
File "/tmp/c.py", line 14, in <module>
assert(result == int(expected))
AssertionError
so, if we have to output 123456789101112 when we input 12, then we need a mathematical function (not a string function) that can count the number of digit in a number:
output 2 if we input 12, 40, 99, 80 (two digit number)
output 1 if we input 1, 5, 2 (one digit number)
etc.
such function is called logarithm function: e.g.:
math.floor(math.log(i, 10)) + 1
first we try to logarithm the input to base 10, then we floor the result (so that the result is not a decimal/fractional number); then we add 1
here is the code that incorporate that: note that for simplicity, we're looping backward (e.g.: 12,11,10,9..1)
import math
inp = int(input())
result = 0
pad = 0
for i in range(inp, 0, -1):
result = result + i*10**pad
pad = pad + math.floor(math.log(i, 10)) + 1
print(result)
expected = ""
for i in range(1, inp+1):
expected = expected + str(i)
print(expected)
assert(result == int(expected))
print("assertion passed")
here I added a variable pad that will contain the number of pad to be added on next iteration, e.g.: input=5
iteration=1 i=5 pad=1 result=5 (so next number, i.e: 4, will be multiplied with 10^1)
iteration=2 i=4 pad=2 result=45 (so next number, i.e: 3, will be multiplied with 10^2)
iteration=3 i=3 pad=3 result=345
iteration=4 i=2 pad=4 result=2345
iteration=5 i=1 pad=5 result=12345
when input=12
iteration=1 i=12 pad=2 result=12
iteration=2 i=11 pad=4 result=1112
iteration=3 i=10 pad=6 result=101112
iteration=4 i=9 pad=7 result=9101112
iteration=5 i=8 pad=8 result=89101112
iteration=6 i=7 pad=9 result=789101112
iteration=7 i=6 pad=10 result=6789101112
iteration=8 i=5 pad=11 result=56789101112
iteration=9 i=4 pad=12 result=456789101112
iteration=10 i=3 pad=13 result=3456789101112
iteration=11 i=2 pad=14 result=23456789101112
iteration=12 i=1 pad=15 result=123456789101112
output:
$ python3 /tmp/a.py
5
12345
12345
assertion passed
$ python3 /tmp/a.py
12
123456789101112
123456789101112
assertion passed
so the final code is:
import math
inp = int(input())
result = 0
pad = 0
for i in range(inp, 0, -1):
result = result + i*10**pad
pad = pad + math.floor(math.log(i, 10)) + 1
print(result)
Help! I'm a Python beginner given the assignment of displaying the Collatz Sequence from a user-inputted integer, and displaying the contents in columns and rows. As you may know, the results could be 10 numbers, 30, or 100. I'm supposed to use '\t'. I've tried many variations, but at best, only get a single column. e.g.
def sequence(number):
if number % 2 == 0:
return number // 2
else:
result = number * 3 + 1
return result
n = int(input('Enter any positive integer to see Collatz Sequence:\n'))
while sequence != 1:
n = sequence(int(n))
print('%s\t' % n)
if n == 1:
print('\nThank you! The number 1 is the end of the Collatz Sequence')
break
Which yields a single vertical column, rather than the results being displayed horizontally. Ideally, I'd like to display 10 results left to right, and then go to another line. Thanks for any ideas!
Something like this maybe:
def get_collatz(n):
return [n // 2, n * 3 + 1][n % 2]
while True:
user_input = input("Enter a positive integer: ")
try:
n = int(user_input)
assert n > 1
except (ValueError, AssertionError):
continue
else:
break
sequence = [n]
while True:
last_item = sequence[-1]
if last_item == 1:
break
sequence.append(get_collatz(last_item))
print(*sequence, sep="\t")
Output:
Enter a positive integer: 12
12 6 3 10 5 16 8 4 2 1
>>>
EDIT Trying to keep it similar to your code:
I would change your sequence function to something like this:
def get_collatz(n):
if n % 2 == 0:
return n // 2
return n * 3 + 1
I called it get_collatz because I think that is more descriptive than sequence, it's still not a great name though - if you wanted to be super explicit maybe get_collatz_at_n or something.
Notice, I took the else branch out entirely, since it's not required. If n % 2 == 0, then we return from the function, so either you return in the body of the if or you return one line below - no else necessary.
For the rest, maybe:
last_number = int(input("Enter a positive integer: "))
while last_number != 1:
print(last_number, end="\t")
last_number = get_collatz(last_number)
In Python, print has an optional keyword parameter named end, which by default is \n. It signifies which character should be printed at the very end of a print-statement. By simply changing it to \t, you can print all elements of the sequence on one line, separated by tabs (since each number in the sequence invokes a separate print-statement).
With this approach, however, you'll have to make sure to print the trailing 1 after the while loop has ended, since the loop will terminate as soon as last_number becomes 1, which means the loop won't have a chance to print it.
Another way of printing the sequence (with separating tabs), would be to store the sequence in a list, and then use str.join to create a string out of the list, where each element is separated by some string or character. Of course this requires that all elements in the list are strings to begin with - in this case I'm using map to convert the integers to strings:
result = "\t".join(map(str, [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]))
print(result)
Output:
12 6 3 10 5 16 8 4 2 1
>>>
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)
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
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: