Skip to content

Python

pseudo shell:

from cmd import Cmd
from colorama import Fore, Back, Style

class Terminal(Cmd):
    # prompt = '>>> '
    # prompt = '\033[91m>>> \033[00m'
    prompt = Fore.RED +'>>> ' + Fore.RESET

    def default(self, args):
        # do stuff
        Pass

term = Terminal()
term.cmdloop()

HTTPLib request

import httplib
con = httplib.HTTPConnection('challenge02.root-me.org', 60005)
con.request('GET', '/', headers = {'header_name': 'header_value'}
con.getresponse().read()

Python - get "." character (blacklisted input)

repr(float(2/3))[1]

String Manipulation

Take groups of n characters from a string

txt = "ABCDEFGHI"
n = 3
listofnums = [txt[i:i+n] for i in range(0, len(txt), n)]

IPython

Logging

Turning logging on/off:

%logstart

%logstop

https://stackoverflow.com/questions/16858724/how-to-log-ipython-history-to-text-file

https://ipython.org/ipython-doc/rel-0.10.2/html/interactive/tutorial.html

Read lines from file and remove newlines:

with open('filename', 'r') as file:
    temp = file.read().splitlines()

Convert integer to binary (as string):

"{0:b}".format(25)

Bit Counting:

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

def countBits(n):
    # use format to convert integer to binary
    # then use list comprehension to sum the digits
    return sum([int(x) for x in '{0:0b}'.format(n)])

Solutions from others:

def countBits(n):
    return bin(n).count("1")
" ".join([str(ord(x) % 97 + 1) for x in "He".lower() if x.isalpha()])

import string string.ascii_letters string.ascii_lowercase

Given an array, find the int that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

a = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]

import operator
def find_it(xs):
    return reduce(operator.xor, xs)

def find_it_2(xs):
    return [x for x in xs if xs.count(x) % 2 == 1][0]

def find_it_2(xs):
    reduce((lambda x,y: x^y), xs)

md5 of text:

import hashlib

def pass_hash(str):
    return hashlib.md5(str.encode()).hexdigest()

convert list of numbers into phone number format

def create_phone_number(n):
    b = ''.join(map(str,n))
    return f'({b[0:3]}) {b[3:6]}-{b[6:]}'

def create_phone_number(n):
  return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)

Count the number of Duplicates Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

def duplicate_count(text):
return len(set([i for i in map((lambda x: chr(x).lower()), range(48,91)) if text.lower().count(i) > 1]))
    return len([chr(i) for i in range(48,123) if text.count(chr(i)) > 1])

def duplicate_count(s):
  return len([c for c in set(s.lower()) if s.lower().count(c)>1])

Playing with digits Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p

we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

def dig_pow(n, p):
    x,y = divmod(sum([int(b)**(a+p) for a,b in enumerate(str(n))]), n)
    if y == 0:
        return x
    else:
        return -1

Build Tower by the following given argument: number of floors (integer and always greater than 0). Tower block is represented as *

example 6 level tower: [ ' * ', ' ', ' ', ' * ', ' * ', '*****' ]

def tower_builder(n_floors):
    return [("*"*(2*i-1)).center(2*n_floors-1) for i in range(1, n_floors+1)]
def int2romannumeral(n):
    ints = (1000, 900,  500, 400, 100,  90, 50,  40, 10,  9,   5,  4,   1)
    nums = ('M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
    result = ""
    for i in range(len(ints)):
       count = n // ints[i]
       result += nums[i] * count
       n -= ints[i] * count
    return result

from functools import reduce product = reduce((lambda x, y: x * y), [1, 2, 3, 4])

A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.

He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).

His mother looks out of a window 1.5 meters from the ground.

How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?

Three conditions must be met for a valid experiment: Float parameter "h" in meters must be greater than 0 Float parameter "bounce" must be greater than 0 and less than 1 Float parameter "window" must be less than h. If all three conditions above are fulfilled, return a positive integer, otherwise return -1.

Note: The ball can only be seen if the height of the rebounding ball is stricty greater than the window parameter.

from math import log

def bouncingBall(h, b, w):
    return (2 * int(log(w / h, b)) + 1) if (h > 0 and b > 0 and b < 1 and w < h) else -1