I have the question where i need to find the sum of elements in the given numArray for .
But i am unable to get the desired output i want.
numArray = map(int, input().split())
sum_integer = 0
#write your logic to add these 4 numbers here
print(sum_integer) # Print the sum
My solution for that is
for i in range(len(numArray):
sum_integer=sum_integer+numArray[i]
What is wrong with my solution? And i cannot change the way the input is taken.
Your problem is that map(int, input().split()) returns a map object which is an iterator, not a list. To illustrate, your code would work if you converted it to a list.
numArray = list(map(int, input().split()))
As the comments have point out, there are other, better ways to go about it. Changing the for loop to
for i in numArray:
sum_integer += i
is a better solution, and doesn't force you to enter exactly 4 numbers. The other suggestion in the comments, to simply use
print(sum(map(int, input().split())))
which does all the steps in one line is far more concise.
Related
I have just started with Python programming language. I tried to write a function which takes input either a list or multiple integers to find their product. I am trying to find the product of first million natural numbers but its displaying an MemoryError.
def product(*arg):
answer=1
if type(arg) == tuple:
arg=str(arg)
arg=arg.lstrip('[(')
arg=arg.rstrip('],)')
arg=arg.split(',')
for i in arg:
answer*=int(i)
return answer
else:
for i in arg:
answer*=int(i)
return answer
j=range(1,1000000,1)
j=list(j)
print(product(j))
Steps:
I convert the range object into list object if i am to pass a list as
argument
Now, within the function, i try to split the tuple by converting it
string.
I convert the resultant string into a list and then loop over the
elements to find the product
Q1: How to avoid the memory error as i try to find the product of first Million natural numbers?
Q2 How to improve this code?
You can use a Generator in Python.
def generate_product():
r = 1
for i in range(1,1000000):
r *= i + 1
yield r
list(generate_product())[0]
It is more memory efficient and better in terms of performance.
To calculate the product of all numbers from 1 to 1 million use a simple loop:
r = 1
for l in range(1,1000000):
r*=(i+1)
print(res)
But keep in mind that the result will be a pretty big number.
That means that your calculation might take long and the resulting number will need a lot memory.
EDIT Then i missread your question a little. This is a function that multiplies the elements in a list:
def multiply_list_elements(_list):
result = 1
for element in _list:
result*=element
return result
multiply_list_elements([1,2,3,4])
>>> 24
The memory error probably came from the huge number as #ZabirAlNazi calculated so nicely.
All of the solution is fine, but one point to make - your question is equivalent to find the factorial of 1 million.
The number of digits of n! = log10(1) + log10(2) + ... log10(n)
import math
num_dig = 1
for i in range(1,1000000):
num_dig += math.log10(i)
print(num_dig)
So, the number of digits in your answer is 5565703 (approx.).
That's only the final n, if you also want the intermediate results it will require squared memory O(m^2).
import math
ans = 1
for i in range(2,1000001):
ans *= i
print(ans)
N.B: You can approximate with logarithms and Stirling numbers with faster run-time.
A very simple solution would be:
def prod_of():
p=1
for i in range(1,1000000):
p* = i
print(p)
Array with elements sorted in descending order - l
ans=[]
for t in l:
if t<=S:
S-=t
ans.append(t)
if S==0:
break
ans, Gives us list with selected elements.
Please tell me whether it is satisfiable by all big numbers or not?
No it doesn't work for all cases:
For example: S = 17 and l = [10,5,4,3]
The answer and will be:
ans = [10,5] and
S = 2 (because it didn't get down to 0)
But it could have been solved by: ans [10,4,3]
For n=8 and omitted element=2.
This won't return the right answer.
The task is following: sum the list elements with even indexes and multiply the result by the last list's elemet.
I have this oneliner solution code in Python.
array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
print sum(i for i in array if array.index(i) % 2 == 0)*array[-1] if array != [] else 0
My result is -1476 ( The calculation is: 41*(-37-19+29+3-64+36+26+55+84-65) )
The right result is 1968.
I can't figure it out why this code is not working correctly in this particular case.
This is what you are looking for:
array[-1] * sum(array[::2])
array[::2] traverses the array from first index to last index in steps of two, i.e., every alternate number. sum(array[::2]) gets the sum of alternate numbers from the original list.
Using index will work as expected only when you are sure the list does not have duplicates, which is why your code fails to give the correct result.
There is a repeated element 84 in the list, thus array.index does not work as you expected it to be. Also, your code has a quadratic complexity which is not required.
To fix your code with a minimum amount of edit, it would look something like this:
array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
print sum(array[i] for i in range(len(array)) if i % 2 == 0)*array[-1] if array != [] else 0
>>> sum(x for i, x in enumerate(array) if not i % 2)*array[-1]
1968
Use the built-in enumerate function, since there're duplicate elements in your list, and list.index(x) returns the index of the first element equal to x (as said in the documentation). Also take a look at the documentation on enumerate.
Whenever I use permutations, I have to create a list of the permutations because it returns a 'itertools.permutations object at 0x0190A5D0'. Then after I create the list, I have to combine the strings in each list so that I have the permutation I wanted originally. If it is a number, then I have to make them all integers again.
Two part question:
1) Is there an easier way to do a permutation and create the list of numbers?
2) Below I've created a permutation of a number with 5 digits. However, where I have '12345', I want the user to input their own number. Thus the formatting string b=['s%s%s...] will have to be n %s and n x. Anyone know how to do this?
(FYI my program is trying to find the next largest number with the same digits given a user's input so 12345 next largest is 12354)
Both questions were answered below please see both responses. Thanks!!!
def nexthighest():
from itertools import permutations
numb = str(12345)
a = list(permutations(numb))
b = ['%s%s%s%s%s' % xxxxx for xxxxx in a] #<-- this is where the n length problem occurs
c = list(map(int,b))
for i in c:
if i >12345:
print(i)
break
You don't need to build all those lists. Just loop over the return value from permutations, joining and parsing as an integer each permutation as it comes by:
def nexthigher(n):
for p in permutations(sorted(str(n))):
i = int("".join(p))
if i > n:
return i
I can answer part two for you:
b = ["".join(x) for x in a]
I'm making my way through project Euler and I'm trying to write the most concise code I can. I know it's possible, so how could I simplify the following code. Preferably, I would want it to be one line and not use the int->string->int conversion.
Question: What is the sum of the digits of the number 21000?
My answer:
>>> i=0
>>> for item in [int(n) for n in str(2**1000)];i+=item
sum(int(n) for n in str(2**1000))
Not a one-liner, but a cleaner-looking generator solution, also avoiding the int->string->int conversion:
def asDigits(n):
while n:
n,d = divmod(n,10)
yield d
print sum(asDigits(2**1000))
Gives 1366.
Interestingly, the sum of the digits in 2**10000 is 13561, whose digits add up to the same value as 1366.
Of course, if expressed in binary, the sum of the digits in 2**1000 is 1. (I even did it in my head!)
Single int to str conversion to get length:
int(sum(map(lambda x:2**1000/x % 10, (10**x for x in xrange(len(str(2**1000)))))))