can the order of code make this program faster?

2024/10/6 11:23:46

Hi this is my first post, I am learning how to write code so technically I am a newbie.

I am learning python I am still at the very basics, I was getting to Know the if statement and I tried to mix it with another concepts(function definition,input,variables) in order to get a wider vision of python, I wrote some code without a specific idea of what I wanted to do I just wanted to mix everything that I have learned so far so probably I over do it and its not practical, it "works" when I run it.

The question that I have its not about how to do it more efficient or with less code it is about the order of code in all programming in general. Here I'll show 2 different order of code that gives the same result with exactly the same code(but with different order).

on (1) I define a function on the first line.
on (2) I define the same function closer to when I use it on line 5.

which one is faster? is defining a function "closer" to when I need it impractical for the complexity of larger programs(but does it make it faster), or defining a function "far" from where I need it makes a larger program slower when running(but also more practical).

(1)

def t(n1,n2):v=n1-n2return abs(v)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))c=t(a,b)if a==b:print ('you are both the same age')else:print('you are not the same age\nthe difference of years is %s year(s)' % c)input()

(2)

a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))def t(n1,n2):v=n1-n2return abs(v)c=t(a,b)if a==b:print ('you are both the same age')else:print('you are not the same age\nthe difference of years is %s year(s)' % c)input()
Answer

The function definition must be located above the function call, but the distance between the function definition and the function call does not matter (as the function code would already be loaded).

One way to make your program faster is to avoid repeated calculations that produce the same result, by performing the calculation once, storing the result in a variable and using that variable whenever you need the result.

For example, suppose your program handles a very large tuple. If len(veryLargeTuple) occurs many times in the code, Python will repeatedly try to determine the length of the very large tuple. This is a waste of time because a tuple is immutable, so its length would not change, and finding the length of a very large tuple may take some time. It would be faster to store the result of len(veryLargeTuple) in a variable veryLargeTupleLength and use veryLargeTupleLength whenever you need the length of the very large tuple (looking up the value of a variable is a very fast operation).

https://en.xdnf.cn/q/118959.html

Related Q&A

How can I label a node that is the initial vertex in a cycle from graph data

I need to implement an algorithm such that in a collection of unique and ordered graph edges, I can find a cyclic node. E.g. for a ->b, b->c, c->a, then a is a cyclic node and thus I want to a…

Pandas : How to drop #DIV/0! and NA values in new column in pandas dataframe?

I did some calculation and have #DIV/0! in my dataframe. How to drop these values and count further ? I followed df.dropna but dataframe still counting #DIV/0!. Please suggest.df.insert(loc=df.column…

unsupported operand for 3 instances of two classes and one method?

Im trying to get the program to take the hp stat from enemyUnit, the attack stat from unit, and the damage stat from tackle and put them into one math problem in the method getHit(). this is the code:…

Telling the script to wait until button is clickable? [duplicate]

This question already has answers here:Check whether element is clickable in selenium(3 answers)Closed 4 years ago.Im writing a script in Selenium (Python) and I am having an issue with a disabled clic…

Python: UnicodeDecodeError: utf8

Im having problem to save accented letters. Im using POSTGRESQL and Python 2.7POSTGRESQL - ENCODING = LATIN1I already added this line but does not worked! #!/usr/bin/python # -*- coding: UTF-8 -*-More…

Get continuous response of POST request in python

Im writing a script which does a POST request to a server and gets blocked the server keeps sending the response whenever a specific event is triggered. I have to take a cookie for post request with ea…

DataType of Pandas Multiindex [duplicate]

This question already has answers here:get the dtype of a pandas multiindex(3 answers)Closed 6 years ago.import pandas as pd index = pd.MultiIndex.from_tuples([(1,2, None), (1,2,3)]) print(index.get_le…

Is there a way to see the internal representation of float?

In python tutorial for floating point, In base 2, 1/10 is the infinitely repeating fraction0.0001100110011001100110011001100110011001100110011...How do I get python interpreter to print this intenal re…

Create function from try-except

Based on the example provided in this answer, how can I create a function from:from collections import Counter s = [0, 0, 2, 1, 1, 0, 0, 0] try:print(next(t[0] for t in Counter(s).most_common(2) if t[…

Bad request error flask with POST request

I have the following route that is getting values from a submitted form@app.route(/authenticate, methods=["POST"]) def authenticate():username = request.form[username]print(username, file = s…