Python

import time,timeit


def power(limit):
    return [x**2 for x in range(limit)]




def measure_runtime(func):
    start = time.time()
    func()
    end = time.time()
    print(end - start) # number of seconds since 1970



measure_runtime(lambda :power(5000000)) # lamda function allows us to pass an argument


## another way


print(timeit.timeit('[x**2 for x in range(10)]')) # it runs it many times many times
print(timeit.timeit('list(map(lambda x: x**2,range(10)))'))
from datetime import datetime ,timezone,timedelta


print(datetime.now()) # not aware about time zones , local computer time

print(datetime.now(timezone.utc)) # UTC TIME  +00:00 meaning there is not offset


today =  datetime.now(timezone.utc)
tomorrow = today + timedelta(days=1)

print(tomorrow)

print(today.strftime('%d-%m-%Y %H:%M:%S'))

#user_date = input('Give time in YYYY-mm-dd format')
#user_date = datetime.strptime(user_date,'%Y-%m-%d')

#print(user_date)

print(today.timestamp()) # linux timestamp
import re

email = 'bartoszjakubiak23@gmail.com'
expresion = '[a-z\.]+'


domain = re.findall(expresion ,email)

print(domain)



price = 'Price : $189.45454'
expresion = 'Price : \$([0-9]*\.[0-9]*)' # \ escape character , * any number of numbers


matches = re.search(expresion ,price)

print(matches.group(0)) # entire match
print(matches.group(1)) # first thing in brackets
"""
. - matches one character
* many characters
[abc] - range of characters
[abc]+ matches one or more of this set
[A-z]+ - upercase
[A-z\.]@[A-z\.]+  - email
[A-z\.]@[A-z]+\.(com|me) - email


"""

"""
Our definition of a secure filename is:
- The filename must start with an English letters or a number (a-zA-Z0-9).
- The filename can **only** contain English letters, numbers and symbols among these four: `-_()`.
- The filename must end with a proper file extension among `.jpg`, `.jpeg`, `.png` and `.gif`
"""


def is_filename_safe(filename):
    # you only need to change the regular expression (regex) below
    regex = '^[a-zA-Z0-9][a-zA-Z0-9_()-]*(\.jpg|\.jpeg|\.png|\.gif)$'

    return re.match(regex, filename) is not None


import logging

logging.basicConfig(
    format='%(asctime)s %(levelname) -8s [%(filename)s:%(lineno)d]  %(message)s',
    level=logging.DEBUG,
    datefmt= '%Y-%m-%d %H:%M:%S',
    filename= 'log.txt'
)

#s - turn it to a string

logger = logging.getLogger('test_log')

logger.info('This will not show up')
logger.warning('This will')
logger.error('this is error')
logger.critical('Critical error')


"""
DEBUG
INFO

#those show up by default
WARNING
ERROR
CRITICAL

"""
#functions that accepts other functions as parameter

def greet():
    print('Hello')

def before_and_after(func):
    print('Before')
    func()
    print('After')

#before_and_after(greet)


#before_and_after(lambda: 5)


books = [
    {'name': 'Matrix', 'Director': 'Wahowski'},
{'name': 'Matrix2', 'Director': 'Wahowski'},
{'name': 'Ogniem I mieczem', 'Director': 'WAJDA'},
{'name': 'Chlopi', 'Director': 'Rejmond'},
{'name': 'QV', 'Director': 'Sienkiewicz'},
{'name': 'LORD', 'Director': 'Tolkien'}

]

def find_book(expected,finder):
    list = []
    for book in books:
        if finder(book) == expected:
            list.append(book)

    return list





find_by = input('What property are u searching by?')
looking_for = input('What are u looking for?')

book = find_book(looking_for ,lambda book: book[find_by])

print(book or 'No mowies found')
def transform_text(text: str) -> str:
    transform_text = ""
    for _index, _char in enumerate(text):
        if _index % 2:
            transform_text += _char.upper()

        else:
            transform_text += _char.lower()

    return transform_text


def display_vertical_text(text: str):
    for _char in text:
        print(_char)




if __name__ == "__main__":
    _text = "Hellow World"
    out = transform_text(text=_text)
    display_vertical_text(out)
# ANY - if any element evaluate to true
# ALL - if all elements evaluete to true

friends = [
    {'name': 'Rolf', 'Location': 'Warszawa'},
    {'name': 'Piotr', 'Location': 'Warszawa'},
    {'name': 'Marek', 'Location': 'Warszawa'},
    {'name': 'Tomasz', 'Location': 'Kraków'},
    {'name': 'Zenek', 'Location': 'Warszawa'},
    {'name': 'Stanislaw', 'Location': 'Warszawa'}

]

yourlocation = input('Where are u?')

friends_nearby = [friend for friend in friends if friend['Location'] == yourlocation ]

if any(friends_nearby): # if there is at least one and False if empty
    print("u are not alone")

if all(friends_nearby):
    print("u are not alone")


#Values that evaluate to false

"""
0 , 0.0 ...
none
[] () {}
False
"""

#print(bool(0))


print(all([1, 2, 3, 4, 5]))
print(all([0, 1, 2, 3, 4, 5]))
class Car:
  def __init__(self,make,model):
    self.make =make
    self.model = model

  def __repr__(self):
    return f'<car {self.make} {self.model}>'


class Garage:
  def __init__(self):
    self.cars = []
    
  def __len__(self):
      return len(self.cars)
  
  def add_car(self,car):
    if not isinstance(car,Car):# accept only clss obcject clas car
      raise TypeError(f'Tried to add `car.__class__.__name__ to the garage but you can only add car object')
    self.cars.append(car)
    #raise NotImplemented('We cant add catss to the garage yet')# you create a new error of type notimplemented error 



ford =Garage()
car = Car('Ford','Fiesta')

ford.add_car(car)
print(len(ford))
from collections import defaultdict, OrderedDict, namedtuple, deque


def task1() -> defaultdict:
    """
    - create a `defaultdict` object, and its default value would be set to the string `Unknown`.
    - Add an entry with key name `Alan` and its value being `Manchester`.
    - Return the `defaultdict` object you created.
    """
    # you code starts here:
    val = 'Unknown'
    dd = defaultdict(lambda: val)
    dd['Alan'] = 'Manchester'

    return dd




def task2(arg_od: OrderedDict):

  #  - takes in an OrderedDict `arg_od`
   # - Remove the first and last entry in `arg_od`.
  arg_od.popitem()
  arg_od.popitem(False)
    #- Move the entry with key name `Bob` to the end of `arg_od`.
  arg_od.move_to_end('Bob')
    #- Move the entry with key name `Dan` to the start of `arg_od`.
  arg_od.move_to_end('Dan',False)
    #- You may assume that `arg_od` would always contain the keys `Bob` and `Dan`,
    #   and they won't be the first or last entry initially.






def task3(name: str, club: str) -> namedtuple:
    """
    - create a `namedtuple` with type `Player`, and it will have two fields, `name` and `club`.
    - create a `Player` `namedtuple` instance that has the `name` and `club` field set by the given arguments.
    - return the `Player` `namedtuple` instance you created.
    """
    # you code starts here:
    Player =namedtuple('Player', ['name', 'club'])
    player = Player(name, club)

    return player




def task4(arg_deque: deque):
    """
    - Manipulate the `arg_deque` in any order you preferred to achieve the following effect:
        -- remove last element in `deque`
        -- move the fist (left most) element to the end (right most)
        -- add an element `Zack`, a string, to the start (left)
    """
    arg_deque.pop()  # remove last element
    arg_deque.append(arg_deque.popleft())  # remove first element and append it to last
    arg_deque.appendleft('Zack')  # add Zack to start
import sqlite3


class DatabaseConnection:
    def __init__(self,host):
        self.connection = None
        self.host = host

    def __enter__(self):
        self.connection = sqlite3.connect(self.host)
        return self.connection

    def __exit__(self, exc_type, exc_val, exc_tb): #parameters in case of exception
        if exc_tb or exc_val or exc_type: # if one of thos erros happen
            self.connection.close()
        else:
            self.connection.commit()
            self.connection.close()

Similiar Collections

Python strftime reference pandas.Period.strftime python - Formatting Quarter time in pandas columns - Stack Overflow python - Pandas: Change day - Stack Overflow python - Check if multiple columns exist in a df - Stack Overflow Pandas DataFrame apply() - sending arguments examples python - How to filter a dataframe of dates by a particular month/day? - Stack Overflow python - replace a value in the entire pandas data frame - Stack Overflow python - Replacing blank values (white space) with NaN in pandas - Stack Overflow python - get list from pandas dataframe column - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to lowercase a pandas dataframe string column if it has missing values? - Stack Overflow How to Convert Integers to Strings in Pandas DataFrame - Data to Fish How to Convert Integers to Strings in Pandas DataFrame - Data to Fish create a dictionary of two pandas Dataframe columns? - Stack Overflow python - ValueError: No axis named node2 for object type <class 'pandas.core.frame.DataFrame'> - Stack Overflow Python Pandas iterate over rows and access column names - Stack Overflow python - Creating dataframe from a dictionary where entries have different lengths - Stack Overflow python - Deleting DataFrame row in Pandas based on column value - Stack Overflow python - How to check if a column exists in Pandas - Stack Overflow python - Import pandas dataframe column as string not int - Stack Overflow python - What is the most efficient way to create a dictionary of two pandas Dataframe columns? - Stack Overflow Python Loop through Excel sheets, place into one df - Stack Overflow python - How do I get the row count of a Pandas DataFrame? - Stack Overflow python - How to save a new sheet in an existing excel file, using Pandas? - Stack Overflow Python Loop through Excel sheets, place into one df - Stack Overflow How do I select a subset of a DataFrame? — pandas 1.2.4 documentation python - Delete column from pandas DataFrame - Stack Overflow