Pastebin
API
tools
faq
paste
Login
Sign up
Please fix the following errors:
New Paste
Syntax Highlighting
#!/usr/bin/env python3.8 """ Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers: cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument: cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory. cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory. cd / switches the current directory to the outermost directory, /. ls means list. It prints out all of the files and directories immediately contained by the current directory: 123 abc means that the current directory contains a file named abc with size 123. dir xyz means that the current directory contains a directory named xyz. """ import sys from pathlib import Path import pytest import time from functools import wraps INPUTS_DIR = 'inputs' INPUT_FILE = 'day07.txt' PROJECT_DIR = Path('.') FILE_PATH = PROJECT_DIR / INPUTS_DIR / INPUT_FILE LOOP_NO = 1 def f_time(f): @wraps(f) def time_check(*args, **kwargs): print(f'{LOOP_NO=}') start_time = time.monotonic() for i in range(LOOP_NO): sizes = f(*args, *kwargs) end_time = time.monotonic() print(f"It took {end_time-start_time:.10f} seconds to compute") return sizes return time_check FACTOR_SIZE = 10**5 DISK_SPACE = 7*10**7 UNUSED_SPACE = 3*10**7 def read_filesystem_output(file_path): with open(file_path) as f: return f.read() @f_time def filesystem_directory_structure_size(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_struct(output) calc_dir_1kk = calculate_directory_limited_size(fs, limit=FACTOR_SIZE) return calc_dir_1kk @f_time def filesystem_directory_tree_size(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_tree(output) total_size, limited_size = _calc(fs, limit=FACTOR_SIZE) return total_size, limited_size @f_time def filesystem_directory_tree_size_second_recursion(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_tree(output) total_size, limited_size = calculate_filesystem_tree_size(fs, limit=FACTOR_SIZE) return total_size, limited_size def find_directory_for_removal(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_struct(output) USED_SPACE = fs['/'] print(USED_SPACE) min_space_for_removal = UNUSED_SPACE - (DISK_SPACE - USED_SPACE) directory, size = find_directory_specified_size(fs, min_space_for_removal) return directory, size def find_directory_specified_size(fs, size): """Caculate total size of directories with limited size""" print(size) dirs = [(k, v) for k, v in fs.items() if v in range(size, UNUSED_SPACE)] dirs = sorted(dirs, key=lambda d: d[1]) print(dirs) return dirs[0] def create_filesystem_tree(iterator): filesystem = dict() filesystem['/'] = {} path = [] cur_dir = filesystem['/'] for line in iterator: line_split = line.split() if '$' in line_split[0]: if 'ls' in line_split[1]: continue if 'cd' in line_split[1]: cd_opt = line_split[2] if cd_opt == '/': cur_dir = filesystem['/'] path = ['/'] elif cd_opt == '..': path.pop() cur_dir = filesystem for d in path: cur_dir = cur_dir[d] else: dir_name = f'/{cd_opt}' cur_dir = cur_dir[dir_name] path.append(dir_name) continue else: if 'dir' in line_split[0]: dir_name = f'/{line_split[1]}' cur_dir[dir_name] = {} continue size = int(line_split[0]) cur_dir[line_split[1]] = size return filesystem def _calc(d, limit, total_size=0): dir_size = 0 for k, v in d.items(): if isinstance(v, dict): size, total_size = _calc(v, limit, total_size) dir_size += size if limit and size < limit: total_size += size else: dir_size += v return dir_size, total_size def calc_dirs_size(d): size = 0 _d = d.copy() for k, v in _d.items(): if isinstance(v, dict): tmp = calc_dirs_size(v) d['dirs'] = tmp size += tmp else: size += v return size def calc_size(d, limit=0, total_size=0): dir_size = 0 for k, v in d.items(): if isinstance(v, dict): size, total_size = calc_size(v, limit, total_size) if limit and size <= limit: total_size += size else: dir_size += v return dir_size, total_size def calculate_filesystem_tree_size(fs, limit=0): total_dirs_size = calc_dirs_size(fs) total_size, limited_size = calc_size(fs, limit) assert total_dirs_size == total_size return total_size, limited_size def propage_size(fs, paths, size): for path in paths: fs[path] += size def create_filesystem_struct(iterator): """Prepare files system as paths with sizes interpretation""" filesystem = dict() paths = [] cur_dir = '/' filesystem[cur_dir] = 0 for line in iterator: line_split = line.split() if '$' in line_split[0]: if 'ls' in line_split[1]: continue if 'cd' in line_split[1]: cd_opt = line_split[2] if cd_opt == '/': cur_dir = '/' paths.clear() elif cd_opt == '..': cur_dir = paths.pop() else: paths.append(cur_dir) cur_dir = f'{cur_dir}/{cd_opt}' if cur_dir.strip('/') else f'/{cd_opt}' else: if 'dir' in line_split[0]: dir_name = line_split[1] if cur_dir == '/': ls_dir = f'/{dir_name}' else: ls_dir = f'{cur_dir}/{dir_name}' if ls_dir not in filesystem: filesystem[ls_dir] = 0 else: size = int(line_split[0]) filesystem[cur_dir] += size propage_size(filesystem, paths, size) return filesystem def calculate_directory_limited_size(fs, limit=0): """Caculate total size of directories with limited size""" if limit == 0: return fs['/'] size = 0 for k, v in fs.items(): if v <= limit: size += v return size ex_output = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """ ex_struct = {'/': 48381165, '/a': 94853, '/d': 24933642, '/a/e': 584} def test_dir_structure(): iterator = ex_output.strip().split('\n') struct = create_filesystem_struct(iterator) assert (struct == ex_struct), ( f'Incorrect struct\nExpected: {ex_struct}\nActual: {struct}' ) SIZE_1KK = 95437 def test_calc_limited_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_struct(iterator) size = calculate_directory_limited_size(struct, limit=FACTOR_SIZE) assert size == SIZE_1KK, f'Incorrect size. Expected: {SIZE_1KK}. Actual: {size}' def test_calc_limited_tree_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_tree(iterator) total_size, limited_size = calculate_filesystem_tree_size(struct, limit=FACTOR_SIZE) assert limited_size == SIZE_1KK, f'Incorrect size. Expected: {SIZE_1KK}. Actual: {limited_size}' TOTAL_SIZE = 48381165 def test_calc_total_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_struct(iterator) size = calculate_directory_limited_size(struct) assert size == TOTAL_SIZE, f'Incorrect size. Expected: {TOTAL_SIZE}. Actual: {size}' def test_calc_total_tree_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_tree(iterator) size = calc_dirs_size(struct) assert size == TOTAL_SIZE, f'Incorrect size. Expected: {TOTAL_SIZE}. Actual: {size}' def test_removal_directory_closest_size(): ex_size = ex_struct['/d'] directory, size = find_directory_for_removal(file_path=FILE_PATH, output=ex_output) assert ex_size == size, ( f'Incorrect directory size for removal. Expected: {ex_size}. Actual: {size}') ex_filesystem = """ - / (dir) - a (dir) - E (dir) - i (file, size=584) - f (file, size=29116) - g (file, size=2557) - h.lst (file, size=62596) - b.txt (file, size=14848514) - c.dat (file, size=8504156) - d (dir) - j (file, size=4060174) - d.log (file, size=8033020) - d.ext (file, size=5626152) - k (file, size=7214296) """ """ The total sizes of the directories above can be found as follows: The total size of directory 'e' is 584 because it contains a single file 'i' of size 584 and no other directories. The directory 'a' has total size 94853 because it contains files: 'f' (size 29116), 'g' (size 2557), and 'h.lst' (size 62596), plus file 'i' indirectly (a contains e which contains i). Directory 'd' has total size 24933642. As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file. To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are 'a' and 'e'; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!) Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories? """ if __name__ == '__main__': file_path = sys.argv[1] if len(sys.argv) > 1 else FILE_PATH output = read_filesystem_output(file_path) print(filesystem_directory_structure_size(file_path, output)) print(filesystem_directory_tree_size(file_path, output)) print(filesystem_directory_tree_size_second_recursion(file_path, output)) print(find_directory_for_removal(file_path, output)) pytest.main(sys.argv) import os if (loop_no := os.getenv('LOOP_NO')) is None: exit() LOOP_NO = int(loop_no) print(filesystem_directory_structure_size(file_path, output)) print(filesystem_directory_tree_size(file_path, output)) print(filesystem_directory_tree_size_second_recursion(file_path, output))
Optional Paste Settings
Category:
None
Cryptocurrency
Cybersecurity
Fixit
Food
Gaming
Haiku
Help
History
Housing
Jokes
Legal
Money
Movies
Music
Pets
Photo
Science
Software
Source Code
Spirit
Sports
Travel
TV
Writing
Tags:
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
JSON
Java
JavaScript
Lua
Markdown (PRO members only)
Objective C
PHP
Perl
Python
Ruby
Swift
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
AIMMS
ALGOL 68
APT Sources
ARM
ASM (NASM)
ASP
ActionScript
ActionScript 3
Ada
Apache Log
AppleScript
Arduino
Asymptote
AutoIt
Autohotkey
Avisynth
Awk
BASCOM AVR
BNF
BOO
Bash
Basic4GL
Batch
BibTeX
Blitz Basic
Blitz3D
BlitzMax
BrainFuck
C
C (WinAPI)
C Intermediate Language
C for Macs
C#
C++
C++ (WinAPI)
C++ (with Qt extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
CMake
COBOL
CSS
Ceylon
ChaiScript
Chapel
Clojure
Clone C
Clone C++
CoffeeScript
ColdFusion
Cuesheet
D
DCL
DCPU-16
DCS
DIV
DOT
Dart
Delphi
Delphi Prism (Oxygene)
Diff
E
ECMAScript
EPC
Easytrieve
Eiffel
Email
Erlang
Euphoria
F#
FO Language
Falcon
Filemaker
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
GDB
GDScript
Game Maker
Genero
Genie
GetText
Go
Godot GLSL
Groovy
GwBasic
HQ9 Plus
HTML
HTML 5
Haskell
Haxe
HicEst
IDL
INI file
INTERCAL
IO
ISPF Panel Definition
Icon
Inno Script
J
JCL
JSON
Java
Java 5
JavaScript
Julia
KSP (Kontakt Script)
KiXtart
Kotlin
LDIF
LLVM
LOL Code
LScript
Latex
Liberty BASIC
Linden Scripting
Lisp
Loco Basic
Logtalk
Lotus Formulas
Lotus Script
Lua
M68000 Assembler
MIX Assembler
MK-61/52
MPASM
MXML
MagikSF
Make
MapBasic
Markdown (PRO members only)
MatLab
Mercury
MetaPost
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MySQL
Nagios
NetRexx
Nginx
Nim
NullSoft Installer
OCaml
OCaml Brief
Oberon 2
Objeck Programming Langua
Objective C
Octave
Open Object Rexx
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
PARI/GP
PCRE
PHP
PHP Brief
PL/I
PL/SQL
POV-Ray
ParaSail
Pascal
Pawn
Per
Perl
Perl 6
Phix
Pic 16
Pike
Pixel Bender
PostScript
PostgreSQL
PowerBuilder
PowerShell
ProFTPd
Progress
Prolog
Properties
ProvideX
Puppet
PureBasic
PyCon
Python
Python for S60
QBasic
QML
R
RBScript
REBOL
REG
RPM Spec
Racket
Rails
Rexx
Robots
Roff Manpage
Ruby
Ruby Gnuplot
Rust
SAS
SCL
SPARK
SPARQL
SQF
SQL
SSH Config
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
StandardML
StoneScript
SuperCollider
Swift
SystemVerilog
T-SQL
TCL
TeXgraph
Tera Term
TypeScript
TypoScript
UPC
Unicon
UnrealScript
Urbi
VB.NET
VBScript
VHDL
VIM
Vala
Vedit
VeriLog
Visual Pro Log
VisualBasic
VisualFoxPro
WHOIS
WhiteSpace
Winbatch
XBasic
XML
XPP
Xojo
Xorg Config
YAML
YARA
Z80 Assembler
ZXBasic
autoconf
jQuery
mIRC
newLISP
q/kdb+
thinBasic
Paste Expiration:
Never
Burn after read
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Exposure:
Public
Unlisted
Private
Folder:
(members only)
Password
NEW
Enabled
Disabled
Burn after read
NEW
Paste Name / Title:
Create New Paste
Hello
Guest
Sign Up
or
Login
Sign in with Facebook
Sign in with Twitter
Sign in with Google
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Public Pastes
December smells like money
CSS | 3 min ago | 0.28 KB
✅ Changelly.com Exploit
16 min ago | 0.28 KB
Trading method
CSS | 30 min ago | 0.28 KB
Google Docs - Exploit
43 min ago | 0.28 KB
Earn money on Changelly
CSS | 56 min ago | 0.28 KB
Untitled
C | 9 hours ago | 0.88 KB
acg
1 day ago | 0.05 KB
AI METHODS
2 days ago | 0.29 KB
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the
Cookies Policy
.
OK, I Understand
Not a member of Pastebin yet?
Sign Up
, it unlocks many cool features!