Author: polar

  • Codes and programs

    This page contains codes and little programs I’ve made

    Random numbers



    How long would it take to make a coin land on heads 10 times in a row?

    Let’s say 1 is heads, and 2 is tails. And let’s say that one toss takes 7 seconds.

    This program uses the secsToDHM function.

    heads = 0; tosses = 0
    while(heads < 10):
    	toss = Random.randint(1,2)
    
    	if toss == 1:
    		heads += 1
    	else:
    		heads = 0
    
    	tosses += 1
    
    
    print(f"It took {tosses} tosses ({secsToDHM(7 * tosses)})")
    
    
    # How many spins does it take on a roulette wheel to hit zero X times in a row?
    # We'll go with 30 seconds per spin for this one
    spins = 0; green = 0
    while(green < 4):
    	spins += 1
    	spin = Random.randint(1,37) # 37 is green
    
    	if spin == 37: green += 1
    	else: green = 0
    
    print(f"It took {spins} spins to hit green 4 times in a row ({secsToDHM(30 * spins)})")

  • “Prettify” seconds

    secsToDHM (seconds)

    This “prettifies” seconds by returning a string of the amount of hours and minutes the given seconds convert to. Days are also included, if hours are 24 or over. Example of a returned string:
    “3 days, 8 hours, 23 minutes”

    def secsToDHM(seconds: int) -> str:
    	minutes = round(seconds / 60)
    	hours = round(minutes / 60)
    	remM = minutes % 60
    	days = 0
    
    	if hours >= 24:
    		days = round(hours / 24)
    		remH = hours % 24
    
    	if (days > 0):
    		return f"{days} days, {remH} hours, {remM} minutes"
    
    	return f"{hours} hours, {remM} minutes"

  • Python (3)

    This is where I will document my progress in learning Python.

    One key aspect when first starting with Python is that it differs from other languages in that commands are not necessarily ending with a semicolon, and blocks are not defined by { and }. Instead, commands end where the line ends, and blocks are defined by indetation (a tab, or spaces). Example:

    1) print("Hello world!")
    2) print("Hello!"); print("Hello, world I mean!)

    The first example above is all you need for the program to work. No semicolon is needed.
    The second one, there are two commands on a single line, so a semicolon is needed to separate them.

    Intendation

    Intendantion is needed to form a new block. In C and many other languages, it is usually done like this:

    if (x > y)
    {
    print("Yes, x is indeed larger than y");
    }

    While in Python, the same would be achieved like this:

    if x > y:
    print(“Yes, x is indeed larger than y”)