Understanding How to Use len, random.randrange, timeout.Timer and Meaning of Arguments

Asked 5 months ago, Updated 5 months ago, 15 views

Good job. I'm a beginner who hasn't really touched Python.
I would like to ask you a few questions about the program below.

That's all I didn't understand.
I am sorry to trouble you, but I would appreciate your help.

import timeout
import random

def del_dict_items(x):
        delx [ random_index ]
        x.setdefault(random_index, None)
        delx [ random_index ]

for i in range (100000, 1000001,20000):
    t_list=timeit.Timer("del x[random.randrange(len(x)-1)]", "from__main__import random, x")
    t_dict=timeit.Timer("del_dict_items(x)"", "from__main_import random, x, del_dict_items")
    x = list(range(i))
    x = {j:None for jin range(i)}
    dict_del_time = t_dict.timeit (number = 1000)

python python3

2022-09-30 11:12

2 Answers

It is recommended that you search Google or read documents before asking questions, and then write down what you know and what you don't understand.

According to the random.randrange document, the maximum value is an argument, where len(x)-1 is a random integer.

In addition, the embedded function len(x) returns the number of elements of the argument.

Now, the function del_dict_items seems to be trying to remove random elements of type dict given as arguments.For this reason, random_index appears to be substituting a random value of -1 as an index.


As I commented, I cannot answer correctly because the code is not written correctly, but at least the purpose of this function is not to insert elements, but to randomly delete elements.

The order of recognition is reversed.

Instead of "KeyError Occurs When SetDefault Inserts None in Index", "SetDefault Inserts None in Index When KeyError Occurs" is correct.

Yes, dict.setdefault is a function that returns a value that corresponds to the first argument, if any, or a second argument after it is set as a value.

If you do del in the first place, you don't need a branch, and if you do x[random_index]=None, you don't need a try-catch...

_main__ refers to the module that is currently running.Perhaps you are pointing to this script itself and calling it from timeit.Timer.

del_deict_items doesn't appear. Is it typo?

2022-09-30 11:12

If you don't understand the meaning of the entire code, you may be able to understand the meaning by dividing the code and examining its behavior.

len(x) is the length of the argument x.
Since x is a list, it returns the number of elements in the list.

 x = [1,2]

random.randrange(i) returns a random integer from 0 to i-1.
If you specify len(x)-1, you will no longer delete the last element of the list, but you cannot infer from the questionnaire what you intend to leave the end here.(random.randrange(0,len(x)-1) can be inferred to be intended to prevent exceptions.)

 x = [1,2]
print(random.randrange(len(x))-1)# Returns an integer (i.e., 0) of 0 NN<(2-1) no matter how many times you try.

random_index is a valid variable in a function named del_dict_items.
You can understand that you can enter random integers in the range of range

As a result of KeyError, the except KeyError moves to the random_index key in the setdefault with a value of None.
You can understand that if you enter a dictionary key in setdefault, you can run a dictionary del regardless of whether the value is None or anything.

timeit.Timer(stmt, setup) describes the code for measuring execution time in the first argument (stmt).Write the code to initialize to the second argument (setup).
By writing from__main__import random, x, del_dict_items during setup, you can use the variables x defined in the main function called by python hoge.py from the command line, as well as functions del_dict_items.
The above statement makes del_dict_items(x) available for execution (stmt).
Note the differences and errors in the sample code below.

#Set up as above
t_dict=timeit.Timer(stmt="del_dict_items(x), setup="from_main__import random, x, del_dict_items")
# ModuleNotFoundError: No module named 'x' error during setup process
t_dict=timeit.Timer(stmt="del_dict_items(x), setup="import random, x, del_dict_items")
# Error "del_dict_items not defined" (NameError: name 'del_dict_items' is not defined) in execution operation
t_dict=timeit.Timer(stmt="del_dict_items(x), setup="from_main__import random,x")

While writing the answers, I was concerned about the following points:

  • The title "About the Python Program" is abstract, so we recommend a title that can specifically determine the question.(If the questions are too wide to be specific, it is recommended to split them.)
  • There are many typographical errors in the function name of the questionnaire, such as
  • del_deict_items.Be especially careful of typographical errors in functions and variable names as they confuse the respondents.(Edited)
  • There may be some parts where the usage of variables and functions is unclear.It is recommended that you pause for a moment to break down the code and deepen your understanding.

It was an old woman's advice from above.
Rather than describing multiple questions by illustrating difficult codes, it is more likely to be answered correctly by focusing on the question "I don't know where the simple sample code is."

2022-09-30 11:12

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.