Python map vs List comprehension Time Complexity - python-3.x

a = [1,2,3,4,5]
All the integers in this array can be converted into strings individually in the following 3 ways.
1) Using Str
a=[1,2,3,4,5]
for i in range(len(a)):
a[i] = str(a[i])
print(type(a[0]))
2) Using Map
a=[1,2,3,4,5]
a = list(map(str,a))
print(type(a[0]))
3) Using List Comprehension
a=[1,2,3,4,5]
a = [str(i) for i in a]
print(type(a[0]))
Can I know what is the time complexity in all the 3 cases to find out which method is efficient? I am a bit confused about this.
Thanks in advance!

Related

Appending Elements From Left/Start of List/Array

I came across appending elements to array from left. and it has two solution
Solution 1:
List = [2,3,4,5,6]
List.insert(0,1) # Using insert
List = [1,2,3,4,5,6]
Solution 2:
List = [2,3,4,5,6]
[1] + List # Concatenation of array
List = [1,2,3,4,5,6]
I'm new to Python So please can any one explain the time complexity of both solution according to me both solution takes O(n) am I right or wrong?

I don't know why the correct answer isn't coming up

I'm novice programmer.
I want the smallest of the input values ​​to be output, but I don't know what's wrong.
Input example :
10
10 4 2 3 6 6 7 9 8 5
Output example :
2
n = int(input())
a = input().split()
min=a[0]
for i in range(n) :
if a[i] < min :
min = a[i]
print(min)
what is the problem? please help me
Your code should work (and it does for me).
Nevertheless, min is a reserved Python word. Taking that into consideration, I also recommend the following changes for it to be more idiomatic:
a = input().split()
min_num = a[0]
for element in a:
if element < min :
min = element
print(min)
Variables can be either number or strings. For example "2" is different from 2.
The function split returns an array of strings. You would need to convert each to a number if you want to do number comparison, like:
n = int(input())
a = input().split()
min=int(a[0])
for i in range(n) :
if int(a[i]) < min :
min = int(a[i])
print(min)
Note: you already did that for n (first line in original code), but you did not do the same when you access a.
So, min is actually a python built-in, which would be very useful in this scenario. Also, you are not making the input values in a into integers, so we can do that too:
n = int(input())
a = list(map(int, input().split()))
print(min(a))
We use map to turn all the values from the split list into integers, then turn the map object back into a list. Then, using min, we can find the smallest number very easily, without a for loop.
I think you should convert each element to integers before comparing them.
a = [int(i) for i in input().split()]
Your code should work, but it will compare strings against strings instead of integers against integers.

Can we change for loop result into list with index?

I am currently learning python, I just have one little question over here.
I used for loop and getting a result below.
Here is my code:
def psuedo_random(multiplier, modulus, X_0, x_try):
for i in range(x_try):
place_holder = []
count = []
next_x = multiplier * X_0 % modulus
place_holder.append(next_x)
X_0 = next_x
for j in place_holder:
j = j/modulus
count.append(j)
print(count)
Result:
[0.22021484375]
[0.75439453125]
[0.54443359375]
[0.47705078125]
Can we somehow change it into something like this?
[0.22021484375, 0.75439453125, 0.54443359375, 0.47705078125]
After you initialized a list, you can use append function in the loop.
initialize a list where you want to list these numbers
mylist = []
use this function in your for loop
for i in .....:
mylist.append(i)
It's simple. Do not initialize your list inside the loop. Just place it outside.

Python 3 list comprehension in list of lists to convert types

Consider the following list of lists:
list1 = [['1.1', '1.2', '1.3'], ['2.1', '2.2', '2.3'], ...]
To comprehend a list of strings to convert them to floats one could use
list1[0] = [float(i) for i in list1[0]]
But my attempt to comprehend a list of lists of floats didn't quite work:
list1 = [[float(j) for j in list1[i]] for i in list1]
due to
TypeError: list indices must be integers or slices, not list
Is there a way to do this sort of list comprehension without using loops explicitly?
[[float(j) for j in i] for i in list1]
shall do it

Non-recursive Most Efficient Big-O Permutation Alghoritm Python3 (non-built-in)

Hi Guys For my Data Structure assignment I have to find the most efficient way (big-o wise) to calculate permutations of a list of objects.
I found recursive examples on the web but this doesn't seem to be the most efficient way; I tried my own code but then I realized that when I count the number of possible permutations I'm actually making my algorithm O(!n). Any suggestions? .-.
from random import sample
import time
start = time.time()
testList = list(x for x in range(7))
print('list lenght: %i objects' % len(testList))
nOfPerms = 1
for i in range(1,len(testList)+1):
nOfPerms *= i
print('number of permutations:', nOfPerms)
listOfPerms = []
n = 1
while n <= nOfPerms:
perm = tuple(sample(testList, len(testList)))
listOfPerms.append(perm)
permutations = set(listOfPerms)
if len(permutations) == len(listOfPerms):
n += 1
else:
del(listOfPerms[-1])
end = time.time() - start
print('time elapsed:', end)
OUTPUT:
list lenght: 7 objects
number of permutations: 5040
time elapsed: 13.142292976379395
If instead of 7 I put 8 or 9, or 10, those are the number of permutations (I won't show the time cause it's taking too long):
list lenght: 8 objects
number of permutations: 40320
list lenght: 9 objects
number of permutations: 362880
list lenght: 10 objects
number of permutations: 3628800
I believe this will be the best you can do. Generating the number of permutations of a list generates n! permutations. As you need to generate them all this is also how much time it will take (O(n!)). What you could try to do is to make it a python generator function so you will always only generate exactly as many as you need instead of precalculating them all and storing them in memory. If you want an example of this i could give you one.
Im sorry this might be a quite negative answer. It's a good question but im pretty sure this is about the best that you can do, asymptotically. You could optimize the code itself a bit to use less instructions but in the end that wont help too much.
Edit:
This is a python implementation of Heap's algorithm which i promised
(https://en.wikipedia.org/wiki/Heap%27s_algorithm) generating N! permutations where the generation of every one permutation takes amortized O(1) time and which uses O(n) space complexity (by alteri
def permute(lst, k=None):
if k == None:
k = len(lst)
if k == 1:
yield lst
else:
yield from permute(lst, k-1)
for i in range(k-1):
if i % 2 == 0:
#even
lst[i], lst[k-1] = lst[k-1], lst[i]
else:
#odd
lst[0], lst[k-1] = lst[k-1], lst[0]
yield from permute(lst, k-1)
for i in permute([1, 2, 3, 4]):
print(i)

Resources