// constants are declared without a $-prefix const name = "Robb"; // get a reference of the constant $myname = name; echo $myname; // reference
Day 64: Check If A String is a Palindrome With Python
We get a string and check if it is a palindrome:
# Find out if a word is a palindrome def palin(word): ''' take word, build inverted string and check if it is a palindrome ''' word = word.replace(".", "") # get rid of eventual "." word = word.lower() # make lowercase length = len(word) new = list("") # build an empty list for the inversed string index = -1 # -1 so we start building in reverse order # take every letter and add it to new list in reverse order for i in word: new.insert(index, i) index -= 1 # change list to string new_str = "".join(new) # get rid of any spaces in a sentence word_stripped = word.replace(" ", "") new_stripped = new_str.replace(" ", "") # check if word and the reverse string are the same if (word_stripped == new_stripped): return (word + ": This is a palindrome") else: return (word + ": This is NOT a palindrome") print(palin("Anna")) # anna: This is a palindrome print(palin("peter")) # peter: This is NOT a palindrome print(palin("Name not one man.")) # name not one man: This is a palindrome
Day 28: A Simple Password Generator With random.choice()
What is the most elegant way to choose a random char from a string, list or tuple?
I build a simple password generator that will build a password the length the user has chosen.
If the length is smaller than 8 though the user will have to redo his entry.
This is what the output looks like:
This is what the code looks like:
# A simple password generator # creates a random String # will ask anew if length was too short import random # the string contains all the chars we want to use. alphabet = "1234567890abcdefghijklmnopqrstuvwxyz!@#$%^&<>?ABCDEFGHIJKLMNOPQRSTUVWXYZ" def pass_gen(pass_length): i = 1 password = "" if (int(pass_length) >= 8): while i <= int(pass_length): # random.choice() is the shortest and lean way # to select a random char from a string, list or tuple password = password + random.choice(alphabet) i += 1 else: pass_gen(input("Chosen length too short. Enter a length (min 8): ")) print(password) pass_gen(input("Enter the maximum length of your password (min 8): "))
You find more information about random.choice() here.