# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Code More, Code Daily 
# - Goal is to Write code regularly
# - my own implementation of the tricks with added links or personal experimetnation

# [🐍PyTricks]: Python list slice syntax fun
# ---

# Python's list slice syntax can be used without indices
# for a few fun and useful things:

#  You can clear all elements from a list:

listy = [1, 2,3,4,5]
print(listy)
del listy[:] # deletes all items in place?
listy

# You can replace all elements of a list
# without creating a new list object:

a = listy
listy[:] = [7,8,9] # selects all items and assignes ne values?
print(listy)

a

a is listy

# you can also create a shallow copy of a list

b = listy[:]

b

b is listy

a is listy

a is b

# assignment via slicing is trickyyyyy good to know!

a.append([1,3])
print(a)
print(listy)

b


# [🐍PyTricks]: Python 3.5+ type annotations
# ---
# Fri, Jul 5,

# *mypy not able to install via anaconda navigator?*

# Python 3.5+ supports 'type annotations' that can be
# used with tools like [Mypy](http://mypy-lang.org/) to write statically typed Python:
# - Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or "duck") typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking. Mypy type checks standard Python programs; run them using any Python VM with basically no runtime overhead.

def my_add(a: int, b: int) -> int:
    return a + b


my_add(5,10)

my_add(5,"10")

5 + "10"

# not a good test...?  not raising on str
#

my_add(5, 10.0) # not working?

# from docs https://github.com/python/mypy  :
# - see example on [online playground](https://mypy-play.net/)
# - https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html
# - http://mypy-lang.org/examples.html :
#  - word frequencies with dynamic typic
#  - simple class
#  - prime number sieve with generators
#  

# +
from typing import Iterator

def fib(n: int) -> Iterator[int]:
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a + b


# -

fib(123)

fib("10") 

# http://mypy-lang.org/examples.html : word frequencies with dynamic typic
#
# - [file object returned by open](https://docs.python.org/3.7/glossary.html#term-file-object)
# - [`re.sub(pattern, repl, string, count=0, flags=0)`](https://devdocs.io/python~3.7/library/re#re.sub)  Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.

# +
# Mypy with dynamic typing
# filename: wordfreq.py
import sys
import re

if not sys.argv[1:]: # retrieve when run in command line with filename as arg
    raise RuntimeError('Usage: wordfreq FILE')
    
dictionary = {}

with open(sys.argv[1]) as file:
    # s(treams) - file object, text file
    for s in f: 
        for word in re.sub('\W', ' ', ).split():
            # add word to dictionary
            d[word] = d.get(word, 0) + 1 

#list comprehension
lst = [(freq, word) for word, freq in d.items()]

for freq, word in sorted(lst):
    print('%-6d %s' % (freq, word) )

# +
# Display the frequencies of words in a file.

import sys
import re
from typing import Dict

if not sys.argv[1:]:
    raise RuntimeError('Usage: wordfreq FILE')

d = {}  # type: Dict[str, int]

with open(sys.argv[1]) as f:
    for s in f:
        for word in re.sub('\W', ' ', s).split():
            d[word] = d.get(word, 0) + 1

# Use list comprehension
l = [(freq, word) for word, freq in d.items()]

for freq, word in sorted(l):
    print('%-6d %s' % (freq, word))
# -

# - Copy to file and run...?
# - or hmmm find a data set to use on thats persnonal from my note sin the past eg on Evernote, Workflowy, Google Docs, ...
#

import sys
print(sys.argv[1])

# +
# Mypy with dynamic typing
import re

if not sys.argv[1:]: # retrieve when run in command line with filename as arg
    raise RuntimeError('Usage: wordfreq FILE')
    
dictionary = {}

filename = './data/WorkFlowy-sept-15-2017.txt'
with open(filename,encoding='utf-8') as file:
    # s(treams) - file object, text file
    for stream in file: 
        for word in re.sub('\W', ' ', stream).split():
            # add word to dictionary
            dictionary[word] = dictionary.get(word, 0) + 1 

#list comprehension
lst = [(freq, word) for word, freq in dictionary.items()]

for freq, word in sorted(lst):
    print('%-6d %s' % (freq, word) )
# -

size = len(lst)
print(size)

# +
sizeInDaMiddle = len(lst[int(size*0.25) : int(size*0.75) ]) 
# size of between 20% - 80%  second and third quantile?

print(sizeInDaMiddle)
print(sizeInDaMiddle/size*100) 
# percentage of total... lol makes sense haha sanity chekc


# -

# Get unique numbers ? use set propert!~https://stackoverflow.com/questions/12897374/get-unique-values-from-a-list-in-python

list(set(size))

lst[10:20]

# list of tuple keywords pairs... 

type(lst)

type(lst[1])

set(dictionary.values()) # unique counts.... ?

# Okay but what question am I Investigating? I want to see what topics eg Javascript, Python or Cooking etc is being talked aobut... hmmm
#
# **PAUSE FOR NEXT TIME**

# **ERROR Unicode decode error** ?  `'charmap' codec can't decode byte 0x9d in position 5443: character maps to <undefined>`
#
# - https://stackoverflow.com/a/21129492/11539023 answer
# - ecxport again.. or export as OPML specification ?
# - review open file docs! 
#
# **Fix** open(filename) -> open(filename,encoding='utf-8')
#

# [🐍PyTricks]: Merging two dicts in Python 3.5+ with a single expression
# ---
# Sat, May 25 2019

# Screencast: [A Shorthand for Merging Dictionaries in Python 3.5+](https://www.youtube.com/watch?v=Duexw08KaC8)
#
# Detailed info from on [PEP 448 -- Additional Unpacking Generalizations](https://www.python.org/dev/peps/pep-0448/)
# -  * iterable unpacking operator and ** dictionary unpacking operators 
# -  function calls, in comprehensions and generator expressions, and in displays.
#
# More [examples here](https://codeyarns.com/2012/04/26/unpack-operator-in-python/)

# +
# How to Merge two dictionaries?
# May 25, 2019
x = {'a': 1, 'b':2}
y = {'b': 3, 'b':4} 
print({**x, **{'c':1,'d':2}})

z = {**x, **y}
print(z) # {'a': 1, 'b': 4},  cant have dupes so last one was added

# for dicts : ** unpacks the values , while * unpacks the keys
print(*x,*y,*{'c':1,'d':2})
print(y) # -> cant create duplicates, strangely python does not raise a warning

# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting 
# duplicates from left to right.
# -

print(*[1,23],*[2],3,*{'x':3})

StarcoderdataJupyterScriptsDedupFiltered