Skip to content

Instantly share code, notes, and snippets.

@trilliwon
Created December 12, 2021 07:00
Show Gist options
  • Save trilliwon/544c42c2629912792c4835de3974c159 to your computer and use it in GitHub Desktop.
Save trilliwon/544c42c2629912792c4835de3974c159 to your computer and use it in GitHub Desktop.

Python Study

여러개의 입력값을 받을 때

def sum_many(*args): # 입력값들을 튜플로 만듬
    sum = 0
    for i in args:
        sum = sum + i
    return sum

sum_many(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

55

키워드 파라미터 kwargs (keyword arguments)

key=value 형식의 파라미터를 넘겨주면 kwargs 에 저장된다.

def func(**kwargs):
    print(kwargs)

func(a=1, b=2)

함수 인자에 초기값 설정, (defaults parameter는 맨 마지막 arguments로)

def log_in(ids, pw, admin = True):
    print(admin)
    print(ids, pw)

global # not recommended

a = 1
def vartest():
    global a
    a = a+1

vartest()
print(a)

print

print("life" "is" "too short")
lifeistoo short

print("life"+"is"+"too short")
lifeistoo short

print("life", "is", "too short")
life is too short

Reading and Writing Files

open() returns a file object, and is most commonly used with two arguments: open(filename, mode). file object - (raw binary files, buffered binary files and text files.) It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks: f.seek(offset, from_what)

>>> f = open('workfile', 'r')
>>> with open('workfile') as f:
...     read_data = f.read()
>>> f.closed
True

Classes

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

x = MyClass()
m.__doc__

x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print(x.counter)
del x.counter # delete x.counter

#######

class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']

# Empty class
class Employee:
    pass

Inheritance

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

Iterators

This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method __next__() which accesses elements in the container one at a time. When there are no more elements, __next__() raises a StopIteration exception which tells the for loop to terminate. You can call the __next__() method using the next() built-in function.

class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
...     print(char)
...
m
a
p
s

Generators

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed). An example shows that generators can be trivially easy to create:

def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]

>>> for char in reverse('golf'):
...     print(char)
...
f
l
o
g

#
>>> gen_exp = (x ** 2 for x in range(10) if x % 2 == 0)
>>> for x in gen_exp:
...     print(x)
0
4
16
36
64

Python List Comprehension vs Generator Expressions

advantage Generator Expressionsof is use of less memory

>>> from sys import getsizeof
>>> my_comp = [x * 5 for x in range(1000)]
>>> my_gen = (x * 5 for x in range(1000))
>>> getsizeof(my_comp)
9024
>>> getsizeof(my_gen)
88

The generator yields one item at a time — thus it is more memory efficient than a list.


A counter tool is provided to support convenient and rapid tallies. For example:

>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0
>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry

most_common([n])

elements()

subtract([iterable-or-mapping])

fromkeys(iterable)

update([iterable-or-mapping])

Common pattern

sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts


>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d                       # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d                       # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})


>>> c = Counter(a=2, b=-4)
>>> +c
Counter({'a': 2})
>>> -c
Counter({'b': 4})

apply(function, (args))는 함수 이름과 그 함수의 인수를 입력으로 받아 간접적으로 함수를 실행시키는 명령어이다.

def sum(a,b):
    return a+b

apply(sum, (3,4))
7

A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

>>> set([1, 2, 3])
{1, 2, 3}

>>> set("Hello set")
{'t', 's', 'o', 'e', 'l', 'H', ' '}


>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}


# list comprehensions
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

Python binary

# int to binary string
format(1000, "b")

# binary string to int
int('100101011', 2)

string to list

str = 'abcdefg'
strlist = list(str)

# reversed
str[::-1]
print(str) # gfedcba

Check if all elements in list are identicial

values = [1, 1, 1, 1, 1, 1]
# set(values) -> {1}
len(set(values)) == 1

Reduce

>>> from functools import reduce
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102

Lambda

>>> sum = lambda x, y : x + y
>>> sum(3,4)
7
>>>

Map

>>> a = [1, 2, 3, 4]
>>> b = [17, 12, 11, 10]
>>> list(map(lambda x, y : x+y, a, b))
[18, 14, 14, 14]

>>> list(map(lambda x : x * x, a))
[1, 4, 9, 16]

Filter

{% highlight python %}

fibonacci = [0,1,1,2,3,5,8,13,21,34,55] odd_numbers = list(filter(lambda x: x % 2, fibonacci)) [1, 1, 3, 5, 13, 21, 55] f = lambda x: x % 2 odd_numbers = list(filter(f, fibonacci)) [1, 1, 3, 5, 13, 21, 55]

{% endhighlight %}

lower upper case

>>> a = 'abC'
>>> a.lower()
'abc'
>>> a.upper()
'ABC'

combind two dictionaries

>>> a = {'a':1, 'b':1}
>>> b = {'c':2, 'd':2}
>>> {**a, **b} # only for string key
{'a': 1, 'b': 1, 'c': 2, 'd': 2}

>>> dict(a, **b) # only for string key
{'a': 1, 'b': 1, 'c': 2, 'd': 2}

>>> dict(a.items() | b.items())
{'c': 2, 'b': 1, 'a': 1, 'd': 2}

import queue

que = queue.Queue()
que.put(1)
que.put(2)

que.get() # 1
que.get() # 2

que.empty()

Stack

stack = []
stack.append(1)
stack.append(2)
stack.pop() # 2
stack.pop() # 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment