Infinite Series in Python [duplicate] - python

This question already has answers here:
Is there an expression for an infinite iterator?
(7 answers)
Closed 4 years ago.
Is there any function in Python that provides an infinite series similar to generateSequence in Kotlin?
In Kotlin I can do something like:
generateSequence(1) { it + 1 }.take(5).forEach { println(it) }
Obviously this stops with an integer overflow error but I would like to do something similar in Python.

you can write a simple generator
def count(x):
while True:
yield x
x += 1
for i in count(5):
print(i)
of coarse this particular generator is builtin with itertools.count
import itertools
for i in itertools.count(5):
print(i)

Use itertools.count() to get a count object that generates an infinite sequence of values.
You can take the first n items by explicitly retrieving the next item from the count object for the required number of times. Alternatively, and preferably, use itertools.islice() to take the first n items.
Mirroring your example, to take the first 5 values of the sequence using explicit iteration:
from itertools import count
c = count(1) # start from 1 instead of 0
for i in range(5):
print(next(c))
Or using islice():
for n in islice(count(1), 5):
print(n)

Related

Python function which takes two arrays of integers and returns the number of integers that occur in both arrays [duplicate]

This question already has answers here:
Count duplicates between 2 lists
(5 answers)
Closed 2 years ago.
For example, if it takes the arrays [1,44,5,8,35] and [35,12,44,7,42,31] it will return 2,
because exactly two integers (44 and 35) occur in both the arrays.
The code should be library free
I have tried the following code:
A = [1,44,5,8,35]
B = [35,12,44,7,42,31]
def occurInBoth(A, B):
for i in range(len(A)):
for j in range(len(B)):
if A[i] == B[j]:
newA = [A[i]]
print(newA)
occurInBoth(A, B)
The result I get is:
[44]
[35]
And I'd like to get 2 as a result
Just editing this question because due to the nature of this module I cannot use libraries, import anything, use intersection etc. I have researched how to do this but I can only get answers that I cannot use for this task. Sorry if this has been asked before but haven't found anything for this specific task
You have the right idea with your for loops. What you want to do is create an accumulator value, and add 1 to it every time you find a match:
def occurInBoth(A, B):
total = 0
for i in range(len(A)):
for j in range(len(B)):
if A[i] == B[j]:
total += 1
return total
If both lists only contain unique numbers (no duplicates within their own lists), the below code is the simplest solution. We just need to compare the length of A+B combined lists with the length of the same integers put into a set (which removes all duplicates).
def occurInBoth(a, b):
return len(a+b) - len(set(a+b))
The easiest way to do this is:
def function_array_intersect(arr1,arr2):
return list(set(arr1).intersection(set(arr2)))
>>> function_array_intersect([1,2,3],[3,4,5])
Ans: [3]
Edit: to get the len, just add a len(list(set(arr1).intersection(set(arr2)))) in the return statement.

What is Python equivalent of for(i=1;i<10000000;i=1*10)? [duplicate]

This question already has answers here:
How to generate exponentially increasing range in Python
(9 answers)
Closed 3 years ago.
In python how can we create a for-loop that does not have a constant step-size? I want to create a for-loop with step-function i=i*10, How can I do that?
For example: I want to create a python equivalent for: for(i=1;i<10000000;i=i*10){...}
How do I do this in python2 and python3?
I know that I can just use while-loop But I want to know if there is a way using for-loop?
this is a variant:
from math import log
for i in (10 ** e for e in range(round(log(10000000, 10)))):
print(i)
One option would be to use a while loop:
i = 1
while i < 10000000:
print(i)
# the rest of your logic
i = i*10
Trivially, a C for loop is a syntactic sugar, where
for (init; cond; step)
body
is equivalent to
init;
while (cond) {
body;
step;
}
which is, again trivially, translatable into Python:
i = 1
while i < 10000000:
do_stuff(i)
i *= 10
On the other hand, Python's for loop consumes an iterator. I can't think of an off-the-shelf iterator you could use, but if you create an iterator that has the property you desire, you can do so.
def geometric_range(start, end, step):
i = start
while i < end:
yield i
i *= step
for i in geometric_range(1, 10000000, 10):
do_stuff(i)

Python Running Sum in List [duplicate]

This question already has answers here:
How to find the cumulative sum of numbers in a list?
(25 answers)
Closed 6 years ago.
Given the following list:
a=[1,2,3]
I'd like to generate a new list where each number is the sum of it and the values before it, like this:
result = [1,3,6]
Logic:
1 has no preceding value, so it stays the same.
3 is from the first value (1) added to the value of the second number in the list (2)
6 is from the sum of 1 and 2 from the first two elements, plus the third value of 3.
Thanks in advance!
Python 3 has itertools.accumulate for exactly this purpose:
>>> from itertools import accumulate
>>> a=[1,2,3]
>>> list(accumulate(a))
[1, 3, 6]
If you'd like a numpy solution
from numpy import cumsum
result = list(cumsum(a))
How about an ordinary loop?
a = [1,2,3]
result = []
s = 0
for item in a:
s += item
result.append(s)
print(result)
Python has a function for this.
import itertools
result = list(itertools.accumlate([1, 2, 3]))
Python itertools solve some problems really well you should take some time and read over them.
https://docs.python.org/3/library/itertools.html
try this..
def running_sum(a):
tot = 0
for item in a:
tot += item
yield tot
a = [1,2,3,4]
print list(running_sum(a))
Avinash Raj's code doesn't work correctly.
a = [1,2,3]
b = [sum(a[:(i+1)]) for i, j in enumerate(a)]
print(b)
Edited based on #Avinash Raj
There are about a hundred different ways to do this kind of cumulative sum. Depending on what you actually want to use the result for, a less obvious or less general-purpose solution might be more time- or memory-efficient—although the simple solution below is O(1) in terms of memory and O(N) in time.
The most straightforward procedural approach in virtually every imperative programming language goes something like this:
csum=0
result=[]
for val in a:
csum += val
result.append(csum)
The Python standard library also includes a function to do just this: itertools.accumulate.
import itertools
result = list(itertools.accumulate(a))

Why doesn't filter method return a list? [duplicate]

This question already has answers here:
How to use filter, map, and reduce in Python 3
(7 answers)
Closed 5 years ago.
I am learning the concept of filters in Python. I am running a simple code like this.
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
But instead of getting a list, I am getting some message like this.
<filter object at 0x00FDC550>
What does this mean? Does it means that my filtered object i.e list to come out is stored at that memory location? How do I get the list which I need?
It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,
filter(func,data) #python 2.x
is equivalent to:
list(filter(func,data)) #python 3.x
I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.
If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:
( x for x in data if func(x) )
As opposed to:
[ x for x in data if func(x) ]
in python 2.x
It's an iterator returned by the filter function.
If you want a list, just do
list(filter(f, range(2, 25)))
Nonetheless, you can just iterate over this object with a for loop.
for e in filter(f, range(2, 25)):
do_stuff(e)

Repeat length of list on Python? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
find the maximum number in a list using a loop
I'm finding the maximum number in a list on Python by using a loop. In order to do that, I need to have a loop where it goes through the entire list. What loop can I use that runs through the entire list? I'm new to Python.
You can go through a list with a for loop like:
for item in lst:
# do something with item
However, an easier way to get the maximum item in a list (which appears to be what you want) is:
max(lst)
Repeating a block of code n times, where n is the length of some_list is done like this:
for i in xrange(len(some_list)):
# block of code
or...
i = 0
while i < len(some_list):
# block of code
i = i + 1
max = None
for e in lst:
if max is None or e > max: max = e
But as David already stated, simply calling max(lst) would do the job.

Categories

Resources