Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
D = dict()
NOTFOUND = object()
def f1(x):
result = D.get(x, NOTFOUND)
if result is NOTFOUND:
result = D[x] = long_calculation()
return result
import time
from math import tan, atan
import timeit
NOTFOUND = object()
def long_calculation(x):
return atan(tan(x) / 2)
def f1(x):
if x not in D:
D[x] = long_calculation(x)
return D[x]
def f2(x):
try:
return D[x]
except:
D[x] = long_calculation(x)
return D[x]
def f3(x):
result = D.get(x, NOTFOUND)
if result is NOTFOUND:
result = D[x] = long_calculation(x)
return result
FUNCS = (
(f1, 'get triple'),
(f2, 'except'),
(f3, 'get once'),
)
def work(f, gap=0.1, count=1000):
for x in range(0, count):
f(x + gap)
D = {}
number = 10000
for func, descr in FUNCS:
print(f'{func.__name__} ({descr}):')
print(f' Cache empty:', timeit.timeit(f"work({func.__name__})", setup=f'D=dict()', globals=globals(), number=number))
print(f' Total reuse:', timeit.timeit(f"work({func.__name__})", setup=f'D=dict(); work({func.__name__})', globals=globals(), number=number))
print(f' Total miss :', timeit.timeit(f"work({func.__name__})", setup=f'D=dict(); work({func.__name__}, gap=0.2)', globals=globals(), number=number))
f1 (get triple):
Cache empty: 2.8940897800493985
Total reuse: 1.7486431139986962
Total miss : 1.6964515489526093
f2 (except):
Cache empty: 1.2670072519686073
Total reuse: 1.2622331579914317
Total miss : 1.2547212480567396
f3 (get once):
Cache empty: 1.6983374420087785
Total reuse: 1.6465996010228992
Total miss : 1.6999219709541649
from PIL import Image, ImageDraw
from random import randint
import time
image = Image.open('enter-image.png')
pix = image.load()
width = image.size[0]
height = image.size[1]
draw = ImageDraw.Draw(image)
pixel_id = []
print(f'Через 3 секунды начнётся анализ картинки. Размеры {width}x{height}')
time.sleep(3)
start_time = time.time()
for x in range(width):
for y in range(height):
print(x, y)
if not pix[x,y] in [i[0] for i in pixel_id]:
pixel_id.append([pix[x,y], []])
pixel_id[[i[0] for i in pixel_id].index(pix[x,y])][1].append((x,y))
for a in pixel_id:
color = (randint(0, 255), randint(0, 255) , randint(0, 255))
for draw_zone in a[1]:
draw.point(draw_zone, color)
print('Проработка изменённой картинки завершена. Начинается сохранение.')
image.save("output-image.png")
print(f'Сохранение завершено за {time.time()-start_time}.')
if pix[x,y] not in [(0, 0, 0, 255), (255,255,255, 255)]:
if not pix[x,y] in [i[0] for i in pixel_id]:
pixel_id.append([pix[x,y], []])
pixel_id[[i[0] for i in pixel_id].index(pix[x,y])][1].append((x,y))
$result = array_reduce( array_reverse( $keys ), function ( $c, $i ) use ( $value ) {
return [ $i => ( is_null( $c ) ? $value : $c ) ];
} );
print_r( $result );
// или по-модному, если слоник не древний
$result = array_reduce( array_reverse( $keys ), fn( $c, $i ) => [ $i => $c ?? $value ] );
print_r( $result );
https://3v4l.org/tLFqe from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
import datetime
import time
import random
from datetime import datetime
from random import randint
from random import choice
from string import ascii_lowercase
from string import digits
import os
import shutil
from shutil import copytree, ignore_patterns
def regger():
count = 1
login = 'testprofile2@mail.com'
shutil.copytree('/home/user/.mozilla/firefox/source/', "/home/user/.mozilla/firefox/"+ str("source") + str(count))
profile = "/home/user/.mozilla/firefox/source" + str(count)
fp = webdriver.FirefoxProfile(profile)
# Addons
directory = '/home/user/ffadns/'
files = os.listdir(directory)
addon = directory + str(random.choice(files)); addon2 = directory + str(random.choice(files)); addon3 = directory + str(random.choice(files))
fp.add_extension(addon); fp.add_extension(addon2); fp.add_extension(addon3)
addon_name = addon.split('/'[-1]) ; addon2_name = addon2.split('/'[-1]); addon3_name = addon3.split('/'[-1])
driver = webdriver.Firefox(fp)
dd = fp.profile_dir.split('/')
tempProfile_name = dd[-2]
shutil.move('/tmp/' + str(tempProfile_name) + '/webdriver-py-profilecopy/', '/tmp/' + str(login))
shutil.copytree('/tmp/' + login, '/home/user/.mozilla/firefox/' + login, ignore=ignore_patterns('lock'))
shutil.rmtree('/home/user/.mozilla/firefox/source1')
driver.quit()