به نام خداوند مهربان

آخرین مطالب

۱۱ مطلب با کلمه‌ی کلیدی «python» ثبت شده است

Linear search is the simplest searching algorithm. It sequentially checks each element of the list until it finds the target value.

Steps:

  • Start from the first element of the list.
  • Compare each element of the list with the target value.
  • If the element matches the target value, return its index.
  • If the target value is not found after iterating through the entire list, return -1.

 

def linear_search(arr, target):
    """
    Perform linear search to find the target value in the given list.

    Parameters:
        arr (list): The list to be searched.
        target: The value to be searched for.

    Returns:
        int: The index of the target value if found, otherwise -1.
    """
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = linear_search(arr, target)
if result != -1:
    print(f"Linear Search: Element found at index {result}")
else:
    print("Linear Search: Element not found")

 

  • حسن دلدار
np_arr = torch_tensor.detach().cpu().numpy()
  • حسن دلدار

نمایش اطلاعات بیشتری از یک تنسور:

 

In [18]: torch.set_printoptions(edgeitems=1)

In [19]: a
Out[19]:
tensor([[-0.7698,  ..., -0.1949],
        ...,
        [-0.7321,  ...,  0.8537]])

In [20]: torch.set_printoptions(edgeitems=3)

In [21]: a
Out[21]:
tensor([[-0.7698,  1.3383,  0.5649,  ...,  1.3567,  0.6896, -0.1949],
        [-0.5761, -0.9789, -0.2058,  ..., -0.5843,  2.6311, -0.0008],
        [ 1.3152,  1.8851, -0.9761,  ...,  0.8639, -0.6237,  0.5646],
        ...,
        [ 0.2851,  0.5504, -0.9471,  ...,  0.0688, -0.7777,  0.1661],
        [ 2.9616, -0.8685, -1.5467,  ..., -1.4646,  1.1098, -1.0873],
        [-0.7321,  0.7610,  0.3182,  ...,  2.5859, -0.9709,  0.8537]])
  • حسن دلدار

 

From the comment:

sudo update-alternatives --config python

Will show you an error:

update-alternatives: error: no alternatives for python3 

You need to update your update-alternatives , then you will be able to set your default python version.

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.4 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2

Then run :

sudo update-alternatives --config python

Set python3.6 as default.

Or use the following command to set python3.6 as default:

sudo update-alternatives  --set python /usr/bin/python3.6
  • حسن دلدار

Run python script in background

Introduction

If you want to run a python script in the background you can use an ampersand(&). But at first, we need to prepare our script for this.

For example, we have a python file my_script.py. At first, we need to add execution permission for this file using the next command:

chmod +x my_script.py

Then I recommend adding a shebang line to the top of this file. This allowed you don't indicate in the terminal that it is a python script.

#!/usr/bin/env python3

Now we need some logic that will show us that the script is running in the background. For example, a simple script that will have been printing time during the next ten seconds.

Script content:

 #!/usr/bin/env python3

from datetime import datetime

start_time = datetime.now()
print(f"Start time: {datetime.now().strftime('%H:%M:%S')}")

interval = 10

while interval != 0:
    if (datetime.now() - start_time).seconds == 1:
        start_time = datetime.now()
        print(f"Current time: {datetime.now().strftime('%H:%M:%S')}")
        interval -= 1

Using only ampersand (&)

For running the script use the next command:

your/path/my_script.py > output.log &

We save the script's output to the log file, so after running this command we will get output like this in the terminal:

[1] 3010186

This is a process id (PID). If you want to stop the script before its ending you can use the kill command:

kill PID

It is also possible to kill the process by using pkill command. If you run a few scripts with the same name they all will be stopped.

pkill -f my_script.py

We can see our process using the next command:

ps ax | grep my_script.py

Command output:

3010186 pts/0    R      0:03 python3 ./my_script.py
3012286 pts/1    S+     0:00 grep --color=auto my_script.py

After finishing the process all script output will be saved to output.log. It has the next content:

Start time: 10:46:21
Current time: 10:46:22
Current time: 10:46:23
Current time: 10:46:24
Current time: 10:46:25
Current time: 10:46:26
Current time: 10:46:27
Current time: 10:46:28
Current time: 10:46:29
Current time: 10:46:30
Current time: 10:46:31

The background script seems to work perfectly, but it's not quite true. For example, if you use ssh session connection, the disconnect will stop our script. As a solution, you could use nohup or a better screen. This allows us to return to the script after reconnecting the session.

Using the 'screen' command for background scripts

At first, you need to install the screen. Use the next command for this:

sudo apt install screen

Now we can run our script using the screen command. We need a little to modify the command for the identical logging as in the previous heading. For that, we need to add the next keys: -L for resolving logging and -Logfile path/to/filename.log to indicate log file (by default screenlog.0)

screen -L -Logfile ./output.log ./my_script.py &

Despite the screen output, logging still saves to our log file. 

Let's check the process list during performing the screen command using the next command:

ps ax | grep my_script.py

Command output:

3038184 pts/0    S      0:00 screen -L -Logfile ./output.log ./my_script.py
3038185 ?        Ss     0:00 SCREEN -L -Logfile ./output.log ./my_script.py
3038186 pts/3    Rs+    0:03 python3 ./my_script.py
3038214 pts/1    S+     0:00 grep --color=auto my_script.py

You can also detach the screen using Ctrl + a and also return back to the screen using the command screen -r.

 

 
  • حسن دلدار

استفاده ستاره در پارامتر های ارسالی:

 

def foo(a, b, c):
    return(a, b, c)

t = (1, 4, 6)
print('Output tuple unpacking: ',foo(*t))

d = {'a': 10, 'b': 20, 'c': 30}
print('Output dictionary unpacking: ',foo(*d))
print('Output dictionary unpacking: ',foo(**d))


 

خروجی:

    
Output tuple unpacking:  (1, 4, 6)
Output dictionary unpacking:  ('a', 'b', 'c')
Output dictionary unpacking:  (10, 20, 30)

استفاده در آرگمان:

def test_var_args(farg, *args):
    print ("formal arg:", farg)
    for arg in args:
        print ("another arg:", arg)

test_var_args(1, "two", 3)


def test_var_kwargs(farg, **kwargs):
    print ("formal arg:", farg)
    for key in kwargs:
        print ("another keyword arg: %s: %s" % (key, kwargs[key]))

test_var_kwargs(farg=1, myarg2="two", myarg3=3)

خروجی:

 

formal arg: 1
another arg: two
another arg: 3
formal arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3

 

 

 

 

 

 

  • حسن دلدار

create a virtual environment using the Python venv module:

python -m venv .env

You can jump in and out of your virtual environment with the activate and deactivate scripts:

# Activate the virtual environment
source .env/bin/activate

# Deactivate the virtual environment
source .env/bin/deactivate

In windows:

.env\Scripts\activate

 

You can make sure that the environment is activated by running the which python command: if it points to the virtual environment, then you have successfully activated it!

which python
/home/<user>/transformers-course/.env/bin/python

 

 

  • حسن دلدار

توابع بینام یا Anonymous Functions یا lambda functions :

تابع لامدای زیر :

lambda x: x % 3 == 0

دقیقا برابر :

def by_three(x):
    return x % 3 == 0

می باشد.

مثال :

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)

# print : [0, 3, 6, 9, 12, 15]








  • حسن دلدار

برشی از لیست :

[start:end:stride]

l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]

#Should be [9, 25, 49, 81]

حذف اندکس ها از نحو برش (Omitting Indices):

to_five = ['A', 'B', 'C', 'D', 'E']

print to_five[3:]
# prints ['D', 'E'] 

print to_five[:2]
# prints ['A', 'B']

print to_five[::2]
# print ['A', 'C', 'E']

معکوس کردن لیست( Reversing a List):

letters = ['A', 'B', 'C', 'D', 'E']
print letters[::-1]
# print ['E', 'D', 'C', 'B', 'A']


  • حسن دلدار

ساخت لیست های ادراکی(فهمی) یا  comprehension lists در پایتون

l = [i ** 2 for i in range(1, 11)]

l = [i  for i in range(1, 51) if i % 2 == 0]

  • حسن دلدار