input during for-loop in comprension - python

data=[]
for i in range(int(input())):
name=input()
point=float(input())
data.append([name,point])
how i can convert this code to comprehension or is there any other way to reduce runtime.
for comprehension i tried this code below:
data=[[input() float(input())] for i in range(int(input()))]
i dont know is there any special ways to do list opearations and inputs during for-loop in comprensions.
As i know for statements, they should be mentioned after loop but operations for list before loop. But for my version it gives syntax error.

how i can convert this code to comprehension or is there any other way to reduce runtime.
Do the items of your outer list need to be more lists? Why not make a list of tuples? Anyways your code gave you a syntax error because you forgot to include a comma.
data = [(input(), float(input())) for i in range(int(input()))]
I'm also not sure why you are trying to find speed improvements on code that takes user input. No human is every going to provide input fast enough to notice any performance increase from one solution to another. Do you have another program providing input automatically through stdin or something?

Related

str.split() in the for-loop instantiation, does it cause slower execution?

I'm a sucker for reducing code to its bare minimum and love keeping it short and slim, but occasionally I get into the dilemma of whether I'm doing more harm than good. Below is an example of a situation I frequently encounter and where I start pondering if I am minifying at the expense of speed.
str = "my name is john"
##Alternative 1
for el in str.split(" "):
print(el)
##Alternative 2
splittedStr = str.split(" ")
for el in splittedStr:
print(el)
What is faster? I'd assume it's the second one because we don't split the string after every iteration (not even sure we do that)?
str.split(" ") does the exact same thing in both cases. It creates an anonymous list of the split strings. In the second case you have the minor overhead of assigning it to a variable and then fetching the value of the variable. Its wasted time if you don't need to keep the object for other reasons. But this is a trivial amount of time compared to other object referencing taking place in the same loop. Alternative 2 also leaves the data in memory which is another small performance issue.
The real reason Alternative 1 is better than 2, IMHO, is that it doesn't leave the hint that splittedStr is going to be needed later.
Look my friend, if you want to actually reduce the amount of time in the code in general,loop on a tuple instead of list but assigning the result in a variable then using the variable is not the best approach is you just reserved a memory location just to store the value but sometimes you can do that just for the sake of having a clean code like if you have more than one operation in one line like
min(str.split(mylist)[3:10])
In this case, it is better to have a variable called min_value for example just to make things cleaner.
returning back to the performance issue, you could actually notice the difference in performance if you loop through a list or a tuple like
This is looping through a tuple
for i in (1,2,3):
print(i)
& This is looping through a list
for i in [1,2,3]:
print(i)
you will find that using tuple will be faster !

Could someone explain how this piece of Python code works? (sorted list with lambda function)

I was trying to sort a list of lists on the second item in each of the lists in my "unsorted list", and found this piece of code. It works, but even though I have read about lambda function I'm having some problems wrapping my head around how it works. Could someone explain how it works, and maybe give me some input if this is a good way of sorting a list of lists or if i should use a different approach. In advance, thanks!
sorted_list = sorted(unsorted_list,key=lambda l:l[1])
I don't recognize the language, but it seems that the code is sorting an array of arrays, using the element at index 1 as the sorting key.

Using list elements as variable names in Python

I'm guessing this will be a really simple problem but I have no solution yet.
I have a long code that does modelling and updates values of variables for optimisation. The code is initially written like this:
init_old(x,y):
return {(k):olddict[k][x][0]*prod[y] for k in realnames}
Q_house=init_old(“Q_house”,"P_house")
Q_car=init_old(“Q_car”,"P_car")
Q_holiday=init_old(“Q_holiday”,"P_holiday")
I already can simplify it a bit with a comprehension:
ListOfExpenses=["house","car","holiday"]
Q_house, Q_car, Q_holiday=[init_old(“Q_”+i,"P0_"+i) for i in ListOfExpenses]
I am trying to find an equivalent but more flexible way of writing that final line, so that I change the list of Expenses and the "Q_..." variables together easily:
ListOfExpenses=["house","car","holiday"]
ListOfCost=["Q_house","Q_car","Q_holiday"]
Elements_Of_ListOfCost=[init_old(“Q_”+i,"P0_"+i) for i in ListOfExpenses]
So when I look for Q_house, Q_car or Q_holiday later, it returns the same Q_house=init_old(“Q_house”,"P_house") calculated in the original code.
I don't want to use dictionaries for now as they would require major change to the rest of the code and calling dictionaries causes problems in some of the other functions. Thanks in advance for the help.

How to use list comprehension on this for loop in python

I've just learned of list comprehension but I can't quite get it to work in the right context.
my for loop is:
results and instances are lists
for i in results:
instances.remove(i)
results.remove(i)
I tried [i for i in one if one.count(i)<2 if two.count(i)<2] but it doesn't work. I can get it to work on just one of them with this, [i for i in one if one.count(i)<2], but I wanted to incorporate both of them into the same loop. Can someone show me the easiest way to go about this?
Assuming results is a list. You seem to be trying to do this
for i in results:
instances.remove(i)
del results[:]
list comprehension is the wrong thing to use here. You're not trying to create a new list from a sequence.
This loops is similar, but will remove the instances in the reverse order
while results:
instances.remove(results.pop())
You need to first take the results out of the for loop. Set it after it and then delete it once the for loop has finished.

Improving Python Snippet Performance

This statement is running quite slowly, and I have run out of ideas to optimize it. Could someone help me out?
[dict(zip(small_list1, small_list2)) for small_list2 in really_huge_list_of_list]
The small_lists contain only about 6 elements.
A really_huge_list_of_list of size 209,510 took approximately 16.5 seconds to finish executing.
Thank you!
Edit:
really_huge_list_of_list is a generator. Apologies for any confusion.
The size is obtained from the result list.
Possible minor improvement:
[dict(itertools.izip(small_list1, small_list2)) for small_list2 in really_huge_list_of_list]
Also, you may consider to use generator instead of list comprehensions.
To expand on what the comments are trying to say, you should use a generator instead of that list comprehension. Your code currently looks like this:
[dict(zip(small_list1, small_list2)) for small_list2 in really_huge_list_of_list]
and you should change it to this instead:
def my_generator(input_list_of_lists):
small_list1 = ["wherever", "small_list1", "comes", "from"]
for small_list2 in input_list_of_lists:
yield dict(zip(small_list1, small_list2))
What you're doing right now is taking ALL the results of iterating over your really huge list, and building up a huge list of the results, before doing whatever you do with that list of results. Instead, you should turn that list comprehension into a generator so that you never have to build up a list of 200,000 results. It's building that result list that's taking up so much memory and time.
... Or better yet, just turn that list comprehension into a generator comprehension by changing its outer brackets into parentheses:
(dict(zip(small_list1, small_list2)) for small_list2 in really_huge_list_of_list)
That's really all you need to do. The syntax for list comprehensions and generator comprehensions is almost identical, on purpose: if you understand a list comprehension, you'll understand the corresponding generator comprehension. (In this case, I wrote out the generator in "long form" first so that you'd see what that comprehension expands to).
For more on generator comprehensions, see here, here and/or here.
Hope this helps you add another useful tool to your Python toolbox!

Categories