├── LICENSE ├── README.md ├── _config.yml └── src └── string.md /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Allwin Raju 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This github repo is a collection of amazing python one liners. 2 | 3 | # A 4 | * [alternate elements](#alternate-elements) 5 | * [anagram](#anagram) 6 | 7 | # B 8 | * [binary to decimal](#binary-to-decimal) 9 | 10 | # C 11 | * [check data type](#check-data-type) 12 | * [combine strings from a list](#combine-strings-from-a-list) 13 | * [combine two lists to dictionary](#combine-two-lists-to-dictionary) 14 | * [common element between two lists](#common-element-between-two-lists) 15 | * [convert decimal to binary](#convert-decimal-to-binary) 16 | * [convert decimal to octal](#convert-decimal-to-octal) 17 | * [convert decimal to hexadecimal](#convert-deciaml-to-hexadecimal) 18 | * [convert a list of strings to integers](#convert-a-list-of-strings-to-integers) 19 | * [convert key value pair to dictionary](#convert-key-value-pair-to-dictionary) 20 | * [convert string to lower case](#convert-string-to-lower-case) 21 | * [convert string to upper case](#convert-string-to-upper-case) 22 | * [convert string to bytes](#convert-string-to-bytes) 23 | * [copy files](#copy-files) 24 | * [count occurence of a character in a string](#count-occurence-of-a-character-in-a-string) 25 | 26 | # D 27 | * [dictionary comprehension](#dictionary-comprehension) 28 | * [deleting multiple elements from a list](#deleting-multiple-elements-from-a-list) 29 | 30 | # E 31 | * [execute strings](#execute-strings) 32 | 33 | # F 34 | * [fibonacci series](#fibanocci-series) 35 | * [fizzbuzz](#fizzbuzz) 36 | * [flatten list](#flatten-list) 37 | * [factorial of a number](#factorial-of-a-number) 38 | * [floor division result](#floor-division-result) 39 | * [for and if](#for-and-if) 40 | 41 | # G 42 | * [generate a random number of n digits](#generate-a-random-number-of-n-digits) 43 | * [get a string of small case alphabets](#get-a-string-of-small-case-alphabets) 44 | * [get a string of upper case alphabets](#get-a-string-of-upper-case-alphabets) 45 | * [get a string of digits from 0 to 9](#get-a-string-of-digits-from-0-to-9) 46 | * [get even numbers from a list](#get-even-numbers-from-a-list) 47 | * [get individual digits from a number](#get-individual-digits-from-a-number) 48 | * [get timestamp](#get-timestamp) 49 | * [get quotient and remainder](#get-quotient-and-remainder) 50 | 51 | # H 52 | * [half pyramid](#half-pyramid) 53 | * [hexadecimal to decimal](#hexadecimal-to-decimal) 54 | * [hypotenuse](#hypotenuse) 55 | * [human-readable-datetime](#human-readable-datetime) 56 | 57 | # I 58 | * [if-else](#if-else) 59 | * [if-elif-else](#if-elif-else) 60 | * [infinite-while-loop](#infinite-while-loop) 61 | * [input a list of tuples](#input-a-list-of-tuples) 62 | 63 | # L 64 | * [lambda function with if else](#lambda-function-with-if-else) 65 | * [longest string in a list](#longest-string-in-a-list) 66 | * [list comprehension](#list-comprehension) 67 | 68 | # M 69 | * [max value key](#max-value-key) 70 | * [merge two lists](#merge-two-lists) 71 | * [merge two dictionaries](#merge-two-dictionaries) 72 | * [merge two sets](#merge-two-sets) 73 | * [min value key](#min-value-key) 74 | * [most frequnet element in a list](#most-frequent-element-in-a-list) 75 | 76 | # N 77 | * [nested list comprehension](#nested-list-comprehension) 78 | 79 | # O 80 | * [object creation](#object-creation) 81 | * [octal to decimal](#octal-to-decimal) 82 | 83 | # P 84 | * [performance profiling](#performance-profiling) 85 | * [permutation](#permutation) 86 | * [prefix sum](#prefix-sum) 87 | * [prime numbers in a range](#prime-numbers-in-a-range) 88 | * [python zen](#python-zen) 89 | 90 | # Q 91 | * [quick sort](#quick-sort) 92 | 93 | # R 94 | * [remove duplicate elements from a list](#remove-duplicate-elements-from-a-list) 95 | * [remove numbers from string](#remove-numbers-from-string) 96 | * [repeat values in a list for n times](#repeat-values-in-a-list-for-n-time) 97 | * [replace words in a sentence](#replace-words-in-a-sentence) 98 | * [replace with regular expression](#replace-with-regular-expression) 99 | * [replace multiple spaces](#replace-multiple-spaces) 100 | * [rotate a list](#rotate-a-list) 101 | * [reverse a list](#reverse-a-list) 102 | 103 | # S 104 | * [set comprehension](#set-comprehension) 105 | * [sort dictionary with values](#sort-dictionary-with-values) 106 | * [sort dictionary with key](#sort-dictionary-with-key) 107 | * [sort list in ascending order](#sort-list-in-ascending-order) 108 | * [sort list in descending order](#sort-list-in-descending-order) 109 | * [substring in a string](#substring-in-a-string) 110 | * [sum of n consecutive numbers](#sum-of-n-consecutive-numbers) 111 | * [starting a http server](#starting-a-http-server) 112 | * [swap two numbers](#swap-two-numbers) 113 | 114 | # T 115 | * [transpose matrix](#transpose-matrix) 116 | 117 | # U 118 | * [Unpacking elements](#unpacking-elements) 119 | 120 | # W 121 | * [while loop](#while-loop) 122 | * [write to a file using print](#write-to-a-file-using-print) 123 | 124 | 125 | ### alternate elements 126 | 127 | Elements from even index 128 | ```python 129 | li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 130 | print(li[0::2]) 131 | # [1, 3, 5, 7, 9] 132 | ``` 133 | 134 | Elements from odd index 135 | ```python 136 | li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 137 | print(li[1::2]) 138 | # [2, 4, 6, 8, 10] 139 | ``` 140 | 141 | ### anagram 142 | ```python 143 | from collections import Counter 144 | 145 | s1 = 'below' 146 | s2 = 'elbow' 147 | 148 | print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram') 149 | ``` 150 | 151 | ### binary to decimal 152 | ```python 153 | decimal = int('1010', 2) 154 | print(decimal) #10 155 | ``` 156 | ### convert decimal to binary 157 | ```python 158 | bin(24) 159 | ``` 160 | 161 | ### convert decimal to hexadecimal 162 | ```python 163 | hex(24) 164 | ``` 165 | 166 | ### convert decimal to octal 167 | ```python 168 | oct(24) 169 | ``` 170 | 171 | ### convert key value pair to dictionary 172 | ```python 173 | dict(name='allwin', age=23) 174 | ``` 175 | 176 | ### convert string to lower case 177 | ```python 178 | "Hi my name is Allwin".lower() 179 | # 'hi my name is allwin' 180 | "Hi my name is Allwin".casefold() 181 | # 'hi my name is allwin' 182 | ``` 183 | 184 | ### convert string to upper case 185 | ```python 186 | "hi my name is Allwin".upper() 187 | # 'HI MY NAME IS ALLWIN' 188 | ``` 189 | 190 | ### convert string to bytes 191 | ```python 192 | "convert string to bytes using encode method".encode() 193 | # b'convert string to bytes using encode method' 194 | ``` 195 | 196 | ### copy files 197 | ```python 198 | import shutil; shutil.copyfile('source.txt', 'dest.txt') 199 | ``` 200 | 201 | ### deleting multiple elements from a list 202 | ```python 203 | li = [1, 2, 3, 4, 5] 204 | del li[0:3] 205 | # [4, 5] 206 | ``` 207 | 208 | ### execute strings 209 | ``` 210 | exec('print("hello world!")') 211 | # hello world! 212 | ``` 213 | 214 | ### fibonacci series 215 | ```python 216 | lambda x: x if x<=1 else fib(x-1) + fib(x-2) 217 | ``` 218 | 219 | ### fizzbuzz 220 | ```python 221 | n = 20 222 | print('\n'.join('Fizz' * (i%3==0) + 'Buzz' * (i%5==0) or str(i) for i in range(1, n))) 223 | 224 | 1 225 | 2 226 | Fizz 227 | 4 228 | Buzz 229 | Fizz 230 | 7 231 | 8 232 | Fizz 233 | Buzz 234 | 11 235 | Fizz 236 | 13 237 | 14 238 | FizzBuzz 239 | 16 240 | 17 241 | Fizz 242 | 19 243 | ``` 244 | 245 | ### half pyramid 246 | ```python 247 | n = 5 248 | print('\n'.join('* ' * i for i in range(1, n + 1))) 249 | 250 | * 251 | * * 252 | * * * 253 | * * * * 254 | * * * * * 255 | ``` 256 | 257 | ### quick sort 258 | ```python 259 | qsort = lambda l : l if len(l)<=1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]]) 260 | ``` 261 | 262 | ### sum of n consecutive numbers 263 | ```python 264 | sum(range(0, n+1)) 265 | ``` 266 | 267 | ### swap two values 268 | ```python 269 | a,b = b,a 270 | ``` 271 | 272 | ### flatten list 273 | ``` python 274 | [item for sublist in main_list for item in sublist] 275 | ``` 276 | 277 | Using itertools 278 | ```python 279 | import itertools 280 | print(list(itertools.chain.from_iterable(a_list))) 281 | [1, 2, 3, 4, 5, 6] 282 | ``` 283 | 284 | ### starting a http server 285 | ```python 286 | python3 -m http.server 8000 287 | python2 -m SimpleHTTPServer 288 | ``` 289 | 290 | ### factorial of a number 291 | ```python 292 | import math; fact_5 = math.factorial(5) 293 | ``` 294 | 295 | ### floor division result 296 | ```python 297 | print(5//2) 298 | # 2 299 | ``` 300 | 301 | ### for and if 302 | ```python 303 | new_li = [number for number in [1, 2, 3, 4] if number % 2 == 0] 304 | # [2, 4] 305 | ``` 306 | 307 | ### lambda function with if else 308 | ```python 309 | list(map(lambda x: x if x%2==0 else x+1, [1, 2, 3, 4])) 310 | # [2, 2, 4, 4] 311 | # converts only odd numbers to even numbers by adding 1 to it 312 | ``` 313 | 314 | ### longest string in a list 315 | ```python 316 | # words = ['This', 'is', 'a', 'list', 'of', 'words'] 317 | max(words, key=len) 318 | # 'words' 319 | ``` 320 | 321 | ### list comprehension 322 | ```python 323 | li = [num for num in range(0,100)] 324 | # this will create a list of numbers from 0 to 99 325 | ``` 326 | 327 | ### set comprehension 328 | ```python 329 | num_set = { num for num in range(0,100)} 330 | # this will create a set of numbers from 0 to 99 331 | ``` 332 | 333 | ### dictionary comprehension 334 | ```python 335 | dict_numbers = {x:x*x for x in range(0,5) } 336 | ``` 337 | 338 | ### if else 339 | ```python 340 | print("even") if 4%2==0 else print("odd") 341 | ``` 342 | 343 | ### if elif else 344 | ```python 345 | grade = "A" if score >= 80 else "B" if score >= 60 else "C" 346 | ``` 347 | 348 | ### infinite while loop 349 | ```python 350 | while 1:0 351 | ``` 352 | 353 | ### check data type 354 | ```python 355 | isinstance(2, int) 356 | isinstance("allwin", str) 357 | isinstance([3,4,1997], list) 358 | ``` 359 | 360 | ### while loop 361 | ```python 362 | a=5 363 | while a > 0: a = a - 1; print(a) 364 | ``` 365 | 366 | ### write to a file using print 367 | ```python 368 | print("Hello, World!", file=open('file.txt', 'w')) 369 | ``` 370 | 371 | ### count occurence of a character in a string 372 | ```python 373 | print("umbrella".count('l')) 374 | ``` 375 | 376 | ### max value key 377 | ```python 378 | d = {320: 1, 321: 0, 322: 3} 379 | max_value_key = max(d, key=d.get) 380 | 381 | # 322 382 | ``` 383 | 384 | ### merge two lists 385 | ```python 386 | list1.extend(list2) 387 | # contents of list 2 will be added to the list1 388 | ``` 389 | 390 | or 391 | ```python 392 | [1, 2] + [3, 4] 393 | # [1, 2, 3, 4] 394 | ``` 395 | 396 | ### merge two dictionaries 397 | ```python 398 | dict1.update(dict2) 399 | # contents of dictionary 2 will be added to the dictionary 1 400 | ``` 401 | 402 | ### merge two sets 403 | ```python 404 | set1.update(set2) 405 | # contents of set2 will be copied to the set1 406 | ``` 407 | 408 | ### min value key 409 | ```python 410 | d = {320: 1, 321: 0, 322: 3} 411 | min_value_key = min(d, key=d.get) 412 | 413 | # 321 414 | ``` 415 | 416 | 417 | ### get timestamp 418 | ```python 419 | import time; print(time.time()) 420 | ``` 421 | 422 | ### most frequent element in a list 423 | ```python 424 | numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4] 425 | most_frequent_element = max(set(test_list), key=test_list.count) 426 | # 4 427 | ``` 428 | ```python 429 | from collections import Counter 430 | 431 | numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4] 432 | print(list(Counter(numbers).most_common())) 433 | # [(4, 4), (5, 3), (9, 2)] 434 | ``` 435 | 436 | ### nested list comprehension 437 | ```python 438 | numbers = [[num] for num in range(10)] 439 | # [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]] 440 | ``` 441 | 442 | ### object creation 443 | ```python 444 | obj_1 = type('obj_1', (object,), {'property': 'value'})() 445 | ``` 446 | 447 | ### octal to decimal 448 | ```python 449 | print(int('30', 8)) 450 | # 24 451 | ``` 452 | 453 | ### repeat values in a list for n time 454 | ```python 455 | import itertools; print(list(itertools.repeat(10,5))) 456 | # [10, 10, 10, 10, 10] will be printed 457 | ``` 458 | 459 | ### generate a random number of n digits 460 | ```python 461 | from random import randint; print(''.join(["{}".format(randint(0, 9)) for num in range(0, n)])) 462 | # This will print 1038496714 given the value of n=10 463 | ``` 464 | 465 | ### get quotient and remainder 466 | ```python 467 | quotient, remainder = divmod(4,5) 468 | ``` 469 | 470 | ### python zen 471 | ```python 472 | import this 473 | ``` 474 | 475 | ### remove duplicate elements from a list 476 | ```python 477 | list(set([4, 4, 5, 5, 6])) 478 | ``` 479 | 480 | ### sort list in ascending order 481 | ```python 482 | sorted([5, 2, 9, 1]) 483 | ``` 484 | 485 | ### sort list in descending order 486 | ```python 487 | sorted([5, 2, 9, 1], reverse=True) 488 | ``` 489 | 490 | ### get a string of small case alphabets 491 | ```python 492 | import string; print(string.ascii_lowercase) 493 | # abcdefghijklmnopqrstuvwxyz 494 | ``` 495 | 496 | ### get a string of upper case alphabets 497 | ```python 498 | import string; print(string.ascii_uppercase) 499 | # ABCDEFGHIJKLMNOPQRSTUVWXYZ 500 | ``` 501 | 502 | ### get a string of digits from 0 to 9 503 | ```python 504 | import string; print(string.digits) 505 | # 0123456789 506 | ``` 507 | 508 | ### get individual digits from a number 509 | ```python 510 | digits = [int(digit) for digit in str(12345)] 511 | ``` 512 | 513 | ### hexadecimal to decimal 514 | ```python 515 | print(int('da9', 16)) 516 | # 3497 517 | ``` 518 | 519 | ### hypotenuse 520 | ```python 521 | import math; math.hypot(8, 6) 522 | ``` 523 | 524 | ### human readable datetime 525 | ```python 526 | import time; print(time.ctime()) 527 | # Thu Aug 13 20:16:23 2020 528 | ``` 529 | 530 | ### convert a list of strings to integers 531 | ```python 532 | list(map(int, ['1', '2', '3'])) 533 | # [1, 2, 3] 534 | ``` 535 | 536 | ### combine strings from a list 537 | ```python 538 | " ".join(["hello", "world"]) 539 | # "hello world" 540 | ``` 541 | 542 | ### combine two lists to dictionary 543 | ```python 544 | dict(zip([1,2,3,4], ['a','b','c','d'])) 545 | {1: 'a', 2: 'b', 3: 'c', 4: 'd'} 546 | ``` 547 | 548 | ### common element between two lists 549 | ```python 550 | list1 = [1, 2, 4, 5] 551 | list2 = [6, 8, 4, 2] 552 | 553 | print(set(list1) & set(list2)) 554 | print(set(list1).intersection(set(list2))) 555 | # {2, 4} 556 | ``` 557 | 558 | ### get even numbers from a list 559 | ```python 560 | list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] )) 561 | # [2, 4, 6] 562 | ``` 563 | 564 | ### input a list of tuples 565 | ```python 566 | list(tuple(map(int, input().split())) for r in range(int(input('enter the no of rows:')))) 567 | # enter the no of rows: 568 | # 3 569 | # 1 2 570 | # 3 4 571 | # 5 6 572 | # [(1, 2), (3, 4), (5, 6)] 573 | ``` 574 | 575 | ### performance profiling 576 | ```shell 577 | $ python -m cProfile foo.py 578 | ``` 579 | 580 | ### permutation 581 | ```python 582 | from itertools import permutations 583 | print([''.join(perm) for perm in permutations('abc')]) 584 | 585 | # ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] 586 | ``` 587 | 588 | ### prefix sum 589 | ```python 590 | import itertools 591 | prefix_sum = itertools.accumulate([1, 2, 3, 4, 5]) 592 | print(list(prefix_sum)) 593 | 594 | # [1, 3, 6, 10, 15] 595 | ``` 596 | 597 | ### prime numbers in a range 598 | ```python 599 | primes = list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 100))) 600 | print(primes) 601 | # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] 602 | ``` 603 | 604 | ### remove numbers from string 605 | ```python 606 | ''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2'))) 607 | # abcdeffgvcg 608 | ``` 609 | 610 | ### replace words in a sentence 611 | ```python 612 | string = "He is a good boy" 613 | string.replace('good', 'bad') 614 | # returns 'he is a bad boy' 615 | ``` 616 | 617 | ### replace with regular expression 618 | ```python 619 | # replace everythin in one go 620 | 621 | import re 622 | re.sub(r'[.+()@]', '', 'A(ll+wi)@n.') 623 | # 'Allwin' 624 | ``` 625 | 626 | ### replace multiple spaces 627 | ```python 628 | # replace-multiple-spaces 629 | s = 'string with multiple spaces and \n\n new lines' 630 | ' '.join(s.split()) # 'string with multiple spaces and new lines' 631 | ``` 632 | 633 | ### reverse a list 634 | ```python 635 | numbers[::-1] 636 | ``` 637 | 638 | ### rotate a list 639 | ```python 640 | # li = [1,2,3,4,5] 641 | # right to left 642 | li[n:] + li[:n] # n is the no of rotations 643 | li[2:] + li[:2] 644 | [3, 4, 5, 1, 2] 645 | # left to right 646 | li[-n:] + li[:-n] 647 | li[-1:] + li[:-1] 648 | [5, 1, 2, 3, 4] 649 | ``` 650 | 651 | ### sort dictionary with values 652 | ```python 653 | # x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} 654 | {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} 655 | # {0: 0, 2: 1, 1: 2, 4: 3, 3: 4} 656 | ``` 657 | 658 | ### sort dictionary with key 659 | ```python 660 | # {'one': 1, 'four': 4, 'eight': 8} 661 | {key:d[key] for key in sorted(d.keys())} 662 | # {'eight': 8, 'four': 4, 'one': 1} 663 | ``` 664 | 665 | ### substring in a string 666 | ```python 667 | 'sent' in 'sentence' 668 | # returns True 669 | ``` 670 | 671 | ### transpose matrix 672 | ```python 673 | list(list(x) for x in zip(*old_list)) 674 | # old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]] 675 | # [[1, 3, 5], [2, 4, 6], [3, 6, 7]] 676 | ``` 677 | 678 | ### unpacking elements 679 | ```python 680 | a, *b, c = [1, 2, 3, 4, 5] 681 | print(a) # 1 682 | print(b) # [2, 3, 4] 683 | print(c) # 5 684 | ``` 685 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker -------------------------------------------------------------------------------- /src/string.md: -------------------------------------------------------------------------------- 1 | ### Anagram 2 | ```python 3 | str = "hi" 4 | ``` 5 | --------------------------------------------------------------------------------