You all have seen how to write loops in python. Now is the time to implement what you have learned.
Given an array A of N numbers, you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].
Input Format:
The first line of the input contains a number N representing the number of elements in array A.
The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)
Output Format:
Print the resultant array elements separated by a space. (no space after the last element)
Example:
Input:
4
2 5 3 1
Output:
3883
Explanation:
Here array A is [2,5,3,1] os reverse of this array is [1,3,5,2] and hence the resultant array is [3,8,8,3]
My solution is not working.
my solution is:
r=input()
r=int(r)
result_t = []
d=[]
for i in range(0, r):
c=input()
c=int(c)
t = i
result_t.append(c)
d=reversed(result_t)
d=int(d)
s=result_t+d
for i in range(0, r):
print(s[i])
You just need to loop over both result_t and d. You can use zip() to combine two lists so you can loop over them in parallel:
r=input()
r=int(r)
result_t = []
for i in range(r):
c=input()
c=int(c)
result_t.append(c)
d = reversed(result_t)
result = [x + y for x, y in zip(result_t, d)]
print(result.join(" "))
You can also do it without making the reversed list.
result = [x + result_t[-(i+1)] for i, x in enumerate(result_t)]
When you use a negative index in a list, it counts from the end. You have to add 1 before negating, because the last element is -1 (since -0 is the same as 0, which is the first element).
"can only concatenate list (not "list_reverseiterator") to list"
reversed(result_t) returns not the list but iterator
try:
rev = []
for i in reversed(result_t):
rev.append(i)
print(rev)
Try This One:
x = input()
result_t = [int(x) for x in input().split()]
rev = [x for x in reversed(result_t)]
result = [int(x) + int(y) for x, y in zip(result_t, rev)]
for i in result:
print(i,end=" ")
Here array A is [2,5,3,1] and reverse of this array is [1,3,5,2] and hence the resultant array is [3,8,8,3].
a = []
n = int(input("Enter the number of elements"))
for i in range(n):
x = int(input("Enter the elements"))
a.append(x)
print(a)
res = []
b = [None] * len(a)
for i in range(0, len(a)):
b[i] = a[i]
b.reverse()
print(b)
for i in range(0, len(a)):
res.append(a[i] + b[i])
print(res)
Related
I want to make a new list from the existing list such that each element in the new list is the product of all the numbers in the existing list except the element in the same position of a new list element.
For example [2,4,5] --> [20,10,8]
I came up with a solution wherein one for-loop, j traverses to the right side of the i-th (current) element while in other for loop, k covers the left side of the elements - Multiplies and gives the result.
def mulList():
oldList = [2,4,5]
newList = []
for i in range(len(oldList)):
a = 1
for j in range(i+1,len(oldList)):
a *= oldList[j]
for j in range(i-1,-1,-1):
a *= oldList[j]
newList.append(a)
print(newList)
mulList()
Later I got to know that we can solve it with two for-loops like this where I am not doing anything if i equals j
def mulList():
oldList = [2,4,5]
newList = []
for i in range(len(oldList)):
a = 1
for j in range(len(oldList)):
if j == i:
a += 0
else:
a *= oldList[j]
newList.append(a)
print(newList)
mulList()
I was wondering whether there is any better way to solve it with only one for loop.
You can just multiply everything together once, and then loop through the elements again and divide the total product with the current element:
def mulList():
oldList = [2,4,5]
newList = []
total = 1
for x in oldList:
total *= x # total = total * x
for x in oldList:
# Use // to get int (4) instead of float (4.0)
newList.append(total // x)
print(newList)
You can take the product of all elements in the list via functools.reduce, and then divide each element in the list with the product using integer division //
from functools import reduce
from operator import mul
li = [2,4,5]
#Take product of all elements via reduce operation on the list
mult = reduce(mul, li)
#40
#Divide the product found in the step above by each item via integer division
res = [mult//item for item in li]
print(res)
You can also multiply elements in a for loop if you don't want to use functools.reduce
#Or loop over the element to multiply
mult = 1
for item in li:
mult *= item
The output will be
[20, 10, 8]
I saw this question in leetcode I think and there was a constraint to not use division and still do this algorithm in O(n). Basically I traverse the array two times once in forward direction and once in reverse and the multipies corresponding elements in the third iteration to get the output you see.
oldlist = [2,4,5]
forwardlist=[1]*len(oldlist)
backwardlist=[1]*len(oldlist)
mul = oldlist[0]
for i in range(1,len(oldlist)):
forwardlist[i] = mul
mul*= oldlist[i]
mul = oldlist[len(oldlist) - 1]
for i in range(len(oldlist) - 2, -1, -1):
backwardlist[i] = mul
mul*= oldlist[i]
newlist = []
for i in range(len(oldlist)):
newlist.append(forwardlist[i]*backwardlist[i])
print(newlist)
OUTPUT
[20, 10, 8]
Hope that was helpful. :)
How about just this
c = 1
for i in oldList:
c *= i
newList = [c//e for e in oldList]
Now your function will be
def mulList():
oldList = [2,4,5]
c = 1
for i in oldList:
c *= i
newList = [c//e for e in oldList]
print(newList)
Given an array A of N numbers, you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].
Input Format:
The first line of the input contains a number N representing the number of elements in array A.
The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)
Output Format:
Print the resultant array elements separated by a space. (no space after the last element)
Example:
Input:
4
2 5 3 1
Output:
3883
take input
parse input to a list
reverse the list and put a new list
using zip function and + operation create the final list
Parse the final list to get rid of ',' and '[]'
L = raw_input()
L = map(int, L.split())
R = L[::-1]
S = [x + y for x, y in zip(L, R)]
print ' '.join(map(str, S))
n = int(input())
list1 = list(map(int, input().strip().split()))[:n]
list2 = list1[::-1]
sum_list = []
for (item1, item2) in zip(list1, list2):
sum_list.append(item1+item2)
print(*sum_list, sep=' ')
you just reverse the list using slicing method and use it with zip in a for loop like this.
arr = [1,2,3]
result = []
for i, j in zip(arr, arr[::-1]):
print (i, j)
result.append(i+j)
print(result)
import math
size = int(input())
list1 = []
for x in input().split():
num = int(x)
list1 = list1 + [num]
for i in range(math.ceil(size/2)):
list1[i] = list1[size -1 -i] = list1[i] + list1[size -1 -i]
for i in range(size-1):
print(list1[i], end=" ")
print(list1[size-1], end="")
Clear the console
Asks for user input as a list
Prints the List and the Reversed List
Initialize the sumList
Use python ZIP function to iterate through the list and the reversed list, and adding their sum.
Please note: The entered values were treated as strings hence the conversion to int.
import os
os.system('clear')
numList = input("Enter an array/list separated by space : ").split(" ")
print (numList)
print (numList[::-1])
sumList = list()
sumList = [int(x)+int(y) for x,y in zip(numList, numList[::-1])]
print(sumList)
print("\n")
N=int(input())
A=list(map(int,input().split()))
s=[]
for i in range(N):
s.append(A[i]+A[N-i-1])
print (*s,end="")
This question already has answers here:
How to sum columns of an array in Python
(13 answers)
Closed 4 years ago.
I have lists that contain only integers like [1,2,3] and [4,5,6]. Some times I even have [7,8,9] or more lists. How do I add each elements together to form a new list of the same length?
[1,2,3] + [4,5,6] + [7,8,9] = [12,15,18]
I know that the above would just append the elements and create a longer list (with 9 elements), but instead I would like to add the lists element-wise.
You can put the lists in a list, zip the sub-lists after unpacking them with the * operator, and map the sum to a list:
l = [[1,2,3], [4,5,6], [7,8,9]]
print(list(map(sum, zip(*l))))
This outputs:
[12, 15, 18]
Edit: The above is for Python 3.x. If you're using an earlier version, you can use itertools.izip instead of zip, and you would not need to call the list constructor:
import itertools
l = [[1,2,3], [4,5,6], [7,8,9]]
print map(sum, itertools.izip(*l))
Numpy is well suited for this task, although it might be slight overkill for your case.
Let's say you have
x = [1,2,3]
y = [4,5,6]
z = [7,8,9]
You can turn them into an array and sum across them:
np.array([x, y, z]).sum(axis=0)
You could use a similar approach with regular lists and zip:
[sum(col) for col in zip(x, y, z)]
You can do it like this:
#Create the list
x = [1,2,3,12,13]
y = [4,5,7,11]
z = [7,8,9,14,15,16]
#create a list with the list length
lenList = [len(x),len(y),len(z)]
finalList = []
#get the minimum and maximum list length
minLen = min(lenList)
maxLen = max(lenList)
#if the three list have the same length then you can simply sum the element
if(maxLen == minLen):
for j in range(maxLen):
finalList.append(x[j]+y[j]+z[j])
else:
#if the list have different length look for the minimum value
while(lenList[0] != lenList[1] or lenList[0] != lenList[2]):
minLen = min(lenList)
maxLen = max(lenList)
#if the min len is the x list then add some zero
if(lenList.index(minLen) == 0):
#change the len to the max len
lenList[0] = maxLen
for a in range(minLen,maxLen):
x.append(0)
#if the min len is the y list then add some zero
elif(lenList.index(minLen) == 1):
lenList[1] = maxLen
for b in range(minLen,maxLen):
y.append(0)
#if the min len is the z list then add some zero
elif(lenList.index(minLen) == 2):
lenList[2] = maxLen
for c in range(minLen,maxLen):
z.append(0)
#sum all the element
for j in range(0,maxLen):
finalList.append(x[j]+y[j]+z[j])
print finalList
output:
[12, 15, 19, 37, 28, 16]
Comments:
This program can sum all the list element and insert the result in another list. You can sum 3 list, with infinite element and without having the same list length. If you need to sum more list just edit this part:
while(lenList[0] != lenList[1] or lenList[0] != lenList[2]):
minLen = min(lenList)
maxLen = max(lenList)
#if the min len is the x list then add some zero
if(lenList.index(minLen) == 0):
#change the len to the max len
lenList[0] = maxLen
for a in range(minLen,maxLen):
x.append(0)
#if the min len is the y list then add some zero
elif(lenList.index(minLen) == 1):
lenList[1] = maxLen
for b in range(minLen,maxLen):
y.append(0)
#if the min len is the z list then add some zero
elif(lenList.index(minLen) == 2):
lenList[2] = maxLen
for c in range(minLen,maxLen):
z.append(0)
Here you can add:
elif(lenList.index(minLen) == 3):
lenList[3] = maxLen
for c in range(minLen,maxLen):
listN.append(0)
After that you have to add the list:
#Create the list
x = [1,2,3,12,13]
y = [4,5,7,11]
z = [7,8,9,14,15,16]
listN = [0,0,0]
#create a list with the list length
lenList = [len(x),len(y),len(z),len(listN)]
And in the sum iteration you have to change:
#sum all the element
for j in range(0,maxLen):
finalList.append(x[j]+y[j]+z[j],listN[j])
an alternative method if you know the length of the sub lists are 3
a = [1,2,3] + [4,5,6] + [7,8,9]
[sum([a[3*q+i] for q in range(len(a)//3)]) for i in range(len(a)//3)]
output
[12,15,18]
alternatively
dicta = {q:i for q,i in enumerate(a)}
[sum([dicta[3*q+i] for q in range(len(a)//3)]) for i in range(len(a)//3)]
you can just swap the 3's out with what ever length you use, but since you showed in your code that they where already laid to gether, i wouldn't be able to read it automaticly. What goes for the alternative solution, then dictionaries uses hashes so if your list gets big it won't be a problem.
I am trying to input and then print a matrix in Python without a library.
Code:
a = []
n = int(input('Length of the row'))
m = int(input('Length of the column'))
for j in range(0, m):
a[j].append([])
for i in range(0, n):
for j in range(0, m):
a[i][j] = int(input())
for i in range(0, n):
print()
for j in range(0, m):
print(a[i][j], end=" ")
Working:
When I put my list to be let's say:
a = [[1,1,1],[1,1,1],[1,1,1]]
And put both m and n to be 3, It works exactly as it should.
Error:
But having only an empty list, as in the code example, I always get an error that list index is out of range.
a[j].append([]) IndexError: list index out of range
Problem:
I don't know how to input nested lists inside a list, and integers inside those nested lists, with a loop, or with anything for that matter.
It is bound to fail:
a = []
# ...
for j in range(0, m):
a[j].append([]) # a is empty, so a[j] must fail!
Try instead:
a = []
n = int(input('Length of the row'))
m = int(input('Length of the column'))
for i in range(m): # m is len of outer list: number of rows == len of column
a.append([])
for j in range(n): # n is len of inner list (those are the rows)
a[i].append(int(input()))
# append as well, as indexes to fill do not exist yet
# the loop could be written as a comprehension:
a = [[int(input()) for _ in range(n)] for _ in range(m)]
for i in range(m):
print()
for j in range(n):
print(a[i][j], end=" ")
Remove the first loop and then make the input loop look something like this:
a = [None] * n
for i in range(n):
a[i] = []
for j in range(m):
a[i].append(int(input()))
append will add elements to a list. a is empty at firsts so a[i] is an error. See my sample that does what you want.
a = []
n = int(input('Enter row count: '))
m = int(input('Enter column count: '))
for i in range(0, n):
a.append([])
for i in range(0, n):
for j in range(0, m):
a[i].append(int(input()))
for i in range(0, n):
print()
for j in range(0, m):
print(a[i][j], end=" ")
print()
Sample run:
Enter row count: 2
Enter column count: 3
1
2
3
4
5
6
1 2 3
4 5 6
When you create a it is empty so you cannot not index anything in it.
>>> a = []
>>> len(a)
0
>>> a[0]
Traceback (most recent call last):
File "<pyshell#126>", line 1, in <module>
a[0]
IndexError: list index out of range
>>>
Just append the empty lists:
>>> a.append([])
>>> a
[[]]
>>> len(a)
1
>>> a[0]
[]
>>>
You have a similar problem when adding to the inner loops. It could be done like this
>>> i = 0
>>> a[i].append(int(input()))
4
>>> a
[[4]]
>>>
You have two mistakes:
You are not being consistent on what are rows and what columns
You are addressing an array/list content that hasn't been allocated any memory
Furthermore, you don't need that third for loop.
n=2
m=3
a=[]
for i in range(0, n):
a.append([])
for j in range(0, m):
a[i].append( int(input()) )
print(a)
which, for input 1-6, gives you
1
2
3
4
5
6
[[1, 2, 3], [4, 5, 6]]
I have a problem I can't seem to figure out. I am very new to Python and have only been coding for three weeks. Any help is appreciated.
Problem:
We are passing in 3 inputs:
a list of numbers
a multiplier value, M
a value, N
You should multiply every Nth element (do not multiply the 0th element) by M. So if N is 3, you start with the 3rd element, which is index 2.
If there are less than N elements then you should output the unchanged input list.
I can't seem to figure this out. I have tried many different things here. Currently, I have the following, which is not working at all.
Provided:
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
My Code:
for N in numbers:
if numbers[i] > 0:
total = N * M
print(total)
else:
print(numbers)
Output:
I am not even close to what the output should be. Feeling lost on this. Here is what my code comes to. It looks like they want the output in a list.
Program Failed for Input: 1,2,3,4,5,6 5 3
Expected Output: [1, 2, 15, 4, 5, 30]
Your Program Output:
5
10
15
20
25
30
You could try a list comprehension with slicing.
numbers[N-1::N] = [x * M for x in numbers[N-1::N]]
A more elegant solution using list comprehensions ;)
[item*M if (index and not (index+1)%N) else item for index, item in enumerate(items)]
This solution is based on your original one. A more pythonic one would use for instance, a list comprehension so keep that in mind in the future,
output = [numbers[0]]
if len(numbers) >= N:
for i in range(1,len(numbers)):
if ((i+1)%N) is 0:
output.append(numbers[i]*M)
else:
output.append(numbers[i]);
else:
output = numbers
If N is not larger than the list size, the program constructs a new list of numbers with each Nth number being multiplied by M. This is done with a simple modulo operator. Indexing in Python starts with zero and i iterates through index values but your desired output counts the elements as if starting from 1 - thus i+1 in the modulo. If it is not every Nth - program just append the old value. If the list is shorter than N altogether, it assigns the whole unchanged list to the output list.
will this work for you?
res = []
for num in numbers:
if num > 0:
total = num * M
res.append(total)
if len(res) != len(numbers):
print (numbers)
else:
res.reverse()
print (res)
So after many attempts and bouncing this off of a friend who works as a programmer, I ended up with this that gave me the proper output:
newlist = []
if len(numbers) < N:
newlist = numbers
else:
for i in range(0, len(numbers)):
num = numbers[i]
if (i+1) % N == 0:
newlist.append(num*M)
else:
newlist.append(num)
i+=1
print(newlist)
# Input
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
# convert strings to integers
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
# if the length of our list is greater than our supplied value
# loop to multiply(starting at the 3rd position in the list) by M
if len(numbers) > N :
for num in range(2, len(numbers), 3) :
numbers[num] = numbers[num] * M
print(numbers)